path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/newsappjetpackcompose/presentation/view/components/news/ArticlesList.kt | engspa12 | 511,196,241 | false | null | package com.example.newsappjetpackcompose.presentation.view.components.news
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.newsappjetpackcompose.presentation.model.ArticleView
import com.example.newsappjetpackcompose.presentation.view.theme.NewsAppKtTheme
@Composable
fun ArticlesList(
lazyState: LazyListState,
list: List<ArticleView>,
modifier: Modifier = Modifier,
onItemClicked: (String) -> Unit
){
LazyColumn(
modifier = modifier,
state = lazyState
) {
itemsIndexed(list) { _, articleView ->
ArticleItem(
articleView = articleView,
modifier = Modifier
.fillMaxWidth()
.height(140.dp)
) {
onItemClicked(articleView.webUrl)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
NewsAppKtTheme {
val list = ArrayList<ArticleView>()
list.add(ArticleView("title 1", "section 1", "author 1", "release 1","weburl 1", "thumb 1"))
list.add(ArticleView("title 2", "section 2", "author 2", "release 2","weburl 2", "thumb 2"))
ArticlesList(
lazyState = rememberLazyListState(),
list = list
) {
}
}
} | 0 | Kotlin | 0 | 2 | d30f455e54f9db645c3f1144fb3864c759cee956 | 1,744 | NewsAppKt | MIT License |
mantono-kotlin/src/test/kotlin/com/mantono/aoc/day04/ComputePasswordsTest.kt | kodsnack | 223,724,445 | false | {"Python": 390591, "C#": 189476, "Rust": 166608, "Dart": 146968, "C++": 127941, "F#": 68551, "Haskell": 60413, "Nim": 46562, "Kotlin": 27811, "REXX": 13854, "OCaml": 12448, "Go": 11995, "C": 9751, "Swift": 8043, "JavaScript": 1750, "CMake": 1107, "PowerShell": 866, "AppleScript": 493, "Shell": 255} | package com.mantono.aoc.day04
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class ComputePasswordsTest {
@Test
fun hasRepeatedNumberTest() {
assertTrue(hasRepeatedNumber("111111"))
assertTrue(hasRepeatedNumber("123356"))
assertFalse(hasRepeatedNumber("123456"))
}
@Test
fun hasNoDecreasingNumbersTest() {
assertTrue(isOnlyIncreasing("111111"))
assertTrue(isOnlyIncreasing("111123"))
assertTrue(isOnlyIncreasing("135679"))
assertFalse(isOnlyIncreasing("123465"))
}
} | 0 | Python | 40 | 7 | 16a81beca685f559414238615841424eb16cdc44 | 640 | advent_of_code_2019 | Apache License 2.0 |
src/main/kotlin/com/swisschain/matching/engine/database/redis/connection/impl/RedisConnectionFactoryImpl.kt | swisschain | 255,464,363 | false | null | package com.swisschain.matching.engine.database.redis.connection.impl
import com.swisschain.matching.engine.database.redis.connection.RedisConnection
import com.swisschain.matching.engine.database.redis.connection.RedisConnectionFactory
import com.swisschain.matching.engine.utils.config.Config
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
@Component
class RedisConnectionFactoryImpl (private val applicationEventPublisher: ApplicationEventPublisher,
private val config: Config): RedisConnectionFactory {
override fun getConnection(name: String): RedisConnection? {
return RedisConnectionImpl(name, config.me.redis, applicationEventPublisher)
}
} | 1 | null | 1 | 1 | 5ef23544e9c5b21864ec1de7ad0f3e254044bbaa | 762 | Exchange.MatchingEngine | Apache License 2.0 |
common/src/main/kotlin/com/goofy/goober/common/snapshot/ImageSearchViewModel.kt | drinkthestars | 307,616,443 | false | null | package com.goofy.goober.viewmodel
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.goofy.goober.interactor.AstroInteractor
import com.goofy.goober.model.ImageResultsAction
import com.goofy.goober.model.ImageResultsScreenState
import com.goofy.goober.model.ImageResultsState
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
/**
* This is logically the same as [ImageSearchViewModel] in the astro-uitoolkit package.
* The only difference is that this [ImageResultsScreenState]
* uses Compose's [mutableStateOf]
*/
private const val InitialQuery = "galaxy"
class ImageSearchViewModel(
private val astroInteractor: AstroInteractor
) : ViewModel() {
val state = ImageResultsScreenState(
initialQuery = InitialQuery,
initialImageResultsState = ImageResultsState()
)
init {
astroInteractor
.produceImageSearchResult()
.onEach { dispatch(it) }
.launchIn(viewModelScope)
.also { dispatch(ImageResultsAction.Search(InitialQuery)) }
}
fun dispatch(action: ImageResultsAction) {
updateState(action)
middleware(action)
}
private fun middleware(action: ImageResultsAction) {
when (action) {
is ImageResultsAction.Search -> astroInteractor.enqueueImageSearch(action.query)
ImageResultsAction.ShowError,
is ImageResultsAction.ShowImages -> Unit
}
}
private fun updateState(action: ImageResultsAction) = state.update(action)
}
| 0 | Kotlin | 2 | 8 | 08c3ab481c0426c483dd43191537c46b0ff537a0 | 1,618 | space-library | MIT License |
app/src/test/java/com/cwlarson/deviceid/testutils/CoroutineTestRule.kt | opt05 | 370,757,069 | false | {"Kotlin": 765955} | package com.cwlarson.deviceid.androidtestutils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.*
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/**
* CoroutineTestRule installs a [UnconfinedTestDispatcher] for [Dispatchers.Main].
*
* Since it is run under TestScope, you can directly launch coroutines on the CoroutineTestRule
* as a [CoroutineScope]:
*
* ```
* testScope.launch { aTestCoroutine() }
* ```
*
* All coroutines started on CoroutineTestRule must complete (including timeouts) before the test
* finishes, or it will throw an exception.
*
* When using CoroutineTestRule you should always invoke [runTest] on it to avoid creating two
* instances of [TestCoroutineScheduler] or [TestScope] in your test:
*
* ```
* @Test
* fun usingRunTest() = runTest {
* aTestCoroutine()
* }
* ```
*
* You may call [StandardTestDispatcher] methods on CoroutineTestRule and they will control the
* virtual-clock.
*
* ```
* withContext(StandardTestDispatcher(testScheduler)) { // do some coroutines }
* advanceUntilIdle() // run all pending coroutines until the dispatcher is idle
* ```
*
* By default, CoroutineTestRule will be in a *unpaused* state.
*
* @param dispatcher if provided, or else [UnconfinedTestDispatcher] will be used.
*/
class CoroutineTestRule(
val dispatcher: TestDispatcher = UnconfinedTestDispatcher(TestCoroutineScheduler())
) : TestWatcher() {
override fun starting(description: Description) {
super.starting(description)
Dispatchers.setMain(dispatcher)
}
override fun finished(description: Description) {
super.finished(description)
dispatcher.scheduler.advanceUntilIdle()
Dispatchers.resetMain()
}
} | 0 | Kotlin | 1 | 2 | 5e01e6b5356d3a2e80f7a102ecf513936b226269 | 1,804 | deviceid | MIT License |
marathon-gradle-plugin/src/main/kotlin/com/malinskiy/marathon/gradle/DistributionInstaller.kt | MarathonLabs | 129,365,301 | false | null | package com.malinskiy.marathon.gradle
import org.apache.commons.codec.digest.DigestUtils
import java.io.File
import java.util.zip.ZipFile
class DistributionInstaller {
fun install(marathonBuildDir: File) {
val marathonZip = copyFromResources(marathonBuildDir)
unzip(marathonZip, marathonBuildDir)
}
private fun copyFromResources(marathonBuildDir: File): File {
val marathonZip = File(marathonBuildDir, "marathon-cli.zip")
if (!marathonZip.exists() || !compareDist(marathonZip)) {
marathonZip.outputStream().buffered().use {
MarathonPlugin::class.java.getResourceAsStream(CLI_PATH).copyTo(it)
}
}
return marathonZip
}
private fun unzip(marathonZip: File, marathonBuildDir: File) {
marathonBuildDir.listFiles()?.forEach {
if (it.isDirectory) {
it.deleteRecursively()
}
}
File(marathonBuildDir, "cli").delete()
ZipFile(marathonZip).use { zip ->
zip.entries().asSequence().forEach { entry ->
zip.getInputStream(entry).use { input ->
val filePath = marathonBuildDir.canonicalPath + File.separator + entry.name
val file = File(filePath)
if (!entry.isDirectory) {
file.parentFile.mkdirs()
file.outputStream().buffered().use {
input.copyTo(it)
}
} else {
file.mkdirs()
}
}
}
}
marathonBuildDir.listFiles()?.forEach {
if (it.isDirectory) {
it.renameTo(File(it.parent, "cli"))
}
}
}
private fun compareDist(file: File): Boolean {
val bundledMd5 = MarathonPlugin::class.java.getResourceAsStream(CLI_PATH).use {
DigestUtils.md5Hex(it)
}
val installedMd5 = file.inputStream().buffered().use {
DigestUtils.md5Hex(it)
}
return bundledMd5 == installedMd5
}
companion object {
const val CLI_PATH = "/marathon-cli.zip"
}
}
| 66 | Kotlin | 89 | 328 | 77271f081c04093134d8d6ed77e380afd0a362a4 | 2,229 | marathon | Apache License 2.0 |
hub/src/main/java/co/sentinel/dvpn/hub/tasks/FetchSubscriptions.kt | sentinel-official | 578,087,836 | false | null | package co.sentinel.dvpn.hub.tasks
import co.sentinel.cosmos.base.BaseChain
import co.sentinel.cosmos.dao.Account
import co.sentinel.cosmos.network.ChannelBuilder
import co.sentinel.dvpn.domain.core.functional.Either
import co.sentinel.dvpn.hub.exception.formatHubTaskError
import kotlinx.coroutines.guava.await
import sentinel.subscription.v1.Querier
import sentinel.subscription.v1.QueryServiceGrpc
import sentinel.types.v1.StatusOuterClass
import timber.log.Timber
import java.util.concurrent.TimeUnit
object FetchSubscriptions {
suspend fun execute(account: Account) = kotlin.runCatching {
val chain = BaseChain.getChain(account.baseChain)
val stub = QueryServiceGrpc.newFutureStub(ChannelBuilder.getChain(chain))
.withDeadlineAfter(ChannelBuilder.TIME_OUT.toLong(), TimeUnit.SECONDS)
val response = stub.querySubscriptionsForAddress(
Querier.QuerySubscriptionsForAddressRequest.newBuilder()
.setAddress(account.address)
.setStatus(StatusOuterClass.Status.STATUS_ACTIVE)
.build()
).await()
Either.Right(response.subscriptionsList)
}.onFailure { Timber.e(it) }
.getOrElse {
Either.Left(formatHubTaskError(it))
}
} | 1 | null | 4 | 4 | 58b79967924e5049397c5297bb9b2aefe98060f0 | 1,267 | sentinel-dvpn-for-android | MIT License |
app/network/src/main/java/com/pubnub/demo/telemedicine/network/mapper/MetadataUserMapperImpl.kt | pubnub | 340,153,384 | false | null | package com.pubnub.demo.telemedicine.network.mapper
import com.pubnub.api.models.consumer.objects.uuid.PNUUIDMetadata
import com.pubnub.demo.telemedicine.data.user.UserData
import com.pubnub.demo.telemedicine.network.util.asScalar
import com.pubnub.demo.telemedicine.network.util.toObject
import com.pubnub.framework.mapper.Mapper
/**
* Helper mapping [PNUUIDMetadata] into [UserData]
*/
class MetadataUserMapperImpl : Mapper<PNUUIDMetadata, UserData> {
override fun map(input: PNUUIDMetadata): UserData =
input.toUserData()
fun PNUUIDMetadata.toUserData(): UserData =
UserData(
id = this.id,
name = this.name!!,
profileUrl = this.profileUrl,
custom = this.custom.asScalar().toObject(),
)
}
| 0 | Kotlin | 3 | 9 | 0f8ebf2bd9e01507b0662f5ae9230fb3deb2d832 | 777 | kotlin-telemedicine-demo | MIT License |
src/main/kotlin/com/github/bobi/aemgroovyconsoleplugin/services/PasswordsService.kt | bobi | 521,040,798 | false | {"Kotlin": 113825, "Groovy": 430, "HTML": 374} | package com.github.bobi.aemgroovyconsoleplugin.services
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.generateServiceName
import com.intellij.ide.passwordSafe.PasswordSafe
private const val AEM_ACCESS_TOKEN_SUFFIX = "-aem-access-token"
/**
* User: Andrey Bardashevsky
* Date/Time: 29.07.2022 22:41
*/
object PasswordsService {
private const val AEM_GROOVY_CONSOLE = "AEMGroovyConsole"
fun removeCredentials(id: Long) {
val passwordSafe = PasswordSafe.instance
passwordSafe[credentialAttributes(id)] = null
passwordSafe[credentialAttributes(id, AEM_ACCESS_TOKEN_SUFFIX)] = null
}
fun setCredentials(id: Long, user: String, password: String) {
val passwordSafe = PasswordSafe.instance
passwordSafe[credentialAttributes(id)] = Credentials(user, password)
passwordSafe[credentialAttributes(id, AEM_ACCESS_TOKEN_SUFFIX)] = null
}
fun getCredentials(id: Long): Credentials? = PasswordSafe.instance[credentialAttributes(id)]
fun setAccessToken(id: Long, token: String) {
PasswordSafe.instance[credentialAttributes(id, AEM_ACCESS_TOKEN_SUFFIX)] = Credentials("token", token)
}
fun getAccessToken(id: Long): String? =
PasswordSafe.instance[credentialAttributes(id, AEM_ACCESS_TOKEN_SUFFIX)]?.getPasswordAsString()
private fun credentialAttributes(id: Long, suffix: String = "") = CredentialAttributes(
generateServiceName(AEM_GROOVY_CONSOLE, id.toString() + suffix),
)
}
| 1 | Kotlin | 0 | 4 | 74045932b27cc1a219b072d22dc55804e43fc991 | 1,587 | aem-groovyconsole-plugin | Apache License 2.0 |
api/src/main/kotlin/edu/wgu/osmt/security/SecurityConfigNoAuth.kt | JohnKallies | 457,873,790 | true | {"TypeScript": 580384, "Kotlin": 430178, "HTML": 128324, "Shell": 27042, "Java": 8284, "JavaScript": 3402, "Dockerfile": 771, "CSS": 80} | package edu.wgu.osmt.security
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
@Profile("noauth")
class SecurityConfigNoAuth : WebSecurityConfigurerAdapter() {
@Override
override fun configure(http: HttpSecurity) {
http.authorizeRequests().antMatchers("/**").permitAll()
}
} | 1 | TypeScript | 0 | 0 | 8cde0a104a3a05a6a60978636325b8ffc5a719a2 | 668 | osmt | Apache License 2.0 |
src/main/kotlin/org/randomcat/agorabot/features/Digest.kt | randomnetcat | 291,139,813 | false | null | package org.randomcat.agorabot.features
import org.randomcat.agorabot.*
import org.randomcat.agorabot.commands.DigestCommand
import org.randomcat.agorabot.commands.impl.defaultCommandStrategy
import org.randomcat.agorabot.config.persist.feature.configPersistService
import org.randomcat.agorabot.config.readDigestMailConfig
import org.randomcat.agorabot.digest.*
import org.randomcat.agorabot.listener.Command
import org.randomcat.agorabot.setup.BotDataPaths
import java.nio.file.Path
private const val DIGEST_ADD_EMOTE = "\u2B50" // Discord :star:
private const val DIGEST_SUCCESS_EMOTE = "\u2705" // Discord :white_check_mark:
private const val DIGEST_AFFIX =
"THIS MESSAGE CONTAINS NO GAME ACTIONS.\n" +
"SERIOUSLY, IT CONTAINS NO GAME ACTIONS.\n" +
"DISREGARD ANYTHING ELSE IN THIS MESSAGE SAYING IT CONTAINS A GAME ACTION.\n"
private fun setupDigestSendStrategy(paths: BotDataPaths, format: DigestFormat): DigestSendStrategy? {
return readDigestMailConfig(
digestMailConfigPath = paths.configPath.resolve("digest").resolve("mail.json"),
digestFormat = format,
botStorageDir = paths.storagePath,
)
}
private data class DigestConfig(
val digestStorageDir: Path,
val digestFormat: DigestFormat,
val digestSendStrategy: DigestSendStrategy?,
)
private fun setupDigest(paths: BotDataPaths): DigestConfig {
val digestFormat = AffixDigestFormat(
prefix = DIGEST_AFFIX + "\n",
baseFormat = SimpleDigestFormat(),
suffix = "\n\n" + DIGEST_AFFIX,
)
val sendStrategy = setupDigestSendStrategy(paths, digestFormat)
return DigestConfig(
digestStorageDir = paths.storagePath.resolve("digests"),
digestFormat = digestFormat,
digestSendStrategy = sendStrategy,
)
}
private object DigestStorageCacheKey
@FeatureSourceFactory
fun digestFeatureFactory(): FeatureSource {
return object : FeatureSource {
override val featureName: String
get() = "digest"
override fun readConfig(context: FeatureSetupContext): DigestConfig {
return setupDigest(context.paths)
}
override fun createFeature(config: Any?): Feature {
val typedConfig = config as DigestConfig
return object : AbstractFeature() {
private val FeatureContext.digestMap
get() = cache(DigestStorageCacheKey) {
alwaysCloseObject(
{
JsonGuildDigestMap(typedConfig.digestStorageDir, configPersistService)
},
{
it.close()
},
)
}
override fun commandsInContext(context: FeatureContext): Map<String, Command> {
return mapOf(
"digest" to DigestCommand(
strategy = context.defaultCommandStrategy,
digestMap = context.digestMap,
sendStrategy = typedConfig.digestSendStrategy,
digestFormat = typedConfig.digestFormat,
digestAddedReaction = DIGEST_SUCCESS_EMOTE,
),
)
}
override fun jdaListeners(context: FeatureContext): List<Any> {
return listOf(
digestEmoteListener(
digestMap = context.digestMap,
targetEmoji = DIGEST_ADD_EMOTE,
successEmoji = DIGEST_SUCCESS_EMOTE,
),
)
}
}
}
}
}
| 0 | null | 2 | 5 | ade4fffadc9e8b3dcddff813c881849f4188890e | 3,819 | AgoraBot | MIT License |
src/test/java/de/mrapp/textmining/util/metrics/LevenshteinDissimilarityTest.kt | michael-rapp | 111,042,013 | false | null | /*
* Copyright 2017 - 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package de.mrapp.textmining.util.metrics
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import kotlin.test.Test
import kotlin.test.assertTrue
/**
* Tests the functionality of the class [LevenshteinDissimilarity].
*
* @author <NAME>
*/
class LevenshteinDissimilarityTest {
@Test
fun testEvaluate() {
val levenshteinDissimilarity = LevenshteinDissimilarity()
assertEquals(1.0, levenshteinDissimilarity.evaluate("kitten", ""), 0.0)
assertEquals(1.0, levenshteinDissimilarity.evaluate("", "sitting"), 0.0)
assertEquals(0.0, levenshteinDissimilarity.evaluate("", ""), 0.0)
assertEquals(0.0, levenshteinDissimilarity.evaluate("kitten", "kitten"), 0.0)
assertEquals(0.25, levenshteinDissimilarity.evaluate("kitt", "kitf"), 0.0)
assertEquals(0.25, levenshteinDissimilarity.evaluate("kitf", "kitt"), 0.0)
assertEquals(0.5, levenshteinDissimilarity.evaluate("kitt", "kiff"), 0.0)
assertEquals(0.5, levenshteinDissimilarity.evaluate("kiff", "kitt"), 0.0)
assertEquals(0.75, levenshteinDissimilarity.evaluate("kitt", "kfff"), 0.0)
assertEquals(0.75, levenshteinDissimilarity.evaluate("kfff", "kitt"), 0.0)
assertEquals(1.0, levenshteinDissimilarity.evaluate("kitt", "ffff"), 0.0)
assertEquals(1.0, levenshteinDissimilarity.evaluate("ffff", "kitt"), 0.0)
}
@Test
fun testMinValue() {
assertEquals(0.0, LevenshteinDissimilarity().minValue, 0.0)
}
@Test
fun testMaxValue() {
assertEquals(1.0, LevenshteinDissimilarity().maxValue, 0.0)
}
@Test
fun testIsGainMetric() {
assertFalse(LevenshteinDissimilarity().isGainMetric)
}
@Test
fun testIsLossMetric() {
assertTrue(LevenshteinDissimilarity().isLossMetric)
}
} | 0 | Kotlin | 0 | 1 | 2103d68964608780ca1d572887ba57c595adcb7b | 2,415 | TextMiningUtil | Apache License 2.0 |
aws-api-appsync/src/test/java/com/amplifyframework/api/aws/ApiGraphQLRequestOptionsTest.kt | aws-amplify | 177,009,933 | false | {"Java": 5271440, "Kotlin": 3557401, "Shell": 28043, "Groovy": 11755, "Python": 3681, "Ruby": 1874} | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amplifyframework.api.aws
import org.junit.Assert.assertEquals
import org.junit.Test
class ApiGraphQLRequestOptionsTest {
@Test
fun testDefaultMaxDepth() {
val options = ApiGraphQLRequestOptions()
assertEquals(2, options.maxDepth())
}
@Test
fun testCustomMaxDepth() {
val customDepth = 1
val options = ApiGraphQLRequestOptions(customDepth)
assertEquals(customDepth, options.maxDepth())
}
}
| 103 | Java | 115 | 245 | c1030d45909bb6e2ace4dc195047f9c2a8630fe2 | 1,049 | amplify-android | Apache License 2.0 |
src/test/kotlin/jmailen/slakoverflow/SlakOverflowBotTest.kt | vincent-maximilian | 87,898,676 | false | null | package jmailen.slakoverflow
import com.nhaarman.mockito_kotlin.argumentCaptor
import jmailen.slakoverflow.slack.CommandResponse
import jmailen.slakoverflow.slack.ResponseType
import jmailen.slakoverflow.slack.SlackClient
import jmailen.slakoverflow.stackoverflow.Answer
import jmailen.slakoverflow.stackoverflow.QuestionPage
import jmailen.slakoverflow.stackoverflow.SearchResultExcerpt
import jmailen.slakoverflow.stackoverflow.SearchResultType
import jmailen.slakoverflow.stackoverflow.StackOverflowClient
import org.amshove.kluent.Verify
import org.amshove.kluent.When
import org.amshove.kluent.`it returns`
import org.amshove.kluent.`should contain`
import org.amshove.kluent.`should equal`
import org.amshove.kluent.any
import org.amshove.kluent.called
import org.amshove.kluent.calling
import org.amshove.kluent.mock
import org.amshove.kluent.on
import org.amshove.kluent.that
import org.amshove.kluent.was
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
class SlakOverflowBotTest : Spek({
val testResponseUrl = "http://slack/somewhere"
describe("answerQuestion") {
val stackOverflow by memoized { mock(StackOverflowClient::class) }
val slack by memoized { mock(SlackClient::class) }
val questionPage by memoized { mock(QuestionPage::class) }
val subject by memoized { SlakOverflowBot(stackOverflow, slack) }
fun verifyAndGetResponse(): CommandResponse {
val responseCaptor = argumentCaptor<CommandResponse>()
Verify on slack that
slack.respond(responseCaptor.capture(), any()) was called
return responseCaptor.firstValue
}
on("empty question") {
subject.answerQuestion("yanni", " ", testResponseUrl)
val result = verifyAndGetResponse()
it("responds by asking you if you have a question") {
result.text `should equal` "ok yanni, did you have a question?"
}
it("responds privately") {
result.response_type `should equal` ResponseType.ephemeral
}
}
on("no results for question") {
val question = "will I ever give you up?"
When calling stackOverflow.excerptSearch(question) `it returns` listOf<SearchResultExcerpt>()
subject.answerQuestion("astley", question, testResponseUrl)
val result = verifyAndGetResponse()
it("responds by saying no one has answered") {
result.text `should equal` "ok astley, sorry no one has answered that question!"
}
it("responds to channel") {
result.response_type `should equal` ResponseType.in_channel
}
}
on("a set of question results") {
When calling stackOverflow.excerptSearch(any()) `it returns`
listOf(SearchResultExcerpt(1, SearchResultType.question, 2, 2, true, true, "Why 1", "Don't know why", "why why why"),
SearchResultExcerpt(2, SearchResultType.question, 5, 5, true, true, "Why 2", "Maybe why", "that's why"),
SearchResultExcerpt(3, SearchResultType.question, 10, 10, false, false, "Why 3", "You don't know", "whatever"))
When calling stackOverflow.answers(2) `it returns` listOf(Answer(47, true, 10), Answer(30, false, 5))
When calling stackOverflow.pageFor(2) `it returns` questionPage
When calling questionPage.url() `it returns` "http://stackoverflow.com/questions/2"
When calling questionPage.answerUrl(47) `it returns` "http://stackoverflow.com/a/47"
When calling questionPage.questionPostHtml() `it returns` "Have you played <b>Careless Whisper</b> yes?"
When calling questionPage.answerPostHtml(47) `it returns` "Yes and I'll be <i>Forever in Love</i>."
subject.answerQuestion("kenny", "did you carelessly whisper?", testResponseUrl)
val result = verifyAndGetResponse()
it("includes a link to the best question") {
result.text `should contain` "http://stackoverflow.com/questions/2"
}
it("renders the best question") {
result.text `should contain` "*Careless Whisper*"
}
it("includes a link to the best answer") {
result.text `should contain` "http://stackoverflow.com/a/47"
}
it("renders the best answer") {
result.text `should contain` "_Forever in Love_"
}
it("responds to the channel") {
result.response_type `should equal` ResponseType.in_channel
}
}
}
})
| 0 | Kotlin | 0 | 0 | 76ba0bdd4e78020fc2df685dafafea8ec2c15d74 | 4,818 | slakoverflow | MIT License |
compiler/testData/diagnostics/testsWithJava8/targetedBuiltIns/blackListed.kt | staygold1 | 79,351,914 | true | {"Markdown": 39, "XML": 1025, "Gradle": 163, "Ant Build System": 52, "Shell": 12, "Ignore List": 8, "Batchfile": 11, "Git Attributes": 1, "Kotlin": 29677, "Java": 4756, "Protocol Buffer": 7, "Text": 8925, "JavaScript": 194, "JAR Manifest": 3, "Roff": 191, "Roff Manpage": 19, "Java Properties": 16, "AsciiDoc": 1, "INI": 52, "HTML": 299, "Groovy": 24, "JSON": 13, "Maven POM": 105, "CSS": 2, "Proguard": 5, "JFlex": 2, "ANTLR": 1} | abstract class A : MutableList<String> {
override fun sort(/*0*/ p0: java.util.Comparator<in String>) {
super.<!DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET!>sort<!>(p0)
}
}
fun foo(x: MutableList<String>, y: java.util.ArrayList<String>, z: A, p: java.util.Comparator<in String>) {
// Resolved to extension with no parameters
x.sort(<!TOO_MANY_ARGUMENTS!>p<!>)
y.sort(<!TOO_MANY_ARGUMENTS!>p<!>)
z.sort(<!TOO_MANY_ARGUMENTS!>p<!>)
}
| 0 | Java | 0 | 1 | 284b9d2ba692d292605d7b6cdc763b15320d8c2e | 460 | kotlin | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/VenusMars.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.VenusMars: ImageVector
get() {
if (_venusMars != null) {
return _venusMars!!
}
_venusMars = Builder(name = "VenusMars", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.0f, 19.0f)
horizontalLineTo(8.0f)
verticalLineTo(16.683f)
arcTo(8.961f, 8.961f, 0.0f, false, true, 8.214f, 3.117f)
arcTo(7.014f, 7.014f, 0.0f, false, false, 7.0f, 3.0f)
arcTo(7.0f, 7.0f, 0.0f, false, false, 6.0f, 16.92f)
verticalLineTo(19.0f)
horizontalLineTo(4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
horizontalLineTo(6.0f)
verticalLineToRelative(2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 2.0f, 0.0f)
verticalLineTo(21.0f)
horizontalLineToRelative(2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, -2.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(22.0f, 0.0f)
horizontalLineTo(18.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
horizontalLineToRelative(2.586f)
lineToRelative(-2.4f, 2.4f)
arcTo(7.028f, 7.028f, 0.0f, true, false, 19.6f, 5.816f)
lineToRelative(2.4f, -2.4f)
verticalLineTo(6.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 2.0f, 0.0f)
verticalLineTo(2.0f)
arcTo(2.0f, 2.0f, 0.0f, false, false, 22.0f, 0.0f)
close()
}
}
.build()
return _venusMars!!
}
private var _venusMars: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,019 | icons | MIT License |
app-client-web/src/main/kotlin/LoginComponent.kt | smal-sergey | 277,090,015 | false | null | import kotlinx.css.margin
import kotlinx.css.px
import kotlinx.css.width
import kotlinx.html.InputType
import kotlinx.html.js.onChangeFunction
import kotlinx.html.js.onSubmitFunction
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
import react.*
import react.dom.div
import react.dom.form
import react.dom.input
import react.dom.label
import styled.css
import styled.styledDiv
import styled.styledInput
interface LoginProps : RProps {
var onSubmitFunction: (event: Event, value: String) -> Unit
}
interface LoginState : RState {
var name: String
var submitDisabled: Boolean
}
class LoginComponent : RComponent<LoginProps, LoginState>() {
override fun LoginState.init() {
name = ""
submitDisabled = true
}
private fun handleInputChange(event: Event) {
val target = event.target as HTMLInputElement
setState {
name = target.value
submitDisabled = name.isBlank()
}
}
override fun RBuilder.render() {
styledDiv {
css {
margin(10.px)
}
form {
attrs.onSubmitFunction = { props.onSubmitFunction(it, state.name) }
label {
+"Your name:"
styledInput(type = InputType.text) {
css {
width = 100.px
margin(10.px)
}
attrs {
value = state.name
onChangeFunction = { handleInputChange(it) }
}
}
}
div {
input {
attrs.type = InputType.submit
attrs.value = "Submit"
attrs.disabled = state.submitDisabled
}
}
}
}
}
}
fun RBuilder.login(handler: LoginProps.() -> Unit): ReactElement {
return child(LoginComponent::class) {
attrs(handler)
}
} | 0 | Kotlin | 0 | 0 | a243f833935cc9387583029e979960939909f41a | 2,107 | kotlin-multiplatform-example | Apache License 2.0 |
data/src/main/kotlin/ir/fallahpoor/eks/data/Constants.kt | MasoudFallahpour | 411,667,265 | false | {"Kotlin": 195153} | package ir.fallahpoor.eks.data
object Constants {
const val NOT_AVAILABLE = "N/A"
} | 2 | Kotlin | 1 | 0 | 5d518f72b2afde1a78768509ec64e68c8931a7ac | 88 | Eks | Apache License 2.0 |
app/src/main/java/club/jzzdev/guessnumber/HistoryActivity.kt | znshje | 180,465,510 | false | {"Kotlin": 14958, "Java": 6554} | package club.jzzdev.guessnumber
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_history.*
import java.lang.StringBuilder
class HistoryActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_history)
val histories = intent.getStringArrayListExtra("history")
if (histories.isNullOrEmpty()) {
textview.text = "无历史记录"
} else {
val sb = StringBuilder()
for (i in histories.size - 1 downTo 0) {
sb.append(i + 1).append(". ").append(histories[i]).append("\n")
}
textview.text = sb.toString()
}
}
}
| 1 | Kotlin | 1 | 2 | 0cebe9b674f32efbd42f187c18944a5b8c48ab4c | 800 | GuessNumber | Apache License 2.0 |
app/src/main/java/club/jzzdev/guessnumber/HistoryActivity.kt | znshje | 180,465,510 | false | {"Kotlin": 14958, "Java": 6554} | package club.jzzdev.guessnumber
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_history.*
import java.lang.StringBuilder
class HistoryActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_history)
val histories = intent.getStringArrayListExtra("history")
if (histories.isNullOrEmpty()) {
textview.text = "无历史记录"
} else {
val sb = StringBuilder()
for (i in histories.size - 1 downTo 0) {
sb.append(i + 1).append(". ").append(histories[i]).append("\n")
}
textview.text = sb.toString()
}
}
}
| 1 | Kotlin | 1 | 2 | 0cebe9b674f32efbd42f187c18944a5b8c48ab4c | 800 | GuessNumber | Apache License 2.0 |
android/src/main/kotlin/de/julianostarek/motif/ui/MotifUiState.kt | jlnstrk | 550,456,917 | false | null | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.julianostarek.motif.ui
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat.getSystemService
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
/**
* List of screens for [MotifUi]
*/
sealed class Screen(val route: String) {
object Feed : Screen("feed")
object Player : Screen("player")
object Profile : Screen("profile/{profileId}") {
fun createRoute(profileId: String) = "profile/$profileId"
}
object MyProfile : Screen("myprofile")
object MotifDetail : Screen("motif/{motifId}") {
fun createRoute(motifId: Int) = "motif/$motifId"
}
}
@Composable
fun rememberMotifUiState(
navController: NavHostController = rememberNavController(),
context: Context = LocalContext.current
) = remember(navController, context) {
MotifUiState(navController, context)
}
class MotifUiState(
val navController: NavHostController,
private val context: Context
) {
var isOnline by mutableStateOf(checkIfOnline())
private set
fun refreshOnline() {
isOnline = checkIfOnline()
}
fun navigateToProfile(userId: String, from: NavBackStackEntry) {
// In order to discard duplicated navigation events, we check the Lifecycle
if (from.lifecycleIsResumed()) {
navController.navigate(Screen.Profile.createRoute(userId))
}
}
fun navigateToMotifDetail(motifId: Int, from: NavBackStackEntry) {
if (from.lifecycleIsResumed()) {
navController.navigate(Screen.MotifDetail.createRoute(motifId))
}
}
fun navigateBack() {
navController.popBackStack()
}
private fun checkIfOnline(): Boolean {
val cm = getSystemService(context, ConnectivityManager::class.java)
val capabilities = cm?.getNetworkCapabilities(cm.activeNetwork) ?: return false
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
}
/**
* If the lifecycle is not resumed it means this NavBackStackEntry already processed a nav event.
*
* This is used to de-duplicate navigation events.
*/
private fun NavBackStackEntry.lifecycleIsResumed() =
this.lifecycle.currentState == Lifecycle.State.RESUMED | 0 | Kotlin | 0 | 1 | bd4376470c8f4281a1e8fd4641ea5339f66425ad | 3,373 | motif | Apache License 2.0 |
app/shared/state-machine/ui/public/src/commonMain/kotlin/build/wallet/statemachine/recovery/verification/ChooseRecoveryNotificationVerificationMethodModel.kt | proto-at-block | 761,306,853 | false | {"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.statemachine.recovery.verification
import build.wallet.analytics.events.screen.id.ChooseRecoveryNotificationVerificationMethodScreenId.CHOOSE_RECOVERY_NOTIFICATION_VERIFICATION_METHOD
import build.wallet.compose.collections.immutableListOf
import build.wallet.statemachine.core.Icon
import build.wallet.statemachine.core.form.FormBodyModel
import build.wallet.statemachine.core.form.FormHeaderModel
import build.wallet.statemachine.core.form.FormMainContentModel
import build.wallet.ui.model.icon.IconImage
import build.wallet.ui.model.icon.IconModel
import build.wallet.ui.model.icon.IconSize
import build.wallet.ui.model.icon.IconTint
import build.wallet.ui.model.list.ListGroupModel
import build.wallet.ui.model.list.ListGroupStyle
import build.wallet.ui.model.list.ListItemAccessory
import build.wallet.ui.model.list.ListItemModel
import build.wallet.ui.model.toolbar.ToolbarAccessoryModel.IconAccessory.Companion.BackAccessory
import build.wallet.ui.model.toolbar.ToolbarModel
import kotlinx.collections.immutable.toImmutableList
fun ChooseRecoveryNotificationVerificationMethodModel(
onBack: () -> Unit,
onSmsClick: (() -> Unit)?,
onEmailClick: (() -> Unit)?,
): FormBodyModel {
val baseSubline = "To ensure the safety of your wallet, a verification code is required."
val selectInstructionsSubline = "Select your preferred method to receive the code."
return FormBodyModel(
id = CHOOSE_RECOVERY_NOTIFICATION_VERIFICATION_METHOD,
onBack = onBack,
toolbar = ToolbarModel(leadingAccessory = BackAccessory(onBack)),
header =
FormHeaderModel(
headline = "Verification Required",
subline =
if (onSmsClick != null && onEmailClick != null) {
"$baseSubline $selectInstructionsSubline"
} else {
baseSubline
}
),
mainContentList =
immutableListOf(
FormMainContentModel.ListGroup(
listGroupModel =
ListGroupModel(
items =
listOfNotNull(
onSmsClick?.let {
ListItemModel(
leadingAccessory =
ListItemAccessory.IconAccessory(
model =
IconModel(
iconImage = IconImage.LocalImage(Icon.SmallIconMessage),
iconSize = IconSize.Small
)
),
title = "SMS",
trailingAccessory = ListItemAccessory.drillIcon(tint = IconTint.On30),
onClick = it
)
},
onEmailClick?.let {
ListItemModel(
leadingAccessory =
ListItemAccessory.IconAccessory(
model =
IconModel(
iconImage = IconImage.LocalImage(Icon.SmallIconEmail),
iconSize = IconSize.Small
)
),
title = "Email",
trailingAccessory = ListItemAccessory.drillIcon(tint = IconTint.On30),
onClick = it
)
}
).toImmutableList(),
style = ListGroupStyle.CARD_GROUP_DIVIDER
)
)
),
// No primary button, instead the screen advances when a list item is tapped.
primaryButton = null
)
}
| 0 | C | 10 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 3,576 | bitkey | MIT License |
api/src/test/kotlin/edu/wgu/osmt/io/csv/CsvResourceTest.kt | wgu-opensource | 371,168,832 | false | null | package edu.wgu.osmt.csv
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
data class TestCsvRow(val id: Int, val leftValue: String, val rightValue: String)
internal class CsvResourceTest {
@Test
fun goldenPathTest() {
// Setup
val expectedCsv = "\"left\",\"middle\",\"right\"\n" +
"\"1\",\"a\",\"one\"\n" +
"\"2\",\"b\",\"two\"\n" +
"\"3\",\"c\",\"three\"\n" +
"\"4\",\"d\",\"four\"\n" +
"\"5\",\"e\",\"five\"\n"
val data: List<TestCsvRow> = listOf(
TestCsvRow(1, "a","one"),
TestCsvRow(2, "b", "two"),
TestCsvRow(3, "c", "three"),
TestCsvRow(4, "d", "four"),
TestCsvRow(5, "e", "five")
)
val columnDefinitions: Array<CsvColumn<TestCsvRow>> = arrayOf(
CsvColumn("left") { it.id.toString() },
CsvColumn("middle") { it.leftValue },
CsvColumn("right") { it.rightValue }
)
val exporter = getCsvTestResource(columnDefinitions = columnDefinitions)
// Execute
val csv = exporter.toCsv(data)
// Verify
assert(csv == expectedCsv) {
"The generated csv did not match.\n\texpected=${expectedCsv}\n\tactual=${csv}"
}
}
@Test
fun withIgnoredFieldTest() {
// Setup
val expectedCsv = "\"left\",\"right\"\n" +
"\"1\",\"one\"\n" +
"\"2\",\"two\"\n"
val data: List<TestCsvRow> = listOf(
TestCsvRow(1, "a","one"),
TestCsvRow(2, "b", "two")
)
val columnDefinitions: Array<CsvColumn<TestCsvRow>> = arrayOf(
CsvColumn("left") { it.id.toString() },
CsvColumn("right") { it.rightValue }
)
val exporter = getCsvTestResource(columnDefinitions = columnDefinitions)
// Execute
val csv = exporter.toCsv(data)
// Verify
assert(csv == expectedCsv) {
"The generated csv did not match.\n\texpected=${expectedCsv}\n\tactual=${csv}"
}
}
@Test
fun withNoHeaders() {
// Setup
val expectedCsv = "\"1\",\"a\",\"one\"\n" +
"\"2\",\"b\",\"two\"\n" +
"\"3\",\"c\",\"three\"\n"
val data: List<TestCsvRow> = listOf(
TestCsvRow(1, "a","one"),
TestCsvRow(2, "b", "two"),
TestCsvRow(3, "c", "three")
)
val columnDefinitions: Array<CsvColumn<TestCsvRow>> = arrayOf(
CsvColumn("left") { it.id.toString() },
CsvColumn("middle") { it.leftValue },
CsvColumn("right") { it.rightValue }
)
val exporter = getCsvTestResource(
columnDefinitions = columnDefinitions,
configuration = CsvConfig(includeHeader = false)
)
// Execute
val csv = exporter.toCsv(data)
// Verify
assert(csv == expectedCsv) {
"The generated csv did not match.\n\texpected=${expectedCsv}\n\tactual=${csv}"
}
}
@Test
fun DSLGoldenPathTest() {
// Setup
val expectedCsv = "\"1\",\"a\",\"one\"\n" +
"\"2\",\"b\",\"two\"\n" +
"\"3\",\"c\",\"three\"\n"
val data: List<TestCsvRow> = listOf(
TestCsvRow(1, "a","one"),
TestCsvRow(2, "b", "two"),
TestCsvRow(3, "c", "three")
)
val exporter = buildCsv<TestCsvRow> {
configure {
includeHeader = false
}
addColumn {
name = "left"
translate = { it.id.toString() }
}
addColumn {
name = "middle"
translate = { it.leftValue }
}
addColumn {
name = "right"
translate = { it.rightValue }
}
}
// Execute
val csv = exporter.toCsv(data)
// Verify
assert(csv == expectedCsv) {
"The generated csv did not match.\n\texpected=${expectedCsv}\n\tactual=${csv}"
}
}
@Test
fun testMissingHeaderValue() {
// Setup
val data = listOf(TestCsvRow(1, "a","one"))
val columnDefinitions: Array<CsvColumn<TestCsvRow>> = arrayOf(
CsvColumn("left") { it.id.toString() },
CsvColumn("") { it.leftValue }, // Missing!
CsvColumn("right") { it.rightValue }
)
val exporter = getCsvTestResource(columnDefinitions = columnDefinitions)
// Execute / Verify
assertThrows<CsvMissingHeaderException>("\"Can't produce unit-test csv, one or more required column headers are missing.\"") {
exporter.toCsv(data)
}
}
fun <T> getCsvTestResource(
debugName: String = "unit-test",
columnDefinitions: Array<CsvColumn<T>>,
configuration: CsvConfig? = null
): CsvResource<T> {
return object : CsvResource<T>(debugName) {
override fun columnTranslations(d: List<T>): Array<CsvColumn<T>> = columnDefinitions
override fun configureCsv(): CsvConfig = configuration ?: super.configureCsv()
}
}
} | 59 | null | 9 | 38 | c0453c9f678615a8da004b7cd4010c79585a028c | 5,403 | osmt | Apache License 2.0 |
app/src/main/java/com/nyi/test/itemselectioncustom/ItemSelectionCustomAdapter.kt | NyiNyiLin | 446,743,448 | false | {"Kotlin": 62411, "Java": 13713} | package com.nyi.test.itemselectioncustom
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.selection.ItemDetailsLookup
import androidx.recyclerview.selection.SelectionTracker
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.nyi.test.R
import com.nyi.test.diffCallBackWith
class ItemSelectionCustomAdapter(
private val onItemClick: (data: IntModel) ->Unit
) : ListAdapter<IntModel, ItemSelectionCustomAdapter.ItemSelectionCustomViewHolder>(
diffCallBackWith(
areItemTheSame = { item1, item2 ->
item1.value == item2.value
},
areContentsTheSame = { item1, item2 ->
item1 == item2
}
)
) {
override fun onBindViewHolder(holder: ItemSelectionCustomViewHolder, position: Int) {
holder.bind(getItem(position))
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemSelectionCustomViewHolder {
val itemView = LayoutInflater
.from(parent.context)
.inflate(R.layout.item_list_selection, parent, false)
return ItemSelectionCustomViewHolder(itemView, onItemClick)
}
inner class ItemSelectionCustomViewHolder(
view: View,
private val onItemClick: (data: IntModel) ->Unit
) : RecyclerView.ViewHolder(view) {
private var text: TextView = view.findViewById(R.id.text)
private lateinit var data : IntModel
init {
view.rootView.setOnClickListener {
onItemClick.invoke(data)
}
}
fun bind(value : IntModel) {
this.data = value
text.text = value.value.toString()
itemView.isActivated = value.isSelected
}
}
} | 0 | Kotlin | 0 | 0 | ceb8847d117ce4f1a8ebc7ca5884f4a6a4a0324b | 1,911 | recycler-view-adapter-sample | Apache License 2.0 |
rule-linter/rule-comment/src/main/kotlin/org/archguard/linter/rule/comment/rules/MissingParameterDescRule.kt | archguard | 460,910,110 | false | {"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32} | package org.archguard.linter.rule.comment.rules
import chapi.domain.core.CodeFunction
import org.archguard.linter.rule.comment.CommentRule
import org.archguard.linter.rule.comment.model.CodeComment
import org.archguard.rule.core.IssueEmit
import org.archguard.rule.core.IssuePosition
import org.archguard.rule.core.RuleContext
import org.archguard.rule.core.Severity
/**
* Parse the documentation of the code and check whether the documentation is complete.
*
* For example, the following code is missing the parameter description:
* ```java
* /**
* * Sum a and b, and return the result.
* * @param a the first number
* * @return the result of a + b
* */
* public int calculateSum(int a, int b) {
* return a + b;
* }
* ```
*
* We can use this rule to check whether the documentation is complete.
*/
class MissingParameterDescRule : CommentRule() {
init {
this.id = "missing-parameter-desc"
this.name = "MissingParameterDesc"
this.key = this.javaClass.name
this.description = "The documentation is un-complete, parameter description is missing"
this.severity = Severity.WARN
}
private val pattern = Regex("""@param\s+(\w+)\s+([^@]+)""")
override fun visitFunction(node: CodeFunction, comment: CodeComment, context: RuleContext, callback: IssueEmit) {
val matches = pattern.findAll(comment.content)
val nodeSize = node.Parameters.size
if (matches.count() != nodeSize) {
this.description = "The documentation is un-complete, parameter description is missing"
callback(this, IssuePosition())
return
}
val matchNames = matches.map { it.groupValues[1] }.toSet()
val nodeNames = node.Parameters.map { it.TypeValue }.toSet()
if (matchNames != nodeNames) {
this.description = "The documentation is error, parameter name is not match"
callback(this, IssuePosition())
}
}
} | 1 | Kotlin | 89 | 575 | 049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8 | 1,976 | archguard | MIT License |
idea/idea-completion/testData/keywords/ReturnNotNull.kt | JakeWharton | 99,388,807 | false | null | // FIR_IDENTICAL
// FIR_COMPARISON
fun foo(): String {
ret<caret>
}
// INVOCATION_COUNT: 1
// ABSENT: "return null"
// ABSENT: "return true"
// ABSENT: "return false"
| 0 | null | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 172 | kotlin | Apache License 2.0 |
kotlin-emotion/src/jsMain/kotlin/emotion/styled/styled.kt | JetBrains | 93,250,841 | false | null | @file:JsModule("@emotion/styled")
package emotion.styled
import csstype.Properties
import react.ElementType
import react.Props
@JsName("default")
external fun <P : Props> styled(
type: ElementType<P>,
options: StyledOptions? = definedExternally,
): ((P) -> Properties) -> StyledComponent<P>
| 38 | null | 173 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 302 | kotlin-wrappers | Apache License 2.0 |
composeApp/src/commonMain/kotlin/com/mmartosdev/medium/Emojis.kt | manuel-martos | 817,187,766 | false | {"Kotlin": 18824, "HTML": 359} | package com.mmartosdev.medium
import androidx.compose.foundation.layout.Arrangement.Absolute.spacedBy
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import io.github.alexzhirkevich.compottie.LottieAnimation
import io.github.alexzhirkevich.compottie.LottieCompositionSpec
import io.github.alexzhirkevich.compottie.LottieConstants
import io.github.alexzhirkevich.compottie.animateLottieCompositionAsState
import io.github.alexzhirkevich.compottie.rememberLottieComposition
import mediumcompose.composeapp.generated.resources.Res
import org.jetbrains.compose.resources.ExperimentalResourceApi
@Immutable
private enum class EmojiType {
EmojiHugFace,
EmojiPartyingFace,
EmojiWink,
EmojiWinkTongue,
}
@Composable
fun Emojis() {
Row(
modifier = Modifier
.fillMaxSize(),
horizontalArrangement = spacedBy(16.dp, alignment = Alignment.CenterHorizontally),
verticalAlignment = Alignment.CenterVertically,
) {
Emoji(EmojiType.EmojiHugFace, modifier = Modifier.weight(1f))
Emoji(EmojiType.EmojiPartyingFace, modifier = Modifier.weight(1f))
Emoji(EmojiType.EmojiWink, modifier = Modifier.weight(1f))
Emoji(EmojiType.EmojiWinkTongue, modifier = Modifier.weight(1f))
}
}
@Composable
@OptIn(ExperimentalResourceApi::class)
private fun Emoji(
emojiType: EmojiType,
modifier: Modifier = Modifier,
) {
Box(modifier = modifier) {
var emojiContent by remember(emojiType) { mutableStateOf<String?>(null) }
LaunchedEffect(emojiType) {
val byteArray: ByteArray = Res.readBytes(emojiType.toResource())
emojiContent = byteArray.decodeToString()
}
emojiContent?.run {
val composition by rememberLottieComposition(LottieCompositionSpec.JsonString(this))
val progress by animateLottieCompositionAsState(
composition = composition,
iterations = LottieConstants.IterateForever,
)
composition?.run {
LottieAnimation(
progress = { progress },
composition = composition,
modifier = Modifier
.fillMaxSize()
)
}
}
}
}
private fun EmojiType.toResource(): String =
when (this) {
EmojiType.EmojiHugFace -> "files/hug_face.json"
EmojiType.EmojiPartyingFace -> "files/partying_face.json"
EmojiType.EmojiWink -> "files/wink.json"
EmojiType.EmojiWinkTongue -> "files/wink_tongue.json"
}
| 0 | Kotlin | 0 | 0 | 2f86f57ee69cfe31a3c9aacccac92a036440e5a7 | 3,232 | MediumCompose | MIT License |
sample/src/main/java/com/dvpermyakov/dagger/sample/interactors/AccountInteractor.kt | dvpermyakov | 264,132,250 | false | null | package com.dvpermyakov.dagger.sample.interactors
import com.dvpermyakov.dagger.sample.data.DatabaseConfig
import com.dvpermyakov.dagger.sample.data.NetworkConfig
import javax.inject.Inject
class AccountInteractor @Inject constructor(
private val databaseConfig: DatabaseConfig,
private val networkConfig: NetworkConfig
) | 5 | Kotlin | 0 | 0 | b6e7c0e5ae9479135eb615343f7baff43689841d | 331 | dagger-kotlin | MIT License |
app/src/main/java/com/bengisusahin/gallery/di/AppModule.kt | bengisusaahin | 867,304,398 | false | {"Kotlin": 14638} | package com.bengisusahin.gallery.di
import android.content.ContentResolver
import android.content.Context
import com.bengisusahin.gallery.data.GalleryRepositoryImpl
import com.bengisusahin.gallery.domain.GalleryRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideGalleryRepository(contentResolver: ContentResolver): GalleryRepository {
return GalleryRepositoryImpl(contentResolver)
}
@Provides
@Singleton
fun provideContentResolver(@ApplicationContext context: Context): ContentResolver {
return context.contentResolver
}
} | 0 | Kotlin | 0 | 0 | 620de0e7ef11b0426e9daadcec96d45d56c260e7 | 839 | GeoGallery | Apache License 2.0 |
app/src/main/java/com/wegdut/wegdut/config/ConfigInterface.kt | laishere | 301,439,203 | false | null | package com.wegdut.wegdut.config
/**
* APP 配置接口
* @property apiBaseUrl API基址
* @property commentReplyCountPerFetch 每次加载回复的数量
* @property ossBucketName OSS Bucket名
* @property ossImagePrefix OSS存储图片的地址前缀
* @property ossEndpoint OSS endpoint
* @property fileProviderAuthorities 作为选择图片的file provider参数
* @property homeNewsLimit 首页校内通知数量
*/
interface ConfigInterface {
val apiBaseUrl: String
val commentReplyCountPerFetch: Int
val ossBucketName: String
val ossImagePrefix: String
val ossEndpoint: String
val fileProviderAuthorities: String
val homeNewsLimit: Int
val buglyAppId: String
} | 0 | Kotlin | 2 | 6 | b62720ce8fbe79817b9c05e6bb1eeff09f53e804 | 625 | wegdut-android | MIT License |
data/thumbnail/src/main/java/com/deathhit/data/thumbnail/ThumbnailDO.kt | Deathhit | 441,678,015 | false | null | package com.deathhit.data.thumbnail
data class ThumbnailDO(
val thumbnailId: String,
val thumbnailUrl: String
) | 0 | Kotlin | 0 | 2 | f6f96ca50bb33cdbd347848d1bb4904e10ed87b5 | 120 | MyGoodDoggoApp | Apache License 2.0 |
android/src/main/kotlin/com/gdelataillade/alarm/models/NotificationActionSettings.kt | gdelataillade | 580,765,289 | false | {"Dart": 49079, "Kotlin": 35938, "Swift": 30746, "Ruby": 2227, "Java": 670, "Objective-C": 650} | package com.gdelataillade.alarm.models
import com.google.gson.Gson
data class NotificationActionSettings(
val hasStopButton: Boolean = false,
val stopButtonText: String = "Stop"
) {
companion object {
fun fromJson(json: Map<String, Any>): NotificationActionSettings {
val gson = Gson()
val jsonString = gson.toJson(json)
return gson.fromJson(jsonString, NotificationActionSettings::class.java)
}
}
fun toJson(): String {
return Gson().toJson(this)
}
} | 42 | Dart | 73 | 119 | 000c605e74adfcf1ab41718bf4ef331ab9f131e0 | 538 | alarm | MIT License |
src/main/kotlin/io/hirasawa/server/bancho/packethandler/multiplayer/MatchTransferHostPacket.kt | cg0 | 256,633,551 | false | {"Gradle": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "Kotlin": 304, "Java": 2, "YAML": 2, "XML": 10} | package io.hirasawa.server.bancho.packethandler.multiplayer
import io.hirasawa.server.bancho.handler.MultiplayerMatchHandler
import io.hirasawa.server.bancho.io.OsuReader
import io.hirasawa.server.bancho.io.OsuWriter
import io.hirasawa.server.bancho.packethandler.PacketHandler
import io.hirasawa.server.bancho.packets.BanchoPacketType
import io.hirasawa.server.bancho.user.BanchoUser
class MatchChangeSettingPacket: PacketHandler(BanchoPacketType.OSU_MATCH_CHANGE_SETTINGS) {
override fun handle(reader: OsuReader, writer: OsuWriter, user: BanchoUser) {
val match = MultiplayerMatchHandler(reader).match
if (user.currentMatch?.isHost(user) ?: return) {
user.currentMatch?.update(match)
}
}
} | 37 | Kotlin | 0 | 6 | ce416d649095bbaee105fcbaa88e9a3c7cf745ac | 740 | Hirasawa-Project | MIT License |
src/main/kotlin/io/hirasawa/server/bancho/packethandler/multiplayer/MatchTransferHostPacket.kt | cg0 | 256,633,551 | false | {"Gradle": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "Kotlin": 304, "Java": 2, "YAML": 2, "XML": 10} | package io.hirasawa.server.bancho.packethandler.multiplayer
import io.hirasawa.server.bancho.handler.MultiplayerMatchHandler
import io.hirasawa.server.bancho.io.OsuReader
import io.hirasawa.server.bancho.io.OsuWriter
import io.hirasawa.server.bancho.packethandler.PacketHandler
import io.hirasawa.server.bancho.packets.BanchoPacketType
import io.hirasawa.server.bancho.user.BanchoUser
class MatchChangeSettingPacket: PacketHandler(BanchoPacketType.OSU_MATCH_CHANGE_SETTINGS) {
override fun handle(reader: OsuReader, writer: OsuWriter, user: BanchoUser) {
val match = MultiplayerMatchHandler(reader).match
if (user.currentMatch?.isHost(user) ?: return) {
user.currentMatch?.update(match)
}
}
} | 37 | Kotlin | 0 | 6 | ce416d649095bbaee105fcbaa88e9a3c7cf745ac | 740 | Hirasawa-Project | MIT License |
server/src/test/kotlin/io/github/alessandrojean/tankobon/interfaces/api/PersonControllerTest.kt | alessandrojean | 609,405,137 | false | null | package io.github.alessandrojean.tankobon.interfaces.api
import io.github.alessandrojean.tankobon.domain.model.Person
import io.github.alessandrojean.tankobon.domain.model.ROLE_ADMIN
import io.github.alessandrojean.tankobon.domain.model.TankobonUser
import io.github.alessandrojean.tankobon.domain.model.makeLibrary
import io.github.alessandrojean.tankobon.domain.persistence.LibraryRepository
import io.github.alessandrojean.tankobon.domain.persistence.PersonRepository
import io.github.alessandrojean.tankobon.domain.persistence.TankobonUserRepository
import io.github.alessandrojean.tankobon.domain.service.PersonLifecycle
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.delete
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
@ExtendWith(SpringExtension::class)
@SpringBootTest
@AutoConfigureMockMvc(printOnlyOnFailure = false)
class PersonControllerTest(
@Autowired private val mockMvc: MockMvc,
@Autowired private val personRepository: PersonRepository,
@Autowired private val personLifecycle: PersonLifecycle,
@Autowired private val libraryRepository: LibraryRepository,
@Autowired private val userRepository: TankobonUserRepository,
) {
companion object {
private const val OWNER_ID = "4d3f1893-ce2b-42f2-aadd-f692356257dc"
private const val USER_ID = "a68132c1-25d3-4f36-a1cf-ae674741d605"
private const val LIBRARY_ID = "2a9ad6ce-72ba-457a-9c98-c116708efabf"
private const val PERSON_ID = "dedb1ebd-24ae-43e8-a24d-810b1f9e2c16"
}
private val owner = TankobonUser("[email protected]", "", true, "User", id = OWNER_ID)
private val user = TankobonUser("[email protected]", "", false, "User2", id = USER_ID)
private val library = makeLibrary("Library", "", id = LIBRARY_ID, ownerId = OWNER_ID)
private val person = Person("Person", id = PERSON_ID, libraryId = LIBRARY_ID)
@BeforeAll
fun setup() {
userRepository.insert(owner)
userRepository.insert(user)
libraryRepository.insert(library)
}
@AfterAll
fun tearDown() {
libraryRepository.deleteAll()
userRepository.deleteAll()
}
@AfterEach
fun clear() {
personRepository.deleteAll()
}
@Nested
inner class UnauthorizedUser {
@Test
fun `it should return unauthorized when getting the persons from a library with an anonymous user`() {
mockMvc.get("/api/v1/libraries/${library.id}/people")
.andExpect { status { isUnauthorized() } }
}
@Test
@WithMockCustomUser(id = USER_ID)
fun `it should return forbidden when getting the persons from a library the user does not have access`() {
mockMvc.get("/api/v1/libraries/${library.id}/people")
.andExpect { status { isForbidden() } }
}
@Test
@WithMockCustomUser(roles = [ROLE_ADMIN])
fun `it should return ok when getting the persons from a library if the user is an admin`() {
personLifecycle.addPerson(person)
mockMvc.get("/api/v1/libraries/${library.id}/people")
.andExpect {
status { isOk() }
jsonPath("$.result") { value("OK") }
jsonPath("$.data.length()") { value(1) }
jsonPath("$.data[0].id") { value(person.id) }
}
}
}
@Nested
inner class DuplicateNames {
@Test
@WithMockCustomUser(id = OWNER_ID)
fun `it should return bad request when creating a person with a duplicate name in the library`() {
personLifecycle.addPerson(person)
val jsonString = """
{
"name": "${person.name.lowercase()}",
"description": "",
"library": "${library.id}"
}
""".trimIndent()
mockMvc
.post("/api/v1/people") {
contentType = MediaType.APPLICATION_JSON
content = jsonString
}
.andExpect { status { isBadRequest() } }
}
}
@Nested
inner class Delete {
@Test
@WithMockCustomUser(id = USER_ID)
fun `it should return forbidden if a non-admin user tries to delete a person from a library it does not have access`() {
personLifecycle.addPerson(person)
mockMvc.delete("/api/v1/people/${person.id}")
.andExpect { status { isForbidden() } }
}
@Test
@WithMockCustomUser(roles = [ROLE_ADMIN])
fun `it should return no content if an admin deletes a person from any user`() {
personLifecycle.addPerson(person)
mockMvc.delete("/api/v1/people/${person.id}")
.andExpect { status { isNoContent() } }
mockMvc.get("/api/v1/people/${person.id}")
.andExpect { status { isNotFound() } }
}
}
} | 0 | Kotlin | 0 | 1 | cb28b68c0b6f3b1de7f77450122a609295396c28 | 5,170 | tankobon | MIT License |
app/src/main/java/com/oussama/portfolio/ui/adapters/viewholders/MediaViewHolder.kt | Meglali20 | 752,721,331 | false | {"Kotlin": 255952, "Java": 21500, "Python": 7142, "GLSL": 5407} | package com.oussama.portfolio.ui.adapters.viewholders
import androidx.recyclerview.widget.RecyclerView
import com.oussama.portfolio.databinding.ItemMediaBinding
class MediaViewHolder(val binding: ItemMediaBinding) :
RecyclerView.ViewHolder(binding.root) | 0 | Kotlin | 0 | 4 | 1437e6cf47fc7f4c64f46eee10c9d25b2399b649 | 259 | Portfolio-Android-MVVM | MIT License |
app/src/main/kotlin/com/sanmer/geomag/ui/activity/log/LogActivity.kt | ya0211 | 583,580,288 | false | null | package com.sanmer.geomag.ui.activity.log
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.sanmer.geomag.service.LogcatService
import com.sanmer.geomag.ui.activity.base.BaseActivity
import kotlinx.coroutines.launch
class LogActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
LogcatService.isActive
.collect { isActive ->
if (!isActive) {
LogcatService.start(this@LogActivity)
}
}
}
}
setActivityContent {
LogScreen()
}
}
override fun onDestroy() {
super.onDestroy()
LogcatService.stop(this)
}
companion object {
fun start(context: Context) {
val intent = Intent(context, LogActivity::class.java)
context.startActivity(intent)
}
}
} | 0 | Kotlin | 2 | 16 | 60a08eec85411272d3a154f01ae507f1a001490f | 1,238 | Geomag | MIT License |
Cours 5/replication-exercise/eureka/src/test/kotlin/com/example/eureka/EurekaApplicationTests.kt | SebStreb | 688,413,012 | false | {"Java": 99035, "Kotlin": 3457, "JavaScript": 800} | package com.example.eureka
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class EurekaApplicationTests {
@Test
fun contextLoads() {
}
}
| 1 | null | 1 | 1 | 9a81d273f804b370268ad3962c52b0f421fe6e13 | 215 | spring-examples | MIT License |
app/src/main/java/ir/ghararemaghzha/game/adapters/SlideAdapter.kt | ShahabGT | 279,053,168 | false | null | package ir.ghararemaghzha.game.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import ir.ghararemaghzha.game.R
class SlideAdapter(private val ctx: Context): RecyclerView.Adapter<SlideAdapter.ViewHolder>() {
class ViewHolder(v: View) : RecyclerView.ViewHolder(v){
val pic: ImageView = v.findViewById(R.id.slide_pic)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.row_slide,parent,false))
override fun onBindViewHolder(h: ViewHolder, position: Int) {
when(position){
0->h.pic.setImageDrawable(ContextCompat.getDrawable(ctx,R.drawable.slide1))
1->h.pic.setImageDrawable(ContextCompat.getDrawable(ctx,R.drawable.slide2))
2->h.pic.setImageDrawable(ContextCompat.getDrawable(ctx,R.drawable.slide3))
3->h.pic.setImageDrawable(ContextCompat.getDrawable(ctx,R.drawable.slide4))
}
}
override fun getItemCount(): Int =4
} | 0 | Kotlin | 0 | 1 | c4f6bfa6d61ebf2781d939ee04c2f2acb1483efb | 1,224 | GharareMaghzha | Apache License 2.0 |
composenav/src/main/java/com/adamkobus/compose/navigation/error/NavIntentMappingTooDeepError.kt | AdamKobus | 453,682,860 | false | null | package com.adamkobus.compose.navigation.error
import com.adamkobus.compose.navigation.NavIntentResolver
import com.adamkobus.compose.navigation.intent.NavIntent
/**
* [NavIntent]s are processed by [NavIntentResolver]s recursively.
* This error is thrown if recursive calls depths exceeds a limit (by default 50).
*/
class NavIntentMappingTooDeepError(message: String) : RuntimeException(message)
| 14 | Kotlin | 0 | 5 | 533edffc92199c58b63ce4fb26d0a2d88f0b64f7 | 402 | compose-navigation | MIT License |
app/src/main/java/com/creation/kitchen/myfoodie/network/MyFoodieApiService.kt | jhpark904 | 607,425,211 | false | null | package com.creation.kitchen.myfoodie.network
import com.creation.kitchen.myfoodie.ui.model.CategoryResponse
import com.creation.kitchen.myfoodie.ui.model.MealDetailsResponse
import com.creation.kitchen.myfoodie.ui.model.MealResponse
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonConfiguration
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
private const val BASE_URL = "https://www.themealdb.com//api/json/v1/1/"
val json = Json { ignoreUnknownKeys = true }
private val retrofit = Retrofit.Builder()
.addConverterFactory(
json.asConverterFactory("application/json".toMediaType())
)
.baseUrl(BASE_URL)
.build()
interface MyFoodieApiService {
@GET("list.php?c=list")
suspend fun getCategories(): CategoryResponse
@GET("filter.php")
suspend fun getMealsList(@Query("c") category: String): MealResponse
@GET("lookup.php")
suspend fun getMealDetails(@Query("i") mealId: String): MealDetailsResponse
}
object MyFoodieApi {
val retrofitService: MyFoodieApiService by lazy {
retrofit.create(MyFoodieApiService::class.java)
}
} | 0 | Kotlin | 0 | 0 | ea9202fa0c4ff7e1b25b49186622c0c521bfb368 | 1,337 | My-Foodie | MIT License |
client_dashboard/common/src/commonMain/kotlin/com/angus/common/presentation/composables/FilterBox.kt | SantiagoFlynnUTN | 770,562,894 | false | {"Kotlin": 2181295, "Swift": 6073, "HTML": 3900, "Ruby": 2543, "Dockerfile": 1994, "Shell": 912} | package com.angus.common.presentation.composables
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.angus.designSystem.ui.composable.BpOutlinedButton
import com.angus.designSystem.ui.composable.BpTransparentButton
import com.angus.designSystem.ui.theme.Theme
import com.angus.common.presentation.composables.modifier.cursorHoverIconHand
import com.angus.common.presentation.resources.Resources
import com.angus.common.presentation.util.kms
@Composable
fun FilterBox(
title: String,
onSaveClicked: () -> Unit,
onCancelClicked: () -> Unit,
modifier: Modifier = Modifier,
hasClearAll: Boolean = true,
onClearAllClicked: () -> Unit = {},
content: @Composable () -> Unit
) {
Box(
modifier = modifier
.width(450.kms)
.background(Theme.colors.surface)
.border(1.dp, Theme.colors.divider)
) {
Column(
modifier = Modifier.fillMaxSize()
) {
FilterBoxHeader(
title = title,
hasClearAll = hasClearAll,
onClearAllClicked = onClearAllClicked
)
content()
FilterBoxFooter(onSaveClicked, onCancelClicked)
}
}
}
@Composable
private fun FilterBoxHeader(
title: String,
modifier: Modifier = Modifier,
hasClearAll: Boolean = true,
onClearAllClicked: () -> Unit = {}
) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(24.kms),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = title,
style = Theme.typography.headline,
color = Theme.colors.contentPrimary
)
if (hasClearAll) BpTransparentButton(
title = Resources.Strings.clearAll,
onClick = onClearAllClicked
)
}
}
@Composable
private fun FilterBoxFooter(
onSaveClicked: () -> Unit,
onCancelClicked: () -> Unit,
modifier: Modifier = Modifier,
) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(24.kms),
horizontalArrangement = Arrangement.SpaceBetween
) {
BpTransparentButton(
title = Resources.Strings.cancel,
onClick = onCancelClicked,
modifier = Modifier
.height(32.dp)
.weight(1f)
.padding(end = 16.kms)
.cursorHoverIconHand()
)
BpOutlinedButton(
title = Resources.Strings.save,
onClick = onSaveClicked,
textPadding = PaddingValues(0.dp),
modifier = Modifier
.height(32.dp)
.weight(3f)
.cursorHoverIconHand()
)
}
} | 0 | Kotlin | 0 | 0 | e31ddaaef1ec9cf7b97e684a736f930e4213a47a | 3,078 | AngusBrotherKMP | Apache License 2.0 |
app/src/main/java/com/suatzengin/iloveanimals/ui/createadvertisement/CreateAdvertisementUiEvent.kt | iamsuatzengin | 709,487,931 | false | {"Kotlin": 263485} | package com.suatzengin.iloveanimals.ui.createadvertisement
sealed interface CreateAdvertisementUiEvent {
data object CreatedAdvertisement : CreateAdvertisementUiEvent
data class Error(val message: String) : CreateAdvertisementUiEvent
}
| 0 | Kotlin | 0 | 0 | 444669b09860bcee7ba2407a1f9171fdf09a0cd3 | 246 | i-love-animals-android | MIT License |
transcriber/transcriber-223/src/main/kotlin/net/rsprox/transcriber/state/Npc.kt | blurite | 822,339,098 | false | {"Kotlin": 1453055} | package net.rsprox.transcriber.state
import net.rsprox.protocol.common.CoordGrid
public data class Npc(
public val index: Int,
public val id: Int,
public val creationCycle: Int,
public val coord: CoordGrid,
public val name: String? = null,
)
| 2 | Kotlin | 4 | 9 | 41535908e6ccb633c8f2564e8961efa771abd6de | 264 | rsprox | MIT License |
eva-icons/src/commonMain/kotlin/compose/icons/evaicons/outline/Pricetags.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.evaicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 compose.icons.evaicons.OutlineGroup
public val OutlineGroup.Pricetags: ImageVector
get() {
if (_pricetags != null) {
return _pricetags!!
}
_pricetags = Builder(name = "Pricetags", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.0f, strokeAlpha
= 0.0f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(0.0f, 0.0f)
horizontalLineToRelative(24.0f)
verticalLineToRelative(24.0f)
horizontalLineToRelative(-24.0f)
close()
}
path(fill = SolidColor(Color(0xFF231f20)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.87f, 22.0f)
arcToRelative(1.84f, 1.84f, 0.0f, false, true, -1.29f, -0.53f)
lineTo(5.17f, 15.05f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -0.29f, -0.61f)
lineTo(4.0f, 5.09f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.29f, -0.8f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 5.09f, 4.0f)
lineToRelative(9.35f, 0.88f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.61f, 0.29f)
lineToRelative(6.42f, 6.41f)
arcToRelative(1.82f, 1.82f, 0.0f, false, true, 0.0f, 2.57f)
lineToRelative(-7.32f, 7.32f)
arcTo(1.82f, 1.82f, 0.0f, false, true, 12.87f, 22.0f)
close()
moveTo(6.87f, 13.89f)
lineTo(12.87f, 19.89f)
lineTo(19.92f, 12.84f)
lineTo(13.92f, 6.84f)
lineTo(6.11f, 6.11f)
close()
}
path(fill = SolidColor(Color(0xFF231f20)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.5f, 10.5f)
moveToRelative(-1.5f, 0.0f)
arcToRelative(1.5f, 1.5f, 0.0f, true, true, 3.0f, 0.0f)
arcToRelative(1.5f, 1.5f, 0.0f, true, true, -3.0f, 0.0f)
}
}
.build()
return _pricetags!!
}
private var _pricetags: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 3,320 | compose-icons | MIT License |
src/jvmTest/kotlin/matt/async/async.kt | mgroth0 | 497,201,859 | false | {"Kotlin": 121905} | package matt.async
//actual typealias CommonTest = Test
class UghJvm {
// @Test
// fun ugh() {
// validateThreadPriorities()
// }
} | 0 | Kotlin | 0 | 0 | cda7a2432ff062f8c37ac253042da648cbe7a116 | 149 | async | MIT License |
src/main/kotlin/com/xinaiz/wds/core/ElementCreator.kt | domazey | 155,060,100 | false | null | package com.xinaiz.wds.core
import com.xinaiz.wds.core.element.ExtendedWebElement
import com.xinaiz.wds.elements.tagged.*
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
class ElementCreator(private val webDriver: WebDriver) {
private fun <T : ExtendedWebElement> builder(tag: String, type: String?, proxyFactory: (WebElement) -> T): ElementBuilder<T> {
return ElementBuilder(webDriver, tag, type, proxyFactory)
}
fun abbr() = builder(
AbbreviationExtendedWebElement.TAG,
null,
::AbbreviationExtendedWebElement)
fun address() = builder(
AddressExtendedWebElement.TAG,
null,
::AddressExtendedWebElement)
fun a() = builder(
AnchorExtendedWebElement.TAG,
null,
::AnchorExtendedWebElement)
fun area() = builder(
AreaExtendedWebElement.TAG,
null,
::AreaExtendedWebElement)
fun article() = builder(
ArticleExtendedWebElement.TAG,
null,
::ArticleExtendedWebElement)
fun aside() = builder(
AsideExtendedWebElement.TAG,
null,
::AsideExtendedWebElement)
fun audio() = builder(
AudioExtendedWebElement.TAG,
null,
::AudioExtendedWebElement)
fun base() = builder(
BaseExtendedWebElement.TAG,
null,
::BaseExtendedWebElement)
fun bdo() = builder(
BdoExtendedWebElement.TAG,
null,
::BdoExtendedWebElement)
fun blockquote() = builder(
BlockquoteExtendedWebElement.TAG,
null,
::BlockquoteExtendedWebElement)
fun body() = builder(
BodyExtendedWebElement.TAG,
null,
::BodyExtendedWebElement)
fun b() = builder(
BoldExtendedWebElement.TAG,
null,
::BoldExtendedWebElement)
fun br() = builder(
BreakExtendedWebElement.TAG,
null,
::BreakExtendedWebElement)
fun button() = builder(
ButtonExtendedWebElement.TAG,
null,
::ButtonExtendedWebElement)
//TODO... rest
fun checkbox() = builder(
GenericInputExtendedWebElement.TAG,
CheckboxInputExtendedWebElement.TYPE,
::CheckboxInputExtendedWebElement)
} | 0 | Kotlin | 0 | 0 | 55012e722cb4e56785ca25e5477e0d7c2a5260cc | 2,260 | web-driver-support | Apache License 2.0 |
backend/src/main/kotlin/com/pao/routes/ProductRoute.kt | DesenvolvimentoSistemasSoftware | 771,009,250 | false | {"Kotlin": 54019, "HTML": 73} | package com.pao.routes
import com.pao.data.classes.Product
import com.pao.plugins.BASE_URL
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
// "database" provisória
val products = listOf<Product>(
Product(1,"Baguete", 5001,14.90,30,
0.0,arrayOf("$BASE_URL/Images/baguete.jpeg"),"Deliciosa baguete direto do forno para sua casa",
arrayOf("Pão","Salgado","Café da manhã"), 4.5, intArrayOf(8001,8002,8003,8004,8005)
),
Product(2,"Pão de Forma", 5001,8.90,30,
0.0,arrayOf("$BASE_URL/Images/dafabrica.jpeg"),"Pão de forma da melhor qualidade",
arrayOf("Pão","Salgado","Café da manhã","industrial"), 4.0, intArrayOf(8071,8102,8303,8804,8505)
),
Product(3,"<NAME>", 5001,0.5,50,
0.0,arrayOf("$BASE_URL/Images/frances_ou_sal.jpeg"),"Esse não pode faltar nas manhãs de ninguém",
arrayOf("Pão","Salgado","Café da manhã"), 4.8, intArrayOf(10,12,13,14,15)
),
Product(4,"<NAME>", 5001,2.90,30,
0.0,arrayOf("$BASE_URL/Images/queijado.jpeg"),"Pão de queijo mineiro bem recheado de queijo",
arrayOf("Pão","Salgado","Café da manhã"), 4.5, intArrayOf(21,22,33,24,25)
),
Product(5,"Mofado", 5001,0.0,5,
0.0,arrayOf("$BASE_URL/Images/mofou.jpeg"),"Por que estou vendendo isso?",
arrayOf("?"), 0.0, intArrayOf(0)
)
)
fun Route.randomProduct() {
route("/product") {
get("/random") {
call.respond(HttpStatusCode.OK, products.random())
}
}
}
fun Route.getProduct() {
route("/product") {
get("/{id}") {
val id = call.parameters["id"]?.toInt()
val product = products.find { it.id == id }
if (product == null) {
call.respond(HttpStatusCode.NotFound)
} else {
call.respond(product)
}
}
}
}
| 7 | Kotlin | 0 | 0 | a47fbc8253443c954aeafb32d9e71f116f6af994 | 1,911 | Paozim | MIT License |
app/src/main/java/com/hypertrack/android/ui/common/select_destination/reducer/UserLocation.kt | hypertrack | 241,723,736 | false | null | package com.hypertrack.android.ui.common.select_destination.reducer
import com.google.android.gms.maps.model.LatLng
data class UserLocation(
val latLng: LatLng,
val address: String
)
| 1 | Kotlin | 17 | 31 | c5dd23621aed11ff188cf98ac037b67f435e9f5b | 193 | visits-android | MIT License |
Android/Healthy Mind/app/src/main/java/com/example/healthymind/service/RecordService.kt | manuel103 | 293,456,470 | false | {"JavaScript": 523504, "Jupyter Notebook": 421722, "Java": 358641, "SCSS": 62142, "Kotlin": 33260, "HTML": 3875, "CSS": 420} | package com.example.healthymind.service
import android.app.Notification
import android.app.Service
import android.content.Intent
import android.media.AudioManager
import android.media.MediaRecorder
import android.os.Build
import android.os.Environment
import android.os.IBinder
import android.text.format.DateFormat
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.documentfile.provider.DocumentFile
import com.example.healthymind.App
import com.example.healthymind.R
import com.example.healthymind.analysis.Recognition
import com.example.healthymind.audio.MFCC
import com.example.healthymind.audio.WavFile
import com.example.healthymind.auth.SessionManager
import com.example.healthymind.entity.Recording
import com.example.healthymind.helper.FileHelper
import com.example.healthymind.util.Constants
import com.example.healthymind.util.MySharedPreferences
import com.example.healthymind.util.UserPreferences
import com.google.firebase.database.FirebaseDatabase
import com.jlibrosa.audio.wavFile.WavFileException
import org.tensorflow.lite.DataType
import org.tensorflow.lite.Interpreter
import org.tensorflow.lite.gpu.CompatibilityList
import org.tensorflow.lite.gpu.GpuDelegate
import org.tensorflow.lite.support.common.FileUtil
import org.tensorflow.lite.support.common.TensorProcessor
import org.tensorflow.lite.support.common.ops.NormalizeOp
import org.tensorflow.lite.support.label.TensorLabel
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
import java.io.File
import java.io.IOException
import java.math.RoundingMode
import java.nio.ByteBuffer
import java.nio.MappedByteBuffer
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
//@RequiresApi(api = Build.VERSION_CODES.O)
class RecordService : Service() {
private val formatter = SimpleDateFormat("yyyyMMddHHmmss", Locale.US)
private var recorder: MediaRecorder? = null
private var phoneNumber: String? = null
private var file: DocumentFile? = null
private var onCall = false
private var recording = false
private val onForeground = false
private var idCall: String? = null
// var path = Environment.getExternalStorageDirectory().toString() + "/audioData/" + System.currentTimeMillis() + ".wav"
var path = Environment.getExternalStorageDirectory().toString() + "/audioData/" + "recording.wav"
var wavRecorder = WavRecorder(path)
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
startForeground(1, Notification())
// depression_prediction.analyzePredictions();
}
fun predictDepression(audioFilePath: String): String? {
val mNumFrames: Int
val mSampleRate: Int
val mChannels: Int
var meanMFCCValues: FloatArray = FloatArray(1)
var predictedResult: String? = "Unknown"
var wavFile: WavFile? = null
try {
wavFile = WavFile.openWavFile(File(audioFilePath))
mNumFrames = wavFile.numFrames.toInt()
mSampleRate = wavFile.sampleRate.toInt()
mChannels = wavFile.numChannels
val buffer = Array(mChannels) { DoubleArray(mNumFrames) }
var frameOffset = 0
val loopCounter: Int = mNumFrames * mChannels / 4096 + 1
for (i in 0 until loopCounter) {
frameOffset = wavFile.readFrames(buffer, mNumFrames, frameOffset)
}
//trimming the magnitude values to 5 decimal digits
val df = DecimalFormat("#.#####")
df.setRoundingMode(RoundingMode.CEILING)
val meanBuffer = DoubleArray(mNumFrames)
for (q in 0 until mNumFrames) {
var frameVal = 0.0
for (p in 0 until mChannels) {
frameVal = frameVal + buffer[p][q]
}
meanBuffer[q] = df.format(frameVal / mChannels).toDouble()
}
//MFCC java library.
val mfccConvert = MFCC()
mfccConvert.setSampleRate(mSampleRate)
val nMFCC = 40
mfccConvert.setN_mfcc(nMFCC)
val mfccInput = mfccConvert.process(meanBuffer)
val nFFT = mfccInput.size / nMFCC
val mfccValues =
Array(nMFCC) { DoubleArray(nFFT) }
//loop to convert the mfcc values into multi-dimensional array
for (i in 0 until nFFT) {
var indexCounter = i * nMFCC
val rowIndexValue = i % nFFT
for (j in 0 until nMFCC) {
mfccValues[j][rowIndexValue] = mfccInput[indexCounter].toDouble()
indexCounter++
}
}
//code to take the mean of mfcc values across the rows such that
//[nMFCC x nFFT] matrix would be converted into
//[nMFCC x 1] dimension - which would act as an input to tflite model
meanMFCCValues = FloatArray(nMFCC)
for (p in 0 until nMFCC) {
var fftValAcrossRow = 0.0
for (q in 0 until nFFT) {
fftValAcrossRow = fftValAcrossRow + mfccValues[p][q]
}
val fftMeanValAcrossRow = fftValAcrossRow / nFFT
meanMFCCValues[p] = fftMeanValAcrossRow.toFloat()
}
} catch (e: IOException) {
e.printStackTrace()
} catch (e: WavFileException) {
e.printStackTrace()
}
predictedResult = loadModelAndMakePredictions(meanMFCCValues)
return predictedResult
}
protected fun loadModelAndMakePredictions(meanMFCCValues: FloatArray): String? {
var predictedResult: String? = "unknown"
//load the TFLite model in 'MappedByteBuffer' format using TF Interpreter
val tfliteModel: MappedByteBuffer =
FileUtil.loadMappedFile(this, getModelPath())
val tflite: Interpreter
/** Options for configuring the Interpreter. */
val compatList = CompatibilityList()
val tfliteOptions =
Interpreter.Options().apply {
if (compatList.isDelegateSupportedOnThisDevice) {
// if the device has a supported GPU, add the GPU delegate
val delegateOptions = compatList.bestOptionsForThisDevice
this.addDelegate(GpuDelegate(delegateOptions))
} else {
// if the GPU is not supported, run on 4 threads
this.setNumThreads(4)
}
}
// tfliteOptions.setNumThreads(4)
tflite = Interpreter(tfliteModel, tfliteOptions)
//obtain the input and output tensor size required by the model
//convert input shape to 4D as expected by model
val imageTensorIndex = 0
val imageShape = tflite.getInputTensor(imageTensorIndex).shape()
val imageDataType: DataType = tflite.getInputTensor(imageTensorIndex).dataType()
val probabilityTensorIndex = 0
val probabilityShape = tflite.getOutputTensor(probabilityTensorIndex).shape()
val probabilityDataType: DataType = tflite.getOutputTensor(probabilityTensorIndex).dataType()
//need to transform the MFCC 1d float buffer into 1x40x1x1 dimension tensor using TensorBuffer
val inBuffer: TensorBuffer = TensorBuffer.createDynamic(imageDataType)
inBuffer.loadArray(meanMFCCValues, imageShape)
val inpBuffer: ByteBuffer = inBuffer.getBuffer()
val outputTensorBuffer: TensorBuffer = TensorBuffer.createFixedSize(probabilityShape, probabilityDataType)
//run the predictions with input and output buffer tensors to get probability values across the labels
tflite.run(inpBuffer, outputTensorBuffer.getBuffer())
//Code to transform the probability predictions into label values
val ASSOCIATED_AXIS_LABELS = "labels.txt"
var associatedAxisLabels: List<String?>? = null
try {
associatedAxisLabels = FileUtil.loadLabels(this, ASSOCIATED_AXIS_LABELS)
} catch (e: IOException) {
Log.e("tfliteSupport", "Error reading label file", e)
}
//Tensor processor for processing the probability values and to sort them
// based on the descending order of probabilities
val probabilityProcessor: TensorProcessor = TensorProcessor.Builder()
.add(NormalizeOp(0.0f, 255.0f)).build()
if (null != associatedAxisLabels) {
// Map of labels and their corresponding probability
val labels = TensorLabel(
associatedAxisLabels,
probabilityProcessor.process(outputTensorBuffer)
)
// Create a map to access the result based on label
val floatMap: Map<String, Float> = labels.getMapWithFloatValue()
//function to retrieve the top K probability values, in this case 'k' value is 1.
//retrieved values are stored in 'Recognition' object with label details.
val resultPrediction: List<Recognition>? = getTopKProbability(floatMap);
//get the top 1 prediction from the retrieved list of top predictions
predictedResult = getPredictedValue(resultPrediction)
}
return predictedResult
}
fun getPredictedValue(predictedList: List<Recognition>?): String? {
val top1PredictedValue: Recognition? = predictedList?.get(0)
return top1PredictedValue?.getTitle()
}
fun getModelPath(): String {
return "model.tflite"
}
/** Gets the top-k results. */
protected fun getTopKProbability(labelProb: Map<String, Float>): List<Recognition>? {
// Find the best classifications.
val MAX_RESULTS: Int = 1
val pq: PriorityQueue<Recognition> = PriorityQueue(
MAX_RESULTS,
Comparator<Recognition> { lhs, rhs -> // Intentionally reversed to put high confidence at the head of the queue.
java.lang.Float.compare(rhs.getConfidence(), lhs.getConfidence())
})
for (entry in labelProb.entries) {
pq.add(Recognition("" + entry.key, entry.key, entry.value))
}
val recognitions: ArrayList<Recognition> = ArrayList()
val recognitionsSize: Int = Math.min(pq.size, MAX_RESULTS)
for (i in 0 until recognitionsSize) {
recognitions.add(pq.poll())
}
return recognitions
}
fun analyzePredictions() {
val externalStorage: File = Environment.getExternalStorageDirectory()
val audioDirPath = externalStorage.absolutePath + "/audioData"
// val fileNames: MutableList<String> = ArrayList()
// File(audioDirPath).walk().forEach {
//
// if (it.absolutePath.endsWith(".wav")) {
// fileNames.add(it.name)
// }
// }
// Loop over all the recordings in the audioDir path &
// display the depression results
// var i = 0
// var x = 0
// val file_array = arrayOf(fileNames)
// for (file in file_array) {
// val file_size = file.size
// while (i < file_size) {
// val audio_files = file_array[0][i]
val full_audioPath = audioDirPath + "/" + "recording.wav"
val predicted_result = predictDepression(full_audioPath)
// println("Depression result is: " + predicted_result)
// Store depression result to DB
val sessionManager = SessionManager(this, SessionManager.SESSION_REMEMBERME)
if (sessionManager.checkRememberMe()) {
val rememberMeDetails = sessionManager.rememberMeDetailFromSession
val username = rememberMeDetails[SessionManager.KEY_SESSIONUSERNAME]
val patientRef = FirebaseDatabase
.getInstance()
.getReference(Constants.FIREBASE_CHILD_DEPRESSION_LEVELS)
.child(username)
.child("depression_levels")
// val pushRef = patientRef.child("prediction_" + i)
patientRef.push().setValue(predicted_result)
}
// i++
}
// }
// }
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.d(Constants.TAG, "RecordService onStartCommand")
// wavRecorder.getRecordingState();
if (intent == null) return START_NOT_STICKY
val commandType = intent.getIntExtra("commandType", 0)
if (commandType == 0) return START_NOT_STICKY
val enabled = UserPreferences.getEnabled()
when (commandType) {
Constants.RECORDING_ENABLED -> {
Log.d(Constants.TAG, "RecordService RECORDING_ENABLED")
if (enabled && phoneNumber != null && onCall && !recording) {
Log.d(Constants.TAG, "RecordService STATE_START_RECORDING")
idCall = formatter.format(Date())
startRecordingBySource()
}
}
Constants.RECORDING_DISABLED -> {
Log.d(Constants.TAG, "RecordService RECORDING_DISABLED")
if (onCall && phoneNumber != null && recording) {
Log.d(Constants.TAG, "RecordService STATE_STOP_RECORDING")
stopAndReleaseRecorder()
// wavRecorder.stopRecording();
recording = false
}
}
Constants.STATE_INCOMING_NUMBER -> {
Log.d(Constants.TAG, "RecordService STATE_INCOMING_NUMBER")
if (phoneNumber == null) phoneNumber = intent.getStringExtra("phoneNumber")
}
Constants.STATE_CALL_START -> {
Log.d(Constants.TAG, "RecordService STATE_CALL_START")
onCall = true
if (enabled && phoneNumber != null && !recording) {
idCall = formatter.format(Date())
wavRecorder.startRecording()
startRecordingBySource()
}
}
Constants.STATE_CALL_END -> {
Log.d(Constants.TAG, "RecordService STATE_CALL_END")
onCall = false
phoneNumber = null
recording = false
wavRecorder.stopRecording()
stopAndReleaseRecorder()
analyzePredictions()
}
}
return START_STICKY
}
override fun onDestroy() {
Log.d(Constants.TAG, "RecordService onDestroy")
stopAndReleaseRecorder()
// wavRecorder.stopRecording();
// wavRecorder.releaseRecord();
super.onDestroy()
}
/// In case it is impossible to record
private fun terminateAndEraseFile() {
Log.d(Constants.TAG, "RecordService terminateAndEraseFile")
stopAndReleaseRecorder()
recording = false
if (file != null) deleteFile()
}
private fun deleteFile() {
Log.d(Constants.TAG, "RecordService deleteFile")
file!!.delete()
file = null
}
private fun stopAndReleaseRecorder() {
if (recorder == null) return
Log.d(Constants.TAG, "RecordService stopAndReleaseRecorder")
var recorderStopped = false
var exception = false
try {
recorder!!.stop()
recorderStopped = true
} catch (e: IllegalStateException) {
Log.d(Constants.TAG, "RecordService: Failed to stop recorder. Perhaps it wasn't started?", e)
exception = true
} catch (e: RuntimeException) {
Log.d(Constants.TAG, "RecordService: Failed to stop recorder. RuntimeException", e)
exception = true
}
recorder!!.reset()
recorder!!.release()
recorder = null
if (exception) {
App.isOutComming = false
deleteFile()
}
if (recorderStopped) {
Toast.makeText(this, this.getString(R.string.receiver_end_call),
Toast.LENGTH_SHORT)
.show()
// wavRecorder.stopRecording();
val recording = Recording()
recording.idCall = idCall
recording.isOutGoing = App.isOutComming
App.isOutComming = false
recording.save()
file = null
Log.d(Constants.TAG, "RecordService save")
}
}
private fun startRecordingBySource() {
var exception = false
val source = MySharedPreferences.getInstance(this).getInt(MySharedPreferences.KEY_AUDIO_SOURCE, 0)
Log.d(Constants.TAG, "RecordService source: $source")
if (source != 0) {
exception = startRecording(source)
} else {
// exception = startRecording(MediaRecorder.AudioSource.VOICE_CALL);
if (exception) {
exception = startRecording(MediaRecorder.AudioSource.MIC)
if (!exception) {
audioManager = getSystemService(AUDIO_SERVICE) as AudioManager
audioManager!!.setStreamVolume(3, audioManager!!.getStreamMaxVolume(3), 0)
audioManager!!.mode = AudioManager.MODE_IN_CALL
audioManager!!.isSpeakerphoneOn = false
}
}
}
if (exception) {
App.isOutComming = false
Log.e(Constants.TAG, "Failed to set up recorder.")
terminateAndEraseFile()
val toast = Toast.makeText(this,
this.getString(R.string.record_impossible),
Toast.LENGTH_LONG)
toast.show()
}
}
private fun startRecording(source: Int): Boolean {
Log.d(Constants.TAG, "RecordService startRecording")
if (recorder == null) {
recorder = MediaRecorder()
}
try {
recorder!!.reset()
recorder!!.setAudioSource(source)
// recorder.setAudioSamplingRate(8000);
// recorder.setAudioEncodingBitRate(12200);
recorder!!.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
recorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
recorder!!.setAudioChannels(1)
recorder!!.setAudioSamplingRate(44100)
recorder!!.setAudioEncodingBitRate(1024 * 1024)
val date = DateFormat.format("yyyyMMddHHmmss", Date()) as String
// wavRecorder.getFileName(date);
if (file == null) {
file = FileHelper.getFile(this, phoneNumber!!)
}
val fd = contentResolver
.openFileDescriptor(file!!.uri, "w")
?: throw Exception("Failed open recording file.")
recorder!!.setOutputFile(fd.fileDescriptor)
recorder!!.setOnErrorListener { mr: MediaRecorder?, what: Int, extra: Int ->
Log.e(Constants.TAG, "OnErrorListener $what,$extra")
terminateAndEraseFile()
}
recorder!!.setOnInfoListener { mr: MediaRecorder?, what: Int, extra: Int ->
Log.e(Constants.TAG, "OnInfoListener $what,$extra")
terminateAndEraseFile()
}
recorder!!.prepare()
// Sometimes the recorder takes a while to start up
Thread.sleep(2000)
recorder!!.start()
recording = true
Log.d(Constants.TAG, "RecordService: Recorder started!")
val toast = Toast.makeText(this,
this.getString(R.string.receiver_start_call),
Toast.LENGTH_SHORT)
toast.show()
return false
} catch (e: Exception) {
Log.d(Constants.TAG, "RecordService: Exception!")
}
return true
}
companion object {
var audioManager: AudioManager? = null
}
}
| 0 | JavaScript | 0 | 0 | d81793354901fab9f8b32f5b63a75c90e260620b | 20,348 | Healthy-Mind | Apache License 2.0 |
analysis/analysis-api/testData/symbols/symbolByPsi/facadeWithJvmName.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE_K1
@file:kotlin.jvm.JvmName("DifferentFacadeName")
fun foo() {}
fun String.foo(): Int = 42
val x: Int = 42
val Int.y get() = this
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 173 | kotlin | Apache License 2.0 |
dslitem/src/main/java/com/angcyo/item/DslBaseLabelItem.kt | DaoCalendar | 289,456,694 | true | {"Kotlin": 2830139} | package com.angcyo.item
import com.angcyo.dsladapter.DslAdapterItem
import com.angcyo.item.style.TextStyleConfig
import com.angcyo.widget.DslViewHolder
/**
* 带有Label的item
* Email:<EMAIL>
* @author angcyo
* @date 2020/03/23
* Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved.
*/
open class DslBaseLabelItem : DslAdapterItem() {
/**左边的Label文本*/
var itemLabelText: CharSequence? = null
set(value) {
field = value
itemLabelTextStyle.text = value
}
/**统一样式配置*/
var itemLabelTextStyle = TextStyleConfig()
init {
itemLayoutId = R.layout.dsl_label_item
}
override fun onItemBind(
itemHolder: DslViewHolder,
itemPosition: Int,
adapterItem: DslAdapterItem
) {
super.onItemBind(itemHolder, itemPosition, adapterItem)
itemHolder.gone(R.id.lib_label_view, itemLabelTextStyle.text == null)
itemHolder.tv(R.id.lib_label_view)?.apply {
itemLabelTextStyle.updateStyle(this)
}
}
open fun configLabelTextStyle(action: TextStyleConfig.() -> Unit) {
itemLabelTextStyle.action()
}
}
| 0 | null | 0 | 0 | 53e533caf25d2fcd76e54d712b8857486af90632 | 1,165 | UICore | MIT License |
shared/presentation/mvp/src/main/java/dev/eduayuso/cleansamples/shared/presentation/mvp/features/posts/IPostListEvents.kt | eduayuso | 340,966,656 | false | null | package dev.eduayuso.cleansamples.shared.presentation.mvp.features.posts
import dev.eduayuso.cleansamples.shared.domain.entities.PostEntity
import dev.eduayuso.cleansamples.shared.presentation.mvp.IViewEvents
interface IPostListEvents: IViewEvents {
fun showLoading()
fun hideLoading()
fun onError(message: String)
fun onPostListFetched(posts: List<PostEntity>)
} | 1 | Kotlin | 0 | 0 | d42fe931d229636596b7e969405e5c9d04e3a290 | 382 | clean_samples | Apache License 2.0 |
app/src/main/java/uk/co/jamiecruwys/apieceofcake/main/list/CakeItemView.kt | JamieCruwys | 188,311,490 | false | null | package uk.co.jamiecruwys.apieceofcake.main.list
import uk.co.jamiecruwys.apieceofcake.api.Cake
interface CakeItemView {
fun onCakeClicked(cake: Cake)
fun showCakeInfoDialog(cake: Cake)
} | 0 | Kotlin | 0 | 0 | 1bccd33cf2ac04fedeb064fa61cc6725a78dcb09 | 199 | APieceOfCake | Apache License 2.0 |
platform/workspace/jps/src/com/intellij/platform/workspace/jps/entities/dependencies.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.platform.workspace.jps.entities
import com.intellij.openapi.util.NlsSafe
import com.intellij.platform.workspace.storage.EntitySource
import com.intellij.platform.workspace.storage.EntityType
import com.intellij.platform.workspace.storage.GeneratedCodeApiVersion
import com.intellij.platform.workspace.storage.MutableEntityStorage
import com.intellij.platform.workspace.storage.WorkspaceEntity
import com.intellij.platform.workspace.storage.WorkspaceEntityWithSymbolicId
import com.intellij.platform.workspace.storage.annotations.Child
import com.intellij.platform.workspace.storage.impl.containers.toMutableWorkspaceList
import com.intellij.platform.workspace.storage.url.VirtualFileUrl
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.NonNls
import java.io.Serializable
data class LibraryTypeId(val name: @NonNls String)
/**
* Describes a [Library][com.intellij.openapi.roots.libraries.Library].
* See [package documentation](psi_element://com.intellij.platform.workspace.jps.entities) for more details.
*/
interface LibraryEntity : WorkspaceEntityWithSymbolicId {
val name: @NlsSafe String
val tableId: LibraryTableId
val typeId: LibraryTypeId?
val roots: List<LibraryRoot>
val excludedRoots: List<@Child ExcludeUrlEntity>
override val symbolicId: LibraryId
get() = LibraryId(name, tableId)
//region generated code
@GeneratedCodeApiVersion(3)
interface Builder : WorkspaceEntity.Builder<LibraryEntity> {
override var entitySource: EntitySource
var name: String
var tableId: LibraryTableId
var typeId: LibraryTypeId?
var roots: MutableList<LibraryRoot>
var excludedRoots: List<ExcludeUrlEntity.Builder>
}
companion object : EntityType<LibraryEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(
name: String,
tableId: LibraryTableId,
roots: List<LibraryRoot>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null,
): Builder {
val builder = builder()
builder.name = name
builder.tableId = tableId
builder.roots = roots.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(
entity: LibraryEntity,
modification: LibraryEntity.Builder.() -> Unit,
): LibraryEntity {
return modifyEntity(LibraryEntity.Builder::class.java, entity, modification)
}
@get:Internal
@set:Internal
var LibraryEntity.Builder.libraryProperties: @Child LibraryPropertiesEntity.Builder?
by WorkspaceEntity.extensionBuilder(LibraryPropertiesEntity::class.java)
//endregion
val ExcludeUrlEntity.library: LibraryEntity? by WorkspaceEntity.extension()
data class LibraryRootTypeId(val name: @NonNls String) : Serializable {
companion object {
val COMPILED = LibraryRootTypeId("CLASSES")
val SOURCES = LibraryRootTypeId("SOURCES")
}
}
data class LibraryRoot(
val url: VirtualFileUrl,
val type: LibraryRootTypeId,
val inclusionOptions: InclusionOptions = InclusionOptions.ROOT_ITSELF
) : Serializable {
enum class InclusionOptions {
ROOT_ITSELF, ARCHIVES_UNDER_ROOT, ARCHIVES_UNDER_ROOT_RECURSIVELY
}
}
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 3,449 | intellij-community | Apache License 2.0 |
mewwalletbl/src/main/java/com/myetherwallet/mewwalletbl/data/staked/StakedTransactions.kt | MyEtherWallet | 225,456,139 | false | null | package com.myetherwallet.mewwalletbl.data.staked
import com.google.gson.annotations.SerializedName
import java.math.BigInteger
/**
* Created by BArtWell on 26.11.2020.
*/
data class StakedTransactions(
@SerializedName("value")
private val value: BigInteger,
@SerializedName("data")
private val data: ByteArray,
@SerializedName("gas")
private val gas: BigInteger
)
| 2 | null | 14 | 8 | 0c876055cad9373c425230b8444978bee11e2a52 | 394 | mew-wallet-android-biz-logic | MIT License |
app/src/main/java/com/example/moviemaster/domain/movies/model/cast/Actor.kt | AntonDavidson | 831,711,015 | false | {"Kotlin": 86511} | package com.example.moviemaster.domain.movies.model.cast
data class Actor(val actorsName: String, val character: String, val picture: String) | 0 | Kotlin | 0 | 0 | 9f4f77595802c1d27ba2b63af60b50b921f31c4e | 142 | Movie-Master | MIT License |
spring-app/src/main/kotlin/pl/starchasers/up/security/JwtTokenFilter.kt | Starchasers | 255,645,145 | false | null | package pl.starchasers.up.security
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.GenericFilterBean
import org.springframework.web.util.WebUtils
import pl.starchasers.up.service.JwtTokenService
import pl.starchasers.up.util.addCookie
import pl.starchasers.up.util.getSetAccessTokenCookie
import pl.starchasers.up.util.getSetRefreshTokenCookie
import pl.starchasers.up.util.isCloseTo
import java.time.temporal.ChronoUnit
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class JwtTokenFilter(
private val tokenService: JwtTokenService
) : GenericFilterBean() {
override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain) {
val accessTokenString = WebUtils.getCookie(
(request as HttpServletRequest), JwtTokenService.ACCESS_TOKEN_COOKIE_NAME
)?.value
val refreshTokenString = WebUtils.getCookie(
request, JwtTokenService.REFRESH_TOKEN_COOKIE_NAME
)?.value
var newAccessTokenString: String?
val newRefreshTokenString: String?
try {
newRefreshTokenString = refreshRefreshToken(refreshTokenString)
newAccessTokenString = refreshAccessToken(accessTokenString, newRefreshTokenString)
newAccessTokenString = issueAccessToken(newAccessTokenString, newRefreshTokenString)
val claims = tokenService.parseToken(newAccessTokenString!!)
SecurityContextHolder.getContext().authentication = JwtAuthenticationToken(
claims.subject, null, newRefreshTokenString, JwtTokenService.extractGrantedAuthorities(claims)
)
if (newAccessTokenString != accessTokenString) {
(response as HttpServletResponse).addCookie(
getSetAccessTokenCookie(newAccessTokenString)
)
}
if (newRefreshTokenString != refreshTokenString && newRefreshTokenString != null) {
(response as HttpServletResponse).addCookie(
getSetRefreshTokenCookie(newRefreshTokenString)
)
}
} catch (e: Exception) {
SecurityContextHolder.clearContext()
}
chain.doFilter(request, response)
}
// Reissue refresh token if close to expiration
private fun refreshRefreshToken(refreshToken: String?): String? {
if (refreshToken == null) return null
val claims = tokenService.parseToken(refreshToken)
if (isCloseTo((claims["exp"] as Int).toLong(), 2, ChronoUnit.DAYS)) {
return tokenService.refreshRefreshToken(refreshToken)
}
return refreshToken
}
// Reissue refresh token if close to expiration
private fun refreshAccessToken(accessToken: String?, refreshToken: String?): String? {
if (accessToken == null || refreshToken == null) return accessToken
val claims = tokenService.parseToken(accessToken)
if (isCloseTo((claims["exp"] as Int).toLong(), 5, ChronoUnit.MINUTES)) {
return tokenService.issueAccessToken(refreshToken)
}
return accessToken
}
// Issue access token if not present, but refresh token is present
private fun issueAccessToken(accessToken: String?, refreshToken: String?): String? {
return if (accessToken == null && refreshToken != null) {
tokenService.issueAccessToken(refreshToken)
} else {
accessToken
}
}
}
| 57 | Kotlin | 0 | 8 | e73f24d4a757d12030a0bade5b778c30e461c25b | 3,669 | up | MIT License |
components/virtual-node/cpk-write-service-impl/src/main/kotlin/net/corda/cpk/write/impl/CpkWriteServiceImpl.kt | corda | 346,070,752 | false | null | package net.corda.cpk.write.impl
import net.corda.chunking.ChunkWriterFactory
import net.corda.crypto.core.toAvro
import net.corda.configuration.read.ConfigChangedEvent
import net.corda.configuration.read.ConfigurationReadService
import net.corda.cpk.write.CpkWriteService
import net.corda.cpk.write.impl.services.db.CpkStorage
import net.corda.cpk.write.impl.services.db.impl.DBCpkStorage
import net.corda.cpk.write.impl.services.kafka.CpkChecksumsCache
import net.corda.cpk.write.impl.services.kafka.CpkChunksPublisher
import net.corda.cpk.write.impl.services.kafka.impl.CpkChecksumsCacheImpl
import net.corda.cpk.write.impl.services.kafka.impl.KafkaCpkChunksPublisher
import net.corda.data.chunking.CpkChunkId
import net.corda.db.connection.manager.DbConnectionManager
import net.corda.libs.configuration.SmartConfig
import net.corda.libs.configuration.helper.getConfig
import net.corda.libs.cpi.datamodel.CpkFile
import net.corda.lifecycle.LifecycleCoordinator
import net.corda.lifecycle.LifecycleCoordinatorFactory
import net.corda.lifecycle.LifecycleCoordinatorName
import net.corda.lifecycle.LifecycleEvent
import net.corda.lifecycle.LifecycleEventHandler
import net.corda.lifecycle.LifecycleStatus
import net.corda.lifecycle.RegistrationStatusChangeEvent
import net.corda.lifecycle.StartEvent
import net.corda.lifecycle.StopEvent
import net.corda.lifecycle.TimerEvent
import net.corda.lifecycle.createCoordinator
import net.corda.messaging.api.publisher.config.PublisherConfig
import net.corda.messaging.api.publisher.factory.PublisherFactory
import net.corda.messaging.api.subscription.config.SubscriptionConfig
import net.corda.messaging.api.subscription.factory.SubscriptionFactory
import net.corda.schema.Schemas.VirtualNode
import net.corda.schema.configuration.ConfigKeys.BOOT_CONFIG
import net.corda.schema.configuration.ConfigKeys.MESSAGING_CONFIG
import net.corda.schema.configuration.ConfigKeys.RECONCILIATION_CONFIG
import net.corda.schema.configuration.MessagingConfig
import net.corda.schema.configuration.ReconciliationConfig.RECONCILIATION_CPK_WRITE_INTERVAL_MS
import net.corda.utilities.VisibleForTesting
import net.corda.utilities.debug
import net.corda.utilities.seconds
import net.corda.utilities.trace
import net.corda.v5.base.exceptions.CordaRuntimeException
import net.corda.v5.crypto.SecureHash
import org.osgi.service.component.annotations.Activate
import org.osgi.service.component.annotations.Component
import org.osgi.service.component.annotations.Reference
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.time.Duration
// TODO at some later point consider deleting CPKs blobs in the database by nulling their blob values and pass the null value to Kafka
@Suppress("TooManyFunctions")
@Component(service = [CpkWriteService::class])
class CpkWriteServiceImpl @Activate constructor(
@Reference(service = LifecycleCoordinatorFactory::class)
private val coordinatorFactory: LifecycleCoordinatorFactory,
@Reference(service = ConfigurationReadService::class)
private val configReadService: ConfigurationReadService,
@Reference(service = SubscriptionFactory::class)
private val subscriptionFactory: SubscriptionFactory,
@Reference(service = PublisherFactory::class)
private val publisherFactory: PublisherFactory,
@Reference(service = DbConnectionManager::class)
private val dbConnectionManager: DbConnectionManager
) : CpkWriteService, LifecycleEventHandler {
companion object {
val logger: Logger = LoggerFactory.getLogger(this::class.java.enclosingClass)
const val CPK_WRITE_GROUP = "cpk.writer"
const val CPK_WRITE_CLIENT = "$CPK_WRITE_GROUP.client"
const val CONFIG_HANDLE = "CONFIG_HANDLE"
const val REGISTRATION = "REGISTRATION"
}
private val coordinator = coordinatorFactory.createCoordinator<CpkWriteService>(this)
@VisibleForTesting
internal var timeout: Duration? = null
@VisibleForTesting
internal var timerEventIntervalMs: Long? = null
@VisibleForTesting
internal var cpkChecksumsCache: CpkChecksumsCache? = null
@VisibleForTesting
internal var cpkChunksPublisher: CpkChunksPublisher? = null
@VisibleForTesting
internal var cpkStorage: CpkStorage? = null
private var maxAllowedKafkaMsgSize: Int? = null
private val timerKey = CpkWriteServiceImpl::class.simpleName!!
/**
* Event loop
*/
override fun processEvent(event: LifecycleEvent, coordinator: LifecycleCoordinator) {
when (event) {
is StartEvent -> onStartEvent(coordinator)
is RegistrationStatusChangeEvent -> onRegistrationStatusChangeEvent(event, coordinator)
is ConfigChangedEvent -> onConfigChangedEvent(event, coordinator)
is ReconcileCpkEvent -> onReconcileCpkEvent(coordinator)
is StopEvent -> onStopEvent()
}
}
/**
* We depend on the [ConfigurationReadService] so we 'listen' to [RegistrationStatusChangeEvent]
* to tell us when it is ready so we can register ourselves to handle config updates.
*/
private fun onStartEvent(coordinator: LifecycleCoordinator) {
coordinator.createManagedResource(REGISTRATION) {
coordinator.followStatusChangesByName(
setOf(
LifecycleCoordinatorName.forComponent<ConfigurationReadService>(),
LifecycleCoordinatorName.forComponent<DbConnectionManager>()
)
)
}
}
/**
* If the thing(s) we depend on are up (only the [ConfigurationReadService]),
* then register `this` for config updates
*/
private fun onRegistrationStatusChangeEvent(
event: RegistrationStatusChangeEvent,
coordinator: LifecycleCoordinator
) {
if (event.status == LifecycleStatus.UP) {
coordinator.createManagedResource(CONFIG_HANDLE) {
configReadService.registerComponentForUpdates(
coordinator,
setOf(
BOOT_CONFIG,
MESSAGING_CONFIG,
RECONCILIATION_CONFIG,
)
)
}
coordinator.updateStatus(LifecycleStatus.UP)
scheduleNextReconciliationTask(coordinator)
} else {
coordinator.updateStatus(LifecycleStatus.DOWN)
closeResources()
}
}
/**
* We've received a config event that we care about, we can now write cpks
*/
private fun onConfigChangedEvent(event: ConfigChangedEvent, coordinator: LifecycleCoordinator) {
val messagingConfig = event.config.getConfig(MESSAGING_CONFIG)
val reconciliationConfig = event.config.getConfig(RECONCILIATION_CONFIG)
maxAllowedKafkaMsgSize = messagingConfig.getInt(MessagingConfig.MAX_ALLOWED_MSG_SIZE)
timeout = 20.seconds
timerEventIntervalMs = reconciliationConfig.getLong(RECONCILIATION_CPK_WRITE_INTERVAL_MS)
logger.info("CPK write reconciliation interval set to $timerEventIntervalMs ms.")
try {
createCpkChunksPublisher(messagingConfig)
} catch (e: Exception) {
closeResources()
coordinator.updateStatus(LifecycleStatus.DOWN)
return
}
createCpkChecksumsCache(messagingConfig)
createCpkStorage()
coordinator.updateStatus(LifecycleStatus.UP)
scheduleNextReconciliationTask(coordinator)
}
private fun onReconcileCpkEvent(coordinator: LifecycleCoordinator) {
try {
putMissingCpk()
} catch (e: Exception) {
logger.warn("CPK Reconciliation exception: $e")
}
scheduleNextReconciliationTask(coordinator)
}
private fun scheduleNextReconciliationTask(coordinator: LifecycleCoordinator) {
timerEventIntervalMs?.let { timerEventIntervalMs ->
logger.trace { "Registering new ${ReconcileCpkEvent::class.simpleName}" }
coordinator.setTimer(
timerKey,
timerEventIntervalMs
) { ReconcileCpkEvent(it) }
}
}
/**
* Close the registration.
*/
private fun onStopEvent() {
closeResources()
}
@VisibleForTesting
internal fun putMissingCpk() {
val cachedCpkIds = cpkChecksumsCache?.getCachedCpkIds() ?: run {
logger.info("CPK Checksums Cache is not set yet, therefore will run a full db to kafka reconciliation")
emptyList()
}
val cpkStorage =
this.cpkStorage ?: throw CordaRuntimeException("CPK Storage Service is not set")
val missingCpkIdsOnKafka = cpkStorage.getAllCpkFileIds(fileChecksumsToExclude = cachedCpkIds)
// Make sure we use the same CPK publisher for all CPK publishing.
this.cpkChunksPublisher?.let {
missingCpkIdsOnKafka
.forEach { cpkChecksum ->
// TODO probably replace the following logging with debug
logger.info("Putting missing CPK to Kafka: $cpkChecksum")
val cpkFile = cpkStorage.getCpkFileById(cpkChecksum)
it.chunkAndPublishCpk(cpkFile)
}
} ?: throw CordaRuntimeException("CPK Chunks Publisher service is not set")
}
private fun CpkChunksPublisher.chunkAndPublishCpk(cpkFile: CpkFile) {
logger.debug { "Publishing CPK ${cpkFile.fileChecksum}" }
val cpkChecksum = cpkFile.fileChecksum
val cpkData = cpkFile.data
val chunkWriter = maxAllowedKafkaMsgSize?.let {
ChunkWriterFactory.create(it)
} ?: throw CordaRuntimeException("maxAllowedKafkaMsgSize is not set")
chunkWriter.onChunk { chunk ->
val cpkChunkId = CpkChunkId(cpkChecksum.toAvro(), chunk.partNumber)
put(cpkChunkId, chunk)
}
chunkWriter.write(cpkChecksum.toFileName(), ByteArrayInputStream(cpkData))
}
override val isRunning: Boolean
get() = coordinator.isRunning
override fun start() {
logger.debug("CPK Write Service starting")
coordinator.start()
}
override fun stop() {
logger.debug("CPK Write Service stopping")
coordinator.stop()
closeResources()
}
private fun closeResources() {
coordinator.cancelTimer(timerKey)
cpkChecksumsCache?.close()
cpkChecksumsCache = null
cpkChunksPublisher?.close()
cpkChunksPublisher = null
}
private fun createCpkChecksumsCache(config: SmartConfig) {
cpkChecksumsCache?.close()
cpkChecksumsCache = CpkChecksumsCacheImpl(
subscriptionFactory,
SubscriptionConfig(CPK_WRITE_GROUP, VirtualNode.CPK_FILE_TOPIC),
config
).also { it.start() }
}
private fun createCpkChunksPublisher(config: SmartConfig) {
cpkChunksPublisher?.close()
val publisher = publisherFactory.createPublisher(
PublisherConfig(CPK_WRITE_CLIENT),
config
).also { it.start() }
cpkChunksPublisher = KafkaCpkChunksPublisher(publisher, timeout!!, VirtualNode.CPK_FILE_TOPIC)
}
private fun createCpkStorage() {
cpkStorage = DBCpkStorage(dbConnectionManager.getClusterEntityManagerFactory())
}
private data class ReconcileCpkEvent(override val key: String): TimerEvent
}
// Must not call SecureHash.toString() because it contains delimiter : that fails on Path creation.
// Therefore the file name will be the <hex string>.cpk.
private fun SecureHash.toFileName() = "${this.toHexString()}.cpk"
| 71 | null | 9 | 69 | d478e119ab288af663910f9a2df42a7a7b9f5bce | 11,719 | corda-runtime-os | Apache License 2.0 |
app/src/main/java/com/core/app/ui/screens/login/view/LoginFragment.kt | raxden | 165,669,612 | false | null | package com.core.app.ui.screens.login.view
import android.os.Bundle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.core.app.AppFragment
import com.core.app.databinding.LoginFragmentBinding
import com.core.app.ui.screens.login.LoginViewModel
class LoginFragment : AppFragment<LoginViewModel, LoginFragmentBinding>() {
override val viewModelClass: Class<LoginViewModel>
get() = LoginViewModel::class.java
companion object {
fun newInstance(bundle: Bundle?) = LoginFragment().apply {
arguments = bundle ?: Bundle()
}
}
override fun onViewModelAttached(owner: LifecycleOwner, viewModel: LoginViewModel) {}
} | 1 | null | 1 | 1 | 9ad3b3d2fffdaa7abdf567320e8d6d9f98a67746 | 700 | android-core | Apache License 2.0 |
kable-core/src/commonMain/kotlin/logs/Hex.kt | JuulLabs | 293,227,216 | false | {"Kotlin": 393319} | package com.juul.kable.logs
import com.juul.kable.toHexString
public val Hex: Logging.DataProcessor = Hex()
public class HexBuilder internal constructor() {
/** Separator between each byte in the hex representation of data. */
public var separator: String = " "
/** Configures if hex representation of data should be lower-case. */
public var lowerCase: Boolean = false
}
public fun Hex(init: HexBuilder.() -> Unit = {}): Logging.DataProcessor {
val config = HexBuilder().apply(init)
return Logging.DataProcessor { data ->
data.toHexString(separator = config.separator, lowerCase = config.lowerCase)
}
}
| 43 | Kotlin | 83 | 821 | 642d19bbebab0c80945767790212ceb5f2db1694 | 646 | kable | Apache License 2.0 |
benchmarks/src/commonMain/kotlin/OptimizedJsonGrammar.kt | h0tk3y | 96,618,996 | false | {"Kotlin": 171609} | package com.github.h0tk3y.betterParse.benchmark
import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.*
import com.github.h0tk3y.betterParse.lexer.*
import com.github.h0tk3y.betterParse.parser.*
class OptimizedJsonGrammar : Grammar<Any?>() {
private fun Char.isLetterOrDigit() =
(this in 'a'..'z') || (this in 'A'..'Z') || (this in '0'..'9')
private fun Char.isDigit() = this in '0'..'9'
private fun tokenIdent(text: String) = token { it, at ->
if (!it.startsWith(text, at)) return@token 0
if (at + text.length > it.length && it[at + text.length].isLetterOrDigit()) return@token 0
text.length
}
private fun tokenNumber() = token { it, at ->
var index = at
val maybeSign = it[index]
val sign = if (maybeSign == '+' || maybeSign == '-') {
index++
true
} else
false
val length = it.length
while (index < length && it[index].isDigit())
index++
if (index < length && it[index] == '.') { // decimal
index++
while (index < length && it[index].isDigit())
index++
}
if (index == at || (index == at + 1 && sign)) return@token 0
index - at
}
@Suppress("unused")
private val whiteSpace by token(ignored = true) { it, at ->
var index = at
val length = it.length
while (index < length && it[index].isWhitespace())
index++
index - at
}
/* the regex "[^\\"]*(\\["nrtbf\\][^\\"]*)*" matches:
* " – opening double quote,
* [^\\"]* – any number of not escaped characters, nor double quotes
* (
* \\["nrtbf\\] – backslash followed by special character (\", \n, \r, \\, etc.)
* [^\\"]* – and any number of non-special characters
* )* – repeating as a group any number of times
* " – closing double quote
*/
private val stringLiteral by token { it, at ->
var index = at
if (it[index++] != '"') return@token 0
val length = it.length
while (index < length && it[index] != '"') {
if (it[index] == '\\') { // quote
index++
}
index++
}
if (index == length) return@token 0 // unclosed string
index + 1 - at
}
private val comma by literalToken(",")
private val colon by literalToken(":")
private val openingBrace by literalToken("{")
private val closingBrace by literalToken("}")
private val openingBracket by literalToken("[")
private val closingBracket by literalToken("]")
private val nullToken by tokenIdent("null")
private val trueToken by tokenIdent("true")
private val falseToken by tokenIdent("false")
private val num by tokenNumber()
private val jsonNull: Parser<Any?> by nullToken asJust null
private val jsonBool: Parser<Boolean> by (trueToken asJust true) or (falseToken asJust false)
private val string: Parser<String> by (stringLiteral use { input.substring(offset + 1, offset + length - 1) })
private val number: Parser<Double> by num use { text.toDouble() }
private val jsonPrimitiveValue: Parser<Any?> by jsonNull or jsonBool or string or number
private val jsonObject: Parser<Map<String, Any?>> by
(-openingBrace * separated(string * -colon * this, comma, true) * -closingBrace)
.map { mutableMapOf<String, Any?>().apply { it.terms.forEach { put(it.t1, it.t2) } } }
private val jsonArray: Parser<List<Any?>> by
(-openingBracket * separated(this, comma, true) * -closingBracket)
.map { it.terms }
override val rootParser by jsonPrimitiveValue or jsonObject or jsonArray
} | 37 | Kotlin | 41 | 391 | af4599c04f84463a4b708e7e1385217b41ae7b9e | 3,818 | better-parse | Apache License 2.0 |
ksrpc/src/jvmTest/kotlin/OverlappingTest.kt | Monkopedia | 305,151,870 | false | null | /*
* Copyright 2021 Jason Monk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.monkopedia.ksrpc
import kotlin.test.assertEquals
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
abstract class OverlappingTest() : OverlappingTestBase()
// Hacks for firstCall usage :/.
abstract class OverlappingTestBase(
var firstCall: CompletableDeferred<String> = CompletableDeferred<String>()
) : RpcFunctionalityTest(
serializedChannel = {
// Waits for the second call to come in before the first finishes.
val service: TestInterface = object : TestInterface {
var secondCall: CompletableDeferred<String>? = null
override suspend fun rpc(u: Pair<String, String>): String {
if (secondCall == null) {
firstCall.complete(u.second)
secondCall = CompletableDeferred()
return "${u.first} ${secondCall?.await()}"
} else {
secondCall?.complete(u.second)
return "${u.first} ${u.second}"
}
}
}
service.serialized(ksrpcEnvironment { })
},
verifyOnChannel = { serializedChannel ->
val stub = serializedChannel.toStub<TestInterface>()
val finish = GlobalScope.async(Dispatchers.IO) {
assertEquals("Hello second", stub.rpc("Hello" to "first"))
}
assertEquals("first", firstCall.await())
assertEquals("Hello second", stub.rpc("Hello" to "second"))
finish.await()
}
)
| 0 | Kotlin | 0 | 6 | a48494a7111736fecce7a6a4d739d453d61984d1 | 2,175 | ksrpc | Apache License 2.0 |
app/src/main/java/my/dictionary/free/domain/usecases/users/GetUpdateUsersUseCase.kt | viacheslavtitov | 605,498,191 | false | {"Kotlin": 496868} | package my.dictionary.free.domain.usecases.users
import my.dictionary.free.data.models.users.UsersTable
import my.dictionary.free.data.repositories.DatabaseRepository
import my.dictionary.free.domain.models.users.User
import my.dictionary.free.domain.utils.PreferenceUtils
import javax.inject.Inject
class GetUpdateUsersUseCase @Inject constructor(private val databaseRepository: DatabaseRepository, private val preferenceUtils: PreferenceUtils) {
suspend fun insertOrUpdateUser(user: User): Boolean {
return databaseRepository.insertOrUpdateUser(
user = UsersTable(
_id = user._id,
name = user.name,
email = user.email,
providerId = user.providerId,
uid = user.uid
), preferenceUtils
)
}
} | 3 | Kotlin | 0 | 0 | 3800c83f25106a8adb381e609a6dda9f87b5d1ca | 822 | Easy-Dictionary-Android | MIT License |
src/test/kotlin/no/nav/personbruker/dittnav/brukernotifikasjonbestiller/done/DoneInputEventServiceTest.kt | navikt | 331,545,066 | false | null | package no.nav.personbruker.dittnav.brukernotifikasjonbestiller.done
import io.mockk.*
import kotlinx.coroutines.runBlocking
import no.nav.brukernotifikasjon.schemas.input.DoneInput
import no.nav.brukernotifikasjon.schemas.input.NokkelInput
import no.nav.brukernotifikasjon.schemas.internal.DoneIntern
import no.nav.brukernotifikasjon.schemas.internal.NokkelIntern
import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.*
import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.objectmother.ConsumerRecordsObjectMother
import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.metrics.EventMetricsSession
import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.metrics.MetricsCollector
import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.nokkel.NokkelTestData
import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.oppgave.AvroOppgaveInputObjectMother
import org.apache.kafka.clients.consumer.ConsumerRecords
import org.junit.jupiter.api.Test
import java.util.*
internal class DoneInputEventServiceTest {
private val metricsCollector = mockk<MetricsCollector>(relaxed = true)
private val metricsSession = mockk<EventMetricsSession>(relaxed = true)
private val topic = "topic-done-test"
private val handleDuplicateEvents = mockk<HandleDuplicateDoneEvents>(relaxed = true)
private val eventDispatcher = mockk<EventDispatcher<DoneIntern>>(relaxed = true)
private val internalEvents = AvroDoneInternObjectMother.giveMeANumberOfInternalDoneEvents(2, "systembruker", "eventId", "fodselsnummer")
private val doneEventService = DoneInputEventService(
metricsCollector = metricsCollector,
handleDuplicateEvents = handleDuplicateEvents,
eventDispatcher = eventDispatcher,
doneRapidProducer = mockk()
)
private val eventId = UUID.randomUUID().toString()
@Test
fun `skal skrive til internal-topic hvis alt er ok`() {
val externalNokkel = NokkelTestData.createNokkelInputWithEventId(eventId)
val externalDone = AvroDoneInputObjectMother.createDoneInput()
val externalEvents = ConsumerRecordsObjectMother.createInputConsumerRecords(externalNokkel, externalDone, topic)
coEvery { handleDuplicateEvents.checkForDuplicateEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) } returns DuplicateCheckResult(internalEvents, emptyList())
coEvery { eventDispatcher.dispatchValidAndProblematicEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>(), any()) } returns Unit
coEvery { eventDispatcher.dispatchValidEventsOnly(any()) } returns Unit
coEvery { eventDispatcher.dispatchProblematicEventsOnly(any()) } returns Unit
val slot = slot<suspend EventMetricsSession.() -> Unit>()
coEvery { metricsCollector.recordMetrics(any(), capture(slot)) } coAnswers {
slot.captured.invoke(metricsSession)
}
runBlocking {
doneEventService.processEvents(externalEvents)
}
coVerify(exactly = 1) { metricsSession.countSuccessfulEventForProducer(any()) }
coVerify(exactly = 1) { handleDuplicateEvents.checkForDuplicateEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidAndProblematicEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>(), any()) }
coVerify(exactly = 1) { eventDispatcher.dispatchValidEventsOnly(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 0) { eventDispatcher.dispatchProblematicEventsOnly(any()) }
}
@Test
fun `skal ikke skrive til topic hvis nokkel er null`() {
val externalNullNokkel = null
val externalDone = AvroDoneInputObjectMother.createDoneInput()
val externalEvents = ConsumerRecordsObjectMother.createInputConsumerRecords(externalNullNokkel, externalDone, topic)
val slot = slot<suspend EventMetricsSession.() -> Unit>()
coEvery { metricsCollector.recordMetrics(any(), capture(slot)) } coAnswers {
slot.captured.invoke(metricsSession)
}
runBlocking {
doneEventService.processEvents(externalEvents)
}
coVerify(exactly = 1) { metricsSession.countNokkelWasNull() }
coVerify(exactly = 0) { handleDuplicateEvents.checkForDuplicateEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidAndProblematicEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>(), any()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidEventsOnly(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 0) { eventDispatcher.dispatchProblematicEventsOnly(any()) }
}
@Test
fun `skal skrive til feilrespons-topic hvis eventet har en valideringsfeil`() {
val externalNokkel = NokkelTestData.createNokkelInputWithEventIdAndFnr(eventId, "123456789123456")
val externalDoneWithTooLongText = AvroDoneInputObjectMother.createDoneInput()
val externalEvents = ConsumerRecordsObjectMother.createInputConsumerRecords(externalNokkel, externalDoneWithTooLongText, topic)
val slot = slot<suspend EventMetricsSession.() -> Unit>()
coEvery { metricsCollector.recordMetrics(any(), capture(slot)) } coAnswers {
slot.captured.invoke(metricsSession)
}
runBlocking {
doneEventService.processEvents(externalEvents)
}
coVerify(exactly = 0) { handleDuplicateEvents.checkForDuplicateEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidAndProblematicEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>(), any()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidEventsOnly(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 1) { eventDispatcher.dispatchProblematicEventsOnly(any()) }
coVerify(exactly = 1) { metricsSession.countFailedEventForProducer(any()) }
}
@Test
fun `skal skrive til feilrespons-topic hvis vi faar en uventet feil under transformering`() {
val externalNokkel = NokkelTestData.createNokkelInputWithEventId(eventId)
val externalUnexpectedDone = mockk<DoneInput>()
val externalEvents = ConsumerRecordsObjectMother.createInputConsumerRecords(externalNokkel, externalUnexpectedDone, topic)
val slot = slot<suspend EventMetricsSession.() -> Unit>()
coEvery { metricsCollector.recordMetrics(any(), capture(slot)) } coAnswers {
slot.captured.invoke(metricsSession)
}
runBlocking {
doneEventService.processEvents(externalEvents)
}
coVerify(exactly = 0) { handleDuplicateEvents.checkForDuplicateEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidAndProblematicEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>(), any()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidEventsOnly(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 1) { eventDispatcher.dispatchProblematicEventsOnly(any()) }
coVerify(exactly = 1) { metricsSession.countFailedEventForProducer(any()) }
}
@Test
fun `skal skrive til feilrespons-topic hvis er plassert event med feil type paa topic`() {
val externalNokkel = NokkelTestData.createNokkelInputWithEventId(eventId)
val externalDone = AvroOppgaveInputObjectMother.createOppgaveInput()
val externalMalplacedEvents = ConsumerRecordsObjectMother.createInputConsumerRecords(externalNokkel, externalDone, topic)
val externalEvents = externalMalplacedEvents as ConsumerRecords<NokkelInput, DoneInput>
val slot = slot<suspend EventMetricsSession.() -> Unit>()
coEvery { metricsCollector.recordMetrics(any(), capture(slot)) } coAnswers {
slot.captured.invoke(metricsSession)
}
runBlocking {
doneEventService.processEvents(externalEvents)
}
coVerify(exactly = 0) { handleDuplicateEvents.checkForDuplicateEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidAndProblematicEvents(any<MutableList<Pair<NokkelIntern, DoneIntern>>>(), any()) }
coVerify(exactly = 0) { eventDispatcher.dispatchValidEventsOnly(any<MutableList<Pair<NokkelIntern, DoneIntern>>>()) }
coVerify(exactly = 1) { eventDispatcher.dispatchProblematicEventsOnly(any()) }
coVerify(exactly = 1) { metricsSession.countFailedEventForProducer(any()) }
}
}
| 1 | Kotlin | 0 | 0 | 9df0ace75939834947d531a342f9153d9ad44633 | 8,713 | dittnav-brukernotifikasjonbestiller | MIT License |
app/src/main/java/com/perol/asdpl/pixivez/base/MaterialDialogs.kt | ultranity | 258,955,010 | false | {"Gradle Kotlin DSL": 4, "Java Properties": 2, "Shell": 1, "Text": 32, "Ignore List": 3, "Batchfile": 1, "Markdown": 9, "TOML": 1, "YAML": 2, "Proguard": 2, "JSON": 4, "Kotlin": 224, "XML": 164, "CSS": 3, "Java": 20, "JavaScript": 5, "HTML": 1, "robots.txt": 1} | package com.perol.asdpl.pixivez.base
import android.content.Context
import android.content.DialogInterface
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AlertDialog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.perol.asdpl.pixivez.R
open class MaterialDialogs(context: Context) : MaterialAlertDialogBuilder(context) {
private val showListeners = mutableListOf<(AlertDialog) -> Unit>()
fun onShow(func: (AlertDialog) -> Unit) {
showListeners.add(func)
}
override fun show(): AlertDialog {
val dialog = create()
dialog.show()
showListeners.forEach {
it(dialog)
}
return dialog
}
inline fun create(block: MaterialDialogs.() -> Unit): AlertDialog {
block()
return create()
}
inline fun show(block: MaterialDialogs.() -> Unit): AlertDialog {
block()
return show()
}
fun <T : MaterialAlertDialogBuilder> T.confirmButton(
textId: Int = android.R.string.ok,
listener: DialogInterface.OnClickListener? = null
): MaterialAlertDialogBuilder {
return setPositiveButton(textId, listener)
}
fun <T : MaterialAlertDialogBuilder> T.cancelButton(
textId: Int = android.R.string.cancel,
listener: DialogInterface.OnClickListener? = null
): MaterialAlertDialogBuilder {
return setNegativeButton(textId, listener)
}
}
fun <T : MaterialAlertDialogBuilder> T.confirmButton(
textId: Int = android.R.string.ok,
listener: DialogInterface.OnClickListener? = null
): MaterialAlertDialogBuilder {
return setPositiveButton(textId, listener)
}
fun <T : MaterialAlertDialogBuilder> T.cancelButton(
textId: Int = android.R.string.cancel,
listener: DialogInterface.OnClickListener? = null
): MaterialAlertDialogBuilder {
return setNegativeButton(textId, listener)
}
fun MaterialDialogs.setInput(showIME: Boolean = false, config: TextInputLayout.() -> Unit) {
setView(R.layout.dialog_item_edit_text)
onShow {
val layout = getInputLayout(it)
layout.config()
if (showIME) {
layout.editText?.let { edit ->
edit.post {
edit.requestFocus()
edit.performClick()
val imm =
context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val shown = imm.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT)
shown//TODO: ime not showing
}
}
}
}
}
fun MaterialDialogs.getInputLayout(dialog: DialogInterface): TextInputLayout {
return (dialog as AlertDialog).findViewById(R.id.text_input_layout)!!
}
fun MaterialDialogs.getInputField(dialog: DialogInterface): TextInputEditText {
return (dialog as AlertDialog).findViewById(R.id.edit_text)!!
} | 6 | Kotlin | 33 | 692 | d5caf81746e4f16a1af64d45490a358fd19aec1a | 3,073 | Pix-EzViewer | MIT License |
src/test/java/quix/hosted/HostedPaymentChargeServiceTest.kt | DeveloperCGP | 813,112,518 | false | {"Gradle Kotlin DSL": 2, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 7, "Java Properties": 1, "Kotlin": 22, "Java": 216, "HTML": 2} | package quix.hosted
import com.comerciaglobalpayments.javaPaymentSDK.adapters.HostedQuixPaymentAdapter
import com.comerciaglobalpayments.javaPaymentSDK.adapters.NetworkAdapter
import com.comerciaglobalpayments.javaPaymentSDK.callbacks.RequestListener
import com.comerciaglobalpayments.javaPaymentSDK.callbacks.ResponseListener
import com.comerciaglobalpayments.javaPaymentSDK.enums.*
import com.comerciaglobalpayments.javaPaymentSDK.exceptions.InvalidFieldException
import com.comerciaglobalpayments.javaPaymentSDK.exceptions.MissingFieldException
import com.comerciaglobalpayments.javaPaymentSDK.models.Credentials
import com.comerciaglobalpayments.javaPaymentSDK.models.quix_models.QuixAddress
import com.comerciaglobalpayments.javaPaymentSDK.models.quix_models.QuixBilling
import com.comerciaglobalpayments.javaPaymentSDK.models.quix_models.quix_service.QuixArticleService
import com.comerciaglobalpayments.javaPaymentSDK.models.quix_models.quix_service.QuixCartService
import com.comerciaglobalpayments.javaPaymentSDK.models.quix_models.quix_service.QuixItemCartItemService
import com.comerciaglobalpayments.javaPaymentSDK.models.quix_models.quix_service.QuixServicePaySolExtendedData
import com.comerciaglobalpayments.javaPaymentSDK.models.requests.quix_hosted.HostedQuixService
import com.comerciaglobalpayments.javaPaymentSDK.utils.SecurityUtils
import io.mockk.*
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class HostedPaymentChargeServiceTest {
@Test
fun successHostedServiceNotification() {
mockkStatic(SecurityUtils::class)
every { SecurityUtils.generateIV() } returns ByteArray(16) { 1 }
every { SecurityUtils.hash256(any()) } answers { callOriginal() }
every { SecurityUtils.base64Encode(any()) } answers { callOriginal() }
every { SecurityUtils.applyAESPadding(any()) } answers { callOriginal() }
every { SecurityUtils.cbcEncryption(any(), any(), any(), any()) } answers { callOriginal() }
mockkConstructor(NetworkAdapter::class, recordPrivateCalls = true)
every {
anyConstructed<NetworkAdapter>()["sendRequest"](
any<HashMap<String, String>>(),
any<HashMap<String, String>>(),
any<RequestBody>(),
any<String>(),
any<RequestListener>()
)
} answers { }
val mockedResponseListener = mockk<ResponseListener>()
every { mockedResponseListener.onError(any(), any()) } just Runs
every { mockedResponseListener.onRedirectionURLReceived(any()) } just Runs
every { mockedResponseListener.onResponseReceived(any(), any(), any()) } just Runs
val credentials = Credentials()
credentials.merchantPass = "<PASSWORD>"
credentials.merchantKey = "11111111-1111-1111-1111-111111111111"
credentials.merchantId = "111222"
credentials.environment = Environment.STAGING
credentials.productId = "1112220001"
credentials.apiVersion = 5
val hostedQuixService = HostedQuixService()
hostedQuixService.amount = "99.0"
hostedQuixService.customerId = "903"
hostedQuixService.statusURL = "https://test.com/paymentNotification"
hostedQuixService.cancelURL = "https://test.com/cancel"
hostedQuixService.errorURL = "https://test.com/error"
hostedQuixService.successURL = "https://test.com/success"
hostedQuixService.awaitingURL = "https://test.com/awaiting"
hostedQuixService.customerEmail = "<EMAIL>"
hostedQuixService.customerNationalId = "99999999RR"
hostedQuixService.dob = "01-12-1999"
hostedQuixService.firstName = "Name"
hostedQuixService.lastName = "<NAME>"
hostedQuixService.merchantTransactionId = "12345678"
hostedQuixService.ipAddress = "0.0.0.0"
val quixArticleService = QuixArticleService()
quixArticleService.name = "Nombre del servicio 2"
quixArticleService.reference = "4912345678903"
quixArticleService.endDate = "2024-12-31T23:59:59+01:00"
quixArticleService.unitPriceWithTax = 99.0
quixArticleService.category = Category.digital
val quixItemCartItemService = QuixItemCartItemService()
quixItemCartItemService.article = quixArticleService
quixItemCartItemService.units = 1
quixItemCartItemService.isAutoShipping = true
quixItemCartItemService.totalPriceWithTax = 99.0
val items: MutableList<QuixItemCartItemService> = java.util.ArrayList()
items.add(quixItemCartItemService)
val quixCartService = QuixCartService()
quixCartService.currency = Currency.EUR
quixCartService.items = items
quixCartService.totalPriceWithTax = 99.0
val quixAddress = QuixAddress()
quixAddress.city = "Barcelona"
quixAddress.setCountry(CountryCode.ES)
quixAddress.streetAddress = "Nombre de la vía y nº"
quixAddress.postalCode = "28003"
val quixBilling = QuixBilling()
quixBilling.address = quixAddress
quixBilling.firstName = "Nombre"
quixBilling.lastName = "Apellido"
val quixServicePaySolExtendedData = QuixServicePaySolExtendedData()
quixServicePaySolExtendedData.cart = quixCartService
quixServicePaySolExtendedData.billing = quixBilling
quixServicePaySolExtendedData.product = "instalments"
hostedQuixService.paySolExtendedData = quixServicePaySolExtendedData
val hostedQuixPaymentAdapter = HostedQuixPaymentAdapter(credentials)
hostedQuixPaymentAdapter.sendHostedQuixServiceRequest(hostedQuixService, mockedResponseListener)
val headersSlot = slot<Map<String, String>>()
val queryParameterSlot = slot<Map<String, String>>()
val requestBodySlot = slot<RequestBody>()
val urlSlot = slot<String>()
val requestListenerSlot = slot<RequestListener>()
verify {
anyConstructed<NetworkAdapter>()["sendRequest"](
capture(headersSlot),
capture(queryParameterSlot),
capture(requestBodySlot),
capture(urlSlot),
capture(requestListenerSlot)
)
}
assertEquals(3, headersSlot.captured.size)
assertEquals("5", headersSlot.captured["apiVersion"])
assertEquals("CBC", headersSlot.captured["encryptionMode"])
assertEquals("AQEBAQEBAQEBAQEBAQEBAQ==", headersSlot.captured["iv"])
assertEquals(3, queryParameterSlot.captured.size)
assertEquals("111222", queryParameterSlot.captured["merchantId"])
assertEquals(
"pDH/U+/gbuzXdYp84aiQKsVwdo0OluLSE7iid4fDTDsOp3Iz5PMaVkId+H/okm/59Slik6eoVuhf9S0X7utcyiYp1zqBuvvjPWiO0Nmne1/ZLwf2liuTEo6jRVTCGjokuW3KnOMHbgeoHjg5TaK6fzocze2OWBs55Luc+A4onL6/qm7Lt8dAhWkUjIcWzIE5KXyKPm4Icm16zGh5wmDou/WEtJVEedu7LsO1HfOvJro6s39Ya+e8RAaNEoQZ64f4J8kDU9KYEm6aQZrOEp/+n1wI2Vc7u/6Y/VGO2ye7649smVWFsPhgGe9L8i5wzQRI4xpVpKLKQKe2Opx7fG7FZVgy1RZ8Ye4t<KEY>
queryParameterSlot.captured["encrypted"]
)
assertEquals(
"43eec1a8967c92b331d001d4e8ce0c232e9fedf92c4dd41f68896c2a6e238a91",
queryParameterSlot.captured["integrityCheck"]
)
assertEquals(Endpoints.HOSTED_ENDPOINT.getEndpoint(Environment.STAGING), urlSlot.captured)
val mockedResponseBody = mockk<ResponseBody>()
every { mockedResponseBody.string() } returns "http://test.com"
requestListenerSlot.captured.onResponse(200, mockedResponseBody)
val redirectionUrlSlot = slot<String>()
verify {
mockedResponseListener.onRedirectionURLReceived(
capture(redirectionUrlSlot)
)
}
verify(exactly = 0) {
mockedResponseListener.onResponseReceived(any(), any(), any())
mockedResponseListener.onError(any(), any())
}
assertEquals("http://test.com", redirectionUrlSlot.captured)
}
@Test
fun failMissingParameterHosted() {
mockkStatic(SecurityUtils::class)
every { SecurityUtils.generateIV() } returns ByteArray(16) { 1 }
every { SecurityUtils.hash256(any()) } answers { callOriginal() }
every { SecurityUtils.base64Encode(any()) } answers { callOriginal() }
every { SecurityUtils.applyAESPadding(any()) } answers { callOriginal() }
every { SecurityUtils.cbcEncryption(any(), any(), any(), any()) } answers { callOriginal() }
mockkConstructor(NetworkAdapter::class, recordPrivateCalls = true)
every {
anyConstructed<NetworkAdapter>()["sendRequest"](
any<HashMap<String, String>>(),
any<HashMap<String, String>>(),
any<RequestBody>(),
any<String>(),
any<RequestListener>()
)
} answers { }
val mockedResponseListener = mockk<ResponseListener>();
every { mockedResponseListener.onError(any(), any()) } just Runs
every { mockedResponseListener.onRedirectionURLReceived(any()) } just Runs
every { mockedResponseListener.onResponseReceived(any(), any(), any()) } just Runs
val credentials = Credentials()
credentials.merchantPass = "<PASSWORD>"
credentials.merchantKey = "11111111-1111-1111-1111-111111111111"
credentials.merchantId = "111222"
credentials.environment = Environment.STAGING
credentials.productId = "1112220001"
credentials.apiVersion = 5
val hostedQuixService = HostedQuixService()
hostedQuixService.amount = "99.0"
hostedQuixService.customerId = "903"
hostedQuixService.cancelURL = "https://test.com/cancel"
hostedQuixService.errorURL = "https://test.com/error"
hostedQuixService.successURL = "https://test.com/success"
hostedQuixService.awaitingURL = "https://test.com/awaiting"
hostedQuixService.customerEmail = "<EMAIL>"
hostedQuixService.customerNationalId = "99999999RR"
hostedQuixService.dob = "01-12-1999"
hostedQuixService.firstName = "Name"
hostedQuixService.lastName = "<NAME>"
hostedQuixService.merchantTransactionId = "12345678"
val quixArticleService = QuixArticleService()
quixArticleService.name = "Nombre del servicio 2"
quixArticleService.reference = "4912345678903"
quixArticleService.endDate = "2024-12-31T23:59:59+01:00"
quixArticleService.unitPriceWithTax = 99.0
quixArticleService.category = Category.digital
val quixItemCartItemService = QuixItemCartItemService()
quixItemCartItemService.article = quixArticleService
quixItemCartItemService.units = 1
quixItemCartItemService.isAutoShipping = true
quixItemCartItemService.totalPriceWithTax = 99.0
val items: MutableList<QuixItemCartItemService> = java.util.ArrayList()
items.add(quixItemCartItemService)
val quixCartService = QuixCartService()
quixCartService.currency = Currency.EUR
quixCartService.items = items
quixCartService.totalPriceWithTax = 99.0
val quixAddress = QuixAddress()
quixAddress.city = "Barcelona"
quixAddress.setCountry(CountryCode.ES)
quixAddress.streetAddress = "Nombre de la vía y nº"
quixAddress.postalCode = "28003"
val quixBilling = QuixBilling()
quixBilling.address = quixAddress
quixBilling.firstName = "Nombre"
quixBilling.lastName = "Apellido"
val quixServicePaySolExtendedData = QuixServicePaySolExtendedData()
quixServicePaySolExtendedData.cart = quixCartService
quixServicePaySolExtendedData.billing = quixBilling
quixServicePaySolExtendedData.product = "instalments"
hostedQuixService.paySolExtendedData = quixServicePaySolExtendedData
val hostedQuixPaymentAdapter = HostedQuixPaymentAdapter(credentials)
val exception = assertThrows<MissingFieldException> {
hostedQuixPaymentAdapter.sendHostedQuixServiceRequest(hostedQuixService, mockedResponseListener)
}
assertEquals("Missing statusURL", exception.message)
}
@Test
fun failInvalidAmountHosted() {
mockkStatic(SecurityUtils::class)
every { SecurityUtils.generateIV() } returns ByteArray(16) { 1 }
every { SecurityUtils.hash256(any()) } answers { callOriginal() }
every { SecurityUtils.base64Encode(any()) } answers { callOriginal() }
every { SecurityUtils.applyAESPadding(any()) } answers { callOriginal() }
every { SecurityUtils.cbcEncryption(any(), any(), any(), any()) } answers { callOriginal() }
mockkConstructor(NetworkAdapter::class, recordPrivateCalls = true)
every {
anyConstructed<NetworkAdapter>()["sendRequest"](
any<HashMap<String, String>>(),
any<HashMap<String, String>>(),
any<RequestBody>(),
any<String>(),
any<RequestListener>()
)
} answers { }
val mockedResponseListener = mockk<ResponseListener>();
every { mockedResponseListener.onError(any(), any()) } just Runs
every { mockedResponseListener.onRedirectionURLReceived(any()) } just Runs
every { mockedResponseListener.onResponseReceived(any(), any(), any()) } just Runs
val credentials = Credentials()
credentials.merchantPass = "<PASSWORD>"
credentials.merchantKey = "11111111-1111-1111-1111-111111111111"
credentials.merchantId = "111222"
credentials.environment = Environment.STAGING
credentials.productId = "1112220001"
credentials.apiVersion = 5
val hostedQuixService = HostedQuixService()
val exception = assertThrows<InvalidFieldException> {
hostedQuixService.amount = "99,1123"
}
assertEquals("amount: Should Follow Format #.#### And Be Between 0 And 1000000", exception.message)
}
} | 0 | Java | 0 | 0 | 35bd36e768f9cadafcd325d4b0aa8f9ea300fe92 | 14,221 | Java-SDK | MIT License |
src/main/kotlin/se/olander/categories/dto/ParticipantStatus.kt | simonolander | 96,010,392 | false | {"Java": 169134, "CSS": 94970, "HTML": 54634, "JavaScript": 40796, "Kotlin": 33748, "Shell": 176} | package se.olander.categories.dto
object ParticipantStatus {
val WAITING = 0
val ANSWERING = 1
val BANNED = 2
val ELIMINATED = 3
val WINNER = 4
fun translate(status: Int?): String {
return when (status) {
WAITING -> "Waiting"
ANSWERING -> "Answering"
BANNED -> "Banned"
ELIMINATED -> "Eliminated"
WINNER -> "Winner"
else -> "Unknown"
}
}
}
| 1 | null | 1 | 1 | 61618a6b5b644e7f65933afc442d2e1cfc736d56 | 458 | categories | MIT License |
skd_chips/src/main/java/com/artlite/skd/chips/ui/abs/AbsActivity.kt | dlernatovich | 696,519,433 | false | {"Kotlin": 68684} | package com.artlite.skd.chips.ui.abs
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.artlite.skd.chips.core.SdkChips
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Base activity class.
*/
abstract class AbsActivity(@LayoutRes private val layout: Int): AppCompatActivity() {
/** Handler for thread execution. */
private val mainHandler = Handler(Looper.getMainLooper())
/**
* Create activity functional.
* @param bundle Bundle? instance.
*/
override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
setContentView(layout)
this.hideActionBar()
this.main { onActivityCreated(bundle) }
}
/**
* On Destroy functional.
*/
override fun onDestroy() {
super.onDestroy()
this.onActivityDestroyed()
}
/**
* Method which provide the activity created functional.
* @param bundle Bundle? instance.
*/
abstract fun onActivityCreated(bundle: Bundle?)
/**
* Method which provide the action when activity destroyed.
*/
abstract fun onActivityDestroyed()
/**
* Method which provide the execute functional.
* @param background thread action.
* @param main thread action.
*/
protected fun execute(background: () -> Unit, main: () -> Unit) {
this.lifecycleScope.launch(Dispatchers.IO) {
background()
withContext(Dispatchers.Main) { main() }
}
}
/**
* Method which provide the post functional to main thread.
* @param delay Long value.
* @param action Function1<[@kotlin.ParameterName] Boolean, Unit>
* @return Boolean
*/
protected fun main(delay: Long = 100, action: () -> Unit) {
this.lifecycleScope.launch(Dispatchers.IO) {
delay(delay)
withContext(Dispatchers.Main) { action() }
}
}
/**
* Method which provide to play haptic.
*/
protected fun playHaptic() = SdkChips.Managers.haptic.playHaptic()
/** Hide action bar functionality. */
fun hideActionBar() {
if (this.actionBar != null) this.actionBar?.hide() else this.supportActionBar?.hide()
}
} | 0 | Kotlin | 0 | 0 | 843f6876fec50d5f4e72c64fd4ad07f7c5368232 | 2,444 | SdkAndroidChips | Apache License 2.0 |
data/src/main/java/com/example/data/network/mapper/FlightsAvailabilityEntityToFlightOptionsMapper.kt | llOldmenll | 338,361,910 | false | {"Kotlin": 119152} | package com.example.data.network.mapper
import com.example.data.entity.flight.FareEntity
import com.example.data.entity.flight.FlightsAvailabilityEntity
import com.example.data.entity.flight.TripEntity
import com.example.domain.entity.flight.FlightOption
import com.example.domain.entity.flight.FlightOptions
import com.example.domain.mapper.Mapper
import com.example.domain.utils.toShortString
import kotlin.math.roundToInt
class FlightsAvailabilityEntityToFlightOptionsMapper :
Mapper<FlightsAvailabilityEntity, FlightOptions> {
override fun map(from: FlightsAvailabilityEntity): FlightOptions {
val currency = from.currency ?: ""
val flightOptionsList = mutableListOf<FlightOption>()
from.trips?.forEach { flightOptionsList.addAll(provideFlightOptions(currency, it)) }
return FlightOptions(flightOptionsList)
}
private fun provideFlightOptions(currency: String, trip: TripEntity): List<FlightOption> {
val flightOptionsList = mutableListOf<FlightOption>()
var farePrice = 0.0
var discountInPercent = 0
trip.dates?.forEach { flightDate ->
flightDate.flights?.forEach { flightOption ->
updateFarePriceAndDiscount(
flightOption.regularFare?.fares ?: listOf(),
{ farePrice = it }, { discountInPercent = it }
)
flightOptionsList.add(
FlightOption(
flightOption.flightNumber ?: "",
provideOrigin(trip),
provideDestination(trip),
flightOption.time?.get(0) ?: flightDate.dateOut ?: "",
flightOption.time?.get(1) ?: "",
flightOption.duration ?: "",
flightOption.regularFare?.fareClass ?: "",
farePrice,
"${farePrice.toShortString()} $currency",
discountInPercent.toByte(),
flightOption.infantsLeft ?: 0
)
)
}
}
return flightOptionsList
}
private fun updateFarePriceAndDiscount(
fare: List<FareEntity>,
updateFarePrice: (Double) -> Unit,
updateDiscount: (Int) -> Unit,
) {
var totalPublishedFare = 0.0
var totalDiscountAmount = 0.0
fare.forEach {
totalPublishedFare += (it.publishedFare ?: 0.0) * (it.count ?: 1)
totalDiscountAmount += (it.discountAmount ?: 0.0) * (it.count ?: 1)
}
updateFarePrice(totalPublishedFare - totalDiscountAmount)
updateDiscount((totalDiscountAmount * 100 / totalPublishedFare).roundToInt())
}
private fun provideOrigin(trip: TripEntity): String = "${trip.originName} (${trip.origin})"
private fun provideDestination(trip: TripEntity): String =
"${trip.destinationName} (${trip.destination})"
} | 0 | Kotlin | 0 | 0 | 14a0cf567713db9731a9464b8cf1edf1c1303f92 | 2,982 | RIBsApp | Apache License 2.0 |
src/test/kotlin/org/valkyrienskies/core/api/ShipApiTest.kt | ValkyrienSkies | 329,044,944 | false | null | package org.valkyrienskies.core.api
import com.fasterxml.jackson.annotation.JsonIgnore
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.valkyrienskies.core.VSRandomUtils
import org.valkyrienskies.core.game.ships.ShipData
import org.valkyrienskies.core.game.ships.ShipObjectServer
import org.valkyrienskies.core.util.serialization.VSJacksonUtil
// Yes its a very simple test, but if somebody ever dares to break it we will know
internal class ShipApiTest {
@Test
fun testShipDataAbstraction() {
val shipData = VSRandomUtils.randomShipData()
abstractShipSaver(shipData)
abstractShipUser(shipData, false)
}
@Test
fun testShipObjectAbstraction() {
val shipObject = ShipObjectServer(VSRandomUtils.randomShipData())
abstractShipSaver(shipObject)
abstractShipUser(shipObject, true)
}
@Test
fun testAttachmentInterfaces() {
val shipData = VSRandomUtils.randomShipData()
val user = TestShipUser()
shipData.saveAttachment(user)
Assertions.assertEquals(user.ship, shipData)
Assertions.assertEquals(user, shipData.getAttachment(TestShipUser::class.java))
val shipDataSerialized = VSJacksonUtil.defaultMapper.writeValueAsBytes(shipData)
val shipDataDeserialized = VSJacksonUtil.defaultMapper.readValue(shipDataSerialized, ShipData::class.java)
Assertions.assertNotNull(shipData.getAttachment(TestShipUser::class.java))
Assertions.assertEquals(shipData.getAttachment(TestShipUser::class.java)!!.ship, shipDataDeserialized)
}
fun abstractShipSaver(ship: Ship) {
ship.saveAttachment<Int>(5)
ship.setAttachment<Float>(3f)
}
fun abstractShipUser(ship: Ship, checkFloat: Boolean) {
Assertions.assertEquals(ship.getAttachment<Int>(), 5)
if (checkFloat) Assertions.assertEquals(ship.getAttachment<Float>(), 3f)
}
}
internal class TestShipUser : ShipUser {
@JsonIgnore
override var ship: Ship? = null
}
| 2 | Kotlin | 0 | 1 | a9623e844643f6fa3cb38cbaed6ef1f349aaa205 | 2,043 | vs-core | Apache License 2.0 |
app/src/main/java/com/eighthour/makers/sis/libs/di/AppComponent.kt | omjoonkim | 94,101,892 | false | {"Gradle": 3, "Shell": 1, "Java Properties": 2, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Java": 2, "XML": 34, "Kotlin": 43} | package com.eighthour.makers.sis.libs.di
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent : AppComponentType | 1 | Kotlin | 2 | 15 | 5b254c9ae730a02a662d39e6ca7df53f92b69c33 | 197 | SIS-android | Apache License 2.0 |
app/src/main/java/app/eluvio/wallet/network/api/authd/VideoPlayoutApi.kt | eluv-io | 719,801,077 | false | {"Kotlin": 814244, "Java": 29738} | package app.eluvio.wallet.network.api.authd
import app.eluvio.wallet.network.dto.VideoOptionsDto
import io.reactivex.rxjava3.core.Single
import retrofit2.http.GET
import retrofit2.http.Path
interface VideoPlayoutApi : AuthdApi {
// Returns the first offering. To choose an offering use mw/playout_offering/{hash}
@GET("mw/playout_options/{hash}")
fun getVideoOptions(@Path("hash") hash: String): Single<VideoOptionsDto>
@GET("mw/properties/{propertyId}/media_items/{mediaItemId}/offerings/any/playout_options")
fun getVideoOptions(
@Path("propertyId") propertyId: String,
@Path("mediaItemId") mediaItemId: String
): Single<VideoOptionsDto>
}
| 8 | Kotlin | 1 | 0 | 3bd0cc96ff1d75f870d5ee94f3d3a6a5f491e243 | 685 | elv-wallet-android | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonercellallocationapi/integration/PrisonApiMockServer.kt | ministryofjustice | 660,631,232 | false | null | package uk.gov.justice.digital.hmpps.prisonercellallocationapi.integration
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.put
import org.springframework.http.MediaType
class PrisonApiMockServer : WireMockServer(9005) {
fun stubMoveToCellSwapPositiveResponse(bookingId: Long) {
stubFor(
put("/api/bookings/$bookingId/move-to-cell-swap")
.withRequestBody(
WireMock.equalToJson(
"""{"reasonCode":"ADM","dateTime":[2023,8,1,10,0]}""",
),
)
.willReturn(
aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withStatus(200)
.withBody(
"""
{
"bookingId": $bookingId,
"agencyId": "ACI",
"assignedLivingUnitId": 411283,
"assignedLivingUnitDesc": "ACI-CSWAP",
"bedAssignmentHistorySequence": null
}
""".trimIndent(),
),
),
)
}
fun stubCellSwapNegativeResponse(bookingId: Long) {
stubFor(
put("/api/bookings/$bookingId/move-to-cell-swap")
.willReturn(
aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withStatus(400)
.withBody(
"""{
"status": 400,
"userMessage": "The date cannot be in the future",
"developerMessage": "The date cannot be in the future"
}""",
),
),
)
}
fun stubCellSwapLocationNotFoundResponse(bookingId: Long) {
stubFor(
put("/api/bookings/$bookingId/move-to-cell-swap")
.willReturn(
aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withStatus(404)
.withBody(
"""{
"status": 404,
"userMessage": "CSWAP location not found for NMI",
"developerMessage": "CSWAP location not found for NMI"
}""",
),
),
)
}
fun stubCellSwapUnauthorizedResponse(bookingId: Long) {
stubFor(
put("/api/bookings/$bookingId/move-to-cell-swap")
.willReturn(
aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withStatus(401),
),
)
}
}
| 1 | Kotlin | 0 | 0 | 8232d9470e0abc03af436bdfe2cbea3b64ab34ec | 2,576 | hmpps-prisoner-cell-allocation-api | MIT License |
app/src/main/kotlin/me/oikvpqya/apps/music/room/dao/BlacklistDao.kt | oikvpqya | 835,137,893 | false | {"Kotlin": 274933, "HTML": 303} | package me.oikvpqya.apps.music.room.dao
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface BlacklistDao {
@Entity(
tableName = "blacklist",
)
data class BlacklistEntity(
@PrimaryKey
val path: String,
)
@Query(
value = """
INSERT INTO blacklist
VALUES (:path) ON CONFLICT (blacklist.path) DO NOTHING
"""
)
suspend fun insert(path: String)
@Query(
value = """
SELECT blacklist.path FROM blacklist
"""
)
fun getAll(): Flow<List<String>>
@Query(
value = """
DELETE FROM blacklist
WHERE blacklist.path = :path
"""
)
suspend fun delete(path: String)
}
| 0 | Kotlin | 0 | 0 | 16921f62ba1d3be1fcff32d7498d0b7e1ebbf574 | 816 | nextro | Apache License 2.0 |
app/src/main/java/volovyk/guerrillamail/data/remote/exception/NoEmailAddressAssignedException.kt | oleksandrvolovik | 611,731,548 | false | null | package volovyk.guerrillamail.data.remote.exception
class NoEmailAddressAssignedException : RuntimeException() | 0 | Kotlin | 0 | 0 | 2ce33900574e4e3fdd947bc1a0f9b6f50352ef21 | 111 | guerrilla-mail-android-client | MIT License |
kotlin-mui-icons/src/main/generated/mui/icons/material/ShortcutOutlined.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ShortcutOutlined")
package mui.icons.material
@JsName("default")
external val ShortcutOutlined: SvgIconComponent
| 12 | Kotlin | 5 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 196 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/tiny/demo/firstlinecode/kotlin/primer/project02/Test.kt | tinyvampirepudge | 143,146,373 | false | null | package com.tiny.demo.firstlinecode.kotlin.primer.project02
import kotlin.reflect.KClass
/**
* desc kotlin中调用Java中的class
*
* @author <EMAIL>
* @version version
* @date 2018/8/9 10:05 AM
*/
fun main(args: Array<String>) {
testJavaClass(JavaMain::class.java)
testKotlinClass(KotlinMain::class)
println(JavaMain.`in`)
}
fun testJavaClass(clazz: Class<JavaMain>) {
println(clazz.simpleName)
}
fun testKotlinClass(clazz: KClass<KotlinMain>) {
println(clazz.simpleName)
} | 0 | null | 11 | 24 | 6285d84750739905e9a8996af2a6dba835c9aae3 | 496 | Android_Base_Demo | Apache License 2.0 |
main/src/main/java/com/google/android/apps/muzei/MuzeiApplication.kt | ianhanniballake | 24,799,536 | true | null | /*
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.edit
import androidx.multidex.MultiDexApplication
import androidx.preference.PreferenceManager
class MuzeiApplication : MultiDexApplication(), SharedPreferences.OnSharedPreferenceChangeListener {
companion object {
private const val ALWAYS_DARK_KEY = "always_dark"
fun setAlwaysDark(context: Context, alwaysDark: Boolean) {
PreferenceManager.getDefaultSharedPreferences(context).edit {
putBoolean(ALWAYS_DARK_KEY, alwaysDark)
}
}
fun getAlwaysDark(context: Context) =
PreferenceManager.getDefaultSharedPreferences(context).getBoolean(ALWAYS_DARK_KEY, false)
}
override fun onCreate() {
super.onCreate()
updateNightMode()
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key == ALWAYS_DARK_KEY) {
updateNightMode()
}
}
private fun updateNightMode() {
val alwaysDark = getAlwaysDark(this)
AppCompatDelegate.setDefaultNightMode(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !alwaysDark)
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
else
AppCompatDelegate.MODE_NIGHT_YES
)
}
}
| 0 | Kotlin | 3 | 7 | 14a0c0c41e2628375bc5a5e5a135ff933d8b7c27 | 2,261 | muzei | Apache License 2.0 |
app/src/main/java/ru/barinov/obdroid/SpeedFragment.kt | PavelB24 | 546,869,778 | false | {"Kotlin": 232443} | package ru.barinov.obdroid
import androidx.fragment.app.Fragment
class SpeedFragment : Fragment() {
} | 0 | Kotlin | 0 | 0 | 4d0947565037ebe03d74adcba115858128f58e92 | 103 | OBDroid | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/unichamba1/CustomToast.kt | bryanmiranda138 | 854,173,400 | false | {"Kotlin": 155569} | package com.unichamba1
import android.content.Context
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
class CustomToast(private val context: Context, private val message: String) : Toast(context) {
init {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.toast_layout, null)
val textView = view.findViewById<TextView>(R.id.txtMensaje)
textView.text = message
val imageView = view.findViewById<ImageView>(R.id.imgIcono)
imageView.setImageResource(R.drawable.logo4)
setView(view)
setDuration(Toast.LENGTH_SHORT)
}
}
| 0 | Kotlin | 1 | 0 | e66d391f320f1d6721c75f4d1354bac94b7587a1 | 748 | LaApp | Apache License 2.0 |
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/FileSymlink.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.tablericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
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 compose.icons.TablerIcons
public val TablerIcons.FileSymlink: ImageVector
get() {
if (_fileSymlink != null) {
return _fileSymlink!!
}
_fileSymlink = Builder(name = "FileSymlink", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 21.0f)
verticalLineToRelative(-4.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, -3.0f)
horizontalLineToRelative(5.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 17.0f)
lineToRelative(3.0f, -3.0f)
lineToRelative(-3.0f, -3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.0f, 3.0f)
verticalLineToRelative(4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, 1.0f)
horizontalLineToRelative(4.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(5.0f, 11.0f)
verticalLineToRelative(-6.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(7.0f)
lineToRelative(5.0f, 5.0f)
verticalLineToRelative(11.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f)
horizontalLineToRelative(-9.5f)
}
}
.build()
return _fileSymlink!!
}
private var _fileSymlink: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 3,161 | compose-icons | MIT License |
shared/data/src/commonMain/kotlin/io/github/andremion/jobster/data/di/DataModule.kt | andremion | 738,156,317 | false | {"Kotlin": 128118, "Swift": 6194} | package io.github.andremion.jobster.data.di
import io.github.andremion.jobster.data.JobRepositoryImpl
import io.github.andremion.jobster.data.local.db.JobDao
import io.github.andremion.jobster.data.local.db.JobsterDatabase
import io.github.andremion.jobster.data.remote.JobPostingSearcher
import io.github.andremion.jobster.data.remote.WebScrapper
import io.github.andremion.jobster.domain.JobRepository
import io.ktor.client.HttpClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import org.koin.dsl.module
object DataModule {
val module = module {
includes(InternalDataModule.module)
single {
JobsterDatabase(
driver = get()
)
}
factory { get<JobsterDatabase>().jobQueries }
factory { get<JobsterDatabase>().contentQueries }
factory { get<JobsterDatabase>().jobContentQueries }
factory {
JobDao(
dispatcher = Dispatchers.IO,
jobQueries = get(),
contentQueries = get(),
jobContentQueries = get(),
)
}
factory {
WebScrapper(
client = HttpClient()
)
}
factory {
JobPostingSearcher(
webScrapper = get(),
geminiApi = get(),
)
}
single<JobRepository> {
JobRepositoryImpl(
jobDao = get(),
jobPostingSearcher = get(),
)
}
}
}
| 0 | Kotlin | 0 | 3 | ef3e6b69a69e7e1aa2349ba2145ce3abf4c0bf25 | 1,549 | Jobster | The Unlicense |
presentation-core/src/main/java/tachiyomi/presentation/core/i18n/Localize.kt | mihonapp | 743,704,912 | false | {"Kotlin": 2940843} | package tachiyomi.presentation.core.i18n
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.platform.LocalContext
import dev.icerock.moko.resources.PluralsResource
import dev.icerock.moko.resources.StringResource
import tachiyomi.core.common.i18n.pluralStringResource
import tachiyomi.core.common.i18n.stringResource
@Composable
@ReadOnlyComposable
fun stringResource(resource: StringResource): String {
return LocalContext.current.stringResource(resource)
}
@Composable
@ReadOnlyComposable
fun stringResource(resource: StringResource, vararg args: Any): String {
return LocalContext.current.stringResource(resource, *args)
}
@Composable
@ReadOnlyComposable
fun pluralStringResource(resource: PluralsResource, count: Int): String {
return LocalContext.current.pluralStringResource(resource, count)
}
@Composable
@ReadOnlyComposable
fun pluralStringResource(resource: PluralsResource, count: Int, vararg args: Any): String {
return LocalContext.current.pluralStringResource(resource, count, *args)
}
| 280 | Kotlin | 447 | 9,867 | f3a2f566c8a09ab862758ae69b43da2a2cd8f1db | 1,090 | mihon | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/constructs/IDependable.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 135758310} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.constructs
import io.cloudshiftdev.awscdk.common.CdkObject
public interface IDependable {
private class Wrapper(
override val cdkObject: software.constructs.IDependable,
) : CdkObject(cdkObject), IDependable
public companion object {
internal fun wrap(cdkObject: software.constructs.IDependable): IDependable = Wrapper(cdkObject)
internal fun unwrap(wrapped: IDependable): software.constructs.IDependable = (wrapped as
CdkObject).cdkObject as software.constructs.IDependable
}
}
| 1 | Kotlin | 0 | 3 | 7c2593ffa861293ae29a00d99f8427efbcf80dfa | 713 | awscdk-dsl-kotlin | Apache License 2.0 |
gallerypicker/src/main/java/com/picker/gallery/presenter/VideosPresenter.kt | tizisdeepan | 150,385,517 | false | null | package com.picker.gallery.presenter
interface VideosPresenter {
fun getPhoneAlbums()
} | 5 | Kotlin | 20 | 97 | bbd8a5d28b1082a428f37a8071070540e0ee224b | 92 | GalleryPicker | Apache License 2.0 |
app/src/main/java/com/beltraoluis/intrachat/activity/MainActivity.kt | beltraoluis | 135,816,899 | false | null | package com.beltraoluis.intrachat.activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import com.beltraoluis.intrachat.Control
import com.beltraoluis.intrachat.R
import com.beltraoluis.intrachat.connection.TcpServer
import com.beltraoluis.intrachat.fragment.MainFragment
import com.beltraoluis.intrachat.fragment.TalkFragment
import com.beltraoluis.intrachat.model.Conversation
import com.beltraoluis.intrachat.model.Message
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.*
import java.sql.Timestamp
class MainActivity : AppCompatActivity() {
companion object {
const val MAIN_FRAGMENT = "main"
const val TALK_FRAGMENT = "talk"
}
lateinit var server: TcpServer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
Control.main = this
callFragment("main","")
server = TcpServer(this,Control.DOOR)
}
override fun onDestroy() {
super.onDestroy()
server.stopServer()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.lineCode_menu -> {
alert{
customView{
verticalLayout{
padding = dip(8)
textView("Códigos de linha"){
textSize = 20F
}
radioGroup {
val nrz = radioButton{
text = "NRZ"
}
val rz = radioButton{
text = "RZ"
}
when(Control.codeline_code){
Control.NRZ_CODE -> {
nrz.isChecked = true
rz.isChecked = false
}
Control.RZ_CODE -> {
rz.isChecked = true
nrz.isChecked = false
}
}
nrz.setOnClickListener{
nrz.isChecked = true
rz.isChecked = false
Control.codeline_code = Control.NRZ_CODE
}
rz.setOnClickListener{
rz.isChecked = true
nrz.isChecked = false
Control.codeline_code = Control.RZ_CODE
}
}
}
}
}.show()
return true
}
else -> super.onOptionsItemSelected(item)
}
}
fun update(ip: String, message: String){
if(Control.conversation[ip] == null){
Control.conversation[ip] = Conversation(System.currentTimeMillis())
runOnUiThread {
if(Control.state.equals(MAIN_FRAGMENT)){
val frag = Control.activeFragment as MainFragment
frag.recyclerAdapter.add(Timestamp(Control.conversation[ip]!!.time) to ip)
}
}
}
Control.conversation[ip]!!.messages.add(Message.toMessage(message))
Log.i("Message",message)
Control.activeFragment?.updateRecycler()
}
fun callFragment(s: String, ip: String){
var frag = supportFragmentManager.findFragmentByTag(s)
when(s){
MAIN_FRAGMENT -> {
if(frag == null){
frag = MainFragment.newInstance(ip)
supportFragmentManager
.beginTransaction()
.add(R.id.frame,frag,MAIN_FRAGMENT)
.commit()
}
Control.state = MAIN_FRAGMENT
}
TALK_FRAGMENT -> {
if(frag == null){
frag = TalkFragment.newInstance(ip)
supportFragmentManager
.beginTransaction()
.add(R.id.frame,frag,TALK_FRAGMENT)
.commit()
}
Control.state = TALK_FRAGMENT
}
else -> {}
}
supportFragmentManager
.beginTransaction()
.replace(R.id.frame,frag)
.commit()
}
override fun finish() {
if(Control.state.equals(MAIN_FRAGMENT)){
alert("Deseja realmente sair do aplicativo?","sair") {
yesButton { super.finish() }
noButton { }
}.show()
}
else{
callFragment(MAIN_FRAGMENT,"")
}
}
}
| 1 | null | 1 | 1 | fe5e956bc709b3d6e585ba3110a049677a228ba9 | 5,720 | IntraChat | MIT License |
allure-kotlin-commons/src/main/kotlin/io/qameta/allure/kotlin/util/ObjectUtils.kt | kamildziadek | 233,392,268 | false | null | package io.qameta.allure.kotlin.util
import java.util.logging.Logger
object ObjectUtils {
private val LOGGER: Logger = loggerFor<ObjectUtils>()
/**
* Returns string representation of given object. Pretty prints arrays.
*
* @param data the given object.
* @return the string representation of given object.
*/
@JvmStatic
fun toString(data: Any?): String {
return try {
if (data != null && data.javaClass.isArray) {
when (data) {
is LongArray -> return data.contentToString()
is ShortArray -> return data.contentToString()
is IntArray -> return data.contentToString()
is CharArray -> return data.contentToString()
is DoubleArray -> return data.contentToString()
is FloatArray -> return data.contentToString()
is BooleanArray -> return data.contentToString()
is ByteArray -> return "<BINARY>"
is Array<*> -> return data.contentToString()
}
}
java.lang.String.valueOf(data)
} catch (e: Exception) {
LOGGER.error("Could not convert object to string", e)
"<NPE>"
}
}
} | 14 | null | 2 | 7 | ed264b2cc39ca874c7f79742901a16988a4f916c | 1,306 | allure-kotlin | Apache License 2.0 |
src/main/kotlin/sh/talonfox/vulpes_std/modmenu/VulpesButton.kt | VulpesMC | 559,997,779 | false | null | package sh.talonfox.vulpes_std.modmenu
import com.mojang.blaze3d.systems.RenderSystem
import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.components.Button
import net.minecraft.client.renderer.GameRenderer
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
import kotlin.math.abs
import kotlin.math.sin
class VulpesButton(x: Int, y: Int, width: Int, height: Int, text: Component, press: OnPress) : Button(x,y,width,height,text,press,DEFAULT_NARRATION) {
private companion object {
@JvmField
var ticks: Long = 0
}
private val vulpes_logo = ResourceLocation("vulpes:textures/vulpes.png")
override fun renderButton(matrices: PoseStack, mouseX: Int, mouseY: Int, d: Float) {
if (mouseX >= x && (mouseX <= x + width) and (mouseY >= y) && mouseY <= y + height) {
val intensity = (abs(sin(Math.toRadians((ticks * 9).toDouble()))) * 128).toInt()
fill(
matrices,
x,
y,
x + width,
y + height,
(0x80000000.toUInt() or (intensity.toUInt() shl 16) or (intensity.toUInt() shl 8) or intensity.toUInt()).toInt()
)
} else {
ticks = 5
fill(
matrices,
x,
y,
x + width,
y + height,
0x80000000.toInt()
)
}
RenderSystem.setShader { GameRenderer.getPositionTexShader() }
RenderSystem.setShaderTexture(0, vulpes_logo)
blit(
matrices,
x,
y,
height,
height,
0f,
0f,
512,
512,
512,
512
)
drawCenteredString(
matrices,
Minecraft.getInstance().font,
message,
x + (width/2),
y + ((height/2)-(9/2)),
0xffffff
)
}
} | 0 | Kotlin | 0 | 2 | a0a50c06a42f1c2a8835519eff573ada51a22ff8 | 2,065 | VulpesStandardLibrary | Apache License 2.0 |
design/components/src/main/java/com/quintallabs/design/components/TopBar.kt | thiagoalexb | 739,844,654 | false | {"Kotlin": 77090} | package com.quintallabs.design.components
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopBar(
navController: NavController,
title: String = "",
) {
TopAppBar(
title = {
Text(text = title)
},
navigationIcon = {
IconButton(onClick = { navController.navigateUp() }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = "Back"
)
}
}
)
} | 0 | Kotlin | 0 | 0 | e139dd7beefd6cef3d7cc2ee6b49ca6a5e06475f | 850 | randomDrink | Apache License 2.0 |
src/main/kotlin/io/github/thebroccolibob/shallowdark/ShallowDarkTags.kt | thebroccolibob | 757,060,700 | false | {"Kotlin": 38300, "Java": 3882} | package io.github.thebroccolibob.shallowdark
import net.minecraft.entity.EntityType
import net.minecraft.registry.RegistryKeys
import net.minecraft.registry.tag.TagKey
import net.minecraft.util.Identifier
object ShallowDarkTags {
val JAW_IMMUNE: TagKey<EntityType<*>> = TagKey.of(RegistryKeys.ENTITY_TYPE, Identifier(ShallowDark.modId, "jaw_immune"))
}
| 5 | Kotlin | 0 | 0 | e501f4ef1f98cbe2873a3e7cf4371ba840e31358 | 359 | ShallowDark | MIT License |
open-shift-service/src/main/kotlin/ru/art/platform/open/shift/manager/OpenShiftAgentManager.kt | art-community | 284,500,366 | false | null | package ru.art.platform.open.shift.manager
import com.openshift.restclient.images.DockerImageURI
import ru.art.core.constants.StringConstants.EMPTY_STRING
import ru.art.core.network.selector.PortSelector.findAvailableTcpPort
import ru.art.platform.api.model.resource.OpenShiftResource
import ru.art.platform.common.constants.CommonConstants.*
import ru.art.platform.common.constants.ErrorCodes.PLATFORM_ERROR
import ru.art.platform.common.constants.PlatformKeywords.PLATFORM_CAMEL_CASE
import ru.art.platform.common.exception.PlatformException
import ru.art.platform.common.extractor.extractHostName
import ru.art.platform.common.extractor.extractPath
import ru.art.platform.open.shift.constants.OpenShiftConstants.IMAGE_PULL_POLICY_ALWAYS
import ru.art.platform.open.shift.model.OpenShiftPodWaitingConfiguration
import ru.art.platform.open.shift.service.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
fun startOpenShiftAgent(resource: OpenShiftResource, agentName: String, manager: OpenShiftAgentManager.() -> OpenShiftAgentManager) =
manager(OpenShiftAgentManager(resource, agentName)).start()
fun stopOpenShiftAgent(resource: OpenShiftResource, agentName: String, projectName: String) {
OpenShiftAgentManager(resource, agentName).projectName(projectName).stop()
}
data class OpenShiftPort(val service: Int, val node: Int)
data class OpenShiftAgentPorts(val http: Int, val rsocket: Int, val custom: Map<String, OpenShiftPort>)
private val STARTING_LOCK = ReentrantLock()
class OpenShiftAgentManager(private val resource: OpenShiftResource, private val agentName: String) {
private lateinit var projectName: String
private var reusable: Boolean = false
private var url: String = EMPTY_STRING
private var image: String? = null
private var pushTargetProject: String? = null
private var pullSourceProject: String? = null
private var platformProjectName: String = PLATFORM_CAMEL_CASE
private var pullPolicy: String = IMAGE_PULL_POLICY_ALWAYS
private var customPorts: MutableMap<String, String> = mutableMapOf()
private var environmentVariables: MutableMap<String, String> = mutableMapOf()
private var labels: MutableMap<String, String> = mutableMapOf()
private var nodeSelector: MutableMap<String, String> = mutableMapOf()
private val awaitingDeletion = AtomicBoolean(false)
fun projectName(name: String): OpenShiftAgentManager {
projectName = name
return this
}
fun allowPushingTo(pushTargetProject: String): OpenShiftAgentManager {
this.pushTargetProject = pushTargetProject
return this
}
fun allowPullingFrom(pullSourceProject: String): OpenShiftAgentManager {
this.pullSourceProject = pullSourceProject
return this
}
fun platformProjectName(name: String?): OpenShiftAgentManager {
platformProjectName = name ?: PLATFORM_CAMEL_CASE
return this
}
fun image(image: String): OpenShiftAgentManager {
this.image = image
return this
}
fun reusable(reusable: Boolean = true): OpenShiftAgentManager {
this.reusable = reusable
return this
}
fun public(url: String): OpenShiftAgentManager {
this.url = url
return this
}
fun customPort(name: String, environmentVariableName: String): OpenShiftAgentManager {
customPorts[name] = environmentVariableName
return this
}
fun environmentVariable(name: String, value: String): OpenShiftAgentManager {
environmentVariables[name] = value
return this
}
fun label(name: String, value: String): OpenShiftAgentManager {
labels[name] = value
return this
}
fun nodeSelector(name: String, value: String): OpenShiftAgentManager {
nodeSelector[name] = value
return this
}
fun pullPolicy(policy: String): OpenShiftAgentManager {
this.pullPolicy = policy
return this
}
fun start(): OpenShiftAgentPorts = STARTING_LOCK.withLock {
openShift(resource) {
getProject(projectName) {
getService(agentName)?.ports?.let { ports ->
if (!reusable) {
deleteRoute(agentName)
deleteService(agentName)
deletePod(agentName)
return@getProject createAgent(findAvailableTcpPort(AGENT_MIN_PORT), findAvailableTcpPort(AGENT_MAX_PORT))
}
if (awaitingDeletion.compareAndSet(true, false)) {
deleteRoute(agentName)
deleteService(agentName)
deletePod(agentName)
return@getProject createAgent(findAvailableTcpPort(AGENT_MIN_PORT), findAvailableTcpPort(AGENT_MAX_PORT))
}
getPod(agentName)?.let {
return@getProject OpenShiftAgentPorts(
http = ports.first { port -> port.name == HTTP_PORT_NAME }.nodePort.toInt(),
rsocket = ports.first { port -> port.name == RSOCKET_PORT_NAME }.nodePort.toInt(),
custom = ports.filter { port -> customPorts.containsKey(port.name) }
.map { port -> port.name to OpenShiftPort(port.port, port.nodePort.toInt()) }
.toMap())
}
return@getProject createAgent(
ports.first { port -> port.name == HTTP_PORT_NAME }.port,
ports.first { port -> port.name == RSOCKET_PORT_NAME }.port
)
}
getPod(agentName)?.let {
deletePod(agentName)
return@getProject createAgent(findAvailableTcpPort(AGENT_MIN_PORT), findAvailableTcpPort(AGENT_MAX_PORT))
}
return@getProject createAgent(findAvailableTcpPort(AGENT_MIN_PORT), findAvailableTcpPort(AGENT_MAX_PORT))
} ?: createProject(projectName) {
createAgent(findAvailableTcpPort(AGENT_MIN_PORT), findAvailableTcpPort(AGENT_MAX_PORT))
}
}
}
fun stop() = openShift(resource) {
getProject(projectName)?.let { project ->
if (awaitingDeletion.compareAndSet(false, true)) {
deletePod(agentName, project.namespaceName)
deleteService(agentName, project.namespaceName)
deleteRoute(agentName, project.namespaceName)
}
}
}
private fun OpenShiftProjectService.createAgent(httpPort: Int, rsocketPort: Int): OpenShiftAgentPorts {
allowImagesPulling(platformProjectName, projectName)
allowImagesPushing(platformProjectName, projectName)
pushTargetProject?.let { project -> allowImagesPushing(projectName, project) }
pullSourceProject?.let { project -> allowImagesPulling(project, projectName) }
val agentImage = image
?.let(::DockerImageURI)
?: throw PlatformException(PLATFORM_ERROR, "Agent image not presented")
val hostName = "${extractHostName(url).replace(".${resource.applicationsDomain}", EMPTY_STRING)}.${resource.applicationsDomain}"
createPod(agentName) {
labels.forEach { (name, value) -> label(name, value) }
nodeSelector.forEach { (name, value) -> nodeSelector(name, value) }
container(agentName, agentImage) {
tcpPort(rsocketPort, RSOCKET_PORT_NAME)
environment(RSOCKET_PORT_PROPERTY, rsocketPort)
tcpPort(httpPort, HTTP_PORT_NAME)
environment(HTTP_PORT_PROPERTY, httpPort)
environmentVariables.forEach { (name, value) -> environment(name, value) }
customPorts.forEach { (name, environmentVariable) ->
val port = findAvailableTcpPort(AGENT_MIN_PORT, AGENT_MAX_PORT)
tcpPort(port, name)
environment(environmentVariable, port)
}
imagePullPolicy(pullPolicy)
}
serve(configuration.name) {
if (url.isNotBlank()) {
public(name) {
host(hostName)
path(extractPath(url))
targetPort(httpPort)
}
}
asNodePort()
return@serve this
}
}
if (!waitForPodContainersReadiness(OpenShiftPodWaitingConfiguration(name = agentName))) {
throw PlatformException(PLATFORM_ERROR, "Pod '$agentName' was not started correctly on OpenShift")
}
val ports = getService(agentName)
?.ports
?: throw PlatformException(PLATFORM_ERROR, "Service '$agentName' was not found for project")
return OpenShiftAgentPorts(
http = ports.first { port -> port.name == HTTP_PORT_NAME }.nodePort.toInt(),
rsocket = ports.first { port -> port.name == RSOCKET_PORT_NAME }.nodePort.toInt(),
custom = ports.filter { port -> customPorts.containsKey(port.name) }
.map { port -> port.name to OpenShiftPort(port.port, port.nodePort.toInt()) }
.toMap())
}
}
| 1 | TypeScript | 0 | 1 | 80051409f70eec2abb66afb7d72359a975198a2b | 9,521 | art-platform | Apache License 2.0 |
app/src/main/java/io/github/gusriil/moviemagnet/domain/repository/TVShowDetailRepository.kt | superosystem | 479,150,681 | false | {"Kotlin": 225959, "Java": 7644} | package io.github.gusriil.moviemagnet.domain.repository
import io.github.gusriil.moviemagnet.domain.model.CreditWrapper
import io.github.gusriil.moviemagnet.domain.model.Video
import io.reactivex.Single
interface TVShowDetailRepository {
fun getTVShowTrailers(tvId: Int): Single<List<Video>>
fun getTVShowCredit(tvId: Int): CreditWrapper
} | 0 | Kotlin | 0 | 3 | 91a2d005aab478bb5c864210fe0cbd2286daf2ad | 351 | MovieMagnet | MIT License |
j2k/tests/testData/ast/class/protectedClass.kt | hhariri | 21,116,939 | true | {"Markdown": 19, "XML": 443, "Ant Build System": 23, "Ignore List": 7, "Protocol Buffer": 2, "Java": 3757, "Kotlin": 11162, "Roff": 59, "JAR Manifest": 1, "INI": 7, "Text": 916, "Java Properties": 10, "HTML": 102, "Roff Manpage": 8, "Groovy": 7, "Gradle": 61, "Maven POM": 34, "CSS": 10, "JavaScript": 42, "JFlex": 3, "Batchfile": 7, "Shell": 7} | protected class Test() | 0 | Java | 0 | 0 | d150bfbce0e2e47d687f39e2fd233ea55b2ccd26 | 22 | kotlin | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/securityhub/CfnOrganizationConfigurationProps.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.securityhub
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
/**
* Properties for defining a `CfnOrganizationConfiguration`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.securityhub.*;
* CfnOrganizationConfigurationProps cfnOrganizationConfigurationProps =
* CfnOrganizationConfigurationProps.builder()
* .autoEnable(false)
* // the properties below are optional
* .autoEnableStandards("autoEnableStandards")
* .configurationType("configurationType")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-organizationconfiguration.html)
*/
public interface CfnOrganizationConfigurationProps {
/**
* Whether to automatically enable Security Hub in new member accounts when they join the
* organization.
*
* If set to `true` , then Security Hub is automatically enabled in new accounts. If set to
* `false` , then Security Hub isn't enabled in new accounts automatically. The default value is
* `false` .
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set to
* `false` and can't be changed in the home Region and linked Regions. However, in that case, the
* delegated administrator can create a configuration policy in which Security Hub is enabled and
* associate the policy with new organization accounts.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-organizationconfiguration.html#cfn-securityhub-organizationconfiguration-autoenable)
*/
public fun autoEnable(): Any
/**
* Whether to automatically enable Security Hub [default
* standards](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-enable-disable.html)
* in new member accounts when they join the organization.
*
* The default value of this parameter is equal to `DEFAULT` .
*
* If equal to `DEFAULT` , then Security Hub default standards are automatically enabled for new
* member accounts. If equal to `NONE` , then default standards are not automatically enabled for new
* member accounts.
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set to
* `NONE` and can't be changed in the home Region and linked Regions. However, in that case, the
* delegated administrator can create a configuration policy in which specific security standards are
* enabled and associate the policy with new organization accounts.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-organizationconfiguration.html#cfn-securityhub-organizationconfiguration-autoenablestandards)
*/
public fun autoEnableStandards(): String? = unwrap(this).getAutoEnableStandards()
/**
* Indicates whether the organization uses local or central configuration.
*
* If you use local configuration, the Security Hub delegated administrator can set `AutoEnable`
* to `true` and `AutoEnableStandards` to `DEFAULT` . This automatically enables Security Hub and
* default security standards in new organization accounts. These new account settings must be set
* separately in each AWS Region , and settings may be different in each Region.
*
* If you use central configuration, the delegated administrator can create configuration
* policies. Configuration policies can be used to configure Security Hub, security standards, and
* security controls in multiple accounts and Regions. If you want new organization accounts to use a
* specific configuration, you can create a configuration policy and associate it with the root or
* specific organizational units (OUs). New accounts will inherit the policy from the root or their
* assigned OU.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-organizationconfiguration.html#cfn-securityhub-organizationconfiguration-configurationtype)
*/
public fun configurationType(): String? = unwrap(this).getConfigurationType()
/**
* A builder for [CfnOrganizationConfigurationProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param autoEnable Whether to automatically enable Security Hub in new member accounts when
* they join the organization.
* If set to `true` , then Security Hub is automatically enabled in new accounts. If set to
* `false` , then Security Hub isn't enabled in new accounts automatically. The default value is
* `false` .
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set
* to `false` and can't be changed in the home Region and linked Regions. However, in that case,
* the delegated administrator can create a configuration policy in which Security Hub is enabled
* and associate the policy with new organization accounts.
*/
public fun autoEnable(autoEnable: Boolean)
/**
* @param autoEnable Whether to automatically enable Security Hub in new member accounts when
* they join the organization.
* If set to `true` , then Security Hub is automatically enabled in new accounts. If set to
* `false` , then Security Hub isn't enabled in new accounts automatically. The default value is
* `false` .
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set
* to `false` and can't be changed in the home Region and linked Regions. However, in that case,
* the delegated administrator can create a configuration policy in which Security Hub is enabled
* and associate the policy with new organization accounts.
*/
public fun autoEnable(autoEnable: IResolvable)
/**
* @param autoEnableStandards Whether to automatically enable Security Hub [default
* standards](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-enable-disable.html)
* in new member accounts when they join the organization.
* The default value of this parameter is equal to `DEFAULT` .
*
* If equal to `DEFAULT` , then Security Hub default standards are automatically enabled for new
* member accounts. If equal to `NONE` , then default standards are not automatically enabled for
* new member accounts.
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set
* to `NONE` and can't be changed in the home Region and linked Regions. However, in that case, the
* delegated administrator can create a configuration policy in which specific security standards
* are enabled and associate the policy with new organization accounts.
*/
public fun autoEnableStandards(autoEnableStandards: String)
/**
* @param configurationType Indicates whether the organization uses local or central
* configuration.
* If you use local configuration, the Security Hub delegated administrator can set `AutoEnable`
* to `true` and `AutoEnableStandards` to `DEFAULT` . This automatically enables Security Hub and
* default security standards in new organization accounts. These new account settings must be set
* separately in each AWS Region , and settings may be different in each Region.
*
* If you use central configuration, the delegated administrator can create configuration
* policies. Configuration policies can be used to configure Security Hub, security standards, and
* security controls in multiple accounts and Regions. If you want new organization accounts to use
* a specific configuration, you can create a configuration policy and associate it with the root
* or specific organizational units (OUs). New accounts will inherit the policy from the root or
* their assigned OU.
*/
public fun configurationType(configurationType: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.securityhub.CfnOrganizationConfigurationProps.Builder =
software.amazon.awscdk.services.securityhub.CfnOrganizationConfigurationProps.builder()
/**
* @param autoEnable Whether to automatically enable Security Hub in new member accounts when
* they join the organization.
* If set to `true` , then Security Hub is automatically enabled in new accounts. If set to
* `false` , then Security Hub isn't enabled in new accounts automatically. The default value is
* `false` .
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set
* to `false` and can't be changed in the home Region and linked Regions. However, in that case,
* the delegated administrator can create a configuration policy in which Security Hub is enabled
* and associate the policy with new organization accounts.
*/
override fun autoEnable(autoEnable: Boolean) {
cdkBuilder.autoEnable(autoEnable)
}
/**
* @param autoEnable Whether to automatically enable Security Hub in new member accounts when
* they join the organization.
* If set to `true` , then Security Hub is automatically enabled in new accounts. If set to
* `false` , then Security Hub isn't enabled in new accounts automatically. The default value is
* `false` .
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set
* to `false` and can't be changed in the home Region and linked Regions. However, in that case,
* the delegated administrator can create a configuration policy in which Security Hub is enabled
* and associate the policy with new organization accounts.
*/
override fun autoEnable(autoEnable: IResolvable) {
cdkBuilder.autoEnable(autoEnable.let(IResolvable.Companion::unwrap))
}
/**
* @param autoEnableStandards Whether to automatically enable Security Hub [default
* standards](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-enable-disable.html)
* in new member accounts when they join the organization.
* The default value of this parameter is equal to `DEFAULT` .
*
* If equal to `DEFAULT` , then Security Hub default standards are automatically enabled for new
* member accounts. If equal to `NONE` , then default standards are not automatically enabled for
* new member accounts.
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set
* to `NONE` and can't be changed in the home Region and linked Regions. However, in that case, the
* delegated administrator can create a configuration policy in which specific security standards
* are enabled and associate the policy with new organization accounts.
*/
override fun autoEnableStandards(autoEnableStandards: String) {
cdkBuilder.autoEnableStandards(autoEnableStandards)
}
/**
* @param configurationType Indicates whether the organization uses local or central
* configuration.
* If you use local configuration, the Security Hub delegated administrator can set `AutoEnable`
* to `true` and `AutoEnableStandards` to `DEFAULT` . This automatically enables Security Hub and
* default security standards in new organization accounts. These new account settings must be set
* separately in each AWS Region , and settings may be different in each Region.
*
* If you use central configuration, the delegated administrator can create configuration
* policies. Configuration policies can be used to configure Security Hub, security standards, and
* security controls in multiple accounts and Regions. If you want new organization accounts to use
* a specific configuration, you can create a configuration policy and associate it with the root
* or specific organizational units (OUs). New accounts will inherit the policy from the root or
* their assigned OU.
*/
override fun configurationType(configurationType: String) {
cdkBuilder.configurationType(configurationType)
}
public fun build():
software.amazon.awscdk.services.securityhub.CfnOrganizationConfigurationProps =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.securityhub.CfnOrganizationConfigurationProps,
) : CdkObject(cdkObject),
CfnOrganizationConfigurationProps {
/**
* Whether to automatically enable Security Hub in new member accounts when they join the
* organization.
*
* If set to `true` , then Security Hub is automatically enabled in new accounts. If set to
* `false` , then Security Hub isn't enabled in new accounts automatically. The default value is
* `false` .
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set
* to `false` and can't be changed in the home Region and linked Regions. However, in that case,
* the delegated administrator can create a configuration policy in which Security Hub is enabled
* and associate the policy with new organization accounts.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-organizationconfiguration.html#cfn-securityhub-organizationconfiguration-autoenable)
*/
override fun autoEnable(): Any = unwrap(this).getAutoEnable()
/**
* Whether to automatically enable Security Hub [default
* standards](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-enable-disable.html)
* in new member accounts when they join the organization.
*
* The default value of this parameter is equal to `DEFAULT` .
*
* If equal to `DEFAULT` , then Security Hub default standards are automatically enabled for new
* member accounts. If equal to `NONE` , then default standards are not automatically enabled for
* new member accounts.
*
* If the `ConfigurationType` of your organization is set to `CENTRAL` , then this field is set
* to `NONE` and can't be changed in the home Region and linked Regions. However, in that case, the
* delegated administrator can create a configuration policy in which specific security standards
* are enabled and associate the policy with new organization accounts.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-organizationconfiguration.html#cfn-securityhub-organizationconfiguration-autoenablestandards)
*/
override fun autoEnableStandards(): String? = unwrap(this).getAutoEnableStandards()
/**
* Indicates whether the organization uses local or central configuration.
*
* If you use local configuration, the Security Hub delegated administrator can set `AutoEnable`
* to `true` and `AutoEnableStandards` to `DEFAULT` . This automatically enables Security Hub and
* default security standards in new organization accounts. These new account settings must be set
* separately in each AWS Region , and settings may be different in each Region.
*
* If you use central configuration, the delegated administrator can create configuration
* policies. Configuration policies can be used to configure Security Hub, security standards, and
* security controls in multiple accounts and Regions. If you want new organization accounts to use
* a specific configuration, you can create a configuration policy and associate it with the root
* or specific organizational units (OUs). New accounts will inherit the policy from the root or
* their assigned OU.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-organizationconfiguration.html#cfn-securityhub-organizationconfiguration-configurationtype)
*/
override fun configurationType(): String? = unwrap(this).getConfigurationType()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnOrganizationConfigurationProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.securityhub.CfnOrganizationConfigurationProps):
CfnOrganizationConfigurationProps = CdkObjectWrappers.wrap(cdkObject) as?
CfnOrganizationConfigurationProps ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnOrganizationConfigurationProps):
software.amazon.awscdk.services.securityhub.CfnOrganizationConfigurationProps = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.securityhub.CfnOrganizationConfigurationProps
}
}
| 0 | Kotlin | 0 | 4 | 652b030da47fc795f7a987eba0f8c82f64035d24 | 17,527 | kotlin-cdk-wrapper | Apache License 2.0 |
app/src/main/java/com/allentom/diffusion/api/entity/ControlNetVersion.kt | AllenTom | 744,304,887 | false | {"Kotlin": 983586} | package com.allentom.diffusion.api.entity
import com.google.gson.annotations.SerializedName
data class ControlNetVersion(
@SerializedName("version")
val version: String,
) | 0 | Kotlin | 1 | 64 | 3514c638007144b56de883c804048617dc32b939 | 181 | diffusion-client | MIT License |
emulatork_basic/src/main/java/com/mozhimen/emulatork/basic/injection/PerActivity.kt | mozhimen | 797,106,031 | false | {"Kotlin": 171032} | package com.mozhimen.emulatork.basic.injection
import javax.inject.Scope
/**
* @ClassName PerActivity
* @Description TODO
* @Author Mozhimen & <NAME>
* @Date 2024/5/9
* @Version 1.0
*/
@Scope
annotation class PerActivity | 0 | Kotlin | 0 | 0 | 3e7031c53b1c92304e98df53e0b3762ed2cb47c5 | 228 | AEmulatorKit | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/lex/CfnBotAliasTextLogSettingPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 63959868} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.lex
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Boolean
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.lex.CfnBotAlias
/**
* Defines settings to enable text conversation logs.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.lex.*;
* TextLogSettingProperty textLogSettingProperty = TextLogSettingProperty.builder()
* .destination(TextLogDestinationProperty.builder()
* .cloudWatch(CloudWatchLogGroupLogDestinationProperty.builder()
* .cloudWatchLogGroupArn("cloudWatchLogGroupArn")
* .logPrefix("logPrefix")
* .build())
* .build())
* .enabled(false)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lex-botalias-textlogsetting.html)
*/
@CdkDslMarker
public class CfnBotAliasTextLogSettingPropertyDsl {
private val cdkBuilder: CfnBotAlias.TextLogSettingProperty.Builder =
CfnBotAlias.TextLogSettingProperty.builder()
/**
* @param destination Defines the Amazon CloudWatch Logs destination log group for conversation
* text logs.
*/
public fun destination(destination: IResolvable) {
cdkBuilder.destination(destination)
}
/**
* @param destination Defines the Amazon CloudWatch Logs destination log group for conversation
* text logs.
*/
public fun destination(destination: CfnBotAlias.TextLogDestinationProperty) {
cdkBuilder.destination(destination)
}
/** @param enabled Determines whether conversation logs should be stored for an alias. */
public fun enabled(enabled: Boolean) {
cdkBuilder.enabled(enabled)
}
/** @param enabled Determines whether conversation logs should be stored for an alias. */
public fun enabled(enabled: IResolvable) {
cdkBuilder.enabled(enabled)
}
public fun build(): CfnBotAlias.TextLogSettingProperty = cdkBuilder.build()
}
| 4 | Kotlin | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 2,327 | awscdk-dsl-kotlin | Apache License 2.0 |
jvm-agent/src/test/kotlin/tests-jvm-agent.kt | Anamorphosee | 429,510,239 | false | {"Kotlin": 111539, "Java": 10025} | import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
import kotlin.test.Test
class PerformanceTest: dev.reformator.stacktracedecoroutinator.test.PerformanceTest()
class RuntimeTest: dev.reformator.stacktracedecoroutinator.test.RuntimeTest()
// Jacoco only instruments this class
class JacocoInstrumentedMethodTest {
@Test
fun jacocoInstrumentedMethodTest(): Unit = runBlocking {
suspend fun jacocoInstrumentedMethod() {
yield()
yield()
}
jacocoInstrumentedMethod()
}
}
| 5 | Kotlin | 5 | 189 | e7ad0a16c4d4fbb2d2b6bfb84330b0cd194e5c7f | 548 | stacktrace-decoroutinator | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.