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
libs/messaging/messaging-impl/src/main/kotlin/net/corda/messaging/mediator/StateManagerHelper.kt
corda
346,070,752
false
{"Kotlin": 18977647, "Java": 318968, "Smarty": 101152, "Shell": 48766, "Groovy": 30256, "PowerShell": 6350, "TypeScript": 5826, "Solidity": 2024}
package net.corda.messaging.mediator import net.corda.avro.serialization.CordaAvroDeserializer import net.corda.avro.serialization.CordaAvroSerializer import net.corda.libs.statemanager.api.Metadata import net.corda.libs.statemanager.api.State import net.corda.libs.statemanager.api.StateManager import net.corda.libs.statemanager.api.metadata import net.corda.messaging.api.constants.MessagingMetadataKeys.PROCESSING_FAILURE import net.corda.messaging.api.processor.StateAndEventProcessor /** * Helper for working with [StateManager], used by [MultiSourceEventMediatorImpl]. */ class StateManagerHelper<S : Any>( private val stateSerializer: CordaAvroSerializer<S>, private val stateDeserializer: CordaAvroDeserializer<S>, ) { /** * Creates an updated [State] or a new one if there was no previous version. * * @param key Event's key. * @param persistedState State being updated. * @param newState Updated state. */ fun createOrUpdateState( key: String, persistedState: State?, newState: StateAndEventProcessor.State<S>?, ) = serialize(newState?.value)?.let { serializedValue -> State( key, serializedValue, persistedState?.version ?: State.VERSION_INITIAL_VALUE, mergeMetadata(persistedState?.metadata, newState?.metadata), ) } fun failStateProcessing(key: String, originalState: State?) : State { val newMetadata = (originalState?.metadata?.toMutableMap() ?: mutableMapOf()).also { it[PROCESSING_FAILURE] = true } return State( key, byteArrayOf(), version = originalState?.version ?: State.VERSION_INITIAL_VALUE, metadata = Metadata(newMetadata) ) } private fun mergeMetadata(existing: Metadata?, newMetadata: Metadata?): Metadata { val map = (existing ?: metadata()).toMutableMap() newMetadata?.forEach { map[it.key] = it.value } return Metadata(map) } /** * Serializes state value. * * @param value State value. * @return Serialized state value. */ private fun serialize(value: S?) = value?.let { stateSerializer.serialize(it) } /** * Deserializes state value. * * @param state State. * @return Deserialized state value. */ fun deserializeValue(state: State?) = state?.value?.let { stateDeserializer.deserialize(it) } }
91
Kotlin
21
49
24c83ecfff4ae28b898ceca8e8cb469e300a0cc5
2,509
corda-runtime-os
Apache License 2.0
src/test/kotlin/r2dbcfun/test/AutoTest.kt
dkindler
351,886,663
false
null
package r2dbcfun.test import failfast.FailFast.autoTest fun main() { autoTest() }
0
null
0
0
e35b459f245806125ea5820fbb31ced6e183e209
88
r2dbcfun
MIT License
bitcoinkit/src/test/kotlin/io/horizontalsystems/bitcoinkit/network/MainNetTest.kt
diop
180,641,789
true
{"Kotlin": 544801, "Java": 48890}
package io.horizontalsystems.bitcoinkit.network import io.horizontalsystems.bitcoinkit.io.BitcoinInput import io.horizontalsystems.bitcoinkit.models.Block import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) @PrepareForTest(MainNet::class) class MainNetTest { private val block1 = mock(Block::class.java) private val block2 = mock(Block::class.java) private lateinit var network: MainNet @Before fun setup() { network = MainNet() } @Test fun packetMagic() { val stream = BitcoinInput(byteArrayOf( 0xf9.toByte(), 0xbe.toByte(), 0xb4.toByte(), 0xd9.toByte() )) val magic = stream.readUnsignedInt() assertEquals(magic, network.magic) } }
0
Kotlin
0
0
fb11666b177815e0210c4d6072f201101151acdc
1,028
bitcoin-kit-android
MIT License
src/commonMain/kotlin/data/items/ApostleOfArgus.kt
marisa-ashkandi
332,658,265
false
null
package `data`.items import `data`.Constants import `data`.buffs.Buffs import `data`.model.Item import `data`.model.ItemSet import `data`.model.Socket import `data`.model.SocketBonus import character.Buff import character.Stats import kotlin.Array import kotlin.Boolean import kotlin.Double import kotlin.Int import kotlin.String import kotlin.collections.List import kotlin.js.JsExport @JsExport public class ApostleOfArgus : Item() { public override var isAutoGenerated: Boolean = true public override var id: Int = 30908 public override var name: String = "Apostle of Argus" public override var itemLevel: Int = 151 public override var quality: Int = 4 public override var icon: String = "inv_staff_54.jpg" public override var inventorySlot: Int = 17 public override var itemSet: ItemSet? = null public override var itemClass: Constants.ItemClass? = Constants.ItemClass.WEAPON public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.STAFF public override var allowableClasses: Array<Constants.AllowableClass>? = null public override var minDmg: Double = 145.63999938964844 public override var maxDmg: Double = 322.6400146484375 public override var speed: Double = 3200.0 public override var stats: Stats = Stats( stamina = 62, intellect = 59 ) public override var sockets: Array<Socket> = arrayOf() public override var socketBonus: SocketBonus? = null public override val buffs: List<Buff> by lazy { listOfNotNull( Buffs.byIdOrName(42059, "Increase Healing 486", this), Buffs.byIdOrName(42060, "Increased Mana Regen", this) )} }
21
null
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
1,665
tbcsim
MIT License
dlang/psi-api/src/main/kotlin/io/github/intellij/dlanguage/psi/DResolveResult.kt
intellij-dlanguage
27,922,930
false
{"D": 1787183, "Kotlin": 1068238, "Java": 834373, "Lex": 22913, "DTrace": 3220, "HTML": 1386, "Makefile": 457}
package io.github.intellij.dlanguage.psi import com.intellij.psi.PsiElement import com.intellij.psi.ResolveResult class DResolveResult(private val element: PsiElement) : ResolveResult { override fun getElement(): PsiElement = element override fun isValidResult(): Boolean = true }
160
D
51
328
298d1db45d2b35c1715a1b1b2e1c548709101f05
292
intellij-dlanguage
MIT License
src/main/kotlin/com/example/streamersk/StreamWindowItemCount.kt
samaitra
226,595,697
false
null
package com.example.streamersk import org.apache.commons.lang3.StringUtils.isNotBlank import org.apache.flink.api.common.serialization.SimpleStringSchema import org.apache.flink.configuration.Configuration import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment import org.apache.flink.streaming.api.windowing.time.Time import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010 import org.apache.ignite.sink.flink.IgniteSink import java.io.FileInputStream import java.io.FileNotFoundException import java.io.InputStream import java.util.Properties fun main(args: Array<String>) { //load configurations val appProperties = Properties() appProperties.load(config(args[0])) //start IgniteSink instance val igniteSink = sink(appProperties) // get the execution environment val env = StreamExecutionEnvironment.getExecutionEnvironment() // get input data by connecting to kafka val text = env.addSource(FlinkKafkaConsumer010<String>( appProperties.getProperty("topic"), SimpleStringSchema(), appProperties)) // parse the data, group it, window it, and aggregate the counts val windowCounts = text .flatMap(Splitter()) .keyBy(0) .timeWindow(Time.seconds(10)) .sum(1) .map(Formatter()) windowCounts.addSink(igniteSink) env.execute("Stream Window Item Count") } private fun sink(appProperties: Properties): IgniteSink<Map<String, Int>> { //start IgniteSink instance val igniteSink = IgniteSink<Map<String, Int>>(appProperties.getProperty("ignite.cache"), appProperties.getProperty("ignite.config")) igniteSink.setAllowOverwrite(true) igniteSink.setAutoFlushFrequency(5L) val p = Configuration() igniteSink.open(p) return igniteSink } private fun config(configPath: String): InputStream { if (isNotBlank(configPath)) { return FileInputStream(configPath) } else throw FileNotFoundException() }
0
Kotlin
2
2
acadb72c15c69b1d382d5e12116ae4353bac533a
2,016
streamersk
Apache License 2.0
app/src/main/java/io/flaterlab/kyrgyzdaamy/service/response/AccessToken.kt
chorobaev
355,274,946
false
{"Kotlin": 168085}
package io.flaterlab.kyrgyzdaamy.service.response data class AccessToken( val accessToken : String, val userName : String, val roles : List<String> )
0
Kotlin
0
1
a1c17e42cefdf0536f4e1b9c235e0f434b9a1e58
162
kyrgyz-daamy
MIT License
CSP-Library/src/main/java/com/mbp/csp/sw1020sp.kt
mbpatel6245
534,200,692
false
{"Kotlin": 109510}
package com.mbp.csp import androidx.compose.ui.unit.sp val sw1020sp = ComposableDimens().apply { _1csp = 3.40.sp _2csp = 6.80.sp _3csp = 10.20.sp _4csp = 13.60.sp _5csp = 17.00.sp _6csp = 20.40.sp _7csp = 23.80.sp _8csp = 27.20.sp _9csp = 30.60.sp _10csp = 34.00.sp _11csp = 37.40.sp _12csp = 40.80.sp _13csp = 44.20.sp _14csp = 47.60.sp _15csp = 51.00.sp _16csp = 54.40.sp _17csp = 57.80.sp _18csp = 61.20.sp _19csp = 64.60.sp _20csp = 68.00.sp _21csp = 71.40.sp _22csp = 74.80.sp _23csp = 78.20.sp _24csp = 81.60.sp _25csp = 85.00.sp _26csp = 88.40.sp _27csp = 91.80.sp _28csp = 95.20.sp _29csp = 98.60.sp _30csp = 102.00.sp _31csp = 105.40.sp _32csp = 108.80.sp _33csp = 112.20.sp _34csp = 115.60.sp _35csp = 119.00.sp _36csp = 122.40.sp _37csp = 125.80.sp _38csp = 129.20.sp _39csp = 132.60.sp _40csp = 136.00.sp _41csp = 139.40.sp _42csp = 142.80.sp _43csp = 146.20.sp _44csp = 149.60.sp _45csp = 153.00.sp _46csp = 156.40.sp _47csp = 159.80.sp _48csp = 163.20.sp _49csp = 166.60.sp _50csp = 170.00.sp _51csp = 173.40.sp _52csp = 176.80.sp _53csp = 180.20.sp _54csp = 183.60.sp _55csp = 187.00.sp _56csp = 190.40.sp _57csp = 193.80.sp _58csp = 197.20.sp _59csp = 200.60.sp _60csp = 204.00.sp _61csp = 207.40.sp _62csp = 210.80.sp _63csp = 214.20.sp _64csp = 217.60.sp _65csp = 221.00.sp _66csp = 224.40.sp _67csp = 227.80.sp _68csp = 231.20.sp _69csp = 234.60.sp _70csp = 238.00.sp _71csp = 241.40.sp _72csp = 244.80.sp _73csp = 248.20.sp _74csp = 251.60.sp _75csp = 255.00.sp _76csp = 258.40.sp _77csp = 261.80.sp _78csp = 265.20.sp _79csp = 268.60.sp _80csp = 272.00.sp _81csp = 275.40.sp _82csp = 278.80.sp _83csp = 282.20.sp _84csp = 285.60.sp _85csp = 289.00.sp _86csp = 292.40.sp _87csp = 295.80.sp _88csp = 299.20.sp _89csp = 302.60.sp _90csp = 306.00.sp _91csp = 309.40.sp _92csp = 312.80.sp _93csp = 316.20.sp _94csp = 319.60.sp _95csp = 323.00.sp _96csp = 326.40.sp _97csp = 329.80.sp _98csp = 333.20.sp _99csp = 336.60.sp _100csp = 340.00.sp _101csp = 343.40.sp _102csp = 346.80.sp _103csp = 350.20.sp _104csp = 353.60.sp _105csp = 357.00.sp _106csp = 360.40.sp _107csp = 363.80.sp _108csp = 367.20.sp _109csp = 370.60.sp _110csp = 374.00.sp _111csp = 377.40.sp _112csp = 380.80.sp _113csp = 384.20.sp _114csp = 387.60.sp _115csp = 391.00.sp _116csp = 394.40.sp _117csp = 397.80.sp _118csp = 401.20.sp _119csp = 404.60.sp _120csp = 408.00.sp _121csp = 411.40.sp _122csp = 414.80.sp _123csp = 418.20.sp _124csp = 421.60.sp _125csp = 425.00.sp _126csp = 428.40.sp _127csp = 431.80.sp _128csp = 435.20.sp _129csp = 438.60.sp _130csp = 442.00.sp _131csp = 445.40.sp _132csp = 448.80.sp _133csp = 452.20.sp _134csp = 455.60.sp _135csp = 459.00.sp _136csp = 462.40.sp _137csp = 465.80.sp _138csp = 469.20.sp _139csp = 472.60.sp _140csp = 476.00.sp _141csp = 479.40.sp _142csp = 482.80.sp _143csp = 486.20.sp _144csp = 489.60.sp _145csp = 493.00.sp _146csp = 496.40.sp _147csp = 499.80.sp _148csp = 503.20.sp _149csp = 506.60.sp _150csp = 510.00.sp }
0
Kotlin
0
4
58a6b1134c4fcf5a53d41c0acffe0430640e5676
3,561
csp
MIT License
CSP-Library/src/main/java/com/mbp/csp/sw1020sp.kt
mbpatel6245
534,200,692
false
{"Kotlin": 109510}
package com.mbp.csp import androidx.compose.ui.unit.sp val sw1020sp = ComposableDimens().apply { _1csp = 3.40.sp _2csp = 6.80.sp _3csp = 10.20.sp _4csp = 13.60.sp _5csp = 17.00.sp _6csp = 20.40.sp _7csp = 23.80.sp _8csp = 27.20.sp _9csp = 30.60.sp _10csp = 34.00.sp _11csp = 37.40.sp _12csp = 40.80.sp _13csp = 44.20.sp _14csp = 47.60.sp _15csp = 51.00.sp _16csp = 54.40.sp _17csp = 57.80.sp _18csp = 61.20.sp _19csp = 64.60.sp _20csp = 68.00.sp _21csp = 71.40.sp _22csp = 74.80.sp _23csp = 78.20.sp _24csp = 81.60.sp _25csp = 85.00.sp _26csp = 88.40.sp _27csp = 91.80.sp _28csp = 95.20.sp _29csp = 98.60.sp _30csp = 102.00.sp _31csp = 105.40.sp _32csp = 108.80.sp _33csp = 112.20.sp _34csp = 115.60.sp _35csp = 119.00.sp _36csp = 122.40.sp _37csp = 125.80.sp _38csp = 129.20.sp _39csp = 132.60.sp _40csp = 136.00.sp _41csp = 139.40.sp _42csp = 142.80.sp _43csp = 146.20.sp _44csp = 149.60.sp _45csp = 153.00.sp _46csp = 156.40.sp _47csp = 159.80.sp _48csp = 163.20.sp _49csp = 166.60.sp _50csp = 170.00.sp _51csp = 173.40.sp _52csp = 176.80.sp _53csp = 180.20.sp _54csp = 183.60.sp _55csp = 187.00.sp _56csp = 190.40.sp _57csp = 193.80.sp _58csp = 197.20.sp _59csp = 200.60.sp _60csp = 204.00.sp _61csp = 207.40.sp _62csp = 210.80.sp _63csp = 214.20.sp _64csp = 217.60.sp _65csp = 221.00.sp _66csp = 224.40.sp _67csp = 227.80.sp _68csp = 231.20.sp _69csp = 234.60.sp _70csp = 238.00.sp _71csp = 241.40.sp _72csp = 244.80.sp _73csp = 248.20.sp _74csp = 251.60.sp _75csp = 255.00.sp _76csp = 258.40.sp _77csp = 261.80.sp _78csp = 265.20.sp _79csp = 268.60.sp _80csp = 272.00.sp _81csp = 275.40.sp _82csp = 278.80.sp _83csp = 282.20.sp _84csp = 285.60.sp _85csp = 289.00.sp _86csp = 292.40.sp _87csp = 295.80.sp _88csp = 299.20.sp _89csp = 302.60.sp _90csp = 306.00.sp _91csp = 309.40.sp _92csp = 312.80.sp _93csp = 316.20.sp _94csp = 319.60.sp _95csp = 323.00.sp _96csp = 326.40.sp _97csp = 329.80.sp _98csp = 333.20.sp _99csp = 336.60.sp _100csp = 340.00.sp _101csp = 343.40.sp _102csp = 346.80.sp _103csp = 350.20.sp _104csp = 353.60.sp _105csp = 357.00.sp _106csp = 360.40.sp _107csp = 363.80.sp _108csp = 367.20.sp _109csp = 370.60.sp _110csp = 374.00.sp _111csp = 377.40.sp _112csp = 380.80.sp _113csp = 384.20.sp _114csp = 387.60.sp _115csp = 391.00.sp _116csp = 394.40.sp _117csp = 397.80.sp _118csp = 401.20.sp _119csp = 404.60.sp _120csp = 408.00.sp _121csp = 411.40.sp _122csp = 414.80.sp _123csp = 418.20.sp _124csp = 421.60.sp _125csp = 425.00.sp _126csp = 428.40.sp _127csp = 431.80.sp _128csp = 435.20.sp _129csp = 438.60.sp _130csp = 442.00.sp _131csp = 445.40.sp _132csp = 448.80.sp _133csp = 452.20.sp _134csp = 455.60.sp _135csp = 459.00.sp _136csp = 462.40.sp _137csp = 465.80.sp _138csp = 469.20.sp _139csp = 472.60.sp _140csp = 476.00.sp _141csp = 479.40.sp _142csp = 482.80.sp _143csp = 486.20.sp _144csp = 489.60.sp _145csp = 493.00.sp _146csp = 496.40.sp _147csp = 499.80.sp _148csp = 503.20.sp _149csp = 506.60.sp _150csp = 510.00.sp }
0
Kotlin
0
4
58a6b1134c4fcf5a53d41c0acffe0430640e5676
3,561
csp
MIT License
ide-common/src/main/kotlin/org/digma/intellij/plugin/env/EnvironmentsSupplier.kt
digma-ai
472,408,329
false
{"Kotlin": 1357472, "Java": 547090, "C#": 115880, "HTML": 16050, "FreeMarker": 13789, "Shell": 6494}
package org.digma.intellij.plugin.env interface EnvironmentsSupplier { fun getEnvironments(): List<Env> fun getEnvironmentsNames(): List<String> fun setCurrent(selectedItem: String?) /** * a variant of setCurrent that notifies all listeners not to update the insights view. and will run a task right * after the environment was changed so that this task will see the new environment, the task should run even if the * environment didn't change, so this task must run if its not null */ fun setCurrent(selectedItem: String, taskToRunAfterChange: Runnable?) fun getCurrent(): Env? fun refreshNowOnBackground() fun setCurrent(env: Env) fun getLatestKnownEnv(): String }
430
Kotlin
7
22
8995a81e2ede5d60ec5979319a876a1a9026b922
731
digma-intellij-plugin
MIT License
libs/membership/membership-datamodel/src/main/kotlin/net/corda/membership/datamodel/ApprovalRulesEntity.kt
corda
346,070,752
false
null
package net.corda.membership.datamodel import net.corda.db.schema.DbSchema import java.io.Serializable import java.util.Objects import javax.persistence.Column import javax.persistence.Embeddable import javax.persistence.Entity import javax.persistence.Id import javax.persistence.IdClass import javax.persistence.Table /** * An entity representing approval rules applied to registration requests for determining the approval method (manual * or automatic). */ @Entity @Table(name = DbSchema.VNODE_GROUP_APPROVAL_RULES) @IdClass(ApprovalRulesEntityPrimaryKey::class) class ApprovalRulesEntity( @Id @Column(name = "rule_id", nullable = false, updatable = false) var ruleId: String, @Id @Column(name = "rule_type", nullable = false, updatable = false) var ruleType: String, @Column(name = "rule_regex", nullable = false, updatable = false) var ruleRegex: String, @Column(name = "rule_label", nullable = true, updatable = false) var ruleLabel: String? = null ) { override fun equals(other: Any?): Boolean { if (other === this) return true if (other == null) return false if (other !is ApprovalRulesEntity) return false return other.ruleId == this.ruleId && other.ruleType == this.ruleType } override fun hashCode(): Int { return Objects.hash(ruleId, ruleType) } } @Embeddable data class ApprovalRulesEntityPrimaryKey( var ruleId: String, var ruleType: String ) : Serializable
96
null
27
69
d478e119ab288af663910f9a2df42a7a7b9f5bce
1,503
corda-runtime-os
Apache License 2.0
app/src/main/java/com/motionapps/sensorbox/fragments/advanced/extrahandlers/AlarmHandler.kt
Foxpace
297,182,599
false
null
package com.motionapps.sensorbox.fragments.advanced.extrahandlers import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.Window import android.widget.* import androidx.fragment.app.Fragment import com.motionapps.sensorbox.R import com.motionapps.sensorbox.fragments.advanced.ExtraFragmentArgs import com.motionapps.sensorservices.services.MeasurementService.Companion.ENDLESS import com.motionapps.sensorservices.services.MeasurementService.Companion.LONG import com.motionapps.sensorservices.services.MeasurementService.Companion.SHORT import com.shawnlin.numberpicker.NumberPicker import dagger.hilt.android.scopes.ViewModelScoped import es.dmoral.toasty.Toasty import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.InternalCoroutinesApi import java.util.concurrent.TimeUnit import javax.inject.Inject @ExperimentalCoroutinesApi @InternalCoroutinesApi @ViewModelScoped /** * Handles custom alarms during measurement * Handles not only time points, but also UI - dialogs * Customised for LONG and SHORT measurements */ class AlarmHandler @Inject constructor() { val alarmsList: ArrayList<Int> = ArrayList() // stores alarms /** * Called by activity, when is restarted * Inflates all the views into linearLayout * @param linearLayout - layout to inflate views * @param layoutInflater - inflater to use * @param args - args from ExtraFragment, could be replaced by type integer */ fun refreshLayout(linearLayout: LinearLayout, layoutInflater: LayoutInflater, args: ExtraFragmentArgs){ for(i in alarmsList) if (args.typeMeasurement == SHORT) { createAlarmShort(linearLayout, layoutInflater, i, false) }else{ val hours = TimeUnit.SECONDS.toHours(i.toLong()).toInt() val minutes = TimeUnit.SECONDS.toMinutes((i - hours*3600).toLong()).toInt() createAlarmLong(linearLayout, layoutInflater, hours, minutes, false) } } /** * Views are customised for seconds * * @param linearLayout - layout to inflate views * @param layoutInflater - inflater to use * @param value - seconds to show * @param addToList - true if the stamp is added recently, false for the refreshing */ private fun createAlarmShort(linearLayout: LinearLayout, layoutInflater: LayoutInflater, value: Int, addToList: Boolean) { // inflation val view: View = layoutInflater.inflate(R.layout.item_layout_annotation, linearLayout, false) // data insertion (view.findViewById<TextView>(R.id.annot_row_text)).also { it.text = linearLayout.context.getString(R.string.extra_seconds, value) } (view.findViewById<ImageButton>(R.id.annot_row_button)).also { it.setOnClickListener { removeNote(linearLayout, view, value) } } // to add stamp into list if(addToList){ alarmsList.add(value) } linearLayout.addView(view) } /** * Removes timestamp from list and linearLayout * * @param linearLayout - linearLayout from which the view is removed * @param view - view to remove * @param value - value in seconds to remove */ private fun removeNote(linearLayout: LinearLayout, view: View, value: Int) { linearLayout.removeView(view) alarmsList.remove(value) } /** * Views are customised for seconds * * @param linearLayout - linearLayout to add views * @param layoutInflater - to inflate * @param hours - integer * @param mins - integer * @param addToList - true if the stamp is added recently, false for the refreshing */ private fun createAlarmLong(linearLayout: LinearLayout, layoutInflater: LayoutInflater, hours: Int, mins: Int, addToList: Boolean) { val view: View = layoutInflater.inflate(R.layout.item_layout_annotation, linearLayout, false) val value = 3600 * hours + 60 * mins // recalculated to seconds (view.findViewById<TextView>(R.id.annot_row_text)).also { it.text = linearLayout.context.getString(R.string.extra_hours_mins, hours, mins) } (view.findViewById<ImageButton>(R.id.annot_row_button)).also { it.setOnClickListener { removeNote(linearLayout, view, value) } } if(addToList){ alarmsList.add(value) } linearLayout.addView(view) } /** * @return ArrayList of alarms in seconds */ fun getAlarms(): ArrayList<Int> { if(alarmsList.isEmpty()){ return arrayListOf(-1) } return alarmsList } /** * Dialog to handle insertion of the alarm - called by some button * * @property fragment - fragment upon which the dialog is shown * @property alarmHandler - alarmHandler of the fragment to store values * @property type - Value from ExtraFragment */ class CustomDialog( val fragment: Fragment, private val alarmHandler: AlarmHandler, val type: ExtraFragmentArgs ) : Dialog(fragment.requireContext()) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) window?.setBackgroundDrawableResource(android.R.color.transparent) // picked by type if (type.typeMeasurement == SHORT) { setContentView(R.layout.template_picker) // only for seconds createDialogShort(context, type) } else { setContentView(R.layout.template_double_picker) // hours and minutes createDialogLong(context, type) } } private fun createDialogShort(context: Context, args: ExtraFragmentArgs) { // set restrictions for number picker val numberPicker: NumberPicker = findViewById(R.id.number_picker_right) numberPicker.maxValue = args.secondTime numberPicker.minValue = 1 (findViewById<Button>(R.id.extra_adding_button)).also { it.setOnClickListener { // checks if the time is not registered already if (numberPicker.value in alarmHandler.alarmsList) { Toasty.info( context, context.getString(R.string.extra_alarm_registered), Toasty.LENGTH_LONG, true ).show() return@setOnClickListener } // adding to linearlayout and storage val linearLayout = fragment.requireView().findViewById<LinearLayout>(R.id.extra_container_alarms) alarmHandler.createAlarmShort(linearLayout, fragment.layoutInflater, numberPicker.value, true) dismiss() } } } private fun createDialogLong(context: Context, args: ExtraFragmentArgs) { // set restrictions for number picker val leftNumberPicker: NumberPicker = findViewById(R.id.number_picker_left) val rightNumberPicker: NumberPicker = findViewById(R.id.number_picker_right) leftNumberPicker.minValue = 0 rightNumberPicker.minValue = 0 if(args.typeMeasurement == ENDLESS){ leftNumberPicker.maxValue = 100 }else{ leftNumberPicker.maxValue = args.firstTime } rightNumberPicker.maxValue = 60 (findViewById<Button>(R.id.extra_adding_button)).also { it.setOnClickListener { // checks if the time is not registered already if ((leftNumberPicker.value * 3600 + rightNumberPicker.value * 60) in alarmHandler.alarmsList) { Toasty.info( context, context.getString(R.string.extra_alarm_registered), Toasty.LENGTH_LONG, true ).show() return@setOnClickListener // time was not set } else if (leftNumberPicker.value == 0 && rightNumberPicker.value == 0) { Toasty.info( context, context.getString(R.string.advanced_setup_time), Toasty.LENGTH_LONG, true ).show() return@setOnClickListener // time is beyond stated time for measurement } else if((leftNumberPicker.value * 3600 + rightNumberPicker.value * 60) > (args.firstTime*3600 + args.secondTime*60) && args.typeMeasurement == LONG){ Toasty.error( context, context.getString(R.string.advanced_time_pass_limit), Toasty.LENGTH_LONG, true ).show() return@setOnClickListener } val linearLayout = fragment.requireView().findViewById<LinearLayout>(R.id.extra_container_alarms) alarmHandler.createAlarmLong(linearLayout, fragment.layoutInflater, leftNumberPicker.value, rightNumberPicker.value, true) dismiss() } } } } }
4
Kotlin
7
8
8f3adacb38f437ea3d85a886a6f8acbb3e8d2e0e
9,816
SensorBox
Apache License 2.0
src/main/kotlin/extensions/String.kt
FACUA
122,469,261
false
null
package extensions val String.isS3Redirection get(): Boolean = "s3-website-[a-z0-9-]+\\.amazonaws\\.com\\." .toRegex() .matches(this) /** * Hosted zone record sets have a trailing dot, like this: * example.com. * and we want: * example.com */ val String.s3BucketName get(): String = "(.+)\\." .toRegex() .matchEntire(this) ?.groups ?.get(1) ?.value ?: this /** * Gets the root domain from a string representing a subdomain, like this: * foo.bar.example.com --> example.com * * The string itself might also be the root domain itself: * example.com --> example.con */ val String.rootDomain get(): String = "([a-z0-9|-]+\\.)*([a-z0-9|-]+\\.[a-z]+)" .toRegex() .matchEntire(this) ?.groups ?.get(2) ?.value ?: this
1
Kotlin
0
3
ceec58a8cd8301224ae1cf917c9a0831572c1624
738
aws-redirect-manager
MIT License
android/library-magiccube/src/main/java/com/hellobike/magiccube/v2/StyleModelCache.kt
hellof2e
651,011,094
false
{"Kotlin": 499995, "Objective-C": 421129, "JavaScript": 39299, "Java": 29943, "Swift": 24514, "Ruby": 5345, "TypeScript": 3969, "Shell": 255}
package com.hellobike.magiccube.v2 import android.util.LruCache import com.hellobike.magiccube.model.StyleModel import com.hellobike.magiccube.utils.tryCatch internal object StyleModelCache { private val cardStyleModels = LruCache<String, StyleModel>(30) fun hasValidStyleModel(url: String): Boolean = getStyleModelFromCache(url)?.isValidViewModel() ?: false fun getStyleModelFromCache(url: String): StyleModel? { synchronized(cardStyleModels) { try { return cardStyleModels.get(url) } catch (t: Throwable) { t.printStackTrace() } } return null } fun cacheStyleModel(url: String, model: StyleModel) { if (!model.isValidViewModel()) return // 数据不可靠,不保存 tryCatch { synchronized(cardStyleModels) { cardStyleModels.put(url, model) } } } fun removeStyleModel(url: String) { tryCatch { synchronized(cardStyleModels) { cardStyleModels.remove(url) } } } }
3
Kotlin
9
60
8123fdaafa9ee7eaeee43fb73789b7fa3feac697
1,109
Wukong
Apache License 2.0
android/library-magiccube/src/main/java/com/hellobike/magiccube/v2/StyleModelCache.kt
hellof2e
651,011,094
false
{"Kotlin": 499995, "Objective-C": 421129, "JavaScript": 39299, "Java": 29943, "Swift": 24514, "Ruby": 5345, "TypeScript": 3969, "Shell": 255}
package com.hellobike.magiccube.v2 import android.util.LruCache import com.hellobike.magiccube.model.StyleModel import com.hellobike.magiccube.utils.tryCatch internal object StyleModelCache { private val cardStyleModels = LruCache<String, StyleModel>(30) fun hasValidStyleModel(url: String): Boolean = getStyleModelFromCache(url)?.isValidViewModel() ?: false fun getStyleModelFromCache(url: String): StyleModel? { synchronized(cardStyleModels) { try { return cardStyleModels.get(url) } catch (t: Throwable) { t.printStackTrace() } } return null } fun cacheStyleModel(url: String, model: StyleModel) { if (!model.isValidViewModel()) return // 数据不可靠,不保存 tryCatch { synchronized(cardStyleModels) { cardStyleModels.put(url, model) } } } fun removeStyleModel(url: String) { tryCatch { synchronized(cardStyleModels) { cardStyleModels.remove(url) } } } }
3
Kotlin
9
60
8123fdaafa9ee7eaeee43fb73789b7fa3feac697
1,109
Wukong
Apache License 2.0
src/main/java/test/BJTUTest.kt
YZune
232,583,513
false
null
package main.java.test import main.java.parser.BJTUParser import java.io.File //北京交通大学本科 fun main(){ val file = File("C:\\Users\\14223\\Desktop\\北京交通大学教学服务管理平台01.html") val parser = BJTUParser(file.readText()) parser.saveCourse() }
0
null
119
96
2bc26e588f80cb7f9a1715b02309b653ba090454
245
CourseAdapter
MIT License
src/main/java/team/redrock/rain/arathoth/Arathoth.kt
ColdRain-Moro
611,618,522
false
null
package team.redrock.rain.arathoth import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import taboolib.common.env.RuntimeDependencies import taboolib.common.env.RuntimeDependency import taboolib.common.platform.Plugin import taboolib.common.platform.event.SubscribeEvent import taboolib.common.platform.function.info import taboolib.platform.BukkitPlugin import team.redrock.rain.arathoth.core.event.ArathothEvents import team.redrock.rain.arathoth.utils.coroutine.BukkitMain import java.io.File @RuntimeDependencies( RuntimeDependency( value = "!org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2", test = "kotlinx.coroutines.AwaitAll", relocate = ["!kotlin.", "!kotlin@kotlin_version_escape@."] ), ) object Arathoth : Plugin() { val pluginInst = BukkitPlugin.getInstance() val attributesDir = pluginInst.dataFolder.resolve("attributes") val pluginScope = CoroutineScope(Dispatchers.BukkitMain) override fun onEnable() { if (!attributesDir.exists()) { attributesDir.createNewFile() } // 加载所有模块 ArathothEvents.PluginLoad().call() } }
0
Kotlin
0
0
ff6719c57c8f8ce8b48711d8af2a11e7ae858232
1,161
Arathoth-IV
Creative Commons Zero v1.0 Universal
2737.Find the Closest Marked Node.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
import java.util.* internal class Solution { fun minimumDistance(n: Int, edges: List<List<Int?>>, s: Int, marked: IntArray): Int { val inf = 1 shl 29 val g = Array(n) { IntArray(n) } for (e in g) { Arrays.fill(e, inf) } for (e in edges) { val u: Int = e[0] val v: Int = e[1] val w: Int = e[2] g[u][v] = min(g[u][v], w) } val dist = IntArray(n) Arrays.fill(dist, inf) dist[s] = 0 val vis = BooleanArray(n) for (i in 0 until n) { var t = -1 for (j in 0 until n) { if (!vis[j] && (t == -1 || dist[t] > dist[j])) { t = j } } vis[t] = true for (j in 0 until n) { dist[j] = min(dist[j], dist[t] + g[t][j]) } } var ans = inf for (i in marked) { ans = min(ans, dist[i]) } return if (ans >= inf) -1 else ans } }
0
Kotlin
0
0
17a80985d970c8316fb694e4952692e598d700af
878
kotlin-leetcode
MIT License
app/src/main/kotlin/me/liuyun/bjutlgn/ui/UserActivity.kt
yunowo
55,282,179
false
null
package me.liuyun.bjutlgn.ui import android.content.SharedPreferences import android.os.Bundle import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.TextAppearanceSpan import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.appcompat.app.AppCompatActivity import androidx.core.content.edit import androidx.lifecycle.Observer import androidx.preference.PreferenceManager import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import me.liuyun.bjutlgn.App import me.liuyun.bjutlgn.R import me.liuyun.bjutlgn.databinding.ActivityUsersBinding import me.liuyun.bjutlgn.databinding.ItemUserBinding import me.liuyun.bjutlgn.databinding.UserDialogBinding import me.liuyun.bjutlgn.db.UserDao import me.liuyun.bjutlgn.entity.User class UserActivity : AppCompatActivity() { private lateinit var binding: ActivityUsersBinding private lateinit var adapter: UserAdapter private lateinit var userDao: UserDao private lateinit var prefs: SharedPreferences private var currentId: Int = 0 private var currentPackage: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityUsersBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.appBar.toolbar) binding.appBar.toolbar.setNavigationOnClickListener { onBackPressed() } binding.fab.setOnClickListener { openUserDialog(true, User(0, "", "", 0, 0)) } userDao = (application as App).appDatabase.userDao() adapter = UserAdapter() val users = userDao.all() users.observe(this@UserActivity, Observer { it?.let { val diff = DiffUtil.calculateDiff(UsersDiffCallback(adapter.users, it)) adapter.users = it diff.dispatchUpdatesTo(adapter) } }) binding.recycler.adapter = adapter binding.recycler.itemAnimator = DefaultItemAnimator() ItemTouchHelper( object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.START) { override fun onMove(view: RecyclerView, holder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { adapter.onItemMove(holder.adapterPosition, target.adapterPosition) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { adapter.onItemDismiss(viewHolder.adapterPosition) } }).attachToRecyclerView(binding.recycler) prefs = PreferenceManager.getDefaultSharedPreferences(this) currentId = prefs.getInt("current_user", 0) } internal fun openUserDialog(newUser: Boolean, user: User) { val binding = UserDialogBinding.inflate(layoutInflater, null, false) with(binding) { account.setText(user.account) account.setSelection(user.account.length) password.setText(user.password) val items = resources.getStringArray(R.array.packages) val adapter = ArrayAdapter(this@UserActivity, R.layout.item_package, items) spinnerPack.setAdapter(adapter) if (!newUser) { spinnerPack.setText(items[user.pack], false) } spinnerPack.setOnItemClickListener { _, _, position, _ -> currentPackage = position } } with(MaterialAlertDialogBuilder(this)) { setView(binding.root) setPositiveButton(R.string.button_ok) { _, _ -> user.account = binding.account.text.toString() user.password = binding.password.text.toString() if (!newUser) { user.pack = currentPackage userDao.update(user) } else { user.position = userDao.maxPosition()?.let { it.position + 1 } ?: 0 userDao.insert(user) } } setNegativeButton(R.string.button_cancel) { _, _ -> Unit } show() } } internal inner class UserAdapter(var users: MutableList<User> = mutableListOf()) : RecyclerView.Adapter<UserAdapter.UserViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, i: Int) = UserViewHolder(ItemUserBinding.inflate(LayoutInflater.from(parent.context), parent, false)) override fun getItemCount() = users.size override fun onBindViewHolder(holder: UserViewHolder, i: Int) { val user = users[holder.adapterPosition] holder.itemView.setOnClickListener { prefs.edit { putString("account", user.account) putString("password", <PASSWORD>) putInt("current_package", user.pack) putInt("current_user", user.id) } this@UserActivity.finish() } val builder = SpannableStringBuilder() .append(user.account) .append("\n") .append(resources.getStringArray(R.array.packages)[user.pack]) builder.setSpan(TextAppearanceSpan(this@UserActivity, android.R.style.TextAppearance_Small), user.account.length + 1, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) holder.binding.user.text = builder if (user.id == currentId) { holder.binding.user.isChecked = true } holder.binding.buttonEdit.setOnClickListener { openUserDialog(false, user.copy()) } holder.binding.buttonDelete.setOnClickListener { userDao.delete(user) } } fun onItemMove(from: Int, to: Int) { val step = if (from < to) 1 else -1 val first = users[from] var previousPos = first.position var i = from while (if (from < to) i < to else i > to) { val next = users[i + step] val pos = next.position next.position = previousPos previousPos = pos users[i] = next userDao.update(next) i += step } first.position = previousPos users[to] = first userDao.update(first) notifyItemMoved(from, to) } fun onItemDismiss(pos: Int) { userDao.delete(adapter.users[pos]) } internal inner class UserViewHolder(val binding: ItemUserBinding) : RecyclerView.ViewHolder(binding.root) } internal class UsersDiffCallback(private val oldUsers: List<User>, private val newUsers: List<User>) : DiffUtil.Callback() { override fun getOldListSize() = oldUsers.size override fun getNewListSize() = newUsers.size override fun areItemsTheSame(p0: Int, p1: Int) = oldUsers[p0].id == newUsers[p1].id override fun areContentsTheSame(p0: Int, p1: Int) = oldUsers[p0] == newUsers[p1] } }
10
Kotlin
1
7
65842c934a79d55a78662d03f3d34560c30c2aab
7,466
BJUTWiFi
MIT License
ion-schema/src/main/kotlin/com/amazon/ionschema/internal/DeferredReferenceManager.kt
amazon-ion
148,685,964
false
{"Kotlin": 804755, "Inno Setup": 15625, "Java": 795, "Shell": 631}
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.ionschema.internal import com.amazon.ion.IonSymbol import com.amazon.ionschema.InvalidSchemaException import com.amazon.ionschema.Schema import java.util.LinkedList import java.util.Queue /** * A single-use "session" for creating, tracking, and resolving deferred references _for multiple [Schema]_. * * A [DeferredReferenceManager] allows you to create [DeferredReference] instances, and it keeps track of any * [DeferredReference] instances that it creates. When this [DeferredReferenceManager] is closed, it attempts to * resolve all of the [DeferredReference]. If any cannot be resolved, it throws an [InvalidSchemaException] listing * the types that cannot be resolved. * * A [DeferredReferenceManager] ensures that all [DeferredReference]s it creates refer to a type that does actually * exist in the source ISL. (Caveat—it can't yet do that for local references in anonymous schemas.) This check is not * strictly necessary since the non-existence of the type would be discovered when attempting to resolve the type, but * including this check does help to reason about the correctness of the implementation. If it is discovered to be a * performance bottleneck, it could safely be removed. * * In addition, a schema can be registered with the [DeferredReferenceManager] as being dependent on the outcome of * resolving the deferred references. See [registerDependentSchema] for details. * * Once a [DeferredReferenceManager] instance has been closed, you cannot use that instance to create any new references * nor can you register any dependent schemas, and the instance should be discarded. Attempting to perform any operation * once closed will result in an [IllegalStateException] being thrown. */ @OptIn(DeferredReferenceManagerImplementationDetails::class) internal class DeferredReferenceManager( private val loadSchemaFn: (DeferredReferenceManager, String) -> SchemaInternal, private val unloadSchema: (String) -> Unit, private val isSchemaAlreadyLoaded: (String) -> Boolean, private val doesSchemaDeclareType: (String, IonSymbol) -> Boolean, ) { private val deferredTypeReferences: Queue<DeferredReference> = LinkedList() private val dependentSchemas = mutableSetOf<String>() private var isClosed = false /** * Creates a [DeferredLocalReference] for a type with name [typeId] that is in scope for the given [schema]. */ fun createDeferredLocalReference(schema: SchemaInternal, typeId: IonSymbol): TypeInternal { if (isClosed) throw IllegalStateException("Cannot create a new reference using a closed DeferredReferenceManager") // TODO: See if it's possible to enforce this guarantee for anonymous schemas schema.schemaId?.let { schemaId -> if (!doesSchemaDeclareType(schemaId, typeId)) throw InvalidSchemaException("No type named '$typeId' in schema $schemaId") } val ref = DeferredLocalReference(typeId, schema) deferredTypeReferences.add(ref) return ref } /** * Creates an [DeferredImportReference] for a type with name [typeId] that is declared in [schemaId]. */ fun createDeferredImportReference(schemaId: String, typeId: IonSymbol): ImportedType { if (isClosed) throw IllegalStateException("Cannot create a new reference using a closed DeferredReferenceManager") if (!doesSchemaDeclareType(schemaId, typeId)) throw InvalidSchemaException("No type named '$typeId' in schema $schemaId") val ref = DeferredImportReference(typeId, schemaId) { loadSchemaFn(this, schemaId) } deferredTypeReferences.add(ref) return ref } /** * Indicates that the validity of the [Schema] for the given [schemaId] depends on the outcome of this * [DeferredReferenceManager]. If the [Schema] for the given [schemaId] is already loaded into the [IonSchemaSystemImpl], * then this function does nothing. Otherwise, the [schemaId] is added to the list of [dependentSchemas] that will * need to be invalidated if any deferred references cannot be resolved. * * In other words, we cannot guarantee that a schema is valid until we have validated all of its deferred references. * If any references are deferred, and then later discovered to be invalid, then we must invalidate all schemas that * depend on that reference—directly or indirectly. In practice, however, this class takes a safe-but-naive approach * and will unload *all* schemas that are dependent on the outcome of this [DeferredReferenceManager]. * * This function should only be called from the initializer block of a [Schema] implementation. */ internal fun registerDependentSchema(schemaId: String) { if (isClosed) throw IllegalStateException("Cannot register a dependent schema with a closed DeferredReferenceManager") // If this function is only called from the init block of a Schema implementation (as prescribed), then it // should not be possible for the given schemaId to already be loaded. However, we check anyway so that this // function does not have to make assumptions about its preconditions. if (isSchemaAlreadyLoaded(schemaId)) return dependentSchemas.add(schemaId) } fun resolve() { if (isClosed) throw IllegalStateException("Cannot call resolve() on a closed DeferredReferenceManager") try { // NOTE: we must use a loop rather than an iterator/stream/sequence since more items can be // added to the queue as a side effect of resolving a deferred type reference. while (deferredTypeReferences.isNotEmpty()) { deferredTypeReferences.poll().resolve() } } catch (e: Exception) { // If anything goes wrong, evict all possibly bad schemas that might have been cached dependentSchemas.forEach { unloadSchema(it) } throw e } finally { isClosed = true } } }
40
Kotlin
14
27
7a9ee6d06e9cfdaa530310f5d9be9f5a52680d3b
6,631
ion-schema-kotlin
Apache License 2.0
springboot-starter/src/main/kotlin/com/labijie/infra/aspect/DistributedSynchronizedAspect.kt
hongque-pro
307,931,824
false
{"Kotlin": 143121}
package com.labijie.infra.aspect import com.labijie.infra.annotation.DistributedSynchronized import com.labijie.infra.distribution.IDistributedLock import com.labijie.infra.distribution.LockScope import com.labijie.infra.utils.ifNullOrBlank import org.aspectj.lang.JoinPoint import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation.Around import org.aspectj.lang.annotation.Aspect import org.aspectj.lang.annotation.Pointcut import org.aspectj.lang.reflect.MethodSignature import org.springframework.core.annotation.AnnotatedElementUtils import org.springframework.core.annotation.Order /** * @author <NAME> * @date 2018-09-25 */ @Aspect @Order(1) class DistributedSynchronizedAspect(private val distributedLock: IDistributedLock) { @Pointcut("@annotation(com.labijie.infra.annotation.DistributedSynchronized)") private fun pointCut() {} @Around("pointCut()") fun around(joinPoint:JoinPoint):Any { val point = joinPoint as ProceedingJoinPoint val method = (point.signature as MethodSignature).method val anno = AnnotatedElementUtils.findMergedAnnotation(method, DistributedSynchronized::class.java) //val anno = method.getAnnotation(DistributedSynchronized::class.java) val syncName = (anno?.lockName).ifNullOrBlank("${method.declaringClass.name}.${method.name}")!! this.distributedLock.acquire(syncName, LockScope.Instance) try { return point.proceed(joinPoint.args) } finally { this.distributedLock.release(syncName, LockScope.Instance) } } }
0
Kotlin
0
3
d486e2d186a1074473e874e3882b478a42239b64
1,599
infra-commons
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/pipelines/EcrDockerCredentialOptions.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.pipelines import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import io.cloudshiftdev.awscdk.services.iam.IRole import kotlin.Unit import kotlin.collections.List /** * Options for defining access for a Docker Credential composed of ECR repos. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.iam.*; * import io.cloudshiftdev.awscdk.pipelines.*; * Role role; * EcrDockerCredentialOptions ecrDockerCredentialOptions = EcrDockerCredentialOptions.builder() * .assumeRole(role) * .usages(List.of(DockerCredentialUsage.SYNTH)) * .build(); * ``` */ public interface EcrDockerCredentialOptions { /** * An IAM role to assume prior to accessing the secret. * * Default: - none. The current execution role will be used. */ public fun assumeRole(): IRole? = unwrap(this).getAssumeRole()?.let(IRole::wrap) /** * Defines which stages of the pipeline should be granted access to these credentials. * * Default: - all relevant stages (synth, self-update, asset publishing) are granted access. */ public fun usages(): List<DockerCredentialUsage> = unwrap(this).getUsages()?.map(DockerCredentialUsage::wrap) ?: emptyList() /** * A builder for [EcrDockerCredentialOptions] */ @CdkDslMarker public interface Builder { /** * @param assumeRole An IAM role to assume prior to accessing the secret. */ public fun assumeRole(assumeRole: IRole) /** * @param usages Defines which stages of the pipeline should be granted access to these * credentials. */ public fun usages(usages: List<DockerCredentialUsage>) /** * @param usages Defines which stages of the pipeline should be granted access to these * credentials. */ public fun usages(vararg usages: DockerCredentialUsage) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.pipelines.EcrDockerCredentialOptions.Builder = software.amazon.awscdk.pipelines.EcrDockerCredentialOptions.builder() /** * @param assumeRole An IAM role to assume prior to accessing the secret. */ override fun assumeRole(assumeRole: IRole) { cdkBuilder.assumeRole(assumeRole.let(IRole.Companion::unwrap)) } /** * @param usages Defines which stages of the pipeline should be granted access to these * credentials. */ override fun usages(usages: List<DockerCredentialUsage>) { cdkBuilder.usages(usages.map(DockerCredentialUsage.Companion::unwrap)) } /** * @param usages Defines which stages of the pipeline should be granted access to these * credentials. */ override fun usages(vararg usages: DockerCredentialUsage): Unit = usages(usages.toList()) public fun build(): software.amazon.awscdk.pipelines.EcrDockerCredentialOptions = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.pipelines.EcrDockerCredentialOptions, ) : CdkObject(cdkObject), EcrDockerCredentialOptions { /** * An IAM role to assume prior to accessing the secret. * * Default: - none. The current execution role will be used. */ override fun assumeRole(): IRole? = unwrap(this).getAssumeRole()?.let(IRole::wrap) /** * Defines which stages of the pipeline should be granted access to these credentials. * * Default: - all relevant stages (synth, self-update, asset publishing) are granted access. */ override fun usages(): List<DockerCredentialUsage> = unwrap(this).getUsages()?.map(DockerCredentialUsage::wrap) ?: emptyList() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): EcrDockerCredentialOptions { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.pipelines.EcrDockerCredentialOptions): EcrDockerCredentialOptions = CdkObjectWrappers.wrap(cdkObject) as? EcrDockerCredentialOptions ?: Wrapper(cdkObject) internal fun unwrap(wrapped: EcrDockerCredentialOptions): software.amazon.awscdk.pipelines.EcrDockerCredentialOptions = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.pipelines.EcrDockerCredentialOptions } }
1
Kotlin
0
4
a18731816a3ec710bc89fb8767d2ab71cec558a6
4,735
kotlin-cdk-wrapper
Apache License 2.0
privacysandbox/ads/ads-adservices/src/main/java/androidx/privacysandbox/ads/adservices/common/KeyedFrequencyCap.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.privacysandbox.ads.adservices.common import android.os.Build import android.os.ext.SdkExtensions import androidx.annotation.RequiresExtension import androidx.annotation.RestrictTo import java.time.Duration /** * A frequency cap for a specific ad counter key. * * Frequency caps define the maximum rate an event can occur within a given time interval. If the * frequency cap is exceeded, the associated ad will be filtered out of ad selection. * * @param adCounterKey The ad counter key that the frequency cap is applied to. * @param maxCount A render URL for the winning ad. * @param interval The caller adtech entity's [AdTechIdentifier]. */ @ExperimentalFeatures.Ext8OptIn class KeyedFrequencyCap public constructor( val adCounterKey: Int, val maxCount: Int, val interval: Duration ) { /** Checks whether two [KeyedFrequencyCap] objects contain the same information. */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is KeyedFrequencyCap) return false return this.adCounterKey == other.adCounterKey && this.maxCount == other.maxCount && this.interval == other.interval } /** Returns the hash of the [KeyedFrequencyCap] object's data. */ override fun hashCode(): Int { var hash = adCounterKey.hashCode() hash = 31 * hash + maxCount.hashCode() hash = 31 * hash + interval.hashCode() return hash } /** Overrides the toString method. */ override fun toString(): String { return "KeyedFrequencyCap: adCounterKey=$adCounterKey, maxCount=$maxCount, " + "interval=$interval" } @RestrictTo(RestrictTo.Scope.LIBRARY) @RequiresExtension(extension = SdkExtensions.AD_SERVICES, version = 8) @RequiresExtension(extension = Build.VERSION_CODES.S, version = 9) internal fun convertToAdServices(): android.adservices.common.KeyedFrequencyCap { return android.adservices.common.KeyedFrequencyCap.Builder( adCounterKey, maxCount, interval) .build() } }
29
Kotlin
937
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
2,748
androidx
Apache License 2.0
library/src/main/java/io/github/achmadhafid/toolbar_badge_menu_item/ToolbarBadgeKtx.kt
AchmadHafid
169,933,361
false
null
package io.github.achmadhafid.toolbar_badge_menu_item import android.view.Menu import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment fun AppCompatActivity.createToolbarBadge( menu: Menu, config: ToolbarBadgeConfig.() -> Unit ) = ToolbarBadgeConfig(ToolbarBadgeColor()).apply(config).let { menu.createToolbarBadge(it.items, it.color, activity = this) } fun Fragment.createToolbarBadge( menu: Menu, config: ToolbarBadgeConfig.() -> Unit ) = ToolbarBadgeConfig(ToolbarBadgeColor()).apply(config).let { menu.createToolbarBadge(it.items, it.color, fragment = this) }
0
Kotlin
2
5
dbffc26a9f8756c354d7b13ee009898e61e03406
621
ToolbarBadgeMenuItem
Apache License 2.0
app/src/main/java/com/app/skyss_companion/model/geocode/Engine.kt
martinheitmann
339,335,251
false
null
package com.app.skyss_companion.model.geocode import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Engine( val name: String, val author: String, val version: String, )
0
Kotlin
0
1
a4a79e658643731cd76617cdb9458aa1f742d4c3
211
bus-companion
MIT License
src/main/kotlin/com/personia/plugins/Authentication.kt
fractalliter
482,401,665
false
null
package com.personia.plugins import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.config.* import io.ktor.server.response.* fun Application.configureAuthentication(config: ApplicationConfig) { val issuer = config.property("jwt.issuer").getString() val myRealm = config.property("jwt.realm").getString() val secret = config.property("jwt.secret").getString() val audience = config.property("jwt.audience").getString() install(Authentication) { jwt("auth-jwt") { realm = myRealm verifier( JWT .require(Algorithm.HMAC256(secret)) .withAudience(audience) .withIssuer(issuer) .build() ) validate { credential -> if (credential.payload.getClaim("username").asString() != "") { JWTPrincipal(credential.payload) } else { null } } challenge { _, _ -> call.respond(HttpStatusCode.Unauthorized, "Token is not valid or has expired") } } } }
2
null
7
9
832099f2ae2f1c977c7a651d33ef56f390dc9ed8
1,311
ktor-postgres-backend
MIT License
later/core/src/awaitedMain/kotlin/koncurrent/LaterConstructorsActuals.kt
aSoft-Ltd
521,074,922
false
{"Kotlin": 89425, "Java": 1554, "JavaScript": 348}
@file:Suppress( "FunctionName", "NON_EXPORTABLE_TYPE", "NOTHING_TO_INLINE", "ACTUAL_WITHOUT_EXPECT" ) package koncurrent import kase.progress.ProgressBus import kase.progress.ProgressPublisher import kase.progress.VoidProgressBus import kollections.List import kase.Result import kase.Success import kollections.toList import kollections.toTypedArray import kollections.Collection import koncurrent.later.filterSuccess import koncurrent.later.mapValues import koncurrent.later.then import kotlinx.JsName actual inline fun <T> Later( executor: Executor, noinline handler: ((resolve: (T) -> Unit, reject: ((Throwable) -> Unit)) -> Unit) ): Later<T> = awaited(executor, handler) actual inline fun <T> PendingLater(executor: Executor): Later<T> = MutableAwaited(executor) actual fun <T> Executor.later(bus: ProgressBus = VoidProgressBus, builder: ProgressPublisher.() -> T): Later<T> = awaited(builder) actual inline fun <T> SuccessfulLater( value: T, executor: Executor ): Later<T> = SuccessfulAwaited(value, executor) actual inline fun FailedLater( error: Throwable, executor: Executor ): Later<Nothing> = FailedAwaited(error, executor) actual fun <T> Laters(vararg laters: Later<T>): Later<List<Result<T>>> = allAwaited(*laters) actual fun <T> Laters(them: Collection<Later<T>>) : Later<List<Result<T>>> = Laters(*them.toList().toTypedArray()) actual inline fun <T> SuccessfulLaters(vararg laters: Later<T>): Later<List<Success<T>>> = SuccessfulAllAwaited(*laters) actual inline fun <T> SuccessfulLaterValues(vararg laters: Later<T>): Later<List<T>> = SuccessfulAwaitedValues(*laters)
0
Kotlin
0
2
0e2a6b9955fca321dce3f1bc7d2b7dce6765b0c8
1,636
koncurrent
MIT License
knowledgebase-gui/src/main/java/ru/usedesk/knowledgebase_gui/screens/article/ArticlePagesAdapter.kt
usedesk
127,645,126
false
null
package ru.usedesk.knowledgebase_gui.screens.article import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import androidx.lifecycle.LifecycleCoroutineScope import androidx.viewpager.widget.ViewPager import ru.usedesk.common_gui.onEachWithOld import ru.usedesk.knowledgebase_gui.screens.article.item.ArticleItem import ru.usedesk.knowledgebase_sdk.entity.UsedeskArticleInfo internal class ArticlePagesAdapter( private val viewPager: ViewPager, fragmentManager: FragmentManager, private val viewModel: ArticlePageViewModel, lifecycleCoroutineScope: LifecycleCoroutineScope, private val withArticleRating: Boolean ) : FragmentStatePagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { private var items: List<UsedeskArticleInfo> = listOf() init { viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) { viewModel.onSelect(position) } override fun onPageScrollStateChanged(state: Int) { } }) viewPager.adapter = this viewModel.modelFlow.onEachWithOld(lifecycleCoroutineScope) { old, new -> if (old?.articles != new.articles) { items = new.articles notifyDataSetChanged() } if (viewPager.currentItem != new.selectedPosition) { viewPager.setCurrentItem(new.selectedPosition, false) } } } override fun getCount(): Int = items.size override fun getItem(position: Int): Fragment { val previous = items.getOrNull(position - 1) val current = items[position] val next = items.getOrNull(position + 1) return ArticleItem.newInstance( withArticleRating, current.id, previous?.title, next?.title ) } fun onPrevious() { val position = viewPager.currentItem - 1 viewPager.setCurrentItem(position, true) viewModel.onSelect(position) } fun onNext() { val position = viewPager.currentItem + 1 viewPager.setCurrentItem(position, true) } }
0
Kotlin
7
3
869286167808166a3e0b88ebc874ea2b87b75011
2,467
Android_SDK
MIT License
js/js.translator/testData/box/expression/evaluationOrder/concatWithTerminator.kt
JakeWharton
99,388,807
false
null
// EXPECTED_REACHABLE_NODES: 1110 package foo fun box(): String { return "Fail${return "OK"}${return "Fail2"}" }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
118
kotlin
Apache License 2.0
feature_rss_list/src/main/java/com/phicdy/mycuration/rss/RssListUpdateAction.kt
phicdy
24,188,186
false
{"Kotlin": 688608, "HTML": 1307, "Shell": 1127}
package com.phicdy.mycuration.rss import com.phicdy.mycuration.core.Action class RssListUpdateAction(override val value: RssListUpdateState) : Action<RssListUpdateState>
43
Kotlin
9
30
6c8bafba7341c1003da2196bd618b9505f32e42c
172
MyCuration
MIT License
android/common-ui/src/main/java/any/ui/common/widget/ServicesPopup.kt
dokar3
572,488,513
false
null
package any.ui.common.widget import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.animation.slideIn import androidx.compose.animation.slideOut import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import any.base.compose.ImmutableHolder import any.base.util.compose.performLongPress import any.data.entity.ServiceResource import any.domain.entity.UiServiceManifest import any.ui.common.modifier.verticalScrollBar import any.ui.common.theme.divider import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import any.base.R as BaseR import any.ui.common.R as CommonUiR @Composable fun ServicesPopup( services: ImmutableHolder<List<UiServiceManifest>>, selected: UiServiceManifest?, onDismissRequest: () -> Unit, onManagementClick: () -> Unit, onSelectedItem: (UiServiceManifest) -> Unit, modifier: Modifier = Modifier, onItemLongClick: ((UiServiceManifest) -> Unit)? = null, ) { val dismissRequester = rememberAnimatedPopupDismissRequester() val currentOnDismissRequest = rememberUpdatedState(onDismissRequest) LaunchedEffect(dismissRequester.visibleState) { dismissRequester.visibleState.targetState = true snapshotFlow { dismissRequester.visibleState.currentState to dismissRequester.visibleState.targetState } .distinctUntilChanged() .filter { !it.first && !it.second } .collect { currentOnDismissRequest.value() } } Dialog( onDismissRequest = { dismissRequester.dismiss() }, ) { Box( modifier = modifier .fillMaxSize() .padding(vertical = 32.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = { dismissRequester.dismiss() }, ) ) { AnimatedDialogContent(dismissRequester = dismissRequester) { val hapticFeedback = LocalHapticFeedback.current val listState = rememberLazyListState() val topBarHeight = 48.dp val barsBackground = MaterialTheme.colors.surface.copy(alpha = 0.94f) val barsDividerColor = MaterialTheme.colors.divider LaunchedEffect(listState) { val selectedIndex = services.value.indexOf(selected) if (selectedIndex != -1) { listState.scrollToItem(selectedIndex) } } LazyColumn( state = listState, modifier = Modifier .fillMaxWidth() .heightIn(min = 300.dp, max = 600.dp) .verticalScrollBar( state = listState, padding = PaddingValues(top = topBarHeight), ), contentPadding = PaddingValues(top = topBarHeight), ) { items(items = services.value) { val isSelected = it == selected ServiceItem( onClick = { dismissRequester.dismiss() if (!isSelected) { onSelectedItem(it) } }, onLongClick = { hapticFeedback.performLongPress() onItemLongClick?.invoke(it) }, service = it, isSelected = isSelected, ) } } Row( modifier = Modifier .fillMaxWidth() .height(topBarHeight) .background(barsBackground) .drawWithContent { drawContent() drawRect( color = barsDividerColor, topLeft = Offset(0f, size.height - 1.dp.toPx()), size = size.copy(height = 1.dp.toPx()), ) } .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = {}, ) .padding(horizontal = 12.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { Icon( painter = painterResource(CommonUiR.drawable.ic_settings), contentDescription = stringResource(BaseR.string.service_management), modifier = Modifier.clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple(bounded = false), onClick = { dismissRequester.dismiss() onManagementClick() }, ), ) Text( text = stringResource(BaseR.string.services), fontWeight = FontWeight.Bold, ) Icon( imageVector = Icons.Default.Close, contentDescription = stringResource(BaseR.string.close), modifier = Modifier.clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple(bounded = false), onClick = { dismissRequester.dismiss() }, ), ) } } } } } private val slideSpring = spring<IntOffset>( dampingRatio = Spring.DampingRatioLowBouncy, stiffness = Spring.StiffnessMediumLow, ) private val floatSpring = spring<Float>( dampingRatio = Spring.DampingRatioLowBouncy, stiffness = Spring.StiffnessLow, ) @Composable private fun AnimatedDialogContent( dismissRequester: AnimatedPopupDismissRequester, modifier: Modifier = Modifier, content: @Composable () -> Unit, ) { AnimatedVisibility( visibleState = dismissRequester.visibleState, enter = slideIn(animationSpec = slideSpring) { IntOffset(0, -it.height) } + fadeIn( animationSpec = tween( durationMillis = 300, easing = FastOutSlowInEasing, ) ) + scaleIn( initialScale = 0.9f, animationSpec = floatSpring, ), exit = slideOut( animationSpec = tween( durationMillis = 255, easing = FastOutSlowInEasing, ) ) { IntOffset(0, -it.height) } + fadeOut( animationSpec = tween( durationMillis = 255, easing = FastOutSlowInEasing, ) ) + scaleOut( targetScale = 0.9f, animationSpec = tween( durationMillis = 255, easing = FastOutSlowInEasing, ) ), ) { Surface( modifier = modifier, color = MaterialTheme.colors.surface, shape = MaterialTheme.shapes.medium, elevation = 6.dp, ) { content() } } } @OptIn(ExperimentalFoundationApi::class) @Composable private fun ServiceItem( onClick: () -> Unit, onLongClick: () -> Unit, service: UiServiceManifest, isSelected: Boolean, modifier: Modifier = Modifier, ) { val textColor = if (isSelected) { if (MaterialTheme.colors.isLight) { if (service.themeColor != null) { Color(service.themeColor!!) } else { MaterialTheme.colors.primary } } else { if (service.darkThemeColor != null) { Color(service.darkThemeColor!!) } else { MaterialTheme.colors.primary } } } else { MaterialTheme.colors.onBackground } Row( modifier = modifier .fillMaxWidth() .heightIn(min = 48.dp) .padding(horizontal = 8.dp, vertical = 4.dp) .clip(MaterialTheme.shapes.small) .drawWithContent { drawContent() if (isSelected) { drawRoundRect( color = textColor, topLeft = Offset(2.dp.toPx(), this.size.height * 0.1f), size = Size(6.dp.toPx(), this.size.height * 0.8f), cornerRadius = CornerRadius(6.dp.toPx()) ) } } .combinedClickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple(), onClick = onClick, onLongClick = onLongClick, ) .padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { Avatar( name = service.name, url = service.localFirstResourcePath( type = ServiceResource.Type.Icon, fallback = { service.icon } ), size = 36.dp ) Spacer(modifier = Modifier.width(16.dp)) Text(text = service.name, color = textColor) } }
1
Kotlin
0
11
5161c783d0ec054bfaf2889b6573aef9ac2815d7
12,600
any
Apache License 2.0
pleo-antaeus-core/src/main/kotlin/io/pleo/antaeus/core/services/billing/BillingService.kt
hkorkmaz
207,559,808
false
null
package io.pleo.antaeus.core.services.billing import io.pleo.antaeus.core.exceptions.InsufficientFundException import io.pleo.antaeus.core.external.PaymentProvider import io.pleo.antaeus.core.services.InvoiceService import io.pleo.antaeus.models.InvoiceStatus import mu.KotlinLogging private val logger = KotlinLogging.logger {} class BillingService( private val invoiceService: InvoiceService, private val paymentProvider: PaymentProvider ) { fun chargeInvoice(invoiceId: Int) { logger.info("Charging invoice, [invoiceId=$invoiceId]") val invoice = invoiceService.fetch(invoiceId) if (invoice.status == InvoiceStatus.PENDING) { val paymentStatus = paymentProvider.charge(invoice) when (paymentStatus) { true -> invoiceService.updateStatus(invoiceId, InvoiceStatus.PAID) false -> throw InsufficientFundException(invoiceId, invoice.customerId) } logger.info("Charged successfully, [invoiceId=$invoiceId]") } else { logger.info("Already charged, [invoiceId=$invoiceId]") } } }
0
Kotlin
0
0
8eeaf3faea40d6a74ebe34bff70245f892c2d08c
1,134
pleo-challenge
Creative Commons Zero v1.0 Universal
frogocoreconsumeapi/src/main/java/com/frogobox/coreapi/movie/model/TvDetailsNetwork.kt
frogobox
389,577,716
false
null
package com.frogobox.coreapi.movie.model data class TvDetailsNetwork( val id: Int?, val logo_path: String?, val name: String?, val origin_country: String? )
0
Kotlin
2
7
1dd90a037f9acb2ba30066f753d35f7b909621a6
173
frogo-consume-api
Apache License 2.0
theme/src/main/java/projekt/commons/theme/backend/SynergyBackend.kt
prjkt-io
204,901,746
false
{"Kotlin": 87948, "Shell": 933}
/* * Copyright (c) 2019, Projekt Development LLC. * * SPDX-License-Identifier: Apache-2.0 */ package projekt.commons.theme.backend import android.content.Intent import android.os.Parcelable import androidx.core.content.FileProvider import projekt.andromeda.client.util.OverlayInfo.OverlayState.STATE_DISABLED import projekt.andromeda.client.util.OverlayInfo.OverlayState.STATE_ENABLED import projekt.andromeda.client.util.OverlayInfo.OverlayState.STATE_UNKNOWN import projekt.commons.theme.ThemeApplication import java.io.File import java.net.URLConnection internal class SynergyBackend : Backend { override val overlayState: Map<String, Int> get() = emptyMap() override val targetWithMultipleOverlay: List<String> get() = emptyList() override val miscStateValue: Int get() = STATE_UNKNOWN override val disabledStateValue: Int get() = STATE_DISABLED override val enabledStateValue: Int get() = STATE_ENABLED override fun installOverlay(paths: List<String>) { // Use ACTION_SEND intent to send only one item if (paths.size == 1) { val file = File(paths[0]) val fileUri = FileProvider.getUriForFile(ThemeApplication.instance, "${ThemeApplication.instance.packageName}.provider", file) Intent(Intent.ACTION_SEND).run { `package` = "projekt.samsung.theme.compiler" putExtra(Intent.EXTRA_STREAM, fileUri) type = URLConnection.guessContentTypeFromName(file.name) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) ThemeApplication.instance.startActivity(this) } } else if (paths.size > 1) { val fileExtras = arrayListOf<Parcelable>() paths.forEach { path -> val fileUri = FileProvider.getUriForFile(ThemeApplication.instance, "${ThemeApplication.instance.packageName}.provider", File(path)) fileExtras.add(fileUri) } Intent(Intent.ACTION_SEND_MULTIPLE).run { `package` = "projekt.samsung.theme.compiler" putParcelableArrayListExtra(Intent.EXTRA_STREAM, fileExtras) type = URLConnection.guessContentTypeFromName(File(paths[0]).name) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) ThemeApplication.instance.startActivity(this) } } } override fun uninstallOverlay(packages: List<String>, restartUi: Boolean) {} override fun switchOverlay(packages: List<String>, state: Boolean, restartUi: Boolean) {} override fun setPriority(packages: List<String>, restartUi: Boolean) {} override fun getEnabledOverlayWithTarget(targetPackage: String): List<String> = emptyList() override fun restartSystemUi() {} override fun applyFonts(themePid: String, name: String) {} override fun restoreFonts() {} }
0
Kotlin
0
2
c31faa3f6876be8b71c9debc304c13fbf9935502
3,072
android-commons
Apache License 2.0
marketkit/src/main/java/io/horizontalsystems/marketkit/models/NftPrice.kt
horizontalsystems
408,718,031
false
{"Kotlin": 191652}
package io.definenulls.marketkit.models import java.math.BigDecimal data class NftPrice( val token: Token, val value: BigDecimal )
1
Kotlin
23
9
872cb042bdd6eb9063ecb3a2e3954f3954b501bf
141
market-kit-android
MIT License
src/test/java/org/jetbrains/plugins/ideavim/action/copy/YankAndPutTest.kt
JetBrains
1,459,486
false
null
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.action.copy import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.options.OptionConstants import org.jetbrains.plugins.ideavim.TestOptionConstants import org.jetbrains.plugins.ideavim.VimTestCase import org.jetbrains.plugins.ideavim.impl.OptionTest import org.jetbrains.plugins.ideavim.impl.TraceOptions import org.jetbrains.plugins.ideavim.impl.VimOption @TraceOptions(TestOptionConstants.clipboard) class YankAndPutTest : VimTestCase() { @OptionTest(VimOption(TestOptionConstants.clipboard, limitedValues = [OptionConstants.clipboard_unnamed])) fun `test yank to number register with unnamed`() { val before = """ I ${c}found it in a legendary land consectetur adipiscing elit """.trimIndent() configureByText(before) // Select and yank first word typeText(injector.parser.parseKeys("vey")) // Replace second word typeText(injector.parser.parseKeys("wvep")) // Replace previous word typeText(injector.parser.parseKeys("bbvep")) assertState( """ I it found in a legendary land consectetur adipiscing elit """.trimIndent(), ) } @OptionTest(VimOption(TestOptionConstants.clipboard, limitedValues = [OptionConstants.clipboard_unnamed + "," + OptionConstants.clipboard_ideaput])) fun `test yank to number register with unnamed and ideaput`() { val before = """ I ${c}found it in a legendary land consectetur adipiscing elit """.trimIndent() configureByText(before) // Select and yank first word typeText(injector.parser.parseKeys("vey")) // Replace second word typeText(injector.parser.parseKeys("wvep")) // Replace previous word typeText(injector.parser.parseKeys("bbvep")) assertState( """ I it found in a legendary land consectetur adipiscing elit """.trimIndent(), ) } @OptionTest(VimOption(TestOptionConstants.clipboard, limitedValues = [""])) fun `test yank to number register`() { val before = """ I ${c}found it in a legendary land consectetur adipiscing elit """.trimIndent() configureByText(before) // Select and yank first word typeText(injector.parser.parseKeys("vey")) // Replace second word typeText(injector.parser.parseKeys("wvep")) // Replace previous word typeText(injector.parser.parseKeys("bbvep")) assertState( """ I it found in a legendary land consectetur adipiscing elit """.trimIndent(), ) } }
8
null
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
2,818
ideavim
MIT License
platform-domain/src/main/kotlin/org/ossiaustria/amigo/platform/domain/repositories/AlbumRepository.kt
ossi-austria
430,611,101
false
null
package org.ossiaustria.amigo.platform.domain.repositories import org.ossiaustria.amigo.platform.domain.models.Album import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository import java.util.UUID @Repository internal interface AlbumRepository : CrudRepository<Album, UUID> { fun findAllByOwnerIdOrderByCreatedAt(ownerId: UUID): List<Album> fun findAllByOwnerIdIn(ownerIds: List<UUID>): List<Album> fun findByOwnerIdAndId(ownerId: UUID, albumId: UUID): Album? }
0
Kotlin
0
1
0d19a0b0c4d7d55a8f9b74bf2632ea655e373deb
526
amigo-server
MIT License
src/tr/hayalistic/src/eu/kanade/tachiyomi/extension/tr/hayalistic/Hayalistic.kt
keiyoushi
740,710,728
false
{"Kotlin": 5826268, "JavaScript": 2160}
package eu.kanade.tachiyomi.extension.tr.hayalistic import eu.kanade.tachiyomi.multisrc.madara.Madara class Hayalistic : Madara("Hayalistic", "https://hayalistic.com", "tr")
218
Kotlin
251
1,073
4ef8962bc417dc0b34753f6fc0535107799a6f32
176
extensions-source
Apache License 2.0
device-explorer-files/src/com/android/tools/idea/device/explorer/files/adbimpl/AdbDeviceCapabilities.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) 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.tools.idea.device.explorer.files.adbimpl import com.android.adblib.ConnectedDevice import com.android.adblib.RemoteFileMode import com.android.adblib.syncSend import com.android.tools.idea.adb.AdbShellCommandException import com.android.tools.idea.adb.AdbShellCommandResult import com.android.tools.idea.adb.AdbShellCommandsUtil import com.android.tools.idea.concurrency.AndroidDispatchers.diskIoThread import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.util.io.FileUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.withContext /** * Helper class used to detect various capabilities/features supported by a device * so callers can make decisions about which adb commands to use. */ class AdbDeviceCapabilities(coroutineScope: CoroutineScope, private val deviceName: String, private val device: ConnectedDevice) { private val logger = thisLogger() private val shellCommandsUtil = AdbShellCommandsUtil.create(device) suspend fun supportsTestCommand() = supportsTestCommand.await() private val supportsTestCommand = coroutineScope.async(start = CoroutineStart.LAZY) { assertNotDispatchThread() ScopedRemoteFile(AdbPathUtil.resolve(PROBE_FILES_TEMP_PATH, ".__temp_test_test__file__.tmp")).use { tempFile -> // Create the remote file used for testing capability tempFile.create() // Try the "test" command on it (it should succeed if the command is supported) val command = AdbShellCommandBuilder().withText("test -e ").withEscapedPath(tempFile.remotePath).build() val commandResult = shellCommandsUtil.executeCommand(command) try { commandResult.throwIfError() true } catch (e: AdbShellCommandException) { logger.debug( """Device "$deviceName" does not seem to support the "test" command: ${ commandResult.outputSummary()}""") false } } } suspend fun supportsRmForceFlag() = supportsRmForceFlag.await() private val supportsRmForceFlag = coroutineScope.async(start = CoroutineStart.LAZY) { assertNotDispatchThread() ScopedRemoteFile(AdbPathUtil.resolve(PROBE_FILES_TEMP_PATH, ".__temp_rm_test_file__.tmp")).use { tempFile -> // Create the remote file used for testing capability tempFile.create() // Try to delete it with "rm -f" (it should work if th command is supported) val command = AdbShellCommandBuilder().withText("rm -f ").withEscapedPath(tempFile.remotePath).build() val commandResult = shellCommandsUtil.executeCommand(command) try { commandResult.throwIfError() // If no error, "rm -f" is supported and test file has been deleted, so no need to delete it again. tempFile.deleteOnClose = false true } catch (e: AdbShellCommandException) { logger.debug("""Device "$deviceName" does not seem to support "-f" flag for rm: ${ commandResult.outputSummary()}""") false } } } suspend fun supportsTouchCommand() = supportsTouchCommand.await() private val supportsTouchCommand = coroutineScope.async(start = CoroutineStart.LAZY) { assertNotDispatchThread() ScopedRemoteFile(AdbPathUtil.resolve(PROBE_FILES_TEMP_PATH, ".__temp_touch_test_file__.tmp")).use { tempFile -> // Try to create the file with the "touch" command val command = AdbShellCommandBuilder().withText("touch ").withEscapedPath(tempFile.remotePath).build() val commandResult = shellCommandsUtil.executeCommand(command) try { commandResult.throwIfError() // If "touch" worked, we want to delete the temporary file tempFile.deleteOnClose = true true } catch (e: AdbShellCommandException) { logger.debug("""Device "$deviceName" does not seem to support "touch" command: ${ commandResult.outputSummary() }""") false } } } suspend fun supportsSuRootCommand() = supportsSuRootCommand.await() private val supportsSuRootCommand = coroutineScope.async(start = CoroutineStart.LAZY) { assertNotDispatchThread() // Try a "su" command ("id") that should always succeed, unless "su" is not supported val command = AdbShellCommandBuilder().withSuRootPrefix().withText("id").build() val commandResult = shellCommandsUtil.executeCommand(command) try { commandResult.throwIfError() true } catch (e: AdbShellCommandException) { logger.debug( """Device "$deviceName" does not seem to support the "su 0" command: ${ commandResult.outputSummary()}""") false } } suspend fun isRoot() = isRoot.await() private val isRoot = coroutineScope.async(start = CoroutineStart.LAZY) { assertNotDispatchThread() val result = shellCommandsUtil.executeCommandNoErrorCheck("echo \$USER_ID") result.output.joinToString().trim() == "0" } suspend fun supportsCpCommand() = supportsCpCommand.await() private val supportsCpCommand = coroutineScope.async(start = CoroutineStart.LAZY) { assertNotDispatchThread() ScopedRemoteFile(AdbPathUtil.resolve(PROBE_FILES_TEMP_PATH, ".__temp_cp_test_file__.tmp")).use { srcFile -> ScopedRemoteFile(AdbPathUtil.resolve(PROBE_FILES_TEMP_PATH, ".__temp_cp_test_file_dst__.tmp")).use { dstFile -> // Create the remote file used for testing capability srcFile.create() // Copy source file to destination file val command = AdbShellCommandBuilder() .withText("cp ") .withEscapedPath(srcFile.remotePath) .withText(" ") .withEscapedPath(dstFile.remotePath) .build() val commandResult = shellCommandsUtil.executeCommand(command) try { commandResult.throwIfError() // If "cp" succeeded, we need to delete the destination file dstFile.deleteOnClose = true true } catch (e: AdbShellCommandException) { logger.debug( """Device "$deviceName" does not seem to support the "cp" command: ${ commandResult.outputSummary()}""") false } } } } suspend fun hasEscapingLs(): Boolean = hasEscapingLs.await() private val hasEscapingLs = coroutineScope.async(start = CoroutineStart.LAZY) { assertNotDispatchThread() try { touchEscapedPath() } catch (exception: AdbShellCommandException) { logger.debug("""Device "$deviceName" does not seem to support the touch command""", exception) return@async false } try { ScopedRemoteFile(ESCAPING_LS_NOT_ESCAPED_PATH).use { file -> file.deleteOnClose = true lsEscapedPath() } } catch (exception: AdbShellCommandException) { logger.debug("""Device "$deviceName" does not seem to support the ls command""", exception) false } } private suspend fun touchEscapedPath() { val command = AdbShellCommandBuilder().withText("touch $ESCAPING_LS_ESCAPED_PATH").build() val result = shellCommandsUtil.executeCommand(command) result.throwIfError() if (!result.isEmpty()) { throw AdbShellCommandException("Unexpected output from touch") } } private suspend fun lsEscapedPath(): Boolean { val command = AdbShellCommandBuilder().withText("ls $ESCAPING_LS_ESCAPED_PATH").build() val result = shellCommandsUtil.executeCommand(command) result.throwIfError() return when (result.output[0]) { ESCAPING_LS_ESCAPED_PATH -> true ESCAPING_LS_NOT_ESCAPED_PATH -> false else -> throw AdbShellCommandException("Unexpected output from ls") } } suspend fun supportsMkTempCommand() = supportsMkTempCommand.await() private val supportsMkTempCommand = coroutineScope.async(start = CoroutineStart.LAZY) { assertNotDispatchThread() // Copy source file to destination file val command = AdbShellCommandBuilder().withText("mktemp -p ").withEscapedPath(AdbPathUtil.DEVICE_TEMP_DIRECTORY).build() val commandResult = shellCommandsUtil.executeCommand(command) try { commandResult.throwIfError() if (commandResult.isEmpty()) { throw AdbShellCommandException("Unexpected output from mktemp, assuming not supported") } // If "mktemp" succeeded, we need to delete the destination file val remotePath = commandResult.output[0] ScopedRemoteFile(remotePath).use { tempFile -> tempFile.deleteOnClose = true } true } catch (e: AdbShellCommandException) { logger.debug( """Device "$deviceName" does not seem to support the "cp" command: ${ commandResult.outputSummary()}""") false } } /** * An [AutoCloseable] wrapper around a temporary file on a remote device.f * The [close] method attempts to delete the file from the remote device * unless [deleteOnClose] is set to false. */ private inner class ScopedRemoteFile(val remotePath: String) { var deleteOnClose = false suspend fun create() { assert(!deleteOnClose) assertNotDispatchThread() createRemoteTemporaryFile() deleteOnClose = true } /** Suspending version of [AutoCloseable.use()] */ suspend fun <R> use(block: suspend (ScopedRemoteFile) -> R): R { var exception: Throwable? = null try { return block(this) } catch (e: Throwable) { exception = e throw e } finally { withContext(NonCancellable) { when (exception) { null -> close() else -> try { close() } catch (closeException: Throwable) { exception.addSuppressed(closeException) } } } } } suspend fun close() { if (!deleteOnClose) { return } try { val command = AdbShellCommandBuilder().withText("rm ").withEscapedPath(remotePath).build() val commandResult = shellCommandsUtil.executeCommand(command) try { commandResult.throwIfError() } catch (e: AdbShellCommandException) { // There is not much we can do if we can't delete the test file other than logging the error. logger.debug( """Device "$deviceName": Error deleting temporary test file "$remotePath": ${ commandResult.outputSummary()}""") } } catch (e: Exception) { // There is not much we can do if we can't delete the test file other than logging the error. logger.debug("""Device "$deviceName": Error deleting temporary test file "$remotePath"""") } } /** * Create an empty file on the remote device by first creating a local empty temporary file, * then pushing it to the remote device. */ private suspend fun createRemoteTemporaryFile() = withContext(diskIoThread) { val tempFile = FileUtil.createTempFile(remotePath, "", true) try { val tempFileChannel = device.session.channelFactory.openFile(tempFile.toPath()) logger.trace("""Device "$deviceName": Uploading temporary file "$tempFile" to remote file "$remotePath"""") device.session.deviceServices.syncSend(device.selector, tempFileChannel, remotePath, RemoteFileMode.DEFAULT) } finally { withContext(NonCancellable) { try { FileUtil.delete(tempFile) } catch (e: Exception) { logger.debug("""Device "$deviceName": Error deleting temporary file "$tempFile"""") } } } } } companion object { private val PROBE_FILES_TEMP_PATH = AdbPathUtil.resolve(AdbPathUtil.DEVICE_TEMP_DIRECTORY, "device-explorer") private val ESCAPING_LS_ESCAPED_PATH = AdbPathUtil.resolve(AdbPathUtil.DEVICE_TEMP_DIRECTORY, "oyX2HCKL\\ acuauQGJ") private val ESCAPING_LS_NOT_ESCAPED_PATH = AdbPathUtil.resolve(AdbPathUtil.DEVICE_TEMP_DIRECTORY, "oyX2HCKL acuauQGJ") private fun assertNotDispatchThread() { val application = ApplicationManager.getApplication() assert(application == null || !application.isDispatchThread) } private fun AdbShellCommandResult.outputSummary(): String = when { isEmpty() -> "[command output is empty]" else -> output.joinToString(prefix = "\n ", postfix = "", separator = "\n ", limit = 5) } } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
13,232
android
Apache License 2.0
app/src/main/java/jr/brian/rickandmortyrest/model/local/rmcharacter/CharacterResult.kt
BrianJr03
794,274,786
false
{"Kotlin": 55456}
package jr.brian.rickandmortyrest.model.local.rmcharacter import jr.brian.rickandmortyrest.model.local.Character data class CharacterResult( val info: Info, val results: List<Character> )
0
Kotlin
1
0
1e0d4d0fbc560d987fc59a3e6d6cbfff794f22e7
197
Rick-And-Morty
MIT License
app/src/main/java/jr/brian/rickandmortyrest/model/local/rmcharacter/CharacterResult.kt
BrianJr03
794,274,786
false
{"Kotlin": 55456}
package jr.brian.rickandmortyrest.model.local.rmcharacter import jr.brian.rickandmortyrest.model.local.Character data class CharacterResult( val info: Info, val results: List<Character> )
0
Kotlin
1
0
1e0d4d0fbc560d987fc59a3e6d6cbfff794f22e7
197
Rick-And-Morty
MIT License
services/csm.cloud.reset/src/main/kotlin/com/bosch/pt/iot/smartsite/reset/boundary/ProjectStatisticsServiceResetService.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: Robert Bosch Power Tools GmbH, 2018 - 2022 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.reset.boundary import com.bosch.pt.iot.smartsite.reset.Resettable import com.bosch.pt.iot.smartsite.reset.jdbc.JdbcResetStrategy import org.springframework.beans.factory.annotation.Qualifier import org.springframework.jdbc.core.JdbcOperations import org.springframework.stereotype.Service @Service class ProjectStatisticsServiceResetService( jdbcResetStrategy: JdbcResetStrategy, @Qualifier("statisticsJdbcTemplate") jdbcOperations: JdbcOperations ) : AbstractRelationalDatabaseResetService(jdbcResetStrategy, jdbcOperations, "statistics-service"), Resettable
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
843
bosch-pt-refinemysite-backend
Apache License 2.0
app/src/main/java/com/example/instagramclone/domain/use_cases/user_use_cases/GetUserDetails.kt
maryam2070
747,865,960
false
{"Kotlin": 347845}
package com.example.instagramclone.domain.use_cases.user_use_cases import com.example.instagramclone.domain.repository.UserRepository import javax.inject.Inject class GetUserDetails @Inject constructor( val repository: UserRepository ) { operator fun invoke(userId: String) = repository.getUserDetails(userId = userId) }
0
Kotlin
0
3
a7c1053d6de2af3d7da556fcdda6527e8a438878
330
Instagram_Clone
MIT License
app/src/main/java/com/barryzhang/gankkotlin/data/remote/SimpleSubscriber.kt
barryhappy
64,583,744
false
null
package com.barryzhang.gankkotlin.data.remote import android.app.Activity import android.widget.Toast import com.barryzhang.gankkotlin.ext.toast import com.barryzhang.gankkotlin.ui.base.BaseActivity import com.barryzhang.gankkotlin.ui.wiget.LoadingDialog import rx.Subscriber /** * <EMAIL> * https://github.com/barryhappy * http://www.barryzhang.com/ * Created by Barry on 16/7/19 22:37. */ abstract class SimpleSubscriber<T> : Subscriber<T> { var act: BaseActivity? = null var dialog : LoadingDialog? = null constructor(act: Activity) : super() { if(act is BaseActivity) { this.act = act } } override fun onStart() { if (show()) { act?.showLoadingDialog() } } override fun onCompleted() { act?.hideLoadingDialog() this.unsubscribe() } override fun onError(e: Throwable) { onException(e) act?.hideLoadingDialog() act?.toast("异常\n: ${e.message}") this.unsubscribe() } fun show(): Boolean = shouldShowProgressbar() || getProgressTip() != null open fun shouldShowProgressbar(): Boolean = true open fun getProgressTip(): String ? = null open fun onException(e: Throwable?) { } }
1
Kotlin
10
32
d5f12648d5a28cb3626e595db5f5fd6dde6935ae
1,257
Gank.Kotlin
Apache License 2.0
src/main/kotlin/io/sc3/library/recipe/ShapedRecipeSpec.kt
SwitchCraftCC
536,362,058
false
null
package io.sc3.library.recipe import com.google.gson.JsonObject import io.sc3.library.ScLibrary.ModId import net.minecraft.item.ItemStack import net.minecraft.network.PacketByteBuf import net.minecraft.recipe.Ingredient import net.minecraft.recipe.RecipeSerializer import net.minecraft.recipe.ShapedRecipe import net.minecraft.recipe.book.CraftingRecipeCategory import net.minecraft.util.collection.DefaultedList /** * The underlying structure of a [ShapedRecipe]-esque recipe, useful for writing serialisation and deserialization * code. */ class ShapedRecipeSpec private constructor( val group: String, val category: CraftingRecipeCategory, val width: Int, val height: Int, val ingredients: DefaultedList<Ingredient>, val output: ItemStack, ) { fun write(buf: PacketByteBuf) { buf.writeString(group) buf.writeEnumConstant(category) buf.writeVarInt(width) buf.writeVarInt(height) for (ingredient in ingredients) ingredient.write(buf) buf.writeItemStack(output) } companion object { fun ofRecipe(recipe: ShapedRecipe) = ShapedRecipeSpec( recipe.group, recipe.category, recipe.width, recipe.height, recipe.ingredients, recipe.output ) fun ofJson(json: JsonObject): ShapedRecipeSpec = ofRecipe(RecipeSerializer.SHAPED.read(ModId("ignore"), json)) fun ofPacket(buf: PacketByteBuf): ShapedRecipeSpec { val group = buf.readString() val category = buf.readEnumConstant(CraftingRecipeCategory::class.java) val width = buf.readVarInt() val height = buf.readVarInt() val ingredients = DefaultedList.ofSize(width * height, Ingredient.EMPTY) for (i in ingredients.indices) ingredients[i] = Ingredient.fromPacket(buf) val output = buf.readItemStack() return ShapedRecipeSpec(group, category, width, height, ingredients, output) } } }
0
null
0
2
cc988b7fbe4ff0798f3db39e646db01255307ab3
1,853
sc-library
MIT License
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/numberConversion/toChar/byte.kt
JetBrains
2,489,216
false
null
// "Convert expression to 'Char'" "true" fun char(x: Char) {} fun test(b: Byte) { char(<caret>b) }
233
null
4912
15,461
9fdd68f908db0b6bb6e08dc33fafb26e2e4712af
104
intellij-community
Apache License 2.0
app/src/test/java/in/testpress/testpress/util/RegistrationFormEmptyInputValidatorTest.kt
testpress
32,573,386
false
{"Gemfile.lock": 1, "Java Properties": 4, "Gradle": 8, "Batchfile": 2, "INI": 2, "Shell": 2, "Text": 1, "Ignore List": 2, "Git Attributes": 1, "YAML": 4, "Markdown": 4, "Ruby": 7, "JSON": 3, "Kotlin": 56, "Java": 183, "XML": 155, "CSS": 1, "JavaScript": 1, "Python": 1}
package `in`.testpress.testpress.util import `in`.testpress.testpress.models.UserDetails import `in`.testpress.testpress.util.fakes.FakeRegistrationFormEmptyInputValidation import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class RegistrationFormEmptyInputValidatorTest { @Test fun nonEmptyDataShouldReturnTrue() { val registrationFormEmptyInputValidation = FakeRegistrationFormEmptyInputValidation(UserDetails( "helen01", "<EMAIL>", "9876543210", "1234567", "1234567" )) Assert.assertTrue(registrationFormEmptyInputValidation.isValid()) } @Test fun emptyEmailShouldReturnFalse() { val registrationFormEmptyInputValidation = FakeRegistrationFormEmptyInputValidation(UserDetails( "helen01", "", "9876543210", "1234567", "1234567" )) Assert.assertEquals(false, registrationFormEmptyInputValidation.isValid()) } @Test fun emptyUserNameShouldReturnFalse() { val registrationFormEmptyInputValidation = FakeRegistrationFormEmptyInputValidation(UserDetails( "", "<EMAIL>", "9876543210", "1234567", "1234567" )) Assert.assertEquals(false, registrationFormEmptyInputValidation.isValid()) } @Test fun emptyPasswordShouldReturnTrue() { val registrationFormEmptyInputValidation = FakeRegistrationFormEmptyInputValidation(UserDetails( "helen01", "<EMAIL>", "9876543210", "", "" )) Assert.assertEquals(false, registrationFormEmptyInputValidation.isValid()) } }
29
Java
4
9
bddfa5b62235296b8f8a96bcb013afc4a746956c
1,903
android
MIT License
room/room-compiler/src/main/kotlin/androidx/room/solver/query/result/CoroutineFlowResultBinder.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.solver.query.result import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XCodeBlock.Builder.Companion.addLocalVal import androidx.room.compiler.codegen.XMemberName.Companion.packageMember import androidx.room.compiler.codegen.XPropertySpec import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.codegen.box import androidx.room.compiler.processing.XType import androidx.room.ext.ArrayLiteral import androidx.room.ext.CallableTypeSpecBuilder import androidx.room.ext.CommonTypeNames import androidx.room.ext.InvokeWithLambdaParameter import androidx.room.ext.LambdaSpec import androidx.room.ext.RoomCoroutinesTypeNames.COROUTINES_ROOM import androidx.room.ext.RoomTypeNames import androidx.room.ext.SQLiteDriverTypeNames import androidx.room.solver.CodeGenScope /** Binds the result of a Kotlin Coroutine Flow<T> */ class CoroutineFlowResultBinder( val typeArg: XType, val tableNames: Set<String>, adapter: QueryResultAdapter? ) : BaseObservableQueryResultBinder(adapter) { override fun convertAndReturn( roomSQLiteQueryVar: String, canReleaseQuery: Boolean, dbProperty: XPropertySpec, inTransaction: Boolean, scope: CodeGenScope ) { val callableImpl = CallableTypeSpecBuilder(scope.language, typeArg.asTypeName()) { addCode( XCodeBlock.builder(language) .apply { createRunQueryAndReturnStatements( builder = this, roomSQLiteQueryVar = roomSQLiteQueryVar, dbProperty = dbProperty, inTransaction = inTransaction, scope = scope, cancellationSignalVar = "null" ) } .build() ) } .apply { if (canReleaseQuery) { createFinalizeMethod(roomSQLiteQueryVar) } } .build() scope.builder.apply { val arrayOfTableNamesLiteral = ArrayLiteral(scope.language, CommonTypeNames.STRING, *tableNames.toTypedArray()) addStatement( "return %T.createFlow(%N, %L, %L, %L)", COROUTINES_ROOM, dbProperty, if (inTransaction) "true" else "false", arrayOfTableNamesLiteral, callableImpl ) } } override fun isMigratedToDriver() = adapter?.isMigratedToDriver() == true override fun convertAndReturn( sqlQueryVar: String, dbProperty: XPropertySpec, bindStatement: (CodeGenScope.(String) -> Unit)?, returnTypeName: XTypeName, inTransaction: Boolean, scope: CodeGenScope ) { val arrayOfTableNamesLiteral = ArrayLiteral(scope.language, CommonTypeNames.STRING, *tableNames.toTypedArray()) val connectionVar = scope.getTmpVar("_connection") val createBlock = InvokeWithLambdaParameter( scope = scope, functionName = RoomTypeNames.FLOW_UTIL.packageMember("createFlow"), argFormat = listOf("%N", "%L", "%L"), args = listOf(dbProperty, inTransaction, arrayOfTableNamesLiteral), lambdaSpec = object : LambdaSpec( parameterTypeName = SQLiteDriverTypeNames.CONNECTION, parameterName = connectionVar, returnTypeName = returnTypeName.box(), javaLambdaSyntaxAvailable = scope.javaLambdaSyntaxAvailable ) { override fun XCodeBlock.Builder.body(scope: CodeGenScope) { val returnPrefix = when (language) { CodeLanguage.JAVA -> "return " CodeLanguage.KOTLIN -> "" } val statementVar = scope.getTmpVar("_stmt") addLocalVal( statementVar, SQLiteDriverTypeNames.STATEMENT, "%L.prepare(%L)", connectionVar, sqlQueryVar ) beginControlFlow("try") bindStatement?.invoke(scope, statementVar) val outVar = scope.getTmpVar("_result") adapter?.convert(outVar, statementVar, scope) addStatement("$returnPrefix%L", outVar) nextControlFlow("finally") addStatement("%L.close()", statementVar) endControlFlow() } } ) scope.builder.add("return %L", createBlock) } }
29
Kotlin
978
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
6,046
androidx
Apache License 2.0
solar/src/main/java/com/chiksmedina/solar/boldduotone/like/HeartBroken.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.boldduotone.like 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 com.chiksmedina.solar.boldduotone.LikeGroup val LikeGroup.HeartBroken: ImageVector get() { if (_heartBroken != null) { return _heartBroken!! } _heartBroken = Builder( name = "HeartBroken", 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 ) { moveTo(15.0383f, 18.9111f) curveTo(17.9806f, 16.5917f, 22.0f, 14.0003f, 22.0f, 9.1373f) curveTo(22.0f, 4.2744f, 16.4998f, 0.8257f, 12.0f, 5.5009f) lineTo(10.8822f, 7.7359f) curveTo(10.6998f, 8.1007f, 10.6086f, 8.2831f, 10.6531f, 8.4622f) curveTo(10.6975f, 8.6413f, 10.8635f, 8.7599f, 11.1954f, 8.997f) lineTo(13.111f, 10.3652f) curveTo(13.5268f, 10.6622f, 13.7346f, 10.8107f, 13.7612f, 11.0293f) curveTo(13.7878f, 11.2478f, 13.6215f, 11.4418f, 13.289f, 11.8298f) lineTo(11.6027f, 13.7971f) curveTo(11.3168f, 14.1307f, 11.1738f, 14.2975f, 11.1813f, 14.4933f) curveTo(11.1888f, 14.6891f, 11.3442f, 14.8444f, 11.6548f, 15.155f) lineTo(12.5996f, 16.0999f) curveTo(12.7952f, 16.2954f, 12.893f, 16.3932f, 12.9281f, 16.5202f) curveTo(12.9633f, 16.6471f, 12.9298f, 16.7812f, 12.8627f, 17.0495f) lineTo(12.0f, 20.5002f) curveTo(13.0f, 20.5002f, 14.0f, 19.7296f, 15.0383f, 18.9111f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(8.1063f, 18.2471f) curveTo(5.2982f, 16.0836f, 2.0f, 13.5424f, 2.0f, 9.1373f) curveTo(2.0f, 4.2744f, 7.5002f, 0.8257f, 12.0f, 5.5009f) lineTo(10.8822f, 7.7359f) curveTo(10.6998f, 8.1007f, 10.6086f, 8.2831f, 10.6531f, 8.4622f) curveTo(10.6975f, 8.6413f, 10.8635f, 8.7599f, 11.1954f, 8.997f) lineTo(13.111f, 10.3652f) curveTo(13.5268f, 10.6622f, 13.7346f, 10.8107f, 13.7612f, 11.0293f) curveTo(13.7878f, 11.2478f, 13.6215f, 11.4418f, 13.289f, 11.8297f) lineTo(11.6027f, 13.7971f) curveTo(11.3168f, 14.1307f, 11.1738f, 14.2975f, 11.1813f, 14.4933f) curveTo(11.1888f, 14.6891f, 11.3442f, 14.8444f, 11.6548f, 15.155f) lineTo(12.5996f, 16.0999f) curveTo(12.7952f, 16.2954f, 12.893f, 16.3932f, 12.9281f, 16.5202f) curveTo(12.9633f, 16.6471f, 12.9298f, 16.7812f, 12.8627f, 17.0495f) lineTo(12.0f, 20.5002f) curveTo(11.0f, 20.5002f, 10.0f, 19.7296f, 8.9617f, 18.9111f) curveTo(8.6847f, 18.6927f, 8.3981f, 18.4719f, 8.1063f, 18.2471f) close() } } .build() return _heartBroken!! } private var _heartBroken: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
3,999
SolarIconSetAndroid
MIT License
data/src/main/java/uk/co/applylogic/marvel/data/di/module/ApplicationModule.kt
golanshy
224,468,840
false
null
package uk.co.applylogic.marvel.data.di.module import android.app.Application import android.content.Context import uk.co.applylogic.marvel.data.di.qualifier.ApplicationContext import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class ApplicationModule(private val context: Context) { @Provides @Singleton @ApplicationContext fun provideContext(): Context { return context } @Provides @Singleton internal fun provideApplicationContext(): Application { return context.applicationContext as Application } }
0
Kotlin
0
1
96b12dc42a37613ce8cf76d969adcee59ae9bcf0
591
marvel_demo
Apache License 2.0
subprojects/client-gui/src/main/kotlin/com/handtruth/mc/mcsman/client/gui/view/MCSManView.kt
handtruth
417,843,728
false
null
package com.handtruth.mc.mcsman.client.gui.view import com.handtruth.mc.mcsman.client.gui.Styles import com.handtruth.mc.mcsman.client.gui.util.CoroutineView import javafx.animation.Timeline import javafx.beans.property.SimpleDoubleProperty import javafx.geometry.VPos import javafx.util.Duration import tornadofx.* import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin class MCSManView : CoroutineView("main", "MCSMan") { private inline val radius get() = 200 private inline val circleRadius get() = 60 private inline val controllers get() = controller.controllers private inline val count get() = controllers.size private inline val circleStrokeWidth get() = 4.0 private inline val strokeDashOffsetWidth get() = 4.0 private inline val offset get() = 5.0 private data class Coordinates(val x: Double, val y: Double) override val root = pane { val spaceSize = radius + circleRadius + circleStrokeWidth + offset prefWidth = spaceSize * 2 prefWidth = spaceSize * 2 group { val angleStep = 2 * PI / count var angle = .0 val coordinates = mutableListOf<Coordinates>() val dashOffset = SimpleDoubleProperty(.0) for (i in 0 until count) { val y = -radius * cos(angle) + spaceSize val x = radius * sin(angle) + spaceSize coordinates += Coordinates(x, y) angle += angleStep for (j in 0 until i) { val second = coordinates[j] line(x, y, second.x, second.y) { strokeDashArray += strokeDashOffsetWidth strokeDashOffsetProperty().bind(dashOffset) } } } timeline { keyframe(Duration.seconds(1.0)) { keyvalue(dashOffset, strokeDashOffsetWidth * 2) } cycleCount = Timeline.INDEFINITE } for (i in coordinates.indices) { val (xPos, yPos) = coordinates[i] val controller = controllers[i] stackpane { val offset = circleRadius + circleStrokeWidth layoutX = xPos - offset layoutY = yPos - offset val fillColor = c("#d5e8d4") val strokeColor = c("#82b366") val symbol = circle(radius = offset) { fill = fillColor stroke = strokeColor strokeWidth = circleStrokeWidth } text(controller.name) { textOrigin = VPos.CENTER addClass(Styles.controllerText) } val enteredFill = c("#e5f8e4") val enteredStroke = c("#92c376") setOnMouseEntered { symbol.fill = enteredFill symbol.stroke = enteredStroke } setOnMouseExited { symbol.fill = fillColor symbol.stroke = strokeColor } setOnMousePressed { symbol.fill = c("#c5d8c4") symbol.stroke = c("#72a356") } setOnMouseClicked { symbol.fill = enteredFill symbol.stroke = enteredStroke controller.open(this@MCSManView) } } } circle(spaceSize, spaceSize, circleRadius) { fill = c("#dae8fc") stroke = c("#667d9d") strokeWidth = circleStrokeWidth } } controller.activateShortcuts(this@MCSManView) } }
0
Kotlin
0
0
58b2d4bd0413522dbf1cbabc1c8bab78e1b1edfe
3,971
mcsman
Apache License 2.0
library/src/main/kotlin/fr/rolandl/rijsel/lifecycle/DummyRijselComposeViewModel.kt
ludovicroland
527,699,170
false
{"Kotlin": 212529}
package fr.rolandl.rijsel.lifecycle import android.app.Application import androidx.lifecycle.SavedStateHandle /** * A default RijselViewModel implementation in order to provide a default value to the * [fr.rolandl.rijsel.activity.RijselComposeSplashscreenActivity] activity * * @author <NAME> * @since 2022.04.11 */ class DummyRijselComposeViewModel(application: Application, savedStateHandle: SavedStateHandle) : RijselComposeViewModel(application, savedStateHandle) { override suspend fun computeViewModel() { } }
0
Kotlin
0
0
9f388b307ebf452ddea97769aed4b10a91630502
535
rijsel-android
MIT License
presentation/src/main/kotlin/io/petros/github/presentation/image/glide/GeneratedGlideModule.kt
ParaskP7
140,927,471
false
{"Kotlin": 118109}
package io.petros.github.presentation.image.glide import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule @GlideModule class GeneratedGlideModule : AppGlideModule()
0
Kotlin
1
9
ad9c53165db32af9ca08e4ae3ca4ea9b30e24d2e
208
sample-code-github
Apache License 2.0
pcbridge-spigot/src/main/kotlin/com/projectcitybuild/integrations/essentials/EssentialsIntegration.kt
projectcitybuild
42,997,941
false
null
package com.projectcitybuild.integrations.essentials import com.earth2me.essentials.Essentials import com.projectcitybuild.events.PlayerPreWarpEvent import com.projectcitybuild.integrations.SpigotIntegration import com.projectcitybuild.pcbridge.core.contracts.PlatformLogger import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.plugin.Plugin class EssentialsIntegration( private val plugin: Plugin, private val logger: PlatformLogger, ) : Listener, SpigotIntegration { class EssentialsAPINotFoundException : Exception("Essentials plugin not found") private var essentials: Essentials? = null override fun onEnable() { val anyPlugin = plugin.server.pluginManager.getPlugin("Essentials") if (anyPlugin == null) { logger.fatal("Cannot find EssentialsX plugin. Disabling integration") return } if (anyPlugin !is Essentials) { logger.fatal("Found EssentialsX plugin but cannot access API") throw EssentialsAPINotFoundException() } logger.info("Essentials integration enabled") essentials = anyPlugin } override fun onDisable() { if (essentials != null) { essentials = null } } /** * Sets the player's current position as their last known location * in Essentials */ @EventHandler fun onPlayerPreWarp(event: PlayerPreWarpEvent) { val essentials = essentials ?: return essentials .getUser(event.player) .setLastLocation() logger.verbose("Registered last location for ${event.player.name} with Essentials") } }
9
Kotlin
0
3
8d28ab2bd10ef2dde00d7d5772ff0a5ea94c0a2b
1,704
PCBridge
MIT License
app/src/main/java/me/hegj/wandroid/mvp/ui/adapter/CollectAdapter.kt
hegaojian
206,478,384
false
null
package me.hegj.wandroid.mvp.ui.adapter import android.text.Html import android.text.TextUtils import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.chad.library.adapter.base.util.MultiTypeDelegate import com.jess.arms.http.imageloader.glide.ImageConfigImpl import com.jess.arms.utils.ArmsUtils import me.hegj.wandroid.R import me.hegj.wandroid.app.weight.CollectView import me.hegj.wandroid.mvp.model.entity.CollectResponse class CollectAdapter(data: ArrayList<CollectResponse>?) : BaseQuickAdapter<CollectResponse, BaseViewHolder>(data) { private var mOnCollectViewClickListener: OnCollectViewClickListener? = null private val Ariticle = 1//文章类型 private val Project = 2//项目类型 本来打算不区分文章和项目布局用统一布局的,但是布局完以后发现差异化蛮大的,所以还是分开吧 init { //初始化 multiTypeDelegate = object : MultiTypeDelegate<CollectResponse>() { override fun getItemType(entity: CollectResponse): Int { //根据是否有图片 判断为文章还是项目,好像有点low的感觉。。。我看实体类好像没有相关的字段,就用了这个,也有可能是我没发现 return if (TextUtils.isEmpty(entity.envelopePic)) Ariticle else Project } } //注册多布局 multiTypeDelegate .registerItemType(Ariticle, R.layout.item_ariticle) .registerItemType(Project, R.layout.item_project) } override fun convert(helper: BaseViewHolder, item: CollectResponse?) { if (item != null) { when (helper.itemViewType) { Ariticle -> { //文章布局的赋值 item.run{ helper.setText(R.id.item_home_author, if(author.isEmpty()) "匿名用户" else author) helper.setText(R.id.item_home_content, Html.fromHtml(title)) helper.setText(R.id.item_home_type2, Html.fromHtml(chapterName)) helper.setText(R.id.item_home_date, niceDate) helper.getView<CollectView>(R.id.item_home_collect).isChecked = true //隐藏所有标签 helper.setGone(R.id.item_home_top, false) helper.setGone(R.id.item_home_type1, false) helper.setGone(R.id.item_home_new, false) } helper.getView<CollectView>(R.id.item_home_collect).setOnCollectViewClickListener(object : CollectView.OnCollectViewClickListener { override fun onClick(v: CollectView) { mOnCollectViewClickListener?.onClick(helper, v, helper.adapterPosition) } }) } Project -> { //项目布局的赋值 item.run{ helper.setText(R.id.item_project_author, if(author.isEmpty()) "匿名用户" else author) helper.setText(R.id.item_project_title, Html.fromHtml(title)) helper.setText(R.id.item_project_content, Html.fromHtml(desc)) helper.setText(R.id.item_project_type, Html.fromHtml(chapterName)) helper.setText(R.id.item_project_date, niceDate) //隐藏所有标签 helper.setGone(R.id.item_project_top, false) helper.setGone(R.id.item_project_type1, false) helper.setGone(R.id.item_project_new, false) helper.getView<CollectView>(R.id.item_project_collect).isChecked = true ArmsUtils.obtainAppComponentFromContext(mContext).imageLoader().loadImage(mContext.applicationContext, ImageConfigImpl .builder() .url(envelopePic) .imageView(helper.getView(R.id.item_project_imageview)) .isCrossFade(true) .imageRadius(8) .build() ) } helper.getView<CollectView>(R.id.item_project_collect).setOnCollectViewClickListener(object : CollectView.OnCollectViewClickListener { override fun onClick(v: CollectView) { mOnCollectViewClickListener?.onClick(helper, v, helper.adapterPosition) } }) } } } } fun setOnCollectViewClickListener(onCollectViewClickListener: OnCollectViewClickListener) { mOnCollectViewClickListener = onCollectViewClickListener } interface OnCollectViewClickListener { fun onClick(helper: BaseViewHolder, v: CollectView, position: Int) } }
1
null
100
713
622016c9695c01f3a134a23c4af1f76686aad6f1
4,834
WanAndroid
Apache License 2.0
cropper/src/main/kotlin/com/canhub/cropper/CropImageContractOptions.kt
CanHub
314,844,143
false
{"Kotlin": 264782}
package com.canhub.cropper import android.net.Uri @Deprecated( """ This ActivityResultContract is deprecated. Please either roll your own ActivityResultContract with the desired behavior or copy paste this. """, ) data class CropImageContractOptions( val uri: Uri?, val cropImageOptions: CropImageOptions, )
11
Kotlin
259
1,248
71c372b671b06dcba61b4804f1e6cc0e1cb1a66d
320
Android-Image-Cropper
Apache License 2.0
src/test/kotlin/com/statsradio/lambdas/tracing/LambdaTracingFactoryTest.kt
statsradio
205,160,037
false
null
package com.statsradio.lambdas.tracing import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isInstanceOf import com.statsradio.lambdas.contexts.env.TestEnvLoader import com.statsradio.tracing.Settings import com.statsradio.tracing.Tracer import com.statsradio.tracing.TracerFactory import io.mockk.clearMocks import io.mockk.every import io.mockk.mockk import org.apache.http.impl.client.HttpClientBuilder import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class LambdaTracingFactoryTest { private val tracerFactory = mockk<TracerFactory>() private val expectedTracer = mockk<Tracer>() @BeforeEach internal fun setUp() { clearMocks(expectedTracer, tracerFactory) } @Test fun `given no xray configuration, should create tracer only with sentry`() { val envLoader = TestEnvLoader(emptyMap()) every { tracerFactory.create(Settings(enableXRay = false, enableSentry = true)) } returns expectedTracer val tracer = LambdaTracingFactory(envLoader, tracerFactory).createTracer() assertThat(tracer).isEqualTo(expectedTracer) } @Test fun `given xray disabled, should create tracer only with sentry`() { val envLoader = TestEnvLoader(mapOf("XRAY_TRACING_ENABLED" to "false")) every { tracerFactory.create(Settings(enableXRay = false, enableSentry = true)) } returns expectedTracer val tracer = LambdaTracingFactory(envLoader, tracerFactory).createTracer() assertThat(tracer).isEqualTo(expectedTracer) } @Test fun `given xray enabled, should create tracer only both xray and sentry`() { val envLoader = TestEnvLoader(mapOf("XRAY_TRACING_ENABLED" to "true")) every { tracerFactory.create(Settings(enableXRay = true, enableSentry = true)) } returns expectedTracer val tracer = LambdaTracingFactory(envLoader, tracerFactory).createTracer() assertThat(tracer).isEqualTo(expectedTracer) } @Test fun `given no xray configuration, should create default apache http client builder`() { val envLoader = TestEnvLoader(emptyMap()) val httpClientBuilder = LambdaTracingFactory(envLoader, tracerFactory).createHttpClientBuilder() assertThat(httpClientBuilder).isInstanceOf(HttpClientBuilder::class) } @Test fun `given xray disabled, should create default apache http client builder`() { val envLoader = TestEnvLoader(mapOf("XRAY_TRACING_ENABLED" to "false")) val httpClientBuilder = LambdaTracingFactory(envLoader, tracerFactory).createHttpClientBuilder() assertThat(httpClientBuilder).isInstanceOf(HttpClientBuilder::class) } @Test fun `given xray enabled, should create xray proxied apache http client builder`() { val envLoader = TestEnvLoader(mapOf("XRAY_TRACING_ENABLED" to "true")) val httpClientBuilder = LambdaTracingFactory(envLoader, tracerFactory).createHttpClientBuilder() assertThat(httpClientBuilder).isInstanceOf(com.amazonaws.xray.proxies.apache.http.HttpClientBuilder::class) } }
6
Kotlin
0
2
df694704ffa1b704207d18596fc7d889ccabf49d
3,128
aws-lambda4j
MIT License
idea/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjector.kt
gigliovale
89,726,097
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.injection import com.intellij.codeInsight.AnnotationUtil import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiTreeUtil import org.intellij.plugins.intelliLang.Configuration import org.intellij.plugins.intelliLang.inject.InjectorUtils import org.intellij.plugins.intelliLang.inject.config.BaseInjection import org.intellij.plugins.intelliLang.inject.java.JavaLanguageInjectionSupport import org.intellij.plugins.intelliLang.util.AnnotationUtilEx import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import java.util.* class KotlinLanguageInjector : LanguageInjector { val kotlinSupport: KotlinLanguageInjectionSupport? by lazy { ArrayList(InjectorUtils.getActiveInjectionSupports()).filterIsInstance(KotlinLanguageInjectionSupport::class.java).firstOrNull() } override fun getLanguagesToInject(host: PsiLanguageInjectionHost, injectionPlacesRegistrar: InjectedLanguagePlaces) { if (!host.isValidHost) return val ktHost: KtElement = host as? KtElement ?: return if (!ProjectRootsUtil.isInProjectOrLibSource(ktHost)) return val injectionInfo = findInjectionInfo(host) ?: return val language = InjectorUtils.getLanguageByString(injectionInfo.languageId) ?: return injectionPlacesRegistrar.addPlace(language, TextRange.from(0, ktHost.textLength), injectionInfo.prefix, injectionInfo.suffix) } private fun findInjectionInfo(place: KtElement, originalHost: Boolean = true): InjectionInfo? { return injectWithExplicitCodeInstruction(place) ?: injectWithCall(place) ?: injectWithReceiver(place) ?: injectWithVariableUsage(place, originalHost) } private fun injectWithExplicitCodeInstruction(host: KtElement): InjectionInfo? { val support = kotlinSupport ?: return null val languageId = support.findAnnotationInjectionLanguageId(host) ?: return null return InjectionInfo(languageId, null, null) } private fun injectWithReceiver(host: KtElement): InjectionInfo? { val qualifiedExpression = host.parent as? KtDotQualifiedExpression ?: return null if (qualifiedExpression.receiverExpression != host) return null val callExpression = qualifiedExpression.selectorExpression as? KtCallExpression ?: return null val callee = callExpression.calleeExpression ?: return null if (isAnalyzeOff(qualifiedExpression.project)) return null for (reference in callee.references) { ProgressManager.checkCanceled() val resolvedTo = reference.resolve() if (resolvedTo is KtFunction) { val injectionInfo = findInjection(resolvedTo.receiverTypeReference, Configuration.getInstance().getInjections(KOTLIN_SUPPORT_ID)) if (injectionInfo != null) { return injectionInfo } } } return null } private fun injectWithVariableUsage(host: KtElement, originalHost: Boolean): InjectionInfo? { // Given place is not original host of the injection so we stop to prevent stepping through indirect references if (!originalHost) return null val ktHost: KtElement = host val ktProperty = host.parent as? KtProperty?: return null if (ktProperty.initializer != host) return null if (isAnalyzeOff(ktHost.project)) return null val searchScope = LocalSearchScope(arrayOf(ktProperty.containingFile), "", true) return ReferencesSearch.search(ktProperty, searchScope).asSequence().mapNotNull { psiReference -> val element = psiReference.element as? KtElement ?: return@mapNotNull null findInjectionInfo(element, false) }.firstOrNull() } private fun injectWithCall(host: KtElement): InjectionInfo? { val ktHost: KtElement = host val argument = ktHost.parent as? KtValueArgument ?: return null val callExpression = PsiTreeUtil.getParentOfType(ktHost, KtCallExpression::class.java) ?: return null val callee = callExpression.calleeExpression ?: return null if (isAnalyzeOff(ktHost.project)) return null for (reference in callee.references) { ProgressManager.checkCanceled() val resolvedTo = reference.resolve() if (resolvedTo is PsiMethod) { val injectionForJavaMethod = injectionForJavaMethod(argument, resolvedTo) if (injectionForJavaMethod != null) { return injectionForJavaMethod } } else if (resolvedTo is KtFunction) { val injectionForJavaMethod = injectionForKotlinCall(argument, resolvedTo) if (injectionForJavaMethod != null) { return injectionForJavaMethod } } } return null } private fun injectionForJavaMethod(argument: KtValueArgument, javaMethod: PsiMethod): InjectionInfo? { val argumentIndex = (argument.parent as KtValueArgumentList).arguments.indexOf(argument) val psiParameter = javaMethod.parameterList.parameters.getOrNull(argumentIndex) ?: return null val injectionInfo = findInjection(psiParameter, Configuration.getInstance().getInjections(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID)) if (injectionInfo != null) { return injectionInfo } val annotations = AnnotationUtilEx.getAnnotationFrom( psiParameter, Configuration.getProjectInstance(psiParameter.project).advancedConfiguration.languageAnnotationPair, true) if (annotations.size > 0) { return processAnnotationInjectionInner(annotations) } return null } private fun injectionForKotlinCall(argument: KtValueArgument, ktFunction: KtFunction): InjectionInfo? { val argumentIndex = (argument.parent as KtValueArgumentList).arguments.indexOf(argument) val ktParameter = ktFunction.valueParameters.getOrNull(argumentIndex) ?: return null val patternInjection = findInjection(ktParameter, Configuration.getInstance().getInjections(KOTLIN_SUPPORT_ID)) if (patternInjection != null) { return patternInjection } val injectAnnotation = ktParameter.findAnnotation(FqName(AnnotationUtil.LANGUAGE)) ?: return null val languageId = extractLanguageFromInjectAnnotation(injectAnnotation) ?: return null return InjectionInfo(languageId, null, null) } private fun findInjection(element: PsiElement?, injections: List<BaseInjection>): InjectionInfo? { for (injection in injections) { if (injection.acceptsPsiElement(element)) { return InjectionInfo(injection.injectedLanguageId, injection.prefix, injection.suffix) } } return null } private fun isAnalyzeOff(project: Project): Boolean { return Configuration.getProjectInstance(project).advancedConfiguration.dfaOption == Configuration.DfaOption.OFF } private class InjectionInfo(val languageId: String?, val prefix: String?, val suffix: String?) private fun processAnnotationInjectionInner(annotations: Array<PsiAnnotation>): InjectionInfo? { val id = AnnotationUtilEx.calcAnnotationValue(annotations, "value") val prefix = AnnotationUtilEx.calcAnnotationValue(annotations, "prefix") val suffix = AnnotationUtilEx.calcAnnotationValue(annotations, "suffix") return InjectionInfo(id, prefix, suffix) } }
1
null
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
8,610
kotlin
Apache License 2.0
idea/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjector.kt
gigliovale
89,726,097
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.injection import com.intellij.codeInsight.AnnotationUtil import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiTreeUtil import org.intellij.plugins.intelliLang.Configuration import org.intellij.plugins.intelliLang.inject.InjectorUtils import org.intellij.plugins.intelliLang.inject.config.BaseInjection import org.intellij.plugins.intelliLang.inject.java.JavaLanguageInjectionSupport import org.intellij.plugins.intelliLang.util.AnnotationUtilEx import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import java.util.* class KotlinLanguageInjector : LanguageInjector { val kotlinSupport: KotlinLanguageInjectionSupport? by lazy { ArrayList(InjectorUtils.getActiveInjectionSupports()).filterIsInstance(KotlinLanguageInjectionSupport::class.java).firstOrNull() } override fun getLanguagesToInject(host: PsiLanguageInjectionHost, injectionPlacesRegistrar: InjectedLanguagePlaces) { if (!host.isValidHost) return val ktHost: KtElement = host as? KtElement ?: return if (!ProjectRootsUtil.isInProjectOrLibSource(ktHost)) return val injectionInfo = findInjectionInfo(host) ?: return val language = InjectorUtils.getLanguageByString(injectionInfo.languageId) ?: return injectionPlacesRegistrar.addPlace(language, TextRange.from(0, ktHost.textLength), injectionInfo.prefix, injectionInfo.suffix) } private fun findInjectionInfo(place: KtElement, originalHost: Boolean = true): InjectionInfo? { return injectWithExplicitCodeInstruction(place) ?: injectWithCall(place) ?: injectWithReceiver(place) ?: injectWithVariableUsage(place, originalHost) } private fun injectWithExplicitCodeInstruction(host: KtElement): InjectionInfo? { val support = kotlinSupport ?: return null val languageId = support.findAnnotationInjectionLanguageId(host) ?: return null return InjectionInfo(languageId, null, null) } private fun injectWithReceiver(host: KtElement): InjectionInfo? { val qualifiedExpression = host.parent as? KtDotQualifiedExpression ?: return null if (qualifiedExpression.receiverExpression != host) return null val callExpression = qualifiedExpression.selectorExpression as? KtCallExpression ?: return null val callee = callExpression.calleeExpression ?: return null if (isAnalyzeOff(qualifiedExpression.project)) return null for (reference in callee.references) { ProgressManager.checkCanceled() val resolvedTo = reference.resolve() if (resolvedTo is KtFunction) { val injectionInfo = findInjection(resolvedTo.receiverTypeReference, Configuration.getInstance().getInjections(KOTLIN_SUPPORT_ID)) if (injectionInfo != null) { return injectionInfo } } } return null } private fun injectWithVariableUsage(host: KtElement, originalHost: Boolean): InjectionInfo? { // Given place is not original host of the injection so we stop to prevent stepping through indirect references if (!originalHost) return null val ktHost: KtElement = host val ktProperty = host.parent as? KtProperty?: return null if (ktProperty.initializer != host) return null if (isAnalyzeOff(ktHost.project)) return null val searchScope = LocalSearchScope(arrayOf(ktProperty.containingFile), "", true) return ReferencesSearch.search(ktProperty, searchScope).asSequence().mapNotNull { psiReference -> val element = psiReference.element as? KtElement ?: return@mapNotNull null findInjectionInfo(element, false) }.firstOrNull() } private fun injectWithCall(host: KtElement): InjectionInfo? { val ktHost: KtElement = host val argument = ktHost.parent as? KtValueArgument ?: return null val callExpression = PsiTreeUtil.getParentOfType(ktHost, KtCallExpression::class.java) ?: return null val callee = callExpression.calleeExpression ?: return null if (isAnalyzeOff(ktHost.project)) return null for (reference in callee.references) { ProgressManager.checkCanceled() val resolvedTo = reference.resolve() if (resolvedTo is PsiMethod) { val injectionForJavaMethod = injectionForJavaMethod(argument, resolvedTo) if (injectionForJavaMethod != null) { return injectionForJavaMethod } } else if (resolvedTo is KtFunction) { val injectionForJavaMethod = injectionForKotlinCall(argument, resolvedTo) if (injectionForJavaMethod != null) { return injectionForJavaMethod } } } return null } private fun injectionForJavaMethod(argument: KtValueArgument, javaMethod: PsiMethod): InjectionInfo? { val argumentIndex = (argument.parent as KtValueArgumentList).arguments.indexOf(argument) val psiParameter = javaMethod.parameterList.parameters.getOrNull(argumentIndex) ?: return null val injectionInfo = findInjection(psiParameter, Configuration.getInstance().getInjections(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID)) if (injectionInfo != null) { return injectionInfo } val annotations = AnnotationUtilEx.getAnnotationFrom( psiParameter, Configuration.getProjectInstance(psiParameter.project).advancedConfiguration.languageAnnotationPair, true) if (annotations.size > 0) { return processAnnotationInjectionInner(annotations) } return null } private fun injectionForKotlinCall(argument: KtValueArgument, ktFunction: KtFunction): InjectionInfo? { val argumentIndex = (argument.parent as KtValueArgumentList).arguments.indexOf(argument) val ktParameter = ktFunction.valueParameters.getOrNull(argumentIndex) ?: return null val patternInjection = findInjection(ktParameter, Configuration.getInstance().getInjections(KOTLIN_SUPPORT_ID)) if (patternInjection != null) { return patternInjection } val injectAnnotation = ktParameter.findAnnotation(FqName(AnnotationUtil.LANGUAGE)) ?: return null val languageId = extractLanguageFromInjectAnnotation(injectAnnotation) ?: return null return InjectionInfo(languageId, null, null) } private fun findInjection(element: PsiElement?, injections: List<BaseInjection>): InjectionInfo? { for (injection in injections) { if (injection.acceptsPsiElement(element)) { return InjectionInfo(injection.injectedLanguageId, injection.prefix, injection.suffix) } } return null } private fun isAnalyzeOff(project: Project): Boolean { return Configuration.getProjectInstance(project).advancedConfiguration.dfaOption == Configuration.DfaOption.OFF } private class InjectionInfo(val languageId: String?, val prefix: String?, val suffix: String?) private fun processAnnotationInjectionInner(annotations: Array<PsiAnnotation>): InjectionInfo? { val id = AnnotationUtilEx.calcAnnotationValue(annotations, "value") val prefix = AnnotationUtilEx.calcAnnotationValue(annotations, "prefix") val suffix = AnnotationUtilEx.calcAnnotationValue(annotations, "suffix") return InjectionInfo(id, prefix, suffix) } }
1
null
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
8,610
kotlin
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/RttOutlined.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/RttOutlined") package mui.icons.material @JsName("default") external val RttOutlined: SvgIconComponent
12
null
5
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
186
kotlin-wrappers
Apache License 2.0
src/commonMain/kotlin/BoardGraphicsState.kt
simenvg
340,636,770
false
null
import com.soywiz.korge.view.RoundRect class BoardGraphicsState(selectedCellView: RoundRect, row: Int, col: Int) { var selectedCellView = selectedCellView var row = row var col = col }
0
Kotlin
0
1
620806e13b4439b8b4441cf6c2bffb104964f555
197
kChess
MIT License
app/models/src/main/java/com/danielvilha/models/network/OpenWeatherApi.kt
danielvilha
403,757,694
false
{"Kotlin": 54460}
package com.danielvilha.models.network import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Created by <NAME> 27/01/2024. */ private const val BASE_URL = "https://api.openweathermap.org/data/3.0/" private val retrofit = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .baseUrl(BASE_URL) .build() object OpenWeatherApi { val retrofitService: OpenWeatherService by lazy { retrofit.create(OpenWeatherService::class.java) } }
0
Kotlin
0
0
935e784111731bdce57e4e46b10f1913d391dc22
655
kotlin-open-weather
The Unlicense
compiler/testData/diagnostics/tests/inference/pcla/fixationOnDemand/scopeNavigation/genericScopeOwner/GenericCallableReference.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// ISSUE: KT-71662 fun test() { val resultA = pcla { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation val callable = otvOwner.provide()::<!UNRESOLVED_REFERENCE!>memberFunction<!> <!DEBUG_INFO_MISSING_UNRESOLVED!>callable(TypeArgument)<!> // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(Interloper) } // expected: ScopeOwner<Value> <!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultA<!> // ISSUE: KT-72031 val resultB = <!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>pcla<!> { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation val callable = <!BUILDER_INFERENCE_STUB_RECEIVER!>otvOwner.provide()<!>::<!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>extensionFunction<!> callable(TypeArgument) // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(<!TYPE_MISMATCH!>Interloper<!>) } // expected: ScopeOwner<Value> <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE, DEBUG_INFO_EXPRESSION_TYPE("[Error type: Not found recorded type for pcla { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation val callable = otvOwner.provide()::extensionFunction callable(TypeArgument) // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(Interloper) }]")!>resultB<!> val resultC = pcla { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation val callable = otvOwner.provide()::<!UNRESOLVED_REFERENCE!>InnerKlass<!> <!DEBUG_INFO_MISSING_UNRESOLVED!>callable(TypeArgument)<!> // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(Interloper) } // expected: ScopeOwner<Value> <!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultC<!> val resultD = pcla { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation <!BUILDER_INFERENCE_STUB_RECEIVER!>otvOwner.provide()<!>::fix // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(Interloper) } // expected: ScopeOwner<Value> <!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultD<!> val resultE = pcla { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation <!BUILDER_INFERENCE_STUB_RECEIVER!>otvOwner.provide()<!>::accessorBackedReadableProperty // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(Interloper) } // expected: ScopeOwner<Value> <!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultE<!> val resultF = pcla { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation <!BUILDER_INFERENCE_STUB_RECEIVER!>otvOwner.provide()<!>::accessorBackedWriteableProperty // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(Interloper) } // expected: ScopeOwner<Value> <!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultF<!> val resultG = pcla { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation <!BUILDER_INFERENCE_STUB_RECEIVER!>otvOwner.provide()<!>::delegatedReadableProperty // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(Interloper) } // expected: ScopeOwner<Value> <!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultG<!> val resultH = pcla { otvOwner -> otvOwner.constrain(ScopeOwner(Value)) // should fix OTv := ScopeOwner<Value> for scope navigation <!BUILDER_INFERENCE_STUB_RECEIVER!>otvOwner.provide()<!>::delegatedWriteableProperty // expected: Interloper </: ScopeOwner<Value> otvOwner.constrain(Interloper) } // expected: ScopeOwner<Value> <!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultH<!> } class TypeVariableOwner<T> { fun constrain(subtypeValue: T) {} fun provide(): T = null!! } fun <OT> pcla(lambda: (TypeVariableOwner<OT>) -> Unit): OT = null!! interface BaseType object Value class ScopeOwner<SOT>(value: SOT): BaseType { fun <A> memberFunction(arg: A) {} inner class InnerKlass<C>(arg: C) companion object { fun <SOT> Nullable(value: SOT): ScopeOwner<SOT>? = null } } fun <SOTB, B> ScopeOwner<SOTB>.extensionFunction(arg: B) {} object TypeArgument fun <D> D.fix() {} val <E> E.accessorBackedReadableProperty: Value get() = Value var <F> F.accessorBackedWriteableProperty: Value get() = Value set(value) {} operator fun <X> X.getValue(reference: X, property: Any?): Value = Value operator fun <Y> Y.setValue(reference: Y, property: Any?, value: Value) {} val <G> G.delegatedReadableProperty: Value by Any() var <H> H.delegatedWriteableProperty: Value by Any() object Interloper: BaseType
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
5,146
kotlin
Apache License 2.0
src/main/kotlin/dev/arli/openapi/mapper/HeaderMapper.kt
alipovatyi
487,519,792
false
{"Kotlin": 451322}
package dev.arli.openapi.mapper import dev.arli.openapi.annotation.Header import dev.arli.openapi.model.HeaderComponent import dev.arli.openapi.model.HeaderObject import dev.arli.openapi.parser.HeaderNameParser import kotlin.reflect.KProperty import kotlin.reflect.full.findAnnotation internal class HeaderMapper( private val headerNameParser: HeaderNameParser = HeaderNameParser(), private val schemaComponentMapper: SchemaComponentMapper = SchemaComponentMapper() ) { fun map(property: KProperty<*>): HeaderComponent { val name = headerNameParser.parse(property) val headerAnnotation = requireNotNull(property.findAnnotation<Header>()) { "Header [$name] must be annotated with @Header annotation" } return HeaderObject( description = headerAnnotation.description, required = headerAnnotation.required, deprecated = headerAnnotation.deprecated, schema = schemaComponentMapper.map(property) ) } }
0
Kotlin
1
1
3637b43dc2e255f263b559a5a80ebf80f3e78d96
1,017
ktor-openapi
Apache License 2.0
src/nl/hannahsten/texifyidea/completion/pathcompletion/LatexPathProviderBase.kt
niknetniko
275,614,106
true
{"Gradle": 2, "Java Properties": 1, "Markdown": 7, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 3, "Kotlin": 530, "Java": 93, "TeX": 31, "BibTeX": 3, "INI": 1, "XML": 5, "JFlex": 2, "CODEOWNERS": 1, "SVG": 74, "HTML": 98, "Python": 1}
package nl.hannahsten.texifyidea.completion.pathcompletion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.util.PlatformIcons import com.intellij.util.ProcessingContext import nl.hannahsten.texifyidea.TexifyIcons import nl.hannahsten.texifyidea.completion.handlers.CompositeHandler import nl.hannahsten.texifyidea.completion.handlers.FileNameInsertionHandler import nl.hannahsten.texifyidea.completion.handlers.LatexReferenceInsertHandler import nl.hannahsten.texifyidea.lang.RequiredFileArgument import nl.hannahsten.texifyidea.util.files.findRootFile import nl.hannahsten.texifyidea.util.files.isLatexFile import java.io.File import java.util.regex.Pattern /** * @author <NAME> */ abstract class LatexPathProviderBase : CompletionProvider<CompletionParameters>() { private var parameters: CompletionParameters? = null private var resultSet: CompletionResultSet? = null private var validExtensions: Set<String>? = null private var absolutePathSupport = true companion object { private val TRIM_SLASH = Pattern.compile("/[^/]*$") } override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { this.parameters = parameters // We create a result set with the correct autocomplete text as prefix, which may be different when multiple LaTeX parameters (comma separated) are present val autocompleteText = processAutocompleteText(parameters.position.text) resultSet = result.withPrefixMatcher(autocompleteText) val parentCommand = context.get("type") if (parentCommand is RequiredFileArgument) { validExtensions = parentCommand.supportedExtensions absolutePathSupport = parentCommand.isAbsolutePathSupported } selectScanRoots(parameters.originalFile).forEach { addByDirectory(it, autocompleteText) } } /** * return a List of Paths to be searched in * eg. project root * eg. \includegraphics roots */ abstract fun selectScanRoots(file: PsiFile): Collection<VirtualFile> /** * enable folder search? */ abstract fun searchFolders(): Boolean /** * enable file search? */ abstract fun searchFiles(): Boolean /** * scan directory for completions */ private fun addByDirectory(baseDirectory: VirtualFile, autoCompleteText: String) { // Check if path is relative or absolute if (File(autoCompleteText).isAbsolute) { if (absolutePathSupport) { // Split text in path and completion text val pathOffset = trimAutocompleteText(autoCompleteText) addAbsolutePathCompletion(pathOffset) } } else { val pathOffset = trimAutocompleteText(autoCompleteText) addRelativePathCompletion(baseDirectory, pathOffset) } } /** * add completion entries for relative path */ private fun addRelativePathCompletion(projectDir: VirtualFile, pathOffset: String) { LocalFileSystem.getInstance().findFileByPath(projectDir.path + "/" + pathOffset)?.let { baseDir -> if (searchFolders()) { addFolderNavigations(pathOffset) getContents(baseDir, true).forEach { addDirectoryCompletion(pathOffset, it) } } if (searchFiles()) getContents(baseDir, false).forEach { addFileCompletion(pathOffset, it) } } } /** * add completion entries for absolute path */ private fun addAbsolutePathCompletion(baseDir: String) { LocalFileSystem.getInstance().findFileByPath(baseDir)?.let { dirFile -> if (searchFolders()) { addFolderNavigations(baseDir) getContents(dirFile, true).forEach { addDirectoryCompletion(baseDir, it) } } if (searchFiles()) getContents(dirFile, false).forEach { addFileCompletion(baseDir, it) } } } /** * add basic folder navigation options such as ../ and ./ */ private fun addFolderNavigations(baseDir: String) { // Add current directory. resultSet?.addElement( LookupElementBuilder.create("$baseDir./") .withPresentableText(".") .withIcon(PlatformIcons.PACKAGE_ICON) ) // Add return directory. resultSet?.addElement( LookupElementBuilder.create("$baseDir../") .withPresentableText("..") .withIcon(PlatformIcons.PACKAGE_ICON) ) } /** * add Directory to autocompletion dialog */ private fun addDirectoryCompletion(baseDir: String, foundFile: VirtualFile) { resultSet?.addElement( LookupElementBuilder.create(baseDir + foundFile.name + "/") .withPresentableText(foundFile.presentableName) .withIcon(PlatformIcons.PACKAGE_ICON) ) } /** * add file to autocompletion dialog */ private fun addFileCompletion(baseDir: String, foundFile: VirtualFile) { if (validExtensions != null) { if (validExtensions!!.contains(foundFile.extension).not()) return } val icon = TexifyIcons.getIconFromExtension(foundFile.extension) resultSet?.addElement( LookupElementBuilder.create(baseDir + foundFile.name) .withPresentableText(foundFile.presentableName) .withInsertHandler(CompositeHandler<LookupElement>( LatexReferenceInsertHandler(), FileNameInsertionHandler() )) .withIcon(icon) ) } /** * Get project roots * @return all Project Root directories as VirtualFile */ fun getProjectRoots(): ArrayList<VirtualFile> { val resultList = ArrayList<VirtualFile>() parameters?.apply { // Get base data. val baseFile = this.originalFile.virtualFile if (this.originalFile.isLatexFile()) { this.originalFile.findRootFile().containingDirectory?.virtualFile?.apply { resultList.add(this) } } else resultList.add(baseFile.parent) val rootManager = ProjectRootManager.getInstance(this.originalFile.project) rootManager.contentSourceRoots.asSequence() .filter { it != resultList.first() } .toSet() .forEach { resultList.add(it) } } return resultList } /** * @param autoCompleteText full path (relative or absolute) including the completion offset * @return path without autocompletion text including forward slash at end */ private fun trimAutocompleteText(autoCompleteText: String): String { return if (!autoCompleteText.contains("/")) { "" } else TRIM_SLASH.matcher(autoCompleteText).replaceAll("/") // delete last subpath occurence } /** * prepare auto-complete text before searching for files */ private fun processAutocompleteText(autocompleteText: String): String { var result = if (autocompleteText.endsWith("}")) { autocompleteText.substring(0, autocompleteText.length - 1) } else autocompleteText // When the last parameter is autocompleted, parameters before that may also be present in // autocompleteText so we split on commas and take the last one. If it is not the last // parameter, no commas will be present so the split will do nothing. result = result.replace("IntellijIdeaRulezzz", "") .split(",").last() // Prevent double ./ if (result.startsWith("./")) { result = result.substring(2) } // Prevent double / if (result.startsWith("//")) { result = result.substring(1) } return result } /** * search in given path for subfiles or directories */ private fun getContents(base: VirtualFile?, directory: Boolean): List<VirtualFile> { val contents = java.util.ArrayList<VirtualFile>() if (base == null) { return contents } for (file in base.children) { if (file.isDirectory == directory) { contents.add(file) } } return contents } }
0
null
0
0
ddb3790dd4eadf482caa511bbee1039dc4367d0a
9,219
TeXiFy-IDEA
MIT License
core/src/main/kotlin/com/example/core/sign/application/port/out/command/VerifyAuthenticationSuccessCommand.kt
PARKPARKWOO
737,782,254
false
{"Kotlin": 206755}
package com.example.core.sign.application.port.out.command import java.util.UUID data class VerifyAuthenticationSuccessCommand( val email: String, val authenticationString: UUID, )
8
Kotlin
0
0
01438f0d1e0edb69f179e54c7649e9e85dc5b7b0
191
health-trainer-backend
Apache License 2.0
app/src/androidTest/java/com/jnyakush/maktaba/ExampleInstrumentedTest.kt
nyumbapoa
275,025,035
false
null
package com.jnyakush.maktaba import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.jnyakush.maktaba", appContext.packageName) } }
1
Kotlin
0
0
d034cd1999d367d3b1d71a04a16bf2743fcc9e94
668
maktaba
MIT License
app/src/main/java/com/theandroidcoffee/bottomnavigation_multistack/contacts/ContactListFragment.kt
theandroidcoffee
309,079,727
false
null
/* * * * Copyright 2020, * * ☕ Marco Finadri - theandroidcoffee.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.theandroidcoffee.bottomnavigation_multistack.contacts import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.navigation.findNavController import androidx.recyclerview.widget.RecyclerView import com.theandroidcoffee.bottomnavigation_multistack.R import com.theandroidcoffee.bottomnavigation_multistack.databinding.FragmentContactListBinding import com.theandroidcoffee.bottomnavigation_multistack.databinding.ItemContactBinding import com.theandroidcoffee.bottomnavigation_multistack.model.Contact class ContactListFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = DataBindingUtil.inflate<FragmentContactListBinding>( inflater, R.layout.fragment_contact_list, container, false ) val contacts = listOf( Contact("Debra Espresso", R.drawable.person_1), Contact("Ben Doppio", R.drawable.person_2), Contact("Lara Lungo", R.drawable.person_3), Contact("John Ristretto", R.drawable.person_4), Contact("Jeanna Macchiato", R.drawable.person_5), Contact("Mary Corretto", R.drawable.person_6), Contact("Rachel Romano", R.drawable.person_7), Contact("Rick Cappuccino", R.drawable.person_8), Contact("Tara Affogato", R.drawable.person_9), Contact("Larry Marocchino", R.drawable.person_10) ) binding.contactsRecyclerView.apply { setHasFixedSize(true) adapter = PersonAdapter(contacts) } return binding.root } } class PersonAdapter(private val contacts: List<Contact>) : RecyclerView.Adapter<PersonAdapter.ViewHolder>() { companion object { const val CONTACT_KEY = "contact_key" } class ViewHolder(item: View) : RecyclerView.ViewHolder(item) { val binding = DataBindingUtil.bind<ItemContactBinding>(item) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder = ViewHolder( DataBindingUtil.inflate<ItemContactBinding>( LayoutInflater.from(parent.context), R.layout.item_contact, parent, false ).root ) override fun onBindViewHolder(holder: ViewHolder, position: Int) { val contact = contacts[position] val binding = holder.binding if (binding != null) { binding.contactNameTextView.text = contact.name binding.contactImageView.setImageResource(contact.imageId) binding.root.setOnClickListener { val bundle = bundleOf(CONTACT_KEY to contact) holder.itemView.findNavController() .navigate(R.id.action_contactListFragment_to_contactFragment, bundle) } } } override fun getItemCount(): Int = contacts.size }
0
Kotlin
0
1
8d31f83e0138dfc47be59b2aa42207fa27d2afac
3,445
BottomNavigation_MultiStack
Apache License 2.0
week10/bankClass.kt
AleS2478
747,264,223
false
{"Kotlin": 10185}
class BankAccount( val accountNumber: String, val balance: Int, val ownerName: String ) fun main(){ val c1 = BankAccount ("123456789123", 500, "<NAME>") println(c1.accountNumber) println(c1.balance) println(c1.ownerName) }
0
Kotlin
0
0
c61a496d6f2fc590d874beb378448b6a5138c4c5
251
Kotlin
MIT License
api/src/test/kotlin/com/seedcompany/cordtables/up/UpPrayerRequestsTestSuite.kt
CordField
409,237,733
false
null
package com.seedcompany.cordtables.up import com.seedcompany.cordtables.TestUtility import com.seedcompany.cordtables.admin.AdminPeopleTestUtility import com.seedcompany.cordtables.admin.AdminUsersTestUtility import com.seedcompany.cordtables.common.CommonLanguagesTestUtility import com.seedcompany.cordtables.components.tables.up.prayer_requests.* import com.seedcompany.cordtables.sil.SilLanguageIndexTestUtility import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.boot.web.server.LocalServerPort import org.springframework.test.context.DynamicPropertyRegistry import org.springframework.test.context.DynamicPropertySource import org.testcontainers.Testcontainers.exposeHostPorts import org.testcontainers.containers.GenericContainer import org.testcontainers.images.builder.ImageFromDockerfile import org.testcontainers.junit.jupiter.Container import org.testcontainers.junit.jupiter.Testcontainers import java.nio.file.Paths @Testcontainers @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class PrayerRequestsTestSuite( @LocalServerPort val port: Int, @Autowired val testUtil: TestUtility, @Autowired val usersUtil: AdminUsersTestUtility, @Autowired val silLanguageIndexUtil: SilLanguageIndexTestUtility, @Autowired val commonLanguagesTestUtility: CommonLanguagesTestUtility, @Autowired val adminPeopleTestUtility: AdminPeopleTestUtility, @Autowired val rest: TestRestTemplate, ) { companion object { val home = Paths.get("").toRealPath() val util = TestUtility() @Container val postgreSQLContainer: GenericContainer<Nothing> = GenericContainer<Nothing>(ImageFromDockerfile().withDockerfile(home.resolve("src/Dockerfile").toAbsolutePath())) .apply { withEnv("POSTGRES_USER", util.dbUser) withEnv("POSTGRES_PASSWORD", util.dbPassword) withEnv("POSTGRES_DB", util.dbDatabase) withEnv("POSTGRES_PORT", util.dbPort.toString()) }.withExposedPorts(util.dbPort) @DynamicPropertySource @JvmStatic fun registerDynamicProperties(registry: DynamicPropertyRegistry) { System.setProperty("DB_DOMAIN", util.dbDomain) System.setProperty("DB_DATABASE", util.dbDatabase) System.setProperty("DB_PORT", util.dbPort.toString()) System.setProperty("DB_USERNAME", util.dbUser) System.setProperty("DB_PASSWORD", util.dbPassword) System.setProperty("SERVER_URL", util.serverUrl) System.setProperty("SERVER_PORT", util.serverPort.toString()) System.setProperty("AWS_ACCESS_KEY_ID", util.awsAccessKey) System.setProperty("AWS_SECRET_ACCESS_KEY", util.awsSecret)+ System.setProperty("EMAIL_SERVER", util.emailServer) System.setProperty("NEO4J_URL", "asdfasdf") System.setProperty("NEO4J_USERNAME", "asdfasdf") System.setProperty("NEO4J_PASSWORD", "asdfasdf") System.setProperty("CORD_ADMIN_PASSWORD", util.cordAdminPassword) registry.add("cord.admin.password") { util.cordAdminPassword } registry.add("spring.datasource.username") { util.dbUser } registry.add("spring.datasource.password") { util.dbPassword } registry.add( "spring.datasource.jdbcUrl" ) { "jdbc:postgresql://localhost:${postgreSQLContainer.getMappedPort(util.dbPort)}/${util.dbDatabase}" } } } init { exposeHostPorts(port); } @Test fun `create prayer request`(){ val languageId = commonLanguagesTestUtility.`create common language`(port = port.toString()) val translator = adminPeopleTestUtility.`create admin people`(port = port.toString()) val prayerRequestCreateResponse = rest.postForEntity( "http://localhost:$port/up/prayer-requests/create", UpPrayerRequestsCreateRequest( token = usersUtil.getAdminToken(port = port.toString()), prayerRequest = prayerRequestInput( request_language_id = languageId, target_language_id = languageId, sensitivity = "Low", organization_name = "Test Organization", parent = null, translator = translator, location = "Texas", title = "Test Prayer Request", content = "Test Prayer Request Content", reviewed = true, prayer_type = "Request", ) ), UpPrayerRequestsCreateResponse::class.java ) assert(prayerRequestCreateResponse !== null) {"response was null"} assert(prayerRequestCreateResponse.body !== null) {"response body was null"} assert(prayerRequestCreateResponse.body!!.id !== null) {"response id was null"} } @Test fun `create prayer request from form`() { val ethCode = "eng" // create language first val silLangIndexId = silLanguageIndexUtil.`create sil language_index entry`(port = port.toString(), lang = ethCode) // create prayer entry val prayerCreateResponse = rest.postForEntity( "http://localhost:$port/up/prayer-requests/create-from-form", UpPrayerRequestsCreateFromFormRequest( token = usersUtil.getAdminToken(port = port.toString()), prayerForm = PrayerForm( creatorEmail = "creator_email@asdf.asdf", translatorEmail = "translator_email@asdf.asdf", ethCode = ethCode, sensitivity = "Low", location = "location", prayerType = "Request", title = "title", content = "content", ), ), UpPrayerRequestsCreateFromFormResponse::class.java, ) assert(prayerCreateResponse !== null) {"response was null"} assert(prayerCreateResponse.body !== null) {"response body was null"} assert(prayerCreateResponse.body!!.id !== null) {"response id was null"} } }
93
Kotlin
1
3
7e5588a8b3274917f9a5df2ffa12d27db23fb909
6,275
cordtables
MIT License
app/src/main/java/com/shentu/brvlinkagerecyclerview/bean/Wallpaper.kt
walkthehorizon
361,345,417
false
null
package com.shentu.brvlinkagerecyclerview.bean data class Wallpaper( val name: String = "name", val url: String = "https://wallpager-1251812446.cos.ap-beijing.myqcloud.com/image/7322/2a6a73383fb2eefc737284e63bff9f97cd41167d.jpg", val desc: String = "", )
1
Kotlin
2
1
ec965df8e1a7e9dfeca5e759d2d34b8fedd076bb
267
BrvLinkageRecyclerView
Apache License 2.0
app/src/main/java/ge/nnasaridze/messengerapp/scenes/chat/presentation/recycler/RecyclerMessageEntity.kt
nikushaa991
388,067,994
false
null
package ge.nnasaridze.messengerapp.scenes.chat.presentation.recycler data class RecyclerMessageEntity( var text: String, var timestamp: Long, var sent: Boolean, )
0
Kotlin
0
0
5fa22a79e9e7c7866afcad22cd6e511551f6bcde
175
Android-MessengerApp
MIT License
src/commonTest/kotlin/com/michaeltroger/latintocyrillic/ukrainian/UkrainianLatinToCyrillicTest.kt
michaeltroger
415,145,615
false
{"Kotlin": 93788}
package com.michaeltroger.latintocyrillic.ukrainian import com.michaeltroger.latintocyrillic.Alphabet import com.michaeltroger.latintocyrillic.LatinCyrillic import com.michaeltroger.latintocyrillic.LatinCyrillicImpl import com.michaeltroger.latintocyrillic.runBlockingTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals internal class UkrainianCyrillicToLatinTest { private lateinit var converter: LatinCyrillic @BeforeTest fun setUp() { converter = LatinCyrillicImpl(Alphabet.UkrainianIso9) } @Test fun testEdgeCases() = runBlockingTest { assertEquals("", converter.cyrillicToLatin("")) assertEquals(".", converter.cyrillicToLatin(".")) assertEquals(",", converter.cyrillicToLatin(",")) assertEquals("!", converter.cyrillicToLatin("!")) assertEquals("?", converter.cyrillicToLatin("?")) } @Test fun testAlphabet() = runBlockingTest { // verified with: https://www.translitteration.com/transliteration/en/russian/iso-9/ assertEquals("""" A a B b V v G g G̀ g̀ D d E e Ê ê Ž ž Z z I i Ì ì Ï ï J j K k L l M m N n O o P p R r S s T t U u F f H h C c Č č Š š Ŝ ŝ ʹ Û û Â â """, converter.cyrillicToLatin( """" А а Б б В в Г г Ґ ґ Д д Е е Є є Ж ж З з И и І і Ї ї Й й К к Л л М м Н н О о П п Р р С с Т т У у Ф ф Х х Ц ц Ч ч Ш ш Щ щ ь Ю ю Я я """ )) } @Test fun testAlphabetFromTransliteration() = runBlockingTest { // verified with: https://www.translitteration.com/transliteration/en/russian/iso-9/ assertEquals( """" aabbvvggg̀g̀ddeeêêžžzziiììïïjjkkllmmnnoopprrssttuuffhhccččššŝŝûûââʹʹ’’ AABBVVGGG̀G̀DDEEÊÊŽŽZZIIÌÌÏÏJJKKLLMMNNOOPPRRSSTTUUFFHHCCČČŠŠŜŜÛÛÂÂ′’’ """, converter.cyrillicToLatin( """" аaбbвvгgґg̀дdеeєêжžзzиiіìїïйjкkлlмmнnоoпpрrсsтtуuфfхhцcчčшšщŝюûяâьʹ’’ АAБBВVГGҐG̀ДDЕEЄÊЖŽЗZИIІÌЇÏЙJКKЛLМMНNОOПPРRСSТTУUФFХHЦCЧČШŠЩŜЮÛЯÂ′’’ """ )) } }
0
Kotlin
2
2
33fe806cbba2f1bc7cb0784841883417a23df103
2,022
latin-to-cyrillic
MIT License
src/main/kotlin/com/sandrabot/sandra/commands/essential/Help.kt
sandrabot
121,549,855
false
{"Kotlin": 185578}
/* * Copyright 2017-2024 <NAME> and <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sandrabot.sandra.commands.essential import com.sandrabot.sandra.constants.Constants import com.sandrabot.sandra.constants.Emotes import com.sandrabot.sandra.constants.Unicode import com.sandrabot.sandra.entities.Category import com.sandrabot.sandra.entities.Command import com.sandrabot.sandra.events.CommandEvent import com.sandrabot.sandra.utils.asEmoji import dev.minn.jda.ktx.coroutines.await @Suppress("unused") class Help : Command(arguments = "[command]") { override suspend fun execute(event: CommandEvent) { if (event.argumentString.isNotEmpty()) { val command = event.arguments.command() // additionally respond with "not found" if the command can't or shouldn't be listed in /commands if (command == null || (command.ownerOnly && !event.isOwner) || command.category == Category.CUSTOM) { event.replyError(event.get("not_found")).setEphemeral(true).queue() return } // Begin putting the embed together, starting with the command path and category val readablePath = command.path.replace('.', ' ') val wordCommands = event.getAny("commands.commands.command_title") val author = "$readablePath • ${command.category.name.lowercase()} $wordCommands" // The command's category emote is used as the author image val emojiUrl = command.category.emote.asEmoji().asCustom().imageUrl val embed = event.embed.setAuthor(author).setThumbnail(emojiUrl) embed.setTitle(event.get("extra_help"), Constants.DIRECT_SUPPORT) // Retrieve the translation for the command's description, this time we need to not use the root val descriptionValue = "> ${event.getAny("commands.${command.path}.description")}" embed.addField("${Emotes.PROMPT} ${event.get("description_title")}", descriptionValue, false) // Display a field describing the command usage if there's any arguments if (command.arguments.isNotEmpty()) { // Combine all the arguments into a string to be displayed val joined = command.arguments.joinToString(" ") { it.usage } val usageValue = "> **/$readablePath** $joined" embed.addField("${Emotes.INFO} ${event.get("usage_title")}", usageValue, false) // Set the footer as well for context about arguments embed.setFooter(event.get("required_arguments")) } event.reply(embed.build()).setEphemeral(true).queue() return } event.deferReply(ephemeral = true).await() // If no arguments were supplied, just show information about the bot val lang = event.localeContext.withRoot("commands.help.info_embed") val embed = event.embed.setTitle(lang["title"]) embed.setThumbnail(event.selfUser.effectiveAvatarUrl) embed.addField(lang["configure", Emotes.CONFIG], lang["configure_content"], false) embed.addField(lang["commands", Emotes.COMMANDS], lang["commands_content"], false) val invite = if (event.sandra.settings.development) Constants.BETA_INVITE else Constants.DIRECT_INVITE embed.addField(lang["invite", Emotes.INVITE], lang["invite_content", invite], false) embed.addField(lang["support", Emotes.CHAT], lang["support_content", Constants.DIRECT_SUPPORT], false) val devs = Constants.DEVELOPERS.mapNotNull { event.retrieveUser(it)?.name }.toTypedArray() embed.setFooter(lang.get("built", Unicode.HEAVY_BLACK_HEART, *devs)) event.sendMessage(embed.build()).setEphemeral(true).queue() } }
1
Kotlin
3
9
de60e73553ca81daac1f111824b5573bc0233591
4,303
sandra
Apache License 2.0
app/src/test/java/com/rafaelds/swapi/data/model/planets/PlanetsDtoToPlanetListMapperTest.kt
themobilecoder
376,679,661
false
null
package com.rafaelds.swapi.data.model.planets import com.rafaelds.swapi.data.TestData.PLANET import com.rafaelds.swapi.data.TestData.PLANET_DTO import org.junit.Test import kotlin.test.assertEquals class PlanetsDtoToPlanetListMapperTest { private val planetsDtoToPlanetListMapper = PlanetsDtoToPlanetListMapper() @Test fun `should convert correctly dto with app uri`() { val planetsDTO = PlanetsDTO( count = 100, next = "", results = listOf(PLANET_DTO), previous = "" ) assertEquals(listOf(PLANET), planetsDtoToPlanetListMapper.convert(planetsDTO)) } }
0
Kotlin
0
3
b13f3b682c9701c2c64d6610950fb4d4f2b02725
645
swapi
MIT License
src/main/kotlin/component/TabMenu.kt
cybernetics
340,575,199
true
{"Kotlin": 11149}
package component import androidx.compose.animation.core.Animatable import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Path import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import helper.fitMaxWidth import helper.hoverIndicator import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch @Composable fun TabMenu( onSelectionChange: (Int) -> Unit, tabLabels: List<String>, horizontalArrangement: Arrangement.Horizontal = Arrangement.Center, ) { val primaryColor = MaterialTheme.colors.primary var selectedIndex by remember { mutableStateOf(0) } LaunchedEffect(selectedIndex) { onSelectionChange(selectedIndex) } Row( Modifier.fitMaxWidth().padding(horizontal = 4.dp).horizontalScroll(rememberScrollState()), horizontalArrangement = horizontalArrangement, verticalAlignment = Alignment.CenterVertically ) { Box { val widthList: SnapshotStateList<IntSize> = remember { mutableStateListOf(*(Array(tabLabels.size) { IntSize(0, 0) })) } Row(verticalAlignment = Alignment.CenterVertically) { tabLabels.forEachIndexed { i, it -> Tab(widthList, it, i) { selectedIndex = i } } } // Animation val xAnimator = remember { Animatable(0f) } val widthAnimator = remember { Animatable(0f) } LaunchedEffect(selectedIndex) { coroutineScope { launch { xAnimator.animateTo(widthList.take(selectedIndex).sumBy { it.width }.toFloat()) } launch { widthAnimator.animateTo(widthList[selectedIndex].width.toFloat()) } } } // Canvas drawing Canvas(Modifier.height(52.dp)) { val preSize = widthAnimator.value val x = xAnimator.value drawPath(Path().apply { moveTo(x, size.height - 2.dp.roundToPx()) lineTo(x, size.height) lineTo(x + preSize, size.height) lineTo(x + preSize, size.height - 2.dp.roundToPx()) close() }, color = primaryColor) } } } } @Composable fun Tab( widthList: SnapshotStateList<IntSize>, text: String, index: Int, onSelect: () -> Unit, ) { Box(Modifier .onSizeChanged { widthList[index] = it } .clickable { onSelect() } .hoverIndicator() .height(52.dp) .padding(16.dp) ) { Text(text, color = MaterialTheme.colors.onBackground) } }
0
null
0
0
12ffea35d2d98d546ad873cac6c0a818d02f6207
3,165
Compose-Tab-Component
MIT License
src/main/kotlin/com/github/myra/kmongo/Serializers.kt
MyraBot
405,667,559
false
{"Kotlin": 32420}
package com.github.myra.kmongo import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.awt.Color internal object ColorHexSerializer : KSerializer<Color> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("color_hex", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: Color) { val hex = String.format("#%06x", value.rgb and 0xFFFFFF) encoder.encodeString(hex) } override fun deserialize(decoder: Decoder): Color { return Color.decode(decoder.decodeString()) } }
0
Kotlin
0
0
e18ff207b8b256c4198d0e288d2c9e2b7bcb7347
818
kmongo
MIT License
src/Day05.kt
yeung66
574,904,673
false
{"Kotlin": 8143}
fun main() { fun initStacks() = listOf(ArrayDeque(), ArrayDeque("DBJV".toList()), ArrayDeque("PVBWRDF".toList()), ArrayDeque("RGFLDCWQ".toList()), ArrayDeque("WJPMLNDB".toList()), ArrayDeque("HNBPCSQ".toList()), ArrayDeque("RDBSNG".toList()), ArrayDeque("ZBPMQFSH".toList()), ArrayDeque("WLF".toList()), ArrayDeque("SVFMR".toList())) fun parse(input: String): List<List<Int>> { return input.lines().map { line -> val parts = line.split(" ") listOf(parts[1], parts[3], parts[5]).map { it.toInt() } }.toList() } fun part1(input: List<List<Int>>): String { val stacks = initStacks() input.forEach {op -> (1..op[0]).forEach { stacks[op[2]].addLast(stacks[op[1]].removeLast()) } } return stacks.filter { it.isNotEmpty() }.map { it.last() }.joinToString(separator = "") } fun part2(input: List<List<Int>>): String { val stacks = initStacks() input.forEach {op -> val temp = mutableListOf<Char>() (1..op[0]).forEach { temp.add(stacks[op[1]].removeLast()) } stacks[op[2]].addAll(temp.reversed()) } return stacks.filter { it.isNotEmpty() }.map { it.last() }.joinToString(separator = "") } val input = parse(readInput("5")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
554217f83e81021229759bccc8b616a6b270902c
1,423
advent-of-code-2022-kotlin
Apache License 2.0
MCAPI-client/src/main/kotlin/us/sodiumlabs/mcapi/client/Client.kt
napentathol
231,537,113
false
{"Gradle Kotlin DSL": 6, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Java Properties": 1, "Java": 14, "JSON": 3, "XML": 1, "Kotlin": 12, "INI": 1}
package us.sodiumlabs.mcapi.client import com.github.steveice10.mc.auth.exception.request.RequestException import com.github.steveice10.mc.protocol.MinecraftProtocol import com.github.steveice10.mc.protocol.data.SubProtocol import com.github.steveice10.mc.protocol.data.status.ServerStatusInfo import com.github.steveice10.mc.protocol.packet.login.server.LoginSuccessPacket import com.github.steveice10.mc.protocol.packet.status.server.StatusResponsePacket import com.github.steveice10.packetlib.Client import com.github.steveice10.packetlib.event.session.PacketReceivedEvent import com.github.steveice10.packetlib.event.session.SessionAdapter import com.github.steveice10.packetlib.packet.Packet import com.github.steveice10.packetlib.tcp.TcpSessionFactory import org.apache.logging.log4j.LogManager import us.sodiumlabs.mcapi.client.trackers.ErrorTracker import us.sodiumlabs.mcapi.client.trackers.MiscTracker import us.sodiumlabs.mcapi.client.trackers.ServerCommsTracker import us.sodiumlabs.mcapi.client.trackers.WorldTracker import us.sodiumlabs.mcapi.client.trackers.entity.EntityTracker import us.sodiumlabs.mcapi.client.utilities.HandlerChain import us.sodiumlabs.mcapi.client.utilities.HandlerLink import us.sodiumlabs.mcapi.common.Signing import java.time.Clock import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Future class Client(private val creds: Creds) { private val log = LogManager.getFormatterLogger() private lateinit var client: Client private lateinit var future: Future<Any> private val handler = HandlerChain() private val trackers = linkedMapOf<String, HandlerLink>() fun status(): Future<ServerStatusInfo> { val protocol = MinecraftProtocol(SubProtocol.STATUS) val client = Client(creds.host, creds.port, protocol, TcpSessionFactory()) val future = CompletableFuture<ServerStatusInfo>() client.session.addListener(object: SessionAdapter() { override fun packetReceived(event: PacketReceivedEvent) { if (event.getPacket<Packet>() is StatusResponsePacket) { val packet = event.getPacket<StatusResponsePacket>() future.complete(packet.info) } } }) client.session.connect() return future } fun init() { val protocol: MCAPIProtocol? try { protocol = MCAPIProtocol(creds.key) protocol.isUseDefaultListeners = false } catch (e: RequestException) { log.error("Caught request exception", e) e.printStackTrace() return } future = CompletableFuture() val signing = Signing(Clock.systemUTC()) client = Client(creds.host, creds.port, protocol, TcpSessionFactory()) client.session.addListener(MCAPIClientListener(SubProtocol.LOGIN, signing, creds.secret)) client.session.addListener(object : SessionAdapter() { override fun packetReceived(event: PacketReceivedEvent?) { if(event!!.getPacket<Packet>() is LoginSuccessPacket) { (future as CompletableFuture).complete(Any()) } } }) client.session.addListener(handler) } fun registerLink(key: String, tracker: HandlerLink) { trackers[key] = tracker handler.addLink(tracker) } fun registerDefaultTrackers() { registerLink("EntityTracker", EntityTracker()) registerLink("WorldTracker", WorldTracker()) registerLink("ServerCommsTracker", ServerCommsTracker()) registerLink("MiscTracker", MiscTracker()) registerLink("ErrorTracker", ErrorTracker()) } fun removeLink(key: String) { trackers.remove(key) handler.clearAllLinks() trackers.values.forEach { handler.addLink(it) } } @Suppress("UNCHECKED_CAST") fun <T: HandlerLink> queryLink(key: String): Optional<T> { return Optional.ofNullable(trackers[key]) as Optional<T> } fun addListener(sessionAdapter: SessionAdapter) { client.session.addListener(sessionAdapter) } fun removeListener(sessionAdapter: SessionAdapter) { client.session.removeListener(sessionAdapter) } fun connect() { client.session.connect() while (!future.isDone) { Thread.sleep(100) } } fun disconnect() { client.session.disconnect("Shutting down.") } fun send(packet: Packet) { client.session.send(packet) } } data class Creds(val host: String, val port: Int, val key: String, val secret: String)
0
Kotlin
1
0
2bde7d3dc2b5f4f01cbb624df7610b3d120d8a30
4,704
MCAPI
MIT License
src/test/kotlin/com/target/liteforjdbc/HikariDataSourceFactoryTest.kt
target
530,689,815
false
{"Kotlin": 225123}
package com.target.liteforjdbc import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class HikariDataSourceFactoryTest { @Test fun `Test dataSource`() { val config = DbConfig( type = DbType.POSTGRES, jdbcUrl = "JDBC:", username = "user", password = "<PASSWORD>", databaseName = "dbName", ssl = true, connectionTimeoutMillis = 1000, idleTimeoutMillis = 2000, keepAliveTime = 3000, maxLifetime = 4000, minimumIdle = 1, maximumPoolSize = 10, dataSourceProperties = listOf( DataSourceProperty("propName", "propValue"), DataSourceProperty("otherPropName", "otherPropValue") ) ) val result = buildHikariDataSource(config) result.jdbcUrl shouldBe "JDBC:" result.connectionTimeout shouldBe 1000 result.idleTimeout shouldBe 2000 result.keepaliveTime shouldBe 3000 result.maxLifetime shouldBe 4000 result.minimumIdle shouldBe 1 result.maximumPoolSize shouldBe 10 result.username shouldBe "user" result.password shouldBe "<PASSWORD>" result.dataSourceProperties.size shouldBe 2 result.dataSourceProperties.getProperty("propName") shouldBe "propValue" result.dataSourceProperties.getProperty("otherPropName") shouldBe "otherPropValue" } }
8
Kotlin
10
16
2682f48a8602d39e37113b9b2573ae9d1c74fb34
1,481
lite-for-jdbc
MIT License
analysis/analysis-api-fe10/src/org/jetbrains/kotlin/analysis/api/descriptors/symbols/psiBased/KtFe10PsiTypeParameterSymbol.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.descriptors.symbols.psiBased import org.jetbrains.kotlin.analysis.api.descriptors.KtFe10AnalysisSession import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.toKtType import org.jetbrains.kotlin.analysis.api.descriptors.symbols.pointers.KtFe10NeverRestoringSymbolPointer import org.jetbrains.kotlin.analysis.api.descriptors.symbols.psiBased.base.KtFe10PsiSymbol import org.jetbrains.kotlin.analysis.api.descriptors.utils.cached import org.jetbrains.kotlin.analysis.api.symbols.KtTypeParameterSymbol import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtPsiBasedSymbolPointer import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.analysis.api.withValidityAssertion import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.types.Variance internal class KtFe10PsiTypeParameterSymbol( override val psi: KtTypeParameter, override val analysisSession: KtFe10AnalysisSession ) : KtTypeParameterSymbol(), KtFe10PsiSymbol<KtTypeParameter, TypeParameterDescriptor> { override val descriptor: TypeParameterDescriptor? by cached { val bindingContext = analysisSession.analyze(psi) bindingContext[BindingContext.TYPE_PARAMETER, psi] } override val variance: Variance get() = withValidityAssertion { psi.variance } override val upperBounds: List<KtType> get() = withValidityAssertion { descriptor?.upperBounds?.map { it.toKtType(analysisSession) } ?: emptyList() } override val isReified: Boolean get() = withValidityAssertion { psi.hasModifier(KtTokens.REIFIED_KEYWORD) } override val name: Name get() = withValidityAssertion { psi.nameAsSafeName } override fun createPointer(): KtSymbolPointer<KtTypeParameterSymbol> = withValidityAssertion { return KtPsiBasedSymbolPointer.createForSymbolFromSource(this) ?: KtFe10NeverRestoringSymbolPointer() } }
182
null
5617
47,637
d257153a50bdaa761d54bbc9fd1c5d78a3769f0f
2,442
kotlin
Apache License 2.0
src/commonMain/kotlin/de/westermann/kobserve/list/SyncList.kt
pixix4
243,975,894
false
null
package de.westermann.kobserve.list import de.westermann.kobserve.base.ObservableList import de.westermann.kobserve.base.ObservableValue import de.westermann.kobserve.event.EventListener import dev.gitlive.difflib.DiffUtils fun<T> MutableList<T>.sync(other: List<T>) { val patch = DiffUtils.diff(this, other) for (delta in patch.getDeltas().asReversed()) { delta.applyTo(this) } } fun<T> ObservableValue<ObservableList<T>>.flattenListBinding(): ObservableList<T> { val list = observableListOf<T>() list.addAll(value) var handler: EventListener<*> = value.onChange.reference { list.sync(value) } onChange { handler.detach() list.sync(value) handler = value.onChange.reference { list.sync(value) } } return list } fun <T> ObservableValue<List<T>>.flatten() : ObservableList<T> { val list = observableListOf<T>() list.addAll(value) onChange { list.sync(value) } return list }
4
Kotlin
0
2
1f20731971a9b02f971f01ab8ae8f4e506ff542b
1,011
robolab-renderer
MIT License
demo/src/main/java/me/jessyan/mvparms/demo/mvp/model/api/cache/CommonCache.kt
petma
192,675,016
true
{"Kotlin": 331292}
/* * Copyright 2017 JessYan * * 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 me.jessyan.mvparms.demo.mvp.model.api.cache import java.util.concurrent.TimeUnit import io.reactivex.Observable import io.rx_cache2.DynamicKey import io.rx_cache2.EvictProvider import io.rx_cache2.LifeCache import io.rx_cache2.Reply import io.rx_cache2.internal.RxCache import me.jessyan.mvparms.demo.mvp.model.entity.User /** * ================================================ * 展示 [RxCache.using] 中需要传入的 Providers 的使用方式 * * * Created by JessYan on 08/30/2016 13:53 * [Contact me](mailto:<EMAIL>) * [Follow me](https://github.com/JessYanCoding) * ================================================ */ interface CommonCache { @LifeCache(duration = 2, timeUnit = TimeUnit.MINUTES) fun getUsers(users: Observable<List<User>>, idLastUserQueried: DynamicKey, evictProvider: EvictProvider): Observable<Reply<List<User>>> }
0
Kotlin
0
0
64ac1d9e092ef637f67b57a7effac7e0a6d029f9
1,437
MVPArms
Apache License 2.0
app/src/main/java/com/tc/gamegallery/domain/Genre.kt
JerbiJ456
804,320,356
false
{"Kotlin": 128407}
package com.tc.gamegallery.domain data class Genre( val name: String = "N/A" )
0
Kotlin
0
0
06425f3849a5ff4ec9162c8ce20dcab8e2b7a480
84
Game-Gallery
MIT License
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/Pageable.kt
jamiesanson
153,975,742
true
{"Gradle": 6, "YAML": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Java": 5, "Kotlin": 96, "JSON": 26}
package com.sys1yagi.mastodon4j.api class Pageable<T>(val part: List<T>, val link: Link?) { fun nextRange(limit: Int = 20): Range = Range(link?.maxId, limit = limit) fun prevRange(limit: Int = 20): Range = Range(sinceId = link?.sinceId, limit = limit) fun toRange(limit: Int = 20): Range = Range(maxId = link?.maxId, sinceId = link?.sinceId, limit = limit) }
0
Kotlin
0
0
33907ff18c18b5225c6b49557264f32996317ab1
372
mastodon4j
MIT License
feature/funding/link/src/main/kotlin/app/k9mail/feature/funding/FeatureFundingModule.kt
thunderbird
1,326,671
false
{"Kotlin": 5319476, "Java": 2152605, "Python": 23566, "Shell": 2768, "AIDL": 1946}
package app.k9mail.feature.funding import app.k9mail.feature.funding.api.FundingManager import app.k9mail.feature.funding.api.FundingNavigation import app.k9mail.feature.funding.link.LinkFundingManager import app.k9mail.feature.funding.link.LinkFundingNavigation import org.koin.dsl.module val featureFundingModule = module { single<FundingManager> { LinkFundingManager() } single<FundingNavigation> { LinkFundingNavigation() } }
871
Kotlin
2492
10,524
8a342003bce092e7e501814dada4eb9118ff45a5
440
thunderbird-android
Apache License 2.0
app/src/main/java/com/zigis/paleontologas/features/launcher/stories/main/LauncherView.kt
edgar-zigis
240,962,785
false
{"Kotlin": 166682}
package com.zigis.paleontologas.features.launcher.stories.main import android.content.Context import android.widget.Toast import com.zigis.paleontologas.core.architecture.BaseView import com.zigis.paleontologas.databinding.ViewLauncherBinding class LauncherView(context: Context) : BaseView<LauncherViewState, ViewLauncherBinding>(context) { override var binding: ViewLauncherBinding? = ViewLauncherBinding.inflate(layoutInflater) init { addView(requireBinding().root) } override fun render(state: LauncherViewState) { state.errorMessage?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } } }
0
Kotlin
16
122
81af233ad89b9ec192e466d6604f211720a65445
665
Paleontologas
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/ui/list/PuppyList.kt
kingsleyadio
427,661,601
false
{"Kotlin": 32994}
package com.example.androiddevchallenge.ui.list import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Pets import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.data.PhotoInfo import com.example.androiddevchallenge.data.Puppy import com.example.androiddevchallenge.ui.theme.elevated import com.google.accompanist.coil.rememberCoilPainter import com.google.accompanist.imageloading.ImageLoadState import com.google.accompanist.insets.LocalWindowInsets import com.google.accompanist.insets.statusBarsPadding /** * @author <NAME> * @since 02 Mar, 2021 */ @Composable fun PuppyList(puppies: List<Puppy>, onClick: (Puppy) -> Unit) { Scaffold( modifier = Modifier.fillMaxSize(), topBar = { val backgroundColor = MaterialTheme.colors.primarySurface.elevated(4.dp) Column( modifier = Modifier .clip(RoundedCornerShape(bottomStart = 16.dp, bottomEnd = 16.dp)) .background(backgroundColor) ) { TopAppBar( backgroundColor = Color.Transparent, contentColor = contentColorFor(backgroundColor), elevation = 0.dp, title = { Icon(imageVector = Icons.Outlined.Pets, contentDescription = "Puppies") Spacer(modifier = Modifier.size(16.dp)) Text(text = "Compose Puppy") }, modifier = Modifier.statusBarsPadding() ) } } ) { val navHeight = with(LocalDensity.current) { LocalWindowInsets.current.navigationBars.bottom.toDp() } LazyColumn( contentPadding = PaddingValues(8.dp, 8.dp, 8.dp, navHeight), verticalArrangement = Arrangement.spacedBy(8.dp) ) { items(puppies) { puppy -> PuppyItem( puppy, modifier = Modifier .clickable { onClick(puppy) } ) } } } } @Composable fun PuppyItem(puppy: Puppy, modifier: Modifier = Modifier) { Card( backgroundColor = MaterialTheme.colors.background, elevation = 2.dp, modifier = modifier.fillMaxWidth() ) { Row( modifier = modifier .fillMaxWidth() .padding(16.dp) ) { Box(Modifier.wrapContentSize()) { val imagePainter = rememberCoilPainter( request = puppy.photos[0].small ) Image( painter = imagePainter, contentDescription = puppy.name, contentScale = ContentScale.Crop, modifier = Modifier .size(84.dp) .border(4.dp, puppy.genderBgColor, CircleShape) .padding(2.dp) .clip(CircleShape) ) if (imagePainter.loadState is ImageLoadState.Loading) { CircularProgressIndicator(Modifier.align(Alignment.Center)) } } Column( verticalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() .padding(start = 16.dp) ) { Text(text = puppy.name, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.body1) Text( text = puppy.breed, maxLines = 1, overflow = TextOverflow.Ellipsis, color = LocalContentColor.current.copy(alpha = ContentAlpha.medium) ) Text( text = "${puppy.age} ${puppy.gender}", color = puppy.genderColor, style = MaterialTheme.typography.caption, modifier = Modifier .background(puppy.genderBgColor, RoundedCornerShape(8.dp)) .padding(vertical = 4.dp, horizontal = 12.dp) ) } Spacer(modifier = Modifier.height(8.dp)) } } } val photoUrl = "https://dl5zpyw5k3jeb.cloudfront.net/photos/pets/50687636/1/?bust=1614516620&width=300" val fakePuppy = Puppy( id = 0, url = "https://hello-world", breed = "Rotweiler", color = "White", age = "Young", gender = "Female", size = "Medium", coat = "Fur", name = "Buddie", description = "Lorem ipsum".repeat(20), listOf(PhotoInfo(photoUrl, photoUrl, photoUrl)), emptyList(), 1.7f ) @Preview @Composable fun Puppies() { PuppyList(puppies = (1..10).map { fakePuppy }, onClick = { /*TODO*/ }) } @Preview @Composable fun OnePuppy() { PuppyItem(puppy = fakePuppy) }
0
Kotlin
0
0
20af902ad1218b5c14f128bba8394a1cf06a7df3
5,879
compose-puppy
Apache License 2.0
kollect-core/src/main/kotlin/kollect/model/Model.kt
47degrees
118,812,251
false
null
package kollect import arrow.Kind import arrow.data.NonEmptyList sealed class KollectRequest /** * Reified operations to query a data source. You can kollect one, or many (batch). `I` stands for the Identity used to * perform the query. `A` would be the result. */ sealed class KollectQuery<I, A> : KollectRequest() { abstract val dataSource: DataSource<I, A> abstract val identities: NonEmptyList<I> data class KollectOne<I, A>(val id: I, val ds: DataSource<I, A>) : KollectQuery<I, A>() { override val identities: NonEmptyList<I> = NonEmptyList(id, emptyList()) override val dataSource: DataSource<I, A> = ds } data class Batch<I, A>(val ids: NonEmptyList<I>, val ds: DataSource<I, A>) : KollectQuery<I, A>() { override val identities: NonEmptyList<I> = ids override val dataSource: DataSource<I, A> = ds } } /** * Kollect query result states. */ sealed class KollectStatus { data class KollectDone<A>(val result: A) : KollectStatus() object KollectMissing : KollectStatus() } /** * Kollect query error types. */ sealed class KollectException { abstract val environment: Env data class MissingIdentity<I, A>(val i: I, val request: KollectQuery<I, A>, override val environment: Env) : KollectException() data class UnhandledException(val e: Throwable, override val environment: Env) : KollectException() fun toThrowable() = NoStackTrace(this) } /** * Ongoing request (currently in progress). */ data class BlockedRequest<F>(val request: KollectRequest, val result: (KollectStatus) -> Kind<F, Unit>) /* A map from data sources to blocked requests used to group requests to the same data source. */ data class RequestMap<F>(val m: Map<DataSource<Any, Any>, BlockedRequest<F>>) // [Kollect] result data type sealed class KollectResult<F, A> { data class Done<F, A>(val x: A) : KollectResult<F, A>() data class Blocked<F, A>(val rs: RequestMap<F>, val cont: Kollect<F, A>) : KollectResult<F, A>() data class Throw<F, A>(val e: (Env) -> KollectException) : KollectResult<F, A>() }
8
Kotlin
5
33
a72ee95996fc8537406dbc010afe8fd82984b14b
2,090
kollect
Apache License 2.0
app/src/main/java/com/arcieri/wagner/dictionary/feature_dictionary/data/local/entity/WordInfoEntity.kt
wagarcdev
509,314,266
false
null
package com.arcieri.wagner.dictionary.feature_dictionary.data.local.entity import androidx.room.Entity import androidx.room.PrimaryKey import com.arcieri.wagner.dictionary.feature_dictionary.domain.model.Meaning import com.arcieri.wagner.dictionary.feature_dictionary.domain.model.WordInfo @Entity data class WordInfoEntity( @PrimaryKey val id: Int? = null, val meanings: List<Meaning>, val phonetic: String, val sourceUrls: List<String>, val word: String ) { fun toWordInfo(): WordInfo { return WordInfo( meanings = meanings, phonetic = phonetic, sourceUrls = sourceUrls, word = word ) } }
0
Kotlin
0
1
2c96ae0f9b1b4e7739560b21a4c5c7b8c081508b
694
Dictionary
MIT License
src/main/kotlin/io/github/smaugfm/lunchmoney/request/budget/params/GetBudgetSummaryParams.kt
smaugfm
609,011,135
false
{"Kotlin": 190467, "Shell": 1786}
@file:UseSerializers(LocalDateSerializer::class, CurrencySerializer::class) package io.github.smaugfm.lunchmoney.request.budget.params import io.github.smaugfm.lunchmoney.serializer.CurrencySerializer import io.github.smaugfm.lunchmoney.serializer.LocalDateSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import java.time.LocalDate import java.util.Currency @Serializable internal data class GetBudgetSummaryParams( val startDate: LocalDate, val endDate: LocalDate, val currency: Currency? )
0
Kotlin
0
1
913a67b4f81302894a64ab1dacf6937e262a6831
556
lunchmoney
MIT License
src/jsMain/kotlin/net/kyori/adventure/webui/js/ExternalFunctions.kt
KyoriPowered
390,772,083
false
{"Kotlin": 91655, "HTML": 21526, "CSS": 6432}
// this entire file is everything that is bad about kotlin/js @file:Suppress("ClassName") package net.kyori.adventure.webui.js import kotlinx.browser.document import kotlinx.html.DIV import kotlinx.html.div import kotlinx.html.dom.create import kotlin.js.Json import kotlin.js.json // standard js methods public external fun decodeURIComponent(encodedURI: String): String public external fun encodeURIComponent(string: String): String // bulma toast public external class bulmaToast { public companion object { public fun toast(settings: Json) public fun setDefaults(settings: Json) } } public fun bulmaToast.Companion.toast(message: String, type: String = "is-success") { this.toast(json("message" to message, "type" to type)) } public inline fun bulmaToast.Companion.toast(type: String = "is-success", crossinline block: DIV.() -> Unit) { val element = document.create.div(block = block) this.toast(json("message" to element, "type" to type)) }
41
Kotlin
16
28
e8016f1f487d738a56ca52f79c431c7e2b7bb23f
990
adventure-webui
MIT License
vendor/tipkit/tipkit/src/main/kotlin/dev/bmcreations/tipkit/Tip.kt
code-payments
723,049,264
false
{"Kotlin": 2069923, "C": 198685, "C++": 83029, "Java": 52287, "Ruby": 4594, "Shell": 4515, "CMake": 2594}
package dev.bmcreations.tipkit import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import dev.bmcreations.tipkit.engines.EligibilityCriteria import dev.bmcreations.tipkit.engines.Event import dev.bmcreations.tipkit.engines.EventEngine import dev.bmcreations.tipkit.engines.TipsEngine import dev.bmcreations.tipkit.engines.Trigger import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.combine abstract class Tip( private val engine: EventEngine, private val tipEngine: TipsEngine ) { val name: String get() = this::class.java.simpleName.lowercase() // region flow control private var wasHidden: Boolean = false var flowPosition: Int = 0 var flowId: String? = null set(value) { if (value != null) { tipEngine.associateTipWithFlow(this, flowPosition, value) } field = value } val flow: List<Tip> get() = flowId?.let { tipEngine.flows[it] }.orEmpty() // endregion private val triggers = mutableListOf<Trigger>() private val events: Flow<List<Event.TriggerOccurrence>> get() { val flows = triggers.map { it.events } return combine(*flows.toTypedArray()) { it.toList().flatten() } } /** * Registers the [trigger] for watching events */ open fun await(trigger: Trigger) = triggers.add(trigger.copy(id = "$name-${trigger.id}")) // region UI configuration open fun asset(): @Composable () -> Unit = {} open fun title(): @Composable () -> Unit = {} open fun message(): @Composable () -> Unit = {} open fun image(): @Composable () -> Unit = {} open fun actions(): List<TipAction> = emptyList() // endregion /** * event stream for [triggers] */ open fun observe(): Flow<List<Event>> = events val flowContinuation: MutableSharedFlow<Unit> = MutableSharedFlow() /** * Eligibility criteria for whether this tip should show */ open suspend fun criteria(): List<EligibilityCriteria> = listOf { true } /** * Triggers a check of all [criteria] and if so, the Modifier will pass the [TipLocation] to the [TipProvider] * for display. */ suspend fun show(): Boolean { return criteria().all { it() } } /** * Whether or not this tip has been displayed */ suspend fun hasBeenSeen(): Boolean { if (flow.isNotEmpty()) { return wasHidden } return engine.isComplete(name) } /** * Marks the tip completed */ suspend fun dismiss() { if (flow.isNotEmpty()) { // if all other tips (not including this one) have been seen, then we can mark them all as hidden if (flow.all { it.hasBeenSeen() }) { engine.complete(name) } else { wasHidden = true // trigger show of next tip in flow flow.getOrNull(flowPosition + 1)?.flowContinuation?.emit(Unit) } } } } data class TipAction(val tipId: String, val id: String, val title: String) val TipDefaultAlignment: Alignment = Alignment.CenterStart val TipDefaultPadding: Dp = 8.dp
3
Kotlin
12
14
cdfa14fe252c817c0b6414a5aa64db0801036666
3,419
code-android-app
MIT License
app/src/main/java/earth/levi/app/store/NotificationsStore.kt
levibostian
640,550,940
false
null
package earth.levi.app.store import android.content.SharedPreferences import earth.levi.app.DiGraph import earth.levi.app.android.ShownNotification import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json val DiGraph.notificationsStore: NotificationsStore get() = NotificationsStore(sharedPreferences) class NotificationsStore(val sharedPreferences: SharedPreferences): KeyValueStorage(sharedPreferences) { // Android's NotificationManager has a property activeNotifications that tells you what notifications are shown on the device. But it's only available API >= 23. // We keep track of what notifications are shown and hidden ourselves for compatibility reasons. fun notificationShown(notification: ShownNotification) { val existingNotificationsShown = this.notificationsShown.toMutableList() existingNotificationsShown.add(notification) sharedPreferences.edit().putJson(Keys.NotificationShown.name, existingNotificationsShown).commit() } val notificationsShown: List<ShownNotification> get() = sharedPreferences.getFromJson(Keys.NotificationShown.name) ?: emptyList() fun removeNotificationShown(notification: ShownNotification) { val existingNotificationsShown = this.notificationsShown.toMutableList() existingNotificationsShown.remove(notification) sharedPreferences.edit().putJson(Keys.NotificationShown.name, existingNotificationsShown).commit() } }
7
Kotlin
0
0
f001dd86ce9c42220ce84272de8404b3fe888155
1,482
BatteryBird
MIT License
webservice/src/test/kotlin/com/noticemedan/dykkerdan/webservice/service/DiveServiceTest.kt
NoticeMeDan
285,365,234
false
null
package com.noticemedan.dykkerdan.webservice.service import com.noticemedan.dykkerdan.webservice.TestConfig import com.noticemedan.dykkerdan.webservice.dto.DiveInfo import com.noticemedan.dykkerdan.webservice.dto.DiverInfo import com.noticemedan.dykkerdan.webservice.exception.DiverNotFound import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.jupiter.api.assertThrows import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner import java.time.Instant import java.time.temporal.ChronoUnit @RunWith(SpringRunner::class) @SpringBootTest(classes = [TestConfig::class]) class DiveServiceTest { @Autowired private lateinit var diveService: DiveService @Autowired private lateinit var diverService: DiverService private fun createTestDiver (diverEmail: String): DiverInfo { return diverService.createDiver(DiverInfo(), diverEmail, "test") } private fun createTestDive (diverEmail: String): DiveInfo { return diveService.createDive(DiveInfo( buddyName = "testBuddy", diveNumber = 42, date = Instant.now(), location = "Månen", timeIn = Instant.now(), timeOut = Instant.now().plus(1, ChronoUnit.HOURS), startPressure = 200, endPressure = 70, maxDepth = 14, weight = 12, comment = "Smart smart, god kommentar", saltWater = true, freshWater = false, shoreDive = true, boatDive = false, visibility = "Omkring 5 meter", airTemp = 21, surfaceTemp = 20, bottomTemp = 14 ), diverEmail) } @Test fun createDive () { val diver = createTestDiver("test1") val dive = createTestDive(diver.email!!) assertThat(dive).isNotNull } @Test fun getDives () { val diver = createTestDiver("test2") createTestDive(diver.email!!) createTestDive(diver.email!!) val result = diveService.getDives(diver.email!!) assertThat(result).isNotNull assertThat(result.size).isEqualTo(2) } @Test fun getDive () { val diver = createTestDiver("test3") val dive = createTestDive(diver.email!!) val result = diveService.getDive(dive.id!!, diver.email!!) assertThat(result).isNotNull assertThat(result.id).isEqualTo(dive.id!!) } @Test fun updateDive () { val diver = createTestDiver("test4") val dive = createTestDive(diver.email!!) dive.maxDepth = 42 val result = diveService.updateDive(dive, diver.email!!) assertThat(result).isNotNull assertThat(result.id).isEqualTo(dive.id) assertThat(result.maxDepth).isEqualTo(42) } }
0
Kotlin
0
0
8e7b2f52386fe6e37e53a948013d5f419c60a24c
3,056
dykkerdan
MIT License
app/src/main/java/com/raywenderlich/android/runtracker/MVP.kt
JonnySueck
699,961,976
false
{"Kotlin": 19575}
package com.raywenderlich.android.runtracker import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.MutableLiveData import com.google.android.gms.maps.model.LatLng /* Creates info needed to render UI properly. Includes the distance the user walks, their current location, and the list of locations that the app recorded */ data class Ui( val formattedPace: String, val formattedDistance: String, val currentLocation: LatLng?, val userPath: List<LatLng> ) { companion object { val EMPTY = Ui( formattedPace = "", formattedDistance = "", currentLocation = null, userPath = emptyList() ) } class MapPresenter(private val activity: AppCompatActivity) { val ui = MutableLiveData(EMPTY) private val locationProvider = LocationProvider(activity) private val stepCounter = StepCounter(activity) private val permissionsManager = PermissionsManager(activity, locationProvider, stepCounter) fun onViewCreated() { // creates listener for LOCATIONS and updates the UI locationProvider.liveLocations.observe(activity) { locations -> val current = ui.value ui.value = current?.copy(userPath = locations) } // Creates listener for the CURRENT LOCATION and updates the UI locationProvider.liveLocation.observe(activity) { currentLocation -> val current = ui.value ui.value = current?.copy(currentLocation = currentLocation) } // Creates listener for the DISTANCE and updates the UI locationProvider.liveDistance.observe(activity) { distance -> val current = ui.value val formattedDistance = activity.getString(R.string.distance_value, distance) ui.value = current?.copy(formattedDistance = formattedDistance) } // Create listener for STEPS and update UI stepCounter.liveSteps.observe(activity) { steps -> val current = ui.value ui.value = current?.copy(formattedPace = "$steps") } } fun onMapLoaded() { permissionsManager.requestUserLocation() } fun startTracking() { locationProvider.trackUser() permissionsManager.requestActivityRecognition() } fun stopTracking() { locationProvider.stopTracking() stepCounter.unloadStepCounter() } } }
0
Kotlin
0
0
e9a84594e3bd322baa6aa0e1707cae6aee384087
2,593
Run-Tracker
The Unlicense
src/test/kotlin/org/overrun/ktwiki/test/TestWiki.kt
Over-Run
641,871,336
false
null
/* * MIT License * * Copyright (c) 2023 Overrun Organization * * 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. */ package org.overrun.ktwiki.test import org.overrun.ktwiki.* import org.overrun.ktwiki.theme.builtin.builtin import org.overrun.ktwiki.theme.builtin.color import org.overrun.ktwiki.theme.builtin.spoiler val indexID = PageID("_ktwiki_index", { when (it) { LANG_ZH_HANS -> "索引" else -> "Index" } }, { "" }) val downloadID = PageID("download", { when (it) { LANG_ZH_HANS -> "下载" else -> "Download" } }) val basicFunctionsID = PageID("basic_functions", { when (it) { LANG_ZH_HANS -> "基本函数" else -> "Basic functions" } }) val allFeaturesID = PageID("all_features", { when (it) { LANG_ZH_HANS -> "特性一览" else -> "All features" } }) /** * @author squid233 * @since 0.1.0 */ fun main() = builtin( indexID, orgName = "Overrun Organization", license = a(href = "https://github.com/Over-Run/ktwiki/blob/main/LICENSE", content = "MIT").toString(), source = "https://github.com/Over-Run/ktwiki" ) { site("ktwiki Wiki") { sidebar = sidebar { +links { +link { +relativeLink(indexID) } +link { +relativeLink(downloadID) } } +links { +link { +relativeLink(basicFunctionsID) } +link { +relativeLink(allFeaturesID) } } +links { +about { -"Other languages" } +link { pid -> +a(href = "${rootDir(pid, <EMAIL>)}$LANG_ZH_HANS/", content = "简体中文") } } } +builtinCss +page(indexID) { +"Welcome to ktwiki Wiki!" +("Introduction" to 2) +"ktwiki is a Kotlin DSL that allows you to generate your own wiki or pages." +"An official theme is available." +"Check the sidebar for more information." } +page(downloadID) { +("Download" to 1) +"You can download the source on ${a(href = "https://github.com/Over-Run/ktwiki", content = "GitHub")}." +"You need to use Java 17 and Kotlin 1.8.22 to run your generator." +("Add to Dependencies" to 2) +("Gradle" to 3) +"Simply add this code to your ${code("build.gradle")}:" !""" dependencies { implementation "io.github.over-run:ktwiki:+" } """.trimIndent() +("Maven" to 3) +"Simply add this code to your ${code("pom.xml")}:" !""" &lt;dependencies> &lt;dependency> &lt;groupId>io.github.over-run&lt;/groupId> &lt;artifactId>ktwiki&lt;/artifactId> &lt;version><i>The version</i>&lt;/version> &lt;/dependency> &lt;/dependencies> """.trimIndent() } +page(basicFunctionsID) { fun defFun(name: String) = +a(href = "#$name", content = h(2, "${code(name)}", id = name)) fun refFun(name: String) = a(href = "#$name", content = code(name), openInBlank = false) fun sign(content: String) { +("Signatures" to 3) !content } fun param(vararg params: Pair<String, String>) { +("Parameters" to 3) +ul { params.forEach { (name, desc) -> -"${code(name)}: $desc" } } } +("Basic functions" to 1) defFun("PageID") sign("PageID(id: String, name: (String) -> String, path: (String) -> String = { \"\${name(it)}/\" })") param( "id" to "An unique identifier of the page. For special pages, start with \"${code("_")}\".", "name" to "The name of the page for each language.", "path" to "The path of the page. Defaults to the name of the page." ) +"Creates a page ID." defFun("builtin") sign("${b("fun")} builtin(indexId: PageID, action: BuiltinTheme.() -> Unit)") param( "indexId" to "The ${refFun("PageID")} of the index.", "action" to "The code of the generator." ) +"Uses the builtin theme. Enables to use builtin stylesheet and templates." } +page(allFeaturesID) { +("All features" to 1) +("Heading 1" to 1) +("Heading 2" to 2) +("Heading 3" to 3) +("Heading 4" to 4) +("Heading 5" to 5) +("Heading 6" to 6) +"This is a paragraph" -"This is a literal text." -" Appending" !""" This is a code block. Another line """.trimIndent() +"We haven’t supported to highlighting yet." +codeBlock( """ ${color("#475F63", "1")} ${color("#546E7A", "/* This is a code block */")} ${color("#475F63", "2")} ${color("#C792EA", "void")} ${color("#82AAFF", "main")}() { ${ color("#546E7A", "System.out.") } ${color("#475F63", "3")} ${color("#82AAFF", "printf")}(${color("#C3E88D", "\"Hello world!\"")}); ${color("#475F63", "4")} } """.trimIndent(), style = "background-color:#263238;color:#89DDFF" ) +"sidebar and footer are added as ${code("div")}." +a(href = "https://github.com/Over-Run/overrungl", content = "A link that opens in a new tab") +a(href = "https://github.com/Over-Run/ktwiki", content = h(6, p("Another link with ${code("h6")}"))) +relativeLink(indexID, content = p("Jump to index").toString()) +relativeLink(allFeaturesID, content = "Cannot click (reference to this page)") +p { +spoiler("Just kidding") } +p { +b("BOLD") +i("ITALIC") +s("strikethrough") +u("underline") +strong("IMPORTANT TEXT") +em("emphasized text") } +p { +small("small text") +sup("2") +sub("n") } !"void ${del("mian")}${ins("main")}() {" +ul { -"Test" +b("Bold") +"Paragraph" } +ol { -"Test" +b("Bold") +"Paragraph" } } } site("ktwiki Wiki", lang = LANG_ZH_HANS) { sidebar = sidebar { +links { +link { +relativeLink(indexID, lang = <EMAIL>) } +link { +relativeLink(downloadID, lang = <EMAIL>) } } +links { +link { +relativeLink(basicFunctionsID, lang = <EMAIL>) } } +links { +about { -"其他语言" } +link { pid -> +a(href = rootDir(pid, <EMAIL>), content = "English (United States)") } } } +builtinCss +page(indexID) { +"欢迎来到 ktwiki Wiki!" +("介绍" to 2) +"ktwiki 是一个 Kotlin DSL,允许您生成自己的 wiki 或页面。" +"自带一个官方主题。" +"查看边栏了解更多信息。" } +page(downloadID) { +("下载" to 1) +"可在 ${a(href = "https://github.com/Over-Run/ktwiki", content = "GitHub")} 上下载源码。" +"您需要 Java 17 和 Kotlin 1.8.22 来运行生成器。" +("添加到依赖" to 2) +("Gradle" to 3) +"添加以下代码到 ${code("build.gradle")}:" !""" dependencies { implementation "io.github.over-run:ktwiki:+" } """.trimIndent() +("Maven" to 3) +"添加以下代码到 ${code("pom.xml")}:" !""" &lt;dependencies> &lt;dependency> &lt;groupId>io.github.over-run&lt;/groupId> &lt;artifactId>ktwiki&lt;/artifactId> &lt;version><i>版本</i>&lt;/version> &lt;/dependency> &lt;/dependencies> """.trimIndent() } +page(basicFunctionsID) { fun defFun(name: String) = +a(href = "#$name", content = h(2, "${code(name)}", id = name)) fun refFun(name: String) = a(href = "#$name", content = code(name), openInBlank = false) fun sign(content: String) { +("函数签名" to 3) !content } fun param(vararg params: Pair<String, String>) { +("参数" to 3) +ul { params.forEach { (name, desc) -> -"${code(name)}: $desc" } } } +("基本函数" to 1) defFun("PageID") sign("PageID(id: String, name: (String) -> String, path: (String) -> String = { \"\${name(it)}/\" })") param( "id" to "页面的唯一标识符。特殊页面以 \"${code("_")}\" 开头。", "name" to "页面每种语言的名称。", "path" to "页面的路径。默认为页面名称。" ) +"创建一个页面 ID。" defFun("builtin") sign("${b("fun")} builtin(indexId: PageID, action: BuiltinTheme.() -> Unit)") param( "indexId" to "索引页面的 ${refFun("PageID")}。", "action" to "生成器代码。" ) +"使用内置主题,启用内置样式表和模板。" } } }
0
Kotlin
0
0
e6212f4489624cf07d181cccac5c1570ed4ddaa8
10,322
ktwiki
MIT License
src/test/kotlin/com/jeayeob/coffeelog/controller/CoffeeControllerTest.kt
radic2510
664,984,356
false
null
package com.jeayeob.coffeelog.controller import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.jeayeob.coffeelog.dto.CoffeeCreateRequest import com.jeayeob.coffeelog.dto.CoffeeUpdateRequest import com.jeayeob.coffeelog.entity.Coffee import com.jeayeob.coffeelog.repository.CoffeeRepository import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.* import org.springframework.test.web.servlet.result.MockMvcResultHandlers.print import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @AutoConfigureMockMvc class CoffeeControllerTest @Autowired constructor( private val mockMvc: MockMvc, private val coffeeRepository: CoffeeRepository, ) { @AfterEach fun clean() { coffeeRepository.deleteAll() } @Test fun getCoffeeByName() { // given val coffeeName = "테스트원두1" val uri = "/coffee/$coffeeName" coffeeRepository.save(Coffee(name = coffeeName)) // when & then mockMvc.perform(get(uri)) .andExpect(status().isOk) .andExpect(jsonPath("$.name").value(coffeeName)) .andDo(print()) } @Test fun saveCoffee() { // given val uri = "/coffee" val request = CoffeeCreateRequest(name = "테스트원두1") val json = jacksonObjectMapper().writeValueAsString(request) // when mockMvc.perform( post(uri) .content(json) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk) .andExpect(jsonPath("$.name").value(request.name)) .andDo(print()) // then val coffee = coffeeRepository.findByName(request.name) .orElseThrow { throw Exception() } assertEquals(request.name, coffee.name) } @Test fun updateCoffee() { // given val targetCoffee = coffeeRepository.save(Coffee(name = "테스트원두1")) val uri = "/coffee" val request = CoffeeUpdateRequest(id = targetCoffee.id, name = "테스트원두2") val json = jacksonObjectMapper().writeValueAsString(request) // when mockMvc.perform( put(uri) .content(json) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk) .andExpect(jsonPath("$.name").value(request.name)) .andDo(print()) // then val coffee = coffeeRepository.findByName(request.name) .orElseThrow { throw Exception() } assertEquals(request.name, coffee.name) } @Test fun deleteCoffee() { // given coffeeRepository.save(Coffee(name = "테스트원두1")) val uri = "/coffee" val request = CoffeeCreateRequest(name = "테스트원두2") val json = jacksonObjectMapper().writeValueAsString(request) // when mockMvc.perform(get(uri)) .andExpect(status().isOk) .andDo(print()) // then assertEquals(true, coffeeRepository.findByName(request.name).isEmpty) //.orElse(null) } }
0
Kotlin
0
0
d96e843364766d93559dcc8d363df9c4a22d14a6
3,761
coffee-log
MIT License
app/test/mottak/StreamsTest.kt
navikt
768,053,576
false
{"Kotlin": 69244, "Dockerfile": 1027}
package mottak import io.micrometer.core.instrument.simple.SimpleMeterRegistry import lib.kafka.StreamsMock import mottak.enhet.EnhetService import mottak.enhet.NavEnhet import mottak.kafka.MottakTopology import mottak.kafka.Topics import no.nav.joarkjournalfoeringhendelser.JournalfoeringHendelseRecord import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import uk.org.webcompere.systemstubs.environment.EnvironmentVariables import uk.org.webcompere.systemstubs.jupiter.SystemStub import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension @ExtendWith(SystemStubsExtension::class) class StreamsTest { @SystemStub val naisCluster = EnvironmentVariables("NAIS_CLUSTER_NAME", "dev") @Test fun `Happy path oppretter sak og journalfører`() { val config = TestConfig() val kafka = setUpStreamsMock(config) val topics = Topics(config.kafka) val journalføringstopic = kafka.testTopic(topics.journalfoering) journalføringstopic.produce("1") { lagHendelseRecord() } assertTrue(BehandlingsflytFake.harOpprettetSak(123)) assertTrue(JoarkFake.harOppdatert(123, NavEnhet(NorgFake.ENHET_NR))) assertTrue(JoarkFake.harFerdigstilt(123)) } @Test fun `Filtrerer ut alt annet enn AAP`() { val config = TestConfig() val kafka = setUpStreamsMock(config) val topics = Topics(config.kafka) val journalføringstopic = kafka.testTopic(topics.journalfoering) journalføringstopic.produce("1") { lagHendelseRecord( nyttTema = "DAG" ) } assertFalse(BehandlingsflytFake.harOpprettetSak(123)) } private fun setUpStreamsMock(config: TestConfig): StreamsMock { val kafka = StreamsMock() val registry = SimpleMeterRegistry() val topology = MottakTopology( config, registry, SafFake, JoarkFake, BehandlingsflytFake, EnhetService( NorgFake, SkjermingFake, PdlFake ), ) kafka.connect( topology = topology(), config = config.kafka, registry = registry, ) return kafka } private fun lagHendelseRecord( id: String = "1", v: Int = 1, type: String = "", jpId: Long = 123L, gammeltTema: String = "AAP", nyttTema: String = "AAP", jpStatus: String = "MOTTATT", kanal: String = "NAV_NO", kanalRefId: String = "", behandlingTema: String = "" ) = JournalfoeringHendelseRecord.newBuilder().apply { hendelsesId = id versjon = v hendelsesType = type journalpostId = jpId temaGammelt = gammeltTema temaNytt = nyttTema journalpostStatus = jpStatus mottaksKanal = kanal kanalReferanseId = kanalRefId behandlingstema = behandlingTema }.build() }
1
Kotlin
0
0
a2a39287648c4eeec5543a57f4f0001e89fbfbb3
3,161
aap-mottak
MIT License
server/src/main/kotlin/ru/cororo/authserver/util/ProtocolUtils.kt
TheSirCororo
401,031,314
false
null
package ru.cororo.authserver.util import io.ktor.utils.io.* import io.ktor.utils.io.core.* import io.netty.buffer.ByteBuf import io.netty.buffer.Unpooled import net.kyori.adventure.nbt.* import net.kyori.adventure.text.Component import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer import java.io.ByteArrayOutputStream import java.io.DataOutputStream import java.io.IOException import java.nio.file.Files.readString import java.nio.file.Files.writeString import java.util.* import kotlin.experimental.and import kotlin.experimental.or fun ByteBuf.readVarInt(): Int { var numRead = 0 var result = 0 var read: Byte do { read = readByte() val value = (read and 127).toInt() result = result or (value shl 7 * numRead) numRead++ if (numRead > 5) { throw RuntimeException("VarInt is too big") } } while (read and 128.toByte() != 0.toByte()) return result } fun ByteBuf.writeVarInt(int: Int) { var value = int do { var temp = (value and 127).toByte() value = value ushr 7 if (value != 0) { temp = temp or 128.toByte() } writeByte(temp.toInt()) } while (value != 0) } fun ByteBuf.readVarLong(): Long { var value: Long = 0 var length = 0 var currentByte: Byte while (true) { currentByte = readByte() value = value or ((currentByte and 0x7F).toLong() shl length * 7) length += 1 if (length > 10) { throw RuntimeException("VarLong is too big") } if ((currentByte and 0x80.toByte()).toInt() != 0x80) { break } } return value } fun ByteBuf.writeVarLong(i: Long) { var value = i while (true) { if (value and 0x7F.inv() == 0L) { writeByte(value.toInt()) return } writeByte((value and 0x7F or 0x80).toInt()) // Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone value = value ushr 7 } } const val DEFAULT_MAX_STRING_SIZE = 65536 // 64KiB fun ByteBuf.readString(capacity: Int = DEFAULT_MAX_STRING_SIZE): String { val length = readVarInt() return readString(capacity, length) } fun ByteBuf.readString(capacity: Int, length: Int): String { check(length >= 0) { "Hot a negative-length string ($length)" } check(length <= capacity * 4) { "Bad string size (got $length, maximum is $capacity)" } // check(availableForRead >= length) { // "Trying to read a string that is too long (wanted $length, only have $availableForRead)" // } val string = String(Unpooled.copiedBuffer(readBytes(length)).array()) check(string.length <= capacity) { "Got a too-long string (got ${string.length}, max $capacity)" } return string } fun ByteBuf.writeString(string: String) { val bytes = string.toByteArray() writeVarInt(bytes.size) writeBytes(bytes) } fun ByteBuf.writeUUID(uuid: UUID) { writeLong(uuid.mostSignificantBits) writeLong(uuid.leastSignificantBits) } fun ByteBuf.writeComponent(component: Component) { writeString(GsonComponentSerializer.gson().serialize(component)) } fun ByteBuf.readComponent(): Component { return GsonComponentSerializer.gson().deserialize(readString()) } fun ByteBuf.readUUID(): UUID { return UUID(readLong(), readLong()) } fun ByteBuf.readByteArray(): ByteArray { val length: Int = readVarInt() return Unpooled.copiedBuffer(readBytes(length)).array() } fun ByteBuf.writeByteArray(array: ByteArray) { writeVarInt(array.size) writeBytes(array) } fun ByteBuf.writeStringArray(array: Array<String>) { writeVarInt(array.size) array.forEach { writeString(it) } } fun ByteBuf.writeNBT(nbt: CompoundBinaryTag) { val outputStream = ByteArrayOutputStream() BinaryTagIO.writer().write(nbt, outputStream) writeBytes(outputStream.toByteArray()) } fun ByteBuf.writeNBT(nbt: MutableMap.MutableEntry<String, CompoundBinaryTag>) { val outputStream = ByteArrayOutputStream() BinaryTagIO.writer().writeNamed(nbt, outputStream) writeBytes(outputStream.toByteArray()) } fun ByteBuf.writeTag(tag: BinaryTag) { writeTag("", tag) } fun ByteBuf.writeTag(name: String, tag: BinaryTag) { val bytes = ByteArrayOutputStream() val output = DataOutputStream(bytes) writeTag(name, tag, output) output.flush() writeBytes(bytes.toByteArray()) } private fun writeTag(name: String, tag: BinaryTag, output: DataOutputStream) { val type = tag.type() val nameBytes: ByteArray = name.toByteArray(Charsets.UTF_8) if (type == BinaryTagTypes.END) { throw IOException("Named TAG_End not permitted.") } output.writeByte(type.id().toInt()) output.writeShort(nameBytes.size) output.write(nameBytes) writeTagPayload(tag, output) } private fun writeTagPayload(tag: BinaryTag, output: DataOutputStream) { val type = tag.type() val bytes: ByteArray when (type) { BinaryTagTypes.BYTE -> output.writeByte((tag as ByteBinaryTag).value().toInt()) BinaryTagTypes.SHORT -> output.writeShort((tag as ShortBinaryTag).value().toInt()) BinaryTagTypes.INT -> output.writeInt((tag as IntBinaryTag).value()) BinaryTagTypes.LONG -> output.writeLong((tag as LongBinaryTag).value()) BinaryTagTypes.FLOAT -> output.writeFloat((tag as FloatBinaryTag).value()) BinaryTagTypes.DOUBLE -> output.writeDouble((tag as DoubleBinaryTag).value()) BinaryTagTypes.BYTE_ARRAY -> { bytes = (tag as ByteArrayBinaryTag).value() output.writeInt(bytes.size) output.write(bytes) } BinaryTagTypes.STRING -> { bytes = (tag as StringBinaryTag).value().toByteArray(Charsets.UTF_8) output.writeShort(bytes.size) output.write(bytes) } BinaryTagTypes.LIST -> { val listTag = tag as ListBinaryTag val tags = listTag.toList() output.writeByte(listTag.type().id().toInt()) output.writeInt(tags.size) for (child in tags) { writeTagPayload(child, output) } } BinaryTagTypes.COMPOUND -> { val map: Map<String, BinaryTag> = (tag as CompoundBinaryTag).associate { it.key to it.value } for ((key, value) in map) { writeTag(key, value, output) } output.writeByte(0) // end tag } BinaryTagTypes.INT_ARRAY -> { val ints = (tag as IntArrayBinaryTag).value() as IntArray output.writeInt(ints.size) for (value in ints) { output.writeInt(value) } } BinaryTagTypes.LONG_ARRAY -> { val longs = (tag as LongArrayBinaryTag).value() as LongArray output.writeInt(longs.size) for (value in longs) { output.writeLong(value) } } else -> throw IOException("Invalid tag type: $type.") } }
0
Kotlin
0
4
a82a3d64239128dd3dd84c4b9248ed08730d8ec7
7,100
AuthServer
Apache License 2.0