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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
docs/src/pages/tegral-web-example.kt
|
utybo
| 491,247,680
| false
|
{"Kotlin": 1066259, "Nix": 2449, "Shell": 8}
|
// NOTE: this syntax is not available yet.
fun Routing.greeter() {
get("/hello") {
call.respond("Hello World!")
}
}
fun main() {
tegral {
put(Routing::greeter)
}
}
| 26
|
Kotlin
|
4
| 37
|
fa4284047f2ce7ba9ee78e92d8c67954716e9dcc
| 188
|
Tegral
|
Apache License 2.0
|
app/src/main/java/com/quizapp/presentation/update_password/UpdatePasswordViewModel.kt
|
AhmetOcak
| 591,704,302
| false
| null |
package com.quizapp.presentation.update_password
import android.content.SharedPreferences
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.quizapp.core.common.Response
import com.quizapp.core.common.getToken
import com.quizapp.domain.model.user.UpdatePasswordBody
import com.quizapp.domain.usecase.user.UpdatePasswordUseCase
import com.quizapp.presentation.utils.Messages
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class UpdatePasswordViewModel @Inject constructor(
private val updatePasswordUseCase: UpdatePasswordUseCase,
sharedPreferences: SharedPreferences
) : ViewModel() {
private val _updatePasswordState = MutableStateFlow<UpdatePasswordState>(UpdatePasswordState.Nothing)
val updatePasswordState = _updatePasswordState.asStateFlow()
private val _showChangePasswordErrorInpErrors = MutableStateFlow<ShowChangePasswordInputErrors>(ShowChangePasswordInputErrors.Nothing)
val showChangePasswordErrorInpErrors = _showChangePasswordErrorInpErrors.asStateFlow()
private var token: String? = null
var oldPassword by mutableStateOf("")
private set
var newPassword by mutableStateOf("")
private set
var confirmNewPassword by mutableStateOf("")
private set
var oldPasswordError by mutableStateOf(false)
private set
var newPasswordError by mutableStateOf(false)
private set
var confirmNewPasswordError by mutableStateOf(false)
private set
init {
token = sharedPreferences.getToken()
}
fun updateOldPasswordField(newValue: String) { oldPassword = newValue }
fun updateNewPasswordField(newValue: String) { newPassword = newValue }
fun updateConfirmNewPasswordField(newValue: String) { confirmNewPassword = newValue }
fun updatePassword() = viewModelScope.launch(Dispatchers.IO) {
if (checkChangePasswordInputs()) {
token?.let {
updatePasswordUseCase(
token = "Bearer $it",
updatePasswordBody = UpdatePasswordBody(
oldPassword = <PASSWORD>,
newPassword = <PASSWORD>
)
).collect() { response ->
when(response) {
is Response.Loading -> {
_updatePasswordState.value = UpdatePasswordState.Loading
}
is Response.Success -> {
_updatePasswordState.value = UpdatePasswordState.Success
}
is Response.Error -> {
_updatePasswordState.value = UpdatePasswordState.Error(response.errorMessage)
}
}
}
}
}
}
private fun checkChangePasswordInputs(): Boolean =
!checkIsPasswordsBlank() && checkIsPasswordConfirmed() && checkPasswordLength()
private fun checkIsPasswordsBlank(): Boolean {
return if (oldPassword.isBlank() || newPassword.isBlank() || confirmNewPassword.isBlank()) {
oldPasswordError = oldPassword.isBlank()
newPasswordError = <PASSWORD>()
confirmNewPasswordError = confirmNewPassword.isBlank()
_showChangePasswordErrorInpErrors.value = ShowChangePasswordInputErrors.Error(Messages.FILL)
true
} else {
_showChangePasswordErrorInpErrors.value = ShowChangePasswordInputErrors.Nothing
oldPasswordError = false
newPasswordError = false
confirmNewPasswordError = false
false
}
}
private fun checkIsPasswordConfirmed(): Boolean {
return if (newPassword == confirmNewPassword) {
_showChangePasswordErrorInpErrors.value = ShowChangePasswordInputErrors.Nothing
confirmNewPasswordError = false
true
} else {
_showChangePasswordErrorInpErrors.value = ShowChangePasswordInputErrors.Error(Messages.PASSWORD_MATCH)
confirmNewPasswordError = true
false
}
}
private fun checkPasswordLength(): Boolean {
return if (newPassword.length > 6) {
_showChangePasswordErrorInpErrors.value = ShowChangePasswordInputErrors.Nothing
confirmNewPasswordError = false
true
} else {
_showChangePasswordErrorInpErrors.value = ShowChangePasswordInputErrors.Error(Messages.LENGTH_PASSWORD)
confirmNewPasswordError = true
false
}
}
fun resetUpdatePasswordState() {
_updatePasswordState.value = UpdatePasswordState.Nothing
oldPassword = ""
newPassword = ""
confirmNewPassword = ""
}
fun resetUpdatePasswordInputState() { _showChangePasswordErrorInpErrors.value = ShowChangePasswordInputErrors.Nothing }
}
| 0
|
Kotlin
|
0
| 5
|
cc9d467fcd37cc88c9bbac315bd9aae920722bac
| 5,269
|
QuizApp
|
MIT License
|
data/src/test/java/com/github/cheapmon/balalaika/data/repositories/HistoryRepositoryTest.kt
|
cheapmon
| 233,464,548
| false
| null |
package com.github.cheapmon.balalaika.data.repositories
import com.github.cheapmon.balalaika.data.db.FakeHistoryItemDao
import com.github.cheapmon.balalaika.data.db.history.HistoryItemEntity
import com.github.cheapmon.balalaika.data.mappers.CategoryEntityToDataCategory
import com.github.cheapmon.balalaika.data.mappers.HistoryItemToHistoryItemEntity
import com.github.cheapmon.balalaika.data.mappers.HistoryItemWithCategoryToHistoryItem
import com.github.cheapmon.balalaika.model.Dictionary
import com.github.cheapmon.balalaika.model.HistoryItem
import com.github.cheapmon.balalaika.model.InstalledDictionary
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runBlockingTest
import org.junit.After
import org.junit.Assert
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
internal class HistoryRepositoryTest {
private val dao = FakeHistoryItemDao()
private val repository = HistoryRepository(
dao = dao,
toHistoryItem = HistoryItemWithCategoryToHistoryItem(CategoryEntityToDataCategory()),
fromHistoryItem = HistoryItemToHistoryItemEntity()
)
val dictionary = InstalledDictionary(
dictionary = Dictionary(
id = "dic_a",
version = 0,
name = "Dictionary A",
summary = "",
authors = "",
additionalInfo = ""
)
)
private val entities = listOf(
HistoryItemEntity(1, null, "dic_a", null, "query"),
HistoryItemEntity(2, null, "dic_a", null, "query"),
HistoryItemEntity(3, null, "dic_a", null, "something")
)
private val items = listOf(
HistoryItem(1, "query", null),
HistoryItem(2, "query", null),
HistoryItem(3, "something", null)
)
@After
fun after() {
dao.clear()
}
@Test
fun isInitiallyEmpty() = runBlockingTest {
Assert.assertTrue(repository.getHistoryItems(dictionary).first().isEmpty())
}
@Test
fun hasHistoryItems() = runBlockingTest {
for (entity in entities) dao.insert(entity)
Assert.assertEquals(
items,
repository.getHistoryItems(dictionary).first()
)
}
@Test
fun addToHistory() = runBlockingTest {
for (item in items) repository.addToHistory(dictionary, item)
Assert.assertEquals(
items.subList(1, 3),
repository.getHistoryItems(dictionary).first()
)
}
@Test
fun removeFromHistory() = runBlockingTest {
for (item in items) repository.addToHistory(dictionary, item)
repository.removeFromHistory(dictionary, items.first())
Assert.assertEquals(
items.subList(1, 3),
repository.getHistoryItems(dictionary).first()
)
}
@Test
fun clearHistory() = runBlockingTest {
for (item in items) repository.addToHistory(dictionary, item)
repository.clearHistory(dictionary)
Assert.assertTrue(repository.getHistoryItems(dictionary).first().isEmpty())
}
}
| 1
|
Kotlin
|
1
| 2
|
ced6f772ab5df750ce0005f58a276361554fde63
| 3,097
|
balalaika
|
Apache License 2.0
|
solar/src/main/java/com/chiksmedina/solar/broken/designtools/RulerPen.kt
|
CMFerrer
| 689,442,321
| false
|
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.broken.designtools
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.Round
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.broken.DesignToolsGroup
val DesignToolsGroup.RulerPen: ImageVector
get() {
if (_rulerPen != null) {
return _rulerPen!!
}
_rulerPen = Builder(
name = "RulerPen", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(22.0f, 7.0f)
verticalLineTo(6.0f)
curveTo(22.0f, 4.1144f, 22.0f, 3.1716f, 21.4142f, 2.5858f)
curveTo(20.8284f, 2.0f, 19.8856f, 2.0f, 18.0f, 2.0f)
lineTo(16.0f, 2.0f)
curveTo(14.1144f, 2.0f, 13.1716f, 2.0f, 12.5858f, 2.5858f)
curveTo(12.0f, 3.1716f, 12.0f, 4.1144f, 12.0f, 6.0f)
lineTo(12.0f, 18.0f)
curveTo(12.0f, 19.8856f, 12.0f, 20.8284f, 12.5858f, 21.4142f)
curveTo(13.1716f, 22.0f, 14.1144f, 22.0f, 16.0f, 22.0f)
horizontalLineTo(18.0f)
curveTo(19.8856f, 22.0f, 20.8284f, 22.0f, 21.4142f, 21.4142f)
curveTo(22.0f, 20.8284f, 22.0f, 19.8856f, 22.0f, 18.0f)
verticalLineTo(11.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(12.0f, 12.0f)
horizontalLineTo(14.0f)
moveTo(12.0f, 6.0f)
lineTo(14.0f, 6.0f)
moveTo(12.0f, 18.0f)
horizontalLineTo(14.0f)
moveTo(12.0f, 15.0f)
lineTo(15.0f, 15.0f)
moveTo(12.0f, 9.0f)
lineTo(15.0f, 9.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(2.0f, 6.0f)
lineTo(2.0f, 5.0f)
curveTo(2.0f, 3.3431f, 3.3431f, 2.0f, 5.0f, 2.0f)
curveTo(6.6568f, 2.0f, 8.0f, 3.3431f, 8.0f, 5.0f)
verticalLineTo(6.0f)
moveTo(2.0f, 6.0f)
curveTo(2.0f, 6.0f, 3.125f, 7.0f, 5.0f, 7.0f)
curveTo(6.875f, 7.0f, 8.0f, 6.0f, 8.0f, 6.0f)
moveTo(2.0f, 6.0f)
lineTo(2.0f, 10.5462f)
moveTo(8.0f, 6.0f)
verticalLineTo(15.1935f)
curveTo(8.0f, 15.8161f, 8.0f, 16.1275f, 7.9622f, 16.433f)
curveTo(7.9177f, 16.7934f, 7.834f, 17.1479f, 7.7127f, 17.4902f)
curveTo(7.6098f, 17.7804f, 7.4706f, 18.0589f, 7.1921f, 18.6158f)
lineTo(6.0121f, 20.9759f)
moveTo(6.0121f, 20.9759f)
lineTo(5.7236f, 21.5528f)
curveTo(5.5866f, 21.8269f, 5.3064f, 22.0f, 5.0f, 22.0f)
curveTo(4.6936f, 22.0f, 4.4134f, 21.8269f, 4.2764f, 21.5528f)
lineTo(3.9879f, 20.9759f)
moveTo(6.0121f, 20.9759f)
horizontalLineTo(3.9879f)
moveTo(3.9879f, 20.9759f)
lineTo(2.8079f, 18.6158f)
curveTo(2.5294f, 18.0589f, 2.3902f, 17.7804f, 2.2873f, 17.4902f)
curveTo(2.166f, 17.1479f, 2.0823f, 16.7934f, 2.0378f, 16.433f)
curveTo(2.0f, 16.1275f, 2.0f, 15.8162f, 2.0f, 15.1935f)
lineTo(2.0f, 14.3224f)
}
}
.build()
return _rulerPen!!
}
private var _rulerPen: ImageVector? = null
| 0
|
Kotlin
|
0
| 0
|
3414a20650d644afac2581ad87a8525971222678
| 4,608
|
SolarIconSetAndroid
|
MIT License
|
src/main/kotlin/github/samyycx/fisherman/modules/gameconfig/fishgroup/FishGroupParser.kt
|
samyycX
| 742,795,853
| false
|
{"Kotlin": 42404, "Java": 351}
|
package github.samyycx.fisherman.modules.gameconfig.fishgroup
import org.bukkit.configuration.ConfigurationSection
object FishGroupParser {
fun parseFromSection(section: ConfigurationSection): FishGroup {
val id = section.name
val condition = section.getStringList("condition")
val items = section.getStringList("items")
return FishGroup(id, condition, items)
}
}
| 0
|
Kotlin
|
0
| 0
|
8336b73de9e8461612791651aec6ef9f246e92ac
| 410
|
Fisherman
|
MIT License
|
action/runner/src/test/kotlin/org/archguard/runner/ActionManifestManagerTest.kt
|
archguard
| 565,163,416
| false
| null |
package org.archguard.runner
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import java.io.File
class ActionManifestManagerTest {
@Test
fun `should load action manifest`() {
val source = this.javaClass.classLoader.getResource("pipeline/basic.yml")!!.path
val actionManifest = ActionManifestManager().load(File(source).readText())
actionManifest.name shouldBe "ArchGuard 3.0 - CodeDB"
actionManifest.config.server.url shouldBe "http://localhost:8084"
}
}
| 2
|
Kotlin
|
1
| 11
|
3b5b1acefcf8b94276b38d9133bfe0b916d4a810
| 523
|
codedb-poc
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonerevents/repository/SqlRepository.kt
|
ministryofjustice
| 526,285,463
| false
| null |
package uk.gov.justice.digital.hmpps.prisonerevents.repository
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Repository
import java.sql.ResultSet
import java.time.LocalDate
import java.time.LocalTime
@Repository
class SqlRepository(private val jdbcTemplate: NamedParameterJdbcTemplate) {
fun getNomsIdFromOffender(offenderId: Long): Collection<String> {
return jdbcTemplate.query(
GET_OFFENDER,
MapSqlParameterSource().addValue("offenderId", offenderId)
) { resultSet: ResultSet, _: Int -> resultSet.getString("OFFENDER_ID_DISPLAY") }
}
fun getNomsIdFromBooking(bookingId: Long): Collection<String> {
return jdbcTemplate.query(
GET_BOOKING,
MapSqlParameterSource().addValue("bookingId", bookingId)
) { resultSet: ResultSet, _: Int -> resultSet.getString("OFFENDER_ID_DISPLAY") }
}
fun getMovement(bookingId: Long, sequenceNumber: Int): Collection<Movement> {
return jdbcTemplate.query(
GET_MOVEMENT_BY_BOOKING_AND_SEQUENCE,
MapSqlParameterSource()
.addValue("bookingId", bookingId)
.addValue("sequenceNumber", sequenceNumber)
) { resultSet: ResultSet, _: Int ->
Movement(
resultSet.getString("OFFENDER_NO"),
resultSet.getString("FROM_AGENCY"),
resultSet.getString("TO_AGENCY"),
resultSet.getString("MOVEMENT_TYPE"),
resultSet.getString("DIRECTION_CODE"),
resultSet.getDate("MOVEMENT_DATE").toLocalDate(),
resultSet.getTime("MOVEMENT_TIME").toLocalTime(),
)
}
}
companion object {
val GET_OFFENDER = """
SELECT OFFENDER_ID_DISPLAY
FROM OFFENDERS
WHERE OFFENDER_ID = :offenderId
""".trimIndent()
val GET_BOOKING = """
SELECT OFFENDER_ID_DISPLAY
FROM OFFENDER_BOOKINGS
INNER JOIN OFFENDERS ON OFFENDER_BOOKINGS.OFFENDER_ID = OFFENDERS.OFFENDER_ID
WHERE OFFENDER_BOOK_ID = :bookingId
""".trimIndent()
val GET_MOVEMENT_BY_BOOKING_AND_SEQUENCE = """
SELECT OFFENDERS.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OEM.FROM_AGY_LOC_ID AS FROM_AGENCY,
OEM.TO_AGY_LOC_ID AS TO_AGENCY,
OEM.MOVEMENT_DATE,
OEM.MOVEMENT_TIME,
OEM.MOVEMENT_TYPE,
OEM.DIRECTION_CODE
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID
INNER JOIN OFFENDERS ON OFFENDERS.OFFENDER_ID = OB.OFFENDER_ID
WHERE OEM.MOVEMENT_SEQ = :sequenceNumber
AND OEM.OFFENDER_BOOK_ID = :bookingId
""".trimIndent()
}
}
data class Movement(
val offenderNo: String?,
val fromAgency: String? = null,
val toAgency: String? = null,
val movementType: String? = null,
val directionCode: String? = null,
val movementDate: LocalDate? = null,
val movementTime: LocalTime? = null,
)
| 2
|
Kotlin
|
0
| 0
|
f4e8040096cc70bd07387032f76f2ff70ae2eb43
| 2,960
|
hmpps-prisoner-events
|
MIT License
|
api/src/main/kotlin/com/example/api/test/TestController.kt
|
PARKPARKWOO
| 737,782,254
| false
|
{"Kotlin": 209522}
|
package com.example.api.test
import com.example.api.common.annotation.PublicEndPoint
import com.example.common.log.Log
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/v1/test")
class TestController : Log {
@GetMapping
@PublicEndPoint
fun hello(): String {
log.info("hi")
return "Hello"
}
}
| 10
|
Kotlin
|
0
| 0
|
9bb2b77dfede5968affb9590186136acd160683f
| 496
|
barbellrobot-backend
|
Apache License 2.0
|
compiler/src/main/java/cz/levinzonr/saferoute/processor/codegen/NavControllerExtensionsBuilder.kt
|
levinzonr
| 372,225,040
| false
| null |
package cz.levinzonr.saferoute.processor.codegen
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import cz.levinzonr.saferoute.annotations.Route
import cz.levinzonr.saferoute.processor.constants.ClassNames
import cz.levinzonr.saferoute.processor.models.ModelData
import cz.levinzonr.saferoute.processor.models.RouteData
internal class NavControllerExtensionsBuilder(
private val modelData: ModelData
) {
fun build(): FileSpec {
val builder = FileSpec.builder(modelData.packageName, "NavController+RouteActions")
modelData.routes.forEach { builder.addFunction(createActionFunSpec(it)) }
return builder.build()
}
private fun createActionFunSpec(route: RouteData) : FunSpec {
val arguments = route.arguments.joinToString(",") { it.name }
return FunSpec.builder("navigateTo${route.name.capitalize()}")
.addParameters(route.arguments.map { it.toParamSpec() })
.receiver(ClassNames.NavController)
.returns(Unit::class)
.addCode("navigate(RoutesActions.to${route.name.capitalize()}($arguments))")
.build()
}
}
| 7
|
Kotlin
|
0
| 40
|
3d652d2b1f80a5698df0f4579cc49747ed07d13c
| 1,156
|
compose-safe-routing
|
Apache License 2.0
|
ERMSEmployee/src/main/java/com/kust/ermsemployee/di/ViewModelLevel.kt
|
sabghat90
| 591,653,827
| false
|
{"Kotlin": 583902, "HTML": 87217}
|
package com.kust.ermsemployee.di
import android.content.SharedPreferences
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.StorageReference
import com.google.gson.Gson
import com.kust.ermsemployee.data.repository.AttendanceRepository
import com.kust.ermsemployee.data.repository.AttendanceRepositoryImpl
import com.kust.ermsemployee.data.repository.ChatRepository
import com.kust.ermsemployee.data.repository.ChatRepositoryImpl
import com.kust.ermsemployee.data.repository.CompanyRepository
import com.kust.ermsemployee.data.repository.CompanyRepositoryImpl
import com.kust.ermsemployee.data.repository.ComplaintRepository
import com.kust.ermsemployee.data.repository.ComplaintRepositoryImpl
import com.kust.ermsemployee.data.repository.EmployeeRepository
import com.kust.ermsemployee.data.repository.EmployeeRepositoryImpl
import com.kust.ermsemployee.data.repository.EventRepository
import com.kust.ermsemployee.data.repository.EventRepositoryImpl
import com.kust.ermsemployee.data.repository.TaskRepository
import com.kust.ermsemployee.data.repository.TaskRepositoryImpl
import com.kust.ermslibrary.utils.FirebaseStorageConstants
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.scopes.ViewModelScoped
import javax.inject.Named
@Module
@InstallIn(ViewModelComponent::class)
object ViewModelLevel {
@Provides
@ViewModelScoped
fun provideChatRepository(
database: FirebaseDatabase,
auth: FirebaseAuth
) : ChatRepository {
return ChatRepositoryImpl(database, auth)
}
@Provides
@ViewModelScoped
fun provideAttendanceRepository(
firebaseDatabase: FirebaseDatabase,
auth: FirebaseAuth,
sharedPreferences: SharedPreferences
) : AttendanceRepository {
return AttendanceRepositoryImpl(firebaseDatabase, auth, sharedPreferences)
}
@Provides
@ViewModelScoped
fun provideTaskRepository(
database: FirebaseFirestore,
firebaseAuth: FirebaseAuth,
sharedPreferences: SharedPreferences
) : TaskRepository {
return TaskRepositoryImpl(database,firebaseAuth, sharedPreferences)
}
@Provides
@ViewModelScoped
fun provideEventRepository(
database: FirebaseFirestore,
sharedPreferences: SharedPreferences
) : EventRepository {
return EventRepositoryImpl(database, sharedPreferences)
}
@Provides
@ViewModelScoped
fun provideEmployeeRepository(
auth: FirebaseAuth,
database: FirebaseFirestore,
@Named(FirebaseStorageConstants.EMPLOYEE_PROFILE)
firebaseStorage: StorageReference,
sharedPreferences: SharedPreferences,
gson: Gson
) : EmployeeRepository {
return EmployeeRepositoryImpl(auth, database, firebaseStorage, sharedPreferences, gson)
}
@Provides
@ViewModelScoped
fun provideComplaintRepository(
database: FirebaseFirestore,
auth: FirebaseAuth
) : ComplaintRepository {
return ComplaintRepositoryImpl(database, auth)
}
@Provides
@ViewModelScoped
fun provideCompanyRepository (
database: FirebaseFirestore,
sharedPreferences: SharedPreferences
) : CompanyRepository {
return CompanyRepositoryImpl(database, sharedPreferences)
}
}
| 1
|
Kotlin
|
0
| 2
|
56497f553ddcbbe2bdbafb987caa40cb44d552e8
| 3,523
|
ERMS
|
MIT License
|
build-logic/convention/src/main/kotlin/pl/droidsonroids/composekit/utils/Libs.kt
|
DroidsOnRoids
| 514,214,122
| false
|
{"Kotlin": 105234}
|
package pl.droidsonroids.composekit.utils
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalog
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.getByType
internal val Project.libs: VersionCatalog
get() = project.extensions.getByType<VersionCatalogsExtension>().named("libs")
| 29
|
Kotlin
|
0
| 0
|
61097320067374bafc35eb333c38d8e8a4497637
| 342
|
ComposeKit
|
MIT License
|
examples/graphql/src/main/kotlin/example/spring/boot/graphql/api/BookController.kt
|
test-automation-in-practice
| 506,693,260
| false
| null |
package example.spring.boot.graphql.api
import example.spring.boot.graphql.business.Book
import example.spring.boot.graphql.business.BookCollection
import example.spring.boot.graphql.business.BookRecord
import example.spring.boot.graphql.business.Isbn
import example.spring.boot.graphql.business.Page
import example.spring.boot.graphql.business.Pagination
import example.spring.boot.graphql.business.Title
import org.springframework.graphql.data.method.annotation.Argument
import org.springframework.graphql.data.method.annotation.MutationMapping
import org.springframework.graphql.data.method.annotation.QueryMapping
import org.springframework.stereotype.Controller
import java.util.UUID
@Controller
class BookController(
private val collection: BookCollection
) {
@MutationMapping
fun addBook(@Argument title: Title, @Argument isbn: Isbn): BookRepresentation =
collection.add(Book(title, isbn)).toRepresentation()
@QueryMapping
fun getAllBooks(@Argument pagination: Pagination): Page<BookRepresentation> =
collection.getAll(pagination).map(BookRecord::toRepresentation)
@QueryMapping
fun getBookById(@Argument id: UUID): BookRepresentation? =
collection.get(id)?.toRepresentation()
@MutationMapping
fun deleteBookById(@Argument id: UUID): Boolean =
collection.delete(id)
}
| 0
|
Kotlin
|
0
| 17
|
fbc2a5931c9e27a80ec78bd69db60b1ee25ee671
| 1,349
|
cnt-spring-boot
|
Apache License 2.0
|
src/main/kotlin/nl/toefel/blog/aggregatefunctions/dto/UserStatistic.kt
|
toefel18
| 239,209,052
| false
| null |
package nl.toefel.blog.aggregatefunctions.dto
data class UserStatistic(
val fromUser: String,
val totalLikes: Long,
val totalDislikes: Long)
| 0
|
Kotlin
|
0
| 0
|
73af966500cc63372b005c611c78212f6096e9e2
| 153
|
kotlin-exposed-blog-aggregate-functions
|
MIT License
|
src/main/kotlin/klev/db/wishes/Status.kt
|
torland-klev
| 822,687,443
| false
|
{"Kotlin": 73616}
|
package klev.db.wishes
enum class Status {
OPEN,
SELECTED,
FULFILLED,
DELETED,
}
| 0
|
Kotlin
|
0
| 0
|
55b99f3fb843763b9a4d2363f97879c924bd6ea4
| 98
|
gavelista-api
|
MIT License
|
src/main/kotlin/no/nav/helse/domene/person/PersonService.kt
|
navikt
| 157,684,573
| false
|
{"Kotlin": 756905, "Shell": 328, "Dockerfile": 47}
|
package no.nav.helse.domene.person
import arrow.core.flatMap
import no.nav.helse.Feilårsak
import no.nav.helse.arrow.sequenceU
import no.nav.helse.domene.AktørId
import no.nav.helse.oppslag.person.PersonClient
import no.nav.tjeneste.virksomhet.person.v3.binding.HentGeografiskTilknytningPersonIkkeFunnet
import no.nav.tjeneste.virksomhet.person.v3.binding.HentGeografiskTilknytningSikkerhetsbegrensing
import no.nav.tjeneste.virksomhet.person.v3.binding.HentPersonPersonIkkeFunnet
import no.nav.tjeneste.virksomhet.person.v3.binding.HentPersonSikkerhetsbegrensning
import no.nav.tjeneste.virksomhet.person.v3.informasjon.AktoerId
import no.nav.tjeneste.virksomhet.person.v3.metadata.Endringstyper
import org.slf4j.LoggerFactory
class PersonService(private val personClient: PersonClient) {
companion object {
private val aktiveEndringstyper = listOf(Endringstyper.NY, Endringstyper.ENDRET, null)
private val log = LoggerFactory.getLogger(PersonService::class.java)
}
fun personInfo(aktørId: AktørId) =
personClient.personMedAdresse(aktørId).toEither { err ->
log.error("Error while doing person lookup", err)
when (err) {
is HentPersonPersonIkkeFunnet -> Feilårsak.IkkeFunnet
is HentPersonSikkerhetsbegrensning -> Feilårsak.FeilFraTjeneste
else -> Feilårsak.FeilFraTjeneste
}
}.map {
PersonMapper.toPerson(it)
}
fun geografiskTilknytning(aktørId: AktørId) =
personClient.geografiskTilknytning(aktørId).toEither { err ->
log.error("Error while doing geografisk tilknytning lookup", err)
when (err) {
is HentGeografiskTilknytningPersonIkkeFunnet -> Feilårsak.IkkeFunnet
is HentGeografiskTilknytningSikkerhetsbegrensing -> Feilårsak.FeilFraTjeneste
else -> Feilårsak.FeilFraTjeneste
}
}.map {
GeografiskTilknytningMapper.tilGeografiskTilknytning(it)
}
fun barn(aktørId: AktørId) =
personClient.familierelasjoner(aktørId).toEither { error ->
log.error("Feil ved oppslag på familierelasjoner", error)
when (error) {
is HentPersonPersonIkkeFunnet -> Feilårsak.IkkeFunnet
is HentPersonSikkerhetsbegrensning -> Feilårsak.FeilFraTjeneste
else -> Feilårsak.FeilFraTjeneste
}
}.map { familierelasjoner ->
familierelasjoner
.filter { "BARN" == it.tilRolle.value }
.filter { aktiveEndringstyper.contains(it.endringstype) }
.map { AktørId((it.tilPerson.aktoer as AktoerId).aktoerId) }
}.flatMap { barnAktørIder ->
barnAktørIder.map { barnAktørId ->
personClient.person(barnAktørId).toEither { err ->
log.error("Feil ved oppslag på barn", err)
when (err) {
is HentGeografiskTilknytningPersonIkkeFunnet -> Feilårsak.IkkeFunnet
is HentGeografiskTilknytningSikkerhetsbegrensing -> Feilårsak.FeilFraTjeneste
else -> Feilårsak.FeilFraTjeneste
}
}
}.sequenceU()
}.map { barn ->
barn.map { PersonMapper.toBarn(it) }
}
}
| 0
|
Kotlin
|
0
| 1
|
ed034e9b111afd53715c410029b67c8b06aaf702
| 3,458
|
helse-sparkel
|
MIT License
|
src/main/kotlin/com/deflatedpickle/rawky/component/ToolOptions.kt
|
DeflatedPickle
| 197,672,095
| false
| null |
/* Copyright (c) 2020 DeflatedPickle under the MIT license */
package com.deflatedpickle.rawky.component
import com.deflatedpickle.rawky.api.annotations.Options
import com.deflatedpickle.rawky.api.component.Component
import com.deflatedpickle.rawky.util.Components
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import javax.swing.BorderFactory
import javax.swing.JLabel
import javax.swing.JScrollPane
import javax.swing.JTabbedPane
import javax.swing.SwingConstants
import org.jdesktop.swingx.JXPanel
class ToolOptions : Component() {
object StickEast : GridBagConstraints() {
init {
anchor = EAST
}
}
object FillHorizontalFinishLine : GridBagConstraints() {
init {
fill = HORIZONTAL
weightx = 1.0
gridwidth = REMAINDER
insets = Insets(2, 2, 2, 2)
}
}
object FillHorizontal : GridBagConstraints() {
init {
fill = BOTH
weightx = 1.0
}
}
object FinishLine : GridBagConstraints() {
init {
gridwidth = REMAINDER
}
}
val tabList = arrayOfNulls<JXPanel>(3).toMutableList()
val tabbedPane = JTabbedPane().apply {
this.tabLayoutPolicy = JTabbedPane.SCROLL_TAB_LAYOUT
// Tool options are singletons, we need to relayout the panel on-change in case any settings have been changed
this.addChangeListener { relayout(this.selectedIndex) }
for ((groupIndex, group) in Toolbox.Group.values().withIndex()) {
this.addTab(group.name.toLowerCase().capitalize(), JScrollPane(JXPanel().apply {
this.layout = GridBagLayout()
this.scrollableTracksViewportWidth = true
this.scrollableTracksViewportHeight = false
tabList[groupIndex] = this
}).apply { border = BorderFactory.createEmptyBorder() })
}
}
init {
this.add(tabbedPane)
}
fun relayout(tabIndex: Int) {
with(this.tabList[tabIndex]!!) {
this.removeAll()
this.add(JLabel(Components.toolbox.toolIndexList[tabIndex]!!::class.java.simpleName.capitalize() + ":").apply {
font = font.deriveFont(14f)
horizontalAlignment = SwingConstants.CENTER
}, FillHorizontalFinishLine)
for (clazz in Components.toolbox.toolIndexList[tabIndex]!!::class.java.declaredClasses) {
if (clazz.annotations.map { it.annotationClass == Options::class }.contains(true)) {
for (field in clazz.fields) {
if (field.name != "INSTANCE") {
Components.processAnnotations(this, field)
}
}
for (subClazz in clazz.classes) {
Components.processAnnotations(this, subClazz)
}
}
}
this.invalidate()
this.revalidate()
this.repaint()
}
}
}
| 20
|
Kotlin
|
5
| 23
|
7fe5d6ad2953a4a0ef5d7f865bee476a0fb15d0a
| 3,099
|
Rawky
|
MIT License
|
data/tmdbApi/src/main/java/com/ant/tmdb/old/TmdbImageOptions.kt
|
toaderandrei
| 786,415,615
| false
|
{"Kotlin": 214427, "Java": 376}
|
package com.ant.tmdb.old
class ImageUrlProvider(private val imageSize: String, private val path: String? = null) {
companion object {
const val IMAGE_URL = "https://image.tmdb.org/t/p/"
}
fun imageUrl(): String {
val stringBuilder: StringBuilder = StringBuilder()
stringBuilder.append(IMAGE_URL)
.append(imageSize)
.append("/")
.append(path)
return stringBuilder.toString()
}
}
enum class BackdropSizes(val wSize: String) {
W300("w300"),
W780("w780"),
W1280("w1280"),
ORIGINAL("original"),
}
enum class LogoSizes(val wSize: String) {
W45("w45"),
W92("w92"),
W154("w154"),
W185("w185"),
W300("w300"),
W500("w500"),
ORIGINAL("original")
}
enum class PosterSizes(val wSize: String) {
W92("w92"),
W154("w154"),
W185("w185"),
W342("w342"),
W500("w500"),
W780("w780"),
ORIGINAL("original")
}
| 0
|
Kotlin
|
0
| 0
|
2b66ec4a0f2ca5161c3e9e1b687459a8c972edaa
| 947
|
popular-movies-kt
|
The Unlicense
|
compression/src/commonTest/kotlin/pw/binom/compression/zlib/ZlibTest.kt
|
caffeine-mgn
| 182,165,415
| false
|
{"C": 13079003, "Kotlin": 1913743, "C++": 200, "Shell": 88}
|
package pw.binom.compression.zlib
import pw.binom.ByteBuffer
import kotlin.test.Test
import kotlin.test.assertEquals
class ZlibTest {
@Test
fun test() {
val sourceData = ByteBuffer.alloc(30)
repeat(sourceData.capacity) {
sourceData.put(10)
}
sourceData.clear()
val compressed = ByteBuffer.alloc(sourceData.capacity * 2)
val def = Deflater(6, true, true)
while (true) {
if (def.deflate(sourceData, compressed) <= 0)
break
}
while (true) {
if (!def.flush(compressed))
break
}
def.finish()
while (true) {
if (!def.flush(compressed))
break
}
compressed.flip()
(compressed.position until compressed.limit).forEach {
assertEquals(TestData.COMPRESSED[it], compressed[it])
}
println("compressed size: ${compressed.remaining}")
assertEquals(11, compressed.remaining)
(compressed.position until compressed.limit).forEach {
println("$it->${compressed[it]}")
}
val inf = Inflater()
val uncompressed = ByteBuffer.alloc(sourceData.capacity * 2)
while (true) {
if (inf.inflate(compressed, uncompressed) <= 0)
break
}
inf.end()
uncompressed.flip()
assertEquals(sourceData.capacity, uncompressed.remaining)
assertArrayEquals(sourceData, 0, uncompressed, 0, sourceData.capacity)
}
}
fun assertArrayEquals(expected: ByteBuffer, expectedOffset: Int, actual: ByteBuffer, actualOffset: Int, length: Int) {
for (i in expectedOffset until expectedOffset + length) {
assertEquals(expected[i], actual[i - expectedOffset + actualOffset], "On Element ${i - expectedOffset}")
}
}
| 7
|
C
|
2
| 59
|
580ff27a233a1384273ef15ea6c63028dc41dc01
| 1,858
|
pw.binom.io
|
Apache License 2.0
|
androidunsplash/src/main/java/com/keenencharles/unsplash/models/Result.kt
|
KeenenCharles
| 90,798,987
| false
| null |
package com.keenencharles.unsplash.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class Result(
var id: String? = null,
var width: Int? = null,
var height: Int? = null,
var color: String? = null,
var likes: Int? = null,
var user: User? = null,
var urls: Urls? = null,
var links: Links? = null,
val categories: List<Category>? = null,
@SerializedName("current_user_collections") var currentUserCollections: List<Collection>? = null,
@SerializedName("liked_by_user") var likedByUser: Boolean? = null,
@SerializedName("created_at") var createdAt: String? = null,
@SerializedName("updated_at") var updatedAt: String? = null
) : Parcelable
| 0
|
Kotlin
|
22
| 87
|
37b41a1a2f3669001e7876dfa53b6a664940c419
| 830
|
AndroidUnplash
|
MIT License
|
library/src/test/kotlin/ru/kontur/kinfra/kfixture/data/objects/random1/Electricity.kt
|
skbkontur
| 212,616,062
| false
| null |
package ru.kontur.kinfra.kfixture.data.objects.random1
data class Electricity(
val act: Int,
val adult: Boolean,
val afraid: Int,
val all: Int,
val alphabet: Boolean,
val among: Double,
val anyway: Boolean,
val appearance: Boolean,
val apple: String,
val arrow: String,
val aside: String,
val baby: String,
val barn: Double,
val basis: String,
val bean: Boolean,
val beauty: Boolean,
val began: String,
val bill: Double,
val blanket: Boolean,
val breathing: Int,
val bright: String,
val building: String,
val carry: Boolean,
val cave: String,
val chain: String,
val change: String,
val choose: String,
val clay: String,
val close: Boolean,
val cloth: Double,
val composition: Double,
val consist: Double,
val continent: Int,
val cost: String,
val course: Double,
val cowboy: Double,
val cream: Boolean,
val describe: String,
val design: Boolean,
val discover: Double,
val doctor: String,
val dog: Boolean,
val dollar: Int,
val driver: Boolean,
val during: Boolean,
val dust: String,
val early: Int,
val egg: String,
val explore: Boolean,
val expression: String,
val felt: Int,
val `field`: Double,
val finish: Boolean,
val fish: Boolean,
val flag: Double,
val forget: String,
val former: Double,
val forty: String,
val four: Boolean,
val fully: Boolean,
val gift: Int,
val glad: Double,
val gold: Boolean,
val golden: String,
val grew: Double,
val grown: String,
val habit: String,
val handle: String,
val happily: String,
val harbor: Int,
val heading: Int,
val hearing: Int,
val hidden: Boolean,
val higher: Double,
val history: Boolean,
val home: String,
val honor: Double,
val improve: String,
val independent: String,
val influence: Double,
val instead: Int,
val involved: Int,
val jar: String,
val lack: Int,
val lady: String,
val laid: Boolean,
val lake: Boolean,
val lead: Int,
val learn: Int,
val leather: Boolean,
val led: Double,
val length: Boolean,
val lift: Double,
val liquid: Int,
val lose: Double,
val lying: String,
val main: Boolean,
val manner: Boolean,
val map: String,
val means: Boolean,
val melted: Boolean,
val negative: String,
val nervous: String,
val nest: Int,
val news: String,
val newspaper: Double,
val noun: Int,
val observe: Boolean,
val official: String,
val oldest: Boolean,
val on: String,
val one: Boolean,
val orange: Double,
val ordinary: Boolean,
val original: Int,
val over: String,
val pack: Double,
val page: Double,
val park: String,
val pile: Boolean,
val pitch: Int,
val plan: Boolean,
val plant: Boolean,
val political: Int,
val positive: Boolean,
val printed: Double,
val quiet: String,
val race: Boolean,
val railroad: String,
val ran: Int,
val recently: Boolean,
val refer: Boolean,
val relationship: Int,
val result: Boolean,
val route: Double,
val sat: Boolean,
val say: String,
val scared: String,
val science: String,
val see: Double,
val sell: Boolean,
val settle: String,
val settlers: Int,
val seven: Boolean,
val shown: Int,
val sides: Boolean,
val single: Boolean,
val sitting: Boolean,
val sleep: String,
val slept: Boolean,
val slight: Boolean,
val softly: String,
val solve: Double,
val soon: Boolean,
val source: Boolean,
val southern: Int,
val speed: Int,
val spent: String,
val state: Int,
val straw: String,
val stream: String,
val stretch: String,
val tail: String,
val tape: String,
val teacher: Teacher,
val temperature: String,
val them: Boolean,
val then: String,
val `this`: Double,
val though: String,
val through: Boolean,
val thumb: Double,
val traffic: String,
val transportation: String,
val tree: Boolean,
val triangle: Int,
val twenty: String,
val unit: String,
val using: String,
val usually: Double,
val vapor: Double,
val weak: String,
val wheat: Double,
val whole: String,
val whose: Boolean,
val why: Double,
val will: Boolean,
val wolf: Int,
val wood: Int,
val word: Double,
val worker: String,
val wrong: Int,
val yard: Boolean,
val yellow: Int
)
| 7
|
Kotlin
|
1
| 1
|
e1845e8c9737c66b63cfa49925ad3bb9c589fbd1
| 4,609
|
KFixture
|
MIT License
|
src/main/kotlin/de/brainsizzle/twitchbotpaint/bot/Config.kt
|
brainsizzle
| 363,224,097
| false
| null |
package de.brainsizzle.twitchbotpaint.bot
data class Config(
val debug: Boolean,
val bot: Bot,
val api: Api,
val credentials: Credentials,
val channels: List<String>,
)
data class Bot(
val name: String,
val version: String
)
data class Api(
val twitch_client_id: String,
val twitch_client_secret: String,
)
data class Credentials(val irc: String)
| 0
|
Kotlin
|
1
| 0
|
81817eb5c81ddd0a90f286bb6d9ff98798871ed6
| 387
|
twitchbotpaint
|
Apache License 2.0
|
app/src/main/java/com/example/jetpack_compose_all_in_one/ui/components/CustomSpacer.kt
|
myofficework000
| 626,474,700
| false
|
{"Kotlin": 1392414}
|
package com.example.jetpack_compose_all_in_one.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import com.example.jetpack_compose_all_in_one.ui.theme.dp_1
import kotlin.random.Random
@Composable
fun CustomSpacer(height: Dp, color: Color = getRandomColor()) {
Box(
modifier = Modifier
.padding(dp_1)
.height(height)
.fillMaxWidth()
.background(color)
)
}
@Composable
fun getRandomColor(): Color {
val random = Random.Default
return Color(random.nextFloat(), random.nextFloat(), random.nextFloat())
}
| 21
|
Kotlin
|
22
| 222
|
4de5418608d6917b5c97fac7d868454c424daa26
| 942
|
Jetpack-Compose-All-in-one-Guide
|
MIT License
|
seattle-parks-tracker/app/src/main/java/com/google/codelabs/buildyourfirstmap/place/PlaceRenderer.kt
|
Jessicawyn
| 454,191,813
| false
|
{"Kotlin": 27724, "Python": 554}
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.codelabs.buildyourfirstmap.place
import android.content.Context
import androidx.core.content.ContextCompat
import androidx.preference.PreferenceManager
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.codelabs.buildyourfirstmap.BitmapHelper
import com.google.codelabs.buildyourfirstmap.R
import com.google.maps.android.clustering.ClusterManager
import com.google.maps.android.clustering.view.DefaultClusterRenderer
/**
* A custom cluster renderer for Place objects.
*/
class PlaceRenderer(
private val context: Context,
map: GoogleMap,
private val clusterManager: ClusterManager<Place>
) : DefaultClusterRenderer<Place>(context, map, clusterManager) {
fun setListener() {
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
clusterManager.markerCollection.setOnInfoWindowClickListener(object : GoogleMap.OnInfoWindowClickListener {
override fun onInfoWindowClick(marker: Marker?) {
val place = marker?.tag as? Place ?: return
place.visited = !place.visited
marker.setIcon(placeIcon(place))
marker.showInfoWindow()
val editor = preferences.edit()
if (place.visited && !preferences.getBoolean(place.locID, false))
editor.putBoolean(place.locID, true)
else if(!place.visited && preferences.getBoolean(place.locID, false))
editor.remove(place.locID)
editor.apply()
}
})
}
/**
* The icon to use for each cluster item
*/
private val unvisitedParkIcon: BitmapDescriptor by lazy {
val color = ContextCompat.getColor(context,
R.color.colorPrimary
)
BitmapHelper.vectorToBitmap(
context,
R.drawable.ic_baseline_nature_people_24,
color
)
}
private val visitedParkIcon: BitmapDescriptor by lazy {
val color = ContextCompat.getColor(context,
R.color.colorAccent
)
BitmapHelper.vectorToBitmap(
context,
R.drawable.ic_baseline_nature_people_24,
color
)
}
private fun placeIcon(item: Place) : BitmapDescriptor = if (item.visited)
visitedParkIcon else unvisitedParkIcon
/**
* Method called before the cluster item (i.e. the marker) is rendered. This is where marker
* options should be set
*/
override fun onBeforeClusterItemRendered(item: Place, markerOptions: MarkerOptions) {
markerOptions.title(item.name)
.position(item.latLng)
.icon(placeIcon(item))
}
/**
* Method called right after the cluster item (i.e. the marker) is rendered. This is where
* properties for the Marker object should be set.
*/
override fun onClusterItemRendered(clusterItem: Place, marker: Marker) {
marker.tag = clusterItem
}
}
| 0
|
Kotlin
|
0
| 0
|
b7ea64e96510609e63b5bc868df2079e7af0deb1
| 3,734
|
Seattle-Parks-Tracker
|
Apache License 2.0
|
app/src/main/java/ru/qdev/kudashov/jokes/api/ApiService.kt
|
wn1
| 162,917,801
| false
| null |
package ru.qdev.kudashov.jokes.api
import com.localebro.okhttpprofiler.OkHttpProfilerInterceptor
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import retrofit2.http.GET
import retrofit2.Retrofit
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Query
import ru.qdev.kudashov.jokes.BuildConfig
import ru.qdev.kudashov.jokes.api.model.JokeApiModel
interface UmoriliService {
companion object {
private val baseUrl: String
get() = "http://umorili.herokuapp.com/api/"
val wwwUrl: String
get() = "http://umori.li"
private var service: UmoriliService? = null
fun instance(): UmoriliService {
if (service == null) {
service = create()
}
return service!!
}
fun create() : UmoriliService {
val okHttpClientBuilder = OkHttpClient.Builder()
okHttpClientBuilder.addInterceptor(
HttpLoggingInterceptor()
.setLevel(
if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
else HttpLoggingInterceptor.Level.NONE)
)
if (BuildConfig.DEBUG) {
okHttpClientBuilder.addInterceptor(OkHttpProfilerInterceptor())
}
val okHttpClient = okHttpClientBuilder.build()
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
return retrofit.create(UmoriliService::class.java)
}
}
class JokeResponse : ArrayList<JokeApiModel>()
@GET("random")
fun randomJokeList(
@Query("num") count: Int,
@Query("site") site: String?,
@Query("name") name: String?
) : Single<JokeResponse>
@GET("random?num=10")
fun randomJokeCall() : Single<JokeResponse>
}
| 0
|
Kotlin
|
1
| 0
|
87541695d1c8dae91067bfc215867765fc3952a5
| 2,277
|
Jokes
|
MIT License
|
app/src/main/java/com/vycius/tasty/RecipeDetailActivity.kt
|
vycius
| 95,029,302
| false
| null |
package com.vycius.tasty
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
import com.vycius.tasty.adapter.RecipeListAdapter
import com.vycius.tasty.adapter.delegate.RecipeStepsAdapter
import com.vycius.tasty.manager.RecipeInfoWidgetManager
import com.vycius.tasty.model.Recipe
import com.vycius.tasty.model.Step
import kotlinx.android.synthetic.main.recipe_detail_list.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
/**
* An activity representing a list of Recipes. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a [RecipeStepActivity] representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
class RecipeDetailActivity : AppCompatActivity(), RecipeStepsAdapter.OnRecipeStepClicked {
@Inject
lateinit var recipeInfoWidgetManager: RecipeInfoWidgetManager
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private var mTwoPane: Boolean = false
private lateinit var recipe: Recipe
private lateinit var recipesAdapter: RecipeListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recipe_detail)
App.get(this).component.inject(this)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.title = title
recipe = intent.extras.getParcelable(ARG_RECIPE) ?: throw IllegalArgumentException("Pass recipe")
setupRecyclerView(recycler_view)
if (findViewById(R.id.recipe_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.recipe_info, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item?.itemId) {
R.id.action_add_to_widget -> {
recipeInfoWidgetManager.updateWidgetRecipe(recipe)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onStart() {
super.onStart()
title = recipe.name
recipesAdapter.bind(recipe.steps, recipe.ingredients)
}
private fun setupRecyclerView(recyclerView: RecyclerView) {
recipesAdapter = RecipeListAdapter(this)
recyclerView.adapter = recipesAdapter
}
override fun onRecipeStepClicked(step: Step) {
if (mTwoPane) {
val fragment = RecipeStepsPagerFragment.instance(recipe, step)
supportFragmentManager.beginTransaction()
.replace(R.id.recipe_detail_container, fragment)
.commit()
} else {
val intent = Intent(this, RecipeStepActivity::class.java)
intent.putExtra(ARG_RECIPE, recipe)
intent.putExtra(ARG_RECIPE_STEP, step)
startActivity(intent)
}
}
companion object {
private const val ARG_RECIPE = "recipe"
private const val ARG_RECIPE_STEP = "recipe_step"
}
}
| 1
|
Kotlin
|
9
| 33
|
f00503f587ce3d91c622d71a84f2fa56f7f0235e
| 3,737
|
udacity-baking-app-tasty
|
MIT License
|
redis/src/main/java/info/xiaomo/redis/job/TaskJob.kt
|
tangyinbo
| 109,561,532
| true
|
{"Kotlin": 323648, "CSS": 117781, "FreeMarker": 7915, "HTML": 6836, "Java": 2501, "Ruby": 37}
|
package info.xiaomo.redis.job
import com.alibaba.fastjson.JSON
import info.xiaomo.redis.service.CityService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.util.*
/**
* @author : xiaomo
*/
@Component
class TaskJob @Autowired
constructor(private val cityService: CityService) {
/**
* Job
*/
@Scheduled(fixedDelay = 5000)
fun retrieveCountry() {
val index = Random().nextInt(LIST.size)
val city = find(index)
val info = cityService.getCity(index, city)
LOGGER.debug("{}", JSON.toJSONString(info))
}
private fun find(index: Int): String {
return LIST[index]
}
companion object {
private val LOGGER = LoggerFactory.getLogger(TaskJob::class.java)
private val LIST = Arrays.asList("北京市", "上海市", "天津市", "重庆市", "河北省", "山西省", "内蒙古自治区", "辽宁省",
"吉林省", "黑龙江", "江苏省", "浙江省", "安徽省", "福建省", "江西省", "山东省", "河南省", "湖北省", "湖南省", "广东省", "广西自治区", "海南省", "四川省",
"贵州省", "云南省", "西藏自治区", "陕西省", "甘肃省", "青海省", "宁夏自治区", "新疆自治区", "香港特别行政区", "澳门特别行政区", "台湾省")
}
}
| 0
|
Kotlin
|
0
| 0
|
23d20b605e842d32f53c8b7e0effe92e52475c65
| 1,238
|
SpringBootUnity
|
MIT License
|
app/src/main/java/com/example/moviedatabase/compose/AppBottomBar.kt
|
ali-gevari
| 838,166,478
| false
|
{"Kotlin": 150986}
|
package com.example.moviedatabase.compose
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.moviedatabase.navigation.Destination
@Composable
fun AppBottomBar(
allScreens: List<Destination>,
onTabSelected: (Destination) -> Unit,
currentScreen: Destination
) {
Surface(
Modifier.height(86.dp)
) {
NavigationBar(modifier = Modifier.fillMaxWidth()) {
allScreens.forEach { destination ->
NavigationBarItem(
selected = currentScreen == destination,
onClick = { onTabSelected(destination) },
icon = {
Icon(
imageVector = destination.icon,
contentDescription = destination.route
)
}
)
}
}
}
}
| 2
|
Kotlin
|
0
| 0
|
d485ccf9e6fab0107155921d4b233af31346061a
| 1,242
|
MovieDatabase
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/nonassociations/NonAssociationsResource.kt
|
ministryofjustice
| 445,140,246
| false
|
{"Kotlin": 1229627, "Mustache": 1803, "Dockerfile": 1118}
|
package uk.gov.justice.digital.hmpps.prisonertonomisupdate.nonassociations
import com.microsoft.applicationinsights.TelemetryClient
import io.swagger.v3.oas.annotations.Hidden
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.config.trackEvent
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.listeners.EventFeatureSwitch
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.NomisApiService
@RestController
class NonAssociationsResource(
private val telemetryClient: TelemetryClient,
private val nonAssociationsReconciliationService: NonAssociationsReconciliationService,
private val nomisApiService: NomisApiService,
private val eventFeatureSwitch: EventFeatureSwitch,
private val reportScope: CoroutineScope,
) {
private companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
}
/**
* For dev environment only - delete all nonAssociations, for when activities environment is reset
*/
@Hidden
@PreAuthorize("hasRole('ROLE_QUEUE_ADMIN')")
@DeleteMapping("/non-associations")
@ResponseStatus(HttpStatus.NO_CONTENT)
suspend fun deleteAllNonAssociations() {
if (eventFeatureSwitch.isEnabled("DELETEALL")) {
// TODO nonAssociationsService.deleteAllNonAssociations()
} else {
throw RuntimeException("Attempt to delete nonAssociations in wrong environment")
}
}
@PutMapping("/non-associations/reports/reconciliation")
@ResponseStatus(HttpStatus.ACCEPTED)
suspend fun generateReconciliationReport() {
val nonAssociationsCount = nomisApiService.getNonAssociations(0, 1).totalElements
telemetryClient.trackEvent("non-associations-reports-reconciliation-requested", mapOf("non-associations-nomis-total" to nonAssociationsCount.toString()))
log.info("Non-associations reconciliation report requested for $nonAssociationsCount non-associations")
reportScope.launch {
runCatching { nonAssociationsReconciliationService.generateReconciliationReport(nonAssociationsCount) }
.onSuccess { listOfLists ->
val fullResults = listOfLists.flatten()
log.info("Non-associations reconciliation report completed with ${fullResults.size} mismatches")
val results = fullResults.take(10) // Only log the first 10 to avoid an insights error with too much data
val map = mapOf("mismatch-count" to fullResults.size.toString()) +
results.associate { "${it.id}" to "nomis=${it.nomisNonAssociation}, dps=${it.dpsNonAssociation}" }
telemetryClient.trackEvent("non-associations-reports-reconciliation-success", map)
log.info("Non-associations reconciliation report logged")
}
.onFailure {
telemetryClient.trackEvent("non-associations-reports-reconciliation-failed")
log.error("Non-associations reconciliation report failed", it)
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
49fb8c4285fd2dfa957856f04b224cefd97a475b
| 3,359
|
hmpps-prisoner-to-nomis-update
|
MIT License
|
types-jdbi/src/test/kotlin/dk/cloudcreate/essentials/kotlin/types/jdbi/model/LastUpdated.kt
|
cloudcreate-dk
| 571,305,651
| false
|
{"Maven POM": 27, "XML": 18, "Ignore List": 1, "Text": 2, "Markdown": 28, "Java": 894, "Avro IDL": 1, "Kotlin": 87, "YAML": 4}
|
/*
* Copyright 2021-2024 the original author or authors.
*
* 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 dk.cloudcreate.essentials.kotlin.types.jdbi.model
import dk.cloudcreate.essentials.kotlin.types.InstantValueType
import dk.cloudcreate.essentials.kotlin.types.jdbi.InstantValueTypeArgumentFactory
import dk.cloudcreate.essentials.kotlin.types.jdbi.InstantValueTypeColumnMapper
import java.time.Instant
@JvmInline
value class LastUpdated(override val value: Instant) : InstantValueType<LastUpdated> {
companion object {
fun of(value: Instant): LastUpdated {
return LastUpdated(value)
}
fun now(): LastUpdated {
return LastUpdated(Instant.now())
}
}
}
class LastUpdatedArgumentFactory : InstantValueTypeArgumentFactory<LastUpdated>() {
}
class LastUpdatedColumnMapper : InstantValueTypeColumnMapper<LastUpdated>() {
}
| 0
|
Java
|
2
| 3
|
6b428edc1dfd406b0ae55c7e066669d507ecd2a4
| 1,415
|
essentials-project
|
Apache License 2.0
|
app/src/main/java/star/iota/acgrip/ui/fan/FanAdapter.kt
|
iota9star
| 102,921,744
| false
| null |
/*
* Copyright 2017. iota9star
*
* 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 star.iota.acgrip.ui.fan
import android.annotation.SuppressLint
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.nex3z.flowlayout.FlowLayout
import star.iota.acgrip.Category
import star.iota.acgrip.R
import star.iota.acgrip.ext.addFragmentToActivity
import star.iota.acgrip.ui.item.ItemFragment
import java.util.*
internal class FanAdapter : RecyclerView.Adapter<FanAdapter.MyViewHolder>() {
private val items: MutableList<FansBean>
init {
items = ArrayList()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_fans, parent, false))
}
@SuppressLint("InflateParams")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = items[position]
holder.flowLayoutFans.removeAllViews()
if (item.isActive) {
holder.textViewWeek.text = ("『 " + item.week + " 』")
} else {
holder.textViewWeek.text = item.week
}
val inflater = LayoutInflater.from(holder.context)
for (bean in item.fans) {
@SuppressLint("InflateParams") val fan = inflater.inflate(R.layout.item_fan, null) as TextView
fan.text = bean.name
fan.setOnClickListener { (holder.context as AppCompatActivity).addFragmentToActivity(ItemFragment.newInstance(Category.URL.id, bean.url, bean.name), R.id.frame_layout_container) }
holder.flowLayoutFans.addView(fan)
}
}
fun clear() {
val size = items.size
items.clear()
notifyItemRangeRemoved(0, size)
}
fun add(items: List<FansBean>) {
val size = this.items.size
this.items.addAll(items)
notifyItemRangeInserted(size, items.size)
}
override fun getItemCount(): Int {
return items.size
}
class MyViewHolder(
itemView: View,
val context: Context = itemView.context,
var textViewWeek: TextView = itemView.findViewById(R.id.text_view_week),
var flowLayoutFans: FlowLayout = itemView.findViewById(R.id.flow_layout_fans)
) : RecyclerView.ViewHolder(itemView)
}
| 0
|
Kotlin
|
2
| 9
|
5825689d5af38e9925765c7e709d1fd38f14aa80
| 3,052
|
acg.rip
|
Apache License 2.0
|
backend/src/main/kotlin/com/mobilispect/backend/schedule/gtfs/GTFSRouteDataSourceConfiguration.kt
|
alandovskis
| 502,662,711
| false
|
{"Kotlin": 360467, "Shell": 472, "Swift": 345}
|
package com.mobilispect.backend.schedule.gtfs
import com.mobilispect.backend.schedule.agency.AgencyIDDataSource
import com.mobilispect.backend.schedule.route.RouteDataSource
import com.mobilispect.backend.schedule.route.RouteIDDataSource
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
internal class GTFSRouteDataSourceConfiguration {
@Bean
fun routeDataSource(
agencyIDDataSource: AgencyIDDataSource,
routeIDDataSource: RouteIDDataSource
): RouteDataSource = GTFSRouteDataSource(agencyIDDataSource, routeIDDataSource)
}
| 3
|
Kotlin
|
0
| 1
|
0b0378fc2bfa7f9c0f9a135950a4d11712f6af17
| 630
|
mobilispect
|
Apache License 2.0
|
app/src/main/java/com/igorapp/deckster/DecksterApp.kt
|
igormsiqueira
| 568,021,005
| false
| null |
package com.igorapp.deckster
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class DecksterApp : Application()
| 0
|
Kotlin
|
0
| 0
|
65e5d6d2ace941e93be74c112c56cf0f4e0a1439
| 153
|
deckster-android
|
MIT License
|
app/src/main/java/io/github/wulkanowy/data/repositories/reportingunit/ReportingUnitLocal.kt
|
mafineeek
| 297,426,962
| true
|
{"Kotlin": 966636, "HTML": 1949, "Shell": 220}
|
package io.github.wulkanowy.data.repositories.reportingunit
import io.github.wulkanowy.data.db.dao.ReportingUnitDao
import io.github.wulkanowy.data.db.entities.ReportingUnit
import io.github.wulkanowy.data.db.entities.Student
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ReportingUnitLocal @Inject constructor(private val reportingUnitDb: ReportingUnitDao) {
suspend fun getReportingUnits(student: Student): List<ReportingUnit> {
return reportingUnitDb.load(student.studentId)
}
suspend fun getReportingUnit(student: Student, unitId: Int): ReportingUnit? {
return reportingUnitDb.loadOne(student.studentId, unitId)
}
suspend fun saveReportingUnits(reportingUnits: List<ReportingUnit>): List<Long> {
return reportingUnitDb.insertAll(reportingUnits)
}
suspend fun deleteReportingUnits(reportingUnits: List<ReportingUnit>) {
reportingUnitDb.deleteAll(reportingUnits)
}
}
| 0
| null |
0
| 0
|
b0b3ccfd530e2b450804c194365b4e4fe225c754
| 967
|
wulkanowy
|
Apache License 2.0
|
plugins/kotlin/compiler-reference-index/tests/testData/compilerIndex/classOrObject/innerClassWithPackage/MainClass.kt
|
ingokegel
| 72,937,917
| false
| null |
package one.two.three
class MainClass {
inner class Nested<caret>Class
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 77
|
intellij-community
|
Apache License 2.0
|
compiler/testData/writeSignature/IntQ.kt
|
JakeWharton
| 99,388,807
| false
| null |
fun sometimes(): Int? = null
// method: IntQKt::sometimes
// jvm signature: ()Ljava/lang/Integer;
// generic signature: null
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 129
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/kaajjo/orgtechservice/data/remote/api/info/TariffService.kt
|
kaajjo
| 661,326,276
| false
|
{"Kotlin": 173213}
|
package com.kaajjo.orgtechservice.data.remote.api.info
import com.kaajjo.orgtechservice.data.remote.dto.Tariffs
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface TariffService {
@GET("api.php?call=tariffs")
suspend fun getTariffs(
@Query("key") key: String
): Response<Tariffs>
}
| 0
|
Kotlin
|
0
| 1
|
0f95a681d0444e537b0f6fbf25ca2892057c9f6a
| 341
|
orgtechservice-alt
|
Apache License 2.0
|
pictl-ktor/test/org/unividuell/pictl/server/usecase/InteractorTestBase.kt
|
cleemansen
| 321,330,316
| false
| null |
package org.unividuell.pictl.server.usecase
import io.mockk.MockKAnnotations
import org.junit.jupiter.api.BeforeEach
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.core.module.Module
abstract class InteractorTestBase {
init {
stopKoin()
}
fun startInjection(module: Module) = startKoin {
modules(
module
)
}
@BeforeEach
internal fun setUpBase() {
MockKAnnotations.init(this)
}
}
| 13
|
Kotlin
|
2
| 0
|
c2179ae7e9bb9e1cfd314bbcc8bb120967e45d05
| 501
|
pi-audio-multiroom
|
MIT License
|
src/main/kotlin/io/github/cclassen/oakdsl/builder/EndpointBuilder.kt
|
c-classen
| 398,049,382
| false
| null |
package io.github.cclassen.oakdsl.builder
import io.github.cclassen.oakdsl.component.ComponentResolver
import io.github.cclassen.oakdsl.model.endpoint.*
import io.github.cclassen.oakdsl.model.endpoint.response.BaseResponse
import io.github.cclassen.oakdsl.model.endpoint.response.Response
import io.github.cclassen.oakdsl.model.schema.Schema
import kotlin.reflect.KType
import kotlin.reflect.typeOf
class EndpointBuilder(
val endpoint: Endpoint,
val components: ComponentResolver
): ParameterReceiver {
var description by endpoint::description
@OptIn(ExperimentalStdlibApi::class)
inline fun <reified T> requestBody(
contentType: String = "application/json",
description: String? = null,
required: Boolean = true
) {
requestBody(contentType, description, required, typeOf<T>())
}
fun requestBody(
contentType: String,
description: String?,
required: Boolean,
type: KType
) {
val schema = try {
components.resolveType(type)
} catch (ex: RuntimeException) {
throw RuntimeException("Failed to resolve type of request body", ex)
}
val bodyContent = BodyContent(mutableMapOf(contentType to schema))
val requestBody = RequestBody(description, bodyContent, required)
endpoint.requestBody = requestBody
}
fun response(
code: String,
description: String = "Success"
) {
response(code, description, null)
}
@OptIn(ExperimentalStdlibApi::class)
inline fun <reified T> response(
code: String,
description: String = "Success",
contentType: String = "application/json",
noinline content: (ResponseBuilder.() -> Unit)? = null
) {
val schema = components.resolveType(typeOf<T>())
response(code, description, schema, contentType, content)
}
fun response(
code: String,
description: String = "Success",
schema: Schema? = null,
contentType: String = "application/json",
content: (ResponseBuilder.() -> Unit)? = null
) {
val response = Response(description)
if (schema != null) {
response.content = BodyContent(mutableMapOf(contentType to schema))
}
val builder = ResponseBuilder(response)
content?.let { it(builder) }
endpoint.responses[code] = response
}
fun response(code: String, response: BaseResponse) {
endpoint.responses[code] = response
}
fun tags(vararg tags: String) {
endpoint.tags.addAll(tags)
}
@OptIn(ExperimentalStdlibApi::class)
inline fun <reified R> param(
name: String,
required: Boolean = true,
description: String? = null,
kind: String? = null,
noinline content: (ParameterBuilder.() -> Unit)? = null
): ParameterBuilder {
return param(name, typeOf<R>(), required, description, kind, content)
}
override fun param(
name: String,
type: KType,
required: Boolean,
description: String?,
kind: String?,
content: (ParameterBuilder.() -> Unit)?
): ParameterBuilder {
val parameter = Parameter(kind ?: "query", name, required, components.resolveType(type), description)
val builder = ParameterBuilder(parameter)
content?.let { it(builder) }
endpoint.parameters.add(parameter)
return builder
}
fun params(vararg params: BaseParameter) {
endpoint.parameters.addAll(params)
}
}
| 0
|
Kotlin
|
0
| 2
|
71bc5702058443c816a8e355052eb601ed0555ce
| 3,581
|
oak-dsl
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsworkload/utils/StringUtils.kt
|
ministryofjustice
| 378,843,394
| false
|
{"PLpgSQL": 472290, "Kotlin": 436140, "Dockerfile": 1715}
|
package uk.gov.justice.digital.hmpps.hmppsworkload.utils
fun String.capitalize(): String {
if (this.isNotEmpty() && this.isNotBlank()) {
return this[0].uppercase() + this.substring(1).lowercase()
}
return this
}
| 14
|
PLpgSQL
|
0
| 0
|
93ad98d7641fa391aae2753b3cefd38b543f1e74
| 223
|
hmpps-workload
|
MIT License
|
compiler/cli/src/org/jetbrains/kotlin/cli/common/createFlexiblePhaseConfig.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.common
import org.jetbrains.kotlin.backend.common.phaser.FlexiblePhaseConfig
import org.jetbrains.kotlin.backend.common.phaser.PhaseSet
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly
fun createFlexiblePhaseConfig(
arguments: CommonCompilerArguments,
): FlexiblePhaseConfig {
fun Array<String>?.asNonNullSet(): Set<String> = this?.toSet() ?: emptySet()
val toDumpBoth = createPhaseSetFromArguments(arguments.phasesToDump)
val toValidateBoth = createPhaseSetFromArguments(arguments.phasesToValidate)
return FlexiblePhaseConfig(
disabled = arguments.disablePhases.asNonNullSet(),
verbose = arguments.verbosePhases.asNonNullSet(),
toDumpStateBefore = createPhaseSetFromArguments(arguments.phasesToDumpBefore) + toDumpBoth,
toDumpStateAfter = createPhaseSetFromArguments(arguments.phasesToDumpAfter) + toDumpBoth,
toValidateStateBefore = createPhaseSetFromArguments(arguments.phasesToValidateBefore) + toValidateBoth,
toValidateStateAfter = createPhaseSetFromArguments(arguments.phasesToValidateAfter) + toValidateBoth,
dumpOnlyFqName = arguments.dumpOnlyFqName,
dumpToDirectory = arguments.dumpDirectory,
needProfiling = arguments.profilePhases,
checkConditions = arguments.checkPhaseConditions,
checkStickyConditions = arguments.checkStickyPhaseConditions,
)
}
private fun createPhaseSetFromArguments(names: Array<String>?): PhaseSet = when {
names == null -> PhaseSet.Enum(emptySet())
"all" in names.map { it.toLowerCaseAsciiOnly() } -> PhaseSet.ALL
else -> PhaseSet.Enum(names.map { it.toLowerCaseAsciiOnly() }.toSet())
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,995
|
kotlin
|
Apache License 2.0
|
android-legacy/src/main/java/com/amarland/iconvector/androidlegacy/PictureRecording.kt
|
amarland
| 433,039,075
| false
|
{"Kotlin": 113847, "Java": 7176}
|
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amarland.iconvector.androidlegacy
import android.content.res.Resources
import android.graphics.*
import android.graphics.drawable.Drawable
import android.graphics.drawable.PictureDrawable
import androidx.annotation.ColorInt
import androidx.annotation.DimenRes
import androidx.annotation.Dimension
import androidx.annotation.RawRes
import com.amarland.iconvector.lib.IconVGIntermediateRepresentation
import com.amarland.iconvector.lib.IconVGMachine
import okio.buffer
import okio.source
import kotlin.math.roundToInt
import com.amarland.iconvector.lib.IconVGIntermediateRepresentation as IR
@ExperimentalUnsignedTypes
fun Resources.getIconVGDrawable(
@RawRes id: Int,
@DimenRes heightRes: Int,
@ColorInt palette: IntArray = intArrayOf()
) = getIconVGDrawableWithPixelHeight(id, getDimensionPixelSize(heightRes), palette)
@ExperimentalUnsignedTypes
fun Resources.getIconVGDrawableWithPixelHeight(
@RawRes id: Int,
@Dimension height: Int,
@ColorInt palette: IntArray = intArrayOf()
): Drawable =
openRawResource(id)
.source().buffer()
.use { source ->
PictureDrawable(
IconVGMachine(source, palette.toUIntArray())
.intermediateRepresentation
.toPicture(height)
)
}
@ExperimentalUnsignedTypes
fun IconVGIntermediateRepresentation.toPicture(@Dimension height: Int): Picture {
return Picture().apply {
val width = (height / viewportHeight * viewportWidth).roundToInt()
beginRecording(width, height).run {
scale(width / viewportWidth, height / viewportHeight)
if (translationX != 0F || translationY != 0F) {
translate(translationX, translationY)
}
val pathToDraw = Path()
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
for (path in paths) {
pathToDraw.rewind()
var currentX = 0F
var currentY = 0F
for (segment in path.segments) {
val args = segment.arguments
when (segment.command) {
IR.Path.Command.MOVE_TO -> {
pathToDraw.moveTo(args[0], args[1])
currentX = args[0]
currentY = args[1]
}
IR.Path.Command.LINE_TO -> {
pathToDraw.lineTo(args[0], args[1])
currentX = args[0]
currentY = args[1]
}
IR.Path.Command.CUBIC_TO -> {
pathToDraw.cubicTo(
args[0], args[1],
args[2], args[3],
args[4], args[5]
)
currentX = args[4]
currentY = args[5]
}
IR.Path.Command.QUAD_TO -> {
pathToDraw.quadTo(
args[0], args[1],
args[2], args[3]
)
currentX = args[2]
currentY = args[3]
}
/* IconVG.Path.Command.ARC_TO */
else -> {
// no method for drawing elliptical arcs
EllipticalArcDrawingUtil.drawArc(
pathToDraw,
currentX, currentY,
args[5], args[6],
args[0], args[1],
args[2],
args[3] == 1F,
args[4] == 1F
)
currentX = args[5]
currentY = args[6]
}
}
}
fun IR.TileMode.toAndroidTileMode(): Shader.TileMode =
when (this) {
IR.TileMode.REPEAT -> Shader.TileMode.REPEAT
IR.TileMode.MIRROR -> Shader.TileMode.MIRROR
else -> Shader.TileMode.CLAMP
}
when (val fill = path.fill) {
is IR.Path.Fill.Color -> {
paint.color = fill.argb.toInt()
paint.shader = null
}
is IR.Path.Fill.LinearGradient ->
paint.shader = LinearGradient(
fill.startX, fill.startY,
fill.endX, fill.endY,
fill.colors,
fill.stops,
fill.tileMode.toAndroidTileMode()
)
is IR.Path.Fill.RadialGradient ->
paint.shader = RadialGradient(
0F, 0F,
1F,
fill.colors,
fill.stops,
fill.tileMode.toAndroidTileMode()
).apply {
setLocalMatrix(
Matrix().apply {
val values = fill.matrix.values
// column-major order -> row-major order
setValues(
floatArrayOf(
values[0], values[3], values[6],
values[1], values[4], values[7],
values[2], values[5], values[8]
)
)
}
)
}
}
drawPath(pathToDraw, paint)
}
}
endRecording()
}
}
| 0
|
Kotlin
|
0
| 0
|
e05c63280dc922ce6bd3ea961c53ce1f9a415213
| 6,854
|
iconvector
|
Apache License 2.0
|
app/src/main/kotlin/maxeem.america.sleep/JournalFragment.kt
|
maxeema
| 199,365,363
| true
|
{"Kotlin": 58587}
|
package maxeem.america.sleep
import android.os.Bundle
import android.view.*
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.databinding.ObservableBoolean
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.observe
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.transition.*
import com.google.android.material.appbar.AppBarLayout
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import maxeem.america.sleep.adapter.JournalAdapter
import maxeem.america.sleep.adapter.JournalAdapterDecoration
import maxeem.america.sleep.adapter.hasOnlyOneRealItem
import maxeem.america.sleep.adapter.isVirtualAt
import maxeem.america.sleep.data.Night
import maxeem.america.sleep.databinding.FragmentJournalBinding
import maxeem.america.sleep.ext.grid
import maxeem.america.sleep.ext.hash
import maxeem.america.sleep.ext.materialAlert
import maxeem.america.sleep.misc.MOCK_DATA
import maxeem.america.sleep.misc.timeMillis
import maxeem.america.sleep.model.JournalModel
import org.jetbrains.anko.contentView
import org.jetbrains.anko.info
class JournalFragment : BaseFragment() {
private companion object {
private var startKey : Int? = null
}
override val model : JournalModel by viewModels()
private lateinit var binding : FragmentJournalBinding
private val busy = ObservableBoolean()
private val loaded = ObservableBoolean()
private var inserting = false to null as Long?
private val navigateToSleepEvent = MutableLiveData<Long?>()
private var clear : MenuItem? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
info("$hash onCreateView, savedInstanceState: $savedInstanceState")
binding = FragmentJournalBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.model = model
binding.loaded = loaded
binding.busy = busy
info(" startKey: $startKey, cur key: ${context?.hash}, savedInstanceState: $savedInstanceState")
if (startKey == context?.hash || (savedInstanceState != null && startKey != null))
doLoad()
navigateToSleepEvent.observe(viewLifecycleOwner) { nightId ->
nightId ?: return@observe
navigateToSleepEvent.removeObservers(viewLifecycleOwner)
if (activity?.isFinishing != true)
findNavController().navigate(JournalFragmentDirections.actionJournalFragToSleepingFrag(nightId))
}
binding.appbar.addOnLayoutChangeListener { v, _,_,_,_,_,_,_,_ ->
(v.layoutParams as CoordinatorLayout.LayoutParams).behavior?.let {
if (it is AppBarLayout.Behavior) it.setDragCallback(appbarCantDrag)
}
}
binding.toolbar.apply {
clear = menu.findItem(R.id.clearMenuItem).apply {
isEnabled = loaded.get() && model.hasNights.value == true
}
setOnMenuItemClickListener { when {
busy.get() -> false
it == clear -> materialAlert(R.string.confirm_clearing) {
setPositiveButton(R.string.yes) { _, _ ->
model.clearData(); clear?.isEnabled = false
}
setNegativeButton(R.string.cancel) { _, _ -> }
}.let { true }
it.itemId == R.id.aboutFragment -> findNavController().navigate(JournalFragmentDirections.toAbout()).let { true }
else -> false
}}
}
return binding.root
}
private fun doLoad() {
val adapter = JournalAdapter().apply {
onItemClick = View.OnClickListener { val night = it.tag as Night
if (busy.get()) return@OnClickListener
findNavController().navigate(JournalFragmentDirections.actionJournalFragToDetailsFrag(night.id!!))
}
onItemLongClick = View.OnLongClickListener { val night = it.tag as Night
if (busy.get()) return@OnLongClickListener true
materialAlert(R.string.confirm_deleting) {
setPositiveButton(R.string.yes) { _, _ -> model.deleteItem(night) }
setNegativeButton(R.string.cancel) { _, _ -> }
}
true
}
}
binding.recycler.apply {
this.adapter = adapter
layoutManager.grid().apply {
spanSizeLookup = object: GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int) = when {
adapter.isVirtualAt(position) -> spanCount
adapter.hasOnlyOneRealItem -> spanCount
else -> 1
}
}
}
addItemDecoration(JournalAdapterDecoration(R.color.face))
itemAnimator = DefaultItemAnimator()
}
binding.fab.setOnClickListener {
if (busy.get()) return@setOnClickListener
model.doSleep()
}
model.onComplete = { val newNightId = it as Long
busy.set(true)
inserting = true to newNightId
binding.recycler.scrollToPosition(0)
}
model.nights.observe(viewLifecycleOwner) { nights ->
info(" nights update to -> $nights")
nights ?: return@observe
adapter.submitData(nights)
busy.set(true)
viewOwner?.lifecycleScope?.launch {
delay(500)
binding.recycler.itemAnimator?.isRunning {
viewOwner?.lifecycleScope?.launchWhenStarted {
info(" $timeMillis isRunning called on binding.recycler.itemAnimator")
busy.set(false)
val (isInserting, nightId) = inserting
if (isInserting)
navigateToSleepEvent.value = nightId
else
binding.appbar.setExpanded(true, false)
}
}
}
clear?.isEnabled = nights.isNotEmpty()
}
if (MOCK_DATA)
binding.fab.visibility = View.INVISIBLE
startKey = context?.hash
loaded.set(true)
busy.set(false)
info(" loaded: ${loaded.get()}, new startKey: $startKey")
}
override fun onStart() { super.onStart()
if (!loaded.get())
preLoad()
}
private fun preLoad() {
info(" preLoad")
binding.fab.apply { scaleX = 0f; scaleY = 0f }
viewOwner?.lifecycleScope?.launch {
delay(200)
TransitionManager.beginDelayedTransition(activity!!.contentView as ViewGroup, TransitionSet().apply {
ordering = TransitionSet.ORDERING_SEQUENTIAL
addTransition(Slide(Gravity.START)) // empty text will disappeared to start
addTransition(Fade(Fade.IN)) // recycler will appeared with fade in
addTransition(ChangeTransform()) // fab will appear from zero
})
doLoad()
binding.fab.apply { scaleX = 1f; scaleY = 1f }
activity!!.invalidateOptionsMenu()
}
}
// a little optimization of the UI when user can swipe appbar layout out via its dragging - looks not good
private val appbarCantDrag = object: AppBarLayout.Behavior.DragCallback() {
override fun canDrag(appBarLayout: AppBarLayout) = false
}
}
| 0
|
Kotlin
|
0
| 0
|
6f17b30cba2cb276c05854eeb7e23e2f7f2c5025
| 7,815
|
andfun-kotlin-sleep-tracker
|
Apache License 2.0
|
client/jackson/src/test/kotlin/net/corda/client/jackson/JacksonSupportTest.kt
|
kid101
| 133,337,942
| true
|
{"Kotlin": 5697215, "Java": 265838, "CSS": 23489, "Shell": 8259, "Gherkin": 3162, "Groovy": 2129, "Batchfile": 1332, "PowerShell": 660}
|
package net.corda.client.jackson
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.BinaryNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.node.TextNode
import com.fasterxml.jackson.module.kotlin.convertValue
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.whenever
import net.corda.core.contracts.Amount
import net.corda.core.cordapp.CordappProvider
import net.corda.core.crypto.*
import net.corda.core.crypto.CompositeKey
import net.corda.core.identity.AbstractParty
import net.corda.core.identity.AnonymousParty
import net.corda.core.identity.CordaX500Name
import net.corda.core.identity.Party
import net.corda.core.node.NodeInfo
import net.corda.core.node.ServiceHub
import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.toBase58String
import net.corda.core.utilities.toBase64
import net.corda.finance.USD
import net.corda.testing.common.internal.testNetworkParameters
import net.corda.testing.contracts.DummyContract
import net.corda.testing.core.*
import net.corda.testing.internal.createNodeInfoAndSigned
import net.corda.testing.internal.rigorousMock
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.math.BigInteger
import java.security.PublicKey
import java.util.*
import kotlin.collections.ArrayList
import kotlin.test.assertEquals
class JacksonSupportTest {
private companion object {
val SEED: BigInteger = BigInteger.valueOf(20170922L)
val ALICE_PUBKEY = TestIdentity(ALICE_NAME, 70).publicKey
val BOB_PUBKEY = TestIdentity(BOB_NAME, 70).publicKey
val DUMMY_NOTARY = TestIdentity(DUMMY_NOTARY_NAME, 20).party
val MINI_CORP = TestIdentity(CordaX500Name("MiniCorp", "London", "GB"))
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val partyObjectMapper = TestPartyObjectMapper()
private val mapper = JacksonSupport.createPartyObjectMapper(partyObjectMapper)
private lateinit var services: ServiceHub
private lateinit var cordappProvider: CordappProvider
@Before
fun setup() {
services = rigorousMock()
cordappProvider = rigorousMock()
doReturn(cordappProvider).whenever(services).cordappProvider
}
private class Dummy(val notional: Amount<Currency>)
@Test
fun `read Amount`() {
val oldJson = """
{
"notional": {
"quantity": 2500000000,
"token": "USD"
}
}
"""
val newJson = """ { "notional" : "$25000000" } """
assertEquals(Amount(2500000000L, USD), mapper.readValue(newJson, Dummy::class.java).notional)
assertEquals(Amount(2500000000L, USD), mapper.readValue(oldJson, Dummy::class.java).notional)
}
@Test
fun `write Amount`() {
val writer = mapper.writer().without(SerializationFeature.INDENT_OUTPUT)
assertEquals("""{"notional":"25000000.00 GBP"}""", writer.writeValueAsString(Dummy(Amount.parseCurrency("£25000000"))))
assertEquals("""{"notional":"250000.00 USD"}""", writer.writeValueAsString(Dummy(Amount.parseCurrency("$250000"))))
}
@Test
fun SignedTransaction() {
val attachmentRef = SecureHash.randomSHA256()
doReturn(attachmentRef).whenever(cordappProvider).getContractAttachmentID(DummyContract.PROGRAM_ID)
doReturn(testNetworkParameters()).whenever(services).networkParameters
val writer = mapper.writer()
val stx = makeDummyStx()
val json = writer.writeValueAsString(stx)
val deserializedTransaction = mapper.readValue(json, SignedTransaction::class.java)
assertThat(deserializedTransaction).isEqualTo(stx)
}
@Test
fun OpaqueBytes() {
val opaqueBytes = OpaqueBytes(secureRandomBytes(128))
val json = mapper.valueToTree<BinaryNode>(opaqueBytes)
assertThat(json.binaryValue()).isEqualTo(opaqueBytes.bytes)
assertThat(json.asText()).isEqualTo(opaqueBytes.bytes.toBase64())
assertThat(mapper.convertValue<OpaqueBytes>(json)).isEqualTo(opaqueBytes)
}
@Test
fun CordaX500Name() {
testToStringSerialisation(CordaX500Name(commonName = "COMMON", organisationUnit = "ORG UNIT", organisation = "ORG", locality = "NYC", state = "NY", country = "US"))
}
@Test
fun `SecureHash SHA256`() {
testToStringSerialisation(SecureHash.randomSHA256())
}
@Test
fun NetworkHostAndPort() {
testToStringSerialisation(NetworkHostAndPort("localhost", 9090))
}
@Test
fun UUID() {
testToStringSerialisation(UUID.randomUUID())
}
@Test
fun `Date is treated as Instant`() {
val date = Date()
val json = mapper.valueToTree<TextNode>(date)
assertThat(json.textValue()).isEqualTo(date.toInstant().toString())
assertThat(mapper.convertValue<Date>(json)).isEqualTo(date)
}
@Test
fun `Party serialization`() {
val json = mapper.valueToTree<TextNode>(MINI_CORP.party)
assertThat(json.textValue()).isEqualTo(MINI_CORP.name.toString())
}
@Test
fun `Party deserialization on full name`() {
fun convertToParty() = mapper.convertValue<Party>(TextNode(MINI_CORP.name.toString()))
assertThatThrownBy { convertToParty() }
partyObjectMapper.identities += MINI_CORP.party
assertThat(convertToParty()).isEqualTo(MINI_CORP.party)
}
@Test
fun `Party deserialization on part of name`() {
fun convertToParty() = mapper.convertValue<Party>(TextNode(MINI_CORP.name.organisation))
assertThatThrownBy { convertToParty() }
partyObjectMapper.identities += MINI_CORP.party
assertThat(convertToParty()).isEqualTo(MINI_CORP.party)
}
@Test
fun `Party deserialization on public key`() {
fun convertToParty() = mapper.convertValue<Party>(TextNode(MINI_CORP.publicKey.toBase58String()))
assertThatThrownBy { convertToParty() }
partyObjectMapper.identities += MINI_CORP.party
assertThat(convertToParty()).isEqualTo(MINI_CORP.party)
}
@Test
fun PublicKey() {
val json = mapper.valueToTree<TextNode>(MINI_CORP.publicKey)
assertThat(json.textValue()).isEqualTo(MINI_CORP.publicKey.toBase58String())
assertThat(mapper.convertValue<PublicKey>(json)).isEqualTo(MINI_CORP.publicKey)
}
@Test
fun `EdDSA public key`() {
val publicKey = Crypto.deriveKeyPairFromEntropy(Crypto.EDDSA_ED25519_SHA512, SEED).public
val json = mapper.valueToTree<TextNode>(publicKey)
assertThat(json.textValue()).isEqualTo(publicKey.toBase58String())
assertThat(mapper.convertValue<PublicKey>(json)).isEqualTo(publicKey)
}
@Test
fun CompositeKey() {
val innerKeys = (1..3).map { i ->
Crypto.deriveKeyPairFromEntropy(Crypto.EDDSA_ED25519_SHA512, SEED + i.toBigInteger()).public
}
// Build a 2 of 3 composite key
val publicKey = CompositeKey.Builder().let {
innerKeys.forEach { key -> it.addKey(key, 1) }
it.build(2)
}
val json = mapper.valueToTree<TextNode>(publicKey)
assertThat(json.textValue()).isEqualTo(publicKey.toBase58String())
assertThat(mapper.convertValue<CompositeKey>(json)).isEqualTo(publicKey)
}
@Test
fun AnonymousParty() {
val anon = AnonymousParty(ALICE_PUBKEY)
val json = mapper.valueToTree<TextNode>(anon)
assertThat(json.textValue()).isEqualTo(ALICE_PUBKEY.toBase58String())
assertThat(mapper.convertValue<AnonymousParty>(json)).isEqualTo(anon)
}
@Test
fun `PartyAndCertificate serialisation`() {
val json = mapper.valueToTree<ObjectNode>(MINI_CORP.identity)
assertThat(json.fieldNames()).containsOnly("name", "owningKey")
assertThat(mapper.convertValue<CordaX500Name>(json["name"])).isEqualTo(MINI_CORP.name)
assertThat(mapper.convertValue<PublicKey>(json["owningKey"])).isEqualTo(MINI_CORP.publicKey)
}
@Test
fun `NodeInfo serialisation`() {
val (nodeInfo) = createNodeInfoAndSigned(ALICE_NAME)
val json = mapper.valueToTree<ObjectNode>(nodeInfo)
assertThat(json.fieldNames()).containsOnly("addresses", "legalIdentitiesAndCerts", "platformVersion", "serial")
val address = (json["addresses"] as ArrayNode).also { assertThat(it).hasSize(1) }[0]
assertThat(mapper.convertValue<NetworkHostAndPort>(address)).isEqualTo(nodeInfo.addresses[0])
val identity = (json["legalIdentitiesAndCerts"] as ArrayNode).also { assertThat(it).hasSize(1) }[0]
assertThat(mapper.convertValue<CordaX500Name>(identity["name"])).isEqualTo(ALICE_NAME)
assertThat(mapper.convertValue<Int>(json["platformVersion"])).isEqualTo(nodeInfo.platformVersion)
assertThat(mapper.convertValue<Long>(json["serial"])).isEqualTo(nodeInfo.serial)
}
@Test
fun `NodeInfo deserialisation on name`() {
val (nodeInfo) = createNodeInfoAndSigned(ALICE_NAME)
fun convertToNodeInfo() = mapper.convertValue<NodeInfo>(TextNode(ALICE_NAME.toString()))
assertThatThrownBy { convertToNodeInfo() }
partyObjectMapper.identities += nodeInfo.legalIdentities
partyObjectMapper.nodes += nodeInfo
assertThat(convertToNodeInfo()).isEqualTo(nodeInfo)
}
@Test
fun `NodeInfo deserialisation on public key`() {
val (nodeInfo) = createNodeInfoAndSigned(ALICE_NAME)
fun convertToNodeInfo() = mapper.convertValue<NodeInfo>(TextNode(nodeInfo.legalIdentities[0].owningKey.toBase58String()))
assertThatThrownBy { convertToNodeInfo() }
partyObjectMapper.identities += nodeInfo.legalIdentities
partyObjectMapper.nodes += nodeInfo
assertThat(convertToNodeInfo()).isEqualTo(nodeInfo)
}
private fun makeDummyStx(): SignedTransaction {
val wtx = DummyContract.generateInitial(1, DUMMY_NOTARY, MINI_CORP.ref(1))
.toWireTransaction(services)
val signatures = listOf(
TransactionSignature(ByteArray(1), ALICE_PUBKEY, SignatureMetadata(1, Crypto.findSignatureScheme(ALICE_PUBKEY).schemeNumberID)),
TransactionSignature(ByteArray(1), BOB_PUBKEY, SignatureMetadata(1, Crypto.findSignatureScheme(BOB_PUBKEY).schemeNumberID))
)
return SignedTransaction(wtx, signatures)
}
private inline fun <reified T : Any> testToStringSerialisation(value: T) {
val json = mapper.valueToTree<TextNode>(value)
assertThat(json.textValue()).isEqualTo(value.toString())
assertThat(mapper.convertValue<T>(json)).isEqualTo(value)
}
private class TestPartyObjectMapper : JacksonSupport.PartyObjectMapper {
val identities = ArrayList<Party>()
val nodes = ArrayList<NodeInfo>()
override fun wellKnownPartyFromX500Name(name: CordaX500Name): Party? {
return identities.find { it.name == name }
}
override fun partyFromKey(owningKey: PublicKey): Party? {
return identities.find { it.owningKey == owningKey }
}
override fun partiesFromName(query: String): Set<Party> {
return identities.filter { query in it.name.toString() }.toSet()
}
override fun nodeInfoFromParty(party: AbstractParty): NodeInfo? {
return nodes.find { party in it.legalIdentities }
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e47a84ab49861d12320073b6ccb64cb5c4c18bf4
| 11,856
|
corda
|
Apache License 2.0
|
src/main/kotlin/com/piashcse/models/product/request/AddProduct.kt
|
piashcse
| 410,331,425
| false
| null |
package com.piashcse.models.product.request
import org.valiktor.functions.*
import org.valiktor.validate
data class AddProduct(
val categoryId: String,
val subCategoryId: String,
val brandId: String?,
val productName: String,
val productCode: String,
val productQuantity: Int,
val productDetail: String,
val price: Double,
val discountPrice: Double?,
val status: Int,
val videoLink: String?,
val mainSlider: String?,
val hotDeal: String?,
val bestRated: String?,
val midSlider: String?,
val hot_new: String?,
val trend: String?,
val buyOneGetOne: String?,
val imageOne: String?,
val imageTwo: String?,
) {
fun validation() {
validate(this) {
validate(AddProduct::categoryId).isNotNull().isNotEmpty()
validate(AddProduct::productName).isNotNull().isNotEmpty()
validate(AddProduct::productDetail).isNotNull().isNotEmpty()
validate(AddProduct::price).isNotNull().isGreaterThan(0.0)
validate(AddProduct::productQuantity).isNotNull().isGreaterThan(0)
}
}
}
/*data class AddProduct(val map: Map<String?, PartData>) {
val categoryId: PartData.FormItem by map
val title: PartData.FormItem by map
val description: PartData.FormItem by map
val price: PartData.FormItem by map
val discountPrice: PartData.FormItem by map
val quantity: PartData.FormItem by map
val shopId: PartData.FormItem by map
val color: PartData.FormItem by map
val size: PartData.FormItem by map
fun validation() {
validate(this) {
validate(AddProduct::categoryId).isNotNull()
validate(AddProduct::title).isNotNull()
validate(AddProduct::price).isNotNull()
}
}
}*/
| 0
|
Kotlin
|
2
| 18
|
a75eb54470bd2171f144d9b63580c2179168d3ff
| 1,789
|
ktor-E-Commerce
|
Apache License 2.0
|
src/main/kotlin/xyz/jptrzy/specialized/bundles/items/LunchboxItem.kt
|
jptrzy
| 790,254,371
| false
|
{"Kotlin": 15126}
|
package xyz.jptrzy.specialized.bundles.items
import eu.pb4.polymer.core.api.item.PolymerItem
import net.fabricmc.fabric.api.item.v1.FabricItemSettings
import net.minecraft.item.BundleItem
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.server.network.ServerPlayerEntity
class LunchboxItem : BundleLikeItem, PolymerItem {
constructor() : super(
64,
FabricItemSettings()
){
}
override fun getPolymerItem(itemStack: ItemStack?, player: ServerPlayerEntity?): Item {
return if (itemStack!!.count > 32) Items.REDSTONE else Items.SPRUCE_WOOD;
}
override fun getPolymerCustomModelData(itemStack: ItemStack?, player: ServerPlayerEntity?): Int {
return super.getPolymerCustomModelData(itemStack, player)
}
}
| 1
|
Kotlin
|
0
| 0
|
2a0d35f69a47bd0edc08c309f59dbf5f35d9b442
| 836
|
specialized-bundles-mod
|
MIT License
|
buildSrc/src/main/kotlin/ProjectExtensions.kt
|
Crazy-Marvin
| 114,458,675
| false
|
{"Kotlin": 290284, "Python": 841}
|
import org.gradle.api.Project
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.*
fun File.asProperties(): Properties {
return Properties()
.apply {
this@asProperties.takeIf(File::exists)
?.inputStream()
?.use { load(it) }
}
}
fun Project.properties(path: Any): Properties = file(path).asProperties()
val Project.localProperties: Properties
get() = properties("local.properties")
fun Properties.asStringMap() =
map { (key, value) -> key.toString() to value.toString() }.toMap()
val Project.latestCommitHash: String
get() {
return ByteArrayOutputStream()
.also { stream ->
exec {
commandLine = listOf(
"git",
"rev-parse",
"--short",
"HEAD"
)
standardOutput = stream
}
}
.toString()
.trim()
}
| 9
|
Kotlin
|
15
| 93
|
7f40dbb24a057a0395c57a07483f40fb71b040d6
| 1,145
|
MetadataRemover
|
Apache License 2.0
|
src/main/kotlin/no/nav/sosialhjelp/modia/utbetalinger/UtbetalingerResponse.kt
|
navikt
| 216,780,859
| false
|
{"Kotlin": 461383, "Dockerfile": 427}
|
package no.nav.sosialhjelp.modia.utbetalinger
import com.fasterxml.jackson.annotation.JsonFormat
import no.nav.sosialhjelp.modia.digisossak.domain.UtbetalingsStatus
import java.time.LocalDate
data class UtbetalingerResponse(
val tittel: String?,
val belop: Double,
@JsonFormat(pattern = "yyyy-MM-dd")
val utbetalingEllerForfallDigisosSoker: LocalDate?,
val status: UtbetalingsStatus,
val fiksDigisosId: String,
@JsonFormat(pattern = "yyyy-MM-dd")
val fom: LocalDate?,
@JsonFormat(pattern = "yyyy-MM-dd")
val tom: LocalDate?,
val mottaker: String?,
val annenMottaker: Boolean,
val kontonummer: String?,
val utbetalingsmetode: String?,
val harVilkar: Boolean,
val navKontor: NavKontor?
)
data class NavKontor(
val enhetsNavn: String,
val enhetsNr: String
)
| 1
|
Kotlin
|
0
| 1
|
e5eda33bfcf16d2f519a76a53349005b064dcd1c
| 830
|
sosialhjelp-modia-api
|
MIT License
|
app/src/main/java/mx/luix/mymovies/data/server/TheMovieDbDataSource.kt
|
luix
| 281,203,060
| false
| null |
package mx.luix.mymovies.data.server
import mx.luix.mymovies.data.source.RemoteDataSource
import mx.luix.mymovies.data.toDomainMovie
import mx.luix.mymovies.domain.Movie
class TheMovieDbDataSource(private val theMovieDb: TheMovieDb) : RemoteDataSource {
override suspend fun getPopularMovies(apiKey: String, region: String): List<Movie> =
theMovieDb.service
.listPopularMoviesAsync(apiKey, region)
.results
.map { it.toDomainMovie() }
}
| 0
|
Kotlin
|
0
| 0
|
eaad7aa8d6ee9dc5d17acd8a0aea6cd657d20c56
| 487
|
architect-coders
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/DoNotDisturbSharp.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/DoNotDisturbSharp")
package mui.icons.material
@JsName("default")
external val DoNotDisturbSharp: SvgIconComponent
| 12
|
Kotlin
|
5
| 983
|
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
| 198
|
kotlin-wrappers
|
Apache License 2.0
|
common/src/commonMain/kotlin/io/tonnyl/moka/common/data/Direction.kt
|
ETSEmpiricalStudyKotlinAndroidApps
| 496,360,843
| false
|
{"Kotlin": 1391177, "Swift": 100384, "CSS": 30407, "JavaScript": 13933, "Shell": 2990}
|
package io.tonnyl.moka.common.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class Direction(val rawValue: String) {
@SerialName("asc")
Ascending("asc"),
@SerialName("desc")
Descending("desc")
}
| 0
| null |
0
| 0
|
34db6153b274028158de1ee08f080b1a8f985325
| 274
|
Moka
|
MIT License
|
Filters/src/main/kotlin/opekope2/optigui/filter/PostProcessorFilter.kt
|
opekope2
| 578,779,647
| false
|
{"Kotlin": 168622, "Java": 45138}
|
package opekope2.optigui.filter
/**
* A post-processor filter, which enables the output of the given sub-filter to be changed.
*
* Useful, when the sub-filter doesn't yield a result (like [ConjunctionFilter] or [DisjunctionFilter])
*
* @param T The type the filter accepts
* @param TFilterResult The type the sub-filter's returns
* @param TResult The type the filter returns
* @param filter The sub-filter to evaluate
* @param transform The function, which transforms the result of [evaluate].
* Its input is both the input of [evaluate] and the result of [filter]
*
* @see PreProcessorFilter
*/
class PostProcessorFilter<T, TFilterResult, TResult : Any>(
private val filter: IFilter<T, out TFilterResult>,
private val transform: (input: T, result: IFilter.Result<out TFilterResult>) -> IFilter.Result<out TResult>
) : IFilter<T, TResult>, Iterable<IFilter<T, out TFilterResult>> {
/**
* Creates a new post-processor filter by specifying [IFilter.Result.Match.result].
*
* @param filter The sub-filter to evaluate
* @param result The (constant) result of the [transform] function
*/
constructor(filter: IFilter<T, out TFilterResult>, result: TResult) : this(
filter,
{ _, filterResult -> filterResult.withResult(result) }
)
override fun evaluate(value: T): IFilter.Result<out TResult> = transform(value, filter.evaluate(value))
override fun iterator(): Iterator<IFilter<T, out TFilterResult>> = setOf(filter).iterator()
override fun toString(): String = javaClass.name
}
| 14
|
Kotlin
|
1
| 17
|
7d806e6201a8b9d7920992e9eb70897e3ba91a84
| 1,561
|
OptiGUI
|
MIT License
|
codebase/android/core/ui/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/ui/component/bottomsheet/account/SelectAccountListItemBottomSheetUIData.kt
|
Abhimanyu14
| 429,663,688
| false
|
{"Kotlin": 1876553}
|
package com.makeappssimple.abhimanyu.financemanager.android.core.ui.component.bottomsheet.account
import androidx.annotation.StringRes
import androidx.compose.runtime.Immutable
import com.makeappssimple.abhimanyu.financemanager.android.core.ui.component.listitem.accounts.AccountsListItemContentDataAndEventHandler
@Immutable
internal data class SelectAccountListItemBottomSheetUIData(
@StringRes val titleTextStringResourceId: Int = 0,
val data: List<AccountsListItemContentDataAndEventHandler> = emptyList(),
)
| 11
|
Kotlin
|
0
| 3
|
7e080a68bc038bd64d2d406b75a49e8f1ea2a791
| 523
|
finance-manager
|
Apache License 2.0
|
src/main/kotlin/com/example/gungjeonjegwa/domain/bread/service/BreadService.kt
|
gungjeonjegwa
| 579,803,041
| false
| null |
package com.example.gungjeonjegwa.domain.bread.service
import com.example.gungjeonjegwa.domain.bread.data.dto.BreadDetailQueryDto
import com.example.gungjeonjegwa.domain.bread.data.dto.BreadDto
import com.example.gungjeonjegwa.domain.bread.data.dto.BreadQueryDto
import com.example.gungjeonjegwa.domain.bread.data.enum.Category
import org.springframework.data.domain.PageRequest
interface BreadService {
fun findAllPost(pagination: PageRequest): BreadQueryDto
fun findAllPostByCategory(pagination: PageRequest, category: Category): BreadQueryDto
fun findPostByIndex(id: Long): BreadDetailQueryDto
}
| 0
|
Kotlin
|
0
| 0
|
30a77ac8c8ec594a6d1267ae36df365f1622f250
| 616
|
GGJG-Backend
|
MIT License
|
app/src/main/java/com/example/filemanager/FileUtil.kt
|
zeyang919
| 275,339,202
| false
| null |
package com.example.filemanager
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.OutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
class FileUtil {
/**
* 检测所删除项目为文件还是文件夹
* @param fileName 文件名
*/
fun delete(fileName: String?) {
val file = File(fileName)
if (!file.exists()) {
println("删除文件失败:" + fileName + "不存在!")
} else {
if (file.isFile) deleteFile(fileName) else deleteDirectory(fileName)
}
}
fun renameFile(path: String?, oldname: String?, newname: String) {
val oldfile = File("$path/$oldname")
val newfile = File("$path/$newname")
if (!oldfile.exists()) {
println("重命名文件不存在")
return //重命名文件不存在
}
if (newfile.exists()) //若在该目录下已经有一个文件和新文件名相同,则不允许重命名
println(newname + "已经存在!") else {
oldfile.renameTo(newfile)
}
}
companion object {
private const val BUFFER_SIZE = 2 * 1024
fun deleteFile(fileName: String?): Boolean {
val file = File(fileName)
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
return if (file.exists() && file.isFile) {
if (file.delete()) {
println("删除单个文件" + fileName + "成功!")
true
} else {
println("删除单个文件" + fileName + "失败!")
false
}
} else {
println("删除单个文件失败:" + fileName + "不存在!")
false
}
}
fun deleteDirectory(dir: String?): Boolean { // 如果dir不以文件分隔符结尾,自动添加文件分隔符
var dir = dir
if (!dir!!.endsWith(File.separator)) dir = dir + File.separator
val dirFile = File(dir)
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory) {
println("删除目录失败:" + dir + "不存在!")
return false
}
var flag = true
// 删除文件夹中的所有文件包括子目录
val files = dirFile.listFiles()
for (i in files.indices) { // 删除子文件
if (files[i].isFile) {
flag = deleteFile(files[i].absolutePath)
if (!flag) break
} else if (files[i].isDirectory) {
flag = deleteDirectory(files[i].absolutePath)
if (!flag) break
}
}
if (!flag) {
println("删除目录失败!")
return false
}
// 删除当前目录
return if (dirFile.delete()) {
println("删除目录" + dir + "成功!")
true
} else {
false
}
}
}
}
| 0
|
Kotlin
|
2
| 2
|
14fbb7fdf4c0aae79405557dbd27c398b26d28ac
| 2,817
|
FileManager
|
MIT License
|
kmp/compose/foundation/icons/src/commonMain/kotlin/com/egoriku/grodnoroads/foundation/icons/outlined/ArrowRight.kt
|
BehindWheel
| 485,026,420
| false
|
{"Kotlin": 1186756, "Ruby": 5708, "Swift": 1889, "Shell": 830}
|
package com.egoriku.grodnoroads.foundation.icons.outlined
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.egoriku.grodnoroads.foundation.icons.GrodnoRoads
val GrodnoRoads.Outlined.ArrowRight: ImageVector
get() {
if (_ArrowRight != null) {
return _ArrowRight!!
}
_ArrowRight = ImageVector.Builder(
name = "Outlined.ArrowRight",
defaultWidth = 24.dp,
defaultHeight = 24.dp,
viewportWidth = 24f,
viewportHeight = 24f
).apply {
path(fill = SolidColor(Color(0xFFE676FF))) {
moveTo(3f, 12.688f)
curveTo(3f, 13.24f, 3.448f, 13.688f, 4f, 13.688f)
lineTo(17.452f, 13.688f)
lineTo(11.513f, 19.531f)
curveTo(11.125f, 19.913f, 11.114f, 20.535f, 11.488f, 20.931f)
lineTo(11.793f, 21.254f)
curveTo(12.181f, 21.663f, 12.829f, 21.671f, 13.227f, 21.273f)
lineTo(22f, 12.5f)
lineTo(13.207f, 3.707f)
curveTo(12.817f, 3.317f, 12.183f, 3.317f, 11.793f, 3.707f)
lineTo(11.532f, 3.968f)
curveTo(11.142f, 4.358f, 11.142f, 4.991f, 11.531f, 5.381f)
lineTo(17.452f, 11.313f)
lineTo(4f, 11.313f)
curveTo(3.448f, 11.313f, 3f, 11.76f, 3f, 12.313f)
verticalLineTo(12.688f)
close()
}
}.build()
return _ArrowRight!!
}
private var _ArrowRight: ImageVector? = null
| 19
|
Kotlin
|
1
| 18
|
07b1ec1f97c6f4a4948ba28b7cd0743f8efa850a
| 1,748
|
BehindWheelKMP
|
Apache License 2.0
|
android/src/main/java/com/reactnativeiosmapviewobjc/IosMapviewObjcPackage.kt
|
shengchenmicrosoftworkemail
| 314,676,862
| false
|
{"Java": 6326, "Ruby": 6147, "Objective-C": 4480, "TypeScript": 1855, "JavaScript": 1419, "Kotlin": 1374, "C": 103, "Swift": 66}
|
package com.reactnativeiosmapviewobjc
import java.util.Arrays
import java.util.Collections
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
import com.facebook.react.bridge.JavaScriptModule
class IosMapviewObjcPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return Arrays.asList<NativeModule>(IosMapviewObjcModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList<ViewManager<*, *>>()
}
}
| 1
| null |
1
| 1
|
b10f972145fcd737f398f67f12448fd4e98ca956
| 719
|
RNBindingWithIOS
|
MIT License
|
app/src/main/java/com/newkirkj/seattlesearch/ui/main/MainActivity.kt
|
newkirkjosh
| 187,752,979
| false
| null |
package com.newkirkj.seattlesearch.ui.main
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.newkirkj.seattlesearch.R
import com.newkirkj.seattlesearch.networking.foursquare.models.VenueSearchItem
import com.newkirkj.seattlesearch.ui.venuedetail.VenueDetailActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity(),
MainViewModel.MainContract,
VenueSearchRecyclerAdapter.VenueSearchItemClickListener {
private lateinit var viewModel: MainViewModel
private var searchRecyclerAdapter: VenueSearchRecyclerAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
init()
fab.setOnClickListener { view ->
Toast.makeText(
view.context,
"If time allows, implement full screen map with pins for search results.",
Toast.LENGTH_SHORT
).show()
}
}
override fun onResume() {
Log.d(TAG, "onResume hit")
super.onResume()
viewModel.refreshData()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
val searchView = menu.findItem(R.id.action_search).actionView as SearchView
searchView.setOnQueryTextListener(viewModel)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_search -> return true
else -> super.onOptionsItemSelected(item)
}
}
private fun init() {
setupRecyclerView()
setupViewModel()
}
private fun setupViewModel() {
val viewModelFactory = MainViewModelFactory(this)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel::class.java)
viewModel.getVenueSearchItems().observe(this, Observer<List<VenueSearchItem>> { searchItems ->
searchRecyclerAdapter?.updateSearchItems(searchItems)
})
viewModel.getSearchResultsVisibility().observe(this, Observer {
search_recyclerview?.visibility = if (it) View.VISIBLE else View.GONE
if (it) fab?.show() else fab?.hide()
welcome_message?.visibility = if (it) View.GONE else View.VISIBLE
})
viewModel.getWelcomeMessage().observe(this, Observer {
welcome_message.text = it
})
}
private fun setupRecyclerView() {
if (searchRecyclerAdapter == null) {
searchRecyclerAdapter = VenueSearchRecyclerAdapter(listOf(), this)
}
search_recyclerview.adapter = searchRecyclerAdapter
search_recyclerview.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
}
// VenueSearchRecyclerAdapter.VenueSearchItemClickListener
override fun onItemClick(view: View, position: Int) {
viewModel.searchItemClicked(position)
}
// MainViewModel.MainContract
override fun launchDetail(venueSearchItem: VenueSearchItem) {
Log.d(TAG, "launchDetail: for item ${venueSearchItem.id}")
val intent = Intent(this@MainActivity, VenueDetailActivity::class.java)
intent.putExtra(VenueSearchItem.EXTRA_TAG, venueSearchItem)
startActivity(intent)
}
companion object {
private const val TAG = "MainActivity"
}
}
| 0
|
Kotlin
|
0
| 0
|
122b9eac4c5d824bd11a637fe8f03418d057c43d
| 4,042
|
android-homeaway-challenge
|
MIT License
|
src/main/day15/Part1.kt
|
ollehagner
| 572,141,655
| false
| null |
package day15
import common.Point
import readInput
import kotlin.math.abs
fun main() {
val sensors = parseInput(readInput("day15/input.txt"))
val rowToCheck = 2000000
val beaconsInRow = sensors.map { it.beacon }.filter { it.y == rowToCheck }.distinct().count()
val positionsWithNoBeacon = coveredRowPositions(sensors, rowToCheck)
.sumOf { it.count() } - beaconsInRow
println("Day 15 part 1. Positions with no beacons: $positionsWithNoBeacon")
}
fun coveredRowPositions(sensors: List<Sensor>, rowToCheck: Int): List<IntRange> {
return sensors
.map { it.rowCoverage(rowToCheck) }
.filterNotNull()
.fold(listOf()) { acc, rowCoverage ->
merge(buildList {
addAll(acc)
add(rowCoverage)
})
}
}
fun merge(ranges: List<IntRange>): List<IntRange> {
if(ranges.size == 1) return ranges
val toCheck = ranges.first()
val overlapping = ranges.drop(1).filter { it.overlapsOrAdjoins(toCheck) }
val notOverlapping = ranges.drop(1).filter { !it.overlapsOrAdjoins(toCheck) }
return if(overlapping.isEmpty()) {
listOf(listOf(toCheck), merge(ranges.drop(1))).flatten()
} else {
val merged = overlapping.fold(toCheck) { acc, value -> acc.merge(value) }
return merge(listOf(listOf(merged), notOverlapping).flatten())
}
}
fun parseInput(input: List<String>): List<Sensor> {
val pattern = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""")
return input
.map{ pattern.find(it)!!.destructured }
.map { (sensorX, sensorY, beaconX, beaconY) -> Sensor(Point(sensorX.toInt(), sensorY.toInt()), Point(beaconX.toInt(), beaconY.toInt())) }
}
data class Sensor(val position: Point, val beacon: Point) {
fun rowCoverage(yValue: Int): IntRange? {
val horizontalReach = position.manhattanDistance(beacon) - abs(position.y - yValue)
return if(horizontalReach > 0) {
IntRange(position.x - horizontalReach, position.x + horizontalReach)
} else {
null
}
}
}
private infix fun IntRange.overlapsOrAdjoins(other: IntRange): Boolean =
(first <= other.last && other.first <= last) || last + 1 == other.first || other.last + 1 == first
private infix fun IntRange.merge(other: IntRange): IntRange {
return IntRange(minOf(first, other.first), maxOf(last, other.last))
}
| 0
|
Kotlin
|
0
| 0
|
b935fcfb465152f08307399eb85ee8a8a335f1a3
| 2,433
|
aoc2022
|
Apache License 2.0
|
src/main/kotlin/com/emberjs/hbs/HbsCompletionContributor.kt
|
patricklx
| 412,986,421
| false
| null |
package com.emberjs.hbs
import com.emberjs.hbs.HbsPatterns.BLOCK_MUSTACHE_NAME_ID
import com.emberjs.hbs.HbsPatterns.BLOCK_MUSTACHE_PARAM
import com.emberjs.hbs.HbsPatterns.IMPORT_NAMES
import com.emberjs.hbs.HbsPatterns.IMPORT_PATH_AUTOCOMPLETE
import com.emberjs.hbs.HbsPatterns.MUSTACHE_ID_MISSING
import com.emberjs.hbs.HbsPatterns.MUSTACHE_ID
import com.emberjs.hbs.HbsPatterns.SIMPLE_MUSTACHE_NAME_ID
import com.emberjs.hbs.HbsPatterns.SUB_EXPR_NAME_ID
import com.emberjs.hbs.HbsPatterns.inXmlTag
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.patterns.XmlTagPattern
val InternalsWithBlock = arrayListOf(
"component",
"each",
"each-in",
"if",
"input",
"let",
"link-to",
"mount",
"outlet",
"query-params",
"textarea",
"unbound",
"unless",
"with")
val InternalsWithoutBlock = arrayListOf(
"action",
"array",
"component",
"concat",
"debugger",
"fn",
"get",
"hasBlock",
"hasBlockParams",
"hash",
"if",
"in-element",
"input",
"link-to",
"loc",
"log",
"mount",
"mut",
"on",
"outlet",
"query-params",
"textarea",
"unbound",
"unless",
"yield")
/**
* The `HbsCompletionContributor` class is responsible for registering all
* available `CompletionProviders` for the Handlebars language to their
* corresponding `PsiElementPatterns`.
*/
class HbsCompletionContributor : CompletionContributor() {
init {
extend(CompletionType.BASIC, SIMPLE_MUSTACHE_NAME_ID, HbsBuiltinHelperCompletionProvider(InternalsWithoutBlock))
extend(CompletionType.BASIC, BLOCK_MUSTACHE_NAME_ID, HbsBuiltinHelperCompletionProvider(InternalsWithBlock))
extend(CompletionType.BASIC, SUB_EXPR_NAME_ID, HbsBuiltinHelperCompletionProvider(InternalsWithoutBlock))
extend(CompletionType.BASIC, SIMPLE_MUSTACHE_NAME_ID, HbsLocalCompletion())
extend(CompletionType.BASIC, BLOCK_MUSTACHE_NAME_ID, HbsLocalCompletion())
extend(CompletionType.BASIC, SUB_EXPR_NAME_ID, HbsLocalCompletion())
extend(CompletionType.BASIC, MUSTACHE_ID, HbsLocalCompletion())
extend(CompletionType.BASIC, IMPORT_NAMES, HbsLocalCompletion())
extend(CompletionType.BASIC, IMPORT_PATH_AUTOCOMPLETE, HbsLocalCompletion())
extend(CompletionType.BASIC, BLOCK_MUSTACHE_PARAM, HbsLocalCompletion())
extend(CompletionType.BASIC, MUSTACHE_ID_MISSING, HbsLocalCompletion())
extend(CompletionType.BASIC, inXmlTag, HbsLocalCompletion())
}
}
| 1
|
Kotlin
|
1
| 5
|
10193476a26a4e11773c17281e4db1c23e2ca06b
| 2,785
|
intellij-emberjs-experimental
|
Apache License 2.0
|
app/src/main/java/com/example/nisa/soundrecorder/recorder/RecorderViewModel.kt
|
nisajamalia
| 424,438,074
| false
|
{"Kotlin": 17063}
|
package com.example.nisa.soundrecorder.recorder
import android.arch.lifecycle.ViewModel
import com.example.nisa.soundrecorder.util.RecorderState
class RecorderViewModel(val recorderRepository: RecorderRepository): ViewModel() {
var recorderState: RecorderState = RecorderState.Stopped
fun startRecording() = recorderRepository.startRecording()
fun stopRecording() = recorderRepository.stopRecording()
fun pauseRecording() = recorderRepository.pauseRecording()
fun resumeRecording() = recorderRepository.resumeRecording()
fun getRecordingTime() = recorderRepository.getRecordingTime()
}
| 0
|
Kotlin
|
0
| 0
|
0ecb4ef81d7479401e57af0270c75c32722ce4d7
| 618
|
SoundRecorder
|
MIT License
|
src/main/kotlin/org/ocpp/client/server/ServerRequestService.kt
|
NLCProject
| 494,622,679
| false
|
{"Kotlin": 45823}
|
package org.ocpp.client.server
import eu.chargetime.ocpp.model.core.*
import org.ocpp.client.server.interfaces.IServerRequestService
import org.ocpp.client.server.interfaces.IServerService
import org.ocpp.client.utils.Ids
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class ServerRequestService @Autowired constructor(
private val service: IServerService
) : IServerRequestService {
private val logger = LoggerFactory.getLogger(this::class.java)
override fun changeAvailability(
connectorId: Int,
type: AvailabilityType,
sessionIndex: String
): ChangeAvailabilityConfirmation {
logger.info("Sending server request | Change Availability | session index '$sessionIndex'")
val request = ChangeAvailabilityRequest(connectorId, type)
return service.send(request = request, sessionIndex = sessionIndex) as ChangeAvailabilityConfirmation
}
override fun getConfiguration(keys: Array<String>, sessionIndex: String): GetConfigurationConfirmation {
// Currently, not handled by server
logger.info("Sending server request | Get Configuration | session index '$sessionIndex'")
val request = GetConfigurationRequest()
request.key = keys
return service.send(request = request, sessionIndex = sessionIndex) as GetConfigurationConfirmation
}
override fun changeConfiguration(
key: String,
value: String,
sessionIndex: String
): ChangeConfigurationConfirmation {
// Currently, not handled by server
logger.info("Sending server request | Change Configuration | session index '$sessionIndex'")
val request = ChangeConfigurationRequest(key, value)
return service.send(request = request, sessionIndex = sessionIndex) as ChangeConfigurationConfirmation
}
override fun clearCache(sessionIndex: String): ClearCacheConfirmation {
logger.info("Sending server request | Clear Cache | session index '$sessionIndex'")
val request = ClearCacheRequest()
return service.send(request = request, sessionIndex = sessionIndex) as ClearCacheConfirmation
}
override fun dataTransfer(vendorId: String, data: String, sessionIndex: String): DataTransferConfirmation {
// Currently, not handled by server
logger.info("Sending server request | Data Transfer | session index '$sessionIndex'")
val request = DataTransferRequest(vendorId)
request.data = data
return service.send(request = request, sessionIndex = sessionIndex) as DataTransferConfirmation
}
override fun remoteStartTransaction(
connectorId: Int,
idTag: String,
profile: ChargingProfile?,
sessionIndex: String
): RemoteStartTransactionConfirmation {
logger.info("Sending server request | Remote Start Transaction | session index '$sessionIndex'")
val request = RemoteStartTransactionRequest(Ids.getRandomId().toString())
request.idTag = idTag
request.connectorId = connectorId
request.chargingProfile = profile
return service.send(request = request, sessionIndex = sessionIndex) as RemoteStartTransactionConfirmation
}
override fun remoteStopTransaction(transactionId: Int, sessionIndex: String): RemoteStopTransactionConfirmation {
logger.info("Sending server request | Remote Stop Transaction | session index '$sessionIndex'")
val request = RemoteStopTransactionRequest(transactionId)
return service.send(request = request, sessionIndex = sessionIndex) as RemoteStopTransactionConfirmation
}
override fun reset(type: ResetType, sessionIndex: String): ResetConfirmation {
logger.info("Sending server request | Reset")
val request = ResetRequest(type)
return service.send(request = request, sessionIndex = sessionIndex) as ResetConfirmation
}
override fun unlockConnector(connectorId: Int, sessionIndex: String): UnlockConnectorConfirmation {
logger.info("Sending server request | Unlock Connector | session index '$sessionIndex'")
val request = UnlockConnectorRequest(connectorId)
return service.send(request = request, sessionIndex = sessionIndex) as UnlockConnectorConfirmation
}
}
| 0
|
Kotlin
|
0
| 0
|
26e0d5608de1daa723ef0f03ffc20e083e497d39
| 4,369
|
OcppClient
|
ISC License
|
app/src/main/java/ru/maxim/barybians/data/network/exception/NotFoundException.kt
|
maximborodkin
| 286,116,912
| false
| null |
package ru.maxim.barybians.data.network.exception
import java.io.IOException
/**
* Exception class for represent 404 HTTP code
**/
class NotFoundException : IOException()
| 0
|
Kotlin
|
1
| 5
|
033704d0e141bce002800c6bc00fd19983acc99f
| 174
|
Barybians-Android-App
|
MIT License
|
app/src/main/java/com/liamgoodwin/movieslist/util/Constants.kt
|
liamgoodwin
| 521,338,970
| false
|
{"Kotlin": 25552}
|
package com.liamgoodwin.movieslist.util
object Constants {
const val OMDB_BASE_URL = "http://www.omdbapi.com"
const val OMDB_API_KEY = "your_api_key_here"
const val PER_PAGE = 10
}
| 0
|
Kotlin
|
0
| 0
|
d714e0cecfea654a18fa2817ce9c230287832b83
| 193
|
movies-list
|
MIT License
|
sdk/src/main/kotlin/com/cobox/vulture/standard/xutil/NetAddress.kt
|
Mysterious-organization
| 336,003,139
| false
| null |
package com.cobox.vulture.standard.xutil
import java.net.InetAddress
object NetAddress {
val EMPTY_ADDRESS = InetAddress.getByAddress(byteArrayOf(0, 0, 0, 0))
}
| 0
|
Kotlin
|
0
| 3
|
ae0c4a9b7f12bc556a5e9a674ab5a14b6a581ce4
| 168
|
Vulture-Station
|
MIT License
|
cxrv/src/main/java/com/xiaocydx/cxrv/list/ListOwner.kt
|
xiaocydx
| 460,257,515
| false
| null |
package com.xiaocydx.cxrv.list
import androidx.annotation.MainThread
/**
* 列表所有者
*
* @author xcc
* @date 2021/9/11
*/
interface ListOwner<T : Any> {
/**
* 当前列表
*
* 通过[getItem]、[getItemOrNull]等扩展函数可以访问列表。
*/
val currentList: List<T>
/**
* 更新列表,该函数必须在主线程调用
*
* 通过[submitList]、[setItem]等扩展函数可以更新列表。
*/
@MainThread
fun updateList(op: UpdateOp<T>)
}
/**
* item数量
*/
val ListOwner<*>.size: Int
get() = currentList.size
/**
* 通过[position]获取item
*/
fun <T : Any> ListOwner<T>.getItem(position: Int): T = currentList[position]
/**
* 通过[position]获取item
*
* @param position 取值范围[0, size),若超过则返回`null`
*/
fun <T : Any> ListOwner<T>.getItemOrNull(position: Int): T? = currentList.getOrNull(position)
/**
* 返回与[predicate]匹配的第一个item,如果未找到item,则返回null。
*/
inline fun <T : Any> ListOwner<T>.getItemOrNull(
predicate: (T) -> Boolean
): T? = currentList.firstOrNull(predicate)
/**
* [position]是否为第一个item
*/
fun ListOwner<*>.isFirstItem(position: Int): Boolean {
return currentList.isNotEmpty() && position == 0
}
/**
* [position]是否为最后一个item
*/
fun ListOwner<*>.isLastItem(position: Int): Boolean {
return position == currentList.lastIndex
}
/**
* 提交新列表,该函数必须在主线程调用
*
* 通过[submitChange]、[submitTransform]可以方便的更改列表。
*
* @param newList 需要是新的列表对象,若传入旧的列表对象,则不会更改。
* 若[newList]的类型是[SafeMutableList],则表示可作为内部的可变列表。
*/
@MainThread
fun <T : Any> ListOwner<T>.submitList(newList: List<T>) {
updateList(UpdateOp.SubmitList(newList))
}
/**
* 设置item,该函数必须在主线程调用
*
* **注意**:当[item]为新对象时,才能跟旧对象进行差异对比。
*
* @param position 取值范围[0, size),越界时不会抛出异常,仅作为无效操作.
*/
@MainThread
fun <T : Any> ListOwner<T>.setItem(position: Int, item: T) {
updateList(UpdateOp.SetItem(position, item))
}
/**
* 设置items,该函数必须在主线程调用
*
* **注意**:当[items]的元素为新对象时,才能跟旧对象进行差异对比。
*
* @param position 取值范围[0, size),越界时不会抛出异常,仅作为无效操作。
* @param items 设置范围[position, size),元素越界时不会抛出异常。
*/
@MainThread
fun <T : Any> ListOwner<T>.setItems(position: Int, items: List<T>) {
updateList(UpdateOp.SetItems(position, items))
}
/**
* 添加item,该函数必须在主线程调用
*
* @param position 取值范围[0, size],越界时不会抛出异常,仅作为无效操作。
*/
@MainThread
fun <T : Any> ListOwner<T>.addItem(position: Int, item: T) {
updateList(UpdateOp.AddItem(position, item))
}
/**
* 添加items,该函数必须在主线程调用
*
* @param position 取值范围[0, size],越界时不会抛出异常,仅作为无效操作。
*/
@MainThread
fun <T : Any> ListOwner<T>.addItems(position: Int, items: List<T>) {
updateList(UpdateOp.AddItems(position, items))
}
/**
* 移除起始下标为[position]的[itemCount]个item,该函数必须在主线程调用
*
* @param position 取值范围[0, size),越界时不会抛出异常,仅作为无效操作。
* @param itemCount 小于1不会抛出异常,仅作为无效操作。
*/
@MainThread
fun ListOwner<*>.removeItems(position: Int, itemCount: Int) {
updateList(UpdateOp.RemoveItems(position, itemCount))
}
/**
* 下标为[fromPosition]的item移动至[toPosition],该函数必须在主线程调用
*
* @param fromPosition 取值范围[0, size),越界时不会抛出异常,仅作为无效操作。
* @param toPosition 取值范围[0, size),越界时不会抛出异常,仅作为无效操作。
*/
@MainThread
fun ListOwner<*>.moveItem(fromPosition: Int, toPosition: Int) {
updateList(UpdateOp.MoveItem(fromPosition, toPosition))
}
/**
* 交换下标为[fromPosition]和[toPosition]的item,该函数必须在主线程调用
*
* @param fromPosition 取值范围[0, size),越界时不会抛出异常,仅作为无效操作。
* @param toPosition 取值范围[0, size),越界时不会抛出异常,仅作为无效操作。
*/
@MainThread
@Deprecated(
message = "早期理解错误,以为局部更新的move等同于swap",
replaceWith = ReplaceWith("moveItem(fromPosition, toPosition)")
)
fun ListOwner<*>.swapItem(fromPosition: Int, toPosition: Int) {
moveItem(fromPosition, toPosition)
}
/**
* 往首位插入item,该函数必须在主线程调用
*/
@MainThread
fun <T : Any> ListOwner<T>.insertItem(item: T) = addItem(0, item)
/**
* 往首位插入items,该函数必须在主线程调用
*/
@MainThread
fun <T : Any> ListOwner<T>.insertItems(items: List<T>) = addItems(0, items)
/**
* 移除下标为[position]的item,该函数必须在主线程调用
*
* @param position 取值范围[0, size),越界时不会抛出异常,仅作为无效操作。
*/
@MainThread
fun ListOwner<*>.removeItemAt(position: Int) = removeItems(position, itemCount = 1)
/**
* 移除item,该函数必须在主线程调用
*/
@MainThread
fun <T : Any> ListOwner<T>.removeItem(item: T) = removeItemAt(currentList.indexOfFirst { it === item })
/**
* 清空列表,该函数必须在主线程调用
*/
@MainThread
fun ListOwner<*>.clear() = submitList(emptyList())
/**
* 提交更改的列表,该函数必须在主线程调用
*
* ```
* listOwner.submitChange {
* removeFirst()
* }
* ```
*/
@MainThread
inline fun <T : Any> ListOwner<T>.submitChange(change: MutableList<T>.() -> Unit) {
currentList.toSafeMutableList().apply(change).also(::submitList)
}
/**
* 提交转换的列表,该函数必须在主线程调用
*
* ```
* listOwner.submitTransform {
* filter{...}.map{...}
* }
* ```
*/
@MainThread
inline fun <T : Any> ListOwner<T>.submitTransform(transform: MutableList<T>.() -> List<T>) {
currentList.toSafeMutableList().transform().also(::submitList)
}
/**
* 遍历[ListOwner.currentList],设置[block]返回的第一个不空的item,该函数必须在主线程调用
*/
@MainThread
inline fun <T : Any> ListOwner<T>.setFirstNotNull(block: (item: T) -> T?) {
for (position in currentList.indices) {
val item = block(getItem(position))
if (item != null) return setItem(position, item)
}
}
/**
* 反向遍历[ListOwner.currentList],设置[block]返回的最后一个不空的item,该函数必须在主线程调用
*/
@MainThread
inline fun <T : Any> ListOwner<T>.setLastNotNull(block: (item: T) -> T?) {
for (position in currentList.indices.reversed()) {
val item = block(getItem(position))
if (item != null) return setItem(position, item)
}
}
/**
* 返回安全的可变列表
*
* 这是和调用者之间的约定,返回的列表对[ListOwner.submitList]提交后,
* 不会再被其它地方修改,用于[ListOwner]的实现类减少列表copy次数。
*/
fun <T> Collection<T>.toSafeMutableList() = SafeMutableList(this)
/**
* 安全的可变列表
*
* 这是和调用者之间的约定,该列表对[ListOwner.submitList]提交后,
* 不会再被其它地方修改,用于[ListOwner]的实现类减少列表copy次数。
*/
open class SafeMutableList<T> : ArrayList<T> {
constructor() : super()
constructor(initialCapacity: Int) : super(initialCapacity)
constructor(collection: Collection<T>) : super(collection)
}
| 0
|
Kotlin
|
0
| 7
|
7283f04892a84661ff82f33eed377da2cc015874
| 5,908
|
CXRV
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/eks/CfnIdentityProviderConfigPropsDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.eks
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.eks.CfnIdentityProviderConfigProps
@Generated
public fun buildCfnIdentityProviderConfigProps(initializer: @AwsCdkDsl
CfnIdentityProviderConfigProps.Builder.() -> Unit): CfnIdentityProviderConfigProps =
CfnIdentityProviderConfigProps.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
e9a0ff020b0db2b99e176059efdb124bf822d754
| 464
|
aws-cdk-kt
|
Apache License 2.0
|
winter/src/main/kotlin/io/jentz/winter/plugin/PluginRegistry.kt
|
AlexWih
| 156,714,313
| true
|
{"Kotlin": 306587, "HTML": 9144, "Java": 5620, "Ruby": 2097}
|
package io.jentz.winter.plugin
import io.jentz.winter.ComponentBuilder
import io.jentz.winter.Graph
import io.jentz.winter.Scope
import java.util.concurrent.CopyOnWriteArrayList
/**
* The registry for [Winter plugins][Plugin].
*/
class PluginRegistry {
private val plugins = CopyOnWriteArrayList<Plugin>()
/**
* The number of registered plugins.
*/
val size: Int get() = plugins.size
/**
* Register a plugin.
*
* The plugin will only be registered if the registry doesn't already contain the plugin.
*
* @param plugin The plugin to register.
* @return True if plugin was added false otherwise.
*/
fun register(plugin: Plugin): Boolean {
if (contains(plugin)) return false
plugins.add(plugin)
return true
}
/**
* Unregister a plugin.
*
* @param plugin The plugin to register.
* @return False if the plugin wasn't found otherwise true.
*/
fun unregister(plugin: Plugin): Boolean = plugins.remove(plugin)
/**
* Unregister all plugins.
*/
fun unregisterAll() {
plugins.clear()
}
/**
* Returns true if the plugin is already registered.
*
* @param plugin The plugin to check for.
* @return true if the registry contains the plugin
*/
fun contains(plugin: Plugin): Boolean = plugins.contains(plugin)
/**
* Returns true if the registry contains no plugin.
*/
fun isEmpty(): Boolean = plugins.isEmpty()
/**
* Returns true if the registry contains plugins.
*/
fun isNotEmpty(): Boolean = plugins.isNotEmpty()
internal fun runPostConstruct(graph: Graph, scope: Scope, argument: Any, instance: Any) {
plugins.forEach { it.postConstruct(graph, scope, argument, instance) }
}
internal fun runInitializingComponent(graph: Graph?, builder: ComponentBuilder) {
plugins.forEach { it.initializingComponent(graph, builder) }
}
internal fun runGraphDispose(graph: Graph) {
plugins.forEach { it.graphDispose(graph) }
}
}
| 0
|
Kotlin
|
0
| 0
|
3c0ea4336c87fcbe38143dd6787390756fbfc68f
| 2,087
|
winter
|
Apache License 2.0
|
core/src/main/kotlin/org/rewedigital/dialog/model/google/order/OrderUpdate.kt
|
rewe-digital-incubator
| 169,550,416
| false
| null |
package org.rewedigital.dialog.model.google.order
interface OrderUpdate {
var googleOrderId: String?
var actionOrderId: String?
var orderState: OrderState?
var orderManagementActions: MutableList<OrderAction>
var receipt: Receipt?
var updateTime: String?
var totalPrice: Price?
var lineItemUpdates: LineItemUpdate?
var userNotification: UserNotification?
var infoExtension: Map<String, String>?
}
data class RejectedOrder(
override var googleOrderId: String? = null,
override var actionOrderId: String? = null,
override var orderState: OrderState? = null,
override var orderManagementActions: MutableList<OrderAction> = mutableListOf(),
override var receipt: Receipt? = null,
override var updateTime: String? = null,
override var totalPrice: Price? = null,
override var lineItemUpdates: LineItemUpdate? = null,
override var userNotification: UserNotification? = null,
override var infoExtension: Map<String, String>? = emptyMap(),
var rejectionInfo: RejectionInfo? = null
) : OrderUpdate
data class CanceledOrder(
override var googleOrderId: String? = null,
override var actionOrderId: String? = null,
override var orderState: OrderState? = null,
override var orderManagementActions: MutableList<OrderAction> = mutableListOf(),
override var receipt: Receipt? = null,
override var updateTime: String? = null,
override var totalPrice: Price? = null,
override var lineItemUpdates: LineItemUpdate? = null,
override var userNotification: UserNotification? = null,
override var infoExtension: Map<String, String>? = emptyMap(),
var cancellationInfo: Reason? = null
) : OrderUpdate
data class SentOrder(
override var googleOrderId: String? = null,
override var actionOrderId: String? = null,
override var orderState: OrderState? = null,
override var orderManagementActions: MutableList<OrderAction> = mutableListOf(),
override var receipt: Receipt? = null,
override var updateTime: String? = null,
override var totalPrice: Price? = null,
override var lineItemUpdates: LineItemUpdate? = null,
override var userNotification: UserNotification? = null,
override var infoExtension: Map<String, String>? = emptyMap(),
var inTransitInfo: InTransitInfo? = null
) : OrderUpdate
data class FulfilledOrder(
override var googleOrderId: String? = null,
override var actionOrderId: String? = null,
override var orderState: OrderState? = null,
override var orderManagementActions: MutableList<OrderAction> = mutableListOf(),
override var receipt: Receipt? = null,
override var updateTime: String? = null,
override var totalPrice: Price? = null,
override var lineItemUpdates: LineItemUpdate? = null,
override var userNotification: UserNotification? = null,
override var infoExtension: Map<String, String>? = emptyMap(),
var fulfillmentInfo: FulfillmentInfo? = null
) : OrderUpdate
data class ReturnedOrder(
override var googleOrderId: String? = null,
override var actionOrderId: String? = null,
override var orderState: OrderState? = null,
override var orderManagementActions: MutableList<OrderAction> = mutableListOf(),
override var receipt: Receipt? = null,
override var updateTime: String? = null,
override var totalPrice: Price? = null,
override var lineItemUpdates: LineItemUpdate? = null,
override var userNotification: UserNotification? = null,
override var infoExtension: Map<String, String>? = emptyMap(),
var returnInfo: Reason? = null
) : OrderUpdate
| 3
|
Kotlin
|
5
| 10
|
7ea2fac743323acd9e17f41eb4511df1782b874d
| 3,604
|
dialog
|
MIT License
|
app/src/main/java/com/mlm09kdev/superHeroDB/ui/superhero/search/SearchViewModel.kt
|
mlm09kDev
| 236,341,237
| false
| null |
package com.mlm09kdev.superHeroDB.ui.superhero.search
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mlm09kdev.superHeroDB.model.database.entity.SuperHeroEntity
import com.mlm09kdev.superHeroDB.model.repository.SuperHeroRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class SearchViewModel(private val superHeroRepository: SuperHeroRepository) : ViewModel() {
val searchList = MutableLiveData<List<SuperHeroEntity>>()
fun fetchSuperHeroList(queryString: String) {
viewModelScope.launch(Dispatchers.IO) {
searchList.postValue(superHeroRepository.getSuperHero(queryString))
}
}
fun updateFavorites(superHeroEntity: SuperHeroEntity) {
viewModelScope.launch(Dispatchers.IO) {
superHeroRepository.updateFavorite(superHeroEntity)
}
}
}
| 0
|
Kotlin
|
1
| 2
|
2976c527025f045e9e04bad1551e2b3f1497e19a
| 928
|
SuperHero-DB
|
The Unlicense
|
src/main/kotlin/no/nav/helse/journalforing/gateway/JournalforingGateway.kt
|
navikt
| 169,743,207
| false
| null |
package no.nav.helse.journalforing.gateway
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.github.kittinunf.fuel.core.Headers
import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult
import com.github.kittinunf.fuel.httpPost
import io.ktor.http.*
import no.nav.helse.dusseldorf.ktor.client.*
import no.nav.helse.dusseldorf.ktor.health.HealthCheck
import no.nav.helse.dusseldorf.ktor.health.Healthy
import no.nav.helse.dusseldorf.ktor.health.Result
import no.nav.helse.dusseldorf.ktor.health.UnHealthy
import no.nav.helse.dusseldorf.ktor.metrics.Operation
import no.nav.helse.dusseldorf.oauth2.client.AccessTokenClient
import no.nav.helse.dusseldorf.oauth2.client.CachedAccessTokenClient
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.net.URI
import kotlin.IllegalStateException
/*
https://dokmotinngaaende-q1.nais.preprod.local/rest/mottaInngaaendeForsendelse
*/
class JournalforingGateway(
baseUrl: URI,
private val accessTokenClient: AccessTokenClient,
private val oppretteJournalPostScopes : Set<String>
) : HealthCheck {
private companion object {
private val logger: Logger = LoggerFactory.getLogger(JournalforingGateway::class.java)
}
private val mottaInngaaendeForsendelseUrl = Url.buildURL(
baseUrl = baseUrl,
pathParts = listOf("rest", "mottaInngaaendeForsendelse")
).toString()
private val cachedAccessTokenClient = CachedAccessTokenClient(accessTokenClient)
private val objectMapper = configuredObjectMapper()
override suspend fun check(): Result {
return try {
accessTokenClient.getAccessToken(oppretteJournalPostScopes)
Healthy("JournalforingGateway", "Henting av access token for opprettelse av journalpost OK.")
} catch (cause: Throwable) {
logger.error("Feil ved henting av access token for opprettelse av journalpost", cause)
UnHealthy("JournalforingGateway", "Henting av access token for opprettelse av journalpost Feilet.")
}
}
internal suspend fun jorunalfor(journalPostRequest: JournalPostRequest) : JournalPostResponse {
val authorizationHeader = cachedAccessTokenClient.getAccessToken(oppretteJournalPostScopes).asAuthoriationHeader()
logger.trace("Genererer body for request")
val body = objectMapper.writeValueAsBytes(journalPostRequest)
val contentStream = { ByteArrayInputStream(body) }
logger.trace("Generer http request")
val httpRequest = mottaInngaaendeForsendelseUrl
.httpPost()
.body(contentStream)
.header(
Headers.AUTHORIZATION to authorizationHeader,
Headers.CONTENT_TYPE to "application/json",
Headers.ACCEPT to "application/json"
)
logger.trace("Sender request")
val (request, _, result) = Operation.monitored(
app = "pleiepenger-joark",
operation = "opprette-journalpost",
resultResolver = { 200 == it.second.statusCode}
) { httpRequest.awaitStringResponseResult() }
logger.trace("Håndterer response")
val journalPostResponse : JournalPostResponse = result.fold(
{ success -> objectMapper.readValue(success) },
{ error ->
logger.error("Error response = '${error.response.body().asString("text/plain")}' fra '${request.url}'")
logger.error(error.toString())
throw IllegalStateException("Feil ved opperttelse av jorunalpost.")
}
)
if (journalPostRequest.forsokEndeligJF && JournalTilstand.ENDELIG_JOURNALFOERT != journalTilstandFraString(journalPostResponse.journalTilstand)) {
throw IllegalStateException("Journalføring '$journalPostResponse' var forventet å bli endelig journalført, men ble det ikke..")
} else {
return journalPostResponse
}
}
private fun configuredObjectMapper() : ObjectMapper {
val objectMapper = jacksonObjectMapper()
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
return objectMapper
}
}
| 0
|
Kotlin
|
0
| 0
|
7873640bc7ddda828f8931d8a99ab881034235fb
| 4,402
|
pleiepenger-joark
|
MIT License
|
app/src/main/java/com/items/bim/ui/Color.kt
|
losebai
| 800,799,665
| false
|
{"Kotlin": 644896, "Java": 11455}
|
package com.items.bim.ui
import androidx.compose.ui.graphics.Color
// 基础 -对表面高度强调的填充、文本和图标
val primaryLight = Color(0xFF000000)
//+ On primary -文本和图标相对于primary
val onPrimaryLight = Color(0xFF000000)
// 主容器-突出的表面填充颜色,用于关键组件,如FAB
val primaryContainerLight = Color(0xFFFFFFFF)
// 在主容器上-文本和图标对主容器
val onPrimaryContainerLight = Color(0xFF9E4F4F)
// 不太突出的填充、文本和图标对表面
val secondaryLight = Color(0xFFC2C6CC)
// 文本和图标相对次要
val onSecondaryLight = Color(0xFFA528DA)
// 对表面不太突出的填充颜色,用于色调按钮等隐性组件
val secondaryContainerLight = Color(0xFFD8E3F8)
// 文本和图标对辅助容器
val onSecondaryContainerLight = Color(0xFF327391)
// 对表面补充填充、文本和图标
val tertiaryLight = Color(0xFFFFFFFF)
// 文本和图标对第三级
val onTertiaryLight = Color(0xFFA01717)
// 对表面的补充容器颜色,用于组件,如输入字段
val tertiaryContainerLight = Color(0xFFF5D9FF)
// 文本和图标对第三容器
val onTertiaryContainerLight = Color(0xFF000000)
val errorLight = Color(0xFFBA1A1A)
val onErrorLight = Color(0xFFFFFFFF)
val errorContainerLight = Color(0xFFFFDAD6)
val onErrorContainerLight = Color(0xFF410002)
val backgroundLight = Color(0xFFFAFAFA)
val onBackgroundLight = Color(0xFF000000)
// 默认的背景颜色
val surfaceLight = Color(0xFFFFFFFF)
// 文本和图标反对任何表面颜色
val onSurfaceLight = Color(0xFF0862DA)
// 低强调颜色的文本和图标对任何表面颜色
val surfaceVariantLight = Color(0xFFE0DADA)
// 表面变型光
val onSurfaceVariantLight = Color(0xFF000000)
val outlineLight = Color(0xFF73777F)
val outlineVariantLight = Color(0xFF000000)
val scrimLight = Color(0xFF000000)
val inverseSurfaceLight = Color(0xFFFFFFFF)
val inverseOnSurfaceLight = Color(0xFFEFF0F7)
val inversePrimaryLight = Color(0xFFC0C7CF)
val surfaceDimLight = Color(0xFFD8DAE0)
val surfaceBrightLight = Color(0xFFF8F9FF)
val surfaceContainerLowestLight = Color(0xFFFFFFFF)
val surfaceContainerLowLight = Color(0xFFF2F3FA)
val surfaceContainerLight = Color(0xFFECEDF4)
val surfaceContainerHighLight = Color(0xFFE7E8EE)
val surfaceContainerHighestLight = Color(0xFFE1E2E8)
val primaryLightMediumContrast = Color(0xFF194471)
val onPrimaryLightMediumContrast = Color(0xFFFFFFFF)
val primaryContainerLightMediumContrast = Color(0xFF5177A7)
val onPrimaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val secondaryLightMediumContrast = Color(0xFF384454)
val onSecondaryLightMediumContrast = Color(0xFFFFFFFF)
val secondaryContainerLightMediumContrast = Color(0xFF6A7587)
val onSecondaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val tertiaryLightMediumContrast = Color(0xFF503B5A)
val onTertiaryLightMediumContrast = Color(0xFFFFFFFF)
val tertiaryContainerLightMediumContrast = Color(0xFF836C8E)
val onTertiaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val errorLightMediumContrast = Color(0xFF8C0009)
val onErrorLightMediumContrast = Color(0xFFFFFFFF)
val errorContainerLightMediumContrast = Color(0xFFDA342E)
val onErrorContainerLightMediumContrast = Color(0xFFFFFFFF)
val backgroundLightMediumContrast = Color(0xFFF8F9FF)
val onBackgroundLightMediumContrast = Color(0xFF191C20)
val surfaceLightMediumContrast = Color(0xFFF8F9FF)
val onSurfaceLightMediumContrast = Color(0xFF191C20)
val surfaceVariantLightMediumContrast = Color(0xFFDFE2EB)
val onSurfaceVariantLightMediumContrast = Color(0xFF3F434A)
val outlineLightMediumContrast = Color(0xFF5B5F67)
val outlineVariantLightMediumContrast = Color(0xFF777B83)
val scrimLightMediumContrast = Color(0xFF000000)
val inverseSurfaceLightMediumContrast = Color(0xFF2E3035)
val inverseOnSurfaceLightMediumContrast = Color(0xFFEFF0F7)
val inversePrimaryLightMediumContrast = Color(0xFFA3C9FE)
val surfaceDimLightMediumContrast = Color(0xFFD8DAE0)
val surfaceBrightLightMediumContrast = Color(0xFFF8F9FF)
val surfaceContainerLowestLightMediumContrast = Color(0xFFFFFFFF)
val surfaceContainerLowLightMediumContrast = Color(0xFFF2F3FA)
val surfaceContainerLightMediumContrast = Color(0xFFECEDF4)
val surfaceContainerHighLightMediumContrast = Color(0xFFE7E8EE)
val surfaceContainerHighestLightMediumContrast = Color(0xFFE1E2E8)
val primaryLightHighContrast = Color(0xFF002343)
val onPrimaryLightHighContrast = Color(0xFFFFFFFF)
val primaryContainerLightHighContrast = Color(0xFF194471)
val onPrimaryContainerLightHighContrast = Color(0xFFFFFFFF)
val secondaryLightHighContrast = Color(0xFF172332)
val onSecondaryLightHighContrast = Color(0xFFFFFFFF)
val secondaryContainerLightHighContrast = Color(0xFF384454)
val onSecondaryContainerLightHighContrast = Color(0xFFFFFFFF)
val tertiaryLightHighContrast = Color(0xFF2D1B38)
val onTertiaryLightHighContrast = Color(0xFFFFFFFF)
val tertiaryContainerLightHighContrast = Color(0xFF503B5A)
val onTertiaryContainerLightHighContrast = Color(0xFFFFFFFF)
val errorLightHighContrast = Color(0xFF4E0002)
val onErrorLightHighContrast = Color(0xFFFFFFFF)
val errorContainerLightHighContrast = Color(0xFF8C0009)
val onErrorContainerLightHighContrast = Color(0xFFFFFFFF)
val backgroundLightHighContrast = Color(0xFFF8F9FF)
val onBackgroundLightHighContrast = Color(0xFF191C20)
val surfaceLightHighContrast = Color(0xFFF8F9FF)
val onSurfaceLightHighContrast = Color(0xFF000000)
val surfaceVariantLightHighContrast = Color(0xFFDFE2EB)
val onSurfaceVariantLightHighContrast = Color(0xFF20242B)
val outlineLightHighContrast = Color(0xFF3F434A)
val outlineVariantLightHighContrast = Color(0xFF3F434A)
val scrimLightHighContrast = Color(0xFF000000)
val inverseSurfaceLightHighContrast = Color(0xFF2E3035)
val inverseOnSurfaceLightHighContrast = Color(0xFFFFFFFF)
val inversePrimaryLightHighContrast = Color(0xFFE3EDFF)
val primaryDark = Color(0xFFEAECF0)
val onPrimaryDark = Color(0xFFEAECF0)
val primaryContainerDark = Color(0xFFEAECF0)
val onPrimaryContainerDark = Color(0xFFD3E4FF)
val secondaryDark = Color(0xFFBCC7DB)
val onSecondaryDark = Color(0xFF263141)
val secondaryContainerDark = Color(0xFF3C4758)
val onSecondaryContainerDark = Color(0xFFD8E3F8)
val tertiaryDark = Color(0xFFD8BDE3)
val onTertiaryDark = Color(0xFF3C2947)
val tertiaryContainerDark = Color(0xFF543F5E)
val onTertiaryContainerDark = Color(0xFFF5D9FF)
val errorDark = Color(0xFFFFB4AB)
val onErrorDark = Color(0xFF690005)
val errorContainerDark = Color(0xFF93000A)
val onErrorContainerDark = Color(0xFFFFDAD6)
val backgroundDark = Color(0xFF111418)
val onBackgroundDark = Color(0xFFE1E2E8)
val surfaceDark = Color(0xFF111418)
val onSurfaceDark = Color(0xFFE1E2E8)
val surfaceVariantDark = Color(0xFF43474E)
val onSurfaceVariantDark = Color(0xFFC3C6CF)
val outlineDark = Color(0xFF8D9199)
val outlineVariantDark = Color(0xFF43474E)
val scrimDark = Color(0xFF000000)
val inverseSurfaceDark = Color(0xFFE1E2E8)
val inverseOnSurfaceDark = Color(0xFF2E3035)
val inversePrimaryDark = Color(0xFFFFFFFF)
val primaryDarkMediumContrast = Color(0xFFAACDFF)
val onPrimaryDarkMediumContrast = Color(0xFF00172F)
val primaryContainerDarkMediumContrast = Color(0xFF6D93C5)
val onPrimaryContainerDarkMediumContrast = Color(0xFF000000)
val secondaryDarkMediumContrast = Color(0xFFC0CBE0)
val onSecondaryDarkMediumContrast = Color(0xFF0B1725)
val secondaryContainerDarkMediumContrast = Color(0xFF8691A4)
val onSecondaryContainerDarkMediumContrast = Color(0xFF000000)
val tertiaryDarkMediumContrast = Color(0xFFDDC1E8)
val onTertiaryDarkMediumContrast = Color(0xFF200E2B)
val tertiaryContainerDarkMediumContrast = Color(0xFFA188AC)
val onTertiaryContainerDarkMediumContrast = Color(0xFF000000)
val errorDarkMediumContrast = Color(0xFFFFBAB1)
val onErrorDarkMediumContrast = Color(0xFF370001)
val errorContainerDarkMediumContrast = Color(0xFFFF5449)
val onErrorContainerDarkMediumContrast = Color(0xFF000000)
val backgroundDarkMediumContrast = Color(0xFF111418)
val onBackgroundDarkMediumContrast = Color(0xFFE1E2E8)
val surfaceDarkMediumContrast = Color(0xFF111418)
val onSurfaceDarkMediumContrast = Color(0xFFFAFAFF)
val surfaceVariantDarkMediumContrast = Color(0xFF43474E)
val onSurfaceVariantDarkMediumContrast = Color(0xFFC7CBD3)
val outlineDarkMediumContrast = Color(0xFF9FA3AB)
val outlineVariantDarkMediumContrast = Color(0xFF7F838B)
val scrimDarkMediumContrast = Color(0xFF000000)
val inverseSurfaceDarkMediumContrast = Color(0xFFE1E2E8)
val inverseOnSurfaceDarkMediumContrast = Color(0xFF272A2F)
val inversePrimaryDarkMediumContrast = Color(0xFF204977)
val surfaceDimDarkMediumContrast = Color(0xFF111418)
val surfaceBrightDarkMediumContrast = Color(0xFF37393E)
val surfaceContainerLowestDarkMediumContrast = Color(0xFF0C0E13)
val surfaceContainerLowDarkMediumContrast = Color(0xFF191C20)
val surfaceContainerDarkMediumContrast = Color(0xFF1D2024)
val surfaceContainerHighDarkMediumContrast = Color(0xFF272A2F)
val surfaceContainerHighestDarkMediumContrast = Color(0xFF32353A)
val primaryDarkHighContrast = Color(0xFFFAFAFF)
val onPrimaryDarkHighContrast = Color(0xFF000000)
val primaryContainerDarkHighContrast = Color(0xFFAACDFF)
val onPrimaryContainerDarkHighContrast = Color(0xFF000000)
val secondaryDarkHighContrast = Color(0xFFFAFAFF)
val onSecondaryDarkHighContrast = Color(0xFF000000)
val secondaryContainerDarkHighContrast = Color(0xFFC0CBE0)
val onSecondaryContainerDarkHighContrast = Color(0xFF000000)
val tertiaryDarkHighContrast = Color(0xFFFFF9FB)
val onTertiaryDarkHighContrast = Color(0xFF000000)
val tertiaryContainerDarkHighContrast = Color(0xFFDDC1E8)
val onTertiaryContainerDarkHighContrast = Color(0xFF000000)
val errorDarkHighContrast = Color(0xFFFFF9F9)
val onErrorDarkHighContrast = Color(0xFF000000)
val errorContainerDarkHighContrast = Color(0xFFFFBAB1)
val onErrorContainerDarkHighContrast = Color(0xFF000000)
val backgroundDarkHighContrast = Color(0xFF111418)
val onBackgroundDarkHighContrast = Color(0xFFE1E2E8)
val surfaceDarkHighContrast = Color(0xFF111418)
val onSurfaceDarkHighContrast = Color(0xFFFFFFFF)
val surfaceVariantDarkHighContrast = Color(0xFF43474E)
val onSurfaceVariantDarkHighContrast = Color(0xFFFAFAFF)
val outlineDarkHighContrast = Color(0xFFC7CBD3)
val outlineVariantDarkHighContrast = Color(0xFFC7CBD3)
val scrimDarkHighContrast = Color(0xFF000000)
val inverseSurfaceDarkHighContrast = Color(0xFFE1E2E8)
val inverseOnSurfaceDarkHighContrast = Color(0xFF000000)
val inversePrimaryDarkHighContrast = Color(0xFF002B51)
val surfaceDimDarkHighContrast = Color(0xFF111418)
val surfaceBrightDarkHighContrast = Color(0xFF37393E)
val surfaceContainerLowestDarkHighContrast = Color(0xFF0C0E13)
val surfaceContainerLowDarkHighContrast = Color(0xFF191C20)
val surfaceContainerDarkHighContrast = Color(0xFF1D2024)
val surfaceContainerHighDarkHighContrast = Color(0xFF272A2F)
val surfaceContainerHighestDarkHighContrast = Color(0xFF32353A)
| 0
|
Kotlin
|
0
| 0
|
86f8cb939b3671158e568638b0c8e3b82df87fa1
| 10,451
|
B-Im
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/quicksight/SheetDefinitionPropertyDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.quicksight
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.quicksight.CfnTemplate
@Generated
public fun buildSheetDefinitionProperty(initializer: @AwsCdkDsl
CfnTemplate.SheetDefinitionProperty.Builder.() -> Unit): CfnTemplate.SheetDefinitionProperty =
CfnTemplate.SheetDefinitionProperty.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
b22e397ff37c5fce365a5430790e5d83f0dd5a64
| 467
|
aws-cdk-kt
|
Apache License 2.0
|
publish-to-maven-central/src/nativeMain/kotlin/X.kt
|
h0tk3y
| 139,852,818
| false
| null |
package com.github.h0tk3y.kotlinMppDemo.lib
actual val platformName: String = "Kotlin/Native"
| 3
|
Kotlin
|
11
| 68
|
71ae083c84de8f484ad6ed1d7317c2524a2229f4
| 94
|
k-new-mpp-samples
|
Apache License 2.0
|
shared_resources/src/main/java/com/thewizrd/shared_resources/icons/WeatherIconsEFProvider.kt
|
SimpleAppProjects
| 82,603,731
| false
| null |
package com.thewizrd.shared_resources.icons
import androidx.annotation.DrawableRes
import com.thewizrd.shared_resources.R
class WeatherIconsEFProvider : WeatherIconProvider() {
companion object {
const val KEY = "wi-erik-flowers"
}
override fun getKey(): String {
return KEY
}
override fun getDisplayName(): String {
return "Weather Icons"
}
override fun getAuthorName(): String {
return "Erik Flowers"
}
override fun getAttributionLink(): String {
return "https://erikflowers.github.io/weather-icons/"
}
override fun isFontIcon(): Boolean {
return true
}
@DrawableRes
override fun getWeatherIconResource(icon: String): Int {
var weatherIcon = when (icon) {
WeatherIcons.DAY_SUNNY -> R.drawable.wi_day_sunny
WeatherIcons.DAY_CLOUDY -> R.drawable.wi_day_cloudy
WeatherIcons.DAY_CLOUDY_GUSTS -> R.drawable.wi_day_cloudy_gusts
WeatherIcons.DAY_CLOUDY_WINDY -> R.drawable.wi_day_cloudy_windy
WeatherIcons.DAY_FOG -> R.drawable.wi_day_fog
WeatherIcons.DAY_HAIL -> R.drawable.wi_day_hail
WeatherIcons.DAY_HAZE -> R.drawable.wi_day_haze
WeatherIcons.DAY_LIGHTNING -> R.drawable.wi_day_lightning
WeatherIcons.DAY_RAIN -> R.drawable.wi_day_rain
WeatherIcons.DAY_RAIN_MIX -> R.drawable.wi_day_rain_mix
WeatherIcons.DAY_RAIN_WIND -> R.drawable.wi_day_rain_wind
WeatherIcons.DAY_SHOWERS -> R.drawable.wi_day_showers
WeatherIcons.DAY_SLEET -> R.drawable.wi_day_sleet
WeatherIcons.DAY_SLEET_STORM -> R.drawable.wi_day_sleet_storm
WeatherIcons.DAY_SNOW -> R.drawable.wi_day_snow
WeatherIcons.DAY_SNOW_THUNDERSTORM -> R.drawable.wi_day_snow_thunderstorm
WeatherIcons.DAY_SNOW_WIND -> R.drawable.wi_day_snow_wind
WeatherIcons.DAY_SPRINKLE -> R.drawable.wi_day_sprinkle
WeatherIcons.DAY_STORM_SHOWERS -> R.drawable.wi_day_storm_showers
WeatherIcons.DAY_PARTLY_CLOUDY,
WeatherIcons.DAY_SUNNY_OVERCAST -> R.drawable.wi_day_sunny_overcast
WeatherIcons.DAY_THUNDERSTORM -> R.drawable.wi_day_thunderstorm
WeatherIcons.DAY_WINDY -> R.drawable.wi_day_windy
WeatherIcons.DAY_HOT -> R.drawable.wi_hot
WeatherIcons.DAY_CLOUDY_HIGH -> R.drawable.wi_day_cloudy_high
WeatherIcons.DAY_LIGHT_WIND -> R.drawable.wi_day_light_wind
WeatherIcons.NIGHT_CLEAR -> R.drawable.wi_night_clear
WeatherIcons.NIGHT_ALT_CLOUDY -> R.drawable.wi_night_alt_cloudy
WeatherIcons.NIGHT_ALT_CLOUDY_GUSTS -> R.drawable.wi_night_alt_cloudy_gusts
WeatherIcons.NIGHT_ALT_CLOUDY_WINDY -> R.drawable.wi_night_alt_cloudy_windy
WeatherIcons.NIGHT_ALT_HAIL -> R.drawable.wi_night_alt_hail
WeatherIcons.NIGHT_ALT_LIGHTNING -> R.drawable.wi_night_alt_lightning
WeatherIcons.NIGHT_ALT_RAIN -> R.drawable.wi_night_alt_rain
WeatherIcons.NIGHT_ALT_RAIN_MIX -> R.drawable.wi_night_alt_rain_mix
WeatherIcons.NIGHT_ALT_RAIN_WIND -> R.drawable.wi_night_alt_rain_wind
WeatherIcons.NIGHT_ALT_SHOWERS -> R.drawable.wi_night_alt_showers
WeatherIcons.NIGHT_ALT_SLEET -> R.drawable.wi_night_alt_sleet
WeatherIcons.NIGHT_ALT_SLEET_STORM -> R.drawable.wi_night_alt_sleet_storm
WeatherIcons.NIGHT_ALT_SNOW -> R.drawable.wi_night_alt_snow
WeatherIcons.NIGHT_ALT_SNOW_THUNDERSTORM -> R.drawable.wi_night_alt_snow_thunderstorm
WeatherIcons.NIGHT_ALT_SNOW_WIND -> R.drawable.wi_night_alt_snow_wind
WeatherIcons.NIGHT_ALT_SPRINKLE -> R.drawable.wi_night_alt_sprinkle
WeatherIcons.NIGHT_ALT_STORM_SHOWERS -> R.drawable.wi_night_alt_storm_showers
WeatherIcons.NIGHT_ALT_THUNDERSTORM -> R.drawable.wi_night_alt_thunderstorm
WeatherIcons.NIGHT_ALT_PARTLY_CLOUDY,
WeatherIcons.NIGHT_OVERCAST -> R.drawable.wi_night_alt_partly_cloudy
WeatherIcons.NIGHT_ALT_CLOUDY_HIGH -> R.drawable.wi_night_alt_cloudy_high
WeatherIcons.NIGHT_FOG,
WeatherIcons.NIGHT_HAZE -> R.drawable.wi_night_fog
WeatherIcons.NIGHT_WINDY -> R.drawable.wi_windy
WeatherIcons.NIGHT_HOT -> R.drawable.wi_thermometer_up
WeatherIcons.NIGHT_LIGHT_WIND -> R.drawable.wi_windy
WeatherIcons.CLOUD -> R.drawable.wi_cloud
WeatherIcons.CLOUDY -> R.drawable.wi_cloudy
WeatherIcons.CLOUDY_GUSTS -> R.drawable.wi_cloudy_gusts
WeatherIcons.CLOUDY_WINDY -> R.drawable.wi_cloudy_windy
WeatherIcons.FOG -> R.drawable.wi_fog
WeatherIcons.HAIL -> R.drawable.wi_hail
WeatherIcons.HAZE -> R.drawable.wi_windy
WeatherIcons.HOT -> R.drawable.wi_thermometer_up
WeatherIcons.LIGHT_WIND -> R.drawable.wi_windy
WeatherIcons.OVERCAST -> R.drawable.wi_cloudy
WeatherIcons.RAIN -> R.drawable.wi_rain
WeatherIcons.RAIN_MIX -> R.drawable.wi_rain_mix
WeatherIcons.RAIN_WIND -> R.drawable.wi_rain_wind
WeatherIcons.SHOWERS -> R.drawable.wi_showers
WeatherIcons.SLEET -> R.drawable.wi_sleet
WeatherIcons.SLEET_STORM -> R.drawable.wi_sleet_storm
WeatherIcons.SNOW -> R.drawable.wi_snow
WeatherIcons.SNOW_THUNDERSTORM -> R.drawable.wi_snow_thunderstorm
WeatherIcons.SPRINKLE -> R.drawable.wi_sprinkle
WeatherIcons.STORM_SHOWERS -> R.drawable.wi_storm_showers
WeatherIcons.THUNDERSTORM -> R.drawable.wi_thunderstorm
WeatherIcons.SNOW_WIND -> R.drawable.wi_snow_wind
WeatherIcons.SMOG -> R.drawable.wi_smog
WeatherIcons.SMOKE -> R.drawable.wi_smoke
WeatherIcons.LIGHTNING -> R.drawable.wi_lightning
WeatherIcons.DUST -> R.drawable.wi_dust
WeatherIcons.SNOWFLAKE_COLD -> R.drawable.wi_snowflake_cold
WeatherIcons.WINDY -> R.drawable.wi_windy
WeatherIcons.STRONG_WIND -> R.drawable.wi_strong_wind
WeatherIcons.SANDSTORM -> R.drawable.wi_sandstorm
WeatherIcons.HURRICANE -> R.drawable.wi_hurricane
WeatherIcons.TORNADO -> R.drawable.wi_tornado
WeatherIcons.FIRE -> R.drawable.wi_fire
WeatherIcons.FLOOD -> R.drawable.wi_flood
WeatherIcons.VOLCANO -> R.drawable.wi_volcano
WeatherIcons.BAROMETER -> R.drawable.wi_barometer
WeatherIcons.HUMIDITY -> R.drawable.wi_humidity
WeatherIcons.MOONRISE -> R.drawable.wi_moonrise
WeatherIcons.MOONSET -> R.drawable.wi_moonset
WeatherIcons.RAINDROP -> R.drawable.wi_raindrop
WeatherIcons.RAINDROPS -> R.drawable.wi_raindrops
WeatherIcons.SUNRISE -> R.drawable.wi_sunrise
WeatherIcons.SUNSET -> R.drawable.wi_sunset
WeatherIcons.THERMOMETER -> R.drawable.wi_thermometer
WeatherIcons.UMBRELLA -> R.drawable.wi_umbrella
WeatherIcons.WIND_DIRECTION -> R.drawable.wi_wind_direction
WeatherIcons.DIRECTION_UP -> R.drawable.wi_direction_up
WeatherIcons.DIRECTION_DOWN -> R.drawable.wi_direction_down
WeatherIcons.WIND_BEAUFORT_0 -> R.drawable.wi_wind_beaufort_0
WeatherIcons.WIND_BEAUFORT_1 -> R.drawable.wi_wind_beaufort_1
WeatherIcons.WIND_BEAUFORT_2 -> R.drawable.wi_wind_beaufort_2
WeatherIcons.WIND_BEAUFORT_3 -> R.drawable.wi_wind_beaufort_3
WeatherIcons.WIND_BEAUFORT_4 -> R.drawable.wi_wind_beaufort_4
WeatherIcons.WIND_BEAUFORT_5 -> R.drawable.wi_wind_beaufort_5
WeatherIcons.WIND_BEAUFORT_6 -> R.drawable.wi_wind_beaufort_6
WeatherIcons.WIND_BEAUFORT_7 -> R.drawable.wi_wind_beaufort_7
WeatherIcons.WIND_BEAUFORT_8 -> R.drawable.wi_wind_beaufort_8
WeatherIcons.WIND_BEAUFORT_9 -> R.drawable.wi_wind_beaufort_9
WeatherIcons.WIND_BEAUFORT_10 -> R.drawable.wi_wind_beaufort_10
WeatherIcons.WIND_BEAUFORT_11 -> R.drawable.wi_wind_beaufort_11
WeatherIcons.WIND_BEAUFORT_12 -> R.drawable.wi_wind_beaufort_12
WeatherIcons.MOON_NEW -> R.drawable.wi_moon_new
WeatherIcons.MOON_WAXING_CRESCENT_3 -> R.drawable.wi_moon_waxing_crescent_3
WeatherIcons.MOON_FIRST_QUARTER -> R.drawable.wi_moon_first_quarter
WeatherIcons.MOON_WAXING_GIBBOUS_3 -> R.drawable.wi_moon_waxing_gibbous_3
WeatherIcons.MOON_FULL -> R.drawable.wi_moon_full
WeatherIcons.MOON_WANING_GIBBOUS_3 -> R.drawable.wi_moon_waning_gibbous_3
WeatherIcons.MOON_THIRD_QUARTER -> R.drawable.wi_moon_third_quarter
WeatherIcons.MOON_WANING_CRESCENT_3 -> R.drawable.wi_moon_waning_crescent_3
WeatherIcons.MOON_ALT_NEW -> R.drawable.wi_moon_alt_new
WeatherIcons.MOON_ALT_WAXING_CRESCENT_3 -> R.drawable.wi_moon_alt_waxing_crescent_3
WeatherIcons.MOON_ALT_FIRST_QUARTER -> R.drawable.wi_moon_alt_first_quarter
WeatherIcons.MOON_ALT_WAXING_GIBBOUS_3 -> R.drawable.wi_moon_alt_waxing_gibbous_3
WeatherIcons.MOON_ALT_FULL -> R.drawable.wi_moon_alt_full
WeatherIcons.MOON_ALT_WANING_GIBBOUS_3 -> R.drawable.wi_moon_alt_waning_gibbous_3
WeatherIcons.MOON_ALT_THIRD_QUARTER -> R.drawable.wi_moon_alt_third_quarter
WeatherIcons.MOON_ALT_WANING_CRESCENT_3 -> R.drawable.wi_moon_alt_waning_crescent_3
WeatherIcons.FAHRENHEIT -> R.drawable.wi_fahrenheit
WeatherIcons.CELSIUS -> R.drawable.wi_celsius
WeatherIcons.UV_INDEX,
WeatherIcons.UV_INDEX_1,
WeatherIcons.UV_INDEX_2,
WeatherIcons.UV_INDEX_3,
WeatherIcons.UV_INDEX_4,
WeatherIcons.UV_INDEX_5,
WeatherIcons.UV_INDEX_6,
WeatherIcons.UV_INDEX_7,
WeatherIcons.UV_INDEX_8,
WeatherIcons.UV_INDEX_9,
WeatherIcons.UV_INDEX_10,
WeatherIcons.UV_INDEX_11 -> R.drawable.wi_day_sunny
WeatherIcons.TREE_POLLEN -> R.drawable.ic_outline_tree
WeatherIcons.GRASS_POLLEN -> R.drawable.ic_baseline_grass
WeatherIcons.RAGWEED_POLLEN -> R.drawable.ic_ragweed_pollen
WeatherIcons.NA -> R.drawable.wi_na
else -> -1
}
if (weatherIcon == -1) {
// Not Available
weatherIcon = R.drawable.wi_na
}
return weatherIcon
}
}
| 0
| null |
8
| 37
|
56ddf09611d786e3bb2b802bdbcbbec648f0df9a
| 10,718
|
SimpleWeather-Android
|
Apache License 2.0
|
src/api/kotlin/tools/ModContext.kt
|
2xsaiko
| 123,460,493
| false
| null |
package therealfarfetchd.quacklib.api.tools
import net.minecraftforge.fml.common.ModContainer
interface ModContext {
fun <R> lockMod(op: () -> R): R
fun currentMod(): ModContainer?
}
| 6
|
Kotlin
|
2
| 4
|
76c9a55f186c699fb4458f2a4a40a483ab3e3ef2
| 191
|
QuackLib
|
MIT License
|
src/main/kotlin/org/mailcall/yaml/YamlHelper.kt
|
OdysseusLevy
| 58,777,555
| false
| null |
package org.mailcall.yaml
import org.kale.api.EmailAccount
import org.kale.mail.EmailAccountConfig
import org.mailcall.script.SimpleConfiguration
import org.yaml.snakeyaml.Yaml
import java.io.File
import java.io.FileInputStream
/**
* @author <NAME> (<EMAIL>)
*/
class YamlHelper {
fun loadAccounts(): List<EmailAccountConfig> {
val yaml = Yaml()
val folder = File("config")
val listOfFiles = folder.listFiles{file -> file.extension.equals("imap")}
return listOfFiles.map { file ->
yaml.loadAs(FileInputStream(file), EmailAccountConfig::class.java)
}
}
}
fun main(args: Array<String>) {
val helper = YamlHelper()
// Need placeholder for Tags.
// Utility for creating an EmailAccount would be good
// Need notion of "named" objects (using duck typing?
val accounts = helper.loadAccounts().map {config -> EmailAccount.create(config, YamlTags()) }
val config = SimpleConfiguration()
//config.putAll(accounts)
}
| 0
|
Kotlin
|
0
| 0
|
15cd8558c704cd770b4f54ad3597a09c04dcd3f6
| 1,010
|
kale
|
Apache License 2.0
|
idea/tests/testData/inspectionsLocal/replaceWithOperatorAssignment/list.kt
|
JetBrains
| 278,369,660
| false
| null |
// WITH_RUNTIME
// HIGHLIGHT: INFORMATION
fun foo() {
var list = listOf(1, 2, 3)
// Should not be highlighted because it's the way we use to say explicitly
// "yes, we want to re-assign this immutable list"
list <caret>= list + 4
}
| 1
| null |
30
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 248
|
intellij-kotlin
|
Apache License 2.0
|
src/main/kotlin/io/github/tsb99x/trakt/core/Utils.kt
|
tsb99x
| 203,202,702
| false
| null |
package io.github.tsb99x.trakt.core
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.time.temporal.ChronoUnit
import java.util.*
const val API_TOKEN_ID_ATTRIBUTE = "api-token-id"
const val API_TOKEN_MUST_BE_UUID = "API token must be UUID"
const val API_V1_PATH = "/api/v1"
const val AUTHORIZATION_HEADER_MUST_BE_PRESENT = "Authorization header must be present"
const val BEARER = "Bearer"
const val INCORRECT_API_TOKEN = "Incorrect API token"
const val ONLY_AUTHORIZATION_BEARER_IS_SUPPORTED = "Only Authorization: Bearer is supported"
const val REQUEST_ID = "requestId"
const val USER_ATTRIBUTE = "user"
const val USER_IS_NOT_ENABLED = "User is not enabled"
const val USER_NOT_FOUND = "User not found"
const val USERNAME_AND_PASSWORD_COMBO_NOT_FOUND = "Such combination of username and password was not found"
fun getConfigVariable(name: String, default: String? = null): String =
System.getProperty(name)
?: System.getenv(name.replace(".", "_").toUpperCase())
?: default
?: throw IllegalStateException("Could not acquire configuration variable with name of '${name}'")
fun String.toUUID(): UUID =
UUID.fromString(this)
fun Instant.toUTC(): OffsetDateTime =
this.atOffset(ZoneOffset.UTC)
fun Instant.minusMinutes(minutes: Long): Instant =
this.minus(minutes, ChronoUnit.MINUTES)
fun Any.classLogger(): Logger =
LoggerFactory.getLogger(this::class.java)
fun <T> tryOrNull(f: () -> T): T? =
try { f() } catch (_: Exception) { null }
| 12
|
Kotlin
|
0
| 0
|
8c664fb60d185c4fc466d8026a76eb3ccd4ccae8
| 1,591
|
trakt
|
MIT License
|
src/main/kotlin/com/github/hirokazumiyaji/http/Client.kt
|
hirokazumiyaji
| 118,339,761
| false
| null |
package com.github.hirokazumiyaji.http
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import reactor.core.publisher.Mono
open class Client(private val http: OkHttpClient) {
fun request(request: Request): Mono<Response> {
return Mono.just(http.newCall(request).execute())
.doOnError {
throw HttpException(it)
}.doOnSuccess {
if (!it.isSuccessful) {
throw HttpException(it)
}
}
}
fun get(url: String, headers: Headers? = null): Mono<Response> {
var req = Request.Builder()
.url(url)
.get()
headers?.let {
req = req.headers(it)
}
return request(req.build())
}
fun post(url: String, body: RequestBody, headers: Headers? = null): Mono<Response> {
var req = Request.Builder()
.url(url)
.post(body)
headers?.let {
req = req.headers(it)
}
return request(req.build())
}
fun put(url: String, body: RequestBody, headers: Headers? = null): Mono<Response> {
var req = Request.Builder()
.url(url)
.put(body)
headers?.let {
req = req.headers(it)
}
return request(req.build())
}
fun patch(url: String, body: RequestBody, headers: Headers? = null): Mono<Response> {
var req = Request.Builder()
.url(url)
.patch(body)
headers?.let {
req = req.headers(it)
}
return request(req.build())
}
fun delete(url: String, body: RequestBody? = null, headers: Headers? = null): Mono<Response> {
var req = Request.Builder()
.url(url)
.delete(body)
headers?.let {
req = req.headers(it)
}
return request(req.build())
}
}
| 0
|
Kotlin
|
0
| 0
|
bf4b5e3ed8a170b35fafb3542d793841cee4960d
| 1,972
|
httpclient
|
MIT License
|
app/src/main/java/com/thedearbear/nnov/home/Announcement.kt
|
TheDearbear
| 828,962,865
| false
|
{"Kotlin": 194806}
|
package com.thedearbear.nnov.home
import java.time.LocalDate
data class Announcement(
val id: Int,
val title: String,
val body: String,
val author: String,
val date: LocalDate
)
| 0
|
Kotlin
|
0
| 0
|
5a53ab4e8d8784178f72bfd4ddc8479f5866f5fd
| 200
|
DigitalJournal
|
MIT License
|
shared/src/commonMain/kotlin/me/gulya/bitwarden/server/request/EventRequest.kt
|
IlyaGulya
| 306,867,791
| false
| null |
package me.gulya.bitwarden.server.request
import com.soywiz.klock.DateTime
import me.gulya.bitwarden.enums.EventType
data class EventRequest(
val type: EventType,
val cipherId: String,
val date: DateTime,
)
| 0
|
Kotlin
|
1
| 3
|
9177134c7940d143f1f3da14e6dd56f3102c367d
| 220
|
bitwarden-client-mpp
|
MIT License
|
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/javaLibraryProject/app/src/main/kotlin/App.kt
|
JakeWharton
| 99,388,807
| false
| null |
import com.example.*
fun main(args: Array<String>) {
println(helloA())
println(helloB())
}
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 99
|
kotlin
|
Apache License 2.0
|
src/backend/ci/ext/tencent/remotedev/biz-remotedev-tencent/src/main/kotlin/com/tencent/devops/remotedev/common/exception/ErrorCodeEnum.kt
|
terlinhe
| 281,661,499
| true
|
{"Kotlin": 45598476, "Vue": 6397657, "Java": 5707849, "Go": 3274290, "JavaScript": 1968867, "Lua": 856156, "HTML": 649832, "Dart": 551043, "TypeScript": 411134, "SCSS": 405673, "Shell": 403216, "C++": 149772, "CSS": 95042, "Python": 79300, "Mustache": 65146, "Smarty": 46819, "C": 33502, "Less": 24714, "Dockerfile": 22944, "Makefile": 19753, "Objective-C": 18613, "C#": 9787, "Swift": 8479, "Batchfile": 8243, "Ruby": 6807, "Starlark": 3608, "PowerShell": 840, "VBScript": 189}
|
package com.tencent.devops.remotedev.common.exception
import com.tencent.devops.common.api.annotation.BkFieldI18n
import com.tencent.devops.common.api.pojo.ErrorType
import com.tencent.devops.common.web.utils.I18nUtil
enum class ErrorCodeEnum(
@BkFieldI18n
val errorType: ErrorType,
val errorCode: String,
val formatErrorMessage: String
) {
USER_NOT_EXISTS(
errorType = ErrorType.USER,
errorCode = "2132001",
formatErrorMessage = "Account [%s] does not exist, please contact DevOps-helper to register"
),
OAUTH_ILLEGAL(
errorType = ErrorType.USER,
errorCode = "2132002",
formatErrorMessage = "%s oauth invalid, need to re-authorize"
),
WORKSPACE_NOT_FIND(
errorType = ErrorType.USER,
errorCode = "2132003",
formatErrorMessage = "workspace %s not find"
),
DEVFILE_ERROR(
errorType = ErrorType.USER,
errorCode = "2132004",
formatErrorMessage = "load devfile error: %s"
),
USERINFO_ERROR(
errorType = ErrorType.USER,
errorCode = "2132005",
formatErrorMessage = "load user info error: %s"
),
WORKSPACE_STATUS_CHANGE_FAIL(
errorType = ErrorType.USER,
errorCode = "2132006",
formatErrorMessage = "workspace(%s) change failed: %s"
),
WORKSPACE_SHARE_FAIL(
errorType = ErrorType.USER,
errorCode = "2132007",
formatErrorMessage = "workspace share failed: %s"
),
FORBIDDEN(
errorType = ErrorType.USER,
errorCode = "2132008",
formatErrorMessage = "You do not have permission: %s"
),
WORKSPACE_MAX_RUNNING(
errorType = ErrorType.USER,
errorCode = "2132009",
formatErrorMessage = "The current workspace running count(%s) has reached the user limit(%s)"
),
WORKSPACE_MAX_HAVING(
errorType = ErrorType.USER,
errorCode = "2132010",
formatErrorMessage = "The number of created workspaces(%s) has reached the user limit(%s)"
),
UPDATE_BK_TICKET_FAIL(
errorType = ErrorType.USER,
errorCode = "2132011",
formatErrorMessage = "update BkTicket fail,please check hostName exists."
),
DENIAL_OF_SERVICE(
errorType = ErrorType.USER,
errorCode = "2132012",
formatErrorMessage = "Sorry, you are not authorized to access this resource."
),
REPEAT_REQUEST(
errorType = ErrorType.USER,
errorCode = "2132013",
formatErrorMessage = "Repeat request! Please try again later."
),
WORKSPACE_ERROR(
errorType = ErrorType.USER,
errorCode = "2132014",
formatErrorMessage = "The workspace has error and cannot be repaired, please choose to destroy."
),
WORKSPACE_ERROR_FIX(
errorType = ErrorType.USER,
errorCode = "2132015",
formatErrorMessage = "The errored workspace has been restored to [%s], please try again."
),
WORKSPACE_NOT_RUNNING(
errorType = ErrorType.USER,
errorCode = "2132016",
formatErrorMessage = "Workspace is not currently running."
),
CHECK_USER_TICKET_FAIL(
errorType = ErrorType.USER,
errorCode = "2132017",
formatErrorMessage = "check user login ticket fail."
);
fun getErrorMessage(): String {
return I18nUtil.getCodeLanMessage(this.errorCode)
}
}
| 0
|
Kotlin
|
0
| 0
|
dccbcb9f44260f80ebfa1c2dad0c401222f7f93c
| 3,411
|
bk-ci
|
MIT License
|
src/test/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls/SolutionTest.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
|
package g1601_1700.s1648_sell_diminishing_valued_colored_balls
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun maxProfit() {
assertThat(Solution().maxProfit(intArrayOf(2, 5), 4), equalTo(14))
}
@Test
fun maxProfit2() {
assertThat(Solution().maxProfit(intArrayOf(3, 5), 6), equalTo(19))
}
}
| 0
|
Kotlin
|
20
| 43
|
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
| 445
|
LeetCode-in-Kotlin
|
MIT License
|
src/Main.kt
|
CreeperSan
| 98,320,470
| false
| null |
fun main(args: Array<String>) {
val window = MainWindow()
window.title = "杉果爬虫"
window.setSize(1280,720)
window.isResizable = false
window.isVisible = true
}
| 0
|
Kotlin
|
0
| 0
|
095910dc81e418ca1f6130ec40ad4c66696d459f
| 178
|
Sonkwo_Spider
|
Apache License 2.0
|
core/src/test/kotlin/me/lusory/kitsune/core/test/ImageRegistryTest.kt
|
lusory
| 501,750,007
| false
| null |
/*
* This file is part of kitsune, licensed under the Apache License, Version 2.0 (the "License").
*
* Copyright (c) 2022-present lusory contributors
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.lusory.kitsune.core.test
import me.lusory.kitsune.api.image.Image
import me.lusory.kitsune.api.image.ImageRegistry
import me.lusory.kitsune.core.image.ImageRegistryImpl
import me.lusory.kitsune.core.test.util.EXAMPLE_METADATA
import org.junit.jupiter.api.assertDoesNotThrow
import kotlin.test.*
class ImageRegistryTest {
private val reg: ImageRegistry = ImageRegistryImpl().apply { loadImages() }
@Test
fun `create, query and delete image`() {
val image: Image = assertDoesNotThrow(message = "Image creation failed") {
reg.create(Image.Format.VMDK, 20_000_000, EXAMPLE_METADATA)
}
val foundImage: Image? = reg.find(image.id)
assertNotNull(foundImage, message = "Image was not added to the registry")
assertSame(image, foundImage, message = "A different instance was returned upon query")
assertEquals(Image.Format.VMDK, image.format, message = "Image had a different format")
assertEquals(20_000_000, image.size, message = "Image had a different size")
assertEquals(false, image.isReadonly, message = "Image was not readable")
assertEquals(Image.Media.DISK, image.mediaType, message = "Image was not a DISK media type")
assertEquals(
EXAMPLE_METADATA.entries,
reg.getMetadata(image).entries,
message = "Image metadata was not saved correctly"
)
assertTrue(image.file.isFile, message = "Image file was not created on the filesystem")
assertTrue(
image.file.resolveSibling("${image.id}.properties").isFile,
message = "Image metadata file was not created on the filesystem"
)
assertDoesNotThrow(message = "Image deletion failed") {
reg.delete(image)
}
assertFalse(image.file.parentFile.isFile, message = "Image directory was not removed from the filesystem")
assertNull(reg.find(image.id), message = "Image was not removed from registry")
}
}
| 1
|
Kotlin
|
0
| 4
|
c65e0686a08df5c4144d6203556d1f69dfe6f82e
| 2,652
|
kitsune
|
Apache License 2.0
|
data/src/main/java/com/team_ia/data/repository/MemberRepositoryImpl.kt
|
Idea-Archive
| 613,424,839
| false
| null |
package com.team_ia.data.repository
import com.team_ia.data.remote.datasource.member.MemberDataSource
import com.team_ia.data.remote.request.member.toRequest
import com.team_ia.data.remote.response.member.toEntity
import com.team_ia.domain.entity.MemberEntity
import com.team_ia.domain.param.ChangeNickNameParam
import com.team_ia.domain.param.FindPasswordParam
import com.team_ia.domain.param.PasswordParam
import com.team_ia.domain.repository.MemberRepository
import javax.inject.Inject
class MemberRepositoryImpl @Inject constructor(
private val memberDataSource: MemberDataSource
) : MemberRepository {
override suspend fun profileInfo(): MemberEntity =
memberDataSource.profileInfo().toEntity()
override suspend fun changePassword(param: PasswordParam) =
memberDataSource.changePassword(param.toRequest())
override suspend fun withdrawalMember(email: String, password: String) {
memberDataSource.withdrawalMember(email = email, password = password)
}
override suspend fun findPassword(param: FindPasswordParam) {
memberDataSource.findPassword(param.toRequest())
}
override suspend fun changeNickName(param: ChangeNickNameParam) {
memberDataSource.changeNickName(param.toRequest())
}
}
| 8
|
Kotlin
|
0
| 9
|
1023841971d28065c875427d323475701a845fdc
| 1,272
|
Idea-Archive-Android
|
MIT License
|
cosky-rest-api/src/main/kotlin/me/ahoo/cosky/rest/security/authorization/InitialPolicyLoader.kt
|
Ahoo-Wang
| 360,576,464
| false
| null |
package me.ahoo.cosky.rest.security.authorization
import me.ahoo.cosec.api.policy.Policy
import me.ahoo.cosec.policy.DefaultPolicyEvaluator
import me.ahoo.cosec.serialization.CoSecJsonSerializer
object InitialPolicyLoader {
const val policyResourceName = "cosky-policy.json"
val policy: Policy by lazy(this) {
requireNotNull(javaClass.classLoader.getResource(policyResourceName)).let { resource ->
resource.openStream().use {
val policy = CoSecJsonSerializer.readValue(it, Policy::class.java)
DefaultPolicyEvaluator.evaluate(policy)
policy
}
}
}
}
| 8
| null |
21
| 80
|
3361bbf31ed8422e216fd2e2b363e41423d8afbe
| 650
|
CoSky
|
Apache License 2.0
|
src/test/kotlin/no/roedt/ringesentralen/samtale/RingServiceBeanTest.kt
|
Roedt
| 300,015,002
| false
| null |
package no.roedt.ringesentralen.samtale
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.whenever
import io.quarkus.hibernate.orm.panache.PanacheQuery
import no.roedt.DatabaseUpdater
import no.roedt.Kilde
import no.roedt.Kommune
import no.roedt.lokallag.LokallagService
import no.roedt.person.Person
import no.roedt.person.PersonRepository
import no.roedt.person.Postnummer
import no.roedt.person.UserId
import no.roedt.ringesentralen.Modus
import no.roedt.ringesentralen.ringer.RingerRepository
import no.roedt.ringesentralen.samtale.resultat.AutentisertResultatFraSamtaleRequest
import no.roedt.ringesentralen.samtale.resultat.Resultat
import no.roedt.ringesentralen.samtale.resultat.ResultatFraSamtaleRequest
import no.roedt.ringesentralen.samtale.resultat.Valg21SpesifikkeResultat
import no.roedt.ringesentralen.samtale.start.NestePersonAaRingeFinder
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class RingServiceBeanTest {
private val personRepository: PersonRepository = mock()
private val databaseUpdater: DatabaseUpdater = mock()
private val persistentSamtaleRepository: PersistentSamtaleRepository = mock()
private val oppfoelgingValg21Repository: OppfoelgingValg21Repository = mock()
private val lokallagService: LokallagService = mock()
private val ringerRepository: RingerRepository = mock()
private val nestePersonAaRingeFinder: NestePersonAaRingeFinder = mock()
private var ringService = RingServiceBean(
personRepository = personRepository,
databaseUpdater = databaseUpdater,
samtaleRepository = persistentSamtaleRepository,
oppfoelgingValg21Repository = oppfoelgingValg21Repository,
lokallagService = lokallagService,
ringerRepository = ringerRepository,
nestePersonAaRingeFinder = nestePersonAaRingeFinder
)
@BeforeEach
fun setup() {
createRingbarPerson("Anders", "And", "12345678", 1, 1)
createRingbarPerson("Andre", "Kvakk", "12345679", 2, 2)
}
// TODO Mads: følg opp denne
fun `samtale blir registrert`() {
ringService = spy(ringService)
doReturn(1).whenever(ringService).hypersysIDTilRingerId(any())
doReturn(false).whenever(ringService).isBrukerEllerVenterPaaGodkjenning(any())
val request = AutentisertResultatFraSamtaleRequest(
UserId(1),
ResultatFraSamtaleRequest(
modus = Modus.medlemmer,
ringtID = 2,
resultat = Resultat.Svarte,
kommentar = "Hei",
modusspesifikkeResultat = Valg21SpesifikkeResultat(
vilPolitikkLink = false,
vilBliMerAktiv = false,
vilBliRingtAugust = false,
vilHaMedlemsLink = false,
vilHaFellesskapLink = true
),
vilIkkeBliRingt = false
),
modus = Modus.velgere
)
val response = ringService.registrerResultatFraSamtale(request)
assertNotNull(response)
}
@Test
fun `resultattype som ikkje passar med modusen kastar feilmelding`() {
val request = AutentisertResultatFraSamtaleRequest(
userId = UserId(1),
request = ResultatFraSamtaleRequest(
modus = Modus.medlemmer,
ringtID = 2,
resultat = Resultat.Ringes_etter_valget,
kommentar = "Hei",
modusspesifikkeResultat = Valg21SpesifikkeResultat(
vilPolitikkLink = false,
vilBliMerAktiv = false,
vilBliRingtAugust = false,
vilHaMedlemsLink = false,
vilHaFellesskapLink = true
),
vilIkkeBliRingt = false
),
modus = Modus.medlemmer
)
assertThrows(AssertionError::class.java) {
ringService.registrerResultatFraSamtale(request)
}
}
private fun createRingbarPerson(
fornavn: String,
etternavn: String,
telefonnummer: String,
id: Int,
hypersysID: Int
) {
val person = Person(
hypersysID = hypersysID,
fornavn = fornavn,
etternavn = etternavn,
telefonnummer = telefonnummer,
email = "",
postnummer = Postnummer("1234", "Lillevik", Kommune("", "", 0, 0)),
fylke = 0,
lokallag = 0,
groupID = 0,
kilde = Kilde.Hypersys,
sistOppdatert = null
)
doReturn(person).whenever(personRepository).findById(id)
val query: PanacheQuery<Person> = mock()
doReturn(person).whenever(query).firstResult<Person>()
doReturn(query).whenever(personRepository).find("hypersysID", hypersysID)
}
}
| 10
|
Kotlin
|
0
| 0
|
fdca6b0524d1f2d3c53edbb026c5f2ee736e7559
| 5,153
|
ringesentralen-backend
|
MIT License
|
app/src/main/java/com/example/thinkpress/ui/NewsViewModel.kt
|
LM-Git760
| 703,797,062
| false
|
{"Kotlin": 33671}
|
package com.example.thinkpress.ui
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.thinkpress.api.Article
import com.example.thinkpress.api.NewsApiResponse
import com.example.thinkpress.api.NewsApiService
import com.example.thinkpress.api.NewsResult
import com.example.thinkpress.remote.FavoriteArticlesRepository
import com.example.thinkpress.remote.NewsRepository
import com.google.firebase.database.FirebaseDatabase
import kotlinx.coroutines.launch
import retrofit2.Response
class NewsViewModel(
newsApiService: NewsApiService,
private val favoriteArticlesRepository: FavoriteArticlesRepository,
private val apiKey: String,
) : ViewModel() {
private val newsRepository = NewsRepository(newsApiService)
private val _newsResult = MutableLiveData<NewsResult>()
val newsResult: LiveData<NewsResult> get() = _newsResult
fun removeFavoriteFromDatabase(favorite: Article) {
viewModelScope.launch {
try {
// Entfernen aus der Room-Datenbank
favoriteArticlesRepository.removeFavorite(favorite)
// Entfernen aus der Firebase-Datenbank
val favoriteArticlesRef = FirebaseDatabase.getInstance().getReference("favoriteArticles")
favoriteArticlesRef.child(favorite.articleId).removeValue()
} catch (e: Exception) {
Log.e("NewsViewModel", "Fehler beim Entfernen des Favoriten: ${e.localizedMessage}")
}
}
}
// Sucht News basierend auf einer Query
fun searchNews(query: String) {
viewModelScope.launch {
try {
val response: Response<NewsApiResponse> = newsRepository.fetchNews(apiKey, query)
if (response.isSuccessful) {
_newsResult.postValue(NewsResult.Success(response.body()?.results ?: mutableListOf()))
} else {
_newsResult.postValue(NewsResult.Failure(response.code()))
}
} catch (e: Exception) {
Log.e("NewsViewModel", e.localizedMessage ?: "Ein unbekannter Fehler ist aufgetreten.")
_newsResult.postValue(NewsResult.Failure(-1))
}
}
}
// Ruft News mit festgelegten Suchbegriffen ab
fun fetchNews() {
viewModelScope.launch {
try {
val response: Response<NewsApiResponse> = newsRepository.fetchNews(apiKey, "heute")
if (response.isSuccessful) {
_newsResult.postValue(NewsResult.Success(response.body()?.results ?: mutableListOf()))
Log.i("NewsViewModel", response.body().toString())
} else {
_newsResult.postValue(NewsResult.Failure(response.code()))
}
} catch (e: Exception) {
Log.e("NewsViewModel", e.localizedMessage ?: "Ein unbekannter Fehler ist aufgetreten.")
_newsResult.postValue(NewsResult.Failure(-1))
}
}
}
// Überprüft, ob ein Artikel favorisiert ist
suspend fun isFavorite(article: Article): Boolean {
return favoriteArticlesRepository.isFavorite(article.articleId)
}
// Fügt einen Artikel zu den Favoriten hinzu
fun addFavorite(article: Article) {
viewModelScope.launch {
favoriteArticlesRepository.addFavorite(article)
}
}
// Entfernt einen Artikel aus den Favoriten
fun removeFavorite(article: Article) {
viewModelScope.launch {
favoriteArticlesRepository.removeFavorite(article)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e8d53aa70269dc9f9180c180351dbac628f69e7c
| 3,754
|
ThinkPress
|
RSA Message-Digest License
|
compiler/testData/diagnostics/tests/multiplatform/nestedClassViaActualTypealias.fir.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// MODULE: m1-common
// FILE: common.kt
expect class Foo {
class Inner()
}
expect class SeveralInner {
class Inner1 {
class Inner2 {
class Inner3()
}
}
}
// MODULE: m2-jvm()()(m1-common)
// FILE: jvm.kt
class FooImpl {
class Inner
}
actual typealias Foo = FooImpl
class SeveralInnerImpl {
class Inner1 {
class Inner2 {
class Inner3
}
}
}
actual typealias SeveralInner = SeveralInnerImpl
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 472
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/de/jupf/staticlog/format/Builders.kt
|
AutoWay
| 101,705,625
| true
|
{"Kotlin": 32668, "Java": 2112}
|
package de.jupf.staticlog.format
import de.jupf.staticlog.core.LogLevel
import java.text.SimpleDateFormat
import java.util.Date
import kotlin.collections.indices
import kotlin.text.split
/**
* @author J.Pfeifer
* @created 20.12.2015
*/
interface Builder {
fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String)
}
open class TextBuilder(val text: String) : Builder {
override fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String) {
builder.append(text)
}
}
class MessageBuilder : Builder {
override fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String) {
builder.append(message)
}
}
class LevelBuilder : Builder {
override fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String) {
builder.append(logLevel.toString())
}
}
class EpochBuilder : Builder {
override fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String) {
builder.append(time)
}
}
class DateBuilder(format: String) : Builder {
val dateFormat = SimpleDateFormat(format)
override fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String) {
builder.append(dateFormat.format(Date(time)))
}
}
class TagBuilder : Builder {
override fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String) {
builder.append("$tag")
}
}
class OccurrenceBuilder : Builder {
override fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String) {
builder.append("[${trace.toString()}]")
}
}
internal class ExceptionBuilder : Builder {
override fun buildString(logLevel: LogLevel, time: Long, message: String, tag: String, exception: Throwable?, builder: StringBuilder, trace: StackTraceElement?, indent: String) {
if (exception != null) {
builder.append(exception.javaClass.name + ": " + exception.message + "\n" + indent + " ")
for (i in exception.stackTrace.indices) {
builder.append("at " + exception.stackTrace[i].toString() + "\n" + indent + " ")
}
if (exception.cause != null) {
builder.setLength(builder.length - 3)
builder.append("Caused by: " + exception.cause!!.javaClass.name + ": " + exception.cause!!.message + "\n" + indent + " ")
for (i in exception.stackTrace.indices) {
builder.append("at " + exception.stackTrace[i].toString() + "\n" + indent + " ")
}
}
builder.setLength(builder.length - (indent.length + 4))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2e0dd66cc070dadbb309491b8644164368b88153
| 3,408
|
staticlog
|
MIT License
|
application/shared/src/main/kotlin/financial/shared/adapters/console/command/Command.kt
|
gustavofreze
| 414,017,610
| false
|
{"Kotlin": 104127, "Makefile": 1058, "Shell": 638, "Dockerfile": 512}
|
package financial.shared.adapters.console.command
interface Command
| 0
|
Kotlin
|
3
| 70
|
c21ec989470a9b4c4b367a85923d4285d53320e7
| 69
|
financial
|
MIT License
|
app/src/main/java/com/cuong/moviehero/ui/components/MovieItem.kt
|
cuonghuynhvan
| 471,910,042
| false
|
{"Kotlin": 141883}
|
package com.cuong.moviehero.ui.components
import androidx.compose.foundation.background
import androidx.compose.runtime.Composable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.MaterialTheme
import androidx.compose.ui.res.painterResource
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.cuong.moviehero.R
import com.cuong.moviehero.ui.theme.MovieHeroTheme
import com.cuong.moviehero.ui.theme.Yellow
import androidx.compose.ui.graphics.Color
@Composable
fun MovieItem(
modifier: Modifier = Modifier,
imageUrl: String = "",
title: String = "",
releaseDate: String = "",
overview: String = "",
rate: Float = 0f,
onClick: () -> Unit = {},
) {
ConstraintLayout(
modifier = modifier
.fillMaxWidth()
.clickable( role = Role.Button, onClick = onClick )
.height(152.dp)
.padding(16.dp),
) {
val ( imageRef, titleRef, overviewRef, dateRef, starRef, rateRef ) = createRefs()
NetImage(
modifier = Modifier
.height(120.dp)
.width(80.dp)
.constrainAs(imageRef) {
top.linkTo(parent.top)
start.linkTo(parent.start)
},
contentDescription = null,
imageUrl = imageUrl,
)
Text(
modifier = Modifier
.constrainAs(titleRef) {
top.linkTo(parent.top)
start.linkTo(imageRef.end, margin = 8.dp)
},
text = title,
style = MaterialTheme.typography.body1.copy(
color = MaterialTheme.colors.onBackground,
),
fontWeight = FontWeight.Bold,
)
Text(
modifier = Modifier
.constrainAs(dateRef) {
top.linkTo(titleRef.bottom)
start.linkTo(titleRef.start)
},
text = releaseDate,
style = MaterialTheme.typography.body2.copy(
color = MaterialTheme.colors.onBackground,
),
)
Icon(
modifier = Modifier
.constrainAs(starRef) {
bottom.linkTo(parent.bottom)
start.linkTo(titleRef.start)
},
painter = painterResource(id = R.drawable.ic_star),
tint = Yellow,
contentDescription = null
)
Text(
modifier = Modifier
.constrainAs(rateRef) {
top.linkTo(starRef.top)
start.linkTo(starRef.end, margin = 4.dp)
},
text = "$rate",
style = MaterialTheme.typography.body2.copy(
color = MaterialTheme.colors.onBackground,
),
)
Text(
modifier = Modifier
.constrainAs(overviewRef) {
top.linkTo(dateRef.bottom)
bottom.linkTo(starRef.top)
start.linkTo(titleRef.start)
end.linkTo(parent.end)
height = Dimension.fillToConstraints
width = Dimension.fillToConstraints
},
maxLines = 3,
text = overview,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.body2.copy(
color = MaterialTheme.colors.onBackground,
),
fontStyle = FontStyle.Italic,
)
}
}
@Preview(showBackground = true)
@Composable
fun MovieItemPreview() {
MovieHeroTheme {
Column(
modifier = Modifier.background(Color.White)
) {
MovieItem(
imageUrl = "",
title = "name",
releaseDate = "2020/11/20",
overview = "Framed in the 1940s for the double murder of his wife and her lover, upstanding banker <NAME> begins a new life at the Shawshank prison, where he puts his accounting skills to work for an amoral warden. During his long stretch in prison, Dufresne comes to be admired by the other inmates -- including an older prisoner named Red -- for his integrity and unquenchable sense of hope.",
rate = 6.5f,
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
36bc4b4d840343e7f7b63bc70f81546f8b49665d
| 5,042
|
MovieHero
|
MIT License
|
app/src/main/java/com/cuong/moviehero/ui/components/MovieItem.kt
|
cuonghuynhvan
| 471,910,042
| false
|
{"Kotlin": 141883}
|
package com.cuong.moviehero.ui.components
import androidx.compose.foundation.background
import androidx.compose.runtime.Composable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.MaterialTheme
import androidx.compose.ui.res.painterResource
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.cuong.moviehero.R
import com.cuong.moviehero.ui.theme.MovieHeroTheme
import com.cuong.moviehero.ui.theme.Yellow
import androidx.compose.ui.graphics.Color
@Composable
fun MovieItem(
modifier: Modifier = Modifier,
imageUrl: String = "",
title: String = "",
releaseDate: String = "",
overview: String = "",
rate: Float = 0f,
onClick: () -> Unit = {},
) {
ConstraintLayout(
modifier = modifier
.fillMaxWidth()
.clickable( role = Role.Button, onClick = onClick )
.height(152.dp)
.padding(16.dp),
) {
val ( imageRef, titleRef, overviewRef, dateRef, starRef, rateRef ) = createRefs()
NetImage(
modifier = Modifier
.height(120.dp)
.width(80.dp)
.constrainAs(imageRef) {
top.linkTo(parent.top)
start.linkTo(parent.start)
},
contentDescription = null,
imageUrl = imageUrl,
)
Text(
modifier = Modifier
.constrainAs(titleRef) {
top.linkTo(parent.top)
start.linkTo(imageRef.end, margin = 8.dp)
},
text = title,
style = MaterialTheme.typography.body1.copy(
color = MaterialTheme.colors.onBackground,
),
fontWeight = FontWeight.Bold,
)
Text(
modifier = Modifier
.constrainAs(dateRef) {
top.linkTo(titleRef.bottom)
start.linkTo(titleRef.start)
},
text = releaseDate,
style = MaterialTheme.typography.body2.copy(
color = MaterialTheme.colors.onBackground,
),
)
Icon(
modifier = Modifier
.constrainAs(starRef) {
bottom.linkTo(parent.bottom)
start.linkTo(titleRef.start)
},
painter = painterResource(id = R.drawable.ic_star),
tint = Yellow,
contentDescription = null
)
Text(
modifier = Modifier
.constrainAs(rateRef) {
top.linkTo(starRef.top)
start.linkTo(starRef.end, margin = 4.dp)
},
text = "$rate",
style = MaterialTheme.typography.body2.copy(
color = MaterialTheme.colors.onBackground,
),
)
Text(
modifier = Modifier
.constrainAs(overviewRef) {
top.linkTo(dateRef.bottom)
bottom.linkTo(starRef.top)
start.linkTo(titleRef.start)
end.linkTo(parent.end)
height = Dimension.fillToConstraints
width = Dimension.fillToConstraints
},
maxLines = 3,
text = overview,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.body2.copy(
color = MaterialTheme.colors.onBackground,
),
fontStyle = FontStyle.Italic,
)
}
}
@Preview(showBackground = true)
@Composable
fun MovieItemPreview() {
MovieHeroTheme {
Column(
modifier = Modifier.background(Color.White)
) {
MovieItem(
imageUrl = "",
title = "name",
releaseDate = "2020/11/20",
overview = "Framed in the 1940s for the double murder of his wife and her lover, upstanding banker <NAME> begins a new life at the Shawshank prison, where he puts his accounting skills to work for an amoral warden. During his long stretch in prison, Dufresne comes to be admired by the other inmates -- including an older prisoner named Red -- for his integrity and unquenchable sense of hope.",
rate = 6.5f,
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
36bc4b4d840343e7f7b63bc70f81546f8b49665d
| 5,042
|
MovieHero
|
MIT License
|
src/main/kotlin/no/nav/omsorgspenger/omsorgsdager/OmsorgsdagerBeregning.kt
|
navikt
| 293,469,365
| false
|
{"Kotlin": 598600, "Dockerfile": 223}
|
package no.nav.omsorgspenger.omsorgsdager
import no.nav.omsorgspenger.Periode
import no.nav.omsorgspenger.lovverk.*
import no.nav.omsorgspenger.lovverk.Lovanvendelser
internal object OmsorgsdagerBeregning {
private const val DagerMedGrunnrettOppTilToBarn = 10
private const val DagerMedGrunnrettTreEllerFlerBarn = 15
private const val DagerMedAleneOmsorgOppTilToBarn = 10
private const val DagerMedAleneOmsorgTreEllerFlerBarn = 15
private const val DagerMedUtvidetRettPerBarn = 10
private const val DagerMedUtvidetRettOgAleneOmsorgPerBarn = 20
internal fun beregnOmsorgsdager(barnMedOmsorgenFor: List<OmsorgsdagerBarn>): OmsorgsdagerResultat {
val barnMedAleneOmOmsorgen = barnMedOmsorgenFor.filter { it.aleneOmOmsorgen }
val barnMedKunUtvidetRett = barnMedOmsorgenFor.filter { it.utvidetRett && !it.aleneOmOmsorgen }
val barnMedUtvidetRettOgAleneOmOmsorgen = barnMedOmsorgenFor.filter { it.utvidetRett && it.aleneOmOmsorgen }
val grunnrett = when (barnMedOmsorgenFor.size) {
0 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = 0, antallDager = 0)
in 1..2 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedOmsorgenFor.size, antallDager = DagerMedGrunnrettOppTilToBarn)
else -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedOmsorgenFor.size, antallDager = DagerMedGrunnrettTreEllerFlerBarn)
}
val aleneOmsorg = when (barnMedAleneOmOmsorgen.size) {
0 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = 0, antallDager = 0)
in 1..2 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedAleneOmOmsorgen.size, antallDager = DagerMedAleneOmsorgOppTilToBarn)
else -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedAleneOmOmsorgen.size, antallDager = DagerMedAleneOmsorgTreEllerFlerBarn)
}
val utvidetRett = when (barnMedKunUtvidetRett.size) {
0 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = 0, antallDager = 0)
else -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedKunUtvidetRett.size, antallDager = DagerMedUtvidetRettPerBarn * barnMedKunUtvidetRett.size)
}
val aleneomsorgOgUtvidetRett = when (barnMedUtvidetRettOgAleneOmOmsorgen.size) {
0 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = 0, antallDager = 0)
else -> OmsorgsdagerResultat.Omsorgsdager(
antallBarn = barnMedUtvidetRettOgAleneOmOmsorgen.size,
antallDager = DagerMedUtvidetRettOgAleneOmsorgPerBarn * barnMedUtvidetRettOgAleneOmOmsorgen.size
)
}
return OmsorgsdagerResultat(
grunnrettsdager = grunnrett,
aleneomsorgsdager = aleneOmsorg,
utvidetRettDager = utvidetRett,
aleneomsorgOgUtvidetRettDager = aleneomsorgOgUtvidetRett
)
}
internal fun OmsorgsdagerResultat.leggTilLovanvendelser(
lovanvendelser: Lovanvendelser,
periode: Periode) {
if (grunnrettsdager.antallBarn in 1..2) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = GrunnrettOppTilToBarn,
anvendelse = "Har omsorgen for ${grunnrettsdager.antallBarn} barn"
)
}
if (grunnrettsdager.antallBarn >= 3) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = GrunnrettTreEllerFlerBarn,
anvendelse = "Har omsorgen for ${grunnrettsdager.antallBarn} barn"
)
}
if (aleneomsorgsdager.antallBarn > 0) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = AleneOmOmsorgenForBarnet,
anvendelse = "Har aleneomsorg for ${aleneomsorgsdager.antallBarn} barn"
)
}
if (utvidetRettDager.antallBarn > 0) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = UtvidetRettForBarnet,
anvendelse = "Har utvidet rett for ${utvidetRettDager.antallBarn} barn"
)
}
if (aleneomsorgOgUtvidetRettDager.antallBarn > 0) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = UtvidetRettOgAleneOmOmsorgenForBarnet,
anvendelse = "Har aleneomsorg og utvidet rett for ${aleneomsorgOgUtvidetRettDager.antallBarn} barn"
)
}
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = AntallOmsorgsdager,
anvendelser = setOf(
"Har $antallOmsorgsdager omsorgsdager",
"Har grunnrett på ${grunnrettsdager.antallDager} dager"
)
)
}
}
| 1
|
Kotlin
|
1
| 2
|
378101129956af238282bb37bfee2af0ec9a0bec
| 4,805
|
omsorgspenger-rammemeldinger
|
MIT License
|
src/main/kotlin/no/nav/omsorgspenger/omsorgsdager/OmsorgsdagerBeregning.kt
|
navikt
| 293,469,365
| false
|
{"Kotlin": 598600, "Dockerfile": 223}
|
package no.nav.omsorgspenger.omsorgsdager
import no.nav.omsorgspenger.Periode
import no.nav.omsorgspenger.lovverk.*
import no.nav.omsorgspenger.lovverk.Lovanvendelser
internal object OmsorgsdagerBeregning {
private const val DagerMedGrunnrettOppTilToBarn = 10
private const val DagerMedGrunnrettTreEllerFlerBarn = 15
private const val DagerMedAleneOmsorgOppTilToBarn = 10
private const val DagerMedAleneOmsorgTreEllerFlerBarn = 15
private const val DagerMedUtvidetRettPerBarn = 10
private const val DagerMedUtvidetRettOgAleneOmsorgPerBarn = 20
internal fun beregnOmsorgsdager(barnMedOmsorgenFor: List<OmsorgsdagerBarn>): OmsorgsdagerResultat {
val barnMedAleneOmOmsorgen = barnMedOmsorgenFor.filter { it.aleneOmOmsorgen }
val barnMedKunUtvidetRett = barnMedOmsorgenFor.filter { it.utvidetRett && !it.aleneOmOmsorgen }
val barnMedUtvidetRettOgAleneOmOmsorgen = barnMedOmsorgenFor.filter { it.utvidetRett && it.aleneOmOmsorgen }
val grunnrett = when (barnMedOmsorgenFor.size) {
0 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = 0, antallDager = 0)
in 1..2 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedOmsorgenFor.size, antallDager = DagerMedGrunnrettOppTilToBarn)
else -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedOmsorgenFor.size, antallDager = DagerMedGrunnrettTreEllerFlerBarn)
}
val aleneOmsorg = when (barnMedAleneOmOmsorgen.size) {
0 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = 0, antallDager = 0)
in 1..2 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedAleneOmOmsorgen.size, antallDager = DagerMedAleneOmsorgOppTilToBarn)
else -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedAleneOmOmsorgen.size, antallDager = DagerMedAleneOmsorgTreEllerFlerBarn)
}
val utvidetRett = when (barnMedKunUtvidetRett.size) {
0 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = 0, antallDager = 0)
else -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = barnMedKunUtvidetRett.size, antallDager = DagerMedUtvidetRettPerBarn * barnMedKunUtvidetRett.size)
}
val aleneomsorgOgUtvidetRett = when (barnMedUtvidetRettOgAleneOmOmsorgen.size) {
0 -> OmsorgsdagerResultat.Omsorgsdager(antallBarn = 0, antallDager = 0)
else -> OmsorgsdagerResultat.Omsorgsdager(
antallBarn = barnMedUtvidetRettOgAleneOmOmsorgen.size,
antallDager = DagerMedUtvidetRettOgAleneOmsorgPerBarn * barnMedUtvidetRettOgAleneOmOmsorgen.size
)
}
return OmsorgsdagerResultat(
grunnrettsdager = grunnrett,
aleneomsorgsdager = aleneOmsorg,
utvidetRettDager = utvidetRett,
aleneomsorgOgUtvidetRettDager = aleneomsorgOgUtvidetRett
)
}
internal fun OmsorgsdagerResultat.leggTilLovanvendelser(
lovanvendelser: Lovanvendelser,
periode: Periode) {
if (grunnrettsdager.antallBarn in 1..2) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = GrunnrettOppTilToBarn,
anvendelse = "Har omsorgen for ${grunnrettsdager.antallBarn} barn"
)
}
if (grunnrettsdager.antallBarn >= 3) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = GrunnrettTreEllerFlerBarn,
anvendelse = "Har omsorgen for ${grunnrettsdager.antallBarn} barn"
)
}
if (aleneomsorgsdager.antallBarn > 0) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = AleneOmOmsorgenForBarnet,
anvendelse = "Har aleneomsorg for ${aleneomsorgsdager.antallBarn} barn"
)
}
if (utvidetRettDager.antallBarn > 0) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = UtvidetRettForBarnet,
anvendelse = "Har utvidet rett for ${utvidetRettDager.antallBarn} barn"
)
}
if (aleneomsorgOgUtvidetRettDager.antallBarn > 0) {
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = UtvidetRettOgAleneOmOmsorgenForBarnet,
anvendelse = "Har aleneomsorg og utvidet rett for ${aleneomsorgOgUtvidetRettDager.antallBarn} barn"
)
}
lovanvendelser.leggTil(
periode = periode,
lovhenvisning = AntallOmsorgsdager,
anvendelser = setOf(
"Har $antallOmsorgsdager omsorgsdager",
"Har grunnrett på ${grunnrettsdager.antallDager} dager"
)
)
}
}
| 1
|
Kotlin
|
1
| 2
|
378101129956af238282bb37bfee2af0ec9a0bec
| 4,805
|
omsorgspenger-rammemeldinger
|
MIT License
|
src/main/kotlin/dev/aohara/bookshelf/Main.kt
|
oharaandrew314
| 618,205,252
| false
| null |
package dev.aohara.bookshelf
import org.http4k.client.Java8HttpClient
import org.http4k.cloudnative.env.Environment
import org.http4k.cloudnative.env.EnvironmentKey
import org.http4k.connect.amazon.CredentialsProvider
import org.http4k.connect.amazon.Profile
import org.http4k.connect.amazon.RegionProvider
import org.http4k.connect.amazon.dynamodb.DynamoDb
import org.http4k.connect.amazon.dynamodb.Http
import org.http4k.connect.amazon.dynamodb.model.TableName
import org.http4k.lens.value
import org.http4k.server.SunHttp
import org.http4k.server.asServer
import org.http4k.serverless.ApiGatewayV2LambdaFunction
import org.http4k.serverless.AppLoader
private val tableKey = EnvironmentKey.value(TableName).required("TABLE_NAME")
// run the main method to run the server locally
// requires AWS_PROFILE env var to be set
fun main() {
val env = Environment.ENV
val dynamoDb = DynamoDb.Http(
region = RegionProvider.Profile(env).orElseThrow(),
credentialsProvider = CredentialsProvider.Profile(env)
)
val tableName = tableKey(env)
dynamoBookShelf(dynamoDb, tableName)
.toHttp()
.asServer(SunHttp(8000))
.start()
.block()
}
// entrypoint for the AWS Lambda Runtime
class ApiLambdaHandler : ApiGatewayV2LambdaFunction(AppLoader {
val env = Environment.from(it)
val dynamoDb = DynamoDb.Http(
env = env, // get AWS credentials and region directly from env
http = Java8HttpClient() // Has faster cold-start than the java 11 client
)
val tableName = tableKey(env)
dynamoBookShelf(dynamoDb, tableName)
.toHttp()
})
| 0
|
Kotlin
|
0
| 1
|
e69feb756388d8d32fc5bcc1123a88bb78925b01
| 1,630
|
http4k-api-on-lambda
|
Apache License 2.0
|
bot/src/main/kotlin/me/y9san9/prizebot/resources/markups/selectLinkedChatMarkup.kt
|
y9san9
| 337,414,979
| false
| null |
package me.y9san9.prizebot.resources.markups
import dev.inmo.tgbotapi.types.buttons.ReplyKeyboardMarkup
import dev.inmo.tgbotapi.types.buttons.SimpleKeyboardButton
import me.y9san9.prizebot.extensions.telegram.PrizebotLocalizedBotUpdate
import me.y9san9.prizebot.extensions.telegram.locale
fun selectLinkedChatMarkup(update: PrizebotLocalizedBotUpdate, usernames: List<String>): ReplyKeyboardMarkup {
val linkedChats = usernames
.map(::SimpleKeyboardButton)
.chunked(size = 4)
return ReplyKeyboardMarkup (
keyboard = listOf (
listOf(SimpleKeyboardButton(update.locale.updateChannels))
) + linkedChats,
resizeKeyboard = true
)
}
| 14
|
Kotlin
|
13
| 51
|
74fbd7e83ea8a1083a0b0f72ae79c62e95d7a421
| 696
|
prizebot
|
MIT License
|
compiler/testData/psi/EnumSemicolonBetweenWithMembers.kt
|
staltz
| 38,581,975
| true
|
{"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831}
|
enum class Color {
NORTH;
fun foo() = 1
SOUTH;
companion object {
fun bar() = 2
}
WEST;
EAST
}
| 0
|
Java
|
0
| 1
|
80074c71fa925a1c7173e3fffeea4cdc5872460f
| 130
|
kotlin
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.