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
app/src/main/java/org/simple/clinic/registration/register/RegistrationLoadingEffect.kt
KelvnPere
310,601,209
true
{"Kotlin": 4452962, "Shell": 3616, "Python": 3162}
package org.simple.clinic.registration.register import org.simple.clinic.facility.Facility import org.simple.clinic.user.User sealed class RegistrationLoadingEffect object LoadRegistrationDetails: RegistrationLoadingEffect() data class RegisterUserAtFacility(val user: User, val facility: Facility): RegistrationLoadingEffect() object GoToHomeScreen: RegistrationLoadingEffect()
0
null
0
0
79b5055be07a4e9b46b84b0a157bb07f6cc254ad
384
simple-android
MIT License
flipted/app/src/main/java/edu/calpoly/flipted/ui/myProgress/missionDetails/CustomListAdapterTask.kt
CPSECapstone
337,579,565
false
null
package edu.calpoly.flipted.ui.myProgress.missionDetails import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ProgressBar import android.widget.TextView import androidx.core.content.ContextCompat import edu.calpoly.flipted.R import edu.calpoly.flipted.businesslogic.UidToStableId import edu.calpoly.flipted.businesslogic.missions.TaskStats class CustomListAdapterTask( private val layoutInflater: LayoutInflater, private val context: Context ) : BaseAdapter() { var data: List<TaskStats> = listOf() set(value) { field = value notifyDataSetChanged() } private val uidMap = UidToStableId<String>() override fun getCount(): Int { return data.size } override fun getItem(position: Int): TaskStats { return data[position] } override fun getItemId(position: Int): Long { return uidMap.getStableId(data[position].task.id) } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val fillInView = convertView ?: layoutInflater.inflate(R.layout.mission_progress_task_item, parent, false) val taskName: TextView = fillInView.findViewById(R.id.mission_task_name) val taskProgressBar: ProgressBar = fillInView.findViewById(R.id.mission_task_progress) val taskProgressText: TextView = fillInView.findViewById(R.id.mission_task_percent) val data = getItem(position) taskName.text = data.task.name if(data.submission != null){ val progressVal: Float = if(data.submission.pointsPossible == 0) { 100F } else { (data.submission.pointsAwarded.toFloat() / data.submission.pointsPossible.toFloat())*100 } if (progressVal <= 50){ taskProgressBar.progressDrawable = context.let { ContextCompat.getDrawable(it, R.drawable.progress_bar_failed) } } if (progressVal < 80 && progressVal >= 50){ taskProgressBar.progressDrawable = context.let { ContextCompat.getDrawable(it, R.drawable.progress_bar_almost_pass) } } taskProgressBar.progress = progressVal.toInt() val progressString = progressVal.toInt() taskProgressText.text = progressString.toString() + "%" } return fillInView } }
0
Kotlin
0
1
4e5449655bb0f75908e676279cad28e6297c5cb9
2,519
ambigouslyandroid
MIT License
app/src/main/kotlin/com/github/shchurov/gitterclient/presentation/ui/RoomView.kt
tantai96nd
96,689,551
false
null
package com.github.shchurov.gitterclient.presentation.ui import com.github.shchurov.gitterclient.domain.models.Message interface RoomView { fun getRoomId(): String fun getRoomName(): String fun setToolbarTitle(title: String) fun showInitLoading() fun hideInitLoading() fun enablePagingListener() fun disablePagingListener() fun showLoadingMore() fun hideLoadingMore() fun addMessages(messages: List<Message>) fun invalidateMessage(message: Message) fun hideKeyboard() fun showSendingInProgress() fun showSendingError() fun hideSendingInProgress() fun clearMessageEditText() fun addMessage(message: Message) }
0
Kotlin
0
1
4e65f404124986f9606bdab2b7040903085604a4
696
gitter-kotlin-client
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationapi/models/probationoffendersearch/ContactDetails.kt
ministryofjustice
572,524,532
false
{"Kotlin": 676647, "Python": 32511, "Shell": 13474, "Dockerfile": 1154, "Makefile": 684}
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.probationoffendersearch open class ContactDetails( open val addresses: List<Address>? = listOf(), )
0
Kotlin
1
2
dc4f9d559aa43e41ee9df5b1695c8f122674d3e9
167
hmpps-integration-api
MIT License
Retainer/app/src/main/java/com/example/dell/retainer/Content.kt
sad786
196,528,384
false
null
package com.example.dell.retainer import android.app.Activity import android.os.Bundle import android.widget.Toast import android.widget.TextView import java.io.* class Content:Activity() { override fun onCreate(savedInstance:Bundle?) { super.onCreate(savedInstance) this.setContentView(R.layout.activity_content) val textView = this.findViewById<TextView>(R.id.data) try { val file = File("file:///AndroidProjects/Retainer/info.txt") if(file.exists()) { val fin = FileReader(file) textView.text = fin.readText() fin.close() } else textView.text = "No Data Available" }catch(e:IOException){Toast.makeText(this,e.message,Toast.LENGTH_LONG).show()} } }
0
Kotlin
0
0
b87caf8ac3668f96629677ed5342b89ac151629a
826
AndroidProjects
MIT License
business/src/test/java/com/architecture/business/weather/WeatherUseCaseImplTest.kt
hoanggiang063
275,876,192
false
null
package com.architecture.business.weather import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.architecture.business.core.exception.BusinessException import com.architecture.business.core.exception.TechnicalException import com.architecture.business.core.exception.UnknownException import com.architecture.cleanmvvm.node1.demo.callback.WeatherCallBack import com.architecture.cleanmvvm.node1.demo.info.WeatherInfo import com.architecture.cleanmvvm.node1.demo.repository.WeatherRepository import com.architecture.cleanmvvm.node1.demo.usecase.WeatherRequest import com.architecture.cleanmvvm.node1.demo.usecase.WeatherUseCaseImpl import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.verify import kotlinx.coroutines.Dispatchers.Unconfined import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule import org.junit.runner.RunWith import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations import org.mockito.junit.MockitoJUnitRunner import kotlin.coroutines.CoroutineContext @RunWith(MockitoJUnitRunner::class) class WeatherUseCaseImplTest { @Rule @JvmField public var rule: TestRule = InstantTaskExecutorRule() @Mock lateinit var weatherUseCase: WeatherUseCaseImpl @Mock lateinit var weatherRepository: WeatherRepository val testContext: CoroutineContext = Unconfined @Before fun setUp() { MockitoAnnotations.initMocks(this) weatherUseCase = WeatherUseCaseImpl(weatherRepository) } @Test fun shouldCallbackSuccessWhenRepoReturnSuccessData() = runBlocking { doReturn(WeatherInfo()).`when`(weatherRepository).invoke() val callback = mockCallback<WeatherInfo>() excuseTest(callback) verify(callback).onSuccess(ArgumentMatchers.isA(WeatherInfo::class.java)) } @Test fun shouldCallbackFailByDeFaultWhenRepoReturnReturnFailByDeFault() = runBlocking { doAnswer { throw UnknownException() }.`when`(weatherRepository).invoke() val callback = mockCallback<WeatherInfo>() excuseTest(callback) verify(callback).onDefaultFail(any()) } @Test fun shouldCallbackFailByTechnicalWhenRepoReturnReturnFailTechnical() = runBlocking { doAnswer { throw TechnicalException() }.`when`(weatherRepository).invoke() val callback = mockCallback<WeatherInfo>() excuseTest(callback) verify(callback).onFailByTechnical(any()) } @Test fun shouldReturnCityNotFoundWhenRepoReturnReturnFailTechnical() = runBlocking { doAnswer { throw BusinessException() }.`when`(weatherRepository).invoke() val callback = mockCallback<WeatherInfo>() excuseTest(callback) verify(callback).onCityNotFound(any()) } private fun excuseTest(callback: WeatherCallBack<WeatherInfo>) { weatherUseCase.buildUseCase(WeatherRequest()) weatherUseCase.subscriberContext = testContext weatherUseCase.observerContext = testContext weatherUseCase.invoke(callback) } private fun <T> mockCallback(): WeatherCallBack<T> { return Mockito.mock(WeatherCallBack::class.java) as WeatherCallBack<T> } }
0
Kotlin
0
3
40ec6d77c381984dc178e01c990ef1a74fe85886
3,468
weatherdemo
Apache License 2.0
app/src/main/java/com/samuelokello/kazihub/presentation/common/components/EditTextField.kt
OkelloSam21
749,782,789
false
{"Kotlin": 326914}
package com.samuelokello.kazihub.presentation.shared.components import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun EditTextField( label: String? = null, value: String, onValueChange: (String) -> Unit, error: Boolean? = false, readOnly: Boolean? = false, singleLine: Boolean?, trailingIcon: @Composable (() -> Unit)? = null, keyboardOptions: KeyboardOptions, modifier: Modifier ) { OutlinedTextField( value = value, onValueChange = { onValueChange(it) }, label = { Text(text = label ?: "") }, // placeholder = { Text(text = label ?: "") }, keyboardOptions = keyboardOptions, isError = error ?: false, trailingIcon = trailingIcon, singleLine = singleLine ?: true, readOnly = readOnly ?: false, shape = RoundedCornerShape(10.dp), modifier = modifier.fillMaxWidth() ) }
0
Kotlin
0
0
6333e167c837eb9ae9d4549a09ca6ae621e12353
1,240
KaziHub
MIT License
Code/[7] Collections/mapOf Function/src/main.kt
SonarSystems
162,897,384
false
null
fun main(args: Array<String>) { var map: Map<Int, String> = mapOf<Int, String>(1 to "Hello", 20 to "World", 5 to "!!!"); println(map[20]); println(); for (key in map.keys) { println(map.get(key)); } println(); var nonGeneric = mapOf(10 to 5, "Hello" to "World"); for (key in nonGeneric.keys) { println(nonGeneric[key]); } }
0
Kotlin
5
4
7ff04b55314ac2e4f53838991fb26dba701b67a8
390
Kotlin-Programming-Series
The Unlicense
src/main/kotlin/me/youm/plumblossom/feature/module/ModuleCategory.kt
YOM667
587,803,127
false
null
package me.youm.plumblossom.feature.module /** * @author You_M */ enum class ModuleCategory { MOVEMENT,VISUAL,PLAYER,CLIENT,MISC }
0
Kotlin
0
5
33ba23757e4d0e2e0efcbe89d194c838736bcd19
137
PlumBlossomClient
Apache License 2.0
sample/composeApp/src/commonMain/kotlin/ru/sulgik/mapkit/sample/App.kt
SuLG-ik
813,953,018
false
{"Kotlin": 321441}
package ru.sulgik.mapkit.sample import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import ru.sulgik.mapkit.MapKit fun initMapKit() { MapKit.setApiKey(BuildKonfig.MAPKIT_API_KEY) } enum class NavItem { SELECTION, OLD_API, NEW_API_OBJECTS; companion object { val Saver: Saver<NavItem, Int> = Saver( save = { it.ordinal }, restore = { NavItem.entries[it] } ) } } @Composable fun App() { var navItem by rememberSaveable(stateSaver = NavItem.Saver) { mutableStateOf(NavItem.SELECTION) } NavHost(navItem, onNavigate = { navItem = it }, modifier = Modifier.fillMaxSize()) } @Composable fun NavHost( navItem: NavItem, onNavigate: (NavItem) -> Unit, modifier: Modifier = Modifier ) { when (navItem) { NavItem.SELECTION -> Selection(onNavigate, modifier) NavItem.OLD_API -> MapScreen(modifier) NavItem.NEW_API_OBJECTS -> NewMapScreen(modifier) } } @Composable fun Selection( onNavigate: (NavItem) -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { OutlinedButton( onClick = { onNavigate(NavItem.OLD_API) } ) { Text("Old api objects") } OutlinedButton( onClick = { onNavigate(NavItem.NEW_API_OBJECTS) } ) { Text("New api objects") } } }
0
Kotlin
1
17
2d292b701adb2c538f8cd3ddf614250f9d6a444d
2,107
yandex-mapkit-kmp
Apache License 2.0
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/others/RecycleFill.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.remix.remix.others 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.woowla.compose.icon.collections.remix.remix.OthersGroup public val OthersGroup.RecycleFill: ImageVector get() { if (_recycleFill != null) { return _recycleFill!! } _recycleFill = Builder(name = "RecycleFill", 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(19.561f, 12.099f) lineTo(21.093f, 14.75f) curveTo(22.059f, 16.424f, 21.486f, 18.565f, 19.812f, 19.531f) curveTo(19.279f, 19.838f, 18.676f, 20.0f, 18.062f, 20.0f) lineTo(15.999f, 20.0f) verticalLineTo(22.0f) lineTo(10.999f, 18.5f) lineTo(15.999f, 15.0f) verticalLineTo(17.0f) lineTo(18.062f, 17.0f) curveTo(18.149f, 17.0f, 18.236f, 16.977f, 18.312f, 16.933f) curveTo(18.524f, 16.81f, 18.612f, 16.555f, 18.532f, 16.332f) lineTo(18.494f, 16.25f) lineTo(16.963f, 13.599f) lineTo(19.561f, 12.099f) close() moveTo(7.736f, 9.384f) lineTo(8.267f, 15.464f) lineTo(6.536f, 14.465f) lineTo(5.504f, 16.25f) curveTo(5.46f, 16.326f, 5.437f, 16.412f, 5.437f, 16.5f) curveTo(5.437f, 16.746f, 5.614f, 16.95f, 5.847f, 16.992f) lineTo(5.937f, 17.0f) lineTo(8.999f, 17.0f) verticalLineTo(20.0f) lineTo(5.937f, 20.0f) curveTo(4.004f, 20.0f, 2.437f, 18.433f, 2.437f, 16.5f) curveTo(2.437f, 15.886f, 2.599f, 15.282f, 2.906f, 14.75f) lineTo(3.938f, 12.965f) lineTo(2.205f, 11.964f) lineTo(7.736f, 9.384f) close() moveTo(13.749f, 2.969f) curveTo(14.281f, 3.276f, 14.723f, 3.718f, 15.03f, 4.25f) lineTo(16.061f, 6.036f) lineTo(17.794f, 5.036f) lineTo(17.262f, 11.116f) lineTo(11.731f, 8.536f) lineTo(13.463f, 7.536f) lineTo(12.432f, 5.75f) curveTo(12.388f, 5.674f, 12.325f, 5.611f, 12.249f, 5.567f) curveTo(12.037f, 5.444f, 11.771f, 5.495f, 11.618f, 5.676f) lineTo(11.566f, 5.75f) lineTo(10.036f, 8.402f) lineTo(7.438f, 6.902f) lineTo(8.968f, 4.25f) curveTo(9.935f, 2.576f, 12.075f, 2.003f, 13.749f, 2.969f) close() } } .build() return _recycleFill!! } private var _recycleFill: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,545
compose-icon-collections
MIT License
app/src/main/java/com/example/android/ballBounce/gameSimulation/gameEntities/BallEntityFactory.kt
trlaw
330,268,031
false
null
package com.example.android.ballBounce.gameSimulation.gameEntities const val NUM_COLORS = 4 const val BASE_COR = 0.6 const val BASE_BALL_RADIUS = 30.0 const val MAX_SPEED = BASE_BALL_RADIUS / (5.0) open class BallEntityFactory { var nextColorIndex = 0 open fun create(): BallEntity { return BallEntity().apply { cOr = BASE_COR radius = BASE_BALL_RADIUS this.colorIndex = nextColorIndex++ nextColorIndex %= NUM_COLORS } } }
0
Kotlin
0
0
eaa330713095bca6f90cd068201b4ffdad9984ab
500
BallBounce
MIT License
src/SPDEditor.kt
integralfx
193,193,822
false
null
import java.io.File import java.io.FileOutputStream import java.io.IOException import java.nio.file.Files import java.util.Arrays import kotlin.math.round class SPDEditor @Throws(IllegalArgumentException::class) constructor(bytes: UByteArray) { private val bytes: UByteArray // 0x06: 1.25v, 1.35v, not 1.50v val voltages: LinkedHashMap<String, Boolean> private var tCKmin: UByte = 0u // 0x0C // 0x0E: 11 to 4, 0x0F: 18 to 12 val supportedCLs: LinkedHashMap<UInt, Boolean> private var tCLmin: UByte = 0u // 0x10 private var tWRmin: UByte = 0u // 0x11 private var tRCDmin: UByte = 0u // 0x12 private var tRRDmin: UByte = 0u // 0x13 private var tRPmin: UByte = 0u // 0x14 private var tRASmin: UShort = 0u // (0x15 bits[3:0]) | (0x16 bits[7:0]) private var tRCmin: UShort = 0u // (0x15 bits[7:4]) | (0x17 bits[7:0]) private var tRFCmin: UShort = 0u // (0x19 bits[7:0]) | (0x18 bits[7:0]) private var tWTRmin: UByte = 0u // 0x1A private var tRTPmin: UByte = 0u // 0x1B private var tFAWmin: UShort = 0u // (0x1C bits[3:0]) | (0x1D bits[7:0]) // all in picoseconds (1 thousandth of a ns) private var tCKminCorrection: UByte = 0u // 0x22 private var tCLminCorrection: UByte = 0u // 0x23 private var tRCDminCorrection: UByte = 0u // 0x24 private var tRPminCorrection: UByte = 0u // 0x25 private var tRCminCorrection: UByte = 0u // 0x26 var xmp: XMP? = null private set // 0xB0, can be null if no XMP var frequency: Double get() { var tCKns = tCKmin.toInt().toDouble() / 8.0 + tCKminCorrection.toInt().toDouble() / 1000.0 tCKns = getMorePrecisetCKns(tCKns) return 1000 / tCKns } set(freq) { val tCKns = 1000 / freq val value = (tCKns * 8).toInt() val correction = round(1000 * (tCKns * 8 - value) / 8) tCKmin = value.toUByte() tCKminCorrection = correction.toInt().toUByte() } var timings: LinkedHashMap<String, UInt> get() { val timings = LinkedHashMap<String, UInt>() var tCKns = tCKmin.toInt().toDouble() / 8.0 + tCKminCorrection.toInt().toDouble() / 1000.0 tCKns = getMorePrecisetCKns(tCKns) val tCLns = tCLmin.toInt() / 8.0 + tCLminCorrection.toInt() / 1000.0 val tCL = round(tCLns / tCKns) val tRCDns = tRCDmin.toInt() / 8.0 + tRCDminCorrection.toInt() / 1000.0 val tRCD = round(tRCDns / tCKns) val tRPns = tRPmin.toInt() / 8.0 + tRPminCorrection.toInt() / 1000.0 val tRP = round(tRPns / tCKns) val tRASns = tRASmin.toInt() / 8.0 val tRAS = round(tRASns / tCKns) val tRCns = tRCmin.toInt() / 8.0 + tRCminCorrection.toInt() / 1000.0 val tRC = round(tRCns / tCKns) val tRFCns = tRFCmin.toInt() / 8.0 val tRFC = round(tRFCns / tCKns) val tRRDns = tRRDmin.toInt() / 8.0 val tRRD = round(tRRDns / tCKns) val tFAWns = tFAWmin.toInt().toInt() / 8.0 val tFAW = round(tFAWns / tCKns) val tWRns = tWRmin.toInt() / 8.0 val tWR = round(tWRns / tCKns) val tWTRns = tWTRmin.toInt() / 8.0 val tWTR = round(tWTRns / tCKns) val tRTPns = tRTPmin.toInt() / 8.0 val tRTP = round(tRTPns / tCKns) timings["tCL"] = tCL.toInt().toUInt() timings["tRCD"] = tRCD.toInt().toUInt() timings["tRP"] = tRP.toInt().toUInt() timings["tRAS"] = tRAS.toInt().toUInt() timings["tRC"] = tRC.toInt().toUInt() timings["tRFC"] = tRFC.toInt().toUInt() timings["tRRD"] = tRRD.toInt().toUInt() timings["tFAW"] = tFAW.toInt().toUInt() timings["tWR"] = tWR.toInt().toUInt() timings["tWTR"] = tWTR.toInt().toUInt() timings["tRTP"] = tRTP.toInt().toUInt() return timings } set(timings) { for ((key, value) in timings) setTiming(key, value) } companion object { @JvmStatic fun main(args: Array<String>) { /* try { File f = new File("c-die_2133C11-13-12.bin"); SPDEditor spd = new SPDEditor(Files.readAllBytes(f.toPath())); spd.setFrequency(800); spd.setTiming("tCL", 10); spd.setTiming("tRCD", 10); spd.setTiming("tRP", 10); spd.setTiming("tRAS", 30); spd.setCLSupported(11, false); spd.save("test.bin"); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } */ } } init { if (bytes.size < 128) { throw IllegalArgumentException("Expected 128 bytes. Got " + bytes.size + " bytes.") } this.bytes = bytes.copyOf() voltages = LinkedHashMap() voltages["1.25v"] = bytes[0x06].toUInt() shr 2 and 0x1u == 0x1u voltages["1.35v"] = bytes[0x06].toUInt() shr 1 and 0x1u == 0x1u voltages["1.50v"] = bytes[0x06].toUInt() and 0x1u != 0x1u // not 1.50v tCKmin = bytes[0x0C] supportedCLs = LinkedHashMap() for (i in 4..11) { val index = i - 4 supportedCLs[i.toUInt()] = bytes[0x0E].toUInt() shr index and 0x1u == 0x1u } for (i in 12..18) { val index = i - 12 supportedCLs[i.toUInt()] = bytes[0x0F].toUInt() shr index and 0x1u == 0x1u } tCLmin = bytes[0x10] tWRmin = bytes[0x11] tRCDmin = bytes[0x12] tRRDmin = bytes[0x13] tRPmin = bytes[0x14] var msb = bytes[0x15].toUInt() and 0xFu tRASmin = (msb shl 8 or bytes[0x16].toUInt()).toUShort() msb = bytes[0x15].toUInt() shr 4 and 0xFu tRCmin = (msb shl 8 or bytes[0x17].toUInt()).toUShort() tRFCmin = (bytes[0x19].toUInt() shl 8 or bytes[0x18].toUInt()).toUShort() tWTRmin = bytes[0x1A] tRTPmin = bytes[0x1B] msb = bytes[0x1C].toUInt() and 0xFu tFAWmin = (msb shl 8 or bytes[0x1D].toUInt()).toUShort() tCKminCorrection = bytes[0x22] tCLminCorrection = bytes[0x23] tRCDminCorrection = bytes[0x24] tRPminCorrection = bytes[0x25] tRCminCorrection = bytes[0x26] try { xmp = XMP(bytes.copyOfRange(0xB0, 0xB0 + XMP.SIZE)) } catch (e: IllegalArgumentException) { xmp = null println("No XMP found.") } } fun setVoltage(voltage: String, enabled: Boolean): Boolean { if (!voltages.containsKey(voltage)) return false voltages[voltage] = enabled return true } fun setCLSupported(cl: UInt, supported: Boolean): Boolean { if (!supportedCLs.containsKey(cl)) return false supportedCLs[cl] = supported return true } fun setTiming(timing: String, ticks: UInt): Boolean { if (ticks < 1u) return false var tCKns = tCKmin.toInt() / 8.0 + tCKminCorrection.toInt() / 1000.0 tCKns = getMorePrecisetCKns(tCKns) val ns = ticks.toInt() * tCKns val value = (ns * 8).toInt() val correction = round(1000 * (ns * 8 - value) / 8).toInt() when (timing) { "tCL" -> { if (!supportedCLs.containsKey(ticks)) return false supportedCLs[value.toUInt()] = true tCLmin = value.toUByte() tCLminCorrection = correction.toUByte() } "tRCD" -> { tRCDmin = value.toUByte() tRCDminCorrection = correction.toUByte() } "tRP" -> { tRPmin = value.toUByte() tRPminCorrection = correction.toUByte() } "tRAS" -> tRASmin = value.toUShort() "tRC" -> { tRCmin = value.toUShort() tRCminCorrection = correction.toUByte() } "tRFC" -> tRFCmin = value.toUShort() "tRRD" -> tRRDmin = value.toUByte() "tFAW" -> tFAWmin = value.toUShort() "tWR" -> tWRmin = value.toUByte() "tWTR" -> tWTRmin = value.toUByte() "tRTP" -> tRTPmin = value.toUByte() else -> return false } return true } fun printTimings() { for ((key, value) in timings) { println("$key: $value") } } fun save(filename: String): Boolean { updateBytes() val crc = crc16XModem().toUInt() // little endian - LSB goes last bytes[0x7F] = (crc shr 8 and 0xFFu).toUByte() bytes[0x7E] = (crc and 0xFFu).toUByte() try { FileOutputStream(filename).use { fos -> fos.write(bytes.toByteArray()) return true } } catch (e: IOException) { e.printStackTrace() } return false } private fun getMorePrecisetCKns(tCKns: Double): Double { val value = round(1000 * tCKns).toInt() when (value) { 938 -> return 0.9375 // 1066.666... 1071 -> return 1000 / (2800 / 3.0) // 933.333... else -> return tCKns } } // source: http://mdfs.net/Info/Comp/Comms/CRC16.htm private fun crc16XModem(): Short { var crc = 0 for (i in 0..0x74) { crc = crc xor (bytes[i].toInt() shl 8) for (j in 0..7) { crc = crc shl 1 if (crc and 0x10000 == 0x10000) crc = crc xor 0x1021 and 0xFFFF } } return crc.toShort() } private fun updateBytes() { var n = 0 if (voltages["1.25v"]!!) n = n or (1 shl 2) if (voltages["1.35v"]!!) n = n or (1 shl 1) if (!voltages["1.50v"]!!) n = n or 1 bytes[0x06] = n.toUByte() bytes[0x0C] = tCKmin n = 0 for (i in 4..11) { val index = i - 4 if (supportedCLs[i.toUInt()]!!) n = n or (1 shl index) } bytes[0x0E] = n.toUByte() n = 0 for (i in 12..18) { val index = i - 12 if (supportedCLs[i.toUInt()]!!) n = n or (1 shl index) } bytes[0x0F] = n.toUByte() bytes[0x10] = tCLmin bytes[0x11] = tWRmin bytes[0x12] = tRCDmin bytes[0x13] = tRRDmin bytes[0x14] = tRPmin var msb = tRASmin.toUInt() shr 8 and 0xFu bytes[0x15] = msb.toUByte() bytes[0x16] = (tRASmin and 0xFFu).toUByte() msb = tRCmin.toUInt() shr 8 and 0xFFu bytes[0x15] = bytes[0x15] or (msb shl 4).toUByte() bytes[0x17] = (tRCmin and 0xFFu).toUByte() bytes[0x18] = (tRFCmin and 0xFFu).toUByte() bytes[0x19] = (tRFCmin.toUInt() shr 8 and 0xFu).toUByte() bytes[0x1A] = tWTRmin bytes[0x1B] = tRTPmin bytes[0x1C] = (tFAWmin.toUInt() shr 8 and 0xFu).toUByte() bytes[0x1D] = (tFAWmin.toUInt() and 0xFFu).toUByte() bytes[0x22] = tCKminCorrection bytes[0x23] = tCLminCorrection bytes[0x24] = tRCDminCorrection bytes[0x25] = tRPminCorrection bytes[0x26] = tRCminCorrection if (xmp != null) xmp!!.bytes.copyInto(bytes, 0xB0) } }
0
Kotlin
0
7
9dbb303b71a82e5d67088828126fe141abcdb44b
11,760
SPDEditor
MIT License
kmdc/kmdc-tooltip/src/jsMain/kotlin/MDCTooltipLink.kt
mpetuska
430,798,310
false
null
package dev.petuska.kmdc.tooltip import androidx.compose.runtime.Composable import dev.petuska.kmdc.core.MDCDsl import org.jetbrains.compose.web.attributes.href import org.jetbrains.compose.web.dom.A import org.jetbrains.compose.web.dom.AttrBuilderContext import org.jetbrains.compose.web.dom.ContentBuilder import org.jetbrains.compose.web.dom.Text import org.w3c.dom.HTMLAnchorElement /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-tooltip) */ @MDCDsl @Composable public fun MDCTooltipRichContentScope.MDCTooltipLink( attrs: AttrBuilderContext<HTMLAnchorElement>? = null, content: ContentBuilder<HTMLAnchorElement>? = null, ) { A( attrs = { classes("mdc-tooltip__content-link") attrs?.invoke(this) }, content = content ) } /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-tooltip) */ @MDCDsl @Composable public fun MDCTooltipRichContentScope.MDCTooltipLink( text: String, href: String, attrs: AttrBuilderContext<HTMLAnchorElement>? = null, ) { MDCTooltipLink(attrs = { href(href) attrs?.invoke(this) }) { Text(text) } }
22
Kotlin
8
29
67b31502b5f76b64f7571821fdd0b78a3df0a68c
1,197
kmdc
Apache License 2.0
src/test/kotlin/no/nav/tiltakspenger/overgangsstonad/efsak/EfSakClientTest.kt
navikt
591,314,899
false
null
package no.nav.tiltakspenger.overgangsstonad.efsak internal class EfSakClientTest { // @Language("JSON") // val personHarOvergangsstønad = """{ // "data": { // "perioder": [ // {"personIdent":"123","fomDato":"2025-01-01","tomDato":"2025-01-10","datakilde":"kilde"} // ], // "status":"test", // "melding":"test", // "frontendFeilmelding":"test", // "stacktrace":"test" // } // } // """.trimMargin() // // @Language("JSON") // val personHarIkkeOvergangsstønad = """{ // "data": { // "perioder": [], // "status":"test", // "melding":"test", // "frontendFeilmelding":"test", // "stacktrace":"test" // } // } // """.trimMargin() // // @Test // fun `EF Sak svarer OK og personen har overgangsstønad`() { // val mockEngine = MockEngine { // respond( // content = personHarOvergangsstønad, // status = HttpStatusCode.OK, // headers = headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString()), // ) // } // val client = httpClientGeneric(mockEngine) // val efSakClient = EfSakClient(client) { "token for testing" } // runTest { // val response = efSakClient.hentOvergangsstønad("ident", "fom", "tom", "behovId") // assert(response.data.perioder.size == 1) // assert(response.data.perioder.get(0).fomDato == "2025-01-01") // assert(response.data.perioder.get(0).tomDato == "2025-01-10") // } // } // // @Test // fun `EF Sak svarer 200 og personen har ikke overgangsstønad`() { // val mockEngine = MockEngine { // respond( // content = personHarIkkeOvergangsstønad, // status = HttpStatusCode.OK, // headers = headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString()), // ) // } // val client = httpClientGeneric(mockEngine) // val efSakClient = EfSakClient(client) { "token for testing" } // runTest { // val response = efSakClient.hentOvergangsstønad("ident", "fom", "tom", "behovId") // assert(response.data.perioder.size == 0) // } // } // // @Test // fun `EF Sak svarer 400 Bad Request og det kastes exception`() { // val mockEngine = MockEngine { // respond( // content = """400 Bad Request""".trimMargin(), // status = HttpStatusCode.BadRequest, // headers = headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString()), // ) // } // assertThrows(ClientRequestException::class.java) { // runTest { efSakClient.hentOvergangsstønad("ident", "fom", "tom", "behovId") } // } // } }
0
Kotlin
0
0
d59a10ea52ebfe13f2dc7c7d485ae92342059691
2,907
tiltakspenger-overgangsstonad
MIT License
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/message/ChatEvents/ChatBoostAdded.kt
InsanusMokrassar
163,152,024
false
{"Kotlin": 3243076, "Shell": 373}
package dev.inmo.tgbotapi.types.message.ChatEvents import dev.inmo.tgbotapi.types.boostCountField import dev.inmo.tgbotapi.types.message.ChatEvents.abstracts.PublicChatEvent import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ChatBoostAdded( @SerialName(boostCountField) val count: Int ) : PublicChatEvent
13
Kotlin
29
358
482c375327b7087699a4cb8bb06cb09869f07630
371
ktgbotapi
Apache License 2.0
browser/json/src/main/kotlin/ch/sourcemotion/vertx/kotlin/eventbus/browser/codec/json/JsonEventBusCodec.kt
wem
380,808,411
false
null
package ch.sourcemotion.vertx.kotlin.eventbus.browser.codec.json import ch.sourcemotion.vertx.kotlin.eventbus.browser.core.codec.EventBusCodec import ch.sourcemotion.vertx.kotlin.eventbus.browser.core.codec.EventBusCodecs import kotlinx.serialization.KSerializer import kotlinx.serialization.json.Json class JsonEventBusCodec<T : Any>( private val json: Json, private val kSerializer: KSerializer<T> ) : EventBusCodec<T> { companion object { inline fun <reified T : Any> register(kSerializer: KSerializer<T>, json: Json = Json) = EventBusCodecs.registerCodec(JsonEventBusCodec(json, kSerializer)) } override fun serialize(value: T): dynamic { return json.encodeToString(kSerializer, value) } override fun deserialize(value: dynamic): T { return json.decodeFromString(kSerializer, value.unsafeCast<String>()) } }
0
Kotlin
0
0
3c82178ad26ed37c528e61b902d0403e9847f2d1
885
kotlin-js-vertx-eventbus
MIT License
app/src/main/java/musicboxd/android/ui/search/charts/ChartsScreenViewModel.kt
MusicBoxd
793,151,068
false
{"Kotlin": 235637}
package musicboxd.android.ui.search.charts import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import musicboxd.android.ui.search.charts.billboard.BillBoardChartType import musicboxd.android.ui.search.charts.billboard.model.BillBoardCharts import musicboxd.android.ui.search.charts.billboard.model.Data import musicboxd.android.utils.customConfig import org.jsoup.Jsoup class ChartsScreenViewModel : ViewModel() { private val _billBoardChartData = MutableStateFlow(BillBoardCharts(date = "", data = listOf())) val billBoardData = _billBoardChartData.asStateFlow() val chartTitle = mutableStateOf("") fun onUiEvent(chartUIEvent: ChartUIEvent) { when (chartUIEvent) { is ChartUIEvent.OnBillBoardChartClick -> { viewModelScope.launch { _billBoardChartData.emit(BillBoardCharts(date = "", data = listOf())) _billBoardChartData.emit( scrapeBillBoardChartsData( when (chartUIEvent.billBoardChartType) { BillBoardChartType.ARTIST_100 -> { chartTitle.value = "Artist 100" "https://www.billboard.com/charts/artist-100/" } BillBoardChartType.BILLBOARD_200 -> { chartTitle.value = "Billboard 200" "https://www.billboard.com/charts/billboard-200/" } BillBoardChartType.GLOBAL_200 -> { chartTitle.value = "Global 200" "https://www.billboard.com/charts/billboard-global-200/" } BillBoardChartType.HOT_100 -> { chartTitle.value = "Hot 100" "https://www.billboard.com/charts/hot-100/" } } ) ) } } } } private suspend fun scrapeBillBoardChartsData(url: String): BillBoardCharts { val hot100Doc = withContext(Dispatchers.IO) { Jsoup.connect(url).customConfig().get() } val dateOfTheChart = hot100Doc.toString() .substringAfter("<p class=\"c-tagline a-font-primary-medium-xs u-font-size-11@mobile-max u-letter-spacing-0106 u-letter-spacing-0089@mobile-max lrv-u-line-height-copy lrv-u-text-transform-uppercase lrv-u-margin-a-00 lrv-u-padding-l-075 lrv-u-padding-l-00@mobile-max\">") .substringBefore("</p>") val itemImages = hot100Doc.toString().substringAfter( "Wks on Chart" ).split("<div class=\"o-chart-results-list-row-container\">").map { it.substringAfter("<div class=\"a-chart-image lrv-u-flex lrv-u-align-items-center lrv-u-justify-content-center lrv-a-glue-parent\" style=\"background-image: url('") .substringBefore("')") }.filter { it.contains("https://") it.endsWith(".jpg") } val itemTitles = hot100Doc.toString().substringAfter( "Wks on Chart" ).split("<div class=\"o-chart-results-list-row-container\">").map { it.substringAfter("<h3 id=\"title-of-a-story\" class=").substringAfter("\">") .substringBefore("</h3>").trim() }.filter { !it.contains("</") } val itemArtists = hot100Doc.toString().substringAfter( "Wks on Chart" ).split("<div class=\"o-chart-results-list-row-container\">").map { it.substringAfter("<h3 id=\"title-of-a-story\" class=") .substringAfter("<span class=\"c-label").substringAfter("\">") .substringBefore("</span>").replace("&amp;", "&").trim() }.filter { it.isNotEmpty() } val positionRowItems = hot100Doc.toString().substringAfter("<div class=\"chart-results-list") .split("<div class=\"o-chart-results-list-row-container\">").flatMap { it.substringAfter("<li class=\"lrv-u-width-100p\">") .substringAfter("<li class=\"lrv-u-width-100p") .split("<li class=\"o-chart-results-list__item").map { it.substringAfter("<span class=\"c-label").substringAfter("\">") .substringBefore("</span>").trim() } }.filter { try { if (it == "-") { true } else { it.toInt() true } } catch (_: Exception) { false } }.chunked(3) return BillBoardCharts(date = dateOfTheChart, data = List(itemTitles.size) { Data( itemImgURL = try { itemImages[it] } catch (_: Exception) { "" }, itemTitle = try { itemTitles[it] } catch (_: Exception) { "" }, itemArtists = try { itemArtists[it] } catch (_: Exception) { "" }, itemLastWeek = try { positionRowItems[it][0] } catch (_: Exception) { "" }, itemPeakPosition = try { positionRowItems[it][1] } catch (_: Exception) { "" }, itemWeeksOnChart = try { positionRowItems[it][2] } catch (_: Exception) { "" } ) }) } }
0
Kotlin
0
1
b6e9451e0bd69aa9b880901fb88e4ae126808a90
6,407
android
MIT License
app-web/src/main/kotlin/com/usvision/web/configuration/routing.kt
the-sortinghat
419,233,583
false
{"Kotlin": 185733, "Dockerfile": 1834, "JavaScript": 293}
package com.usvision.web.configuration import com.usvision.reports.ReportSupervisor import com.usvision.web.exceptions.MissingRequiredPathParameterException import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.configureRouting(reportSupervisor: ReportSupervisor) { val defaultPreset = environment.config.property("reports.default_preset_name").getString() routing { route("/systems/{name}/reports") { get { val systemName: String = call.parameters["name"] ?: throw MissingRequiredPathParameterException("name", "String") val detections = call.request.queryParameters.getAll("detections") ?: emptyList() val preset = call.request.queryParameters["preset"] ?: defaultPreset val report = if (detections.isNotEmpty()) reportSupervisor.generateReport( detectorsNames = detections.toSet(), systemName = systemName ) else reportSupervisor.generateReport( presetName = preset, systemName = systemName ) call.respond( message = report, status = HttpStatusCode.OK ) } } route("/info") { get("/report_presets") { val presets = reportSupervisor.getPresets() call.respond( message = mapOf("presets" to presets), status = HttpStatusCode.OK ) } get("/detectors") { call.respond( message = mapOf("detectors" to reportSupervisor.getDetectors()), status = HttpStatusCode.OK ) } } } }
3
Kotlin
0
3
d5143ab39da2efe586cf185808d387ce902be64f
1,984
pattern-detector
MIT License
src/main/kotlin/org/http4k/intellij/wizard/StackId.kt
http4k
844,511,114
false
{"Kotlin": 39585}
package org.http4k.intellij.wizard import dev.forkhandles.values.NonBlankStringValueFactory import dev.forkhandles.values.StringValue class StackId private constructor(value: String) : StringValue(value) { companion object : NonBlankStringValueFactory<StackId>(::StackId) }
0
Kotlin
0
3
630c7d45ba711d5c2df2d48c0376882cfdda133b
280
intellij-plugin
Apache License 2.0
configurablecare/app/src/main/java/com/google/fhir/examples/configurablecare/AddPatientViewModel.kt
google
500,670,991
false
{"Kotlin": 334314, "Java": 12985}
/* * Copyright 2022-2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.fhir.examples.configurablecare import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import ca.uhn.fhir.context.FhirContext import ca.uhn.fhir.context.FhirVersionEnum import com.google.android.fhir.FhirEngine import com.google.android.fhir.datacapture.validation.Invalid import com.google.android.fhir.datacapture.validation.QuestionnaireResponseValidator import com.google.android.fhir.get import com.google.android.fhir.testing.jsonParser import com.google.fhir.examples.configurablecare.util.CustomResourceMapper import com.google.fhir.examples.configurablecare.util.TransformSupportServicesMatchBox import java.io.File import java.time.Instant import java.time.Period import java.util.Date import java.util.UUID import kotlinx.coroutines.launch import org.hl7.fhir.r4.model.Base import org.hl7.fhir.r4.model.Bundle import org.hl7.fhir.r4.model.DateType import org.hl7.fhir.r4.model.IdType import org.hl7.fhir.r4.model.Observation import org.hl7.fhir.r4.model.Patient import org.hl7.fhir.r4.model.Questionnaire import org.hl7.fhir.r4.model.QuestionnaireResponse import org.hl7.fhir.r4.model.Reference import org.hl7.fhir.r4.model.Resource import org.hl7.fhir.r4.model.StructureMap import org.hl7.fhir.r4.model.Task import org.hl7.fhir.r4.utils.StructureMapUtilities /** ViewModel for patient registration screen {@link AddPatientFragment}. */ class AddPatientViewModel(application: Application, private val state: SavedStateHandle) : AndroidViewModel(application) { var questionnaire: String = "" var savedPatient = MutableLiveData<Patient?>() var structureMapId: String = "" var currentTargetResourceType: String = "" val context = application.applicationContext private val questionnaireResource: Questionnaire get() = FhirContext.forCached(FhirVersionEnum.R4).newJsonParser().parseResource(questionnaire) as Questionnaire private var fhirEngine: FhirEngine = FhirApplication.fhirEngine(application.applicationContext) /** * Saves patient registration questionnaire response into the application database. * * @param questionnaireResponse patient registration questionnaire response */ fun savePatient(questionnaireResponse: QuestionnaireResponse) { viewModelScope.launch { if (QuestionnaireResponseValidator.validateQuestionnaireResponse( questionnaireResource, questionnaireResponse, getApplication() ) .values .flatten() .any { it is Invalid } ) { savedPatient.value = null return@launch } if (structureMapId.isEmpty()) { // no structure map needed println(" Structure map is empty") val bundle = CustomResourceMapper.extract(questionnaireResource, questionnaireResponse) var flag = false var patient: Patient for (entry in bundle.entry) { if (entry.resource is Patient) { patient = entry.resource as Patient patient.id = generateUuid() fhirEngine.create(patient) savedPatient.value = patient flag = true } } if (!flag) return@launch } else { println(" Structure map is: $structureMapId") println(" Target resource: $currentTargetResourceType") val outputFile = File(getApplication<Application>().externalCacheDir, "questionnaireResponse.json") outputFile.writeText( FhirContext.forCached(FhirVersionEnum.R4) .newJsonParser() .encodeResourceToString(questionnaireResponse) ) val contextR4 = FhirApplication.contextR4(getApplication<FhirApplication>().applicationContext) if (contextR4 == null) { savedPatient.value = null println("**** contextR4 not created yet") return@launch } val outputs = mutableListOf<Base>() val transformSupportServices = TransformSupportServicesMatchBox(contextR4, outputs) val structureMapUtilities = StructureMapUtilities(contextR4, transformSupportServices) val structureMap = fhirEngine.get<StructureMap>(IdType(structureMapId).idPart) val targetResource: Base = if (currentTargetResourceType == "Patient") Patient() else Bundle() val baseElement = jsonParser.parseResource( QuestionnaireResponse::class.java, jsonParser.encodeResourceToString(questionnaireResponse) ) println("QR: ${jsonParser.encodeResourceToString(baseElement)}") structureMapUtilities.transform(contextR4, baseElement, structureMap, targetResource) if (targetResource is Bundle) { if (!targetResource.hasEntry()) { savedPatient.value = null return@launch } } if (targetResource is Bundle) { var flag = false var patient = Patient() val outputFile = File(getApplication<Application>().externalCacheDir, "bundle.json") outputFile.writeText( FhirContext.forCached(FhirVersionEnum.R4) .newJsonParser() .encodeResourceToString(targetResource) ) targetResource.entry.forEach { bundleEntryComponent -> val resource = bundleEntryComponent.resource if (resource is Observation && resource.effective is DateType) { resource.effective = null } resource.id = UUID.randomUUID().toString() fhirEngine.create(resource) if (resource is Patient) { createImmunizationReviewTask(resource.id) flag = true patient = resource } } if (flag) { savedPatient.value = patient } else { savedPatient.value = null } } else if (targetResource is Resource) { targetResource.id = UUID.randomUUID().toString() println("Patient: ${jsonParser.encodeResourceToString(targetResource)}") fhirEngine.create(targetResource) questionnaireResponse.id = UUID.randomUUID().toString() questionnaireResponse.subject = Reference("${targetResource.resourceType}/${IdType(targetResource.id).idPart}") println("QR: ${jsonParser.encodeResourceToString(questionnaireResponse)}") fhirEngine.create(questionnaireResponse) createImmunizationReviewTask(targetResource.id) savedPatient.value = if (targetResource is Patient) targetResource else null } } } } private suspend fun createImmunizationReviewTask(patientId: String) { val task = Task().apply { id = UUID.randomUUID().toString() status = Task.TaskStatus.DRAFT intent = Task.TaskIntent.PROPOSAL description = "Immunization Review" focus.reference = "Questionnaire/IMMZD1ClientHistoryMeasles" `for`.reference = "Patient/${IdType(patientId).idPart}" restriction.period.end = Date.from(Instant.now().plus(Period.ofDays(180))) } fhirEngine.create(task) } private fun readFileFromAssets(filename: String): String { return getApplication<Application>().assets.open(filename).bufferedReader().use { it.readText() } } private fun generateUuid(): String { return UUID.randomUUID().toString() } }
17
Kotlin
27
37
4b79549db6fd0fc3f87cb9d79c46da2038b67a9f
8,171
fhir-app-examples
Apache License 2.0
crypto_api/src/commonMain/kotlin/org/kethereum/crypto/api/ec/ECDSASignature.kt
wiyarmir
469,944,902
true
{"Kotlin": 724732}
package org.kethereum.crypto.api.ec import com.ionspin.kotlin.bignum.integer.BigInteger data class ECDSASignature(val r: BigInteger, val s: BigInteger)
0
Kotlin
0
0
a602f94b6b90938a958425930cb0058c985790f1
154
KEthereum
MIT License
app/src/main/java/com/nitish/privacyindicator/repository/AccessLogsRepo.kt
NitishGadangi
294,875,570
false
null
package com.nitish.privacyindicator.repository import com.nitish.privacyindicator.db.AccessLogsDatabase import com.nitish.privacyindicator.models.AccessLog class AccessLogsRepo( val db: AccessLogsDatabase ) { suspend fun save(accessLog: AccessLog) = db.getAccessLogsDao().upsert(accessLog) suspend fun clear() = db.getAccessLogsDao().clearLogs() fun fetchAll() = db.getAccessLogsDao().getAllLogs() }
27
Kotlin
29
273
8e0db14b9188e2df26d2859dad99b6584fafac9a
423
Privacy-Indicator-App
MIT License
solar/src/main/java/com/chiksmedina/solar/boldduotone/essentionalui/Fuel.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.boldduotone.essentionalui 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.EssentionalUiGroup val EssentionalUiGroup.Fuel: ImageVector get() { if (_fuel != null) { return _fuel!! } _fuel = Builder( name = "Fuel", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { 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(2.5533f, 9.1475f) curveTo(2.0f, 9.9424f, 2.0f, 10.9906f, 2.0f, 13.0869f) verticalLineTo(15.8834f) curveTo(2.0f, 18.7668f, 2.0f, 20.2085f, 2.8787f, 21.1042f) curveTo(3.7574f, 22.0f, 5.1716f, 22.0f, 8.0f, 22.0f) horizontalLineTo(16.0f) curveTo(18.8284f, 22.0f, 20.2426f, 22.0f, 21.1213f, 21.1042f) curveTo(22.0f, 20.2085f, 22.0f, 18.7668f, 22.0f, 15.8834f) verticalLineTo(10.2325f) curveTo(22.0f, 6.3054f, 22.0f, 4.3418f, 20.7359f, 3.4276f) curveTo(19.4718f, 2.5133f, 17.6539f, 3.162f, 14.0179f, 4.4593f) lineTo(6.0179f, 7.3137f) curveTo(4.077f, 8.0062f, 3.1065f, 8.3525f, 2.5533f, 9.1475f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(11.0162f, 5.5303f) lineTo(10.9442f, 5.2371f) curveTo(10.7929f, 4.6611f, 10.3519f, 4.2112f, 9.7872f, 4.0569f) curveTo(9.5791f, 4.0f, 9.3254f, 4.0f, 8.8182f, 4.0f) horizontalLineTo(8.0f) curveTo(6.7206f, 4.0f, 6.0809f, 4.0f, 5.6402f, 4.3449f) curveTo(5.5268f, 4.4337f, 5.4252f, 4.5373f, 5.3382f, 4.653f) curveTo(5.0f, 5.1025f, 5.0f, 5.7551f, 5.0f, 7.0601f) verticalLineTo(7.6812f) curveTo(5.3059f, 7.5677f, 5.6439f, 7.4472f, 6.0179f, 7.3137f) lineTo(11.0162f, 5.5303f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(7.4697f, 9.4697f) curveTo(7.1768f, 9.7626f, 7.1768f, 10.2374f, 7.4697f, 10.5303f) lineTo(8.9697f, 12.0303f) curveTo(9.008f, 12.0687f, 9.0495f, 12.102f, 9.0933f, 12.1304f) curveTo(9.0f, 12.564f, 9.0f, 13.1561f, 9.0f, 14.0f) curveTo(9.0f, 14.8313f, 9.0f, 15.4182f, 9.0892f, 15.8501f) lineTo(7.4697f, 17.4697f) curveTo(7.1768f, 17.7626f, 7.1768f, 18.2374f, 7.4697f, 18.5303f) curveTo(7.7626f, 18.8232f, 8.2374f, 18.8232f, 8.5303f, 18.5303f) lineTo(10.1499f, 16.9108f) curveTo(10.5818f, 17.0f, 11.1687f, 17.0f, 12.0f, 17.0f) curveTo(12.8313f, 17.0f, 13.4182f, 17.0f, 13.8501f, 16.9108f) lineTo(15.4697f, 18.5303f) curveTo(15.7626f, 18.8232f, 16.2374f, 18.8232f, 16.5303f, 18.5303f) curveTo(16.8232f, 18.2374f, 16.8232f, 17.7626f, 16.5303f, 17.4697f) lineTo(14.9108f, 15.8501f) curveTo(15.0f, 15.4182f, 15.0f, 14.8313f, 15.0f, 14.0f) curveTo(15.0f, 13.1687f, 15.0f, 12.5818f, 14.9108f, 12.1499f) lineTo(16.5303f, 10.5303f) curveTo(16.8232f, 10.2374f, 16.8232f, 9.7626f, 16.5303f, 9.4697f) curveTo(16.2374f, 9.1768f, 15.7626f, 9.1768f, 15.4697f, 9.4697f) lineTo(13.8501f, 11.0892f) curveTo(13.4182f, 11.0f, 12.8313f, 11.0f, 12.0f, 11.0f) curveTo(11.1561f, 11.0f, 10.564f, 11.0f, 10.1304f, 11.0933f) curveTo(10.102f, 11.0495f, 10.0687f, 11.008f, 10.0303f, 10.9697f) lineTo(8.5303f, 9.4697f) curveTo(8.2374f, 9.1768f, 7.7626f, 9.1768f, 7.4697f, 9.4697f) close() } } .build() return _fuel!! } private var _fuel: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
5,142
SolarIconSetAndroid
MIT License
sharedprefinspector/src/main/java/com/github/dhaval2404/sharedprefinspector/data/entity/SharedPref.kt
rahulupadhyay
298,191,817
true
{"Kotlin": 33995}
package com.github.dhaval2404.sharedprefinspector.data.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.github.dhaval2404.sharedprefinspector.constant.Action import java.util.Date @Entity(tableName = "shared_pref") data class SharedPref( @ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) var id: Long = 0, @Action @ColumnInfo(name = "action") var action: String = Action.ADD, @ColumnInfo(name = "key") var key: String = "", @ColumnInfo(name = "value") var value: String? = null, @ColumnInfo(name = "timestamp") var date: Date = Date() ) { fun getNotificationText():String{ return "$action $key => $value" } }
0
null
0
1
185754d8bf8369f6524dea83392b270f0b9ec36a
746
SharedPrefInspector
Apache License 2.0
app/src/main/java/com/nguyen/shelter/model/Comment.kt
dtnguyn
292,352,460
false
null
package com.nguyen.shelter.model import java.util.* data class Comment ( var id: String, var blogId: String, var user: User, var date: Date, var content: String, var isOwner: Boolean = false )
0
Kotlin
0
2
39bb09297edd9f999ed2710ee51608a53254aa8d
219
Shelter
The Unlicense
kotlin-csstype/src/main/generated/csstype/AccentColor.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) package csstype // language=JavaScript @JsName("""({auto: 'auto'})""") sealed external interface AccentColor { companion object { val auto: AccentColor } }
11
Kotlin
141
957
91f081c19cd5647a1d84f7b3698639fe396a2974
314
kotlin-wrappers
Apache License 2.0
serialization/std/src/test/kotlin/io/github/airflux/serialization/std/validator/string/IsNotEmptyValidatorTest.kt
airflux
336,002,943
false
null
/* * Copyright 2021-2023 <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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.airflux.serialization.std.validator.string import io.github.airflux.serialization.core.location.Location import io.github.airflux.serialization.core.reader.env.ReaderEnv import io.github.airflux.serialization.core.reader.result.ReaderResult import io.github.airflux.serialization.core.reader.validator.Validator import io.github.airflux.serialization.std.common.JsonErrors import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe internal class IsNotEmptyValidatorTest : FreeSpec() { companion object { private val ENV = ReaderEnv(EB(), Unit) private val CONTEXT = Unit private val LOCATION = Location.empty } init { "The string validator IsNotEmpty" - { val validator: Validator<EB, Unit, Unit, String> = StdStringValidator.isNotEmpty() "when a string is empty" - { val str = "" "then the validator should return an error" { val failure = validator.validate(ENV, CONTEXT, LOCATION, str) failure.shouldNotBeNull() failure shouldBe ReaderResult.Failure( location = LOCATION, error = JsonErrors.Validation.Strings.IsEmpty ) } } "when a string is blank" - { val str = " " "then the validator should return the null value" { val errors = validator.validate(ENV, CONTEXT, LOCATION, str) errors.shouldBeNull() } } "when a string is not blank" - { val str = "a" "then the validator should return the null value" { val errors = validator.validate(ENV, CONTEXT, LOCATION, str) errors.shouldBeNull() } } } } internal class EB : IsNotEmptyStringValidator.ErrorBuilder { override fun isNotEmptyStringError(): ReaderResult.Error = JsonErrors.Validation.Strings.IsEmpty } }
0
Kotlin
3
3
9dfcfe4ec288e27f150beeef12dff45f131d0805
2,823
airflux-serialization
Apache License 2.0
SparMePlease/app/src/main/java/com/example/sparmeplease/retro/MoneyAPI.kt
SABERGLOW
437,119,208
false
{"Kotlin": 16403}
package com.example.sparmeplease.retro import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface MoneyAPI { @GET("/latest") fun getRates(@Query("from") base: String): Call<MoneyResult> }
0
Kotlin
1
5
77e61e7e57a441cdf5f9bc5bfcea3257a2630e14
224
SparMePlease
MIT License
SparMePlease/app/src/main/java/com/example/sparmeplease/retro/MoneyAPI.kt
SABERGLOW
437,119,208
false
{"Kotlin": 16403}
package com.example.sparmeplease.retro import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface MoneyAPI { @GET("/latest") fun getRates(@Query("from") base: String): Call<MoneyResult> }
0
Kotlin
1
5
77e61e7e57a441cdf5f9bc5bfcea3257a2630e14
224
SparMePlease
MIT License
bindings/darwin/darwin/foundation/src/main/kotlin/darwin/NSApplication.kt
ygdrasil-io
634,882,904
false
{"Kotlin": 292451, "C": 3541, "Shell": 2951, "Objective-C": 1076, "C++": 567}
package darwin val NSApplicationClass by lazy { NSClass("NSApplication") } class NSApplication(id: Long) : NSObject(id) { fun run() = msgSend("run") companion object{ fun sharedApplication(): NSApplication = NSApplication(NSApplicationClass.msgSend("sharedApplication")) } }
2
Kotlin
1
0
5889fb009a06f141d238587b7288ef727873253e
284
klang
MIT License
examples/src/tl/td/BotInfo.kt
andreypfau
719,064,910
false
{"Kotlin": 62259}
// This file is generated by TLGenerator.kt // Do not edit manually! package tl.td import io.github.andreypfau.tl.serialization.TLCombinatorId import kotlin.jvm.JvmName import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @SerialName("botInfo") @TLCombinatorId(0xA83AB851) public data class BotInfo( @SerialName("short_description") @get:JvmName("shortDescription") public val shortDescription: String, @get:JvmName("description") public val description: String, @get:JvmName("photo") public val photo: Photo, @get:JvmName("animation") public val animation: Animation, @SerialName("menu_button") @get:JvmName("menuButton") public val menuButton: BotMenuButton, @get:JvmName("commands") public val commands: List<BotCommand>, @SerialName("default_group_administrator_rights") @get:JvmName("defaultGroupAdministratorRights") public val defaultGroupAdministratorRights: ChatAdministratorRights, @SerialName("default_channel_administrator_rights") @get:JvmName("defaultChannelAdministratorRights") public val defaultChannelAdministratorRights: ChatAdministratorRights, @SerialName("edit_commands_link") @get:JvmName("editCommandsLink") public val editCommandsLink: InternalLinkType, @SerialName("edit_description_link") @get:JvmName("editDescriptionLink") public val editDescriptionLink: InternalLinkType, @SerialName("edit_description_media_link") @get:JvmName("editDescriptionMediaLink") public val editDescriptionMediaLink: InternalLinkType, @SerialName("edit_settings_link") @get:JvmName("editSettingsLink") public val editSettingsLink: InternalLinkType, ) { public companion object }
0
Kotlin
0
1
11f05ad1f977235e3e360cd6f6ada6f26993208e
1,762
tl-kotlin
MIT License
app/src/main/java/com/peceoqicka/demo/wheelayoutmanager/MainActivity.kt
peceoqicka
176,448,211
false
null
package com.peceoqicka.demo.wheelayoutmanager import android.databinding.DataBindingUtil import android.databinding.ObservableArrayList import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.peceoqicka.demo.wheelayoutmanager.databinding.ActivityMainBinding import com.peceoqicka.demo.wheelayoutmanager.index.ItemAdapter import com.peceoqicka.demo.wheelayoutmanager.index.ItemViewModel import com.peceoqicka.demo.wheelayoutmanager.index.ViewModel import com.peceoqicka.demo.wheelayoutmanager.util.color import com.peceoqicka.demo.wheelayoutmanager.util.timer import com.peceoqicka.wheellayoutmanager.WheelLayoutManager import org.jetbrains.anko.dimen import java.util.* class MainActivity : AppCompatActivity() { private lateinit var bindModel: ViewModel private var currentYear: Int = 0 private var currentMonth: Int = 0 private var currentDay: Int = 0 private var selectedMaxDayOfMonth: Int = 0 private var selectedYear: Int = 0 private var selectedMonth: Int = 0 private var selectedDay: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = DataBindingUtil.setContentView<ActivityMainBinding>( this, R.layout.activity_main ) binding.model = ViewModel().apply { yearLayoutManager = WheelLayoutManager(5).apply { selectionChangedListener = this@MainActivity::onYearSelectionChanged draggingStartListener = { deselectIndex(yearAdapter) } } monthLayoutManager = WheelLayoutManager(5, true).apply { selectionChangedListener = this@MainActivity::onMonthSelectionChanged draggingStartListener = { deselectIndex(monthAdapter) } } dayLayoutManager = WheelLayoutManager(5, true).apply { selectionChangedListener = this@MainActivity::onDaySelectionChanged draggingStartListener = { deselectIndex(dayAdapter) } } yearItemDecoration = DateItemDecoration( color(R.color.hex_ffffff), dimen(R.dimen.px_1), color(R.color.hex_c6c6c6), enableHighlightMarker = true, highlightMarkerWidth = dimen(R.dimen.px_6), highlightMarkerColor = color(R.color.hex_db262e), enableHintText = true, hintText = getString(R.string.year), hintTextRightMargin = dimen(R.dimen.px_60), hintTextSize = dimen(R.dimen.px_30), hintTextColor = color(R.color.hex_db262e) ) monthItemDecoration = DateItemDecoration( color(R.color.hex_ffffff), dimen(R.dimen.px_1), color(R.color.hex_c6c6c6), enableHintText = true, hintText = getString(R.string.month), hintTextRightMargin = dimen(R.dimen.px_92), hintTextSize = dimen(R.dimen.px_30), hintTextColor = color(R.color.hex_db262e) ) dayItemDecoration = DateItemDecoration( color(R.color.hex_ffffff), dimen(R.dimen.px_1), color(R.color.hex_c6c6c6), enableHintText = true, hintText = getString(R.string.day), hintTextRightMargin = dimen(R.dimen.px_92), hintTextSize = dimen(R.dimen.px_30), hintTextColor = color(R.color.hex_db262e) ) bindModel = this } getDateOfToday() loadData() selectCurrentDate() } private fun onYearSelectionChanged(position: Int) { val selectedValue = bindModel.yearAdapter?.getValue(position) ?: -1 if (selectedValue > 0) { selectedYear = selectedValue onDayChanged() selectIndex(bindModel.yearAdapter, position) bindModel.yearDisplay = selectedYear } } private fun onMonthSelectionChanged(position: Int) { val selectedValue = bindModel.monthAdapter?.getValue(position) ?: -1 if (selectedValue > 0) { selectedMonth = selectedValue onDayChanged() selectIndex(bindModel.monthAdapter, position) bindModel.monthDisplay = selectedMonth } } private fun onDaySelectionChanged(position: Int) { val selectedValue = bindModel.dayAdapter?.getValue(position) ?: -1 if (selectedValue > 0) { selectedDay = selectedValue selectIndex(bindModel.dayAdapter, position) bindModel.dayDisplay = selectedDay } } /** * 因为年或月变化可能产生的当月最大天数变化 */ private fun onDayChanged() { val newMaxDayOfMonth = getMaxDayOfMonth(selectedYear, selectedMonth) if (newMaxDayOfMonth > selectedMaxDayOfMonth) { bindModel.dayAdapter?.addRange(selectedMaxDayOfMonth + 1, newMaxDayOfMonth) } else if (newMaxDayOfMonth < selectedMaxDayOfMonth) { val lastMaxDayOfMonth = selectedMaxDayOfMonth bindModel.dayAdapter?.removeRange(newMaxDayOfMonth + 1, lastMaxDayOfMonth) //不应从适配器层面来重新定位选中的元素 } selectedMaxDayOfMonth = newMaxDayOfMonth } private fun getDateOfToday() { val calendar = Calendar.getInstance() currentYear = calendar.get(Calendar.YEAR) currentMonth = calendar.get(Calendar.MONTH) + 1 currentDay = calendar.get(Calendar.DAY_OF_MONTH) println("$currentYear-$currentMonth-$currentDay") } private fun getMaxDayOfMonth(year: Int, month: Int): Int { val calendar = Calendar.getInstance() calendar.set(year, month - 1, 1) return calendar.getActualMaximum(Calendar.DAY_OF_MONTH) } private fun loadData() { val yearList = ObservableArrayList<ItemViewModel>() for (i in (0 until 10)) { val year = currentYear + i yearList.add(ItemViewModel().apply { this.value = year }) } bindModel.yearAdapter = ItemAdapter(yearList) val monthList = ObservableArrayList<ItemViewModel>() for (i in (1..12)) { monthList.add(ItemViewModel().apply { this.value = i }) } bindModel.monthAdapter = ItemAdapter(monthList) val dayList = ObservableArrayList<ItemViewModel>() for (i in (1..getMaxDayOfMonth(currentYear, currentMonth))) { dayList.add(ItemViewModel().apply { this.value = i }) } bindModel.dayAdapter = ItemAdapter(dayList) } private fun selectDate(year: Int, month: Int, day: Int) { selectValue(bindModel.yearLayoutManager, bindModel.yearAdapter, year) selectValue(bindModel.monthLayoutManager, bindModel.monthAdapter, month) selectValue(bindModel.dayLayoutManager, bindModel.dayAdapter, day) } private fun selectValue(layoutManager: WheelLayoutManager, adapter: ItemAdapter?, value: Int) { if (adapter != null) { val targetPosition = adapter.findPositionOf(value) layoutManager.scrollToPosition(targetPosition) } } private fun selectCurrentDate() { timer(100) { selectedMaxDayOfMonth = getMaxDayOfMonth(selectedYear, selectedMonth) selectDate(currentYear, currentMonth, currentDay) } } private fun selectIndex(adapter: ItemAdapter?, index: Int) { adapter?.selectItem(index) } private fun deselectIndex(adapter: ItemAdapter?) { adapter?.deselectItem() } }
2
Kotlin
0
5
a112452f182bdb1bb67ffd837a11c5673656b11f
7,840
WheelLayoutManager
Apache License 2.0
app/src/main/java/com/iamageo/weather/domain/location/LocationTracker.kt
iamageo
512,027,915
false
null
package com.iamageo.weather.domain.location import android.location.Location interface LocationTracker { suspend fun getCurrentLocation(): Location? }
0
Kotlin
0
2
d9f3f05caa0444de87d99397a35bfb943d4f9dcf
156
WeatherApp
MIT License
shared/src/commonMain/kotlin/app/duss/easyproject/presentation/ui/dashboard/DashboardComponent.kt
Shahriyar13
721,031,988
false
{"Kotlin": 247935, "Swift": 6282, "Ruby": 2302}
package app.duss.easyproject.presentation.ui.dashboard import app.duss.easyproject.presentation.ui.dashboard.store.DashboardStore import app.duss.easyproject.presentation.ui.dashboard.store.DashboardStoreFactory import com.arkivanov.decompose.ComponentContext import com.arkivanov.mvikotlin.core.instancekeeper.getStore import com.arkivanov.mvikotlin.core.store.StoreFactory import com.arkivanov.mvikotlin.extensions.coroutines.stateFlow import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.StateFlow class DashboardComponent( componentContext: ComponentContext, storeFactory: StoreFactory, private val output: (Output) -> Unit ): ComponentContext by componentContext { private val mainStore = instanceKeeper.getStore { DashboardStoreFactory( storeFactory = storeFactory, ).create() } @OptIn(ExperimentalCoroutinesApi::class) val state: StateFlow<DashboardStore.State> = mainStore.stateFlow fun onEvent(event: DashboardStore.Intent) { mainStore.accept(event) } fun onOutput(output: Output) { output(output) } sealed class Output { data object Unauthorized : Output() data class SearchSubmitted(val searchValue: String) : Output() data object DatabaseClicked : Output() data object CEClicked : Output() data object ProjectClicked : Output() data object SEClicked : Output() data object SQClicked : Output() data object PIClicked : Output() data object POClicked : Output() data object ShippingClicked : Output() data object InvoiceClicked : Output() data object BafaClicked : Output() data object PaymentClicked : Output() data object ProfileClicked : Output() data object ComingSoonClicked : Output()//TODO remove } }
0
Kotlin
0
0
3b21efcf1c9bcdc2148884458a7c34f75020e071
1,898
Kara_EasyProject_CMP
Apache License 2.0
app/src/main/java/com/example/movieapp/ui/ViewState.kt
jaumpelicon
480,804,537
false
{"Kotlin": 78030}
package com.example.movieapp.ui data class ViewState<out T>(val status: Status, val data: T?, val message: String? = null) { enum class Status { SUCCESS, FAILURE, LOADING, INITIAL } companion object { fun <T> success(data: T): ViewState<T> { return ViewState(Status.SUCCESS, data) } fun <T> failure(message: String): ViewState<T> { return ViewState(Status.FAILURE, null, message) } fun <T> initial(): ViewState<T> { return ViewState(Status.INITIAL, null) } fun <T> loading(): ViewState<T> { return ViewState(Status.LOADING, null) } } }
0
Kotlin
0
0
74a6b54f9c694de5885a92241c2604fa32475be7
676
movie-app
MIT License
src/main/kotlin/com/ctseducare/kotlin/k04_input_data/CalcularPrecoConsumidor.kt
erosvitor
712,607,250
false
{"Kotlin": 27437}
/* O preço consumidor de um carro novo é a soma do custo de fábrica com a porcentagem do distribuidor e dos impostos (aplicados ao custo de fábrica). Supondo que a porcentagem do distribuidor seja de 28% e os impostos sobre o custo de fábrica seja de 45%, crie um programa que leia o custo de fábrica de um determinado carro e depois mostre na tela o preço consumidor. */ package com.ctseducare.kotlin.k04_input_data import java.util.Scanner fun main() { println("Calcular preço consumidor") println("") val leitura = Scanner(System.`in`) val porcentagemDistribuidor = 28/100 val impostos = 45/100 print("Informe o custo de fábrica: ") val custoFabrica = leitura.nextFloat() var precoConsumidor = custoFabrica + (custoFabrica * porcentagemDistribuidor) precoConsumidor += (precoConsumidor * impostos) println("O preço consumidor é de $precoConsumidor") }
0
Kotlin
0
0
463553734d5d344a199a28ee300b6d3665727517
892
exercicios-kotlin-fundamentos
MIT License
plugins/kotlin/base/test/test/org/jetbrains/kotlin/idea/test/ExpectedPluginModeProvider.kt
JetBrains
2,489,216
false
{"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.test import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.testFramework.UsefulTestCase import com.intellij.util.ThrowableRunnable import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.base.plugin.KotlinPluginMode import org.jetbrains.kotlin.idea.base.plugin.KotlinPluginModeProvider import org.jetbrains.kotlin.idea.base.plugin.useK2Plugin import org.junit.Assert @TestOnly interface ExpectedPluginModeProvider { val pluginMode: KotlinPluginMode } fun ExpectedPluginModeProvider.assertKotlinPluginMode() = assertKotlinPluginMode( expectedPluginMode = pluginMode, ) // do not expose internal fun assertKotlinPluginMode( expectedPluginMode: KotlinPluginMode, actualPluginMode: KotlinPluginMode = KotlinPluginModeProvider.currentPluginMode, ) = Assert.assertEquals( "Invalid Kotlin plugin detected: $actualPluginMode, but $expectedPluginMode was expected", expectedPluginMode, actualPluginMode, ) /** * Executes a [setUp] function after enabling the K1 or K2 Kotlin plugin in system properties. * The correct Kotlin plugin should be set up after [setUp] finishes. */ @TestOnly fun ExpectedPluginModeProvider.setUpWithKotlinPlugin( rootDisposable: Disposable, setUp: ThrowableRunnable<*>, ) { val oldUseK2Plugin = useK2Plugin useK2Plugin = pluginMode == KotlinPluginMode.K2 Disposer.register(rootDisposable) { useK2Plugin = oldUseK2Plugin } setUp.run() assertKotlinPluginMode() } @TestOnly fun <T> T.setUpWithKotlinPlugin( setUp: ThrowableRunnable<*>, ) where T : UsefulTestCase, T : ExpectedPluginModeProvider = setUpWithKotlinPlugin(testRootDisposable, setUp)
1
null
1
1
0d546ea6a419c7cb168bc3633937a826d4a91b7c
1,878
intellij-community
Apache License 2.0
clients/ktorm-schema/generated/src/main/kotlin/org/openapitools/database/models/CatalogsFeedValidationDetails.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * Pinterest REST API * Pinterest's REST API * * The version of the OpenAPI document: 5.12.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.database.models import org.ktorm.dsl.* import org.ktorm.schema.* import org.ktorm.database.Database import .* /** * * @param errors * @param warnings */ object CatalogsFeedValidationDetailss : BaseTable<CatalogsFeedValidationDetails>("CatalogsFeedValidationDetails") { val errors = long("errors") val warnings = long("warnings") /** * Create an entity of type CatalogsFeedValidationDetails from the model */ override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = CatalogsFeedValidationDetails( errors = CatalogsFeedValidationErrorss.createEntity(row, withReferences) /* CatalogsFeedValidationErrors */, warnings = CatalogsFeedValidationWarningss.createEntity(row, withReferences) /* CatalogsFeedValidationWarnings */ ) /** * Assign all the columns from the entity of type CatalogsFeedValidationDetails to the DML expression. * * Usage: * * ```kotlin * let entity = CatalogsFeedValidationDetails() * database.update(CatalogsFeedValidationDetailss, { * assignFrom(entity) * }) * ``` * @return the builder with the columns for the update or insert. */ fun AssignmentsBuilder.assignFrom(entity: CatalogsFeedValidationDetails) { this.apply { set(CatalogsFeedValidationDetailss.errors, entity.errors) set(CatalogsFeedValidationDetailss.warnings, entity.warnings) } } }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
1,750
pinterest-sdk
MIT License
src/main/kotlin/me/kacper/model/Color.kt
kac-kon
518,861,100
false
null
package me.kacper.model import com.fasterxml.jackson.annotation.JsonAlias import com.fasterxml.jackson.annotation.JsonAutoDetect import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) data class Color( @JsonAlias(value = ["Red"]) val red: Int, @JsonAlias(value = ["Green"]) val green: Int, @JsonAlias(value = ["Blue"]) val blue: Int, @JsonAlias(value = ["Brightness"]) val brightness: Int ) { fun toMap() = mapOf( RED to red, GREEN to green, BLUE to blue ) private fun Int.tone(): Int { return (this * brightness).div(100) } fun toMapToned() = mapOf( RED to red.tone(), GREEN to green.tone(), BLUE to blue.tone() ) companion object{ const val RED = "RED" const val GREEN = "GREEN" const val BLUE = "BLUE" } }
0
Kotlin
0
0
79c4d9f724557f89d5326c2701f01c6881db4e1a
1,071
home-system
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/resource/ActivityCategoryController.kt
ministryofjustice
533,838,017
false
{"Kotlin": 3866023, "Shell": 9529, "Dockerfile": 1514}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.resource import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.ArraySchema import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.config.ErrorResponse import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.refdata.toModel import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model.response.ActivityCategory import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.refdata.ActivityCategoryRepository @RestController @RequestMapping("/activity-categories", produces = [MediaType.APPLICATION_JSON_VALUE]) class ActivityCategoryController(private val activityCategoryRepository: ActivityCategoryRepository) { @Operation( summary = "Get the list of top-level activity categories", ) @ApiResponses( value = [ ApiResponse( responseCode = "200", description = "Activity categories found", content = [Content(mediaType = "application/json", array = ArraySchema(schema = Schema(implementation = ActivityCategory::class)))], ), ApiResponse( responseCode = "401", description = "Unauthorised, requires a valid Oauth2 token", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Forbidden, requires an appropriate role", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) @GetMapping @ResponseBody @PreAuthorize("hasAnyRole('PRISON', 'ACTIVITY_ADMIN', 'NOMIS_ACTIVITIES')") fun getCategories(): List<ActivityCategory> = activityCategoryRepository.findAll().toModel() }
2
Kotlin
0
1
084728653c2c5a4c17177c18c116001af30b1029
2,398
hmpps-activities-management-api
MIT License
leic41n/EchoServer/src/main/kotlin/pt/isel/leic/pc/echo/coroutines/Main_coroutines.kt
isel-leic-pc
466,188,773
false
null
package pt.isel.leic.pc.echo.coroutines import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import org.slf4j.LoggerFactory import pt.isel.leic.pc.echo.SessionInfo import java.nio.channels.AsynchronousSocketChannel import java.util.LinkedList import java.util.concurrent.CompletableFuture import java.util.concurrent.Executors import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine private const val EXIT = "exit" private val logger = LoggerFactory.getLogger("Async IO NIO Echo Server") private class AsyncSemaphore(initialUnits: Int) { private var units: Int = initialUnits private val guard = ReentrantLock() private val requests = LinkedList<CompletableFuture<Unit>>() fun acquire(): CompletableFuture<Unit> { guard.withLock { if (units != 0) { units -= 1 return CompletableFuture.completedFuture(Unit) } val operation = CompletableFuture<Unit>() requests.addLast(operation) return operation } } fun release() { guard.withLock { if (requests.isEmpty()) { units += 1 null } else { requests.removeFirst() } }?.complete(Unit) } } /** * The server's entry point. */ fun main(args: Array<String>) { runBlocking { val port = if (args.isEmpty() || args[0].toIntOrNull() == null) 8000 else args[0].toInt() logger.info("Process id is = ${ProcessHandle.current().pid()}. Starting echo server at port $port") val executor = Executors.newSingleThreadExecutor() val serverSocket = createServerChannel("localhost", port, executor) val throttle = AsyncSemaphore(2) val acceptJob = CoroutineScope(executor.asCoroutineDispatcher()).launch { while (true) { throttle.acquire().await() logger.info("Ready to accept connections") val sessionSocket = serverSocket.suspendingAccept() launch { try { handleEchoSession(sessionSocket) } finally { throttle.release() } } } } logger.info("Blocking on readln") val gooodByeMesssage = readln() // Initiate shutdown ... acceptJob.cancelAndJoin() executor.shutdown() } } suspend fun <T> CompletableFuture<T>.await(): T { return suspendCancellableCoroutine { continuation -> this.whenComplete { result, error -> if (error != null) continuation.resumeWithException(error) else continuation.resume(result) } } } suspend fun handleEchoSession(sessionSocket: AsynchronousSocketChannel) { val sessionId = SessionInfo.createSession() var echoCount = 0 sessionSocket.use { logger.info("Accepted session $sessionId") sessionSocket.suspendingWriteLine("Welcome client number $sessionId!") sessionSocket.suspendingWriteLine("I'll echo everything you send me. Finish with '$EXIT'. Ready when you are!") try { while (true) { val line = sessionSocket.suspendingReadLine() if (line == EXIT) break logger.info("Received line number '${++echoCount}'. Echoing it.") sessionSocket.suspendingWriteLine("($echoCount) Echo: $line") } sessionSocket.suspendingWriteLine("Bye!") } catch (cancelled: CancellationException) { withContext(NonCancellable) { sessionSocket.suspendingWriteLine("Server is shutting down for maintenance. Please come back later") } } finally { SessionInfo.endSession() } } }
0
Kotlin
0
8
a9c586ee9563cf46340cdfd5de5a9981839a8af9
4,402
s2122v-li43d-li41n
MIT License
app/src/main/java/com/example/minilydia/data/entity/remote/PictureEntity.kt
icodeyou
478,231,113
false
null
package com.example.minilydia.data.entity.remote data class PictureEntity( val large: String? = null, val medium: String? = null, val thumbnail: String? = null )
0
Kotlin
0
2
59f5126d0d8ace6c2cdad22a5456a9debf7b768d
174
minilydia
Apache License 2.0
src/main/kotlin/com/lithium/kapitalize/Kapitalize.kt
leosarra
178,259,303
false
{"Kotlin": 10051}
package com.lithium.kapitalize import com.lithium.kapitalize.languages.EnglishLanguage import com.lithium.kapitalize.languages.Language import com.lithium.kapitalize.languages.SpecialRules class Kapitalize(private val language: Language = EnglishLanguage(SpecialRules.NONE)) { fun capitalize(input: String): String { return language.transform(this, input) } }
0
Kotlin
0
1
36b37c614934493c613bff51a1297b2b45ae8af2
378
kapitalize
MIT License
Patient/app/src/main/java/com/signalDoc_patient/ui/fragment/SignupLoginPhase/LoginFragment.kt
Signal-A-Doc
253,424,098
false
null
package com.signalDoc_patient.ui.fragment.SignupLoginPhase import android.app.Dialog import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.text.method.PasswordTransformationMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProviders import com.google.gson.Gson import com.signalDoc_patient.BuildConfig import com.signalDoc_patient.R import com.signalDoc_patient.databinding.DialogRatingBinding import com.signalDoc_patient.databinding.FragmentLoginBinding import com.signalDoc_patient.model.ProfileData import com.signalDoc_patient.ui.activity.LoginSignUpActivity import com.signalDoc_patient.ui.activity.MainActivity import com.signalDoc_patient.ui.extensions.checkString import com.signalDoc_patient.ui.extensions.replaceFragment import com.signalDoc_patient.ui.fragment.BaseFragment import com.signalDoc_patient.utils.Const import com.signalDoc_patient.viewModel.LoginSignupViewModel.SignupViewModel import kotlinx.android.synthetic.main.fragment_login.* import org.json.JSONException import org.json.JSONObject class LoginFragment : BaseFragment() { private var binding: FragmentLoginBinding? = null private lateinit var signupViewModel: SignupViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) signupViewModel = ViewModelProviders.of(this)[SignupViewModel::class.java] signupViewModel.setData(baseActivity!!, restFullClient!!, api!!, this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { (baseActivity as LoginSignUpActivity).setToolbar(false) if (binding == null) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false) } return binding!!.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initUI() } private fun initUI() { if (BuildConfig.DEBUG) { emailET.setText("<EMAIL>") passwordET.setText("<PASSWORD>") } passwordET.transformationMethod = PasswordTransformationMethod() binding!!.loginBT.setOnClickListener(this) binding!!.forgetPassTV.setOnClickListener(this) binding!!.createAccountTV.setOnClickListener(this) binding!!.hideIV.setOnClickListener(this) binding!!.showIV.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.loginBT -> { if (signupViewModel.isLoginValidate(emailET, passwordET)) { signupViewModel.hitLoginApi(emailET.checkString(), passwordET.checkString()) } } R.id.forgetPassTV -> baseActivity!!.showErrorToast(baseActivity!!.getString(R.string.under_delvelopment)) R.id.createAccountTV -> baseActivity!!.replaceFragment(SignUpFragment(), R.id.login_frame) R.id.showIV -> { hideIV.visibility = View.VISIBLE showIV.visibility = View.GONE passwordET.transformationMethod = null } R.id.hideIV -> { hideIV.visibility = View.GONE showIV.visibility = View.VISIBLE passwordET.transformationMethod = PasswordTransformationMethod() } } } private fun gotoMainActivity() { startActivity(Intent(baseActivity, MainActivity::class.java)) baseActivity!!.finish() } override fun onSuccess(responseCode: Int, responseMessage: String, responseUrl: String, jsonObject: JSONObject) { super.onSuccess(responseCode, responseMessage, responseUrl, jsonObject) try { if (responseUrl.equals(Const.API_LOGIN)) { if (responseCode == Const.STATUS_OK) { if (jsonObject.has("message")) { baseActivity!!.showSuccessToast(jsonObject.getString("message")) } if (jsonObject.has("user_detail")) { val data = Gson().fromJson(jsonObject.getJSONObject("user_detail").toString(), ProfileData::class.java) baseActivity!!.restFullClient!!.setLoginStatus(jsonObject.getString("access-token")) store!!.saveProfileDataInPrefStore(data) gotoMainActivity() } } } } catch (e: JSONException) { baseActivity!!.printJsonException(e) } } }
0
Kotlin
0
0
ba6b7e75164ef04e42122841d47465bd4ad88a9f
4,848
android
MIT License
app/src/main/kotlin/com/apps/longhrk/ui/HRKApp.kt
LongHRK1912
835,793,057
false
{"Kotlin": 780216, "Shell": 15556}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apps.longhrk.ui import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarDuration.Indefinite import androidx.compose.material3.SnackbarDuration.Short import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult.ActionPerformed import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.adaptive.WindowAdaptiveInfo import androidx.compose.material3.adaptive.currentWindowAdaptiveInfo import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavDestination import androidx.navigation.NavDestination.Companion.hierarchy import com.apps.longhrk.R import com.apps.longhrk.core.designsystem.component.HRKBackground import com.apps.longhrk.core.designsystem.component.HRKGradientBackground import com.apps.longhrk.core.designsystem.component.HRKNavigationSuiteScaffold import com.apps.longhrk.core.designsystem.component.HRKTopAppBar import com.apps.longhrk.core.designsystem.icon.NiaIcons import com.apps.longhrk.core.designsystem.theme.GradientColors import com.apps.longhrk.core.designsystem.theme.LocalGradientColors import com.apps.longhrk.navigation.HRKNavHost import com.apps.longhrk.navigation.TopLevelDestination @Composable fun HRKApp( appState: HRKAppState, modifier: Modifier = Modifier, windowAdaptiveInfo: WindowAdaptiveInfo = currentWindowAdaptiveInfo(), ) { val shouldShowGradientBackground = appState.currentTopLevelDestination == TopLevelDestination.HOME var showSettingsDialog by rememberSaveable { mutableStateOf(false) } HRKBackground(modifier = modifier) { HRKGradientBackground( gradientColors = if (shouldShowGradientBackground) { LocalGradientColors.current } else { GradientColors() }, ) { val snackbarHostState = remember { SnackbarHostState() } val isOffline by appState.isOffline.collectAsStateWithLifecycle() // If user is not connected to the internet show a snack bar to inform them. val notConnectedMessage = stringResource(R.string.not_connected) LaunchedEffect(isOffline) { if (isOffline) { snackbarHostState.showSnackbar( message = notConnectedMessage, duration = Indefinite, ) } } HRKApp( appState = appState, snackbarHostState = snackbarHostState, onTopAppBarActionClick = { showSettingsDialog = true }, windowAdaptiveInfo = windowAdaptiveInfo, ) } } } @Composable @OptIn( ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class, ) internal fun HRKApp( appState: HRKAppState, snackbarHostState: SnackbarHostState, onTopAppBarActionClick: () -> Unit, modifier: Modifier = Modifier, windowAdaptiveInfo: WindowAdaptiveInfo = currentWindowAdaptiveInfo(), ) { val unreadDestinations by appState.topLevelDestinationsWithUnreadResources .collectAsStateWithLifecycle() val currentDestination = appState.currentDestination HRKNavigationSuiteScaffold( navigationSuiteItems = { appState.topLevelDestinations.forEach { destination -> val hasUnread = unreadDestinations.contains(destination) val selected = currentDestination.isTopLevelDestinationInHierarchy(destination) item( selected = selected, onClick = { appState.navigateToTopLevelDestination(destination) }, icon = { Icon( imageVector = destination.unselectedIcon, contentDescription = null, ) }, selectedIcon = { Icon( imageVector = destination.selectedIcon, contentDescription = null, ) }, label = { Text(stringResource(destination.iconTextId)) }, modifier = Modifier .testTag("NiaNavItem") .then(if (hasUnread) Modifier.notificationDot() else Modifier), ) } }, windowAdaptiveInfo = windowAdaptiveInfo, ) { Scaffold( modifier = modifier.semantics { testTagsAsResourceId = true }, containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.onBackground, contentWindowInsets = WindowInsets(0, 0, 0, 0), snackbarHost = { SnackbarHost(snackbarHostState) }, ) { padding -> Column( Modifier .fillMaxSize() .padding(padding) .consumeWindowInsets(padding) .windowInsetsPadding( WindowInsets.safeDrawing.only( WindowInsetsSides.Horizontal, ), ), ) { // Show the top app bar on top level destinations. val destination = appState.currentTopLevelDestination val shouldShowTopAppBar = destination != null if (destination != null) { HRKTopAppBar( titleRes = destination.titleTextId, navigationIcon = NiaIcons.Search, navigationIconContentDescription = stringResource( id = 0, ), actionIcon = NiaIcons.Settings, actionIconContentDescription = stringResource( id = 0, ), colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = Color.Transparent, ), onActionClick = { onTopAppBarActionClick() }, onNavigationClick = { }, ) } Box( // Workaround for https://issuetracker.google.com/338478720 modifier = Modifier.consumeWindowInsets( if (shouldShowTopAppBar) { WindowInsets.safeDrawing.only(WindowInsetsSides.Top) } else { WindowInsets(0, 0, 0, 0) }, ), ) { HRKNavHost( appState = appState, onShowSnackbar = { message, action -> snackbarHostState.showSnackbar( message = message, actionLabel = action, duration = Short, ) == ActionPerformed }, ) } // TODO: We may want to add padding or spacer when the snackbar is shown so that // content doesn't display behind it. } } } } private fun Modifier.notificationDot(): Modifier = composed { val tertiaryColor = MaterialTheme.colorScheme.tertiary drawWithContent { drawContent() drawCircle( tertiaryColor, radius = 5.dp.toPx(), // This is based on the dimensions of the NavigationBar's "indicator pill"; // however, its parameters are private, so we must depend on them implicitly // (NavigationBarTokens.ActiveIndicatorWidth = 64.dp) center = center + Offset( 64.dp.toPx() * .45f, 32.dp.toPx() * -.45f - 6.dp.toPx(), ), ) } } private fun NavDestination?.isTopLevelDestinationInHierarchy(destination: TopLevelDestination) = this?.hierarchy?.any { it.route?.contains(destination.name, true) ?: false } ?: false
0
Kotlin
0
0
c24e5897e5b9fd93f82ccc8139b02d793cb26830
10,591
ReadFile
Apache License 2.0
sykepenger-model/src/main/kotlin/no/nav/helse/serde/api/builders/SykdomstidslinjeBuilder.kt
navikt
193,907,367
false
null
package no.nav.helse.serde.api.builders import no.nav.helse.hendelser.* import no.nav.helse.serde.api.SykdomstidslinjedagDTO import no.nav.helse.serde.mapping.SpeilDagtype import no.nav.helse.serde.mapping.SpeilKildetype import no.nav.helse.sykdomstidslinje.Dag import no.nav.helse.sykdomstidslinje.Sykdomstidslinje import no.nav.helse.sykdomstidslinje.SykdomstidslinjeHendelse import no.nav.helse.økonomi.Økonomi import java.time.LocalDate internal class SykdomstidslinjeBuilder(private val sykdomstidslinjeListe: MutableList<SykdomstidslinjedagDTO> = mutableListOf()) : BuilderState() { internal fun build() = sykdomstidslinjeListe.toList() override fun visitDag(dag: Dag.UkjentDag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde) = leggTilDag(dag, dato, null, kilde) override fun visitDag(dag: Dag.Arbeidsdag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde) = leggTilDag(dag, dato, null, kilde) override fun visitDag( dag: Dag.Arbeidsgiverdag, dato: LocalDate, økonomi: Økonomi, kilde: SykdomstidslinjeHendelse.Hendelseskilde ) = leggTilDag(dag, dato, økonomi, kilde) override fun visitDag(dag: Dag.Feriedag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde) = leggTilDag(dag, dato, null, kilde) override fun visitDag(dag: Dag.FriskHelgedag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde) = leggTilDag(dag, dato, null, kilde) override fun visitDag( dag: Dag.ArbeidsgiverHelgedag, dato: LocalDate, økonomi: Økonomi, kilde: SykdomstidslinjeHendelse.Hendelseskilde ) = leggTilDag(dag, dato, økonomi, kilde) override fun visitDag( dag: Dag.Sykedag, dato: LocalDate, økonomi: Økonomi, kilde: SykdomstidslinjeHendelse.Hendelseskilde ) = leggTilDag(dag, dato, økonomi, kilde) override fun visitDag( dag: Dag.ForeldetSykedag, dato: LocalDate, økonomi: Økonomi, kilde: SykdomstidslinjeHendelse.Hendelseskilde ) = leggTilDag(dag, dato, økonomi, kilde) override fun visitDag( dag: Dag.SykHelgedag, dato: LocalDate, økonomi: Økonomi, kilde: SykdomstidslinjeHendelse.Hendelseskilde ) = leggTilDag(dag, dato, økonomi, kilde) override fun visitDag(dag: Dag.Permisjonsdag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde) = leggTilDag(dag, dato, null, kilde) override fun visitDag(dag: Dag.ProblemDag, dato: LocalDate, kilde: SykdomstidslinjeHendelse.Hendelseskilde, melding: String) = leggTilDag(dag, dato, null, kilde) private fun leggTilDag(dag: Dag, dato: LocalDate, økonomi: Økonomi?, kilde: SykdomstidslinjeHendelse.Hendelseskilde) { val dagDto = SykdomstidslinjedagDTO( dato, dag.toSpeilDagtype(), SykdomstidslinjedagDTO.KildeDTO(kilde.toSpeilKildetype(), kilde.meldingsreferanseId()), økonomi?.medData { grad, _, _ -> grad } ) sykdomstidslinjeListe.add(dagDto) } private fun SykdomstidslinjeHendelse.Hendelseskilde.toSpeilKildetype() = when { erAvType(Inntektsmelding::class) -> SpeilKildetype.Inntektsmelding erAvType(Søknad::class) -> SpeilKildetype.Søknad erAvType(Sykmelding::class) -> SpeilKildetype.Sykmelding erAvType(OverstyrTidslinje::class) -> SpeilKildetype.Saksbehandler else -> SpeilKildetype.Ukjent } private fun Dag.toSpeilDagtype() = when (this) { is Dag.Sykedag -> SpeilDagtype.SYKEDAG is Dag.UkjentDag -> SpeilDagtype.ARBEIDSDAG is Dag.Arbeidsdag -> SpeilDagtype.ARBEIDSDAG is Dag.Arbeidsgiverdag -> SpeilDagtype.ARBEIDSGIVERDAG is Dag.Feriedag -> SpeilDagtype.FERIEDAG is Dag.FriskHelgedag -> SpeilDagtype.FRISK_HELGEDAG is Dag.ArbeidsgiverHelgedag -> SpeilDagtype.ARBEIDSGIVERDAG is Dag.ForeldetSykedag -> SpeilDagtype.FORELDET_SYKEDAG is Dag.SykHelgedag -> SpeilDagtype.SYK_HELGEDAG is Dag.Permisjonsdag -> SpeilDagtype.PERMISJONSDAG is Dag.ProblemDag -> SpeilDagtype.UBESTEMTDAG is Dag.AvslåttDag -> SpeilDagtype.AVSLÅTT } override fun postVisitSykdomstidslinje(tidslinje: Sykdomstidslinje, låstePerioder: MutableList<Periode>) { popState() } }
0
Kotlin
2
4
470b02c1f41847ea2afcf2c4fd78ae66229b03d5
4,392
helse-spleis
MIT License
app/src/main/java/com/yilmaz/hybridtranslationapp/ListTranslationAdapter.kt
burraaook
679,711,808
false
null
package com.yilmaz.hybridtranslationapp import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView class ListTranslationAdapter(val translatorList : ArrayList<String>) : RecyclerView.Adapter<ListTranslationAdapter.TranslatorHolder>() { class TranslatorHolder (itemView : View) : RecyclerView.ViewHolder(itemView) { } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TranslatorHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.recycler_row, parent, false) return TranslatorHolder(view) } override fun getItemCount(): Int { return translatorList.size } override fun onBindViewHolder(holder: TranslatorHolder, position: Int) { holder.itemView.findViewById<TextView>(R.id.recyclerRowText) .text = translatorList[position] holder.itemView.setOnClickListener { if (translatorList[position].equals("ML-KIT Translator")) { val action = TranslationListFragmentDirections .actionTranslationListFragmentToMlkitFragment() Navigation.findNavController(it).navigate(action) } else if (translatorList[position].equals("Google Cloud API Translator")) { val action = TranslationListFragmentDirections .actionTranslationListFragmentToGCFragment() Navigation.findNavController(it).navigate(action) } else if (translatorList[position].equals("Advanced ML-KIT Translator")) { val action = TranslationListFragmentDirections .actionTranslationListFragmentToAdvancedMLKITFragment() Navigation.findNavController(it).navigate(action) } } } }
0
Kotlin
0
0
b26cb47f15da05c2734e3d2e88e17eb82f85755e
1,981
hybrid-translation-app
MIT License
ktorfit/src/main/java/com/jintin/ktorfit/POST.kt
Jintin
549,049,000
false
{"Kotlin": 15183}
package com.jintin.ktorfit @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.SOURCE) annotation class POST(val path: String)
0
Kotlin
0
1
18bc1ca6573b2280fa5aa93a221fb90135e955a8
142
Ktorfit
Apache License 2.0
services/hanke-service/src/main/kotlin/fi/hel/haitaton/hanke/permissions/Kayttooikeustaso.kt
City-of-Helsinki
300,534,352
false
{"Kotlin": 1149104, "Python": 56759, "Mustache": 55964, "Shell": 21528, "Batchfile": 4764, "Dockerfile": 1251, "PLpgSQL": 555}
package fi.hel.haitaton.hanke.permissions import jakarta.persistence.Entity import jakarta.persistence.EnumType import jakarta.persistence.Enumerated import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.Table import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository enum class Kayttooikeustaso { KAIKKI_OIKEUDET, KAIKKIEN_MUOKKAUS, HANKEMUOKKAUS, HAKEMUSASIOINTI, KATSELUOIKEUS } @Entity @Table(name = "kayttooikeustaso") class KayttooikeustasoEntity( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Int = 0, @Enumerated(EnumType.STRING) val kayttooikeustaso: Kayttooikeustaso, val permissionCode: Long, ) { fun hasPermission(permission: PermissionCode): Boolean = permissionCode and permission.code > 0 val permissionCodes: List<PermissionCode> get() = PermissionCode.entries.filter(this::hasPermission) } @Repository interface KayttooikeustasoRepository : JpaRepository<KayttooikeustasoEntity, Int> { fun findOneByKayttooikeustaso(kayttooikeustaso: Kayttooikeustaso): KayttooikeustasoEntity }
5
Kotlin
5
2
cc26ead5048b0cc11bb6729f14707085a46225cf
1,209
haitaton-backend
MIT License
library/src/main/java/com/angcyo/library/annotation/FunctionConfig.kt
angcyo
229,037,615
false
{"Kotlin": 6706235, "JavaScript": 5194}
package com.angcyo.library.annotation /** * 功能开关配置, 描述当前属性是一个功能 * @author <a href="mailto:<EMAIL>">angcyo</a> * @since 2022-10-20 */ @MustBeDocumented @Retention(AnnotationRetention.SOURCE) @Target( AnnotationTarget.PROPERTY, AnnotationTarget.FIELD, ) annotation class FunctionConfig(val des: String = "" /*功能的描述*/)
0
Kotlin
6
5
83f761e205ed6ce510599bf92ceafc508f5645e7
330
UICore
MIT License
app/src/test/java/com/github/takahirom/roborazzi/compare/on/github/comment/MainActivityScreenshotTest.kt
takahirom
636,076,436
false
{"Kotlin": 6874}
package com.github.takahirom.roborazzi.compare.on.github.comment import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.test.espresso.Espresso.onView import androidx.test.espresso.matcher.ViewMatchers import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.takahirom.roborazzi.DEFAULT_ROBORAZZI_OUTPUT_DIR_PATH import com.github.takahirom.roborazzi.captureRoboImage import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.GraphicsMode @RunWith(AndroidJUnit4::class) @GraphicsMode(GraphicsMode.Mode.NATIVE) class MainActivityScreenshotTest { @get:Rule val composeRule = createAndroidComposeRule<MainActivity>() @Test fun launch() { // Espresso onView(ViewMatchers.isRoot()) .captureRoboImage(outputPath("espresso_root")) // Compose test composeRule.onNode(hasTestTag("hello_text")) .captureRoboImage(outputPath("compose_text")) } private fun outputPath(name: String) = "$DEFAULT_ROBORAZZI_OUTPUT_DIR_PATH/$name.png" }
7
Kotlin
1
9
475685723f0ac095911a261235144a28e1038599
1,100
roborazzi-compare-on-github-comment-sample
Apache License 2.0
core-ui/src/main/java/com/anytypeio/anytype/core_ui/features/objects/holders/ObjectTypeHolder.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.core_ui.features.objects.holders import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.anytypeio.anytype.core_ui.R import com.anytypeio.anytype.core_ui.databinding.ItemObjectTypeHorizontalItemBinding import com.anytypeio.anytype.core_ui.databinding.ItemObjectTypeItemBinding import com.anytypeio.anytype.core_utils.ext.gone import com.anytypeio.anytype.core_utils.ext.visible import com.anytypeio.anytype.presentation.objects.ObjectTypeView class ObjectTypeHolder( val binding: ItemObjectTypeItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(item: ObjectTypeView) = with(binding) { if (item.isSelected) { icSelected.visible() } else { icSelected.gone() } ivIcon.setIcon( emoji = item.emoji, image = null, name = item.name ) tvTitle.text = item.name if (item.description.isNullOrBlank()) { tvSubtitle.gone() } else { tvSubtitle.visible() tvSubtitle.text = item.description } } } class ObjectTypeHorizontalHolder( val binding: ItemObjectTypeHorizontalItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(item: ObjectTypeView) = with(binding) { icon.setIcon( emoji = item.emoji, image = null, name = item.name ) name.text = item.name } } class ObjectTypeSearchHolder(parent: ViewGroup) : RecyclerView.ViewHolder( LayoutInflater.from(parent.context).inflate( R.layout.item_object_type_search, parent, false ) )
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
1,724
anytype-kotlin
RSA Message-Digest License
app/src/main/java/com/al/custom_view/small_red_book_start/use_rv/FitImageView.kt
Chen-keeplearn
262,473,049
false
null
package com.al.custom_view.small_red_book_start.use_rv import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import androidx.appcompat.widget.AppCompatImageView /** * 图片宽度充满屏幕,高度按比例生成 */ class FitImageView @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, defaultAttr: Int = 0 ) : AppCompatImageView(context, attributeSet, defaultAttr) { private val mDrawable: Drawable? = drawable override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { if (mDrawable != null) { val width = MeasureSpec.getSize(widthMeasureSpec) val height = width * mDrawable.intrinsicHeight / mDrawable.intrinsicWidth setMeasuredDimension(width,height) } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } } }
0
Kotlin
0
1
d0cf46c60d3eceb5c35e295155b575dafc671791
892
CustomView
Apache License 2.0
features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesView.kt
vector-im
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.analytics.api.preferences import androidx.annotation.StringRes import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.features.analytics.api.AnalyticsOptInEvents import io.element.android.libraries.designsystem.LinkColor import io.element.android.libraries.designsystem.components.preferences.PreferenceCategory import io.element.android.libraries.designsystem.components.preferences.PreferenceSwitch import io.element.android.libraries.designsystem.preview.ElementPreviewDark import io.element.android.libraries.designsystem.preview.ElementPreviewLight import io.element.android.libraries.ui.strings.R as StringR @Composable fun AnalyticsPreferencesView( state: AnalyticsPreferencesState, modifier: Modifier = Modifier, ) { fun onEnabledChanged(isEnabled: Boolean) { state.eventSink(AnalyticsOptInEvents.EnableAnalytics(isEnabled = isEnabled)) } PreferenceCategory(title = stringResource(id = StringR.string.screen_analytics_settings_share_data)) { val firstPart = stringResource(id = StringR.string.screen_analytics_settings_help_us_improve, state.applicationName) val secondPart = buildAnnotatedStringWithColoredPart( StringR.string.screen_analytics_settings_read_terms, StringR.string.screen_analytics_settings_read_terms_content_link ) val title = "$firstPart\n\n$secondPart" PreferenceSwitch( title = title, isChecked = state.isEnabled, onCheckedChange = ::onEnabledChanged ) } } @Composable fun buildAnnotatedStringWithColoredPart( @StringRes fullTextRes: Int, @StringRes coloredTextRes: Int, color: Color = LinkColor, underline: Boolean = true, ) = buildAnnotatedString { val coloredPart = stringResource(coloredTextRes) val fullText = stringResource(fullTextRes, coloredPart) val startIndex = fullText.indexOf(coloredPart) append(fullText) addStyle( style = SpanStyle( color = color, textDecoration = if (underline) TextDecoration.Underline else null ), start = startIndex, end = startIndex + coloredPart.length ) } @Preview @Composable fun AnalyticsPreferencesViewLightPreview(@PreviewParameter(AnalyticsPreferencesStateProvider::class) state: AnalyticsPreferencesState) = ElementPreviewLight { ContentToPreview(state) } @Preview @Composable fun AnalyticsPreferencesViewDarkPreview(@PreviewParameter(AnalyticsPreferencesStateProvider::class) state: AnalyticsPreferencesState) = ElementPreviewDark { ContentToPreview(state) } @Composable private fun ContentToPreview(state: AnalyticsPreferencesState) { AnalyticsPreferencesView(state) }
101
Kotlin
25
183
5f79988c06daa6e5eb27223bc3db821edb0865bc
3,723
element-x-android
Apache License 2.0
app/src/main/java/danielabbott/personalorganiser/ui/SpinnerChangeDetector.kt
danielabbott
266,279,538
false
null
package danielabbott.personalorganiser.ui import android.view.View import android.widget.AdapterView class SpinnerChangeDetector(val onClick: (View) -> Unit) : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } private var x = false override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // First call to this function is ignored (for some reason Android calls it when the view is created) if (x && view != null) { onClick(view) } x = true } }
0
Kotlin
0
0
02beaf1ecaeab1db5656acaf796bc530b3543c47
595
Day-Planner-App
MIT License
app/src/main/java/com/breezebaruch/features/viewAllOrder/interf/EmptyProductOnClick.kt
DebashisINT
863,564,790
false
{"Kotlin": 15819808, "Java": 1028932}
package com.breezebaruch.features.viewAllOrder.interf import com.breezebaruch.features.viewAllOrder.model.ProductOrder interface EmptyProductOnClick { fun emptyProductOnCLick(emptyFound:Boolean) fun delProductOnCLick(isDel:Boolean) }
0
Kotlin
0
0
5ff295242877825b98ac559a3a10320a77130181
243
BaruchEngineering
Apache License 2.0
log4k/src/main/java/com/shenhua/libs/log4k/handler/BundleHandler.kt
shenhuanet
116,492,844
false
null
package com.shenhua.libs.log4k.handler import android.os.Bundle import android.util.Log import com.google.gson.Gson import com.shenhua.libs.log4k.LK import com.shenhua.libs.log4k.core.BaseHandler import com.shenhua.libs.log4k.core.Box import com.shenhua.libs.log4k.ext.Constant import com.shenhua.libs.log4k.ext.Utils import org.json.JSONException import org.json.JSONObject /** * Created by shenhua on 2018-01-09-0009. * @author shenhua * Email <EMAIL> */ class BundleHandler : BaseHandler() { override fun handle(obj: Any): Boolean { if (obj is Bundle) { val map = HashMap<String, Any>() val gson = Gson() for (key in obj.keySet()) { try { if (Utils.isPrimitiveType(obj.get(key))) { map.put(key.toString(), obj.get(key)) } else { map.put(key.toString(), JSONObject(gson.toJson(obj.get(key)))) } } catch (e: JSONException) { LK.e("Invalid Json") } } val jsonObject = JSONObject(map) var message = jsonObject.toString(Constant.JSON_INDENT) message = message.replace("\n".toRegex(), "\n║ ") val msg = obj.javaClass.toString() + Constant.BR + "║ " Log.d(LK.TAG, String.format(Box.getBox(), msg + message)) return true } return false } }
0
Kotlin
0
1
3bdc1a770d0c93cc610d1dc71da284ede21fba07
1,477
Log4k
Apache License 2.0
elmslie-samples/coroutines-loader/src/main/java/vivid/money/elmslie/samples/coroutines/timer/elm/TimerReducer.kt
vivid-money
328,970,240
false
null
package vivid.money.elmslie.samples.coroutines.timer.elm import vivid.money.elmslie.core.store.dsl_reducer.DslReducer internal object TimerReducer : DslReducer<Event, State, Effect, Command>() { override fun Result.reduce(event: Event) = when (event) { is Event.Init -> Unit is Event.Start -> { state { copy(isStarted = true) } commands { +Command.Start } } is Event.Stop -> { state { copy(isStarted = false) } commands { +Command.Stop } } is Event.OnTimeTick -> { state { copy(secondsPassed = secondsPassed + 1) } } is Event.OnTimeError -> { state { copy(isStarted = false) } effects { +Effect.Error(event.throwable) } } } }
7
Kotlin
12
94
fb50f3714da87a912e50bfe95edd6b08eb020b26
793
elmslie
Apache License 2.0
src/main/kotlin/com/stannia/plugin/example_plugin/commands/plugin_config/actions/ConfigKeyTabCompleter.kt
stanniamc
446,668,111
false
{"Kotlin": 22983, "Java": 1039}
package com.stannia.plugin.example_plugin.commands.plugin_config.actions import com.stannia.plugin.api.library.commands.types.SimpleServerCommand import com.stannia.plugin.api.library.commands.types.utils.Args import com.stannia.plugin.api.library.commands.types.utils.Suggestions import com.stannia.plugin.api.library.extensions.parseColors import org.bukkit.command.CommandSender abstract class ConfigKeyTabCompleter : SimpleServerCommand() { /** * Tab completion that will show the possible configuration keys. * It will also warn users if they try to search with space. */ override fun tabComplete(sender: CommandSender, alias: String, args: Args): Suggestions { if (args.isEmpty()) return emptyList() val hookResult = tabCompleteConditionHook(args) if (hookResult != null) return hookResult val levels = args[0].split("\\.") val searchTerm = levels.subList(0, levels.size - 1).joinToString(".") return (plugin.config.getConfigurationSection(searchTerm)?.getKeys(true)?.toList() ?: emptyList<String>()) .filter { it.contains(args[0]) || it == args[0] } } open fun tabCompleteConditionHook(args: Args): Suggestions? = null }
2
Kotlin
0
0
4879110acf994858dba6ea31ef568e1bbbdf501f
1,225
plugin-base-kotlin
MIT License
sample/src/main/java/com/litesoftteam/mvvm/sample/presentation/navigation/MainActivityNavigator.kt
udfvirus
352,020,196
false
{"Kotlin": 29982}
/* * Copyright (C) 2021 Vitaliy Sychov * * 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.litesoftteam.mvvm.sample.presentation.navigation import com.litesoftteam.mvvm.presentation.navigation.BaseNavigator import com.litesoftteam.mvvm.sample.R import com.litesoftteam.mvvm.sample.presentation.screen.main.MainActivity class MainActivityNavigator(activity: MainActivity) : BaseNavigator(activity, R.id.fragmentContent)
2
Kotlin
0
1
24a5db9c7fd042c5c56e1e3e95882fdfa776a029
944
mvvmframework
Apache License 2.0
examples/src/tl/telegram/PhotoSize.kt
andreypfau
719,064,910
false
{"Kotlin": 62942}
// This file is generated by TLGenerator.kt // Do not edit manually! package tl.telegram import io.github.andreypfau.tl.serialization.Base64ByteStringSerializer import io.github.andreypfau.tl.serialization.TLCombinatorId import kotlin.jvm.JvmName import kotlinx.io.bytestring.ByteString import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonClassDiscriminator @Serializable @JsonClassDiscriminator("@type") public sealed interface PhotoSize { @Serializable @SerialName("photoSizeEmpty") @TLCombinatorId(0xE17E23C) public data class PhotoSizeEmpty( @get:JvmName("type") public val type: String, ) : tl.telegram.PhotoSize { public companion object } @Serializable @SerialName("photoSize") @TLCombinatorId(0x75C78E60) public data class PhotoSize( @get:JvmName("type") public val type: String, @get:JvmName("w") public val w: Int, @get:JvmName("h") public val h: Int, @get:JvmName("size") public val size: Int, ) : tl.telegram.PhotoSize { public companion object } @Serializable @SerialName("photoCachedSize") @TLCombinatorId(0x21E1AD6) public data class PhotoCachedSize( @get:JvmName("type") public val type: String, @get:JvmName("w") public val w: Int, @get:JvmName("h") public val h: Int, @get:JvmName("bytes") public val bytes: @Serializable(Base64ByteStringSerializer::class) ByteString, ) : tl.telegram.PhotoSize { public companion object } @Serializable @SerialName("photoStrippedSize") @TLCombinatorId(0xE0B0BC2E) public data class PhotoStrippedSize( @get:JvmName("type") public val type: String, @get:JvmName("bytes") public val bytes: @Serializable(Base64ByteStringSerializer::class) ByteString, ) : tl.telegram.PhotoSize { public companion object } @Serializable @SerialName("photoSizeProgressive") @TLCombinatorId(0xFA3EFB95) public data class PhotoSizeProgressive( @get:JvmName("type") public val type: String, @get:JvmName("w") public val w: Int, @get:JvmName("h") public val h: Int, @get:JvmName("sizes") public val sizes: List<Int>, ) : tl.telegram.PhotoSize { public companion object } @Serializable @SerialName("photoPathSize") @TLCombinatorId(0xD8214D41) public data class PhotoPathSize( @get:JvmName("type") public val type: String, @get:JvmName("bytes") public val bytes: @Serializable(Base64ByteStringSerializer::class) ByteString, ) : tl.telegram.PhotoSize { public companion object } public companion object }
0
Kotlin
0
1
16de3f335d8005e35543cb7515a810fd9ac4236d
2,872
tl-kotlin
MIT License
app/app/src/main/java/com/solutions/note_it/data/Note.kt
biagioPiraino
839,976,127
false
{"Kotlin": 90243, "Vue": 52032, "Go": 41922, "TypeScript": 22926, "HCL": 12288, "HTML": 335, "SCSS": 207}
package com.solutions.note_it.data import com.google.gson.annotations.SerializedName data class Note( @field:SerializedName("id") val id: String = "", @field:SerializedName("title") val title: String = "", @field:SerializedName("summary") val summary: String = "", @field:SerializedName("content") val content: String = "", @field:SerializedName("category") val category: Category = Category(type = CategoryType.Note.ordinal) ) { }
0
Kotlin
0
0
06117965f19ba6a028d9ee144cdec76d7dba4b92
453
note-it
MIT License
app/src/main/java/com/example/lieon/record/view/RecordAccuracyDialog.kt
LIE-ON
796,529,527
false
{"Kotlin": 49855}
package com.example.lieon.record.view import android.app.Dialog import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.WindowManager import android.widget.SeekBar import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.fragment.app.viewModels import com.example.lieon.R import com.example.lieon.databinding.DialogRecordAccuracyBinding class RecordAccuracyDialog(context: Context) : Dialog(context){ private var _binding : DialogRecordAccuracyBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = DialogRecordAccuracyBinding.inflate(LayoutInflater.from(context)) setContentView(binding.root) // window?.setLayout( // WindowManager.LayoutParams.MATCH_PARENT, // WindowManager.LayoutParams.WRAP_CONTENT // ) window?.setBackgroundDrawableResource(R.drawable.dialog_background) val window = window ?: return val layoutParams = window.attributes val marginHorizontal = (context.resources.displayMetrics.density * 25).toInt() layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT layoutParams.width = context.resources.displayMetrics.widthPixels - 2 * marginHorizontal window.attributes = layoutParams window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) setCanceledOnTouchOutside(true) setCancelable(true) val spf = context.getSharedPreferences("LieonPrefs",Context.MODE_PRIVATE) val beforeAccuracyGoal = spf.getInt("goalAccuracy",90) binding.accuracySeekbar.apply { progress = beforeAccuracyGoal setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{ override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { binding.accuracySeekbarTextview.text = progress.toString() } override fun onStartTrackingTouch(seekBar: SeekBar?) { } override fun onStopTrackingTouch(seekBar: SeekBar?) { } }) } binding.accuracySeekbarTextview.text = beforeAccuracyGoal.toString() binding.accuracySubmitButton.setOnClickListener { spf.edit() .putInt("goalAccuracy", binding.accuracySeekbar.progress) .apply() Toast.makeText(context, spf.getInt("goalAccuracy", 90).toString(), Toast.LENGTH_SHORT).show() dismiss() } } }
2
Kotlin
0
0
f92db6da4ceb8e5cb77fdaa0895381ec4685bcb9
2,766
Lieon_application
Apache License 2.0
app/src/main/java/com/ph03nix_x/capacityinfo/MainApp.kt
hobbit19
239,760,828
true
{"Kotlin": 136548}
package com.ph03nix_x.capacityinfo import android.app.Application import android.content.res.Configuration import android.os.Build import androidx.preference.PreferenceManager import com.ph03nix_x.capacityinfo.helpers.LocaleHelper import com.ph03nix_x.capacityinfo.helpers.ThemeHelper.isSystemDarkMode import com.ph03nix_x.capacityinfo.helpers.ThemeHelper.setTheme import com.ph03nix_x.capacityinfo.interfaces.BillingInterface import com.ph03nix_x.capacityinfo.utils.PreferencesKeys.LANGUAGE import com.ph03nix_x.capacityinfo.utils.Utils.billingClient import com.ph03nix_x.capacityinfo.utils.Utils.isInstalledGooglePlay import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch class MainApp : Application(), BillingInterface { companion object { var defLang: String = "en" } override fun onCreate() { super.onCreate() setTheme(this) if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) isSystemDarkMode(resources.configuration) defLang() isInstalledGooglePlay = isInstalledGooglePlay(this) if(isInstalledGooglePlay) billingClient() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) isSystemDarkMode(newConfig) if(LocaleHelper.getSystemLocale(newConfig) != defLang) defLang() } private fun defLang() { defLang = "en" val systemLanguage = LocaleHelper.getSystemLocale(resources.configuration) if(systemLanguage in resources.getStringArray(R.array.languages_codes)) defLang = systemLanguage val pref = PreferenceManager.getDefaultSharedPreferences(this) if(pref.getString(LANGUAGE, null) != defLang) pref.edit().putString(LANGUAGE, defLang).apply() } private fun billingClient() { CoroutineScope(Dispatchers.Default).launch { if(billingClient == null) billingClient = onBillingClientBuilder(this@MainApp) onBillingStartConnection() delay(5 * 1000) billingClient?.endConnection() billingClient = null } } }
0
null
0
0
26b6304bdf60cf9e10d523c55fa75d20475818a4
2,307
CapacityInfo
Apache License 2.0
modulecheck-parsing/android/src/main/kotlin/modulecheck/parsing/android/AndroidStylesParser.kt
RBusarow
316,627,145
false
null
/* * Copyright (C) 2021-2022 <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 modulecheck.parsing.android import groovy.util.Node import groovy.util.NodeList import modulecheck.parsing.source.McName.CompatibleLanguage.XML import modulecheck.parsing.source.UnqualifiedAndroidResource import modulecheck.parsing.source.UnqualifiedAndroidResourceReferenceName import modulecheck.utils.flatMapToSet import java.io.File class AndroidStylesParser { fun parseFile(file: File): Set<UnqualifiedAndroidResourceReferenceName> { val xmlParser = SafeXmlParser() return xmlParser.parse(file) ?.takeIf { it.name() == "resources" } ?.children() ?.filterIsInstance<Node>() ?.filter { it.name() == "style" } ?.map { parseNode(it) } .orEmpty() .flatMapToSet { it } } private fun parseNode(styleNode: Node): Set<UnqualifiedAndroidResourceReferenceName> { // We don't actually need this attribute, but if it isn't there, this isn't a valid style. styleNode.attribute("name")?.toString() ?: return emptySet() val parentOrNull = styleNode.attribute("parent") ?.toString() ?.let { parentName -> val declaration = when { // ex: `parent="@style/Theme.AppCompat.Light.DarkActionBar"` // ex: `parent="@android:style/Theme.AppCompat.Light.DarkActionBar"` parentName.startsWith("@") -> { UnqualifiedAndroidResource.fromXmlString(parentName) } // ex: `parent="Theme.AppCompat.Light.DarkActionBar"` // ex: `parent="android:Theme.AppCompat.Light.DarkActionBar"` else -> { UnqualifiedAndroidResource.fromValuePair( "style", parentName.removePrefix("android:") ) } } declaration?.let { UnqualifiedAndroidResourceReferenceName(it.name, XML) } } return styleNode.children() .asSequence() .filterIsInstance<Node>() .map { it.value() } .filterIsInstance<NodeList>() .mapNotNull { valueNodeList -> UnqualifiedAndroidResource.fromXmlString(valueNodeList.text()) ?.let { UnqualifiedAndroidResourceReferenceName(it.name, XML) } } .plus(listOfNotNull(parentOrNull)) .toSet() } }
76
Kotlin
7
95
24e7c7667490630d30cf8b59cd504cd863cd1fba
2,801
ModuleCheck
Apache License 2.0
app/src/main/java/com/frestoinc/sample/featuredelivery/MainApp.kt
frestoinc
587,570,663
false
null
package com.frestoinc.sample.featuredelivery import android.content.Context import com.google.android.play.core.splitcompat.SplitCompat import com.google.android.play.core.splitcompat.SplitCompatApplication import dagger.hilt.android.HiltAndroidApp import timber.log.Timber @HiltAndroidApp class MainApp : SplitCompatApplication() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree()) } override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) SplitCompat.install(this) } }
0
Kotlin
0
0
ff94bc46be1aad2fe560bbb1fd52bef33a703736
606
FeatureDelivery
Apache License 2.0
src/main/kotlin/com/lucas/matches/service/MatchService.kt
lasiqueira
373,864,866
false
null
package com.lucas.matches.service import com.lucas.matches.infrastructure.document.MatchDocument import com.lucas.matches.infrastructure.repository.MatchRepository import com.lucas.matches.service.converter.MatchConverter import com.lucas.matches.service.domain.License import com.lucas.matches.service.domain.LicenseType import com.lucas.matches.service.domain.Match import com.lucas.matches.service.util.LicenseParser import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.cache.annotation.CacheConfig import org.springframework.cache.annotation.Cacheable import org.springframework.stereotype.Service @Service @CacheConfig(cacheNames = ["match"]) class MatchService(licenseParser: LicenseParser, matchRepository: MatchRepository, matchConverter: MatchConverter) { private val logger: Logger = LoggerFactory.getLogger(MatchService::class.java) private val licenseParser: LicenseParser private val matchRepository: MatchRepository private val matchConverter: MatchConverter @Cacheable(key = "#licenseStringList") fun getMatches(licenseStringList: List<String>): List<Match> { logger.info("Parsing Licenses...") logger.debug(licenseStringList.toString()) val licenses = licenseParser.parse(licenseStringList) logger.info("Fetching matches...") val tournamentLicenses = licenses.filter { it.licenseType == LicenseType.TOURNAMENT } val matchLicenses = licenses.filter {it.licenseType == LicenseType.MATCH } return matchConverter.convert( getMatchesByTournamentId(tournamentLicenses)+ getMatchesByMatchId(matchLicenses) ) } private fun getMatchesByTournamentId(tournamentLicenses: List<License>): List<MatchDocument> { logger.info("Fetching Matches by Tournament ID...") val ids = tournamentLicenses.map { it.id } return matchRepository.findByTournamentIdIn(ids) } private fun getMatchesByMatchId(matchLicenses: List<License>): List<MatchDocument> { logger.info("Fetching Matches by Match ID...") val ids = matchLicenses.map { it.id } return matchRepository.findByMatchIdIn(ids) } init { this.licenseParser = licenseParser this.matchRepository = matchRepository this.matchConverter = matchConverter } }
0
Kotlin
0
0
838fc4158fc8ae2513666a19c49df93ffdfa2d57
2,383
matches
X.Net License
src/test/kotlin/no/nav/syfo/testhelper/TestApiModule.kt
navikt
696,687,106
false
{"Kotlin": 102469, "Dockerfile": 226}
package no.nav.syfo.testhelper import io.ktor.server.application.* import no.nav.syfo.application.api.apiModule import no.nav.syfo.client.veiledertilgang.VeilederTilgangskontrollClient import no.nav.syfo.huskelapp.HuskelappService import no.nav.syfo.huskelapp.database.HuskelappRepository fun Application.testApiModule( externalMockEnvironment: ExternalMockEnvironment, ) { val veilederTilgangskontrollClient = VeilederTilgangskontrollClient( azureAdClient = externalMockEnvironment.azureAdClient, clientEnvironment = externalMockEnvironment.environment.clients.istilgangskontroll, httpClient = externalMockEnvironment.mockHttpClient, ) val huskelappRepository = HuskelappRepository( database = externalMockEnvironment.database, ) val huskelappService = HuskelappService( huskelappRepository = huskelappRepository, ) this.apiModule( applicationState = externalMockEnvironment.applicationState, database = externalMockEnvironment.database, environment = externalMockEnvironment.environment, wellKnownInternalAzureAD = externalMockEnvironment.wellKnownInternalAzureAD, veilederTilgangskontrollClient = veilederTilgangskontrollClient, huskelappService = huskelappService, ) }
1
Kotlin
0
0
afa7aefe4b2a62f07dee9d31d14d1b8ef0a06144
1,299
ishuskelapp
MIT License
app/src/main/java/com/normanfr/todolist/TaskAlarmReciever.kt
normanfrdev
834,739,063
false
{"Kotlin": 23692}
package com.normanfr.todolist import android.content.BroadcastReceiver import android.content.Context import android.content.Intent class TaskAlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val task = intent.getParcelableExtra<Task>("task") task?.let { NotificationHelper(context).sendNotification(it) } } }
0
Kotlin
0
0
63144d325569d3d3e0a71c517cb4854fad7b83fc
403
ToDoList
MIT License
app/src/main/java/com/freeflowgfx/convolution/implementation/FunctionsUnderTest.kt
supercoder3000
330,186,248
false
null
package com.freeflowgfx.convolution.implementation interface FunctionsUnderTest { val implementationType: String fun convolution(signal: FloatArray, filter: FloatArray): FloatArray }
0
Kotlin
0
0
11840a312efc9ebab85def16c6cf902cbf3e9de8
192
benchmarking_android
MIT License
src/main/kotlin/kotlinmud/action/contextBuilder/OptionalFurnitureContextBuilder.kt
danielmunro
241,230,796
false
null
package kotlinmud.action.contextBuilder import kotlinmud.action.model.Context import kotlinmud.action.type.Status import kotlinmud.helper.string.matches import kotlinmud.io.type.Syntax import kotlinmud.item.model.Item class OptionalFurnitureContextBuilder(private val itemsInRoom: List<Item>) : ContextBuilder { override fun build(syntax: Syntax, word: String): Context<Any> { return itemsInRoom.find { word.matches(it.name) }?.let { Context<Any>(syntax, Status.OK, it) } ?: Context<Any>( syntax, Status.FAILED, "you can't find that anywhere." ) } }
0
Kotlin
1
9
b7ee0d21ae813990896b1b8c6703da9bd1f1fc5b
652
kotlinmud
MIT License
common/src/main/java/com/wan/common/constant/Const.kt
qinghuaAndroid
252,683,218
false
{"Kotlin": 278208, "Java": 73348}
package com.wan.common.constant /** * Description: 项目通用常量 * Created by cy on 2019/12/1. */ object Const { /*************************************BASE_URL部分 */ const val BASE_URL = "https://www.wanandroid.com/" /************************************存储键值部分 */ const val IS_LOGIN = "isLogin" /************************************通知事件部分 */ const val THEME_COLOR = "themeColor"//主题颜色 /*************************************传参部分 */ const val WEB_URL = "webUrl" const val WEB_TITLE = "webTitle" /*************************************Arouter extras */ const val NEED_LOGIN = 0X01 }
0
Kotlin
3
3
35e86bbc06a3ef306d3355432b8dc6cdb7217c1e
619
WanAndroid-MVVM
Apache License 2.0
src/main/kotlin/com/londogard/textgen/penalties/Penalty.kt
londogard
224,923,612
false
null
package com.londogard.textgen.penalties /** * [[Penalty]] is a way to penalize different behaviours given history and possible entries. * Example: [[NgramPenalty]] or perhaps you want to filter out swearwords? Or a Trademark? */ interface Penalty { /** * Penalize entries given history returning the updated probabilities. */ fun penalize(entries: List<Pair<Int, Double>>, history: List<Int>): List<Pair<Int, Double>> }
9
Kotlin
0
2
ee09162915a81b96d82e391147a87a5fdb0e0477
443
text-gen-kt
Apache License 2.0
app/src/main/java/co/zemogaapp/posts/data/entities/PostState.kt
ispam
301,282,691
false
null
package co.zemogaapp.posts.data.entities import co.zemogaapp.common.delegate.RecyclerViewType import co.zemogaapp.utils.SuccessData /** * Created by diego.urrea on 10/3/2020. */ sealed class PostState { object Empty: PostState() object Error: PostState() object Continue: PostState() object DeleteAll: PostState() class Initialized(val list: List<RecyclerViewType>): PostState() class Success(val data: SuccessData): PostState() }
0
Kotlin
0
0
07a59750a9aee0dd1f3f5b28f44d83fedf8caeea
458
ZemogaApp
Apache License 2.0
app/src/main/java/com/certified/audionote/adapter/NoteRecyclerAdapter.kt
certified84
435,328,596
false
null
/* * Copyright (c) 2021 <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.certified.audionote.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.certified.audionote.databinding.ItemNoteBinding import com.certified.audionote.model.Note import java.io.File class NoteRecyclerAdapter(private val files: Array<File>) : ListAdapter<Note, NoteRecyclerAdapter.ViewHolder>(DIFF_CALLBACK) { private lateinit var listener: OnItemClickedListener override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ItemNoteBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentItem = getItem(position) holder.bind(currentItem) } inner class ViewHolder(private val binding: ItemNoteBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(note: Note) { binding.note = note } init { itemView.setOnClickListener { val position = absoluteAdapterPosition if (position != RecyclerView.NO_POSITION) { listener.onItemClick(getItem(position)) } } } } interface OnItemClickedListener { fun onItemClick(item: Note) } fun setOnItemClickedListener(listener: OnItemClickedListener) { this.listener = listener } companion object { val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Note>() { override fun areItemsTheSame(oldItem: Note, newItem: Note) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Note, newItem: Note) = oldItem == newItem } } }
2
Kotlin
4
50
6b404551c76c70ebf7644746217818b91c1187ce
2,509
AudioNote
Apache License 2.0
src/main/kotlin/it/krzeminski/githubactionstyping/validation/types/Enum.kt
typesafegithub
502,427,408
false
{"Kotlin": 49359, "Dockerfile": 192}
package it.krzeminski.githubactionstyping.validation.types import it.krzeminski.githubactionstyping.parsing.ApiItem import it.krzeminski.githubactionstyping.validation.ItemValidationResult fun ApiItem.validateEnum(): ItemValidationResult { if (this.allowedValues == null) { return ItemValidationResult.Invalid("Allowed values must be specified.") } if (this.separator != null) { return ItemValidationResult.Invalid("'separator' is not allowed for this type.") } if (this.listItem != null) { return ItemValidationResult.Invalid("'list-item' is not allowed for this type.") } if (this.namedValues != null) { return ItemValidationResult.Invalid("'named-values' are currently supported only for integers.") } if (this.allowedValues.size < 2) { return ItemValidationResult.Invalid("There must be at least two allowed values.") } return ItemValidationResult.Valid }
7
Kotlin
2
35
49eb4c281cd14ed055ab3a47dabec4e48581fb58
946
github-actions-typing
Apache License 2.0
module-api/src/main/java/langchainkt/model/moderation/Moderation.kt
c0x12c
655,095,005
false
{"Kotlin": 322914, "Java": 13181}
package langchainkt.model.moderation data class Moderation( private val flagged: Boolean = false, private val flaggedText: String? = null ) { fun flagged(): Boolean { return flagged } fun flaggedText(): String? { return flaggedText } companion object { fun flagged(flaggedText: String): Moderation { return Moderation(flaggedText = flaggedText, flagged = true) } fun notFlagged(): Moderation { return Moderation() } } }
0
Kotlin
0
0
1dc065a3aec804d53259171f6f95206eb2fdb0b6
477
langchainkt
Apache License 2.0
backend/src/main/kotlin/com/kontinum/service/business/interface.kt
ToniDarodda
753,367,631
false
{"Kotlin": 88726, "TypeScript": 64760, "HTML": 1873}
package com.kontinum.service.business import com.kontinum.model.BusinessData import com.kontinum.model.User import com.kontinum.service.business.dto.* interface BusinessInterface { suspend fun createBusiness(data: BusinessCreateDTO): String? suspend fun loginBusiness(data: BusinessGetDTO): String? suspend fun getBusiness(businessId: Int): BusinessData? suspend fun getBusinessUser(businessId: Int): List<User>; suspend fun patchBusiness(businessId: Int, data: BusinessPatchDTO): Int suspend fun deleteBusiness(businessId: Int): Unit }
5
Kotlin
0
0
51414d8357d2183a41600ff6145aa7c67b9a9e6a
567
Kontinum
MIT License
gson-adapter/src/main/kotlin/fr/speekha/httpmocker/gson/GsonMapper.kt
EGecius
200,020,302
true
{"Kotlin": 185890, "Shell": 959}
/* * Copyright 2019 <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 fr.speekha.httpmocker.gson import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import fr.speekha.httpmocker.Mapper import fr.speekha.httpmocker.model.Header import fr.speekha.httpmocker.model.Matcher import fr.speekha.httpmocker.model.RequestDescriptor import fr.speekha.httpmocker.model.ResponseDescriptor import fr.speekha.httpmocker.gson.Header as JsonHeader import fr.speekha.httpmocker.gson.Matcher as JsonMatcher import fr.speekha.httpmocker.gson.RequestDescriptor as JsonRequestDescriptor import fr.speekha.httpmocker.gson.ResponseDescriptor as JsonResponseDescriptor /** * A mapper using Gson to serialize/deserialize scenarios. */ class GsonMapper : Mapper { private val adapter: Gson = GsonBuilder() .setPrettyPrinting() .disableHtmlEscaping() .registerTypeAdapter(HeaderAdapter.HeaderList::class.java, HeaderAdapter()) .create() private val dataType = MatcherType().type override fun deserialize(payload: String): List<Matcher> = adapter.parse(payload).map { it.toModel() } private fun Gson.parse(json: String) = fromJson<List<JsonMatcher>>(json, dataType) ?: emptyList() override fun serialize(matchers: List<Matcher>): String = adapter.toJson(matchers.map { it.fromModel() }) private class MatcherType : TypeToken<List<JsonMatcher>>() private fun Matcher.fromModel() = JsonMatcher(request.fromModel(), response.fromModel()) private fun JsonMatcher.toModel() = Matcher(request?.toModel() ?: RequestDescriptor(), response.toModel()) private fun JsonRequestDescriptor.toModel() = RequestDescriptor(exactMatch ?: false, protocol, method, host, port, path, headers.toModel(), params, body) private fun RequestDescriptor.fromModel() = JsonRequestDescriptor(exactMatch.takeIf { it }, protocol, method, host, port, path, getHeaders(), params, body) private fun RequestDescriptor.getHeaders() = HeaderAdapter.HeaderList(headers.map { it.fromModel() }) private fun JsonHeader.toModel() = Header(name, value) private fun Header.fromModel() = JsonHeader(name, value) private fun JsonResponseDescriptor.toModel() = ResponseDescriptor(delay, code, mediaType, headers.toModel(), body, bodyFile) private fun HeaderAdapter.HeaderList?.toModel() = this?.map { it.toModel() } ?: emptyList() private fun ResponseDescriptor.fromModel() = JsonResponseDescriptor( delay, code, mediaType, HeaderAdapter.HeaderList().apply { addAll(headers.map { it.fromModel() }) }, body, bodyFile ) }
0
Kotlin
0
0
cc3538de6a5b9a25fc5520194df9e2042c32b4e4
3,344
httpmocker
Apache License 2.0
AndroidKotlin-JSON/MainActivity.kt
narotamsingh
162,389,440
false
null
package com.example.json.kotlin_json import android.os.AsyncTask import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.activity_main.* import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL import org.json.JSONObject class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun get (view: View){ val downloadData = Download() try { val jsonObject = JSONObject(downloadData.execute("https://jigyasu.org/data/json.php").get()) val title = editText.text.toString() val jsonResult = jsonObject.getString(title) textView.text = "URL: " + jsonResult } catch (e: Exception) { e.printStackTrace() } } inner class Download : AsyncTask<String,Void,String>(){ override fun doInBackground(vararg adds: String?): String { var downloaded = "" var url : URL val httpConnection : HttpURLConnection try { url = URL(adds[0]) httpConnection = url.openConnection() as HttpURLConnection val input = httpConnection.inputStream val inputReader = InputStreamReader(input) var data = inputReader.read() while (data > 0) { val character = data.toChar() downloaded += character data = inputReader.read() } return downloaded } catch (e: Exception) { e.printStackTrace() return downloaded } } } }
0
Kotlin
0
0
1c0154f9d59058ddc8a88296c03e5c6659a1ec3e
1,844
Android-Kotlin
Apache License 2.0
player_usecases/src/test/java/com/vmenon/mpo/player/usecases/ListForPlaybackStateChangesTest.kt
hitoshura25
91,402,384
false
{"Kotlin": 574795, "HTML": 14355, "Gherkin": 11761, "Shell": 4889, "Ruby": 4474}
package com.vmenon.mpo.player.usecases import com.vmenon.mpo.player.domain.MediaPlayerEngine import com.vmenon.mpo.player.domain.PlaybackState import com.vmenon.mpo.system.domain.Clock import com.vmenon.mpo.system.domain.ThreadUtil import com.vmenon.mpo.test.TestData import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.* import kotlinx.coroutines.test.runBlockingTest import org.junit.Assert.assertEquals import org.junit.Test import org.mockito.kotlin.* @ExperimentalCoroutinesApi class ListForPlaybackStateChangesTest { private val playerEngine: MediaPlayerEngine = mock() @Test fun listenForChangesWhenEngineEmitsNewState() = runBlockingTest { val clock: Clock = mock() val threadUtil: ThreadUtil = object : ThreadUtil { override fun sleep(millis: Long) { Thread.sleep(millis) } override suspend fun delay(timeMillis: Long) { kotlinx.coroutines.delay(timeMillis) } } val playbackStates = listOf( TestData.playbackState.copy( state = PlaybackState.State.STOPPED, positionInMillis = 0L ), TestData.playbackState.copy( state = PlaybackState.State.PLAYING, positionInMillis = 100L ), TestData.playbackState.copy( state = PlaybackState.State.PAUSED, positionInMillis = 1000L ) ) val playbackStateChanges = flow { emit(playbackStates[0]) emit(playbackStates[1]) emit(playbackStates[2]) } whenever(playerEngine.playbackStateChanges).thenReturn(playbackStateChanges) val useCase = ListenForPlaybackStateChanges(playerEngine, clock, threadUtil) val items = useCase.invoke().take(3).toList() assertEquals(playbackStates[0], items[0]) assertEquals(playbackStates[1], items[1]) assertEquals(playbackStates[2], items[2]) } @Test fun listenForChangesEmitsNewStateWhenEstimationPosition() = runBlockingTest { val clock: Clock = mock() val threadUtil: ThreadUtil = object : ThreadUtil { override fun sleep(millis: Long) { Thread.sleep(millis) } override suspend fun delay(timeMillis: Long) { kotlinx.coroutines.delay(timeMillis) } } val playbackStates = listOf( TestData.playbackState.copy( state = PlaybackState.State.PLAYING, positionInMillis = 100L ), TestData.playbackState.copy( state = PlaybackState.State.PLAYING, positionInMillis = 200L ), TestData.playbackState.copy( state = PlaybackState.State.PLAYING, positionInMillis = 300L ) ) val playbackStateChanges = flow { emit(playbackStates[0]) } whenever(clock.currentTimeMillis()).thenReturn(0L).thenReturn(100L).thenReturn(200L) whenever(playerEngine.playbackStateChanges).thenReturn(playbackStateChanges) val useCase = ListenForPlaybackStateChanges(playerEngine, clock, threadUtil) val items = useCase.invoke().take(3).toList() assertEquals(playbackStates[0], items[0]) assertEquals(playbackStates[1], items[1]) assertEquals(playbackStates[2], items[2]) } @Test fun listenForChangesEmitsSameStateIfNotPlaying() = runBlockingTest { val clock: Clock = mock() val threadUtil: ThreadUtil = object : ThreadUtil { override fun sleep(millis: Long) { Thread.sleep(millis) } override suspend fun delay(timeMillis: Long) { kotlinx.coroutines.delay(timeMillis) } } val playbackState = TestData.playbackState.copy( state = PlaybackState.State.STOPPED, positionInMillis = 100L ) val playbackStateChanges = flow { emit(playbackState) } whenever(playerEngine.playbackStateChanges).thenReturn(playbackStateChanges) val useCase = ListenForPlaybackStateChanges(playerEngine, clock, threadUtil) val items = useCase.invoke().take(3).toList() assertEquals(playbackState, items[0]) assertEquals(playbackState, items[1]) assertEquals(playbackState, items[2]) } }
14
Kotlin
0
1
4a612f2c7b2bb7a569f961c391518756962d6b6f
4,551
Media-Player-Omega-Android
Apache License 2.0
app/src/main/java/me/manulorenzo/mapthecity/ui/city/CityListActivity.kt
noloman
231,260,348
false
{"Kotlin": 54517}
package me.manulorenzo.mapthecity.ui.city import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_city_list.landscapeLayout import kotlinx.android.synthetic.main.custom_appbar_layout.toolbar import me.manulorenzo.mapthecity.R import me.manulorenzo.mapthecity.ui.city.data.Coordinates class CityListActivity : AppCompatActivity() { /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private var twoPane: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_city_list) setSupportActionBar(toolbar) toolbar.title = title if (landscapeLayout != null) { // The detail container view will be present only in the // large-screen layouts (res/values-w900dp). // If this view is present, then the // activity should be in two-pane mode. twoPane = true } else { supportFragmentManager .beginTransaction() .replace(R.id.frameLayout, CityListFragment()) .commit() } supportFragmentManager.addOnBackStackChangedListener { if (supportFragmentManager.backStackEntryCount > 0) { supportActionBar?.setDisplayHomeAsUpEnabled(true) // show back button toolbar.setNavigationOnClickListener { onBackPressed() } } else { supportActionBar?.setDisplayHomeAsUpEnabled(false) } } } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } fun loadCityMapFragmentWhenClicked(coordinates: Coordinates) { if (twoPane) { // It's two pane - we load the fragment val fragment = supportFragmentManager.findFragmentByTag(CityMapFragment::class.java.simpleName) as CityMapFragment fragment.onCityChanged(coordinates) } else { // it's NOT two pane so replace the current fragment by the MapFragment val fragment = CityMapFragment().apply { arguments = Bundle().apply { putParcelable(CityMapFragment.CITY_COORDINATES_KEY, coordinates) } } supportFragmentManager .beginTransaction() .replace(R.id.frameLayout, fragment) .addToBackStack(null) .commit() } } }
11
Kotlin
0
2
e5a14c8e8eca581b44e078dd79595a16ad4079ad
2,804
MapTheCity
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/emr/CfnInstanceFleetConfigVolumeSpecificationPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.emr import cloudshift.awscdk.common.CdkDslMarker import kotlin.Number import kotlin.String import software.amazon.awscdk.services.emr.CfnInstanceFleetConfig /** * `VolumeSpecification` is a subproperty of the `EbsBlockDeviceConfig` property type. * * `VolumeSecification` determines the volume type, IOPS, and size (GiB) for EBS volumes attached to * EC2 instances. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.emr.*; * VolumeSpecificationProperty volumeSpecificationProperty = VolumeSpecificationProperty.builder() * .sizeInGb(123) * .volumeType("volumeType") * // the properties below are optional * .iops(123) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-instancefleetconfig-volumespecification.html) */ @CdkDslMarker public class CfnInstanceFleetConfigVolumeSpecificationPropertyDsl { private val cdkBuilder: CfnInstanceFleetConfig.VolumeSpecificationProperty.Builder = CfnInstanceFleetConfig.VolumeSpecificationProperty.builder() /** * @param iops The number of I/O operations per second (IOPS) that the volume supports. */ public fun iops(iops: Number) { cdkBuilder.iops(iops) } /** * @param sizeInGb The volume size, in gibibytes (GiB). * This can be a number from 1 - 1024. If the volume type is EBS-optimized, the minimum value is * 10. */ public fun sizeInGb(sizeInGb: Number) { cdkBuilder.sizeInGb(sizeInGb) } /** * @param volumeType The volume type. * Volume types supported are gp3, gp2, io1, st1, sc1, and standard. */ public fun volumeType(volumeType: String) { cdkBuilder.volumeType(volumeType) } public fun build(): CfnInstanceFleetConfig.VolumeSpecificationProperty = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
2,132
awscdk-dsl-kotlin
Apache License 2.0
src/main/kotlin/io/mverse/kslack/api/methods/request/users/UsersGetPresenceRequest.kt
mverse
161,946,116
true
{"Kotlin": 403852}
package io.mverse.kslack.api.methods.request.users import io.mverse.kslack.api.methods.SlackApiRequest data class UsersGetPresenceRequest( /** * Authentication token. Requires scope: `users:read` */ override var token: String? = null, /** * User to get presence info on. Defaults to the authed user. */ val user: String? = null): SlackApiRequest
0
Kotlin
0
0
9ebf1dc13f6a3d89a03af11a83074a4d636cb071
369
jslack
MIT License
src/main/kotlin/com/easykotlin/learn/study7/Book.kt
Youngfellows
444,085,016
false
{"HTML": 477285, "Kotlin": 283608, "Java": 24475}
package com.easykotlin.learn.study7 /** * 数据类: 书本 * var name: 书名 * var page: 页数 * val price: 价钱 */ final data class Book( var bookName: String, var page: Int, val price: Double, val author: String, override var size: Int ) : DBase(size), IBaseA, IBaseB { /** * 重写接口方法 */ override fun getWeight(): Double { return 1.5 } /** * 重写接口方法 */ override fun getYear(): Int? { return 2022 } /** * 数据类有以下的限制要求 * 1.主构造函数需要至少有一个参数 * 2.主构造函数的所有参数需要标记为 val 或 var; * 3.跟普通类一样,数据类也可以有次级构造函数 * 4.数据类不能是抽象、开放、密封或者内部的 * 5.数据类只能是final的 * 6.在1.1之前数据类只能实现接口。自 1.1 起,数据类可以扩展其他类 */ var public: String? = null /** * 次级构造函数 */ constructor(bookName: String, page: Int, price: Double, author: String, public: String, size: Int) : this(bookName, page, price, author, size) { this.public = public } /** * 获取描述 */ fun getDes(): String { return toString() } override fun toString(): String { return "Book(bookName='$bookName', page=$page, price=$price, author='$author', public=$public)" } }
0
HTML
0
0
db0669da08cc6e60937902a4b1364391896df9d7
1,191
EasyKotlin
Apache License 2.0
context/src/main/kotlin/me/gegenbauer/catspy/context/ContextService.kt
Gegenbauer
609,809,576
false
{"Kotlin": 652879}
package me.gegenbauer.catspy.context /** * Marks a class as a singleton that is scoped to a context. */ interface ContextService { fun onContextDestroyed(context: Context) {} }
0
Kotlin
1
7
70d905761d3cb0cb2e5ee9b80ceec72fca46ee52
184
CatSpy
Apache License 2.0
app/src/main/java/com/cooper/wordle/app/ui/game/GameScreen.kt
ScottCooper92
453,962,911
false
{"Kotlin": 82146}
package com.cooper.wordle.app.ui.game import android.content.res.Configuration import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.* import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintLayoutScope import androidx.constraintlayout.compose.Dimension import androidx.hilt.navigation.compose.hiltViewModel import com.cooper.wordle.app.ui.components.AppBarAction import com.cooper.wordle.app.ui.components.WordleAppBar import com.cooper.wordle.app.ui.game.components.Key import com.cooper.wordle.app.ui.game.components.Keyboard import com.cooper.wordle.app.ui.game.components.WordGrid import com.cooper.wordle.app.ui.theme.WordleTheme import com.cooper.wordle.game.* import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import timber.log.Timber @Composable fun GameScreen( viewModel: GameViewModel = hiltViewModel(), onHelpClicked: () -> Unit ) { val state by viewModel.state.collectAsState() Timber.d("$state") GameScreen( state, viewModel.effects, onActionClicked = { action -> when (action) { AppBarAction.HELP -> onHelpClicked() } }, onKeyClicked = { key -> viewModel.onKeyClicked(key) }) } @OptIn( ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class, ExperimentalFoundationApi::class, ) @Composable private fun GameScreen( state: GameViewState, effects: Flow<GameUiEffect>, onActionClicked: (AppBarAction) -> Unit, onKeyClicked: (key: Key) -> Unit ) { val snackbarHostState = remember { SnackbarHostState() } LaunchedEffect(effects) { effects.collect { effect -> when (effect) { is GameUiEffect.ShowMessage -> { launch { snackbarHostState.showSnackbar(effect.message) } } GameUiEffect.ClearMessage -> { snackbarHostState.currentSnackbarData?.dismiss() } } } } Scaffold( topBar = { WordleAppBar(onActionClicked) }, ) { SnackbarHost( hostState = snackbarHostState, snackbar = { snackBarData -> Snackbar(snackbarData = snackBarData) }, modifier = Modifier.fillMaxWidth() ) ConstraintLayout(modifier = Modifier.fillMaxSize()) { when (state) { GameViewState.Loading -> Loading() is GameViewState.InProgress -> GameBoard( gridState = state.gridState, usedLetters = state.usedLetters, onKeyClicked = onKeyClicked ) } } } } @Composable private fun ConstraintLayoutScope.Loading() { CircularProgressIndicator( modifier = Modifier .wrapContentSize() .constrainAs(createRef()) { linkTo(parent.start, parent.end) linkTo(parent.top, parent.bottom) } ) } @Composable private fun ConstraintLayoutScope.GameBoard( gridState: GridState, usedLetters: Set<EvaluatedLetterState>, onKeyClicked: (key: Key) -> Unit ) { // Create references for the composables to constrain val (grid, keyboard) = createRefs() val horizontalPadding = 0.05f val guidelineTop = createGuidelineFromTop(0.05f) val guidelineBottom = createGuidelineFromBottom(0.01f) val guidelineStart = createGuidelineFromStart(horizontalPadding) val guidelineEnd = createGuidelineFromEnd(horizontalPadding) val keyboardBarrier = createTopBarrier(keyboard) WordGrid( gridState = gridState, modifier = Modifier .constrainAs(grid) { linkTo( start = guidelineStart, end = guidelineEnd, startMargin = 48.dp, endMargin = 48.dp ) linkTo( top = guidelineTop, bottom = keyboardBarrier, bottomMargin = 24.dp, bias = 0f ) width = Dimension.fillToConstraints height = Dimension.ratio("${gridState.length}:${gridState.height}") } ) Keyboard( usedLetters = usedLetters, onKeyClicked = onKeyClicked, modifier = Modifier .constrainAs(keyboard) { linkTo( start = parent.start, end = parent.end, startMargin = 8.dp, endMargin = 8.dp ) linkTo(top = grid.bottom, bottom = guidelineBottom, bias = 1f) width = Dimension.fillToConstraints height = Dimension.ratio("2:1") } ) } @Preview(name = "empty grid length 4") @Composable private fun PreviewEmptyGameScreen(wordSize: Int = 4) { val emptyRow = GridRow(List(wordSize) { EmptyLetter }) val state = GameViewState.InProgress( solution = "Answer", gridState = GridState(6, wordSize, List(6) { emptyRow }), usedLetters = emptySet() ) WordleTheme { GameScreen( state = state, effects = flow {}, onActionClicked = {}, onKeyClicked = {} ) } } @Preview(name = "empty grid length 5") @Composable private fun PreviewEmptyGameScreenSize5() { PreviewEmptyGameScreen(5) } @Preview(name = "empty grid length 6") @Composable private fun PreviewEmptyGameScreenSize6() { PreviewEmptyGameScreen(6) } @Preview(name = "empty grid length 7") @Composable private fun PreviewEmptyGameScreenSize7() { PreviewEmptyGameScreen(7) } @Preview(name = "light") @Preview(name = "portrait small", heightDp = 400, widthDp = 225) @Preview(name = "portrait medium", heightDp = 800, widthDp = 450) @Preview(name = "dark", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun PreviewGameScreen() { val first = GridRow( listOf( AbsentLetter('P'), PresentLetter('A'), PresentLetter('R'), CorrectLetter('T'), AbsentLetter('Y'), ) ) val second = GridRow( listOf( ProspectiveLetter('P'), ProspectiveLetter('A'), EmptyLetter, EmptyLetter, EmptyLetter, ) ) val third = GridRow( listOf( EmptyLetter, EmptyLetter, EmptyLetter, EmptyLetter, EmptyLetter ) ) val state = GameViewState.InProgress( solution = "Answer", gridState = GridState(6, 5, listOf(first, second, third, third, third, third)), usedLetters = emptySet() ) WordleTheme { GameScreen( state = state, effects = flow {}, onActionClicked = {}, onKeyClicked = {} ) } } @Preview("loading") @Composable fun PreviewGameScreenLoading() { WordleTheme { GameScreen( state = GameViewState.Loading, effects = flow {}, onActionClicked = {}, onKeyClicked = {} ) } }
0
Kotlin
0
1
55afa181f75d4263d9804dd0b40c94bbf159525a
7,815
Wordle
Apache License 2.0
src/main/kotlin/fr/ncomet/Main.kt
ncomet
320,680,478
false
null
package fr.ncomet import org.apache.poi.ss.usermodel.Cell import org.apache.poi.ss.usermodel.CellType.* import org.apache.poi.ss.usermodel.Row import org.apache.poi.ss.usermodel.Sheet import org.apache.poi.xssf.usermodel.XSSFWorkbook import picocli.CommandLine import picocli.CommandLine.* import picocli.CommandLine.Help.Visibility.ALWAYS import picocli.CommandLine.Model.CommandSpec import java.io.File import java.io.FileInputStream import java.lang.System.lineSeparator import java.util.concurrent.Callable import kotlin.system.exitProcess val allowedFileExtensions = listOf("xlsx", "csv") fun main(args: Array<String>): Unit = exitProcess(command(args)) @Command( name = "excel2adoc", mixinStandardHelpOptions = true, version = ["excel2adoc v1.0"], description = ["Prints .xlsx or .csv file(s) into their asciidoc representation on stdout"] ) class Excel2Asciidoc : Callable<Int> { @Spec lateinit var out: CommandSpec @Parameters( index = "0", description = ["One or more .xlsx or .csv file(s) to print to stdout"], arity = "1..*" ) lateinit var inputFiles: List<File> @Option( names = ["-n", "--no-headers"], description = ["Disables interpretation of first row as header"], defaultValue = "false", showDefaultValue = ALWAYS ) var noHeaders: Boolean = false @Option( names = ["-t", "--no-titles"], description = ["Disables table title using file name and sheet name (or just file name for .csv)"], defaultValue = "false", showDefaultValue = ALWAYS ) var noTitles: Boolean = false @Option( names = ["-s", "--sheet"], paramLabel = "2", description = ["Sheet number, starting at 1. if not provided, it will try to print all sheets for all files"], arity = "1" ) var sheetNumber: String = "all" override fun call(): Int { inputFiles.forEach { if (!it.exists()) throw ParameterException(out.commandLine(), "${it.name} does not exist") } inputFiles.forEach { if (it.extension !in allowedFileExtensions) throw ParameterException( out.commandLine(), "${it.name} needs to be of type ${allowedFileExtensions.joinToString()}" ) } inputFiles.forEach { file -> when (file.extension) { "xlsx" -> FileInputStream(file).use { val workBook = XSSFWorkbook(it) if (sheetNumber == "all") { workBook.forEach { sheet -> sheet.print(noHeaders, file.nameWithoutExtension) } } else { workBook.getSheetAt(sheetNumber.toInt() - 1).print(noHeaders, file.nameWithoutExtension) } } else -> with(file) { print() } } out.newLine() } return ExitCode.OK } private fun File.print() { val fileLines = readLines() if (fileLines.isNotEmpty()) { out.println("[${if (noHeaders) "" else "%header,"}format=csv,separator=;]") if (!noTitles) out.println(".${nameWithoutExtension}") out.println("|===") out.println(fileLines.joinToString(separator = lineSeparator())) out.println("|===") } } private fun Sheet.print(noHeaders: Boolean, fileName: String) { val maxOfFirstPhysicalCell = map { row -> row.firstCellNum.toInt() }.max() ?: 0 val minOfFirstNonEmptyCell = map { row -> row.takeWhile { cell -> cell.isEmpty }.size }.min() ?: 0 val emptyCellsToShift = maxOf(maxOfFirstPhysicalCell, minOfFirstNonEmptyCell) val rows = toList().takeLastWhile { row -> row.isNotEmpty } if (rows.isNotEmpty()) { if (noHeaders) { rows.printColumnDescriptor(emptyCellsToShift) tableSeparator(fileName) rows.printContent(emptyCellsToShift) } else { tableSeparator(fileName) rows.printHeader(emptyCellsToShift) rows.printContentAfterHeader(emptyCellsToShift) } out.println("|===") out.newLine() } } private fun List<Row>.printColumnDescriptor(emptyCellsToShift: Int) = out.println( """[cols="${ first().filterIndexed { index, cell -> cell.isNotEmpty || index >= emptyCellsToShift }.count() }*"]""" ) private fun Sheet.tableSeparator(fileName: String) = out.println(if (noTitles) "|===" else ".$fileName $sheetName${lineSeparator()}|===") private fun List<Row>.printHeader(emptyCellsToShift: Int) = out.println( first().cellIterator() .asSequence() .filterIndexed { index, cell -> cell.isNotEmpty || index >= emptyCellsToShift } .map(renderCell) .joinToString(prefix = "|", separator = " |") ) private fun List<Row>.printContentAfterHeader(emptyCellsToShift: Int) = out.println(drop(1).joinRows(emptyCellsToShift)) private fun List<Row>.printContent(emptyCellsToShift: Int) = out.println(joinRows(emptyCellsToShift)) private fun List<Row>.joinRows(emptyCellsToShift: Int) = joinToString(separator = lineSeparator() + lineSeparator()) { it.cellIterator() .asSequence() .filterIndexed { index, cell -> cell.isNotEmpty || index >= emptyCellsToShift } .map(renderCell) .joinToString(prefix = "|", separator = "${lineSeparator()}|") } } val renderCell: (Cell) -> String = { cell -> when (cell.cellType) { NUMERIC -> cell.numericCellValue.toString() STRING -> cell.stringCellValue FORMULA -> cell.cellFormula BOOLEAN -> cell.booleanCellValue.toString() else -> "" } } internal fun command(args: Array<String>) = CommandLine(Excel2Asciidoc()).execute(*args) private fun CommandSpec.println(s: String) = commandLine().out.println(s) private fun CommandSpec.newLine() = commandLine().out.println(lineSeparator()) private val Cell.isEmpty get() = cellType == BLANK || renderCell(this).trim() == "" private val Cell.isNotEmpty get() = !isEmpty private val Row.isNotEmpty get() = cellIterator().asSequence().any { it.isNotEmpty }
0
Kotlin
0
9
6d164f047d91f418b6eeb19d877103707ec39a82
6,461
excel2adoc
MIT License
app/src/main/java/com/chaquo/myapplication/Account.kt
urynb
675,164,733
false
{"Kotlin": 171813, "Python": 88752}
package com.chaquo.myapplication import android.os.Bundle import android.util.Log import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.room.Room import com.chaquo.myapplication.databinding.ActivityAccountBinding import com.chaquo.myapplication.db.AppDatabase import com.chaquo.myapplication.db.User class Account : AppCompatActivity() { private lateinit var viewBinding: ActivityAccountBinding var currentUser : String = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_account) viewBinding = ActivityAccountBinding.inflate(layoutInflater) setContentView(viewBinding.root) viewBinding.addUserButton.setOnClickListener { saveNewUser() } viewBinding.listUsersButton.setOnClickListener { displayUsers() } viewBinding.loginButton.setOnClickListener { login() } viewBinding.logoutButton.setOnClickListener { logout() } this.currentUser = this.checkLogged() this.displayCurrentUser() } private fun saveNewUser() { val username = findViewById<EditText>(R.id.usernameInput) val password = findViewById<EditText>(R.id.passwordInput) val user = User(username=username.text.toString(), password=password.text.toString()); db().userDao().insertAll(user); // finish(); username.text.clear() password.text.clear() } private fun displayCurrentUser() { val textView = findViewById<TextView>(R.id.usernameDisplay) if (this.currentUser == "") { textView.setText("Not Logged In").toString() } else { textView.setText("Logged in as: " + this.currentUser).toString() } } private fun displayUsers() { val userList : List<User> = db().userDao().getAll() Log.d("DU", userList.toString()) } private fun login() { val username = findViewById<EditText>(R.id.usernameInput) val password = findViewById<EditText>(R.id.passwordInput) var user = db().userDao().findByName(username.text.toString(), password.text.toString()) if (user != null) { Log.d("LOGIN", "FOUND USER") db().userDao().log_in_out(user.uid, true) this.currentUser = user.username.toString() displayCurrentUser() } else { Log.d("LOGIN", "NO USER") } // clear inputs ui username.text.clear() password.text.clear() } private fun logout() { val user = db().userDao().findActive() if (user != null) { db().userDao().log_in_out(user.uid, false) this.currentUser = "" displayCurrentUser() } } private fun checkLogged(): String { var userList = db().userDao().getAll() for (user in userList) { if (user.isLogged) { return user.username.toString() } } return "" } private fun db(): AppDatabase { return Room.databaseBuilder( applicationContext, AppDatabase::class.java, "database-name" ).allowMainThreadQueries().fallbackToDestructiveMigration().build() } }
0
Kotlin
0
0
95cf581a31523b847c9ae49d1afaa22c2ff11f88
3,352
MinerFinder
MIT License
src/main/kotlin/co/mercenary/creators/kotlin/minio/MinioStatic.kt
mercenary-creators
224,226,723
false
null
/* * Copyright (c) 2019, Mercenary Creators Company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.mercenary.creators.kotlin.minio import co.mercenary.creators.kotlin.util.* import com.google.common.escape.Escaper import com.google.common.net.UrlEscapers object MinioStatic { private val path: Escaper by lazy { UrlEscapers.urlPathSegmentEscaper() } private val list = ArrayList<Replacer>(16) init { list += Replacer(Regex("!"), "%21") list += Replacer(Regex("\\$"), "%24") list += Replacer(Regex("&"), "%26") list += Replacer(Regex("'"), "%27") list += Replacer(Regex("\\("), "%28") list += Replacer(Regex("\\)"), "%29") list += Replacer(Regex("\\*"), "%2A") list += Replacer(Regex("\\+"), "%2B") list += Replacer(Regex(","), "%2C") list += Replacer(Regex("/"), "%2F") list += Replacer(Regex(":"), "%3A") list += Replacer(Regex(";"), "%3B") list += Replacer(Regex("="), "%3D") list += Replacer(Regex("@"), "%40") list += Replacer(Regex("\\["), "%5B") list += Replacer(Regex("]"), "%5D") } @JvmStatic fun escape(data: Any): String { return path.escape(data.toString()).let { self -> var text = self list.forEach { text = it.replace(text) } text } } @JvmStatic fun hashOf(vararg args: Any?, accumulator: (Int) -> Unit) { args.forEach { each -> val hash = when (each) { null -> 0 is Array<*> -> each.contentDeepHashCode() is IntArray -> each.contentHashCode() is ByteArray -> each.contentHashCode() is CharArray -> each.contentHashCode() is LongArray -> each.contentHashCode() is ShortArray -> each.contentHashCode() is FloatArray -> each.contentHashCode() is DoubleArray -> each.contentHashCode() is BooleanArray -> each.contentHashCode() else -> each.hashCode() } accumulator(hash) } } @JvmStatic fun hashOf(vararg args: Any?): Int { val hash = 1.toAtomic() hashOf(*args) { hash * 31 + it } return hash.get() } @JvmStatic fun same(value: Any?, other: Any?): Boolean { if (value === other) { return true } return when (value) { null -> other == null is Array<*> -> if (other is Array<*>) value contentDeepEquals other else false is IntArray -> if (other is IntArray) value contentEquals other else false is ByteArray -> if (other is ByteArray) value contentEquals other else false is CharArray -> if (other is CharArray) value contentEquals other else false is LongArray -> if (other is LongArray) value contentEquals other else false is ShortArray -> if (other is ShortArray) value contentEquals other else false is DoubleArray -> if (other is DoubleArray) value contentEquals other else false is BooleanArray -> if (other is BooleanArray) value contentEquals other else false else -> value == other } } @Suppress("NOTHING_TO_INLINE") private class Replacer(private val spec: Regex, private val with: String) { inline fun replace(text: String): String = spec.replace(text, with) } }
0
Kotlin
0
1
b786ced3cc52f2bb996130c417d676a79f3ea7cd
4,083
mercenary-creators-kotlin-minio
Apache License 2.0
app/src/test/java/com/github/pavlospt/refactoredumbrella/test/RenderRecorder.kt
pavlospt
246,115,298
false
null
package com.github.pavlospt.refactoredumbrella.test import java.util.concurrent.CopyOnWriteArrayList import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue class RenderRecorder<T : Any?> { val renders: CopyOnWriteArrayList<T> = CopyOnWriteArrayList() fun add(render: T) { renders.add(render) } fun assertRenders(vararg expectedList: T) = apply { assertEquals(expectedList.size, renders.size) expectedList.forEachIndexed { index, expectedItem -> val actualItem = renders[index] assertEquals(expectedItem, actualItem) } } fun assertRenderedOnce() { assertEquals(1, renders.size) } fun assertRenderedTimes(times: Int) { assertEquals(times, renders.size) } fun assertRenderedAtLeastOnce() { assertTrue(renders.size >= 1) } fun assertNoRenders() = apply { assertEquals(0, renders.size) } fun reset() = apply { renders.clear() } }
3
Kotlin
9
114
e41d78a21ebd5e1e93e039dbd2153a5aeba4f912
1,009
refactored-umbrella
Apache License 2.0
samples/src/main/kotlin/com/mechanica/engine/samples/scenes/SceneDemo.kt
DominicDolan
210,876,716
false
{"Kotlin": 437674}
package com.mechanica.engine.samples.scenes import com.cave.library.angle.degrees import com.mechanica.engine.config.configure import com.mechanica.engine.drawer.Drawer import com.mechanica.engine.game.Game import com.mechanica.engine.input.Inputs import com.mechanica.engine.scenes.scenes.Scene import com.mechanica.engine.scenes.setNewMainScene fun main() { Game.configure { setViewport(height = 10.0) setStartingScene { SceneDemo1() } } Game.loop() } class SceneDemo1 : Scene(), Inputs by Inputs.create() { var angle = 0.0 override fun update(delta: Double) { angle += delta*30.0 if (keyboard.space.hasBeenPressed) { setNewMainScene { SceneDemo2() } } } override fun render(draw: Drawer) { draw.ui.centered.red.rotated(angle.degrees).rectangle() draw.centered.darkGrey.text("Press space to change scene", 0.5, 0.0, Game.ui.top - 1.0) } } class SceneDemo2 : Scene(), Inputs by Inputs.create() { var xPosition = 0.0 override fun update(delta: Double) { xPosition += delta*3.0 xPosition %= (Game.ui.width/2.0) if (keyboard.space.hasBeenPressed) { setNewMainScene { SceneDemo1() } } } override fun render(draw: Drawer) { draw.radius(0.5).green.rectangle(x = xPosition, width = 2.0) draw.centered.darkGrey.text("Press space again to go back", 0.5, 0.0, Game.ui.bottom + 1.0) } }
7
Kotlin
1
0
013f2ac3bf156f9d912bfc931a5b8272f764ee7e
1,467
Mechanica
MIT License
src/main/kotlin/org/jetbrains/research/lumberjack/Main.kt
JetBrains-Research
291,968,852
false
null
package org.jetbrains.research.lumberjack import astminer.cli.* import astminer.common.* import astminer.parse.java.GumTreeJavaParser import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.int import java.io.File class Parser : CliktCommand() { private val inputDirectories: List<String> by option( "--input", help = "Root directory with java files for parsing" ).multiple(required = true) private val outputDirectory: String by option( "--output", help = "Path to directory where the output will be stored" ).required() private val numMerges: Int by option(help = "Number of merges to perform").int().default(100) private val maxPathHeight: Int by option( "--maxH", help = "Maximum height of path for code2vec" ).int().default(8) private val maxPathWidth: Int by option( "--maxW", help = "Maximum width of path. " + "Note, that here width is the difference between token indices in contrast to the original code2vec." ).int().default(3) private val maxPathContexts: Int by option( "--maxContexts", help = "Number of path contexts to keep from each method." ).int().default(200) private val splitTokens: Boolean by option( "--split-tokens", help = "if passed, split tokens into sequence of tokens" ).flag(default = false) private fun parseFiles(folder: File, labelExtractor: LabelExtractor): List<Pair<LightNode, String>> { val files = folder.walk().toList().filter { it.extension == "java" }.toList() ?: return emptyList() val parsedMethods = mutableListOf<Pair<LightNode, String>>() GumTreeJavaParser().parseFiles(files) { parseResult -> normalizeParseResult(parseResult, splitTokens) labelExtractor.toLabeledData(parseResult).forEach { (root, label) -> val lightNode = nodeToLightNode(root) ?: return@forEach parsedMethods.add(Pair(lightNode, splitToSubtokens(label).joinToString("|"))) } } return parsedMethods } private fun printCompressedTrees(compressedTrees: List<Pair<LightNode, String?>>) { compressedTrees.take(100).forEach { (root, label) -> println("-------------------------------") println("path to file: $label") root.prettyPrint(indentSymbol = "| ") println("-------------------------------") } } // private fun printCompressionInfo( // compressedTrees: List<LabeledParseResult<SimpleNode>>, // filesToSizes: Map<String, Int> // ) { // println(compressedTrees.map { (root, label) -> // val size = getTreeSize(root) // (filesToSizes[label] as Int).toFloat() / size // }.sum() / compressedTrees.size) // } // // private fun extractCode2VecData( // compressedTrees: List<LabeledParseResult<SimpleNode>>, // labelPrefix: String, // storage: Code2SeqPathStorage // ) { // val miner = PathMiner(PathRetrievalSettings(maxPathHeight, maxPathWidth)) // // compressedTrees.forEach { (root, label) -> // root.preOrder().forEach { node -> processNodeToken(node, splitTokens) } // val paths = miner.retrievePaths(root).take(maxPathContexts) // storage.store(LabeledPathContexts("$labelPrefix:$label", paths.map { // toPathContext(it) { node -> // node.getNormalizedToken() // } // })) // } // } override fun run() { val treeBPE = TreeBPE<String>(numMerges) val storage = Code2SeqPathStorage(outputDirectory) inputDirectories.forEachIndexed { iter, folder -> println("Parsing files in $folder") val labelExtractor = MethodNameExtractor(hideMethodNames = true) val labeledMethods = parseFiles(File(folder), labelExtractor) println("Parsed ${labeledMethods.size} methods") val (methods, labels) = labeledMethods.unzip() val compressedTrees = if (iter == 0) { treeBPE.fitAndTransform(methods, labels) } else { treeBPE.transform(methods, labels) } println("Compressed trees") println("Moving tokens to leaves") compressedTrees.forEach { (root, _) -> moveTokensToLeaves(root) } println("Moved tokens to leaves") printCompressedTrees(compressedTrees) // extractCode2VecData(compressedTrees, folderName, storage) } storage.close() } } fun main(args: Array<String>) = Parser().main(args)
0
Kotlin
0
3
d6a96a6b522f009d9af8213548f6c162da6919fb
4,896
lumberjack
MIT License
core/data/src/main/kotlin/com/matabel/core/data/repository/BtDeviceRepository.kt
anthony-cannon
642,328,700
false
null
package com.matabel.core.data.repository import com.matabel.core.model.BtDevice import kotlinx.coroutines.flow.Flow interface BtDeviceRepository { fun observeAllBtDevices(): Flow<List<BtDevice>> fun insertAll(btDevices: List<BtDevice>) }
0
Kotlin
0
0
226ad1f20a6f35f2a7fb01744a9f04bfd1c47003
247
left-behind
MIT License
app/src/main/java/awersching/gammelgps/ui/Permissions.kt
awersching
128,370,115
false
null
package awersching.gammelgps.ui import android.Manifest import android.app.Activity import android.content.pm.PackageManager import androidx.core.app.ActivityCompat class Permissions(private val ctx: Activity) { private val permissions = arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.FOREGROUND_SERVICE ) fun request() { if (!permissionsGranted()) { ActivityCompat.requestPermissions(ctx, permissions, 0) } } private fun permissionsGranted(): Boolean { var granted = true for (permission in permissions) { granted = granted && ActivityCompat.checkSelfPermission(ctx, permission) == PackageManager.PERMISSION_GRANTED } return granted } }
0
Kotlin
0
0
d8e8a436e2f6a9d22fae447e332ec53188c053ca
855
gammel-gps
MIT License
kotlin-test/src/test/kotlin/org/axonframework/extension/kotlin/test/testObjects.kt
AxonFramework
219,790,172
false
{"Kotlin": 59452}
/* * Copyright (c) 2010-2023. Axon Framework * * 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.axonframework.extension.kotlin.test import org.axonframework.commandhandling.CommandHandler import org.axonframework.commandhandling.RoutingKey import org.axonframework.modelling.command.AggregateIdentifier internal data class ExampleCommand(@RoutingKey val aggregateId: String) internal data class ExampleCommandWithException(@RoutingKey val aggregateId: String) internal class ExampleAggregate { @AggregateIdentifier lateinit var aggregateId: String constructor() @CommandHandler constructor(command: ExampleCommand) @CommandHandler constructor(command: ExampleCommandWithException) { throw Exception() } } class ExampleSaga
7
Kotlin
9
45
e6629dd3a6275905400d3bb3a5ed2968dfdf7567
1,294
extension-kotlin
Apache License 2.0
android/app/src/main/kotlin/com/demirfatih/flutter_habifa_v2/MainActivity.kt
fthdmirr
310,353,884
false
{"Dart": 57669, "Swift": 404, "Kotlin": 137, "Objective-C": 38}
package com.demirfatih.flutter_habifa_v2 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
a500ce7cfe39f3efeac84c743e4872c01b93d6ee
137
Pomodoro_Todo_App
MIT License
kotlin-mui/src/main/generated/mui/material/LinearProgress.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/material/LinearProgress") @file:JsNonModule package mui.material external interface LinearProgressProps : mui.system.StandardProps, react.dom.html.HTMLAttributes<org.w3c.dom.HTMLSpanElement> { /** * Override or extend the styles applied to the component. */ var classes: LinearProgressClasses? /** * The color of the component. It supports those theme colors that make sense for this component. * @default 'primary' */ var color: LinearProgressColor? /** * The system prop that allows defining system overrides as well as additional CSS styles. */ var sx: mui.system.SxProps<mui.system.Theme>? /** * The value of the progress indicator for the determinate and buffer variants. * Value between 0 and 100. */ var value: Number? /** * The value for the buffer variant. * Value between 0 and 100. */ var valueBuffer: Number? /** * The variant to use. * Use indeterminate or query when there is no progress value. * @default 'indeterminate' */ var variant: LinearProgressVariant? } /** * ## ARIA * * If the progress bar is describing the loading progress of a particular region of a page, * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy` * attribute to `true` on that region until it has finished loading. * * Demos: * * - [Progress](https://mui.com/components/progress/) * * API: * * - [LinearProgress API](https://mui.com/api/linear-progress/) */ @JsName("default") external val LinearProgress: react.FC<LinearProgressProps>
10
Kotlin
145
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
1,692
kotlin-wrappers
Apache License 2.0
app/src/main/java/in/jatindhankhar/wlosh/ui/MainActivity.kt
jatindhankhar
120,306,742
false
null
package `in`.jatindhankhar.wlosh.ui import `in`.jatindhankhar.wlosh.R import `in`.jatindhankhar.wlosh.ui.adapters.SimpleFragmentPagerAdapter import `in`.jatindhankhar.wlosh.ui.fragments.ImagesFragment import android.content.Context import android.net.ConnectivityManager import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import kotlinx.android.synthetic.main.activity_main.* import org.jetbrains.anko.design.longSnackbar class MainActivity : AppCompatActivity() { private lateinit var mPagerAdapter: SimpleFragmentPagerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) mPagerAdapter = SimpleFragmentPagerAdapter(supportFragmentManager, this) viewpager.adapter = mPagerAdapter mPagerAdapter.addFragment(ImagesFragment.newInstance("")) mPagerAdapter.addFragment(ImagesFragment.newInstance("curated")) sliding_tabs.setupWithViewPager(viewpager) if (!haveNetworkConnection()) { longSnackbar(coordinator_layout, "Looks like, you are not connected. Some functionality will not be available") } } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } private fun haveNetworkConnection(): Boolean { var haveConnectedWifi = false var haveConnectedMobile = false val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo = cm.allNetworkInfo for (ni in netInfo) { if (ni.typeName.equals("WIFI", ignoreCase = true)) if (ni.isConnected) haveConnectedWifi = true if (ni.typeName.equals("MOBILE", ignoreCase = true)) if (ni.isConnected) haveConnectedMobile = true } return haveConnectedWifi || haveConnectedMobile } }
0
Kotlin
0
4
78583e130df7d8da824416b25bbafcf2b98e34b1
2,343
wlosh
MIT License