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/com/concredito/clientes/screens/prospect/RejectObservationViewModel.kt | FigueroaGit | 749,615,668 | false | {"Kotlin": 180223} | package com.concredito.clientes.screens.prospect
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.concredito.clientes.data.Resource
import com.concredito.clientes.model.RejectObservation
import com.concredito.clientes.repository.RejectObservationRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class RejectObservationViewModel @Inject constructor(private val repository: RejectObservationRepository) :
ViewModel() {
suspend fun getRejectObservationsById(rejectObservationId: String): Resource<RejectObservation> {
return repository.getRejectObservationsById(rejectObservationId)
}
suspend fun getRejectObservationsByProspectId(prospectId: String): Resource<List<RejectObservation>> {
return repository.getRejectObservationsByProspectId(prospectId)
}
fun addRejectObservations(rejectObservation: RejectObservation) {
viewModelScope.launch {
repository.addRejectObservations(rejectObservation)
}
}
suspend fun updateRejectObservations(
id: String,
rejectObservation: RejectObservation,
): Resource<RejectObservation> {
return repository.updateRejectObservations(id, rejectObservation)
}
suspend fun deleteRejectReservations(id: String): Resource<Unit> {
return repository.deleteRejectObservations(id)
}
}
| 0 | Kotlin | 0 | 0 | 92ce5c3f0c2f9990fd2daff3ab083bfdd028f761 | 1,615 | ClientesProspectos | Apache License 2.0 |
common/common-base/src/main/java/com/bbgo/common_base/bean/HttpResult.kt | bbggo | 371,705,786 | false | null | package com.bbgo.common_base.bean
import androidx.annotation.Keep
/**
* @Description:
* @Author: wangyuebin
* @Date: 2021/8/13 11:41 上午
*/
@Keep
class HttpResult<T>(val data: T) : BaseBean()
| 3 | null | 3 | 8 | 9c983af26f5bd9cd5e08b7a6080190305738b435 | 198 | WanAndroid | Apache License 2.0 |
kotlin/app/src/main/java/tw/idv/woofdog/easyhealthrecord/adapters/DbContentAdapter.kt | woofdogtw | 786,333,430 | false | {"Kotlin": 236990, "JavaScript": 740} | package tw.idv.woofdog.easyhealthrecord.adapters
import android.app.Activity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import tw.idv.woofdog.easyhealthrecord.activities.RecBloodGlucoseFragment
import tw.idv.woofdog.easyhealthrecord.activities.RecBloodPressureFragment
import tw.idv.woofdog.easyhealthrecord.activities.RecBodyWeightFragment
class DbContentAdapter(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
parentActivity: Activity,
bodyWeightAdapter: RecBodyWeightAdapter,
bloodPressureAdapter: RecBloodPressureAdapter,
bloodGlucoseAdapter: RecBloodGlucoseAdapter,
) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int {
return 3
}
override fun createFragment(position: Int): Fragment {
return when (position) {
1 -> bloodPressureFragment
2 -> bloodGlucoseFragment
else -> bodyWeightFragment
}
}
val bodyWeightFragment = RecBodyWeightFragment(parentActivity, bodyWeightAdapter)
val bloodPressureFragment = RecBloodPressureFragment(parentActivity, bloodPressureAdapter)
val bloodGlucoseFragment = RecBloodGlucoseFragment(parentActivity, bloodGlucoseAdapter)
}
| 0 | Kotlin | 0 | 0 | 1d219d66d211fe167df54db1d29fd01f6c6d47ee | 1,361 | easyhealthrecord | MIT License |
app/src/androidTest/java/com/jerry/assessment/dialog/HmAlertDialogTest.kt | jchodev | 730,705,691 | false | {"Kotlin": 156097} | package com.jerry.assessment.designlib.dialog
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import com.jerry.assessment.designllib.dialog.HmAlertDialog
import org.junit.Rule
import org.junit.Test
class HmAlertDialogTest {
@get:Rule
val rule = createComposeRule()
@Test
fun testWithExpected() {
//assign
rule.setContent {
HmAlertDialog(
title = "title",
message = "message",
onLeftClick = { },
rightBtnStr = "retry",
onRightClick = { }
)
}
//check
rule.onNodeWithText("title").assertExists()
rule.onNodeWithText("message").assertExists()
}
} | 0 | Kotlin | 0 | 1 | b737b7835995fc9cc461f14c72e188c20792cc05 | 776 | mobile-coverage-2 | MIT License |
base/src/main/java/com/github/zieiony/base/navigation/DeferredNavigator.kt | nkhar | 366,710,280 | true | {"Kotlin": 34941, "Java": 1598} | package com.github.zieiony.base.navigation
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import java.io.Serializable
internal class DeferredNavigator : Navigator {
private var _navigator: Navigator? = null
var navigator: Navigator?
get() = _navigator
set(value) {
_navigator = value
_navigator?.let { navigator ->
events.forEach { event ->
when (event) {
is NavigationEvent.ResultNavigationEvent -> navigator.setResult(
event.key,
event.result
)
is NavigationEvent.ResultNavigationEvent2 -> navigator.setResult(
event.result
)
is NavigationEvent.BackNavigationEvent -> navigator.navigateBack()
is NavigationEvent.FragmentNavigationEvent -> {
navigator.navigateTo(
Class.forName(event.className) as Class<out Fragment>,
event.arguments
)
}
is NavigationEvent.IntentNavigationEvent -> navigator.navigateTo(event.intent)
}
events.remove(event)
}
}
}
private var events = ArrayList<NavigationEvent>()
override fun getNavigatorId(): Int {
throw RuntimeException("Not supported")
}
override fun navigateTo(
target: Class<out Fragment>,
arguments: HashMap<String, Serializable?>?
) {
val localNavigator = navigator
if (localNavigator == null) {
events.add(
NavigationEvent.FragmentNavigationEvent(target.name, arguments)
)
} else {
localNavigator.navigateTo(target, arguments)
}
}
override fun navigateTo(fragment: Fragment) {
val localNavigator = navigator
if (localNavigator == null) {
val bundle = fragment.arguments
events.add(
NavigationEvent.FragmentNavigationEvent(
fragment.javaClass.name, if (bundle == null) {
null
} else {
val arguments = HashMap<String, Serializable?>()
bundle.keySet().forEach {
arguments[it] = bundle[it] as Serializable?
}
arguments
}
)
)
} else {
localNavigator.navigateTo(fragment)
}
}
override fun navigateTo(originalNavigator: Navigator, fragment: Fragment) {
throw RuntimeException("Not supported")
}
override fun navigateTo(intent: Intent) {
val localNavigator = navigator
if (localNavigator == null) {
events.add(NavigationEvent.IntentNavigationEvent(intent))
} else {
localNavigator.navigateTo(intent)
}
}
override fun navigateBack() {
val localNavigator = navigator
if (localNavigator == null) {
events.add(NavigationEvent.BackNavigationEvent)
} else {
localNavigator.navigateBack()
}
}
override fun setResult(key: String, result: Serializable?) {
val localNavigator = navigator
if (localNavigator == null) {
events.add(NavigationEvent.ResultNavigationEvent(key, result))
} else {
localNavigator.setResult(key, result)
}
}
override fun setResult(result: Result) {
val localNavigator = navigator
if (localNavigator == null) {
events.add(NavigationEvent.ResultNavigationEvent2(result))
} else {
localNavigator.setResult(result)
}
}
override fun setResultTarget(resultTarget: Int) {
throw RuntimeException("Not supported")
}
override fun getResultTarget(): Int {
throw RuntimeException("Not supported")
}
fun saveState(bundle: Bundle) {
bundle.putSerializable(EVENTS, events)
}
fun restoreState(bundle: Bundle) {
bundle.getSerializable(EVENTS)?.let {
events = it as ArrayList<NavigationEvent>
}
}
companion object {
const val EVENTS = "events"
}
} | 0 | null | 0 | 0 | 83535bcf3de988609e87860365f57778a5c41384 | 4,530 | Base | Apache License 2.0 |
src/test/kotlin/com/easykotlin/learn/study2/ListDemoTest.kt | Youngfellows | 444,085,016 | false | {"HTML": 477285, "Kotlin": 283608, "Java": 24475} | package com.easykotlin.learn.study2
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ListDemoTest {
/**
* 创建对象
*/
private val listDemo: ListDemo = ListDemo()
@Test
fun testListDemo1() {
listDemo.listDemo1()
}
@Test
fun testListDemo2() {
listDemo.listDemo2()
}
@Test
fun testListDemo3() {
listDemo.listDemo3()
}
@Test
fun testListDemo4() {
listDemo.listDemo4()
}
@Test
fun testListDemo5() {
listDemo.listDemo5()
}
@Test
fun testListDemo6() {
listDemo.listDemo6()
}
@Test
fun testListDemo7() {
listDemo.listDemo7()
}
@Test
fun testListDemo8() {
listDemo.listDemo8()
}
} | 0 | HTML | 0 | 0 | db0669da08cc6e60937902a4b1364391896df9d7 | 823 | EasyKotlin | Apache License 2.0 |
src/kotlin/no/nav/medlemskap/client/StsRestClient.kt | navikt | 286,827,941 | false | null | package no.nav.medlemskap.client
import io.ktor.client.request.*
import io.ktor.http.*
import no.nav.medlemskap.domene.Token
import java.util.*
class StsRestClient(
private val baseUrl: String,
private val username: String,
private val password: String
) {
suspend fun oidcToken(): Token {
return httpClient.get {
url("$baseUrl/rest/v1/sts/token")
header(HttpHeaders.Authorization, "Basic ${credentials()}")
parameter("grant_type", "client_credentials")
parameter("scope", "openid")
}
}
private fun credentials() =
Base64.getEncoder().encodeToString("${username}:${password}".toByteArray(Charsets.UTF_8))
} | 0 | Kotlin | 0 | 0 | f6b4e13fecc4c0f1d3dd26546057eea95f808e0e | 707 | medlemskap-oppslag-funksjonelle-tester | MIT License |
api/src/main/kotlin/com/xboxgamecollection/api/security/TokenService.kt | alexaragao | 809,759,421 | false | {"Kotlin": 126157, "Dockerfile": 709, "Swift": 522} | package com.xboxgamecollection.api.security
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.exceptions.JWTCreationException
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.security.core.userdetails.User
import org.springframework.stereotype.Service
import java.util.Date
@Service
@EnableConfigurationProperties(JwtProperties::class)
class TokenService(
private val jwtProperties: JwtProperties
) {
fun generateAccessToken(user: User): String {
try {
val algorithm = Algorithm.HMAC256(jwtProperties.key);
val accessToken = JWT.create()
.withSubject(user.username)
.withIssuedAt(Date(System.currentTimeMillis()))
.withExpiresAt(generateExpirationDate())
.sign(algorithm)
return accessToken
} catch (exception: JWTCreationException) {
throw RuntimeException("Error while generation token", exception)
}
}
fun generateExpirationDate(): Date =
Date(System.currentTimeMillis() + jwtProperties.accessTokenExpiration)
fun extractSubject(token: String): String {
val algorithm = Algorithm.HMAC256(jwtProperties.key);
val tokenSubject = JWT.require(algorithm)
.build()
.verify(token)
.subject
return tokenSubject
}
}
| 0 | Kotlin | 0 | 1 | 25cdf1704a2f5a9a587dce225cb612df731c38e7 | 1,443 | xbox-game-collection-app | MIT License |
module-front-api/src/main/kotlin/io/klaytn/finder/interfaces/rest/api/view/model/nft/NftTransferListView.kt | klaytn | 678,353,482 | false | {"Kotlin": 1734759, "Solidity": 71874, "Shell": 3957} | package io.klaytn.finder.interfaces.rest.api.view.model.nft
import io.klaytn.finder.view.model.account.AccountAddressView
import io.klaytn.finder.interfaces.rest.api.view.model.contract.ContractSummary
import io.swagger.v3.oas.annotations.media.Schema
import java.math.BigInteger
import java.util.*
@Schema
data class NftTransferListView(
@Schema(title="Block #")
val blockId: Long,
@Schema(title="Transaction Hash")
val transactionHash: String,
@Schema(title="Transaction Timestamp")
val datetime: Date,
@Schema(title="Address (from)")
val from: AccountAddressView,
@Schema(title="Address (to)")
val to: AccountAddressView,
@Schema(title="NFT Contract Information")
val nft: ContractSummary,
@Schema(title="NFT Token ID")
val tokenId: String,
@Schema(title="NFT Token Count")
val tokenCount: BigInteger,
)
| 7 | Kotlin | 0 | 0 | 9826584d291c7ec1a383d91f7238046de2c45656 | 880 | finder-api | MIT License |
device-cleaner/src/test/kotlin/pl/droidsonroids/stf/devicecleaner/DeviceCleanerTest.kt | DroidsOnRoids | 107,314,938 | false | null | package pl.droidsonroids.stf.devicecleaner
import assertk.assertThat
import assertk.assertions.isTrue
import com.android.ddmlib.IDevice
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.doThrow
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import java.io.IOException
class DeviceCleanerTest {
private val serial = "12345"
private val secondSerial = "123456"
private lateinit var device: IDevice
private lateinit var cleaner: DeviceCleaner
@Before
fun setUp() {
device = mock {
on { getProperty("ro.serialno") } doReturn serial
}
cleaner = DeviceCleaner(arrayOf(serial), emptyArray())
}
@Test
fun `storage cleaned when connected`() = runBlocking {
cleaner.deviceConnected(device)
cleaner.cleanAllDevices()
verify(device).executeShellCommand(eq("rm -rf /sdcard/*"), any())
verify(device).executeShellCommand(eq("rm -rf /data/local/tmp/*"), any())
}
@Test
fun `waits until device cleaned successfully`() = runBlocking {
val job = launch {
cleaner.cleanAllDevices()
}
cleaner.deviceConnected(device)
job.join()
assertThat(job.isCompleted).isTrue()
}
@Test
fun `waits until device disconnected`() = runBlocking {
val job = launch {
cleaner.cleanAllDevices()
}
cleaner.deviceDisconnected(device)
job.join()
assertThat(job.isCompleted).isTrue()
}
@Test
fun `reports failure when cleaning failed on all devices`() = runBlocking {
whenever(device.executeShellCommand(any(), any())).thenThrow(IOException::class.java)
val job = launch {
cleaner.cleanAllDevices()
}
cleaner.deviceConnected(device)
job.join()
assertThat(job.isCompleted).isTrue()
}
@Test
fun `reports failure when device cleaning failed on single device`() = runBlocking {
val secondDevice = mock<IDevice> {
on { executeShellCommand(any(), any()) } doThrow IOException::class
on { getProperty("ro.serialno") } doReturn secondSerial
}
cleaner = DeviceCleaner(arrayOf(serial, secondSerial), emptyArray())
val job = launch {
cleaner.cleanAllDevices()
}
cleaner.deviceConnected(device)
cleaner.deviceConnected(secondDevice)
job.join()
assertThat(job.isCompleted).isTrue()
}
@Test
fun `reports success when no devices connected`() = runBlocking {
cleaner = DeviceCleaner(emptyArray(), emptyArray())
assertThat(cleaner.cleanAllDevices()).isTrue()
}
}
| 0 | Kotlin | 17 | 23 | ae3dd73a9b2d4c876149c9de80e84afaa91abb73 | 2,905 | android-device-cleaner | MIT License |
app/src/main/java/com/example/chatopenai/presentation/util/UiText.kt | Pedroid1 | 592,416,987 | false | null | package com.example.chatopenai.presentation.util
import android.content.Context
import androidx.annotation.StringRes
sealed class UiText {
data class DynamicString(val message: String) : UiText()
class StringResource(@StringRes val resId: Int, vararg val args: Any) : UiText()
fun asString(context: Context): String {
return when(this) {
is DynamicString -> message
is StringResource -> context.getString(resId, *args)
}
}
} | 0 | Kotlin | 0 | 2 | 8a005e57ae341b484205c5787d9095b225a1348a | 483 | Chat-Open-Ai | Apache License 2.0 |
app/src/main/java/com/example/chatopenai/presentation/util/UiText.kt | Pedroid1 | 592,416,987 | false | null | package com.example.chatopenai.presentation.util
import android.content.Context
import androidx.annotation.StringRes
sealed class UiText {
data class DynamicString(val message: String) : UiText()
class StringResource(@StringRes val resId: Int, vararg val args: Any) : UiText()
fun asString(context: Context): String {
return when(this) {
is DynamicString -> message
is StringResource -> context.getString(resId, *args)
}
}
} | 0 | Kotlin | 0 | 2 | 8a005e57ae341b484205c5787d9095b225a1348a | 483 | Chat-Open-Ai | Apache License 2.0 |
android/repository/src/main/kotlin/ca/etsmtl/applets/repository/data/repository/signets/EvaluationCoursRepository.kt | mayMadany | 189,744,601 | true | {"Kotlin": 518550, "Swift": 51936, "HTML": 36036, "Shell": 2167, "Ruby": 315} | package ca.etsmtl.applets.repository.data.repository.signets
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import ca.etsmtl.applets.repository.AppExecutors
import ca.etsmtl.applets.repository.data.api.ApiResponse
import ca.etsmtl.applets.repository.data.api.SignetsApi
import ca.etsmtl.applets.repository.data.api.requestbody.signets.ListeEvaluationCoursRequestBody
import ca.etsmtl.applets.repository.data.api.response.mapper.toEvaluationCoursEntities
import ca.etsmtl.applets.repository.data.api.response.signets.ApiListeEvaluationCours
import ca.etsmtl.applets.repository.data.api.response.signets.ApiSignetsModel
import ca.etsmtl.applets.repository.data.db.dao.signets.EvaluationCoursDao
import ca.etsmtl.applets.repository.data.db.entity.mapper.toEvaluationCours
import model.Resource
import model.Cours
import model.EvaluationCours
import model.SignetsUserCredentials
import javax.inject.Inject
/**
* This repository provides a list of course's evaluations (feedback given to teachers about their courses)
*/
class EvaluationCoursRepository @Inject constructor(
appExecutors: AppExecutors,
private val api: SignetsApi,
private val evaluationCoursDao: EvaluationCoursDao
) : SignetsRepository(appExecutors) {
fun getEvaluationCours(
userCredentials: SignetsUserCredentials,
cours: Cours,
shouldFetch: Boolean = true
): LiveData<Resource<List<EvaluationCours>>> = object : SignetsNetworkBoundResource<List<EvaluationCours>, ApiListeEvaluationCours>(appExecutors) {
override fun saveSignetsData(item: ApiListeEvaluationCours) {
evaluationCoursDao.deleteBySession(cours.session)
evaluationCoursDao.insertAll(item.toEvaluationCoursEntities(cours))
}
override fun shouldFetch(data: List<EvaluationCours>?) = shouldFetch
override fun loadFromDb(): LiveData<List<EvaluationCours>> = Transformations.map(evaluationCoursDao.getEvaluationCoursBySession(cours.session)) {
it.toEvaluationCours()
}
override fun createCall(): LiveData<ApiResponse<ApiSignetsModel<ApiListeEvaluationCours>>> {
return api.listeEvaluationCours(ListeEvaluationCoursRequestBody(
userCredentials.codeAccesUniversel.value,
userCredentials.motPasse,
cours.session
))
}
}.asLiveData()
} | 0 | Kotlin | 0 | 0 | dd68a03de80e485a0b67e0827dea81d009e308a3 | 2,402 | Notre-Dame | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Sun.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.Sun: ImageVector
get() {
if (_sun != null) {
return _sun!!
}
_sun = Builder(name = "Sun", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(24.0f, 13.0f)
lineTo(24.0f, 11.0f)
lineTo(18.928f, 11.0f)
arcToRelative(6.927f, 6.927f, 0.0f, false, false, -0.438f, -1.621f)
lineToRelative(4.392f, -2.557f)
lineTo(21.876f, 5.094f)
lineTo(17.482f, 7.652f)
arcToRelative(7.077f, 7.077f, 0.0f, false, false, -1.142f, -1.14f)
lineToRelative(2.55f, -4.385f)
lineTo(17.162f, 1.121f)
lineToRelative(-2.55f, 4.385f)
arcTo(6.91f, 6.91f, 0.0f, false, false, 13.0f, 5.072f)
lineTo(13.0f, 0.0f)
lineTo(11.0f, 0.0f)
lineTo(11.0f, 5.072f)
arcTo(6.908f, 6.908f, 0.0f, false, false, 9.4f, 5.5f)
lineTo(6.854f, 1.121f)
lineTo(5.126f, 2.127f)
lineTo(7.671f, 6.5f)
arcTo(7.046f, 7.046f, 0.0f, false, false, 6.524f, 7.646f)
lineTo(2.14f, 5.094f)
lineTo(1.134f, 6.822f)
lineTo(5.513f, 9.371f)
arcTo(6.9f, 6.9f, 0.0f, false, false, 5.072f, 11.0f)
lineTo(0.0f, 11.0f)
verticalLineToRelative(2.0f)
lineTo(5.072f, 13.0f)
arcToRelative(6.948f, 6.948f, 0.0f, false, false, 0.438f, 1.622f)
lineTo(1.141f, 17.165f)
lineToRelative(1.006f, 1.729f)
lineToRelative(4.372f, -2.546f)
arcToRelative(7.028f, 7.028f, 0.0f, false, false, 1.13f, 1.131f)
lineTo(5.1f, 21.865f)
lineToRelative(1.729f, 1.006f)
lineToRelative(2.548f, -4.382f)
arcTo(6.912f, 6.912f, 0.0f, false, false, 11.0f, 18.928f)
lineTo(11.0f, 24.0f)
horizontalLineToRelative(2.0f)
lineTo(13.0f, 18.928f)
arcToRelative(6.918f, 6.918f, 0.0f, false, false, 1.638f, -0.445f)
lineToRelative(2.552f, 4.388f)
lineToRelative(1.728f, -1.006f)
lineTo(16.362f, 17.47f)
arcToRelative(7.06f, 7.06f, 0.0f, false, false, 1.125f, -1.128f)
lineToRelative(4.383f, 2.552f)
lineToRelative(1.0f, -1.729f)
lineToRelative(-4.382f, -2.551f)
arcTo(6.928f, 6.928f, 0.0f, false, false, 18.928f, 13.0f)
close()
moveTo(17.0f, 12.0f)
curveToRelative(-0.21f, 6.608f, -9.791f, 6.606f, -10.0f, 0.0f)
curveTo(7.21f, 5.392f, 16.791f, 5.394f, 17.0f, 12.0f)
close()
}
}
.build()
return _sun!!
}
private var _sun: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,840 | icons | MIT License |
app/src/main/java/com/awscherb/cardkeeper/util/db/BarcodeConverters.kt | LateNightProductions | 66,697,395 | false | null | package com.awscherb.cardkeeper.util.db
import androidx.room.TypeConverter
import com.google.zxing.BarcodeFormat
object BarcodeConverters {
@[TypeConverter JvmStatic]
fun fromString(string: String): BarcodeFormat = BarcodeFormat.valueOf(string)
@[TypeConverter JvmStatic]
fun toString(format: BarcodeFormat): String = format.toString()
} | 1 | Kotlin | 19 | 99 | 465a581c8f5fd1da24e0a5932d7b81ed90b0b1ab | 358 | CardKeeper | Apache License 2.0 |
app/src/main/java/com/awscherb/cardkeeper/util/db/BarcodeConverters.kt | LateNightProductions | 66,697,395 | false | null | package com.awscherb.cardkeeper.util.db
import androidx.room.TypeConverter
import com.google.zxing.BarcodeFormat
object BarcodeConverters {
@[TypeConverter JvmStatic]
fun fromString(string: String): BarcodeFormat = BarcodeFormat.valueOf(string)
@[TypeConverter JvmStatic]
fun toString(format: BarcodeFormat): String = format.toString()
} | 1 | Kotlin | 19 | 99 | 465a581c8f5fd1da24e0a5932d7b81ed90b0b1ab | 358 | CardKeeper | Apache License 2.0 |
library/src/main/java/cz/mroczis/netmonster/core/model/band/BandNr.kt | rtr-nettest | 459,160,473 | true | {"Kotlin": 418811} | package cz.mroczis.netmonster.core.model.band
import android.os.Build
import cz.mroczis.netmonster.core.model.annotation.SinceSdk
@SinceSdk(Build.VERSION_CODES.Q)
data class BandNr(
val downlinkArfcn: Int,
/**
* Downlink frequency in kHz calculated from [downlinkArfcn]
*
* Unit: kHz
*/
val downlinkFrequency: Int,
override val number: Int?,
override val name: String?
) : IBand {
override val channelNumber: Int = downlinkArfcn
companion object {
/**
* 0 would represent 0 kHz, people can hear up to 20 kHz. If we assume N_{ref} = 20 and delta F_{Raster} = 100
* we can set lower bound to 1 MHz ~ 200.
*
* However [3GPP 38.101-1 specification for NR](https://portal.3gpp.org/desktopmodules/Specifications/SpecificationDetails.aspx?specificationId=3283)
* (chapter 5.4.2.1 NR-ARFCN and channel raster) defaults to 0 as minimal ARFCN possible.
*/
const val DOWNLINK_ARFCN_MIN = 200L
/**
* Source: [3GPP 38.101-1 specification for NR](https://portal.3gpp.org/desktopmodules/Specifications/SpecificationDetails.aspx?specificationId=3283)
* 5.4.2.1 NR-ARFCN and channel raster
*/
const val DOWNLINK_ARFCN_MAX = 2_016_666L
internal val DOWNLINK_EARFCN_RANGE = DOWNLINK_ARFCN_MIN..DOWNLINK_ARFCN_MAX
}
} | 0 | null | 0 | 4 | 4554151838db718c1bd9a78bf6cee3e25a210122 | 1,378 | netmonster-core | Apache License 2.0 |
next/kmp/browser/src/iosMain/kotlin/org/dweb_browser/browser/common/PureViewController.ext.ios.kt | BioforestChain | 594,577,896 | false | null | package org.dweb_browser.browser.common
import org.dweb_browser.core.module.MicroModule
import org.dweb_browser.dwebview.DWebViewOptions
import org.dweb_browser.dwebview.IDWebView
import org.dweb_browser.dwebview.create
import org.dweb_browser.helper.platform.IPureViewController
import org.dweb_browser.helper.platform.PureViewController
actual suspend fun IPureViewController.createDwebView(
remoteMM: MicroModule.Runtime,
options: DWebViewOptions,
): IDWebView {
require(this is PureViewController)
return IDWebView.Companion.create(remoteMM, options)
} | 66 | null | 5 | 20 | 6db1137257e38400c87279f4ccf46511752cd45a | 566 | dweb_browser | MIT License |
src/main/kotlin/com/skywalker/travelnotes/repository/impl/TravelNotesRepositoryImpl.kt | duxingxia081 | 133,362,521 | false | null | package com.skywalker.travelnotes.repository.impl
import com.skywalker.travelnotes.dto.TravelNotesDTO
import com.skywalker.travelnotes.dto.TravelNotesParamDTO
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Repository
import java.util.*
import javax.persistence.EntityManager
import javax.persistence.PersistenceContext
@Repository
class TravelNotesRepositoryImpl(
@PersistenceContext
private val em: EntityManager
) {
fun listAllByParam(param: TravelNotesParamDTO, pageable: Pageable?): HashMap<String, Any?> {
val postUserId = param.postUserId
val travelNotesId = param.travelNotesId
val date = param.date
val dateAfter = param.dateAfter
var sql =
"select new com.skywalker.travelnotes.dto.TravelNotesDTO(t.travelNotesId,t.title,u.userName,u.nickname,u.headImage,t.addressName,t.addressCoordinate,t.content,t.timeCreate)"
var sqlCount = "select count(t.travelNotesId)"
var hql =
" from MhoSkywalkerTravelNotes t,MhoSkywalkerUser u where t.postUserId=u.userId"
if (null != postUserId) {
hql += " and u.userId ='$postUserId'"
}
if (null != travelNotesId) {
hql += " and t.travelNotesId='$travelNotesId'"
}
if (null != date) {
hql += " and t.timeCreate <:date"
}
if (null != dateAfter) {
hql += " and t.timeCreate >:dateAfter"
}
hql += " order by t.timeCreate desc"
val query = em.createQuery(sql + hql)
val queryCount = em.createQuery(sqlCount + hql)
if (null != date) {
query.setParameter("date", date)
queryCount.setParameter("date", date)
}
if (null != dateAfter) {
query.setParameter("dateAfter", dateAfter)
queryCount.setParameter("dateAfter", dateAfter)
}
if (null != pageable) {
query.firstResult = pageable.pageNumber * pageable.pageSize
query.maxResults = pageable.pageSize
}
val list = query.resultList
val count = queryCount.resultList.first()
em.close()
return hashMapOf("total" to count, "list" to list as List<TravelNotesDTO>)
}
} | 0 | Kotlin | 0 | 0 | 4551912543cf95b2372a0aa0d9142f2faa2fcbf5 | 2,270 | skywalker | Apache License 2.0 |
data/api/src/test/java/com/challenge/android_template/api/FooApiClientTest.kt | merRen22 | 392,808,733 | false | null | package com.challenge.android_template.api
import com.google.common.truth.Truth.assertThat
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import retrofit2.Retrofit
@RunWith(JUnit4::class)
class FooApiClientTest {
@get:Rule
val mockWebServer = MockWebServer()
private lateinit var client: FooApiClient
@Before
fun setUp() {
val converterFactory = Json {
isLenient = true
ignoreUnknownKeys = true
}.asConverterFactory("application/json".toMediaType())
val retrofit = Retrofit.Builder()
.baseUrl(mockWebServer.url("/").toString())
.addConverterFactory(converterFactory)
.build()
client = FooApiClient(retrofit)
}
@Test
fun `get foos`() {
runBlocking {
val json =
"""
{
"items" :[
{
"id": 1,
"name": "elon"
},
{
"id": 2,
"name": "jeff"
}
]
}
""".trimIndent()
mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody(json))
val foos = client.getAllFoos()
assertThat(foos.size).isAtLeast(1)
assertThat(foos.first().name).isEqualTo("elon")
}
}
} | 0 | Kotlin | 0 | 0 | e94b54a1b9f4786315bfdf6caf81445fc89b9fab | 1,631 | template-android | Apache License 2.0 |
server/src/main/kotlin/net/eiradir/server/entity/EntityIdCacheImpl.kt | Eiradir | 635,460,745 | false | {"Kotlin": 646160, "Dockerfile": 470} | package net.eiradir.server.entity
import com.badlogic.ashley.core.Entity
import com.google.common.eventbus.Subscribe
import ktx.ashley.mapperFor
import net.eiradir.server.entity.components.IdComponent
import net.eiradir.server.entity.event.EntitiesAddedEvent
import net.eiradir.server.entity.event.EntitiesRemovedEvent
import net.eiradir.server.entity.event.EntityAddedEvent
import net.eiradir.server.entity.event.EntityRemovedEvent
import net.eiradir.server.plugin.EventBusSubscriber
import java.util.*
class EntityIdCacheImpl : EntityIdCache, EventBusSubscriber {
private val idMapper = mapperFor<IdComponent>()
private val entitiesById = mutableMapOf<UUID, Entity>()
override fun getEntityById(id: UUID): Entity? {
return entitiesById[id]
}
private fun add(entity: Entity) {
val entityId = idMapper[entity]?.id ?: throw IllegalStateException("Entity must have an ID")
entitiesById[entityId] = entity
}
private fun remove(entity: Entity) {
val entityId = idMapper[entity]?.id ?: throw IllegalStateException("Entity must have an ID")
entitiesById.remove(entityId)
}
@Subscribe
fun onEntityAdded(event: EntityAddedEvent) {
add(event.entity)
}
@Subscribe
fun onEntityRemoved(event: EntityRemovedEvent) {
remove(event.entity)
}
@Subscribe
fun onEntitiesAdded(event: EntitiesAddedEvent) {
event.entities.forEach { add(it) }
}
@Subscribe
fun onEntitiesRemoved(event: EntitiesRemovedEvent) {
event.entities.forEach { remove(it) }
}
} | 11 | Kotlin | 0 | 0 | edca8986ef06fd5a75fd2a4dc53dfe75dbfbbaae | 1,591 | eiradir-server | MIT License |
app/src/main/kotlin/com/adesso/movee/scene/persondetail/PersonDetailViewModel.kt | adessoTurkey | 246,803,496 | false | null | package com.adesso.movee.scene.persondetail
import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.adesso.movee.base.BaseAndroidViewModel
import com.adesso.movee.domain.FetchPersonDetailsUseCase
import com.adesso.movee.internal.util.AppBarStateChangeListener
import com.adesso.movee.internal.util.AppBarStateChangeListener.State.COLLAPSED
import com.adesso.movee.internal.util.AppBarStateChangeListener.State.EXPANDED
import com.adesso.movee.internal.util.AppBarStateChangeListener.State.IDLE
import com.adesso.movee.uimodel.PersonDetailUiModel
import com.github.michaelbull.result.onFailure
import com.github.michaelbull.result.onSuccess
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class PersonDetailViewModel @Inject constructor(
private val fetchPersonDetailsUseCase: FetchPersonDetailsUseCase,
application: Application
) : BaseAndroidViewModel(application) {
private val _personDetails = MutableLiveData<PersonDetailUiModel>()
private val _profileToolbarTitle = MutableLiveData<String>()
val personDetails: LiveData<PersonDetailUiModel> get() = _personDetails
val profileToolbarTitle: LiveData<String> get() = _profileToolbarTitle
fun fetchPersonDetails(personId: Long) {
if (_personDetails.value == null) {
viewModelScope.launch {
val personDetailResult =
fetchPersonDetailsUseCase.run(FetchPersonDetailsUseCase.Params(personId))
runOnViewModelScope {
personDetailResult
.onSuccess(::postPersonDetails)
.onFailure(::handleFailure)
}
}
}
}
private fun postPersonDetails(personDetailUiModel: PersonDetailUiModel) {
_personDetails.value = personDetailUiModel
}
fun onProfileAppBarStateChange(state: AppBarStateChangeListener.State) {
val title = when (state) {
COLLAPSED -> _personDetails.value?.name ?: ""
EXPANDED, IDLE -> ""
}
_profileToolbarTitle.value = title
}
}
| 32 | null | 13 | 35 | b34346a815204c966311f0c879b66e05a10eab13 | 2,246 | android-sample-app | Apache License 2.0 |
app/src/main/java/ca/llamabagel/transpo/di/CoreComponent.kt | Llamabagel | 175,222,878 | false | {"Kotlin": 191040} | /*
* Copyright (c) 2019 <NAME>. Subject to the MIT license.
*/
package ca.llamabagel.transpo.di
import android.content.Context
import ca.llamabagel.transpo.TranspoApplication
import ca.llamabagel.transpo.home.ui.HomeViewModel
import ca.llamabagel.transpo.map.ui.MapViewModel
import ca.llamabagel.transpo.search.ui.SearchViewModel
import ca.llamabagel.transpo.settings.data.AppSettings
import ca.llamabagel.transpo.trips.ui.StopViewModel
import ca.llamabagel.transpo.trips.ui.TripDetailsViewModel
import ca.llamabagel.transpo.trips.ui.TripsMapViewModel
import ca.llamabagel.transpo.trips.ui.TripsViewModel
import dagger.BindsInstance
import dagger.Component
import javax.inject.Singleton
@Component(
modules = [
CoreModule::class,
DataModule::class,
SharedPreferencesModule::class,
TransitDatabaseModule::class,
WorkerModule::class,
AssistedWorkerInjectModule::class
]
)
@Singleton
interface CoreComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun applicationContext(applicationContext: Context): Builder
fun build(): CoreComponent
}
fun factory(): InjectionWorkerFactory
fun homeViewModelFactory(): ViewModelFactory<HomeViewModel>
fun tripsViewModelFactory(): ViewModelFactory<TripsViewModel>
fun stopViewModelFactory(): ViewModelFactory<StopViewModel>
fun tripsMapViewModelFactory(): ViewModelFactory<TripsMapViewModel>
fun tripDetailsViewModelFactory(): ViewModelFactory<TripDetailsViewModel>
fun searchViewModelFactory(): ViewModelFactory<SearchViewModel>
fun mapViewModelFactory(): ViewModelFactory<MapViewModel>
fun appSettings(): AppSettings
fun inject(application: TranspoApplication)
} | 10 | Kotlin | 2 | 1 | 70ca00367b6cb93a8c1bd19f1a6524e093b65484 | 1,754 | transpo-android | MIT License |
app/src/main/java/ca/llamabagel/transpo/di/CoreComponent.kt | Llamabagel | 175,222,878 | false | {"Kotlin": 191040} | /*
* Copyright (c) 2019 <NAME>. Subject to the MIT license.
*/
package ca.llamabagel.transpo.di
import android.content.Context
import ca.llamabagel.transpo.TranspoApplication
import ca.llamabagel.transpo.home.ui.HomeViewModel
import ca.llamabagel.transpo.map.ui.MapViewModel
import ca.llamabagel.transpo.search.ui.SearchViewModel
import ca.llamabagel.transpo.settings.data.AppSettings
import ca.llamabagel.transpo.trips.ui.StopViewModel
import ca.llamabagel.transpo.trips.ui.TripDetailsViewModel
import ca.llamabagel.transpo.trips.ui.TripsMapViewModel
import ca.llamabagel.transpo.trips.ui.TripsViewModel
import dagger.BindsInstance
import dagger.Component
import javax.inject.Singleton
@Component(
modules = [
CoreModule::class,
DataModule::class,
SharedPreferencesModule::class,
TransitDatabaseModule::class,
WorkerModule::class,
AssistedWorkerInjectModule::class
]
)
@Singleton
interface CoreComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun applicationContext(applicationContext: Context): Builder
fun build(): CoreComponent
}
fun factory(): InjectionWorkerFactory
fun homeViewModelFactory(): ViewModelFactory<HomeViewModel>
fun tripsViewModelFactory(): ViewModelFactory<TripsViewModel>
fun stopViewModelFactory(): ViewModelFactory<StopViewModel>
fun tripsMapViewModelFactory(): ViewModelFactory<TripsMapViewModel>
fun tripDetailsViewModelFactory(): ViewModelFactory<TripDetailsViewModel>
fun searchViewModelFactory(): ViewModelFactory<SearchViewModel>
fun mapViewModelFactory(): ViewModelFactory<MapViewModel>
fun appSettings(): AppSettings
fun inject(application: TranspoApplication)
} | 10 | Kotlin | 2 | 1 | 70ca00367b6cb93a8c1bd19f1a6524e093b65484 | 1,754 | transpo-android | MIT License |
shared/src/commonMain/kotlin/App.kt | amdevprojects | 685,035,772 | false | null | import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import assets.composable.AssetScreen
import assets.viewmodel.AssetsViewModel
import dev.icerock.moko.mvvm.compose.getViewModel
import dev.icerock.moko.mvvm.compose.viewModelFactory
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
@Composable
fun App() {
MaterialTheme {
val viewModel = getViewModel(Unit, viewModelFactory { AssetsViewModel() })
AssetScreen(viewModel)
}
}
expect fun getPlatformName(): String | 0 | Kotlin | 0 | 0 | 55dd62007683dcf83edd7ee7104f4674a2150b95 | 578 | ComposeKMMPOC | Apache License 2.0 |
app/src/main/java/com/dev/nytimes/di/RepoDIComponent.kt | ArsalanReal | 256,028,916 | false | null | package com.dev.nytimes.di
import com.dev.nytimes.repository.NewsRepository
import org.koin.dsl.module
/**
* Repository DI module.
* Provides Repo dependency.
*/
val RepoDependency = module {
factory {
NewsRepository()
}
} | 0 | Kotlin | 0 | 0 | 2739ae0c8e12766f0baa86cacfbdf29a7fea12b4 | 245 | CleanCodeAssessment | Apache License 2.0 |
app/src/main/java/com/ensias/sportnet/showers/ProfileActivity.kt | khaouitiabdelhakim | 768,285,505 | false | {"Kotlin": 113474} | package com.ensias.sportnet.showers
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.ensias.sportnet.databinding.ActivityProfileBinding
import com.ensias.sportnet.models.User
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
class ProfileActivity : AppCompatActivity() {
private lateinit var binding: ActivityProfileBinding
private lateinit var auth: FirebaseAuth
private lateinit var database: FirebaseDatabase
private lateinit var storage: FirebaseStorage
private lateinit var userRef: DatabaseReference
private lateinit var storageRef: StorageReference
private lateinit var currentUser: User
private var selectedContentUri: Uri? = null
private val getContent: ActivityResultLauncher<Intent> =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
result.data?.data?.let { uri ->
selectedContentUri = uri
Glide.with(this)
.load(selectedContentUri)
.apply(RequestOptions().centerCrop())
.into(binding.profile)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityProfileBinding.inflate(layoutInflater)
setContentView(binding.root)
auth = FirebaseAuth.getInstance()
database = FirebaseDatabase.getInstance()
storage = FirebaseStorage.getInstance()
userRef = database.reference.child("users").child(intent.getStringExtra("userId").toString())
storageRef = storage.reference.child("profile_pictures").child(auth.currentUser!!.uid)
loadCurrentUser()
binding.updateProfile.setOnClickListener {
updateProfile()
}
binding.profile.setOnClickListener {
openFilePicker()
}
}
private fun loadCurrentUser() {
userRef.get().addOnSuccessListener { snapshot ->
if (snapshot.exists()) {
currentUser = snapshot.getValue(User::class.java)!!
with(binding) {
username.text = currentUser.username
email.text = currentUser.email
description.setText(currentUser.description)
Glide.with(this@ProfileActivity)
.load(currentUser.profilePictureUrl)
.apply(RequestOptions().circleCrop())
.into(profile)
}
}
}.addOnFailureListener { exception ->
Log.e("ProfileActivity", "Error fetching current user: ${exception.message}")
}
}
private fun openFilePicker() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
getContent.launch(intent)
}
private fun updateProfile() {
val newDescription = binding.description.text.toString().trim()
if (newDescription.isEmpty() && selectedContentUri == null) return
binding.updateProfile.isClickable = false
binding.updateProfileText.visibility = View.INVISIBLE
binding.updateProfileProgress.visibility = View.VISIBLE
if (newDescription.isNotEmpty()) {
currentUser.description = newDescription
updateUser()
} else {
selectedContentUri?.let {
uploadProfilePicture(it)
}
}
}
private fun updateUser() {
userRef.setValue(currentUser)
.addOnSuccessListener {
Log.d("ProfileActivity", "Profile description updated successfully")
selectedContentUri?.let {
uploadProfilePicture(it)
} ?: updateUIAfterUpdate()
}
.addOnFailureListener { exception ->
handleProfileUpdateError(exception)
}
}
private fun uploadProfilePicture(uri: Uri) {
storageRef.putFile(uri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { downloadUri ->
currentUser.profilePictureUrl = downloadUri.toString()
updateUser()
}
.addOnFailureListener { exception ->
handleProfileUpdateError(exception)
}
}
.addOnFailureListener { exception ->
handleProfileUpdateError(exception)
}
}
private fun updateUIAfterUpdate() {
Log.d("ProfileActivity", "Profile picture updated successfully")
binding.updateProfile.isClickable = true
binding.updateProfileText.visibility = View.VISIBLE
binding.updateProfileProgress.visibility = View.INVISIBLE
}
private fun handleProfileUpdateError(exception: Exception) {
Log.e("ProfileActivity", "Error updating profile: ${exception.message}")
binding.updateProfile.isClickable = true
binding.updateProfileText.visibility = View.VISIBLE
binding.updateProfileProgress.visibility = View.INVISIBLE
}
}
| 0 | Kotlin | 0 | 2 | b2286cc655a91058840ac49dd50fce83a5ef1dc8 | 6,052 | SportNet | MIT License |
desktop/src/main/kotlin/be/jameswilliams/preso/desktop/DesktopLauncher.kt | jwill | 116,086,860 | false | null | package be.jameswilliams.preso.desktop
import be.jameswilliams.preso.Presentation
import com.badlogic.gdx.Files
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
object DesktopLauncher {
@JvmStatic
fun main(args: Array<String>) {
createApplication()
}
private fun createApplication() = LwjglApplication(Presentation, defaultConfiguration)
private val defaultConfiguration: LwjglApplicationConfiguration
get() {
val configuration = LwjglApplicationConfiguration()
configuration.title = "Presentation"
// TODO Later support fullscreen toggle
//configuration.width = 1920
//configuration.height = 1080
configuration.width = LwjglApplicationConfiguration.getDesktopDisplayMode().width;
configuration.height = LwjglApplicationConfiguration.getDesktopDisplayMode().height;
//Set full screem
System.setProperty("org.lwjgl.opengl.Window.undecorated", "true");
/*configuration.width = LwjglApplicationConfiguration.getDesktopDisplayMode().width;
configuration.height = LwjglApplicationConfiguration.getDesktopDisplayMode().height;
*/
for (size in intArrayOf(128, 64, 32, 16)) {
configuration.addIcon("libgdx$size.png", Files.FileType.Internal)
}
return configuration
}
} | 0 | Kotlin | 1 | 0 | 33b4e797f69988bd33deb3277fc6866159f3afd1 | 1,484 | refactored-robot | MIT License |
core/src/main/kotlin/org/springframework/samples/petclinic/rest/coroutine/CoroutineSleepController.kt | kotoant | 612,221,740 | false | {"Kotlin": 230920, "JavaScript": 102019, "Mustache": 10054, "PLpgSQL": 2929, "Shell": 1403, "Dockerfile": 709} | package org.springframework.samples.petclinic.rest.coroutine
import org.springframework.context.annotation.Profile
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.samples.petclinic.rest.api.coroutine.SleepAndFetchCoroutineApi
import org.springframework.samples.petclinic.rest.api.coroutine.SleepCoroutineApi
import org.springframework.samples.petclinic.service.coroutine.CoroutineClinicService
import org.springframework.web.bind.annotation.RestController
@RestController
@Profile("coroutine")
class CoroutineSleepController(private val clinicService: CoroutineClinicService) : SleepCoroutineApi,
SleepAndFetchCoroutineApi {
override suspend fun sleep(times: Int, millis: Int, zip: Boolean): ResponseEntity<Unit> {
clinicService.sleep(times, millis, zip)
return ResponseEntity(HttpStatus.OK)
}
override suspend fun sleepAndFetch(
times: Int, sleep: Boolean, millis: Int, strings: Int, length: Int, jooq: Boolean, db: Boolean
): ResponseEntity<List<String>> {
val result = if (db) clinicService.sleepAndFetchWithDb(times, sleep, millis, strings, length, jooq)
else clinicService.sleepAndFetchWithoutDb(times, sleep, millis, strings, length)
return ResponseEntity(result, HttpStatus.OK)
}
}
| 0 | Kotlin | 0 | 2 | 365b0ce4d9eaacee8c888511915c404f414cbd8c | 1,333 | spring-petclinic-rest | Apache License 2.0 |
threejs-wrapper/src/main/kotlin/info/laht/threekt/extras/core/CurvePath.kt | markaren | 111,575,995 | false | null | @file:JsQualifier("THREE")
package info.laht.threekt.extras.core
open external class CurvePath<E> : Curve<E> {
var curves: List<Curve<E>>
var autoClose: Boolean
fun add(curve: Curve<E>)
fun closePath()
fun getPoint(t: Double)
override fun clone(): CurvePath<E>
fun copy(source: CurvePath<E>) : CurvePath<E>
} | 1 | Kotlin | 11 | 53 | c13a96add591a7e0e52911c4d8f59dddfc6165ef | 346 | three-kt-wrapper | MIT License |
src/test/kotlin/com/intellij/ml/llm/template/UtilsTest.kt | JetBrains-Research | 616,565,282 | false | null | package com.intellij.ml.llm.template
import com.intellij.ml.llm.template.extractfunction.EFSuggestion
import com.intellij.ml.llm.template.models.ExtractFunctionLLMRequestProvider
import com.intellij.ml.llm.template.models.LLMRequestProvider
import com.intellij.ml.llm.template.models.sendChatRequest
import com.intellij.ml.llm.template.utils.*
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import junit.framework.TestCase
class UtilsTest : LightPlatformCodeInsightTestCase() {
private var projectPath = "src/test"
override fun getTestDataPath(): String {
return projectPath
}
fun `test identify extract function suggestions from chatgpt reply`() {
val input = """
I would suggest the following extract method refactorings:
1. Extract method for creating `GroupRebalanceConfig` object from lines 2650-2656.
2. Extract method for creating `ConsumerCoordinator` object from lines 2649-2670.
3. Extract method for creating `FetchConfig` object from lines 2674-2684.
4. Extract method for creating `Fetcher` object from lines 2685-2692.
5. Extract method for creating `OffsetFetcher` object from lines 2693-2701.
6. Extract method for creating `TopicMetadataFetcher` object from lines 2702-2703.
The JSON object for these extract method refactorings would be:
```
[
{"function_name": "createRebalanceConfig", "line_start": 2650, "line_end": 2656},
{"function_name": "createConsumerCoordinator", "line_start": 2649, "line_end": 2670},
{"function_name": "createFetchConfig", "line_start": 2674, "line_end": 2684},
{"function_name": "createFetcher", "line_start": 2685, "line_end": 2692},
{"function_name": "createOffsetFetcher", "line_start": 2693, "line_end": 2701},
{"function_name": "createTopicMetadataFetcher", "line_start": 2702, "line_end": 2703}
]
```
""".trimIndent()
val efSuggestionList = identifyExtractFunctionSuggestions(input)
TestCase.assertEquals(6, efSuggestionList.suggestionList.size)
TestCase.assertEquals("createRebalanceConfig", efSuggestionList.suggestionList.get(0).functionName)
TestCase.assertEquals(
2650 to 2656,
efSuggestionList.suggestionList.get(0).lineStart to efSuggestionList.suggestionList.get(0).lineEnd
)
TestCase.assertEquals("createConsumerCoordinator", efSuggestionList.suggestionList.get(1).functionName)
TestCase.assertEquals(
2649 to 2670,
efSuggestionList.suggestionList.get(1).lineStart to efSuggestionList.suggestionList.get(1).lineEnd
)
TestCase.assertEquals("createFetchConfig", efSuggestionList.suggestionList.get(2).functionName)
TestCase.assertEquals(
2674 to 2684,
efSuggestionList.suggestionList.get(2).lineStart to efSuggestionList.suggestionList.get(2).lineEnd
)
TestCase.assertEquals("createFetcher", efSuggestionList.suggestionList.get(3).functionName)
TestCase.assertEquals(
2685 to 2692,
efSuggestionList.suggestionList.get(3).lineStart to efSuggestionList.suggestionList.get(3).lineEnd
)
TestCase.assertEquals("createOffsetFetcher", efSuggestionList.suggestionList.get(4).functionName)
TestCase.assertEquals(
2693 to 2701,
efSuggestionList.suggestionList.get(4).lineStart to efSuggestionList.suggestionList.get(4).lineEnd
)
TestCase.assertEquals("createTopicMetadataFetcher", efSuggestionList.suggestionList.get(5).functionName)
TestCase.assertEquals(
2702 to 2703,
efSuggestionList.suggestionList.get(5).lineStart to efSuggestionList.suggestionList.get(5).lineEnd
)
}
fun `test identify extract function suggestions from ChatGPT reply in mock mode`() {
com.intellij.openapi.util.registry.Registry.get("llm.for.code.enable.mock.requests").setValue(true)
val mockReply = """
{"id":"chatcmpl-7ODaGfLVvacxtdsodruHUvYswiDwH","object":"chat.completion","created":1686006444,"model":"gpt-3.5-turbo-0301","usage":{"prompt_tokens":1830,"completion_tokens":70,"total_tokens":1900},"choices":[{"message":{"role":"assistant","content":"[\n{\"function_name\": \"advanceReadInputCharacter\", \"line_start\": 646, \"line_end\": 691},\n{\"function_name\": \"getNextTransition\", \"line_start\": 692, \"line_end\": 703},\n{\"function_name\": \"handleAction\", \"line_start\": 714, \"line_end\": 788}\n]"},"finish_reason":"stop","index":0}]}
""".trimIndent()
val efLLMRequestProvider: LLMRequestProvider =
ExtractFunctionLLMRequestProvider("text-davinci-003", "text-davinci-edit-001", "gpt-3.5-turbo", mockReply)
val llmResponse = sendChatRequest(
project, emptyList(), efLLMRequestProvider.chatModel, efLLMRequestProvider
)
val llmSuggestions = llmResponse?.getSuggestions()
val efSuggestions = identifyExtractFunctionSuggestions(llmSuggestions?.get(0)?.text!!).suggestionList
TestCase.assertEquals(3, efSuggestions.size)
}
fun `test no identifiable suggestions in chatgpt reply`() {
val input = """
"The above function does not have any extract method opportunities."
""".trimIndent()
val efSuggestionList = identifyExtractFunctionSuggestions(input)
TestCase.assertEquals(0, efSuggestionList.suggestionList.size)
}
fun `test replace github url line range`() {
val url =
"https://github.com/apache/kafka/blob/trunk/clients/src/test/java/org/apache/kafka/common/requests/UpdateMetadataRequestTest.java#L81-L212"
val expectedUrl =
"https://github.com/apache/kafka/blob/trunk/clients/src/test/java/org/apache/kafka/common/requests/UpdateMetadataRequestTest.java#L90-L120"
val actualUrl = replaceGithubUrlLineRange(url, 90, 120)
TestCase.assertEquals(expectedUrl, actualUrl)
}
fun `test isCandidateExtractable generates correct notifications`() {
configureByFile("/testdata/KafkaAdminClientTest.java")
val efSuggestion = EFSuggestion(
functionName = "foo",
lineStart = 114,
lineEnd = 119
)
val efObserver = EFObserver()
val candidates = EFCandidateFactory().buildCandidates(efSuggestion, editor, file).toTypedArray()
TestCase.assertEquals(2, candidates.size)
candidates.forEach { isCandidateExtractable(it, editor, file, efObserver) }
val notifications = efObserver.getNotifications()
TestCase.assertEquals(2, notifications.size)
TestCase.assertEquals(EFApplicationResult.OK, notifications.get(0).result)
TestCase.assertEquals(EFApplicationResult.FAIL, notifications.get(1).result)
}
} | 0 | Kotlin | 0 | 0 | 59c0b32e006f53839d41fe71f6123328854b6ced | 7,020 | llm-guide-refactorings | MIT License |
planty-client/common/src/jvmMain/kotlin/nest/planty/data/sqldelight/DriverFactory.jvm.kt | HLCaptain | 693,789,413 | false | {"Kotlin": 186539, "Python": 9666, "C++": 4729, "HTML": 1243, "JavaScript": 1215, "CSS": 173} | package nest.planty.data.sqldelight
import app.cash.sqldelight.async.coroutines.synchronous
import app.cash.sqldelight.db.QueryResult
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.db.SqlSchema
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
actual suspend fun provideSqlDriver(schema: SqlSchema<QueryResult.AsyncValue<Unit>>): SqlDriver {
// TODO: Use a file-based database instead of in-memory for local persistence
return JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY)
.also { schema.synchronous().create(it) }
}
| 0 | Kotlin | 0 | 0 | bf42461ccd164962a0d19c3718ff074ca1aaa350 | 567 | planty | MIT License |
src/commonMain/kotlin/com/d10ng/datelib/WeekTextType.kt | D10NGYANG | 378,012,609 | false | null | package com.d10ng.datelib
enum class WeekTextType (val list: List<String>) {
// 星期日
CN (listOf("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日")),
// 周日
CN_SHORT (listOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")),
// 日
CN_MINI (listOf("一", "二", "三", "四", "五", "六", "日")),
// MONDAY
EN (listOf("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY")),
// MON
EN_SHORT (listOf("MON", "TUE", "WED", "THUR", "FRI", "SAT", "SUN")),
}
enum class MonthTextType (val list: List<String>) {
// 一月
CN (listOf("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月")),
// JANUARY
EN (listOf("JANUARY", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")),
// JAN
EN_SHORT (listOf("JAN", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")),
} | 0 | Kotlin | 0 | 2 | e91f7f7a884b43c6bf22c7de834753eb6a11d5d3 | 920 | DLDateUtil | MIT License |
src/commonMain/kotlin/com/d10ng/datelib/WeekTextType.kt | D10NGYANG | 378,012,609 | false | null | package com.d10ng.datelib
enum class WeekTextType (val list: List<String>) {
// 星期日
CN (listOf("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日")),
// 周日
CN_SHORT (listOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")),
// 日
CN_MINI (listOf("一", "二", "三", "四", "五", "六", "日")),
// MONDAY
EN (listOf("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY")),
// MON
EN_SHORT (listOf("MON", "TUE", "WED", "THUR", "FRI", "SAT", "SUN")),
}
enum class MonthTextType (val list: List<String>) {
// 一月
CN (listOf("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月")),
// JANUARY
EN (listOf("JANUARY", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")),
// JAN
EN_SHORT (listOf("JAN", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")),
} | 0 | Kotlin | 0 | 2 | e91f7f7a884b43c6bf22c7de834753eb6a11d5d3 | 920 | DLDateUtil | MIT License |
app/src/main/java/com/example/bluromatic/data/WorkManagerBluromaticRepository.kt | Bekzat-Chauvbayev | 729,249,117 | false | {"Kotlin": 36719} | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.bluromatic.data
import android.content.Context
import android.net.Uri
import androidx.lifecycle.asFlow
import androidx.work.Constraints
import androidx.work.Data
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.example.bluromatic.IMAGE_MANIPULATION_WORK_NAME
import com.example.bluromatic.KEY_BLUR_LEVEL
import com.example.bluromatic.KEY_IMAGE_URI
import com.example.bluromatic.TAG_OUTPUT
import com.example.bluromatic.getImageUri
import com.example.bluromatic.workers.BlurWorker
import com.example.bluromatic.workers.CleanupWorker
import com.example.bluromatic.workers.SaveImageToFileWorker
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.mapNotNull
class WorkManagerBluromaticRepository(context: Context) : BluromaticRepository {
private val workManager = WorkManager.getInstance(context)
private var imageUri: Uri = context.getImageUri()
override val outputWorkInfo: Flow<WorkInfo> =
workManager.getWorkInfosByTagLiveData(TAG_OUTPUT).asFlow().mapNotNull {
if (it.isNotEmpty()) it.first() else null
}
override fun applyBlur(blurLevel: Int) {
var continuation = workManager
.beginUniqueWork(
IMAGE_MANIPULATION_WORK_NAME,
ExistingWorkPolicy.REPLACE,
OneTimeWorkRequest.from(CleanupWorker::class.java)
)
val constraints = Constraints.Builder().setRequiresBatteryNotLow(true).build()
val blurBuilder = OneTimeWorkRequestBuilder<BlurWorker>()
blurBuilder.setInputData(createInputDataForWorkRequest(blurLevel, imageUri))
blurBuilder.setConstraints(constraints)
workManager.enqueue(blurBuilder.build())
continuation = continuation.then(blurBuilder.build())
val save = OneTimeWorkRequestBuilder<SaveImageToFileWorker>().addTag(TAG_OUTPUT)
.build()
continuation = continuation.then(save)
continuation.enqueue()
}
override fun cancelWork() {
workManager.cancelUniqueWork(IMAGE_MANIPULATION_WORK_NAME)
}
private fun createInputDataForWorkRequest(blurLevel: Int, imageUri: Uri): Data {
val builder = Data.Builder()
builder.putString(KEY_IMAGE_URI, imageUri.toString()).putInt(KEY_BLUR_LEVEL, blurLevel)
return builder.build()
}
}
| 0 | Kotlin | 0 | 0 | 6c6c4906660bf9a147a42da58e88a4a4b5ad8703 | 3,148 | Background-work-with-WorkManager | Apache License 2.0 |
src/main/kotlin/com/cout970/ps/lexer/ParserImport.kt | cout970 | 68,954,931 | false | null | package com.cout970.ps.lexer
import com.cout970.ps.components.CompImport
import com.cout970.ps.tokenizer.ITokenStream
import com.cout970.ps.tokenizer.TokenType
/**
* Created by cout970 on 2016/09/20.
*/
object ParserImport {
fun parse(tk: ITokenStream): CompImport {
var look = tk.readToken()
look.expect(TokenType.IMPORT, "import keyword")
look = tk.readToken()
look.expect(TokenType.IDENTIFIER, "import path")
var path = look.text
look = tk.readToken()
while (look.type == TokenType.DOT) {
look = tk.readToken()
look.expect(TokenType.IDENTIFIER, "import path")
path += "." + look.text
look = tk.readToken()
}
return CompImport(path)
}
} | 0 | Kotlin | 0 | 3 | ba5e39f2866641b27af4309e87ba144aae93b9c9 | 771 | Kotlin-Interpreter | MIT License |
selfie-lib/src/jvmMain/kotlin/com/diffplug/selfie/guts/WriteTracker.jvm.kt | diffplug | 616,728,028 | false | {"Kotlin": 191646, "JavaScript": 1951, "Scheme": 1876, "CSS": 1639, "FreeMarker": 1430} | /*
* Copyright (C) 2024 DiffPlug
*
* 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.diffplug.selfie.guts
import java.util.stream.Collectors
/** Represents the line at which user code called into Selfie. */
actual data class CallLocation(
val clazz: String,
val method: String,
actual val fileName: String?,
actual val line: Int
) : Comparable<CallLocation> {
actual fun samePathAs(other: CallLocation): Boolean =
clazz == other.clazz && fileName == other.fileName
override fun compareTo(other: CallLocation): Int =
compareValuesBy(this, other, { it.clazz }, { it.method }, { it.fileName }, { it.line })
/**
* If the runtime didn't give us the filename, guess it from the class, and try to find the source
* file by walking the CWD. If we don't find it, report it as a `.class` file.
*/
private fun findFileIfAbsent(layout: SnapshotFileLayout): String {
if (fileName != null) {
return fileName
}
return layout.sourcePathForCall(this)?.let { layout.fs.name(it) }
?: "${clazz.substringAfterLast('.')}.class"
}
/** A `toString` which an IDE will render as a clickable link. */
actual fun ideLink(layout: SnapshotFileLayout): String {
return "$clazz.$method(${findFileIfAbsent(layout)}:$line)"
}
}
/** Generates a CallLocation and the CallStack behind it. */
actual fun recordCall(): CallStack {
val calls =
StackWalker.getInstance().walk { frames ->
frames
.dropWhile { it.className.startsWith("com.diffplug.selfie") }
.map {
com.diffplug.selfie.guts.CallLocation(
it.className, it.methodName, it.fileName, it.lineNumber)
}
.collect(Collectors.toList())
}
return CallStack(calls.removeAt(0), calls)
}
| 13 | Kotlin | 0 | 4 | cacd21ae2c255593e34a3548f30e5df131253bfc | 2,314 | selfie | Apache License 2.0 |
src/main/kotlin/dev/tmsoft/lib/exposed/dao/PrivateEntityClass.kt | turbomates | 377,843,961 | false | null | package dev.tmsoft.lib.exposed.dao
import org.jetbrains.exposed.dao.Entity
import org.jetbrains.exposed.dao.EntityClass
import org.jetbrains.exposed.dao.InnerTableLink
import org.jetbrains.exposed.dao.OptionalBackReference
import org.jetbrains.exposed.dao.OptionalReferrers
import org.jetbrains.exposed.dao.Referrers
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.Table
import kotlin.properties.ReadOnlyProperty
open class PrivateEntityClass<ID : Comparable<ID>, out T : Entity<ID>>(private val base: EntityClass<ID, T>) {
open fun new(init: T.() -> Unit) = base.new(null, init)
fun get(id: EntityID<ID>): T = base[id]
operator fun get(id: ID): T = base[id]
infix fun <REF : Comparable<REF>> referencedOn(column: Column<REF>) = base.referencedOn(column)
infix fun <REF : Comparable<REF>> optionalReferencedOn(column: Column<REF?>) = base.optionalReferencedOn(column)
infix fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> PrivateEntityClass<TargetID, Target>.backReferencedOn(
column: Column<REF>
): ReadOnlyProperty<Entity<TargetID>, Target> {
return base.backReferencedOn(column)
}
@JvmName("backReferencedOnOpt")
infix fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> PrivateEntityClass<TargetID, Target>.backReferencedOn(
column: Column<REF?>
): ReadOnlyProperty<Entity<TargetID>, Target> {
return base.backReferencedOn(column)
}
infix fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> PrivateEntityClass<TargetID, Target>.optionalBackReferencedOn(
column: Column<REF>
): OptionalBackReference<TargetID, Target, TargetID, Entity<TargetID>, REF> {
return base.optionalBackReferencedOn(column)
}
@JvmName("optionalBackReferencedOnOpt")
infix fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> PrivateEntityClass<TargetID, Target>.optionalBackReferencedOn(
column: Column<REF?>
): OptionalBackReference<TargetID, Target, TargetID, Entity<TargetID>, REF> {
return base.optionalBackReferencedOn(column)
}
infix fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> PrivateEntityClass<TargetID, Target>.referrersOn(
column: Column<REF>
): Referrers<TargetID, Entity<TargetID>, TargetID, Target, REF> {
return base.referrersOn(column)
}
fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> PrivateEntityClass<TargetID, Target>.referrersOn(
column: Column<REF>,
cache: Boolean
): Referrers<TargetID, Entity<TargetID>, TargetID, Target, REF> {
return base.referrersOn(column, cache)
}
infix fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> PrivateEntityClass<TargetID, Target>.optionalReferrersOn(
column: Column<REF?>
): OptionalReferrers<TargetID, Entity<TargetID>, TargetID, Target, REF> {
return base.optionalReferrersOn(column)
}
fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> PrivateEntityClass<TargetID, Target>.optionalReferrersOn(
column: Column<REF?>,
cache: Boolean = false
): OptionalReferrers<TargetID, Entity<TargetID>, TargetID, Target, REF> {
return base.optionalReferrersOn(column, cache)
}
infix fun <TID : Comparable<TID>, Target : Entity<TID>> PrivateEntityClass<TID, Target>.via(table: Table): InnerTableLink<ID, Entity<ID>, TID, Target> =
InnerTableLink(table, [email protected])
fun <TID : Comparable<TID>, Target : Entity<TID>> PrivateEntityClass<TID, Target>.via(
sourceColumn: Column<EntityID<ID>>,
targetColumn: Column<EntityID<TID>>
) =
InnerTableLink(sourceColumn.table, <EMAIL>, sourceColumn, targetColumn)
private fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> EntityClass<TargetID, Target>.backReferencedOn(
column: Column<REF?>
): ReadOnlyProperty<Entity<TargetID>, Target> {
return backReferencedOn(column)
}
@JvmName("baseBackReferencedOnOpt")
private fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> EntityClass<TargetID, Target>.backReferencedOn(
column: Column<REF>
): ReadOnlyProperty<Entity<TargetID>, Target> {
return backReferencedOn(column)
}
private fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> EntityClass<TargetID, Target>.optionalBackReferencedOn(
column: Column<REF>
): OptionalBackReference<TargetID, Target, TargetID, Entity<TargetID>, REF> {
return optionalBackReferencedOn(column)
}
@JvmName("baseOptionalBackReferencedOnOpt")
private fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> EntityClass<TargetID, Target>.optionalBackReferencedOn(
column: Column<REF?>
): OptionalBackReference<TargetID, Target, TargetID, Entity<TargetID>, REF> {
return optionalBackReferencedOn(column)
}
infix fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> EntityClass<TargetID, Target>.referrersOn(
column: Column<REF>
): Referrers<TargetID, Entity<TargetID>, TargetID, Target, REF> {
return referrersOn(column)
}
fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> EntityClass<TargetID, Target>.referrersOn(
column: Column<REF>,
cache: Boolean
): Referrers<TargetID, Entity<TargetID>, TargetID, Target, REF> {
return referrersOn(column, cache)
}
private fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> EntityClass<TargetID, Target>.optionalReferrersOn(
column: Column<REF?>
): OptionalReferrers<TargetID, Entity<TargetID>, TargetID, Target, REF> {
return optionalReferrersOn(column)
}
private fun <TargetID : Comparable<TargetID>, Target : Entity<TargetID>, REF : Comparable<REF>> EntityClass<TargetID, Target>.optionalReferrersOn(
column: Column<REF?>,
cache: Boolean = false
): OptionalReferrers<TargetID, Entity<TargetID>, TargetID, Target, REF> {
return optionalReferrersOn(column, cache)
}
}
| 0 | Kotlin | 0 | 0 | 121136cba526937b44a1871699cb067cb1406dbe | 6,555 | kotlin-back-sdk | Apache License 2.0 |
app/src/main/java/bg/dabulgaria/tibroish/domain/image/IGalleryImagesRepository.kt | ti-broish | 359,553,419 | false | null | package bg.dabulgaria.tibroish.domain.image
interface IGalleryImagesRepository {
fun getImages():List<PickedImage>
} | 1 | Kotlin | 0 | 3 | 0d7f6d401539d7a1c13758ab2cd96a616ebdaab1 | 122 | mobile-android | MIT License |
protocol/kotlin/src/solarxr_protocol/pub_sub/PubSubHeader.kt | SlimeVR | 456,320,520 | false | {"Rust": 790111, "Java": 650829, "TypeScript": 507384, "C++": 434772, "Kotlin": 356034, "PowerShell": 959, "Shell": 910, "Nix": 587} | // automatically generated by the FlatBuffers compiler, do not modify
package solarxr_protocol.pub_sub
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
@Suppress("unused")
class PubSubHeader : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : PubSubHeader {
__init(_i, _bb)
return this
}
val uType : UByte
get() {
val o = __offset(4)
return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u
}
fun u(obj: Table) : Table? {
val o = __offset(6); return if (o != 0) __union(obj, o + bb_pos) else null
}
companion object {
@JvmStatic
fun validateVersion() = Constants.FLATBUFFERS_22_10_26()
@JvmStatic
fun getRootAsPubSubHeader(_bb: ByteBuffer): PubSubHeader = getRootAsPubSubHeader(_bb, PubSubHeader())
@JvmStatic
fun getRootAsPubSubHeader(_bb: ByteBuffer, obj: PubSubHeader): PubSubHeader {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
@JvmStatic
fun createPubSubHeader(builder: FlatBufferBuilder, uType: UByte, uOffset: Int) : Int {
builder.startTable(2)
addU(builder, uOffset)
addUType(builder, uType)
return endPubSubHeader(builder)
}
@JvmStatic
fun startPubSubHeader(builder: FlatBufferBuilder) = builder.startTable(2)
@JvmStatic
fun addUType(builder: FlatBufferBuilder, uType: UByte) = builder.addByte(0, uType.toByte(), 0)
@JvmStatic
fun addU(builder: FlatBufferBuilder, u: Int) = builder.addOffset(1, u, 0)
@JvmStatic
fun endPubSubHeader(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
}
}
| 11 | Rust | 20 | 19 | 60f3146f914e2a9e35d759a8146be213e715d6d2 | 1,927 | SolarXR-Protocol | Apache License 2.0 |
buildSrc/src/main/kotlin/com/datadog/gradle/plugin/jsonschema/TypeProperty.kt | hixio-mh | 281,064,117 | true | {"Kotlin": 1797271, "Java": 213999, "C": 74755, "C++": 15178, "CMake": 1606} | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.gradle.plugin.jsonschema
data class TypeProperty(
val name: String,
val type: TypeDefinition,
val nullable: Boolean
) {
fun mergedWith(other: TypeProperty): TypeProperty {
return if (this == other) {
this
} else {
TypeProperty(
name,
type.mergedWith(other.type),
nullable || other.nullable
)
}
}
}
| 4 | null | 0 | 0 | 3b3bfab22b26067330186c4637e80d19adf334c1 | 698 | dd-sdk-android | Apache License 2.0 |
buildSrc/src/main/kotlin/org/jtrim2/build/Versions.kt | kelemen | 4,034,471 | false | {"Java": 4962857, "Kotlin": 69766} | package org.jtrim2.build
import org.gradle.api.Project
object Versions {
private const val GROUP_NAME = "org.jtrim2"
private const val VERSION_BASE_PROPERTY = "versionBase"
private const val VERSION_SUFFIX_PROPERTY = "versionSuffix"
fun setVersion(project: Project) {
val versionBase = project.rootDir.withChildren("version.txt").readTextFile().trim()
project.extensions.add(VERSION_BASE_PROPERTY, versionBase)
project.group = GROUP_NAME
project.version = versionBase + getVersionSuffix(project)
}
private fun getVersionSuffix(project: Project): String {
val release = ReleaseUtils.isRelease(project)
val defaultSuffix = if (release) "" else "DEV"
val suffix = ProjectUtils.getStringProperty(project, VERSION_SUFFIX_PROPERTY, defaultSuffix)!!
return if (suffix.isEmpty()) "" else "-$suffix"
}
fun getVersion(project: Project): String {
return project.version.toString()
}
fun getVersionBase(project: Project): String {
return ProjectUtils.getStringProperty(project, VERSION_BASE_PROPERTY, "")!!
}
}
| 1 | null | 1 | 1 | d087fe99809a84a618cf4fe889d4036fabb87698 | 1,129 | JTrim | Apache License 2.0 |
src/main/kotlin/dev/ebelekhov/typechecker/StellaExtension.kt | BelehovEgor | 759,297,417 | false | {"Gradle Kotlin DSL": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Smalltalk": 470, "StringTemplate": 1, "Kotlin": 77, "Java": 6, "ANTLR": 2, "YAML": 1, "XML": 8} | package dev.ebelekhov.typechecker
enum class StellaExtension(val extensionName: String) {
// 1
UnitType("#unit-type"),
Pairs("#pairs"),
Tuples("#tuples"),
Records("#records"),
LetBindings("#let-bindings"),
TypeAscriptions("#type-ascriptions"),
SumTypes("#sum-types"),
Lists("#lists"),
Variants("#variants"),
FixpointCombinator("#fixpoint-combinator"),
NaturalLiterals("#natural-literals"),
NestedFunctionDeclarations("#nested-function-declarations"),
NullaryFunctions("#nullary-functions"),
MultiparameterFunctions("#multiparameter-functions"),
StructuralPatterns("#structural-patterns"),
NullaryVariantLabels("#nullary-variant-labels"),
LetrecBindings("#letrec-bindings"),
LetrecManyBindings("#letrec-many-bindings"),
LetPatterns("#let-patterns"),
PatternAscriptions("#pattern-ascriptions"),
GeneralRecursion("#general-recursion"),
// 2
Sequencing("#sequencing"),
References("#references"),
Panic("#panic"),
Exceptions("#exceptions"),
ExceptionTypeAnnotation("#exception-type-annotation"),
ExceptionTypeDeclaration("#exception-type-declaration"),
StructuralSubtyping("#structural-subtyping"),
AmbiguousTypeAsBottom("#ambiguous-type-as-bottom"),
OpenVariantExceptions("#open-variant-exceptions"),
TypeCast("#type-cast"),
TryCastAs("#try-cast-as"),
TryCastPatterns("#type-cast-patterns"),
TopType("#top-type"),
BottomType("#bottom-type"),
// 3
ArithmeticOperators("#arithmetic-operators"),
TypeReconstruction("#type-reconstruction"),
UniversalTypes("#universal-types");
companion object {
fun fromString(extension: String): StellaExtension {
return entries.firstOrNull { it.extensionName == extension } ?: error("can't find extension $extension")
}
}
} | 0 | Java | 0 | 0 | 17e95553f3780baaaddd7e6cb50981d61bd9029f | 1,855 | stella-type-checker | MIT License |
normalized-cache-incubating/src/commonTest/kotlin/com/apollographql/cache/normalized/CacheKeyResolverTest.kt | apollographql | 816,945,456 | false | null | package com.apollographql.cache.normalized
import com.apollographql.apollo.api.CompiledField
import com.apollographql.apollo.api.CompiledListType
import com.apollographql.apollo.api.Executable
import com.apollographql.apollo.api.ObjectType
import com.apollographql.apollo.exception.CacheMissException
import com.apollographql.cache.normalized.CacheKeyResolverTest.Fixtures.TEST_LIST_FIELD
import com.apollographql.cache.normalized.CacheKeyResolverTest.Fixtures.TEST_SIMPLE_FIELD
import com.apollographql.cache.normalized.api.CacheHeaders
import com.apollographql.cache.normalized.api.CacheKey
import com.apollographql.cache.normalized.api.CacheKeyResolver
import com.apollographql.cache.normalized.api.DefaultFieldKeyGenerator
import com.apollographql.cache.normalized.api.ResolverContext
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.fail
class CacheKeyResolverTest {
private lateinit var subject: CacheKeyResolver
lateinit var onCacheKeyForField: (context: ResolverContext) -> CacheKey?
lateinit var onListOfCacheKeysForField: (context: ResolverContext) -> List<CacheKey?>?
@BeforeTest
fun setup() {
subject = FakeCacheKeyResolver()
onCacheKeyForField = { _ ->
fail("Unexpected call to cacheKeyForField")
}
onListOfCacheKeysForField = { _ ->
fail("Unexpected call to listOfCacheKeysForField")
}
}
private fun resolverContext(field: CompiledField) =
ResolverContext(field, Executable.Variables(emptyMap()), emptyMap(), "", "", CacheHeaders(emptyMap()), DefaultFieldKeyGenerator)
@Test
fun verify_cacheKeyForField_called_for_named_composite_field() {
val expectedKey = CacheKey("test")
val fields = mutableListOf<CompiledField>()
onCacheKeyForField = { context: ResolverContext ->
fields += context.field
expectedKey
}
val returned = subject.resolveField(resolverContext(TEST_SIMPLE_FIELD))
assertEquals(returned, expectedKey)
assertEquals(fields[0], TEST_SIMPLE_FIELD)
}
@Test
fun listOfCacheKeysForField_called_for_list_field() {
val expectedKeys = listOf(CacheKey("test"))
val fields = mutableListOf<CompiledField>()
onListOfCacheKeysForField = { context: ResolverContext ->
fields += context.field
expectedKeys
}
val returned = subject.resolveField(resolverContext(TEST_LIST_FIELD))
assertEquals(returned, expectedKeys)
assertEquals(fields[0], TEST_LIST_FIELD)
}
@Test
fun super_called_for_null_return_values() {
onCacheKeyForField = { _ -> null }
onListOfCacheKeysForField = { _ -> null }
// The best way to ensure that super was called is to check for a cache miss exception from CacheResolver()
assertFailsWith<CacheMissException> {
subject.resolveField(resolverContext(TEST_SIMPLE_FIELD))
}
assertFailsWith<CacheMissException> {
subject.resolveField(resolverContext(TEST_LIST_FIELD))
}
}
inner class FakeCacheKeyResolver : CacheKeyResolver() {
override fun cacheKeyForField(context: ResolverContext): CacheKey? {
return onCacheKeyForField(context)
}
override fun listOfCacheKeysForField(context: ResolverContext): List<CacheKey?>? {
return onListOfCacheKeysForField(context)
}
}
object Fixtures {
private val TEST_TYPE = ObjectType.Builder(name = "Test").keyFields(keyFields = listOf("id")).build()
val TEST_SIMPLE_FIELD = CompiledField.Builder(name = "test", type = TEST_TYPE).build()
val TEST_LIST_FIELD = CompiledField.Builder(name = "testList", type = CompiledListType(ofType = TEST_TYPE)).build()
}
}
| 6 | null | 1 | 5 | 2c60d90a19a14a80158ad0d5a65742aea0c8716e | 3,667 | apollo-kotlin-normalized-cache-incubating | MIT License |
app/src/main/java/com/aryasurya/siagacorona/main/model/CovidCaseModel.kt | aryasurya21 | 292,035,636 | false | null | package com.aryasurya.siagacorona.main.model
import com.google.gson.annotations.SerializedName
data class CovidCaseModel(
@SerializedName("positif") val totalCases: String = "",
@SerializedName("dirawat") val positiveCase: String = "",
@SerializedName("sembuh") val recoveredCase: String = "",
@SerializedName("meninggal") val deathCase: String = ""
) | 0 | Kotlin | 0 | 0 | 58b8442f1f2265d13521265c86e34b6fb9f335af | 369 | siagacorona | MIT License |
app/src/main/java/com/ancientlore/stickies/menu/popup/PopupMenu.kt | ancientloregames | 146,256,675 | false | null | package com.ancientlore.stickies.menu.popup
import android.content.Context
import android.support.annotation.UiThread
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import com.ancientlore.stickies.databinding.PopupMenuBinding
import com.ancientlore.stickies.menu.MenuItem
class PopupMenu(context: Context) {
private val window = PopupWindow(context)
private val viewModel = PopupMenuViewModel(context)
init {
val binding = PopupMenuBinding.inflate(LayoutInflater.from(context), null)
binding.viewModel = viewModel
setupWindow(binding.root)
}
@UiThread
fun setItems(items: List<MenuItem>) = viewModel.setAdapterItems(items)
@UiThread
fun show(anchor: View) {
if (isNotShowing())
window.showAsDropDown(anchor)
}
@UiThread
fun hide() = window.dismiss()
fun observeItemClicked() = viewModel.observeItemClicked()
private fun setupWindow(view: View) {
window.apply {
width = ViewGroup.LayoutParams.WRAP_CONTENT
height = ViewGroup.LayoutParams.WRAP_CONTENT
contentView = view
isFocusable = true
isOutsideTouchable = true
}
}
private fun isShowing() = window.isShowing
private fun isNotShowing() = !isShowing()
} | 0 | Kotlin | 0 | 1 | 8ff1440de44294c185c83763feaed2bfabdfdb92 | 1,238 | Stickies | MIT License |
code/libraries/network/src/main/java/com/benhurqs/network/data/ChallengeAPI.kt | Benhurqs | 281,213,359 | true | {"Kotlin": 58096} | package com.benhurqs.network.data
import com.benhurqs.network.entities.*
import io.reactivex.Observable
import okhttp3.ResponseBody
import retrofit2.http.*
interface ChallengeAPI {
@GET("banners")
fun banners(): Observable<List<Banner>?>
@GET("spotlight")
fun spotlight(): Observable<List<Spotlight>?>
@GET("games/{game_id}")
fun detail(@Path("game_id") gameID: Int?): Observable<Spotlight?>
@GET("games/search")
fun search(@Query("term") query: String?): Observable<List<Suggestion>?>
@POST("checkout")
fun checkout(): Observable<ResponseBody?>
} | 0 | Kotlin | 0 | 0 | 7b1e1023ff748c20cfbfeba14d407f970cad7072 | 595 | mobile-android-challenge | MIT License |
app/src/main/java/eu/kanade/tachiyomi/ui/download/anime/DownloadHolder.kt | Hibecode | 373,579,242 | true | {"Kotlin": 2758456} | package eu.kanade.tachiyomi.ui.download.anime
import android.view.View
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.download.model.AnimeDownload
import eu.kanade.tachiyomi.databinding.DownloadItemBinding
import eu.kanade.tachiyomi.util.view.popupMenu
/**
* Class used to hold the data of a download.
* All the elements from the layout file "download_item" are available in this class.
*
* @param view the inflated view for this holder.
* @constructor creates a new download holder.
*/
class DownloadHolder(private val view: View, val adapter: DownloadAdapter) :
FlexibleViewHolder(view, adapter) {
private val binding = DownloadItemBinding.bind(view)
init {
setDragHandleView(binding.reorder)
binding.menu.setOnClickListener { it.post { showPopupMenu(it) } }
}
private lateinit var download: AnimeDownload
/**
* Binds this holder with the given category.
*
* @param category The category to bind.
*/
fun bind(download: AnimeDownload) {
this.download = download
// Update the chapter name.
binding.chapterTitle.text = download.episode.name
// Update the manga title
binding.mangaFullTitle.text = download.anime.title
// Update the manga source
binding.mangaSource.text = download.source.name
// Update the progress bar and the number of downloaded pages
val video = download.video
if (video == null) {
binding.downloadProgress.progress = 0
binding.downloadProgress.max = 1
binding.downloadProgressText.text = ""
} else {
binding.downloadProgress.max = 100
notifyProgress()
notifyDownloadedPages()
}
}
/**
* Updates the progress bar of the download.
*/
fun notifyProgress() {
val pages = download.video ?: return
if (binding.downloadProgress.max == 1) {
binding.downloadProgress.max = 100
}
binding.downloadProgress.progress = download.totalProgress
}
/**
* Updates the text field of the number of downloaded pages.
*/
fun notifyDownloadedPages() {
binding.downloadProgressText.text = "${download.progress}%"
}
override fun onItemReleased(position: Int) {
super.onItemReleased(position)
adapter.downloadItemListener.onItemReleased(position)
}
private fun showPopupMenu(view: View) {
view.popupMenu(
menuRes = R.menu.download_single,
initMenu = {
findItem(R.id.move_to_top).isVisible = bindingAdapterPosition != 0
findItem(R.id.move_to_bottom).isVisible =
bindingAdapterPosition != adapter.itemCount - 1
},
onMenuItemClick = {
adapter.downloadItemListener.onMenuItemClick(bindingAdapterPosition, this)
}
)
}
}
| 0 | null | 0 | 0 | 46efb3461e3469dd3fe0ad5690588dd7d3cc6982 | 2,999 | tachiyomi-mi | Apache License 2.0 |
core/src/main/kotlin/gropius/dto/input/user/permission/UpdateBasePermissionInput.kt | ccims | 487,996,394 | false | {"Kotlin": 1064233, "TypeScript": 442476, "MDX": 61402, "JavaScript": 25165, "HTML": 17174, "CSS": 4796, "Shell": 2363} | package gropius.dto.input.user.permission
import com.expediagroup.graphql.generator.annotations.GraphQLDescription
import com.expediagroup.graphql.generator.execution.OptionalInput
import com.expediagroup.graphql.generator.scalars.ID
import gropius.dto.input.common.UpdateNamedNodeInput
import gropius.dto.input.common.UpdateNodeInput
import gropius.dto.input.ensureDisjoint
import gropius.dto.input.ifPresent
import gropius.model.user.permission.BasePermission
import kotlin.properties.Delegates
/**
* Fragment for update mutation inputs for classes extending [BasePermission]
*/
abstract class UpdateBasePermissionInput : UpdateNamedNodeInput() {
@GraphQLDescription("The new value for allUsers")
var allUsers: OptionalInput<Boolean> by Delegates.notNull()
@GraphQLDescription("Ids of affected users to add")
var addedUsers: OptionalInput<List<ID>> by Delegates.notNull()
@GraphQLDescription("Ids of affected users to remove")
var removedUsers: OptionalInput<List<ID>> by Delegates.notNull()
/**
* Entries to add, must be disjoint with [removedEntries]
*/
abstract val addedEntries: OptionalInput<List<String>>
/**
* Entries to remove, must be disjoint with [addedEntries]
*/
abstract val removedEntries: OptionalInput<List<String>>
override fun validate() {
super.validate()
name.ifPresent {
if (it.isBlank()) {
throw IllegalArgumentException("If name is defined, it must not be blank")
}
}
::addedEntries ensureDisjoint ::removedEntries
::addedUsers ensureDisjoint ::removedUsers
}
} | 6 | Kotlin | 1 | 0 | 80f2f32af490afb818245f0c30cc9afcb40e8817 | 1,646 | gropius-backend | MIT License |
app/src/dev/java/com/gggames/hourglass/core/di/UserModule.kt | giladgotman | 252,945,764 | false | null | package com.gggames.hourglass.core.di
import com.gggames.hourglass.features.user.data.UserDataSource
import com.gggames.hourglass.features.user.data.UserRepository
import com.gggames.hourglass.features.user.data.UserRepositoryImpl
import com.gggames.hourglass.features.user.data.remote.UserDataSourceFake
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class UserModule {
@Provides
@Singleton
fun provideUserRepository(
repository: UserRepositoryImpl
): UserRepository = repository
@Provides
@Singleton
fun provideUserDataSource(
dataSource: UserDataSourceFake
): UserDataSource = dataSource
}
| 25 | Kotlin | 0 | 0 | 0f0fa11fbe1131387148e4d6d1b7d85c23d6e5f0 | 680 | celebs | MIT License |
examples/src/tl/ton/engine/validator/EngineValidatorOverlayStatsNode.kt | andreypfau | 719,064,910 | false | {"Kotlin": 62259} | // This file is generated by TLGenerator.kt
// Do not edit manually!
package tl.ton.engine.validator
import io.github.andreypfau.tl.serialization.Base64ByteStringSerializer
import io.github.andreypfau.tl.serialization.TLCombinatorId
import io.github.andreypfau.tl.serialization.TLFixedSize
import kotlin.jvm.JvmName
import kotlinx.io.bytestring.ByteString
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("engine.validator.overlayStatsNode")
@TLCombinatorId(0xF97220D9)
public data class EngineValidatorOverlayStatsNode(
@SerialName("adnl_id")
@TLFixedSize(value = 32)
@get:JvmName("adnlId")
public val adnlId: @Serializable(Base64ByteStringSerializer::class) ByteString,
@SerialName("ip_addr")
@get:JvmName("ipAddr")
public val ipAddr: String,
@SerialName("bdcst_errors")
@get:JvmName("bdcstErrors")
public val bdcstErrors: Int,
@SerialName("fec_bdcst_errors")
@get:JvmName("fecBdcstErrors")
public val fecBdcstErrors: Int,
@SerialName("last_in_query")
@get:JvmName("lastInQuery")
public val lastInQuery: Int,
@SerialName("last_out_query")
@get:JvmName("lastOutQuery")
public val lastOutQuery: Int,
@SerialName("t_out_bytes")
@get:JvmName("tOutBytes")
public val tOutBytes: Int,
@SerialName("t_in_bytes")
@get:JvmName("tInBytes")
public val tInBytes: Int,
@SerialName("t_out_pckts")
@get:JvmName("tOutPckts")
public val tOutPckts: Int,
@SerialName("t_in_pckts")
@get:JvmName("tInPckts")
public val tInPckts: Int,
) {
public companion object
}
| 0 | Kotlin | 0 | 1 | 11f05ad1f977235e3e360cd6f6ada6f26993208e | 1,633 | tl-kotlin | MIT License |
projects/core/src/main/kotlin/site/siredvin/peripheralium/api/config/IOperationAbilityConfig.kt | SirEdvin | 489,457,802 | false | null | package site.siredvin.peripheralium.api.config
interface IOperationAbilityConfig {
val isInitialCooldownEnabled: Boolean
val initialCooldownSensetiveLevel: Int
val cooldownTresholdLevel: Int
}
| 1 | Kotlin | 1 | 2 | 790d37b05fb08164364da37ddb14993e07fd938d | 206 | Peripheralium | MIT License |
java/src/org/futo/inputmethod/v2keyboard/MoreKeysBuilder.kt | futo-org | 797,372,264 | false | {"C++": 10372086, "Java": 4197663, "C": 1116570, "Kotlin": 1018120, "Makefile": 20332, "CMake": 13029, "CSS": 9800, "Shell": 6116, "Python": 5637, "HTML": 2651, "Dockerfile": 926} | package org.futo.inputmethod.v2keyboard
import org.futo.inputmethod.keyboard.KeyConsts
import org.futo.inputmethod.keyboard.internal.KeyboardLayoutKind
import org.futo.inputmethod.keyboard.internal.KeyboardParams
import org.futo.inputmethod.keyboard.internal.MoreKeySpec
import org.futo.inputmethod.latin.settings.LongPressKey
typealias MoreKeys = List<String>
val QwertySymbols = listOf(
"qwertyuiop".toList(),
"asdfghjkl".toList() + listOf("r2_e1"),
"zxcvbnm".toList()
)
private fun getNumForCoordinate(keyCoordinate: KeyCoordinate): String {
if(keyCoordinate.element.kind != KeyboardLayoutKind.Alphabet) return ""
if(keyCoordinate.regularRow == 0) {
val colOffset = (keyCoordinate.measurement.numColumnsByRow[keyCoordinate.regularRow] - 10) / 2
val centeredCol = keyCoordinate.regularColumn - colOffset
if(centeredCol == 9) {
return "!text/keyspec_symbols_0,!text/additional_morekeys_symbols_0"
} else if(centeredCol in 0 until 9) {
return "!text/keyspec_symbols_${centeredCol + 1},!text/additional_morekeys_symbols_${centeredCol + 1}"
} else {
return ""
}
}
return ""
}
private fun symsForCoord(keyCoordinate: KeyCoordinate): String {
if(keyCoordinate.element.kind != KeyboardLayoutKind.Alphabet) return ""
val row = QwertySymbols.getOrNull(keyCoordinate.regularRow) ?: return ""
val colOffset = (keyCoordinate.measurement.numColumnsByRow[keyCoordinate.regularRow] - row.size) / 2
val centeredCol = keyCoordinate.regularColumn - colOffset.coerceAtLeast(0)
if(centeredCol < 0) return ""
val letter = row.getOrNull(centeredCol)
return if(letter != null) {
"!text/qwertysyms_$letter"
} else {
""
}
}
private fun actionForCoord(keyCoordinate: KeyCoordinate): String {
if(keyCoordinate.element.kind != KeyboardLayoutKind.Alphabet) return ""
val row = QwertySymbols.getOrNull(keyCoordinate.regularRow)
val letter = row?.getOrNull(keyCoordinate.regularColumn)
return if(letter != null) {
"!text/actions_$letter"
} else {
""
}
}
data class BuiltMoreKeys(
val specs: List<MoreKeySpec>,
val flags: Int
)
data class MoreKeysBuilder(
val code: Int,
val mode: MoreKeyMode,
val coordinate: KeyCoordinate,
val row: Row,
val keyboard: Keyboard,
val params: KeyboardParams,
val moreKeys: MoreKeys = listOf()
) {
private fun insertMoreKeys(resolvedMoreKeys: MoreKeys): MoreKeysBuilder {
if(resolvedMoreKeys.isEmpty()) return this
val idxOfMarker = moreKeys.indexOf("%")
val newMoreKeys = if(idxOfMarker == -1) {
moreKeys + resolvedMoreKeys
} else {
moreKeys.subList(0, idxOfMarker) + resolvedMoreKeys + moreKeys.subList(idxOfMarker, moreKeys.size)
}
return this.copy(moreKeys = newMoreKeys)
}
fun insertMoreKeys(moreKeysToInsert: String): MoreKeysBuilder {
val resolved = MoreKeySpec.splitKeySpecs(params.mTextsSet.resolveTextReference(moreKeysToInsert))?.toList()
return resolved?.let { insertMoreKeys(it) } ?: this
}
private val isNumberRowActive = keyboard.numberRowMode.isActive(params.mId.mNumberRow)
private fun canAddMoreKey(key: LongPressKey): Boolean =
row.isLetterRow && when(key) {
LongPressKey.QuickActions -> mode.autoSymFromCoord
// Numbers added to top row requires the number row being inactive
LongPressKey.Numbers -> (mode.autoNumFromCoord && !isNumberRowActive)
// Symbols for top row requires number row being active (it replaces the number long-press keys)
LongPressKey.Symbols -> (mode.autoSymFromCoord && (coordinate.regularRow > 0 || isNumberRowActive))
// Language keys require a-z code
LongPressKey.LanguageKeys, LongPressKey.MiscLetters -> (row.isLetterRow && code >= 'a'.code && code <= 'z'.code)
}
private fun moreKey(key: LongPressKey): String =
when(key) {
LongPressKey.Numbers -> getNumForCoordinate(coordinate)
LongPressKey.Symbols -> symsForCoord(coordinate)
LongPressKey.QuickActions -> actionForCoord(coordinate)
LongPressKey.LanguageKeys -> "!text/morekeys_${code.toChar()}"
LongPressKey.MiscLetters -> "!text/morekeys_misc_${code.toChar()}"
}
fun insertMoreKeys(key: LongPressKey): MoreKeysBuilder {
if(!canAddMoreKey(key)) return this
return insertMoreKeys(moreKey(key))
}
fun build(shifted: Boolean): BuiltMoreKeys {
return BuiltMoreKeys(
specs = filterMoreKeysFlags(moreKeys).filter { it != "%" }.map {
MoreKeySpec(it, shifted, params.mId.locale)
},
flags = computeMoreKeysFlags(moreKeys.toTypedArray(), params)
)
}
}
private fun computeMoreKeysFlags(moreKeys: Array<String>, params: KeyboardParams): Int {
// Get maximum column order number and set a relevant mode value.
var moreKeysColumnAndFlags =
(KeyConsts.MORE_KEYS_MODE_MAX_COLUMN_WITH_AUTO_ORDER
or params.mMaxMoreKeysKeyboardColumn)
var value: Int
if ((MoreKeySpec.getIntValue(
moreKeys,
KeyConsts.MORE_KEYS_AUTO_COLUMN_ORDER,
-1
).also {
value = it
}) > 0
) {
// Override with fixed column order number and set a relevant mode value.
moreKeysColumnAndFlags =
(KeyConsts.MORE_KEYS_MODE_FIXED_COLUMN_WITH_AUTO_ORDER
or (value and KeyConsts.MORE_KEYS_COLUMN_NUMBER_MASK))
}
if ((MoreKeySpec.getIntValue(
moreKeys,
KeyConsts.MORE_KEYS_FIXED_COLUMN_ORDER,
-1
).also {
value = it
}) > 0
) {
// Override with fixed column order number and set a relevant mode value.
moreKeysColumnAndFlags =
(KeyConsts.MORE_KEYS_MODE_FIXED_COLUMN_WITH_FIXED_ORDER
or (value and KeyConsts.MORE_KEYS_COLUMN_NUMBER_MASK))
}
if (MoreKeySpec.getBooleanValue(
moreKeys,
KeyConsts.MORE_KEYS_HAS_LABELS
)
) {
moreKeysColumnAndFlags =
moreKeysColumnAndFlags or KeyConsts.MORE_KEYS_FLAGS_HAS_LABELS
}
if (MoreKeySpec.getBooleanValue(
moreKeys,
KeyConsts.MORE_KEYS_NEEDS_DIVIDERS
)
) {
moreKeysColumnAndFlags =
moreKeysColumnAndFlags or KeyConsts.MORE_KEYS_FLAGS_NEEDS_DIVIDERS
}
if (MoreKeySpec.getBooleanValue(
moreKeys,
KeyConsts.MORE_KEYS_NO_PANEL_AUTO_MORE_KEY
)
) {
moreKeysColumnAndFlags =
moreKeysColumnAndFlags or KeyConsts.MORE_KEYS_FLAGS_NO_PANEL_AUTO_MORE_KEY
}
return moreKeysColumnAndFlags
}
private fun filterMoreKeysFlags(moreKeys: List<String>): List<String> =
moreKeys.filter {
!it.startsWith(KeyConsts.MORE_KEYS_AUTO_COLUMN_ORDER) &&
!it.startsWith(KeyConsts.MORE_KEYS_FIXED_COLUMN_ORDER) &&
!it.startsWith(KeyConsts.MORE_KEYS_HAS_LABELS) &&
!it.startsWith(KeyConsts.MORE_KEYS_NEEDS_DIVIDERS) &&
!it.startsWith(KeyConsts.MORE_KEYS_NO_PANEL_AUTO_MORE_KEY)
}
| 363 | C++ | 22 | 629 | c6e8336e763729df1566b42cb8ea982200500eba | 7,363 | android-keyboard | RSA Message-Digest License |
app/src/main/java/scimone/diafit/features/home/presentation/components/ChartComponentCGM.kt | scimone | 821,835,868 | false | {"Kotlin": 56928} | package scimone.diafit.components
import android.text.Layout
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.patrykandpatrick.vico.compose.cartesian.CartesianChartHost
import com.patrykandpatrick.vico.compose.cartesian.axis.rememberAxisLabelComponent
import com.patrykandpatrick.vico.compose.cartesian.axis.rememberBottomAxis
import com.patrykandpatrick.vico.compose.cartesian.axis.rememberStartAxis
import com.patrykandpatrick.vico.compose.cartesian.layer.rememberLine
import com.patrykandpatrick.vico.compose.cartesian.layer.rememberLineCartesianLayer
import com.patrykandpatrick.vico.compose.cartesian.layer.rememberPoint
import com.patrykandpatrick.vico.compose.cartesian.marker.rememberDefaultCartesianMarker
import com.patrykandpatrick.vico.compose.cartesian.rememberCartesianChart
import com.patrykandpatrick.vico.compose.cartesian.rememberVicoScrollState
import com.patrykandpatrick.vico.compose.cartesian.rememberVicoZoomState
import com.patrykandpatrick.vico.compose.common.fill
import com.patrykandpatrick.vico.core.cartesian.Scroll
import com.patrykandpatrick.vico.core.cartesian.Zoom
import com.patrykandpatrick.vico.core.cartesian.axis.Axis.Position
import com.patrykandpatrick.vico.core.cartesian.axis.VerticalAxis
import com.patrykandpatrick.vico.core.cartesian.data.AxisValueOverrider
import com.patrykandpatrick.vico.core.cartesian.data.CartesianChartModelProducer
import com.patrykandpatrick.vico.core.cartesian.data.lineSeries
import com.patrykandpatrick.vico.core.cartesian.layer.LineCartesianLayer
import com.patrykandpatrick.vico.core.cartesian.marker.DefaultCartesianMarker
import com.patrykandpatrick.vico.core.cartesian.marker.DefaultCartesianMarkerValueFormatter
import com.patrykandpatrick.vico.core.common.component.LineComponent
import com.patrykandpatrick.vico.core.common.component.ShapeComponent
import com.patrykandpatrick.vico.core.common.component.TextComponent
import com.patrykandpatrick.vico.core.common.shape.Shape
import scimone.diafit.core.presentation.model.CGMChartData
import scimone.diafit.features.home.presentation.components.CustomAxisItemPlacer
import scimone.diafit.ui.theme.aboveRange
import scimone.diafit.ui.theme.belowRange
import scimone.diafit.ui.theme.inRange
import java.text.DecimalFormat
import java.util.Calendar
@Composable
fun ChartComponentCGM(values: List<CGMChartData>) {
val modelProducer = remember { CartesianChartModelProducer.build() }
val currentTime = System.currentTimeMillis()
val oneDayAgo = currentTime - 24 * 60 * 60 * 1000 // 24 hours in milliseconds
val filteredValues =
values.filter { it.timeFloat >= oneDayAgo && it.timeFloat <= currentTime }
LaunchedEffect(filteredValues) {
if (filteredValues.isNotEmpty()) {
val belowRangePoints = filteredValues.filter { it.value < 70 }
val inRangePoints = filteredValues.filter { it.value in 70..180 }
val aboveRangePoints = filteredValues.filter { it.value > 180 }
modelProducer.runTransaction {
lineSeries {
if (belowRangePoints.isNotEmpty()) {
series(
x = belowRangePoints.map { it.timeFloat },
y = belowRangePoints.map { it.value }
)
}
if (inRangePoints.isNotEmpty()) {
series(
x = inRangePoints.map { it.timeFloat },
y = inRangePoints.map { it.value }
)
}
if (aboveRangePoints.isNotEmpty()) {
series(
x = aboveRangePoints.map { it.timeFloat },
y = aboveRangePoints.map { it.value }
)
}
}
}
}
}
val colors = mutableListOf<Color>()
if (filteredValues.any { it.value < 70 }) colors.add(belowRange)
if (filteredValues.any { it.value in 70..180 }) colors.add(inRange)
if (filteredValues.any { it.value > 180 }) colors.add(aboveRange)
CartesianChartHost(
chart = rememberCartesianChart(
rememberLineCartesianLayer(
lineProvider = LineCartesianLayer.LineProvider.series(
lines = colors.map { color ->
rememberLine(
pointProvider = LineCartesianLayer.PointProvider.single(
rememberPoint(
component = ShapeComponent(
shape = Shape.Pill,
color = color.toArgb()
),
size = 4.dp
)
),
thickness = 0.dp,
fill = LineCartesianLayer.LineFill.single(fill = fill(Color.Transparent))
)
}
),
verticalAxisPosition = Position.Vertical.Start,
axisValueOverrider = AxisValueOverrider.fixed(
minX = oneDayAgo.toDouble(),
maxX = currentTime.toDouble()
)
),
startAxis = rememberStartAxis(
horizontalLabelPosition = VerticalAxis.HorizontalLabelPosition.Inside,
guideline = LineComponent(
color = MaterialTheme.colorScheme.onSurface.toArgb(),
thicknessDp = .5f
),
itemPlacer = remember { CustomAxisItemPlacer() }
),
bottomAxis = rememberBottomAxis(
guideline = LineComponent(
color = MaterialTheme.colorScheme.onSurface.toArgb(),
thicknessDp = .5f
),
label = rememberAxisLabelComponent(
textAlignment = Layout.Alignment.ALIGN_CENTER,
textSize = 10.sp
),
valueFormatter = { value, _, _ ->
val calendar = Calendar.getInstance().apply {
timeInMillis = value.toLong()
}
val hours = calendar.get(Calendar.HOUR_OF_DAY)
String.format("%02d", hours)
}
),
getXStep = { 3600000.0 }, // 1 hour in milliseconds
marker = rememberDefaultCartesianMarker(
label = TextComponent(
color = MaterialTheme.colorScheme.onBackground.toArgb(),
textSizeSp = 10f
),
labelPosition = DefaultCartesianMarker.LabelPosition.AbovePoint,
indicatorSize = 10.dp,
guideline = LineComponent(
color = MaterialTheme.colorScheme.onBackground.toArgb(),
thicknessDp = .5f
),
valueFormatter = DefaultCartesianMarkerValueFormatter(
decimalFormat = DecimalFormat("#.## mg/dl"),
colorCode = false
)
)
),
modelProducer = modelProducer,
zoomState = rememberVicoZoomState(zoomEnabled = true, initialZoom = Zoom.Companion.Content),
scrollState = rememberVicoScrollState(initialScroll = Scroll.Absolute.Companion.End)
)
}
| 0 | Kotlin | 0 | 0 | 3fca1f6ea5dc7de42502623949c7ad5090886fda | 7,823 | diafit-android | MIT License |
app/src/main/java/pw/phylame/github/activity/ProfileActivity.kt | phylame | 87,519,333 | false | null | package pw.phylame.github.activity
import android.os.Bundle
import com.bumptech.glide.Glide
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.android.synthetic.main.activity_profile.*
import pw.phylame.github.GitHub
import pw.phylame.github.R
import pw.phylame.support.dip
class ProfileActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
setupToolbar(toolbar, true)
setImmersive()
val size = dip(64F).toInt()
GitHub.getUser(intent.getStringExtra("username"))
.subscribe({ user ->
Glide.with(this)
.load(user.avatar)
.bitmapTransform(BlurTransformation(this, 25))
.into(banner)
Glide.with(this)
.load(user.avatar)
.override(size, size)
.into(avatar)
username.text = user.username
}, { error ->
})
}
} | 0 | Kotlin | 0 | 1 | e782545b0dec50698048d6a671336d2dd39fb376 | 1,165 | github-android | Apache License 2.0 |
platform/core/data/src/main/java/com/orogersilva/myweatherforecast/data/dto/DailyWeatherForecastDto.kt | orogersilva | 511,682,755 | false | {"Kotlin": 138896} | package com.orogersilva.myweatherforecast.data.dto
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class DailyWeatherForecastDto(
@Json(name = "latitude") val latitude: Double,
@Json(name = "longitude") val longitude: Double,
@Json(name = "generationtime_ms") val generationTimeInMs: Double,
@Json(name = "utc_offset_seconds") val utcOffsetSeconds: Int,
@Json(name = "timezone") val timezone: String,
@Json(name = "timezone_abbreviation") val timezoneAbbreviation: String,
@Json(name = "elevation") val elevation: Double,
@Json(name = "hourly_units") val hourlyUnitDto: HourlyUnitDto,
@Json(name = "hourly") val hourlyDataDto: HourlyDataDto,
@Json(name = "daily_units") val hourlyDailyUnitDto: HourlyDailyUnitDto,
@Json(name = "daily") val hourlyDailyDataDto: HourlyDailyDataDto
)
@JsonClass(generateAdapter = true)
data class HourlyUnitDto(
@Json(name = "time") val time: String,
@Json(name = "temperature_2m") val temperatureUnit: String
)
@JsonClass(generateAdapter = true)
data class HourlyDataDto(
@Json(name = "time") val time: List<String>,
@Json(name = "temperature_2m") val temperature: List<Double>
)
@JsonClass(generateAdapter = true)
data class HourlyDailyUnitDto(
@Json(name = "time") val time: String,
@Json(name = "weathercode") val weatherCode: String
)
@JsonClass(generateAdapter = true)
data class HourlyDailyDataDto(
@Json(name = "time") val time: List<String>,
@Json(name = "weathercode") val weatherCode: List<Int>
)
| 0 | Kotlin | 0 | 3 | ef3abcf66ce4ca699793c700e62cae4ecc4e47e6 | 1,579 | myweatherforecast | Apache License 2.0 |
src/main/kotlin/net/casualuhc/uhcmod/util/PerformanceUtils.kt | CasualUHC | 334,382,250 | false | null | package net.casualuhc.uhcmod.util
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.EntityType.*
import net.minecraft.world.entity.Mob
object PerformanceUtils {
private val DISABLED_ENTITIES: Set<EntityType<*>> = setOf<EntityType<*>>(PIG, COW, SQUID, BAT, GLOW_SQUID, FOX, COD, SALMON, PARROT, MOOSHROOM, HORSE, SKELETON_HORSE, CAT, MULE, DONKEY, CHICKEN, SHEEP, GOAT)
@JvmStatic
fun isEntityAIDisabled(mob: Mob): Boolean {
return DISABLED_ENTITIES.contains(mob.type)
}
} | 0 | Kotlin | 0 | 3 | 4dfc539c3cf7f261c911f45a47206f64faaa37e9 | 527 | UHC-Mod | MIT License |
jobj/src/main/java/cn/yizems/moshi/ex/jobj/MJsonObject.kt | yizems | 497,481,818 | false | {"Kotlin": 43440} | /**
* Copyright (c) 2021 yizems
*
* 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 cn.yizems.moshi.ex.jobj
import com.squareup.moshi.kotlin.jobj.TypeUtils.castToBigDecimal
import com.squareup.moshi.kotlin.jobj.TypeUtils.castToBigInteger
import com.squareup.moshi.kotlin.jobj.TypeUtils.castToBoolean
import com.squareup.moshi.kotlin.jobj.TypeUtils.castToDouble
import com.squareup.moshi.kotlin.jobj.TypeUtils.castToFloat
import com.squareup.moshi.kotlin.jobj.TypeUtils.castToInt
import com.squareup.moshi.kotlin.jobj.TypeUtils.castToLong
import com.squareup.moshi.kotlin.jobj.TypeUtils.wrapValue
import java.io.Serializable
import java.math.BigDecimal
import java.math.BigInteger
typealias JsonObject = MJsonObject
class MJsonObject : Serializable {
private var innerMap: MutableMap<String, Any?>
constructor(initialCapacity: Int = 16, ordered: Boolean = false) {
innerMap = if (ordered) {
LinkedHashMap(initialCapacity)
} else {
HashMap(initialCapacity)
}
}
constructor(map: Map<String, Any?>) {
this.innerMap = HashMap<String, Any?>(16)
map.forEach { (t, u) ->
innerMap[t] = wrapValue(u)
}
}
fun size(): Int {
return innerMap.size
}
fun isEmpty(): Boolean {
return innerMap.isEmpty()
}
fun containsKey(key: Any?): Boolean {
return innerMap.containsKey(key)
}
fun containsValue(value: Any?): Boolean {
return innerMap.containsValue(value)
}
operator fun get(key: Any?): Any? {
return innerMap[key]
}
operator fun set(key: String, value: Any?): Any? {
return put(key, value)
}
fun getBoolean(key: String): Boolean? {
val value = get(key) ?: return null
return castToBoolean(value)
}
fun getBooleanValue(key: String): Boolean {
val value = getBoolean(key)
return value ?: false
}
fun getInteger(key: String?): Int? {
val value = get(key)
return castToInt(value)
}
fun getIntValue(key: String?): Int {
val value = get(key)
return castToInt(value) ?: return 0
}
fun getLong(key: String?): Long? {
val value = get(key)
return castToLong(value)
}
fun getLongValue(key: String?): Long {
val value = get(key)
return castToLong(value) ?: return 0L
}
fun getFloat(key: String?): Float? {
val value = get(key)
return castToFloat(value)
}
fun getFloatValue(key: String?): Float {
val value = get(key)
return castToFloat(value) ?: return 0f
}
fun getDouble(key: String?): Double? {
val value = get(key)
return castToDouble(value)
}
fun getDoubleValue(key: String?): Double {
val value = get(key)
return castToDouble(value) ?: return 0.0
}
fun getBigDecimal(key: String?): BigDecimal? {
val value = get(key)
return castToBigDecimal(value)
}
fun getBigInteger(key: String?): BigInteger? {
val value = get(key)
return castToBigInteger(value)
}
fun getString(key: String?): String? {
val value = get(key) ?: return null
return value.toString()
}
fun put(key: String, value: Any?): Any? {
return innerMap.put(key, wrapValue(value))
}
fun putAll(m: Map<out String, Any?>) {
m.forEach { (s, u) ->
innerMap[s] = wrapValue(u)
}
}
fun clear() {
innerMap.clear()
}
fun remove(key: Any?): Any? {
return innerMap.remove(key)
}
fun keySet(): Set<String> {
return innerMap.keys
}
fun values(): Collection<Any?> {
return innerMap.values
}
fun entrySet(): Set<Map.Entry<String, Any?>?> {
return innerMap.entries
}
fun clone(): Any {
return MJsonObject(LinkedHashMap(innerMap))
}
override fun equals(other: Any?): Boolean {
return innerMap == other
}
override fun hashCode(): Int {
return innerMap.hashCode()
}
fun getInnerMap(): Map<String, Any?> {
return innerMap
}
fun getMJsonObject(key: String): MJsonObject? {
return innerMap[key] as? MJsonObject
}
fun getMJsonArray(key: String): MJsonArray? {
return innerMap[key] as? MJsonArray
}
}
| 0 | Kotlin | 0 | 0 | 6f21dbb44c9683181f695c6e370f9ad63d1501f6 | 4,912 | MoshiEx | MIT License |
shared/feature/images/src/androidMain/kotlin/ly/david/musicsearch/shared/feature/images/PreviewCoverArtsUi.kt | lydavid | 458,021,427 | false | {"Kotlin": 1934721, "HTML": 1854067, "Swift": 4205, "Python": 3527, "Shell": 1594, "Ruby": 955} | package ly.david.musicsearch.shared.feature.images
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.PreviewLightDark
import kotlinx.collections.immutable.persistentListOf
import ly.david.musicsearch.shared.domain.image.ImageUrls
import ly.david.musicsearch.test.image.InitializeFakeImageLoader
import ly.david.musicsearch.ui.core.preview.DefaultPreviews
import ly.david.musicsearch.ui.core.theme.PreviewTheme
@PreviewLightDark
@Composable
internal fun PreviewCoverArtsUiCompact() {
InitializeFakeImageLoader()
PreviewTheme {
Surface {
CoverArtsUi(
isCompact = true,
imageUrlsList = persistentListOf(
ImageUrls(
largeUrl = "https://www.example.com/image.jpg",
),
ImageUrls(
largeUrl = "https://www.example.com/image.jpg",
),
),
)
}
}
}
@DefaultPreviews
@Composable
internal fun PreviewCoverArtsUiNonCompact() {
InitializeFakeImageLoader()
PreviewTheme {
Surface {
CoverArtsUi(
imageUrlsList = persistentListOf(
ImageUrls(
largeUrl = "https://www.example.com/image.jpg",
),
ImageUrls(
largeUrl = "https://www.example.com/image.jpg",
),
),
)
}
}
}
| 115 | Kotlin | 0 | 45 | 3ab7303fca3a33f1a64e88ef3b411198fb25477c | 1,567 | MusicSearch | Apache License 2.0 |
components/project/impl/src/commonMain/kotlin/ru/kyamshanov/mission/components/project/impl/edit/data/api/ProjectApiImpl.kt | KYamshanov | 656,042,097 | false | {"Kotlin": 424932, "Batchfile": 2703, "HTML": 199} | package ru.kyamshanov.mission.components.project.impl.edit.data.api
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.contentType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import ru.kyamshanov.mission.components.project.impl.edit.data.model.AddParticipantRqDto
import ru.kyamshanov.mission.components.project.impl.edit.data.model.EditProjectRqDto
import ru.kyamshanov.mission.components.project.impl.edit.data.model.EditTaskSetRqDto
import ru.kyamshanov.mission.components.project.impl.edit.data.model.GetTeamRsDto
import ru.kyamshanov.mission.components.project.impl.edit.data.model.ProjectInfoDto
import ru.kyamshanov.mission.components.project.impl.edit.data.model.RemoveParticipantRqDto
import ru.kyamshanov.mission.components.project.impl.edit.data.model.SetRoleRqDto
import ru.kyamshanov.mission.core.network.api.RequestFactory
import ru.kyamshanov.mission.core.network.api.utils.retrieveBody
internal class ProjectApiImpl(
private val requestFactory: RequestFactory,
) : ProjectApi {
override suspend fun getProject(projectId: String): ProjectInfoDto =
withContext(Dispatchers.Default) {
requestFactory.get("/project/private/find?id=${projectId}") {
contentType(ContentType.Application.Json)
}.retrieveBody()
}
override suspend fun getTeam(projectId: String): GetTeamRsDto =
withContext(Dispatchers.Default) {
requestFactory.get("/project/private/team?project=${projectId}") {
contentType(ContentType.Application.Json)
}.retrieveBody()
}
override suspend fun getManagedTeam(projectId: String): GetTeamRsDto =
withContext(Dispatchers.Default) {
requestFactory.get("/project/manager/team?project=${projectId}") {
contentType(ContentType.Application.Json)
}.retrieveBody()
}
override suspend fun editProject(body: EditProjectRqDto): Unit =
withContext(Dispatchers.Default) {
requestFactory.post("/project/manager/project/edit") {
contentType(ContentType.Application.Json)
setBody(body)
}.retrieveBody()
}
override suspend fun editTasks(body: EditTaskSetRqDto): Unit =
withContext(Dispatchers.Default) {
requestFactory.post("/project/manager/task/edit/set") {
contentType(ContentType.Application.Json)
setBody(body)
}.retrieveBody()
}
override suspend fun setRole(body: SetRoleRqDto): Unit = withContext(Dispatchers.Default) {
requestFactory.post("/project/manager/role") {
contentType(ContentType.Application.Json)
setBody(body)
}.retrieveBody()
}
override suspend fun addParticipant(body: AddParticipantRqDto): Unit =
withContext(Dispatchers.Default) {
requestFactory.post("/project/manager/participant/add") {
contentType(ContentType.Application.Json)
setBody(body)
}.retrieveBody()
}
override suspend fun removeParticipant(body: RemoveParticipantRqDto): Unit =
withContext(Dispatchers.Default) {
requestFactory.post("/project/manager/participant/remove") {
contentType(ContentType.Application.Json)
setBody(body)
}.retrieveBody()
}
} | 6 | Kotlin | 0 | 1 | 19ba9237ba59a1f52ca54b948647144d9d450902 | 3,460 | Mission-app | Apache License 2.0 |
app/src/main/java/com/sawyer/kotlinmvvmwanandroid/ui/common/CollectRepository.kt | sawyer-lee | 647,531,461 | false | null | package com.sawyer.kotlinmvvmwanandroid.ui.common
import com.sawyer.kotlinmvvmwanandroid.model.api.RetrofitClient
import javax.inject.Inject
class CollectRepository @Inject constructor() {
suspend fun collect(id:Long)=RetrofitClient.apiService.collect(id).apiData()
suspend fun unCollect(id:Long)=RetrofitClient.apiService.unCollect(id).apiData()
} | 0 | Kotlin | 0 | 0 | f62bd7cc379db88df78a4580f471a3e55d802fe4 | 361 | KotlinMvvmWanAndroid | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/SensorFire.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.SensorFire: ImageVector
get() {
if (_sensorFire != null) {
return _sensorFire!!
}
_sensorFire = Builder(name = "SensorFire", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.0f, 9.195f)
curveToRelative(-0.356f, -0.318f, -0.92f, -0.237f, -1.163f, 0.174f)
curveToRelative(-1.369f, 2.316f, -1.055f, 5.632f, -2.282f, 5.632f)
curveToRelative(-0.581f, 0.0f, -0.49f, -1.004f, -0.764f, -1.624f)
curveToRelative(-0.194f, -0.439f, -0.784f, -0.507f, -1.086f, -0.133f)
curveToRelative(-1.157f, 1.432f, -2.271f, 3.953f, -1.246f, 6.416f)
curveToRelative(1.097f, 2.636f, 3.575f, 4.497f, 6.425f, 4.33f)
curveToRelative(3.41f, -0.199f, 6.115f, -3.028f, 6.115f, -6.489f)
curveToRelative(0.0f, -3.417f, -3.789f, -6.333f, -6.0f, -8.305f)
close()
moveTo(19.402f, 21.123f)
curveToRelative(-1.003f, 1.17f, -2.802f, 1.17f, -3.805f, 0.0f)
curveToRelative(-0.867f, -1.011f, -0.699f, -2.557f, 0.243f, -3.499f)
lineToRelative(1.103f, -1.103f)
curveToRelative(0.307f, -0.307f, 0.805f, -0.307f, 1.112f, 0.0f)
lineToRelative(1.103f, 1.103f)
curveToRelative(0.942f, 0.942f, 1.11f, 2.487f, 0.243f, 3.499f)
close()
moveTo(9.613f, 20.428f)
curveToRelative(-1.324f, -3.181f, -0.075f, -6.446f, 1.536f, -8.441f)
curveToRelative(0.587f, -0.726f, 1.483f, -1.087f, 2.412f, -0.962f)
curveToRelative(0.161f, 0.021f, 0.317f, 0.057f, 0.469f, 0.105f)
curveToRelative(0.229f, -0.898f, 0.548f, -1.869f, 1.085f, -2.778f)
curveToRelative(0.421f, -0.711f, 1.131f, -1.191f, 1.948f, -1.318f)
curveToRelative(0.815f, -0.127f, 1.647f, 0.116f, 2.268f, 0.669f)
horizontalLineToRelative(0.0f)
curveToRelative(0.221f, 0.197f, 0.458f, 0.404f, 0.705f, 0.619f)
curveToRelative(1.272f, 1.11f, 2.781f, 2.428f, 3.964f, 3.973f)
lineTo(24.0f, 5.0f)
curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f)
lineTo(5.0f, 0.0f)
curveTo(2.243f, 0.0f, 0.0f, 2.243f, 0.0f, 5.0f)
verticalLineToRelative(14.0f)
curveToRelative(0.0f, 2.757f, 2.243f, 5.0f, 5.0f, 5.0f)
horizontalLineToRelative(7.25f)
curveToRelative(-1.112f, -0.93f, -2.038f, -2.135f, -2.636f, -3.573f)
close()
moveTo(4.0f, 5.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f)
reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.448f, 1.0f, 1.0f)
reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f)
close()
moveTo(8.0f, 5.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f)
reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.448f, 1.0f, 1.0f)
reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f)
close()
}
}
.build()
return _sensorFire!!
}
private var _sensorFire: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,343 | icons | MIT License |
app/src/main/java/com/blockeq/stellarwallet/activities/AboutAnimationActivity.kt | Block-Equity | 128,590,362 | false | null | package com.blockeq.stellarwallet.activities
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import com.blockeq.stellarwallet.R
import kotlinx.android.synthetic.main.activity_about_animation.*
class AboutAnimationActivity : AppCompatActivity() {
private var imageViews = arrayListOf<ImageView>()
private var gradientAnimationInProgress : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about_animation)
imageViews.add(blockeq1)
imageViews.add(blockeq2)
imageViews.add(blockeq3)
imageViews.add(blockeq4)
imageViews.add(blockeq5)
imageViews.add(blockeq6)
imageViews.add(blockeq7)
imageViews.add(blockeq8)
imageViews.add(blockeq9)
imageViews.add(blockeq10)
imageViews.add(blockeq11)
imageViews.reverse()
var counter : Long = 0
imageViews.forEachIndexed { index, image ->
slideView(image, 10f, 0f, 85*counter, 700, object : Animation.AnimationListener {
override fun onAnimationRepeat(animation: Animation?) { }
override fun onAnimationStart(animation: Animation?) { }
override fun onAnimationEnd(animation: Animation?) {
if (index == imageViews.lastIndex) {
startGradientAnimation()
}
}
})
counter++
}
slideView(circle, -20f, 0f, 0,850)
blocks_wrapper.setOnClickListener {
if (!gradientAnimationInProgress) {
startGradientAnimation()
}
}
about_animation_root.setOnClickListener {
finish()
}
}
private fun startGradientAnimation() {
val animation = TranslateAnimation(-circle.width.toFloat(), circle.width.toFloat(), 0f, 0f)
animation.duration = 1500
animation.fillAfter = false
animation.interpolator = AccelerateDecelerateInterpolator()
gradient.startAnimation(animation)
animation.setAnimationListener(object: Animation.AnimationListener {
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
gradient.visibility = View.GONE
gradientAnimationInProgress = false
}
override fun onAnimationStart(animation: Animation?) {
gradient.visibility = View.VISIBLE
gradientAnimationInProgress = true
}
})
}
private fun slideView(view : View, from: Float, to: Float = 0f, offset: Long = 0, duration: Long, listener : Animation.AnimationListener? = null) {
val slide: Animation = TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
from, Animation.RELATIVE_TO_SELF, to)
slide.startOffset = offset
slide.duration = duration
slide.fillAfter = true
slide.isFillEnabled = true
if (listener != null) {
slide.setAnimationListener(listener)
}
view.startAnimation(slide)
}
}
| 14 | Kotlin | 24 | 32 | 7996e9c75f4af6dc49241e918494155d0b82493e | 3,531 | stellar-android-wallet | MIT License |
lightweightlibrary/src/main/java/com/tradingview/lightweightcharts/api/serializer/gson/GsonProvider.kt | grietzercs | 306,704,587 | true | {"Kotlin": 112058, "JavaScript": 21903, "HTML": 142} | package com.tradingview.lightweightcharts.api.serializer.gson
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.tradingview.lightweightcharts.api.series.enums.*
import com.tradingview.lightweightcharts.api.series.models.BarPrices
import com.tradingview.lightweightcharts.api.series.models.Time
object GsonProvider {
fun newInstance(): Gson {
return GsonBuilder()
.registerDefaultAdapters()
.create()
}
}
fun GsonBuilder.registerDefaultAdapters(): GsonBuilder {
registerTypeAdapter(Time::class.java, Time.TimeAdapter())
registerTypeAdapter(BarPrices::class.java, BarPrices.BarPricesAdapter())
//series enums
registerTypeAdapter(CrosshairMode::class.java, CrosshairMode.CrosshairModeAdapter())
registerTypeAdapter(LineStyle::class.java, LineStyle.LineStyleAdapter())
registerTypeAdapter(LineType::class.java, LineType.LineTypeAdapter())
registerTypeAdapter(LineWidth::class.java, LineWidth.LineWidthAdapter())
registerTypeAdapter(PriceScaleMode::class.java, PriceScaleMode.PriceScaleModeAdapter())
return this
} | 0 | null | 0 | 0 | 3dc7289f1860d8ed7374884ebbcfaf9a712b8174 | 1,115 | lightweight-charts-android | Apache License 2.0 |
src/main/kotlin/com/ataraxia/gabriel_vz/root/Resource.kt | MaximilianKopp | 295,046,117 | false | null | package com.ataraxia.gabriel_vz.root
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
import org.springframework.hateoas.Link
import org.springframework.http.CacheControl
import org.springframework.http.MediaType
/**
* A basic Resource implementation.
*
* A Resource is an object a client can interact with through Links and HTTP-methods.
*
* @property self a Link to this very Resource.
* @property id a globally unique identifier.
* @property title the title of this Resource.
* @property created a UTC date of the underlying [Model] of this Resource was created.
* @property modified the most recent UTC date of the underlying [Model] of this Resource was modified,
* equals [created] if no modifications did occur.
* */
@ApiModel(value = "Resource", description = "Represents a Resource")
abstract class Resource(
@ApiModelProperty(
notes = "A Link to this very Resource"
)
open val self: Link?,
@ApiModelProperty(
notes = "A link to the overall Collection"
)
open val collection: Link?,
@ApiModelProperty(
notes = "A globally unique identifier.",
example = "urn:ard:examples:123e4567-e89b-12d3-a456-426655440000",
accessMode = ApiModelProperty.AccessMode.READ_ONLY
)
open val id: String?,
@ApiModelProperty(
notes = "The title of this resource.",
example = "A very nice title",
required = true,
accessMode = ApiModelProperty.AccessMode.READ_WRITE
)
open val title: String?,
@ApiModelProperty(
notes = "A UTC DateTime string this resource was created.",
accessMode = ApiModelProperty.AccessMode.READ_ONLY,
example = "2019-01-20T20:12:11.2389491Z"
)
open val created: String?,
@ApiModelProperty(
notes = "The most recent UTC DateTime this resource was modified, equals created if no modification did occur",
accessMode = ApiModelProperty.AccessMode.READ_ONLY,
example = "2019-01-20T20:12:11.2389491Z"
)
open val modified: String?
) {
/**
* Abstract method for CacheControl header an implementations must provide.
* */
abstract fun cacheControl(): CacheControl
/**
* Abstract method for the MediaType an implementations must provide.
* */
abstract fun contentType(): MediaType
/**
* Abstract method for the eTag an implementations must provide.
* */
abstract fun eTag(): String
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Resource) return false
//if (self != other.self) return false
if (id != other.id) return false
if (title != other.title) return false
if (created != other.created) return false
if (modified != other.modified) return false
return true
}
override fun hashCode(): Int {
var result = self?.hashCode() ?: 0
result = 31 * result + (id?.hashCode() ?: 0)
result = 31 * result + (title?.hashCode() ?: 0)
result = 31 * result + (created?.hashCode() ?: 0)
result = 31 * result + (modified?.hashCode() ?: 0)
return result
}
} | 0 | Kotlin | 0 | 0 | b3248f64bf4f0d49cb10ea167961e0bc72aa2a4e | 3,409 | Digital-Thematic-Catalogues-Master-Thesis | Apache License 2.0 |
app/src/main/kotlin/ch/empa/openbisio/collection/CollectionEntity.kt | empa-scientific-it | 618,383,912 | false | null | /*
* Copyright 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
*
* 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 ch.empa.openbisio.collection
import ch.empa.openbisio.identifier.ConcreteIdentifier
import ch.empa.openbisio.interfaces.*
import ch.ethz.sis.openbis.generic.asapi.v3.dto.common.create.ICreation
import ch.ethz.sis.openbis.generic.asapi.v3.dto.experiment.create.ExperimentCreation
import ch.ethz.sis.openbis.generic.asapi.v3.dto.project.id.ProjectPermId
class CollectionEntity(override val dto: CollectionDTO) : CreatableEntity{
override val identifier: ConcreteIdentifier.CollectionIdentifier =
ConcreteIdentifier.CollectionIdentifier(listOf(dto.code))
val properties = dto.properties
//val children = dto.children()?.map { it.toEntity() }
override fun persist(): List<ICreation> {
val cr = ExperimentCreation().apply {
this.code = dto.code
this.projectId = ProjectPermId(identifier.project().identifier)
this.properties = dto.properties
}
return listOf(cr)
}
}
| 0 | Kotlin | 0 | 0 | f61b168531320739a3450e9c3f0bb2a0f0299ce0 | 1,556 | instanceio | Apache License 2.0 |
biz_discover/src/main/java/com/fmt/kotlin/eyepetizer/discover/model/TopicDetailModel.kt | fmtjava | 310,798,006 | false | null | package com.fmt.kotlin.eyepetizer.discover.model
import com.fmt.kotlin.eyepetizer.provider.model.Data
import com.fmt.kotlin.eyepetizer.provider.model.Header
data class TopicDetailModel(
val adTrack: Any,
val brief: String,
val count: Int,
val headerImage: String,
val id: Int,
val itemList: List<Item>,
val shareLink: String,
val text: String
)
data class Item(
val adIndex: Int,
val `data`: ItemData,
val id: Int,
val tag: Any,
val trackingData: Any,
val type: String
)
data class ItemData(
val dataType: String,
val header: Header,
val content: Content,
)
data class Content(
val adIndex: Int,
val `data`: Data,
val id: Int,
val tag: Any,
val trackingData: Any,
val type: String
)
| 0 | Kotlin | 16 | 98 | 263023794c27fe81d05ac771329e2c3ce1a992f6 | 785 | Jetpack_Kotlin_Eyepetizer | MIT License |
buildSrc/src/main/kotlin/com/delbel/ProjectModulePlugin.kt | matiasdelbel | 213,772,637 | false | {"Kotlin": 16497} | package com.delbel
import com.delbel.plugin.*
import org.gradle.api.Plugin
import org.gradle.api.Project
import kotlin.contracts.ExperimentalContracts
@ExperimentalContracts
@Suppress("unused")
class ProjectModulePlugin : Plugin<Project> {
private val plugin = KotlinPlugin()
.appendNext(next = JavaPlugin())
.appendNext(next = AndroidPlugin())
.appendNext(next = ProGuardPlugin())
.appendNext(next = ScaPlugin())
.appendNext(next = TestPlugin())
.appendNext(next = CoveragePlugin())
.appendNext(next = InjectionPlugin())
override fun apply(project: Project) = plugin.apply(project)
}
| 3 | Kotlin | 0 | 1 | e5191316ea97cb63c11da0fb1b3acb6d6ad164e2 | 653 | android-zygote-multi-modules | Apache License 2.0 |
mine/src/main/java/com/kotlin/android/mine/ui/home/MineVMViewModel.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.mine.ui.home
import android.content.Context
import com.kotlin.android.api.base.BinderUIModel
import com.kotlin.android.api.base.call
import com.kotlin.android.app.data.entity.activity.ActivityList
import com.kotlin.android.app.data.entity.mine.AccountStatisticsInfo
import com.kotlin.android.app.data.entity.user.User
import com.kotlin.android.core.BaseViewModel
import com.kotlin.android.mine.bean.AccountStatisticsInfoViewBean
import com.kotlin.android.mine.bean.ActivityViewBean
import com.kotlin.android.mine.bean.UserViewBean
import com.kotlin.android.mine.repoistory.MineRepository
import com.kotlin.android.widget.adapter.multitype.adapter.binder.MultiTypeBinder
/**
* 创建者: vivian.wei
* 创建时间: 2022/3/10
* 描述: 我的首页ViewModel
*/
class MineVMViewModel: BaseViewModel() {
private val repo by lazy { MineRepository() }
// 用户详情信息
private val mAccountDetailUIModel = BinderUIModel<User, UserViewBean>()
val accountDetailState = mAccountDetailUIModel.uiState
// 用户统计信息
private val mStatisticUIModel = BinderUIModel<AccountStatisticsInfo, AccountStatisticsInfoViewBean>()
val statisticUIState = mStatisticUIModel.uiState
// 活动列表
private val mActivityUIModel = BinderUIModel<ActivityList, MutableList<MultiTypeBinder<*>>>()
val activityUIState = mActivityUIModel.uiState
/**
* 用户详情信息
*/
fun getAccountDetail() {
call(
uiModel = mAccountDetailUIModel,
converter = {
UserViewBean.objectToViewBean(it)
}
) {
repo.getMineUserDetail()
}
}
/**
* 用户统计信息
*/
fun getMineStatisticInfo(context: Context) {
call(
uiModel = mStatisticUIModel,
converter = {
AccountStatisticsInfoViewBean.objectToViewBean(context, it)
}
) {
repo.getMineStatisticInfo()
}
}
/**
* 活动列表
* 未登录用户也可以查看,登录用户从统计信息接口取值
*/
fun getActivityList(context: Context, pageSize: Long) {
call(
uiModel = mActivityUIModel,
converter = {
ActivityViewBean.build(context, it.activities, true)
}
) {
repo.getUserActivityList(
pageSize = pageSize
)
}
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 2,391 | Mtime | Apache License 2.0 |
app/src/main/java/com/ch8n/thatsmine/domain/models/User.kt | ch8n | 309,301,948 | false | null | package com.ch8n.thatsmine.domain.models
import com.github.javafaker.Faker
import java.util.*
data class User(
val userId: String,
val userName: String,
val fullName: String,
val email: String
) {
companion object {
fun default() = User(
userId = "",
userName = "",
fullName = "",
email = "",
)
fun mock() = Faker().let { faker ->
User(
userId = UUID.randomUUID().toString(),
userName = faker.name().username(),
fullName = faker.name().fullName(),
email = faker.internet().emailAddress()
)
}
}
} | 2 | Kotlin | 0 | 9 | bc004927672f027324d4cd59f591921062466077 | 692 | Jetpack-compose-thatsMine | Apache License 2.0 |
wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/ButtonSample.kt | JetBrains | 351,708,598 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.CompactButton
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.OutlinedButton
import androidx.wear.compose.material.OutlinedCompactButton
import androidx.wear.compose.material.Text
@Sampled
@Composable
fun ButtonWithIcon() {
Button(
onClick = { /* Do something */ },
enabled = true,
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier =
Modifier.size(ButtonDefaults.DefaultIconSize)
.wrapContentSize(align = Alignment.Center),
)
}
}
@Sampled
@Composable
fun OutlinedButtonWithIcon() {
OutlinedButton(
onClick = { /* Do something */ },
enabled = true,
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier =
Modifier.size(ButtonDefaults.DefaultIconSize)
.wrapContentSize(align = Alignment.Center),
)
}
}
@Sampled
@Composable
fun LargeButtonWithIcon() {
Button(
onClick = { /* Do something */ },
enabled = true,
modifier = Modifier.size(ButtonDefaults.LargeButtonSize)
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier =
Modifier.size(ButtonDefaults.LargeIconSize)
.wrapContentSize(align = Alignment.Center),
)
}
}
@Sampled
@Composable
fun ButtonWithText() {
Button(
onClick = { /* Do something */ },
enabled = true,
modifier = Modifier.size(ButtonDefaults.LargeButtonSize)
) {
Text("Big")
}
}
@Sampled
@Composable
fun CompactButtonWithIcon() {
CompactButton(
onClick = { /* Do something */ },
enabled = true,
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier =
Modifier.size(ButtonDefaults.SmallIconSize)
.wrapContentSize(align = Alignment.Center),
)
}
}
@Sampled
@Composable
fun OutlinedCompactButtonWithIcon() {
OutlinedCompactButton(
onClick = { /* Do something */ },
enabled = true,
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier =
Modifier.size(ButtonDefaults.SmallIconSize)
.wrapContentSize(align = Alignment.Center),
)
}
}
| 29 | null | 937 | 59 | e18ad812b77fc8babb00aacfcea930607b0794b5 | 3,870 | androidx | Apache License 2.0 |
data/src/commonMain/kotlin/io/gaitian/telekot/data/model/ForumTopicClosed.kt | galik-ya | 668,662,208 | false | null | package io.gaitian.telekot.data.model
import kotlinx.serialization.Serializable
/**
* This object represents a service message about a forum topic closed in the chat. Currently holds no information
*
* @see <a href="https://core.telegram.org/bots/api#forumtopicclosed">Telegram Bot API | ForumTopicClosed</a>
*/
@Serializable
class ForumTopicClosed : Model
| 0 | Kotlin | 0 | 0 | 89189a6509756c30f9f1a658bab0a769b21a9a42 | 363 | telekot | Apache License 2.0 |
objectbox/example/flutter/objectbox_demo/android/app/src/main/kotlin/com/example/objectbox_demo/MainActivity.kt | objectbox | 197,584,193 | false | {"Dart": 1176704, "C": 369830, "C++": 118290, "CMake": 106764, "Shell": 18745, "Ruby": 18692, "Swift": 8931, "Kotlin": 4413, "Makefile": 1182, "Objective-C": 190} | package com.example.objectbox_demo
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 62 | Dart | 117 | 999 | 2dc4caf151c29e4b37cbde422e65a25144db277d | 131 | objectbox-dart | Apache License 2.0 |
compiler/testData/diagnostics/tests/redeclarations/kt2438.fir.kt | BradOselo | 367,097,840 | true | null | // !DIAGNOSTICS: -DUPLICATE_CLASS_NAMES
//KT-2438 Prohibit inner classes with the same name
package kt2438
class B {
<!REDECLARATION!>class C<!>
<!REDECLARATION!>class C<!>
}
class A {
<!REDECLARATION!>class B<!>
companion object {
<!REDECLARATION!>class B<!>
<!REDECLARATION!>class B<!>
}
<!REDECLARATION!>class B<!>
}
| 0 | null | 0 | 3 | 58c7aa9937334b7f3a70acca84a9ce59c35ab9d1 | 375 | kotlin | Apache License 2.0 |
src/test/kotlin/ru/yoomoney/gradle/plugins/backend/build/JavaModulePluginTest.kt | yoomoney | 334,236,333 | false | null | package ru.yoomoney.gradle.plugins.backend.build
import org.apache.commons.io.IOUtils
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.hasItem
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.util.Properties
/**
* @author Valerii Zhirnov
* @since 16.04.2019
*/
class JavaModulePluginTest : AbstractPluginTest() {
@Test
fun `should successfully run jar task`() {
buildFile.writeText("""
buildscript {
repositories {
mavenCentral()
}
}
plugins {
id 'ru.yoomoney.gradle.plugins.java-plugin'
}
dependencies {
optional 'org.testng:testng:6.14.3'
}
javaModule {
repositories = ["https://repo1.maven.org/maven2/"]
}
""".trimIndent())
runTasksSuccessfully("build", "jar")
assertFileExists(File(projectDir.root, "/target/libs/${projectName()}-1.0.1-feature-BACKEND-2588-build-jar-SNAPSHOT.jar"))
assertFileExists(File(projectDir.root, "/target/tmp/jar/MANIFEST.MF"))
val properties = Properties().apply { load(File(projectDir.root, "/target/tmp/jar/MANIFEST.MF").inputStream()) }
assertThat("Implementation-Version", properties.getProperty("Implementation-Version"), notNullValue())
assertThat("Bundle-SymbolicName", properties.getProperty("Bundle-SymbolicName"), notNullValue())
assertThat("Built-By", properties.getProperty("Built-By"), notNullValue())
assertThat("Built-Date", properties.getProperty("Built-Date"), notNullValue())
assertThat("Built-At", properties.getProperty("Built-At"), notNullValue())
}
@Test
fun `should run tests`() {
projectDir.newFolder("src", "test", "java")
val javaTest = projectDir.newFile("src/test/java/JavaTest.java")
javaTest.writeText("""
import org.testng.annotations.Test;
public class JavaTest {
@Test
public void javaTest() {
System.out.println("run java test...");
}
}
""".trimIndent())
projectDir.newFolder("src", "test", "kotlin")
val kotlinTest = projectDir.newFile("src/test/kotlin/KotlinTest.kt")
kotlinTest.writeText("""
import org.testng.annotations.Test
class KotlinTest {
@Test
fun `kotlin test`() {
println("run kotlin test...")
}
}
""".trimIndent())
projectDir.newFolder("src", "slowTest", "java")
val slowTest = projectDir.newFile("src/slowTest/java/SlowTest.java")
slowTest.writeText("""
import org.testng.Assert;
import org.testng.annotations.Test;
public class SlowTest {
@Test
public void slowTest() throws Exception {
sample.HelloWorld.main(null);
System.out.println("run slowTest test...");
}
}
""".trimIndent())
projectDir.newFolder("target", "tmp", "logs", "test")
val slowTestLogs = projectDir.newFile("target/tmp/logs/test/LOGS-SlowTest.xml")
slowTestLogs.writeText("""
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<testlogs className="SlowTest">
<testlog name="slowTest"><![CDATA[
[test] SUCCESS
[test] run slowTest test...
]]></testlog>
</testlogs>
""".trimIndent())
val buildResult = runTasksSuccessfully("test", "componentTest")
assertThat("Java tests passed", buildResult.output, containsString("run java test..."))
assertThat("Kotlin tests passed", buildResult.output, containsString("run kotlin test..."))
assertThat("SlowTest tests passed", buildResult.output, containsString("run slowTest test..."))
assertThat("SlowTest reports overwritten",
IOUtils.toString(
File(projectDir.root, "/target/test-results/slowTestTestNg/TEST-SlowTest.xml").inputStream(),
StandardCharsets.UTF_8
),
containsString("[test]")
)
Files.delete(javaTest.toPath())
Files.delete(kotlinTest.toPath())
Files.delete(slowTest.toPath())
}
@Test
fun `should pass parameters to sonarqube tasks`() {
buildFile.appendText("\n")
buildFile.appendText("""
javaModule {
sonarqube.projectKey = "projectKey"
sonarqube.supplyLibrariesPath = false
}
task printSonarqubeProperties {
doLast {
project.tasks.getByName("sonarqube").properties.forEach { key, value ->
println(key + "=" + value)
}
}
}
""".trimIndent())
val buildResult = runTasksSuccessfully("printSonarqubeProperties")
assertThat(buildResult.output.lines(), hasItem("sonar.projectKey=projectKey"))
assertThat(buildResult.output.lines(), hasItem("sonar.branch.name=feature/BACKEND-2588_build_jar"))
assertThat(buildResult.output.lines(), hasItem("sonar.java.libraries="))
assertThat(buildResult.output.lines(), hasItem("sonar.java.test.libraries="))
}
@Test
fun `sonarqube should depend on jacoco and checkstyle tasks`() {
buildFile.appendText("\n")
buildFile.appendText("""
task printDependsOnSonarqubeTasks {
doLast {
project.tasks.getByName("sonarqube").dependsOn.forEach { println(it) }
}
}
""".trimIndent())
val buildResult = runTasksSuccessfully("printDependsOnSonarqubeTasks")
assertThat(buildResult.output, containsString("checkstyleMain"))
assertThat(buildResult.output, containsString("jacocoAggReport"))
assertThat(buildResult.output, containsString("jacocoTestReport"))
}
@Test
fun `analysis tasks should be disabled when analyseDevelopmentBranchesOnly true`() {
buildFile.appendText("\n")
buildFile.appendText("""
javaModule.sonarqube.enabled = true
task printAnalysisTasksStatus {
doLast {
def sonarqube = project.tasks.getByName("sonarqube")
def checkstyle = project.tasks.getByName("checkstyleMain")
def spotbugs = project.tasks.getByName("spotbugsMain")
println("sonarqube:" + sonarqube.onlyIf.isSatisfiedBy(sonarqube))
println("checkstyle:" + checkstyle.onlyIf.isSatisfiedBy(checkstyle))
println("spotbugs:" + spotbugs.onlyIf.isSatisfiedBy(spotbugs))
}
}
""".trimIndent())
git.checkout().setName("master").call()
val buildResult = runTasksSuccessfully("printAnalysisTasksStatus")
assertThat(buildResult.output, containsString("sonarqube:false"))
assertThat(buildResult.output, containsString("checkstyle:false"))
assertThat(buildResult.output, containsString("spotbugs:false"))
}
@Test
fun `analysis tasks should be enabled when analyseDevelopmentBranchesOnly false`() {
buildFile.appendText("\n")
buildFile.appendText("""
javaModule.sonarqube.enabled = true
javaModule.analyseDevelopmentBranchesOnly = false
task printAnalysisTasksStatus {
doLast {
def sonarqube = project.tasks.getByName("sonarqube")
def checkstyle = project.tasks.getByName("checkstyleMain")
def spotbugs = project.tasks.getByName("spotbugsMain")
println("sonarqube:" + sonarqube.onlyIf.isSatisfiedBy(sonarqube))
println("checkstyle:" + checkstyle.onlyIf.isSatisfiedBy(checkstyle))
println("spotbugs:" + spotbugs.onlyIf.isSatisfiedBy(spotbugs))
}
}
""".trimIndent())
git.checkout().setName("master").call()
val buildResult = runTasksSuccessfully("printAnalysisTasksStatus")
assertThat(buildResult.output, containsString("sonarqube:true"))
assertThat(buildResult.output, containsString("checkstyle:true"))
assertThat(buildResult.output, containsString("spotbugs:true"))
}
}
| 0 | Kotlin | 2 | 2 | 407418a357d0eb5ab626ee640be2a65a92c92d5c | 8,860 | java-plugin | MIT License |
coderunner/src/main/kotlin/io/codegeet/sandbox/coderunner/model/Model.kt | codegeet | 704,806,290 | false | {"Kotlin": 19649} | package io.codegeet.sandbox.coderunner.model
import com.fasterxml.jackson.annotation.JsonProperty
data class ApplicationInput(
@JsonProperty("language")
val language: String,
@JsonProperty("code")
val code: String
//todo add stdin
//todo add command
)
data class ApplicationOutput(
@JsonProperty("std_out")
val stdOut: String,
@JsonProperty("std_err")
val stdErr: String,
@JsonProperty("error")
val error: String,
)
| 4 | Kotlin | 0 | 0 | 611f013de998472b2c24d1de3cf98cc6ef8c9d9f | 467 | codegeet | MIT License |
app/src/robolectricTest/java/org/fnives/test/showcase/testutils/configuration/SpecificTestConfigurationsFactory.kt | fknives | 356,982,481 | false | null | package org.fnives.test.showcase.testutils.configuration
object SpecificTestConfigurationsFactory : TestConfigurationsFactory {
override fun createMainDispatcherTestRule(): MainDispatcherTestRule =
TestCoroutineMainDispatcherTestRule()
override fun createServerTypeConfiguration(): ServerTypeConfiguration =
RobolectricServerTypeConfiguration
override fun createLoginRobotConfiguration(): LoginRobotConfiguration =
RobolectricLoginRobotConfiguration
override fun createSnackbarVerification(): SnackbarVerificationTestRule =
RobolectricSnackbarVerificationTestRule
}
| 15 | Kotlin | 0 | 2 | b35467fcba52f5ac6896b316ca27d3d0b1f2bbf0 | 618 | AndroidTest-ShowCase | Apache License 2.0 |
app/src/main/kotlin/popup/Reminder.kt | Buldugmaster99 | 386,209,155 | false | null | package popup
import calendar.Appointment
import calendar.Reminder
import calendar.Timing
import calendar.Timing.toUTCEpochMinute
import calendar.getAppointments
import datetimepicker.dateTimePicker
import frame.toggleSwitch
import javafx.beans.property.*
import javafx.geometry.*
import javafx.scene.layout.*
import javafx.scene.paint.*
import javafx.scene.text.*
import javafx.stage.*
import listen
import logic.getLangString
import picker.appointmentPicker
import tornadofx.*
import java.time.LocalDateTime
class NewReminderPopup: Fragment() {
override val scope = super.scope as ItemsScope
private var reminder: Reminder? = scope.reminder
// do not bind directly, instead copy values into new Observables, to only save an updateAppointment()
private var reminderTitle: Property<String> = (reminder?.title ?: "").toProperty()
private var end: Property<LocalDateTime> = (reminder?.let { it.time?.let { it1 -> Timing.UTCEpochMinuteToLocalDateTime(it1) } } ?: scope.end).toProperty()
private var reminderDescription: Property<String> = (reminder?.title ?: "").toProperty()
private var onSave: (Reminder) -> Unit = scope.save
private var error: Property<String> = "".toProperty()
private var windowTitle: String = scope.title
private var saveTitle: String = scope.saveTitle
private var toggle: Property<Boolean> = scope.timeOrAppointment.toProperty()
private var toggleName: Property<String> = "".toProperty()
private var control: BorderPane? = null
private var appointment: Property<Appointment?> = SimpleObjectProperty(null)
init {
appointment.listen {
if(it != null)
end.value = Timing.UTCEpochMinuteToLocalDateTime(it.start)
else
end.value = scope.end
}
}
private fun updateDisplay(toggle: Boolean) {
if(toggle) {
toggleName.value = "Appointment"
control?.left = appointmentPicker(getAppointments(), appointment = appointment)
} else {
toggleName.value = "Date"
control?.left = dateTimePicker(dateTime = end)
}
}
private fun updateReminder() {
reminder?.let { rem ->
rem.title = reminderTitle.value
}
}
private fun createReminder(): Reminder = Reminder.new(
end.value.toUTCEpochMinute(), reminderTitle.value, reminderDescription.value,
)
private fun checkReminder(): String? {
if(reminderTitle.value.isEmpty()) {
return getLangString("missing title")
}
return null
}
override fun onBeforeShow() {
modalStage?.height = 320.0
modalStage?.width = 440.0
modalStage?.minWidth = 430.0
modalStage?.minHeight = 280.0
}
override val root = form {
style {
backgroundColor += Color.WHITE
}
fieldset(getLangString(windowTitle)) {
style {
prefHeight = Int.MAX_VALUE.px
}
field(getLangString("Finish")) {
control = borderpane {
right = stackpane {
alignment = Pos.CENTER_RIGHT
style {
paddingLeft = 5
}
label(toggleName) {
style {
paddingRight = 38
}
}
toggleSwitch(selected = toggle) {
}
}
}
}
field(getLangString("title")) {
textfield(reminderTitle)
}
field(getLangString("description")) {
style(append = true) {
prefHeight = Int.MAX_VALUE.px
minHeight = 60.px
padding = box(0.px, 0.px, 20.px, 0.px)
}
textarea(reminderDescription) {
style(append = true) {
prefHeight = Int.MAX_VALUE.px
}
}
}
field(getLangString("notify")) {
text(getLangString("missing %s", "Notifications"))
}
buttonbar {
textfield(error) {
style(append = true) {
backgroundColor += Color.TRANSPARENT
borderStyle += BorderStrokeStyle.NONE
textFill = Color.RED
fontSize = 120.percent
fontWeight = FontWeight.BOLD
}
}
button(getLangString("Cancel")) {
isCancelButton = true
action {
close()
}
}
button(saveTitle) {
isDefaultButton = true
action {
val check = checkReminder()
if(check == null) {
if(reminder == null)
reminder = createReminder()
updateReminder()
onSave.invoke(reminder!!)
close()
} else {
error.value = check
}
}
}
}
}
}
init {
toggle.listen {
updateDisplay(it)
}
updateDisplay(toggle.value)
}
class ItemsScope(
val title: String, val saveTitle: String, val reminder: Reminder?, val end: LocalDateTime, val save: (Reminder) -> Unit, val timeOrAppointment: Boolean
): Scope()
companion object {
fun open(title: String, saveTitle: String, block: Boolean, reminder: Reminder?, end: LocalDateTime, save: (Reminder) -> Unit, timeOrAppointment: Boolean = true): Stage? {
val scope = ItemsScope(title, saveTitle, reminder, end, save, timeOrAppointment)
return find<NewReminderPopup>(scope).openModal(modality = if(block) Modality.APPLICATION_MODAL else Modality.NONE, escapeClosesWindow = false)
}
}
}
| 17 | Kotlin | 0 | 2 | 7dcc1bf012e8f2c72c1eaa691c945f8b3726f841 | 4,884 | Calendar | MIT License |
kotlin-native/build-tools/src/main/kotlin/org/jetbrains/kotlin/testing/native/NativeTest.kt | workfilemmfloe | 492,307,576 | false | {"Kotlin": 64410043, "Java": 7037731, "Swift": 4222561, "C": 2628499, "C++": 2304107, "Objective-C": 537055, "JavaScript": 207226, "Objective-C++": 138365, "Groovy": 103247, "Python": 45251, "Shell": 36903, "TypeScript": 22641, "Lex": 18323, "Batchfile": 15927, "CSS": 11259, "HTML": 5446, "EJS": 5241, "CMake": 5121, "Dockerfile": 4493, "Ruby": 2383, "Pascal": 1698, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.testing.native
import groovy.lang.Closure
import java.io.File
import javax.inject.Inject
import org.gradle.api.*
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.tasks.*
import org.gradle.api.model.ObjectFactory
import org.gradle.process.ExecOperations
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import org.gradle.workers.WorkerExecutor
import org.jetbrains.kotlin.ExecClang
import org.jetbrains.kotlin.konan.target.*
import java.io.OutputStream
interface CompileNativeTestParameters : WorkParameters {
var mainFile: File
var inputFiles: List<File>
var llvmLinkOutputFile: File
var compilerOutputFile: File
var targetName: String
var compilerArgs: List<String>
var linkCommands: List<List<String>>
var konanHome: File
var llvmDir: File
var experimentalDistribution: Boolean
var isInfoEnabled: Boolean
}
abstract class CompileNativeTestJob : WorkAction<CompileNativeTestParameters> {
@get:Inject
abstract val execOperations: ExecOperations
@get:Inject
abstract val objects: ObjectFactory
private fun llvmLink() {
with(parameters) {
val tmpOutput = File.createTempFile("runtimeTests", ".bc").apply {
deleteOnExit()
}
// The runtime provides our implementations for some standard functions (see StdCppStubs.cpp).
// We need to internalize these symbols to avoid clashes with symbols provided by the C++ stdlib.
// But llvm-link -internalize is kinda broken: it links modules one by one and can't see usages
// of a symbol in subsequent modules. So it will mangle such symbols causing "unresolved symbol"
// errors at the link stage. So we have to run llvm-link twice: the first one links all modules
// except the one containing the entry point to a single *.bc without internalization. The second
// run internalizes this big module and links it with a module containing the entry point.
execOperations.exec {
executable = "$llvmDir/bin/llvm-link"
args = listOf("-o", tmpOutput.absolutePath) + inputFiles.map { it.absolutePath }
}
execOperations.exec {
executable = "$llvmDir/bin/llvm-link"
args = listOf(
"-o", llvmLinkOutputFile.absolutePath,
mainFile.absolutePath,
tmpOutput.absolutePath,
"-internalize"
)
}
}
}
private fun compile() {
with(parameters) {
val platformManager = PlatformManager(buildDistribution(konanHome.absolutePath), experimentalDistribution)
val execClang = ExecClang.create(objects, platformManager, llvmDir)
val target = platformManager.targetByName(targetName)
val clangFlags = buildClangFlags(platformManager.platform(target).configurables)
if (target.family.isAppleFamily) {
execClang.execToolchainClang(target) {
executable = "clang++"
this.args = clangFlags + compilerArgs + listOf(llvmLinkOutputFile.absolutePath, "-o", compilerOutputFile.absolutePath)
}
} else {
execClang.execBareClang {
executable = "clang++"
this.args = clangFlags + compilerArgs + listOf(llvmLinkOutputFile.absolutePath, "-o", compilerOutputFile.absolutePath)
}
}
}
}
private fun link() {
with(parameters) {
for (command in linkCommands) {
execOperations.exec {
commandLine(command)
if (!isInfoEnabled && command[0].endsWith("dsymutil")) {
// Suppress dsymutl's warnings.
// See: https://bugs.swift.org/browse/SR-11539.
val nullOutputStream = object: OutputStream() {
override fun write(b: Int) {}
}
errorOutput = nullOutputStream
}
}
}
}
}
override fun execute() {
llvmLink()
compile()
link()
}
}
abstract class CompileNativeTest @Inject constructor(
baseName: String,
@Input val target: KonanTarget,
@InputFile val mainFile: File,
private val platformManager: PlatformManager,
private val mimallocEnabled: Boolean,
) : DefaultTask() {
@SkipWhenEmpty
@InputFiles
val inputFiles: ConfigurableFileCollection = project.files()
@OutputFile
var llvmLinkOutputFile: File = project.buildDir.resolve("bitcode/test/${target.name}/$baseName.bc")
@OutputFile
var compilerOutputFile: File = project.buildDir.resolve("bin/test/${target.name}/$baseName.o")
private val executableExtension: String = when (target) {
is KonanTarget.MINGW_X64 -> ".exe"
is KonanTarget.MINGW_X86 -> ".exe"
else -> ""
}
@OutputFile
var outputFile: File = project.buildDir.resolve("bin/test/${target.name}/$baseName$executableExtension")
@Input
val clangArgs = mutableListOf<String>()
@Input
val linkerArgs = mutableListOf<String>()
@Input @Optional
var sanitizer: SanitizerKind? = null
private val sanitizerFlags = when (sanitizer) {
null -> listOf()
SanitizerKind.ADDRESS -> listOf("-fsanitize=address")
SanitizerKind.THREAD -> listOf("-fsanitize=thread")
}
@get:Input
val linkCommands: List<List<String>>
get() {
// Getting link commands requires presence of a target toolchain.
// Thus we cannot get them at the configuration stage because the toolchain may be not downloaded yet.
val linker = platformManager.platform(target).linker
return linker.finalLinkCommands(
listOf(compilerOutputFile.absolutePath),
outputFile.absolutePath,
listOf(),
linkerArgs,
optimize = false,
debug = true,
kind = LinkerOutputKind.EXECUTABLE,
outputDsymBundle = outputFile.absolutePath + ".dSYM",
needsProfileLibrary = false,
mimallocEnabled = mimallocEnabled,
sanitizer = sanitizer
).map { it.argsWithExecutable }
}
@get:Inject
abstract val workerExecutor: WorkerExecutor
@TaskAction
fun compile() {
val workQueue = workerExecutor.noIsolation()
val parameters = { it: CompileNativeTestParameters ->
it.mainFile = mainFile
it.inputFiles = inputFiles.map { it }
it.llvmLinkOutputFile = llvmLinkOutputFile
it.compilerOutputFile = compilerOutputFile
it.targetName = target.name
it.compilerArgs = clangArgs + sanitizerFlags
it.linkCommands = linkCommands
it.konanHome = project.project(":kotlin-native").projectDir
it.llvmDir = project.file(project.findProperty("llvmDir")!!)
it.isInfoEnabled = logger.isInfoEnabled
}
workQueue.submit(CompileNativeTestJob::class.java, parameters)
}
}
open class RunNativeTest @Inject constructor(
@Input val testName: String,
@InputFile val inputFile: File,
) : DefaultTask() {
@Internal
var workingDir: File = project.buildDir.resolve("testReports/$testName")
@OutputFile
var outputFile: File = workingDir.resolve("report.xml")
@OutputFile
var outputFileWithPrefixes: File = workingDir.resolve("report-with-prefixes.xml")
@Input @Optional
var filter: String? = project.findProperty("gtest_filter") as? String
@Input @Optional
var sanitizer: SanitizerKind? = null
@InputFile
var tsanSuppressionsFile = project.file("tsan_suppressions.txt")
@TaskAction
fun run() {
workingDir.mkdirs()
// Do not run this in workers, because we don't want this task to run in parallel.
project.exec {
executable = inputFile.absolutePath
if (filter != null) {
args("--gtest_filter=${filter}")
}
args("--gtest_output=xml:${outputFile.absolutePath}")
when (sanitizer) {
SanitizerKind.THREAD -> {
environment("TSAN_OPTIONS", "suppressions=${tsanSuppressionsFile.absolutePath}")
}
else -> {} // no action required
}
}
// TODO: Better to use proper XML parsing.
var contents = outputFile.readText()
contents = contents.replace("<testsuite name=\"", "<testsuite name=\"${testName}.")
contents = contents.replace("classname=\"", "classname=\"${testName}.")
outputFileWithPrefixes.writeText(contents)
}
}
/**
* Returns a list of Clang -cc1 arguments (including -cc1 itself) that are used for bitcode compilation in Kotlin/Native.
*
* See also: [org.jetbrains.kotlin.backend.konan.BitcodeCompiler]
*/
private fun buildClangFlags(configurables: Configurables): List<String> = mutableListOf<String>().apply {
require(configurables is ClangFlags)
addAll(configurables.clangFlags)
addAll(configurables.clangNooptFlags)
val targetTriple = if (configurables is AppleConfigurables) {
configurables.targetTriple.withOSVersion(configurables.osVersionMin)
} else {
configurables.targetTriple
}
addAll(listOf("-triple", targetTriple.toString()))
}.toList() | 4 | Kotlin | 0 | 1 | 80ab0a1065d1f40a05ff4995e4b9318d0f20ee09 | 9,967 | effective-tribble | Apache License 2.0 |
src/main/kotlin/com/github/strindberg/emacsj/actions/word/TransposeWordsAction.kt | strindberg | 719,602,205 | false | {"Kotlin": 286724} | package com.github.strindberg.emacsj.actions.word
import com.github.strindberg.emacsj.word.Direction
import com.github.strindberg.emacsj.word.WordTransposeHandler
import com.intellij.openapi.editor.actions.TextComponentEditorAction
class TransposeWordsAction : TextComponentEditorAction(WordTransposeHandler(Direction.FORWARD))
| 3 | Kotlin | 1 | 9 | 798a061f215c8ab2d3bbb67e4ba2afd12d8554d2 | 330 | emacsj | MIT License |
legacy/styles/style-headless/src/commonMain/kotlin/execution/ExecutableNode.kt | CLOVIS-AI | 582,955,979 | false | {"Kotlin": 313151, "JavaScript": 1822, "Dockerfile": 1487, "Shell": 556, "HTML": 372, "CSS": 280} | package opensavvy.decouple.headless.execution
import androidx.compose.runtime.*
import opensavvy.decouple.headless.Component
import opensavvy.decouple.headless.Component.Companion.viewAs
import opensavvy.decouple.headless.node.Attributes
import opensavvy.decouple.headless.node.Node
import opensavvy.decouple.headless.node.NodeTree
import opensavvy.decouple.headless.node.Slots
import kotlin.reflect.KProperty
/**
* The node used internally by Compose to represent the entire UI.
*
* This class is the internal state of the UI, with no protections.
* It should not be used directly when writing UI tests.
* Instead, [viewAs] should be used to convert it into a [Component].
*
* Users of Decouple should only interact with this class when writing a new [Component] instance (to bind the values
* it stores to their component, using [attributes], [nodes] and [content]).
* A complete example is available in [Component]'s documentation.
*/
class ExecutableNode(
override val name: String,
override val isSlot: Boolean,
) : Node {
private val _attributes = HashMap<String, Any?>()
private val _slots = ArrayList<ExecutableNode>()
//region Attributes
override val attributes: Attributes.Mutable = ExecutableAttributes()
private inner class ExecutableAttributes : Attributes.Mutable {
override fun getRaw(attribute: String): Any? =
_attributes[attribute]
override fun set(attribute: String, value: Any?) {
_attributes[attribute] = value
}
override fun clone(): Attributes =
Attributes.Immutable(_attributes)
override fun toString(): String =
if (_attributes.isEmpty()) ""
else _attributes.toString()
}
//endregion
//region Slots
override val slots: Slots = ExecutableSlots()
private inner class ExecutableSlots : Slots {
override val children: MutableList<ExecutableNode>
get() = _slots
override fun clone(): Slots =
Slots.Immutable(this)
}
//endregion
override fun clone() = Node.Immutable(
name,
isSlot,
Attributes.Immutable(_attributes),
Slots.Immutable(slots),
)
override fun toString() = toPrettyString()
internal inner class Applier : AbstractApplier<ExecutableNode>(this) {
override fun insertBottomUp(index: Int, instance: ExecutableNode) {
current._slots.add(index, instance)
}
override fun insertTopDown(index: Int, instance: ExecutableNode) {
// We insert bottom-up, this is a no-op
}
override fun move(from: Int, to: Int, count: Int) {
current._slots.move(from, to, count)
}
override fun onClear() {
current._slots.clear()
}
override fun remove(index: Int, count: Int) {
current._slots.remove(index, count)
}
}
}
/**
* Convenience function to recompose an [ExecutableNode].
*/
@Composable
fun Node(
name: String,
isSlot: Boolean = false,
update: @DisallowComposableCalls() (Updater<ExecutableNode>.() -> Unit),
content: @Composable () -> Unit,
) {
ComposeNode<ExecutableNode, ExecutableNode.Applier>(
factory = { ExecutableNode(name, isSlot) },
update = update,
content = content,
)
}
/**
* Convenience function to recompose a secondary slot named [name].
*
* Secondary slots do not have attributes, so they do not need to be updated.
*/
@Composable
fun Slot(
name: String,
content: @Composable () -> Unit,
) {
Node(
name,
isSlot = true,
update = {},
content,
)
}
/**
* Convenience function to recompose a secondary slot named after [property].
*
* Secondary slots do not have attributes, so they do not need to be updated.
*/
@Composable
fun Slot(
property: KProperty<NodeTree>,
content: @Composable () -> Unit,
) = Slot(property.name, content)
| 0 | Kotlin | 0 | 2 | b97efa62f6c0d5800722001234cf8dd6c2dd6511 | 3,621 | Decouple | Apache License 2.0 |
app/src/main/java/cz/nestresuju/networking/AuthApiDefinition.kt | johnondrej | 371,166,772 | false | null | package cz.nestresuju.networking
import cz.nestresuju.model.entities.api.auth.AuthResponse
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
/**
* Definition of API endpoints for authentication.
*/
interface AuthApiDefinition {
@FormUrlEncoded
@POST("connect/token")
suspend fun login(
@Field("client_id") clientId: String,
@Field("client_secret") clientSecret: String,
@Field("grant_type") grantType: String,
@Field("scope") scope: String,
@Field("username") username: String,
@Field("password") password: String
): AuthResponse
@FormUrlEncoded
@POST("connect/token")
suspend fun loginWithRefreshToken(
@Field("client_id") clientId: String,
@Field("client_secret") clientSecret: String,
@Field("grant_type") grantType: String,
@Field("scope") scope: String,
@Field("refresh_token") refreshToken: String
): AuthResponse
} | 0 | Kotlin | 0 | 0 | 8d7c54c00c865a370ed24a356abd2bfeeef4ed4b | 989 | nestresuju-android | Apache License 2.0 |
src/main/kotlin/com.franzmandl.fileadmin/resource/MvcConfig.kt | franzmandl | 570,884,978 | false | null | package com.franzmandl.fileadmin.resource
import com.franzmandl.fileadmin.Config
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@Configuration
@EnableWebMvc
class MvcConfig(
@Autowired private val config: Config
) : WebMvcConfigurer {
override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
registry
.addResourceHandler("${Config.RequestMappingPaths.bookmarks}/**")
.addResourceLocations("file:${config.paths.bookmarks}/")
registry
.addResourceHandler("${Config.RequestMappingPaths.web}/**")
.addResourceLocations("file:${config.paths.web}/")
}
}
| 0 | Kotlin | 0 | 0 | 34cca7a2272c15a209b52abd9ee47f8cdbf0a1ff | 940 | fileadmin-server | MIT License |
extension-compose/src/main/java/com/mapbox/maps/extension/compose/annotation/internal/generated/PolygonAnnotationManagerNode.kt | mapbox | 330,365,289 | false | {"Kotlin": 3982759, "Java": 98572, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2413, "CMake": 1201, "EJS": 1194} | // This file is generated.
package com.mapbox.maps.extension.compose.annotation.internal.generated
import com.mapbox.maps.MapboxStyleManager
import com.mapbox.maps.extension.compose.annotation.internal.BaseAnnotationNode
import com.mapbox.maps.plugin.annotation.generated.PolygonAnnotation
import com.mapbox.maps.plugin.annotation.generated.PolygonAnnotationManager
import com.mapbox.maps.plugin.annotation.generated.PolygonAnnotationOptions
internal class PolygonAnnotationManagerNode(
mapboxStyleManager: MapboxStyleManager,
val annotationManager: PolygonAnnotationManager,
) : BaseAnnotationNode(mapboxStyleManager) {
internal var currentAnnotations: MutableList<PolygonAnnotation> = mutableListOf()
var annotationClusterItems: List<PolygonAnnotationOptions> = emptyList()
set(value) {
if (currentAnnotations.isNotEmpty()) {
annotationManager.delete(currentAnnotations)
currentAnnotations.clear()
}
currentAnnotations.addAll(annotationManager.create(value))
field = value
}
override fun cleanUp() {
currentAnnotations.clear()
annotationManager.deleteAll()
annotationManager.onDestroy()
}
override fun getLayerIds(): List<String> {
return annotationManager.associatedLayers
}
override fun toString(): String {
return "PolygonAnnotationManagerNode(#${hashCode()})"
}
} | 181 | Kotlin | 131 | 472 | 2700dcaf18e70d23a19fc35b479bff6a2d490475 | 1,364 | mapbox-maps-android | Apache License 2.0 |
feature/main/data/src/main/kotlin/com/timplifier/boilerplate/feature/main/data/remote/paging/FooPagingSource.kt | timplifier | 699,196,884 | false | {"Kotlin": 52985} | package com.timplifier.boilerplate.feature.main.data.remote.paging
import com.timplifier.boilerplate.core.data.foundation.remote.PagingSource
import com.timplifier.boilerplate.feature.main.data.remote.dtos.FooDTO
import com.timplifier.boilerplate.feature.main.domain.models.FooModel
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.http.Url
class FooPagingSource(httpClient: HttpClient) : PagingSource<FooDTO, FooModel>({
httpClient.get(url = Url("foo")) {}.body()
}) | 0 | Kotlin | 0 | 2 | 34278902057924ea7a19439c3ff5f35487b497cf | 538 | Android-Boilerplate | Apache License 2.0 |
src/very_good_flame_game/android/app/src/main/kotlin/com/example/verygoodcore/MainActivity.kt | VeryGoodOpenSource | 542,165,026 | false | {"Dart": 98431, "C++": 34032, "CMake": 16560, "HTML": 7946, "Ruby": 5606, "Swift": 3954, "Shell": 2547, "C": 1430, "Kotlin": 446, "Objective-C": 76} | package com.example.verygoodflamegame
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 6 | Dart | 11 | 80 | 89e68dd232cc785b8c98dee32f6c0fb61b77ee96 | 134 | very_good_flame_game | MIT License |
app/src/main/java/com/moniapps/dictinonary/domain/model/Meaning.kt | MONIBUR2002 | 848,982,652 | false | {"Kotlin": 29381} | package com.moniapps.dictinonary.domain.model
data class Meaning(
val definition: Definition,
val partOfSpeech: String
) | 0 | Kotlin | 0 | 0 | 00d966a6038ed3beb9d7965ec41c83850f875239 | 129 | Dictionary | Apache License 2.0 |
src/main/kotlin/org/ethereum/discv5/EnrSimulator.kt | zilm13 | 240,323,938 | false | {"Gradle": 1, "Gradle Kotlin DSL": 1, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 43, "Java": 1, "XML": 1} | package org.ethereum.discv5
import io.libp2p.core.PeerId
import org.ethereum.discv5.core.MetaKey
import org.ethereum.discv5.core.Node
import org.ethereum.discv5.util.ByteArrayWrapper
import org.ethereum.discv5.util.RoundCounter
import org.ethereum.discv5.util.calcTraffic
import org.ethereum.discv5.util.formatTable
import java.math.BigInteger
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.roundToInt
/**
* Simulator which uses ENR attribute fields for advertisement
*/
class EnrSimulator {
fun runEnrUpdateSimulationUntilDistributed(peers: List<Node>, rounds: RoundCounter): List<Pair<Int, Int>> {
peers.forEach(Node::initTasks)
println("Making $SUBNET_SHARE_PCT% of peers with ENR from subnet")
val subnetNodes = peers.shuffled(RANDOM).take((peers.size * SUBNET_SHARE_PCT / 100.0).roundToInt())
subnetNodes.forEach {
it.updateEnr(
it.enr.seq.inc(),
HashMap<ByteArrayWrapper, ByteArrayWrapper>().apply {
put(MetaKey.SUBNET.of, SUBNET_13)
}
)
}
// TODO: Uncomment to test Ping Shower
// subnetNodes.forEach { it.firePingShower() }
val subnetIds = subnetNodes.map { it.enr.id }.toSet()
assert(subnetIds.isNotEmpty())
println("Total subnet peers count: ${subnetIds.size}")
val enrStats = ArrayList<Pair<Int, Int>>()
enrStats.add(calcEnrSubnetPeersStats(peers, subnetIds))
while (rounds.hasNext()) {
val current = rounds.next()
println("Simulating round #$current")
peers.forEach(Node::step)
enrStats.add(calcEnrSubnetPeersStats(peers, subnetIds))
// TODO: uncomment to print traffic stats on each step
// println("Cumulative traffic for ${subnetIds.size} advertised nodes: " +
// "${subnetNodes.map { node -> calcTraffic(node) }.sum()}"
// )
// TODO: comment to avoid quit on TARGET_PERCENTILE'% distribution reached
if (enrStats.last().second * 100.0 / (enrStats.last().first + enrStats.last().second) > TARGET_PERCENTILE) {
break
}
}
println("Cumulative traffic for ${subnetIds.size} advertised nodes: ${subnetNodes.map { node -> calcTraffic(node) }
.sum()}")
println("Cumulative fresh ENR queries: ${subnetNodes.map { node -> node.enrQueries.filter { it == 2L }.count() }
.sum()}")
return enrStats
}
fun runEnrSubnetSearch(
peers: List<Node>,
rounds: RoundCounter,
searcherCount: Int,
requireAds: Int
): List<Pair<Int, Int>> {
val currentRound = AtomicInteger(0)
val stepsSpent = AtomicInteger(0)
println("Making $searcherCount peers find at least $requireAds subnet peers each")
val searchers = peers.shuffled(RANDOM).take(searcherCount)
val remaining = AtomicInteger(searcherCount)
// TODO: comment to skip search
searchers.forEach {
// TODO: replace standard search to use experimental
// it.findEnrSubnetExperimental(SUBNET_13, requireAds) { set ->
it.findEnrSubnet(SUBNET_13, requireAds) { set ->
println("Peer ${it.enr.toId()} found subnet peers: ${set.map { it.toString() }.joinToString(",")}")
remaining.decrementAndGet()
}
}
while (rounds.hasNext()) {
val current = rounds.next()
currentRound.set(current)
println("Simulating round #${current + 1}")
if (remaining.get() == 0) {
println("$searcherCount peers found each $requireAds subnet peers")
break
}
peers.forEach(Node::step)
stepsSpent.addAndGet(remaining.get())
}
println("For $searcherCount searchers there were spent ${stepsSpent.get()} steps by searchers")
println("Total traffic for ${searchers.size} searchers: ${searchers.map { calcTraffic(it) }.sum()}")
return listOf(Pair(0, 0))
}
private fun changeSubnetForPeers(peers: List<Node>) {
peers.forEach {
it.updateEnr(
it.enr.seq.inc(),
HashMap<ByteArrayWrapper, ByteArrayWrapper>().apply {
put(MetaKey.SUBNET.of, SUBNET_13)
}
)
}
}
fun visualizeSubnetPeersStats(peers: List<Node>) {
val subnetIds = peers.filter { it.enr.seq == BigInteger.valueOf(2) }.map { it.enr.id }.toSet()
println("Peer knowledge stats")
println("===================================")
val header = "Peer #\t Subnet\t Known peers from subnet\n"
val stats = peers.map { peer ->
peer.enr.id.toHex().substring(0, 6) + "\t" +
(peer.enr.seq == BigInteger.valueOf(2)).let { if (it) "X" else " " } + "\t" +
peer.table.findAll()
.filter { subnetIds.contains(it.id) }
.map { it.id.toHex().substring(0, 6) + "(" + it.seq + ")" }
.joinToString(", ")
}.joinToString("\n")
println((header + stats).formatTable(true))
}
fun calcEnrSubnetPeersStats(peers: List<Node>, subnetIds: Set<PeerId>): Pair<Int, Int> {
val firstCounter = AtomicInteger(0)
val secondCounter = AtomicInteger(0)
peers.forEach { peer ->
peer.table.findAll()
.filter { subnetIds.contains(it.id) }
.forEach {
when (it.seq) {
BigInteger.ONE -> firstCounter.incrementAndGet()
BigInteger.valueOf(2) -> secondCounter.incrementAndGet()
}
}
}
// TODO: Uncomment to print share of sequence 2 peers on each step
// println("%: ${secondCounter.get() * 100.0 / (firstCounter.get() + secondCounter.get())}")
return Pair(firstCounter.get(), secondCounter.get())
}
fun printSubnetPeersStats(enrStats: List<Pair<Int, Int>>) {
println("Peer knowledge stats")
println("===================================")
val header = "Round #\t Peers known from 1st subnet\t from 2nd subnet\t Total subnet peer enrs\n"
val stats = enrStats.mapIndexed() { index, pair ->
val total = pair.first + pair.second
index.toString() + "\t" +
"%.2f".format(pair.first * 100.0 / total) + "%\t" +
"%.2f".format(pair.second * 100.0 / total) + "%\t" +
total
}.joinToString("\n")
println((header + stats).formatTable(true))
}
} | 0 | Kotlin | 1 | 3 | 49d817ab5155f8eea978ed9a74c0a2be32ced79c | 6,777 | discv5 | Apache License 2.0 |
src/Utils.kt | tomashavlicek | 571,148,715 | false | null | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt").readLines()
fun readInputAsText(name: String) = File("src", "$name.txt").readText()
fun readInputAsInts(name: String) = File("src", "$name.txt").readLines().map { it.toInt() }
/**
* Converts string to md5 hash.
*/
fun String.md5(): String = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16)
fun IntRange.containsFull(intRange: IntRange): Boolean {
return (this.first <= intRange.first && this.last >= intRange.last)
} | 0 | Kotlin | 0 | 0 | 899d30e241070903fe6ef8c4bf03dbe678310267 | 653 | aoc-2022-in-kotlin | Apache License 2.0 |
src/com/ketris/framework/io/MouseManager.kt | clone-tris | 180,143,011 | false | {"Kotlin": 34316} | package com.ketris.framework.io
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
object MouseManager : MouseAdapter(), IListenToThings<IListenToMouse> {
override val listeners = mutableListOf<IListenToMouse>()
override fun mousePressed(e: MouseEvent) {
// thou shalt not delete from a list while iterating it. so iterate over a copy instead
listeners.toList().forEach { listener ->
listener.mousePressed(e)
}
}
}
| 0 | Kotlin | 0 | 1 | 89dcd7f502846972bb612f46aef6e2a0462bd084 | 459 | ketris | Apache License 2.0 |
app/src/main/java/com/kotlin/education/android/easytodo/adapters/ImagesAdapter.kt | sravyasona | 226,566,335 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 26, "XML": 49, "Java": 1} | package com.kotlin.education.android.easytodo.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.education.android.easytodo.R
import com.kotlin.education.android.easytodo.activities.ImageViewerActivity
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.row_image.view.*
import java.io.File
/**
* The adapter for showing a list of images associated with a task.
* The definition of the adapter is usually in the activity class,
* however we will use this adapter twice.
* When adding or edition task we have a delete option. This option is however hidden
* when just showing images in detail.
*/
class ImagesAdapter(private val context: AppCompatActivity, private val images: ArrayList<String>, private val hideDelete: Boolean) : RecyclerView.Adapter<ImagesAdapter.ImageViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
return ImageViewHolder(LayoutInflater.from(context).inflate(R.layout.row_image, parent, false))
}
override fun getItemCount(): Int {
return images.size
}
override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
val image: String = images.get(position)
// load the image using Picasso.
Picasso.get().load(File(context.filesDir,image)).into(holder.image)
holder.itemView.setOnClickListener {
context.startActivity(ImageViewerActivity.createIntent(context, images, holder.adapterPosition))
}
if (!hideDelete) {
holder.delete.setOnClickListener {
images.removeAt(holder.adapterPosition)
notifyItemRemoved(holder.adapterPosition)
}
} else {
holder.delete.visibility = View.GONE
}
}
/**
* The ViewHolder class holds all the references of the views for each row.
* It extends RecyclerView.ViewHolder which needs only the View containing all the other elements.
*/
inner class ImageViewHolder(view: View) : RecyclerView.ViewHolder(view){
val image: ImageView = view.image
val delete: ImageButton = view.deleteImage
}
} | 1 | null | 1 | 1 | ab690df6d7381051c4a0ed80f8ce5d04b3637340 | 2,388 | easytodokotlinapp | The Unlicense |
app/src/main/java/io/github/zwieback/familyfinance/business/preference/activity/SettingsActivity.kt | zwieback | 111,666,879 | false | null | package io.github.zwieback.familyfinance.business.preference.activity
import android.os.Bundle
import androidx.fragment.app.FragmentTransaction
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceScreen
import io.github.zwieback.familyfinance.R
import io.github.zwieback.familyfinance.business.preference.fragment.SettingsFragment
import io.github.zwieback.familyfinance.core.activity.DataActivityWrapper
import io.github.zwieback.familyfinance.core.model.IBaseEntity
import io.reactivex.functions.Consumer
class SettingsActivity :
DataActivityWrapper(),
PreferenceFragmentCompat.OnPreferenceStartScreenCallback {
override val titleStringId: Int
get() = R.string.settings_activity_title
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
initFragment()
}
}
override fun setupContentView() {
setContentView(R.layout.activity_settings)
}
override fun onPreferenceStartScreen(
preferenceFragmentCompat: PreferenceFragmentCompat,
preferenceScreen: PreferenceScreen
): Boolean {
val fragment = createFragment().apply {
arguments = Bundle().apply {
putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, preferenceScreen.key)
}
}
supportFragmentManager
.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.settings_fragment, fragment, preferenceScreen.key)
.addToBackStack(preferenceScreen.key)
.commit()
return true
}
private fun initFragment() {
val fragment = createFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_fragment, fragment)
.commit()
}
private fun createFragment(): PreferenceFragmentCompat {
return SettingsFragment()
}
public override fun <E : IBaseEntity> loadEntity(
entityClass: Class<E>,
entityId: Int,
onSuccess: Consumer<E>,
onError: Consumer<in Throwable>
) {
super.loadEntity(entityClass, entityId, onSuccess, onError)
}
}
| 0 | Kotlin | 0 | 0 | a640c6ce73ca195f2ee5e41ed71fbf6169d9bb3e | 2,296 | FamilyFinance | Apache License 2.0 |
example/itest/src/test/kotlin/SmartUpdateTest.kt | holunda-io | 213,882,987 | false | {"Kotlin": 344278, "Java": 115142} | package io.holunda.camunda.bpm.data
import io.holunda.camunda.bpm.data.CamundaBpmData.stringVariable
import io.holunda.camunda.bpm.data.factory.VariableFactory
import org.camunda.bpm.engine.RuntimeService
import org.camunda.community.mockito.service.RuntimeServiceStubBuilder
import org.camunda.community.mockito.verify.RuntimeServiceVerification
import org.junit.jupiter.api.Test
import org.mockito.kotlin.mock
import java.util.*
/**
* Test to verify that update is not touching a variable is the value has not changed.
*/
class SmartUpdateTest {
companion object {
val MY_VAR: VariableFactory<String> = stringVariable("myVar")
}
@Test
fun should_not_touch_global() {
val execId = UUID.randomUUID().toString()
val runtime: RuntimeService = mock()
val verifier = RuntimeServiceVerification(runtime)
RuntimeServiceStubBuilder(runtime).defineAndInitialize(MY_VAR, "value").build()
MY_VAR.on(runtime, execId).update { "value" }
verifier.verifyGet(MY_VAR, execId)
verifier.verifyNoMoreInteractions()
}
@Test
fun should_not_touch_local() {
val execId = UUID.randomUUID().toString()
val runtime: RuntimeService = mock()
val verifier = RuntimeServiceVerification(runtime)
RuntimeServiceStubBuilder(runtime).defineAndInitializeLocal(MY_VAR, "value").build()
MY_VAR.on(runtime, execId).updateLocal { "value" }
verifier.verifyGetLocal(MY_VAR, execId)
verifier.verifyNoMoreInteractions()
}
}
| 20 | Kotlin | 5 | 29 | c0a139b1d495d95a0111b0cd263222e0d8772547 | 1,464 | camunda-bpm-data | Apache License 2.0 |
processor/src/main/kotlin/io/mcarle/konvert/processor/AnnotatedConverter.kt | mcarleio | 615,488,544 | false | {"Kotlin": 549656} | package io.mcarle.konvert.processor
import io.mcarle.konvert.converter.api.TypeConverter
fun interface AnnotatedConverterData {
fun toTypeConverters(): List<AnnotatedConverter>
}
interface AnnotatedConverter: TypeConverter {
val alreadyGenerated: Boolean
}
| 16 | Kotlin | 6 | 69 | 5861071a3f50006bbcde312a6fe4e35204a60a53 | 268 | konvert | Apache License 2.0 |
serializer/src/commonMain/kotlin/org/angproj/io/pipes/BufferedProtocol.kt | angelos-project | 486,974,547 | false | {"Kotlin": 128831, "C++": 8700, "C": 2529} | /**
* Copyright (c) 2022 by <NAME> <<EMAIL>>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* <NAME> - initial implementation
*/
package org.angproj.io.pipes
import org.angproj.io.buf.Buffer
interface BufferedProtocol : BaseProtocol {
fun getBuffer(sizeHint: Int): Buffer
fun bufferUpdated(nBytes: Int)
fun eofReceived(): Boolean
} | 0 | Kotlin | 0 | 0 | 049203e515e5230e8f2b4e5205e1a1d1d5ae4a31 | 614 | angelos-project-serializer | MIT License |
app/src/main/java/com/AERYZ/treasurefind/main/ui/victory/VictoryActivity.kt | eddyspaghette | 510,928,327 | false | null | package com.AERYZ.treasurefind.main.ui.victory
import android.content.Intent
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import com.AERYZ.treasurefind.R
import com.AERYZ.treasurefind.db.MyFirebase
import com.AERYZ.treasurefind.db.MyUser
import com.AERYZ.treasurefind.main.entry_point.MainActivity
import com.AERYZ.treasurefind.main.ui.hider_map.HiderMapActivity
import com.google.firebase.firestore.ktx.toObject
class VictoryActivity : AppCompatActivity() {
private var myFirebase = MyFirebase()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_victory)
val wid = intent.getStringExtra(HiderMapActivity.wid_KEY)!!
val tid = intent.getStringExtra(HiderMapActivity.tid_KEY)!!
val author_textview: TextView = findViewById(R.id.author_textview)
val profileImageView: ImageView = findViewById(R.id.victory_avatar)
val victory_imageview: ImageView = findViewById(R.id.victory_imageview)
val btn_btm: Button = findViewById(R.id.btn_btm)
val profileImageMutableLiveData = MutableLiveData(BitmapFactory.decodeResource(resources, R.drawable.tf_logo))
val srImageMutableLiveData = MutableLiveData(BitmapFactory.decodeResource(resources, R.drawable.tf_logo))
myFirebase.getProfileImage(this, wid, profileImageMutableLiveData)
myFirebase.getSRImage(this, tid, wid, srImageMutableLiveData)
profileImageMutableLiveData.observe(this) {
profileImageView.setImageBitmap(it)
}
srImageMutableLiveData.observe(this) {
victory_imageview.setImageBitmap(it)
}
myFirebase.getUserDocument(wid)
.get()
.addOnCompleteListener {
val myUser = it.result.toObject<MyUser>()
if (myUser != null) {
author_textview.text = myUser.userName
}
}
btn_btm.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
} | 8 | Kotlin | 0 | 2 | 680daf2f803778700c074d31addd1f576a6486a4 | 2,335 | TreasureFind | Apache License 2.0 |
example/src/main/kotlin/net/ormr/exabot/modules/greetings.kt | Olivki | 473,789,476 | false | {"Kotlin": 389470} | /*
* MIT License
*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Module
package net.ormr.exabot.modules
import dev.kord.common.entity.Snowflake
import kotlinx.serialization.Serializable
import net.ormr.kommando.commands.commands
import net.ormr.kommando.commands.execute
import net.ormr.kommando.commands.guildSlashCommand
import net.ormr.kommando.processor.Module
import net.ormr.kommando.processor.Tag
import net.ormr.kommando.utils.respond
import org.kodein.db.DB
import org.kodein.db.getById
import org.kodein.db.model.Id
fun greetings(@Tag guildId: Snowflake, db: DB) = commands {
guildSlashCommand("greet", "Greet the bot!", guildId) {
execute {
val deferred = interaction.deferEphemeralResponse()
val timesGreeted = db.getById<GreetedUser>(user.id)?.timesGreeted ?: 0
if (timesGreeted < 0) {
deferred.respond("This is the first time you've greeted me, hello!")
} else {
deferred.respond("Hello! You've greeted me ${timesGreeted + 1} times so far!")
}
db.put(GreetedUser(user.id, timesGreeted + 1))
}
}
}
@Serializable
data class GreetedUser(
@Id val id: Snowflake,
val timesGreeted: Int,
) | 3 | Kotlin | 0 | 2 | a3cbb08a332873cc783296c45c21cf950aed7ed5 | 2,309 | kommando | MIT License |
app/src/main/java/com/rezau_mehedi/prayerreminder/data/repository/UserPrefImpl.kt | imusshas | 807,444,645 | false | {"Kotlin": 58818} | package com.rezau_mehedi.prayerreminder.data.repository
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.rezau_mehedi.prayerreminder.core.Constants.DIVISIONS
import com.rezau_mehedi.prayerreminder.data.model.UserModel
import com.rezau_mehedi.prayerreminder.domain.repository.UserPref
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class UserPrefImpl (private val context: Context) : UserPref {
companion object {
private val PHONE_NO = stringPreferencesKey("PHONE_NO")
private val LOCATION = stringPreferencesKey("LOCATION")
private const val DATASTORE_NAME = "USER"
private val Context.datastore: DataStore<Preferences> by preferencesDataStore(name = DATASTORE_NAME)
}
override suspend fun saveUserModel(userModel: UserModel) {
context.datastore.edit { users ->
users[PHONE_NO] = userModel.phoneNo
users[LOCATION] = userModel.location
}
}
override fun getUserModel(): Flow<UserModel> = context.datastore.data.map { user ->
UserModel(
phoneNo = user[PHONE_NO] ?: "",
location = user[LOCATION] ?: DIVISIONS[0]
)
}
} | 0 | Kotlin | 0 | 0 | f4317e59ea5c33b3d06df451ebee0795e48e37dc | 1,439 | PrayerRemider | MIT License |
jar-filter/src/test/kotlin/net/corda/gradle/jarfilter/asm/ClassMetadata.kt | corda | 120,318,601 | false | {"Kotlin": 810473, "Java": 383021, "Groovy": 76556, "Shell": 4346, "Batchfile": 106} | package net.corda.gradle.jarfilter.asm
import kotlinx.metadata.ClassName
import kotlinx.metadata.KmClass
import net.corda.gradle.jarfilter.toInternalName
import net.corda.gradle.jarfilter.toPackageFormat
class ClassMetadata(metadata: KmClass) {
private val className: ClassName = metadata.name.toPackageFormat
val sealedSubclasses: List<ClassName> = metadata.sealedSubclasses.map {
it.toInternalName().toPackageFormat
}
val nestedClasses: List<ClassName> = metadata.nestedClasses.map { name ->
"$className\$$name"
}
}
| 17 | Kotlin | 35 | 24 | aeb324e3b9cb523f55bc32541688b2e90d920791 | 558 | corda-gradle-plugins | Apache License 2.0 |
app/src/main/java/com/example/admin/thebestapp/utils/Utils.kt | alekseytimoshchenko | 137,639,666 | false | {"Gradle": 3, "Ignore List": 2, "Markdown": 1, "Proguard": 1, "Kotlin": 42, "XML": 14, "Java": 4} | package com.example.admin.thebestapp.utils
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
class Utils (private val context: Context)
{
fun isConnectedToInternet(): Boolean
{
val connectivity = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if(connectivity != null)
{
val info = connectivity.allNetworkInfo
if(info != null) for(i in info.indices) if(info[i].state == NetworkInfo.State.CONNECTED)
{
return true
}
}
return false
}
} | 0 | Kotlin | 0 | 0 | 4892fa7ee44f5e09a8ad7af84424662eb8c15455 | 644 | MovieApp | Do What The F*ck You Want To Public License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.