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/test/kotlin/no/nav/personbruker/dittnav/api/common/serializer/LocalDateTimeSerializerTest.kt | navikt | 202,547,457 | false | null | package no.nav.personbruker.dittnav.api.common.serializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import no.nav.personbruker.dittnav.api.config.json
import org.amshove.kluent.`should be equal to`
import org.junit.jupiter.api.Test
import java.time.LocalDateTime
internal class LocalDateTimeSerializerTest {
@Test
fun `Serialize and deserialize`() {
val original = SerializableClassWithLDT(LocalDateTime.now())
val serialized = json().encodeToString(original)
val deserialized = json().decodeFromString<SerializableClassWithLDT>(serialized)
deserialized `should be equal to` original
}
}
@Serializable
private data class SerializableClassWithLDT(
@Serializable(with = LocalDateTimeSerializer::class) val dato: LocalDateTime
)
| 0 | Kotlin | 0 | 1 | a0c40c22998fccd54b25a2e08a0487b56cae6c2e | 873 | dittnav-api | MIT License |
android/core/src/main/kotlin/com/chicagoroboto/features/sessiondetail/SessionDetailPresenter.kt | balrampandey19 | 88,132,786 | true | {"Kotlin": 70729, "JavaScript": 48211, "CSS": 8379, "HTML": 5361, "Python": 3988} | package com.chicagoroboto.features.sessiondetail
import com.chicagoroboto.data.SessionProvider
import com.chicagoroboto.data.SpeakerProvider
import com.chicagoroboto.model.Session
import com.chicagoroboto.model.Speaker
class SessionDetailPresenter(private val sessionProvider: SessionProvider, private val speakerProvider: SpeakerProvider) : SessionDetailMvp.Presenter {
private var view: SessionDetailMvp.View? = null
private var session: Session? = null
private var speakers: MutableSet<Speaker> = mutableSetOf()
override fun onAttach(view: SessionDetailMvp.View) {
this.view = view
}
override fun onDetach() {
this.view = null
}
override fun setSessionId(sessionId: String) {
sessionProvider.addSessionListener(sessionId, { session: Session? ->
if (session != null) {
view?.showSessionDetail(session)
session.speakers?.map {
speakerProvider.addSpeakerListener(it, onSpeakerReceived)
}
}
})
}
private val onSpeakerReceived = { speaker: Speaker? ->
if (speaker != null) {
speakers.add(speaker)
view?.showSpeakerInfo(speakers)
}
}
} | 0 | Kotlin | 0 | 0 | e9e7797b4fbd9edbd81ddbe76203f1fb3d9ce62b | 1,248 | chicago-roboto | Apache License 2.0 |
src/concurrentMain/kotlin/Save.concurrent.kt | alex-s168 | 805,508,903 | false | {"Kotlin": 32527, "Shell": 127} | import korlibs.io.file.VfsFile
import korlibs.render.*
actual suspend fun export(gameWindow: GameWindow, file: VfsFile) =
defaultExport(gameWindow, file)
actual suspend fun CardEditor.save(gameWindow: GameWindow, editor: CardEditor) =
defaultSave(gameWindow, editor)
| 0 | Kotlin | 0 | 0 | 9f8524568c8bbb625bd509e082869bbba352d673 | 277 | CardWars-card-maker | MIT License |
coordinator/ethereum/finalization-monitor/src/test/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImplTest.kt | Consensys | 681,656,806 | false | null | package net.consensys.zkevm.ethereum.finalization
import io.vertx.core.Vertx
import io.vertx.junit5.VertxExtension
import io.vertx.junit5.VertxTestContext
import net.consensys.linea.BlockParameter
import net.consensys.zkevm.coordinator.clients.smartcontract.LineaRollupSmartContractClientReadOnly
import org.apache.tuweni.bytes.Bytes
import org.apache.tuweni.bytes.Bytes32
import org.assertj.core.api.Assertions.assertThat
import org.awaitility.Awaitility.await
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mockito.RETURNS_DEEP_STUBS
import org.mockito.Mockito.atLeastOnce
import org.mockito.Mockito.verify
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.web3j.protocol.Web3j
import org.web3j.protocol.core.methods.response.EthBlock
import org.web3j.protocol.core.methods.response.EthBlockNumber
import tech.pegasys.teku.infrastructure.async.SafeFuture
import java.math.BigInteger
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger
import kotlin.random.Random
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.toJavaDuration
@ExtendWith(VertxExtension::class)
class FinalizationMonitorImplTest {
private val expectedBlockNumber = 2UL
private val pollingInterval = 20.milliseconds
private val config = FinalizationMonitorImpl.Config(pollingInterval)
private lateinit var mockL2Client: Web3j
private lateinit var contractMock: LineaRollupSmartContractClientReadOnly
private val mockBlockNumberReturn = mock<EthBlockNumber>()
@BeforeEach
fun setup() {
mockL2Client = mock<Web3j>(defaultAnswer = RETURNS_DEEP_STUBS)
contractMock = mock<LineaRollupSmartContractClientReadOnly>(defaultAnswer = RETURNS_DEEP_STUBS)
whenever(mockBlockNumberReturn.blockNumber).thenReturn(BigInteger.TWO)
}
@Test
fun start_startsPollingProcess(vertx: Vertx, testContext: VertxTestContext) {
whenever(contractMock.finalizedL2BlockNumber(eq(BlockParameter.Tag.FINALIZED)))
.thenReturn(SafeFuture.completedFuture(expectedBlockNumber))
val expectedStateRootHash = Bytes32.random()
whenever(contractMock.blockStateRootHash(any(), any()))
.thenReturn(SafeFuture.completedFuture(expectedStateRootHash.toArray()))
val expectedBlockHash = Bytes32.random()
val mockBlockByNumberReturn = mock<EthBlock>()
val mockBlock = mock<EthBlock.Block>()
whenever(mockBlockByNumberReturn.block).thenReturn(mockBlock)
whenever(mockBlock.hash).thenReturn(expectedBlockHash.toHexString())
whenever(mockL2Client.ethGetBlockByNumber(any(), any()).sendAsync()).thenAnswer {
SafeFuture.completedFuture(mockBlockByNumberReturn)
}
val finalizationMonitorImpl =
FinalizationMonitorImpl(
config = config,
contract = contractMock,
l2Client = mockL2Client,
vertx = vertx
)
finalizationMonitorImpl
.start()
.thenApply {
await()
.atMost(5.seconds.toJavaDuration())
.untilAsserted {
verify(mockL2Client, atLeastOnce()).ethGetBlockByNumber(eq(null), eq(false))
verify(contractMock, atLeastOnce()).finalizedL2BlockNumber(BlockParameter.Tag.FINALIZED)
verify(contractMock, atLeastOnce()).blockStateRootHash(BlockParameter.Tag.FINALIZED, expectedBlockNumber)
}
}
.thenCompose { finalizationMonitorImpl.stop() }
.thenApply { testContext.completeNow() }
.whenException(testContext::failNow)
}
@Test
fun finalizationUpdatesAreSentToTheRightHandlers(vertx: Vertx, testContext: VertxTestContext) {
var blockNumber = 0
whenever(contractMock.finalizedL2BlockNumber(any())).thenAnswer {
blockNumber += 1
SafeFuture.completedFuture(blockNumber.toULong())
}
whenever(contractMock.blockStateRootHash(any(), any())).thenAnswer {
SafeFuture.completedFuture(intToBytes32(blockNumber).toArray())
}
val expectedBlockHash = intToBytes32(blockNumber).toHexString()
val mockBlockByNumberReturn = mock<EthBlock>()
val mockBlock = mock<EthBlock.Block>()
whenever(mockBlockByNumberReturn.block).thenReturn(mockBlock)
whenever(mockBlock.hash).thenReturn(expectedBlockHash)
whenever(mockL2Client.ethGetBlockByNumber(any(), any()).sendAsync()).thenAnswer {
SafeFuture.completedFuture(mockBlockByNumberReturn)
}
val finalizationMonitorImpl =
FinalizationMonitorImpl(
config = config,
contract = contractMock,
l2Client = mockL2Client,
vertx = vertx
)
val updatesReceived1 = mutableListOf<FinalizationMonitor.FinalizationUpdate>()
val updatesReceived2 = mutableListOf<FinalizationMonitor.FinalizationUpdate>()
finalizationMonitorImpl.addFinalizationHandler("handler1") {
SafeFuture.completedFuture(updatesReceived1.add(it))
}
val secondFinalisationHandlerSet = testContext.checkpoint()
finalizationMonitorImpl
.start()
.thenApply {
secondFinalisationHandlerSet.flag()
await()
.untilAsserted {
finalizationMonitorImpl.addFinalizationHandler("handler2") {
SafeFuture.completedFuture(updatesReceived2.add(it))
}
}
await()
.untilAsserted {
finalizationMonitorImpl
.stop()
.thenApply {
assertThat(updatesReceived1).isNotEmpty
assertThat(updatesReceived2).isNotEmpty
assertThat(updatesReceived1).isNotEqualTo(updatesReceived2)
assertThat(updatesReceived2).contains(updatesReceived1.last())
testContext.completeNow()
}
.whenException(testContext::failNow)
}
}.whenException(testContext::failNow)
}
@Test
fun finalizationUpdatesDontCrashTheWholeMonitorInCaseOfErrors(
vertx: Vertx,
testContext: VertxTestContext
) {
var blockNumber = 0
whenever(contractMock.finalizedL2BlockNumber(any())).thenAnswer {
blockNumber += 1
SafeFuture.completedFuture(blockNumber.toULong())
}
whenever(contractMock.blockStateRootHash(any(), any())).thenAnswer {
SafeFuture.completedFuture(intToBytes32(blockNumber).toArray())
}
val expectedBlockHash = intToBytes32(blockNumber).toHexString()
val mockBlockByNumberReturn = mock<EthBlock>()
val mockBlock = mock<EthBlock.Block>()
whenever(mockBlockByNumberReturn.block).thenReturn(mockBlock)
whenever(mockBlock.hash).thenReturn(expectedBlockHash)
whenever(mockL2Client.ethGetBlockByNumber(any(), any()).sendAsync()).thenAnswer {
SafeFuture.completedFuture(mockBlockByNumberReturn)
}
val finalizationMonitorImpl =
FinalizationMonitorImpl(
config = config,
contract = contractMock,
l2Client = mockL2Client,
vertx = vertx
)
val updatesReceived = CopyOnWriteArrayList<FinalizationMonitor.FinalizationUpdate>()
val numberOfEventsBeforeError = AtomicInteger(0)
finalizationMonitorImpl.addFinalizationHandler("handler1") {
SafeFuture.completedFuture(updatesReceived.add(it))
}
val errorsThrown = AtomicInteger(0)
finalizationMonitorImpl.start()
await()
.pollInterval(10.milliseconds.toJavaDuration())
.atMost(10.seconds.toJavaDuration())
.untilAsserted {
assertThat(updatesReceived).hasSizeGreaterThanOrEqualTo(1)
finalizationMonitorImpl.addFinalizationHandler("handler2") {
errorsThrown.incrementAndGet()
numberOfEventsBeforeError.set(updatesReceived.size)
throw Exception("Finalization callback failure for the testing!")
}
}
await()
.pollInterval(10.milliseconds.toJavaDuration())
.untilAsserted {
assertThat(errorsThrown.get()).isGreaterThan(1)
}
await()
.pollInterval(10.milliseconds.toJavaDuration())
.untilAsserted {
assertThat(updatesReceived).hasSizeGreaterThanOrEqualTo(numberOfEventsBeforeError.get())
testContext.completeNow()
}
finalizationMonitorImpl.stop().whenException(testContext::failNow)
}
@Test
fun monitorDoesntCrashInCaseOfWeb3Exceptions(vertx: Vertx, testContext: VertxTestContext) {
val updatesReceived = CopyOnWriteArrayList<FinalizationMonitor.FinalizationUpdate>()
var blockNumber = 0
var errorThrown = false
var eventsReceivedBeforeError = 0
whenever(contractMock.finalizedL2BlockNumber(any())).thenAnswer {
blockNumber += 1
if (blockNumber in 3..4) {
errorThrown = true
eventsReceivedBeforeError = updatesReceived.size
throw Exception("Web3 client failure for the testing!")
}
SafeFuture.completedFuture(blockNumber.toULong())
}
whenever(contractMock.blockStateRootHash(any(), any())).thenAnswer {
SafeFuture.completedFuture(intToBytes32(blockNumber).toArray())
}
val expectedBlockHash = intToBytes32(blockNumber).toHexString()
val mockBlockByNumberReturn = mock<EthBlock>()
val mockBlock = mock<EthBlock.Block>()
whenever(mockBlockByNumberReturn.block).thenReturn(mockBlock)
whenever(mockBlock.hash).thenReturn(expectedBlockHash)
whenever(mockL2Client.ethGetBlockByNumber(any(), any()).sendAsync()).thenAnswer {
SafeFuture.completedFuture(mockBlockByNumberReturn)
}
val finalizationMonitorImpl =
FinalizationMonitorImpl(
config = config,
contract = contractMock,
l2Client = mockL2Client,
vertx = vertx
)
finalizationMonitorImpl.addFinalizationHandler("handler1") {
SafeFuture.completedFuture(updatesReceived.add(it))
}
finalizationMonitorImpl.start()
await()
.untilAsserted {
assertThat(updatesReceived).isNotEmpty
assertThat(errorThrown).isTrue()
assertThat(updatesReceived).hasSizeGreaterThan(eventsReceivedBeforeError)
}
finalizationMonitorImpl.stop()
.thenApply { testContext.completeNow() }
}
@Test
fun finalizationUpdatesHandledInOrderTheyWereSet(vertx: Vertx, testContext: VertxTestContext) {
var blockNumber = 0
whenever(contractMock.finalizedL2BlockNumber(any())).thenAnswer {
blockNumber += 1
SafeFuture.completedFuture(blockNumber.toULong())
}
whenever(contractMock.blockStateRootHash(any(), any())).thenAnswer {
SafeFuture.completedFuture(intToBytes32(blockNumber).toArray())
}
val expectedBlockHash = intToBytes32(blockNumber).toHexString()
val mockBlockByNumberReturn = mock<EthBlock>()
val mockBlock = mock<EthBlock.Block>()
whenever(mockBlockByNumberReturn.block).thenReturn(mockBlock)
whenever(mockBlock.hash).thenReturn(expectedBlockHash)
whenever(mockL2Client.ethGetBlockByNumber(any(), any()).sendAsync()).thenAnswer {
SafeFuture.completedFuture(mockBlockByNumberReturn)
}
val finalizationMonitorImpl =
FinalizationMonitorImpl(
config = config.copy(pollingInterval = pollingInterval * 2),
contract = contractMock,
l2Client = mockL2Client,
vertx = vertx
)
val updatesReceived = CopyOnWriteArrayList<Pair<FinalizationMonitor.FinalizationUpdate, String>>()
fun simulateRandomWork(fromMillis: Long, toMillis: Long) {
Thread.sleep(Random.nextLong(fromMillis, toMillis))
}
val handlerName1 = "handler1"
finalizationMonitorImpl.addFinalizationHandler(handlerName1) { finalizationUpdate ->
val result = SafeFuture.runAsync {
simulateRandomWork(3, 7)
updatesReceived.add(finalizationUpdate to handlerName1)
}
SafeFuture.of(result)
}
val handlerName2 = "handler2"
finalizationMonitorImpl.addFinalizationHandler(handlerName2) { finalizationUpdate ->
val result = SafeFuture.COMPLETE.thenApply {
simulateRandomWork(2, 6)
updatesReceived.add(finalizationUpdate to handlerName2)
}
SafeFuture.of(result)
}
val handlerName3 = "handler3"
finalizationMonitorImpl.addFinalizationHandler(handlerName3) { finalizationUpdate ->
val result = SafeFuture.COMPLETE.thenApply {
simulateRandomWork(0, 4)
updatesReceived.add(finalizationUpdate to handlerName3)
}
SafeFuture.of(result)
}
fun allUpdatesHandledInTheRightOrder() {
assertThat(updatesReceived.size % 3).isZero()
.overridingErrorMessage("Unexpected number of updates! $updatesReceived")
assertThat(
updatesReceived.windowed(3, 3).all { finalizationUpdates ->
finalizationUpdates.map { it.second } == listOf(handlerName1, handlerName2, handlerName3)
}
)
.overridingErrorMessage("Updates aren't in the right order! $updatesReceived")
.isTrue()
}
finalizationMonitorImpl
.start()
.thenApply {
await()
.atMost(10.seconds.toJavaDuration())
.pollInterval(200.milliseconds.toJavaDuration())
.untilAsserted {
allUpdatesHandledInTheRightOrder()
}
finalizationMonitorImpl.stop()
testContext.completeNow()
}
.whenException(testContext::failNow)
}
private fun intToBytes32(i: Int): Bytes32 {
return Bytes32.leftPad(Bytes.wrap(listOf(i.toByte()).toByteArray()))
}
}
| 5 | null | 2 | 26 | 48547c9f3fb21e9003d990c9f62930f4facee0dd | 13,493 | linea-monorepo | Apache License 2.0 |
bitgouel-api/src/main/kotlin/team/msg/domain/university/presentation/data/web/CreateUniversityWebRequest.kt | School-of-Company | 700,741,727 | false | {"Kotlin": 629756, "Shell": 2040, "Dockerfile": 206} | package team.msg.domain.university.presentation.data.web
import javax.validation.constraints.NotBlank
data class CreateUniversityWebRequest(
@field:NotBlank
val universityName: String
) | 0 | Kotlin | 0 | 17 | 5c01f1073ebcfb8c4bfd0accd56a659819ffe534 | 195 | Bitgouel-Server | MIT License |
PennMobile/src/test/java/HomePageSerializerTest.kt | pennlabs | 16,791,473 | false | null | package com.pennapps.labs.pennmobile.classes
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.pennapps.labs.pennmobile.api.Serializer
import org.joda.time.Interval
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
// Unit tests
class HomePageSerializerTest {
var serializer = Serializer.HomePageSerializer()
var jsonStr = """{"cells":[{"info":{"image_url":"https://s3.amazonaws.com/penn.mobile.portal/images/Penn%20Labs/1619465670.144596-cropped.png","post_id":53,"post_url":"https://docs.google.com/forms/u/1/d/12TQpqnattdWnL4tpczR6HPGu8a6-FuujU5dWS7k2k8I/edit","source":"Penn Labs","subtitle":"Having issues with Penn Mobile? Or maybe an idea for a new feature? Chat with us to share your thoughts and help improve the Penn Mobile experience!","test":false,"time_label":"Tap the Image!","title":"Penn Mobile User Feedback"},"type":"post"},{"info":{"venues":[593,636]},"type":"dining"},{"info":{"article_url":"https://www.thedp.com/article/2021/04/penn-museum-move-protest-philadelphia","image_url":"https://s3.amazonaws.com/snwceomedia/dpn/b1fb9439-7490-4f86-980a-55152825dc69.sized-1000x1000.gif?w=1000","source":"The Daily Pennsylvanian","subtitle":"The protest was organized by Black liberation advocacy group MOVE, in collaboration with Black Lives Matter Philadelphia, following the discovery that the Penn Museum stored the remains of at least one child killed in the bombing.","timestamp":"13 hours ago\n","title":"West Philadelphians protest on campus for Penn to return MOVE victim remains to family"},"type":"news"},{"info":[{"end":"2021-05-04","name":"Reading Days","start":"2021-04-30"},{"end":"2021-05-12","name":"Final Examinations","start":"2021-05-04"},{"end":"2021-05-11","name":"Spring Term ends","start":"2021-05-11"}],"type":"calendar"},{"info":[1086,2587],"type":"gsr-locations"},{"info":{"room_id":29},"type":"laundry"}]}"""
var gson = Gson()
var jsonObj = gson.fromJson(jsonStr, JsonObject::class.java)
lateinit var homeData: List<HomeCell>
@Before
fun parse() {
this.homeData = this.serializer.deserialize(this.jsonObj, null, null)
}
@Test
fun testCellCount() {
assertEquals(6, this.homeData.size)
}
@Test
fun testCellContentZero() {
var imgUrl = "https://s3.amazonaws.com/penn.mobile.portal/images/Penn%20Labs/1619465670.144596-cropped.png"
var postId = 53
var postUrl = "https://docs.google.com/forms/u/1/d/12TQpqnattdWnL4tpczR6HPGu8a6-FuujU5dWS7k2k8I/edit"
var source = "Penn Labs"
var subtitle = "Having issues with Penn Mobile? Or maybe an idea for a new feature? Chat with us to share your thoughts and help improve the Penn Mobile experience!"
var test = false
var timeLabel = "Tap the Image!"
var title = "Penn Mobile User Feedback"
var type = "post"
var cell = homeData[0]
var info = cell.info!!
assertEquals(imgUrl, info.imageUrl)
assertEquals(postId, info.postId)
assertEquals(postUrl, info.postUrl)
assertEquals(source, info.source)
assertEquals(subtitle, info.subtitle)
assertEquals(test, info.isTest)
assertEquals(timeLabel, info.timeLabel)
assertEquals(title, info.title)
assertEquals(type, cell.type)
}
@Test
fun testCellContentOne() {
var type = "dining"
var cell = homeData[1]
var info = cell.info!!
assertEquals(2, info.venues!!.size)
assertEquals(593, info.venues!![0])
assertEquals(636, info.venues!![1])
assertEquals(type, cell.type)
}
@Test
fun testCellContentTwo() {
var articleUrl = "https://www.thedp.com/article/2021/04/penn-museum-move-protest-philadelphia"
var imageUrl = "https://s3.amazonaws.com/snwceomedia/dpn/b1fb9439-7490-4f86-980a-55152825dc69.sized-1000x1000.gif?w=1000"
var source = "The Daily Pennsylvanian"
var subtitle = "The protest was organized by Black liberation advocacy group MOVE, in collaboration with Black Lives Matter Philadelphia, following the discovery that the Penn Museum stored the remains of at least one child killed in the bombing."
var timestamp = "13 hours ago\n"
var title = "West Philadelphians protest on campus for Penn to return MOVE victim remains to family"
var type = "news"
var cell = homeData[2]
var info = cell.info!!
assertEquals(articleUrl, info.articleUrl)
assertEquals(imageUrl, info.imageUrl)
assertEquals(source, info.source)
assertEquals(subtitle, info.subtitle)
assertEquals(timestamp, info.timestamp)
assertEquals(title, info.title)
assertEquals(type, cell.type)
}
@Test
fun testCellContentThree() {
var end0 = "2021-05-04"
var name0 = "Reading Days"
var start0 = "2021-04-30"
var end1 = "2021-05-12"
var name1 = "Final Examinations"
var start1 = "2021-05-04"
var end2 = "2021-05-11"
var name2 = "Spring Term ends"
var start2 = "2021-05-11"
var type = "calendar"
assertEquals(3, homeData[3].events!!.size)
assertEquals(name0, homeData[3].events!![0].name)
assertEquals(name1, homeData[3].events!![1].name)
assertEquals(name2, homeData[3].events!![2].name)
assertEquals(end0, homeData[3].events!![0].end)
assertEquals(end1, homeData[3].events!![1].end)
assertEquals(end2, homeData[3].events!![2].end)
assertEquals(start0, homeData[3].events!![0].start)
assertEquals(start1, homeData[3].events!![1].start)
assertEquals(start2, homeData[3].events!![2].start)
assertEquals(type, homeData[3].type)
}
@Test
fun testCellContentFour() {
var type = "gsr-locations"
assertEquals(type, homeData[4].type)
}
@Test
fun testCellContentFive() {
var roomId = 29
var type = "laundry"
assertEquals(roomId, homeData[5].info!!.roomId)
assertEquals(type, homeData[5].type)
}
} | 31 | null | 5 | 33 | c65247bc2d56f59c329381029d308f89831dbedd | 6,175 | penn-mobile-android | MIT License |
app/src/main/java/com/yuno/clearsale/example/ui/activities/FragmentHostActivity.kt | yuno-payments | 546,698,606 | false | null | package com.yuno.clearsale.example.ui.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.yuno.clearsale.example.R
import com.yuno.clearsale.example.ui.fragments.MainFragment
class FragmentHostActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment_host)
supportFragmentManager.beginTransaction()
.replace(R.id.frameLayout_container, MainFragment())
.commit()
}
} | 0 | Kotlin | 0 | 0 | 64c42653b8a64f6f549c1b84d137f3a5d4e55a49 | 571 | yuno-antifraud-clearsale | MIT License |
libnavui-maps/src/test/java/com/mapbox/navigation/ui/maps/internal/route/line/RouteLineEventDataTest.kt | mapbox | 87,455,763 | false | {"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624} | package com.mapbox.navigation.ui.maps.internal.route.line
import com.mapbox.navigation.testing.FieldsAreDoubledTest
import com.mapbox.navigation.ui.maps.route.line.model.RouteLineData
import com.mapbox.navigation.ui.maps.route.line.model.RouteLineDynamicData
internal class RouteLineEventDataTest : FieldsAreDoubledTest<RouteLineEventData, RouteLineData>() {
override val fieldsTypesMap: Map<Class<*>, Class<*>> = mapOf(
RouteLineDynamicData::class.java to RouteLineDynamicEventData::class.java,
)
override fun getDoublerClass(): Class<*> {
return RouteLineEventData::class.java
}
override fun getOriginalClass(): Class<*> {
return RouteLineData::class.java
}
}
| 508 | Kotlin | 318 | 621 | 88163ae3d7e34948369d6945d5b78a72bdd68d7c | 715 | mapbox-navigation-android | Apache License 2.0 |
platform/src/main/kotlin/researchstack/backend/adapter/outgoing/mongo/repository/healthdata/HealthDataRepositoryLookup.kt | S-ResearchStack | 520,365,362 | false | {"Kotlin": 1297740, "Dockerfile": 202, "Shell": 59} | package researchstack.backend.adapter.outgoing.mongo.repository.healthdata
import org.springframework.stereotype.Component
import researchstack.backend.adapter.outgoing.mongo.entity.healthdata.HealthDataEntity
import researchstack.backend.enums.HealthDataType
@Component
class HealthDataRepositoryLookup(
accelerometerRepository: AccelerometerRepository,
batteryRepository: BatteryRepository,
bloodGlucoseRepository: BloodGlucoseRepository,
bloodPressureRepository: BloodPressureRepository,
deviceStatMobileWearConnectionRepository: DeviceStatMobileWearConnectionRepository,
deviceStatWearBatteryRepository: DeviceStatWearBatteryRepository,
deviceStatWearOffBodyRepository: DeviceStatWearOffBodyRepository,
deviceStatWearPowerOnOffRepository: DeviceStatWearPowerOnOffRepository,
exerciseRepository: ExerciseRepository,
gyroscopeRepository: GyroscopeRepository,
heartRateRepository: HeartRateRepository,
heightRepository: HeightRepository,
lightRepository: ExerciseRepository,
offBodyRepository: OffBodyRepository,
oxygenSaturationRepository: OxygenSaturationRepository,
respiratoryRateRepository: RespiratoryRateRepository,
sleepSessionRepository: SleepSessionRepository,
sleepStageRepository: SleepStageRepository,
stepsRepository: StepsRepository,
totalCaloriesBurnedRepository: TotalCaloriesBurnedRepository,
wearAccelerometerRepository: WearAccelerometerRepository,
wearBatteryRepository: WearBatteryRepository,
wearBiaRepository: WearBiaRepository,
wearBloodPressureRepository: WearBloodPressureRepository,
wearEcgRepository: WearEcgRepository,
wearGyroscopeRepository: WearGyroscopeRepository,
wearHealthEventRepository: WearHealthEventRepository,
wearHeartRateRepository: WearHeartRateRepository,
wearPpgGreenRepository: WearPpgGreenRepository,
wearPpgIrRepository: WearPpgIrRepository,
wearPpgRedRepository: WearPpgRedRepository,
wearSpo2Repository: WearSpo2Repository,
wearSweatLossRepository: WearSweatLossRepository,
weightRepository: WeightRepository
) {
@Suppress("UNCHECKED_CAST")
private val typeToRepository: Map<HealthDataType, HealthDataRepository<HealthDataEntity>> =
mapOf(
HealthDataType.ACCELEROMETER to accelerometerRepository,
HealthDataType.BATTERY to batteryRepository,
HealthDataType.BLOOD_GLUCOSE to bloodGlucoseRepository,
HealthDataType.BLOOD_PRESSURE to bloodPressureRepository,
HealthDataType.DEVICE_STAT_MOBILE_WEAR_CONNECTION to deviceStatMobileWearConnectionRepository,
HealthDataType.DEVICE_STAT_WEAR_BATTERY to deviceStatWearBatteryRepository,
HealthDataType.DEVICE_STAT_WEAR_OFF_BODY to deviceStatWearOffBodyRepository,
HealthDataType.DEVICE_STAT_WEAR_POWER_ON_OFF to deviceStatWearPowerOnOffRepository,
HealthDataType.EXERCISE to exerciseRepository,
HealthDataType.GYROSCOPE to gyroscopeRepository,
HealthDataType.HEART_RATE to heartRateRepository,
HealthDataType.HEIGHT to heightRepository,
HealthDataType.LIGHT to lightRepository,
HealthDataType.OFF_BODY to offBodyRepository,
HealthDataType.OXYGEN_SATURATION to oxygenSaturationRepository,
HealthDataType.RESPIRATORY_RATE to respiratoryRateRepository,
HealthDataType.SLEEP_SESSION to sleepSessionRepository,
HealthDataType.SLEEP_STAGE to sleepStageRepository,
HealthDataType.STEPS to stepsRepository,
HealthDataType.TOTAL_CALORIES_BURNED to totalCaloriesBurnedRepository,
HealthDataType.WEAR_ACCELEROMETER to wearAccelerometerRepository,
HealthDataType.WEAR_BATTERY to wearBatteryRepository,
HealthDataType.WEAR_BIA to wearBiaRepository,
HealthDataType.WEAR_BLOOD_PRESSURE to wearBloodPressureRepository,
HealthDataType.WEAR_ECG to wearEcgRepository,
HealthDataType.WEAR_GYROSCOPE to wearGyroscopeRepository,
HealthDataType.WEAR_HEALTH_EVENT to wearHealthEventRepository,
HealthDataType.WEAR_HEART_RATE to wearHeartRateRepository,
HealthDataType.WEAR_PPG_GREEN to wearPpgGreenRepository,
HealthDataType.WEAR_PPG_IR to wearPpgIrRepository,
HealthDataType.WEAR_PPG_RED to wearPpgRedRepository,
HealthDataType.WEAR_SPO2 to wearSpo2Repository,
HealthDataType.WEAR_SWEAT_LOSS to wearSweatLossRepository,
HealthDataType.WEIGHT to weightRepository
) as Map<HealthDataType, HealthDataRepository<HealthDataEntity>>
fun getRepository(type: HealthDataType): HealthDataRepository<HealthDataEntity>? = typeToRepository[type]
}
| 1 | Kotlin | 9 | 29 | edd76f219cdb10c8151b8ac14175b1e818a6036a | 4,781 | backend-system | Apache License 2.0 |
dispatcher/src/main/kotlin/pl/droidsonroids/testing/mockwebserver/condition/PathQueryConditionFactory.kt | morristech | 120,860,743 | true | {"Kotlin": 25237} | package pl.droidsonroids.testing.mockwebserver.condition
/**
* Factory which can be used to create similar [PathQueryCondition]s sharing the same path prefix
* so it does not need to be repeated each time when new [PathQueryCondition] is needed.
* @param pathPrefix common path prefix
* @constructor creates new factory with given prefix
*/
class PathQueryConditionFactory(private val pathPrefix: String) {
/**
* Creates condition with both <code>path</code>, <code>queryParameterName</code>
* and <code>queryParameterValue</code>.
* @param pathInfix path infix, may be empty
* @param queryParameterName query parameter name <code>queryParameterName</code>
* @param queryParameterValue query parameter value for given
* @return a PathQueryCondition
*/
fun withPathInfixAndQueryParameter(pathInfix: String, queryParameterName: String, queryParameterValue: String) =
PathQueryCondition(pathPrefix + pathInfix, queryParameterName, queryParameterValue)
/**
* Creates condition with both <code>path</code>, <code>queryParameterName</code>.
* @param pathInfix path infix, may be empty
* @param queryParameterName query parameter name <code>queryParameterName</code>
* @return a PathQueryCondition
*/
fun withPathInfixAndQueryParameter(pathInfix: String, queryParameterName: String) =
PathQueryCondition(pathPrefix + pathInfix, queryParameterName)
/**
* Creates condition with <code>path</code> only.
* @param pathInfix path infix, may be empty
* @return a PathQueryCondition
*/
fun withPathInfix(pathInfix: String) =
PathQueryCondition(pathPrefix + pathInfix)
} | 0 | Kotlin | 0 | 0 | fcddb5ad63a272ecd5801d7fb52c967938805b57 | 1,703 | mockwebserver-path-dispatcher | MIT License |
src/main/kotlin/com/github/jflc/spring/cloud/service/s3/configuration/AmazonS3Properties.kt | jflc | 148,643,991 | false | null | package com.github.jflc.spring.cloud.service.s3.configuration
import com.amazonaws.auth.AWSCredentials
import com.amazonaws.auth.AWSCredentialsProvider
import org.hibernate.validator.constraints.NotEmpty
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.validation.annotation.Validated
@ConfigurationProperties(prefix = "spring.cloud.aws.s3")
@Validated
class AmazonS3Properties : AWSCredentialsProvider {
@NotEmpty
lateinit var region: String
lateinit var bucket: String
val credentials: AWSCredentialsProperties = AWSCredentialsProperties()
override fun refresh() {}
override fun getCredentials(): AWSCredentials = this.getCredentials()
}
class AWSCredentialsProperties : AWSCredentials {
@NotEmpty
lateinit var accessKey: String
@NotEmpty
lateinit var secretKey: String
override fun getAWSAccessKeyId(): String = this.accessKey
override fun getAWSSecretKey(): String = this.secretKey
} | 0 | Kotlin | 0 | 0 | 58fb76744fdbd97907b1a5984c2f407772cddcdf | 1,001 | spring-cloud-services-s3 | Apache License 2.0 |
components-core/src/test/java/com/adyen/checkout/components/core/internal/util/DateUtilsTest.kt | Adyen | 91,104,663 | false | null | /*
* Copyright (c) 2024 Adyen N.V.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by ararat on 22/1/2024.
*/
package com.adyen.checkout.components.core.internal.util
import com.adyen.checkout.core.AdyenLogger
import com.adyen.checkout.core.internal.util.Logger
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.Calendar
import java.util.Locale
class DateUtilsTest {
@BeforeEach
fun beforeEach() {
AdyenLogger.setLogLevel(Logger.NONE)
}
@ParameterizedTest
@MethodSource("parseDateToView")
fun testParseDateToView(month: String, year: String, expectedFormattedDate: String) {
val formattedDate = DateUtils.parseDateToView(month, year)
assertEquals(expectedFormattedDate, formattedDate)
}
@ParameterizedTest
@MethodSource("toServerDateFormat")
fun testToServerDateFormat(calendar: Calendar, expectedFormattedDate: String) {
val formattedDate = DateUtils.toServerDateFormat(calendar)
assertEquals(expectedFormattedDate, formattedDate)
}
@ParameterizedTest
@MethodSource("matchesFormat")
fun testMatchesFormat(date: String, format: String, expectedResult: Boolean) {
val result = DateUtils.matchesFormat(date, format)
assertEquals(expectedResult, result)
}
@ParameterizedTest
@MethodSource("formatStringDate")
fun testFormatStringDate(date: String, shopperLocale: Locale, inputFormat: String, expectedFormattedDate: String?) {
val formattedDate = DateUtils.formatStringDate(date, shopperLocale, inputFormat)
assertEquals(expectedFormattedDate, formattedDate)
}
@ParameterizedTest
@MethodSource("formatDateToString")
fun testFormatDateToString(calendar: Calendar, pattern: String, expectedFormattedDate: String?) {
val formattedDate = DateUtils.formatDateToString(calendar, pattern)
assertEquals(expectedFormattedDate, formattedDate)
}
companion object {
@JvmStatic
fun parseDateToView() = listOf(
// month, year, expectedFormattedDate
arguments("1", "2021", "1/21"),
arguments("02", "2020", "02/20"),
arguments("12", "2023", "12/23"),
)
@JvmStatic
fun toServerDateFormat() = listOf(
// date, expectedFormattedDate
arguments(getCalendar(2023, 1, 7), "2023-02-07"),
arguments(getCalendar(2024, 0, 1), "2024-01-01"),
arguments(getCalendar(2024, 11, 1), "2024-12-01"),
arguments(getCalendar(2019, 0, 1, 0, 0, 0), "2019-01-01"),
arguments(getCalendar(2019, 0, 1, 20, 30, 30), "2019-01-01"),
)
@JvmStatic
fun matchesFormat() = listOf(
// date, format, expectedResult
arguments("2023-02-07'T'20:00:00", "yyyyMMdd", false),
arguments("2023-02-07", "yyyyMMdd", false),
arguments("2023-02-07", "yyyyMM", false),
arguments("20233112", "yyyyMMdd", false),
arguments("233112", "yyMMdd", false),
arguments("2331", "yyMM", false),
arguments("20230207T20:00:00", "yyyyMMdd'T'HH:mm:ss", true),
arguments("20230207T20:00:00", "yyyyMMdd", true),
arguments("230207T20:00:00", "yyMMdd", true),
arguments("20230207", "yyyyMMdd", true),
arguments("202302", "yyyyMM", true),
arguments("230201", "yyMMdd", true),
arguments("2302", "yyMM", true),
)
@JvmStatic
fun formatStringDate() = listOf(
// date, shopperLocale, inputFormat, expectedResult
arguments("2023-02-07'T'20:00:00", Locale.US, "yyyy-MM-dd'T'HH:mm:ss", null),
arguments("2024-02-01", Locale.US, "yyyy-MM-dd", "2/1/24"),
arguments("230207", Locale.US, "yyMMdd", "2/7/23"),
arguments("231302", Locale.US, "yyMMdd", "1/2/24"),
arguments("2024-02-01", Locale.UK, "yy-MM-dd", "01/02/2024"),
arguments("231302", Locale.UK, "yyMMdd", "02/01/2024"),
arguments("2024-02-01", Locale.JAPAN, "yy-MM-dd", "2024/02/01"),
arguments("2024-02-01", Locale.CHINA, "yy-MM-dd", "2024/2/1"),
arguments("2024-02-01", Locale.CANADA, "yy-MM-dd", "2024-02-01"),
arguments("2024-02-01", Locale.FRANCE, "yy-MM-dd", "01/02/2024"),
)
@JvmStatic
fun formatDateToString() = listOf(
// date, pattern, expectedFormattedDate
arguments(getCalendar(2024, 0, 5, 20, 10, 5), "yyyy-MM-dd'T'HH:mm:ss", "2024-01-05T20:10:05"),
arguments(getCalendar(2020, 11, 31, 23, 59, 59), "yyyy-MM-dd'T'HH:mm:ss", "2020-12-31T23:59:59"),
arguments(getCalendar(2019, 0, 1, 0, 0, 0), "yyyy-MM-dd'T'HH:mm:ss", "2019-01-01T00:00:00"),
arguments(getCalendar(2019, 0, 1, 0, 0, 0), "yyyyMMdd'T'HHmmss", "20190101T000000"),
arguments(getCalendar(2019, 1, 1, 0, 0, 0), "yyyyMMdd", "20190201"),
arguments(getCalendar(2024, 0, 5, 20, 10, 5), "xxxxxxxxxxxx", null),
)
@JvmStatic
fun getCalendar(year: Int, month: Int, date: Int): Calendar =
Calendar.getInstance().apply {
set(year, month, date)
}
@JvmStatic
@Suppress("LongParameterList")
fun getCalendar(year: Int, month: Int, date: Int, hourOfDay: Int, minute: Int, second: Int): Calendar =
Calendar.getInstance().apply {
set(year, month, date, hourOfDay, minute, second)
}
}
}
| 27 | null | 66 | 126 | c45a6ee4d2039163ae075436a9d1231ffcb16f5c | 5,846 | adyen-android | MIT License |
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day02.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.*
class Day02 : Day(title = "Inventory Management System") {
override fun first(input: Sequence<String>): Any = input
.asSequence()
.map { id -> id.groupingBy { it }.eachCount().values }
.fold(Pair(0, 0)) { (twos, threes), counts ->
Pair(
if (2 in counts) twos + 1 else twos,
if (3 in counts) threes + 1 else threes
)
}.let { (twos, threes) -> twos * threes }
override fun second(input: Sequence<String>): Any = input
.toList()
.tails()
.asSequence()
.flatMap { c -> c.head.let { head -> c.tail.map { Pair(head, it) }.asSequence() } }
.mapNotNull { (current, other) ->
current.extractCommonCharacters(other).takeIf { it.length == current.length - 1 }
}
.first()
private fun String.extractCommonCharacters(other: String): String =
this.iterator().extractCommonCharacters(other.iterator())
private fun CharIterator.extractCommonCharacters(other: CharIterator): String {
tailrec fun extractCommon(
t: Char,
o: Char,
diffs: Int,
acc: StringBuilder
): StringBuilder =
if (diffs > 1) acc
else if (!this.hasNext() || !other.hasNext()) acc.applyIf({ t == o }) { append(t) }
else if (t == o) extractCommon(this.next(), other.next(), diffs, acc.append(t))
else extractCommon(this.next(), other.next(), diffs + 1, acc)
return extractCommon(this.next(), other.next(), 0, StringBuilder()).toString()
}
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 1,751 | AdventOfCode | MIT License |
app/src/main/java/br/com/anderson/composefirstlook/domain/model/CityWeather.kt | andersonrsoares | 503,539,472 | false | null | package br.com.anderson.composefirstlook.domain.model
import android.os.Parcelable
import br.com.anderson.composefirstlook.domain.converter.TemperatureConverter
import kotlinx.parcelize.Parcelize
@Parcelize
data class CityWeather(
var description: String = "",
var urlIcon: String = "",
var temperature: Double = 0.0,
var city: String = "",
var date: Long = 0
) : Parcelable | 1 | Kotlin | 0 | 0 | e7168e43e2b317ea8be8cec1fd2959bae7ca6374 | 396 | weather-app | MIT License |
feature-staking-impl/src/main/java/com/edgeverse/wallet/feature_staking_impl/domain/rewards/RewardCalculatorFactory.kt | finn-exchange | 512,140,809 | false | {"Kotlin": 2956205, "Java": 14536, "JavaScript": 399} | package com.edgeverse.wallet.feature_staking_impl.domain.rewards
import com.edgeverse.wallet.feature_staking_api.domain.api.AccountIdMap
import com.edgeverse.wallet.feature_staking_api.domain.api.StakingRepository
import com.edgeverse.wallet.feature_staking_api.domain.api.getActiveElectedValidatorsExposures
import com.edgeverse.wallet.feature_staking_api.domain.model.Exposure
import com.edgeverse.wallet.feature_staking_api.domain.model.ValidatorPrefs
import com.edgeverse.wallet.feature_staking_impl.data.StakingSharedState
import com.edgeverse.wallet.feature_staking_impl.domain.error.accountIdNotFound
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class RewardCalculatorFactory(
private val stakingRepository: StakingRepository,
private val sharedState: StakingSharedState,
) {
suspend fun create(
exposures: AccountIdMap<Exposure>,
validatorsPrefs: AccountIdMap<ValidatorPrefs?>
): RewardCalculator = withContext(Dispatchers.Default) {
val chainId = sharedState.chainId()
val totalIssuance = stakingRepository.getTotalIssuance(chainId)
val validators = exposures.keys.mapNotNull { accountIdHex ->
val exposure = exposures[accountIdHex] ?: accountIdNotFound(accountIdHex)
val validatorPrefs = validatorsPrefs[accountIdHex] ?: return@mapNotNull null
RewardCalculationTarget(
accountIdHex = accountIdHex,
totalStake = exposure.total,
commission = validatorPrefs.commission
)
}
RewardCalculator(
validators = validators,
totalIssuance = totalIssuance
)
}
suspend fun create(): RewardCalculator = withContext(Dispatchers.Default) {
val chainId = sharedState.chainId()
val exposures = stakingRepository.getActiveElectedValidatorsExposures(chainId)
val validatorsPrefs = stakingRepository.getValidatorPrefs(chainId, exposures.keys.toList())
create(exposures, validatorsPrefs)
}
}
| 0 | Kotlin | 1 | 0 | 03229c4188cb56b0fb0340e60d60184c7afa2c75 | 2,064 | edgeverse-wallet | Apache License 2.0 |
diktat-rules/src/test/resources/test/paragraph3/boolean_expressions/BooleanExpressionsTest.kt | saveourtool | 275,879,956 | false | {"Kotlin": 2386437, "TeX": 190514, "Shell": 2900, "Batchfile": 541, "Makefile": 47} | package test.paragraph3.boolean_expressions
fun foo() {
if (some != null && some != null && some == 6) {
}
if ((some != null || c > 2) && (a > 4 || b > 3)) {
}
if (a > 3 && b > 3 && a > 3) {
}
if (!(a || b)) {}
if (!(a || b) && c) {}
} | 149 | Kotlin | 39 | 535 | 9e73d811d9fd9900af5917ba82ddeed0177ac52e | 275 | diktat | MIT License |
app/src/main/java/org/p2p/wallet/home/analytics/HomeAnalytics.kt | p2p-org | 306,035,988 | false | null | package org.p2p.wallet.home.analytics
import java.math.BigDecimal
import org.p2p.core.token.Token
import org.p2p.wallet.bridge.analytics.ClaimAnalytics
import org.p2p.wallet.common.analytics.Analytics
import org.p2p.wallet.common.analytics.constants.EventNames.HOME_USER_AGGREGATE_BALANCE
import org.p2p.wallet.common.analytics.constants.EventNames.HOME_USER_HAS_POSITIVE_BALANCE
import org.p2p.wallet.moonpay.analytics.BuyAnalytics
import org.p2p.wallet.newsend.analytics.NewSendAnalytics
import org.p2p.wallet.sell.analytics.SellAnalytics
import org.p2p.wallet.swap.analytics.SwapAnalytics
private const val TOKEN_DETAILS_CLICKED = "Main_Screen_Token_Details_Open"
private const val HOME_MAIN_WALLET = "Main_Wallet"
private const val HOME_MAIN_HISTORY = "Main_History"
private const val HOME_MAIN_SETTINGS = "Main_Settings"
private const val HOME_HIDDEN_TOKENS_CLICKED = "Main_Screen_Hidden_Tokens"
class HomeAnalytics(
private val tracker: Analytics,
private val claimAnalytics: ClaimAnalytics,
private val sendAnalytics: NewSendAnalytics,
private val sellAnalytics: SellAnalytics,
private val swapAnalytics: SwapAnalytics,
private val buyAnalytics: BuyAnalytics,
) {
fun logUserHasPositiveBalanceProperty(hasPositiveBalance: Boolean) {
tracker.setUserPropertyOnce(HOME_USER_HAS_POSITIVE_BALANCE, hasPositiveBalance)
logUserHasPositiveBalanceEvent(hasPositiveBalance)
}
fun logUserAggregateBalanceProperty(usdBalance: BigDecimal) {
tracker.setUserPropertyOnce(HOME_USER_AGGREGATE_BALANCE, usdBalance.toString())
logUserAggregateBalanceEvent(usdBalance)
}
fun logMainScreenTokenDetailsOpen(tokenTier: String) {
tracker.logEvent(
event = TOKEN_DETAILS_CLICKED,
params = mapOf(
"Token_Tier" to tokenTier
)
)
}
fun logHiddenTokensClicked() {
tracker.logEvent(HOME_HIDDEN_TOKENS_CLICKED)
}
fun logBottomNavigationHomeClicked() {
tracker.logEvent(event = HOME_MAIN_WALLET)
}
fun logBottomNavigationHistoryClicked() {
tracker.logEvent(HOME_MAIN_HISTORY)
}
fun logBottomNavigationSettingsClicked() {
tracker.logEvent(HOME_MAIN_SETTINGS)
}
private fun logUserAggregateBalanceEvent(usdBalance: BigDecimal) {
tracker.logEvent(
HOME_USER_AGGREGATE_BALANCE,
arrayOf("Usd_Balance" to usdBalance)
)
}
private fun logUserHasPositiveBalanceEvent(hasPositiveBalance: Boolean) {
tracker.logEvent(
HOME_USER_HAS_POSITIVE_BALANCE,
arrayOf("Has_Positive_Balance" to hasPositiveBalance)
)
}
fun logClaimButtonClicked() {
claimAnalytics.logClaimButtonClicked()
}
fun logSellSubmitClicked() {
sellAnalytics.logSellSubmitClicked()
}
fun logSwapActionButtonClicked() {
swapAnalytics.logSwapActionButtonClicked()
}
fun logTopupHomeBarClicked() {
buyAnalytics.logTopupHomeBarClicked()
}
fun logSendActionButtonClicked() {
sendAnalytics.logSendActionButtonClicked()
}
fun logClaimAvailable(ethTokens: List<Token.Eth>) {
claimAnalytics.logClaimAvailable(ethTokens.any { !it.isClaiming })
}
}
| 6 | Kotlin | 16 | 27 | 8caa107366b13512266ed975ca9db2a5a4fd396f | 3,286 | key-app-android | MIT License |
module_common/src/main/kotlin/life/chenshi/keepaccounts/module/common/database/dao/AssetsAccountDao.kt | SMAXLYB | 340,857,932 | false | null | package life.chenshi.keepaccounts.module.common.database.dao
import androidx.room.*
import kotlinx.coroutines.flow.Flow
import life.chenshi.keepaccounts.module.common.constant.TB_ASSETS_ACCOUNT
import life.chenshi.keepaccounts.module.common.database.entity.AssetsAccount
import java.math.BigDecimal
@Dao
interface AssetsAccountDao {
@Insert
suspend fun insertAssetsAccount(assetsAccount: AssetsAccount): Long
@Query("SELECT * FROM $TB_ASSETS_ACCOUNT")
fun getAllAssetsAccount(): Flow<List<AssetsAccount>>
@Delete
suspend fun deleteAssetsAccountBy(assetsAccount: AssetsAccount)
@Update
suspend fun updateAssetsAccount(assetsAccount: AssetsAccount): Int
@Query("SELECT * FROM $TB_ASSETS_ACCOUNT WHERE id = :id")
suspend fun getAssetsAccountById(id: Long): AssetsAccount?
// 使用sum查询如果没查到会返回Null, 使用total会返回0
@Query("SELECT TOTAL(balance) FROM $TB_ASSETS_ACCOUNT WHERE include_in_all_asset = 1")
fun getSumBalance(): Flow<BigDecimal>
} | 0 | Kotlin | 0 | 2 | 389632d87e90588555c10682a5804f6fddba5278 | 991 | KeepAccount | Apache License 2.0 |
core/domain/src/main/java/com/wap/wapp/core/domain/usecase/management/RegisterSurveyUseCase.kt | pknu-wap | 689,890,586 | false | {"Kotlin": 265360, "Shell": 233} | package com.wap.wapp.core.domain.usecase.management
import com.wap.wapp.core.data.repository.management.ManagementRepository
import com.wap.wapp.core.data.repository.user.UserRepository
import com.wap.wapp.core.model.event.Event
import com.wap.wapp.core.model.survey.SurveyForm
import com.wap.wapp.core.model.survey.SurveyQuestion
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import javax.inject.Inject
class RegisterSurveyUseCase @Inject constructor(
private val managementRepository: ManagementRepository,
private val userRepository: UserRepository,
) {
suspend operator fun invoke(
event: Event,
title: String,
content: String,
surveyQuestion: List<SurveyQuestion>,
deadlineDate: LocalDate,
deadlineTime: LocalTime,
): Result<Unit> {
return runCatching {
val userId = userRepository.getUserId().getOrThrow()
managementRepository.postSurveyForm(
SurveyForm(
eventId = event.eventId,
userId = userId,
title = title,
content = content,
surveyQuestion = surveyQuestion,
deadline = LocalDateTime.of(deadlineDate, deadlineTime),
),
)
}
}
}
| 3 | Kotlin | 1 | 8 | 787381e60e8b95f99bba78787454a623c8afaa2d | 1,352 | WAPP | MIT License |
domain/src/main/java/com/thumbs/android/thumbsAndroid/api/UserApi.kt | thumbs-project | 158,828,606 | false | null | package com.thumbs.android.thumbsAndroid.api
import com.thumbs.android.thumbsAndroid.model.Status
import com.thumbs.android.thumbsAndroid.model.StatusRequestParam
import com.thumbs.android.thumbsAndroid.model.User
import io.reactivex.Single
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
interface UserApi {
@POST("/")
fun getStatus(
@Body
statusRequestParam: StatusRequestParam
): Single<Status>
@GET("/get")
fun getUsers(): Single<User>
}
| 1 | Kotlin | 5 | 2 | 11d3a19e9afeafa7368429f68f1cf346cc7a12e4 | 495 | thumbs-android | MIT License |
app/src/androidTest/java/org/eurofurence/connavigator/ui/activities/LoginFragmentTest.kt | eurofurence | 50,885,645 | false | null | package org.eurofurence.connavigator.ui.activities
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.eurofurence.connavigator.R
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.hamcrest.core.IsInstanceOf
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class LoginFragmentTest {
@Test
fun loginActivityTest() {
val textView = onView(
allOf(withText("You're not logged in!"),
childAtPosition(
childAtPosition(
IsInstanceOf.instanceOf(android.widget.LinearLayout::class.java),
1),
0),
isDisplayed()))
textView.check(matches(withText("You're not logged in!")))
val _LinearLayout = onView(
allOf(childAtPosition(
allOf(withId(R.id.home_user_status),
childAtPosition(
withClassName(`is`("org.jetbrains.anko._LinearLayout")),
1)),
0),
isDisplayed()))
_LinearLayout.perform(click())
val _LinearLayout2 = onView(
allOf(childAtPosition(
allOf(withId(R.id.home_user_status),
childAtPosition(
withClassName(`is`("org.jetbrains.anko._LinearLayout")),
1)),
0),
isDisplayed()))
_LinearLayout2.perform(click())
val button = onView(
allOf(childAtPosition(
childAtPosition(
IsInstanceOf.instanceOf(android.widget.LinearLayout::class.java),
1),
4),
isDisplayed()))
button.check(matches(isDisplayed()))
pressBack()
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
| 21 | null | 5 | 13 | 3da7b778cda0a9b39a5172bf48cb3cbc27604de8 | 3,305 | ef-app_android | MIT License |
app/src/main/java/com/nawrot/mateusz/recipey/base/BaseActivity.kt | mateusz-nawrot | 109,833,275 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Kotlin": 35, "Proguard": 2, "XML": 27, "Java": 2} | package com.nawrot.mateusz.recipey.base
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
open class BaseActivity : AppCompatActivity() {
fun initToolbar(toolbar: Toolbar, navigationIconEnabled: Boolean? = null) {
setSupportActionBar(toolbar)
navigationIconEnabled?.let { supportActionBar?.setDisplayHomeAsUpEnabled(navigationIconEnabled) }
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
} | 0 | Kotlin | 0 | 0 | a9750fc944886f785ec1be8311108352ea616376 | 708 | recipey | Apache License 2.0 |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/demo/DanceAuton.kt | titanium-knights | 424,002,290 | false | {"Java": 381417, "Kotlin": 34984, "Shell": 561} | package org.firstinspires.ftc.teamcode.demo
import com.qualcomm.robotcore.eventloop.opmode.Autonomous
import org.firstinspires.ftc.teamcode.util.Slide2
@Autonomous(name = "Dance", group = "Demo")
class DanceAuton: TimepointAuton() {
override fun setup() {
at(0) {
drive.turnRightWithPower(1.0)
intake.spin()
slideTargetPosition = (Slide2.MIN_POSITION + Slide2.MAX_POSITION) / 2
}
after(1.0) {
drive.turnLeftWithPower(1.0)
intake.outtake()
slideTargetPosition = Slide2.MIN_POSITION + 10
}
after(1.0) {
drive.driveForwardsWithPower(1.0)
intake.stop()
}
after(0.5) {
drive.driveForwardsWithPower(-1.0)
}
after(0.5) {
drive.stop()
slideTargetPosition = Slide2.MAX_POSITION - 10
}
after(1.0) {
slideTargetPosition = Slide2.MIN_POSITION + 10
drive.driveForwardsWithPower(-1.0)
}
after(0.5) {
drive.driveForwardsWithPower(1.0)
}
after(0.5) {
drive.stop()
restart()
}
}
} | 1 | Java | 1 | 1 | a570b84a21c1ef122404c5d2665b3bea30936229 | 1,200 | team-a-2021-2022 | MIT License |
customize/order/src/main/java/com/tzt/customize/order/widget/SuperOndrawAboveView.kt | tzt1994 | 263,828,419 | false | null | package com.tzt.customize.order.widget
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
/**
* Description: super.onDraw()上面
* @author tangzhentao
* @since 2020/5/6
*/
class SuperOndrawAboveView: AppCompatTextView {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor("#FFD700")
}
constructor(context: Context): this(context, null)
constructor(context: Context, attributeSet: AttributeSet?): this(context, attributeSet, 0)
constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int): super(context, attributeSet, defStyleAttr)
override fun onDraw(canvas: Canvas?) {
canvas?.drawRect(0f , 0f, width * 1f, height / 4f ,paint)
canvas?.drawRect(0f, height / 4f * 3, width * 1f, height * 1f ,paint)
super.onDraw(canvas)
}
} | 0 | Kotlin | 1 | 5 | b3ede59ae12d614fc827dddb5c506cb103cc3211 | 931 | customizeKt | Apache License 2.0 |
src/main/java/org/tokend/sdk/api/requests/model/limits/LimitsUpdateDetailsHolder.kt | TamaraGambarova | 291,018,574 | true | {"Kotlin": 715884, "Java": 293039, "Ruby": 13011} | package org.tokend.sdk.api.requests.model.limits
import com.google.gson.annotations.SerializedName
class LimitsUpdateDetailsHolder(
@SerializedName("document_hash")
val documentHash: String,
@SerializedName("details")
val details: LimitsUpdateDetails
) | 0 | Kotlin | 0 | 1 | 941186aee243d0639d72e7ee189d509afc6292b9 | 286 | kotlin-sdk | Apache License 2.0 |
airbyte-cdk/java/airbyte-cdk/gcs-destinations/src/main/kotlin/io/airbyte/cdk/integrations/destination/gcs/GcsStorageOperations.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.cdk.integrations.destination.gcs
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.model.DeleteObjectsRequest
import io.airbyte.cdk.integrations.destination.NamingConventionTransformer
import io.airbyte.cdk.integrations.destination.s3.S3DestinationConfig
import io.airbyte.cdk.integrations.destination.s3.S3StorageOperations
import io.github.oshai.kotlinlogging.KotlinLogging
private val LOGGER = KotlinLogging.logger {}
class GcsStorageOperations(
nameTransformer: NamingConventionTransformer,
s3Client: AmazonS3,
s3Config: S3DestinationConfig
) : S3StorageOperations(nameTransformer, s3Client, s3Config) {
/** GCS only supports the legacy AmazonS3#doesBucketExist method. */
override fun doesBucketExist(bucket: String?): Boolean {
@Suppress("deprecation") return s3Client.doesBucketExist(bucket)
}
/**
* This method is overridden because GCS doesn't accept request to delete multiple objects. The
* only difference is that the AmazonS3#deleteObjects method is replaced with
* AmazonS3#deleteObject.
*/
override fun cleanUpObjects(
bucket: String?,
keysToDelete: List<DeleteObjectsRequest.KeyVersion>
) {
for (keyToDelete in keysToDelete) {
LOGGER.info { "Deleting object ${keyToDelete.key}" }
s3Client.deleteObject(bucket, keyToDelete.key)
}
}
override fun getMetadataMapping(): Map<String, String> {
return HashMap()
}
companion object {}
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 1,604 | airbyte | MIT License |
camera-core/src/main/java/com/stripe/android/camera/scanui/SimpleScanStateful.kt | stripe | 6,926,049 | false | null | package com.stripe.android.camera.scanui
import android.util.Log
import androidx.annotation.RestrictTo
import com.stripe.android.camera.framework.AnalyzerLoopErrorListener
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
abstract class ScanState(val isFinal: Boolean)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
interface SimpleScanStateful<State : ScanState> {
var scanStatePrevious: State?
var scanState: State?
val scanErrorListener: ScanErrorListener
fun displayState(newState: State, previousState: State?)
fun changeScanState(newState: State): Boolean {
if (newState == scanStatePrevious || scanStatePrevious?.isFinal == true) {
return false
}
scanState = newState
displayState(newState, scanStatePrevious)
scanStatePrevious = newState
return true
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class ScanErrorListener : AnalyzerLoopErrorListener {
override fun onAnalyzerFailure(t: Throwable): Boolean {
Log.e(TAG, "Error executing analyzer", t)
return false
}
override fun onResultFailure(t: Throwable): Boolean {
Log.e(TAG, "Error executing result", t)
return true
}
private companion object {
val TAG: String = SimpleScanStateful::class.java.simpleName
}
}
| 64 | null | 522 | 935 | bec4fc5f45b5401a98a310f7ebe5d383693936ea | 1,321 | stripe-android | MIT License |
app/src/main/java/com/strvacademy/drabekj/movieapp/model/remote/rest/RestResponseHandler.kt | drabekj | 98,216,289 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Kotlin": 105, "XML": 63, "Java": 4} | package com.strvacademy.drabekj.movieapp.model.remote.rest
import com.strvacademy.drabekj.movieapp.model.entity.ErrorEntity
import org.alfonz.rest.HttpException
import org.alfonz.rest.ResponseHandler
import retrofit2.Response
class RestResponseHandler : ResponseHandler {
override fun isSuccess(response: Response<*>): Boolean {
return response.isSuccessful
}
override fun getErrorMessage(exception: HttpException): String {
val error = exception.error() as ErrorEntity
return error.statusMessage!!
}
override fun getFailMessage(throwable: Throwable): String {
return throwable.localizedMessage
}
override fun createHttpException(response: Response<*>): HttpException {
return RestHttpException(response)
}
} | 0 | Kotlin | 0 | 3 | 980539fcfc8da00eed52f7f255050e7e0d861432 | 734 | MovieApp | Apache License 2.0 |
src/main/java/com/resuscitation/Instagram/user/entity/UserEntity.kt | Team-Resuscitation | 675,347,330 | false | {"Java": 34331, "Kotlin": 6557} | package com.resuscitation.Instagram.user.entity
import jakarta.persistence.*
@Entity
public class UserEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var idx: Long= 0,
@Column(unique = true)
var nickname: String = "",
@Column(unique = true)
var email: String = "",
var password: String = "",
var name: String = "",
var introduce: String = "",
var profileImage: String = "",
@Column(unique = true)
var oauthToken: String? = null,
@ElementCollection(fetch = FetchType.EAGER)
var roles: MutableList<UserRole> = mutableListOf()
) {
override fun toString(): String {
return "UserEntity(idx=$idx, nickname='$nickname', email='$email', password='$password', name='$name', introduce='$introduce', oauthToken=$oauthToken)"
}
} | 1 | null | 1 | 1 | 59a423e6a92ef7b5b00a7c5403501b5f1cfc5ca3 | 881 | instagram-Server | MIT License |
server/src/main/com/broll/gainea/server/core/cards/impl/play/C_Barriere.kt | Rolleander | 253,573,579 | false | {"Kotlin": 521531, "Java": 313909, "HTML": 1714, "CSS": 1069, "Shell": 104, "Batchfile": 100, "JavaScript": 24} | package com.broll.gainea.server.core.cards.impl.play
import com.broll.gainea.net.NT_Event
import com.broll.gainea.server.core.cards.Card
import com.broll.gainea.server.core.cards.EffectType
import com.broll.gainea.server.core.objects.buffs.BuffType
import com.broll.gainea.server.core.objects.buffs.GlobalBuff
import com.broll.gainea.server.core.objects.buffs.IntBuff
import com.broll.gainea.server.core.processing.rounds
class C_Barriere : Card(
41,
EffectType.BUFF,
"Magische Barriere",
"Eure Einheiten erhalten +" + BUFF + " Leben für " + DURATION + " Runden, können solange aber nicht mehr angreifen."
) {
init {
drawChance = 0.4f
}
override val isPlayable: Boolean
get() = true
override fun play() {
val healthBuff = IntBuff(BuffType.ADD, BUFF)
val noAttackBuff = IntBuff(BuffType.SET, 0)
GlobalBuff.createForPlayer(
game,
owner,
healthBuff,
{ it.addHealthBuff(healthBuff) },
NT_Event.EFFECT_BUFF
)
GlobalBuff.createForPlayer(
game,
owner,
noAttackBuff,
{ it.attacksPerTurn.addBuff(noAttackBuff) },
NT_Event.EFFECT_DEBUFF
)
game.buffProcessor.timeoutBuff(healthBuff, rounds(DURATION))
game.buffProcessor.timeoutBuff(noAttackBuff, rounds(DURATION))
}
companion object {
private const val DURATION = 3
private const val BUFF = 2
}
}
| 0 | Kotlin | 0 | 3 | ab47587c08ce2884269653a49c8fd8351cc4349f | 1,501 | Gainea | MIT License |
KeepNotesPhone/src/main/java/net/geeksempire/ready/keep/notes/EntryConfigurations.kt | eliasdfazel | 320,059,275 | false | {"Kotlin": 582291, "Java": 349087, "HTML": 6718, "JavaScript": 1135} | /*
* Copyright © 2021 By Geeks Empire.
*
* Created by <NAME>
* Last modified 4/12/21 8:50 AM
*
* Licensed Under MIT License.
* https://opensource.org/licenses/MIT
*/
package net.geeksempire.ready.keep.notes
import android.Manifest
import android.app.ActivityOptions
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.View
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.main.offline_indicator.view.*
import net.geeksempire.ready.keep.notes.AccountManager.SignInProcess.SetupAccount
import net.geeksempire.ready.keep.notes.AccountManager.Utils.UserInformationIO
import net.geeksempire.ready.keep.notes.Browser.BuiltInBrowser
import net.geeksempire.ready.keep.notes.Notes.Taking.TakeNote
import net.geeksempire.ready.keep.notes.Overview.UserInterface.KeepNoteOverview
import net.geeksempire.ready.keep.notes.SecurityConfiguratios.Biometric.BiometricAuthentication
import net.geeksempire.ready.keep.notes.SecurityConfiguratios.Checkpoint.SecurityCheckpoint
import net.geeksempire.ready.keep.notes.Utils.Network.NetworkCheckpoint
import net.geeksempire.ready.keep.notes.Utils.Network.NetworkConnectionListener
import net.geeksempire.ready.keep.notes.Utils.Network.NetworkConnectionListenerInterface
import net.geeksempire.ready.keep.notes.Utils.UI.NotifyUser.SnackbarActionHandlerInterface
import net.geeksempire.ready.keep.notes.Utils.UI.NotifyUser.SnackbarBuilder
import net.geeksempire.ready.keep.notes.databinding.EntryConfigurationLayoutBinding
import java.util.*
import javax.inject.Inject
class EntryConfigurations : AppCompatActivity(), NetworkConnectionListenerInterface {
private val securityCheckpoint: SecurityCheckpoint by lazy {
SecurityCheckpoint(applicationContext)
}
private val userInformationIO: UserInformationIO by lazy {
UserInformationIO(applicationContext)
}
lateinit var signInSuccessListener: OnSuccessListener<AuthResult>
lateinit var signInFailureListener: OnFailureListener
@Inject lateinit var networkCheckpoint: NetworkCheckpoint
@Inject lateinit var networkConnectionListener: NetworkConnectionListener
lateinit var entryConfigurationLayoutBinding: EntryConfigurationLayoutBinding
companion object {
const val PermissionRequestCode: Int = 123
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
entryConfigurationLayoutBinding = EntryConfigurationLayoutBinding.inflate(layoutInflater)
setContentView(entryConfigurationLayoutBinding.root)
(application as KeepNoteApplication)
.dependencyGraph
.subDependencyGraph()
.create(this@EntryConfigurations, entryConfigurationLayoutBinding.rootView)
.inject(this@EntryConfigurations)
networkConnectionListener.networkConnectionListenerInterface = this@EntryConfigurations
if (networkCheckpoint.networkConnection()) {
if (userInformationIO.readPrivacyAgreement()
&& checkAllPermissions()
&& Firebase.auth.currentUser != null) {
entryConfigurationLayoutBinding.agreementDataView.visibility = View.INVISIBLE
entryConfigurationLayoutBinding.proceedButton.visibility = View.INVISIBLE
openOverviewActivity()
} else if (userInformationIO.readPrivacyAgreement()) {
entryConfigurationLayoutBinding.agreementDataView.visibility = View.INVISIBLE
entryConfigurationLayoutBinding.proceedButton.visibility = View.INVISIBLE
runtimePermission()
} else {
window.setBackgroundDrawable(getDrawable(R.drawable.splash_screen_initial))
entryConfigurationLayoutBinding.agreementDataView.visibility = View.VISIBLE
entryConfigurationLayoutBinding.proceedButton.visibility = View.VISIBLE
entryConfigurationLayoutBinding.blurryBackground.startAnimation(AnimationUtils.loadAnimation(applicationContext, android.R.anim.fade_in))
entryConfigurationLayoutBinding.blurryBackground.visibility = View.VISIBLE
entryConfigurationLayoutBinding.proceedButton.setOnClickListener {
userInformationIO.savePrivacyAgreement()
Handler(Looper.getMainLooper()).postDelayed({
entryConfigurationLayoutBinding.agreementDataView.startAnimation(AnimationUtils.loadAnimation(applicationContext, android.R.anim.fade_out))
entryConfigurationLayoutBinding.agreementDataView.visibility = View.INVISIBLE
entryConfigurationLayoutBinding.proceedButton.startAnimation(AnimationUtils.loadAnimation(applicationContext, android.R.anim.fade_out))
entryConfigurationLayoutBinding.proceedButton.visibility = View.INVISIBLE
runtimePermission()
}, 333)
}
entryConfigurationLayoutBinding.agreementDataView.setOnClickListener {
BuiltInBrowser.show(
context = applicationContext,
linkToLoad = getString(R.string.privacyAgreementLink),
gradientColorOne = getColor(R.color.default_color_dark),
gradientColorTwo = getColor(R.color.default_color_game_dark)
)
}
}
} else {
SnackbarBuilder(applicationContext).show (
rootView = entryConfigurationLayoutBinding.rootView,
messageText= getString(R.string.noNetworkConnection),
messageDuration = Snackbar.LENGTH_INDEFINITE,
actionButtonText = android.R.string.ok,
snackbarActionHandlerInterface = object : SnackbarActionHandlerInterface {
override fun onActionButtonClicked(snackbar: Snackbar) {
super.onActionButtonClicked(snackbar)
startActivity(
Intent(Settings.ACTION_WIFI_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
[email protected]()
}
}
)
}
}
override fun onPause() {
super.onPause()
}
override fun onRequestPermissionsResult(requestCode: Int, permissionsList: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissionsList, grantResults)
when (requestCode) {
EntryConfigurations.PermissionRequestCode -> {
if (checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.CHANGE_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.WAKE_LOCK) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.VIBRATE) == PackageManager.PERMISSION_GRANTED) {
val setupAccount = SetupAccount()
if (setupAccount.firebaseUser == null) {
entryConfigurationLayoutBinding.blurryBackground.visibility = View.VISIBLE
entryConfigurationLayoutBinding.waitingView.startAnimation(AnimationUtils.loadAnimation(applicationContext, android.R.anim.fade_in))
entryConfigurationLayoutBinding.waitingView.visibility = View.VISIBLE
entryConfigurationLayoutBinding.waitingInformationView.startAnimation(AnimationUtils.loadAnimation(applicationContext, android.R.anim.fade_in))
entryConfigurationLayoutBinding.waitingInformationView.visibility = View.VISIBLE
signInSuccessListener = OnSuccessListener<AuthResult> {
entryConfigurationLayoutBinding.waitingView.visibility = View.GONE
entryConfigurationLayoutBinding.waitingInformationView.visibility = View.GONE
it.user?.let { firebaseUser ->
userInformationIO.saveOldFirebaseUniqueIdentifier(firebaseUser.uid)
}
openTakeNoteActivity()
}
signInFailureListener = OnFailureListener { exception ->
exception.printStackTrace()
SnackbarBuilder(applicationContext).show (
rootView = entryConfigurationLayoutBinding.rootView,
messageText= getString(R.string.anonymouslySignInError),
messageDuration = Snackbar.LENGTH_INDEFINITE,
actionButtonText = R.string.retryText,
snackbarActionHandlerInterface = object : SnackbarActionHandlerInterface {
override fun onActionButtonClicked(snackbar: Snackbar) {
super.onActionButtonClicked(snackbar)
invokeAccountSetup(setupAccount, signInSuccessListener, signInFailureListener)
}
}
)
}
invokeAccountSetup(setupAccount, signInSuccessListener, signInFailureListener)
} else {
openOverviewActivity()
}
} else {
runtimePermissionMessage()
}
}
}
}
override fun networkAvailable() {
}
override fun networkLost() {
}
private fun openOverviewActivity() {
if (securityCheckpoint.securityEnabled()) {
BiometricAuthentication(this@EntryConfigurations)
.startAuthenticationProcess()
} else {
startActivity(Intent(applicationContext, KeepNoteOverview::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}, ActivityOptions.makeCustomAnimation(applicationContext, R.anim.fade_in, android.R.anim.fade_out).toBundle())
[email protected]()
}
}
private fun openTakeNoteActivity() {
TakeNote.open(context = applicationContext,
incomingActivityName = EntryConfigurations::class.java.simpleName,
extraConfigurations = TakeNote.NoteConfigurations.KeyboardTyping,
encryptedTextContent = false)
[email protected]()
}
private fun invokeAccountSetup(setupAccount: SetupAccount, signInSuccessListener: OnSuccessListener<AuthResult>, signInFailureListener: OnFailureListener) {
setupAccount.signInAnonymously().also { signInAnonymously ->
signInAnonymously.addOnSuccessListener(signInSuccessListener)
signInAnonymously.addOnFailureListener(signInFailureListener)
}
}
private fun runtimePermission() {
val permissionsList = arrayListOf(
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.CHANGE_NETWORK_STATE,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_CALENDAR,
Manifest.permission.READ_CALENDAR,
Manifest.permission.WAKE_LOCK,
Manifest.permission.VIBRATE
)
requestPermissions(
permissionsList.toTypedArray(),
EntryConfigurations.PermissionRequestCode
)
}
private fun checkAllPermissions() : Boolean {
return (checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.CHANGE_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.WAKE_LOCK) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.VIBRATE) == PackageManager.PERMISSION_GRANTED)
}
private fun runtimePermissionMessage() {
SnackbarBuilder(applicationContext).show (
rootView = entryConfigurationLayoutBinding.rootView,
messageText= getString(R.string.permissionMessage),
messageDuration = Snackbar.LENGTH_INDEFINITE,
actionButtonText = R.string.grantPermission,
snackbarActionHandlerInterface = object : SnackbarActionHandlerInterface {
override fun onActionButtonClicked(snackbar: Snackbar) {
super.onActionButtonClicked(snackbar)
runtimePermission()
}
}
)
}
} | 0 | Kotlin | 0 | 2 | 0294e1d30a24b7703c803223451dce1d4bff9fbd | 14,735 | ReadyKeepNotes | MIT License |
app/src/main/java/com/github/pavelkv96/portfolioapp/sidemenu/MenuViewHolder.kt | pavelkv96 | 345,286,720 | false | null | package com.github.pavelkv96.portfolioapp.sidemenu
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.github.pavelkv96.portfolioapp.R
class MenuViewHolder(itemView: View, listener: (Int) -> Unit) : RecyclerView.ViewHolder(itemView) {
private val icon: ImageView = itemView.findViewById(R.id.item_menu_icon)
private val isSelected: ImageView = itemView.findViewById(R.id.item_menu_selected)
init {
itemView.setOnClickListener { listener.invoke(adapterPosition) }
}
fun bind(item: MenuItem) {
Glide.with(itemView).load(item.icon).into(icon)
if (item.isSelected) isSelected.visibility = View.VISIBLE else isSelected.visibility = View.GONE
}
} | 1 | null | 1 | 1 | a4f7f379ddfc0b2e445c9a23f8b53fa74d5a3af0 | 790 | PortfolioApp | Apache License 2.0 |
ui-toolkit/src/main/kotlin/io/snabble/sdk/widgets/snabble/locationpermission/usecases/HasLocationPermissionUseCase.kt | snabble | 124,525,499 | false | null | package io.snabble.sdk.widgets.snabble.locationpermission.usecases
import android.util.Log
import io.snabble.sdk.Snabble
internal interface HasLocationPermissionUseCase {
operator fun invoke(): Boolean
}
internal class HasLocationPermissionUseCaseImpl(
private val snabble: Snabble,
) : HasLocationPermissionUseCase {
override operator fun invoke(): Boolean =
try {
snabble.checkInLocationManager.checkLocationPermission()
} catch (e: UninitializedPropertyAccessException) {
Log.d(this.javaClass.name, "invokeError: ${e.message} ")
true
}
}
| 2 | null | 1 | 6 | 529f14b276b6b0250df3c7525479e607a7db4554 | 618 | Android-SDK | MIT License |
compiler/testData/codegen/boxWithStdlib/reflection/classLiterals/arrays.kt | staltz | 38,581,975 | true | {"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831} | import kotlin.test.*
import kotlin.reflect.jvm.*
fun box(): String {
val any = Array<Any>::class
val string = Array<String>::class
assertNotEquals(any, string)
assertNotEquals(any.java, string.java)
return "OK"
}
| 0 | Java | 0 | 1 | 80074c71fa925a1c7173e3fffeea4cdc5872460f | 236 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/inventory/ui/item/ItemEditViewModel.kt | Tyronexx | 653,736,749 | false | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.inventory.ui.item
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.inventory.data.ItemsRepository
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
/**
* ViewModel to retrieve and update an item from the [ItemsRepository]'s data source.
*/
class ItemEditViewModel(
savedStateHandle: SavedStateHandle,
private val itemsRepository: ItemsRepository
) : ViewModel() {
/**
* Holds current item ui state
*/
var itemUiState by mutableStateOf(ItemUiState())
private set
private val itemId: Int = checkNotNull(savedStateHandle[ItemEditDestination.itemIdArg])
// implementation (this will retrieve the item entity details and populate the edit page)
init {
viewModelScope.launch {
// retrieve the entity details with itemsRepository.getItemStream(itemId).
itemUiState = itemsRepository.getItemStream(itemId)
.filterNotNull() // filter to return a flow that only contains values that are not null
.first()
.toItemUiState(actionEnabled = true) // convert the item entity to ItemUiState //pass the actionEnabled value as true to enable the Save button.
}
}
/** This function updates the itemUiState with new values that the user enters.*/
fun updateUiState(newItemUiState: ItemUiState){
// The app enables the Save button if actionEnabled is true. You set this value to true only if the input that the user enters is valid.
itemUiState = newItemUiState.copy(
actionEnabled = newItemUiState.isValid()
)
}
/**This function saves the updated entity to the Room database*/
suspend fun updateItem(){
if (itemUiState.isValid()){
itemsRepository.updateItem(itemUiState.toItem())
}
}
}
| 0 | Kotlin | 0 | 0 | 3d9506df8e22a771906af4c22a53a532cb766070 | 2,735 | Inventory_App | Apache License 2.0 |
app/src/main/java/jet/pack/compose/masterdetails/ui/theme/Theme.kt | damienlo | 353,440,081 | false | null | package jet.pack.compose.masterdetails.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = darkColors(
primary = LightBlue500,
primaryVariant = DeepBlue.copy(alpha = .8f),
secondary = NiceYellow500,
background = DarkGray,
surface = DarkGray500,
onPrimary = Color.White.copy(alpha = .8f),
onSecondary = DarkGray,
onBackground = Color.White.copy(alpha = .8f),
onSurface = Color.White.copy(alpha = .8f),
error = ElectricRed500,
onError = DarkGray
)
private val LightColorPalette = lightColors(
primary = LightBlue,
primaryVariant = DeepBlue,
secondary = NiceYellow,
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = DarkGray.copy(alpha = .8f),
onBackground = DarkGray.copy(alpha = .8f),
onSurface = DarkGray.copy(alpha = .8f),
error = ElectricRed,
onError = Color.White
)
@Composable
fun MasterDetailsTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | 0 | Kotlin | 0 | 3 | 5694b9dca530339b300e578923d8980771096f81 | 1,527 | Compose-Pokemon-List-Details | Beerware License |
travelmaker_android/app/src/main/java/com/gumibom/travelmaker/data/dto/request/RequestDto.kt | Leewoogun | 767,396,774 | false | {"Kotlin": 481004, "Java": 174550, "HTML": 4622, "Dockerfile": 516} | package com.gumibom.travelmaker.data.dto.request
data class RequestDto(
val birth: String,
val categories: List<String>,
val email: String,
val gender: String,
val nation: String,
val nickname: String,
val password: String,
val phone: String,
val town: String,
val username: String
) | 0 | Kotlin | 0 | 0 | 04e4d7a7a2b613db4a4c9181d015b23b58ea7f70 | 324 | TravelMaker | Apache License 1.1 |
app/src/main/java/br/com/gondim/orgs/ui/dialog/FormularioImagemDialog.kt | IagoGondim | 643,031,862 | false | null | package br.com.gondim.orgs.ui.dialog
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import br.com.gondim.orgs.databinding.FormularioImagemBinding
import br.com.gondim.orgs.extensions.tentaCarregarImagem
class FormularioImagemDialog(private val context: Context) {
fun mostra(
urlPadrao: String? = null,
quandoImagemCarregada: (imagem: String) -> Unit
) {
FormularioImagemBinding
.inflate(LayoutInflater.from(context)).apply {
urlPadrao?.let {
formularioImagemImageview.tentaCarregarImagem(it)
formularioImagemUrl.setText(it)
}
formularioImagemBotaoCarregar.setOnClickListener {
val url = formularioImagemUrl.text.toString()
formularioImagemImageview.tentaCarregarImagem(url)
}
AlertDialog.Builder(context)
.setView(root)
.setPositiveButton("Confirmar") { _, _ ->
val url = formularioImagemUrl.text.toString()
quandoImagemCarregada(url)
}
.setNegativeButton("Cancelar") { _, _ ->
}
.show()
}
}
} | 0 | Kotlin | 0 | 0 | 9f1d326e8334b94a8e15ef376ee8724bd3a6a4f1 | 1,215 | list-orgs | MIT License |
composeApp/src/commonMain/kotlin/App.kt | open-tool | 312,407,423 | false | {"Kotlin": 861507, "Java": 13304, "HTML": 3222, "Swift": 594, "Batchfile": 236, "Shell": 236, "CSS": 102} | import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.ui.tooling.preview.Preview
import ui.screens.ContactsListScreen
import ultron.composeapp.generated.resources.Res
import ultron.composeapp.generated.resources.compose_multiplatform
@Composable
@Preview
fun App() {
MaterialTheme {
var showContent by remember { mutableStateOf(false) }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = { showContent = !showContent }) {
Text("Click me!")
}
AnimatedVisibility(showContent) {
val greeting = remember { Greeting().greet() }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Image(painterResource(Res.drawable.compose_multiplatform), null)
Text("Compose: $greeting", modifier = Modifier.semantics { testTag = "greeting" })
}
}
ContactsListScreen()
}
}
} | 8 | Kotlin | 10 | 99 | 7d19d4e0a653acc87b823b7b0c806b226faafb12 | 1,589 | ultron | Apache License 2.0 |
src/main/kotlin/org/carPooling/groupsOfPeople/infrastructure/controller/dropOff/DropOffController.kt | ortzit | 588,298,236 | false | null | package org.carPooling.groupsOfPeople.infrastructure.controller.dropOff
import org.carPooling.groupsOfPeople.application.dropOff.DropOffGroupOfPeopleCommand
import org.carPooling.groupsOfPeople.application.dropOff.DropOffGroupOfPeopleUseCase
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
class DropOffController @Autowired constructor(
private val dropOffGroupOfPeopleUseCase: DropOffGroupOfPeopleUseCase,
private val responseEntityFactory: DropOffResponseEntityFactory,
) {
private val logger: Logger = LoggerFactory.getLogger(this::class.java)
@PostMapping(
path = [DROPOFF_PATH],
consumes = [MediaType.APPLICATION_FORM_URLENCODED_VALUE],
)
fun dropOff(@RequestParam(name = DROPOFF_ID_PARAM) id: Int): ResponseEntity<*> {
logger.debug("Request received in [$DROPOFF_PATH] - $DROPOFF_ID_PARAM: [$id]")
return DropOffGroupOfPeopleCommand(id)
.let { command ->
try {
dropOffGroupOfPeopleUseCase.run(command)
} catch (ex: Exception) {
ex
}.let { response ->
responseEntityFactory.build(response)
}
}
}
companion object {
private const val DROPOFF_PATH = "/dropoff"
private const val DROPOFF_ID_PARAM = "ID"
}
} | 0 | Kotlin | 0 | 0 | a39c6ad957e366480e19adef9a6089e1300535d1 | 1,701 | car-pooling | MIT License |
sample-backend-service/src/main/kotlin/com/example/notification/service/RedisService.kt | awarenessxz | 476,939,977 | false | null | package com.example.notification.service
import com.example.notification.redis.AbstractRedisService
import com.example.notification.redis.RedisClientProperties
import org.springframework.data.redis.core.ReactiveRedisTemplate
import org.springframework.stereotype.Service
@Service
class RedisService(
reactiveRedisTemplate: ReactiveRedisTemplate<String, String>,
redisClientProperties: RedisClientProperties
): AbstractRedisService(reactiveRedisTemplate, redisClientProperties) {
override fun processReceivedMessage(topic: String, message: String) {
logger.info("Processing redis event - topic: $topic, message: $message")
}
} | 0 | Kotlin | 0 | 0 | 33351cc3c2b407fa1469c227e486564affcbca1a | 651 | notification-websockets | Apache License 2.0 |
app/src/main/java/com/josejordan/rickmortyapp/ui/home/components/CharacterListScreen.kt | mundodigitalpro | 662,102,982 | false | null | package com.josejordan.rickmortyapp.ui.home.components
import androidx.compose.runtime.Composable
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.livedata.observeAsState
import com.josejordan.rickmortyapp.viewmodel.CharacterListViewModel
@Composable
fun CharacterListScreen() {
val viewModel: CharacterListViewModel = viewModel()
val characters = viewModel.characters.observeAsState(initial = emptyList()).value
LazyColumn {
items(characters) { character ->
CharacterListItem(character)
}
}
}
/*@Composable
fun CharacterListScreen() {
val viewModel: CharacterListViewModel = viewModel()
val characters = viewModel.characters.value ?: emptyList()
LazyColumn {
items(characters) { character ->
CharacterListItem(character)
}
}
}*/
| 0 | Kotlin | 0 | 0 | aad39073088387658d07b11b9f017678c7c3ba5e | 958 | RickMortyApp | MIT License |
src/main/java/uk/gov/justice/digital/hmpps/whereabouts/dto/VideoLinkBookingUpdateSpecification.kt | uk-gov-mirror | 356,783,561 | false | {"Gradle Kotlin DSL": 2, "YAML": 20, "Dockerfile": 1, "INI": 5, "Shell": 4, "Java Properties": 11, "Text": 3, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Markdown": 3, "JSON": 14, "Kotlin": 155, "Java": 26, "Public Key": 1, "XML": 1, "SQL": 17, "Mustache": 2} | package uk.gov.justice.digital.hmpps.whereabouts.dto
import io.swagger.annotations.ApiModelProperty
import javax.validation.Valid
data class VideoLinkBookingUpdateSpecification(
@ApiModelProperty(value = "Free text comments", example = "Requires special access")
val comment: String? = null,
@ApiModelProperty(value = "Pre-hearing appointment")
@Valid
val pre: VideoLinkAppointmentSpecification? = null,
@ApiModelProperty(value = "Main appointment", required = true)
@field:Valid
val main: VideoLinkAppointmentSpecification,
@ApiModelProperty(value = "Post-hearing appointment")
@Valid
val post: VideoLinkAppointmentSpecification? = null
)
| 1 | null | 1 | 1 | fcb65de589127fb83239a288c579b6fe8db4fde6 | 668 | ministryofjustice.whereabouts-api | Apache License 2.0 |
shared/java/top/fpsmaster/ui/screens/oobe/impls/Login.kt | FPSMasterTeam | 816,161,662 | false | {"Java": 620089, "Kotlin": 396547, "GLSL": 2647} | package top.fpsmaster.ui.screens.oobe.impls
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.ScaledResolution
import top.fpsmaster.FPSMaster
import top.fpsmaster.modules.account.AccountManager.Companion.login
import top.fpsmaster.ui.common.TextField
import top.fpsmaster.ui.screens.oobe.Scene
import top.fpsmaster.ui.common.GuiButton
import top.fpsmaster.ui.screens.mainmenu.MainMenu
import top.fpsmaster.utils.math.animation.ColorAnimation
import top.fpsmaster.utils.math.animation.Type
import top.fpsmaster.utils.os.FileUtils.saveTempValue
import top.fpsmaster.utils.render.Render2DUtils
import java.awt.Color
import java.awt.Desktop
import java.net.URI
class Login(isOOBE: Boolean) : Scene() {
private var msg: String? = null
private var msgbox = false
var btn: GuiButton
private var btn2: GuiButton
private var username: TextField =
TextField(
FPSMaster.fontManager.s18,
false,
FPSMaster.i18n["oobe.login.username"],
-1,
Color(200, 200, 200).rgb,
32
)
private var password: TextField =
TextField(
FPSMaster.fontManager.s18,
true,
FPSMaster.i18n["oobe.login.password"],
-1,
Color(200, 200, 200).rgb,
32
)
private var msgBoxAnimation = ColorAnimation(Color(0, 0, 0, 0))
init {
username.text = FPSMaster.configManager.configure.getOrCreate("username", "")
btn = GuiButton(FPSMaster.i18n["oobe.login.login"]) {
try {
val login = login(username.text, password.text)
if (login["code"].asInt == 200) {
if (FPSMaster.accountManager != null) {
FPSMaster.accountManager.username = username.text
FPSMaster.accountManager.token = login["msg"].asString
}
saveTempValue("token", FPSMaster.accountManager.token)
FPSMaster.INSTANCE.loggedIn = true
if (isOOBE) {
FPSMaster.oobeScreen.nextScene()
} else {
Minecraft.getMinecraft().displayGuiScreen(MainMenu())
}
} else {
msg = login["msg"].asString
msgbox = true
}
} catch (e: Exception) {
e.printStackTrace()
msg = "未知错误: " + e.message
msgbox = true
}
}
btn2 = GuiButton(FPSMaster.i18n["oobe.login.skip"]) {
if (isOOBE) {
FPSMaster.oobeScreen.nextScene()
} else {
Minecraft.getMinecraft().displayGuiScreen(MainMenu())
}
FPSMaster.configManager.configure["username"] = "offline"
}
}
override fun drawScreen(mouseX: Int, mouseY: Int, partialTicks: Float) {
super.drawScreen(mouseX, mouseY, partialTicks)
val sr = ScaledResolution(Minecraft.getMinecraft())
// GradientUtils.drawGradient(
// 0f,
// 0f,
// sr.scaledWidth.toFloat(),
// sr.scaledHeight.toFloat(),
// 1f,
// Color(255, 255, 255),
// Color(235, 242, 255),
// Color(255, 255, 255),
// Color(235, 242, 255)
// )
Render2DUtils.drawRect(
0f,
0f,
sr.scaledWidth.toFloat(),
sr.scaledHeight.toFloat(),
Color(235, 242, 255).rgb
)
// GlStateManager.pushMatrix()
// GlStateManager.enableBlend()
FPSMaster.fontManager.s24.drawCenteredString(
FPSMaster.i18n["oobe.login.desc"],
sr.scaledWidth / 2f,
sr.scaledHeight / 2f - 90,
FPSMaster.theme.textColorDescription.rgb
)
FPSMaster.fontManager.s18.drawString(
FPSMaster.i18n["oobe.login.register"],
sr.scaledWidth / 2f - 90,
sr.scaledHeight / 2f + 15,
FPSMaster.theme.primary.rgb
)
FPSMaster.fontManager.s40.drawCenteredString(
FPSMaster.i18n["oobe.login.title"],
sr.scaledWidth / 2f,
sr.scaledHeight / 2f - 75,
FPSMaster.theme.primary.rgb
)
btn.render(sr.scaledWidth / 2f - 70, sr.scaledHeight / 2f + 40, 60f, 24f, mouseX.toFloat(), mouseY.toFloat())
btn2.render(sr.scaledWidth / 2f + 5, sr.scaledHeight / 2f + 40, 60f, 24f, mouseX.toFloat(), mouseY.toFloat())
username.drawTextBox(sr.scaledWidth / 2f - 90, sr.scaledHeight / 2f - 40, 180f, 20f)
password.drawTextBox(sr.scaledWidth / 2f - 90, sr.scaledHeight / 2f - 10, 180f, 20f)
msgBoxAnimation.update()
if (msgbox) {
msgBoxAnimation.start(Color(0, 0, 0, 0), Color(0, 0, 0, 100), 0.6f, Type.EASE_IN_OUT_QUAD)
Render2DUtils.drawRect(0f, 0f, sr.scaledWidth.toFloat(), sr.scaledHeight.toFloat(), msgBoxAnimation.color)
Render2DUtils.drawOptimizedRoundedRect(
sr.scaledWidth / 2f - 100,
sr.scaledHeight / 2f - 50,
200f,
100f,
Color(255, 255, 255)
)
Render2DUtils.drawOptimizedRoundedRect(
sr.scaledWidth / 2f - 100,
sr.scaledHeight / 2f - 50,
200f,
20f,
Color(113, 127, 254)
)
FPSMaster.fontManager.s18.drawString(
FPSMaster.i18n["oobe.login.info"],
sr.scaledWidth / 2f - 90,
sr.scaledHeight / 2f - 45,
-1
)
FPSMaster.fontManager.s18.drawString(
msg,
sr.scaledWidth / 2f - 90,
sr.scaledHeight / 2f - 20,
Color(60, 60, 60).rgb
)
} else {
msgBoxAnimation.start(Color(0, 0, 0, 100), Color(0, 0, 0, 0), 0.6f, Type.EASE_IN_OUT_QUAD)
}
// GlStateManager.disableBlend()
// GlStateManager.popMatrix()
}
override fun mouseClick(mouseX: Int, mouseY: Int, mouseButton: Int) {
super.mouseClick(mouseX, mouseY, mouseButton)
btn.mouseClick(mouseX.toFloat(), mouseY.toFloat(), mouseButton)
btn2.mouseClick(mouseX.toFloat(), mouseY.toFloat(), mouseButton)
username.mouseClicked(mouseX, mouseY, mouseButton)
password.mouseClicked(mouseX, mouseY, mouseButton)
val sr = ScaledResolution(Minecraft.getMinecraft())
if (Render2DUtils.isHovered(
sr.scaledWidth / 2f - 90,
sr.scaledHeight / 2f + 15,
100f,
10f,
mouseX,
mouseY
) && mouseButton == 0
) {
val url = "https://fpsmaster.top/register"
if (Desktop.isDesktopSupported()) {
val desktop = Desktop.getDesktop()
try {
desktop.browse(URI(url))
} catch (e: Exception) {
e.printStackTrace()
}
}
}
if (msgbox && msgBoxAnimation.color.alpha > 50) msgbox = false
}
override fun keyTyped(typedChar: Char, keyCode: Int) {
super.keyTyped(typedChar, keyCode)
username.textboxKeyTyped(typedChar, keyCode)
FPSMaster.configManager.configure["username"] = username.text
password.textboxKeyTyped(typedChar, keyCode)
}
}
| 14 | Java | 34 | 97 | 34a00cc1834e80badd0df6f5d17ae027163d0ce9 | 7,591 | FPSMaster | MIT License |
app/src/main/java/io/itch/fr/quizgame/ui/theme/Type.kt | fruzelee | 658,160,537 | false | null | package io.itch.fr.quizgame.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import io.itch.fr.quizgame.R
val Jost = FontFamily(
Font(R.font.jost_light, FontWeight.Light),
Font(R.font.jost_regular, FontWeight.Normal),
Font(R.font.jost_medium, FontWeight.Medium),
Font(R.font.jost_semibold, FontWeight.SemiBold),
Font(R.font.jost_bold, FontWeight.Bold)
)
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = Jost,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
// Other default text styles to override
titleLarge = TextStyle(
fontFamily = Jost,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
), labelSmall = TextStyle(
fontFamily = Jost,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
) | 0 | Kotlin | 0 | 1 | b977935d552b4655db92ce841988114602b816d2 | 1,276 | trivia-quiz-game-android | Open Market License |
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/methods/CopyMessages.kt | gagarski | 314,041,476 | false | {"Kotlin": 361258} | package ski.gagar.vxutil.vertigram.methods
import ski.gagar.vertigram.annotations.TgMethod
import ski.gagar.vxutil.vertigram.throttling.HasChatId
import ski.gagar.vxutil.vertigram.throttling.Throttled
import ski.gagar.vxutil.vertigram.types.ChatId
import ski.gagar.vxutil.vertigram.types.Message
@TgMethod
@Throttled
data class CopyMessages(
override val chatId: ChatId,
val fromChatId: ChatId,
val messageIds: List<Long>,
val messageThreadId: Long? = null,
val disableNotification: Boolean = false,
val protectContent: Boolean = false,
val removeCaption: Boolean = false
) : JsonTgCallable<Message>(), HasChatId
| 0 | Kotlin | 0 | 0 | 3ee5ab95995c0df14c25cec2b13b62614bcfabea | 643 | vertigram | Apache License 2.0 |
cloneapp/src/main/java/kr/co/lee/cloneapp/MainActivity.kt | dhtmaks2540 | 437,895,583 | false | null | package kr.co.lee.cloneapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kr.co.lee.cloneapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private set
// Android KTX에 선언된 확장 함수와 by를 사용해 viewModel의 객체 생성을 위임(지연 생성)
// 매개변수로 함수 타입을 전달하는데 반환값이 ViewModelProvider.Factory
private val viewModel: SimpleViewModel by viewModels { SimpleViewModelFactory(application) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// DataBinding 레이아웃 초기화
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
setContentView(binding.root)
// RecyclerView를 위한 어댑터
val adapter = RecyclerAdapter()
binding.recycler.adapter = adapter
// ViewModel을 어댑터가 subscribe하면 목록이 변경될 때 어댑터의 항목이 새로 고침
// lifecycleScope 프로퍼티를 사용하여 CoroutineScope에 접근
// launch 메소드를 통해 새로운 코루틴 실행
lifecycleScope.launch {
viewModel.allItems.collectLatest { adapter.submitData(it) }
}
// DataBinding 변수 셋팅
binding.main = this
initAddButtonListener()
initSwipeToDelete()
}
// 새로운 아이템 추가 메소드
fun addItem() {
// 공백 제거
val newItem = binding.editView.text.trim()
if (newItem.isNotEmpty()) {
viewModel.insert(newItem)
binding.editView.setText("")
}
}
// ItemTouchHelper.Callback과 RecyclerView를 ItemTouchHelper를 사용하여 연결
private fun initSwipeToDelete() {
// ItemTouchHelper의 생성자로 ItemTouchHelper.Callback() 추상 클래스를 구현하는 클래스 셋팅
ItemTouchHelper(object : ItemTouchHelper.Callback() {
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
val simpleViewHolder = viewHolder as SimpleViewHolder
// 아이템이 널이 아니라면
return if(simpleViewHolder.simpleItem != null) {
// dragFlags는 0을 주어 드래그는 되지 않도록 설정
// 왼쪽이나 오른쪽으로 움직이도록
makeMovementFlags(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT)
} else {
makeMovementFlags(0, 0)
}
}
// 항목이 움직이면 호출되는 콜백 메소드
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean = false
// 항목이 스와이프되면 호출되는 메소드
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// SimpleViewHolder의 simpleItem이 널이 아니라면
(viewHolder as SimpleViewHolder).simpleItem?.let {
// Dao의 remove 메소드
viewModel.remove(it)
}
}
}).attachToRecyclerView(binding.recycler) // ItemTouchHelper와 RecyclerView를 연결
}
private fun initAddButtonListener() {
// 사용자가 스크린 키보드의 "Done"버튼을 클릭한 경우 아이템 저장
// Editor에 작업이 수행될 때 호출할 콜백에 대한 인터페이스 정의
binding.editView.setOnEditorActionListener { _, actionId, _ -> // 메소드가 하나 존재하는 SAM이기에 람다로 변경
// EditorInfo 클래스는 입력 메서드가 통신 중인 텍스트 편집 객체(일반적으로 EditText)의 몇 가지 특성을
// 설명하며, 가장 중요한 것은 포함하는 텍스트 콘텐츠 유형과 현재 커서 위치를 설명합니다.
if(actionId == EditorInfo.IME_ACTION_DONE) {
addItem()
return@setOnEditorActionListener true
}
false // DONE을 하지 않은 액션은 무시
}
// 사용자가 버튼을 클릭하거나, 엔터를 누를 경우 아이템 저장
// 하드웨어 키 이벤트가 이 뷰에 디스패치될 때 호출할 콜백 메소드에 대한 인터페이스 정의
binding.editView.setOnKeyListener { _, keyCode, event -> // 메소드가 하나 존재하는 SAM이기에 람다로 변경
if(event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
addItem()
return@setOnKeyListener true
}
false // DOWN이나 ENTER를 클릭하지 않은 이벤트는 무시
}
}
} | 0 | Kotlin | 0 | 0 | d74735708e53e9cbace1040c7f2ccd1b09b808b0 | 4,514 | PagingSampleClone | Apache License 2.0 |
KCrypt/src/commonMain/kotlin/studio/zebro/kcrypt/entity/KCryptEntity.kt | abhriyaroy | 680,813,150 | false | {"Kotlin": 18106, "Ruby": 1722, "Swift": 342} | import io.realm.kotlin.types.RealmObject
class KCryptEntity : RealmObject {
var encodedKey: String = ""
var isStringInHex : Boolean = false
}
| 0 | Kotlin | 0 | 7 | 717c9a7ea2c0ed039c7d0dcab4a8e511216a7f19 | 147 | KCrypt | MIT License |
src/jvmMain/kotlin/matt/shell/win/win.kt | mgroth0 | 640,054,316 | false | {"Kotlin": 94115} | package matt.shell.win
import matt.lang.common.unsafeErr
import matt.lang.model.file.AnyResolvableFilePath
import matt.lang.model.file.MacDefaultFileSystem
import matt.log.j.DefaultLogger
import matt.log.logger.Logger
import matt.model.code.sys.NewMac
import matt.prim.str.strings
import matt.shell.ShellVerbosity
import matt.shell.command
import matt.shell.commands.bash.bashC
import matt.shell.common.Shell
import matt.shell.commonj.context.DefaultWindowsExecutionContext
import matt.shell.commonj.context.ReapingShellExecutionContext
import matt.shell.shell
class WindowsGitBashReturner(
override val executionContext: ReapingShellExecutionContext,
private val verbosity: ShellVerbosity,
val logger: Logger = DefaultLogger
) : Shell<String> {
override val AnyResolvableFilePath.pathOp
get() =
NewMac.replaceFileSeparators(
path,
run {
unsafeErr("am I sure its not a removable filesystem of a different case-sensitivity?")
MacDefaultFileSystem
}
)
override fun sendCommand(vararg args: String): String {
with(executionContext) {
return shell(
*wrapWindowsBashCmd(*(args.strings())).asArray(),
verbosity = verbosity,
outLogger = logger,
errLogger = logger
)
}
}
}
fun wrapWindowsBashCmd(vararg command: String) =
DefaultWindowsExecutionContext.command.bashC {
sendCommand(*command)
}
| 0 | Kotlin | 0 | 0 | 6bed93f8596f52fe2292bb84c97b0bee22ac0f2b | 1,554 | shell | MIT License |
data/src/main/kotlin/data/tinder/dislike/DislikeRecommendationActionFactoryWrapper.kt | cybernhl | 355,816,087 | true | {"Kotlin": 257579, "Shell": 5304, "IDL": 1080} | package data.tinder.dislike
import domain.recommendation.DomainRecommendationUser
internal class DislikeRecommendationActionFactoryWrapper(
val delegate: (DomainRecommendationUser) -> DislikeRecommendationAction)
| 1 | Kotlin | 1 | 1 | fecfefd7a64dc8c9397343850b9de4d52117b5c3 | 219 | dinger-unpublished | MIT License |
src/main/kotlin/io/github/recipestore/converter/reader/ClobToStringConverter.kt | AahzBrut | 302,587,602 | false | null | package io.github.recipestore.converter.reader
import io.r2dbc.spi.Clob
import kotlinx.coroutines.flow.fold
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.runBlocking
import org.springframework.core.convert.converter.Converter
import org.springframework.stereotype.Service
@Service
class ClobToStringConverter : Converter<Clob, String> {
override fun convert(source: Clob): String {
@Suppress("BlockingMethodInNonBlockingContext")
return runBlocking {
source
.stream()
.asFlow()
.fold(StringBuilder()) { a, e ->
a.append(e)
}
.toString()
}
}
} | 0 | Kotlin | 0 | 1 | 47b29469c48f7caa5813e20b92d7fb460299125d | 712 | recipestore | MIT License |
src/main/kotlin/io/swagger/client/models/CreateMessageDto.kt | em-ad | 443,796,768 | false | null | /**
* Datyar REST APIs
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.models
/**
*
* @param fileSize
* @param fileUrl
* @param filename
* @param messageType
* @param sessionId
* @param text
*/
data class CreateMessageDto (
val fileSize: kotlin.String? = null,
val fileUrl: kotlin.String? = null,
val filename: kotlin.String? = null,
val messageType: CreateMessageDto.MessageType,
val sessionId: kotlin.String,
val text: kotlin.String? = null
) {
/**
*
* Values: DOCUMENT,IMAGE,TEXT,VOICE
*/
enum class MessageType(val value: kotlin.String){
DOCUMENT("DOCUMENT"),
IMAGE("IMAGE"),
TEXT("TEXT"),
VOICE("VOICE");
}
} | 0 | Kotlin | 0 | 0 | be4c2e4a6222d467a51d9148555eed25264c7eb0 | 1,007 | kotlinsdk | Condor Public License v1.1 |
src/Day03.kt | lassebe | 573,423,378 | false | {"Kotlin": 33148} | import kotlin.streams.toList
fun main() {
fun itemPriority(c: Int): Int =
if (c >= 97) (c - 97 + 1)
else (c - 65 + 27)
fun part1Alt(input: List<String>) =
input.sumOf { bag ->
val wholeBag = bag.chars().toList()
val (firstBagItems, secondBagItems) = wholeBag.chunked(wholeBag.size / 2).map { it.toSet() }
for (item in firstBagItems) {
if (secondBagItems.contains(item)) {
return@sumOf itemPriority(item)
}
}
return@sumOf 0
}
fun String.toCharSet() = this.chars().toList().toSet()
fun part2(input: List<String>) =
input.chunked(3).sumOf { bagGroup ->
val firstBag = bagGroup[0].toCharSet()
val secondBag = bagGroup[1].toCharSet()
val thirdBag = bagGroup[2].toCharSet()
for (item in firstBag) {
if (secondBag.contains(item) && thirdBag.contains(item)) {
return@sumOf itemPriority(item)
}
}
return@sumOf 0
}
val testInput = readInput("Day03_test")
println(part1Alt(testInput))
check(part1Alt(testInput) == 157)
val input = readInput("Day03")
check(part2(testInput) == 70)
println(part1Alt(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c3157c2d66a098598a6b19fd3a2b18a6bae95f0c | 1,357 | advent_of_code_2022 | Apache License 2.0 |
app/src/androidTest/java/com/xently/news/MainActivityTest.kt | morristech | 376,544,553 | false | null | package com.xently.news
import androidx.test.filters.LargeTest
import org.junit.Before
import org.junit.Assert.*
@LargeTest
class MainActivityTest {
@Before
fun setUp() {
}
} | 0 | null | 0 | 0 | 779dd3f9fbdf7dd98501c76b5e686aa69f536d5d | 190 | news | Apache License 2.0 |
core/network/src/main/java/com/vproject/texttoimage/core/network/model/ResultWrapper.kt | viethua99 | 652,124,255 | false | {"Kotlin": 240107} | package com.vproject.texttoimage.core.network.model
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.io.IOException
import java.net.SocketTimeoutException
sealed class ResultWrapper<out ResponseType> {
data class Success<out ResponseType>(val data: ResponseType) :
ResultWrapper<ResponseType>()
data class Error<ResponseType>(val message: ErrorType) : ResultWrapper<ResponseType>()
}
enum class ErrorType {
HTTP,
IO, // IO
TIMEOUT, // Socket
UNKNOWN
}
suspend fun <ResponseType> safeApiCall(
dispatcher: CoroutineDispatcher,
apiCall: suspend () -> ResponseType
): ResultWrapper<ResponseType> {
return try {
val response = withContext(dispatcher) { apiCall.invoke() }
ResultWrapper.Success(response)
} catch (exception: Exception) {
when (exception) {
is HttpException -> ResultWrapper.Error(ErrorType.HTTP)
is SocketTimeoutException -> ResultWrapper.Error(ErrorType.TIMEOUT)
is IOException -> ResultWrapper.Error(ErrorType.IO)
else -> ResultWrapper.Error(ErrorType.UNKNOWN)
}
}
} | 1 | Kotlin | 2 | 16 | fe9363cf032e9d3b32df8da026c39e9823aecb36 | 1,194 | Android-Text-to-Image | Apache License 2.0 |
practicas/app/src/main/java/com/adrianbalam/practicas/todoapp/TodoActivity.kt | adrianbalam | 615,909,656 | false | null | package com.adrianbalam.practicas.todoapp
import android.app.Dialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adrianbalam.practicas.R
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
class TodoActivity : AppCompatActivity() {
private lateinit var rvCategorias:RecyclerView
private lateinit var rvTareas:RecyclerView
private lateinit var edTituloTarea: TextInputEditText
private lateinit var edDescTarea:TextInputEditText
private lateinit var btnAddTarea:MaterialButton
private lateinit var adaptador2:TareasAdaptador
private var objetosCategoria:ArrayList<CategoriaMolde> = ArrayList()
private var objetosTarea:ArrayList<TareaMolde> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_todo)
initComponents()
initRV()
initListeners()
}
private fun initComponents() {
rvCategorias = findViewById(R.id.rvCategorias)
rvTareas = findViewById(R.id.rvTareas)
edTituloTarea = findViewById(R.id.edTituloTarea)
edDescTarea = findViewById(R.id.edDescTarea)
btnAddTarea = findViewById(R.id.btnAddTarea)
}
private fun initListeners(){
btnAddTarea.setOnClickListener {
initDialogoAdd()
}
}
private fun initDialogoAdd(){
val dialogo = Dialog(this)
dialogo.setContentView(R.layout.dialog_add_tarea)
val etTituloTarea:TextInputEditText = dialogo.findViewById(R.id.etTituloTarea)
val etDescTarea:TextInputEditText = dialogo.findViewById(R.id.etDescTarea)
val btnAddTarea2:MaterialButton = dialogo.findViewById(R.id.btnAddTarea2)
btnAddTarea2.setOnClickListener {
if (etTituloTarea.text.toString().isNotEmpty() && etDescTarea.text.toString().isNotEmpty()){
objetosTarea.add(TareaMolde(etTituloTarea.text.toString(),etDescTarea.text.toString()))
adaptador2.notifyItemInserted(objetosTarea.size-1)
dialogo.hide()
}
}
dialogo.show()
}
private fun initRV(){
rvCategorias.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false)
val adaptador = CategoriasAdaptador(obtenerDatos())
rvCategorias.adapter = adaptador
rvTareas.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
adaptador2 = TareasAdaptador(obtenerDatosTareas(), borrarItem = {position -> borrarItem(position)})
rvTareas.adapter = adaptador2
}
private fun obtenerDatos():ArrayList<CategoriaMolde>{
objetosCategoria.add(CategoriaMolde("Personal","Tareas de ámbito personal"))
objetosCategoria.add(CategoriaMolde("Profesional","Tareas de ámbito profesional"))
objetosCategoria.add(CategoriaMolde("Otros","Otros tipos de tareas"))
return objetosCategoria
}
private fun obtenerDatosTareas():ArrayList<TareaMolde>{
objetosTarea.add(TareaMolde("Estudiar Android","Repasar los conceptos de Android"))
objetosTarea.add(TareaMolde("Ir a correr","Hacer al menos 30 minutos"))
objetosTarea.add(TareaMolde("Ir al cine","Comprar boletos en la web"))
return objetosTarea
}
private fun addTarea(){
if(!edTituloTarea.text.toString().isEmpty() && !edDescTarea.text.toString().isEmpty()){
objetosTarea.add(TareaMolde(edTituloTarea.text.toString(),edDescTarea.text.toString()))
adaptador2.notifyItemInserted(objetosTarea.size-1)
}
}
private fun borrarItem(index:Int){
objetosTarea.removeAt(index)
adaptador2.notifyItemRemoved(index)
}
} | 0 | Kotlin | 0 | 0 | 4ad2850741c192e06bf1ced361cf16eee9b4aad6 | 4,050 | EjemploAndroid | MIT License |
formula-android/src/main/java/com/instacart/formula/integration/internal/BackStackUtils.kt | BeemobileAB | 213,854,532 | true | {"Kotlin": 249040, "Shell": 275, "Ruby": 220} | package com.instacart.formula.integration.internal
import com.instacart.formula.integration.BackStack
import com.instacart.formula.integration.LifecycleEvent
internal object BackStackUtils {
/**
* Takes last and current active contract state,
* and calculates attach and detach effects
*/
fun <Key> findLifecycleEffects(
lastState: BackStack<Key>?,
currentState: BackStack<Key>
): Set<LifecycleEvent<Key>> {
val lastActive = lastState?.keys.orEmpty()
val currentlyActive = currentState.keys
val attachedEffects = findAttachedKeys(
lastActive,
currentlyActive
)
.map { LifecycleEvent.Added(it) }
val detachEffects = findDetachedKeys(
lastActive,
currentlyActive
)
.map {
LifecycleEvent.Removed(it)
}
return attachedEffects.plus(detachEffects).toSet()
}
fun <Key> findAttachedKeys(lastActive: List<Key>, currentlyActive: List<Key>): List<Key> {
return currentlyActive.filter { !lastActive.contains(it) }
}
fun <Key> findDetachedKeys(lastActive: List<Key>, currentlyActive: List<Key>): List<Key> {
return lastActive.filter { !currentlyActive.contains(it) }
}
}
| 0 | null | 0 | 0 | 55979634721a90ec284b07a89523e4d690b77d98 | 1,300 | formula | BSD 3-Clause Clear License |
diskord-core/src/commonMain/kotlin/com/jessecorbett/diskord/api/common/Guild.kt | JesseCorbett | 122,362,551 | false | {"Kotlin": 447282} | package com.jessecorbett.diskord.api.common
import com.jessecorbett.diskord.internal.CodeEnum
import com.jessecorbett.diskord.internal.CodeEnumSerializer
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
@Serializable
public data class Guild(
@SerialName("id") val id: String,
@SerialName("name") val name: String,
@SerialName("icon") val iconHash: String?,
@SerialName("splash") val splashHash: String?,
@SerialName("discovery_splash") val discoverySplashHash: String?,
@SerialName("owner") val userIsOwner: Boolean? = null,
@SerialName("owner_id") val ownerId: String,
@SerialName("permissions") val permissions: Permissions? = null,
@SerialName("afk_channel_id") val afkChannelId: String?,
@SerialName("afk_timeout") val afkTimeoutSeconds: Int,
@SerialName("widget_enabled") val widgetEnabled: Boolean? = null,
@SerialName("widget_channel_id") val widgetChannelId: String? = null,
@SerialName("verification_level") val verificationLevel: VerificationLevel,
@SerialName("default_message_notifications") val defaultMessageNotificationLevel: NotificationsLevel,
@SerialName("explicit_content_filter") val explicitContentFilterLevel: ExplicitContentFilterLevel,
@SerialName("roles") val roles: List<Role>,
@SerialName("emojis") val emojis: List<Emoji>,
@SerialName("features") val features: List<GuildFeatures>,
@SerialName("mfa_level") val mfaLevel: MFALevel,
@SerialName("application_id") val owningApplicationId: String?,
@SerialName("system_channel_id") val systemMessageChannelId: String?,
@SerialName("system_channel_flags") val systemChannelFlags: SystemChannelFlags,
@SerialName("rules_channel_id") val rulesChannelId: String?,
@SerialName("max_presences") val maxPresences: Int? = null,
@SerialName("max_members") val maxMembers: Int? = null,
@SerialName("vanity_url_code") val vanityCodeUrl: String?,
@SerialName("description") val description: String?,
@SerialName("banner") val bannerHash: String?,
@SerialName("premium_tier") val premiumType: GuildPremiumType,
@SerialName("premium_subscription_count") val guildBoostCount: Int? = null,
@SerialName("preferred_locale") val preferredLocale: String,
@SerialName("public_updates_channel_id") val publicUpdatesChannelId: String?,
@SerialName("max_video_channel_users") val maxVideoChannelUsers: Int? = null,
@SerialName("approximate_member_count") val approximateMemberCount: Int? = null,
@SerialName("approximate_presence_count") val approximatePresenceCount: Int? = null,
@SerialName("welcome_screen") val welcomeScreen: WelcomeScreen? = null,
@SerialName("nsfw_level") val nsfwLevel: GuildNSFWLevel,
@SerialName("stage_instances") val stageInstances: List<StageInstance>? = null,
@SerialName("stickers") val sticker: List<Sticker>? = null,
)
@Serializable(with = VerificationLevelSerializer::class)
public enum class VerificationLevel(public override val code: Int) : CodeEnum {
UNKNOWN(-1),
NONE(0),
LOW(1),
MEDIUM(2),
HIGH(3),
VERY_HIGH(4)
}
public class VerificationLevelSerializer : CodeEnumSerializer<VerificationLevel>(VerificationLevel.UNKNOWN, VerificationLevel.values())
@Serializable(with = NotificationsLevelSerializer::class)
public enum class NotificationsLevel(public override val code: Int) : CodeEnum {
UNKNOWN(-1),
ALL_MESSAGES(0),
ONLY_MENTIONS(1)
}
public class NotificationsLevelSerializer : CodeEnumSerializer<NotificationsLevel>(NotificationsLevel.UNKNOWN, NotificationsLevel.values())
@Serializable(with = ExplicitContentFilterLevelSerializer::class)
public enum class ExplicitContentFilterLevel(public override val code: Int) : CodeEnum {
UNKNOWN(-1),
DISABLED(0),
MEMBERS_WITHOUT_ROLES(1),
ALL_MEMBERS(2)
}
public class ExplicitContentFilterLevelSerializer : CodeEnumSerializer<ExplicitContentFilterLevel>(ExplicitContentFilterLevel.UNKNOWN, ExplicitContentFilterLevel.values())
@Serializable(with = GuildFeaturesSerializer::class)
public enum class GuildFeatures {
UNKNOWN,
ANIMATED_ICON,
BANNER,
COMMERCE,
COMMUNITY,
DISCOVERABLE,
FEATURABLE,
INVITE_SPLASH,
MEMBER_VERIFICATION_GATE_ENABLED,
NEWS,
PARTNERED,
PREVIEW_ENABLED,
VANITY_URL,
VERIFIED,
VIP_REGIONS,
WELCOME_SCREEN_ENABLED,
TICKETED_EVENTS_ENABLED,
MONETIZATION_ENABLED,
MORE_STICKERS,
THREE_DAY_THREAD_ARCHIVE,
SEVEN_DAY_THREAD_ARCHIVE,
PRIVATE_THREADS,
EXPOSED_TO_ACTIVITIES_WTP_EXPERIMENT
}
public class GuildFeaturesSerializer : KSerializer<GuildFeatures> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor(GuildFeatures::class.simpleName!!, PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): GuildFeatures {
val value = decoder.decodeString()
return try {
GuildFeatures.valueOf(value)
} catch (e: IllegalArgumentException) {
GuildFeatures.UNKNOWN
}
}
override fun serialize(encoder: Encoder, value: GuildFeatures) {
encoder.encodeString(value.name)
}
}
@Serializable(with = GuildPremiumTypeSerializer::class)
public enum class GuildPremiumType(public override val code: Int) : CodeEnum {
UNKNOWN(-1),
NONE(0),
TIER_1(1),
TIER_2(2),
TIER_3(3)
}
public class GuildPremiumTypeSerializer : CodeEnumSerializer<GuildPremiumType>(GuildPremiumType.UNKNOWN, GuildPremiumType.values())
@Serializable(with = MFALevelSerializer::class)
public enum class MFALevel(public override val code: Int) : CodeEnum {
UNKNOWN(-1),
NONE(0),
ELEVATED(1)
}
public class MFALevelSerializer : CodeEnumSerializer<MFALevel>(MFALevel.UNKNOWN, MFALevel.values())
@Serializable
public data class WelcomeScreen(
@SerialName("description") val description: String?,
@SerialName("welcome_channels") val welcomeChannels: List<WelcomeScreenChannel>
)
@Serializable
public data class WelcomeScreenChannel(
@SerialName("channel_id") val channelId: String,
@SerialName("description") val description: String,
@SerialName("emoji_id") val emojiId: String?,
@SerialName("emoji_name") val emojiName: String?
)
@Serializable(with = GuildNSFWLevelSerializer::class)
public enum class GuildNSFWLevel(public override val code: Int) : CodeEnum {
UNKNOWN(-1),
DEFAULT(0),
EXPLICIT(1),
SAFE(2),
AGE_RESTRICTED(3)
}
public class GuildNSFWLevelSerializer : CodeEnumSerializer<GuildNSFWLevel>(GuildNSFWLevel.UNKNOWN, GuildNSFWLevel.values())
@Serializable
public data class StageInstance(
@SerialName("id") val id: String,
@SerialName("guild_id") val guildId: String,
@SerialName("channel_id") val channelId: String,
@SerialName("topic") val topic: String,
@SerialName("privacy_level") val privacyLevel: StagePrivacyLevel,
@SerialName("discoverable_disabled") val discoverable_disabled: Boolean,
)
@Serializable(with = StagePrivacyLevelSerializer::class)
public enum class StagePrivacyLevel(public override val code: Int) : CodeEnum {
UNKNOWN(-1),
PUBLIC(1),
GUILD_ONLY(2)
}
public class StagePrivacyLevelSerializer : CodeEnumSerializer<StagePrivacyLevel>(StagePrivacyLevel.UNKNOWN, StagePrivacyLevel.values())
| 2 | Kotlin | 17 | 170 | acd004fc650cfa34d545666db9ea15a0eb3461ac | 7,611 | diskord | Apache License 2.0 |
oneadapter/src/main/java/com/idanatz/oneadapter/internal/utils/Logger.kt | meruiden | 232,577,694 | true | {"Kotlin": 118230} | package com.idanatz.oneadapter.internal.utils
import android.util.Log
import com.idanatz.oneadapter.BuildConfig
import com.idanatz.oneadapter.internal.InternalAdapter
internal object Logger {
fun logd(internalAdapter: InternalAdapter? = null, body: () -> String) {
if (BuildConfig.DEBUG) {
Log.d("OneAdapter", "adapter: $internalAdapter, ${body()}")
}
}
} | 0 | Kotlin | 0 | 0 | 5eaf19734939f9956d60ceb4a982320921724124 | 394 | OneAdapter | MIT License |
src/main/kotlin/no/nav/fo/veilarbregistrering/bruker/Kontaktinfo.kt | navikt | 131,013,336 | false | {"Kotlin": 863303, "PLpgSQL": 853, "PLSQL": 546, "Dockerfile": 87} | package no.nav.fo.veilarbregistrering.bruker
class Kontaktinfo (
val telefonnummerFraKrr: String?,
var telefonnummerFraNav: Telefonnummer?,
val navn: Navn?
)
| 18 | Kotlin | 5 | 6 | 0ecf248adee242a7eac34b655f86278946641d7e | 171 | veilarbregistrering | MIT License |
app/src/main/java/com/example/fliplearn/ui/testFragment/TestsRecyclerView.kt | gaurishanand13 | 304,346,590 | false | null | package com.example.fliplearn.ui.testFragment
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.fliplearn.R
import com.example.fliplearn.ui.main.ViewHolder
import com.example.fliplearn.ui.onlineTestActivity.onlineTestActivity
import kotlinx.android.synthetic.main.test_item.view.*
import kotlin.collections.ArrayList
class TestsRecyclerView(val list: ArrayList<testModel>, val context: Context): RecyclerView.Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
var view = layoutInflater.inflate(R.layout.test_item,parent,false)
return ViewHolder(view)
}
override fun getItemCount() = list.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.testTextView.text = list.get(position).testName
holder.itemView.testImageView.setImageResource(list.get(position).res)
holder.itemView.setOnClickListener {
context.startActivity(Intent(context,subjectiveAnalysis::class.java))
}
}
} | 0 | Kotlin | 1 | 0 | d1b55013b018e32c385c6fdba92de65b79bd6133 | 1,301 | F-Fliplearn | MIT License |
checkpoint-core/src/test/kotlin/com/natigbabayev/checkpoint/core/rules/length/LengthRangeRuleDslTest.kt | natiginfo | 248,285,985 | false | null | package com.natigbabayev.checkpoint.core.rules.length
import io.mockk.every
import io.mockk.mockk
import io.mockk.verifySequence
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
internal class LengthRangeRuleDslTest {
@Suppress("PrivatePropertyName")
private lateinit var SUT: LengthRangeRule
// region Mocks
private val mockWhenInvalid: (CharSequence) -> Unit = mockk()
// endregion
@BeforeEach
fun setup() {
SUT = lengthRangeRule(minLength = 3, maxLength = 6, whenInvalid = mockWhenInvalid)
}
@Nested
@DisplayName("Given invalid input")
inner class GivenInvalidInput {
private val invalidInput1 = "ab"
private val invalidInput2 = "abcdefg"
@Test
fun whenCanPassCalled_returnsFalse() {
// Arrange
every { mockWhenInvalid(any()) } answers { nothing }
// Act
val canPass1 = SUT.canPass(invalidInput1)
val canPass2 = SUT.canPass(invalidInput2)
// Assert
assertFalse(canPass1)
assertFalse(canPass2)
}
@Test
fun whenCanPassCalled_invokesCallback() {
// Arrange
every { mockWhenInvalid(any()) } answers { nothing }
// Act
SUT.canPass(invalidInput1)
SUT.canPass(invalidInput2)
// Assert
verifySequence {
mockWhenInvalid(invalidInput1)
mockWhenInvalid(invalidInput2)
}
}
}
@Test
fun givenValidInput_whenCanPassCalled_returnsTrue() {
// Arrange
// Act
val results = listOf(
SUT.canPass("abc"),
SUT.canPass("abcd"),
SUT.canPass("abcde"),
SUT.canPass("abcdef")
)
// Assert
assertTrue(results.all { it == true })
}
}
| 3 | Kotlin | 3 | 24 | 3595bb76d753c40f10478e2b9999b77332ac7704 | 2,072 | Checkpoint | Apache License 2.0 |
kotlin-app/src/nativeMain/kotlin/charleskorn/sample/golanginkotlin/App.kt | charleskorn | 451,750,118 | false | {"Kotlin": 6608, "Go": 247} | package charleskorn.sample.golanginkotlin
import charleskorn.sample.golanginkotlin.native.GenerateGreeting
import kotlinx.cinterop.cstr
import kotlinx.cinterop.toKString
fun main() {
println("Hello from Kotlin/Native!")
// FIXME: this leaks the string pointer returned by Golang
println("Golang says: " + GenerateGreeting("<your name here>".cstr)!!.toKString())
}
| 0 | Kotlin | 0 | 5 | 3bb22e15bafad8458acc40a7643ac849e882a510 | 379 | golang-in-kotlin | Apache License 2.0 |
android/src/main/java/com/fullscreenintentmanager/FullScreenIntentManagerModule.kt | riteshshukla04 | 838,474,669 | false | {"Kotlin": 2338, "Ruby": 2058, "TypeScript": 1800, "JavaScript": 1489, "Swift": 330, "Objective-C++": 329, "C": 103, "Objective-C": 67} | package com.fullscreenintentmanager
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.app.NotificationManager
import android.content.Context
import android.provider.Settings
import androidx.annotation.RequiresApi
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
class FullScreenIntentManagerModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
override fun getName(): String {
return NAME
}
// Example method
// See https://reactnative.dev/docs/native-modules-android
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
@ReactMethod
fun hasFullScreenIntentPermission(promise: Promise) {
try {
val notificationManager = reactApplicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val canUseFullScreenIntent = notificationManager.canUseFullScreenIntent()
promise.resolve(canUseFullScreenIntent)
} catch (e: Exception) {
promise.reject("ERROR_CHECKING_PERMISSION", "Error checking full-screen intent permission", e)
}
}
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
@ReactMethod
fun openFullScreenIntentSettings() {
Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT).apply {
data = Uri.parse("package:${reactApplicationContext.packageName}")
}.also {
it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
reactApplicationContext.startActivity(it)
}
}
companion object {
const val NAME = "FullScreenIntentManager"
}
}
| 0 | Kotlin | 0 | 0 | 665ba5b4bab50aeee7b17457dd8bef64f8322b59 | 1,762 | react-native-full-screen-intent-manager | MIT License |
hr-buddy-server/src/main/kotlin/org/hildan/hrbuddy/server/controllers/AgendaGeneratorController.kt | joffrey-bion | 146,783,738 | false | {"Gradle": 5, "Procfile": 1, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "YAML": 2, "Markdown": 2, "INI": 2, "Dockerfile": 1, "Kotlin": 12, "JSON with Comments": 3, "JSON": 6, "EditorConfig": 1, "Browserslist": 1, "HTML": 4, "CSS": 4, "JavaScript": 2, "Java": 1} | package org.hildan.hrbuddy.server.controllers
import org.hildan.hrbuddy.agendagenerator.generateAgendas
import org.hildan.hrbuddy.agendagenerator.parser.PlanningFormatException
import org.hildan.hrbuddy.agendagenerator.parser.PlanningParserOptions
import org.hildan.hrbuddy.server.service.SessionFileMap
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.io.FileSystemResource
import org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo
import org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestPart
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import javax.servlet.http.HttpSession
@Controller
class AgendaGeneratorController @Autowired constructor(
val sessionFileMap: SessionFileMap
) {
data class SendPlanningResponse(
val downloadUrl: String?, val error: String?
)
@PostMapping("/planning")
@CrossOrigin(origins = ["*"])
@ResponseBody
fun sendPlanningFile(
@RequestPart("planningFile") planningFile: MultipartFile,
@RequestPart("options") options: GeneratorOptions? = null,
session: HttpSession
): AgendaGeneratorController.SendPlanningResponse {
val agendasDir = createTempDir("agendas-", "")
try {
generateAgendas(planningFile.inputStream, agendasDir, parserOptions = options?.parserOptions)
} catch (e: PlanningFormatException) {
return SendPlanningResponse(null, e.message)
} catch (e: Exception) {
return SendPlanningResponse(null, "An unexpected error occurred: ${e.message}")
}
val zipFile = createTempFile("agendas-", ".zip")
zipFile.deleteOnExit()
agendasDir.zipInto(zipFile)
agendasDir.deleteRecursively()
val fileId = sessionFileMap.addFile(zipFile)
val fileUrl = getDownloadUrl(fileId)
return SendPlanningResponse(fileUrl, null)
}
class GeneratorOptions(
val jobTitlesWithNoDivision: List<String>
) {
val parserOptions = PlanningParserOptions(jobTitlesWithNoDivision)
}
private fun getDownloadUrl(fileId: String) =
linkTo(methodOn(AgendaGeneratorController::class.java).download(fileId)).toString()
@GetMapping("/download/{fileId}", produces = ["application/octet-stream"])
@CrossOrigin(origins = ["*"])
@ResponseBody
fun download(@PathVariable fileId: String): FileSystemResource {
val zipFile = sessionFileMap.getFile(fileId) ?: throw ResourceNotFoundException(fileId)
return FileSystemResource(zipFile)
}
@ResponseStatus(HttpStatus.NOT_FOUND)
class ResourceNotFoundException(msg: String) : RuntimeException(msg)
private fun File.zipInto(zipFile: File) = ZipOutputStream(zipFile.outputStream()).use { it.putFile(this) }
private fun ZipOutputStream.putFile(file: File, namePrefix: String = "") {
if (file.isHidden) {
return
}
val entryName = "$namePrefix${file.name}"
if (file.isDirectory) {
file.listFiles().forEach { putFile(it, "$entryName/") }
return
}
val entry = ZipEntry(entryName)
putNextEntry(entry)
file.inputStream().use { it.copyTo(this) }
}
}
| 3 | Kotlin | 0 | 0 | 58bd96bb185c60e69c26a899be7cba1306fa8cc6 | 3,847 | hr-buddy | MIT License |
app/src/main/java/com/myproject/radiojourney/data/localDatabaseRoom/AppRoomDBAbstract.kt | FoxyTheOne | 469,217,520 | false | null | package com.myproject.radiojourney.data.localDatabaseRoom
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.myproject.radiojourney.model.local.CountryLocal
import com.myproject.radiojourney.model.local.RadioStationFavouriteLocal
import com.myproject.radiojourney.model.local.RadioStationLocal
import com.myproject.radiojourney.model.local.UserEntity
@Database(
entities = [UserEntity::class, CountryLocal::class, RadioStationLocal::class, RadioStationFavouriteLocal::class],
version = 5,
exportSchema = true,
// autoMigrations = [
// AutoMigration(from = 4, to = 5)
// ]
)
@TypeConverters(LatLngConverter::class)
abstract class AppRoomDBAbstract : RoomDatabase() {
abstract fun getUserDAO(): IUserDAO
abstract fun getCountryDAO(): ICountryDAO
abstract fun getRadioStationDAO(): IRadioStationDAO
abstract fun getRadioStationFavouriteDAO(): IRadioStationFavouriteDAO
} | 0 | Kotlin | 0 | 0 | 71e012f7c3b6a2a282960f603bb197a7c8fff9c2 | 970 | GRADUATE_WORK | FSF All Permissive License |
components/nfc/attack/impl/src/main/java/com/flipperdevices/nfc/attack/impl/viewmodel/NfcAttackViewModel.kt | flipperdevices | 288,258,832 | false | {"Kotlin": 2848644, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21} | package com.flipperdevices.nfc.attack.impl.viewmodel
import androidx.lifecycle.viewModelScope
import com.flipperdevices.core.ui.lifecycle.DecomposeViewModel
import com.flipperdevices.nfc.mfkey32.api.MfKey32Api
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.plus
import javax.inject.Inject
class NfcAttackViewModel @Inject constructor(
private val mfKey32Api: MfKey32Api
) : DecomposeViewModel() {
fun hasMfKey32Notification(): StateFlow<Boolean> = mfKey32Api.hasNotification()
.stateIn(
viewModelScope + Dispatchers.Default,
SharingStarted.Eagerly,
false
)
}
| 12 | Kotlin | 142 | 1,121 | a5ed93cbffaa13d21690386e00d65a33aadb9f58 | 764 | Flipper-Android-App | MIT License |
app/src/main/java/com/jurkowski/newsapp/ui/NewsActivity.kt | konrad241198 | 387,038,045 | false | null | package com.jurkowski.newsapp.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import com.jurkowski.newsapp.App
import com.jurkowski.newsapp.R
import com.jurkowski.newsapp.repository.ArticleRepositoryImpl
import kotlinx.android.synthetic.main.activity_news.*
class NewsActivity : AppCompatActivity() {
private val repository by lazy { App.repository }
private val viewModelProviderFactory by lazy {
NewsViewModelProviderFactory(application, repository as ArticleRepositoryImpl)
}
val viewModel by lazy {
ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_news)
bottomNavigationView.setupWithNavController(newsNavHostFragment.findNavController())
}
} | 0 | Kotlin | 0 | 0 | 599e40e4e601b57cc3d02eadc4ba0bf4df9cdda1 | 1,022 | NewsApp | MIT License |
base/src/main/kotlin/io/goooler/demoapp/base/util/BaseExtensions.kt | Goooler | 188,988,687 | false | null | @file:Suppress("unused")
@file:JvmName("BaseExtensionUtil")
@file:OptIn(ExperimentalContracts::class)
package io.goooler.demoapp.base.util
import android.app.Activity
import android.content.ContentUris
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.graphics.Color
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.os.Parcel
import android.os.Parcelable
import android.text.Spannable
import android.text.Spanned
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.webkit.MimeTypeMap
import android.webkit.URLUtil
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.Dimension
import androidx.annotation.IdRes
import androidx.annotation.IntRange
import androidx.annotation.MainThread
import androidx.core.content.getSystemService
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.os.bundleOf
import androidx.core.text.parseAsHtml
import androidx.core.text.toSpannable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit
import androidx.fragment.app.findFragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.findViewTreeLifecycleOwner
import java.io.File
import java.io.Serializable
import java.math.BigDecimal
import java.util.Collections
import java.util.UUID
import java.util.regex.Pattern
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
// ---------------------Types-------------------------------//
@Dimension(unit = Dimension.DP)
annotation class Dp
@Dimension(unit = Dimension.SP)
annotation class Sp
@Dimension(unit = 3)
annotation class Pt
typealias ParamMap = HashMap<String, Any>
// ---------------------Any-------------------------------//
inline val randomUUID: String get() = UUID.randomUUID().toString()
inline val currentTimeMillis: Long get() = System.currentTimeMillis()
inline val currentThreadName: String get() = Thread.currentThread().name
inline val isMainThread: Boolean get() = Looper.getMainLooper() == Looper.myLooper()
fun <T : Any> unsafeLazy(initializer: () -> T): Lazy<T> =
lazy(LazyThreadSafetyMode.NONE, initializer)
fun <T : Parcelable> T.deepCopy(): T? {
var parcel: Parcel? = null
return try {
parcel = Parcel.obtain().also {
it.writeParcelable(this, 0)
it.setDataPosition(0)
}
parcel.readParcelable(this::class.java.classLoader)
} finally {
parcel?.recycle()
}
}
// ---------------------CharSequence-------------------------------//
operator fun String.times(@IntRange(from = 0) num: Int): String {
require(num >= 0) {
"Param num should >= 0"
}
val origin = this
return buildString {
for (i in 1..num) append(origin)
}
}
fun String.fromHtml(): Spanned = parseAsHtml()
fun String.extension2MimeType(): String? =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(lowercase())
fun String.mimeType2Extension(): String? =
MimeTypeMap.getSingleton().getExtensionFromMimeType(lowercase())
fun String.onlyDigits(): String = replace(Regex("\\D*"), "")
fun String.removeAllSpecialCharacters(): String = replace(Regex("[^a-zA-Z]+"), "")
fun String.isValidFilename(): Boolean {
val filenameRegex =
Pattern.compile("[\\\\\\/:\\*\\?\"<>\\|\\x01-\\x1F\\x7F]", Pattern.CASE_INSENSITIVE)
// It's not easy to use regex to detect single/double dot while leaving valid values
// (filename.zip) behind...
// So we simply use equality to check them
return !filenameRegex.matcher(this).find() && "." != this && ".." != this
}
fun Uri.withAppendedId(id: Long): Uri = ContentUris.withAppendedId(this, id)
@OptIn(ExperimentalContracts::class)
fun CharSequence?.isNotNullOrEmpty(): Boolean {
contract {
returns(true) implies (this@isNotNullOrEmpty != null)
}
return this.isNullOrEmpty().not()
}
fun Spannable.withClickableSpan(clickablePart: String, onClickListener: () -> Unit): Spannable {
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) = onClickListener()
}
setSpan(
clickableSpan,
indexOf(clickablePart),
indexOf(clickablePart) + clickablePart.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
return this
}
fun CharSequence.withColorSpan(coloredPart: String, @ColorInt color: Int): Spannable {
return toSpannable().also {
it.setSpan(
ForegroundColorSpan(color),
it.length - coloredPart.length,
it.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
/**
* subString 防越界处理
*/
fun String.safeSubstring(startIndex: Int, endIndex: Int): String {
val begin = if (startIndex < 0) 0 else startIndex
val end = if (endIndex > length) length else endIndex
return substring(begin, end)
}
fun String?.safeToBoolean(default: Boolean = false): Boolean {
return if (this == null) default else try {
toBoolean()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.safeToInt(default: Int = 0): Int {
return if (this == null) default else try {
toInt()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.safeToLong(default: Long = 0L): Long {
return if (this == null) default else try {
toLong()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.safeToFloat(default: Float = 0f): Float {
return if (this == null) default else try {
toFloat()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.safeToDouble(default: Double = 0.0): Double {
return if (this == null) default else try {
toDouble()
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
@ColorInt
fun String?.safeToColor(@ColorInt default: Int = 0): Int {
return try {
Color.parseColor(this)
} catch (e: Throwable) {
e.printStackTrace()
default
}
}
fun String?.isNetworkUrl(): Boolean = URLUtil.isNetworkUrl(this)
fun String?.isValidUrl(): Boolean = URLUtil.isValidUrl(this)
// ---------------------Calculate-------------------------------//
infix fun Double.plus(that: Double): Double {
return (BigDecimal(this.toString()) + BigDecimal(that.toString())).toDouble()
}
infix fun Double.minus(that: Double): Double {
return (BigDecimal(this.toString()) - BigDecimal(that.toString())).toDouble()
}
infix fun Double.times(that: Double): Double {
return (BigDecimal(this.toString()) * BigDecimal(that.toString())).toDouble()
}
infix fun Double.div(that: Double): Double {
return (BigDecimal(this.toString()) / BigDecimal(that.toString())).toDouble()
}
fun Number.isZero(): Boolean {
return when (this) {
is Byte, is Short, is Int, is Long -> this == 0
is Float, is Double -> BigDecimal(this.toString()) == BigDecimal("0.0")
else -> false
}
}
fun Number.isNotZero(): Boolean = isZero().not()
fun Int?.orZero(): Int = this ?: 0
fun Int.isInvalid(invalidValue: Int = -1) = this == invalidValue
fun Int.isValid(invalidValue: Int = -1) = isInvalid(invalidValue).not()
fun Long.isInvalid(invalidValue: Long = -1) = this == invalidValue
fun Long.isValid(invalidValue: Long = -1) = isInvalid(invalidValue).not()
fun Boolean?.orTrue(): Boolean = this ?: true
fun Boolean?.orFalse(): Boolean = this ?: false
// ---------------------Collections-------------------------------//
@OptIn(ExperimentalContracts::class)
fun <T> Collection<T>?.isNotNullOrEmpty(): Boolean {
contract {
returns(true) implies (this@isNotNullOrEmpty != null)
}
return this.isNullOrEmpty().not()
}
/**
* 判断集合内是否仅有一个元素
*/
@OptIn(ExperimentalContracts::class)
fun <T> Collection<T>?.isSingle(): Boolean {
contract {
returns(true) implies (this@isSingle != null)
}
return this != null && size == 1
}
/**
* 判断集合内是否有多个元素
* @param minSize 最小为 2
*/
@OptIn(ExperimentalContracts::class)
fun <T> Collection<T>?.isMultiple(@IntRange(from = 2) minSize: Int = 2): Boolean {
contract {
returns(true) implies (this@isMultiple != null)
}
val min = if (minSize < 2) 2 else minSize
return this != null && size >= min
}
fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int): List<T> {
val endIndex = if (toIndex > size) size else toIndex
return subList(fromIndex, endIndex)
}
/**
* 取集合内第二个元素
*/
fun <T> List<T>.secondOrNull(): T? {
return if (size < 2) null else this[1]
}
/**
* 取集合内第三个元素
*/
fun <T> List<T>.thirdOrNull(): T? {
return if (size < 3) null else this[2]
}
fun <E> List<E>.toUnmodifiableList(): List<E> = Collections.unmodifiableList(this)
fun <T> Set<T>.toUnmodifiableSet(): Set<T> = Collections.unmodifiableSet(this)
fun <K, V> Map<K, V>.toUnmodifiableMap(): Map<K, V> = Collections.unmodifiableMap(this)
fun paramMapOf(vararg pairs: Pair<String, Any>): HashMap<String, Any> =
HashMap<String, Any>(pairs.size).apply { putAll(pairs) }
fun <K, V> MutableMap<K, V>.removeFirst(): Map.Entry<K, V> {
val iterator = iterator()
val element = iterator.next()
iterator.remove()
return element
}
fun <K, V> MutableMap<K, V>.removeFirstOrNull(predicate: (Map.Entry<K, V>) -> Boolean): Map.Entry<K, V>? =
entries.removeFirstOrNull(predicate)
fun <T> MutableCollection<T>.removeFirstOrNull(predicate: (T) -> Boolean): T? {
val iterator = iterator()
while (iterator.hasNext()) {
val element = iterator.next()
if (predicate(element)) {
iterator.remove()
return element
}
}
return null
}
// ---------------------Coroutine-------------------------------//
fun <T> CoroutineScope.defaultAsync(
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T> = async(SupervisorJob(), start, block)
suspend fun <T> withIoContext(block: suspend CoroutineScope.() -> T): T =
withContext(Dispatchers.IO, block)
suspend fun <T> withDefaultContext(block: suspend CoroutineScope.() -> T): T =
withContext(Dispatchers.Default, block)
// ---------------------File-------------------------------//
fun File.notExists(): Boolean = exists().not()
// ---------------------View-------------------------------//
// ---------------------Intent-------------------------------//
fun Intent.getStringExtra(name: String, defaultValue: String): String =
getStringExtra(name) ?: defaultValue
fun Intent.getCharSequenceExtra(name: String, defaultValue: CharSequence): CharSequence =
getCharSequenceExtra(name) ?: defaultValue
fun <T : Parcelable> Intent.getParcelableExtra(name: String, defaultValue: T): T =
getParcelableExtra(name) ?: defaultValue
fun <T : Serializable> Intent.getSerializableExtra(
name: String,
defaultValue: Serializable
): Serializable = getSerializableExtra(name) ?: defaultValue
// ---------------------Fragment-------------------------------//
fun <T : Fragment> T.putArguments(bundle: Bundle): T {
arguments = bundle
return this
}
fun <T : Fragment> T.putArguments(vararg pairs: Pair<String, Any?>): T =
putArguments(bundleOf(*pairs))
/**
* @param containerViewId 容器 id
* @param fragment 要添加的 fragment
* @param isAddToBackStack 将要添加的 fragment 是否要添加到返回栈,默认不添加
* @param tag fragment 的 tag
*/
@MainThread
fun FragmentManager.addFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
if (fragment.isAdded) return
commit {
if (isAddToBackStack) addToBackStack(tag)
add(containerViewId, fragment, tag)
}
}
/**
* @param containerViewId 容器 id
* @param fragment 要替换的 fragment
* @param isAddToBackStack 将要替换的 fragment 是否要添加到返回栈,默认添加
* @param tag fragment 的 tag
*/
@MainThread
fun FragmentManager.replaceFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = true,
tag: String? = null
) {
if (fragment.isAdded) return
commit {
if (isAddToBackStack) addToBackStack(tag)
replace(containerViewId, fragment, tag)
}
}
@MainThread
fun Fragment.addFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
childFragmentManager.addFragment(fragment, containerViewId, isAddToBackStack, tag)
}
@MainThread
fun Fragment.replaceFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
childFragmentManager.addFragment(fragment, containerViewId, isAddToBackStack, tag)
}
// ---------------------View-------------------------------//
inline val View.attachedFragment: Fragment?
get() = runCatching { findFragment<Fragment>() }.getOrNull()
inline val View.attachedActivity: Activity?
get() {
var baseContext: Context? = context
while (baseContext is ContextWrapper) {
if (baseContext is Activity) break
baseContext = baseContext.baseContext
}
return baseContext as? Activity
}
inline val View.lifecycle: Lifecycle? get() = findViewTreeLifecycleOwner()?.lifecycle
inline val View.lifecycleScope: LifecycleCoroutineScope? get() = lifecycle?.coroutineScope
fun TextView.setOnEditorConfirmActionListener(listener: (TextView) -> Unit) {
setOnEditorActionListener { view, actionId, event ->
val isConfirmAction = if (event != null) {
when (event.keyCode) {
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER,
KeyEvent.KEYCODE_NUMPAD_ENTER -> true
else -> false
} && event.action == KeyEvent.ACTION_DOWN
} else {
when (actionId) {
EditorInfo.IME_NULL, EditorInfo.IME_ACTION_DONE, EditorInfo.IME_ACTION_NEXT -> true
else -> false
}
}
if (isConfirmAction) {
listener(view)
true
} else {
false
}
}
}
// ---------------------Context-------------------------------//
fun Context.addDynamicShortcutCompat(id: String, shortcut: ShortcutInfoCompat) {
if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 &&
ShortcutManagerCompat.getDynamicShortcuts(this).any { it.id == id }.not()
) {
try {
ShortcutManagerCompat.addDynamicShortcuts(this, mutableListOf(shortcut))
} catch (_: Exception) {
}
}
}
/**
* 取消音频静音
*/
fun Context.setMusicUnmute() {
setMusicMute(false)
}
/**
* 设置音频静音
*
* @param mute 是否静音
*/
fun Context.setMusicMute(mute: Boolean = true) {
getSystemService<AudioManager>()?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val direction = if (mute) AudioManager.ADJUST_UNMUTE else AudioManager.ADJUST_MUTE
it.adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, 0)
} else {
it.setStreamMute(AudioManager.STREAM_MUSIC, mute)
}
}
}
// ---------------------Activity-------------------------------//
@MainThread
fun FragmentActivity.addFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
supportFragmentManager.addFragment(fragment, containerViewId, isAddToBackStack, tag)
}
@MainThread
fun FragmentActivity.replaceFragment(
fragment: Fragment,
@IdRes containerViewId: Int = android.R.id.content,
isAddToBackStack: Boolean = false,
tag: String? = null
) {
supportFragmentManager.replaceFragment(fragment, containerViewId, isAddToBackStack, tag)
}
| 6 | Kotlin | 7 | 26 | 0073c1ceab82630ef6098c593f5eee825a997431 | 15,974 | DemoApp | Apache License 2.0 |
app/src/main/kotlin/com/ashish/movieguide/ui/rated/episode/RatedEpisodePresenter.kt | AshishKayastha | 82,365,723 | false | null | package com.ashish.movieguide.ui.rated.episode
import com.ashish.movieguide.data.interactors.AuthInteractor
import com.ashish.movieguide.data.models.Episode
import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewMvpView
import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewPresenter
import com.ashish.movieguide.utils.schedulers.BaseSchedulerProvider
import javax.inject.Inject
class RatedEpisodePresenter @Inject constructor(
private val authInteractor: AuthInteractor,
schedulerProvider: BaseSchedulerProvider
) : BaseRecyclerViewPresenter<Episode, BaseRecyclerViewMvpView<Episode>>(schedulerProvider) {
override fun getResultsObservable(type: String?, page: Int) = authInteractor.getRatedEpisodes(page)
} | 5 | Kotlin | 5 | 16 | f455e468b917491fd1e35b07f70e9e9e2d00649d | 754 | Movie-Guide | Apache License 2.0 |
app/src/main/kotlin/pl/bkacala/threecitycommuter/ui/screen/map/Map.kt | BlazejKacala | 738,632,039 | false | {"Kotlin": 61083} | package pl.bkacala.threecitycommuter.ui.screen.map
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.font.FontWeight
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.model.MapStyleOptions
import com.google.maps.android.clustering.Cluster
import com.google.maps.android.compose.CameraPositionState
import com.google.maps.android.compose.GoogleMap
import com.google.maps.android.compose.MapProperties
import com.google.maps.android.compose.MapsComposeExperimentalApi
import com.google.maps.android.compose.clustering.Clustering
import kotlinx.coroutines.launch
import pl.bkacala.threecitycommuter.R
import pl.bkacala.threecitycommuter.ui.screen.map.component.BusStopMapItem
@OptIn(MapsComposeExperimentalApi::class)
@Composable
fun Map(
cameraPositionState: CameraPositionState,
busStops: List<BusStopMapItem>,
onBusStationSelected: (busStation: BusStopMapItem) -> Unit,
onMapClicked: () -> Unit
) {
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
GoogleMap(
modifier = Modifier.fillMaxSize(),
cameraPositionState = cameraPositionState,
properties = MapProperties().copy(
mapStyleOptions = MapStyleOptions.loadRawResourceStyle(
context,
mapStyle()
)
),
onMapClick = {
onMapClicked()
}
) {
Clustering(
items = busStops,
clusterItemContent = {
BusStationIcon()
},
onClusterItemClick = {
onBusStationSelected(it)
true
},
clusterContent = {
Cluster(it)
},
onClusterClick = {
coroutineScope.launch {
cameraPositionState.animate(
CameraUpdateFactory.zoomIn()
)
}
true
},
)
}
}
@Composable
private fun Cluster(it: Cluster<BusStopMapItem>) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "( ${it.size} )",
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.Bold
)
BusStationIcon()
}
}
@Composable
private fun BusStationIcon() {
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.bus_station),
contentDescription = "Przystanek",
tint = MaterialTheme.colorScheme.primary
)
}
@Composable
private fun mapStyle(): Int {
return if (isSystemInDarkTheme()) {
R.raw.google_dark_mode_map_style
} else {
R.raw.google_light_mode_map_style
}
} | 0 | Kotlin | 0 | 0 | ee30b6050eea76f9f3cffa887821df826f903440 | 3,394 | 3citycommuter | Apache License 2.0 |
app/src/main/java/com/denysnovoa/nzbmanager/settings/screen/repository/RadarrSettingsStorage.kt | denysnovoa | 90,066,913 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 4, "Proguard": 1, "Java": 2, "Kotlin": 110, "XML": 37} | package com.denysnovoa.nzbmanager.settings.screen.repository
import android.content.Context
import com.denysnovoa.nzbmanager.BuildConfig
import com.denysnovoa.nzbmanager.settings.screen.repository.model.RadarrSettingsModel
import io.reactivex.Completable
import io.reactivex.Single
class RadarrSettingsStorage(val context: Context) : RadarrSettingsRepository {
companion object {
val PREFERENCE_RADARR_API_KEY = "PREFERENCE_RADARR_API_KEY"
val PREFERENCE_RADARR_API_HOST = "PREFERENCE_RADARR_API_HOST"
val PREFERENCE_RADARR_API_PORT = "PREFERENCE_RADARR_API_PORT"
val STRING_EMPTY = ""
}
private val DEFAULT_API_HOST = "example.ddns.net"
override var apiKey: String by PreferenceStorageProvider(context, PREFERENCE_RADARR_API_KEY, STRING_EMPTY)
override var apiHost: String by PreferenceStorageProvider(context, PREFERENCE_RADARR_API_HOST, DEFAULT_API_HOST)
override var apiPort: Int by PreferenceStorageProvider(context, PREFERENCE_RADARR_API_PORT, 7878)
init {
if (BuildConfig.DEBUG) {
apiKey = "b5536e00243a4fd9ad002c53202fb771"
apiHost = "dnovoa20.ddns.net"
}
}
override fun get(): Single<RadarrSettingsModel>
= Single.just(RadarrSettingsModel(apiHost, apiPort, apiKey))
override fun save(radarrSettingsModel: RadarrSettingsModel): Completable = Completable.fromAction {
apiKey = radarrSettingsModel.apiKey
apiHost = radarrSettingsModel.hostName
apiPort = radarrSettingsModel.port
}
}
| 0 | Kotlin | 0 | 1 | 8944e3bae4c073856f9856bf2e5064a6dadde4f7 | 1,553 | radarrsonarr | Apache License 2.0 |
app/src/main/java/com/skyyo/samples/features/scanQR/QrScreen.kt | Skyyo | 385,529,955 | false | {"Kotlin": 557302} | package com.skyyo.samples.features.scanQR
import android.Manifest
import android.annotation.SuppressLint
import android.view.View
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionRequired
import com.google.accompanist.permissions.rememberPermissionState
import com.skyyo.samples.R
import com.skyyo.samples.extensions.goAppPermissions
import com.skyyo.samples.utils.OnClick
import com.skyyo.samples.utils.OnValueChange
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun QrScreen(viewModel: QrViewModel = hiltViewModel()) {
val context = LocalContext.current
val cameraPermissionState = rememberPermissionState(Manifest.permission.CAMERA)
PermissionRequired(
permissionState = cameraPermissionState,
permissionNotGrantedContent = {
CameraPermissionNotGrantedContent(
R.string.please_grant_camera_permission_qr,
cameraPermissionState::launchPermissionRequest
)
},
permissionNotAvailableContent = {
CameraPermissionNotAvailableContent(
R.string.please_grant_camera_permission_from_settings,
context::goAppPermissions
)
},
content = {
QrCameraPreview(
modifier = Modifier.fillMaxSize(),
onQrCodeRecognized = viewModel::onQrCodeRecognized
)
}
)
}
@SuppressLint("UnsafeOptInUsageError")
@Composable
fun QrCameraPreview(
modifier: Modifier = Modifier,
onQrCodeRecognized: OnValueChange
) {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
val cameraPreview = remember {
PreviewView(context).apply {
id = View.generateViewId()
scaleType = PreviewView.ScaleType.FILL_CENTER
}
}
val cameraProviderFeature = remember { ProcessCameraProvider.getInstance(context) }
val executor = remember { ContextCompat.getMainExecutor(context) }
val preview = remember {
Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
// .setTargetResolution(Size(1280, 720))
.build().also {
it.setSurfaceProvider(cameraPreview.surfaceProvider)
}
}
val imageCapture = remember {
ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.build()
}
val imageAnalysis = remember {
ImageAnalysis.Builder()
.build()
.also {
it.setAnalyzer(
executor,
QrCodeAnalyzer { qrCode -> onQrCodeRecognized(qrCode) }
)
}
}
val cameraSelector = remember { CameraSelector.DEFAULT_BACK_CAMERA }
DisposableEffect(Unit) {
val cameraProvider = cameraProviderFeature.get()
cameraProviderFeature.addListener(
{
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
lifecycleOwner,
cameraSelector,
preview,
imageCapture,
imageAnalysis
)
},
executor
)
onDispose { cameraProvider.unbindAll() }
}
AndroidView({ cameraPreview }, modifier)
}
@Composable
fun CameraPermissionNotGrantedContent(explanationStringId: Int, onClick: OnClick) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.Gray)
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(explanationStringId),
color = Color.White,
fontSize = 24.sp,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(32.dp))
Button(onClick = onClick) {
Text(
text = "Grant permission",
color = Color.White,
fontSize = 22.sp,
textAlign = TextAlign.Center
)
}
}
}
@Composable
fun CameraPermissionNotAvailableContent(explanationStringId: Int, onClick: OnClick) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.Gray)
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(explanationStringId),
color = Color.White,
fontSize = 24.sp,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(32.dp))
Button(onClick = onClick) {
Text(
text = "Grant permission",
color = Color.White,
fontSize = 22.sp,
textAlign = TextAlign.Center
)
}
}
}
| 10 | Kotlin | 5 | 77 | 1319c3d29da4865d6f1931ee18137cdfc1715891 | 6,093 | samples | MIT License |
src/main/kotlin/dev/syoritohatsuki/fstatsbackend/plugins/Routing.kt | fStats | 501,329,892 | false | null | package dev.syoritohatsuki.fstatsbackend.plugins
import dev.syoritohatsuki.fstatsbackend.routing.*
import io.ktor.server.application.*
import io.ktor.server.routing.*
fun Application.configureRouting() {
routing {
indexRoute()
route("v1") {
authRoute()
exceptionsRoute()
metricsRoute()
projectsRoute()
usersRoute()
}
}
}
| 0 | Kotlin | 0 | 0 | 982e9a54f10cc446401a79badc628e0d477ce386 | 415 | fstats-backend | MIT License |
irouter_activity/src/main/java/com/afirez/irouter/activity/NavActivity.kt | afirez | 194,509,608 | false | null | package com.afirez.irouter.activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.afirez.irouter.activity.api.User
import com.afirez.spi.SPI
@SPI(path = "/irouter/activity/nav")
class NavActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nav)
val user = intent.getParcelableExtra<User>("user")
val users = intent.getParcelableArrayListExtra<User>("users")
val tags = intent.getStringArrayExtra("tags")
Log.w("IRouter", "" + user)
Log.w("IRouter", "" + users)
Log.w("IRouter", "" + tags)
}
}
| 1 | null | 1 | 8 | fb8b91988d35319024d8da186fcfe82d25a458eb | 732 | irouter | Apache License 2.0 |
library/src/test/kotlin/com/gabrielfeo/develocity/api/ConfigTest.kt | gabrielfeo | 579,131,355 | false | {"Kotlin": 73365} | package com.gabrielfeo.develocity.api
import com.gabrielfeo.develocity.api.internal.*
import org.junit.jupiter.api.assertDoesNotThrow
import kotlin.test.*
class ConfigTest {
@BeforeTest
fun before() {
env = FakeEnv("DEVELOCITY_API_URL" to "https://example.com/api/")
systemProperties = FakeSystemProperties()
}
@Test
fun `Given no URL set in env, error`() {
env = FakeEnv()
assertFails {
Config()
}
}
@Test
fun `Given URL set in env, apiUrl is env URL`() {
(env as FakeEnv)["DEVELOCITY_API_URL"] = "https://example.com/api/"
assertEquals("https://example.com/api/", Config().apiUrl)
}
@Test
fun `Given no token, error`() {
assertFails {
Config().apiToken()
}
}
@Test
fun `Given token set in env, apiToken is env token`() {
(env as FakeEnv)["DEVELOCITY_API_TOKEN"] = "bar"
assertEquals("bar", Config().apiToken())
}
@Test
fun `maxConcurrentRequests accepts int`() {
(env as FakeEnv)["DEVELOCITY_API_MAX_CONCURRENT_REQUESTS"] = "1"
assertDoesNotThrow {
Config().maxConcurrentRequests
}
}
@Test
fun `Given timeout set in env, readTimeoutMillis returns env value`() {
(env as FakeEnv)["DEVELOCITY_API_READ_TIMEOUT_MILLIS"] = "100000"
assertEquals(100_000L, Config().readTimeoutMillis)
}
@Test
fun `Given logLevel in env, logLevel is env value`() {
(env as FakeEnv)["DEVELOCITY_API_LOG_LEVEL"] = "trace"
assertEquals("trace", Config().logLevel)
}
@Test
fun `Given logLevel in System props and not in env, logLevel is prop value`() {
(env as FakeEnv)["DEVELOCITY_API_LOG_LEVEL"] = null
(systemProperties as FakeSystemProperties).logLevel = "info"
assertEquals("info", Config().logLevel)
}
@Test
fun `Given no logLevel set, logLevel is off`() {
(env as FakeEnv)["DEVELOCITY_API_LOG_LEVEL"] = null
(systemProperties as FakeSystemProperties).logLevel = null
assertEquals("off", Config().logLevel)
}
}
| 2 | Kotlin | 0 | 18 | c8feea7e3a714ebeff63604d6651f351ddc96cc0 | 2,152 | develocity-api-kotlin | MIT License |
smartassistlib/src/main/java/com/gowittgroup/smartassistlib/network/ChatGptService.kt | wittgroup-inc | 606,868,969 | false | {"Kotlin": 271796} | package com.gowittgroup.smartassistlib.network
import com.gowittgroup.smartassistlib.Constants.API_VERSION
import com.gowittgroup.smartassistlib.models.ChatCompletionRequest
import com.gowittgroup.smartassistlib.models.ChatCompletionResponse
import com.gowittgroup.smartassistlib.models.ModelResponse
import com.gowittgroup.smartassistlib.models.TextCompletionRequest
import com.gowittgroup.smartassistlib.models.TextCompletionResponse
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
interface ChatGptService {
@GET("$API_VERSION/models")
suspend fun getModels(): ModelResponse
@POST("$API_VERSION/completions")
suspend fun sendTextMessage(@Body request: TextCompletionRequest): TextCompletionResponse
@POST("$API_VERSION/chat/completions")
suspend fun sendChatMessage(@Body request: ChatCompletionRequest): ChatCompletionResponse
}
| 0 | Kotlin | 0 | 0 | bec0d9cb6bbeb4fb8ef14d194d22f8573ca56fb1 | 893 | smartassist | Apache License 2.0 |
cardverificationsheet/src/main/java/com/stripe/android/cardverificationsheet/framework/Config.kt | stripe | 6,926,049 | false | null | package com.stripe.android.cardverificationsheet.framework
import com.stripe.android.cardverificationsheet.framework.api.Network
import com.stripe.android.cardverificationsheet.framework.api.StripeNetwork
import com.stripe.android.cardverificationsheet.framework.time.Duration
import com.stripe.android.cardverificationsheet.framework.time.seconds
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.properties.Properties
object Config {
/**
* If set to true, turns on debug information.
*/
@JvmStatic
var isDebug: Boolean = false
/**
* A log tag used by this library.
*/
@JvmStatic
var logTag: String = "CardVerificationSheet"
/**
* Whether or not to display the Stripe logo.
*/
@JvmStatic
var displayLogo: Boolean = true
/**
* Whether or not to display the "I cannot scan" button.
*/
@JvmStatic
var enableCannotScanButton: Boolean = true
}
object NetworkConfig {
/**
* Whether or not to compress network request bodies.
*/
@JvmStatic
var useCompression: Boolean = false
/**
* The total number of times to try making a network request.
*/
@JvmStatic
var retryTotalAttempts: Int = 3
/**
* The delay between network request retries.
*/
@JvmStatic
var retryDelay: Duration = 5.seconds
/**
* Status codes that should be retried from Stripe servers.
*/
@JvmStatic
var retryStatusCodes: Iterable<Int> = 500..599
/**
* The JSON configuration to use throughout this SDK.
*/
@JvmStatic
var json: Json = Json {
ignoreUnknownKeys = true
isLenient = true
encodeDefaults = true
}
@JvmStatic
@ExperimentalSerializationApi
var form: Properties = Properties
/**
* The network interface to use
*/
@JvmStatic
var network: Network = StripeNetwork(
baseUrl = "https://api.stripe.com/v1",
retryDelay = retryDelay,
retryTotalAttempts = retryTotalAttempts,
retryStatusCodes = retryStatusCodes,
)
}
| 54 | null | 502 | 866 | c64b81095c36df34ffb361da276c116ffd5a2523 | 2,160 | stripe-android | MIT License |
src/main/kotlin/dev/usbharu/hideout/application/service/init/MetaServiceImpl.kt | usbharu | 627,026,893 | false | {"Kotlin": 1337734, "Mustache": 111614, "Gherkin": 21440, "JavaScript": 1112, "HTML": 341} | /*
* Copyright (C) 2024 usbharu
*
* 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.usbharu.hideout.application.service.init
import dev.usbharu.hideout.application.external.Transaction
import dev.usbharu.hideout.core.domain.exception.NotInitException
import dev.usbharu.hideout.core.domain.model.meta.Jwt
import dev.usbharu.hideout.core.domain.model.meta.Meta
import dev.usbharu.hideout.core.domain.model.meta.MetaRepository
import org.springframework.stereotype.Service
@Service
class MetaServiceImpl(private val metaRepository: MetaRepository, private val transaction: Transaction) :
MetaService {
override suspend fun getMeta(): Meta =
transaction.transaction { metaRepository.get() ?: throw NotInitException("Meta is null") }
override suspend fun updateMeta(meta: Meta): Unit = transaction.transaction {
metaRepository.save(meta)
}
override suspend fun getJwtMeta(): Jwt = getMeta().jwt
}
| 38 | Kotlin | 0 | 9 | 5512c43ffacf0480f652465ccf5f71b559387592 | 1,458 | Hideout | Apache License 2.0 |
app/src/main/java/com/jammin/myapplication/data/repository/CommentRepositoryImpl.kt | Junction2022 | 526,564,786 | false | {"Kotlin": 140145} | package com.jammin.myapplication.data.repository
import com.jammin.myapplication.data.model.request.comment.CreateCommentRequest
import com.jammin.myapplication.data.model.response.comment.CreateCommentResponse
import com.jammin.myapplication.data.network.CommentAPI
import javax.inject.Inject
class CommentRepositoryImpl @Inject constructor(
private val api: CommentAPI
) : CommentRepository {
override suspend fun createComment(createCommentRequest: CreateCommentRequest): Result<CreateCommentResponse> =
kotlin.runCatching {
api.createComment(createCommentRequest)
}
override suspend fun likeComment(commentId: String) {
api.likeComment(commentId)
}
override suspend fun disLikeComment(commentId: String) {
api.disLikeComment(commentId)
}
}
| 4 | Kotlin | 0 | 1 | 5cefcbb90842b2a3ef87d6533be6093a18f375d1 | 816 | PaperIn_Android | Apache License 2.0 |
app/src/main/java/com/example/kotlincodingtest/baekjoon/단계별/그래프와_순회/숨바꼭질.kt | ichanguk | 788,416,368 | false | {"Kotlin": 233781} | package com.example.kotlincodingtest.baekjoon.단계별.그래프와_순회
import java.io.BufferedReader
fun main() = with(BufferedReader(System.`in`.bufferedReader())) {
val (N, K) = readLine().split(' ').map { it.toInt() }
val isVisit = MutableList(100001) { false }
val q = ArrayDeque<Pair<Int, Int>>()
q.addLast(Pair(N, 0))
isVisit[N] = true
while (q.isNotEmpty()) {
val cur = q.removeFirst()
if (cur.first == K) {
println(cur.second)
break
}
val nc = mutableListOf(cur.first - 1, cur.first + 1, cur.first * 2)
nc.forEach {
if (it in 0..100000 && !isVisit[it]) {
isVisit[it] = true
q.addLast(Pair(it, cur.second + 1))
}
}
}
} | 0 | Kotlin | 0 | 0 | 1d863d3a9a0ced3a1c1e3c1aec934067b03e77bb | 772 | KotlinCodingTest | MIT License |
app/src/main/java/ru/flyview/freemobile/features/splash/SplashComponent.kt | DmiMukh | 669,794,051 | false | null | package ru.flyview.freemobile.features.splash
interface SplashComponent {
val delayTime: Long
fun onFinish()
} | 0 | Kotlin | 0 | 0 | caaacf4879e9f0faaa4e6cff00448f0f3bcc346b | 121 | FreeMobile | MIT License |
musiclibrary/src/main/java/com/cyl/musiclake/baidu/BaiduArtistInfo.kt | cj7865794408 | 154,458,383 | false | null | package com.cyl.musicapi.baidu
import com.google.gson.annotations.SerializedName
data class BaiduArtistInfo(@SerializedName("comment_num")
val commentNum: Int = 0,
@SerializedName("country")
val country: String = "",
@SerializedName("piao_id")
val piaoId: String = "",
@SerializedName("gender")
val gender: String = "",
@SerializedName("albums_total")
val albumsTotal: String = "",
@SerializedName("collect_num")
val collectNum: Int = 0,
@SerializedName("source")
val source: String = "",
@SerializedName("hot")
val hot: String = "",
@SerializedName("avatar_s180")
val avatarS180: String = "",
@SerializedName("is_collect")
val isCollect: Int = 0,
@SerializedName("bloodtype")
val bloodtype: String = "",
@SerializedName("constellation")
val constellation: String = "",
@SerializedName("listen_num")
val listenNum: String = "",
@SerializedName("avatar_mini")
val avatarMini: String = "",
@SerializedName("intro")
val intro: String = "",
@SerializedName("nickname")
val nickname: String = "",
@SerializedName("company")
val company: String = "",
@SerializedName("mv_total")
val mvTotal: Int = 0,
@SerializedName("avatar_s1000")
val avatarS1000: String = "",
@SerializedName("info")
val info: String = "",
@SerializedName("share_num")
val shareNum: Int = 0,
@SerializedName("area")
val area: String = "",
@SerializedName("avatar_s500")
val avatarS: String = "",
@SerializedName("avatar_big")
val avatarBig: String = "",
@SerializedName("weight")
val weight: String = "",
@SerializedName("birth")
val birth: String = "",
@SerializedName("avatar_middle")
val avatarMiddle: String = "",
@SerializedName("avatar_small")
val avatarSmall: String = "",
@SerializedName("artist_id")
val artistId: String = "",
@SerializedName("url")
val url: String = "",
@SerializedName("firstchar")
val firstchar: String = "",
@SerializedName("aliasname")
val aliasname: String = "",
@SerializedName("songs_total")
val songsTotal: String = "",
@SerializedName("stature")
val stature: String = "",
@SerializedName("name")
val name: String = "",
@SerializedName("ting_uid")
val tingUid: String = "")
| 0 | null | 0 | 3 | 472aab2e180fc40de6c22b7aa82b88f30e32370e | 3,995 | MoErDuo_Music_Lib | Apache License 2.0 |
rsql-provider-zeko/src/main/kotlin/team/yi/rsql/zeko/ZekoRsqlProvider.kt | ymind | 774,842,109 | false | {"Kotlin": 139136, "Mustache": 968} | package team.yi.rsql.zeko
import io.zeko.db.sql.*
import io.zeko.db.sql.extensions.common.distinct
import team.yi.rsql.*
import team.yi.rsql.core.RsqlQueryPart
class ZekoRsqlProvider(
config: ZekoRsqlConfig,
) : RsqlProvider<Query, QueryParts, QueryBlock>(config) {
override fun build(input: RsqlInput): RsqlOutput<Query, QueryParts, QueryBlock> {
val query = Query(espTableName = false)
query.fields(*input.fields?.toTypedArray() ?: arrayOf("*"))
input.distinct?.also { if (it) query.distinct() }
input.from?.also { query.from(it) }
val operatorTransformResults = mutableListOf<RsqlQueryPart<QueryBlock>>()
val visitCallback = ZekoVisitCallback(operatorTransformResults)
val where = parse(input.where, visitCallback)
where?.also { query.where(it) }
val groupBy = input.groupBy
if (!groupBy.isNullOrEmpty()) {
query.groupBy(groupBy)
val having = parse(input.having, visitCallback)
having?.also { query.having(it) }
}
input.orderBy?.forEach {
val expr = it.substringBefore(' ').trim()
val order = it.substringAfter(expr).trim()
if (order.startsWith('D') || order.startsWith('d')) {
query.orderDesc(expr)
} else {
query.orderAsc(expr)
}
}
input.limit?.also { limit ->
val offset = input.offset?.toInt() ?: 0
query.limit(limit.toInt(), offset)
}
// `countQuery` MUST need the `table`, noop when groupBy
val countQueryParts = buildCountQueryParts(query)
val countQuery = countQueryParts
return RsqlOutput(query, countQuery, operatorTransformResults)
}
private fun buildCountQueryParts(query: Query): QueryParts {
val parts = query.toParts()
val custom = parts.custom.clone().apply {
this.remove(CustomPart.SELECT)
this.remove(CustomPart.FIELD)
this.remove(CustomPart.ORDER)
this.remove(CustomPart.LIMIT)
}
val countFields = LinkedHashMap<String, Array<String>>()
val q = Query().fields("COUNT(*) __count")
return QueryParts(
q,
countFields,
parts.from,
parts.joins,
parts.where,
emptyList(),
null,
parts.groupBys,
parts.havings,
custom
)
}
}
| 0 | Kotlin | 0 | 0 | 80d77118f68903939ee3f83db6abc1a7b8ade1de | 2,503 | rsql | MIT License |
example/counter-android/app/src/main/kotlin/com/beyondeye/reduks/example/counter/State.kt | beyondeye | 59,747,728 | false | {"Kotlin": 505882, "Java": 192306} | package com.beyondeye.reduks.example.counter
/**
* Created by kittinunf on 9/1/16.
*/
data class CounterState(val counter: Int = 0) | 5 | Kotlin | 10 | 111 | 80b84d221b92aef0b172938c2e6efaef973269b1 | 135 | Reduks | Apache License 2.0 |
src/commonNative/kotlin/io/tcp/Hooks.kt | Mazel-Tovr | 408,492,973 | false | null | package com.epam.drill.hook.io.tcp
import com.epam.drill.hook.gen.DRILL_SOCKET
import com.epam.drill.hook.io.TcpFinalData
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.update
import kotlinx.cinterop.ByteVarOf
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.MemScope
import kotlinx.cinterop.memScoped
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.plus
import kotlin.native.concurrent.freeze
@SharedImmutable
private val _interceptors = atomic(persistentListOf<Interceptor>())
val interceptors: List<Interceptor>
get() = _interceptors.value
fun addInterceptor(interceptor: Interceptor) {
_interceptors.update { it + interceptor }
}
interface ReadInterceptor {
fun MemScope.interceptRead(fd: DRILL_SOCKET, bytes: CPointer<ByteVarOf<Byte>>, size: Int)
}
interface WriteInterceptor {
fun MemScope.interceptWrite(fd: DRILL_SOCKET, bytes: CPointer<ByteVarOf<Byte>>, size: Int): TcpFinalData
}
interface Interceptor : ReadInterceptor, WriteInterceptor {
fun isSuitableByteStream(fd: DRILL_SOCKET, bytes: CPointer<ByteVarOf<Byte>>): Boolean
fun close(fd: DRILL_SOCKET)
}
fun tryDetectProtocol(fd: DRILL_SOCKET, buf: CPointer<ByteVarOf<Byte>>?, size: Int) {
buf?.let { byteBuf ->
interceptors.forEach {
it.let {
if (it.isSuitableByteStream(fd, byteBuf)) {
memScoped {
with(it) {
interceptRead(fd, buf, size)
}
}
}
}
}
}
}
fun close(fd: DRILL_SOCKET) {
interceptors.forEach {
it.close(fd)
}
}
fun MemScope.processWriteEvent(fd: DRILL_SOCKET, buf: CPointer<ByteVarOf<Byte>>?, size: Int): TcpFinalData {
return buf?.let { byteBuf ->
interceptors.forEach {
it.let {
if (it.isSuitableByteStream(fd, byteBuf))
return with(it) {
interceptWrite(fd, buf, size)
}
else TcpFinalData(buf, size)
}
}
TcpFinalData(buf, size)
} ?: TcpFinalData(buf, size)
}
@SharedImmutable
val CR_LF = "\r\n"
@SharedImmutable
val CR_LF_BYTES = CR_LF.encodeToByteArray()
@SharedImmutable
val HEADERS_DELIMITER = CR_LF_BYTES + CR_LF_BYTES
@SharedImmutable
val injectedHeaders = atomic({ emptyMap<String, String>() }.freeze()).freeze()
@SharedImmutable
val readHeaders = atomic({ _: Map<ByteArray, ByteArray> -> Unit }.freeze()).freeze()
@SharedImmutable
val readCallback = atomic({ _: ByteArray -> Unit }.freeze()).freeze()
@SharedImmutable
val writeCallback = atomic({ _: ByteArray -> Unit }.freeze()).freeze() | 0 | null | 0 | 0 | 26e8eda267589aa8e0d09197392c6c02f6c2aae6 | 2,741 | drill-hook | Apache License 2.0 |
phoenix-android/src/main/kotlin/fr/acinq/phoenix/android/MainActivity.kt | ACINQ | 192,964,514 | false | null | /*
* Copyright 2020 ACINQ SAS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.acinq.phoenix.android
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.lifecycleScope
import androidx.navigation.*
import androidx.navigation.compose.rememberNavController
import fr.acinq.lightning.io.PhoenixAndroidLegacyInfoEvent
import fr.acinq.phoenix.android.components.mvi.MockView
import fr.acinq.phoenix.android.service.NodeService
import fr.acinq.phoenix.android.utils.LegacyMigrationHelper
import fr.acinq.phoenix.android.utils.PhoenixAndroidTheme
import fr.acinq.phoenix.legacy.utils.*
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class MainActivity : AppCompatActivity() {
val log: Logger = LoggerFactory.getLogger(MainActivity::class.java)
private val appViewModel by viewModels<AppViewModel>()
private var navController: NavController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appViewModel.walletState.observe(this) {
log.debug("wallet state update=${it.name}")
}
// reset required status to expected if needed
lifecycleScope.launch {
if (PrefsDatastore.getLegacyAppStatus(applicationContext).filterNotNull().first() is LegacyAppStatus.Required) {
PrefsDatastore.saveStartLegacyApp(applicationContext, LegacyAppStatus.Required.Expected)
}
}
// migrate legacy data if needed
lifecycleScope.launch {
val doDataMigration = PrefsDatastore.getDataMigrationExpected(applicationContext).first()
if (doDataMigration == true) {
LegacyMigrationHelper.migrateLegacyPreferences(applicationContext)
LegacyMigrationHelper.migrateLegacyPayments(applicationContext)
PrefsDatastore.saveDataMigrationExpected(applicationContext, false)
}
}
// listen to legacy channels events on the peer's event bus
lifecycleScope.launch {
val application = (application as PhoenixApplication)
application.business.peerManager.getPeer().eventsFlow.collect {
if (it is PhoenixAndroidLegacyInfoEvent) {
if (it.info.hasChannels) {
log.info("legacy channels have been found")
PrefsDatastore.saveStartLegacyApp(applicationContext, LegacyAppStatus.Required.Expected)
} else {
log.info("no legacy channels were found")
PrefsDatastore.saveStartLegacyApp(applicationContext, LegacyAppStatus.NotRequired)
}
}
}
}
setContent {
rememberNavController().let {
navController = it
PhoenixAndroidTheme(it) {
AppView(appViewModel, it)
}
}
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
// force the intent flag to single top, in order to avoid [handleDeepLink] to finish the current activity.
// this would otherwise clear the app view model, i.e. loose the state which virtually reboots the app
// TODO: look into detaching the app state from the activity
intent!!.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
this.navController?.handleDeepLink(intent)
}
override fun onStart() {
super.onStart()
Intent(this, NodeService::class.java).let { intent ->
applicationContext.bindService(intent, appViewModel.serviceConnection, Context.BIND_AUTO_CREATE or Context.BIND_ADJUST_WITH_ACTIVITY)
}
}
override fun onDestroy() {
super.onDestroy()
try {
unbindService(appViewModel.serviceConnection)
} catch (e: Exception) {
log.error("failed to unbind activity from node service: {}", e.localizedMessage)
}
log.info("destroyed main kmp activity")
}
}
@Preview(device = Devices.PIXEL_3)
@Composable
fun DefaultPreview() {
MockView { PhoenixAndroidTheme(rememberNavController()) { Text("Preview") } }
}
| 68 | C | 75 | 399 | b8a0562bc6e1a13491f494bae3187cae0ee63a1e | 5,194 | phoenix | Apache License 2.0 |
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/solid/BxsRightArrowCircle.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.boxicons.boxicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.boxicons.boxicons.SolidGroup
public val SolidGroup.BxsRightArrowCircle: ImageVector
get() {
if (_bxsRightArrowCircle != null) {
return _bxsRightArrowCircle!!
}
_bxsRightArrowCircle = Builder(name = "BxsRightArrowCircle", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 2.0f)
curveTo(6.486f, 2.0f, 2.0f, 6.486f, 2.0f, 12.0f)
reflectiveCurveToRelative(4.486f, 10.0f, 10.0f, 10.0f)
reflectiveCurveToRelative(10.0f, -4.486f, 10.0f, -10.0f)
reflectiveCurveTo(17.514f, 2.0f, 12.0f, 2.0f)
close()
moveTo(12.0f, 17.0f)
verticalLineToRelative(-4.0f)
lineTo(7.0f, 13.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(5.0f)
lineTo(12.0f, 7.0f)
lineToRelative(5.0f, 5.0f)
lineToRelative(-5.0f, 5.0f)
close()
}
}
.build()
return _bxsRightArrowCircle!!
}
private var _bxsRightArrowCircle: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,035 | compose-icon-collections | MIT License |
next/kmp/browser/src/commonMain/kotlin/org/dweb_browser/browser/jmm/JmmI18nResource.kt | BioforestChain | 594,577,896 | false | {"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818} | package org.dweb_browser.browser.jmm
import org.dweb_browser.helper.compose.Language
import org.dweb_browser.helper.compose.SimpleI18nResource
object JmmI18nResource {
val top_bar_title_install =
SimpleI18nResource(Language.ZH to "应用列表", Language.EN to "Application Manage")
val no_select_detail = SimpleI18nResource(
Language.ZH to "未选择要展示的详情",
Language.EN to "select item to show details",
)
val tab_detail = SimpleI18nResource(Language.ZH to "详情", Language.EN to "Detail")
val tab_intro = SimpleI18nResource(Language.ZH to "介绍", Language.EN to "Introduction")
val tab_param = SimpleI18nResource(Language.ZH to "参数", Language.EN to "Parameter")
val short_name = SimpleI18nResource(Language.ZH to "安装管理", Language.EN to "Install Manager")
val history_tab_installed =
SimpleI18nResource(Language.ZH to "已安装", Language.EN to "Installed")
val history_tab_uninstalled =
SimpleI18nResource(Language.ZH to "未安装", Language.EN to "No Install")
val install_mmid = SimpleI18nResource(Language.ZH to "唯一标识", Language.EN to "id")
val install_version = SimpleI18nResource(Language.ZH to "版本", Language.EN to "version")
val install_introduction =
SimpleI18nResource(Language.ZH to "应用介绍", Language.EN to "Introduction")
val install_update_log =
SimpleI18nResource(Language.ZH to "更新日志", Language.EN to "Update Log")
val install_info = SimpleI18nResource(Language.ZH to "信息", Language.EN to "Info")
val install_info_dev =
SimpleI18nResource(Language.ZH to "开发者", Language.EN to "Developer")
val install_info_size = SimpleI18nResource(Language.ZH to "应用大小", Language.EN to "App Size")
val install_info_type = SimpleI18nResource(Language.ZH to "类别", Language.EN to "Type")
val install_info_language =
SimpleI18nResource(Language.ZH to "语言", Language.EN to "Language")
val install_info_age = SimpleI18nResource(Language.ZH to "年龄", Language.EN to "Age")
val install_info_copyright =
SimpleI18nResource(Language.ZH to "版权", Language.EN to "CopyRight")
val install_info_homepage =
SimpleI18nResource(Language.ZH to "应用主页", Language.EN to "Home Page")
val history_details = SimpleI18nResource(Language.ZH to "详情", Language.EN to "Details")
val uninstall =
SimpleI18nResource(Language.ZH to "卸载", Language.EN to "Uninstall")
val remove_record =
SimpleI18nResource(Language.ZH to "删除记录", Language.EN to "Delete Record")
val url_invalid =
SimpleI18nResource(
Language.ZH to "网址已失效,请前往官网进行安装!",
Language.EN to "The website is no longer valid, please go to the official website to install!"
)
} | 66 | Kotlin | 5 | 20 | 6db1137257e38400c87279f4ccf46511752cd45a | 2,595 | dweb_browser | MIT License |
favoritesdatabase/src/main/java/com/programmersbox/favoritesdatabase/ItemDatabase.kt | jakepurple13 | 353,155,453 | false | null | package com.programmersbox.favoritesdatabase
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
@Database(entities = [DbModel::class, ChapterWatched::class, NotificationItem::class], version = 2)
@TypeConverters(ItemConverters::class)
abstract class ItemDatabase : RoomDatabase() {
abstract fun itemDao(): ItemDao
companion object {
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE `Notifications` (`id` INTEGER NOT NULL, `url` TEXT NOT NULL, `summaryText` TEXT NOT NULL, `notiTitle` TEXT NOT NULL, `notiPicture` TEXT, `source` TEXT NOT NULL, `contentTitle` TEXT NOT NULL, PRIMARY KEY(`url`))")
}
}
@Volatile
private var INSTANCE: ItemDatabase? = null
fun getInstance(context: Context): ItemDatabase =
INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context).also { INSTANCE = it } }
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext, ItemDatabase::class.java, "favoriteItems.db")
.addMigrations(MIGRATION_1_2)
.build()
}
} | 1 | Kotlin | 5 | 83 | 6c24eb3f85c9ebc1795a1eb04f916104031d672a | 1,431 | OtakuWorld | Apache License 2.0 |
idea/testData/quickfix/createFromUsage/createVariable/localVariable/afterNullableType.kt | crazyproger | 34,161,856 | true | {"Markdown": 32, "XML": 663, "Ant Build System": 35, "Ignore List": 8, "Kotlin": 17522, "Java": 4262, "Protocol Buffer": 4, "Text": 3708, "JavaScript": 61, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 116, "Groovy": 20, "Maven POM": 47, "Gradle": 68, "Java Properties": 9, "CSS": 3, "JFlex": 2, "Shell": 7, "Batchfile": 7} | // "Create local variable 'foo'" "true"
fun test(): Int? {
val foo = null
return foo
} | 0 | Java | 0 | 0 | e0a394ec62f364a4a96c15b2d2adace32ce61e9e | 95 | kotlin | Apache License 2.0 |
src/test/kotlin/leetcode/LC_67_AddBinaryTest.kt | so3500 | 110,426,646 | false | {"Java": 733632, "Kotlin": 67130, "Python": 10364, "Shell": 893} | package leetcode
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
class LC_67_AddBinaryTest {
private val lcn = LC_67_AddBinary()
@ParameterizedTest
@MethodSource
fun test(a: String, b: String, expected: String) {
assertThat(lcn.addBinary(a, b)).isEqualTo(expected)
}
companion object {
@JvmStatic
private fun test() = listOf(
Arguments.of("11", "1", "100"),
Arguments.of("1010", "1011", "10101"),
Arguments.of("10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101", "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011", "110111101100010011000101110110100000011101000101011001000011011000001100011110011010010011000000000")
)
}
} | 1 | Java | 1 | 1 | 1e2a25431b419d0e8d60f5ca88dde8c08d870786 | 990 | problem-solving | MIT License |
client-app/app/src/main/java/org/feup/group4/supermarket/service/NFCSenderService.kt | fernandorego | 609,645,133 | false | null | package org.feup.group4.supermarket.service
import android.nfc.cardemulation.HostApduService
import android.os.Bundle
import android.preference.PreferenceManager
import kotlin.math.ceil
class NFCSenderService : HostApduService() {
companion object {
private var byteArray: ByteArray? = null
private var index = 0
private var numberOfSlices = 0
fun setByteArray(byteArray: ByteArray) {
NFCSenderService.byteArray = byteArray
index = 0
numberOfSlices =
ceil(byteArray.size.toDouble() / NFCReaderService.NFC_MAX_RES_SIZE).toInt()
}
}
override fun processCommandApdu(command: ByteArray, extra: Bundle?): ByteArray {
if (index == numberOfSlices) {
index = 0
}
if (byteArray == null || !PreferenceManager.getDefaultSharedPreferences(
applicationContext
).getBoolean(NFCReaderService.NFC_PREF_SEND, false)
) {
return NFCReaderService.NFC_CMD_UNKNOWN
}
if (NFCReaderService.NFC_CMD_SELECT_APDU.contentEquals(command)) {
val slice = byteArray!!.sliceArray(
index * NFCReaderService.NFC_MAX_RES_SIZE until kotlin.math.min(
index * NFCReaderService.NFC_MAX_RES_SIZE + NFCReaderService.NFC_MAX_RES_SIZE,
byteArray!!.size
)
)
index += 1
return if (index == numberOfSlices) {
slice + NFCReaderService.NFC_CMD_OK_FINISHED
} else {
slice + NFCReaderService.NFC_CMD_OK_MORE
}
}
return NFCReaderService.NFC_CMD_ERROR
}
override fun onDeactivated(p0: Int) {}
} | 0 | Kotlin | 0 | 0 | 624e2b8950465534e0627820ba89b4ea43a3e582 | 1,753 | feup-cpm-supermarket | MIT License |
src/main/java/io/userfeeds/cryptocache/cryptoverse/main/common/Controller.kt | CryptoverseCC | 136,720,594 | false | {"Kotlin": 64469, "Dockerfile": 225} | package io.userfeeds.cryptocache.cryptoverse.main.common
import io.userfeeds.cryptocache.id
import io.userfeeds.cryptocache.version
object Controller {
fun getFeed(repository: Repository, oldestKnown: String?, lastVersion: Long?, size: Int?): Page {
val cache = repository.cache
check(cache.allItems.isNotEmpty()) { "API is not ready." }
var version: Long? = cache.version
val items = if (oldestKnown != null && lastVersion != null) {
check(size == null)
val almost = cache.allItems.takeWhile { it.id != oldestKnown }
val unfiltered = almost + if (almost.size < cache.allItems.size) cache.allItems[almost.size] else mutableMapOf()
unfiltered.filter { it.version > lastVersion }
} else if (oldestKnown != null && size != null) {
check(lastVersion == null)
version = null
cache.allItems.dropWhile { it.id != oldestKnown }.drop(1).take(size)
} else if (size != null) {
check(oldestKnown == null && lastVersion == null)
cache.allItems.take(size)
} else {
throw UnsupportedOperationException("oldestKnown+lastVersion, oldestKnown+size or size missing")
}
return Page(items = items, total = cache.allItems.size, version = version)
}
}
| 0 | Kotlin | 0 | 0 | 12b9465009f05441d8f5c63d29670a585194fca7 | 1,332 | crypto-cache | The Unlicense |
shared/src/iosMain/kotlin/com.joetr.bundle/util/Platform.kt | j-roskopf | 730,016,308 | false | {"Kotlin": 1489240, "Ruby": 2876, "Shell": 1323, "Swift": 584} | package com.joetr.bundle.util
actual fun displayPlatformName() = "iOS"
actual val iOS: Boolean = true
| 0 | Kotlin | 0 | 6 | c0c924fa4d5b63cd25c080e857e591ace4eac13c | 103 | Rockabye | MIT License |
app-entity/recipe/data/src/main/java/org/codeforvictory/android/recipes/data/api/recipe/RetrofitProvider.kt | codeforvictory | 330,168,795 | false | {"Kotlin": 20445} | package org.codeforvictory.android.recipes.data.api.recipe
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
object RetrofitProvider {
val value: Retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://www.themealdb.com/api/json/v1/1")
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
}
| 10 | Kotlin | 0 | 2 | cfdd706cd57576d757bd6d55ddf79b5f22cbcd20 | 388 | recipes-mvi-playground | The Unlicense |
src/test/kotlin/se/codeboss/slacklin/internal/StringExtensionsTest.kt | Kantis | 161,412,245 | false | null | package se.codeboss.slacklin.internal
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class StringExtensionsTest {
@Test
fun `only lower case remains unchanged`() {
assertEquals("abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz".toLowerCaseWithUnderscores())
}
@Test
fun `upper cased first letter does not result in a leading underscore`() {
assertEquals("a", "A".toLowerCaseWithUnderscores())
assertEquals("abc", "Abc".toLowerCaseWithUnderscores())
}
@Test
fun `upper cased letters are converted to underscore and lower cased letter`() {
assertEquals("a_b_c", "ABC".toLowerCaseWithUnderscores())
assertEquals("ab_c", "abC".toLowerCaseWithUnderscores())
assertEquals("my_value", "MyValue".toLowerCaseWithUnderscores())
}
@Test
fun `with join to string`() {
val strings = listOf("MyName", "MyAge")
assertEquals("my_name,my_age", strings.joinToString(separator = ",") { it.toLowerCaseWithUnderscores() })
}
} | 0 | Kotlin | 1 | 0 | b331ac508c59349f37e8b7f425b3ea2c41860361 | 1,051 | slacklin | Apache License 2.0 |
app/src/main/java/me/sungbin/codemover/MainActivity.kt | jisungbin | 326,364,273 | false | null | package me.sungbin.codemover
import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import me.sungbin.androidutils.extensions.get
import me.sungbin.androidutils.extensions.toast
import me.sungbin.androidutils.util.PermissionUtil
import me.sungbin.androidutils.util.StorageUtil
class MainActivity : AppCompatActivity() {
private lateinit var alert: AlertDialog
private lateinit var adapter: DialogAdapter
private val livedata: MutableLiveData<String> = MutableLiveData()
private var lastCodeReceiveTime = 0L
@SuppressLint("InflateParams")
private fun init() {
livedata.observe(this) { code ->
val nowCodeReceiveTime = System.currentTimeMillis()
if (lastCodeReceiveTime + 3000 >= nowCodeReceiveTime) return@observe
lastCodeReceiveTime = nowCodeReceiveTime
adapter.setOnFolderSelectedListener { path ->
StorageUtil.save(path, code)
alert.cancel()
toast(getString(R.string.main_apply_code))
}
alert.show()
}
val view = layoutInflater.inflate(R.layout.layout_dialog, null)
val recyclerView = view[R.id.rv_view, RecyclerView::class.java]
adapter = DialogAdapter(recyclerView).apply { init() }
recyclerView.adapter = adapter
alert = AlertDialog.Builder(this@MainActivity).apply {
setView(view)
setPositiveButton(getString(R.string.close), null)
setCancelable(false)
}.create()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
init()
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
PermissionUtil.request(
this,
getString(R.string.main_need_permission),
arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
)
val reference = Firebase.database.reference
reference.addChildEventListener(object : ChildEventListener {
override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
val code = snapshot.getValue(String::class.java).toString()
livedata.postValue(code)
reference.removeValue()
}
override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {}
override fun onChildRemoved(snapshot: DataSnapshot) {}
override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {}
override fun onCancelled(error: DatabaseError) {}
})
}
}
| 0 | Kotlin | 0 | 2 | c63f123fbc15ca7837802a5ac0a11ba9d573ee75 | 3,260 | CodeMover | MIT License |
src/main/kotlin/phonon/puppet/animation/AnimationTrack.kt | phonon | 278,514,975 | false | null | /**
* Animation time series track for updating position, quaternion
* properties for multiple bones.
*
* Cache animation p (position) and q (quaternion) states per tick into
* pre-sampled FloatArray tracks on run in format:
* position: [p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, ...]
* quaternion: [q0.x, q0.y, q0.z, q0.w, q1.x, q1.y, q1.z, q1.w, ... ]
*
* Playing animations can iterate the track and consume
* in chunks to gather position, quaternion data.
*
* Keyframe name format for bone properties: "[name].[property].[component]"
* e.g. "head.position.0", "head.quaternion.0", ...
*/
package phonon.puppet.animation
import phonon.puppet.math.*
// wrapper arround individual sampled property tracks
public class TransformTrack(
val position: FloatArray?,
val quaternion: FloatArray?
)
// keyframes map bone name -> keyframe list
public class AnimationTrack(
val name: String,
val keyframesPosition: HashMap<String, List<Keyframe<Vector3f>>>,
val keyframesQuaternion: HashMap<String, List<Keyframe<Quaternion>>>
) {
// map bone name -> sampled transform data in FloatArray format
// containing pre-sampled position, quaternion data tracks
val transformTracks: HashMap<String, TransformTrack> = hashMapOf()
// animation length in ticks (calculated from input keyframes)
val length: Int
/**
* Initialization:
* - get length of animation (last keyframe point in time)
* - presample keyframes to generate transform data tracks.
*/
init {
// get all bones involved in this animation
val bonesToTransform: Set<String> = this.keyframesPosition.keys + this.keyframesQuaternion.keys
var firstKeyframeTick: Int = 0
var lastKeyframeTick: Int = 0
// sort all keyframes (just in case)
// and get animation length (last keyframe tick)
for ( boneName in bonesToTransform ) {
val keyframePositionList = this.keyframesPosition.get(boneName)
if ( keyframePositionList !== null ) {
val sortedKeyframeList = keyframePositionList.sortedBy { it.tick }
this.keyframesPosition.put(boneName, sortedKeyframeList)
val firstKeyframe = sortedKeyframeList.firstOrNull()
if ( firstKeyframe !== null ) {
firstKeyframeTick = if ( firstKeyframe.tick < firstKeyframeTick ) {
firstKeyframe.tick
} else {
firstKeyframeTick
}
}
val lastKeyframe = sortedKeyframeList.lastOrNull()
if ( lastKeyframe !== null ) {
lastKeyframeTick = if ( lastKeyframe.tick > lastKeyframeTick ) {
lastKeyframe.tick
} else {
lastKeyframeTick
}
}
}
val keyframeQuaternionList = this.keyframesQuaternion.get(boneName)
if ( keyframeQuaternionList !== null ) {
val sortedKeyframeList = keyframeQuaternionList.sortedBy { it.tick }
this.keyframesQuaternion.put(boneName, sortedKeyframeList)
val firstKeyframe = sortedKeyframeList.firstOrNull()
if ( firstKeyframe !== null ) {
firstKeyframeTick = if ( firstKeyframe.tick < firstKeyframeTick ) {
firstKeyframe.tick
} else {
firstKeyframeTick
}
}
val lastKeyframe = sortedKeyframeList.lastOrNull()
if ( lastKeyframe !== null ) {
lastKeyframeTick = if ( lastKeyframe.tick > lastKeyframeTick ) {
lastKeyframe.tick
} else {
lastKeyframeTick
}
}
}
}
// add 1 to length because ticks endpoints are inclusive
this.length = 1 + lastKeyframeTick - firstKeyframeTick
// form sampled transform tracks for each bone
for ( boneName in bonesToTransform ) {
val positionTrack = this.keyframesPosition.get(boneName)?.let { keyframeList ->
val buffer = FloatArray(this.length * 3, { 0f })
sampleVectorKeyframesIntoBuffer(keyframeList, buffer, this.length)
buffer
}
val quaternionTrack = this.keyframesQuaternion.get(boneName)?.let { keyframeList ->
val buffer = FloatArray(this.length * 4, { i -> if ( (i+1) % 4 == 0 ) 1f else 0f })
sampleQuaternionKeyframesIntoBuffer(keyframeList, buffer, this.length)
buffer
}
this.transformTracks.put(boneName, TransformTrack(positionTrack, quaternionTrack))
}
}
/**
* Write track data for bone into position, quaternion structures.
*
* @param name name of data track (should correspond to model bone name)
* @param tick frame tick in animation
* @param position position vector output to write data
* @param quaternion quaternion output to write data
* @return boolean status if bone track found and written successfully
*/
public fun writeIntoPositionQuaternion(name: String, tick: Int, position: Vector3f, quaternion: Quaternion): Boolean {
val dataTrack = this.transformTracks.get(name)
if ( dataTrack === null ) {
return false
}
val positionTrack = dataTrack.position
val quaternionTrack = dataTrack.quaternion
if ( positionTrack !== null ) {
val index = tick * 3
position.x = positionTrack[index]
position.y = positionTrack[index+1]
position.z = positionTrack[index+2]
}
if ( quaternionTrack !== null ) {
val index = tick * 4
quaternion.x = quaternionTrack[index]
quaternion.y = quaternionTrack[index+1]
quaternion.z = quaternionTrack[index+2]
quaternion.w = quaternionTrack[index+3]
}
return true
}
// static manager methods
companion object {
// track library
public val library: HashMap<String, AnimationTrack> = hashMapOf()
/**
* Add AnimationTrack prototype into library.
* Will overwrite existing keys in the library.
*/
public fun save(animTrack: AnimationTrack) {
AnimationTrack.library.put(animTrack.name, animTrack)
}
/**
* Delete data in library
*/
public fun clear() {
AnimationTrack.library.clear()
}
/**
* Return AnimationTrack stored in library
*
* @param name name in library
*/
public fun get(name: String): AnimationTrack? {
return AnimationTrack.library.get(name)
}
/**
* Return list of track names
*/
public fun list(): List<String> {
return AnimationTrack.library.keys.toList()
}
}
}
// DEPRECATED
// merge component keyframes into Quaternion object keyframes
// ASSUME all components have keyframes at same points in time
// so, use keyframesX as reference for iterating
private fun formQuaternionKeyframes(
keyframesX: List<Keyframe<Double>>,
keyframesY: List<Keyframe<Double>>,
keyframesZ: List<Keyframe<Double>>,
keyframesW: List<Keyframe<Double>>
): List<Keyframe<Quaternion>> {
// other components
val iterKeysY = keyframesY.iterator()
val iterKeysZ = keyframesZ.iterator()
val iterKeysW = keyframesW.iterator()
var currKeyY = iterKeysY.next()
var currKeyZ = iterKeysZ.next()
var currKeyW = iterKeysW.next()
val keyframesQuat: MutableList<Keyframe<Quaternion>> = mutableListOf()
for ( currKeyX in keyframesX ) {
var frame: Int = currKeyX.tick
currKeyY = if ( iterKeysY.hasNext() && currKeyY.tick < frame ) iterKeysY.next() else currKeyY
currKeyZ = if ( iterKeysZ.hasNext() && currKeyZ.tick < frame ) iterKeysZ.next() else currKeyZ
currKeyW = if ( iterKeysW.hasNext() && currKeyW.tick < frame ) iterKeysW.next() else currKeyW
val x = currKeyX.value.toFloat()
val y = currKeyY.value.toFloat()
val z = currKeyZ.value.toFloat()
val w = currKeyW.value.toFloat()
keyframesQuat.add(Keyframe(
frame,
Quaternion(x, y, z, w).normalize(),
currKeyX.interpolation
))
}
return keyframesQuat.toList()
}
// sample double valued keyframe list into blocked array
private fun sampleDoubleKeyframesIntoBuffer(keyframes: List<Keyframe<Double>>, buffer: FloatArray, numBlocks: Int, block: Int, offset: Int) {
if ( keyframes.size == 0 ) {
return
}
val keyIter = keyframes.iterator()
var currKey = keyIter.next()
var nextKey = if ( keyIter.hasNext() ) keyIter.next() else currKey
// interpolate and write samples
for ( i in 0 until numBlocks ) {
// update current, next keyframes
if ( i >= nextKey.tick && keyIter.hasNext() ) {
currKey = nextKey
nextKey = keyIter.next()
}
// interpolate value
val value = if ( nextKey.tick > currKey.tick ) {
nextKey.interpolation.interpolate(currKey.value, nextKey.value, (i - currKey.tick).toDouble() / (nextKey.tick - currKey.tick).toDouble() )
}
else {
currKey.value
}
buffer[i*block + offset] = value.toFloat()
}
}
// sample Vector3f keyframes list into blocked array
private fun sampleVectorKeyframesIntoBuffer(keyframes: List<Keyframe<Vector3f>>, buffer: FloatArray, numBlocks: Int) {
if ( keyframes.size == 0 ) {
return
}
val keyIter = keyframes.iterator()
var currKey = keyIter.next()
var nextKey = if ( keyIter.hasNext() ) keyIter.next() else currKey
val v = Vector3f.zero()
// interpolate and write samples
for ( i in 0 until numBlocks ) {
// update current, next keyframes
if ( i >= nextKey.tick && keyIter.hasNext() ) {
currKey = nextKey
nextKey = keyIter.next()
}
// slerp interpolation parameter
val a = if ( nextKey.tick > currKey.tick ) {
nextKey.interpolation.interpolate(0.0, 1.0, (i - currKey.tick).toDouble() / (nextKey.tick - currKey.tick).toDouble() )
}
else {
0.0
}
v.lerpVectors(currKey.value, nextKey.value, a)
val index = i * 3
buffer[index] = v.x
buffer[index+1] = v.y
buffer[index+2] = v.z
}
}
// sample quaternion keyframes list into blocked array
private fun sampleQuaternionKeyframesIntoBuffer(keyframes: List<Keyframe<Quaternion>>, buffer: FloatArray, numBlocks: Int) {
if ( keyframes.size == 0 ) {
return
}
val keyIter = keyframes.iterator()
var currKey = keyIter.next()
var nextKey = if ( keyIter.hasNext() ) keyIter.next() else currKey
val q = Quaternion.zero()
// interpolate and write samples
for ( i in 0 until numBlocks ) {
// update current, next keyframes
if ( i >= nextKey.tick && keyIter.hasNext() ) {
currKey = nextKey
nextKey = keyIter.next()
}
// slerp interpolation parameter
val a = if ( nextKey.tick > currKey.tick ) {
nextKey.interpolation.interpolate(0.0, 1.0, (i - currKey.tick).toDouble() / (nextKey.tick - currKey.tick).toDouble() )
}
else {
0.0
}
q.slerp(currKey.value, nextKey.value, a)
val index = i * 4
buffer[index] = q.x
buffer[index+1] = q.y
buffer[index+2] = q.z
buffer[index+3] = q.w
}
}
| 0 | Kotlin | 0 | 9 | 55b6d7055fd6bed9377bebfa39b7084dd24d9341 | 11,998 | minecraft-puppet | MIT License |
app/src/main/java/io/appwrite/almostnetflix/core/ContentDetailViewModelFactory.kt | appwrite | 450,667,742 | false | {"Kotlin": 48456} | package io.appwrite.almostnetflix.core
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.appwrite.Client
import io.appwrite.almostnetflix.movie.MovieDetailViewModel
class ContentDetailViewModelFactory(
private val client: Client,
private val userId: String,
private val movieId: String,
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>) = when (modelClass) {
MovieDetailViewModel::class.java -> MovieDetailViewModel(client, userId, movieId) as T
else -> throw UnsupportedOperationException()
}
} | 0 | Kotlin | 3 | 16 | c37afc1a49873ab42753d80ce3ca91bdfe515567 | 613 | demo-almost-netflix-for-android | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.