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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/pl/mrugacz95/aoc/day11/day11.kt
|
mrugacz95
| 317,354,321
| false
| null |
package pl.mrugacz95.aoc.day11
class Ferry(private var seats: List<String>, private val tolerance: Int, closeNeighbourhood: Boolean = true) {
companion object {
const val EMPTY = 'L'
const val OCCUPIED = '#'
}
private val checker = when (closeNeighbourhood) {
true -> CloseNeighbourChecker()
false -> FarNeighbourChecker()
}
fun getSeat(y: Int, x: Int): Char {
return seats[y][x]
}
abstract inner class NeighbourChecker {
abstract fun check(y: Int, x: Int, direction: Pair<Int, Int>): Boolean
}
inner class CloseNeighbourChecker : NeighbourChecker() {
override fun check(y: Int, x: Int, direction: Pair<Int, Int>): Boolean {
val ny = y + direction.first
val nx = x + direction.second
return ny >= 0 && ny < seats.size && nx >= 0 && nx < seats[0].length && getSeat(ny, nx) == OCCUPIED
}
}
inner class FarNeighbourChecker : NeighbourChecker() {
override fun check(y: Int, x: Int, direction: Pair<Int, Int>): Boolean {
var ny = y + direction.first
var nx = x + direction.second
while (ny >= 0 && ny < seats.size && nx >= 0 && nx < seats[0].length) {
when (getSeat(ny, nx)) {
OCCUPIED -> return true
EMPTY -> return false
}
ny += direction.first
nx += direction.second
}
return false
}
}
private fun countNeighbours(y: Int, x: Int): Int {
val directions = generateDirections()
var count = 0
for (dir in directions) {
if (checker.check(y, x, dir)) {
count += 1
}
}
return count
}
private fun generateDirections(): MutableList<Pair<Int, Int>> {
val directions = mutableListOf<Pair<Int, Int>>()
for (dy in -1..1) {
for (dx in -1..1) {
if (dy == 0 && dx == 0) continue
directions.add(Pair(dy, dx))
}
}
return directions
}
fun step(): Boolean {
val newSeats = seats.mapIndexed { rowId, row ->
row.mapIndexed { colId, seat ->
val occupied = countNeighbours(rowId, colId)
when (seat) {
EMPTY -> if (occupied == 0) OCCUPIED else EMPTY
OCCUPIED -> if (occupied >= tolerance) EMPTY else OCCUPIED
else -> seat
}
}.joinToString("")
}.toList()
val changed = newSeats == seats
seats = newSeats
return changed
}
fun countOccupied(): Int {
return seats.map { it.filter { seat -> seat == OCCUPIED }.count() }.sum()
}
override fun toString(): String {
return "count : ${countOccupied()}\n${seats.joinToString("\n")}\n"
}
}
fun solve(ferry: Ferry): Int {
var afterStep = ferry.countOccupied()
var beforeStep: Int
do {
beforeStep = afterStep
ferry.step()
afterStep = ferry.countOccupied()
} while (beforeStep != afterStep)
return beforeStep
}
fun main() {
val seats = {}::class.java.getResource("/day11.in")
.readText()
.split("\n")
println("Answer part 1: ${solve(Ferry(seats, 4))}")
println("Answer part 2: ${solve(Ferry(seats, 5, false))}")
}
| 0
|
Kotlin
|
0
| 1
|
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
| 3,441
|
advent-of-code-2020
|
Do What The F*ck You Want To Public License
|
src/main/kotlin/ch/leadrian/samp/kamp/cidl/parser/InterfaceDefinitionSource.kt
|
Double-O-Seven
| 142,360,449
| false
| null |
package ch.leadrian.samp.kamp.cidl.parser
import java.io.InputStream
interface InterfaceDefinitionSource {
fun getInputStream(): InputStream
}
| 0
|
Kotlin
|
0
| 0
|
c993feb277b3970504a3202eb96e6eedd829fa9e
| 150
|
cidl-kotlin
|
Apache License 2.0
|
app/web3proxy/src/main/kotlin/io/hamal/app/web3proxy/eth/http/EthController.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 3316689, "C": 1401511, "TypeScript": 450023, "Lua": 193995, "C++": 40651, "Makefile": 11728, "Java": 7564, "JavaScript": 5832, "SCSS": 5191, "CMake": 2838, "CSS": 1626, "HTML": 1245, "Shell": 993}
|
package io.hamal.app.web3proxy.eth.http
import io.hamal.app.web3proxy.eth.handler.HandleEthRequest
import io.hamal.lib.common.hot.HotArray
import io.hamal.lib.common.hot.HotNode
import io.hamal.lib.common.hot.HotObject
import io.hamal.lib.web3.evm.chain.eth.domain.EthRequest
import io.hamal.lib.web3.evm.chain.eth.domain.EthResponse
import io.hamal.lib.web3.evm.chain.eth.domain.parseEthRequest
import io.hamal.lib.web3.json
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
@RestController
internal class EthController(
private val handle: HandleEthRequest
) {
@PostMapping("/eth")
fun handle(@RequestBody body: HotNode<*>): ResponseEntity<*> {
return when (body) {
is HotArray -> handleArray(body)
is HotObject -> handleObject(body)
else -> TODO()
}
}
private fun handleArray(requests: HotArray): ResponseEntity<List<EthResponse>> {
val reqs = requests
.filterIsInstance<HotObject>()
.map { request ->
val (err, req) = parseEthRequest(json, request)
if (err != null) {
err
} else {
req
}
}
return ResponseEntity.ok(
handle(reqs.filterIsInstance<EthRequest>())
.plus(reqs.filterIsInstance<EthResponse>())
)
}
private fun handleObject(request: HotObject): ResponseEntity<EthResponse> {
val (err, req) = parseEthRequest(json, request)
if (err != null) {
return ResponseEntity.ok(err)
}
return ResponseEntity.ok(handle(req!!))
}
}
| 44
|
Kotlin
|
0
| 0
|
1c9b1ad3368823ad9c339b6a56532a602cef7c63
| 1,832
|
hamal
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/com/grudus/planshboard/stats/StatsService.kt
|
grudus
| 115,259,708
| false
| null |
package com.grudus.planshboard.stats
import com.grudus.planshboard.commons.Id
import com.grudus.planshboard.stats.models.OpponentCount
import com.grudus.planshboard.stats.models.StatsDto
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class StatsService
@Autowired
constructor(private val gamesStatsDao: GamesStatsDao,
private val playsStatsDao: PlaysStatsDao) {
fun generateStats(userId: Id, opponentId: Id): StatsDto {
return StatsDto(
boardGamesCount = gamesStatsDao.countAllGames(opponentId),
allPlaysCount = playsStatsDao.countAllPlays(opponentId),
playsPerBoardGameCount = playsStatsDao.countPlaysPerBoardGames(opponentId),
opponentWins = playsStatsDao.findOpponentWins(opponentId),
winsPerBoardGame = playsStatsDao.findOpponentWinsPerBoardGame(opponentId)
)
}
}
| 0
|
Kotlin
|
0
| 1
|
1b9fd909a75d5b0883e8ff39be9aa299bf0ff3ff
| 958
|
Planshboard
|
Apache License 2.0
|
app/src/main/java/br/alexandregpereira/abacate/ui/component/ActionHeader.kt
|
alexandregpereira
| 345,202,106
| false
| null |
package br.alexandregpereira.abacate.ui.component
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import br.alexandregpereira.abacate.ui.theme.AbacateTheme
import br.alexandregpereira.abacate.ui.theme.GrayScale100
import br.alexandregpereira.abacate.ui.theme.White
import dev.chrisbanes.accompanist.coil.CoilImage
const val IMAGE_URL_DEFAULT = ""
private const val MAX_IMAGES = 5
@ExperimentalAnimationApi
@Composable
fun ActionHeader(
text: String,
modifier: Modifier = Modifier,
urls: List<String> = emptyList()
) {
var opened by remember { mutableStateOf(false) }
val rowModifier = Modifier
.then(modifier)
.height(height = 40.dp)
.fillMaxWidth()
.semantics { testTag = "ActionHeader" }
.run {
if (opened) {
horizontalScroll(rememberScrollState())
} else {
this
}
}
Row(
modifier = rowModifier
) {
if (urls.isNotEmpty()) {
val onTap: (Offset) -> Unit = {
opened = opened.not()
}
CircleImages(
urls = urls,
opened = opened,
onTap = onTap,
modifier = Modifier.align(Alignment.CenterVertically)
)
}
val textPaddingStart = if (urls.isEmpty()) 16.dp else 0.dp
TextVisibility(
text = text,
visible = !opened,
modifier = Modifier
.padding(start = textPaddingStart, end = 16.dp)
.align(Alignment.CenterVertically)
)
}
}
@ExperimentalAnimationApi
@Composable
fun TextVisibility(
text: String,
visible: Boolean,
modifier: Modifier = Modifier
) {
AnimatedVisibility(
visible = visible,
enter = slideInHorizontally(initialOffsetX = { it * 3 }),
exit = slideOutHorizontally(targetOffsetX = { it * 3 }),
modifier = modifier
) {
Text(
text = text,
maxLines = 2
)
}
}
@ExperimentalAnimationApi
@Preview(backgroundColor = 0xFFFFFFFF)
@Composable
fun TextVisibilityPreview() {
AbacateTheme(darkTheme = true) {
var visible by remember { mutableStateOf(true) }
TextVisibility("teste", visible)
Button(onClick = { visible = !visible }, modifier = Modifier.padding(top = 24.dp)) {
Text(text = "Click")
}
}
}
@Composable
fun CircleImages(
urls: List<String>,
opened: Boolean,
onTap: (Offset) -> Unit,
modifier: Modifier = Modifier
) {
val paddingTransition = updateTransition(targetState = opened)
val secondPaddingIncrease by paddingTransition.animatePaddingDp { stateOpened ->
if (stateOpened) {
48.dp
} else {
if (urls.size == 2) 32.dp else 24.dp
}
}
val thirdAndMorePaddingIncrease by paddingTransition.animatePaddingDp { stateOpened ->
if (stateOpened) 48.dp else 4.dp
}
var pressed by remember { mutableStateOf(false) }
val boxModifier = Modifier
.then(modifier)
.pressedGesture(
enabled = urls.size > 2,
onTap = onTap,
onPressed = { pressed = it }
)
Box(boxModifier) {
var startPadding = 16.dp
urls.forEachIndexed { index, url ->
CircleImage(
url,
pressed = pressed,
modifier = Modifier.padding(start = startPadding, end = 16.dp)
)
startPadding += when {
index == 0 -> secondPaddingIncrease
index in MAX_IMAGES..urls.size && opened.not() -> 0.dp
else -> thirdAndMorePaddingIncrease
}
}
}
}
@Composable
fun CircleImage(
url: String,
modifier: Modifier = Modifier,
pressed: Boolean = false
) {
val scale = animatePressed(pressed = pressed)
CoilImage(
data = url,
contentDescription = "My content description",
fadeIn = true,
modifier = modifier
.size((40 * scale).dp)
.clip(shape = CircleShape)
.background(color = GrayScale100)
.border(width = 4.dp, color = White, shape = CircleShape)
.semantics { testTag = "OvalImage" }
)
}
@Composable
private fun Transition<Boolean>.animatePaddingDp(
targetValueByState: @Composable (Boolean) -> Dp
) = animateDp(
transitionSpec = {
if (targetState) {
spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
visibilityThreshold = Dp.VisibilityThreshold
)
} else {
spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
visibilityThreshold = Dp.VisibilityThreshold
)
}
},
targetValueByState = targetValueByState
)
@ExperimentalAnimationApi
@Preview(backgroundColor = 0xFFFFFFFF)
@Composable
fun ActionHeaderPreview0() {
AbacateTheme {
ActionHeader(
text = "Anything"
)
}
}
@ExperimentalAnimationApi
@Preview
@Composable
fun ActionHeaderPreview1() {
AbacateTheme {
ActionHeader(
text = "Anything",
urls = listOf(IMAGE_URL_DEFAULT)
)
}
}
@ExperimentalAnimationApi
@Preview
@Composable
fun ActionHeaderPreview2() {
AbacateTheme {
ActionHeader(
text = "Anything asdsa d\nasdasdasddasd asdas\nasdasdasdasd",
urls = listOf(IMAGE_URL_DEFAULT, IMAGE_URL_DEFAULT)
)
}
}
@ExperimentalAnimationApi
@Preview
@Composable
fun ActionHeaderPreview3() {
AbacateTheme {
ActionHeader(
text = "Anything asdsa d\nasdasdasddasd asdas\nasdasdasdasd",
urls = listOf(IMAGE_URL_DEFAULT, IMAGE_URL_DEFAULT, IMAGE_URL_DEFAULT)
)
}
}
@ExperimentalAnimationApi
@Preview(showBackground = true)
@Composable
fun ActionHeaderPreview6() {
AbacateTheme {
ActionHeader(
text = "Anything asdsa d\nasdasdasddasd asdas\nasdasdasdasd",
urls = (0..10).map { IMAGE_URL_DEFAULT }
)
}
}
| 0
|
Kotlin
|
0
| 0
|
ae293bb119f7b78e08856ef5bb7006bb81e7446f
| 6,953
|
abacate
|
Apache License 2.0
|
pleo-antaeus-models/src/main/kotlin/io/pleo/antaeus/models/BillingStatus.kt
|
screaminbug
| 327,298,788
| true
|
{"Kotlin": 45194, "Shell": 861, "Dockerfile": 249}
|
package io.pleo.antaeus.models
enum class BillingStatus {
ACCEPTED,
DECLINED,
UNKNOWN_USER,
UNSUPPORTED_CURRENCY,
COMMUNICATION_PROBLEM,
GENERAL_FAILURE
}
| 0
|
Kotlin
|
0
| 0
|
91b0e59a04d5d2df1dd3f12c6860acdac089bb04
| 179
|
antaeus
|
Creative Commons Zero v1.0 Universal
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/CalendarStar.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.CalendarStar: ImageVector
get() {
if (_calendarStar != null) {
return _calendarStar!!
}
_calendarStar = Builder(name = "CalendarStar", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(16.365f, 14.183f)
curveToRelative(0.0f, 0.379f, -0.264f, 0.698f, -0.566f, 0.866f)
lineToRelative(-1.564f, 0.87f)
lineToRelative(0.694f, 1.893f)
curveToRelative(0.134f, 0.367f, 0.013f, 0.778f, -0.299f, 1.013f)
horizontalLineToRelative(0.0f)
curveToRelative(-0.319f, 0.24f, -0.759f, 0.237f, -1.075f, -0.007f)
lineToRelative(-1.556f, -1.203f)
lineToRelative(-1.556f, 1.203f)
curveToRelative(-0.316f, 0.244f, -0.756f, 0.247f, -1.075f, 0.007f)
horizontalLineToRelative(0.0f)
curveToRelative(-0.312f, -0.235f, -0.433f, -0.646f, -0.299f, -1.013f)
lineToRelative(0.694f, -1.893f)
lineToRelative(-1.564f, -0.87f)
curveToRelative(-0.302f, -0.168f, -0.566f, -0.487f, -0.566f, -0.866f)
curveToRelative(0.0f, -0.321f, 0.279f, -0.676f, 0.731f, -0.676f)
horizontalLineToRelative(2.247f)
lineToRelative(0.596f, -2.283f)
curveToRelative(0.094f, -0.362f, 0.419f, -0.614f, 0.792f, -0.621f)
curveToRelative(0.373f, 0.007f, 0.698f, 0.259f, 0.792f, 0.621f)
lineToRelative(0.596f, 2.283f)
horizontalLineToRelative(2.247f)
curveToRelative(0.452f, 0.0f, 0.731f, 0.354f, 0.731f, 0.676f)
close()
moveTo(18.5f, 2.0f)
horizontalLineToRelative(-0.5f)
verticalLineToRelative(-0.5f)
curveToRelative(0.0f, -0.829f, -0.671f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.671f, -1.5f, 1.5f)
verticalLineToRelative(0.5f)
horizontalLineToRelative(-6.0f)
verticalLineToRelative(-0.5f)
curveToRelative(0.0f, -0.829f, -0.671f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.671f, -1.5f, 1.5f)
verticalLineToRelative(0.5f)
horizontalLineToRelative(-0.5f)
curveTo(2.467f, 2.0f, 0.0f, 4.467f, 0.0f, 7.5f)
verticalLineToRelative(11.0f)
curveToRelative(0.0f, 3.033f, 2.467f, 5.5f, 5.5f, 5.5f)
horizontalLineToRelative(13.0f)
curveToRelative(3.033f, 0.0f, 5.5f, -2.467f, 5.5f, -5.5f)
lineTo(24.0f, 7.5f)
curveToRelative(0.0f, -3.033f, -2.467f, -5.5f, -5.5f, -5.5f)
close()
moveTo(18.5f, 21.0f)
lineTo(5.5f, 21.0f)
curveToRelative(-1.378f, 0.0f, -2.5f, -1.122f, -2.5f, -2.5f)
verticalLineToRelative(-9.5f)
horizontalLineToRelative(18.0f)
verticalLineToRelative(9.5f)
curveToRelative(0.0f, 1.378f, -1.122f, 2.5f, -2.5f, 2.5f)
close()
}
}
.build()
return _calendarStar!!
}
private var _calendarStar: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,184
|
icons
|
MIT License
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/scene/group_link/GroupLinkBundle.kt
|
Anime-Game-Servers
| 642,871,918
| false
|
{"Kotlin": 1651536}
|
package org.anime_game_servers.multi_proto.gi.data.scene.group_link
import org.anime_game_servers.core.base.Version.GI_2_1_0
import org.anime_game_servers.core.base.Version.GI_2_4_0
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.ProtoModel
import org.anime_game_servers.multi_proto.gi.data.general.Vector
@AddedIn(GI_2_1_0)
@ProtoModel
internal interface GroupLinkBundle {
var bundleId: Int
var center: Vector
var isActivated: Boolean
var radius: Int
var sceneId: Int
@AddedIn(GI_2_4_0)
var isShowMark: Boolean
}
| 0
|
Kotlin
|
2
| 6
|
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
| 614
|
anime-game-multi-proto
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/service/OffenderDeallocationServiceTest.kt
|
ministryofjustice
| 533,838,017
| false
| null |
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.PrisonerStatus
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.helpers.activityEntity
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.helpers.rolloutPrison
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.ActivityRepository
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.ActivityScheduleRepository
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.RolloutPrisonRepository
import java.time.LocalDate
import java.time.LocalDateTime
class OffenderDeallocationServiceTest {
private val rolloutPrisonRepo: RolloutPrisonRepository = mock()
private val activityRepo: ActivityRepository = mock()
private val activityScheduleRepo: ActivityScheduleRepository = mock()
private val service = OffenderDeallocationService(rolloutPrisonRepo, activityRepo, activityScheduleRepo)
private val yesterday = LocalDate.now().minusDays(1)
private val today = yesterday.plusDays(1)
@Test
fun `deallocate offenders from activity ending today`() {
val prison = rolloutPrison()
val activity = activityEntity(startDate = yesterday, endDate = today)
val schedule = activity.schedules().first()
val allocation = schedule.allocations().first()
with(allocation) {
assertThat(status(PrisonerStatus.ACTIVE)).isTrue
assertThat(deallocatedTime).isNull()
assertThat(deallocatedReason).isNull()
assertThat(deallocatedBy).isNull()
}
whenever(rolloutPrisonRepo.findAllByActiveIsTrue()).thenReturn(listOf(prison))
whenever(activityRepo.getAllForPrisonAndDate(prison.code, LocalDate.now())).thenReturn(listOf(activity))
service.deallocateOffendersWhenEndDatesReached()
with(allocation) {
assertThat(status(PrisonerStatus.ENDED)).isTrue
assertThat(deallocatedTime).isEqualToIgnoringSeconds(LocalDateTime.now())
assertThat(deallocatedReason).isNotNull
assertThat(deallocatedBy).isNotNull
}
verify(activityScheduleRepo).saveAndFlush(schedule)
}
@Test
fun `deallocate offenders from activity with no end date and allocation ends today`() {
val prison = rolloutPrison()
val activity = activityEntity(startDate = yesterday, endDate = null)
val schedule = activity.schedules().first()
val allocation = schedule.allocations().first().apply { endDate = today }
with(allocation) {
assertThat(status(PrisonerStatus.ACTIVE)).isTrue
assertThat(deallocatedTime).isNull()
assertThat(deallocatedReason).isNull()
assertThat(deallocatedBy).isNull()
}
whenever(rolloutPrisonRepo.findAllByActiveIsTrue()).thenReturn(listOf(prison))
whenever(activityRepo.getAllForPrisonAndDate(prison.code, LocalDate.now())).thenReturn(listOf(activity))
service.deallocateOffendersWhenEndDatesReached()
with(allocation) {
assertThat(status(PrisonerStatus.ENDED)).isTrue
assertThat(deallocatedTime).isEqualToIgnoringSeconds(LocalDateTime.now())
assertThat(deallocatedReason).isNotNull
assertThat(deallocatedBy).isNotNull
}
verify(activityScheduleRepo).saveAndFlush(schedule)
}
@Test
fun `offenders not deallocated from activity with no end date and allocation does not end today`() {
val prison = rolloutPrison()
val activity = activityEntity(startDate = yesterday, endDate = null)
val schedule = activity.schedules().first()
val allocation = schedule.allocations().first()
with(allocation) {
assertThat(status(PrisonerStatus.ACTIVE)).isTrue
assertThat(deallocatedTime).isNull()
assertThat(deallocatedReason).isNull()
assertThat(deallocatedBy).isNull()
}
whenever(rolloutPrisonRepo.findAllByActiveIsTrue()).thenReturn(listOf(prison))
whenever(activityRepo.getAllForPrisonAndDate(prison.code, LocalDate.now())).thenReturn(listOf(activity))
service.deallocateOffendersWhenEndDatesReached()
with(allocation) {
assertThat(status(PrisonerStatus.ACTIVE)).isTrue
assertThat(deallocatedTime).isNull()
assertThat(deallocatedReason).isNull()
assertThat(deallocatedBy).isNull()
}
verify(activityScheduleRepo, never()).saveAndFlush(any())
}
}
| 2
|
Kotlin
|
0
| 1
|
b69e4aee7a632f614ec8edb5a591503dc90a1909
| 4,597
|
hmpps-activities-management-api
|
MIT License
|
domain/src/main/java/com/bacon/domain/models/LocationsModel.kt
|
ItsTheBacon
| 420,929,644
| false
|
{"Kotlin": 66256}
|
package com.bacon.domain.models
data class LocationsModel(
val id: Int,
var name: String? = null,
var type: String? = null,
var dimension: String? = null,
var created: String? = null,
)
| 0
|
Kotlin
|
2
| 5
|
3205db33cc336714cb63d51bd82d1927ad412c6e
| 212
|
RickAndMortyApp
|
MIT License
|
prl-compiler/generated/src/main/kotlin/com/booleworks/prl/model/protobuf/PbDateRangeKt.kt
|
booleworks
| 721,827,334
| false
|
{"Kotlin": 1495826, "JavaScript": 835976, "Vue": 132739, "TypeScript": 50565, "Java": 32652, "ANTLR": 15836, "Lex": 3646, "CSS": 2243, "Shell": 1735, "Dockerfile": 681, "Scheme": 505}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: model_primitives.proto
// Generated files should ignore deprecation warnings
@file:Suppress("DEPRECATION")
package com.booleworks.prl.model.protobuf;
@kotlin.jvm.JvmName("-initializepbDateRange")
public inline fun pbDateRange(block: com.booleworks.prl.model.protobuf.PbDateRangeKt.Dsl.() -> kotlin.Unit): com.booleworks.prl.model.protobuf.ProtoBufPrimitives.PbDateRange =
com.booleworks.prl.model.protobuf.PbDateRangeKt.Dsl._create(com.booleworks.prl.model.protobuf.ProtoBufPrimitives.PbDateRange.newBuilder()).apply { block() }._build()
/**
* Protobuf type `boolerules.primitives.PbDateRange`
*/
public object PbDateRangeKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
public class Dsl private constructor(
private val _builder: com.booleworks.prl.model.protobuf.ProtoBufPrimitives.PbDateRange.Builder
) {
public companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: com.booleworks.prl.model.protobuf.ProtoBufPrimitives.PbDateRange.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): com.booleworks.prl.model.protobuf.ProtoBufPrimitives.PbDateRange = _builder.build()
/**
* `optional int64 start = 1;`
*/
public var start: kotlin.Long
@JvmName("getStart")
get() = _builder.getStart()
@JvmName("setStart")
set(value) {
_builder.setStart(value)
}
/**
* `optional int64 start = 1;`
*/
public fun clearStart() {
_builder.clearStart()
}
/**
* `optional int64 start = 1;`
* @return Whether the start field is set.
*/
public fun hasStart(): kotlin.Boolean {
return _builder.hasStart()
}
/**
* `optional int64 end = 2;`
*/
public var end: kotlin.Long
@JvmName("getEnd")
get() = _builder.getEnd()
@JvmName("setEnd")
set(value) {
_builder.setEnd(value)
}
/**
* `optional int64 end = 2;`
*/
public fun clearEnd() {
_builder.clearEnd()
}
/**
* `optional int64 end = 2;`
* @return Whether the end field is set.
*/
public fun hasEnd(): kotlin.Boolean {
return _builder.hasEnd()
}
/**
* An uninstantiable, behaviorless type to represent the field in
* generics.
*/
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
public class DatesProxy private constructor() : com.google.protobuf.kotlin.DslProxy()
/**
* `repeated int64 dates = 3;`
*/
public val dates: com.google.protobuf.kotlin.DslList<kotlin.Long, DatesProxy>
@kotlin.jvm.JvmSynthetic
get() = com.google.protobuf.kotlin.DslList(
_builder.getDatesList()
)
/**
* `repeated int64 dates = 3;`
* @param value The dates to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addDates")
public fun com.google.protobuf.kotlin.DslList<kotlin.Long, DatesProxy>.add(value: kotlin.Long) {
_builder.addDates(value)
}/**
* `repeated int64 dates = 3;`
* @param value The dates to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignDates")
@Suppress("NOTHING_TO_INLINE")
public inline operator fun com.google.protobuf.kotlin.DslList<kotlin.Long, DatesProxy>.plusAssign(value: kotlin.Long) {
add(value)
}/**
* `repeated int64 dates = 3;`
* @param values The dates to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addAllDates")
public fun com.google.protobuf.kotlin.DslList<kotlin.Long, DatesProxy>.addAll(values: kotlin.collections.Iterable<kotlin.Long>) {
_builder.addAllDates(values)
}/**
* `repeated int64 dates = 3;`
* @param values The dates to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignAllDates")
@Suppress("NOTHING_TO_INLINE")
public inline operator fun com.google.protobuf.kotlin.DslList<kotlin.Long, DatesProxy>.plusAssign(values: kotlin.collections.Iterable<kotlin.Long>) {
addAll(values)
}/**
* `repeated int64 dates = 3;`
* @param index The index to set the value at.
* @param value The dates to set.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("setDates")
public operator fun com.google.protobuf.kotlin.DslList<kotlin.Long, DatesProxy>.set(index: kotlin.Int, value: kotlin.Long) {
_builder.setDates(index, value)
}/**
* `repeated int64 dates = 3;`
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("clearDates")
public fun com.google.protobuf.kotlin.DslList<kotlin.Long, DatesProxy>.clear() {
_builder.clearDates()
}}
}
@kotlin.jvm.JvmSynthetic
public inline fun com.booleworks.prl.model.protobuf.ProtoBufPrimitives.PbDateRange.copy(block: `com.booleworks.prl.model.protobuf`.PbDateRangeKt.Dsl.() -> kotlin.Unit): com.booleworks.prl.model.protobuf.ProtoBufPrimitives.PbDateRange =
`com.booleworks.prl.model.protobuf`.PbDateRangeKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| 0
|
Kotlin
|
0
| 1
|
5a7c0836dc1ccea8a30ccabe3a5f4671348da967
| 5,245
|
boolerules
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/participationhistory/domain/CourseParticipationTest.kt
|
ministryofjustice
| 615,402,552
| false
|
{"Kotlin": 215257, "Shell": 10680, "Dockerfile": 1397}
|
package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.participationhistory.domain
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldThrow
import org.junit.jupiter.api.Test
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.common.domain.BusinessException
import java.util.UUID
class CourseParticipationTest {
private val factory = CourseParticipationEntityFactory()
@Test
fun `assertOnlyCourseIdOrCourseNamePresent should successfully validate with valid courseId`() {
val courseParticipation = factory
.withCourseId(UUID.randomUUID())
.withOtherCourseName(null)
.produce()
shouldNotThrowAny { courseParticipation.assertOnlyCourseIdOrCourseNamePresent() }
}
@Test
fun `assertOnlyCourseIdOrCourseNamePresent should successfully validate with valid otherCourseName`() {
val courseParticipation = factory
.withOtherCourseName("Course Name")
.withCourseId(null)
.produce()
shouldNotThrowAny { courseParticipation.assertOnlyCourseIdOrCourseNamePresent() }
}
@Test
fun `assertOnlyCourseIdOrCourseNamePresent should throw exception when attempting to validate with neither courseId nor otherCourseName`() {
val courseParticipation = factory
.withCourseId(null)
.withOtherCourseName(null)
.produce()
shouldThrow<BusinessException> { courseParticipation.assertOnlyCourseIdOrCourseNamePresent() }
}
@Test
fun `assertOnlyCourseIdOrCourseNamePresent should throw exception when attempting to validate with both courseId and otherCourseName`() {
val courseParticipation = factory
.withCourseId(UUID.randomUUID())
.withOtherCourseName("Course Name")
.produce()
shouldThrow<BusinessException> { courseParticipation.assertOnlyCourseIdOrCourseNamePresent() }
}
}
| 0
|
Kotlin
|
0
| 0
|
f15f6d5030a8bd93970c82afd832c821de3f2c1e
| 1,865
|
hmpps-accredited-programmes-api
|
MIT License
|
TLDMaths/src/main/kotlin/uk/tldcode/math/tldmaths/biginteger/Operaters.kt
|
Thelonedevil
| 78,237,775
| false
| null |
package uk.tldcode.math.tldmaths.biginteger
import java.math.BigInteger
operator fun BigInteger.inc(): BigInteger = this + BigInteger.ONE
operator fun BigInteger.dec(): BigInteger = this - BigInteger.ONE
operator fun BigInteger.rangeTo(other: BigInteger): BigIntegerRange = BigIntegerRange(this, other)
infix fun BigInteger.until(other: BigInteger): BigIntegerRange = this..other - BigInteger.ONE
infix fun BigInteger.downTo(other: BigInteger): BigIntegerProgression = BigIntegerProgression.fromClosedRange(this, other, BigInteger.valueOf(-1))
infix fun BigInteger.downtil(other: BigInteger): BigIntegerProgression = this downTo other + BigInteger.ONE
| 0
|
Kotlin
|
0
| 0
|
c35095888fe85506840b7c1ec04e21673153370c
| 657
|
TLDMaths
|
Apache License 2.0
|
backend/src/main/kotlin/men/brakh/bsuirstudent/domain/iis/faculty/mapping/FacultyBsuirMapping.kt
|
N1ghtF1re
| 184,453,033
| false
| null |
package men.brakh.bsuirstudent.domain.iis.faculty.mapping
import men.brakh.bsuirstudent.application.bsuir.FacultyBsuirDto
import men.brakh.bsuirstudent.application.bsuir.SpecialityBsuirDto
import men.brakh.bsuirstudent.domain.iis.faculty.EducationForm
import men.brakh.bsuirstudent.domain.iis.faculty.Faculty
import men.brakh.bsuirstudent.domain.iis.faculty.Speciality
import org.springframework.stereotype.Component
@Component
class FacultyBsuirMapping {
fun mapSpeciality(specialityBsuirDto: SpecialityBsuirDto, faculty: Faculty): Speciality {
return Speciality(
id = specialityBsuirDto.id,
alias = specialityBsuirDto.abbrev,
name = specialityBsuirDto.name,
educationForm = when(specialityBsuirDto.educationForm.id) {
1 -> EducationForm.FULLTIME
2 -> EducationForm.EXTRAMURAL
3 -> EducationForm.DISTANCE
else -> EducationForm.UNKNOWN
},
faculty = faculty,
iisId = specialityBsuirDto.id
)
}
fun mapToFaculties(facultiesBsuirDto: List<FacultyBsuirDto>, specialitiesDto: List<SpecialityBsuirDto>): List<Faculty> {
val facultiesMap = facultiesBsuirDto.groupBy { it.id }
return specialitiesDto.groupBy { facultiesMap[it.facultyId]?.first() }
.mapNotNull { (faculty, specialities) ->
faculty?.let {
val facultyEntity = Faculty(
id = faculty.id,
alias = faculty.abbrev,
name = faculty.name
)
facultyEntity.specialities = specialities.map { mapSpeciality(it, facultyEntity) }
facultyEntity
}}
}
}
| 0
|
Kotlin
|
0
| 9
|
a4cd806c4658eb2aa736aa40daf47b19d39df80f
| 1,786
|
Bsuir-Additional-Api
|
Apache License 2.0
|
app/src/main/java/org/unifiedpush/distributor/noprovider2push/services/Listener.kt
|
NoProvider2Push
| 321,762,293
| false
| null |
package org.unifiedpush.distributor.noprovider2push.services
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.util.Log
import org.unifiedpush.distributor.noprovider2push.R
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.gson.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import java.net.BindException
const val listeningPort = 51515
class Listener: Service(){
private var isServiceStarted = false
private var wakeLock: PowerManager.WakeLock? = null
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onCreate(){
super.onCreate()
Log.i("Listener","Starting")
val notification = createNotification()
startForeground(51515, notification)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startService()
// by returning this we make sure the service is restarted if the system kills the service
return START_STICKY
}
private fun httpServer(port: Int){
try {
val context = this
Log.i("Listener", "Started")
embeddedServer(Netty, port) {
install(ContentNegotiation) {
gson {}
}
routing {
get("/") {
call.respond("{\"unifiedpush\":{\"version\":1}}")
}
post("/{token}/{...}") {
call.respond(HttpStatusCode.Accepted,"{\"Status\":\"Accepted\"}")
val token = call.parameters["token"]!!
Log.i("Listener", "Received request to $token")
val parameters = call.receiveText()
application?.let {
sendMessage(context, token, parameters)
}
}
post("/{token}/{...}/") { // To fix KTOR tailcard issue
call.respond(HttpStatusCode.Accepted,"{\"Status\":\"Accepted\"}")
val token = call.parameters["token"]!!
Log.i("Listener", "Received request to $token")
val parameters = call.receiveText()
application?.let {
sendMessage(context, token, parameters)
}
}
}
}.start(wait = false)
}catch (e: BindException){
Log.i("Listener","Trying to bind again")
}
}
private fun createNotification(): Notification {
val notificationChannelId = "NoProvider2Push.Listener"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager;
val channel = NotificationChannel(
notificationChannelId,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_LOW
).let {
it.description = "NoProvider2Push Listener"
it
}
notificationManager.createNotificationChannel(channel)
}
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(
this,
notificationChannelId
) else Notification.Builder(this)
return builder
.setContentTitle("NoProvider2Push")
.setContentText("Listening")
.setSmallIcon(R.drawable.ic_launcher_notification)
.setTicker("Listening")
.setPriority(Notification.PRIORITY_LOW) // for under android 26 compatibility
.build()
}
private fun startService() {
if (isServiceStarted) return
isServiceStarted = true
// we need this lock so our service gets not affected by Doze Mode
wakeLock =
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "EndlessService::lock").apply {
acquire()
}
}
httpServer(listeningPort)
}
}
| 12
|
Kotlin
|
0
| 8
|
83b026c14037e5beb2e63fc755fb25e324d46bdc
| 4,670
|
android
|
Apache License 2.0
|
startup-ksp-compiler/src/main/java/com/kronos/startup/ksp/compiler/utils/CollectionsExtensions.kt
|
Leifzhang
| 431,806,948
| false
| null |
package com.kronos.startup.ksp.compiler.utils
/**
*
* @Author LiABao
* @Since 2022/1/11
*
*/
internal fun <K, V> MutableMap<K, V>.getValueByDefault(key: K, function: () -> V): V {
if (!containsKey(key)) {
this[key] = function.invoke()
}
return requireNotNull(this[key])
}
| 0
|
Kotlin
|
8
| 47
|
883e2be9c1c6b19714fa74c803bd517fad081944
| 299
|
AndroidStartup
|
Apache License 2.0
|
startup-ksp-compiler/src/main/java/com/kronos/startup/ksp/compiler/utils/CollectionsExtensions.kt
|
Leifzhang
| 431,806,948
| false
| null |
package com.kronos.startup.ksp.compiler.utils
/**
*
* @Author LiABao
* @Since 2022/1/11
*
*/
internal fun <K, V> MutableMap<K, V>.getValueByDefault(key: K, function: () -> V): V {
if (!containsKey(key)) {
this[key] = function.invoke()
}
return requireNotNull(this[key])
}
| 0
|
Kotlin
|
8
| 47
|
883e2be9c1c6b19714fa74c803bd517fad081944
| 299
|
AndroidStartup
|
Apache License 2.0
|
src/main/kotlin/no/nav/syfo/httpclient/HttpClientFactory.kt
|
navikt
| 327,823,627
| false
| null |
package no.nav.syfo.httpclient
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import io.ktor.client.HttpClient
import io.ktor.client.HttpClientConfig
import io.ktor.client.engine.apache.Apache
import io.ktor.client.engine.apache.ApacheEngineConfig
import io.ktor.client.features.HttpResponseValidator
import io.ktor.client.features.json.JacksonSerializer
import io.ktor.client.features.json.JsonFeature
import io.ktor.network.sockets.SocketTimeoutException
import javax.naming.ServiceUnavailableException
class HttpClientFactory private constructor() {
companion object {
fun getHttpClient(): HttpClient {
val config: HttpClientConfig<ApacheEngineConfig>.() -> Unit = {
install(JsonFeature) {
serializer = JacksonSerializer {
registerKotlinModule()
registerModule(JavaTimeModule())
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}
}
HttpResponseValidator {
handleResponseException { exception ->
when (exception) {
is SocketTimeoutException -> throw ServiceUnavailableException(exception.message)
}
}
}
}
return HttpClient(Apache, config)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4209045b0831a165ceb8c694afd31de47e274325
| 1,706
|
syfonlaltinn
|
MIT License
|
src/main/kotlin/eti/lucasgomes/mercadolivro/events/listener/GenerateNfeListener.kt
|
lucasgomes-eti
| 652,861,178
| false
| null |
package eti.lucasgomes.mercadolivro.events.listener
import eti.lucasgomes.mercadolivro.events.PurchaseEvent
import eti.lucasgomes.mercadolivro.service.PurchaseService
import org.springframework.context.event.EventListener
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import java.util.UUID
@Component
class GenerateNfeListener(
private val purchaseService: PurchaseService
) {
@Async
@EventListener
fun listen(purchaseEvent: PurchaseEvent) {
val nfe = UUID.randomUUID().toString()
val purchaseModel = purchaseEvent.purchaseModel.copy(nfe = nfe)
purchaseService.update(purchaseModel)
}
}
| 0
|
Kotlin
|
0
| 0
|
53626c70941834245beed06b8edb557bd61740a4
| 694
|
mercado-livro
|
Apache License 2.0
|
app/src/main/java/com/andre_max/tiktokclone/presentation/ui/profile/MeFragment.kt
|
Andre-max
| 291,054,765
| false
| null |
/*
* MIT License
*
* Copyright (c) 2021 Andre-max
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.andre_max.tiktokclone.presentation.ui.profile
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.andre_max.tiktokclone.R
import com.andre_max.tiktokclone.databinding.FragmentMeBinding
import com.andre_max.tiktokclone.presentation.ui.profile.with_account.ProfileWithAccountFragment
import com.andre_max.tiktokclone.presentation.ui.profile.without_account.ProfileWithoutAccountFragment
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class MeFragment : Fragment(R.layout.fragment_me) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
requireActivity().supportFragmentManager.beginTransaction()
.add(
R.id.frag_container,
if (Firebase.auth.currentUser == null)
ProfileWithoutAccountFragment()
else
// Since we are retrieving the uid in ProfileWithAccountFragment using by navArgs(), lets include this bundle
ProfileWithAccountFragment().apply {
arguments = Bundle().also {
it.putString("uid", Firebase.auth.uid)
}
}
)
.commit()
}
}
| 7
|
Kotlin
|
27
| 56
|
0dcbc62d6b7d388744c213881a8125157eaf51e2
| 2,491
|
TikTok-Clone
|
MIT License
|
app/src/main/java/org/p2p/wallet/solend/ui/withdraw/SolendWithdrawContract.kt
|
p2p-org
| 306,035,988
| false
| null |
package org.p2p.wallet.solend.ui.withdraw
import androidx.annotation.StringRes
import org.p2p.wallet.common.mvp.MvpPresenter
import org.p2p.wallet.common.mvp.MvpView
import org.p2p.wallet.solend.model.SolendDepositToken
import org.p2p.wallet.solend.model.SolendTransactionDetailsState
import java.math.BigDecimal
interface SolendWithdrawContract {
interface View : MvpView {
fun showFullScreenLoading(isLoading: Boolean)
fun showFeeLoading(isLoading: Boolean)
fun showTokenToWithdraw(depositToken: SolendDepositToken.Active, withChevron: Boolean)
fun showTokensToWithdraw(depositTokens: List<SolendDepositToken>)
fun setEmptyAmountState()
fun setBiggerThenMaxAmountState(tokenAmount: String)
fun setValidDepositState(
output: BigDecimal,
tokenAmount:
String,
state:
SolendTransactionDetailsState.Withdraw
)
fun showIndefiniteInfoMessage(@StringRes messageRes: Int, @StringRes actionButtonRes: Int)
fun navigateToEarnScreen()
}
interface Presenter : MvpPresenter<View> {
fun initialize(userDeposits: List<SolendDepositToken>)
fun selectTokenToWithdraw(tokenToWithdraw: SolendDepositToken.Active)
fun onTokenWithdrawClicked()
fun updateInputs(input: BigDecimal, output: BigDecimal)
fun withdraw()
}
}
| 8
|
Kotlin
|
16
| 28
|
71b282491cdafd26be1ffc412a971daaa9c06c61
| 1,410
|
key-app-android
|
MIT License
|
composeApp/src/commonMain/kotlin/com/jetbrains/kmpapp/viewmodel/BaseViewModel.kt
|
nitinnexgeniots
| 785,100,643
| false
|
{"Kotlin": 75780, "Swift": 661}
|
package com.jetbrains.kmpapp.viewmodel
import dev.icerock.moko.mvvm.viewmodel.ViewModel
import dev.icerock.moko.parcelize.Parcelable
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.launch
private const val SAVED_UI_STATE_KEY = "savedUiStateKey"
| 0
|
Kotlin
|
0
| 0
|
cd09dd9b4fdcd51ae6ef35f7d579b8d76f64f32e
| 516
|
KMP-App-Sample
|
Apache License 2.0
|
feature/media/common/view/api/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/media/common/view/api/ui/DeleteFullySyncedPermissionDialog.kt
|
savvasdalkitsis
| 485,908,521
| false
|
{"Kotlin": 2402997, "Ruby": 1294, "PowerShell": 325, "Shell": 158}
|
/*
Copyright 2022 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.savvasdalkitsis.uhuruphotos.feature.media.common.view.api.ui
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.savvasdalkitsis.uhuruphotos.foundation.strings.api.R.string
import com.savvasdalkitsis.uhuruphotos.foundation.ui.api.ui.MultiButtonDialog
@Composable
fun DeleteFullySyncedPermissionDialog(
onDismiss: () -> Unit,
onDeleteLocalTrashRemote: () -> Unit,
onDeleteLocal: () -> Unit,
) {
MultiButtonDialog(
title = stringResource(string.media_sync_status_fully_synced),
onDismiss = onDismiss,
confirmButton = {
Button(onClick = onDeleteLocalTrashRemote) {
Text(stringResource(string.delete_fully_synced_media_both))
}
},
extraButtons = listOf {
Button(
modifier = Modifier.weight(1f),
onClick = onDeleteLocal,
) {
Text(stringResource(string.delete_fully_synced_media_local))
}
},
negativeButtonText = stringResource(string.cancel),
body = {
Text(
stringResource(string.what_would_like_to_do)
)
Text(stringResource(string.operation_irreverisble))
},
)
}
| 45
|
Kotlin
|
24
| 296
|
09ba2d9d05dc177fbea09da907d51610e8640805
| 1,956
|
uhuruphotos-android
|
Apache License 2.0
|
common/src/main/java/com/example/common/ui/component/HiAbsListFragment.kt
|
xhh4215
| 435,793,681
| false
|
{"Kotlin": 327550, "Java": 107540}
|
package com.example.common.ui.component
import android.os.Bundle
import android.view.View
import androidx.annotation.CallSuper
import androidx.core.widget.ContentLoadingProgressBar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.common.R
import com.example.common.databinding.FragmentListBinding
import com.example.hi.empty.EmptyView
import com.example.hi.input.HiRecyclerView
import com.example.hi.item.HiAdapter
import com.example.hi.item.HiDataItem
import com.example.hi.refresh.HiOverView
import com.example.hi.refresh.HiRefreshLayout
import com.example.hi.refresh.HiTextOverView
import com.example.hi.refresh.IHiRefresh
open class HiAbsListFragment : HiBaseFragment<FragmentListBinding>(), IHiRefresh.HiRefreshListener {
var pageIndex = 1
private lateinit var hiAdapter: HiAdapter
private lateinit var refreshHeaderView: HiTextOverView
private lateinit var layoutManager: RecyclerView.LayoutManager
private var refreshLayout: HiRefreshLayout? = null
private var recyclerView: HiRecyclerView? = null
private var emptyView: EmptyView? = null
private var loadingView: ContentLoadingProgressBar? = null
companion object {
const val PREFETCH_SIZE = 5
}
override fun getLayoutId(): Int {
return R.layout.fragment_list
}
@CallSuper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
this.refreshLayout = layoutView.findViewById(R.id.refresh_layout)
this.recyclerView = layoutView.findViewById(R.id.recycler_view)
this.emptyView = layoutView.findViewById(R.id.empty_view)
this.loadingView = layoutView.findViewById(R.id.content_loading)
refreshHeaderView = HiTextOverView(context!!)
refreshLayout?.setRefreshOverView(refreshHeaderView)
refreshLayout?.setRefreshListener(this)
layoutManager = createLayoutManager()
hiAdapter = HiAdapter(context!!)
recyclerView?.layoutManager = layoutManager
recyclerView?.adapter = hiAdapter
emptyView?.visibility = View.GONE
emptyView?.setIcon(R.string.list_empty)
emptyView?.setDesc(getString(R.string.list_empty_desc))
emptyView?.setButton(getString(R.string.list_empty_action)) {
onRefresh()
}
loadingView?.visibility = View.VISIBLE
pageIndex = 1
}
fun finishRefresh(dataItems: List<HiDataItem<*, out RecyclerView.ViewHolder>>?) {
val success = dataItems != null && dataItems.isNotEmpty()
val refresh = pageIndex == 1
if (refresh) {
loadingView?.visibility = View.GONE
refreshLayout?.refreshFinished()
if (success) {
emptyView?.visibility = View.GONE
hiAdapter.clearItems()
hiAdapter.addItems(items = dataItems!!, true)
} else {
if (hiAdapter.itemCount <= 0) {
emptyView?.visibility = View.VISIBLE
}
}
} else {
if (success) {
hiAdapter.addItems(dataItems!!, true)
}
recyclerView?.loadFinished(success)
}
}
open fun createLayoutManager(): RecyclerView.LayoutManager {
return LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
}
fun enableLoadMore(callback: () -> Unit) {
recyclerView?.enableLoadMore({
if (refreshHeaderView.state == HiOverView.HiRefreshState.STATE_REFRESH) {
recyclerView?.loadFinished(false)
return@enableLoadMore
}
pageIndex++
callback()
}, PREFETCH_SIZE)
}
fun disableLoadMore() {
recyclerView?.disableLoadMore()
}
@CallSuper
override fun onRefresh() {
if (recyclerView?.isLoading() == true) {
refreshLayout?.post {
refreshLayout?.refreshFinished()
}
return
}
pageIndex = 1
}
override fun enableRefresh(): Boolean {
return true
}
}
| 0
|
Kotlin
|
0
| 1
|
e2359ee06795c6b37b24ffc2a3dbe9f4159ba435
| 4,194
|
ShopApp
|
Apache License 2.0
|
testcaller/src/test/kotlin/pers/shawxingkwok/test/util/testPhone.kt
|
ShawxingKwok
| 702,423,277
| false
|
{"Kotlin": 94903, "HTML": 273}
|
package pers.shawxingkwok.test.util
import io.ktor.client.*
import io.ktor.client.engine.*
import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import pers.shawxingkwok.test.client.Phone
import kotlin.reflect.full.declaredFunctions
import kotlin.reflect.full.isSupertypeOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.full.valueParameters
fun testPhone(
api: Any,
configureServer: Application.() -> Unit = {},
configureClient: HttpClientConfig<out HttpClientEngineConfig>.() -> Unit = {},
enablesWss: Boolean = false,
act: suspend ApplicationTestBuilder.(Phone) -> Unit
) =
testApplication {
val client = createClient(configureClient)
val phone = Phone(client, enablesWss = enablesWss)
application {
configureServer()
pers.shawxingkwok.test.server.Phone::class.declaredFunctions
.filter { it.name == "route" }
.first {
val paramType = it.valueParameters[1].type
val argType = api::class.starProjectedType
paramType == argType || paramType.isSupertypeOf(argType)
}
.call(pers.shawxingkwok.test.server.Phone, routing { }, api)
}
act(phone)
}
| 0
|
Kotlin
|
0
| 0
|
ea3924ed9ca8b24148e8ea2ff505f687f7c875a1
| 1,302
|
Phone
|
Apache License 2.0
|
subprojects/android-test/ui-testing-core-app/src/main/kotlin/com/avito/android/ui/BitmapActivity.kt
|
avito-tech
| 230,265,582
| false
|
{"Kotlin": 3573291, "Java": 67252, "Shell": 27675, "Dockerfile": 12799, "Makefile": 7970}
|
package com.avito.android.ui
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class BitmapActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bitmap)
}
}
| 10
|
Kotlin
|
48
| 393
|
accdcfc1f34054978018e583702ac3b4c808b6ee
| 307
|
avito-android
|
MIT License
|
src/main/kotlin/com/bydgoszcz/worldsimulation/worlds/World.kt
|
mniami
| 118,100,266
| false
| null |
package com.bydgoszcz.worldsimulation.worlds
import com.bydgoszcz.worldsimulation.helpers.RandomHelper
import com.bydgoszcz.worldsimulation.history.HistoryLog
import com.bydgoszcz.worldsimulation.items.*
import com.bydgoszcz.worldsimulation.science.DnaHelper
import com.bydgoszcz.worldsimulation.science.Science
import java.util.*
class World(val peoples: MutableList<Person> = LinkedList(),
val items: MutableList<MarketItem> = LinkedList(),
val markets: MutableList<Market> = LinkedList(),
var time : WorldTime = WorldTime(0),
var globalRandoms : GlobalParameters = GlobalParameters(),
var historyLog : HistoryLog = HistoryLog(),
var random : RandomHelper = RandomHelper(),
val science : Science = Science(DnaHelper()))
| 0
|
Kotlin
|
0
| 0
|
4d3e7d7edcb81e36a8eb9b57c86a8a9251a38ca8
| 810
|
wypieki
|
MIT License
|
demo/src/release/java/com/nextfaze/devfun/demo/inject/BuildType.kt
|
suclike
| 98,347,273
| true
|
{"Kotlin": 378699, "Prolog": 1350, "CSS": 355}
|
package com.nextfaze.devfun.demo.inject
import dagger.Module
@Module
class BuildTypeModule
| 0
|
Kotlin
|
0
| 0
|
af96685910e76a00161b26e1962130dace7e80a9
| 93
|
dev-fun
|
Apache License 2.0
|
kotlin/bankaccount/src/main/kotlin/com/tk/bankaccount/AccountRepository.kt
|
Thiago-Kuhl
| 378,936,465
| false
|
{"JavaScript": 56509, "Kotlin": 56230, "HTML": 342}
|
package com.tk.bankaccount
import org.springframework.data.mongodb.repository.MongoRepository
import java.util.Optional
interface AccountRepository : MongoRepository<Account, String> {
fun findByDocument(document: String): Optional<Account>
}
| 0
|
JavaScript
|
0
| 0
|
0c6d9f0a99c97f58f12e7609e44a4bd351751798
| 248
|
my-lab
|
MIT License
|
browser-kotlin/src/jsMain/kotlin/web/svg/SVGFEDropShadowElement.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6272741}
|
// Automatically generated - do not modify!
package web.svg
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEDropShadowElement)
*/
open external class SVGFEDropShadowElement
private constructor() :
SVGElement,
SVGFilterPrimitiveStandardAttributes {
val dx: SVGAnimatedNumber
val dy: SVGAnimatedNumber
val in1: SVGAnimatedString
val stdDeviationX: SVGAnimatedNumber
val stdDeviationY: SVGAnimatedNumber
fun setStdDeviation(
stdDeviationX: Float,
stdDeviationY: Float,
)
}
| 0
|
Kotlin
|
8
| 36
|
95b065622a9445caf058ad2581f4c91f9e2b0d91
| 548
|
types-kotlin
|
Apache License 2.0
|
kompack-kotlin-serialization/src/commonTest/kotlin/com/wunderbee/kompack/mpack/coders/DecodingSpeed.kt
|
dedee
| 621,699,131
| false
| null |
package com.wunderbee.kompack.mpack.coders
import com.wunderbee.kompack.mpack.pack.InMemoryPacker
import kotlin.test.Test
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class DecodingSpeed {
@OptIn(ExperimentalTime::class)
@Test
fun measureDecodingSpeed() {
val book = BookUtil.createBook()
val flat2 = MessagePackEncoder.encodeToByteArray(book, InMemoryPacker(1_000_000))
var t2 = 0L
// FIXME So slow with native
repeat(10) {
t2 += measureTime {
MessagePackDecoder.decodeFromByteArray<Book>(flat2)
}.inWholeMilliseconds
}
println("Decoding speed 1000x book decoding")
println("----------------------------------")
println("com.wunderbee.kompack.mpack.coders.MessagePackEncoder: ${t2} ms")
// JVM
// Decoding speed 1000x book decoding
// ----------------------------------
// com.wunderbee.kompack.mpack.coders.MessagePackEncoder: 85 ms
// NATIVE
// Decoding speed 1000x book decoding
// ----------------------------------
// com.wunderbee.kompack.mpack.coders.MessagePackEncoder: 34595 ms XXXXXX !!!!
}
}
| 7
|
Kotlin
|
0
| 0
|
62ddc06864526bfcacdb2575b7eb91d576a684af
| 1,258
|
kompack
|
Apache License 2.0
|
Sushi/app/src/main/java/com/destructo/sushi/model/jikan/anime/support/Episode.kt
|
destructo570
| 302,356,237
| false
| null |
package com.destructo.sushi.model.jikan.anime.support
import com.squareup.moshi.Json
data class Episode(
@Json(name = "aired")
val aired: String?=null,
@Json(name = "episode_id")
val episodeId: Int?=null,
@Json(name = "filler")
val filler: Boolean?=null,
@Json(name = "forum_url")
val forumUrl: String?=null,
@Json(name = "recap")
val recap: Boolean?=null,
@Json(name = "title")
val title: String?=null,
@Json(name = "title_japanese")
val titleJapanese: String?=null,
@Json(name = "title_romanji")
val titleRomanji: String?=null,
@Json(name = "video_url")
val videoUrl: String?=null
)
| 3
|
Kotlin
|
5
| 21
|
68317c04caa596103d3fd32b0f34fe43b189a721
| 659
|
Sushi-Unofficial-MAL-Client
|
Apache License 2.0
|
GaiaXAndroid/src/main/kotlin/com/alibaba/gaiax/render/view/GXViewTreeUpdater.kt
|
MXPDS6688
| 471,274,978
| true
|
{"Kotlin": 608909, "Objective-C": 581902, "C++": 171660, "CSS": 123633, "Java": 106171, "Objective-C++": 59923, "C": 10418, "Ruby": 2635, "Swift": 2336, "Shell": 2268, "CMake": 2213}
|
/*
* Copyright (c) 2021, Alibaba Group Holding Limited;
*
* 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.alibaba.gaiax.render.view
import android.view.View
import app.visly.stretch.Layout
import com.alibaba.gaiax.context.GXTemplateContext
import com.alibaba.gaiax.render.node.GXNode
/**
* @suppress
*/
open class GXViewTreeUpdater(context: GXTemplateContext, rootNode: GXNode) : GXViewTreeMerger<View>(context, rootNode) {
override fun withRootView(context: GXTemplateContext, node: GXNode, layout: Layout): View? {
return node.viewRef?.get()?.also {
GXViewLayoutParamsUtils.updateLayoutParams(it, layout, 0F, 0F)
}
}
override fun withChildView(context: GXTemplateContext, childType: String, childViewType: String?, parentMergeView: View, childNode: GXNode, childLayout: Layout, mergeX: Float, mergeY: Float): View? {
return childNode.viewRef?.get()?.also { targetView ->
if (childNode.isNeedShadow()) {
childNode.boxLayoutViewRef?.get()?.let { shadowView ->
GXViewLayoutParamsUtils.updateLayoutParams(shadowView, childLayout, mergeX, mergeY)
}
}
GXViewLayoutParamsUtils.updateLayoutParams(targetView, childLayout, mergeX, mergeY)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3a0107a6be36ff3650dc5fbb482f8819f86bf0e2
| 1,815
|
GaiaX
|
Apache License 2.0
|
app/src/main/java/com/ralphdugue/shiftydroid/models/Shift.kt
|
rdugue
| 91,661,459
| false
| null |
package com.ralphdugue.shiftydroid.models
/**
* Created by Ralph on 5/26/2017.
*/
| 0
|
Kotlin
|
0
| 0
|
302659b908eb93dd63e911f0b20c1f999c544ed2
| 85
|
ShiftyDroid
|
Apache License 2.0
|
src/test/kotlin/com/depromeet/makers/domain/usecase/RefreshSessionCodeTest.kt
|
depromeet
| 792,152,807
| false
|
{"Kotlin": 227716}
|
package com.depromeet.makers.domain.usecase
import com.depromeet.makers.domain.gateway.SessionGateway
import com.depromeet.makers.domain.model.Place
import com.depromeet.makers.domain.model.Session
import com.depromeet.makers.domain.model.SessionType
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.kotest.matchers.string.shouldBeInteger
import io.mockk.every
import io.mockk.mockk
import java.time.LocalDateTime
class RefreshSessionCodeTest :
BehaviorSpec({
Given("세션 코드를 갱신할 때") {
val sessionGateway = mockk<SessionGateway>()
val refreshSessionCode = RefreshSessionCode(sessionGateway = sessionGateway)
val previousCode = "previousCode"
val mockSession =
Session(
sessionId = "123e4567-e89b-12d3-a456-426614174000",
generation = 15,
week = 1,
title = "세션 제목",
description = "세션 설명",
startTime = LocalDateTime.of(2030, 10, 1, 10, 0),
sessionType = SessionType.OFFLINE,
place =
Place.newPlace(
name = "<NAME>",
address = "전북 익산시 부송동 100",
longitude = 35.9418,
latitude = 126.9544,
),
code = previousCode,
)
every { sessionGateway.getById(any()) } returns mockSession
every { sessionGateway.save(any()) } returns mockSession.update(code = Session.generateCode())
When("execute가 실행되면") {
val result =
refreshSessionCode.execute(
sessionId = mockSession.sessionId,
)
Then("세션 코드가 갱신된 세션이 반환된다") {
result.code shouldNotBe previousCode
result.code shouldNotBe null
result.code.shouldBeInteger()
result.code!!.length shouldBe 4
}
}
}
})
| 2
|
Kotlin
|
1
| 12
|
b6b4a12497b4f2091538ac9db130290d2a85c1c6
| 2,202
|
depromeet-makers-be
|
MIT License
|
app/src/main/kotlin/com/mlshv/dayree/util/AudioRecorder.kt
|
mlshv
| 73,482,745
| false
| null |
package com.mlshv.dayree.util
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.util.Log
import java.io.IOException
class AudioRecorder {
private val LOG_TAG = "AudioRecorder"
private var mRecorder: MediaRecorder? = null
private var mPlayer: MediaPlayer? = null
private val samplingRate = 44100
private val bitRate = 48000
private val outputFormat = MediaRecorder.OutputFormat.MPEG_4
private val encoder = MediaRecorder.AudioEncoder.AAC
fun startRecordingToFile(outputFileName: String) {
mRecorder = MediaRecorder()
with(mRecorder!!) {
setAudioSource(MediaRecorder.AudioSource.MIC)
setAudioSamplingRate(samplingRate)
setAudioEncodingBitRate(bitRate)
setOutputFormat(outputFormat)
setAudioEncoder(encoder)
setOutputFile(outputFileName)
try {
prepare()
} catch (e: IOException) {
Log.e(LOG_TAG, "prepare() failed")
}
start()
}
}
fun stopRecording() {
mRecorder?.stop()
mRecorder?.release()
mRecorder = null
}
fun release() {
if (mRecorder != null) {
mRecorder?.release()
mRecorder = null
}
if (mPlayer != null) {
mPlayer?.release()
mPlayer = null
}
}
}
| 0
|
Kotlin
|
0
| 0
|
476cb760c52acefba04891a845a60036c4b4cca7
| 1,420
|
DayRee
|
Apache License 2.0
|
app/src/main/java/xyz/junerver/composehooks/net/bean/License.kt
|
junerver
| 767,292,867
| false
|
{"Kotlin": 221216}
|
package xyz.junerver.composehooks.net.bean
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class License(
val key: String,
val name: String,
val node_id: String,
val spdx_id: String,
val url: String,
) : Parcelable
| 0
|
Kotlin
|
0
| 8
|
62ceed502dc25bea6f77ad27e926ac023c7425e3
| 269
|
ComposeHooks
|
Apache License 2.0
|
app/src/main/java/apps/jizzu/simpletodo/utils/Interpolator.kt
|
VineshChauhan24
| 173,085,905
| true
|
{"Kotlin": 97951, "Java": 1131}
|
package apps.jizzu.simpletodo.utils
class Interpolator(private val mAmplitude: Double, private val mFrequency: Double) : android.view.animation.Interpolator {
override fun getInterpolation(time: Float): Float {
return (-1.0 * Math.pow(Math.E, -time / mAmplitude) *
Math.cos(mFrequency * time) + 1).toFloat()
}
}
| 0
|
Kotlin
|
0
| 0
|
7d9d67baac30f207c5f12d7b8c6434727d964118
| 346
|
SimpleToDo
|
MIT License
|
smithy-swift-codegen/src/main/kotlin/software/amazon/smithy/swift/codegen/integration/serde/readwrite/NodeInfoUtils.kt
|
smithy-lang
| 242,852,561
| false
|
{"Kotlin": 1074098, "Swift": 1014625, "Smithy": 121646, "Shell": 1807, "Objective-C": 136}
|
package software.amazon.smithy.swift.codegen.integration.serde.readwrite
import software.amazon.smithy.aws.traits.protocols.Ec2QueryNameTrait
import software.amazon.smithy.model.shapes.MemberShape
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.model.traits.JsonNameTrait
import software.amazon.smithy.model.traits.XmlAttributeTrait
import software.amazon.smithy.model.traits.XmlNameTrait
import software.amazon.smithy.model.traits.XmlNamespaceTrait
import software.amazon.smithy.swift.codegen.SwiftWriter
import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator
import software.amazon.smithy.swift.codegen.model.getTrait
import software.amazon.smithy.swift.codegen.model.hasTrait
class NodeInfoUtils(
val ctx: ProtocolGenerator.GenerationContext,
val writer: SwiftWriter,
val wireProtocol: WireProtocol,
) {
val awsProtocol = ctx.service.awsProtocol
fun nodeInfo(shape: Shape, forRootNode: Boolean = false): String {
if (wireProtocol != WireProtocol.XML && forRootNode) return "\"\""
val xmlName = shape.getTrait<XmlNameTrait>()?.value
val symbol = ctx.symbolProvider.toSymbol(shape)
val resolvedName = xmlName ?: symbol.name
val xmlNamespaceTrait = shape.getTrait<XmlNamespaceTrait>() ?: ctx.service.getTrait<XmlNamespaceTrait>()
val xmlNamespaceParam = namespaceParam(xmlNamespaceTrait)
return nodeInfo(resolvedName, "", xmlNamespaceParam)
}
fun nodeInfo(member: MemberShape, forRootNode: Boolean = false): String {
if (wireProtocol != WireProtocol.XML && forRootNode) return "\"\""
val targetShape = ctx.model.expectShape(member.target)
val resolvedName = resolvedName(member, forRootNode)
val xmlAttributeParam = ", location: .attribute".takeIf { member.hasTrait<XmlAttributeTrait>() } ?: ""
val xmlNamespaceTrait = member.getTrait<XmlNamespaceTrait>() ?: targetShape.getTrait<XmlNamespaceTrait>() ?: ctx.service.getTrait<XmlNamespaceTrait>().takeIf { forRootNode }
val xmlNamespaceParam = namespaceParam(xmlNamespaceTrait)
return nodeInfo(resolvedName, xmlAttributeParam, xmlNamespaceParam)
}
private fun resolvedName(member: MemberShape, forRootNode: Boolean): String {
val targetShape = ctx.model.expectShape(member.target)
when (wireProtocol) {
WireProtocol.XML -> {
if (forRootNode) {
val xmlName = member.getTrait<XmlNameTrait>()?.value ?: targetShape.getTrait<XmlNameTrait>()?.value
return xmlName ?: ctx.symbolProvider.toSymbol(targetShape).name
} else {
return member.getTrait<XmlNameTrait>()?.value ?: member.memberName
}
}
WireProtocol.FORM_URL -> {
if (forRootNode) {
return "\"\""
} else {
if (ctx.service.awsProtocol == AWSProtocol.EC2_QUERY) {
return member.getTrait<Ec2QueryNameTrait>()?.value ?: member.getTrait<XmlNameTrait>()?.value?.capitalize() ?: member.memberName.capitalize()
} else {
return member.getTrait<XmlNameTrait>()?.value ?: member.memberName
}
}
}
WireProtocol.JSON -> {
if (forRootNode) {
return "\"\""
} else if (awsProtocol == AWSProtocol.REST_JSON_1) {
return member.getTrait<JsonNameTrait>()?.value ?: member.memberName
} else {
return member.memberName
}
}
}
}
private fun namespaceParam(xmlNamespaceTrait: XmlNamespaceTrait?): String {
if (wireProtocol != WireProtocol.XML) { return "" }
return xmlNamespaceTrait?.let {
writer.format(
", namespaceDef: .init(prefix: \$S, uri: \$S)",
it.prefix,
it.uri
)
} ?: ""
}
private fun nodeInfo(resolvedName: String, xmlAttributeParam: String, xmlNamespaceParam: String): String {
if (xmlAttributeParam == "" && xmlNamespaceParam == "" || wireProtocol != WireProtocol.XML) {
return writer.format("\$S", resolvedName)
} else {
return writer.format(
".init(\$S\$L\$L)",
resolvedName,
xmlAttributeParam,
xmlNamespaceParam
)
}
}
}
| 9
|
Kotlin
|
27
| 28
|
9e614f2c3e372ddb674fe525356a3d3b6333069d
| 4,565
|
smithy-swift
|
Apache License 2.0
|
library/src/test/java/com/stylingandroid/prefekt/internal/PrefektLiveDataTest.kt
|
StylingAndroid
| 120,488,765
| false
| null |
package com.stylingandroid.prefekt.internal
import android.arch.lifecycle.Observer
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.stylingandroid.prefekt.BaseUnitTest
import com.stylingandroid.prefekt.InstantTaskExecutorExtension
import kotlinx.coroutines.experimental.runBlocking
import org.amshove.kluent.When
import org.amshove.kluent.any
import org.amshove.kluent.calling
import org.amshove.kluent.itReturns
import org.amshove.kluent.mock
import org.amshove.kluent.shouldBe
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
private const val DEFAULT_VALUE = "DEFAULT_VALUE"
private const val NEW_VALUE = "NEW_VALUE"
@ExtendWith(InstantTaskExecutorExtension::class)
internal class PrefektLiveDataTest : BaseUnitTest() {
private val provider: Provider<String> = mock()
private val observer: Observer<String> = mock()
private val liveData: PrefektLiveData<String> = PrefektLiveData(owner, provider)
@Nested
@DisplayName("Given an uninitialised provider")
inner class UninitialisedProvider {
@BeforeEach
fun setup() {
When calling provider.isInitialised itReturns false
}
@Test
@DisplayName("When we call isInitialised Then it returns false")
fun isInitialisedReturnsFalse() {
liveData.isInitialised shouldBe false
}
@Test
@DisplayName("When we call getValue Then it requests the value from the provider")
fun getValueCallsProvider() {
runBlocking {
liveData.getValueBlocking()
verify(provider, times(1)).getValue()
}
}
@Test
@DisplayName("When onCreate is called Then we call onCreate on the provider")
fun onCreateCallsOnCreateOnProvider() {
liveData.onCreate()
verify(provider, times(1)).onCreate()
}
@Test
@DisplayName("When onActive is called Then we subscribe to the provider")
fun onActivateSubscribesToProvider() {
liveData.onCreate()
liveData::class.java.getDeclaredMethod("onActive")?.apply {
invoke(liveData)
}
verify(provider, times(1)).subscribe(any())
}
@Test
@DisplayName("When onInactive is called Then we un-subscribe from the provider")
fun onInactiveUnSubscribesFromProvider() {
liveData.onCreate()
liveData::class.java.getDeclaredMethod("onActive")?.apply {
invoke(liveData)
}
liveData::class.java.getDeclaredMethod("onInactive")?.apply {
invoke(liveData)
}
verify(provider, times(1)).unsubscribe(any())
}
@Test
@DisplayName("When onDestroy is called Then we call onDestroy on the provider")
fun onDestroyCallsOnDestroyOnProvider() {
liveData.onCreate()
liveData.onDestroy()
verify(provider, times(1)).onDestroy()
}
}
@Nested
@DisplayName("Given an initialised provider")
inner class InitialisedProvider {
@BeforeEach
fun setup() {
When calling provider.isInitialised itReturns true
}
@Test
@DisplayName("When we call isInitialised Then it returns true")
fun isInitialisedReturnsFalse() {
liveData.isInitialised shouldBe true
}
}
@Nested
@DisplayName("Given an initialised liveData instance")
inner class InitialisedLiveData {
@BeforeEach
fun setup() {
When calling provider.isInitialised itReturns true
When calling owner.isMainThread itReturns true
liveData.setValue(DEFAULT_VALUE)
}
@Test
@DisplayName("When we call isInitialised Then it returns true")
fun isInitialisedReturnsFalse() {
liveData.isInitialised shouldBe true
}
@Test
@DisplayName("When we call getValue Then it does not request the value from the provider")
fun getValueCallsProvider() {
runBlocking {
liveData.getValueBlocking()
verify(provider, never()).getValue()
}
}
@Test
@DisplayName("When we call setValue Then it updates the internal value")
fun setValueUpdatesValue() {
liveData.setValue(NEW_VALUE)
runBlocking {
liveData.getValueBlocking() shouldBe NEW_VALUE
}
}
@Test
@DisplayName("When we call setValue Then it updates the provider")
fun setValueUpdatesProvider() {
liveData.setValue(NEW_VALUE)
verify(provider, times(1)).setValue(NEW_VALUE)
}
@Test
@DisplayName("When we call setValue twice Then it only updates the provider once")
fun setValueTwiceUpdatesProviderOnce() {
liveData.setValue(NEW_VALUE)
liveData.setValue(NEW_VALUE)
verify(provider, times(1)).setValue(NEW_VALUE)
}
}
}
| 2
|
Kotlin
|
9
| 206
|
5e0a7d5ef462b88e031db7602b4b8b2816b9cb99
| 5,313
|
Prefekt
|
Apache License 2.0
|
src/main/kotlin/us/sodiumlabs/ServerProvider.kt
|
napentathol
| 98,761,068
| false
| null |
package us.sodiumlabs
import net.fabricmc.api.EnvType
import net.fabricmc.loader.api.FabricLoader
import net.minecraft.client.Minecraft
import net.minecraft.server.MinecraftServer
import java.util.Optional
object ServerProvider {
fun getServer(): Optional<MinecraftServer> {
return if (FabricLoader.getInstance().environmentType == EnvType.CLIENT) {
Optional.ofNullable(Minecraft.getInstance().singleplayerServer)
} else {
Optional.of(FabricLoader.getInstance().gameInstance as MinecraftServer)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
83b2ba11940f34f643adfe603ced88d052851713
| 559
|
SodiumLabsPlugin
|
MIT License
|
shared/src/iosMain/kotlin/com/prof18/feedflow/domain/opml/OpmlOutput.kt
|
prof18
| 600,257,020
| false
| null |
package com.prof18.feedflow.domain.opml
import platform.Foundation.NSURL
actual data class OpmlOutput(
val url: NSURL,
)
| 0
|
Kotlin
|
4
| 97
|
e3d2ae617a067c0484d414c34fc4ae87630e3b7a
| 127
|
feed-flow
|
Apache License 2.0
|
module_system/src/main/java/com/jason/system/vm/NavViewModel.kt
|
JasonXuJie
| 388,685,777
| false
| null |
package com.jason.system.vm
import androidx.lifecycle.MutableLiveData
import com.jason.common.base.BaseViewModel
import com.jason.net.bean.ResState
import com.jason.system.model.NavData
import com.jason.system.model.NavRepo
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class NavViewModel @Inject constructor(): BaseViewModel() {
@Inject
lateinit var repo:NavRepo
val data = MutableLiveData<List<NavData>>()
val errMsg = MutableLiveData<String>()
fun loadNavList(){
launch({
val state = repo.loadNavTree()
if (state is ResState.Success){
data.postValue(state.data)
}else if (state is ResState.Fail){
errMsg.postValue(state.errorMsg)
}
})
}
}
| 0
|
Kotlin
|
0
| 1
|
fd6b68c198e16aa8390338fc0dbb419e73e094bc
| 817
|
KotlinWanAndroid
|
Apache License 2.0
|
plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/script/CSharpScriptRunTypePropertiesProcessor.kt
|
JetBrains
| 49,584,664
| false
|
{"Kotlin": 2668816, "C#": 319761, "Java": 101027, "Dockerfile": 831, "CSS": 726}
|
/*
* Copyright 2000-2023 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.script
import jetbrains.buildServer.ToolVersionProvider
import jetbrains.buildServer.serverSide.InvalidProperty
import jetbrains.buildServer.serverSide.PropertiesProcessor
class CSharpScriptRunTypePropertiesProcessor(
private val _toolVersionProvider: ToolVersionProvider)
: PropertiesProcessor {
override fun process(properties: Map<String, String>) =
validate(properties).toCollection(mutableListOf())
private fun validate(properties: Map<String, String>) = sequence {
if (properties[ScriptConstants.CLT_PATH].isNullOrBlank()) {
yield(InvalidProperty(ScriptConstants.CLT_PATH, "The path to ${ScriptConstants.RUNNER_DESCRIPTION} must be specified"))
}
val scriptType = properties[ScriptConstants.SCRIPT_TYPE]?.let { ScriptType.tryParse(it) }
if (scriptType == null) {
yield(InvalidProperty(ScriptConstants.SCRIPT_TYPE, "Script type is not specified"))
}
when(scriptType) {
ScriptType.Custom ->
if(properties[ScriptConstants.SCRIPT_CONTENT].isNullOrBlank()) {
yield(InvalidProperty(ScriptConstants.SCRIPT_CONTENT, "Custom script content is not provided"))
}
ScriptType.File ->
if(properties[ScriptConstants.SCRIPT_FILE].isNullOrBlank()) {
yield(InvalidProperty(ScriptConstants.SCRIPT_FILE, "Script file path is not specified"))
}
else -> { }
}
}
}
| 3
|
Kotlin
|
25
| 91
|
68c95408c1d39158312573573591b8efa4d78cab
| 2,138
|
teamcity-dotnet-plugin
|
Apache License 2.0
|
app/src/main/java/com/fernandez/gatekeep/SettingsFragment.kt
|
Kyne0328
| 615,960,386
| false
| null |
package com.fernandez.gatekeep
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.io.ByteArrayInputStream
import kotlin.random.Random
class SettingsFragment : Fragment() {
private lateinit var githubButton: Button
private lateinit var updateButton: Button
private lateinit var logoutButton: Button
private lateinit var disclaimerButton: Button
private lateinit var auth: FirebaseAuth
private lateinit var database: FirebaseDatabase
private lateinit var accountSettingsButton: Button
private lateinit var userProfileImageView: ImageView
private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_settings, container, false)
accountSettingsButton = view.findViewById(R.id.account_settings)
auth = FirebaseAuth.getInstance()
database = FirebaseDatabase.getInstance()
userProfileImageView = view.findViewById(R.id.ProfilePicture)
updateButton = view.findViewById(R.id.update_button)
updateButton.setOnClickListener {
checkForUpdates()
}
// Initialize views
githubButton = view.findViewById(R.id.github_button)
logoutButton = view.findViewById(R.id.logout_button)
disclaimerButton = view.findViewById(R.id.disclaimer)
// Set click listeners
accountSettingsButton.setOnClickListener {
val intent = Intent(requireContext(), AccountSettingsActivity::class.java)
startActivity(intent)
}
githubButton.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/KyNe0328/GateKeep"))
startActivity(intent)
}
logoutButton.setOnClickListener {
// Log out the user from Firebase Auth
FirebaseAuth.getInstance().signOut()
// Redirect the user to the login activity
val intent = Intent(activity, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
}
disclaimerButton.setOnClickListener {
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Disclaimer")
.setMessage("Please note that the GateKeep app is designed for School entry tracking purposes only. The app is not responsible for verifying the accuracy of the entry records of the attendees. The QR codes assigned to the students are solely for the purpose of entry tracking and should not be used for any other purpose. The app does not guarantee the security or confidentiality of the student's personal information, including their name and email address. The Gate Keeper is solely responsible for ensuring that the attendance records are accurate and up-to-date. The use of this app is at the discretion of the user, and we assume no liability for any issues arising from the use of this app.")
.setPositiveButton("OK", null)
builder.create().show()
}
val currentUserUid = FirebaseAuth.getInstance().currentUser?.uid
if (currentUserUid != null) {
// Retrieve user's name from the 'users' node
val userRef = FirebaseDatabase.getInstance().getReference("users")
.child(currentUserUid)
.child("name")
userRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val name = snapshot.getValue(String::class.java)
if (name != null) {
// Display the username in a TextView
val uname = view.findViewById<TextView>(R.id.userName)
uname.text = name
}
}
override fun onCancelled(databaseError: DatabaseError) {
Toast.makeText(
requireContext(),
"Failed to load user data: ${databaseError.message}",
Toast.LENGTH_SHORT
).show()
}
})
}
loadProfileImage()
return view
}
override fun onDestroy() {
super.onDestroy()
coroutineScope.cancel()
}
private fun checkForUpdates() {
coroutineScope.launch(Dispatchers.IO) {
val latestVersion = getLatestVersionFromGithub()
if (latestVersion != null && latestVersion.first?.let { isUpdateAvailable(it) } == true) {
withContext(Dispatchers.Main) {
showUpdateDialog(latestVersion)
}
}
else {
withContext(Dispatchers.Main) {
Toast.makeText(
requireContext(),
"You are already on the latest version!",
Toast.LENGTH_SHORT
).show()
}
}
}
}
private fun getLatestVersionFromGithub(): Triple<String?, String?, String?>? {
val client = OkHttpClient()
val request = Request.Builder()
.url("https://api.github.com/repos/KyNe0328/GateKeep/releases/latest")
.build()
return try {
val response = client.newCall(request).execute()
val responseString = response.body.string()
val jsonObject = JSONObject(responseString)
val tagName = jsonObject.getString("tag_name")
val body = jsonObject.getString("body")
val assetsArray = jsonObject.getJSONArray("assets")
if (assetsArray.length() > 0) {
val assetObject = assetsArray.getJSONObject(0)
val downloadUrl = assetObject.getString("browser_download_url")
Triple(tagName, downloadUrl, body)
} else {
Triple(tagName, null, body)
}
} catch (e: Exception) {
null
}
}
private fun isUpdateAvailable(latestVersion: String): Boolean {
return latestVersion != BuildConfig.VERSION_NAME
}
private fun showUpdateDialog(updateInfo: Triple<String?, String?, String?>) {
val message = "New update ${updateInfo.first} is available.\n\n${updateInfo.third}\n\nDo you want to download it?"
AlertDialog.Builder(requireContext())
.setTitle("New update found")
.setMessage(message)
.setPositiveButton("Download") { _, _ ->
updateInfo.second?.let {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(it)
startActivity(intent)
}
}
.setNegativeButton("Cancel", null)
.show()
}
private fun loadProfileImage() {
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference
val currentUser = FirebaseAuth.getInstance().currentUser
val filename = currentUser?.uid ?: return
val profileImageRef = storageRef.child("profiles/$filename.jpg")
profileImageRef.downloadUrl
.addOnSuccessListener { uri ->
Glide.with(this)
.load(uri)
.circleCrop()
.into(userProfileImageView)
}
.addOnFailureListener {
// Failed to load the user's custom image, falling back to default avatar
val defaultAvatarPrefix = if (userGender()) "male_" else "female_"
val randomAvatarIndex = Random.nextInt(1, 4)
val defaultAvatarFilename = "$defaultAvatarPrefix$randomAvatarIndex.jpg"
val defaultAvatarRef = storageRef.child("profiles/default_avatars/$defaultAvatarFilename")
defaultAvatarRef.downloadUrl
.addOnSuccessListener { defaultAvatarUri ->
Glide.with(this)
.load(defaultAvatarUri)
.circleCrop()
.into(userProfileImageView)
val userUUID = currentUser.uid
val userAvatarRef = storageRef.child("profiles/$userUUID.jpg")
defaultAvatarRef.getBytes(Long.MAX_VALUE)
.addOnSuccessListener { bytes ->
val inputStream = ByteArrayInputStream(bytes)
val uploadTask = userAvatarRef.putStream(inputStream)
uploadTask.addOnSuccessListener {
Toast.makeText(context, "Default avatar uploaded", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(context, "Failed to upload default avatar", Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener {
Toast.makeText(context, "Failed to load default avatar", Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener {
Toast.makeText(context, "Failed to load default avatar", Toast.LENGTH_SHORT).show()
}
}
}
private fun userGender(): Boolean {
return Random.nextBoolean()
}
override fun onResume() {
super.onResume()
loadProfileImage()
}
}
| 0
|
Kotlin
|
0
| 1
|
0e6b919127d9a7dbf0b0706aa3f89c55b724cfc2
| 10,834
|
GateKeep
|
Apache License 2.0
|
client/src/main/kotlin/io/github/matrixkt/api/GetRoomEvents.kt
|
abueide
| 390,591,652
| true
|
{"Kotlin": 794398}
|
package io.github.matrixkt.api
import io.github.matrixkt.models.Direction
import io.github.matrixkt.models.events.MatrixEvent
import io.github.matrixkt.utils.MatrixRpc
import io.github.matrixkt.utils.RpcMethod
import io.github.matrixkt.utils.resource.Resource
import kotlinx.serialization.Serializable
/**
* This API returns a list of message and state events for a room. It uses
* pagination query parameters to paginate history in the room.
*
* *Note*: This endpoint supports lazy-loading of room member events. See
* `Lazy-loading room members <#lazy-loading-room-members>`_ for more information.
*/
public class GetRoomEvents(
public override val url: Url
) : MatrixRpc.WithAuth<RpcMethod.Get, GetRoomEvents.Url, Any?, GetRoomEvents.Response> {
public override val body: Any?
get() = null
@Resource("/_matrix/client/r0/rooms/{roomId}/messages")
@Serializable
public class Url(
/**
* The room to get events from.
*/
public val roomId: String,
/**
* The token to start returning events from. This token can be obtained
* from a ``prev_batch`` token returned for each room by the sync API,
* or from a ``start`` or ``end`` token returned by a previous request
* to this endpoint.
*/
public val from: String,
/**
* The token to stop returning events at. This token can be obtained from
* a ``prev_batch`` token returned for each room by the sync endpoint,
* or from a ``start`` or ``end`` token returned by a previous request to
* this endpoint.
*/
public val to: String? = null,
/**
* The direction to return events from.
*/
public val dir: Direction,
/**
* The maximum number of events to return. Default: 10.
*/
public val limit: Long? = null,
/**
* A JSON RoomEventFilter to filter returned events with.
*/
public val filter: String? = null
)
@Serializable
public class Response(
/**
* A list of room events. The order depends on the ``dir`` parameter.
* For ``dir=b`` events will be in reverse-chronological order,
* for ``dir=f`` in chronological order, so that events start
* at the ``from`` point.
*/
public val chunk: List<MatrixEvent> = emptyList(),
/**
* The token the pagination ends at. If ``dir=b`` this token should
* be used again to request even earlier events.
*/
public val end: String? = null,
/**
* The token the pagination starts from. If ``dir=b`` this will be
* the token supplied in ``from``.
*/
public val start: String? = null,
/**
* A list of state events relevant to showing the ``chunk``. For example, if
* ``lazy_load_members`` is enabled in the filter then this may contain
* the membership events for the senders of events in the ``chunk``.
*
* Unless ``include_redundant_members`` is ``true``, the server
* may remove membership events which would have already been
* sent to the client in prior calls to this endpoint, assuming
* the membership of those members has not changed.
*/
public val state: List<MatrixEvent> = emptyList()
)
}
| 0
| null |
0
| 0
|
7284bb42b76e80b4b55579346dc3f117352eb033
| 3,427
|
matrix-kt
|
Apache License 2.0
|
app-data/src/main/java/com/kotlin/android/app/data/entity/message/BlockStatusResult.kt
|
R-Gang-H
| 538,443,254
| false
| null |
package com.kotlin.android.app.data.entity.message
import com.kotlin.android.app.data.ProguardRule
/**
* Created by zhaoninglongfei on 2022/3/21
* 获取好友是否在黑名单
*/
data class BlockStatusResult(
var bizCode: Long? = 0L,//1:成功 其他:失败
var err: String? = null,
var bizData: BlockStatus? = null
) : ProguardRule {
data class BlockStatus(
var isBlock: Long? = null,//黑名单状态 1:拉黑中 2:正常
var isOfficial: Boolean? = null//是否官方账号 true:是 false : 不是
) : ProguardRule
}
| 0
|
Kotlin
|
0
| 1
|
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
| 492
|
Mtime
|
Apache License 2.0
|
precompose/src/commonMain/kotlin/moe/tlaster/precompose/navigation/route/Route.kt
|
Tlaster
| 349,750,473
| false
|
{"Kotlin": 191657}
|
package moe.tlaster.precompose.navigation.route
interface Route {
val route: String
}
| 40
|
Kotlin
|
49
| 849
|
276c933397d94b8dfc60b809942bc38b23d945bd
| 91
|
PreCompose
|
MIT License
|
src/main/kotlin/com/melowetty/hsepermhelper/utils/DateUtils.kt
|
Melowetty
| 682,010,195
| false
|
{"Kotlin": 156043, "Dockerfile": 462}
|
package com.melowetty.hsepermhelper.utils
class DateUtils {
companion object {
const val DATE_PATTERN = "dd.MM.yyyy"
const val DATE_TIME_PATTERN = "dd.MM.yyyy HH:mm:ss"
}
}
| 3
|
Kotlin
|
0
| 0
|
ff44e5ad34e08dc427842e438794590d87624ebe
| 197
|
HsePermHelperBackend
|
MIT License
|
src/main/kotlin/org/jetbrains/research/testspark/testmanager/java/JavaTestAnalyzer.kt
|
JetBrains-Research
| 563,889,235
| false
|
{"Kotlin": 733171, "Java": 5347, "Shell": 1563}
|
package org.jetbrains.research.testspark.testmanager.java
import com.github.javaparser.ParseProblemException
import com.github.javaparser.StaticJavaParser
import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.ast.body.MethodDeclaration
import com.github.javaparser.ast.visitor.VoidVisitorAdapter
import org.jetbrains.research.testspark.testmanager.template.TestAnalyzer
object JavaTestAnalyzer : TestAnalyzer {
override fun extractFirstTestMethodCode(classCode: String): String {
var result = ""
try {
val componentUnit: CompilationUnit = StaticJavaParser.parse(classCode)
object : VoidVisitorAdapter<Any?>() {
override fun visit(method: MethodDeclaration, arg: Any?) {
super.visit(method, arg)
if (method.getAnnotationByName("Test").isPresent) {
result += "\t" + method.toString().replace("\n", "\n\t") + "\n\n"
}
}
}.visit(componentUnit, null)
return result
} catch (e: ParseProblemException) {
val upperCutCode = "\t@Test" + classCode.split("@Test").last()
var methodStarted = false
var balanceOfBrackets = 0
for (symbol in upperCutCode) {
result += symbol
if (symbol == '{') {
methodStarted = true
balanceOfBrackets++
}
if (symbol == '}') {
balanceOfBrackets--
}
if (methodStarted && balanceOfBrackets == 0) {
break
}
}
return result + "\n"
}
}
override fun extractFirstTestMethodName(oldTestCaseName: String, classCode: String): String {
var result = ""
try {
val componentUnit: CompilationUnit = StaticJavaParser.parse(classCode)
object : VoidVisitorAdapter<Any?>() {
override fun visit(method: MethodDeclaration, arg: Any?) {
super.visit(method, arg)
if (method.getAnnotationByName("Test").isPresent) {
result = method.nameAsString
}
}
}.visit(componentUnit, null)
return result
} catch (e: ParseProblemException) {
return oldTestCaseName
}
}
override fun getClassFromTestCaseCode(code: String): String {
val pattern = Regex("public\\s+class\\s+(\\S+)\\s*\\{")
val matchResult = pattern.find(code)
matchResult ?: return "GeneratedTest"
val (className) = matchResult.destructured
return className
}
override fun getFileNameFromTestCaseCode(code: String): String {
return "${getClassFromTestCaseCode(code)}.java"
}
}
| 66
|
Kotlin
|
19
| 51
|
e1553b15f05f8e125f17aba1e062e4f3ad2c00e3
| 2,903
|
TestSpark
|
MIT License
|
app/src/main/java/com/paypay/currencyconverter/database/models/Rates.kt
|
mnhmasum
| 523,544,422
| false
| null |
package com.paypay.currencyconverter.database.models
import androidx.room.Entity
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
@Entity(tableName = "currency_rate")
class Rates {
@SerializedName("AED")
var aed: Double? = null
@SerializedName("AFN")
var afn: Double? = null
@SerializedName("ALL")
var all: Double? = null
@SerializedName("AMD")
var amd: Double? = null
@SerializedName("ANG")
var ang: Double? = null
@SerializedName("AOA")
var aoa: Double? = null
@SerializedName("ARS")
var ars: Double? = null
@SerializedName("AUD")
var aud: Double? = null
@SerializedName("AWG")
var awg: Double? = null
@SerializedName("AZN")
var azn: Double? = null
@SerializedName("BAM")
var bam: Double? = null
@SerializedName("BBD")
var bbd: Double? = null
@SerializedName("BDT")
var bdt: Double? = null
@SerializedName("BGN")
var bgn: Double? = null
@SerializedName("BHD")
var bhd: Double? = null
@SerializedName("BIF")
@Expose
var bif: Double? = null
@SerializedName("BMD")
var bmd: Double? = null
@SerializedName("BND")
var bnd: Double? = null
@SerializedName("BOB")
var bob: Double? = null
@SerializedName("BRL")
var brl: Double? = null
@SerializedName("BSD")
var bsd: Double? = null
@SerializedName("BTC")
var btc: Double? = null
@SerializedName("BTN")
var btn: Double? = null
@SerializedName("BWP")
var bwp: Double? = null
@SerializedName("BYN")
var byn: Double? = null
@SerializedName("BZD")
var bzd: Double? = null
@SerializedName("CAD")
var cad: Double? = null
@SerializedName("CDF")
var cdf: Double? = null
@SerializedName("CHF")
var chf: Double? = null
@SerializedName("CLF")
var clf: Double? = null
@SerializedName("CLP")
var clp: Double? = null
@SerializedName("CNH")
var cnh: Double? = null
@SerializedName("CNY")
var cny: Double? = null
@SerializedName("COP")
var cop: Double? = null
@SerializedName("CRC")
var crc: Double? = null
@SerializedName("CUC")
var cuc: Double? = null
@SerializedName("CUP")
var cup: Double? = null
@SerializedName("CVE")
var cve: Double? = null
@SerializedName("CZK")
var czk: Double? = null
@SerializedName("DJF")
var djf: Double? = null
@SerializedName("DKK")
var dkk: Double? = null
@SerializedName("DOP")
var dop: Double? = null
@SerializedName("DZD")
var dzd: Double? = null
@SerializedName("EGP")
var egp: Double? = null
@SerializedName("ERN")
var ern: Double? = null
@SerializedName("ETB")
var etb: Double? = null
@SerializedName("EUR")
var eur: Double? = null
@SerializedName("FJD")
var fjd: Double? = null
@SerializedName("FKP")
var fkp: Double? = null
@SerializedName("GBP")
var gbp: Double? = null
@SerializedName("GEL")
var gel: Double? = null
@SerializedName("GGP")
var ggp: Double? = null
@SerializedName("GHS")
var ghs: Double? = null
@SerializedName("GIP")
var gip: Double? = null
@SerializedName("GMD")
var gmd: Double? = null
@SerializedName("GNF")
var gnf: Double? = null
@SerializedName("GTQ")
var gtq: Double? = null
@SerializedName("GYD")
var gyd: Double? = null
@SerializedName("HKD")
var hkd: Double? = null
@SerializedName("HNL")
var hnl: Double? = null
@SerializedName("HRK")
var hrk: Double? = null
@SerializedName("HTG")
var htg: Double? = null
@SerializedName("HUF")
var huf: Double? = null
@SerializedName("IDR")
var idr: Double? = null
@SerializedName("ILS")
var ils: Double? = null
@SerializedName("IMP")
var imp: Double? = null
@SerializedName("INR")
var inr: Double? = null
@SerializedName("IQD")
var iqd: Double? = null
@SerializedName("IRR")
var irr: Double? = null
@SerializedName("ISK")
var isk: Double? = null
@SerializedName("JEP")
var jep: Double? = null
@SerializedName("JMD")
var jmd: Double? = null
@SerializedName("JOD")
var jod: Double? = null
@SerializedName("JPY")
var jpy: Double? = null
@SerializedName("KES")
var kes: Double? = null
@SerializedName("KGS")
var kgs: Double? = null
@SerializedName("KHR")
var khr: Double? = null
@SerializedName("KMF")
var kmf: Double? = null
@SerializedName("KPW")
var kpw: Double? = null
@SerializedName("KRW")
var krw: Double? = null
@SerializedName("KWD")
var kwd: Double? = null
@SerializedName("KYD")
var kyd: Double? = null
@SerializedName("KZT")
var kzt: Double? = null
@SerializedName("LAK")
var lak: Double? = null
@SerializedName("LBP")
var lbp: Double? = null
@SerializedName("LKR")
var lkr: Double? = null
@SerializedName("LRD")
var lrd: Double? = null
@SerializedName("LSL")
var lsl: Double? = null
@SerializedName("LYD")
var lyd: Double? = null
@SerializedName("MAD")
var mad: Double? = null
@SerializedName("MDL")
var mdl: Double? = null
@SerializedName("MGA")
var mga: Double? = null
@SerializedName("MKD")
var mkd: Double? = null
@SerializedName("MMK")
var mmk: Double? = null
@SerializedName("MNT")
var mnt: Double? = null
@SerializedName("MOP")
var mop: Double? = null
@SerializedName("MRU")
var mru: Double? = null
@SerializedName("MUR")
var mur: Double? = null
@SerializedName("MVR")
var mvr: Double? = null
@SerializedName("MWK")
var mwk: Double? = null
@SerializedName("MXN")
var mxn: Double? = null
@SerializedName("MYR")
var myr: Double? = null
@SerializedName("MZN")
var mzn: Double? = null
@SerializedName("NAD")
var nad: Double? = null
@SerializedName("NGN")
var ngn: Double? = null
@SerializedName("NIO")
var nio: Double? = null
@SerializedName("NOK")
var nok: Double? = null
@SerializedName("NPR")
var npr: Double? = null
@SerializedName("NZD")
var nzd: Double? = null
@SerializedName("OMR")
var omr: Double? = null
@SerializedName("PAB")
var pab: Double? = null
@SerializedName("PEN")
var pen: Double? = null
@SerializedName("PGK")
var pgk: Double? = null
@SerializedName("PHP")
var php: Double? = null
@SerializedName("PKR")
var pkr: Double? = null
@SerializedName("PLN")
var pln: Double? = null
@SerializedName("PYG")
var pyg: Double? = null
@SerializedName("QAR")
var qar: Double? = null
@SerializedName("RON")
var ron: Double? = null
@SerializedName("RSD")
var rsd: Double? = null
@SerializedName("RUB")
var rub: Double? = null
@SerializedName("RWF")
var rwf: Double? = null
@SerializedName("SAR")
var sar: Double? = null
@SerializedName("SBD")
var sbd: Double? = null
@SerializedName("SCR")
var scr: Double? = null
@SerializedName("SDG")
var sdg: Double? = null
@SerializedName("SEK")
var sek: Double? = null
@SerializedName("SGD")
var sgd: Double? = null
@SerializedName("SHP")
var shp: Double? = null
@SerializedName("SLL")
var sll: Double? = null
@SerializedName("SOS")
var sos: Double? = null
@SerializedName("SRD")
var srd: Double? = null
@SerializedName("SSP")
var ssp: Double? = null
@SerializedName("STD")
var std: Double? = null
@SerializedName("STN")
var stn: Double? = null
@SerializedName("SVC")
var svc: Double? = null
@SerializedName("SYP")
var syp: Double? = null
@SerializedName("SZL")
var szl: Double? = null
@SerializedName("THB")
var thb: Double? = null
@SerializedName("TJS")
var tjs: Double? = null
@SerializedName("TMT")
var tmt: Double? = null
@SerializedName("TND")
var tnd: Double? = null
@SerializedName("TOP")
var top: Double? = null
@SerializedName("TRY")
var `try`: Double? = null
@SerializedName("TTD")
var ttd: Double? = null
@SerializedName("TWD")
var twd: Double? = null
@SerializedName("TZS")
var tzs: Double? = null
@SerializedName("UAH")
var uah: Double? = null
@SerializedName("UGX")
var ugx: Double? = null
@SerializedName("USD")
var usd: Double? = null
@SerializedName("UYU")
var uyu: Double? = null
@SerializedName("UZS")
var uzs: Double? = null
@SerializedName("VES")
var ves: Double? = null
@SerializedName("VND")
var vnd: Double? = null
@SerializedName("VUV")
var vuv: Double? = null
@SerializedName("WST")
var wst: Double? = null
@SerializedName("XAF")
var xaf: Double? = null
@SerializedName("XAG")
var xag: Double? = null
@SerializedName("XAU")
var xau: Double? = null
@SerializedName("XCD")
var xcd: Double? = null
@SerializedName("XDR")
var xdr: Double? = null
@SerializedName("XOF")
var xof: Double? = null
@SerializedName("XPD")
var xpd: Double? = null
@SerializedName("XPF")
var xpf: Double? = null
@SerializedName("XPT")
var xpt: Double? = null
@SerializedName("YER")
var yer: Double? = null
@SerializedName("ZAR")
var zar: Double? = null
@SerializedName("ZMW")
var zmw: Double? = null
@SerializedName("ZWL")
var zwl: Double? = null
}
| 0
|
Kotlin
|
0
| 2
|
d1e1a4288748388ef4ef5a7a19937e37d285329e
| 9,705
|
Currency-Converter-MVVM
|
Apache License 2.0
|
app/src/main/java/org/p2p/wallet/newsend/ui/NewSendContract.kt
|
p2p-org
| 306,035,988
| false
| null |
package org.p2p.wallet.newsend.ui
import org.p2p.core.common.TextContainer
import org.p2p.core.token.Token
import org.p2p.uikit.components.UiKitSendDetailsWidgetContract
import org.p2p.wallet.common.mvp.MvpPresenter
import org.p2p.wallet.common.mvp.MvpView
import org.p2p.wallet.send.model.SendFeeTotal
import org.p2p.wallet.transaction.model.NewShowProgress
import java.math.BigDecimal
interface NewSendContract {
interface View : MvpView, UiKitSendDetailsWidgetContract {
fun updateInputValue(textValue: String, forced: Boolean)
fun updateInputFraction(newInputFractionLength: Int)
fun showFreeTransactionsInfo()
fun showTransactionDetails(sendFeeTotal: SendFeeTotal)
fun showProgressDialog(internalTransactionId: String, data: NewShowProgress)
fun showTokenSelection(tokens: List<Token.Active>, selectedToken: Token.Active?)
fun showDebugInfo(text: CharSequence)
fun setBottomButtonText(text: TextContainer?)
fun setSliderText(text: String?)
fun disableInputs()
}
interface Presenter : MvpPresenter<View> {
fun setInitialData(selectedToken: Token.Active?, inputAmount: BigDecimal?)
fun updateToken(newToken: Token.Active)
fun updateInputAmount(amount: String)
fun updateFeePayerToken(feePayerToken: Token.Active)
fun switchCurrencyMode()
fun onMaxButtonClicked()
fun onTokenClicked()
fun onFeeInfoClicked()
fun checkInternetConnection()
fun send()
}
}
| 9
|
Kotlin
|
14
| 23
|
2badf683d824c57654b12ea0c023f96e1a5d0c19
| 1,540
|
key-app-android
|
MIT License
|
app/src/main/java/org/p2p/wallet/newsend/ui/NewSendContract.kt
|
p2p-org
| 306,035,988
| false
| null |
package org.p2p.wallet.newsend.ui
import org.p2p.core.common.TextContainer
import org.p2p.core.token.Token
import org.p2p.uikit.components.UiKitSendDetailsWidgetContract
import org.p2p.wallet.common.mvp.MvpPresenter
import org.p2p.wallet.common.mvp.MvpView
import org.p2p.wallet.send.model.SendFeeTotal
import org.p2p.wallet.transaction.model.NewShowProgress
import java.math.BigDecimal
interface NewSendContract {
interface View : MvpView, UiKitSendDetailsWidgetContract {
fun updateInputValue(textValue: String, forced: Boolean)
fun updateInputFraction(newInputFractionLength: Int)
fun showFreeTransactionsInfo()
fun showTransactionDetails(sendFeeTotal: SendFeeTotal)
fun showProgressDialog(internalTransactionId: String, data: NewShowProgress)
fun showTokenSelection(tokens: List<Token.Active>, selectedToken: Token.Active?)
fun showDebugInfo(text: CharSequence)
fun setBottomButtonText(text: TextContainer?)
fun setSliderText(text: String?)
fun disableInputs()
}
interface Presenter : MvpPresenter<View> {
fun setInitialData(selectedToken: Token.Active?, inputAmount: BigDecimal?)
fun updateToken(newToken: Token.Active)
fun updateInputAmount(amount: String)
fun updateFeePayerToken(feePayerToken: Token.Active)
fun switchCurrencyMode()
fun onMaxButtonClicked()
fun onTokenClicked()
fun onFeeInfoClicked()
fun checkInternetConnection()
fun send()
}
}
| 9
|
Kotlin
|
14
| 23
|
2badf683d824c57654b12ea0c023f96e1a5d0c19
| 1,540
|
key-app-android
|
MIT License
|
src/main/kotlin/io/openfuture/chain/network/message/core/TransactionMessage.kt
|
fossabot
| 160,686,845
| true
|
{"Kotlin": 403732, "Dockerfile": 233, "Shell": 74}
|
package io.openfuture.chain.network.message.core
import io.netty.buffer.ByteBuf
import io.openfuture.chain.core.annotation.NoArgConstructor
import io.openfuture.chain.network.extension.readString
import io.openfuture.chain.network.extension.writeString
import io.openfuture.chain.network.serialization.Serializable
@NoArgConstructor
abstract class TransactionMessage(
var timestamp: Long,
var fee: Long,
var senderAddress: String,
var hash: String,
var senderSignature: String,
var senderPublicKey: String
) : Serializable {
override fun read(buf: ByteBuf) {
timestamp = buf.readLong()
fee = buf.readLong()
senderAddress = buf.readString()
hash = buf.readString()
senderSignature = buf.readString()
senderPublicKey = buf.readString()
}
override fun write(buf: ByteBuf) {
buf.writeLong(timestamp)
buf.writeLong(fee)
buf.writeString(senderAddress)
buf.writeString(hash)
buf.writeString(senderSignature)
buf.writeString(senderPublicKey)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TransactionMessage) return false
if (timestamp != other.timestamp) return false
if (fee != other.fee) return false
if (senderAddress != other.senderAddress) return false
if (hash != other.hash) return false
if (senderSignature != other.senderSignature) return false
if (senderPublicKey != other.senderPublicKey) return false
return true
}
override fun hashCode(): Int {
var result = timestamp.hashCode()
result = 31 * result + fee.hashCode()
result = 31 * result + senderAddress.hashCode()
result = 31 * result + hash.hashCode()
result = 31 * result + senderSignature.hashCode()
result = 31 * result + senderPublicKey.hashCode()
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
5924678aade4147e0f52bc719f41d689085bd57f
| 1,962
|
open-chain
|
MIT License
|
app/src/main/java/com/ch4019/music/config/Route.kt
|
CH4019
| 677,941,702
| false
| null |
package com.ch4019.music.config
object AppRoute {
const val START_PAGE = "start_page"
const val MAIN_PAGE = "main_page"
}
object MainRoute {
const val HOME_PAGE = "home_page"
const val LIKE_LIST_PAGE = "like_list_page"
const val SONGS_LIST_PAGE = "songs_list_page"
const val SETTING_PAGE = "setting_page"
const val ABOUT_PAGE = "about_page"
}
| 0
|
Kotlin
|
0
| 0
|
cb65ebabc44d58ea98ba7a2939a87c5c6833e433
| 373
|
CandyPlayer
|
MIT License
|
Demo/module-base/src/main/java/com/xiaojinzi/component/base/interceptor/CallPhonePermissionInterceptor.kt
|
xiaojinzi123
| 574,764,526
| false
|
{"Kotlin": 479775, "Java": 27180}
|
package com.xiaojinzi.component.base.interceptor
import android.Manifest
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import com.xiaojinzi.component.anno.InterceptorAnno
import com.xiaojinzi.component.base.RouterConfig
import com.xiaojinzi.component.base.api.RouterApi
import com.xiaojinzi.component.impl.RouterInterceptor
import com.xiaojinzi.component.impl.RouterResult
import com.xiaojinzi.component.impl.routeApi
@InterceptorAnno(RouterConfig.INTERCEPTOR_PERMISSION_CALL_PHONE)
class CallPhonePermissionInterceptor : RouterInterceptor {
override suspend fun intercept(chain: RouterInterceptor.Chain): RouterResult {
val context = chain.request().rawAliveContext!!
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.CALL_PHONE
) != PackageManager.PERMISSION_GRANTED
) {
RouterApi::class
.routeApi()
.requestPermission(
context = context,
permission = Manifest.permission.CALL_PHONE,
permissionDesc = "申请电话权限",
)
}
return chain.proceed(request = chain.request())
}
}
| 3
|
Kotlin
|
11
| 99
|
b575c031f91acadc0debbcc96cf96d8235026116
| 1,239
|
KComponent
|
Apache License 2.0
|
multiplatform-compose/src/iosX64Main/kotlin/com/rouge41/kmm/compose/ui/text/style/TextOverflow.kt
|
cl3m
| 327,994,833
| false
| null |
package com.rouge41.kmm.compose.ui.text.style
actual enum class TextOverflow {
Clip,
Ellipsis,
}
| 1
|
Kotlin
|
19
| 385
|
8d2059d69a18b76e3672db3fc9c558a31f9ca576
| 105
|
multiplatform-compose
|
Apache License 2.0
|
app/src/main/java/cc/sovellus/vrcaa/ui/screen/misc/NestedPlaceholderScreen.kt
|
Nyabsi
| 745,635,224
| false
|
{"Kotlin": 248120}
|
package cc.sovellus.vrcaa.ui.screen.misc
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import cc.sovellus.vrcaa.R
class NestedPlaceholderScreen : Screen {
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(onClick = { navigator.pop() }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription =stringResource(R.string.preview_image_description)
)
}
},
title = { Text(text = stringResource(R.string.not_implemented_title)) }
)
},
content = {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = stringResource(R.string.not_implemented_text))
}
}
)
}
}
| 1
|
Kotlin
|
1
| 7
|
3f16af6b6c0869f292b60c7f941492768949e5ba
| 2,166
|
vrcaa
|
Apache License 2.0
|
app/src/main/java/com/example/vnmh/util/ShakeDetector.kt
|
gromov-ivan
| 719,482,988
| false
|
{"Kotlin": 93191}
|
package com.example.museumapp.util
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import kotlin.math.pow
import kotlin.math.sqrt
class ShakeDetector : SensorEventListener {
private companion object {
const val SHAKE_THRESHOLD_GRAVITY = 2.7f
const val SHAKE_SLOP_TIME = 500
const val SHAKE_COUNT_RESET_TIME = 3000
}
private var shakeTimestamp: Long = 0
private var shakesCount: Int = 0
private var onShake: ((Int) -> Unit)? = null
fun setOnShakeListener(callback: ((Int) -> Unit)?) {
onShake = callback
if (callback == null) {
shakesCount = 0
}
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
override fun onSensorChanged(event: SensorEvent) {
val gX = event.values[0] / SensorManager.GRAVITY_EARTH
val gY = event.values[1] / SensorManager.GRAVITY_EARTH
val gZ = event.values[2] / SensorManager.GRAVITY_EARTH
val gForce = sqrt(gX.pow(2) + gY.pow(2) + gZ.pow(2))
if (gForce > SHAKE_THRESHOLD_GRAVITY) {
val now = System.currentTimeMillis()
// ignore shake events too close to each other (500ms)
if (shakeTimestamp + SHAKE_SLOP_TIME > now) {
return
}
// reset the shake count after 3 seconds of no shakes
if (shakeTimestamp + SHAKE_COUNT_RESET_TIME < now) {
shakesCount = 0
}
shakeTimestamp = now
shakesCount++
onShake?.invoke(shakesCount)
}
}
}
| 0
|
Kotlin
|
2
| 0
|
5c14de06b43004952e2dc5937c760c4ed4553374
| 1,678
|
VNMH_Guide
|
MIT License
|
app/src/main/java/com/fafadiatech/newscout/model/SignUpMessageData.kt
|
Vicky-Vicky27
| 484,837,384
| true
|
{"Kotlin": 430654}
|
package com.fafadiatech.newscout.model
data class SignUpMessageData(var header: NewsStatus? = null, var body: MessageBody? = null)
| 0
| null |
0
| 0
|
aa136721998e6c1fa0ab1e2fa1215584a1384b84
| 131
|
newscout_android
|
Apache License 2.0
|
app/src/androidTest/java/com/ae/apps/messagecounter/utils/MockCounters.kt
|
midhunhk
| 9,828,089
| false
|
{"Kotlin": 148066, "Shell": 1219}
|
/*
* Copyright 2018 <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.ae.apps.messagecounter.utils
import com.ae.apps.messagecounter.data.models.Counter
import java.util.*
import java.util.concurrent.ThreadLocalRandom
class MockCounters {
companion object {
fun getSimpleCounter(): Counter {
return Counter("20180715", 1)
}
fun getCounterWithCount(count: Int): Counter {
return Counter("20180718", count)
}
fun getCounters(size: Int): List<Counter> {
val list: MutableList<Counter> = ArrayList(size)
for (i in 0..size) {
val randomNumber = ThreadLocalRandom.current().nextInt(0, 11)
list.add(Counter("20180716", randomNumber))
}
return list
}
fun getSentCount(list: List<Counter>): Int {
var sum = 0
list.forEach {
sum += it.sentCount
}
return sum
}
}
}
| 0
|
Kotlin
|
10
| 21
|
9319d166daa609813688f2ee891fd4558f377494
| 1,527
|
message-counter
|
Apache License 2.0
|
miruken/src/main/kotlin/com/miruken/callback/Provider.kt
|
coridrew
| 151,555,181
| true
|
{"Kotlin": 521215}
|
package com.miruken.callback
import com.miruken.runtime.componentType
import com.miruken.runtime.isCompatibleWith
import kotlin.reflect.KType
class Provider(
private val value: Any,
type: KType? = null
) : Handler() {
private var _key: Any = type?.componentType ?: value::class
@Provides
fun provide(inquiry: Inquiry): Any? =
if (isCompatibleWith(inquiry.key, _key)) value else null
}
| 0
|
Kotlin
|
0
| 0
|
b39c281286eceda5479c0bf3561db9980fcf7f5a
| 428
|
Miruken-1
|
MIT License
|
robot-name/src/main/kotlin/RobotName.kt
|
KA-MIN
| 442,447,607
| false
|
{"HTML": 192045, "JavaScript": 84032, "CSS": 60480, "Kotlin": 51646}
|
import java.util.Random
class Robot {
val name: String
get() = randomName()
fun reset() = randomName()
fun randomName(): String {
var random = Random()
var temp = 'A' + random.nextInt('Z' - 'A')
var temp2 = 'A' + random.nextInt('Z' - 'A')
var number = random.nextInt((999-100)+1)
var result = temp.plus(temp2.toString()).plus(number)
return result
}
}
| 0
|
HTML
|
0
| 0
|
6ad2e808a5a8e6ab872ac4e8c9e6e47a74731bd5
| 429
|
Kotlin
|
MIT License
|
src/test/kotlin/dev/shtanko/algorithms/leetcode/IsSumEqualTest.kt
|
ashtanko
| 203,993,092
| false
|
{"Kotlin": 7464757, "Shell": 1168, "Makefile": 1144}
|
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.stream.Stream
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
abstract class IsSumEqualTest<out T : IsSumEqual>(private val strategy: T) {
private class InputArgumentProvider : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of(
Arguments.of(
"acb",
"cba",
"cdb",
true,
),
Arguments.of(
"aaa",
"a",
"aab",
false,
),
Arguments.of(
"aaa",
"a",
"aaaa",
true,
),
)
}
@ParameterizedTest
@ArgumentsSource(InputArgumentProvider::class)
fun `is sum equal test`(firstWord: String, secondWord: String, targetWord: String, expected: Boolean) {
val actual = strategy.perform(firstWord, secondWord, targetWord)
assertThat(actual).isEqualTo(expected)
}
}
class IsSumEqualImplTest : IsSumEqualTest<IsSumEqual>(IsSumEqualImpl())
| 6
|
Kotlin
|
0
| 19
|
5bfd35e51c9076522e46286c3f6e0a81aef5abaa
| 2,022
|
kotlab
|
Apache License 2.0
|
search-new-component/src/main/java/com/kotlin/android/search/newcomponent/provider/SearchProvider.kt
|
R-Gang-H
| 538,443,254
| false
| null |
package com.kotlin.android.search.newcomponent.provider
import android.app.Activity
import android.content.Context
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.kotlin.android.router.RouterManager
import com.kotlin.android.app.router.path.RouterActivityPath
import com.kotlin.android.app.router.path.RouterProviderPath
import com.kotlin.android.app.router.provider.search.ISearchProvider
import com.kotlin.android.router.ext.put
import com.kotlin.android.search.newcomponent.Search
import com.kotlin.android.search.newcomponent.Search.KEY_SEARCH_DATA_GROUP
import com.kotlin.android.search.newcomponent.Search.PUBLISH_SEARCH_BUNDLE_KEY_FROM
import com.kotlin.android.search.newcomponent.Search.PUBLISH_SEARCH_BUNDLE_KEY_TYPE
/**
*
* Created on 2020/10/15.
*
* @author o.s
*/
@Route(path = RouterProviderPath.Provider.PROVIDER_SEARCH)
class SearchProvider : ISearchProvider {
override fun startSearchActivity(context: Context?) {
RouterManager.instance.navigation(
path = RouterActivityPath.Search.PAGE_SEARCH_ACTIVITY,
context = context
)
// context?.startActivity(SearchActivity::class.java)
}
/**
* 发布组件-搜索影片/影人
*/
override fun startPublishSearchActivity(activity: Activity?, searchType: Long, from: Long) {
activity?.apply {
val bundle = Bundle()
.put(PUBLISH_SEARCH_BUNDLE_KEY_TYPE, searchType)
.put(PUBLISH_SEARCH_BUNDLE_KEY_FROM, from)
RouterManager.instance.navigation(
context = this,
bundle = bundle,
path = RouterActivityPath.Search.PAGE_PUBLISH_SEARCH_ACTIVITY,
requestCode = Search.SEARCH_REQUEST_CODE
)
}
}
override fun startSearchGroupActivity(activity: Activity?, groupId:Long?) {
activity?.apply {
val bundle = Bundle().put(KEY_SEARCH_DATA_GROUP, groupId)
RouterManager.instance.navigation(
bundle = bundle,
path = RouterActivityPath.Search.PAGE_SEARCH_POST_GROUP_ACTIVITY)
}
}
override fun init(context: Context?) {
}
}
| 0
|
Kotlin
|
0
| 1
|
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
| 2,242
|
Mtime
|
Apache License 2.0
|
app/src/main/java/de/klimek/compass/tile/Tile.kt
|
Tetr4
| 299,129,089
| false
|
{"Kotlin": 8847}
|
package de.klimek.compass.tile
import android.service.quicksettings.Tile
fun Tile.update(applyChanges: Tile.() -> Unit) {
applyChanges()
updateTile()
}
| 1
|
Kotlin
|
0
| 4
|
110b23be85fbd1ad6e0c737b94a945f4d1c3ce91
| 162
|
CompassTile
|
Apache License 2.0
|
app/src/main/java/com/omo/rememberme/presentation/peopleList/PeopleListScreen.kt
|
omer358
| 810,455,324
| false
|
{"Kotlin": 173958}
|
package com.omo.rememberme.presentation.peopleList
import android.content.res.Configuration
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.omo.rememberme.R
import com.omo.rememberme.presentation.common.composables.LoadingStateScreen
import com.omo.rememberme.presentation.common.composables.PeopleListItem
import com.omo.rememberme.presentation.peopleList.composable.EmptyStateScreen
import com.omo.rememberme.ui.theme.RememberMeTheme
private const val TAG = "PeopleListScreen"
@Composable
fun PeopleScreen(
modifier: Modifier = Modifier,
viewModel: PeopleViewModel = hiltViewModel(),
navigateToDetailScreen: (Long) -> Unit,
navigateToAddNewPersonScreen: () -> Unit,
navigateToSettingsScreen: () -> Unit
) {
val state by viewModel.state.collectAsStateWithLifecycle()
PeopleScreenContent(
state,
modifier,
navigateToDetailScreen,
navigateToAddNewPersonScreen,
navigateToSettingsScreen
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PeopleScreenContent(
state: PeopleState,
modifier: Modifier = Modifier,
navigateToDetailScreen: (Long) -> Unit,
navigateToAddNewPersonScreen: () -> Unit,
navigateToSettingsScreen: () -> Unit
) {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(stringResource(id = R.string.app_name))
},
actions = {
IconButton(
onClick = {
navigateToSettingsScreen()
}
) {
Icon(
imageVector = Icons.Default.Settings,
contentDescription = "Add a new Person"
)
}
}
)
},
floatingActionButton = {
FloatingActionButton(
onClick = {
navigateToAddNewPersonScreen()
}
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Add a new Person"
)
}
}
) { it ->
AnimatedContent(
state,
transitionSpec = {
fadeIn(
spring(stiffness = Spring.StiffnessMedium)
) togetherWith
fadeOut(
spring(stiffness = Spring.StiffnessMedium)
)
},
label = "PeopleScreen animatedContent"
) { peopleState ->
if (peopleState.isLoading) {
LoadingStateScreen(modifier = modifier.padding(paddingValues = it))
} else {
if (peopleState.people.isEmpty()) {
EmptyStateScreen(modifier = modifier.padding(paddingValues = it))
} else {
LazyColumn(
modifier = modifier
.padding(it)
.fillMaxSize()
.testTag("PeopleListScreen")
) {
items(count = peopleState.people.size) { index ->
PeopleListItem(peopleState.people[index], { personId ->
navigateToDetailScreen(personId)
})
}
}
}
}
}
}
}
@Preview(showBackground = true)
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PeopleScreenContentPreview() {
RememberMeTheme {
PeopleScreenContent(
state = PeopleState(),
navigateToDetailScreen = {},
navigateToAddNewPersonScreen = {},
navigateToSettingsScreen = {}
)
}
}
| 2
|
Kotlin
|
0
| 0
|
ce1f2c7860d032b35d86a9ff3aff34a79b95d436
| 5,156
|
Remember-Me
|
MIT License
|
app/src/main/java/com/citracafe/food/ui/profile/ProfileContract.kt
|
wahyusantso
| 585,018,816
| false
|
{"Kotlin": 117972}
|
package com.citracafe.food.ui.profile
import android.net.Uri
import com.citracafe.food.data.remote.response.pembeli.Pembeli
import com.citracafe.food.utils.base.Base
import com.citracafe.food.utils.base.BasePresenter
interface ProfileContract {
interface View: Base {
fun updateSuccess(data: Pembeli)
fun updateFoto(url: String)
fun updateProfileFailed(message: String)
}
interface Presenter: ProfileContract, BasePresenter {
fun updateProfile(email: String, alamat: String, no_telpon: String, nama_pembeli: String)
fun updatePhoto(file: Uri?)
}
}
| 0
|
Kotlin
|
0
| 0
|
d783ce6aef7fd031da2eec5b8ff6c8db87d49ae0
| 607
|
CitraCafeMobile
|
MIT License
|
src/main/kotlin/crackers/kobots/buttonboard/buttons/HomeAssistantMenus.kt
|
EAGrahamJr
| 647,347,853
| false
|
{"Kotlin": 61741, "Shell": 2873, "Python": 1684}
|
package crackers.kobots.buttonboard.buttons
import crackers.kobots.app.AppCommon
import crackers.kobots.buttonboard.GraphicsStuff.DARK_CYAN
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_BED
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_BULB
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_EAR
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_EXIT
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_FAN
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_HOTEL
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_KITCHEN
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_LIGHTGROUP
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_MOON
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_MOVIE
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_PRINTER
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_RELAX
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_SKULL
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_SUN
import crackers.kobots.buttonboard.GraphicsStuff.IMAGE_TV
import crackers.kobots.buttonboard.GraphicsStuff.LIGHT_GREEN
import crackers.kobots.buttonboard.TheActions.HassActions
import crackers.kobots.buttonboard.TheActions.MusicPlayActions
import crackers.kobots.parts.GOLDENROD
import crackers.kobots.parts.ORANGISH
import crackers.kobots.parts.PURPLE
import crackers.kobots.parts.app.io.NeoKeyMenu.MenuItem
import java.awt.Color
/**
* Ibid
*/
object HomeAssistantMenus {
val nightOffFunction =
MenuItem("Off", icon = IMAGE_EXIT, buttonColor = GOLDENROD) {
HassActions.NOT_ALL()
MusicPlayActions.STOP()
}
val fanControl =
MenuItem("Fan", icon = IMAGE_FAN, buttonColor = Color.BLUE) {
HassActions.OFFICE_FAN()
with(AppCommon.hasskClient) {
(if (switch("small_fan").state().state == "off") MusicPlayActions.PLAY else MusicPlayActions.STOP)()
}
}
val morningScene =
MenuItem("Morn", icon = IMAGE_SUN, buttonColor = GOLDENROD) {
HassActions.MORNING()
MusicPlayActions.PLAY()
}
val daytimeScene = MenuItem("Day", icon = IMAGE_BULB, buttonColor = Color.GREEN) { HassActions.DAYTIME() }
val kitchenLights = MenuItem("Kit", icon = IMAGE_KITCHEN, buttonColor = Color.CYAN) { HassActions.KITCHEN() }
val tvViewing =
MenuItem("TV", icon = IMAGE_TV, buttonColor = PURPLE) {
HassActions.TV()
MusicPlayActions.STOP()
}
val movieViewing =
MenuItem("Movie", icon = IMAGE_MOVIE, buttonColor = Color.RED.darker()) {
HassActions.MOVIE()
MusicPlayActions.STOP()
}
val printerToggle = MenuItem("Pntr", icon = IMAGE_PRINTER, buttonColor = GOLDENROD) { HassActions.THING_PRINTER() }
val bedtimeScene = MenuItem("BTime", icon = IMAGE_HOTEL, buttonColor = Color.PINK) { HassActions.BEDTIME() }
val lateNightScene = MenuItem("Late", icon = IMAGE_MOON, buttonColor = DARK_CYAN) { HassActions.LATE_NIGHT() }
val tfeScene = MenuItem("TFE", icon = IMAGE_SKULL, buttonColor = Color.RED.darker()) { HassActions.TFE() }
val bedroomToggle = MenuItem("BRm", icon = IMAGE_BED, buttonColor = Color.PINK) { HassActions.BEDROOM() }
val allOn = MenuItem("All", icon = IMAGE_LIGHTGROUP, buttonColor = LIGHT_GREEN) { HassActions.ALL_LIGHTS() }
val whiteNoiseToggle = MenuItem("EAR", icon = IMAGE_EAR, buttonColor = ORANGISH) { MusicPlayActions.TOGGLE() }
val postTVScene = MenuItem("Post", icon = IMAGE_RELAX, buttonColor = Color.YELLOW) { HassActions.POST_TV() }
}
| 0
|
Kotlin
|
0
| 0
|
f0e5807c83ebe2a052c8dc15b9a58fefc77112c4
| 3,615
|
kobots-buttonboard
|
Apache License 2.0
|
player/src/test/java/com/tomasznajda/pulpfiction/util/ExoPlayerExtKtTest.kt
|
tomasznajda
| 141,139,295
| false
|
{"Kotlin": 112181}
|
package com.tomasznajda.pulpfiction.util
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.nhaarman.mockitokotlin2.mock
import com.tomasznajda.pulpfiction.__util.assertEquals
import com.tomasznajda.pulpfiction.entity.PlayerState
import org.junit.Test
class ExoPlayerExtKtTest {
@Test
fun `getPulpFictionState returns IDLE when playback state is IDLE`() {
val exoPlayer = mock<SimpleExoPlayer> { on { playbackState }.thenReturn(Player.STATE_IDLE) }
assertEquals(expected = PlayerState.IDLE, actual = exoPlayer.pulpFictionState)
}
@Test
fun `getPulpFictionState returns BUFFERING when playback state is BUFFERING`() {
val exoPlayer = mock<SimpleExoPlayer> { on { playbackState }.thenReturn(Player.STATE_BUFFERING) }
assertEquals(expected = PlayerState.BUFFERING, actual = exoPlayer.pulpFictionState)
}
@Test
fun `getPulpFictionState returns PLAYING when playback state is READY and playWhenReady is true`() {
val exoPlayer = mock<SimpleExoPlayer> {
on { playbackState }.thenReturn(Player.STATE_READY)
on { playWhenReady }.thenReturn(true)
}
assertEquals(expected = PlayerState.PLAYING, actual = exoPlayer.pulpFictionState)
}
@Test
fun `getPulpFictionState returns PAUSED when playback state is READY and playWhenReady is false`() {
val exoPlayer = mock<SimpleExoPlayer> {
on { playbackState }.thenReturn(Player.STATE_READY)
on { playWhenReady }.thenReturn(false)
}
assertEquals(expected = PlayerState.PAUSED, actual = exoPlayer.pulpFictionState)
}
@Test
fun `getPulpFictionState returns FINISHED when playback state is ENDED`() {
val exoPlayer = mock<SimpleExoPlayer> { on { playbackState }.thenReturn(Player.STATE_ENDED) }
assertEquals(expected = PlayerState.FINISHED, actual = exoPlayer.pulpFictionState)
}
}
| 0
|
Kotlin
|
1
| 4
|
43b4db0659929cff71018be9109eb2f3ff10dbfa
| 1,977
|
pulpfiction
|
Apache License 2.0
|
Manga/app/src/main/java/nhdphuong/com/manga/features/admin/AdminFragment.kt
|
duyphuong5126
| 140,096,962
| false
| null |
package nhdphuong.com.manga.features.admin
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SwitchCompat
import androidx.fragment.app.Fragment
import nhdphuong.com.manga.Constants.Companion.ACTION_TAGS_DOWNLOADING_COMPLETED
import nhdphuong.com.manga.Constants.Companion.ACTION_TAGS_DOWNLOADING_FAILED
import nhdphuong.com.manga.Constants.Companion.ACTION_TAGS_DOWNLOADING_PROGRESS
import nhdphuong.com.manga.Constants.Companion.DOWNLOADED_PAGES
import nhdphuong.com.manga.Constants.Companion.TAGS_DOWNLOADING_RESULT
import nhdphuong.com.manga.Logger
import nhdphuong.com.manga.NHentaiApp
import nhdphuong.com.manga.R
import nhdphuong.com.manga.broadcastreceiver.BroadCastReceiverHelper
import nhdphuong.com.manga.service.TagsDownloadingService
import nhdphuong.com.manga.service.TagsDownloadingService.Companion.TagDownloadingResult
import nhdphuong.com.manga.views.customs.MyButton
import nhdphuong.com.manga.views.customs.MyTextView
import nhdphuong.com.manga.views.showTagDataBeingDownloadedDialog
class AdminFragment : Fragment(), AdminContract.View {
companion object {
private enum class DownloadingSwitch {
Start, Stop
}
}
private val logger: Logger by lazy {
Logger("AdminFragment")
}
private lateinit var mbtStartDownloading: MyButton
private lateinit var mtvArtistsCount: MyTextView
private lateinit var mtvCategoriesCount: MyTextView
private lateinit var mtvCharactersCount: MyTextView
private lateinit var mtvGroupsCount: MyTextView
private lateinit var mtvLanguagesCount: MyTextView
private lateinit var mtvPagesCount: MyTextView
private lateinit var mtvPagesDownloaded: MyTextView
private lateinit var mtvParodiesCount: MyTextView
private lateinit var mtvTagsCount: MyTextView
private lateinit var mtvUnknownTagsCount: MyTextView
private lateinit var spCensored: SwitchCompat
private lateinit var presenter: AdminContract.Presenter
private var currentDownloadingSwitch: DownloadingSwitch = DownloadingSwitch.Start
set(value) {
if (value != field) {
changeDownloadButtonStatus(value)
}
field = value
}
private val tagDownloadingReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
ACTION_TAGS_DOWNLOADING_PROGRESS -> {
val downloadedPages = intent.getIntExtra(DOWNLOADED_PAGES, 0).toLong()
intent.getParcelableExtra<TagDownloadingResult>(TAGS_DOWNLOADING_RESULT)?.let {
updateDownloadingStatistics(
downloadedPages,
it.artists,
it.characters,
it.categories,
it.languages,
it.parodies,
it.groups,
it.tags,
it.unknownTypes
)
}
}
ACTION_TAGS_DOWNLOADING_FAILED -> {
clearAllData()
}
ACTION_TAGS_DOWNLOADING_COMPLETED -> {
clearAllData()
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_admin, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpUI(view)
mtvPagesCount.text = ""
mbtStartDownloading.setOnClickListener {
if (!TagsDownloadingService.isTagBeingDownloaded) {
presenter.startDownloading()
} else {
activity?.showTagDataBeingDownloadedDialog {
TagsDownloadingService.stopCurrentTask()
currentDownloadingSwitch = DownloadingSwitch.Start
}
}
}
clearAllData()
spCensored.isChecked = NHentaiApp.instance.isCensored
spCensored.setOnCheckedChangeListener { _, isChecked ->
presenter.toggleCensored(isChecked)
}
presenter.start()
}
override fun onStart() {
super.onStart()
currentDownloadingSwitch = if (TagsDownloadingService.isTagBeingDownloaded) {
DownloadingSwitch.Stop
} else {
DownloadingSwitch.Start
}
BroadCastReceiverHelper.registerBroadcastReceiver(
context,
tagDownloadingReceiver,
ACTION_TAGS_DOWNLOADING_PROGRESS,
ACTION_TAGS_DOWNLOADING_FAILED,
ACTION_TAGS_DOWNLOADING_COMPLETED
)
}
override fun onStop() {
super.onStop()
BroadCastReceiverHelper.unRegisterBroadcastReceiver(context, tagDownloadingReceiver)
}
override fun setPresenter(presenter: AdminContract.Presenter) {
this.presenter = presenter
}
override fun showNumberOfPages(numOfPages: Long) {
mtvPagesCount.text = getString(R.string.number_of_pages, numOfPages)
}
private fun updateDownloadingStatistics(
downloadedPages: Long,
artists: Int,
characters: Int,
categories: Int,
languages: Int,
parodies: Int,
groups: Int,
tags: Int,
unknownsTypes: Int
) {
val resources = resources
mtvPagesDownloaded.text = resources.getString(R.string.downloaded_pages, downloadedPages)
mtvArtistsCount.text = resources.getString(R.string.number_of_artists, artists)
mtvCharactersCount.text = resources.getString(R.string.number_of_characters, characters)
mtvCategoriesCount.text = resources.getString(R.string.number_of_categories, categories)
mtvLanguagesCount.text = resources.getString(R.string.number_of_languages, languages)
mtvParodiesCount.text = resources.getString(R.string.number_of_parodies, parodies)
mtvGroupsCount.text = resources.getString(R.string.number_of_groups, groups)
mtvTagsCount.text = resources.getString(R.string.number_of_tags, tags)
mtvUnknownTagsCount.text =
resources.getString(R.string.number_of_unknown, unknownsTypes)
}
override fun startDownloadingTagData(numberOfPage: Long) {
currentDownloadingSwitch = DownloadingSwitch.Stop
context?.let {
logger.d("isTagBeingDownloaded=${TagsDownloadingService.isTagBeingDownloaded}")
TagsDownloadingService.start(it, numberOfPage)
}
}
override fun restartApp() {
NHentaiApp.instance.restartApp()
}
override fun showLoading() {
}
override fun hideLoading() {
}
override fun isActive(): Boolean = isAdded
private fun setUpUI(rootView: View) {
mbtStartDownloading = rootView.findViewById(R.id.mbt_start_downloading)
mtvArtistsCount = rootView.findViewById(R.id.mtv_artists_count)
mtvCategoriesCount = rootView.findViewById(R.id.mtv_categories_count)
mtvCharactersCount = rootView.findViewById(R.id.mtv_characters_count)
mtvGroupsCount = rootView.findViewById(R.id.mtv_groups_count)
mtvLanguagesCount = rootView.findViewById(R.id.mtv_languages_count)
mtvPagesCount = rootView.findViewById(R.id.mtv_pages_count)
mtvPagesDownloaded = rootView.findViewById(R.id.mtv_pages_downloaded)
mtvParodiesCount = rootView.findViewById(R.id.mtv_parodies_count)
mtvTagsCount = rootView.findViewById(R.id.mtv_tags_count)
mtvUnknownTagsCount = rootView.findViewById(R.id.mtv_unknown_tags_count)
spCensored = rootView.findViewById(R.id.sp_censored)
}
private fun clearAllData() {
mtvPagesDownloaded.text = ""
mtvArtistsCount.text = ""
mtvCharactersCount.text = ""
mtvCategoriesCount.text = ""
mtvLanguagesCount.text = ""
mtvParodiesCount.text = ""
mtvGroupsCount.text = ""
mtvTagsCount.text = ""
mtvUnknownTagsCount.text = ""
}
private fun changeDownloadButtonStatus(newStatus: DownloadingSwitch) {
logger.d("currentDownloadingSwitch=$newStatus")
mbtStartDownloading.text = getString(
if (newStatus == DownloadingSwitch.Start) {
R.string.start_downloading
} else {
R.string.stop_downloading
}
)
}
}
| 4
|
Kotlin
|
0
| 3
|
df34a0edefaae077ec4c3b89ee693fc56a3e67fe
| 8,866
|
H-Manga
|
Apache License 2.0
|
app/src/main/java/com/sdex/activityrunner/ActivityManagerApplication.kt
|
sdex
| 278,636,044
| false
|
{"Kotlin": 215846, "JavaScript": 84722, "Java": 42728, "HTML": 6278}
|
package com.sdex.activityrunner
import android.app.Application
import android.content.Context
import android.content.pm.ApplicationInfo
import androidx.appcompat.app.AppCompatDelegate
import androidx.multidex.MultiDex
import com.sdex.activityrunner.preferences.AppPreferences
import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber
import javax.inject.Inject
@HiltAndroidApp
class ActivityManagerApplication : Application() {
@Inject
lateinit var appPreferences: AppPreferences
override fun onCreate() {
super.onCreate()
if (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) {
Timber.plant(Timber.DebugTree())
}
appPreferences.onAppOpened()
AppCompatDelegate.setDefaultNightMode(appPreferences.theme)
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this)
}
}
| 11
|
Kotlin
|
35
| 583
|
eb68f7a6a10ea61a92f72673c9577d335837e219
| 930
|
ActivityManager
|
Apache License 2.0
|
bukkit/rpk-skills-bukkit/src/main/kotlin/com/rpkit/skills/bukkit/command/SkillCommand.kt
|
blimyj
| 363,192,865
| true
|
{"Kotlin": 2999538}
|
/*
* 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.rpkit.skills.bukkit.command
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.skills.bukkit.RPKSkillsBukkit
import com.rpkit.skills.bukkit.skills.RPKSkillName
import com.rpkit.skills.bukkit.skills.RPKSkillService
import com.rpkit.skills.bukkit.skills.canUse
import com.rpkit.skills.bukkit.skills.use
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class SkillCommand(private val plugin: RPKSkillsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.skills.command.skill")) {
sender.sendMessage(plugin.messages["no-permission-skill"])
return true
}
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val skillService = Services[RPKSkillService::class.java]
if (skillService == null) {
sender.sendMessage(plugin.messages["no-skill-service"])
return true
}
val minecraftProfile = minecraftProfileService.getMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val character = characterService.getActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages["no-character"])
return true
}
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["skill-list-title"])
skillService.skills
.filter { skill -> character.canUse(skill) }
.forEach { skill ->
sender.sendMessage(plugin.messages["skill-list-item", mapOf(
"skill" to skill.name.value
)])
}
return true
}
val skill = skillService.getSkill(RPKSkillName(args[0]))
if (skill != null) {
if (character.canUse(skill)) {
if (character.mana >= skill.manaCost) {
if (skillService.getSkillCooldown(character, skill) <= 0) {
character.use(skill)
skillService.setSkillCooldown(character, skill, skill.cooldown)
character.mana -= skill.manaCost
characterService.updateCharacter(character)
sender.sendMessage(plugin.messages["skill-valid", mapOf(
"skill" to skill.name.value
)])
} else {
sender.sendMessage(plugin.messages["skill-invalid-on-cooldown", mapOf(
"skill" to skill.name.value,
"cooldown" to skillService.getSkillCooldown(character, skill).toString()
)])
}
} else {
sender.sendMessage(plugin.messages["skill-invalid-not-enough-mana", mapOf(
"skill" to skill.name.value,
"mana_cost" to skill.manaCost.toString(),
"mana" to character.mana.toString(),
"max_mana" to character.maxMana.toString()
)])
}
} else {
sender.sendMessage(plugin.messages["skill-invalid-unmet-prerequisites", mapOf(
"skill" to skill.name.value
)])
}
} else {
sender.sendMessage(plugin.messages["skill-invalid-skill"])
}
return true
}
}
| 0
| null |
0
| 0
|
b6f6e90fe466309a97f5620f4c5508df3131154d
| 5,031
|
RPKit
|
Apache License 2.0
|
billMan/src/main/kotlin/com/weesnerdevelopment/billman/bill/occurrence/BillOccurrenceSharedUsersTable.kt
|
adamWeesner
| 239,233,558
| false
| null |
package com.weesnerdevelopment.billman.bill.occurrence
import com.weesnerdevelopment.businessRules.tryTransaction
import org.jetbrains.exposed.dao.id.UUIDTable
import org.jetbrains.exposed.sql.ReferenceOption
object BillOccurrenceSharedUsersTable : UUIDTable() {
val user = varchar("owner", 36)
val occurrence = reference("occurrence", BillOccurrenceTable, ReferenceOption.CASCADE)
fun <T> action(event: BillOccurrenceSharedUsersTable.() -> T) = tryTransaction(event)
}
| 1
|
Kotlin
|
1
| 1
|
c7962e6ccec3b8b327886a3b35e2e17d16449c34
| 484
|
weesnerDevelopment
|
MIT License
|
app/src/androidTest/java/com/zm/org/wallet/di/FakeDatabaseModule.kt
|
zeinabmohamed
| 454,303,737
| false
| null |
package com.zm.org.wallet.di
import android.content.Context
import androidx.room.Room
import com.zm.org.wallet.data.database.AppDatabase
import com.zm.org.wallet.data.database.TransactionsDao
import dagger.Module
import dagger.Provides
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import dagger.hilt.testing.TestInstallIn
import javax.inject.Singleton
@Module
@TestInstallIn(components = [SingletonComponent::class], replaces = [DatabaseModule::class])
object FakeDatabaseModule {
@Provides
fun provideTransactionsDao(database: AppDatabase): TransactionsDao {
return database.transactionsDao()
}
@Provides
@Singleton
fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase {
return Room.inMemoryDatabaseBuilder(
appContext, AppDatabase::class.java
).allowMainThreadQueries().build()
}
}
| 0
|
Kotlin
|
0
| 0
|
84a9765a184346c58a234fbe019cc89dd8442bc6
| 934
|
Wallet
|
BSD Source Code Attribution
|
klaxon/src/main/kotlin/com/beust/klaxon/JsonReader.kt
|
SonOfLilit
| 153,126,061
| true
|
{"Kotlin": 169255, "Batchfile": 126, "Java": 108, "Shell": 99}
|
package com.beust.klaxon
import java.io.Reader
import java.math.BigInteger
/**
* Manages JSON streaming.
*/
class JsonReader(val reader: Reader) : Reader() {
/**
* @return the next String.
* @throws JsonParsingException the next value is not a String.
*/
fun nextString() = consumeValue { value ->
value as? String ?: throw JsonParsingException("Next token is not a string: $value")
}
/**
* @return the next Int.
* @throws JsonParsingException the next value is not an Int.
*/
fun nextInt() = consumeValue { value ->
value as? Int ?: throw JsonParsingException("Next token is not a int: $value")
}
/**
* @return the next Long (upscaling as needed).
* @throws JsonParsingException the next value is not an Long.
*/
fun nextLong() = consumeValue { value ->
when (value) {
is Int -> value.toLong()
is Long -> value
else -> throw JsonParsingException("Next token is not a long: $value")
}
}
/**
* @return the next BigInteger (upscaling as needed).
* @throws JsonParsingException the next value is not an BigInteger.
*/
fun nextBigInteger() = consumeValue { value ->
when (value) {
is Int -> BigInteger.valueOf(value.toLong())
is Long -> BigInteger.valueOf(value)
is BigInteger -> value
else -> throw JsonParsingException("Next token is not a big integer: $value")
}
}
/**
* @return the next Double (upscaling as needed).
* @throws JsonParsingException the next value is not a Double.
*/
fun nextDouble() = consumeValue { value ->
when (value) {
is Int -> value.toDouble()
is Double -> value
else -> throw JsonParsingException("Next token is not a double: $value")
}
}
/**
* @return the next boolean.
* @throws JsonParsingException the next value is not a Boolean.
*/
fun nextBoolean() = consumeValue { value ->
value as? Boolean ?: throw JsonParsingException("Next token is not a boolean: $value")
}
/**
* @return the next object, making sure the current token is an open brace and the last token is a closing brace.
*/
fun nextObject() : JsonObject {
return beginObject {
JsonObject().let { result ->
while (hasNext()) {
val name = nextName()
val value = consumeValue { value -> value }
result[name] = value
}
result
}
}
}
/**
* @return the next array, making sure the current token is an open bracket and the last token is a closing bracket.
*/
fun nextArray() : List<Any> {
return beginArray {
arrayListOf<Any>().let { result ->
while (hasNext()) {
val v = consumeValue { value -> value }
if (v != null) {
result.add(v)
} else {
throw KlaxonException("Couldn't parse")
}
}
result
}
}
}
/**
* @return the next name (the string left of a colon character).
*/
fun nextName(): String {
skip()
val next = lexer.nextToken()
if (next.tokenType == TokenType.VALUE) {
return next.value.toString()
} else {
throw KlaxonException("Expected a name but got $next")
}
}
/**
* Make sure that the next token is the beginning of an object (open brace),
* consume it, run the closure and then make sure the object is closed (closed brace).
*/
fun <T> beginObject(closure: () -> T) : T {
skip()
privateBeginObject()
val result = closure()
privateEndObject()
return result
}
/**
* Makes sure that the next token is the beginning of an array (open bracket),
* consume it, run the closure and then make sure the array is closed (closed bracket).
*/
fun <T> beginArray(closure: () -> T) : T {
skip()
privateBeginArray()
val result = closure()
privateEndArray()
return result
}
/**
* @return true if this reader has more tokens to read before finishing the current object/array.
*/
fun hasNext(): Boolean = lexer.peek().tokenType.let { it != TokenType.RIGHT_BRACKET && it != TokenType.RIGHT_BRACE }
override fun close() {
reader.close()
}
override fun read(cbuf: CharArray?, off: Int, len: Int): Int {
return reader.read(cbuf, off, len)
}
val lexer = Lexer(reader)
private fun consumeToken(type: TokenType, expected: String) {
val next = lexer.nextToken()
if (next.tokenType != type) {
throw KlaxonException("Expected a $expected but read $next")
}
}
private fun privateBeginArray() = consumeToken(TokenType.LEFT_BRACKET, "[")
private fun privateEndArray() = consumeToken(TokenType.RIGHT_BRACKET, "]")
private fun privateBeginObject() = consumeToken(TokenType.LEFT_BRACE, "{")
private fun privateEndObject() = consumeToken(TokenType.RIGHT_BRACE, "}")
private val SKIPS = setOf(TokenType.COLON, TokenType.COMMA)
private fun skip() {
while (SKIPS.contains(lexer.peek().tokenType)) lexer.nextToken()
}
private fun <T> consumeValue(convert: (Any?) -> T): T {
skip()
val next = lexer.nextToken()
if (next.tokenType == TokenType.VALUE) {
return convert(next.value)
} else {
throw KlaxonException("Expected a name but got $next")
}
}
}
| 0
|
Kotlin
|
0
| 1
|
5d134335e1838ff22116e15cecfcaf373f18d34d
| 5,817
|
klaxon
|
Apache License 2.0
|
app/src/internal/java/com/duckduckgo/app/dev/settings/DevSettingsActivity.kt
|
duckduckgo
| 78,869,127
| false
|
{"Kotlin": 10196531, "HTML": 63669, "Ruby": 14445, "JavaScript": 8385, "C++": 1813, "CMake": 1286, "Shell": 784}
|
/*
* Copyright (c) 2021 DuckDuckGo
*
* 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.duckduckgo.app.dev.settings
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.CompoundButton.OnCheckedChangeListener
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.duckduckgo.anvil.annotations.InjectWith
import com.duckduckgo.app.browser.BrowserActivity
import com.duckduckgo.app.browser.R
import com.duckduckgo.app.browser.databinding.ActivityDevSettingsBinding
import com.duckduckgo.app.dev.settings.DevSettingsViewModel.Command
import com.duckduckgo.app.dev.settings.db.UAOverride
import com.duckduckgo.app.dev.settings.privacy.TrackerDataDevReceiver.Companion.DOWNLOAD_TDS_INTENT_ACTION
import com.duckduckgo.app.global.DuckDuckGoActivity
import com.duckduckgo.di.scopes.ActivityScope
import com.duckduckgo.mobile.android.ui.menu.PopupMenu
import com.duckduckgo.mobile.android.ui.viewbinding.viewBinding
import com.duckduckgo.privacy.config.internal.PrivacyConfigInternalSettingsActivity
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@InjectWith(ActivityScope::class)
class DevSettingsActivity : DuckDuckGoActivity() {
private val binding: ActivityDevSettingsBinding by viewBinding()
private val viewModel: DevSettingsViewModel by bindViewModel()
private val nextTdsToggleListener = OnCheckedChangeListener { _, isChecked ->
viewModel.onNextTdsToggled(isChecked)
}
private val startupTraceToggleListener = OnCheckedChangeListener { _, isChecked ->
viewModel.onStartupTraceToggled(isChecked)
}
private val overrideUAListener = OnCheckedChangeListener { _, isChecked ->
viewModel.onOverrideUAToggled(isChecked)
}
private val surveySandboxListener = OnCheckedChangeListener { _, isChecked ->
viewModel.onSandboxSurveyToggled(isChecked)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupToolbar(binding.includeToolbar.toolbar)
configureUiEventHandlers()
observeViewModel()
}
override fun onStart() {
super.onStart()
viewModel.start()
}
private fun configureUiEventHandlers() {
binding.triggerAnr.setOnClickListener {
Handler(Looper.getMainLooper()).post {
Thread.sleep(10000)
}
}
binding.clearSavedSites.setOnClickListener {
viewModel.clearSavedSites()
}
binding.overrideUserAgentSelector.setOnClickListener { viewModel.onUserAgentSelectorClicked() }
binding.overridePrivacyRemoteConfigUrl.setOnClickListener { viewModel.onRemotePrivacyUrlClicked() }
}
private fun observeViewModel() {
viewModel.viewState()
.flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
.onEach { viewState ->
viewState.let {
binding.nextTdsEnabled.quietlySetIsChecked(it.nextTdsEnabled, nextTdsToggleListener)
binding.enableAppStartupTrace.quietlySetIsChecked(it.startupTraceEnabled, startupTraceToggleListener)
binding.overrideUserAgentToggle.quietlySetIsChecked(it.overrideUA, overrideUAListener)
binding.overrideUserAgentSelector.isEnabled = it.overrideUA
binding.overrideUserAgentSelector.setSecondaryText(it.userAgent)
binding.useSandboxSurvey.quietlySetIsChecked(it.useSandboxSurvey, surveySandboxListener)
}
}.launchIn(lifecycleScope)
viewModel.commands()
.flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
.onEach { processCommand(it) }
.launchIn(lifecycleScope)
}
private fun processCommand(it: Command?) {
when (it) {
is Command.SendTdsIntent -> sendTdsIntent()
is Command.OpenUASelector -> showUASelector()
is Command.ShowSavedSitesClearedConfirmation -> showSavedSitesClearedConfirmation()
is Command.ChangePrivacyConfigUrl -> showChangePrivacyUrl()
else -> TODO()
}
}
private fun goToUrl(url: String) {
startActivity(BrowserActivity.intent(this, url))
finish()
}
private fun sendTdsIntent() {
Toast.makeText(this, getString(R.string.devSettingsScreenTdsWait), Toast.LENGTH_SHORT).show()
val intent = Intent()
intent.action = DOWNLOAD_TDS_INTENT_ACTION
sendBroadcast(intent)
}
private fun showUASelector() {
val popup = PopupMenu(layoutInflater, R.layout.popup_window_user_agent_override)
val view = popup.contentView
popup.apply {
onMenuItemClicked(view.findViewById(R.id.noAppId)) { viewModel.onUserAgentSelected(UAOverride.NO_APP_ID) }
onMenuItemClicked(view.findViewById(R.id.noVersion)) { viewModel.onUserAgentSelected(UAOverride.NO_VERSION) }
onMenuItemClicked(view.findViewById(R.id.chrome)) { viewModel.onUserAgentSelected(UAOverride.CHROME) }
onMenuItemClicked(view.findViewById(R.id.firefox)) { viewModel.onUserAgentSelected(UAOverride.FIREFOX) }
onMenuItemClicked(view.findViewById(R.id.duckDuckGo)) { viewModel.onUserAgentSelected(UAOverride.DDG) }
onMenuItemClicked(view.findViewById(R.id.webView)) { viewModel.onUserAgentSelected(UAOverride.WEBVIEW) }
}
popup.show(binding.root, binding.overrideUserAgentSelector)
}
private fun showSavedSitesClearedConfirmation() {
Toast.makeText(this, getString(R.string.devSettingsClearSavedSitesConfirmation), Toast.LENGTH_SHORT).show()
}
private fun showChangePrivacyUrl() {
val options = ActivityOptions.makeSceneTransitionAnimation(this).toBundle()
startActivity(PrivacyConfigInternalSettingsActivity.intent(this), options)
}
companion object {
fun intent(context: Context): Intent {
return Intent(context, DevSettingsActivity::class.java)
}
}
}
| 62
|
Kotlin
|
868
| 3,302
|
9b7fda539c6d1c323a7cd5542767c4c492e628c8
| 6,832
|
Android
|
Apache License 2.0
|
app/src/androidTest/java/com/cmgapps/android/compomaeon/TodoActivityShould.kt
|
chrimaeon
| 345,084,242
| false
| null |
/*
* Copyright (c) 2021. <NAME> <<EMAIL>>
*
* 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.cmgapps.android.compomaeon
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.filter
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onChildren
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.onRoot
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import androidx.compose.ui.test.printToLog
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(AndroidJUnit4::class)
@HiltAndroidTest
@LargeTest
class TodoActivityShould {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@get:Rule
val composeTestRule = createAndroidComposeRule<TodoActivity>()
@Test
fun addAutoItem() {
composeTestRule.onNodeWithTag("AddTodoFAB").assertIsDisplayed().performClick()
composeTestRule.onNodeWithTag("TodoList").onChildren().assertCountEquals(1)
}
@Test
fun addCustomItems() {
val addButtonText = composeTestRule.activity.getString(R.string.add)
composeTestRule.onNodeWithTag("TodoItemInput").assertIsDisplayed()
.performTextInput("Test Todo")
composeTestRule.onNodeWithText(addButtonText).assertIsDisplayed().performClick()
composeTestRule.onNodeWithTag("TodoItemInput").assertIsDisplayed()
.performTextInput("Test Todo 2")
composeTestRule.onNodeWithText(addButtonText).assertIsDisplayed().performClick()
composeTestRule.onRoot().printToLog(TodoActivityShould::class.java.simpleName)
composeTestRule.onNodeWithTag("TodoList").onChildren().assertCountEquals(2)
.filter(hasText("Test Todo"))[0].assertIsDisplayed()
}
}
| 0
|
Kotlin
|
0
| 0
|
b7b5639071e2ced777f3763c6b219720d2d1fa1b
| 2,779
|
compomaeon
|
Apache License 2.0
|
src/main/java/io/dotanuki/burster/burst8.kt
|
ubiratansoares
| 144,885,208
| false
| null |
package io.dotanuki.burster
fun <A, B, C, D, E, F, G, H> using(block: Buster8<A, B, C, D, E, F, G, H>.() -> Unit) =
Buster8<A, B, C, D, E, F, G, H>().apply { block() }.execute()
class Buster8<A, B, C, D, E, F, G, H> {
private val container by lazy { Bullets8<A, B, C, D, E, F, G, H>() }
private var target: ((A, B, C, D, E, F, G, H) -> Unit)? = null
fun burst(block: Bullets8<A, B, C, D, E, F, G, H>.() -> Unit) {
container.apply { block() }
}
fun thenWith(assertion: (A, B, C, D, E, F, G, H) -> Unit) {
target = assertion
}
internal fun execute() = with(container.bullets) {
if (isEmpty()) throw BursterError.NoValues
forEach {
target
?.invoke(it.a, it.b, it.c, it.d, it.e, it.f, it.g, it.h)
?: throw BursterError.NoTarget
}
}
}
class Bullets8<A, B, C, D, E, F, G, H> {
internal val bullets = mutableListOf<T8<A, B, C, D, E, F, G, H>>()
fun values(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H) {
bullets += T8(a, b, c, d, e, f, g, h)
}
}
| 0
|
Kotlin
|
0
| 1
|
35c8d22b3ae8b4a357cbb33c2d3b0d3ec3f09cf3
| 1,089
|
burster
|
MIT License
|
vector/src/main/java/im/vector/app/JgPushHelper.kt
|
John-Tonny
| 420,860,089
| true
| null |
/*
* Copyright (c) 2021 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.app
import android.app.Activity
import android.content.Context
import android.widget.Toast
import androidx.core.content.edit
import cn.jpush.android.api.JPushInterface
import im.vector.app.R
import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.core.di.DefaultSharedPreferences
import im.vector.app.core.pushers.PushersManager
import im.vector.app.features.settings.VectorPreferences
import timber.log.Timber
/**
* This class store the FCM token in SharedPrefs and ensure this token is retrieved.
* It has an alter ego in the fdroid variant.
*/
object JgPushHelper {
private val PREFS_KEY_JPUSH_TOKEN = "JPUSH_TOKEN"
fun isPushSupported(): Boolean = true
/**
* Retrieves the FCM registration token.
*
* @return the FCM token or null if not received from FCM
*/
fun getFcmToken(context: Context): String? {
return DefaultSharedPreferences.getInstance(context).getString(PREFS_KEY_JPUSH_TOKEN, null)
}
/**
* Store FCM token to the SharedPrefs
* TODO Store in realm
*
* @param context android context
* @param token the token to store
*/
fun storeFcmToken(context: Context,
token: String?) {
DefaultSharedPreferences.getInstance(context).edit {
putString(PREFS_KEY_JPUSH_TOKEN, token)
}
}
/**
* onNewToken may not be called on application upgrade, so ensure my shared pref is set
*
* @param activity the first launch Activity
*/
fun ensureFcmTokenIsRetrieved(activity: Activity, pushersManager: PushersManager, registerPusher: Boolean) {
// if (TextUtils.isEmpty(getFcmToken(activity))) {
// 'app should always check the device for a compatible Google Play services APK before accessing Google Play services features'
var token = JPushInterface.getRegistrationID(activity.applicationContext)
if(token != null) {
JgPushHelper.storeFcmToken(activity, token)
if (registerPusher) {
pushersManager.enqueueRegisterPusherWithFcmKey(token)
}
}
}
@Suppress("UNUSED_PARAMETER")
fun onEnterForeground(context: Context, activeSessionHolder: ActiveSessionHolder) {
// No op
}
@Suppress("UNUSED_PARAMETER")
fun onEnterBackground(context: Context, vectorPreferences: VectorPreferences, activeSessionHolder: ActiveSessionHolder) {
// TODO FCM fallback
}
}
| 0
|
Kotlin
|
0
| 0
|
7b05bf06e64b740b3fdf8839aa97ec191aaa90e7
| 3,101
|
Lianchat-android
|
Apache License 2.0
|
app/shared/analytics/public/src/commonMain/kotlin/build/wallet/analytics/events/EventTracker.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
|
package build.wallet.analytics.events
import build.wallet.analytics.events.screen.EventTrackerCountInfo
import build.wallet.analytics.events.screen.EventTrackerFingerprintScanStatsInfo
import build.wallet.analytics.events.screen.EventTrackerScreenInfo
import build.wallet.analytics.v1.Action
/**
* Allows to record analytics events.
*/
interface EventTracker {
/**
* Sends analytics event
*/
fun track(
action: Action,
context: EventTrackerContext? = null,
)
/**
* Sends ACTION_APP_COUNT analytics event with the given screen info
*/
fun track(eventTrackerCountInfo: EventTrackerCountInfo)
/**
* Sends ACTION_APP_SCREEN_IMPRESSION analytics event with the given screen info
*/
fun track(eventTrackerScreenInfo: EventTrackerScreenInfo)
/**
* Sends ACTION_HW_FINGERPRINT_SCAN_STATS.
*/
fun track(eventTrackerFingerprintScanStatsInfo: EventTrackerFingerprintScanStatsInfo)
}
| 3
|
C
|
16
| 113
|
694c152387c1fdb2b6be01ba35e0a9c092a81879
| 929
|
bitkey
|
MIT License
|
app/src/main/kotlin/com/tezov/lib/adapterJavaToKotlin/toolbox/Nullify.kt
|
tezov
| 640,329,100
| false
| null |
package com.tezov.lib.adapterJavaToKotlin.toolbox
import com.tezov.lib_java.toolbox.Nullify
object Nullify {
fun String?.nullify():String?{
return Nullify.string(this)
}
fun CharSequence?.nullify():String?{
return Nullify.string(this)
}
fun <K, V, M: Map<K, V>> M?.nullify():M?{
return Nullify.map(this)
}
fun <T> Collection<T>?.nullify():Collection<T>?{
return Nullify.collection(this)
}
fun ByteArray?.nullify():ByteArray?{
return Nullify.array(this)
}
fun CharArray?.nullify():CharArray?{
return Nullify.array(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
02d5d2125f6211e94410cda57af23469a4fa3a33
| 624
|
gofo
|
MIT License
|
app/src/main/java/br/com/movieapp/movie_detail_feature/data/source/MovieDetailRemoteDataSourceImpl.kt
|
DiegoSCastro
| 837,686,220
| false
|
{"Kotlin": 97072}
|
package br.com.movieapp.movie_detail_feature.data.source
import br.com.movieapp.core.data.remote.MovieService
import br.com.movieapp.core.data.remote.response.MovieDetailResponse
import br.com.movieapp.core.data.remote.response.MovieResponse
import br.com.movieapp.core.domain.model.MovieDetails
import br.com.movieapp.core.paging.MovieSimilarPagingSource
import br.com.movieapp.core.util.toBackdropUrl
import br.com.movieapp.movie_detail_feature.domain.source.MovieDetailRemoteDataSource
import javax.inject.Inject
class MovieDetailRemoteDataSourceImpl @Inject constructor(private val service: MovieService) :
MovieDetailRemoteDataSource {
override suspend fun getMovieDetail(movieId: Int): MovieDetails {
val response: MovieDetailResponse = service.getMovie(movieId = movieId)
val genres: List<String> = response.genres.map { it.name }
return MovieDetails(
id = response.id,
title = response.title,
overview = response.overview,
genres = genres,
releaseDate = response.releaseDate,
backdropPathUrl = response.backdropPath.toBackdropUrl(),
voteAverage = response.voteAverage,
duration = response.runtime,
voteCount = response.voteCount,
)
}
override suspend fun getMoviesSimilar(page: Int, movieId: Int): MovieResponse {
return service.getMoviesSimilar(page = page, movieId = movieId)
}
override fun getSimilarMoviesPagingSource(movieId: Int): MovieSimilarPagingSource {
return MovieSimilarPagingSource(this, movieId = movieId)
}
}
| 0
|
Kotlin
|
0
| 0
|
28802cd0873ebf69743e6031efbd22145101eede
| 1,620
|
MovieApp
|
MIT License
|
plugins/plugin-sandbox/testData/box/inlineableFunctionMultiModules2.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}
|
// DUMP_IR
// MODULE: lib
// FILE: p3/foo.kt
package p3;
import org.jetbrains.kotlin.plugin.sandbox.MyInlineable
fun setContent(content: @MyInlineable () -> Unit): Int {
content()
return 3
}
// MODULE: main(lib)
// FILE: main.kt
import org.jetbrains.kotlin.plugin.sandbox.MyInlineable
import p3.setContent
fun test(): Int {
return setContent {
Greeting("test")
}
}
@MyInlineable
fun Greeting(name: String) {
show("hi $name!")
}
fun show(str: String) {}
fun box(): String = "OK"
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 516
|
kotlin
|
Apache License 2.0
|
ktor-client/ktor-client-java/jvm/test/io/ktor/client/engine/java/JavaClientTest.kt
|
ktorio
| 40,136,600
| false
|
{"Kotlin": 6007831, "C": 453568, "Python": 948, "JavaScript": 775, "HTML": 336, "Mustache": 77, "Handlebars": 9}
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.java
import io.ktor.client.tests.*
class JavaClientTest : HttpClientTest(Java)
| 156
|
Kotlin
|
1051
| 12,926
|
f90f2edf11caca28a61dbe9973faae64c17a2842
| 237
|
ktor
|
Apache License 2.0
|
src/main/kotlin/org/yelog/ideavim/flash/Actions.kt
|
yelog
| 701,944,029
| false
|
{"Kotlin": 27610}
|
package org.yelog.ideavim.flash
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
abstract class BaseAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val editor = e.getData(CommonDataKeys.EDITOR)
e.presentation.isEnabled = editor != null
}
override fun actionPerformed(e: AnActionEvent) {
JumpHandler.start(getMode(), e)
}
abstract fun getMode(): Int
override fun getActionUpdateThread(): ActionUpdateThread {
// Select the appropriate thread type as needed; EDT is typically used for UI-related operations.
return ActionUpdateThread.EDT
}
}
class SearchAction : BaseAction() {
override fun getMode() = JumpHandler.MODE_CHAR1
}
class GotoRecent : BaseAction() {
override fun getMode() = JumpHandler.MODE_CHAR2
}
| 0
|
Kotlin
|
1
| 9
|
df5825d91264096c39398bbc81619375aea91754
| 988
|
vim-flash
|
Apache License 2.0
|
src/main/kotlin/org/jetbrains/lama/psi/impl/LamaFunctionDefinitionBase.kt
|
Mervap
| 457,621,178
| false
|
{"Kotlin": 200465, "Lex": 4986, "HTML": 613}
|
package org.jetbrains.lama.psi.impl
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.stubs.IStubElementType
import org.jetbrains.lama.psi.stubs.LamaFunctionDefinitionStub
abstract class LamaFunctionDefinitionBase : LamaControlFlowHolderImpl<LamaFunctionDefinitionStub>, PsiNameIdentifierOwner {
constructor(node: ASTNode) : super(node)
constructor(stub: LamaFunctionDefinitionStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
}
| 7
|
Kotlin
|
0
| 7
|
25e559d408a8f31fe1dfa8fcadd992da4eb00f44
| 502
|
LamaPlugin
|
MIT License
|
src/main/kotlin/xyz/malkki/tallinkgtfsscraper/tallinkapi/model/Trip.kt
|
mjaakko
| 651,882,672
| false
|
{"Kotlin": 25601}
|
package xyz.malkki.tallinkgtfsscraper.tallinkapi.model
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import xyz.malkki.tallinkgtfsscraper.constants.pierTimezones
import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
@JsonIgnoreProperties(ignoreUnknown = true)
data class Trip(
val arrivalIsoDate: LocalDateTime, //Arrival time and departure time are always LOCAL time
val departureIsoDate: LocalDateTime,
val shipCode: String,
val cityFrom: String,
val cityTo: String,
val pierFrom: String,
val pierTo: String
) {
companion object {
fun List<Trip>.isContinuousVoyage(): Boolean {
var prevTo = first().pierTo
var prevArrival = first().arrivalTime
forEachIndexed { index, trip ->
if (index > 0) {
if (trip.pierFrom == prevTo && trip.departureTime >= prevArrival) {
prevTo = trip.pierTo
prevArrival = trip.arrivalTime
} else {
return false
}
}
}
return map { it.shipCode }.distinct().size == 1
}
fun List<Trip>.createVoyage(): List<Trip> {
if (size > 1) {
subList(1, size - 1).forEach {
if (!first().isSameVoyage(it)) {
throw IllegalArgumentException("Trips must be from same voyage to build a trip set")
}
}
}
val setOfTrips = toMutableSet()
val sorted = mutableListOf<Trip>()
val first = setOfTrips.minWithOrNull { first, second ->
val byDepartureTime = first.departureTime.compareTo(second.departureTime)
if (byDepartureTime == 0) {
first.departureTime
.until(first.arrivalTime, ChronoUnit.MINUTES)
.compareTo(
second.departureTime
.until(second.arrivalTime, ChronoUnit.MINUTES)
)
} else {
byDepartureTime
}
}!!
sorted.add(first)
setOfTrips.remove(first)
while (sorted.size < size - 1) {
val last = sorted.last()
val nextTrip = setOfTrips.filter { it.departureTime >= last.arrivalTime }.minByOrNull { last.arrivalTime.until(it.departureTime, ChronoUnit.MINUTES) }!!
sorted.add(nextTrip)
setOfTrips.remove(nextTrip)
}
return sorted
}
}
val arrivalTime: ZonedDateTime = arrivalIsoDate.atZone(pierTimezones[pierTo])
val departureTime: ZonedDateTime = departureIsoDate.atZone(pierTimezones[pierFrom])
/**
* Returns true if these trips are part of the same voyage (e.g. Tallinn - Stockholm and Tallinn - Mariehamn)
*/
fun isSameVoyage(other: Trip): Boolean = ((departureIsoDate == other.departureIsoDate && pierFrom == other.pierFrom) || (arrivalIsoDate == other.arrivalIsoDate && pierTo == other.pierTo)) && shipCode == other.shipCode
}
| 0
|
Kotlin
|
0
| 0
|
b719ead98f345ca8172e06342925048e9072b758
| 3,253
|
tallink-gtfs-scraper
|
MIT License
|
drawable/src/main/java/com/angcyo/drawable/base/CombineDrawable.kt
|
angcyo
| 229,037,615
| false
|
{"Kotlin": 6722659, "JavaScript": 5194}
|
package com.angcyo.drawable.base
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.widget.LinearLayout
import com.angcyo.library.ex.dpi
import com.angcyo.library.ex.size
import kotlin.math.max
import kotlin.math.min
/**
* 结合多个[Drawable]
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2023/07/29
*/
class CombineDrawable(val drawableList: MutableList<Drawable> = mutableListOf()) : BaseDrawable() {
/**组合的方向*/
var orientation: Int = LinearLayout.HORIZONTAL
/**间隙*/
var margin: Int = 2 * dpi
fun addDrawable(drawable: Drawable?) {
drawable ?: return
drawableList.add(drawable)
}
fun removeDrawable(drawable: Drawable?) {
drawable ?: return
drawableList.remove(drawable)
}
override fun getIntrinsicWidth(): Int {
var width = -1
if (orientation == LinearLayout.VERTICAL) {
drawableList.forEach {
width = max(width, it.minimumWidth)
}
} else {
drawableList.forEach {
width += it.minimumWidth
}
width += margin * max(0, drawableList.size() - 1)
}
return width
}
override fun getIntrinsicHeight(): Int {
var height = -1
if (orientation == LinearLayout.VERTICAL) {
drawableList.forEach {
height += it.minimumHeight
}
height += margin * max(0, drawableList.size() - 1)
} else {
drawableList.forEach {
height = max(height, it.minimumHeight)
}
}
return height
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
var left = bounds.left
var top = bounds.top
val size = min(bounds.width(), bounds.height())
drawableList.forEach {
val w = min(size, it.minimumWidth)
val h = min(size, it.minimumHeight)
it.setBounds(left, top, left + w, top + h)
it.draw(canvas)
if (orientation == LinearLayout.VERTICAL) {
top += margin + h
} else {
left += margin + w
}
}
}
}
| 0
|
Kotlin
|
6
| 5
|
10ad5753c3ff675d7f7513db5d98665bcf6f7418
| 2,223
|
UICore
|
MIT License
|
drawable/src/main/java/com/angcyo/drawable/base/CombineDrawable.kt
|
angcyo
| 229,037,615
| false
|
{"Kotlin": 6722659, "JavaScript": 5194}
|
package com.angcyo.drawable.base
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.widget.LinearLayout
import com.angcyo.library.ex.dpi
import com.angcyo.library.ex.size
import kotlin.math.max
import kotlin.math.min
/**
* 结合多个[Drawable]
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2023/07/29
*/
class CombineDrawable(val drawableList: MutableList<Drawable> = mutableListOf()) : BaseDrawable() {
/**组合的方向*/
var orientation: Int = LinearLayout.HORIZONTAL
/**间隙*/
var margin: Int = 2 * dpi
fun addDrawable(drawable: Drawable?) {
drawable ?: return
drawableList.add(drawable)
}
fun removeDrawable(drawable: Drawable?) {
drawable ?: return
drawableList.remove(drawable)
}
override fun getIntrinsicWidth(): Int {
var width = -1
if (orientation == LinearLayout.VERTICAL) {
drawableList.forEach {
width = max(width, it.minimumWidth)
}
} else {
drawableList.forEach {
width += it.minimumWidth
}
width += margin * max(0, drawableList.size() - 1)
}
return width
}
override fun getIntrinsicHeight(): Int {
var height = -1
if (orientation == LinearLayout.VERTICAL) {
drawableList.forEach {
height += it.minimumHeight
}
height += margin * max(0, drawableList.size() - 1)
} else {
drawableList.forEach {
height = max(height, it.minimumHeight)
}
}
return height
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
var left = bounds.left
var top = bounds.top
val size = min(bounds.width(), bounds.height())
drawableList.forEach {
val w = min(size, it.minimumWidth)
val h = min(size, it.minimumHeight)
it.setBounds(left, top, left + w, top + h)
it.draw(canvas)
if (orientation == LinearLayout.VERTICAL) {
top += margin + h
} else {
left += margin + w
}
}
}
}
| 0
|
Kotlin
|
6
| 5
|
10ad5753c3ff675d7f7513db5d98665bcf6f7418
| 2,223
|
UICore
|
MIT License
|
src/main/kotlin/br/com/zupacademy/giovannimoratto/pix/core/exceptions/handler/ErrorHandler.kt
|
giovnnvm
| 402,067,024
| true
|
{"Kotlin": 21273}
|
package br.com.zupacademy.giovannimoratto.pix.core.exceptions.handler
import io.micronaut.aop.Around
import io.micronaut.context.annotation.Type
/**
*@Author giovanni.moratto
*/
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FILE,
AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER
)
@Around
@Type(ExceptionHandlerInterceptor::class)
annotation class ErrorHandler()
| 0
|
Kotlin
|
0
| 0
|
702ee1b389812266dc12e2629942c2cc8f51688f
| 487
|
orange-talents-06-template-pix-keymanager-grpc
|
Apache License 2.0
|
src/exchange/src/main/kotlin/com/exchange/exchange/core/ReplyEvent.kt
|
exchange-all
| 727,231,684
| false
|
{"Kotlin": 138277, "Java": 26832, "TypeScript": 5623, "Shell": 4239, "Lua": 906}
|
package com.exchange.exchange.core
/**
* Format of external event when consume from kafka
*
* @author uuhnaut69
*
*/
class ReplyEvent(
val id: String?,
val event: Any,
val data: Any?,
val error: String? = null,
)
| 17
|
Kotlin
|
0
| 2
|
884b575efba9c5f4658c8a5d194bcbacaf073a5f
| 235
|
exchange-api
|
Apache License 2.0
|
app/src/main/java/ru/coffeeplanter/maptest/data/model/Point.kt
|
coffeeplanter
| 122,768,972
| false
| null |
package ru.coffeeplanter.maptest.data.model
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import net.sharewire.googlemapsclustering.ClusterItem
@Suppress("MemberVisibilityCanBePrivate")
open class Point : RealmObject, ClusterItem {
@PrimaryKey
var id: Int = 0
var name: String? = null
var lat: Float = 0f
var lng: Float = 0f
var categoryId: Int = 0
var marker: Marker? = null
constructor()
constructor(id: Int, name: String, lat: Float, lng: Float, categoryId: Int) {
this.id = id
this.name = name
this.lat = lat
this.lng = lng
this.categoryId = categoryId
}
// ========== ClusterItem ==========
override val latitude: Double
get() = lat.toDouble()
override val longitude: Double
get() = lng.toDouble()
override val title: String?
get() = name
override val snippet: String?
get() = null
}
| 0
|
Kotlin
|
0
| 0
|
d2c629a0571d2c3e345f8697b30eede286abdda4
| 953
|
MapTest
|
MIT License
|
Lab4/src/main/kotlin/Matrix.kt
|
knu-3-velychko
| 276,469,956
| false
| null |
class Matrix {
var size: Int = 0
private var matrix: Array<Array<Double>> = arrayOf()
constructor(size: Int) {
this.size = size
matrix = Array(size) { Array(size) { 0.0 } }
}
constructor(matrix: Array<Array<Double>>) {
this.size = matrix.size
this.matrix = matrix
}
operator fun get(i: Int): Array<Double> {
checkBoundaries(i)
return matrix[i]
}
operator fun get(i: Int, j: Int): Double {
checkBoundaries(i, j)
return matrix[i][j]
}
operator fun set(i: Int, j: Int, value: Double) {
checkBoundaries(i, j)
matrix[i][j] = value
}
private fun checkBoundaries(i: Int, j: Int = -1) {
if (i >= size || j >= size)
throw IndexOutOfBoundsException(
"Unable to get value at indexes $i and $j"
)
}
operator fun plus(matrix: Matrix): Matrix {
if (this.size != matrix.size)
throw IndexOutOfBoundsException(
"Unable to add matrix with different size"
)
val result = Matrix(size)
for (i in 0 until size)
for (j in 0 until size)
result[i, j] = this[i, j] + matrix[i, j]
return result
}
operator fun times(matrix: Matrix): Matrix {
val result = Matrix(size)
for (i in 0 until size) {
for (j in 0 until size) {
for (k in 0 until size) {
result[i, j] += this[i, k] * matrix[k, j]
}
}
}
return result
}
operator fun minus(matrix: Matrix): Matrix {
val result = Matrix(size)
for (i in 0 until size) {
for (j in 0 until size) {
result[i, j] = this[i, j] - matrix[i, j]
}
}
return result
}
fun getDiagonal(): Matrix {
val result = Matrix(size)
for (i in 0 until size) {
result[i, i] = this[i, i]
}
return result
}
fun getDiagonalInvert(): Matrix {
val result = Matrix(size)
for (i in 0 until size) {
if (this[i, i] != 0.0)
result[i, i] = 1.0 / this[i, i]
}
return result
}
fun getLowerTriangle(): Matrix {
val result = Matrix(size)
for (i in 0 until size) {
for (j in 0 until size) {
if (i > j)
result[i, j] = this[i, j]
}
}
return result
}
fun getLowerTriangleInvert(): Matrix {
val matrix = this.getLowerTriangle() + this.getDiagonal()
val result = Matrix(size)
for (i in 0 until size) {
result[i, i] = 1.0 / this[i][i]
for (j in 0 until i) {
var s = 0.0
for (k in j until i)
s += matrix[i, k] * result[k, j]
result[i, j] = -s * result[i, i]
}
}
return result
}
fun getUpperTriangle(): Matrix {
val result = Matrix(size)
for (i in 0 until size) {
for (j in 0 until size) {
if (i < j)
result[i, i] = this[i, j]
}
}
return result
}
operator fun times(value: Double): Matrix {
val result = Matrix(size)
for (i in 0 until size)
for (j in 0 until size)
result[i, j] = this[i, j] * value
return result
}
operator fun times(vector: Array<Double>): Array<Double> {
val result = Array(size) { 0.0 }
for (i in 0 until size)
for (j in 0 until size)
result[i] += this[i, j] * vector[j]
return result
}
}
operator fun Double.times(matrix: Matrix) = matrix * this
operator fun Array<Double>.plus(vector: Array<Double>): Array<Double> {
val result = Array(vector.size) { 0.0 }
for (i in vector.indices)
result[i] = this[i] + vector[i]
return result
}
| 0
|
Kotlin
|
0
| 0
|
79eaf1bfc471495bd2155b3ec5d4f4aa539d8704
| 4,041
|
NumericalMethods
|
MIT License
|
src/main/kotlin/rhmodding/treasury/model/TreasureWorld.kt
|
rhmodding
| 116,833,971
| false
| null |
package rhmodding.treasury.model
import kotlin.experimental.and
class TreasureWorld {
val courses = mutableListOf<TreasureCourse>()
fun toBytes(): List<Byte> {
val l = mutableListOf<Byte>()
l.add(courses.size.toByte())
for (c in courses) {
l.add((c.id and 0xFF).toByte())
l.add((c.id.toInt() ushr 8).toByte())
}
return l
}
}
| 1
|
Kotlin
|
0
| 7
|
2d463b563fb7e1999f92f37d224999a0c5416e23
| 403
|
Treasury
|
MIT License
|
app/src/main/java/com/anesabml/hunt/model/Post.kt
|
mistrydarshan99
| 269,697,314
| true
|
{"Kotlin": 116200}
|
package com.anesabml.hunt.model
import com.anesabml.lib.recyclerView.Differentiable
import java.io.Serializable
data class Post(
val id: String,
val name: String,
val tagline: String,
val description: String?,
val createdAt: String,
val featuredAt: String?,
val slug: String?,
val thumbnail: Thumbnail?,
val media: List<Media>,
val productLinks: List<ProductLink>,
val url: String?,
val isVoted: Boolean,
val isCollected: Boolean?,
val reviewsRating: Double?,
val reviewsCount: Int?,
val votesCount: Int,
val commentsCount: Int?,
val comments: List<CommentEdge>
) : Differentiable, Serializable {
override val diffId: String
get() = id
constructor(
id: String,
name: String,
tagline: String,
createdAt: String,
featuredAt: String?,
thumbnail: Thumbnail?,
isVoted: Boolean,
votesCount: Int
) : this(
id,
name,
tagline,
null,
createdAt,
featuredAt,
null,
thumbnail,
listOf(),
listOf(),
null,
isVoted,
null,
null,
null,
votesCount,
null,
listOf()
)
}
| 0
| null |
0
| 0
|
edd41a29452441a3c8c94da4401690e653be22d5
| 1,255
|
hunt
|
MIT License
|
app/src/main/java/com/bhavdip/retrofitfuturestud/data/apis/FutureStudioClient.kt
|
mrkk95
| 300,712,979
| true
|
{"Kotlin": 7561}
|
package com.bhavdip.retrofitfuturestud.data.apis
import com.bhavdip.retrofitfuturestud.data.model.Tutorial
import com.bhavdip.retrofitfuturestud.data.model.FutureStudioRssFeed
import com.bhavdip.retrofitfuturestud.data.model.UserInfo
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.http.*
import java.sql.Date
interface FutureStudioClient {
@get:GET("/user/info")
val userInfo: Call<UserInfo?>?
@PUT("/user/info")
fun updateUserInfo(
@Body userInfo: UserInfo?
): Call<UserInfo?>?
@DELETE("/user")
fun deleteUser(): Call<Void?>?
// example for passing a full URL
@GET("https://futurestud.io/tutorials/rss/")
fun getRssFeed(): Call<FutureStudioRssFeed?>?
//Used @Body as parameter
@PUT("/user/info")
fun updateUserInfo1(
@Body userInfo: UserInfo?
): Call<Void?>?
//only @Url used as parameter
@GET
fun getUserProfilePhoto(
@Url profilePhotoUrl: String?
): Call<ResponseBody?>?
// passing "null" will ignore query
@GET("/tutorials")
fun getTutorials(
@Query("page") page: Int?,
@Query("order") order: String?,
@Query("author") author: String?,
@Query("published_at") date: Date?
): Call<List<Tutorial?>?>?
}
| 0
|
Kotlin
|
0
| 1
|
3f818b101a3f09ef4c44d2fa8bc252152255d155
| 1,277
|
RetrofitFutureStud
|
Apache License 2.0
|
app/src/main/java/com/srg/pruebamarvel/domain/features/characters/models/CharactersPageDomainModel.kt
|
sebrodgar
| 342,294,275
| false
|
{"Kotlin": 91857}
|
package com.srg.pruebamarvel.domain.features.characters.models
/**
* Created by sebrodgar on 01/03/2021.
*/
data class CharactersPageDomainModel(
val offset: Int?,
val limit: Int?,
val total: Int?,
val count: Int?,
val results: List<CharacterDomainModel>?
)
| 0
|
Kotlin
|
0
| 0
|
bfec1d716283ee8a7d638391be6272509f2064f0
| 281
|
code-test-marvel
|
Apache License 2.0
|
library/lorcana-data/src/commonTest/kotlin/eu/codlab/lorcana/TestCheckingCards.kt
|
great-illuminary
| 710,799,476
| false
|
{"Kotlin": 42337, "TypeScript": 4085, "Shell": 438}
|
package eu.codlab.lorcana
import eu.codlab.ignore.IgnoreAndroid
import eu.codlab.ignore.IgnoreJs
import eu.codlab.lorcana.buildconfig.BuildKonfig
import eu.codlab.lorcana.cards.CardType
import eu.codlab.lorcana.raw.VirtualCard
import eu.codlab.platform.Platform
import eu.codlab.platform.currentPlatform
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.fail
import kotlin.time.Duration.Companion.seconds
class TestCheckingCards {
@IgnoreJs
@Test
fun testLoadingSetsFromResources() = runTest {
if (currentPlatform != Platform.JVM) {
return@runTest
}
val lorcana = Lorcana().loadFromResources()
checkCards(lorcana.cards)
}
@IgnoreAndroid
@IgnoreJs
@Test
fun testLoadingSetsFromGithub() = runTest(timeout = 20.seconds) {
listOf("main", BuildKonfig.commit).forEach {
println("loading for $it")
checkCards(Lorcana().loadFromGithub(it).cards)
}
}
private fun checkCards(cards: List<VirtualCard>) {
val invalidCard = cards.find {
if (it.type == CardType.Glimmer && null != it.lore && it.lore!! > 4) {
return@find true
}
if (it.type == CardType.Location && null != it.lore && it.lore!! > 2) {
return@find true
}
return@find false
}
if (null != invalidCard) {
when (invalidCard.type) {
CardType.Glimmer -> fail("Lore can't be > 4")
CardType.Location -> fail("Lore can't be > 2")
else -> fail("the ${invalidCard.type} shouldn't have failed here")
}
}
}
}
| 0
|
Kotlin
|
0
| 6
|
e1e4d48b1dede0c066f1e7958446d8f5b538a516
| 1,710
|
lorcana-data
|
MIT License
|
Android/app/src/main/java/com/matthaigh27/chatgptwrapper/ui/base/BaseActivity.kt
|
ttt246
| 651,148,907
| false
| null |
package com.matthaigh27.chatgptwrapper.ui.base
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Hide the status bar (system toolbar)
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
// For hiding the action bar, if you have one
supportActionBar?.hide()
}
}
| 37
|
Kotlin
|
1
| 15
|
353f8c4fd57b48bd003f3aa7d4824ce9d2fb84aa
| 517
|
Brain
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.