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
net.akehurst.language/agl-processor/src/commonMain/kotlin/agl/ast/GrammarDefault.kt
dhakehurst
197,245,665
false
null
/** * Copyright (C) 2018 Dr. <NAME> (http://dr.david.h.akehurst.net) * * 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 net.akehurst.language.agl.ast import net.akehurst.language.api.grammar.* internal class GrammarDefault( override val namespace: Namespace, override val name: String, override val rule: MutableList<Rule> ) : GrammarAbstract(namespace, name, rule) { } internal abstract class GrammarAbstract( override val namespace: Namespace, override val name: String, override val rule: List<Rule> ) : Grammar { override val extends: MutableList<Grammar> = mutableListOf<Grammar>(); override val allRule: List<Rule> by lazy { //TODO: Handle situation where super grammar/rule is included more than once ? val rules = this.extends.flatMap { it.allRule }.toMutableList() this.rule.forEach { rule -> if (rule.isOverride) { val overridden = rules.find { it.name == rule.name } ?: throw GrammarRuleNotFoundException("Rule ${rule.name} is marked as overridden, but there is no super rule with that name to override.") rules.remove(overridden) rules.add(rule) } else { rules.add(rule) } } rules } override val allTerminal: Set<Terminal> by lazy { this.allRule.toSet().flatMap { it.rhs.allTerminal }.toSet() } override val allNodeType: Set<NodeType> by lazy { this.allRule.map { NodeTypeDefault(it.name) }.toSet() } override fun findAllRule(ruleName: String): Rule { val all = this.allRule.filter { it.name == ruleName } return when { all.isEmpty() -> throw GrammarRuleNotFoundException("Rule '${ruleName}' not found in grammar '${this.name}'") all.size > 1 -> { throw GrammarRuleNotFoundException("More than one rule named '${ruleName}' in grammar '${this.name}', have you remembered the 'override' modifier") } else -> all.first() } } override fun findAllTerminal(terminalPattern: String): Terminal { val all = this.allTerminal.filter { it.value == terminalPattern } when { all.isEmpty() -> throw GrammarRuleNotFoundException("${terminalPattern} in Grammar(${this.name}).findAllRule") all.size > 1 -> throw GrammarRuleNotFoundException("More than one rule named ${terminalPattern} in Grammar(${this.name}).findAllRule") } return all.first() } }
2
Kotlin
5
36
c4a404149d165ea57220f978c5f2bde3ac6f14f3
3,072
net.akehurst.language
Apache License 2.0
atomicfu-transformer/src/main/kotlin/kotlinx/atomicfu/transformer/AtomicFUTransformerJS.kt
pandening
153,554,636
true
{"Kotlin": 141963}
package kotlinx.atomicfu.transformer import org.mozilla.javascript.* import org.mozilla.javascript.ast.* import java.io.File import java.io.FileReader import org.mozilla.javascript.Token private const val ATOMIC_CONSTRUCTOR = """atomic\$(ref|int|long|boolean)\$""" private const val MANGLED_VALUE_PROP = "kotlinx\$atomicfu\$value" private const val RECEIVER = "\$receiver" private const val SCOPE = "scope" private const val FACTORY = "factory" private const val REQUIRE = "require" private const val KOTLINX_ATOMICFU = "'kotlinx-atomicfu'" private const val MODULE_KOTLINX_ATOMICFU = "\$module\$kotlinx_atomicfu" class AtomicFUTransformerJS( inputDir: File, outputDir: File, var requireKotlinxAtomicfu: Boolean = false ) : AtomicFUTransformerBase(inputDir, outputDir) { private val atomicConstructors = mutableSetOf<String>() override fun transform() { info("Transforming to $outputDir") inputDir.walk().filter { it.isFile }.forEach { file -> val outBytes = if (file.isJsFile()) { println("Transforming file: ${file.canonicalPath}") transformFile(file) } else { file.readBytes() } file.toOutputFile().mkdirsAndWrite(outBytes) } } private fun File.isJsFile() = name.endsWith(".js") && !name.endsWith(".meta.js") private fun transformFile(file: File): ByteArray { val p = Parser(CompilerEnvirons()) val root = p.parse(FileReader(file), null, 0) root.visit(DependencyEraser()) root.visit(AtomicConstructorDetector()) root.visit(TransformVisitor()) root.visit(AtomicOperationsInliner()) return root.toSource().toByteArray() } inner class DependencyEraser : NodeVisitor { private fun isAtomicfuDependency(node: AstNode) = (node.type == Token.STRING && node.toSource() == KOTLINX_ATOMICFU) private fun isAtomicfuModule(node: AstNode) = (node.type == Token.NAME && node.toSource() == MODULE_KOTLINX_ATOMICFU) override fun visit(node: AstNode): Boolean { when (node.type) { Token.ARRAYLIT -> { // erasing 'kotlinx-atomicfu' from the list of defined dependencies val elements = (node as ArrayLiteral).elements as MutableList val it = elements.listIterator() while (it.hasNext()) { val arg = it.next() if (isAtomicfuDependency(arg)) { it.remove() } } } Token.FUNCTION -> { // erasing 'kotlinx-atomicfu' module passed as parameter if (node is FunctionNode) { val it = node.params.listIterator() while (it.hasNext()) { if (isAtomicfuModule(it.next()) && !requireKotlinxAtomicfu) { it.remove() } } } } Token.CALL -> { if (node is FunctionCall && node.target.toSource() == FACTORY) { val it = node.arguments.listIterator() while (it.hasNext()) { val arg = it.next() when (arg.type) { Token.GETELEM -> { // erasing 'kotlinx-atomicfu' dependency as factory argument if (isAtomicfuDependency((arg as ElementGet).element)) { it.remove() } } Token.CALL -> { // erasing require of 'kotlinx-atomicfu' dependency if ((arg as FunctionCall).target.toSource() == REQUIRE) { if (isAtomicfuDependency(arg.arguments[0]) && !requireKotlinxAtomicfu) { it.remove() } } } } } } } Token.GETELEM -> { if (isAtomicfuDependency((node as ElementGet).element)) { val enclosingNode = node.parent // erasing the check whether 'kotlinx-atomicfu' is defined if (enclosingNode.type == Token.TYPEOF) { if (enclosingNode.parent.parent.type == Token.IF) { val ifStatement = enclosingNode.parent.parent as IfStatement val falseKeyword = KeywordLiteral() falseKeyword.type = Token.FALSE ifStatement.condition = falseKeyword val oneLineBlock = Block() oneLineBlock.addStatement(EmptyLine()) ifStatement.thenPart = oneLineBlock } } } } Token.BLOCK -> { // erasing importsForInline for 'kotlinx-atomicfu' for (stmt in node) { if (stmt is ExpressionStatement) { val expr = stmt.expression if (expr is Assignment && expr.left is ElementGet) { if (isAtomicfuDependency((expr.left as ElementGet).element)) { node.replaceChild(stmt, EmptyLine()) } } } } } } return true } } inner class AtomicConstructorDetector : NodeVisitor { override fun visit(node: AstNode?): Boolean { if (node is Block) { for (stmt in node) { if (stmt is VariableDeclaration) { val varInit = stmt.variables[0] as VariableInitializer if (varInit.initializer is PropertyGet) { if ((varInit.initializer as PropertyGet).property.toSource().matches(Regex(ATOMIC_CONSTRUCTOR))) { atomicConstructors.add(varInit.target.toSource()) node.replaceChild(stmt, EmptyLine()) } } } } } return true } } inner class TransformVisitor : NodeVisitor { override fun visit(node: AstNode): Boolean { // remove atomic constructors from classes fields if (node is FunctionCall) { val functionName = node.target.toSource() if (atomicConstructors.contains(functionName)) { if (node.parent is Assignment) { val valueNode = node.arguments[0] (node.parent as InfixExpression).setRight(valueNode) } return true } } // remove value property call if (node.type == Token.GETPROP) { if ((node as PropertyGet).property.toSource() == MANGLED_VALUE_PROP) { // A.a.value if (node.target.type == Token.GETPROP) { val clearField = node.target as PropertyGet val targetNode = clearField.target val clearProperety = clearField.property node.setLeftAndRight(targetNode, clearProperety) } // other cases with $receiver.kotlinx$atomicfu$value in inline functions else if (node.target.toSource() == RECEIVER) { val rr = ReceiverResolver() node.enclosingFunction.visit(rr) if (rr.receiver != null) { val field = rr.receiver as PropertyGet node.setLeftAndRight(field.target, field.property) } } } } return true } } // receiver data flow inner class ReceiverResolver : NodeVisitor { var receiver: AstNode? = null override fun visit(node: AstNode): Boolean { if (node is VariableInitializer) { if (node.target.toSource() == RECEIVER) { receiver = node.initializer return false } } return true } } inner class AtomicOperationsInliner : NodeVisitor { override fun visit(node: AstNode?): Boolean { // inline atomic operations if (node is FunctionCall) { if (node.target is PropertyGet) { val funcName = (node.target as PropertyGet).property var field = (node.target as PropertyGet).target if (field.toSource() == RECEIVER) { val rr = ReceiverResolver() node.enclosingFunction.visit(rr) if (rr.receiver != null) { field = rr.receiver } } val args = node.arguments val inlined = node.inlineAtomicOperation(funcName.toSource(), field, args) return !inlined } } return true } } private fun AstNode.isThisNode(): Boolean { return if (this is PropertyGet) { if (target.type == Token.THIS) true else target.isThisNode() } else { (this.type == Token.THIS) } } private fun PropertyGet.resolvePropName(): String { val target = this.target return if (target is PropertyGet) { "${target.resolvePropName()}.${property.toSource()}" } else { property.toSource() } } private fun AstNode.scopedSource(): String { return if (this.isThisNode() && this is PropertyGet) { val property = resolvePropName() "$SCOPE.$property" } else if (this.type == Token.THIS) { SCOPE } else { this.toSource() } } private fun FunctionCall.inlineAtomicOperation( funcName: String, field: AstNode, args: List<AstNode> ): Boolean { val f = field.scopedSource() val code = when (funcName) { "getAndSet\$atomicfu" -> { val arg = args[0].toSource() "(function($SCOPE) {var oldValue = $f; $f = $arg; return oldValue;})" } "compareAndSet\$atomicfu" -> { val expected = args[0].scopedSource() val updated = args[1].scopedSource() "(function($SCOPE) {return $f === $expected ? function() { $f = $updated; return true }() : false})" } "getAndIncrement\$atomicfu" -> { "(function($SCOPE) {return $f++;})" } "getAndIncrement\$atomicfu\$long" -> { "(function($SCOPE) {var oldValue = $f; $f = $f.inc(); return oldValue;})" } "getAndDecrement\$atomicfu" -> { "(function($SCOPE) {return $f--;})" } "getAndDecrement\$atomicfu\$long" -> { "(function($SCOPE) {var oldValue = $f; $f = $f.dec(); return oldValue;})" } "getAndAdd\$atomicfu" -> { val arg = args[0].scopedSource() "(function($SCOPE) {var oldValue = $f; $f += $arg; return oldValue;})" } "getAndAdd\$atomicfu\$long" -> { val arg = args[0].scopedSource() "(function($SCOPE) {var oldValue = $f; $f = $f.add($arg); return oldValue;})" } "addAndGet\$atomicfu" -> { val arg = args[0].scopedSource() "(function($SCOPE) {$f += $arg; return $f;})" } "addAndGet\$atomicfu\$long" -> { val arg = args[0].scopedSource() "(function($SCOPE) {$f = $f.add($arg); return $f;})" } "incrementAndGet\$atomicfu" -> { "(function($SCOPE) {return ++$f;})" } "incrementAndGet\$atomicfu\$long" -> { "(function($SCOPE) {return $f = $f.inc();})" } "decrementAndGet\$atomicfu" -> { "(function($SCOPE) {return --$f;})" } "decrementAndGet\$atomicfu\$long" -> { "(function($SCOPE) {return $f = $f.dec();})" } else -> null } if (code != null) { this.setImpl(code) return true } return false } private fun FunctionCall.setImpl(code: String) { val p = Parser(CompilerEnvirons()) val node = p.parse(code, null, 0) if (node.firstChild != null) { val expr = (node.firstChild as ExpressionStatement).expression val func = (expr as ParenthesizedExpression).expression as FunctionNode (node.firstChild as ExpressionStatement).expression = ParenthesizedExpressionDerived(FunctionNodeDerived(func)) this.target = (node.firstChild as ExpressionStatement).expression val thisNode = Parser(CompilerEnvirons()).parse("this", null, 0) this.arguments = listOf((thisNode.firstChild as ExpressionStatement).expression) } } } private class ParenthesizedExpressionDerived(val expr: FunctionNode) : ParenthesizedExpression() { override fun toSource(depth: Int): String = "(" + expr.toSource(0) + ")" } // local FunctionNode parser for atomic operations to avoid internal formatting private class FunctionNodeDerived(val fn: FunctionNode) : FunctionNode() { override fun toSource(depth: Int) = buildString { append("function") append("(") printList(fn.params, this) append(") ") append("{") (fn.body as? Block)?.forEach { when (it.type) { Token.RETURN -> { val retVal = (it as ReturnStatement).returnValue when (retVal.type) { Token.HOOK -> { val cond = retVal as ConditionalExpression append("return ") append(cond.testExpression.toSource()) append(" ? ") val target = (cond.trueExpression as FunctionCall).target as FunctionNode (cond.trueExpression as FunctionCall).target = FunctionNodeDerived(target) append(cond.trueExpression.toSource()) append(" : ") append(cond.falseExpression.toSource()) } else -> { append("return").append(" ").append(retVal.toSource()).append(";") } } } Token.VAR -> { if (it is VariableDeclaration) { append("var").append(" ") printList(it.variables, this) if (it.isStatement) { append(";") } } } Token.EXPR_VOID -> { if (it is ExpressionStatement) { append(it.expression.toSource()).append(";") } } } } append("}") } } private class EmptyLine: EmptyExpression() { override fun toSource(depth: Int) = "\n" } fun main(args: Array<String>) { if (args.size !in 1..3) { println("Usage: AtomicFUTransformerKt <dir> [<output>]") return } val t = AtomicFUTransformerJS(File(args[0]), File(args[1])) if (args.size > 2) { t.requireKotlinxAtomicfu = args[2].toBoolean() } t.transform() }
0
Kotlin
0
0
da92508eb869e9e7e1f9bb073569d8cb08c54c70
16,807
kotlinx.atomicfu
Apache License 2.0
app/src/main/java/com/xeniac/fifaultimateteamcoin_dsfut_sell_fut/feature_history/presentation/player_info/components/PlayerAnimation.kt
WilliamGates99
543,831,202
false
{"Kotlin": 898249}
package com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.feature_history.presentation.player_info.components import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.airbnb.lottie.LottieComposition import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.R @Composable fun PlayerAnimation( modifier: Modifier = Modifier, layoutDirection: LayoutDirection = LocalLayoutDirection.current, animationComposition: LottieComposition? = rememberLottieComposition( spec = LottieCompositionSpec.RawRes(R.raw.anim_history_player) ).value, animationIteration: Int = LottieConstants.IterateForever, animationSpeed: Float = 0.75f, animationRotationDegree: Float = when (layoutDirection) { LayoutDirection.Ltr -> 0f LayoutDirection.Rtl -> 180f }, ) { LottieAnimation( composition = animationComposition, iterations = animationIteration, speed = animationSpeed, modifier = modifier .size(250.dp) .graphicsLayer { rotationY = animationRotationDegree } ) }
0
Kotlin
0
1
a0b03bf204e6e681bbe587fdc928bff81e7e67e6
1,565
FUTSale
Apache License 2.0
src/main/no/nav/pto/veilarbfilter/jobs/CleanupVeilederGrupper.kt
navikt
207,477,352
false
null
package no.nav.pto.veilarbfilter.jobs import kotlinx.coroutines.* import no.nav.pto.veilarbfilter.service.MineLagredeFilterServiceImpl import no.nav.pto.veilarbfilter.service.VeilederGrupperServiceImpl import org.slf4j.LoggerFactory import java.util.concurrent.Executors import kotlin.coroutines.CoroutineContext class CleanupVeilederGrupper( val veilederGrupperService: VeilederGrupperServiceImpl, val mineLagredeFilterService: MineLagredeFilterServiceImpl, val interval: Long, val initialDelay: Long? ) : CoroutineScope { private val log = LoggerFactory.getLogger("CleanupVeilederGrupper") private val job = Job() private val singleThreadExecutor = Executors.newSingleThreadExecutor() override val coroutineContext: CoroutineContext get() = job + singleThreadExecutor.asCoroutineDispatcher() fun stop() { job.cancel() singleThreadExecutor.shutdown() } fun start() = launch { initialDelay?.let { delay(it) } while (isActive) { fjernMineFilterMedInaktiveFilter() fjernVeilederSomErIkkeAktive() delay(interval) } } private suspend fun fjernMineFilterMedInaktiveFilter() { try { //mineLagredeFilterService.fjernMineFilterMedInaktiveFilter() } catch (e: Exception) { log.warn("Exception during cleaning up mine filter $e", e) } } private suspend fun fjernVeilederSomErIkkeAktive() { try { log.info("Fjern veileder som er ikke aktive...") veilederGrupperService.hentAlleEnheter().forEach { veilederGrupperService.slettVeiledereSomIkkeErAktivePaEnheten(it) } log.info("Fjern veileder som er ikke aktive er ferdig") } catch (e: Exception) { log.warn("Exception during clanup $e", e) } } }
7
Kotlin
0
0
d1bd1580d40e3cc248c51cf0c35d5cb6e85b62a7
1,912
veilarbfilter
MIT License
app/src/main/java/com/alialfayed/weathertask/BaseApp.kt
alfayedoficial
413,637,765
false
{"Kotlin": 99303}
package com.alialfayed.weathertask import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class BaseApp : Application()
0
Kotlin
3
14
35613123fa86823e09e9e75c16638183628bee19
154
Code95_Weather_Task
The Unlicense
location-details/src/test/java/com/vkondrav/ram/location/details/di/KoinModuleTest.kt
vkondrav
481,052,423
false
null
package com.vkondrav.ram.location.details.di import com.vkondrav.ram.character.common.domain.RamCharacter import com.vkondrav.ram.character.common.factory.CharacterViewItemFactory import com.vkondrav.ram.collapsable.drawer.usecase.FetchCollapsableDrawerStateUseCase import com.vkondrav.ram.collapsable.drawer.usecase.HandleCollapsableDrawerUseCase import com.vkondrav.ram.graphql.RamRepository import com.vkondrav.ram.location.common.domain.RamLocation import com.vkondrav.ram.location.details.domain.RamLocationDetails import com.vkondrav.ram.room.FavoriteCharactersDao import com.vkondrav.ram.room.FavoriteEpisodesDao import com.vkondrav.ram.room.FavoriteLocationsDao import com.vkondrav.ram.test.BaseTest import io.mockk.mockk import kotlinx.coroutines.Dispatchers import org.junit.Test import org.koin.dsl.koinApplication import org.koin.dsl.module import org.koin.test.KoinTest import org.koin.test.check.checkModules class KoinModuleTest : BaseTest(), KoinTest { @Test fun `verify koin module`() { koinApplication { modules( module { // components needed from other modules factory { mockk<RamRepository>() } factory { mockk<FavoriteCharactersDao>() } factory { mockk<FavoriteLocationsDao>() } factory { mockk<FavoriteEpisodesDao>() } factory { mockk<RamLocationDetails.Factory>() } factory { mockk<FetchCollapsableDrawerStateUseCase>() } factory { mockk<HandleCollapsableDrawerUseCase>() } factory { mockk<CharacterViewItemFactory>() } factory { mockk<RamLocation.Factory>() } factory { mockk<RamCharacter.Factory>() } factory { Dispatchers.Unconfined } }, locationDetailsModule, ) checkModules() } } }
0
Kotlin
1
0
78c466563652800d8001a58504a533b764507461
2,429
rick_and_morty_compose
MIT License
location-details/src/test/java/com/vkondrav/ram/location/details/di/KoinModuleTest.kt
vkondrav
481,052,423
false
null
package com.vkondrav.ram.location.details.di import com.vkondrav.ram.character.common.domain.RamCharacter import com.vkondrav.ram.character.common.factory.CharacterViewItemFactory import com.vkondrav.ram.collapsable.drawer.usecase.FetchCollapsableDrawerStateUseCase import com.vkondrav.ram.collapsable.drawer.usecase.HandleCollapsableDrawerUseCase import com.vkondrav.ram.graphql.RamRepository import com.vkondrav.ram.location.common.domain.RamLocation import com.vkondrav.ram.location.details.domain.RamLocationDetails import com.vkondrav.ram.room.FavoriteCharactersDao import com.vkondrav.ram.room.FavoriteEpisodesDao import com.vkondrav.ram.room.FavoriteLocationsDao import com.vkondrav.ram.test.BaseTest import io.mockk.mockk import kotlinx.coroutines.Dispatchers import org.junit.Test import org.koin.dsl.koinApplication import org.koin.dsl.module import org.koin.test.KoinTest import org.koin.test.check.checkModules class KoinModuleTest : BaseTest(), KoinTest { @Test fun `verify koin module`() { koinApplication { modules( module { // components needed from other modules factory { mockk<RamRepository>() } factory { mockk<FavoriteCharactersDao>() } factory { mockk<FavoriteLocationsDao>() } factory { mockk<FavoriteEpisodesDao>() } factory { mockk<RamLocationDetails.Factory>() } factory { mockk<FetchCollapsableDrawerStateUseCase>() } factory { mockk<HandleCollapsableDrawerUseCase>() } factory { mockk<CharacterViewItemFactory>() } factory { mockk<RamLocation.Factory>() } factory { mockk<RamCharacter.Factory>() } factory { Dispatchers.Unconfined } }, locationDetailsModule, ) checkModules() } } }
0
Kotlin
1
0
78c466563652800d8001a58504a533b764507461
2,429
rick_and_morty_compose
MIT License
app/src/main/java/com/futures/jetictors/androidanimlearn/ui/other/motion/MotionActivity.kt
Jetictors
206,535,913
false
null
package com.futures.jetictors.androidanimlearn.ui.other.motion import android.content.Intent import android.widget.ArrayAdapter import com.futures.jetictors.androidanimlearn.R import com.futures.jetictors.androidanimlearn.base.BaseActivity import kotlinx.android.synthetic.main.act_motion.* /** * Desc : MotionLayout布局动画实例 * Author : Jetictors * Time : 2019/9/12 16:18 * Email : <EMAIL> * Version : v-1.0.1 */ class MotionActivity : BaseActivity(){ private val mData : Array<String> by lazy { arrayOf( "1111", "222", "333", "444", "555", "666" ) } override fun getResLayout(): Int { return R.layout.act_motion } override fun initViewAndData() { setToolBar(true, getString(R.string.tx_motion_anim)) this.lv_motion.adapter = ArrayAdapter<String>(this, R.layout.item_layout_anim, R.id.tv_item, mData) this.lv_motion.setOnItemClickListener { _, _, pos, _ -> when(pos){ 0 -> setIntentClass(MotionFirstActivity::class.java) 1 -> setIntentClass(MotionFirstActivity::class.java) 2 -> setIntentClass(MotionFirstActivity::class.java) 3 -> setIntentClass(MotionFirstActivity::class.java) 4 -> setIntentClass(MotionFirstActivity::class.java) 5 -> setIntentClass(MotionFirstActivity::class.java) } } } private fun setIntentClass(clazz: Class<*>){ val intent = Intent(this, clazz) startActivity(intent) } }
0
Kotlin
0
1
3a20d71139004563a70415961b01fe6674356cf5
1,596
android-anim-demo
Apache License 2.0
library/src/main/java/com/damianogiusti/statedispatcher/internal/ScreenCreatorFactory.kt
damianogiusti
130,755,941
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 17, "XML": 13, "Java": 2}
package com.damianogiusti.statedispatcher.internal import android.view.ViewGroup import com.damianogiusti.statedispatcher.ScreenCreator import com.damianogiusti.statedispatcher.ScreenState import kotlin.reflect.KClass /** * Created by <NAME> on 23/04/18. */ internal interface ScreenCreatorFactory { fun newScreenCreator( container: Lazy<ViewGroup>, screensAndLayouts: Map<KClass<out ScreenState>, Int> ): ScreenCreator companion object { fun newInstance(): ScreenCreatorFactory = ScreenCreatorFactoryImpl() } } private class ScreenCreatorFactoryImpl : ScreenCreatorFactory { override fun newScreenCreator( container: Lazy<ViewGroup>, screensAndLayouts: Map<KClass<out ScreenState>, Int> ): ScreenCreator { return ScreenCreatorImpl(container, screensAndLayouts) } }
0
Kotlin
0
0
b5bd47653f50bb5b8aadc6fe6372f0fddda4f9f8
850
state-dispatcher
Apache License 2.0
library/src/main/java/com/damianogiusti/statedispatcher/internal/ScreenCreatorFactory.kt
damianogiusti
130,755,941
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 17, "XML": 13, "Java": 2}
package com.damianogiusti.statedispatcher.internal import android.view.ViewGroup import com.damianogiusti.statedispatcher.ScreenCreator import com.damianogiusti.statedispatcher.ScreenState import kotlin.reflect.KClass /** * Created by <NAME> on 23/04/18. */ internal interface ScreenCreatorFactory { fun newScreenCreator( container: Lazy<ViewGroup>, screensAndLayouts: Map<KClass<out ScreenState>, Int> ): ScreenCreator companion object { fun newInstance(): ScreenCreatorFactory = ScreenCreatorFactoryImpl() } } private class ScreenCreatorFactoryImpl : ScreenCreatorFactory { override fun newScreenCreator( container: Lazy<ViewGroup>, screensAndLayouts: Map<KClass<out ScreenState>, Int> ): ScreenCreator { return ScreenCreatorImpl(container, screensAndLayouts) } }
0
Kotlin
0
0
b5bd47653f50bb5b8aadc6fe6372f0fddda4f9f8
850
state-dispatcher
Apache License 2.0
src/main/kotlin/a11y/utils/Icons.kt
ApplauseOSS
225,913,356
false
null
package a11y.utils import com.intellij.openapi.util.IconLoader object Icons { val APPLAUSE = IconLoader.getIcon("/icons/icon.png") }
0
Kotlin
0
1
f3ec03d047826f945fbdade421da7b8917e91e5f
140
applause-a11y-fixer-plugin-intellij
MIT License
solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvableImpl.kt
tuProlog
230,784,338
false
{"Kotlin": 3949669, "Java": 18690, "ANTLR": 10366, "CSS": 1535, "JavaScript": 894, "Prolog": 818}
package it.unibo.tuprolog.solve.concurrent import it.unibo.tuprolog.solve.Signature import it.unibo.tuprolog.solve.SolverFactory import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlin.test.Test class TestConcurrentNotProvableImpl : TestConcurrentNotProvable<MultiSet>, SolverFactory by ConcurrentSolverFactory, FromSequence<MultiSet> by ConcurrentFromSequence { override val errorSignature: Signature = Signature("ensure_executable", 1) @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNPTrue() = multiRunConcurrentTest { super.testNPTrue() } @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNPCut() = multiRunConcurrentTest { super.testNPCut() } @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNPCutFail() = multiRunConcurrentTest { super.testNPCutFail() } @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testOrNotCutFail() = multiRunConcurrentTest { super.testOrNotCutFail() } @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNPEquals() = multiRunConcurrentTest { super.testNPEquals() } @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNPNum() = multiRunConcurrentTest { super.testNPNum() } @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNPX() = multiRunConcurrentTest { super.testNPX() } }
92
Kotlin
14
93
3223ffc302e5da0efe2b254045fa1b6a1a122519
1,418
2p-kt
Apache License 2.0
newm-chain/src/main/kotlin/io/newm/chain/grpc/GrpcConfig.kt
projectNEWM
447,979,150
false
null
package io.newm.chain.grpc import io.grpc.netty.GrpcSslContexts import io.grpc.netty.NettyServerBuilder import io.ktor.server.config.ApplicationConfig import io.newm.chain.cardano.randomHex import io.newm.ktor.server.grpc.GRPCApplicationEngine import io.sentry.Sentry import kotlinx.coroutines.CancellationException import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import nl.altindag.ssl.SSLFactory import nl.altindag.ssl.util.KeyManagerUtils import nl.altindag.ssl.util.NettySslUtils import nl.altindag.ssl.util.PemUtils import org.slf4j.Logger import org.slf4j.LoggerFactory import java.nio.file.Files import java.nio.file.Paths import java.nio.file.attribute.BasicFileAttributes import javax.net.ssl.X509ExtendedKeyManager import kotlin.io.path.absolutePathString import kotlin.io.path.exists object GrpcConfig { // Cannot use DI here as GRPC is initialized before it is available. private val log: Logger by lazy { LoggerFactory.getLogger("GrpcConfig") } val init: GRPCApplicationEngine.Configuration.(appConfig: ApplicationConfig) -> Unit = { appConfig -> this.serverConfigurer = { try { // Enable JWT authorization intercept(JwtAuthorizationServerInterceptor(appConfig.config("jwt"))) val grpcConfig = appConfig.config("grpc") val certChain = Paths.get( grpcConfig.propertyOrNull("sslCertChainPath")?.getString() ?: "/nonexistent_${randomHex(16)}.pem" ) val privateKey = Paths.get( grpcConfig.propertyOrNull("sslPrivateKeyPath")?.getString() ?: "/nonexistent_${randomHex(16)}.pem" ) if (certChain.exists() && privateKey.exists()) { (this as? NettyServerBuilder)?.let { nettyServerBuilder -> log.warn("gRPC Secured with TLS") val keyManager: X509ExtendedKeyManager = PemUtils.loadIdentityMaterial(certChain, privateKey) val sslFactory = SSLFactory.builder() .withIdentityMaterial(keyManager) .withSwappableIdentityMaterial() .build() val sslContext = GrpcSslContexts.configure(NettySslUtils.forServer(sslFactory)).build() nettyServerBuilder.sslContext(sslContext) @OptIn(DelicateCoroutinesApi::class) GlobalScope.launch { var privateKeyLastModified = withContext(Dispatchers.IO) { Files.readAttributes(privateKey, BasicFileAttributes::class.java).lastModifiedTime() } var certChainLastModified = withContext(Dispatchers.IO) { Files.readAttributes(certChain, BasicFileAttributes::class.java).lastModifiedTime() } while (true) { try { delay(60000L) val checkPrivateKeyLastModified = withContext(Dispatchers.IO) { Files.readAttributes(privateKey, BasicFileAttributes::class.java) .lastModifiedTime() } val checkCertChainLastModified = withContext(Dispatchers.IO) { Files.readAttributes(certChain, BasicFileAttributes::class.java) .lastModifiedTime() } if (privateKeyLastModified != checkPrivateKeyLastModified || certChainLastModified != checkCertChainLastModified) { // data has changed. reload it val newKeyManager: X509ExtendedKeyManager = PemUtils.loadIdentityMaterial(certChain, privateKey) KeyManagerUtils.swapKeyManager(sslFactory.keyManager.get(), newKeyManager) privateKeyLastModified = checkPrivateKeyLastModified certChainLastModified = checkCertChainLastModified log.warn("RELOADED SSL CERTIFICATES!!!") } } catch (e: CancellationException) { throw e } catch (e: Throwable) { Sentry.captureException(e) log.error("Error with SSL Certificate Reload!", e) } } } } ?: log.error("gRPC TLS Failed: ServerBuilder is not a NettyServerBuilder!") } else { log.warn("gRPC Unsecured with plaintext") if (!certChain.exists()) { log.warn("File not found: ${certChain.absolutePathString()}") } if (!privateKey.exists()) { log.warn("File not found: ${privateKey.absolutePathString()}") } } } catch (e: Throwable) { log.error("Error configuring GRPC!", e) } } } }
0
Kotlin
3
7
f787d9903cd701afd756bdc09b61e5a489cc95c5
5,768
newm-server
Apache License 2.0
app/src/main/java/com/raikwaramit/cryptoatlas/presentation/graph/RootNavGraph.kt
raikwaramit
674,264,028
false
null
package com.raikwaramit.cryptoatlas.presentation.graph import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.raikwaramit.cryptoatlas.common.Constants import com.raikwaramit.cryptoatlas.presentation.detail.DetailScreen import com.raikwaramit.cryptoatlas.presentation.graph.screen.DetailScreenRoute /** * Root navigation graph for the app. */ @Composable fun RootNavGraph(navController: NavHostController) { NavHost( navController = navController, route = Graph.ROOT, startDestination = Graph.HOME ) { homeNavGraph( navController = navController, onDetailScreenOpenRequest = { coinId -> navController.navigate(Graph.DETAIL + "?${Constants.COIN_ID}=$coinId") }, onFavoriteScreenOpenRequest = { navController.navigate(Graph.DETAIL + "?route=${DetailScreenRoute.FavoriteScreen.route}") } ) // To open the screens of detail screen flow with different arguments. composable(route = Graph.DETAIL + "?${Constants.COIN_ID}={${Constants.COIN_ID}}&route={route}") { entry -> val route = entry.arguments?.getString("route") DetailScreen(startDestination = route) } } } object Graph { const val ROOT = "root_graph" const val HOME = "home_graph" const val DETAIL = "detail_graph" }
0
Kotlin
0
0
63faebc30f4456aae35f401326c69c9df59c4572
1,509
CryptoAtlas
MIT License
app/src/main/java/cn/zfs/bledemo/ConnectionActivity.kt
philip858
148,437,941
false
{"Java": 125149, "Kotlin": 10572}
package cn.zfs.bledemo import android.os.Bundle import android.support.v7.app.AppCompatActivity import cn.zfs.blelib.core.Ble import cn.zfs.blelib.core.Connection import cn.zfs.blelib.core.ConnectionConfig import cn.zfs.blelib.core.Device import cn.zfs.blelib.event.Events import cn.zfs.common.utils.ToastUtils import kotlinx.android.synthetic.main.activity_connection.* import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode /** * 描述: * 时间: 2018/6/16 14:01 * 作者: zengfansheng */ class ConnectionActivity : AppCompatActivity() { private var device: Device? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = "功能列表" setContentView(R.layout.activity_connection) device = intent.getParcelableExtra(Consts.EXTRA_DEVICE) Ble.getInstance().registerSubscriber(this) Ble.getInstance().connect(this, device!!, getConnectionConfig(true), null) tvName.text = device!!.name tvAddr.text = device!!.addr } private fun getConnectionConfig(autoReconnect: Boolean): ConnectionConfig { val config = ConnectionConfig.newInstance() config.setDiscoverServicesDelayMillis(500) config.isAutoReconnect = autoReconnect return config } @Subscribe(threadMode = ThreadMode.MAIN) fun onConnectionStateChange(e: Events.ConnectionStateChanged) { when (e.state) { Connection.STATE_CONNECTED -> { tvState.text = "连接成功,等待发现服务" } Connection.STATE_CONNECTING -> { tvState.text = "连接中..." } Connection.STATE_DISCONNECTED -> { tvState.text = "连接断开" ToastUtils.showShort("连接断开") } Connection.STATE_SCANNING -> { tvState.text = "正在搜索设备..." } Connection.STATE_SERVICE_DISCOVERING -> { tvState.text = "连接成功,正在发现服务..." } Connection.STATE_SERVICE_DISCOVERED -> { tvState.text = "连接成功,并成功发现服务" } Connection.STATE_RELEASED -> { tvState.text = "连接已释放" } } invalidateOptionsMenu() } @Subscribe(threadMode = ThreadMode.MAIN) fun onConnectFailed(e: Events.ConnectFailed) { tvState.text = "连接失败: ${e.type}" } @Subscribe(threadMode = ThreadMode.MAIN) fun onConnectTimeout(e: Events.ConnectTimeout) { val msg = when(e.type) { Connection.TIMEOUT_TYPE_CANNOT_DISCOVER_DEVICE -> "无法搜索到设备" Connection.TIMEOUT_TYPE_CANNOT_CONNECT -> "无法连接设备" else -> "无法发现蓝牙服务" } ToastUtils.showShort("连接超时:$msg") } override fun onDestroy() { super.onDestroy() Ble.getInstance().unregisterSubscriber(this) Ble.getInstance().releaseConnection(device)//销毁连接 } }
1
Java
1
1
92260ffd02a04471b69155f6fce74f430b3aab70
2,993
blecore
Apache License 2.0
app/src/main/java/com/iso/easyhodling/ui/trading/TradingFragment.kt
cas1201
406,306,018
false
null
package com.iso.easyhodling.ui.trading import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.iso.easyhodling.R import com.iso.easyhodling.databinding.TradingFragmentBinding class TradingFragment : Fragment() { private lateinit var tradingViewModel: TradingViewModel private var _binding: TradingFragmentBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { tradingViewModel = ViewModelProvider(this).get(TradingViewModel::class.java) _binding = TradingFragmentBinding.inflate(inflater, container, false) val root: View = binding.root binding.buyButton.setOnClickListener { var assetToUse = binding.monedaParaUsar.text.toString().uppercase() var assetToOperate = binding.monedaAOperar.text.toString().uppercase() var quantity = binding.quantity.text.toString() tradingViewModel.buy(requireContext(), assetToUse, assetToOperate, quantity.toDouble()) } binding.sellButton.setOnClickListener { var assetToUse = binding.monedaParaUsar.text.toString().uppercase() var assetToOperate = binding.monedaAOperar.text.toString().uppercase() var quantity = binding.quantity.text.toString() tradingViewModel.sell(requireContext(), assetToOperate, assetToUse, quantity.toDouble()) } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
f7774ca849708184d81fdbe24b4e70356af2ce56
1,797
ISOApp
MIT License
buildSrc/src/main/java/io/github/chenfei0928/walle/Walle.kt
chenfei0928
130,954,695
false
null
package io.github.chenfei0928.walle import com.google.common.io.Files import com.meituan.android.walle.GradlePlugin import io.github.chenfei0928.Contract import io.github.chenfei0928.bean.ApkVariantInfo import io.github.chenfei0928.util.buildOutputsDir import io.github.chenfei0928.util.buildSrcAndroid import io.github.chenfei0928.util.checkApp import io.github.chenfei0928.util.child import io.github.chenfei0928.util.forEachAssembleTasks import io.github.chenfei0928.util.implementation import org.gradle.api.Project import org.gradle.api.Task import org.gradle.kotlin.dsl.dependencies import org.joor.Reflect import java.io.File import java.util.Locale /** * 使用打包脚本CLI进行处理,此处不依赖plugin * 美团官方维护的版本不支持V3签名,使用的版本为:https://github.com/Meituan-Dianping/walle/issues/264 * * 生成签名任务可以参考[com.meituan.android.walle.GradlePlugin.applyTask]和 * [com.meituan.android.walle.ChannelMaker.generateChannelApk] * walle * * @date 2021-11-16 15:00 */ fun Project.applyAppWalle() { checkApp("applyAppWalle") val walleVersion: String = Reflect.onClass(GradlePlugin::class.java) .call("getVersion").get() // 自处理打渠道号流程,不使用Plugin处理,以避免引入了其他Plugin后无法共存 // 也不使用CLI,减少打包流程人工操作的量或额外编写打包后处理脚本 // 美团官方维护的版本不支持V3签名,使用的版本为:https://github.com/Meituan-Dianping/walle/issues/264 dependencies { // https://github.com/Meituan-Dianping/walle implementation("com.meituan.android.walle:library:$walleVersion") } // 此时主build.gradle.kts还未执行完毕,等待project configure完毕后,根据生成的编译任务添加渠道信息注入task afterEvaluate { val appExt = buildSrcAndroid<com.android.build.gradle.AppExtension>() // 读取所有编译任务输出文件路径 val outputsApkPath: List<Pair<ApkVariantInfo, File>> = appExt.applicationVariants.flatMap { variant -> variant.outputs.map { ApkVariantInfo(variant) to it.outputFile } } // 读取所有buildTypes val buildTypeNames: List<String> = appExt.buildTypes.map { it.name } // 根据buildTypes创建属于该buildType的全flavor编译任务,并在之后对该project的所有task遍历中将其添加到该task的依赖中 val buildTypesAllFlavorTask: Map<String, Task> = buildTypeNames.associateWith { buildType -> return@associateWith task( Contract.ASSEMBLE_TASK_PREFIX + buildType.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() } + MAKE_CHANNEL_TASK_SUFFIX ) { outputs.dir(buildOutputsDir.child { CHANNELS_APK_OUTPUT_DIR_NAME / buildType }) description = "Make Multi-Channel by Meituan Walle" group = "Channel" doLast { val outputDir: File = outputs.files.singleFile if (!outputDir.exists()) { outputDir.mkdirs() } // 如果不只是general productFlavor,则说明是全渠道打包,将其它的productFlavors输出文件复制到最终输出目录 outputsApkPath.forEach { (variant, apkFile) -> if (variant.buildTypeName.equals(buildType, true)) { val channels = File( apkFile.parentFile, ChannelMaker.CHANNELS_APK_OUTPUT_DIR_NAME ) if (channels.exists()) { channels.listFiles()?.forEach { Files.copy(it, File(outputDir, it.name)) } } else { Files.copy(apkFile, File(outputDir, apkFile.name)) } } } } } } forEachAssembleTasks { assembleTask, taskInfo -> if (taskInfo.dimensionedFlavorName.isNotEmpty()) { // 当前dimensionedFlavorName的渠道信息文件 val channelFile: File = project.projectDir.child { CHANNELS_PROFILE_DIR / taskInfo.dimensionedFlavorName } // 对当前的flavor+buildType的输出文件加渠道号 val (variant, targetFlavorBuildTypeApkFile) = outputsApkPath .find { (variant, _) -> variant.name == taskInfo.targetFlavorBuildTypeVariantName } ?: throw IllegalArgumentException("没有找到 ${taskInfo.targetFlavorBuildTypeVariantName} 输出apk文件") val channelOutputFolder = File(targetFlavorBuildTypeApkFile.parentFile, CHANNELS_APK_OUTPUT_DIR_NAME) // 某个productFlavor-buildType的渠道包任务 val assembleSomeBuildTypeChannels: Task = task(assembleTask.name + MAKE_CHANNEL_TASK_SUFFIX) { inputs.file(channelFile) outputs.dir(channelOutputFolder) description = "Make Multi-Channel by <NAME>" group = "Channel" doLast { // 收集包信息 val nameVariantMap = mutableMapOf<String, String?>( "appName" to project.name, "projectName" to project.rootProject.name, "buildType" to variant.buildTypeName, "versionName" to variant.versionName, "versionCode" to variant.versionCode.toString(), "packageName" to variant.applicationId, "flavorName" to variant.flavorName ) val outputDir: File = outputs.files.singleFile if (!outputDir.exists()) { outputDir.mkdirs() } // 读取渠道号,并生成签名后的apk包 ChannelMaker.getChannelListFromFile(channelFile).forEach { ChannelMaker.generateChannelApk( apkFile = targetFlavorBuildTypeApkFile, channelOutputFolder = outputDir, nameVariantMap = nameVariantMap, channel = it ) } } } // 要求该任务在标准Apk编译任务完成后进行执行 // 使自己的assembleSomeBuildTypeChannels task依赖其(assembleTask),并在其编译后对输出文件注入渠道号 assembleSomeBuildTypeChannels.dependsOn(assembleTask) // 只有渠道信息文件存在,该task才可用 assembleSomeBuildTypeChannels.onlyIf { channelFile.exists() } // 将该注入渠道名任务依赖到对应buildType的全渠道Task中 buildTypesAllFlavorTask[taskInfo.buildType]!!.dependsOn( assembleSomeBuildTypeChannels ) } } } } /** * 打入渠道的文件的输出文件夹名 */ private const val CHANNELS_APK_OUTPUT_DIR_NAME = ChannelMaker.CHANNELS_APK_OUTPUT_DIR_NAME /** * 打入渠道号的任务名后缀,打渠道包任务命名规则为 * ```assemble[DimensionedFlavorName][BuildType]Channels``` */ private const val MAKE_CHANNEL_TASK_SUFFIX = "Channels" /** * 渠道配置目录名,以flavor名创建文件,内配置要打入的渠道名列表 */ private const val CHANNELS_PROFILE_DIR = "channels"
1
null
0
8
bbe587216a2450deb19af90ea4d7d24d23443dd1
7,404
Util
MIT License
LogisticManager/src/main/kotlin/init/UtilsToInitMainNodes.kt
ostis-apps
209,274,423
false
{"C++": 190974, "Python": 158695, "JavaScript": 121504, "Kotlin": 28151, "CSS": 16444, "CMake": 15212, "Shell": 13239, "HTML": 5019, "Dockerfile": 1567}
package init import engine.Factory import engine.Shop import engine.StopLocation import engine.Warehouse import org.ostis.api.context.UncheckedScContext import org.ostis.scmemory.model.element.edge.EdgeType import org.ostis.scmemory.model.element.link.LinkType import org.ostis.scmemory.model.element.node.NodeType import org.ostis.scmemory.model.element.node.ScNode import org.ostis.scmemory.websocketmemory.memory.SyncOstisScMemory import java.lang.RuntimeException import java.net.URI import java.nio.file.Files import java.nio.file.Paths import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.io.path.name private val scMemory = SyncOstisScMemory(URI("ws://localhost:8090/ws_json")); private val scContext = UncheckedScContext(scMemory); private val warehouses = ArrayList<Warehouse>(); fun initAll() { scMemory.open(); val draftWarehousesLink = HashMap<Warehouse, Map<String, Int>>(); val nameToWarehouseMap = HashMap<String, Warehouse>(); val projectDirAbsolutePath = Paths.get("").toAbsolutePath().toString() val resourcesPath = Paths.get(projectDirAbsolutePath, "/src/main/resources/warehouses") Files.walk(resourcesPath).filter { item -> Files.isRegularFile(item) }.forEach { warehouseFile -> val shops = HashMap<Shop, Int>() val factories = HashMap<Factory, Int>() val connectedWarehouses = HashMap<Warehouse, Int>() val linksForCurrentWarehouse = HashMap<String, Int>(); Files.readAllLines(warehouseFile).stream().forEach { val arr = it.split(" ") if (arr[0] == "F") factories[Factory(arr[1])] = arr[2].toInt() else if (arr[0] == "S") shops[Shop(arr[1])] = arr[2].toInt() else if (arr[0] == "W") linksForCurrentWarehouse[arr[1]] = arr[2].toInt() else throw RuntimeException("Can't parse letter '${arr[0]}'") } val newWarehouse = Warehouse(warehouseFile.fileName.name, shops, factories, connectedWarehouses) nameToWarehouseMap[newWarehouse.name] = newWarehouse; draftWarehousesLink[newWarehouse] = linksForCurrentWarehouse; warehouses.add(newWarehouse) } initWarehouses(); draftWarehousesLink.forEach{(warehouse, linkedWarehouses)-> run { linkedWarehouses.forEach { (otherWarehouse, distance) -> run { val x = nameToWarehouseMap[otherWarehouse]; if (x!=null) warehouse.connectedWarehouse[x] = distance; } } } } scMemory.close(); } fun initWarehouses() { val warehouseClass = scContext.resolveKeynode("warehouse", NodeType.CLASS); val factoryClass = scContext.resolveKeynode("factory", NodeType.CLASS); val shopClass = scContext.resolveKeynode("shop", NodeType.CLASS); val warehouseNameRel = scContext.resolveKeynode("warehouseName*", NodeType.CONST_NO_ROLE); val factoryNameRel = scContext.resolveKeynode("factoryName*", NodeType.CONST_NO_ROLE); val shopNameRel = scContext.resolveKeynode("shopName*", NodeType.CONST_NO_ROLE); val nameToFactoryMap = HashMap<String, ScNode>(); val nameToShopMap = HashMap<String, ScNode>(); warehouses.stream().forEach { val warehouseNode = scContext.createNode(NodeType.NODE); scContext.createEdge( EdgeType.ACCESS, warehouseClass, warehouseNode ); //mean that warehouseNode has class warehouse. val warehouseNameLink = scContext.createStringLink(LinkType.LINK, it.name); val warehouseToNameEdge = scContext.createEdge(EdgeType.D_COMMON, warehouseNode, warehouseNameLink); scContext.createEdge(EdgeType.ACCESS, warehouseNameRel, warehouseToNameEdge); initDependedNodes(it.connectedShops, warehouseNode, shopClass, shopNameRel, nameToShopMap); initDependedNodes(it.connectedFactories, warehouseNode, factoryClass, factoryNameRel, nameToFactoryMap); } scContext.resolveKeynode("freightOrder", NodeType.CLASS); scContext.resolveKeynode("executionStarted", NodeType.CLASS); scContext.resolveKeynode("stop'", NodeType.ROLE); } fun initDependedNodes( connectedShops: MutableMap<out StopLocation, Int>, warehouseNode: ScNode, nodeClass: ScNode, nodeRelToName: ScNode, cacheNameRel: HashMap<String, ScNode> ) { connectedShops.forEach { (location, distance) -> val currentNode: ScNode? if (cacheNameRel.containsKey(location.name)) { currentNode = cacheNameRel[location.name] } else { currentNode = scContext.createNode(NodeType.NODE) scContext.createEdge(EdgeType.ACCESS, nodeClass, currentNode) val nodeNameLink = scContext.createStringLink(LinkType.LINK, location.name) val nodeToNameEdge = scContext.createEdge(EdgeType.D_COMMON, currentNode, nodeNameLink); scContext.createEdge(EdgeType.ACCESS, nodeRelToName, nodeToNameEdge); cacheNameRel[location.name] = currentNode } val toWarehouseDistance = scContext.createIntegerLink(LinkType.LINK, distance); val warehouseShopRoad = scContext.createEdge(EdgeType.U_COMMON, warehouseNode, currentNode); scContext.createEdge(EdgeType.ACCESS, toWarehouseDistance, warehouseShopRoad); } } fun main() { initAll() }
46
C++
128
2
dade10e5ffdb02a7cd7dab3ebeb83496ac43d5ae
5,336
ostis-geography
MIT License
composeApp/src/commonMain/kotlin/com/chipmunksmedia/helldivers/remote/ui/components/transmissions/TransmissionsList.kt
malliaridis
781,833,057
false
{"Kotlin": 222649, "Swift": 1167}
package com.chipmunksmedia.helldivers.remote.ui.components.transmissions import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.chipmunksmedia.helldivers.remote.model.TransmissionListEntry import com.chipmunksmedia.helldivers.remote.ui.components.StripesDecorator import com.chipmunksmedia.helldivers.remote.ui.theme.CustomColors import com.chipmunksmedia.helldivers.remote.ui.theme.Modifiers.border @Composable fun TransmissionsList( modifier: Modifier = Modifier, transmissions: List<TransmissionListEntry>, onSelectTransmission: (String) -> Unit, selectedTransmissionId: String? = null, ) = StripesDecorator( modifier = modifier.border( top = 1.5.dp, color = CustomColors.borderColorVariant, ) ) { LazyColumn( modifier = Modifier.padding(top = 1.5.dp), // to avoid overlap with border contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { items(transmissions) { transmission -> TransmissionListItem( transmission = transmission, isSelected = transmission.id == selectedTransmissionId, onClick = { onSelectTransmission(transmission.id) }, ) } } }
1
Kotlin
0
3
5a0b3860f3df1c719f73257f8683a868438aafd2
1,580
tactical-user-interface
MIT License
backend/telegram/src/main/kotlin/ru/sokomishalov/memeory/telegram/dto/BotCallbackQueryDTO.kt
sokomishalov
191,372,605
false
null
package ru.sokomishalov.memeory.telegram.dto import ru.sokomishalov.memeory.telegram.enum.BotScreen /** * @author sokomishalov */ data class BotCallbackQueryDTO( val screen: BotScreen? = null, val id: String? = null )
20
Kotlin
0
0
2372aff4bcefecad273b56e52e5d501b4ec5c839
237
memeory
MIT License
src/com/github/OpenICP_BR/ktLib/Signature.kt
OpenICP-BR
150,466,067
false
null
package com.github.OpenICP_BR.ktLib import org.bouncycastle.asn1.cms.CMSAttributes import org.bouncycastle.asn1.DERUTCTime import org.bouncycastle.asn1.ASN1UTCTime import org.bouncycastle.cms.* import java.lang.Exception import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder import org.bouncycastle.cert.X509CertificateHolder import org.bouncycastle.cms.SignerInformation import org.bouncycastle.util.Selector import java.io.File import java.security.cert.X509Certificate import java.util.* /** * Represents a single CAdES signature * * @property base the "raw" signature object used by Bouncy Castle * @property signerId identifies which signature we are talking about. */ class Signature(val base: CMSSignedData) { var realSignerId: SignerId? = null val signerId: SignerId get () { if (realSignerId != null) { return realSignerId!! } if (base.signerInfos.size() == 1) { return base.signerInfos.signers.iterator().next().sid } else { throw ICPException( "MULTIPLE_SIGNER_INFOS", "this signature has multiple signers and it is not clear which one we are talking about", "essa assiantura tem múltiplos signatários e não está claro sobre qual estamos falando") } } val signer: SignerInformation get () { if (base.signerInfos.size() == 1) { return base.signerInfos.signers.iterator().next() } else { return base.signerInfos[signerId] } } val cert: X509CertificateHolder get() { try { return base.certificates.getMatches(signer.sid as Selector<X509CertificateHolder>).iterator().next() } catch (e: Exception) { throw FailedToGetCertificateFromSignatureException(e) } } val date: Date get() { try { val attr = base.signerInfos[signerId].signedAttributes.get(CMSAttributes.signingTime) val en = attr.attrValues.objects while (en.hasMoreElements()) { val obj = en.nextElement() if (obj is ASN1UTCTime) { return obj.date } else if (obj is DERUTCTime) { return obj.date } else if (obj is org.bouncycastle.asn1.cms.Time) { return obj.date } } } catch (e: Exception) { throw ICPExceptionWithEncapsulation( e, "SIGNING_TIME_NOT_FOUND", "this signature has no signing time", "essa assinatura não tem a data de assinatura") } throw ICPException( "SIGNING_TIME_NOT_FOUND", "this signature has no signing time", "essa assinatura não tem a data de assinatura") } constructor(base: CMSSignedData, signerId: SignerId): this(base) { this.realSignerId = signerId } /** * Verifies if the integrity of this signature. This is, if the message has not been modified. No checks are made as to whether the certificate itself is valid or not. */ fun verify(): Boolean { try { return signer.verify(JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)) } catch (e: Exception) { throw FailedToVerifySignatureException(e) } } /** * The same as verify(), but checks all signatures within this.base. */ internal fun verifyAll(): Boolean { val certStore = base.certificates val signers = base.signerInfos val c = signers.signers val it = c.iterator() while (it.hasNext()) { val signer = it.next() as SignerInformation val certCollection = certStore.getMatches(signer.sid as Selector<X509CertificateHolder>) val certIt = certCollection.iterator() val cert = certIt.next() as X509CertificateHolder if (!signer.verify(JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) { return false } } return true } fun save(path: String) { File(path).writeBytes(this.base.encoded) } }
0
Kotlin
0
0
9943b8fb37f5ea8021e63f11f9307946f37922de
4,517
ktLib
RSA Message-Digest License
common/src/commonMain/kotlin/io/config4k/blocking/PropertyLoader.kt
Matt1Krause
323,059,657
false
null
package io.config4k.blocking import io.config4k.EmptyPropertyPath import io.config4k.PropertyName import io.config4k.PropertyPath interface PropertyLoader { fun doesNotHave(propertyPath: PropertyPath, pathEnd: PropertyName): Boolean fun doesNotHave(pathEnd: PropertyName): Boolean = doesNotHave(EmptyPropertyPath, pathEnd) fun loadByte(propertyPath: PropertyPath, pathEnd: PropertyName): Byte fun loadShort(propertyPath: PropertyPath, pathEnd: PropertyName): Short fun loadInt(propertyPath: PropertyPath, pathEnd: PropertyName): Int fun loadLong(propertyPath: PropertyPath, pathEnd: PropertyName): Long fun loadFloat(propertyPath: PropertyPath, pathEnd: PropertyName): Float fun loadDouble(propertyPath: PropertyPath, pathEnd: PropertyName): Double @ExperimentalUnsignedTypes fun loadUByte(propertyPath: PropertyPath, pathEnd: PropertyName): UByte @ExperimentalUnsignedTypes fun loadUShort(propertyPath: PropertyPath, pathEnd: PropertyName): UShort @ExperimentalUnsignedTypes fun loadUInt(propertyPath: PropertyPath, pathEnd: PropertyName): UInt @ExperimentalUnsignedTypes fun loadULong(propertyPath: PropertyPath, pathEnd: PropertyName): ULong fun loadBoolean(propertyPath: PropertyPath, pathEnd: PropertyName): Boolean fun loadString(propertyPath: PropertyPath, pathEnd: PropertyName): String fun loadByteArray(propertyPath: PropertyPath, pathEnd: PropertyName): ByteArray fun loadShortArray(propertyPath: PropertyPath, pathEnd: PropertyName): ShortArray fun loadIntArray(propertyPath: PropertyPath, pathEnd: PropertyName): IntArray fun loadLongArray(propertyPath: PropertyPath, pathEnd: PropertyName): LongArray fun loadFloatArray(propertyPath: PropertyPath, pathEnd: PropertyName): FloatArray fun loadDoubleArray(propertyPath: PropertyPath, pathEnd: PropertyName): DoubleArray @ExperimentalUnsignedTypes fun loadUByteArray(propertyPath: PropertyPath, pathEnd: PropertyName): UByteArray @ExperimentalUnsignedTypes fun loadUShortArray(propertyPath: PropertyPath, pathEnd: PropertyName): UShortArray @ExperimentalUnsignedTypes fun loadUIntArray(propertyPath: PropertyPath, pathEnd: PropertyName): UIntArray @ExperimentalUnsignedTypes fun loadULongArray(propertyPath: PropertyPath, pathEnd: PropertyName): ULongArray fun loadBooleanArray(propertyPath: PropertyPath, pathEnd: PropertyName): BooleanArray fun loadStringArray(propertyPath: PropertyPath, pathEnd: PropertyName): Array<String> fun loadByte(pathEnd: PropertyName): Byte = loadByte(EmptyPropertyPath, pathEnd) fun loadShort(pathEnd: PropertyName): Short = loadShort(EmptyPropertyPath, pathEnd) fun loadInt(pathEnd: PropertyName): Int = loadInt(EmptyPropertyPath, pathEnd) fun loadLong(pathEnd: PropertyName): Long = loadLong(EmptyPropertyPath, pathEnd) fun loadFloat(pathEnd: PropertyName): Float = loadFloat(EmptyPropertyPath, pathEnd) fun loadDouble(pathEnd: PropertyName): Double = loadDouble(EmptyPropertyPath, pathEnd) @ExperimentalUnsignedTypes fun loadUByte(pathEnd: PropertyName): UByte = loadUByte(EmptyPropertyPath, pathEnd) @ExperimentalUnsignedTypes fun loadUShort(pathEnd: PropertyName): UShort = loadUShort(EmptyPropertyPath, pathEnd) @ExperimentalUnsignedTypes fun loadUInt(pathEnd: PropertyName): UInt = loadUInt(EmptyPropertyPath, pathEnd) @ExperimentalUnsignedTypes fun loadULong(pathEnd: PropertyName): ULong = loadULong(EmptyPropertyPath, pathEnd) fun loadBoolean(pathEnd: PropertyName): Boolean = loadBoolean(EmptyPropertyPath, pathEnd) fun loadString(pathEnd: PropertyName): String = loadString(EmptyPropertyPath, pathEnd) fun loadByteArray(pathEnd: PropertyName): ByteArray = loadByteArray(EmptyPropertyPath, pathEnd) fun loadShortArray(pathEnd: PropertyName): ShortArray = loadShortArray(EmptyPropertyPath, pathEnd) fun loadIntArray(pathEnd: PropertyName): IntArray = loadIntArray(EmptyPropertyPath, pathEnd) fun loadLongArray(pathEnd: PropertyName): LongArray = loadLongArray(EmptyPropertyPath, pathEnd) fun loadFloatArray(pathEnd: PropertyName): FloatArray = loadFloatArray(EmptyPropertyPath, pathEnd) fun loadDoubleArray(pathEnd: PropertyName): DoubleArray = loadDoubleArray(EmptyPropertyPath, pathEnd) @ExperimentalUnsignedTypes fun loadUByteArray(pathEnd: PropertyName): UByteArray = loadUByteArray(EmptyPropertyPath, pathEnd) @ExperimentalUnsignedTypes fun loadUShortArray(pathEnd: PropertyName): UShortArray = loadUShortArray(EmptyPropertyPath, pathEnd) @ExperimentalUnsignedTypes fun loadUIntArray(pathEnd: PropertyName): UIntArray = loadUIntArray(EmptyPropertyPath, pathEnd) @ExperimentalUnsignedTypes fun loadULongArray(pathEnd: PropertyName): ULongArray = loadULongArray(EmptyPropertyPath, pathEnd) fun loadBooleanArray(pathEnd: PropertyName): BooleanArray = loadBooleanArray(EmptyPropertyPath, pathEnd) fun loadStringArray(pathEnd: PropertyName): Array<String> = loadStringArray(EmptyPropertyPath, pathEnd) }
0
Kotlin
0
0
da4bbb1a0248fb134e6be3942ff0527cb99bb016
5,073
Config4k
Apache License 2.0
qr-code/src/commonMain/kotlin/in/procyk/compose/qrcode/internal/QRMath.kt
avan1235
705,304,457
false
{"Kotlin": 203607}
/** * Based on QRose by <NAME> from [Github](https://github.com/alexzhirkevich/qrose) * * MIT License * * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package `in`.procyk.compose.qrcode.internal /** * Rewritten in Kotlin from the [original (GitHub)](https://github.com/kazuhikoarase/qrcode-generator/blob/master/java/src/main/java/com/d_project/qrcode/QRMath.java) * * @author <NAME> - g0dkar * @author <NAME> - kazuhikoarase */ internal object QRMath { private val EXP_TABLE = IntArray(256) private val LOG_TABLE = IntArray(256) fun glog(n: Int): Int = LOG_TABLE[n] fun gexp(n: Int): Int { var i = n while (i < 0) { i += 255 } while (i >= 256) { i -= 255 } return EXP_TABLE[i] } init { for (i in 0..7) { EXP_TABLE[i] = 1 shl i } for (i in 8..255) { EXP_TABLE[i] = ( EXP_TABLE[i - 4] xor EXP_TABLE[i - 5] xor EXP_TABLE[i - 6] xor EXP_TABLE[i - 8] ) } for (i in 0..254) { LOG_TABLE[EXP_TABLE[i]] = i } } }
1
Kotlin
0
4
64f92b8d5d2785b46141fadc322e4b09839b2c1b
2,257
compose-extensions
MIT License
library/kotlin/io/envoyproxy/envoymobile/RequestTrailersBuilder.kt
envoyproxy
173,839,917
false
null
package io.envoyproxy.envoymobile /* * Builder used for constructing instances of `RequestTrailers`. */ class RequestTrailersBuilder : HeadersBuilder { /** * Initialize a new instance of the builder. */ constructor() : super(mutableMapOf()) /** * Instantiate a new builder. Used only by RequestTrailers to convert back to * RequestTrailersBuilder. * * @param trailers: The trailers to start with. */ internal constructor(trailers: MutableMap<String, MutableList<String>>) : super(trailers) override fun add(name: String, value: String): RequestTrailersBuilder { super.add(name, value) return this } override fun set(name: String, value: MutableList<String>): RequestTrailersBuilder { super.set(name, value) return this } override fun remove(name: String): RequestTrailersBuilder { super.remove(name) return this } override fun internalSet(name: String, value: MutableList<String>): RequestTrailersBuilder { super.internalSet(name, value) return this } /** * Build the request trailers using the current builder. * * @return RequestTrailers, New instance of request trailers. */ fun build(): RequestTrailers { return RequestTrailers(headers) } }
215
Java
71
467
96911b46d0ef47857f74de252de65d8cbf3d106f
1,253
envoy-mobile
Apache License 2.0
src/main/kotlin/coffee/cypher/hexbound/feature/construct/item/SpiderConstructCoreItem.kt
Cypher121
569,248,192
false
null
package coffee.cypher.hexbound.feature.construct.item import coffee.cypher.hexbound.init.HexboundData import net.minecraft.item.Item import org.quiltmc.qkl.library.items.buildItemSettings object SpiderConstructCoreItem : Item( buildItemSettings { group(HexboundData.ItemGroups.HEXBOUND) } )
0
Kotlin
1
2
e48474e0dcc0ceb9b9c4c8d2e7efdd7c7256b592
309
hexbound
MIT License
core/src/main/java/com/justai/aimybox/model/reply/aimybox/AimyboxAudioReply.kt
just-ai
193,669,962
false
null
package com.justai.aimybox.model.reply.aimybox import com.github.salomonbrys.kotson.string import com.google.gson.JsonObject import com.justai.aimybox.model.reply.AudioReply /** * Reply which contains an audio URL. */ data class AimyboxAudioReply( override val json: JsonObject ): AudioReply(json["url"].string), AimyboxReply
25
null
17
71
7ac280c3bfda6fdb49f919e16cb9de70dbd2c207
333
aimybox-android-sdk
Apache License 2.0
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/ext/shell/system/JobController.kt
Sammers21
142,990,532
true
{"Kotlin": 1088656, "Java": 878672, "JavaScript": 76098, "Groovy": 22654, "Ruby": 14717, "FreeMarker": 254}
package io.vertx.kotlin.ext.shell.system import io.vertx.ext.shell.system.JobController import io.vertx.kotlin.coroutines.awaitEvent /** * Close the controller and terminate all the underlying jobs, a closed controller does not accept anymore jobs. * * @param completionHandler * * <p/> * NOTE: This function has been automatically generated from the [io.vertx.ext.shell.system.JobController original] using Vert.x codegen. */ suspend fun JobController.closeAwait() : Unit { return awaitEvent{ this.close({ v -> it.handle(null) })} }
0
Kotlin
0
0
bdf349e87e39aeec85cfbd1a53bae3cb3e420c55
551
vertx-stack-generation
Apache License 2.0
enode/src/main/java/org/enodeframework/domain/AggregateSnapshotter.kt
anruence
165,245,292
false
null
package org.enodeframework.domain import java.util.concurrent.CompletableFuture /** * An interface which can restore aggregate from snapshot storage. */ interface AggregateSnapshotter { /** * Restore the aggregate from snapshot storage. */ fun <T : AggregateRoot?> restoreFromSnapshotAsync( aggregateRootType: Class<T>, aggregateRootId: String ): CompletableFuture<T> }
1
null
55
205
22c81b98b36a6a221d026272594eaf7817145e0f
412
enode
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Gears.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.Gears: ImageVector get() { if (_gears != null) { return _gears!! } _gears = Builder(name = "Gears", 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(10.73f, 10.3f) lineToRelative(1.84f, 1.06f) lineToRelative(1.0f, -1.73f) lineToRelative(-1.84f, -1.06f) curveToRelative(0.17f, -0.5f, 0.28f, -1.02f, 0.28f, -1.57f) reflectiveCurveToRelative(-0.11f, -1.07f, -0.28f, -1.57f) lineToRelative(1.84f, -1.06f) lineToRelative(-1.0f, -1.73f) lineToRelative(-1.84f, 1.06f) curveToRelative(-0.71f, -0.8f, -1.65f, -1.38f, -2.73f, -1.6f) lineTo(8.0f, 0.0f) horizontalLineToRelative(-2.0f) lineTo(6.0f, 2.1f) curveToRelative(-1.08f, 0.22f, -2.02f, 0.8f, -2.73f, 1.6f) lineToRelative(-1.84f, -1.06f) lineToRelative(-1.0f, 1.73f) lineToRelative(1.84f, 1.06f) curveToRelative(-0.17f, 0.5f, -0.28f, 1.02f, -0.28f, 1.57f) reflectiveCurveToRelative(0.11f, 1.07f, 0.28f, 1.57f) lineToRelative(-1.84f, 1.06f) lineToRelative(1.0f, 1.73f) lineToRelative(1.84f, -1.06f) curveToRelative(0.71f, 0.8f, 1.65f, 1.38f, 2.73f, 1.6f) verticalLineToRelative(2.1f) horizontalLineToRelative(2.0f) verticalLineToRelative(-2.1f) curveToRelative(1.08f, -0.22f, 2.02f, -0.8f, 2.73f, -1.6f) close() moveTo(5.5f, 7.0f) curveToRelative(0.0f, -0.83f, 0.67f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.67f, 1.5f, 1.5f) reflectiveCurveToRelative(-0.67f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.67f, -1.5f, -1.5f) close() moveTo(22.0f, 17.0f) curveToRelative(0.0f, -0.55f, -0.11f, -1.07f, -0.28f, -1.57f) lineToRelative(1.84f, -1.06f) lineToRelative(-1.0f, -1.73f) lineToRelative(-1.84f, 1.06f) curveToRelative(-0.71f, -0.8f, -1.65f, -1.38f, -2.73f, -1.6f) verticalLineToRelative(-2.1f) horizontalLineToRelative(-2.0f) verticalLineToRelative(2.1f) curveToRelative(-1.08f, 0.22f, -2.02f, 0.8f, -2.73f, 1.6f) lineToRelative(-1.84f, -1.06f) lineToRelative(-1.0f, 1.73f) lineToRelative(1.84f, 1.06f) curveToRelative(-0.17f, 0.5f, -0.28f, 1.02f, -0.28f, 1.57f) reflectiveCurveToRelative(0.11f, 1.07f, 0.28f, 1.57f) lineToRelative(-1.84f, 1.06f) lineToRelative(1.0f, 1.73f) lineToRelative(1.84f, -1.06f) curveToRelative(0.71f, 0.8f, 1.65f, 1.38f, 2.73f, 1.6f) verticalLineToRelative(2.1f) horizontalLineToRelative(2.0f) verticalLineToRelative(-2.1f) curveToRelative(1.08f, -0.22f, 2.02f, -0.8f, 2.73f, -1.6f) lineToRelative(1.84f, 1.06f) lineToRelative(1.0f, -1.73f) lineToRelative(-1.84f, -1.06f) curveToRelative(0.17f, -0.5f, 0.28f, -1.02f, 0.28f, -1.57f) close() moveTo(17.0f, 18.5f) curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f) reflectiveCurveToRelative(0.67f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.67f, 1.5f, 1.5f) reflectiveCurveToRelative(-0.67f, 1.5f, -1.5f, 1.5f) close() } } .build() return _gears!! } private var _gears: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,817
icons
MIT License
app/src/main/java/org/wikipedia/feed/random/RandomClient.kt
wikimedia
13,862,999
false
{"Kotlin": 3495497, "Python": 24797, "Java": 4408, "Jinja": 533, "Shell": 521}
package org.wikipedia.feed.random import android.content.Context import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch import org.wikipedia.WikipediaApp import org.wikipedia.database.AppDatabase import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.feed.FeedContentType import org.wikipedia.feed.dataclient.FeedClient import org.wikipedia.readinglist.database.ReadingListPage import org.wikipedia.util.log.L class RandomClient( private val coroutineScope: CoroutineScope ) : FeedClient { private var clientJob: Job? = null override fun request(context: Context, wiki: WikiSite, age: Int, cb: FeedClient.Callback) { cancel() clientJob = coroutineScope.launch( CoroutineExceptionHandler { _, caught -> L.v(caught) cb.error(caught) } ) { val deferredSummaries = WikipediaApp.instance.languageState.appLanguageCodes .filter { !FeedContentType.RANDOM.langCodesDisabled.contains(it) } .map { lang -> async { val wikiSite = WikiSite.forLanguageCode(lang) val randomSummary = try { ServiceFactory.getRest(wikiSite).getRandomSummary() } catch (e: Exception) { AppDatabase.instance.readingListPageDao().getRandomPage(lang)?.let { ReadingListPage.toPageSummary(it) } } randomSummary?.let { RandomCard(it, age, wikiSite) } } } cb.success(deferredSummaries.awaitAll().filterNotNull()) } } override fun cancel() { clientJob?.cancel() } }
29
Kotlin
624
2,365
175db9fe3c28084af7290a934f38223eb14934ed
2,074
apps-android-wikipedia
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/CalculatorMoney.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.CalculatorMoney: ImageVector get() { if (_calculatorMoney != null) { return _calculatorMoney!! } _calculatorMoney = Builder(name = "CalculatorMoney", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(21.0f, 0.0f) lineTo(7.0f, 0.0f) curveToRelative(-1.657f, 0.0f, -3.0f, 1.343f, -3.0f, 3.0f) verticalLineToRelative(5.139f) curveToRelative(0.633f, -0.091f, 1.302f, -0.139f, 2.0f, -0.139f) reflectiveCurveToRelative(1.367f, 0.048f, 2.0f, 0.139f) verticalLineToRelative(-4.139f) horizontalLineToRelative(12.0f) verticalLineToRelative(6.0f) horizontalLineToRelative(-7.469f) curveToRelative(0.935f, 0.819f, 1.469f, 1.846f, 1.469f, 3.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(6.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(-6.0f) verticalLineToRelative(1.5f) curveToRelative(0.0f, 1.365f, -0.617f, 2.569f, -1.687f, 3.5f) horizontalLineToRelative(11.687f) lineTo(24.0f, 3.0f) curveToRelative(0.0f, -1.657f, -1.343f, -3.0f, -3.0f, -3.0f) close() moveTo(20.0f, 15.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(2.0f) close() moveTo(18.0f, 6.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(-8.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(8.0f) close() moveTo(12.0f, 13.0f) curveToRelative(0.0f, 1.657f, -2.686f, 3.0f, -6.0f, 3.0f) reflectiveCurveTo(0.0f, 14.657f, 0.0f, 13.0f) reflectiveCurveToRelative(2.686f, -3.0f, 6.0f, -3.0f) reflectiveCurveToRelative(6.0f, 1.343f, 6.0f, 3.0f) close() moveTo(12.0f, 18.5f) verticalLineToRelative(2.0f) curveToRelative(0.0f, 1.995f, -2.579f, 3.5f, -6.0f, 3.5f) reflectiveCurveToRelative(-6.0f, -1.505f, -6.0f, -3.5f) verticalLineToRelative(-2.0f) curveToRelative(0.0f, 1.971f, 2.5f, 3.5f, 6.0f, 3.5f) reflectiveCurveToRelative(6.0f, -1.529f, 6.0f, -3.5f) close() moveTo(12.0f, 14.5f) verticalLineToRelative(2.0f) curveToRelative(0.0f, 1.995f, -2.579f, 3.5f, -6.0f, 3.5f) reflectiveCurveToRelative(-6.0f, -1.505f, -6.0f, -3.5f) verticalLineToRelative(-2.0f) curveToRelative(0.0f, 1.971f, 2.5f, 3.5f, 6.0f, 3.5f) reflectiveCurveToRelative(6.0f, -1.529f, 6.0f, -3.5f) close() } } .build() return _calculatorMoney!! } private var _calculatorMoney: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,219
icons
MIT License
basic/src/main/java/com/xiaoxin/basic/date/page/PageCalendarView.kt
XiaoXin956
474,917,723
false
null
package com.xiaoxin.basic.date.page import android.content.Context import android.content.res.TypedArray import android.os.Bundle import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import androidx.databinding.DataBindingUtil import androidx.fragment.app.* import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.xiaoxin.basic.R import com.xiaoxin.basic.databinding.PageCalendarViewBinding import com.xiaoxin.basic.date.DateToString import com.xiaoxin.basic.date.FormatYYYYMMDD import com.xiaoxin.basic.date.DateBean import java.util.* import kotlin.collections.ArrayList /** * @author: Admin * @date: 2022-04-20 */ class PageCalendarView : FrameLayout { lateinit var vpPageCalendar: ViewPager2 private var showDate: String? = null private lateinit var calendarFragments: ArrayList<FragmentItemCalendar> private lateinit var calendarBean: ArrayList<ViewPageBean> var fragmentItemCalendar: FragmentItemCalendar? = null var pageFragmentAdapter : PageFragmentAdapter? = null constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init(attrs) } constructor( context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) : super(context, attrs, defStyleAttr, defStyleRes) { init(attrs) } fun init(attrs: AttributeSet?) { val pageCalendarView = DataBindingUtil.inflate<PageCalendarViewBinding>( LayoutInflater.from(context), R.layout.page_calendar_view, null, false ) addView(pageCalendarView.root) val typedArray: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.PageCalendarView) typedArray.getString(R.styleable.PageCalendarView_showDate)?.let { showDate = it } typedArray.recycle() calendarFragments = ArrayList() calendarBean = ArrayList() var tempStartDate = FormatYYYYMMDD.parse(showDate!!)!! val instance = Calendar.getInstance(Locale.CHINA) instance.time = tempStartDate instance.add(Calendar.MONTH, -3) for (index in 1..7) { tempStartDate = instance.time addCalendarView(DateToString(tempStartDate, FormatYYYYMMDD), null) instance.add(Calendar.MONTH, 1) } vpPageCalendar = pageCalendarView.vpPageCalendar vpPageCalendar.offscreenPageLimit = 7 if (context is FragmentActivity) { pageFragmentAdapter = PageFragmentAdapter((context as FragmentActivity), calendarFragments) vpPageCalendar.adapter = pageFragmentAdapter } vpPageCalendar.setCurrentItem(3,false) vpPageCalendar.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { var currentPosition:Int = 3 override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { super.onPageScrolled(position, positionOffset, positionOffsetPixels) currentPosition= position } override fun onPageSelected(position: Int) { super.onPageSelected(position) // if (currentPosition<3){ // addCalendarView("2022-05-01", 0) // pageFragmentAdapter?.removeFragment(calendarFragments.size-1) // }else if (currentPosition>3){ // addCalendarView("2022-05-01", calendarFragments.size-1) // pageFragmentAdapter?.removeFragment(0) // } } override fun onPageScrollStateChanged(state: Int) { super.onPageScrollStateChanged(state) } }) } private fun addCalendarView(timeRes: Any, index: Int?) { if (index==null) { fragmentItemCalendar = FragmentItemCalendar() val bundle = Bundle() bundle.putString(SHOW_DATE, timeRes.toString()) fragmentItemCalendar?.arguments = bundle calendarFragments.add(fragmentItemCalendar!!) }else{ fragmentItemCalendar = FragmentItemCalendar() val bundle = Bundle() bundle.putString(SHOW_DATE, timeRes.toString()) fragmentItemCalendar?.arguments = bundle // calendarFragments.add(index,fragmentItemCalendar!!) // pageFragmentAdapter?.notifyDataSetChanged() // pageFragmentAdapter?.addFragment(index,fragmentItemCalendar!!) } } inner class PageFragmentAdapter : FragmentStateAdapter { var fragments: ArrayList<FragmentItemCalendar> constructor(fragmentActivity: FragmentActivity, fragments: ArrayList<FragmentItemCalendar>) : super(fragmentActivity) { this.fragments = fragments } constructor(fragment: Fragment, fragments: ArrayList<FragmentItemCalendar>) : super(fragment) { this.fragments = fragments } constructor(fragmentManager: FragmentManager, lifecycle: Lifecycle, fragments: ArrayList<FragmentItemCalendar>) : super(fragmentManager, lifecycle) { this.fragments = fragments } override fun getItemCount(): Int { return fragments.size } override fun createFragment(position: Int): Fragment { return fragments[position] } } class ViewPageBean(var view: View?, var dateBean: DateBean?) }
0
Kotlin
0
4
bdbf05f52535978e947e3c1f0803e0f9dc4377d2
5,880
Toolkit
Apache License 2.0
androidApp/src/main/java/com/aglushkov/wordteacher/androidApp/general/textroundedbg/TextRoundedBgAttributeReader.kt
soniccat
302,971,014
false
null
package com.aglushkov.wordteacher.androidApp.general.textroundedbg import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import androidx.core.content.res.getDrawableOrThrow import com.aglushkov.wordteacher.androidApp.R /** * Reads default attributes that [TextRoundedBgDrawer] needs from resources. The attributes read * are: * * - chHorizontalPadding: the padding to be applied to left & right of the background * - chVerticalPadding: the padding to be applied to top & bottom of the background * - chDrawable: the drawable used to draw the background * - chDrawableLeft: the drawable used to draw left edge of the background * - chDrawableMid: the drawable used to draw for whole line * - chDrawableRight: the drawable used to draw right edge of the background */ class TextRoundedBgAttributeReader(context: Context, attrs: AttributeSet?) { val horizontalPadding: Int val verticalPadding: Int val drawable: Drawable val drawableLeft: Drawable val drawableMid: Drawable val drawableRight: Drawable init { val typedArray = context.obtainStyledAttributes( attrs, R.styleable.TextRoundedBgHelper, 0, R.style.AdjectiveBgStyle ) horizontalPadding = typedArray.getDimensionPixelSize( R.styleable.TextRoundedBgHelper_roundedTextHorizontalPadding, 0 ) verticalPadding = typedArray.getDimensionPixelSize( R.styleable.TextRoundedBgHelper_roundedTextVerticalPadding, 0 ) drawable = typedArray.getDrawableOrThrow( R.styleable.TextRoundedBgHelper_roundedTextDrawable ) drawableLeft = typedArray.getDrawableOrThrow( R.styleable.TextRoundedBgHelper_roundedTextDrawableLeft ) drawableMid = typedArray.getDrawableOrThrow( R.styleable.TextRoundedBgHelper_roundedTextDrawableMid ) drawableRight = typedArray.getDrawableOrThrow( R.styleable.TextRoundedBgHelper_roundedTextDrawableRight ) typedArray.recycle() } }
0
Kotlin
1
1
1defa8e2973da24f0f313e70c1f5a19595c53e5a
2,156
WordTeacher
MIT License
library/src/commonMain/kotlin/com/otaliastudios/opengl/core/EglNativeConfigChooser.kt
natario1
175,463,832
false
null
package com.otaliastudios.opengl.core import com.otaliastudios.opengl.internal.EGL_ALPHA_SIZE import com.otaliastudios.opengl.internal.EGL_BLUE_SIZE import com.otaliastudios.opengl.internal.EGL_GREEN_SIZE import com.otaliastudios.opengl.internal.EGL_NONE import com.otaliastudios.opengl.internal.EGL_OPENGL_ES2_BIT import com.otaliastudios.opengl.internal.EGL_OPENGL_ES3_BIT_KHR import com.otaliastudios.opengl.internal.EGL_PBUFFER_BIT import com.otaliastudios.opengl.internal.EGL_RED_SIZE import com.otaliastudios.opengl.internal.EGL_RENDERABLE_TYPE import com.otaliastudios.opengl.internal.EGL_SURFACE_TYPE import com.otaliastudios.opengl.internal.EGL_WINDOW_BIT import com.otaliastudios.opengl.internal.EglConfig import com.otaliastudios.opengl.internal.EglDisplay import com.otaliastudios.opengl.internal.eglChooseConfig import com.otaliastudios.opengl.internal.logw open class EglNativeConfigChooser { companion object { private const val EGL_RECORDABLE_ANDROID = 0x3142 // Android-specific extension. } internal fun getConfig(display: EglDisplay, version: Int, recordable: Boolean): EglConfig? { val attributes = getConfigSpec(version, recordable) val configs = arrayOfNulls<EglConfig?>(1) val numConfigs = IntArray(1) if (!eglChooseConfig(display, attributes, configs, 1, numConfigs)) { logw("EglConfigChooser", "Unable to find RGB8888 / $version EGLConfig") return null } return configs.get(0) } /** * Finds a suitable EGLConfig with r=8, g=8, b=8, a=8. * Does not specify depth or stencil size. * * The actual drawing surface is generally RGBA or RGBX, so omitting the alpha doesn't * really help - it can also lead to huge performance hit on glReadPixels() when reading * into a GL_RGBA buffer. */ internal fun getConfigSpec(version: Int, recordable: Boolean): IntArray { val renderableType = if (version >= 3) { EGL_OPENGL_ES2_BIT or EGL_OPENGL_ES3_BIT_KHR } else { EGL_OPENGL_ES2_BIT } return intArrayOf( EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, // We can create both window surfaces and pbuffer surfaces. EGL_SURFACE_TYPE, EGL_WINDOW_BIT or EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, renderableType, if (recordable) EGL_RECORDABLE_ANDROID else EGL_NONE, if (recordable) 1 else 0, EGL_NONE) } }
7
null
16
98
2c13ab28cad9ad143f23d488595d74b020ef78ef
2,597
Egloo
MIT License
src/main/kotlin/br/com/tagliaferrodev/samplerest/domain/enums/Sexo.kt
dritoferro
267,144,273
false
{"TSQL": 393918, "Kotlin": 105072, "Dockerfile": 164}
package br.com.tagliaferrodev.samplerest.domain.enums enum class Sexo(val nome: String) { MASCULINO(nome = "Masculino"), FEMININO(nome = "Feminino") }
4
TSQL
0
1
fb74acaedd511d4e1b10ddcca44e163ea9d50e6b
159
spring_monolithic
MIT License
app/src/main/java/com/renaisn/reader/ui/widget/dynamiclayout/DynamicFrameLayout.kt
RenaisnNce
598,532,496
false
null
package io.legado.app.ui.widget.dynamiclayout import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.ProgressBar import androidx.appcompat.widget.AppCompatButton import androidx.appcompat.widget.AppCompatImageView import androidx.appcompat.widget.AppCompatTextView import io.legado.app.R import kotlinx.android.synthetic.main.view_dynamic.view.* class DynamicFrameLayout(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs), ViewSwitcher { private var errorView: View? = null private var errorImage: AppCompatImageView? = null private var errorTextView: AppCompatTextView? = null private var actionBtn: AppCompatButton? = null private var progressView: View? = null private var progressBar: ProgressBar? = null private var contentView: View? = null private var errorIcon: Drawable? = null private var emptyIcon: Drawable? = null private var errorActionDescription: CharSequence? = null private var emptyActionDescription: CharSequence? = null private var emptyDescription: CharSequence? = null private var errorAction: Action? = null private var emptyAction: Action? = null private var changeListener: OnVisibilityChangeListener? = null init { View.inflate(context, R.layout.view_dynamic, this) val a = context.obtainStyledAttributes(attrs, R.styleable.DynamicFrameLayout) errorIcon = a.getDrawable(R.styleable.DynamicFrameLayout_errorSrc) emptyIcon = a.getDrawable(R.styleable.DynamicFrameLayout_emptySrc) emptyActionDescription = a.getText(R.styleable.DynamicFrameLayout_emptyActionDescription) emptyDescription = a.getText(R.styleable.DynamicFrameLayout_emptyDescription) errorActionDescription = a.getText(R.styleable.DynamicFrameLayout_errorActionDescription) if (errorActionDescription == null) { errorActionDescription = context.getString(R.string.dynamic_click_retry) } a.recycle() } override fun onFinishInflate() { super.onFinishInflate() if (childCount > 2) { contentView = getChildAt(2) } } override fun showErrorView(message: CharSequence) { ensureErrorView() setViewVisible(errorView, true) setViewVisible(contentView, false) setViewVisible(progressView, false) errorTextView?.text = message errorImage?.setImageDrawable(errorIcon) actionBtn?.let { it.tag = ACTION_WHEN_ERROR it.visibility = View.VISIBLE if (errorActionDescription != null) { it.text = errorActionDescription } } dispatchVisibilityChanged(ViewSwitcher.SHOW_ERROR_VIEW) } override fun showErrorView(messageId: Int) { showErrorView(resources.getText(messageId)) } override fun showEmptyView() { ensureErrorView() setViewVisible(errorView, true) setViewVisible(contentView, false) setViewVisible(progressView, false) errorTextView?.text = emptyDescription errorImage?.setImageDrawable(emptyIcon) actionBtn?.let { it.tag = ACTION_WHEN_EMPTY if (errorActionDescription != null) { it.visibility = View.VISIBLE it.text = errorActionDescription } else { it.visibility = View.INVISIBLE } } dispatchVisibilityChanged(ViewSwitcher.SHOW_EMPTY_VIEW) } override fun showProgressView() { ensureProgressView() setViewVisible(errorView, false) setViewVisible(contentView, false) setViewVisible(progressView, true) dispatchVisibilityChanged(ViewSwitcher.SHOW_PROGRESS_VIEW) } override fun showContentView() { setViewVisible(errorView, false) setViewVisible(contentView, true) setViewVisible(progressView, false) dispatchVisibilityChanged(ViewSwitcher.SHOW_CONTENT_VIEW) } fun setOnVisibilityChangeListener(listener: OnVisibilityChangeListener) { changeListener = listener } fun setErrorAction(action: Action) { errorAction = action } fun setEmptyAction(action: Action) { emptyAction = action } private fun setViewVisible(view: View?, visible: Boolean) { view?.let { it.visibility = if (visible) View.VISIBLE else View.INVISIBLE } } private fun ensureErrorView() { if (errorView == null) { errorView = errorViewStub.inflate() errorImage = errorView?.findViewById(R.id.iv_error_image) errorTextView = errorView?.findViewById(R.id.tv_error_message) actionBtn = errorView?.findViewById(R.id.btn_error_retry) actionBtn?.setOnClickListener { when (it.tag) { ACTION_WHEN_EMPTY -> emptyAction?.onAction(this@DynamicFrameLayout) ACTION_WHEN_ERROR -> errorAction?.onAction(this@DynamicFrameLayout) } } } } private fun ensureProgressView() { if (progressView == null) { progressView = progressViewStub.inflate() progressBar = progressView?.findViewById(R.id.loading_progress) } } private fun dispatchVisibilityChanged(@ViewSwitcher.Visibility visibility: Int) { changeListener?.onVisibilityChanged(visibility) } interface Action { fun onAction(switcher: ViewSwitcher) } interface OnVisibilityChangeListener { fun onVisibilityChanged(@ViewSwitcher.Visibility visibility: Int) } companion object { private const val ACTION_WHEN_ERROR = "ACTION_WHEN_ERROR" private const val ACTION_WHEN_EMPTY = "ACTION_WHEN_EMPTY" } }
1
Kotlin
1
4
4ac03e214e951f7f4f337d4da1f7e39fa715d1c0
5,960
Renaisn_Android
MIT License
src/test/kotlin/com/github/shyiko/ktlint/rule/NoConsecutiveBlankLinesRuleTest.kt
rakshakhegde
64,825,492
true
{"Kotlin": 73940, "Shell": 5894, "Batchfile": 3006}
package com.github.shyiko.ktlint.rule import com.github.shyiko.ktlint.LintError import com.github.shyiko.ktlint.format import com.github.shyiko.ktlint.lint import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test class NoConsecutiveBlankLinesRuleTest { @Test fun testLint() { assertThat(NoConsecutiveBlankLinesRule().lint("fun main() {\n\n\n}")).isEqualTo(listOf( LintError(3, 1, "rule-id", "Needless blank line(s)") )) } @Test fun testFormat() { assertThat(NoConsecutiveBlankLinesRule().format( """ fun main() { } """ )).isEqualTo( """ fun main() { } """ ) } }
0
Kotlin
0
1
e8055299ed3ad9d84334ef014d6f85e895f12432
774
ktlint
MIT License
app/src/main/java/hu/tb/minichefy/presentation/screens/recipe/recipe_details/RecipeDeatilsScreen.kt
BTheofil
705,819,849
false
{"Kotlin": 176313}
package hu.tb.minichefy.presentation.screens.recipe.recipe_details import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import hu.tb.minichefy.domain.model.recipe.Recipe import hu.tb.minichefy.domain.model.recipe.SimpleQuickRecipeInfo import hu.tb.minichefy.presentation.preview.RecipePreviewParameterProvider import hu.tb.minichefy.presentation.screens.components.icons.iconVectorResource import hu.tb.minichefy.presentation.screens.recipe.recipe_details.components.DetailsRecipeStepItem import hu.tb.minichefy.presentation.screens.recipe.recipe_details.components.QuickInfoBox import hu.tb.minichefy.presentation.ui.theme.MEDIUM_SPACE_BETWEEN_ELEMENTS import hu.tb.minichefy.presentation.ui.theme.Pink50 import hu.tb.minichefy.presentation.ui.theme.SCREEN_HORIZONTAL_PADDING import hu.tb.minichefy.presentation.ui.theme.SMALL_SPACE_BETWEEN_ELEMENTS @Composable fun RecipeDetailsScreen( viewModel: RecipeDetailsViewModel = hiltViewModel() ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() RecipeDetailsContent( uiState = uiState, onEvent = viewModel::onEvent ) } @Composable fun RecipeDetailsContent( uiState: RecipeDetailsViewModel.UiState, onEvent: (RecipeDetailsViewModel.OnEvent) -> Unit, ) { val screenSize = LocalConfiguration.current Canvas(Modifier.fillMaxSize()) { val cornerRadius = CornerRadius(64f, 64f) val path = Path().apply { addRoundRect( RoundRect( rect = Rect( offset = Offset(0f, 0f), size = Size(size.width, size.height / 3f), ), bottomLeft = cornerRadius, bottomRight = cornerRadius, ) ) } drawPath(path, color = Color(Pink50.value)) } uiState.recipe?.let { recipe -> Column( modifier = Modifier .padding(horizontal = SCREEN_HORIZONTAL_PADDING) ) { Box( modifier = Modifier .fillMaxWidth() .size(DpSize(Dp.Infinity, (screenSize.screenHeightDp.dp / 3))), contentAlignment = Alignment.Center ) { Image( imageVector = iconVectorResource(iconResource = uiState.recipe.icon), contentDescription = "recipe image" ) } Spacer(modifier = Modifier.height(SMALL_SPACE_BETWEEN_ELEMENTS)) Text( modifier = Modifier .fillMaxWidth(), text = recipe.title, style = MaterialTheme.typography.displayMedium, color = MaterialTheme.colorScheme.primary, maxLines = 1, overflow = TextOverflow.Ellipsis ) QuickInfoBox(infoList = uiState.recipeQuickInfoList) LazyColumn( verticalArrangement = Arrangement.spacedBy(MEDIUM_SPACE_BETWEEN_ELEMENTS) ) { itemsIndexed(recipe.howToSteps) { index, step -> DetailsRecipeStepItem( stepNumber = index + 1, stepTextDescription = step.step ) } } Button(onClick = { onEvent(RecipeDetailsViewModel.OnEvent.MakeRecipe) } ) { Text(text = "Make recipe") } } } } @Preview @Composable fun RecipeDetailsContentPreview( @PreviewParameter(RecipePreviewParameterProvider::class) mockRecipe: Recipe ) { RecipeDetailsContent( uiState = RecipeDetailsViewModel.UiState( recipe = mockRecipe, recipeQuickInfoList = listOf(SimpleQuickRecipeInfo("5", "serve")) ), onEvent = {} ) }
0
Kotlin
0
0
0e0e3b3cc3b5fd7a8ce4be1f7ed025c97ae8628a
5,522
MiniChefy
Apache License 2.0
lib/android/src/main/java/com/reactnativeldk/classes/BackupClient.kt
synonymdev
489,280,368
false
{"C++": 3820404, "TypeScript": 239605, "Swift": 154917, "Kotlin": 129172, "C": 68592, "JavaScript": 26856, "Objective-C": 14184, "Java": 7968, "Shell": 3332, "Ruby": 3171, "Objective-C++": 744, "Dockerfile": 138}
package com.reactnativeldk.classes import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import com.reactnativeldk.UiThreadDebouncer import com.reactnativeldk.EventTypes import com.reactnativeldk.LdkEventEmitter import com.reactnativeldk.hexEncodedString import com.reactnativeldk.hexa import com.reactnativeldk.putDateOrNull import org.json.JSONObject import org.ldk.structs.Result_StrSecp256k1ErrorZ.Result_StrSecp256k1ErrorZ_OK import org.ldk.structs.UtilMethods import java.net.HttpURLConnection import java.net.URL import java.security.MessageDigest import java.security.SecureRandom import java.util.Date import java.util.Random import java.util.UUID import java.util.concurrent.locks.ReentrantLock import javax.crypto.Cipher import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec class BackupError : Exception() { companion object { val requiresSetup = RequiresSetup() val missingBackup = MissingBackup() val signingError = SigningError() val serverChallengeResponseFailed = ServerChallengeResponseFailed() val checkError = BackupCheckError() } } class RequiresSetup() : Exception("BackupClient requires setup") class MissingBackup() : Exception("Retrieve failed. Missing backup.") class InvalidServerResponse(code: Int) : Exception("Invalid backup server response ($code)") class DecryptFailed(msg: String) : Exception("Failed to decrypt backup payload. $msg") class SigningError() : Exception("Failed to sign message") class ServerChallengeResponseFailed() : Exception("Server challenge response failed") class BackupCheckError() : Exception("Backup self check failed") class CompleteBackup( val files: Map<String, ByteArray>, val channelFiles: Map<String, ByteArray> ) typealias BackupCompleteCallback = (Exception?) -> Unit class BackupQueueEntry( val uuid: UUID, val label: BackupClient.Label, val bytes: ByteArray, val callback: BackupCompleteCallback? = null ) data class BackupFileState( var lastQueued: Date, var lastPersisted: Date?, var lastFailed: Date?, var lastErrorMessage: String? ) { val encoded: WritableMap get() { val body = Arguments.createMap() body.putDouble("lastQueued", lastQueued.time.toDouble()) body.putDateOrNull("lastPersisted", lastPersisted) body.putDateOrNull("lastFailed", lastFailed) if (lastErrorMessage != null) { body.putString("lastErrorMessage", lastErrorMessage) } else { body.putNull("lastErrorMessage") } return body } } sealed class BackupStateUpdateType { object Queued : BackupStateUpdateType() object Success : BackupStateUpdateType() data class Fail(val e: Exception) : BackupStateUpdateType() } class BackupClient { sealed class Label(val string: String, channelId: String = "") { data class PING(val customName: String = "") : Label("ping") data class CHANNEL_MANAGER(val customName: String = "") : Label("channel_manager") data class CHANNEL_MONITOR(val customName: String = "", val channelId: String) : Label("channel_monitor") data class MISC(val customName: String) : Label(customName.replace(".json", "").replace(".bin", "")) val queueId: String get() = when (this) { is CHANNEL_MONITOR -> "$string-$channelId" is MISC -> "$string-$customName" else -> string } val backupStateKey: String? get() = when (this) { is CHANNEL_MANAGER -> "$string" is CHANNEL_MONITOR -> "${string}_${channelId}" is MISC -> "$string" else -> null } } companion object { enum class Method(val value: String) { PERSIST("persist"), RETRIEVE("retrieve"), LIST("list"), AUTH_CHALLENGE("auth/challenge"), AUTH_RESPONSE("auth/response") } class CachedBearer( val bearer: String, val expires: Long ) private var version = "v1" private var signedMessagePrefix = "react-native-ldk backup server auth:" private var persistQueues: HashMap<String, ArrayList<BackupQueueEntry>> = HashMap() private var persistQueuesLock: HashMap<String, Boolean> = HashMap() var skipRemoteBackup = true //Allow dev to opt out (for development), will not throw error when attempting to persist private var network: String? = null private var server: String? = null private var serverPubKey: String? = null private var secretKey: ByteArray? = null private val encryptionKey: SecretKeySpec? get() = if (secretKey != null) { SecretKeySpec(secretKey, "AES") } else { null } private var pubKey: ByteArray? = null private var cachedBearer: CachedBearer? = null val requiresSetup: Boolean get() = server == null private var backupState: HashMap<String, BackupFileState> = HashMap() fun setup(secretKey: ByteArray, pubKey: ByteArray, network: String, server: String, serverPubKey: String) { this.secretKey = secretKey this.pubKey = pubKey this.network = network this.server = server this.serverPubKey = serverPubKey this.cachedBearer = null LdkEventEmitter.send( EventTypes.native_log, "BackupClient setup for synchronous remote persistence. Server: $server" ) if (requiresSetup) { throw RuntimeException(this.server) } } @Throws(BackupError::class) private fun backupUrl( method: Method, label: Label? = null ): URL { val network = network ?: throw BackupError.requiresSetup val server = server ?: throw BackupError.requiresSetup var urlString = "$server/$version/${method.value}?network=$network" label?.let { urlString += "&label=${it.string}" } if (label is Label.CHANNEL_MONITOR) { urlString += "&channelId=${label.channelId}" } if (method == Method.LIST) { urlString += "&fileGroup=ldk" } return URL(urlString) } @Throws(BackupError::class) private fun encrypt(blob: ByteArray): ByteArray { if (encryptionKey == null) { throw BackupError.requiresSetup } val cipher = Cipher.getInstance("AES/GCM/NoPadding") val random = SecureRandom() val nonce = ByteArray(12) random.nextBytes(nonce) val gcmParameterSpec = GCMParameterSpec(128, nonce) cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, gcmParameterSpec) val cipherBytes = cipher.doFinal(blob) return nonce + cipherBytes } private fun hash(blob: ByteArray): String { val messageDigest = MessageDigest.getInstance("SHA-256") val hash = messageDigest.digest(blob) return hash.joinToString("") { String.format("%02x", it) } } @Throws(BackupError::class) private fun decrypt(blob: ByteArray): ByteArray { try { if (encryptionKey == null) { throw BackupError.requiresSetup } val nonce = blob.take(12).toByteArray() val encrypted = blob.copyOfRange(12, blob.size) val cipher = Cipher.getInstance("AES/GCM/NoPadding") val gcmSpec = GCMParameterSpec(128, nonce) cipher.init(Cipher.DECRYPT_MODE, encryptionKey, gcmSpec) val decryptedBytes = cipher.doFinal(encrypted) return decryptedBytes } catch (e: Exception) { throw DecryptFailed(e.message ?: "") } } @Throws(BackupError::class) private fun persist(label: Label, bytes: ByteArray, retry: Int, onTryFail: ((Exception) -> Unit)) { var attempts = 0 var persistError: Exception? = null while (attempts < retry) { try { persist(label, bytes) LdkEventEmitter.send( EventTypes.native_log, "Remote persist success for ${label.string} after ${attempts+1} attempts" ) return } catch (error: Exception) { persistError = error onTryFail(error) attempts += 1 LdkEventEmitter.send( EventTypes.native_log, "Remote persist failed for ${label.string} ($attempts attempts)" ) Thread.sleep(attempts.toLong()) // Ease off with each attempt } } if (persistError != null) { throw persistError } } @Throws(BackupError::class) private fun persist(label: Label, bytes: ByteArray) { if (skipRemoteBackup) { return } if (pubKey == null || serverPubKey == null) { throw BackupError.requiresSetup } val pubKeyHex = pubKey!!.hexEncodedString() val encryptedBackup = encrypt(bytes) val signedHash = sign(hash(encryptedBackup)) //Hash of pubKey+timestamp val clientChallenge = hash("$pubKeyHex${System.currentTimeMillis()}".toByteArray(Charsets.UTF_8)) val url = backupUrl(Method.PERSIST, label) LdkEventEmitter.send( EventTypes.native_log, "Sending backup to $url" ) val urlConnection = url.openConnection() as HttpURLConnection urlConnection.requestMethod = "POST" urlConnection.doOutput = true urlConnection.setRequestProperty("Content-Type", "application/octet-stream") urlConnection.setRequestProperty("Signed-Hash", signedHash) urlConnection.setRequestProperty("Public-Key", pubKeyHex) urlConnection.setRequestProperty("Challenge", clientChallenge) val outputStream = urlConnection.outputStream outputStream.write(encryptedBackup) outputStream.close() if (urlConnection.responseCode != 200) { LdkEventEmitter.send( EventTypes.native_log, "Remote persist failed for ${label.string} with response code ${urlConnection.responseCode}" ) throw InvalidServerResponse(urlConnection.responseCode) } //Verify signed response val inputStream = urlConnection.inputStream val jsonString = inputStream.bufferedReader().use { it.readText() } inputStream.close() val signature = JSONObject(jsonString).getString("signature") if (!verifySignature(clientChallenge, signature, serverPubKey!!)) { throw BackupError.serverChallengeResponseFailed } LdkEventEmitter.send( EventTypes.native_log, "Remote persist success for ${label.string}" ) } @Throws(BackupError::class) fun retrieve(label: Label): ByteArray { val bearer = authToken() val url = backupUrl(Method.RETRIEVE, label) LdkEventEmitter.send( EventTypes.native_log, "Retrieving backup from $url" ) val urlConnection = url.openConnection() as HttpURLConnection urlConnection.requestMethod = "GET" urlConnection.setRequestProperty("Content-Type", "application/octet-stream") urlConnection.setRequestProperty("Authorization", bearer) val responseCode = urlConnection.responseCode if (responseCode == 404) { throw BackupError.missingBackup } if (responseCode != 200) { LdkEventEmitter.send( EventTypes.native_log, "Remote retrieve failed for ${label.string} with response code $responseCode" ) throw InvalidServerResponse(responseCode) } val inputStream = urlConnection.inputStream val encryptedBackup = inputStream.readBytes() inputStream.close() LdkEventEmitter.send( EventTypes.native_log, "Remote retrieve success for ${label.string}" ) val decryptedBackup = decrypt(encryptedBackup) return decryptedBackup } @Throws(BackupError::class) fun listFiles(): Pair<Array<String>, Array<String>> { val bearer = authToken() val url = backupUrl(Method.LIST) LdkEventEmitter.send( EventTypes.native_log, "Retrieving backup from $url" ) val urlConnection = url.openConnection() as HttpURLConnection urlConnection.requestMethod = "GET" urlConnection.setRequestProperty("Content-Type", "application/json") urlConnection.setRequestProperty("Authorization", bearer) val responseCode = urlConnection.responseCode if (responseCode == 404) { throw BackupError.missingBackup } if (responseCode != 200) { throw InvalidServerResponse(responseCode) } val inputStream = urlConnection.inputStream val jsonString = inputStream.bufferedReader().use { it.readText() } inputStream.close() val jsonObject = JSONObject(jsonString) val fileList = jsonObject.getJSONArray("list") val channelFileList = jsonObject.getJSONArray("channel_monitors") println("fileList: $fileList") return Pair( Array(fileList.length()) { idx -> fileList.getString(idx) }, Array(channelFileList.length()) { idx -> channelFileList.getString(idx) }, ) } @Throws(BackupError::class) fun retrieveCompleteBackup(): CompleteBackup { val list = listFiles() val fileNames = list.first val channelFileNames = list.second val files = mutableMapOf<String, ByteArray>() for (fileName in fileNames) { files[fileName] = retrieve(Label.MISC(fileName)) } val channelFiles = mutableMapOf<String, ByteArray>() for (fileName in channelFileNames) { channelFiles[fileName] = retrieve(Label.CHANNEL_MONITOR(channelId=fileName.replace(".bin", ""))) } return CompleteBackup(files = files, channelFiles = channelFiles) } @Throws(BackupError::class) fun selfCheck() { val ping = "ping${Random().nextInt(1000)}" persist(Label.PING(), ping.toByteArray()) val pingRetrieved = retrieve(Label.PING()) if (pingRetrieved.toString(Charsets.UTF_8) != ping) { LdkEventEmitter.send( EventTypes.native_log, "Backup check failed to verify ping content." ) throw BackupError.checkError } } private fun sign(message: String): String { if (secretKey == null) { throw BackupError.requiresSetup } val res = UtilMethods.sign("$signedMessagePrefix$message".toByteArray(Charsets.UTF_8), secretKey) if (!res.is_ok) { throw BackupError.signingError } return (res as Result_StrSecp256k1ErrorZ_OK).res } private fun verifySignature(message: String, signature: String, pubKey: String): Boolean { return UtilMethods.verify( "$signedMessagePrefix$message".toByteArray(Charsets.UTF_8), signature, pubKey.hexa() ) } @Throws(BackupError::class) private fun authToken(): String { if (cachedBearer != null && cachedBearer!!.expires > System.currentTimeMillis()) { return cachedBearer!!.bearer } if (pubKey == null) { throw BackupError.requiresSetup } //Fetch challenge with signed timestamp as nonce val pubKeyHex = pubKey!!.hexEncodedString() val timestamp = System.currentTimeMillis() val payload = JSONObject( mapOf( "timestamp" to timestamp, "signature" to sign(timestamp.toString()) ) ) val url = backupUrl(Method.AUTH_CHALLENGE) val urlConnection = url.openConnection() as HttpURLConnection urlConnection.requestMethod = "POST" urlConnection.setRequestProperty("Content-Type", "application/json") urlConnection.setRequestProperty("Public-Key", pubKeyHex) val outputStream = urlConnection.outputStream outputStream.write(payload.toString().toByteArray()) outputStream.close() if (urlConnection.responseCode != 200) { LdkEventEmitter.send( EventTypes.native_log, "Fetch server challenge failed." ) throw InvalidServerResponse(urlConnection.responseCode) } val inputStream = urlConnection.inputStream val jsonString = inputStream.bufferedReader().use { it.readText() } inputStream.close() val challenge = JSONObject(jsonString).getString("challenge") //Sign challenge and fetch bearer token val urlBearer = backupUrl(Method.AUTH_RESPONSE) val urlConnectionBearer = urlBearer.openConnection() as HttpURLConnection urlConnectionBearer.requestMethod = "POST" urlConnectionBearer.setRequestProperty("Content-Type", "application/json") urlConnectionBearer.setRequestProperty("Public-Key", pubKeyHex) val outputStreamBearer = urlConnectionBearer.outputStream outputStreamBearer.write(JSONObject( mapOf( "signature" to sign(challenge) ) ).toString().toByteArray()) outputStreamBearer.close() if (urlConnectionBearer.responseCode != 200) { LdkEventEmitter.send( EventTypes.native_log, "Fetch bearer token failed." ) throw InvalidServerResponse(urlConnection.responseCode) } val inputStreamBearer = urlConnectionBearer.inputStream val jsonBearer = JSONObject(inputStreamBearer.bufferedReader().use { it.readText() }) inputStreamBearer.close() val bearer = jsonBearer.getString("bearer") val expires = jsonBearer.getLong("expires") cachedBearer = CachedBearer(bearer, expires) return bearer } private val backupStateLock = ReentrantLock() private fun updateBackupState(label: Label, type: BackupStateUpdateType) { if (label.backupStateKey == null) { return } backupStateLock.lock() backupState[label.backupStateKey!!] = backupState[label.backupStateKey!!] ?: BackupFileState( Date(), null, null, null ) when (type) { is BackupStateUpdateType.Queued -> { backupState[label.backupStateKey!!]!!.lastQueued = Date() backupState[label.backupStateKey!!]!!.lastFailed = null backupState[label.backupStateKey!!]!!.lastErrorMessage = null } is BackupStateUpdateType.Success -> { backupState[label.backupStateKey!!]!!.lastPersisted = Date() backupState[label.backupStateKey!!]!!.lastFailed = null backupState[label.backupStateKey!!]!!.lastErrorMessage = null } is BackupStateUpdateType.Fail -> { backupState[label.backupStateKey!!]!!.lastFailed = Date() backupState[label.backupStateKey!!]!!.lastErrorMessage = type.e.message } } val body = Arguments.createMap() backupState.forEach { (key, state) -> body.putMap(key, state.encoded) } UiThreadDebouncer.debounce(interval = 250, key = "backupStateUpdate") { LdkEventEmitter.send(EventTypes.backup_state_update, body) } backupStateLock.unlock() } //Backup queue management fun addToPersistQueue(label: Label, bytes: ByteArray, callback: BackupCompleteCallback? = null) { if (BackupClient.skipRemoteBackup) { callback?.invoke(null) LdkEventEmitter.send( EventTypes.native_log, "Skipping remote backup queue append for ${label.string}" ) return } persistQueues[label.queueId] = persistQueues[label.queueId] ?: ArrayList() persistQueues[label.queueId]!!.add(BackupQueueEntry(UUID.randomUUID(), label, bytes, callback)) updateBackupState(label, BackupStateUpdateType.Queued) processPersistNextInQueue(label) } private val backupQueueLock = ReentrantLock() private fun processPersistNextInQueue(label: Label) { //Check if queue is locked, if not lock it and process next in queue var backupEntry: BackupQueueEntry? = null backupQueueLock.lock() try { if (persistQueuesLock[label.queueId] == true) { return } persistQueuesLock[label.queueId] = true backupEntry = persistQueues[label.queueId]?.firstOrNull() if (backupEntry == null) { persistQueuesLock[label.queueId] = false return } } finally { backupQueueLock.unlock() } Thread { try { persist(backupEntry!!.label, backupEntry.bytes, 10) { updateBackupState(label, BackupStateUpdateType.Fail(it)) } updateBackupState(label, BackupStateUpdateType.Success) backupEntry.callback?.invoke(null) } catch (e: Exception) { LdkEventEmitter.send( EventTypes.native_log, "Remote persist failed for ${label.string} with error ${e.message}" ) updateBackupState(label, BackupStateUpdateType.Fail(e)) backupEntry?.callback?.invoke(e) } finally { backupQueueLock.lock() try { persistQueues[label.queueId]?.remove(backupEntry) persistQueuesLock[label.queueId] = false } finally { backupQueueLock.unlock() } processPersistNextInQueue(label) } }.start() } } }
16
C++
16
52
12f4da159fabca6ac59caffffd0a031f1222a0b6
24,348
react-native-ldk
MIT License
src/main/kotlin/com/pichler/krakenapi/result/OrderBookResult.kt
patrickpichler
96,604,261
false
null
package com.pichler.krakenapi.result import com.github.salomonbrys.kotson.typeAdapter import com.google.gson.stream.JsonToken /** * Created by <NAME> on 08-Jul-17. */ data class OrderBookResult( val pairName: String, val asks: List<OrderBookEntry>, val bids: List<OrderBookEntry> ) data class OrderBookEntry( val price: Double, val volume: Double, val timestamp: Long ) val orderBookResultTypeAdapter = typeAdapter<OrderBookResult> { write { name(it.pairName) beginObject() name("asks") beginArray() it.asks.forEach { orderBookEntryTypeAdapter.write(this, it) } endArray() name("bids") beginArray() it.bids.forEach { orderBookEntryTypeAdapter.write(this, it) } endArray() endObject() } read { beginObject() val pairName = nextName() beginObject() skipValue() beginArray() val asks = generateSequence { if (peek() == JsonToken.END_ARRAY) null else orderBookEntryTypeAdapter.read(this) }.toList() endArray() skipValue() beginArray() val bids = generateSequence { if (peek() == JsonToken.END_ARRAY) null else orderBookEntryTypeAdapter.read(this) }.toList() endArray() endObject() endObject() OrderBookResult(pairName, asks, bids) } } val orderBookEntryTypeAdapter = typeAdapter<OrderBookEntry> { write { beginArray() value("${it.price}") value("${it.volume}") value(it.timestamp) endArray() } read { beginArray() val price = nextDouble() val volume = nextDouble() val timestamp = nextLong() endArray() OrderBookEntry(price, volume, timestamp) } }
0
Kotlin
0
0
5535fc82282b4e4574fbddd52841135ebe94cfdb
1,688
KotlinKrakenAPI
The Unlicense
sqllitedatasource/src/main/java/com/sanketguru/expensetracker/sqllitedata/Expense.kt
SanketGuru
430,870,568
false
null
package com.sanketguru.expensetracker.sqllitedata import androidx.room.* //https://apipheny.io/free-api/ /*** *Expense */ @Entity public data class Expense( @PrimaryKey(autoGenerate = true) val uid: Int, val name: String, val amount: Double, val time: Long, val tagList: String, val category: String, val note: String?, val isPaid: Boolean, val paymentMethod: PaymentMethod ) @Dao interface ExpenseDoa { @Query("SELECT * FROM expense WHERE uid IN (:ids) ") suspend fun getExpense(ids: IntArray): List<Expense> @Insert suspend fun insertAll(vararg data: Expense) @Delete suspend fun delete(data: Expense): Int @Update suspend fun update(data: Expense): Int @Query("SELECT * FROM expense WHERE time BETWEEN :from AND :to") suspend fun getExpenseBetween(from: Long,to: Long): List<Expense> @Query("SELECT * FROM expense WHERE category =:category AND time BETWEEN :from AND :to ") suspend fun getExpenseBetweenAndCategory(from: Long,to: Long,category:String): List<Expense> }
0
Kotlin
0
0
c9c81bcda52669b5ddc744388f33c8cc5f0aa8ec
1,065
Moneytracker
MIT License
plugins/amazonq/chat/jetbrains-community/src/software/aws/toolkits/jetbrains/services/cwc/commands/OptimizeCodeAction.kt
aws
91,485,909
false
{"Kotlin": 7507266, "TypeScript": 132101, "C#": 97693, "Vue": 47529, "Java": 19596, "JavaScript": 12450, "HTML": 5878, "Python": 2939, "Shell": 2920, "Dockerfile": 2209, "SCSS": 2045, "CSS": 1827, "PowerShell": 386, "Batchfile": 77}
// Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.cwc.commands class OptimizeCodeAction : CustomAction(EditorContextCommand.Optimize)
519
Kotlin
220
757
a81caf64a293b59056cef3f8a6f1c977be46937e
249
aws-toolkit-jetbrains
Apache License 2.0
matisse/src/main/kotlin/com/zhihu/matisse/internal/ui/widget/CheckRadioView.kt
youuupeng
206,088,081
true
{"Kotlin": 151202}
package com.zhihu.matisse.internal.ui.widget import android.content.Context import android.graphics.PorterDuff import android.graphics.drawable.Drawable import android.util.AttributeSet import androidx.appcompat.widget.AppCompatImageView import androidx.core.content.res.ResourcesCompat import com.zhihu.matisse.R /** * Description * <p> * * @author peyo * @date 9/5/2019 */ class CheckRadioView(context: Context, attrs: AttributeSet? = null) : AppCompatImageView(context, attrs) { private var mSelectedColor = context.getColor(R.color.zhihu_item_checkCircle_backgroundColor) private var mUnSelectUdColor = context.getColor(R.color.zhihu_check_original_radio_disable) private var mDrawable: Drawable? = null init { init() } private fun init() { mSelectedColor = ResourcesCompat.getColor( resources, R.color.zhihu_item_checkCircle_backgroundColor, context.theme) mUnSelectUdColor = ResourcesCompat.getColor( resources, R.color.zhihu_check_original_radio_disable, context.theme) setChecked(false) } fun setChecked(enable: Boolean) { if (enable) { setImageResource(R.drawable.ic_preview_radio_on) mDrawable = drawable mDrawable?.setColorFilter(mSelectedColor, PorterDuff.Mode.SRC_IN) } else { setImageResource(R.drawable.ic_preview_radio_off) mDrawable = drawable mDrawable?.setColorFilter(mUnSelectUdColor, PorterDuff.Mode.SRC_IN) } } fun setColor(color: Int) { mDrawable?.let { mDrawable = drawable setColorFilter(color, PorterDuff.Mode.SRC_IN) } } }
1
Kotlin
1
1
292456fbbe09cd3a968ba14ef8a49f944ae87d75
1,737
Matisse
Apache License 2.0
Basics/Loops/Fruit.kt
AbhilashG97
123,691,289
false
null
fun main(args: Array<String>) { var fruits = arrayOf("Watermelon", "Kiwi", "Orange", "Pineapple") for((index, value) in fruits.withIndex()) { if(value.first() == 'W') { println("Yay! Watermelon is at index $index") } else { println("No watermelon :("); } } }
0
Kotlin
1
0
2a4f5ea873bf47f77df862a7a1ff82fb870c08c9
324
WatermelonChocolate
Apache License 2.0
app/src/main/java/com/igweze/ebi/todosqlite/TodosCursorAdapter.kt
ebi-igweze
126,055,743
false
null
package com.igweze.ebi.todosqlite import android.content.Context import android.database.Cursor import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CursorAdapter import android.widget.TextView class TodosCursorAdapter(private val ctx: Context, cursor: Cursor?, autoRequery: Boolean): CursorAdapter(ctx, cursor, autoRequery) { override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View? { return LayoutInflater .from(ctx) .inflate(R.layout.todo_list_item, parent, false) } override fun bindView(view: View?, context: Context?, cursor: Cursor?) { val todoText = view?.findViewById<TextView>(R.id.tvNote) val textColumn = cursor?.getColumnIndex(TodoContract.TodosEntry.COLUMN_TEXT) ?: -1 val text = if (textColumn == -1) "" else cursor?.getString(textColumn) todoText?.text = text } }
0
Kotlin
0
0
6a3307fa3b2accfd7cb5f27fc69316a5939e726d
959
todosqlite
MIT License
acra-core/src/main/java/org/acra/file/CrashReportFileNameParser.kt
ACRA
5,890,835
false
{"Kotlin": 396263, "MDX": 42827, "Java": 16527, "JavaScript": 5285, "CSS": 1328, "Shell": 199}
/* * Copyright 2012 <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 org.acra.file import org.acra.ACRAConstants import java.text.ParseException import java.text.SimpleDateFormat import java.util.* /** * Responsible for determining the state of a Crash Report based on its file name. * * @author <NAME> &amp; F43nd1r * @since 4.3.0 */ class CrashReportFileNameParser { /** * Guess that a report is silent from its file name. * * @param reportFileName Name of the report to check whether it should be sent silently. * @return True if the report has been declared explicitly silent using [ErrorReporter.handleSilentException]. */ fun isSilent(reportFileName: String): Boolean = reportFileName.contains(ACRAConstants.SILENT_SUFFIX) /** * Returns true if the report is considered as approved. * * * This includes: * * * * Reports which were pending when the user agreed to send a report in the NOTIFICATION mode Dialog. * * Explicit silent reports * * * @param reportFileName Name of report to check whether it is approved to be sent. * @return True if a report can be sent. */ @Deprecated("use {@link ReportLocator#getApprovedReports()} and {@link ReportLocator#getUnapprovedReports()} instead") fun isApproved(reportFileName: String): Boolean { return isSilent(reportFileName) || reportFileName.contains(ACRAConstants.APPROVED_SUFFIX) } /** * Gets the timestamp of a report from its name * * @param reportFileName Name of the report to get the timestamp from. * @return timestamp of the report */ fun getTimestamp(reportFileName: String): Calendar { val timestamp = reportFileName.replace(ACRAConstants.REPORTFILE_EXTENSION, "").replace(ACRAConstants.SILENT_SUFFIX, "") val calendar = Calendar.getInstance() try { calendar.time = SimpleDateFormat(ACRAConstants.DATE_TIME_FORMAT_STRING, Locale.ENGLISH).parse(timestamp)!! } catch (ignored: ParseException) { } return calendar } }
11
Kotlin
1135
6,309
3cfb0e03e0fea333f1964d15caba3855ff221043
2,645
acra
Apache License 2.0
app/src/main/java/com/peluso/walletguru/viewstate/MainViewState.kt
pelusodan
351,481,020
false
null
package com.peluso.walletguru.viewstate import com.kirkbushman.araw.models.Submission import com.peluso.walletguru.model.* data class MainViewState( // this is the final view list of reddit posts (what is displayed to in our recyclerview) val submissions: List<Submission>? = null, // use this to decide when to render the progressview on the main page val isLoading: Boolean = false, // to track the current favorites of the user (should import from local database) val favorites: List<SubmissionCell> = listOf(), // to track the account information for the left screen (accounts, balances) val currentAccountBalances: List<AccountDto> = listOf(), // to track the logged transactions the user has made val ledger: List<AccountDto> = listOf(), // MAIN ACCOUNT LIST - this is where we get the proper account information to mess with val userAccounts: List<Account> = listOf(), // to keep track of whether or not we're providing location-based subreddits val locationEnabled: Boolean = false, // to keep track of our location type val countryType: CountryType? = null, // holding error message no accounts added val hasNoAccounts: String? = null ) { fun removeSubmissionAt(position: Int): MainViewState { val mutableList: MutableList<Submission> = submissions as MutableList<Submission> if (submissions.isEmpty()) return this mutableList.removeAt(position) return this.copy(submissions = mutableList) } }
0
Kotlin
0
0
c4b4bcd766612a4669bbfdba597fc1cbbc89e974
1,520
WalletGuru
MIT License
database-sync/src/main/kotlin/com/github/ya0igoddess/dbsync/config/ImportAllOnceExtension.kt
ya0igoddess
642,543,987
false
{"Kotlin": 51513, "Groovy": 716}
package com.github.ya0igoddess.dbsync.config import org.kodein.di.DI fun DI.Builder.importAllOnce(vararg modules: DI.Module) { for (module in modules) { importOnce(module) } }
0
Kotlin
0
0
317407e3ca6da0227bcbf57bbd37fb2b4b5c1c73
193
skaard-database-sync
MIT License
app/src/main/java/com/geode/launcher/log/LogLine.kt
geode-sdk
495,234,000
false
{"Kotlin": 207505, "C++": 3956, "CMake": 1491}
package com.geode.launcher.log import kotlinx.datetime.Clock import kotlinx.datetime.Instant import kotlinx.datetime.TimeZone import kotlinx.datetime.toJavaInstant import kotlinx.datetime.toLocalDateTime import okio.BufferedSource import java.io.IOException fun BufferedSource.readCChar(): Char { return this.readUtf8CodePoint().toChar() } fun BufferedSource.readCString(): String { val buffer = StringBuilder() var lastByte = this.readCChar() while (lastByte != '\u0000') { buffer.append(lastByte) lastByte = this.readCChar() } return buffer.toString() } data class ProcessInformation(val processId: Int, val threadId: Int, val processUid: Int) enum class LogPriority { UNKNOWN, DEFAULT, VERBOSE, DEBUG, INFO, WARN, ERROR, FATAL, SILENT; companion object { fun fromByte(byte: Byte): LogPriority { return when (byte.toInt()) { 0x1 -> DEFAULT 0x2 -> VERBOSE 0x3 -> DEBUG 0x4 -> INFO 0x5 -> WARN 0x6 -> ERROR 0x7 -> FATAL 0x8 -> SILENT else -> UNKNOWN } } } fun toChar(): Char { return when (this) { VERBOSE -> 'V' DEBUG -> 'D' INFO -> 'I' WARN -> 'W' ERROR -> 'E' FATAL -> 'F' SILENT -> 'S' else -> '?' } } } /** * Represents a log entry from logcat. */ data class LogLine( val process: ProcessInformation, val time: Instant, val logId: Int, val priority: LogPriority, val tag: String, val message: String ) { companion object { private enum class EntryVersion { V3, V4 } private fun headerSizeToVersion(size: UShort) = when (size.toInt()) { 0x18 -> EntryVersion.V3 0x1c -> EntryVersion.V4 else -> throw IOException("LogLine::fromInputStream: unknown format for (headerSize = $size)") } fun fromBufferedSource(source: BufferedSource): LogLine { /* // from android <liblog/include/log/log_read.h> // there are multiple logger entry formats // use the header_size to determine the one you have struct logger_entry_v3 { uint16_t len; // length of the payload uint16_t hdr_size; // sizeof(struct logger_entry_v3) int32_t pid; // generating process's pid int32_t tid; // generating process's tid int32_t sec; // seconds since Epoch int32_t nsec; // nanoseconds uint32_t lid; // log id of the payload } struct logger_entry_v4 { uint16_t len; // length of the payload uint16_t hdr_size; // sizeof(struct logger_entry_v4 = 28) int32_t pid; // generating process's pid uint32_t tid; // generating process's tid uint32_t sec; // seconds since Epoch uint32_t nsec; // nanoseconds uint32_t lid; // log id of the payload, bottom 4 bits currently uint32_t uid; // generating process's uid }; */ /* val payloadLength = */ source.readShortLe() val headerSize = source.readShortLe().toUShort() val entryVersion = headerSizeToVersion(headerSize) val pid = source.readIntLe() val tid = source.readIntLe() val sec = source.readIntLe().toLong() val nSec = source.readIntLe() val lid = source.readIntLe() val uid = if (entryVersion == EntryVersion.V4) source.readIntLe() else 0 val processInformation = ProcessInformation(pid, tid, uid) val time = Instant.fromEpochSeconds(sec, nSec) val priorityByte = source.readByte() val priority = LogPriority.fromByte(priorityByte) val tag = source.readCString() val message = source.readCString() return LogLine( process = processInformation, priority = priority, time = time, logId = lid, tag = tag, message = message ) } fun showException(exception: Exception) = LogLine( process = ProcessInformation(0, 0, 0), time = Clock.System.now(), logId = 0, priority = LogPriority.FATAL, tag = "GeodeLauncher", message = "Failed to parse log entry with ${exception.stackTraceToString()}" ) } val identifier = time.toJavaInstant() val messageTrimmed by lazy { this.message.trim() } val formattedTime by lazy { this.time.toLocalDateTime(TimeZone.currentSystemDefault()) } val asSimpleString by lazy { "$formattedTime [${this.priority.toChar()}/${this.tag}]: ${this.messageTrimmed}" } }
2
Kotlin
4
24
c9a712f692428e2fc17e6503cae110f65157dbe5
5,210
android-launcher
Boost Software License 1.0
src/jvmMain/kotlin/tools/empathy/libro/server/health/EnvironmentCheck.kt
ontola
624,799,212
false
null
package tools.empathy.libro.server.health import io.ktor.server.application.ApplicationCall import kotlinx.coroutines.runBlocking import tools.empathy.libro.server.configuration.libroConfig import tools.empathy.libro.server.plugins.persistentStorage import tools.empathy.libro.server.sessions.oidc.OIDCSettingsManager class EnvironmentCheck : Check() { init { name = "Environment variables" } override suspend fun runTest(call: ApplicationCall): Exception? { val config = call.application.libroConfig val env = config.env val failed = buildList { fun checkValue(k: String, v: String?) { if (v.isNullOrBlank()) { add(k) } } val oidcSettings = runBlocking { OIDCSettingsManager(config, call.application.persistentStorage).getOrCreate() } if (env != "development") { checkValue("invalidationChannel", config.redis.invalidationChannel) checkValue("reportingKey", config.serverReportingKey) checkValue("mapboxKey", config.maps?.key) checkValue("mapboxUsername", config.maps?.username) } checkValue("redisUrl", config.redis.uri.toString()) checkValue("clientName", config.sessions.clientName) checkValue("clientId", oidcSettings?.credentials?.clientId) checkValue("clientSecret", oidcSettings?.credentials?.clientSecret) checkValue("jwtEncryptionToken", config.sessions.jwtEncryptionToken) checkValue("sessionSecret", config.sessions.sessionSecret) } if (failed.isNotEmpty()) { throw Exception("Invalid: ${failed.joinToString()}") } return null } }
0
Kotlin
0
0
2e9fa6622e00ebf5ffd1cf6156e8abd774430f7e
1,791
libro-cache
MIT License
app/src/main/java/com/andrii_a/muze/ui/navigation/NavigationScreen.kt
andrew-andrushchenko
655,902,633
false
{"Kotlin": 199050}
package com.andrii_a.muze.ui.navigation import androidx.annotation.StringRes import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Groups import androidx.compose.material.icons.filled.Image import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.outlined.Groups import androidx.compose.material.icons.outlined.Image import androidx.compose.material.icons.outlined.Search import androidx.compose.ui.graphics.vector.ImageVector import com.andrii_a.muze.R enum class NavigationScreen( val screen: Screen, @StringRes val titleRes: Int, val iconUnselected: ImageVector, val iconSelected: ImageVector ) { Artists( screen = Screen.Artists, titleRes = R.string.artists, iconSelected = Icons.Filled.Groups, iconUnselected = Icons.Outlined.Groups ), Artworks( screen = Screen.Artworks, titleRes = R.string.artworks, iconSelected = Icons.Filled.Image, iconUnselected = Icons.Outlined.Image ), Search( screen = Screen.Search, titleRes = R.string.search, iconSelected = Icons.Filled.Search, iconUnselected = Icons.Outlined.Search ) }
0
Kotlin
0
1
09bb666c27d4311a16953738afa398ea73bbc806
1,232
Muze
The Unlicense
app/src/main/java/com/gregory/ideabox/managers/AuthenticationManager.kt
videogreg93
157,008,078
false
null
package com.gregory.ideabox.managers import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.gregory.ideabox.models.User class AuthenticationManager(val firebaseManager: FirebaseManager) { var myId: String = "" suspend fun getCurrentUser(): User { return firebaseManager.getUser(myId) } }
3
Kotlin
0
0
698ef499989350f927ea2cb64340a390711031e9
356
IdeaBox
MIT License
collaboration-suite-phone-ui/src/main/java/com/kaleyra/collaboration_suite_phone_ui/chat/adapter_items/message/abstract_message/KaleyraBaseChatMessageItem.kt
Bandyer
337,367,845
false
null
/* * Copyright 2022 Kaleyra @ https://www.kaleyra.com * * 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.kaleyra.collaboration_suite_phone_ui.chat.adapter_items.message.abstract_message import com.mikepenz.fastadapter.items.AbstractItem /** * Base Kaleyra Chat Message Item containing data of type T * @property data contained in the message * @constructor * @author kristiyan */ abstract class KaleyraBaseChatMessageItem<T : KaleyraBaseChatMessage>(var data: T) : AbstractItem<KaleyraBaseChatMessageViewHolder<*, *>>() { /** * @suppress */ override val type = data.hashCode() }
1
Kotlin
2
2
b102f07b8572ec40f61446d4f052a0f023cdb815
1,131
Bandyer-Android-Design
Apache License 2.0
app/src/main/java/com/spark/fastplayer/presentation/player/PlayBackMetaData.kt
manish218
597,589,035
false
null
package com.spark.fastplayer.presentation.player data class PlayBackMetaData( val title: String, val channelLogoUrl: String, val streamUrl: String )
2
Kotlin
0
0
ed19101e5da5c212c0bd594257bbb7a249ceb8d2
161
fast-player
MIT License
app/src/main/java/hanna/scanme/calculator/ui/viewmodel/ImageViewModel.kt
hannaiazizah
682,931,599
false
null
package hanna.scanme.calculator.ui.viewmodel import android.graphics.Bitmap import androidx.lifecycle.ViewModel import hanna.scanme.calculator.domain.model.MathArgument import hanna.scanme.calculator.domain.model.ScanResult import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow class ImageViewModel : ViewModel() { private val _capturedImage = MutableStateFlow<Bitmap?>(null) val capturedImage: StateFlow<Bitmap?> = _capturedImage private val _scanResult = MutableStateFlow(ScanResult()) val scanResult: StateFlow<ScanResult> = _scanResult fun setCapturedImage(image: Bitmap?) { _capturedImage.value = image } fun calculate(mathArgument: MathArgument) { val result = when (mathArgument.operator) { '+' -> mathArgument.firstInt + mathArgument.secondInt '-' -> mathArgument.firstInt - mathArgument.secondInt '*' -> mathArgument.firstInt * mathArgument.secondInt '/' -> mathArgument.firstInt / mathArgument.secondInt else -> 0 } _scanResult.value = ScanResult( mathArgument = "${mathArgument.firstInt} ${mathArgument.operator} ${mathArgument.secondInt}", result = result ) } }
0
Kotlin
0
0
76246c8e94cd91ef0b80094edca2757fe3e4888f
1,270
ScanMeCalculator
MIT License
app/src/main/java/hanna/scanme/calculator/ui/viewmodel/ImageViewModel.kt
hannaiazizah
682,931,599
false
null
package hanna.scanme.calculator.ui.viewmodel import android.graphics.Bitmap import androidx.lifecycle.ViewModel import hanna.scanme.calculator.domain.model.MathArgument import hanna.scanme.calculator.domain.model.ScanResult import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow class ImageViewModel : ViewModel() { private val _capturedImage = MutableStateFlow<Bitmap?>(null) val capturedImage: StateFlow<Bitmap?> = _capturedImage private val _scanResult = MutableStateFlow(ScanResult()) val scanResult: StateFlow<ScanResult> = _scanResult fun setCapturedImage(image: Bitmap?) { _capturedImage.value = image } fun calculate(mathArgument: MathArgument) { val result = when (mathArgument.operator) { '+' -> mathArgument.firstInt + mathArgument.secondInt '-' -> mathArgument.firstInt - mathArgument.secondInt '*' -> mathArgument.firstInt * mathArgument.secondInt '/' -> mathArgument.firstInt / mathArgument.secondInt else -> 0 } _scanResult.value = ScanResult( mathArgument = "${mathArgument.firstInt} ${mathArgument.operator} ${mathArgument.secondInt}", result = result ) } }
0
Kotlin
0
0
76246c8e94cd91ef0b80094edca2757fe3e4888f
1,270
ScanMeCalculator
MIT License
payments-model/src/main/java/com/stripe/android/model/Card.kt
stripe
6,926,049
false
null
package com.stripe.android.model import androidx.annotation.IntRange import androidx.annotation.RestrictTo import androidx.annotation.Size import com.stripe.android.core.model.StripeModel import kotlinx.parcelize.Parcelize /** * A representation of a [Card API object](https://stripe.com/docs/api/cards/object). */ @Parcelize data class Card @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) constructor( /** * Two-digit number representing the card’s expiration month. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-exp_month). */ @get:IntRange(from = 1, to = 12) val expMonth: Int?, /** * Four-digit number representing the card’s expiration year. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-exp_year). */ val expYear: Int?, /** * Cardholder name. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-name). */ val name: String? = null, /** * Address line 1 (Street address/PO Box/Company name). * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-address_line1). */ val addressLine1: String? = null, /** * If address_line1 was provided, results of the check: `pass`, `fail`, `unavailable`, * or `unchecked`. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-address_line1_check). */ val addressLine1Check: String? = null, /** * Address line 2 (Apartment/Suite/Unit/Building). * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-address_line2). */ val addressLine2: String? = null, /** * City/District/Suburb/Town/Village. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-address_city). */ val addressCity: String? = null, /** * State/County/Province/Region. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-address_state). */ val addressState: String? = null, /** * ZIP or postal code. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-address_zip). */ val addressZip: String? = null, /** * If `address_zip` was provided, results of the check: `pass`, `fail`, `unavailable`, * or `unchecked`. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-address_zip_check). */ val addressZipCheck: String? = null, /** * Billing address country, if provided when creating card. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-address_country). */ val addressCountry: String? = null, /** * The last four digits of the card. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-last4). */ @Size(4) val last4: String? = null, /** * Card brand. See [CardBrand]. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-brand). */ val brand: CardBrand, /** * Card funding type. See [CardFunding]. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-funding). */ val funding: CardFunding? = null, /** * Uniquely identifies this particular card number. You can use this attribute to check whether * two customers who’ve signed up with you are using the same card number, for example. * For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized * number might be provided instead of the underlying card number. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-fingerprint). */ val fingerprint: String? = null, /** * Two-letter ISO code representing the country of the card. You could use this * attribute to get a sense of the international breakdown of cards you’ve collected. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-country). */ val country: String? = null, /** * Three-letter [ISO code for currency](https://stripe.com/docs/payouts). Only * applicable on accounts (not customers or recipients). The card can be used as a transfer * destination for funds in this currency. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-currency). */ val currency: String? = null, /** * The ID of the customer that this card belongs to. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-customer). */ val customerId: String? = null, /** * If a CVC was provided, results of the check: `pass`, `fail`, `unavailable`, * or `unchecked`. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-cvc_check). */ val cvcCheck: String? = null, /** * Unique identifier for the object. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-id). */ override val id: String?, /** * If the card number is tokenized, this is the method that was used. See [TokenizationMethod]. * * See [API Reference](https://stripe.com/docs/api/cards/object#card_object-tokenization_method). */ val tokenizationMethod: TokenizationMethod? = null ) : StripeModel, StripePaymentSource { @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) companion object { /** * See https://stripe.com/docs/api/cards/object#card_object-brand for valid values. */ @JvmSynthetic fun getCardBrand(brandName: String?): CardBrand { return when (brandName) { "American Express" -> CardBrand.AmericanExpress "Diners Club" -> CardBrand.DinersClub "Discover" -> CardBrand.Discover "JCB" -> CardBrand.JCB "MasterCard" -> CardBrand.MasterCard "UnionPay" -> CardBrand.UnionPay "Visa" -> CardBrand.Visa else -> CardBrand.Unknown } } } }
88
null
644
935
bec4fc5f45b5401a98a310f7ebe5d383693936ea
6,279
stripe-android
MIT License
cli/src/main/kotlin/com/malinskiy/marathon/cli/config/deserialize/AnalyticsConfigurationDeserializer.kt
plastiv
366,319,680
true
{"Kotlin": 462782, "JavaScript": 40915, "SCSS": 27604, "HTML": 2960, "Shell": 1972, "CSS": 1662}
package com.malinskiy.marathon.cli.config.deserialize import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.malinskiy.marathon.exceptions.ConfigurationException import com.malinskiy.marathon.execution.AnalyticsConfiguration class AnalyticsConfigurationDeserializer : StdDeserializer<AnalyticsConfiguration>(AnalyticsConfiguration::class.java) { override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): AnalyticsConfiguration { val node: JsonNode? = p?.codec?.readTree(p) val influxNode = node?.get("influx") val graphiteNode = node?.get("graphite") if (influxNode != null && graphiteNode != null) { throw ConfigurationException("You cannot use both InfluxDB and Graphite a the same time") } if (influxNode != null) { val influxDbConfiguration = ctxt?.readValue(influxNode.traverse(p.codec), AnalyticsConfiguration.InfluxDbConfiguration::class.java) if (influxDbConfiguration != null) return influxDbConfiguration } if (graphiteNode != null) { val graphiteConfiguration = ctxt?.readValue(graphiteNode.traverse(p.codec), AnalyticsConfiguration.GraphiteConfiguration::class.java) if (graphiteConfiguration != null) return graphiteConfiguration } return AnalyticsConfiguration.DisabledAnalytics } }
0
null
0
0
2b54a2e579e9c09c8be82d8b2c3a74d601668417
1,573
marathon
Apache License 2.0
core/util/src/main/java/com/loryblu/core/util/validators/NameInputValid.kt
loryblu
665,795,911
false
null
package com.routinely.routinely.util.validators import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize sealed class NameInputValid : Parcelable { data object Valid: NameInputValid() data class Error(val messageId: Int): NameInputValid() data object Empty: NameInputValid() }
18
null
4
8
4eaeb70fe253a12ec4ad3b438aa750dad3c6b548
309
loryblu-android
MIT License
data/src/main/kotlin/ir/aminrahkan/data/di/modules/DbModule.kt
aminrahkan
572,371,818
false
{"Kotlin": 10267}
package ir.aminrahkan.data.di.modules import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent // Developer : Amin Rahkan - [email protected] // Date : 12/26/22 - 2022 // Project name : TheMovieDB @InstallIn(SingletonComponent::class) class DbModule { }
0
Kotlin
0
2
85378f26005bf43b4616fcf0c6b8a4109de77ada
285
TheMovieDB
Apache License 2.0
kotpass/src/main/kotlin/io/github/anvell/kotpass/constants/GroupOverride.kt
Anvell
384,214,968
false
null
package io.github.anvell.kotpass.constants enum class GroupOverride { Inherit, Enabled, Disabled }
2
Kotlin
0
3
ed49133f659b57a1220a98449c0449c3ac0b9f4f
112
kotpass
MIT License
src/main/kotlin/com/rubylight/android/statistics/Uploader.kt
ruby-light
240,274,198
false
null
package com.rubylight.android.statistics import android.os.Handler import android.os.HandlerThread import java.io.BufferedOutputStream import java.io.ByteArrayOutputStream import java.net.HttpURLConnection import java.net.URL import java.util.zip.GZIPOutputStream import kotlin.text.Charsets.UTF_8 class Uploader(private val configuration: Configuration) { internal val sendThread = SendThread() init { sendThread.start() } internal fun uploadReports(reportsContent: String, callback: (success: Boolean) -> Unit) { sendThread.post { debug { String.format("Upload reports: %s.", reportsContent) } try { val encodedContent = encodeContent(reportsContent) val response = doPostRequest( configuration.serverUrl, configuration.connectTimeoutMillis, configuration.readTimeoutMillis, configuration.apiKey, encodedContent.first, encodedContent.second ) when (response) { 200 -> callback(true) else -> { debug { String.format( "Wrong response while do post request: %s", response ) } callback(false) } } } catch (th: Throwable) { debug { String.format("Error while do post request: %s", th.message) } callback(false) } } } private fun doPostRequest( url: URL, connectTimeoutMillis: Long, readTimeoutMillis: Long, apiKey: String, content: ByteArray, contentEncoding: String? ): Int { val connection = url.openConnection() as HttpURLConnection try { with(connection) { connectTimeout = connectTimeoutMillis.toInt() readTimeout = readTimeoutMillis.toInt() doOutput = true requestMethod = "POST" setRequestProperty( "User-Agent", "${Formats.LIBRARY_NAME}/${Formats.LIBRARY_VERSION}" ) setRequestProperty("Api-Version", Formats.API_VERSION) setRequestProperty("Api-Key", apiKey) setRequestProperty("Content-Type", "application/json") contentEncoding?.let { setRequestProperty("Content-Encoding", it) } setFixedLengthStreamingMode(content.size) BufferedOutputStream(outputStream).use { out -> out.write(content) out.flush() } return connection.responseCode } } finally { connection.disconnect() } } private fun encodeContent(content: String): Pair<ByteArray, String?> { if (content.length > 200) { when (configuration.uploadContentEncoding) { "gzip" -> { val gzipContent = gzip(content) debug { String.format( "Use gzip encoding for upload, original size: %s, compressed: %s", content.length, gzipContent.size ) } return Pair(gzipContent, "gzip") } } } return Pair(content.toByteArray(), null) } private fun gzip(content: String): ByteArray { val buffer = ByteArrayOutputStream(content.length / 2) GZIPOutputStream(buffer).bufferedWriter(UTF_8).use { it.write(content) it.flush() } return buffer.toByteArray() } internal class SendThread : HandlerThread("sendStatisticsThread") { private val handler by lazy { Handler(looper) } fun post(task: () -> Unit) { handler.post(task) } } }
1
null
1
1
658fe269b508623bce20a27de7f2425d0b57bf85
4,206
RLT-Android
MIT License
widgetssdk/src/main/java/com/glia/widgets/view/unifiedui/theme/call/VisitorVideoTheme.kt
salemove
312,288,713
false
{"Kotlin": 1962137, "Java": 448482, "Shell": 1802}
package com.glia.widgets.view.unifiedui.theme.call import com.glia.widgets.view.unifiedui.Mergeable import com.glia.widgets.view.unifiedui.merge @JvmInline internal value class VisitorVideoTheme( val flipCameraButton: BarButtonStyleTheme? = null ) : Mergeable<VisitorVideoTheme> { override fun merge(other: VisitorVideoTheme): VisitorVideoTheme = VisitorVideoTheme(flipCameraButton merge other.flipCameraButton) }
3
Kotlin
1
7
3c499a6624bc787a276956bca46d07aa514d3625
424
android-sdk-widgets
MIT License
app/src/main/java/com/letier/brandon/notescleanarch/feature_note/presentation/notes/NoteState.kt
letiger
862,211,455
false
{"Kotlin": 54163}
package com.letier.brandon.notescleanarch.feature_note.presentation.notes import com.letier.brandon.notescleanarch.feature_note.domain.model.NoteEntity import com.letier.brandon.notescleanarch.feature_note.domain.use_case.util.NoteOrder import com.letier.brandon.notescleanarch.feature_note.domain.use_case.util.OrderType data class NoteState( val notes: List<NoteEntity> = emptyList(), val noteOrder: NoteOrder = NoteOrder.Date(OrderType.Descending), val isOrderSectionVisible: Boolean = false )
0
Kotlin
0
0
a893e225242e683b4a277f7b538a0712d65afea7
510
NotesCleanArch
Apache License 2.0
testomania/src/main/kotlin/com/earth/testomania/apis/quiz/opentdb/data/source/OpenTdbQuizApi.kt
Nodrex
469,365,691
false
null
package com.earth.testomania.apis.quiz.opentdb.data.source import com.earth.testomania.apis.quiz.opentdb.data.source.remote.dto.OpenTdbQuizDTO import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface OpenTdbQuizApi { @GET("api.php") suspend fun getQuizList( @Query("amount") questionCount: Int = 20, @Query("category") category: Int = 0, ): Response<OpenTdbQuizDTO> }
64
Kotlin
3
49
c91c7496ad2a8e4b499becb56c042f4e7480e012
432
Testomania
Creative Commons Zero v1.0 Universal
http_client/src/main/kotlin/model/HttpClientCall.kt
hexagonkt
56,139,239
false
null
package com.hexagonkt.http.client.model import com.hexagonkt.http.model.HttpCall data class HttpClientCall( override val request: HttpClientRequest = HttpClientRequest(), override val response: HttpClientResponsePort = HttpClientResponse(), ) : HttpCall<HttpClientRequest, HttpClientResponsePort>
23
Kotlin
81
373
dbc0d602aa48cfc58644f15329a8308b65ca6cc1
307
hexagon
MIT License
app/src/test/java/fr/mcgalanes/rectus/core/common/formatter/PriceFormatterTest.kt
McGalanes
504,936,229
false
{"Kotlin": 46792}
package fr.mcgalanes.rectus.core.common.formatter import org.junit.Assert import org.junit.Test internal class PriceFormatterTest { @Test fun `should format price with plus symbol`() { Assert.assertEquals( "+25,89 €", 25.89.toPriceString(showPlusSymbol = true) ) } @Test fun `should format price without plus symbol`() { Assert.assertEquals( "25,89 €", 25.89.toPriceString(showPlusSymbol = false) ) } @Test fun `should format price with minus symbol`() { Assert.assertEquals( "-2 756,70 €", (-2756.7).toPriceString() ) } }
0
Kotlin
0
0
575d456b0708a588b3979f244b44da543f90f06e
684
rectus
Apache License 2.0
src/main/kotlin/no/nav/syfo/kafka/KafkaUtils.kt
navikt
192,538,863
false
{"Kotlin": 177545, "Dockerfile": 278}
package no.nav.syfo.kafka import java.util.Properties import kotlin.reflect.KClass import org.apache.kafka.clients.consumer.ConsumerConfig import org.apache.kafka.clients.producer.ProducerConfig import org.apache.kafka.common.serialization.* interface KafkaConfig { val kafkaBootstrapServers: String } interface KafkaCredentials { val kafkaUsername: String val kafkaPassword: String } fun loadBaseConfig(env: KafkaConfig, credentials: KafkaCredentials): Properties = Properties().also { it.load(KafkaConfig::class.java.getResourceAsStream("/kafka_base.properties")) it["sasl.jaas.config"] = "org.apache.kafka.common.security.plain.PlainLoginModule required " + "username=\"${credentials.kafkaUsername}\" password=\"${<PASSWORD>";" it["bootstrap.servers"] = env.kafkaBootstrapServers it["specific.avro.reader"] = true } fun Properties.envOverrides() = apply { putAll( System.getenv() .filter { (key, _) -> key.startsWith("KAFKA_") } .map { (key, value) -> key.substring(6).lowercase().replace("_", ".") to value } .toMap() ) } fun Properties.toConsumerConfig( groupId: String, valueDeserializer: KClass<out Deserializer<out Any>>, keyDeserializer: KClass<out Deserializer<out Any>> = StringDeserializer::class ): Properties = Properties().also { it.putAll(this) it[ConsumerConfig.GROUP_ID_CONFIG] = groupId it[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = keyDeserializer.java it[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = valueDeserializer.java it[ConsumerConfig.MAX_POLL_RECORDS_CONFIG] = "1" } fun Properties.toProducerConfig( groupId: String, valueSerializer: KClass<out Serializer<out Any>>, keySerializer: KClass<out Serializer<out Any>> = StringSerializer::class ): Properties = Properties().also { it.putAll(this) it[ConsumerConfig.GROUP_ID_CONFIG] = groupId it[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = valueSerializer.java it[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = keySerializer.java }
0
Kotlin
1
0
98cd8bfc7650a86334c43495c09e10046736a083
2,168
pale-2
MIT License
src/main/kotlin/com/swisschain/matching/engine/incoming/parsers/data/CashInOutParsedData.kt
swisschain
255,464,363
false
{"Gradle": 2, "Text": 2, "Ignore List": 1, "Markdown": 1, "Kotlin": 578, "XML": 2, "Shell": 2, "Batchfile": 1, "Java": 3, "Protocol Buffer": 14, "Java Properties": 1, "INI": 2, "YAML": 2}
package com.swisschain.matching.engine.incoming.parsers.data import com.swisschain.matching.engine.messages.MessageWrapper class CashInOutParsedData(messageWrapper: MessageWrapper, val assetId: String): ParsedData(messageWrapper)
1
null
1
1
5ef23544e9c5b21864ec1de7ad0f3e254044bbaa
257
Exchange.MatchingEngine
Apache License 2.0
src/main/kotlin/com/swisschain/matching/engine/incoming/parsers/data/CashInOutParsedData.kt
swisschain
255,464,363
false
{"Gradle": 2, "Text": 2, "Ignore List": 1, "Markdown": 1, "Kotlin": 578, "XML": 2, "Shell": 2, "Batchfile": 1, "Java": 3, "Protocol Buffer": 14, "Java Properties": 1, "INI": 2, "YAML": 2}
package com.swisschain.matching.engine.incoming.parsers.data import com.swisschain.matching.engine.messages.MessageWrapper class CashInOutParsedData(messageWrapper: MessageWrapper, val assetId: String): ParsedData(messageWrapper)
1
null
1
1
5ef23544e9c5b21864ec1de7ad0f3e254044bbaa
257
Exchange.MatchingEngine
Apache License 2.0
app/src/main/java/ro/alexmamo/firebasesigninwithgoogle/presentation/auth/AuthViewModel.kt
alexmamo
488,559,147
false
{"Kotlin": 33271}
package ro.alexmamo.firebasesigninwithgoogle.presentation.auth import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.android.gms.auth.api.identity.SignInClient import com.google.firebase.auth.AuthCredential import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import ro.alexmamo.firebasesigninwithgoogle.domain.model.Response.Loading import ro.alexmamo.firebasesigninwithgoogle.domain.model.Response.Success import ro.alexmamo.firebasesigninwithgoogle.domain.repository.AuthRepository import ro.alexmamo.firebasesigninwithgoogle.domain.repository.OneTapSignInResponse import ro.alexmamo.firebasesigninwithgoogle.domain.repository.SignInWithGoogleResponse import javax.inject.Inject @HiltViewModel class AuthViewModel @Inject constructor( private val repo: AuthRepository, val oneTapClient: SignInClient ): ViewModel() { val isUserAuthenticated get() = repo.isUserAuthenticatedInFirebase var oneTapSignInResponse by mutableStateOf<OneTapSignInResponse>(Success(null)) private set var signInWithGoogleResponse by mutableStateOf<SignInWithGoogleResponse>(Success(false)) private set fun oneTapSignIn() = viewModelScope.launch { oneTapSignInResponse = Loading oneTapSignInResponse = repo.oneTapSignInWithGoogle() } fun signInWithGoogle(googleCredential: AuthCredential) = viewModelScope.launch { oneTapSignInResponse = Loading signInWithGoogleResponse = repo.firebaseSignInWithGoogle(googleCredential) } }
1
Kotlin
15
56
9e1aedcfc3612526b9316e898cc5fcdb79a2e469
1,691
FirebaseSignInWithGoogle
Apache License 2.0
native/native.tests/testData/codegen/fileCheck/filecheck_expected_failure.kt
JetBrains
3,432,266
false
null
// TARGET_BACKEND: NATIVE // IGNORE_BACKEND: NATIVE // FILECHECK_STAGE: CStubs // The check below is intentionally wrong and must fail. // Test system should report test as passed due to IGNORE_BACKEND directive above. // CHECK-LABEL: NONEXISTENT fun box(): String = "OK"
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
273
kotlin
Apache License 2.0
src/main/kotlin/ru/inforion/lab403/common/logging/dsl/AbstractConfig.kt
inforion
175,940,719
false
null
package ru.inforion.lab403.common.logging.dsl fun interface AbstractConfig<T> { fun generate(): T }
1
Kotlin
2
7
7cc7570b7ec3ace213dea13d1debbc505812f969
104
kotlin-logging
MIT License
profilers-integration/testSrc/com/android/tools/profilers/integration/taskbased/NativeAllocationsTaskTest.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.profilers.integration.taskbased import com.android.tools.asdriver.tests.Emulator import com.android.tools.profilers.integration.ProfilersTestBase import org.junit.Test class NativeAllocationsTaskTest : ProfilersTestBase() { /** * Validate native allocations task workflow is working. * * Test Steps: * 1. Import "minApp" in the testData directory of this module. * 2. Deploy App and open profiler tool window, set to debuggable mode. * 3. Select device -> process -> task-> starting point. * 4. Start the task * 5. Stop the task * * Test Verifications: * 1. Verify if the profiler tool window is opened. * 2. Verify if Transport proxy is created for the device. * 3. Verify task start succeeded. * 4. Verify task stop succeeded. * 5. Verify if the capture is parsed successfully. * 6. Verify UI components after capture is parsed. */ @Test fun test() { taskBasedProfiling( systemImage = Emulator.SystemImage.API_33, deployApp = true, testFunction = { studio, _ -> // Selecting the device. selectDevice(studio) // Selecting the process id which consists of `minapp` selectProcess(studio) // Selecting native allocations task. selectNativeAllocationsTask(studio) // Select Process start to "Now" setProfilingStartingPointToNow(studio) // Starting task, assuming that the default is set to "Now" startTask(studio) verifyIdeaLog(".*PROFILER\\:\\s+Session\\s+started.*support\\s+level\\s+\\=DEBUGGABLE\$", 120) verifyIdeaLog(".*PROFILER\\:\\s+Native\\s+allocations\\s+capture\\s+start\\s+succeeded", 300) Thread.sleep(4000) stopTask(studio) verifyIdeaLog(".*PROFILER\\:\\s+Native\\s+allocations\\s+capture\\s+stop\\s+succeeded", 300) studio.waitForComponentByClass("TooltipLayeredPane", "CapturePanelUi") } ) } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
2,593
android
Apache License 2.0
app/src/main/java/xyz/ramil/pikaviewer/view/adapters/PostAdapter.kt
ramilxyz
300,304,202
false
null
package xyz.ramil.pikaviewer.view.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.appcompat.widget.PopupMenu import androidx.cardview.widget.CardView import androidx.core.view.get import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import xyz.ramil.pikaviewer.R import xyz.ramil.pikaviewer.database.DataBaseManager import xyz.ramil.pikaviewer.model.PostModel class PostAdapter(private var data: List<PostModel>, private val context: Context, view: View?) : RecyclerView.Adapter<PostAdapter.ViewHolder>() { interface OnItemClickListener { fun OnItemClick(postModel: PostModel) } private var mOnItemClickListener: OnItemClickListener? = null fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) { mOnItemClickListener = onItemClickListener } fun update(data: List<PostModel>, view: View?) { this.data = data notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val rowItem = LayoutInflater.from(parent.context).inflate(R.layout.item_feed, parent, false) return ViewHolder(rowItem) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { if (mOnItemClickListener != null) { holder.cvPost.setOnClickListener(View.OnClickListener { mOnItemClickListener?.OnItemClick( data[position] ) }) } if (data[position].images != null && !data[position].images?.isEmpty()!!) { holder.image.visibility = View.VISIBLE val url = data[position].images?.get(0)!! Glide.with(context) .load(url) .apply( RequestOptions.placeholderOf(R.drawable.ic_launcher_background) .error(R.drawable.ic_launcher_background) ) .into(holder.image) } else { holder.image.visibility = View.GONE } if (data[position].body != null) { if (data[position].body?.isEmpty()!!) holder.body.visibility = View.GONE else holder.body.visibility = View.VISIBLE holder.body.text = data[position].body } else holder.body.visibility = View.GONE holder.title.text = data[position].title if (data[position].images != null) { if (data[position].images?.size!! > 1) smallImageRvInit(holder, position) if (data[position].images?.size!! <= 1) { holder.rv.visibility = View.GONE } else { holder.rv.visibility = View.VISIBLE } } menuClick(holder, position) } fun smallImageRvInit(holder: ViewHolder, position: Int) { var feedImageAdapter: FeedImageAdapter? = null var recyclerView: RecyclerView? = null recyclerView = holder.rv recyclerView.setHasFixedSize(true) val horizontalLayoutManagaer = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) recyclerView.layoutManager = horizontalLayoutManagaer feedImageAdapter = context.let { FeedImageAdapter(mutableListOf(), it) } recyclerView.adapter = feedImageAdapter val imageList: MutableList<String> = mutableListOf() imageList.addAll(data[position].images as MutableList<String>) imageList.removeAt(0) //TODO пост может сожержать много изображений, для проверки работы с таким постом // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") // imageList.add("https://i.stack.imgur.com/9TELO.png") feedImageAdapter.update(imageList) } fun menuClick(holder: ViewHolder, position: Int) { holder.menu.setOnClickListener { val pop = PopupMenu(context, it) pop.inflate(R.menu.popup_post) if (data[position].save!!) { pop.menu.get(0).title = context.getString(R.string.remove_from_saved) } else { pop.menu.get(0).title = context.getString(R.string.save) } pop.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.itemSave -> { if (!data[position].save!!) { var item = data[position] item.save = true DataBaseManager.insertData(context, item) pop.menu.get(0).title = context.getString(R.string.save) } else { var item = data[position] item.save = false DataBaseManager.insertData(context, item) pop.menu.get(0).title = context.getString(R.string.remove_from_saved) } } } true } pop.show() true } } override fun getItemCount(): Int { return data.size } class ViewHolder(view: View) : RecyclerView.ViewHolder(view), View.OnClickListener { val title: TextView val body: TextView val image: ImageView val menu: ImageView val rv: RecyclerView val cvPost: CardView override fun onClick(view: View) {} init { view.setOnClickListener(this) title = view.findViewById(R.id.tvPostTitle) body = view.findViewById(R.id.tvPostBody) image = view.findViewById(R.id.ivPicture) menu = view.findViewById(R.id.ivMenu) rv = view.findViewById(R.id.rvSmall) cvPost = view.findViewById(R.id.cvPost) } } }
1
null
1
1
e15716cd61259726569fc3260496fc4fa8add8ea
6,620
pviewer
Apache License 2.0
tmp/arrays/youTrackTests/7254.kt
DaniilStepanov
228,623,440
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
// Original bug: KT-28280 fun issue(firstCondition: Boolean, secondCondition: Boolean) { val names = mutableListOf<String>() when { firstCondition -> names += listOf("Bob", "Tom", "Ann") secondCondition -> names += "Jose" else -> names += "Mary" } }
1
null
12
1
602285ec60b01eee473dcb0b08ce497b1c254983
287
bbfgradle
Apache License 2.0
platform/platform-impl/src/com/intellij/codeInsight/inline/completion/InlineCompletionElements.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.inline.completion import com.intellij.openapi.application.ReadAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental data class InlineCompletionRequest( val file: PsiFile, val editor: Editor, val document: Document, val startOffset: Int, val endOffset: Int, ) { companion object { fun fromDocumentEvent(event: DocumentEvent, editor: Editor): InlineCompletionRequest? { val virtualFile = editor.virtualFile ?: return null val project = editor.project ?: return null val file = ReadAction.compute<PsiFile, Throwable> { PsiManager.getInstance(project).findFile(virtualFile) } return InlineCompletionRequest(file, editor, event.document, event.offset, event.offset + event.newLength) } } } @ApiStatus.Experimental data class InlineCompletionElement(val text: String)
233
null
4912
15,461
9fdd68f908db0b6bb6e08dc33fafb26e2e4712af
1,195
intellij-community
Apache License 2.0
subprojects/delivery/sign-service/src/test/kotlin/com/avito/android/signer/internal/UrlResolverTest.kt
avito-tech
230,265,582
false
{"Kotlin": 3747948, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086}
package com.avito.android.signer.internal import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.Test internal class UrlResolverTest { @Test fun `path with segments`() { val arg = "https://some.ru/service-signer/1" val result = validateUrl(arg) assertThat(result).isEqualTo("https://some.ru/service-signer/1/sign") } }
10
Kotlin
50
414
bc94abf5cbac32ac249a653457644a83b4b715bb
381
avito-android
MIT License
hsm/src/main/java/de/artcom/hsm/Action.kt
igala
226,637,663
false
{"Java": 39015, "Kotlin": 20077}
package de.artcom.hsm abstract class Action() { protected var mPreviousState: State<*>? = null protected var mNextState: State<*>? = null @JvmField protected var mPayload: Map<String?, Any?>? = null abstract fun run() fun setPreviousState(state: State<*>?) { mPreviousState = state } fun setNextState(state: State<*>?) { mNextState = state } fun setPayload(payload: Map<String?, Any?>?) { mPayload = payload } }
1
Java
1
1
204832b927aae2b24cb9648ed91b84c48f5b9a89
482
hsm-kotlin
MIT License
kuberig-dsl-generator/src/main/kotlin/io/kuberig/dsl/generator/meta/kinds/KindTypes.kt
kuberig-io
172,784,898
false
{"Kotlin": 177303, "Shell": 1466, "Java": 360}
package io.kuberig.dsl.generator.meta.kinds data class KindTypes(val kind: Kind, val types: List<String>)
5
Kotlin
1
7
85e1dcd7ed4c25f00d33911d39fee84cb67ca972
106
kuberig-dsl
Apache License 2.0
phoenix-android/src/main/kotlin/fr/acinq/phoenix/android/utils/Clipboard.kt
ACINQ
192,964,514
false
{"C": 8424033, "Kotlin": 2796821, "Swift": 1884690, "Java": 39996, "HTML": 13403, "Dockerfile": 3585, "CMake": 2276, "CSS": 504}
/* * Copyright 2020 ACINQ SAS * * 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 fr.acinq.phoenix.android.utils import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.widget.Toast import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import fr.acinq.phoenix.android.R fun copyToClipboard(context: Context, data: String, dataLabel: String = "") { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.setPrimaryClip(ClipData.newPlainText(dataLabel, data)) Toast.makeText(context, R.string.utils_copied, Toast.LENGTH_SHORT).show() } fun readClipboard(context: Context): String? = (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager) .primaryClip?.getItemAt(0)?.text?.toString().takeIf { !it.isNullOrBlank() } fun share(context: Context, data: String, subject: String, chooserTitle: String? = null) { val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject) shareIntent.putExtra(Intent.EXTRA_TEXT, data) context.startActivity(Intent.createChooser(shareIntent, chooserTitle)) }
97
C
96
666
011c8b85f16ea9ad322cbbba2461439c5e2b0aed
1,804
phoenix
Apache License 2.0
app/src/test/java/com/clean/lbg/domain/mappers/usecase/catDetails/PostFavCatUseCaseTest.kt
P-C-Data
766,525,035
false
{"Gradle Kotlin DSL": 3, "Java Properties": 9, "Shell": 1, "Text": 30, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Proguard": 1, "Kotlin": 82, "XML": 275, "JSON": 360, "Java": 12, "INI": 7, "Motorola 68K Assembly": 3, "SQL": 9, "HTML": 6, "CSS": 4, "JavaScript": 2, "Protocol Buffer Text Format": 1, "PureBasic": 2}
package com.clean.lbg.domain.mappers.usecase.catDetails import com.clean.lbg.data.NetworkResult import com.clean.lbg.data.models.catDetails.PostFavCatModel import com.clean.lbg.domain.mappers.models.CallSuccessModel import com.clean.lbg.domain.repositories.CatDetailsRepository import com.clean.lbg.domain.usecase.catsDetail.PostFavCatUseCase import com.clean.lbg.domain.usecase.catsDetail.PostFavCatUseCaseImpl import com.clean.lbg.models.catMocks.MockPostFavCatModel import com.clean.lbg.models.catMocks.MockSuccessResponse import com.clean.lbg.models.catMocks.toRequestPostFavCatData import com.clean.lbg.models.catMocks.toResponsePostSuccess import com.clean.lbg.utils.Constants import junit.framework.TestCase.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import okhttp3.MediaType.Companion.toMediaType import okhttp3.ResponseBody.Companion.toResponseBody import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.MockitoAnnotations import org.mockito.junit.MockitoJUnitRunner import retrofit2.Response @RunWith(MockitoJUnitRunner::class) class PostFavCatUseCaseTest { @Mock private lateinit var mockRepository: CatDetailsRepository private lateinit var mockUseCae: PostFavCatUseCase @Before fun setUp() { MockitoAnnotations.openMocks(this) mockUseCae = PostFavCatUseCaseImpl(mockRepository) } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `execute should emit success when repository call is successful`() = runTest( UnconfinedTestDispatcher() ) { // Given val imageId = "123" val response = toResponsePostSuccess(MockSuccessResponse()) `when`(mockRepository.postFavouriteCat(PostFavCatModel(imageId, Constants.SUB_ID))) .thenReturn(response) // When val resultFlow = mockUseCae.execute(imageId) // Then resultFlow.collect { result -> if (result is NetworkResult.Success) { assertEquals(response.body()?.message, result.data?.successMessage) assertEquals(response.body()?.id, result.data?.id) } } } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `execute should emit loading state and then error on unsuccessful post data`() = runTest( UnconfinedTestDispatcher() ) { val error = "Invalid request" val imageId = "123" val postFavCatModel = toRequestPostFavCatData(MockPostFavCatModel()) `when`(mockRepository.postFavouriteCat(postFavCatModel)).thenReturn( Response.error( 400, error.toResponseBody("application/json".toMediaType()) ) ) val result = mutableListOf<NetworkResult<CallSuccessModel>>() mockUseCae.execute(imageId).collect { result.add(it) } assert(result.size == 2) // Loading + Error states assert(result[0] is NetworkResult.Loading) assert(result[1] is NetworkResult.Error) // assertions based on the actual error received val errorBody = mockRepository.postFavouriteCat(postFavCatModel).errorBody() val errorString = errorBody?.string() assert(errorString == error) } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `execute should emit loading state and then error on exception`() = runTest( UnconfinedTestDispatcher() ) { val simulatedErrorMessage = "Simulated error" val imageId = "123" `when`(mockRepository.postFavouriteCat(PostFavCatModel(imageId, Constants.SUB_ID))) .thenThrow(RuntimeException(simulatedErrorMessage)) val result = mutableListOf<NetworkResult<CallSuccessModel>>() mockUseCae.execute(imageId).collect { result.add(it) } assert(result.size == 2) // Loading + Error states assert(result[0] is NetworkResult.Loading) assert(result[1] is NetworkResult.Error) // assertions based on the simulated error val errorResult = result[1] as NetworkResult.Error assert(errorResult.message == simulatedErrorMessage) } }
0
Java
0
1
13462ee23e252ab8af068e296542be6c150fc9fb
4,348
LBG-MVVM-Clean-Koin
Apache License 2.0
src/main/kotlin/com/yuukaze/i18next/service/SpreadsheetSynchronizer.kt
ilyatruong-credify
352,675,557
false
{"Gradle Kotlin DSL": 2, "Markdown": 2, "Java Properties": 1, "YAML": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 2, "JSON": 5, "XML": 6, "TSX": 2, "Kotlin": 76, "Java": 16, "SVG": 4, "HTML": 2}
package com.yuukaze.i18next.service import com.google.api.client.auth.oauth2.Credential import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport import com.google.api.client.http.javanet.NetHttpTransport import com.google.api.client.json.JsonFactory import com.google.api.client.json.gson.GsonFactory import com.google.api.client.util.store.FileDataStoreFactory import com.google.api.services.sheets.v4.Sheets import com.google.api.services.sheets.v4.SheetsScopes import com.yuukaze.i18next.PLUGIN_DIRECTORY import java.io.File import java.io.FileNotFoundException import java.io.IOException import java.io.InputStreamReader import java.nio.file.Files import java.security.GeneralSecurityException class SpreadsheetSynchronizer @Throws( IOException::class, GeneralSecurityException::class ) constructor() { var sheetService: Sheets? = null private set var spreadSheetId: String? = null @Throws(IOException::class) private fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): Credential { // Load client secrets. val `in` = SpreadsheetSynchronizer::class.java.getResourceAsStream( CREDENTIALS_FILE_PATH ) ?: throw FileNotFoundException("Resource not found: $CREDENTIALS_FILE_PATH") val clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(`in`)) // Build flow and trigger user authorization request. val flow = GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES ) .setDataStoreFactory(FileDataStoreFactory(File(TOKENS_DIRECTORY_PATH.toUri()))) .setAccessType("offline") .build() val receiver = LocalServerReceiver.Builder().setPort(8888).build() return AuthorizationCodeInstalledApp(flow, receiver).authorize("user") } @Throws(IOException::class, GeneralSecurityException::class) private fun prepare() { val httpTransport = GoogleNetHttpTransport.newTrustedTransport() sheetService = Sheets.Builder( httpTransport, JSON_FACTORY, getCredentials(httpTransport) ) .setApplicationName(APPLICATION_NAME) .build() } companion object { private val SCOPES = listOf(SheetsScopes.SPREADSHEETS) private val JSON_FACTORY: JsonFactory = GsonFactory.getDefaultInstance() private const val CREDENTIALS_FILE_PATH = "/credentials.json" private val TOKENS_DIRECTORY_PATH = PLUGIN_DIRECTORY.resolve("token") private const val APPLICATION_NAME = "IntelliJ i18n Translations" } init { if (!Files.exists(TOKENS_DIRECTORY_PATH)) Files.createDirectories(TOKENS_DIRECTORY_PATH) prepare() } }
1
null
1
1
34dc5ce9589dd3bb9e13b156f57839ec81f852f1
3,136
easy-i18n
MIT License
build-tools/agp-gradle-core/src/main/java/com/android/build/gradle/internal/component/features/BuildConfigCreationConfig.kt
RivanParmar
526,653,590
false
{"Java": 48334972, "Kotlin": 8896058, "HTML": 109232, "Lex": 13233, "ReScript": 3232, "Makefile": 2194}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.component.features import com.android.build.api.variant.BuildConfigField import com.android.builder.compiling.BuildConfigType import org.gradle.api.file.FileCollection import org.gradle.api.provider.MapProperty import java.io.Serializable /** * Creation config for components that support build config. * * To use this in a task that requires assets support, use * [com.android.build.gradle.internal.tasks.factory.features.BuildConfigTaskCreationAction]. * Otherwise, access the nullable property on the component * [com.android.build.gradle.internal.component.ComponentCreationConfig.buildConfigCreationConfig]. */ interface BuildConfigCreationConfig { val buildConfigFields: MapProperty<String, BuildConfigField<out Serializable>> @Deprecated("DO NOT USE, use buildConfigFields map property") val dslBuildConfigFields: Map<String, BuildConfigField<out Serializable>> val compiledBuildConfig: FileCollection val buildConfigType: BuildConfigType }
0
Java
2
17
8fb2bb1433e734aa9901184b76bc4089a02d76ca
1,640
androlabs
Apache License 2.0
app/src/main/java/de/nils_beyer/android/Vertretungen/util/ClassNameConverter.kt
n1lsB
113,602,954
false
{"Java": 115896, "Kotlin": 64863}
package de.nils_beyer.android.Vertretungen.util fun convertClassName(_input : String) : String { var output = _input // Convert 05A as 5a etc if (_input.matches("^\\d+[a-zA-Z]+$".toRegex())) { output = _input.toLowerCase() output = output.replace("^0(\\d[a-zA-Z]+)$".toRegex(), "$1") } return output }
1
null
1
1
115df9ac2df1b684811fac3defa1af5c68c5be0b
338
Vertretungen
MIT License
sdk/src/test/java/de/thomasletsch/StartupTest.kt
thomasletsch
151,754,495
false
{"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "XML": 29, "Kotlin": 43, "Java": 2}
package de.thomasletsch import org.junit.Ignore import org.junit.Test internal class StartupTest { @Test @Ignore // Doesn't work for everyone fun testStartup() { Startup().startup() } }
2
Kotlin
1
3
9e6fa7ec6f8a4b66f064f7cce258f2a9a4c359a1
214
bisecure-gateway
MIT License
Android/sensors/numbizz/StartUp/app/src/main/java/com/hussein/startup/MainActivity.kt
hussien89aa
91,829,561
false
null
package com.hussein.startup import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Vibrator import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(),SensorEventListener { var sensor:Sensor?=null var sensorManager:SensorManager?=null override fun onAccuracyChanged(p0: Sensor?, p1: Int) { } var xold=0.0 var yold=0.0 var zold=0.0 var threadShould=3000.0 var oldtime:Long=0 override fun onSensorChanged(event: SensorEvent?) { var x=event!!.values[0] var y=event!!.values[1] var z=event!!.values[2] var currentTime=System.currentTimeMillis() if((currentTime-oldtime)>100){ var timeDiff=currentTime-oldtime oldtime=currentTime var speed=Math.abs(x+y+z-xold-yold-zold)/timeDiff*10000 if(speed>threadShould){ var v=getSystemService(Context.VIBRATOR_SERVICE) as Vibrator v.vibrate(500) Toast.makeText(applicationContext,"shock",Toast.LENGTH_LONG).show() } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sensorManager=getSystemService(Context.SENSOR_SERVICE)as SensorManager sensor=sensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } override fun onResume() { super.onResume() sensorManager!!.registerListener(this,sensor,SensorManager.SENSOR_DELAY_NORMAL) } override fun onPause() { super.onPause() sensorManager!!.unregisterListener(this) } }
14
null
5101
1,650
29056bcd11c9c22b063370acc20876fa4c77cf30
1,912
KotlinUdemy
MIT License
sample/src/main/java/io/noties/adapt/sample/samples/recyclerview/RecyclerViewGridSample.kt
noties
138,477,077
false
{"Markdown": 10, "Gradle": 9, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "JSON": 2, "XML": 70, "Kotlin": 308, "EditorConfig": 1, "Java": 63, "INI": 4, "YAML": 2, "JavaScript": 1}
package io.noties.adapt.sample.samples.recyclerview import android.view.View import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import io.noties.adapt.Item import io.noties.adapt.recyclerview.AdaptRecyclerView import io.noties.adapt.sample.R import io.noties.adapt.sample.SampleView import io.noties.adapt.sample.annotation.AdaptSample import io.noties.adapt.sample.items.ControlItem @AdaptSample( id = "20210122143147", title = "Grid", description = "<b><tt>RecyclerView</tt></b> with <tt>GridLayoutManager</tt>", tags = ["recyclerview", "grid"] ) class RecyclerViewGridSample : SampleView() { override val layoutResId: Int = R.layout.view_sample_recycler_view override fun render(view: View) { val recyclerView: RecyclerView = view.findViewById(R.id.recycler_view) val layoutManager = GridLayoutManager(view.context, 2) recyclerView.layoutManager = layoutManager val adapt = AdaptRecyclerView.init(recyclerView) val adapter = adapt.adapter() layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { private val controlViewType = Item.Key .just(ControlItem::class.java) .viewType() override fun getSpanSize(position: Int): Int { if (controlViewType == adapter.getItemViewType(position)) { return 2 } return 1 } } initSampleItems(adapt) } }
0
Kotlin
2
4
7a440d50e6dd2ba327851d8ccee369eab1a842f8
1,548
Adapt
Apache License 2.0
app/src/main/java/com/nickming/kotlinlearning/util/DataBindingAdapterUtil.kt
nickming
94,009,580
false
null
package com.nickming.kotlinlearning.util import android.databinding.BindingAdapter import android.widget.ImageView import com.bumptech.glide.Glide /** * class description here * @author nickming * @version 1.0.0 * @since 2017-06-13 上午8:33 * Copyright (c) 2017 nickming All right reserved. */ @BindingAdapter("load_image") fun loadImage(imageView: ImageView, url: String) { Glide.with(imageView.context).load(url).crossFade().into(imageView) } @BindingAdapter("load_asset") fun loadAsset(imageView: ImageView, id: Int) { Glide.with(imageView.context).load(id).crossFade().into(imageView) }
0
Kotlin
0
4
c5cbac38ebebd6e67094314346d515b567a90c45
605
KotlinWeather
MIT License
graph/graph-application/src/main/kotlin/eu/tib/orkg/prototype/statements/api/class-hierarchy-queries.kt
TIBHannover
197,416,205
false
{"Kotlin": 2439902, "Cypher": 212135, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package eu.tib.orkg.prototype.statements.api import eu.tib.orkg.prototype.statements.domain.model.Class import eu.tib.orkg.prototype.statements.domain.model.ThingId import java.util.* import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable interface RetrieveClassHierarchyUseCase { fun findChildren(id: ThingId, pageable: Pageable): Page<ChildClass> fun findParent(id: ThingId): Optional<Class> fun findRoot(id: ThingId): Optional<Class> fun findAllRoots(pageable: Pageable): Page<Class> fun findClassHierarchy(id: ThingId, pageable: Pageable): Page<ClassHierarchyEntry> fun countClassInstances(id: ThingId): Long data class ChildClass( val `class`: Class, val childCount: Long ) data class ClassHierarchyEntry( val `class`: Class, val parentId: ThingId? ) }
0
Kotlin
2
5
8739ce33adc28e780a0c98771cd0c91b63dc922a
876
orkg-backend
MIT License
joiner-kotlin-reactive/src/test/java/cz/encircled/joiner/kotlin/reactive/WithInMemMySql.kt
encircled
49,412,209
false
null
package cz.encircled.joiner.kotlin.reactive import ch.vorburger.mariadb4j.DB import cz.encircled.joiner.TestWithLogging import cz.encircled.joiner.kotlin.JoinerKtQueryBuilder.all import cz.encircled.joiner.model.QUser import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.TestInfo import org.slf4j.LoggerFactory import javax.persistence.EntityManagerFactory import javax.persistence.Persistence import kotlin.test.BeforeTest open class WithInMemMySql : TestWithLogging() { lateinit var joiner: KtReactiveJoiner companion object { @JvmStatic private var db: DB? = null @JvmStatic private var emf: EntityManagerFactory? = null @JvmStatic @BeforeAll fun before() { if (db == null) { LoggerFactory.getLogger(this::class.java).info("Starting DB on 3306 port") db = DB.newEmbeddedDB(3306) db!!.start() } emf = Persistence.createEntityManagerFactory("reactiveTest") } @JvmStatic @AfterAll fun after() { try { emf?.close() db?.stop() } catch (e: Exception) { e.printStackTrace() } db = null emf = null } } @BeforeTest override fun beforeEach(testInfo: TestInfo) { super.beforeEach(testInfo) if (!this::joiner.isInitialized) { joiner = KtReactiveJoiner(emf!!) } runBlocking { joiner.find(QUser.user1.all()).forEach { joiner.remove(it) } } } }
1
Java
0
16
6dfb3bcb551db59bb979c7b0614952c75741d059
1,711
Joiner
Apache License 2.0
app/src/test/java/de/anew/models/time/WeeklyIntervalTest.kt
MarcelBruse
250,358,185
false
null
/* * Copyright 2020 Marcel Bruse * * 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 de.anew.models.time import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.threeten.bp.Clock import org.threeten.bp.ZonedDateTime class WeeklyIntervalTest { @Test fun clockIsInitialized() { val systemClock = Clock.systemUTC() val weekly = Weekly(systemClock) assertThat(systemClock).isNotNull assertThat(weekly.clock()).isEqualTo(systemClock) } @Test fun startOfIntervalIsMonday() { val representativeOfInterval = ZonedDateTime.parse("2019-11-16T10:34:24+01:00[Europe/Berlin]") val monday = ZonedDateTime.parse("2019-11-11T00:00:00+01:00[Europe/Berlin]") val week = Weekly().intervalIncluding(representativeOfInterval) assertThat(week.startsAt()).isEqualTo(monday) } @Test fun startOfNextIntervalIsStartOfNextWeek() { val representativeOfInterval = ZonedDateTime.parse("2020-01-25T21:40:01.614+01:00[Europe/Berlin]") val expectedStartOfNextInterval = ZonedDateTime.parse("2020-01-27T00:00:00+01:00[Europe/Berlin]") val nextWeek = Weekly().intervalIncluding(representativeOfInterval).next() assertThat(nextWeek.startsAt()).isEqualTo(expectedStartOfNextInterval) } @Test fun endOfWeekEqualsStartsOfNextWeek() { val representativeOfInterval = ZonedDateTime.parse("2019-11-15T19:00:00+01:00[Europe/Berlin]") val week = Weekly().intervalIncluding(representativeOfInterval) val nextMonday = ZonedDateTime.parse("2019-11-18T00:00:00+01:00[Europe/Berlin]") assertThat(week.endsBefore()).isEqualTo(nextMonday) assertThat(week.endsBefore()).isEqualTo(week.next().startsAt()) } }
1
null
1
1
7dd2692c8a28f798e843e721d2bd76acb45af774
2,291
Anew
Apache License 2.0
app/src/main/java/com/benrostudios/educatio/ui/home/classrooms/ClassroomsViewModel.kt
DarthBenro008
302,618,804
false
null
package com.benrostudios.educatio.ui.home.classrooms import androidx.lifecycle.ViewModel class ClassroomsViewModel : ViewModel() { // TODO: Implement the ViewModel }
1
Kotlin
1
0
7394bbf21ebccf73281845cb65876b49ecc42ca7
171
EduIn
MIT License
src/main/java/me/shadowalzazel/mcodyssey/enchantments/ranged/HeavyBallistics.kt
ShadowAlzazel
511,383,377
false
null
package me.shadowalzazel.mcodyssey.enchantments.ranged object HeavyBallistics { } // Shoot Bricks, Slimeballs,
0
Kotlin
0
3
5e85f15a3a4184e110c45200f32d7158a827ec99
112
MinecraftOdyssey
MIT License
data/base/src/commonMain/kotlin/io/edugma/data/base/consts/DiConst.kt
Edugma
474,423,768
false
null
package io.edugma.data.base.consts object DiConst { const val Schedule = "schedule" const val Account = "account" const val OtherClient = "other" }
1
Kotlin
0
2
84c11512268b03c6bc37209242d7af2c7c2ca945
161
app
MIT License
concert-demos-rest-service-webflux/src/main/kotlin/org/jesperancinha/concerts/webflux/repos/ConcertListingRepository.kt
jesperancinha
232,411,155
false
{"Markdown": 15, "YAML": 11, "Shell": 9, "Maven POM": 4, "Text": 9, "Ignore List": 2, "Makefile": 3, "Dotenv": 1, "Dockerfile": 3, "SQL": 2, "Kotlin": 93, "INI": 8, "JSON with Comments": 4, "JSON": 6, "Browserslist": 1, "JavaScript": 2, "EditorConfig": 1, "HTML": 2, "Stylus": 2, "Java": 1, "XML": 1}
package org.jesperancinha.concerts.webflux.repos import org.jesperancinha.concerts.webflux.model.ConcertListing import org.springframework.data.r2dbc.repository.Query import org.springframework.data.repository.reactive.ReactiveCrudRepository import org.springframework.stereotype.Repository import reactor.core.publisher.Flux @Repository interface ConcertListingRepository : ReactiveCrudRepository<ConcertListing, Long> { @Query("SELECT * FROM Concert_Listing WHERE concert_id = :concertId") fun findByConcertId(concertId: Long): Flux<ConcertListing> }
1
Kotlin
2
8
966bf4056f2a4d23c3cebe81a29bf4a04ab9f6db
564
concert-demos-root
Apache License 2.0
app/src/main/java/org/ak80/taskbuddy/core/model/Mission.kt
ak80
158,447,057
false
null
package org.ak80.taskbuddy.core.model /** * A Mission is a collection of Tasks */ data class Mission(val title: String, val tasks: List<Task>)
1
Kotlin
0
0
4fe32bc0915e2a8831765f54cb3127c6f89d2db0
145
taskbuddy
Apache License 2.0
app/src/main/java/ca/llamabagel/transpo/home/ui/MainViewModel.kt
Llamabagel
175,222,878
false
{"Kotlin": 191040}
/* * Copyright (c) 2019 <NAME>. Subject to the MIT license. */ package ca.llamabagel.transpo.home.ui import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.work.WorkManager import androidx.work.WorkInfo import androidx.work.Constraints import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import ca.llamabagel.transpo.transit.data.DataRepository import ca.llamabagel.transpo.transit.workers.DataWorker import ca.llamabagel.transpo.transit.workers.RemoteMetadataWorker class MainViewModel(private val dataRepository: DataRepository) : ViewModel() { private val workManager: WorkManager by lazy { WorkManager.getInstance() } val workInfo: LiveData<List<WorkInfo>> init { workInfo = workManager.getWorkInfosByTagLiveData(TAG_OUTPUT) } fun checkAndApplyDataUpdates() { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresStorageNotLow(true) .build() val checkRequest = OneTimeWorkRequestBuilder<RemoteMetadataWorker>() .setConstraints(constraints) .build() val updateRequest = OneTimeWorkRequestBuilder<DataWorker>() .setConstraints(constraints) .addTag(TAG_OUTPUT) .build() workManager.beginWith(checkRequest) .then(updateRequest) .enqueue() } companion object { const val TAG_OUTPUT = "data_worker_output" } }
10
Kotlin
2
1
70ca00367b6cb93a8c1bd19f1a6524e093b65484
1,524
transpo-android
MIT License
tools/src/main/kotlin/pw/binom/material/compiler/OperationExpressionDesc.kt
caffeine-mgn
223,796,620
false
null
package pw.binom.material.compiler import pw.binom.material.SourcePoint import pw.binom.material.lex.OperationExpression class OperationExpressionDesc(val left: ExpressionDesc, val right: ExpressionDesc, val operator: OperationExpression.Operator, source: SourcePoint) : ExpressionDesc(source) { override val resultType: TypeDesc get() = left.resultType override val childs: Sequence<SourceElement> get() = sequenceOf(left, right) }
6
Kotlin
0
4
e673acfcb20e2d62d8e68c43d395731bd9d9d882
459
mogot
Apache License 2.0
immersionbar-diy/src/main/java/com/seiko/immersionbar/annotation/BarHide.kt
qdsfdhvh
273,822,575
true
{"Kotlin": 79797}
package com.seiko.immersionbar.annotation import androidx.annotation.IntDef /** * bar的状态 */ @IntDef( BarHide.FLAG_HIDE_STATUS_BAR, BarHide.FLAG_HIDE_NAVIGATION_BAR, BarHide.FLAG_HIDE_BAR, BarHide.FLAG_SHOW_BAR ) @Retention(AnnotationRetention.SOURCE) annotation class BarHide { companion object { // 隐藏状态栏 const val FLAG_HIDE_STATUS_BAR = 0 // 隐藏导航栏 const val FLAG_HIDE_NAVIGATION_BAR = 1 // 隐藏状态栏和导航栏 const val FLAG_HIDE_BAR = 2 // 显示状态栏和导航栏 const val FLAG_SHOW_BAR = 3 } }
0
Kotlin
0
1
70e0969f96eae5cbf665e8edd38a32c63d3172c5
566
immersionbar
Apache License 2.0