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/pianostudio/ui/screens/record/StudioRecordingScreen.kt
|
coral134
| 695,267,140
| false
|
{"Kotlin": 90538}
|
package com.example.pianostudio.ui.screens.record
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import com.example.pianostudio.ui.navigation.rememberLocalPageNavigator
import com.example.pianostudio.ui.screens.studio.PianoScreen
import com.example.pianostudio.viewmodel.MainViewModel
@Composable
fun StudioRecordingScreen(
modifier: Modifier = Modifier,
vm: MainViewModel
) {
val player = vm.rememberTrackPlayer()
val nav = rememberLocalPageNavigator()
LaunchedEffect(vm) {
player.record(this)
}
PianoScreen(
modifier = modifier,
keysState = vm.keyboardInput.keysState,
keySpacer = vm.keySpacer.value,
trackPlayer = player,
onPause = { nav.navigateTo("MainPages/Home") },
updatePressedNotes = remember(vm.keyboardInput) { vm.keyboardInput::uiKeyPress },
)
}
| 0
|
Kotlin
|
0
| 0
|
e6cc3aab20d1574dbf4f9ccd15aba2200d0b62af
| 971
|
Piano_Studio
|
MIT License
|
droid-app/CoffeeDose/app/src/main/java/com/office14/coffeedose/domain/Order.kt
|
sofinms
| 249,805,970
| true
|
{"Kotlin": 102441, "C#": 99646, "TypeScript": 65904, "HTML": 11001, "JavaScript": 1831, "Dockerfile": 1083, "CSS": 299}
|
package com.office14.coffeedose.domain
data class Order (
var id : Int,
val statusCode : String,
val statusName : String,
val orderNumber : String,
val totalPrice : Int
)
| 0
| null |
0
| 0
|
109a16dbce748a363eeb290ebba46c4b9dbbf357
| 191
|
Drinks
|
MIT License
|
src/main/kotlin/com/mrkirby153/botcore/builder/AutoSplittingMessageBuilder.kt
|
mrkirby153
| 137,817,672
| false
|
{"Kotlin": 123702}
|
package com.mrkirby153.botcore.builder
import net.dv8tion.jda.api.utils.messages.MessageCreateData
fun autoSplittingMessage(
maxCharactersPerMessage: Int = 1990,
body: AutoSplittingMessageBuilder.() -> Unit,
): List<MessageCreateData> {
val builder = AutoSplittingMessageBuilder(maxCharactersPerMessage)
body(builder)
return builder.build()
}
/**
* A message builder that will automatically split messages after a certain length
*/
class AutoSplittingMessageBuilder(private val maxCharactersPerMessage: Int = 1990) {
private val messages = mutableListOf<String>()
private var buffer = ""
private var built = false
/**
* Appends a [data] to the message, splitting the message into multiple if needed.
* Specify [splitMode] to control how the splitting occurs
*/
@JvmOverloads
fun append(data: Any?, splitMode: SplitMode = SplitMode.WHOLE_LINE) {
check(!built) { "Cannot append to a message that's already been built" }
val string = data.toString()
when (splitMode) {
SplitMode.WHOLE_LINE -> {
check(string.length <= maxCharactersPerMessage) { "Cannot append $string to message as its length is greater than the maximum allowed per message. Use SplitMode.BREAK_LINE instead" }
if (buffer.length + string.length > maxCharactersPerMessage) {
splitMessage()
}
buffer += string
}
SplitMode.BREAK_LINE -> {
val remainingCharacters = maxCharactersPerMessage - buffer.length
if (remainingCharacters < string.length) {
val first = string.substring(0 until remainingCharacters)
val second =
string.substring(remainingCharacters until string.length).trimStart()
buffer += first
splitMessage()
buffer += if (second.startsWith("\n"))
second.substring(1)
else
second
}
}
SplitMode.BREAK_WORD -> {
// Break at the closest word
val parts = string.split(" ")
parts.forEach { word ->
check(word.length <= maxCharactersPerMessage) { "Cannot append $word to message, as its length is greater than the maximum allowed per message" }
buffer += if (maxCharactersPerMessage - buffer.length - word.length >= 0) {
" $word"
} else {
splitMessage()
word
}
}
}
}
}
/**
* Appends [data] with a newline character.
*
* @see append
*/
@JvmOverloads
fun appendLine(data: Any? = null, splitMode: SplitMode = SplitMode.WHOLE_LINE) {
val string = data.toString()
append("$string\n", splitMode)
}
fun build(): List<MessageCreateData> {
if (buffer.isNotBlank()) {
messages.add(buffer)
}
return messages.map {
message {
content = it
}.create()
}
}
private fun splitMessage() {
messages.add(buffer)
this.buffer = ""
}
}
enum class SplitMode {
WHOLE_LINE,
BREAK_LINE,
BREAK_WORD
}
| 0
|
Kotlin
|
1
| 0
|
5c07baeff7209c58f2ef84d9944d0b64a8aa913b
| 3,438
|
bot-core
|
MIT License
|
graph/graph-application/src/main/kotlin/eu/tib/orkg/prototype/contenttypes/services/actions/compat.kt
|
TIBHannover
| 197,416,205
| false
|
{"Kotlin": 2548386, "Cypher": 216087, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240}
|
package eu.tib.orkg.prototype.contenttypes.services.actions
import eu.tib.orkg.prototype.contenttypes.api.CreateContributionUseCase
import eu.tib.orkg.prototype.contenttypes.api.CreatePaperUseCase
import eu.tib.orkg.prototype.contenttypes.services.actions.contribution.ContributionAction
import eu.tib.orkg.prototype.contenttypes.services.actions.paper.PaperAction
internal typealias BakedStatement = Triple<String, String, String>
internal typealias CreatePaperCommand = CreatePaperUseCase.CreateCommand
internal typealias CreateContributionCommand = CreateContributionUseCase.CreateCommand
internal typealias PaperState = PaperAction.State
internal typealias ContributionState = ContributionAction.State
| 0
|
Kotlin
|
2
| 5
|
f96c2c41a6e2b1da63a9d93973602573b596ed0d
| 710
|
orkg-backend
|
MIT License
|
example/android/app/src/main/kotlin/com/example/trackierfluttersdk_example/MainActivity.kt
|
trackier
| 403,994,383
| false
|
{"Kotlin": 15843, "Dart": 13394, "Swift": 8927, "Ruby": 2266, "Objective-C": 777, "Java": 655}
|
package com.example.trackierfluttersdk_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Kotlin
|
0
| 1
|
0a97a8d2132e6412e43ded7c6fbfec840ff31826
| 143
|
flutter-sdk
|
MIT License
|
generators/src/main/kotlin/org/kryptonmc/generators/utils.kt
|
KryptonMC
| 255,582,002
| false
| null |
/*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kryptonmc.generators
import java.lang.reflect.Field
import java.lang.reflect.Modifier
import java.nio.file.Path
import kotlin.io.path.createDirectories
import kotlin.io.path.createFile
fun Path.tryCreateDirectories(): Path = catchAndReturnSelf { createDirectories() }
fun Path.tryCreateFile(): Path = catchAndReturnSelf { createFile() }
private inline fun <T> T.catchAndReturnSelf(action: () -> Unit): T = try {
action()
this
} catch (_: Exception) {
this
}
fun Class<*>.staticFields(): Sequence<Field> = declaredFields.asSequence().filter { Modifier.isStatic(it.modifiers) }
fun <T> Class<*>.staticConstantFields(type: Class<T>): Sequence<Field> = staticFields().filter { type.isAssignableFrom(it.type) }
fun <T> Class<*>.collectFields(type: Class<T>): Sequence<CollectedField<T>> = staticConstantFields(type).map { CollectedField(it, type) }
/**
* Kotlinpoet likes to enforce certain restrictions when you use it to generate
* code.
*
* Square believes that these are all conventional, and should be used by
* everyone, however this angers me a little, since I want code to look how I
* would write it manually, so that it is consistent with the rest of the
* project.
*
* To get around the styling that Square enforces, I have created this
* function, which is specifically designed to correct all of the styling that
* is wrong.
*/
fun String.performReplacements(type: String, name: String): String =
replace("@JvmField\n {4}public val (.*): RegistryReference<$type> =(\n {12})?(.*)(\n)?".toRegex(),
"@JvmField\n public val $1: RegistryReference<$type> = $3")
.replace("= ", "= ")
.replace("public object $name {\n", "public object $name {\n\n // @formatter:off\n")
.replace("\n @JvmStatic", "\n\n // @formatter:on\n @JvmStatic")
.replace("`", "")
.replace("(.*)of(.*) =\n( )+(.*)".toRegex(), "$1of$2 = $4")
.replace("import kotlin.String\n", "")
.replace("import kotlin.Suppress\n", "")
.replace("import kotlin.jvm.JvmField\n", "")
.replace("import kotlin.jvm.JvmStatic\n", "")
| 27
|
Kotlin
|
11
| 233
|
a9eff5463328f34072cdaf37aae3e77b14fcac93
| 2,860
|
Krypton
|
Apache License 2.0
|
cloud-integration/spotify/spotify-impl/src/main/kotlin/me/freedom4live/singtocloud/application/cloud/integration/spotify/impl/config/SpotifyIntegrationConfig.kt
|
alekseinovikov
| 241,181,307
| false
|
{"Kotlin": 22934}
|
package me.freedom4live.singtocloud.application.cloud.integration.spotify.impl.config
import org.springframework.context.annotation.Configuration
@Configuration
class SpotifyIntegrationConfig
| 0
|
Kotlin
|
0
| 0
|
ffd22a2d3c1ad63ad7e993fc5a56170b6c4dc5ad
| 193
|
sing-to-cloud
|
MIT License
|
src/main/kotlin/org/batteryparkdev/kotlindev/collect/FlatMapDemo.kt
|
fcriscuo
| 573,547,848
| false
|
{"Kotlin": 63433}
|
package org.batteryparkdev.kotlindev.collect
fun main() {
val names = listOf<String>("Ann","Bob","Charles" )
val chars1: List<Char> = names.flatMap { it.toList() }
println(chars1)
val mapRes: List<List<Char>> = names.map { it.toList()}
println(mapRes)
val chars2 = mapRes.flatten()
println(chars2)
println(chars1 == chars2)
}
| 0
|
Kotlin
|
0
| 0
|
9e7bd1801a4d11b73e46071efdaf8bd3d5c86e47
| 359
|
KotlinSandbox
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/de/seemoo/at_tracking_detection/ui/debug/DebugScansFragment.kt
|
seemoo-lab
| 385,199,222
| false
|
{"Kotlin": 491934, "Ruby": 1078}
|
package de.seemoo.at_tracking_detection.ui.debug
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asFlow
import androidx.lifecycle.asLiveData
import com.google.android.material.composethemeadapter.MdcTheme
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import de.seemoo.at_tracking_detection.R
import de.seemoo.at_tracking_detection.database.models.Scan
import de.seemoo.at_tracking_detection.database.repository.BeaconRepository
import de.seemoo.at_tracking_detection.database.repository.DeviceRepository
import de.seemoo.at_tracking_detection.database.repository.ScanRepository
import de.seemoo.at_tracking_detection.databinding.FragmentDebugScansBinding
import de.seemoo.at_tracking_detection.util.risk.RiskLevelEvaluator
import java.text.DateFormat
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
@AndroidEntryPoint
class DebugScansFragment: Fragment() {
private val viewModel: DebugScanViewModel by viewModels()
private var binding: FragmentDebugScansBinding? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_debug_scans, container, false)
// binding?.lifecycleOwner = viewLifecycleOwner
// binding?.vm = viewModel
val scansView = binding?.root?.findViewById<ComposeView>(R.id.debug_scans_view)
scansView?.setContent {
MdcTheme {
LastScanList()
}
}
return binding?.root
}
@Composable
private fun Test() {
Text(
text = stringResource(id = R.string.last_scans),
style = MaterialTheme.typography.h6,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = Dp(8.0F))
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
@Composable
private fun DateText(scan: Scan) {
Row {
if (scan.startDate != null) {
Text(text = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(scan.startDate))
}
if (scan.endDate != null) {
Text(" - ")
Text(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(scan.endDate))
}
}
}
@Composable
private fun LastScanList() {
Column {
Test()
LazyColumn {
items(viewModel.scans) { scan ->
Row (Modifier.padding(horizontal = Dp(8.0F))) {
Column {
DateText(scan = scan)
Text(text = "| ${scan.duration} | Found: ${scan.noDevicesFound} | Mode: ${scan.scanMode} | ${scan.isManual}")
Divider()
}
}
}
}
}
}
}
| 20
|
Kotlin
|
99
| 1,848
|
2b0e247158376e3169601e44eb286f7fbedae2de
| 3,879
|
AirGuard
|
Apache License 2.0
|
src/main/kotlin/com/github/durun/nitron/core/config/loader/NitronConfigLoader.kt
|
Durun
| 212,494,212
| false
| null |
package com.github.durun.nitron.core.config.loader
import com.github.durun.nitron.core.config.NitronConfig
object NitronConfigLoader : ConfigLoader<NitronConfig> by KSerializationConfigLoader(NitronConfig.serializer())
| 7
|
Kotlin
|
0
| 0
|
0e2f522025e156d74ce2345b1004d6bc684a7763
| 220
|
nitron
|
MIT License
|
gui-app/src/main/kotlin/dev/robocode/tankroyale/gui/ui/console/ConsoleHtmlEditorKit.kt
|
robocode-dev
| 457,523,927
| false
|
{"Kotlin": 510460, "Java": 418305, "C#": 407310, "SCSS": 1367, "TypeScript": 1071, "Shell": 83}
|
package dev.robocode.tankroyale.gui.ui.console
import javax.swing.text.html.HTMLEditorKit
open class ConsoleHtmlEditorKit : HTMLEditorKit() {
init {
styleSheet.apply {
addRule("span { color: white; font-family: monospace; font-size: 12;}")
// Bot console
addRule(".info { color: \"#377B37\"; }") // olive green
addRule(".error { color: \"#FF5733\"; }") // dark pink
addRule(".linenumber { color: gray; }")
// ANSI colors
addRule(".esc.black { color: Black }")
addRule(".esc.red { color: Red }")
addRule(".esc.green { color: Green }")
addRule(".esc.yellow { color: Yellow }")
addRule(".esc.blue { color: Blue }")
addRule(".esc.magenta { color: Magenta }")
addRule(".esc.cyan { color: Cyan }")
addRule(".esc.white { color: LightGray }")
addRule(".esc.bright.black { color: DarkGray }")
addRule(".esc.bright.red { color: LightRed }")
addRule(".esc.bright.green { color: LightGreen }")
addRule(".esc.bright.yellow { color: LightYellow }")
addRule(".esc.bright.blue { color: LightBlue }")
addRule(".esc.bright.magenta { color: LightMagenta }")
addRule(".esc.bright.cyan { color: LightCyan }")
addRule(".esc.bright.white { color: White }")
}
}
}
| 3
|
Kotlin
|
14
| 86
|
69e40aef66df6dd44bf7433e4919b64ae0a9d784
| 1,433
|
tank-royale
|
Apache License 2.0
|
subprojects/delivery/upload-cd-build-result/src/main/kotlin/com/avito/cd/CdBuildConfigValidator.kt
|
avito-tech
| 230,265,582
| false
| null |
package com.avito.cd
internal class CdBuildConfigValidator(private val config: CdBuildConfig) {
fun validate() {
checkUnsupportedDeployments()
checkUniqueGooglePlayDeployments()
checkQappsDeployments()
}
private fun checkUnsupportedDeployments() {
val unknownDeployments = config.deployments.filterIsInstance<CdBuildConfig.Deployment.Unknown>()
require(unknownDeployments.isEmpty()) {
"Unknown deployment types: $unknownDeployments"
}
}
private fun checkUniqueGooglePlayDeployments() {
val googlePlayDeployments = config.deployments.filterIsInstance<CdBuildConfig.Deployment.GooglePlay>()
val deploysByVariant = googlePlayDeployments.groupBy(CdBuildConfig.Deployment.GooglePlay::buildVariant)
deploysByVariant.forEach { (_, deploys) ->
require(deploys.size == 1) {
"Must be one deploy per variant, but was: $googlePlayDeployments"
}
}
}
private fun checkQappsDeployments() {
val deployments = config.deployments.filterIsInstance<CdBuildConfig.Deployment.Qapps>()
require(deployments.size <= 1) {
"Must be one Qapps deployment, but was: $deployments"
}
if(deployments.isNotEmpty()){
require(config.schemaVersion >= 2) {
"Qapps deployments is supported only in the 2'nd version of contract"
}
}
}
}
| 4
| null |
37
| 331
|
44a9f33b2e4ac4607a8269cbf4f7326ba40402fe
| 1,458
|
avito-android
|
MIT License
|
kotlin-options/src/test/kotlin/com/petertackage/kotlinoptions/OptionTest.kt
|
peter-tackage
| 89,383,377
| false
| null |
package com.petertackage.kotlinoptions
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
class OptionTest {
@Rule
@JvmField
var thrown = ExpectedException.none()
@Test
fun `optionOf returns None when value is null`() {
assertThat(optionOf(null) is None).isTrue()
}
@Test
fun `optionOf returns Some when value is non-null`() {
assertThat(optionOf("abc") is Some).isTrue()
}
@Test
fun `optionOf None is single instance`() {
assertThat(optionOf(null)).isSameAs(optionOf(null))
}
@Test
fun `optionOf Some is not single instance`() {
val value = "abc"
assertThat(optionOf(value)).isNotSameAs(optionOf(value))
}
@Test
fun `ifSome returns self`() {
val option = optionOf("value")
val result = option.ifSome { }
assertThat(result).isEqualTo(option)
}
@Test
fun `asType casts type to supertype`() {
val option = optionOf("value")
val result = option.asType<CharSequence>()
assertThat(result).isEqualTo(option)
}
@Test
fun `asType returns None if given supertype is not valid`() {
val option = optionOf("value")
val result = option.asType<Int>()
assertThat(result).isEqualTo(None)
}
@Test
fun `asType on None returns None`() {
assertThat(None.asType<Int>()).isEqualTo(None)
}
@Test
fun `ifSome performs action with value when Some`() {
val value = "value"
val action: (String) -> Unit = mock()
Some(value).ifSome(action)
verify(action).invoke(value)
}
@Test
fun `ifSome does not perform action with value when None`() {
val action: (String) -> Unit = mock()
None.ifSome(action)
verify(action, never()).invoke(any())
}
@Test
fun `ifNone returns self`() {
val result = None.ifNone { }
assertThat(result).isEqualTo(None)
}
@Test
fun `ifNone performs action when None`() {
val action: () -> Unit = mock()
None.ifNone(action)
verify(action).invoke()
}
@Test
fun `ifNone does not perform action when Some`() {
val action: () -> Unit = mock()
Some("value").ifNone(action)
verify(action, never()).invoke()
}
@Test
fun `map invokes function with value when Some`() {
val value = "value"
val function: (String) -> Int = mock()
Some(value).map(function)
verify(function).invoke(value)
}
@Test
fun `map returns Some when function returns non-null`() {
val result = optionOf("abc").map { 0 }
assertThat(result is Some).isTrue()
}
@Test
fun `map returns function value when Some`() {
val value = "value"
val function: (String) -> Int = { it.length }
val result = Some(value).map(function)
assertThat(result).isEqualTo(optionOf(value.length))
assertThat(result.getUnsafe()).isEqualTo(value.length)
}
@Test
fun `map does not invoke function when None`() {
val function: (String) -> Int = mock()
None.map(function)
verify(function, never()).invoke(any())
}
@Test
fun `flatmap returns function value when Some`() {
val value = "value"
val function: (String) -> Option<Int> = { Some(it.length) }
val result = Some(value).flatMap(function)
assertThat(result).isEqualTo(Some(value.length))
}
@Test
fun `flatmap does not invoke function value when None`() {
val function: (String) -> Option<Int> = mock()
None.flatMap(function)
verify(function, never()).invoke(any())
}
@Test
fun `flatmap returns None when None`() {
val function: (String) -> Option<Int> = mock()
val result = None.flatMap(function)
assertThat(result is None).isTrue()
}
@Test
fun `filter returns Some when matches filter`() {
val filterPred: (String) -> Boolean = { it == "value" }
val result = Some("value").filter(filterPred)
assertThat(result is Some).isTrue()
}
@Test
fun `filter returns value when matches filter`() {
val value = "value"
val filterPred: (String) -> Boolean = { it == value }
val result = Some(value).filter(filterPred)
assertThat(result).isEqualTo(optionOf(value))
assertThat(result.getUnsafe()).isEqualTo(value)
}
@Test
fun `filter returns None when does not match filter`() {
val filterPred: (String) -> Boolean = { it == "not value" }
val result = Some("value").filter(filterPred)
assertThat(result is None).isTrue()
}
@Test
fun `matchAction invokes someAction with value not noneAction when Some`() {
val value = "value"
val someAction: (String) -> Unit = mock()
val noneAction: () -> Unit = mock()
Some(value).matchAction(someAction, noneAction)
verify(someAction).invoke(value)
verify(noneAction, never()).invoke()
}
@Test
fun `matchAction invokes noneAction not someAction when None`() {
val someAction: (String) -> Unit = mock()
val noneAction: () -> Unit = mock()
None.matchAction(someAction, noneAction)
verify(noneAction).invoke()
verify(someAction, never()).invoke(any())
}
@Test
fun `match invokes someFunction with value not noneFunction when Some`() {
val value = "value"
val someFunction: (String) -> Int = mock()
val noneFunction: () -> Int = mock()
Some(value).match(someFunction, noneFunction)
verify(someFunction).invoke(value)
verify(noneFunction, never()).invoke()
}
@Test
fun `match returns someFunction result when Some`() {
val someFunction: (String) -> Int = { 6 }
val noneFunction: () -> Int = mock()
val result = Some("value").match(someFunction, noneFunction)
assertThat(result).isEqualTo(6)
}
@Test
fun `match invokes noneFunction not someFunction when None`() {
val someFunction: (String) -> Int = mock()
val noneFunction: () -> Int = mock()
None.match(someFunction, noneFunction)
verify(noneFunction).invoke()
verify(someFunction, never()).invoke(any())
}
@Test
fun `match returns noneFunction result when None`() {
val someFunction: (String) -> Int = mock()
val noneFunction: () -> Int = { 6 }
val result = None.match(someFunction, noneFunction)
assertThat(result).isEqualTo(6)
}
@Test
fun `and invokes action with values when both Options are Some`() {
val option1 = optionOf("1")
val option2 = optionOf("2")
val action: (String, String) -> Unit = mock()
option1.and(option2, action)
verify(action).invoke("1", "2")
}
@Test
fun `and does not invoke action when first Option is None`() {
val option1 = None
val option2 = optionOf("2")
val action: (String, String) -> Unit = mock()
option1.and(option2, action)
verify(action, never()).invoke(any(), any())
}
@Test
fun `and does not invoke action when second Option is None`() {
val option1 = optionOf("1")
val option2 = None
val action: (String, String) -> Unit = mock()
option1.and(option2, action)
verify(action, never()).invoke(any(), any())
}
@Test
fun `getUnsafe returns value when Some`() {
val value = "value"
val result = optionOf(value).getUnsafe()
assertThat(result).isEqualTo(value)
}
@Test
fun `getUnsafe throws IllegalStateException when None`() {
thrown.expect(IllegalStateException::class.java)
thrown.expectMessage("Attempt to unsafely access value when Option is None")
None.getUnsafe()
}
@Test
fun `equals returns true when self`() {
val option1 = None
assertThat(option1 == option1).isTrue()
}
@Test
fun `equals returns true when both None`() {
val option1 = None
val option2 = None
assertThat(option1 == option2).isTrue()
}
@Test
fun `equals returns false when this Some other None`() {
val option1 = optionOf("value")
val option2 = None
assertThat(option1 == option2).isFalse()
}
@Test
fun `equals returns false when this None other Some`() {
val option1 = None
val option2 = optionOf("value")
assertThat(option1 == option2).isFalse()
}
@Test
fun `equals returns true when both same value`() {
val option1 = Some("value")
val option2 = Some("value")
assertThat(option1 == option2).isTrue()
}
@Test
fun `equals returns true when both same Some instance`() {
val value = "value"
val option = Some(value)
assertThat(option == option).isTrue()
}
@Test
fun `equals returns true when both same value instance`() {
val value = "value"
val option1 = Some(value)
val option2 = Some(value)
assertThat(option1 == option2).isTrue()
}
@Test
fun `equals returns true when both same None instance`() {
val option = None
assertThat(option == option).isTrue()
}
@Test
fun `equals returns false when different types`() {
val option1 = optionOf("value")
val option2 = optionOf(1)
assertThat(option1 == option2).isFalse()
}
@Test
fun `hashCode is value hashCode when Some`() {
val value = "value"
val hashCode = Some(value).hashCode()
assertThat(hashCode).isEqualTo(value.hashCode())
}
@Test
fun `hashCode is constant when None`() {
val hashCode1 = None.hashCode()
val hashCode2 = None.hashCode()
assertThat(hashCode1).isEqualTo(hashCode2)
}
@Test
fun `toString is value toString when Some`() {
val value = 1
val toString = Some(value).toString()
assertThat(toString).isEqualTo("Some(value=1)")
}
@Test
fun `toString is None when None`() {
val toString = None.toString()
assertThat(toString).isEqualTo("None")
}
@Test
fun `toNullable returns value when Some`() {
val expected: String? = "value"
val nullable: String? = Some("value").toNullable()
assertThat(nullable).isEqualTo(expected)
}
@Test
fun `toNullable returns null when None`() {
val nullable: String? = None.toNullable()
assertThat(nullable).isNull()
}
@Test
fun `tryAsOption returns Some if non-null value returned`() {
val expected = "result"
val result = tryAsOption { expected }
assertThat(result.getUnsafe()).isEqualTo(expected)
}
@Test
fun `tryAsOption returns None if null value returned`() {
val result = tryAsOption { null }
assertThat(result is None).isTrue()
}
@Test
fun `tryAsOption returns None if function throws`() {
val result = tryAsOption { throw RuntimeException("") }
assertThat(result is None).isTrue()
}
@Test
fun `orDefault returns value when Some`() {
val value = "abc"
val result = Some(value).orDefault { "xyz" }
assertThat(result).isEqualTo(value)
}
@Test
fun `orDefault returns default when None`() {
val value = "abc"
val result = None.orDefault { value }
assertThat(result).isEqualTo(value)
}
}
| 4
|
Kotlin
|
2
| 29
|
7643568965ee88c5cd2a6130d9e7d883f670ed0c
| 11,940
|
kotlin-options
|
Apache License 2.0
|
app/src/main/java/com/ottistech/indespensa/ui/viewmodel/ShopHistoryViewModel.kt
|
OttistTech
| 829,230,723
| false
|
{"Kotlin": 201564}
|
package com.ottistech.indespensa.ui.viewmodel
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ottistech.indespensa.data.exception.ResourceNotFoundException
import com.ottistech.indespensa.data.repository.ShopRepository
import com.ottistech.indespensa.ui.UiConstants
import com.ottistech.indespensa.webclient.dto.shoplist.PurchaseDTO
import kotlinx.coroutines.launch
class ShopHistoryViewModel(
private val repository: ShopRepository
) : ViewModel() {
private val TAG = "SHOP HISTORY VIEWMODEL"
private val _history = MutableLiveData<List<PurchaseDTO>?>()
val history: LiveData<List<PurchaseDTO>?> = _history
private val _error = MutableLiveData<Int?>()
val error: LiveData<Int?> = _error
fun fetchHistory() {
Log.d(TAG, "[fetchHistory] Requesting history")
viewModelScope.launch {
try {
_history.value = repository.getHistory()
_error.value = null
} catch(e: ResourceNotFoundException) {
_error.value = UiConstants.ERROR_NOT_FOUND
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0c33630caa8dc99bf4999d672d3e2826be31d7fa
| 1,225
|
app-indespensa
|
MIT License
|
core/ui/src/main/java/com/peonlee/core/ui/base/BaseBottomSheetFragment.kt
|
YAPP-Github
| 634,125,265
| false
|
{"Kotlin": 288963}
|
package com.peonlee.core.ui.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.peonlee.core.ui.R
import com.peonlee.core.ui.databinding.BaseBottomsheetDialogBinding
import com.peonlee.model.product.ProductSearchConditionUiModel
/**
* BottomSheetFragment 공통 코드 관리
*/
abstract class BaseBottomSheetFragment(
private val title: String
) : BottomSheetDialogFragment() {
private var binding: BaseBottomsheetDialogBinding? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = BaseBottomsheetDialogBinding.inflate(inflater, container, false)
binding?.layoutFilter?.run {
addView(
getFilterLayout(inflater, this)
)
}
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialog?.window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
dialog?.window?.setDimAmount(0.6f)
// 하위 클래스에 따른 filter layout 추가
binding?.apply {
tvTitle.text = title
btnComplete.setOnClickListener { onClickComplete() }
}
}
override fun getTheme(): Int {
return R.style.RoundedBottomSheetDialog
}
abstract fun getFilterLayout(layoutInflater: LayoutInflater, parent: ViewGroup): View
abstract fun onClickComplete()
// 변경된 filter 값 변경
abstract fun setChangedFilter(productSearchCondition: ProductSearchConditionUiModel): BaseBottomSheetFragment
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
}
| 10
|
Kotlin
|
0
| 8
|
8fbb7589215ac6e0d43a7a0ff6e08aca3dafd27e
| 1,901
|
pyeonlee-aos
|
Apache License 2.0
|
android-aop-core/src/main/java/com/flyjingfish/android_aop_core/utils/DebugUtils.kt
|
FlyJingFish
| 722,020,803
| false
|
{"Kotlin": 514894, "Java": 95343}
|
package com.flyjingfish.android_aop_core.utils
import android.content.Context
import android.content.pm.ApplicationInfo
import com.flyjingfish.android_aop_core.AndroidAopContentProvider
internal object DebugUtils {
private var init = false
private var debug = false
fun isDebug(): Boolean {
return if (init) {
debug
} else {
val debugValue = isApkInDebug()
debug = debugValue
init = true
debugValue
}
}
private fun isApkInDebug(): Boolean {
val context: Context = AndroidAopContentProvider.getAppContext()
return try {
val info = context.applicationInfo
info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
} catch (_: Exception) {
false
}
}
}
| 0
|
Kotlin
|
29
| 433
|
b6743fd17ae2c062bc1ee2104d2d95c931139998
| 822
|
AndroidAOP
|
Apache License 2.0
|
src/main/java/com/dzen/campfire/server/tables/TActivitiesCollisions.kt
|
timas130
| 443,572,543
| true
|
{"Kotlin": 1072092}
|
package com.dzen.campfire.server.tables
import com.dzen.campfire.api.API
import com.sup.dev.java_pc.sql.Sql
object TActivitiesCollisions {
val NAME = "activities_collisions"
val id = "id"
val type = "type"
val account_id = "account_id"
val activity_id = "activity_id"
val date_create = "date_create"
val tag_1 = "tag_1"
val tag_2 = "tag_2"
val tag_3 = "tag_3"
val tag_s_1 = "tag_s_1"
val tag_s_2 = "tag_s_2"
val tag_s_3 = "tag_s_3"
val ACCOUNT_NAME = "(SELECT " + TAccounts.name + " FROM " + TAccounts.NAME + " WHERE " + TAccounts.id + "=" + tag_1 + ")"
val ACCOUNT_IMAGE_ID = "(SELECT " + TAccounts.img_id + " FROM " + TAccounts.NAME + " WHERE " + TAccounts.id + "=" + tag_1 + ")"
val ACCOUNT_MEMBER_STATUS = Sql.IFNULL("(SELECT " + tag_1 + " FROM $NAME as t WHERE t." + account_id + "=" + NAME + "." + account_id + " AND " + "t." + activity_id + "=" + NAME + "." + account_id + " AND " + "t." + type + "=" + API.ACTIVITIES_COLLISION_TYPE_RELAY_RACE_MEMBER + " ${Sql.LIMIT} 1)", "0")
val ACCOUNT_POST_ID = Sql.IFNULL("(SELECT " + tag_1 + " FROM $NAME as t WHERE t." + account_id + "=" + NAME + "." + account_id + " AND " + "t." + activity_id + "=" + NAME + "." + account_id + " AND " + "t." + type + "=" + API.ACTIVITIES_COLLISION_TYPE_RELAY_RACE_POST + " ${Sql.LIMIT} 1)", "0")
val ACCOUNT_LOST = Sql.IFNULL("(SELECT " + tag_1 + " FROM $NAME as t WHERE t." + account_id + "=" + NAME + "." + account_id + " AND " + "t." + activity_id + "=" + NAME + "." + account_id + " AND " + "t." + type + "=" + API.ACTIVITIES_COLLISION_TYPE_RELAY_RACE_POST + " ${Sql.LIMIT} 1)", "0")
val ACCOUNT_SUBSCRIBE_STATUS = Sql.IFNULL("(SELECT " + tag_1 + " FROM $NAME as t WHERE t." + account_id + "=" + NAME + "." + account_id + " AND " + "t." + activity_id + "=" + NAME + "." + account_id + " AND " + "t." + type + "=" + API.ACTIVITIES_COLLISION_TYPE_SUBSCRIBE + " ${Sql.LIMIT} 1)", "0")
}
| 0
|
Kotlin
|
0
| 0
|
40a2fbdbbdbe6706ed852f7218cb10fd57e50445
| 1,950
|
CampfireServer
|
Apache License 2.0
|
app/src/test/kotlin/com/mgaetan89/showsrage/activity/MainActivity_GetSettingFragmentForPathTest.kt
|
HD-CIPL
| 61,888,053
| true
|
{"Kotlin": 664263}
|
package com.mgaetan89.showsrage.activity
import com.mgaetan89.showsrage.fragment.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class MainActivity_GetSettingFragmentForPathTest(val path: String?, val fragmentClass: Class<SettingsFragment>?) {
@Test
fun getSettingFragmentForPath() {
if (this.fragmentClass == null) {
assertThat(MainActivity.getSettingFragmentForPath(this.path)).isNull()
} else {
assertThat(MainActivity.getSettingFragmentForPath(this.path)).isExactlyInstanceOf(this.fragmentClass)
}
}
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): Collection<Array<Any?>> {
return listOf(
arrayOf<Any?>(null, null),
arrayOf<Any?>("", null),
arrayOf<Any?>(" ", null),
arrayOf<Any?>("/", SettingsFragment::class.java),
arrayOf<Any?>("/wrong_path", null),
arrayOf<Any?>("/about", SettingsAboutFragment::class.java),
arrayOf<Any?>("/about/licenses", SettingsAboutLicensesFragment::class.java),
arrayOf<Any?>("/about/showsrage", SettingsAboutShowsRageFragment::class.java),
arrayOf<Any?>("/about", SettingsAboutFragment::class.java),
arrayOf<Any?>("/behavior", SettingsBehaviorFragment::class.java),
arrayOf<Any?>("/display", SettingsDisplayFragment::class.java),
arrayOf<Any?>("/experimental_features", SettingsExperimentalFeaturesFragment::class.java),
arrayOf<Any?>("/server", SettingsServerFragment::class.java),
arrayOf<Any?>("/server/api_key", SettingsServerApiKeyFragment::class.java)
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
27453cd388a73cc2ff9abc69109a65fbf1ac5977
| 1,954
|
ShowsRage
|
Apache License 2.0
|
project/src/main/kotlin/cga/exercise/components/geometry/Transformable.kt
|
CaSoThi
| 396,830,912
| true
|
{"Kotlin": 105668, "GLSL": 13895}
|
package cga.exercise.components.geometry
import org.joml.*
import org.joml.Matrix4f
import org.joml.Vector3f
import kotlin.math.pow
import kotlin.math.sqrt
open class Transformable(var parent : Transformable? = null) : ITransformable{
var modelMat = Matrix4f()
/**
* Rotates object around its own origin.
* @param pitch radiant angle around x-axis ccw
* @param yaw radiant angle around y-axis ccw
* @param roll radiant angle around z-axis ccw
*/
override fun rotateLocal(pitch: Float, yaw: Float, roll: Float){
modelMat.rotateXYZ(pitch, yaw, roll)
}
fun rotateLocalBack(pitch: Float, yaw: Float, roll: Float){
modelMat.rotateZYX(roll, yaw, pitch)
}
/**
* Rotates object around given rotation center.
* @param pitch radiant angle around x-axis ccw
* @param yaw radiant angle around y-axis ccw
* @param roll radiant angle around z-axis ccw
* @param altMidpoint rotation center
*/
override fun rotateAroundPoint(pitch: Float, yaw: Float, roll: Float, altMidpoint: Vector3f){
var temp = Matrix4f()
temp.translate(altMidpoint)
temp.rotateXYZ(pitch, yaw, roll)
temp.translate(Vector3f(altMidpoint).negate())
modelMat = temp.mul(modelMat)
}
fun rotateAroundPointModified(pitch: Float, yaw: Float, roll: Float, altMidpoint: Vector3f){
var temp = Matrix4f()
temp.rotateLocal(0.002f, pitch,yaw, roll)
modelMat = temp.mul(modelMat)
}
/**
* Translates object based on its own coordinate system.
* @param deltaPos delta positions
*/
override fun translateLocal(deltaPos: Vector3f){
modelMat.translate(deltaPos)
}
/**
* Translates object based on its parent coordinate system.
* Hint: global operations will be left-multiplied
* @param deltaPos delta positions (x, y, z)
*/
override fun translateGlobal(deltaPos: Vector3f){
var temp = Matrix4f()
modelMat = temp.translate(deltaPos).mul(modelMat)
}
/**
* Scales object related to its own origin
* @param scale scale factor (x, y, z)
*/
override fun scaleLocal(scale: Vector3f){
modelMat.scale(scale)
}
/**
* Returns position based on aggregated translations.
* Hint: last column of model matrix
* @return position
*/
override fun getPosition(): Vector3f{
return Vector3f(modelMat.m30(), modelMat.m31(), modelMat.m32())
}
/**
* Returns position based on aggregated translations incl. parents.
* Hint: last column of world model matrix
* @return position
*/
override fun getWorldPosition(): Vector3f{
var world = getWorldModelMatrix()
return Vector3f(world.m30(), world.m31(), world.m32())
}
/**
* Returns x-axis of object coordinate system
* Hint: first normalized column of model matrix
* @return x-axis
*/
override fun getXAxis(): Vector3f{
return Vector3f(modelMat.m00(),modelMat.m01(), modelMat.m02()).normalize()
}
/**
* Returns y-axis of object coordinate system
* Hint: second normalized column of model matrix
* @return y-axis
*/
override fun getYAxis(): Vector3f{
return Vector3f(modelMat.m10(),modelMat.m11(), modelMat.m12()).normalize()
}
/**
* Returns z-axis of object coordinate system
* Hint: third normalized column of model matrix
* @return z-axis
*/
override fun getZAxis(): Vector3f{
return Vector3f(modelMat.m20(), modelMat.m21(), modelMat.m22()).normalize()
// return Vector3f(modelMat.m02(), modelMat.m12(), modelMat.m22())
}
/**
* Returns x-axis of world coordinate system
* Hint: first normalized column of world model matrix
* @return x-axis
*/
override fun getWorldXAxis(): Vector3f{
var worldMat = getWorldModelMatrix()
return Vector3f(worldMat.m00(),worldMat.m01(), worldMat.m02()).normalize()
// return (Vector3f(worldMat.m00(),worldMat.m10(), worldMat.m20()))
}
/**
* Returns y-axis of world coordinate system
* Hint: second normalized column of world model matrix
* @return y-axis
*/
override fun getWorldYAxis(): Vector3f{
var worldMat = getWorldModelMatrix()
return Vector3f(worldMat.m10(),worldMat.m11(), worldMat.m12()).normalize()
//return Vector3f(worldMat.m01(),worldMat.m11(), worldMat.m21())
}
/**
* Returns z-axis of world coordinate system
* Hint: third normalized column of world model matrix
* @return z-axis
*/
override fun getWorldZAxis(): Vector3f{
var worldMat = getWorldModelMatrix()
return Vector3f(worldMat.m20(), worldMat.m21(), worldMat.m22()).normalize()
}
/**
* Returns multiplication of world and object model matrices.
* Multiplication has to be recursive for all parents.
* Hint: scene graph
* @return world modelMatrix
*/
override fun getWorldModelMatrix(): Matrix4f{
var worldMat = getLocalModelMatrix()
parent?.getWorldModelMatrix()?.mul(modelMat, worldMat)
return worldMat
}
/**
* Returns object model matrix
* @return modelMatrix
*/
override fun getLocalModelMatrix(): Matrix4f = Matrix4f(modelMat)
fun setPosition(x: Float, y: Float, z: Float) {
//model_matrix = Matrix4f().translate(Vector3f(x,y,z))
modelMat.setTranslation(x,y,z)
}
fun getXDir() = java.lang.Math.atan2(modelMat.m11().toDouble(), modelMat.m12().toDouble())
fun getYDir() = java.lang.Math.atan2(modelMat.m00().toDouble(), modelMat.m02().toDouble())
fun getZDir() = Math.asin(modelMat.m01()).toDouble()
}
| 0
|
Kotlin
|
0
| 0
|
1d2c0fdf0de94336a1adcff556b33c4ce70a4515
| 5,794
|
CGA_Project
|
MIT License
|
app/src/main/java/com/globalfsm/features/orderhistory/api/LocationUpdateRepository.kt
|
DebashisINT
| 614,841,798
| false
| null |
package com.globalfsm.features.orderhistory.api
import com.globalfsm.base.BaseResponse
import com.globalfsm.features.orderhistory.model.LocationUpdateRequest
import io.reactivex.Observable
/**
* Created by Pratishruti on 23-11-2017.
*/
class LocationUpdateRepository(val apiService:LocationUpdateApi) {
fun sendLocationUpdate(location: LocationUpdateRequest): Observable<BaseResponse> {
return apiService.sendLocationUpdates(location)
}
}
| 0
|
Kotlin
|
0
| 0
|
f0435b0dd4b1ce20137b6a892ed58c2b7d7142f7
| 458
|
GLOBAL
|
Apache License 2.0
|
app/src/main/java/com/github/k1rakishou/kpnc/domain/MessageReceiver.kt
|
K1rakishou
| 628,245,583
| false
| null |
package com.github.k1rakishou.kpnc.domain
interface MessageReceiver {
fun onGotNewMessage(messageId: String?, data: String?)
data class Message(
val messageId: String,
val data: String
)
}
| 0
|
Kotlin
|
0
| 0
|
0675dbf74239ea36b297ed4a7a12e05b14e148d4
| 205
|
KPNC-client
|
MIT License
|
app/src/main/java/com/guillaumewilmot/swoleai/util/fragmentBackstack/FragmentBackstackImpl.kt
|
Poncholay
| 470,056,464
| false
| null |
package com.guillaumewilmot.swoleai.util.fragmentBackstack
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit
import com.guillaumewilmot.swoleai.R
import com.guillaumewilmot.swoleai.controller.ParentFragment
import kotlinx.coroutines.ExperimentalCoroutinesApi
import java.lang.ref.WeakReference
import java.util.*
@ExperimentalCoroutinesApi
class FragmentBackstackImpl : FragmentBackstack {
private var _currentFragment: WeakReference<ParentFragment<*>>? = null
private var _currentTab: FragmentBackstack.FragmentTab = FragmentBackstack.Tab.DASHBOARD
private val _pool: Bundle = Bundle()
private val _tagStacks = mapOf<FragmentBackstack.FragmentTab, Stack<String>>(
FragmentBackstack.Tab.DASHBOARD to Stack(),
FragmentBackstack.Tab.SESSION to Stack()
)
override val currentTab: FragmentBackstack.FragmentTab
get() = _currentTab
/**
* Starts a new fragment in the current tab
*/
override fun push(
fragmentManager: FragmentManager,
newFragment: ParentFragment<*>,
addToBackStack: Boolean,
) {
val fragmentTag = "${newFragment.name()}$_currentTab"
transaction(
fragmentManager,
newFragment,
fragmentTag,
addToBackStack
)
if (addToBackStack) {
_tagStacks[_currentTab]?.push(fragmentTag)
fragmentManager.putFragment(_pool, fragmentTag, newFragment)
}
_currentFragment = WeakReference(newFragment)
}
/**
* Finishes the fragment without calling its onBackPressed implementation
*/
override fun forcePop(
fragmentManager: FragmentManager
): FragmentBackstack.Finishresult = popOrHandle(
fragmentManager,
onNoPreviousFragment = null,
skipFragmentOnBackPressed = true
)
/**
* Performs the equivalent of a back button press.
* Nothing happens if the fragment handles it.
* Otherwise goes back to previous fragment.
* If no previous fragment and home, executes callback.
*/
override fun popOrHandle(
fragmentManager: FragmentManager,
onNoPreviousFragment: FragmentBackstack.OnNoPreviousFragment?,
skipFragmentOnBackPressed: Boolean
): FragmentBackstack.Finishresult {
val currentTab = _currentTab
val currentFragment = _currentFragment
if (
!skipFragmentOnBackPressed &&
currentFragment?.get()?.onBackPressed() == ParentFragment.BackResult.HANDLED
) {
return FragmentBackstack.Finishresult.HANDLED
}
//We never pop the root fragment of a tab.
val currentStackSize = _tagStacks[currentTab]?.size ?: 0
val previousTag = if (currentStackSize > 1) {
try {
_tagStacks[currentTab]?.peek()
} catch (e: EmptyStackException) {
null
}
} else {
null
}
if (previousTag != null) {
try {
(fragmentManager.getFragment(
_pool,
previousTag
) as? ParentFragment<*>)?.let { previousFragment ->
_currentFragment = WeakReference(previousFragment)
fragmentManager.popBackStack()
_tagStacks[currentTab]?.pop()
return FragmentBackstack.Finishresult.HANDLED
}
} catch (e: Exception) {
e.printStackTrace()
}
} else {
return onNoPreviousFragment?.handleNoPreviousFragment(
currentTab
) ?: FragmentBackstack.Finishresult.NOT_HANDLED
}
return FragmentBackstack.Finishresult.NOT_HANDLED
}
/**
* Switch to another tab
*/
override fun selectTab(
fragmentManager: FragmentManager,
newTab: FragmentBackstack.FragmentTab
) {
if (_currentTab != newTab) {
saveBackstack(fragmentManager)
_currentTab = newTab
}
val newTabRootTag = _tagStacks[newTab]?.getOrNull(0)
if (newTabRootTag != null) {
fragmentManager.restoreBackStack(newTabRootTag)
} else {
val rootFragment = newTab.root().java.newInstance()
push(fragmentManager, rootFragment)
}
}
/**
* Save the current backstack
*/
override fun saveBackstack(fragmentManager: FragmentManager) {
val currentTabRootTag = _tagStacks[_currentTab]?.getOrNull(0)
if (currentTabRootTag != null) {
fragmentManager.saveBackStack(currentTabRootTag)
}
}
/**
* Switch to another tab and go back to the root of that tab
*/
override fun goToTabRoot(fragmentManager: FragmentManager) {
val tagStack = _tagStacks[_currentTab]
tagStack?.getOrNull(0)?.let { currentTabRootTag ->
fragmentManager.popBackStack(currentTabRootTag, 0)
tagStack.clear()
tagStack.push(currentTabRootTag)
}
}
/**
* @param fragment: new fragment
*/
private fun transaction(
fragmentManager: FragmentManager,
fragment: ParentFragment<*>,
fragmentTag: String,
addToBackStack: Boolean
) {
fragmentManager.commit {
setReorderingAllowed(true)
setCustomAnimations(
R.anim.fade_in,
R.anim.fade_out,
R.anim.fade_in,
R.anim.fade_out
)
if (addToBackStack) {
addToBackStack(fragmentTag)
}
replace(R.id.fragmentContainer, fragment, fragmentTag)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3c091da3533dd032553df9006703c7ef8a767be6
| 5,807
|
SwoleAI
|
Apache License 2.0
|
openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/GoFeatureFlagProvider.kt
|
thomaspoignant
| 320,579,524
| false
|
{"Go": 1010738, "JavaScript": 116370, "Kotlin": 82104, "Python": 45815, "CSS": 36770, "Java": 18564, "MDX": 17066, "C#": 14206, "Makefile": 3875, "Shell": 2824, "Smarty": 2207, "Dockerfile": 236}
|
package org.gofeatureflag.openfeature
import dev.openfeature.sdk.EvaluationContext
import dev.openfeature.sdk.FeatureProvider
import dev.openfeature.sdk.Hook
import dev.openfeature.sdk.ProviderEvaluation
import dev.openfeature.sdk.ProviderMetadata
import dev.openfeature.sdk.Value
import dev.openfeature.sdk.events.OpenFeatureEvents
import kotlinx.coroutines.flow.Flow
import okhttp3.Headers
import org.gofeatureflag.openfeature.bean.GoFeatureFlagOptions
import org.gofeatureflag.openfeature.controller.DataCollectorManager
import org.gofeatureflag.openfeature.controller.GoFeatureFlagApi
import org.gofeatureflag.openfeature.hook.DataCollectorHook
import org.gofeatureflag.openfeature.ofrep.OfrepProvider
import org.gofeatureflag.openfeature.ofrep.bean.OfrepOptions
class GoFeatureFlagProvider(private val options: GoFeatureFlagOptions) : FeatureProvider {
private val ofrepProvider: OfrepProvider
private var dataCollectorManager: DataCollectorManager? = null
override var hooks: List<Hook<*>>
override val metadata: ProviderMetadata
get() = GoFeatureFlagMetadata()
init {
val authorizationHeader = options.apiKey?.let { apiKey ->
val headers = Headers.Builder()
headers.add("Authorization", "Bearer $apiKey")
headers.build()
}
val ofrepOptions = OfrepOptions(
endpoint = options.endpoint,
timeout = options.timeout,
maxIdleConnections = options.maxIdleConnections,
keepAliveDuration = options.keepAliveDuration,
headers = authorizationHeader,
pollingIntervalInMillis = options.pollingIntervalInMillis,
)
this.ofrepProvider = OfrepProvider(ofrepOptions)
val dataCollectorManager = DataCollectorManager(
goffApi = GoFeatureFlagApi(options),
flushIntervalMs = options.flushIntervalMs
)
hooks = listOf(DataCollectorHook<Any>(dataCollectorManager))
this.dataCollectorManager = dataCollectorManager
}
override fun getBooleanEvaluation(
key: String,
defaultValue: Boolean,
context: EvaluationContext?
): ProviderEvaluation<Boolean> {
return this.ofrepProvider.getBooleanEvaluation(key, defaultValue, context)
}
override fun getDoubleEvaluation(
key: String,
defaultValue: Double,
context: EvaluationContext?
): ProviderEvaluation<Double> {
return this.ofrepProvider.getDoubleEvaluation(key, defaultValue, context)
}
override fun getIntegerEvaluation(
key: String,
defaultValue: Int,
context: EvaluationContext?
): ProviderEvaluation<Int> {
return this.ofrepProvider.getIntegerEvaluation(key, defaultValue, context)
}
override fun getObjectEvaluation(
key: String,
defaultValue: Value,
context: EvaluationContext?
): ProviderEvaluation<Value> {
return this.ofrepProvider.getObjectEvaluation(key, defaultValue, context)
}
override fun getStringEvaluation(
key: String,
defaultValue: String,
context: EvaluationContext?
): ProviderEvaluation<String> {
return this.ofrepProvider.getStringEvaluation(key, defaultValue, context)
}
override fun getProviderStatus(): OpenFeatureEvents {
return this.ofrepProvider.getProviderStatus()
}
override fun initialize(initialContext: EvaluationContext?) {
if (this.options.flushIntervalMs > 0) {
this.dataCollectorManager?.start()
}
return this.ofrepProvider.initialize(initialContext)
}
override fun observe(): Flow<OpenFeatureEvents> {
return this.ofrepProvider.observe()
}
override fun onContextSet(oldContext: EvaluationContext?, newContext: EvaluationContext) {
return this.ofrepProvider.onContextSet(oldContext, newContext)
}
override fun shutdown() {
this.ofrepProvider.shutdown()
this.dataCollectorManager?.stop()
}
}
| 19
|
Go
|
124
| 1,282
|
a6809013a84a8dc3112be066d160027050b00337
| 4,043
|
go-feature-flag
|
MIT License
|
training/app/src/main/java/com/sfeir/school/android/datastore/ui/fragment/sportsessions/SportSessionsViewModel.kt
|
sfeir-open-source
| 486,275,854
| false
|
{"Kotlin": 56743, "JavaScript": 2270}
|
package com.sfeir.school.android.datastore.ui.fragment.sportsessions
import androidx.lifecycle.ViewModel
import com.sfeir.school.android.datastore.base.model.SportSessionSort
import com.sfeir.school.android.datastore.data.model.SportType
import com.sfeir.school.android.datastore.base.model.SportTypeFilter
import com.sfeir.school.android.datastore.data.model.SportSession
import com.sfeir.school.android.datastore.repository.shared.SettingsRepository
import com.sfeir.school.android.datastore.repository.shared.SportSessionRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import timber.log.Timber
import javax.inject.Inject
@HiltViewModel
class SportSessionsViewModel @Inject constructor(
private val sportSessionRepository: SportSessionRepository,
private val settingsRepository: SettingsRepository
) : ViewModel() {
@OptIn(FlowPreview::class)
fun getSportSessions(): Flow<List<SportSession>> {
return combine(
sportSessionRepository.getSportSessions(),
settingsRepository.filterBySportType,
settingsRepository.filterByDistanceRange,
settingsRepository.sortBy,
settingsRepository.isSortDescending
) { sportSessions, sportTypeFilter, distanceRangeFilter, sortBy, isSortDescending ->
Timber.d("----- sportSessions=$sportSessions")
Timber.d("----- sportTypeFilter=$sportTypeFilter")
Timber.d("----- distanceRangeFilter=$distanceRangeFilter")
Timber.d("----- sortBy=$sortBy")
Timber.d("----- isSortDescending=$isSortDescending")
val filteredSportSessions: List<SportSession> = sportSessions
.filter { sportSession ->
sportSession.type == when (sportTypeFilter) {
SportTypeFilter.NONE -> return@filter true
SportTypeFilter.WALKING -> SportType.WALKING
SportTypeFilter.RUNNING -> SportType.RUNNING
SportTypeFilter.BIKING -> SportType.BIKING
SportTypeFilter.SWIMMING -> SportType.SWIMMING
}
}
.filter {
it.distance in distanceRangeFilter.min..distanceRangeFilter.max
}
Timber.d("----- filteredSportSessions: $filteredSportSessions")
when (sortBy) {
SportSessionSort.DATE -> {
if (!isSortDescending) {
filteredSportSessions.sortedBy { it.startedAt }
} else {
filteredSportSessions.sortedByDescending { it.startedAt }
}
}
SportSessionSort.DISTANCE -> {
if (!isSortDescending) {
filteredSportSessions.sortedBy { it.distance }
} else {
filteredSportSessions.sortedByDescending { it.distance }
}
}
SportSessionSort.DURATION -> {
if (!isSortDescending) {
filteredSportSessions.sortedBy { it.duration }
} else {
filteredSportSessions.sortedByDescending { it.duration }
}
}
SportSessionSort.SPEED -> {
if (!isSortDescending) {
filteredSportSessions.sortedBy { it.speed }
} else {
filteredSportSessions.sortedByDescending { it.speed }
}
}
SportSessionSort.BPM -> {
if (!isSortDescending) {
filteredSportSessions.sortedBy { it.bpm }
} else {
filteredSportSessions.sortedByDescending { it.bpm }
}
}
SportSessionSort.CALORIES -> {
if (!isSortDescending) {
filteredSportSessions.sortedBy { it.calories }
} else {
filteredSportSessions.sortedByDescending { it.calories }
}
}
}
}.debounce(500L)
}
fun addNewRandomSportSession() {
sportSessionRepository.addNewRandomSportSession()
}
fun deleteRandomSportSession() {
sportSessionRepository.deleteRandomSportSession()
}
}
| 0
|
Kotlin
|
0
| 0
|
bd9f09e365e4ae2942c1a1a8e5438eb41117c525
| 3,655
|
sfeir-school-android-jetpack-datastore
|
Apache License 2.0
|
sboot-mockito-integration/src/test/kotlin/com/zigma/service/NLayerServiceImplTest.kt
|
dickensas
| 215,822,427
| false
| null |
package com.zigma.service
import com.zigma.dao.NLayerDAOImplTest
import com.zigma.dao.impl.NLayerDAOImpl
import com.zigma.service.impl.NLayerServiceImpl
import com.zigma.vo.EmployeeVO
import org.springframework.test.util.ReflectionTestUtils
import org.mockito.InjectMocks
import org.mockito.MockitoAnnotations
class NLayerServiceImplTest: NLayerService {
private var dao:NLayerDAOImplTest? = null
@InjectMocks
private var service:NLayerServiceImpl? = null
fun setup() {
MockitoAnnotations.openMocks(this);
dao = NLayerDAOImplTest()
dao?.setup()
ReflectionTestUtils.setField(service!!, "dao", dao)
}
override fun findAll(): List<EmployeeVO?>? {
return service?.findAll()
}
}
| 0
|
C
|
14
| 62
|
4ff966a8d8e26c70af6e11ffed2219f1843135f3
| 738
|
kotlin-gradle-templates
|
MIT License
|
lib/line/src/main/java/de/luckyworks/compose/charts/line/renderer/xaxis/XAxisDrawer.kt
|
lacky1991
| 462,792,840
| false
|
{"Kotlin": 105296}
|
package de.luckyworks.compose.charts.line.renderer.xaxis
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.drawscope.DrawScope
interface XAxisDrawer {
fun requiredHeight(drawScope: DrawScope): Float
fun drawAxisLine(
drawScope: DrawScope,
drawableArea: Rect
)
fun drawAxisLabels(
drawScope: DrawScope,
drawableArea: Rect,
labels: List<String>
)
}
| 11
|
Kotlin
|
0
| 1
|
a83659d13b3ee4ea36ee876fba433da6efe3b653
| 439
|
compose-charts
|
Apache License 2.0
|
sphinx/application/common/wrappers/wrapper-feed/src/main/java/chat/sphinx/wrapper_feed/FeedAuthor.kt
|
stakwork
| 340,103,148
| false
|
{"Kotlin": 4002700, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
|
package chat.sphinx.wrapper_feed
@Suppress("NOTHING_TO_INLINE")
inline fun String.toFeedAuthor(): FeedAuthor? =
try {
FeedAuthor(this)
} catch (e: IllegalArgumentException) {
null
}
@JvmInline
value class FeedAuthor(val value: String) {
init {
require(value.isNotEmpty()) {
"FeedAuthor cannot be empty"
}
}
}
| 99
|
Kotlin
|
2
| 18
|
01d4be42df107d5e4fa8d2411f5390aeea60ea74
| 374
|
sphinx-kotlin
|
MIT License
|
engine/src/main/java/com/autolua/engine/base/LuaTypeError.kt
|
lizhizhuanshu
| 817,824,738
| false
|
{"Kotlin": 186351, "C++": 166018, "Lua": 59924, "Java": 54951, "C": 4551, "CMake": 4544, "AIDL": 697}
|
package com.autolua.engine.base
class LuaTypeError : LuaError {
constructor() : super()
constructor(msg: String?) : super(msg)
}
| 0
|
Kotlin
|
0
| 1
|
4a989db6a88c8142d73b673771d60c0c401b7aca
| 135
|
autolua2
|
MIT License
|
src/main/java/com/ecwid/maleorang/method/v3_0/reports/email/EmailReportActivityDetails.kt
|
lararojasmr
| 70,038,605
| true
|
{"Kotlin": 134005, "Java": 18725}
|
package com.ecwid.maleorang.method.v3_0.reports.email
import com.ecwid.maleorang.MailchimpObject
import com.ecwid.maleorang.annotation.Field
import java.util.*
/**
* Created by: <NAME> <<EMAIL>>
*/
class EmailReportActivityDetails : MailchimpObject() {
@JvmField
@Field
var action: TypeEmailActivity? = null
@JvmField
@Field
var type: TypeBounceActivity? = null
@JvmField
@Field
var timestamp: Date? = null
@JvmField
@Field
var url: String? = null
@JvmField
@Field
var ip: String? = null
fun setAction(action: String) {
this.action = TypeEmailActivity.valueOf(action)
}
fun setType(type: String) {
this.type = TypeBounceActivity.valueOf(type)
}
}
| 0
|
Kotlin
|
0
| 0
|
5b22bdc5fb1efa9ead2c45f9824577da1fb71aeb
| 756
|
maleorang
|
Apache License 2.0
|
src/test/kotlin/passwordStore/widget/TableKtTest.kt
|
sciack
| 669,479,977
| false
| null |
package passwordStore.widget
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import kotlinx.coroutines.test.runTest
import org.junit.Rule
import passwordStore.DiInjection
import kotlin.test.Test
class TableKtTest {
private val di = DiInjection.testDi
@get:Rule
val rule = createComposeRule()
@Test
fun `should display a table with 2 columns`() = runTest {
val headers = listOf("First header", "Second header")
rule.setContent {
Table(
columnCount = 2,
rowCount = 2,
headers = headers,
cellContent = { columnIndex, rowIndex ->
content(rowIndex, columnIndex)
}
)
}
rule.awaitIdle()
headers.forEach {
rule.onNodeWithText(it).assertExists()
}
(0 until 2).forEach {row ->
(0 until 2 ).forEach{col ->
rule.onNodeWithText("Row: $row, Column: $col").assertExists()
}
}
}
@Composable
private fun content(rowIndex: Int, columnIndex: Int) {
Text("Row: $rowIndex, Column: $columnIndex")
}
}
| 1
|
Kotlin
|
0
| 0
|
02c2e4bc5555c50998b3ea07c0e34ae2262ebce7
| 1,305
|
kpassword-store
|
The Unlicense
|
app/src/main/java/com/cs/schoolcontentmanager/di/AppModule.kt
|
CarlosMacaneta
| 474,748,667
| false
|
{"Kotlin": 111395}
|
package com.cs.schoolcontentmanager.di
import android.app.Application
import android.content.Context
import androidx.room.Room
import com.cs.schoolcontentmanager.data.datasource.FileDataSource
import com.cs.schoolcontentmanager.data.datasource.FileDatabase
import com.cs.schoolcontentmanager.data.repository.FileRepositoryImpl
import com.cs.schoolcontentmanager.domain.repository.FileRepository
import com.cs.schoolcontentmanager.domain.usecase.*
import com.cs.schoolcontentmanager.utils.Constants.COURSES
import com.cs.schoolcontentmanager.utils.Constants.UPLOADS
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.storage.ktx.storage
import com.pspdfkit.configuration.activity.PdfActivityConfiguration
import com.pspdfkit.configuration.theming.ThemeMode
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 providesFileDatabase(app: Application): FileDatabase =
Room.databaseBuilder(
app,
FileDatabase::class.java,
FileDatabase.DB_NAME
).build()
@Provides
@Singleton fun providesStorageRef() = Firebase.storage.reference
@Provides
@Singleton fun providesUploadDbRef() = FirebaseDatabase.getInstance().getReference(UPLOADS)
@Provides
@Singleton fun providesAuth() = FirebaseAuth.getInstance()
@Provides
@Singleton fun providesCoursesDocument() = Firebase.firestore.collection(COURSES)
@Provides
@Singleton fun providesFirebaseMessaging() = FirebaseMessaging.getInstance()
@Provides
@Singleton fun providesFileRepository(
dsFile: FileDataSource,
db: FileDatabase
): FileRepository = FileRepositoryImpl(dsFile, db.fileDao)
@Provides
@Singleton fun providesFileUseCases(repository: FileRepository): FileUseCases =
FileUseCases(
CreateFile(repository),
UploadFile(repository),
GetFiles(repository),
SearchCloudFiles(repository),
SearchLocalFileByName(repository),
DownloadFile(repository),
GetCourses(repository),
GetLocalFiles(repository),
DeleteFile(repository)
)
@Provides
@Singleton fun providesPdfViewerActivity(@ApplicationContext context: Context):
PdfActivityConfiguration =
PdfActivityConfiguration.Builder(context)
.disableAnnotationEditing()
.disableBookmarkEditing()
.disableDocumentEditor()
.disableAnnotationList()
.disableBookmarkList()
.disableDocumentInfoView()
.disableFormEditing()
.disableOutline()
.hideDocumentTitleOverlay()
.hideSettingsMenu()
.showSignHereOverlay(false)
.themeMode(ThemeMode.DEFAULT)
.build()
}
| 2
|
Kotlin
|
0
| 2
|
a2bd321ff85b5a30aef2b163930386526b954593
| 3,253
|
school-content-manager
|
Apache License 2.0
|
src/main/kotlin/dev/cchilds/controllers/InventoryController.kt
|
willisjtc
| 210,243,743
| true
|
{"Kotlin": 40611, "JavaScript": 6779, "HTML": 1717, "PLpgSQL": 976, "CSS": 858}
|
package dev.cchilds.controllers
import dev.cchilds.annotations.Body
import dev.cchilds.json.jObj
import dev.cchilds.repositories.InventoryRepo
import io.vertx.core.json.JsonObject
import io.vertx.core.shareddata.impl.ClusterSerializable
class InventoryController(val inventoryRepo: InventoryRepo) : BaseController() {
suspend fun get(id: String?, searchString: String?, limit: Int = 100): ClusterSerializable {
return if (id != null)
da.getConnection { connection -> inventoryRepo.find(id, connection) }
else
da.getConnection { connection -> inventoryRepo.all(connection) }
}
fun post(@Body body:JsonObject): JsonObject {
return jObj("body" to body)
}
}
| 0
| null |
0
| 0
|
7ef6826d375aeb12fffc638c192a96563cb47608
| 721
|
kotlin-vertx-template
|
MIT License
|
app/src/main/java/io/github/alexeychurchill/stickynotes/core/datetime/DateTimeFormatter.kt
|
alexeychurchill
| 77,340,824
| false
| null |
package io.github.alexeychurchill.stickynotes.core.datetime
interface DateTimeFormatter {
fun format(timeMs: Long): String
}
| 10
|
Kotlin
|
0
| 0
|
303b80512e93ca9e90113e9ec9eec7b75235cbcc
| 130
|
sticky-notes-client
|
Apache License 2.0
|
app/src/main/java/io/github/alexeychurchill/stickynotes/core/datetime/DateTimeFormatter.kt
|
alexeychurchill
| 77,340,824
| false
| null |
package io.github.alexeychurchill.stickynotes.core.datetime
interface DateTimeFormatter {
fun format(timeMs: Long): String
}
| 10
|
Kotlin
|
0
| 0
|
303b80512e93ca9e90113e9ec9eec7b75235cbcc
| 130
|
sticky-notes-client
|
Apache License 2.0
|
src/main/kotlin/org/pkl/intellij/completion/PklAutoPopupHandler.kt
|
apple
| 745,600,847
| false
|
{"Kotlin": 844683, "Lex": 12354, "HTML": 486}
|
/**
* Copyright © 2024 Apple Inc. and the Pkl project authors. 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.
* 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 org.pkl.intellij.completion
import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate.Result.CONTINUE
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate.Result.STOP
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.pkl.intellij.psi.PklElementTypes
import org.pkl.intellij.psi.PklModule
import org.pkl.intellij.psi.PklModuleUri
import org.pkl.intellij.psi.elementType
class PklAutoPopupHandler : TypedHandlerDelegate() {
override fun checkAutoPopup(
charTyped: Char,
project: Project,
editor: Editor,
file: PsiFile
): Result {
if (file !is PklModule) return CONTINUE
if (charTyped == '"') {
// trigger auto popup for string literals (module URIs, string literal types)
// only takes effect if completion candidates are found
AutoPopupController.getInstance(project).scheduleAutoPopup(editor, CompletionType.BASIC) {
pklModule ->
val offset = editor.caretModel.offset
val token = pklModule.findElementAt(offset - 1)
token?.elementType == PklElementTypes.STRING_START
}
return STOP
} else if (charTyped == '/') {
AutoPopupController.getInstance(project).scheduleAutoPopup(editor, CompletionType.BASIC) {
pklModule ->
val offset = editor.caretModel.offset
val token = pklModule.findElementAt(offset - 1) ?: return@scheduleAutoPopup false
token.elementType == PklElementTypes.STRING_CHARS &&
token.parent.parent.parent is PklModuleUri
}
return STOP
}
return CONTINUE
}
}
| 0
|
Kotlin
|
1
| 5
|
26f3ec19e2514ca79c999d5ce2f39acea150ee1c
| 2,472
|
pkl-intellij
|
Apache License 2.0
|
app/src/main/java/com/cindaku/holanear/db/entity/ChatMessageWithSender.kt
|
metacdq
| 567,627,709
| false
|
{"Kotlin": 356041}
|
package com.cindaku.holanear.db.entity
import androidx.room.Embedded
import androidx.room.Relation
data class ChatMessageWithSender(
@Embedded var message: ChatMessage,
@Relation(
parentColumn = "contact_id",
entityColumn = "contact_id"
)
var sender: Contact?
)
| 0
|
Kotlin
|
1
| 0
|
94e3e0e88f637a8dc484fa236f0ccdfecf0b7447
| 327
|
holanear
|
MIT License
|
clef-workflow-starter/clef-workflow-starter-spring-boot/src/main/java/io/arkitik/clef/workflow/starter/spring/boot/function/SpringActionBeanStore.kt
|
arkitik
| 443,436,455
| false
|
{"Kotlin": 433170, "Shell": 268, "Dockerfile": 244}
|
package io.arkitik.clef.workflow.starter.spring.boot.function
import io.arkitik.clef.workflow.api.function.action.ActionBean
import io.arkitik.clef.workflow.api.function.action.bean.store.ActionBeanStore
import org.springframework.beans.factory.ListableBeanFactory
import org.springframework.beans.factory.getBeansOfType
/**
* Created By [*<NAME> *](https://www.linkedin.com/in/iloom/)
* Created At 17:21, 26 , **Sun, June 2022**
* Project *clef-workflow* [arkitik.io](https://arkitik.io)
*/
class SpringActionBeanStore(
private val listableBeanFactory: ListableBeanFactory
) : ActionBeanStore {
override fun findBean(actionCode: String): ActionBean? {
return listableBeanFactory.getBeansOfType<ActionBean>().values
.firstOrNull {
it.actionCode == actionCode
}
}
}
| 0
|
Kotlin
|
0
| 0
|
785e1b4ee583b6a6e3ea01e656eecd8365f171ef
| 831
|
clef-workflow
|
Apache License 2.0
|
src/main/kotlin/com/example/demo/spring/webflux/ConfigureWebFlux.kt
|
tanglisha
| 202,626,425
| false
| null |
package com.example.demo.spring.webflux
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.config.EnableWebFlux
import org.springframework.web.reactive.config.WebFluxConfigurer
@Configuration
@EnableWebFlux
class ConfigureWebFlux: WebFluxConfigurer
| 0
|
Kotlin
|
0
| 0
|
0e220cb469a5a7376c491cf117c6083147bf96da
| 299
|
demo.spring.kotlin.webflux
|
Apache License 2.0
|
src/main/kotlin/com/example/demo/spring/webflux/ConfigureWebFlux.kt
|
tanglisha
| 202,626,425
| false
| null |
package com.example.demo.spring.webflux
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.config.EnableWebFlux
import org.springframework.web.reactive.config.WebFluxConfigurer
@Configuration
@EnableWebFlux
class ConfigureWebFlux: WebFluxConfigurer
| 0
|
Kotlin
|
0
| 0
|
0e220cb469a5a7376c491cf117c6083147bf96da
| 299
|
demo.spring.kotlin.webflux
|
Apache License 2.0
|
app/src/main/java/io/github/ellamosi/mchelper/PowerController.kt
|
ellamosi
| 128,687,411
| false
|
{"Kotlin": 14628}
|
package io.github.ellamosi.mchelper
class PowerController(private var mcDeviceState: MCDeviceState) {
companion object {
private const val TAG = "PowerController"
private const val POWER_ON = "on"
private const val MIN_POWER_CYCLE_DELAY = 10 * 1000
}
private var lastShutdown: Long? = null
fun turnOn() {
if (!hasRecentlyTurnedOff() && !isPowered()) MCApi.turnOn()
}
fun turnOff() {
MCApi.turnOff()
lastShutdown = System.currentTimeMillis()
}
private fun isPowered() : Boolean {
return mcDeviceState.power() == POWER_ON
}
private fun hasRecentlyTurnedOff() : Boolean {
return lastShutdown?.let {
System.currentTimeMillis() - it < MIN_POWER_CYCLE_DELAY
} ?: false
}
}
| 0
|
Kotlin
|
1
| 2
|
1a1290a39ea57b7570374ac66e6fe8e5f671670d
| 800
|
MCHelper
|
MIT License
|
app/src/test/java/com/stevesoltys/seedvault/plugins/saf/DocumentFileTest.kt
|
ggehlot
| 369,053,291
| true
|
{"Kotlin": 655523, "Java": 11465, "Shell": 393}
|
package com.stevesoltys.seedvault.plugins.saf
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import androidx.documentfile.provider.DocumentFile
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.stevesoltys.seedvault.TestApp
import io.mockk.mockk
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.core.context.stopKoin
import org.robolectric.annotation.Config
@RunWith(AndroidJUnit4::class)
@Config(
sdk = [29], // robolectric does not support 30, yet
application = TestApp::class
)
internal class DocumentFileTest {
private val context: Context = mockk()
private val parentUri: Uri = Uri.parse(
"content://com.android.externalstorage.documents/tree/" +
"primary%3A/document/primary%3A.SeedVaultAndroidBackup"
)
private val parentFile: DocumentFile = DocumentFile.fromTreeUri(context, parentUri)!!
private val uri: Uri = Uri.parse(
"content://com.android.externalstorage.documents/tree/" +
"primary%3A/document/primary%3A.SeedVaultAndroidBackup%2Ftest"
)
@After
fun afterEachTest() {
stopKoin()
}
@Test
fun `test ugly getTreeDocumentFile reflection hack`() {
assertTrue(DocumentsContract.isTreeUri(uri))
val file = getTreeDocumentFile(parentFile, context, uri)
assertEquals(uri, file.uri)
assertEquals(parentFile, file.parentFile)
}
}
| 0
| null |
0
| 0
|
d53f0fcde2202b79f83d7b77817e1face6c98e13
| 1,554
|
seedvault
|
Apache License 2.0
|
app/src/main/java/com/zeph7/choreapplication/data/Chore.kt
|
zeph7
| 169,548,198
| false
| null |
package com.zeph7.choreapplication.data
import java.text.DateFormat
import java.util.*
class Chore() {
var choreName: String? = null
var assignedBy: String? = null
var assignedTo: String? = null
var timeAssigned: Long? = null
var id: Int? = null
constructor(choreName: String, assignedBy: String,
assignedTo: String, timeAssigned: Long,
id: Int): this() {
this.choreName = choreName
this.assignedBy = assignedBy
this.assignedTo = assignedTo
this.timeAssigned = timeAssigned
this.id = id
}
fun showHumanDate(timeAssigned: Long): String {
var dateFormat: java.text.DateFormat = DateFormat.getDateInstance()
var formattedDate: String = dateFormat.format(Date(timeAssigned).time)
return "${formattedDate}"
}
override fun toString(): String {
return "Chore(choreName=$choreName, assignedBy=$assignedBy, assignedTo=$assignedTo, timeAssigned=$timeAssigned, id=$id)"
}
}
| 0
|
Kotlin
|
3
| 9
|
74fdc77f90e434687937f38b5a858b95593fafa4
| 1,022
|
android-kotlin-Chore-app
|
MIT License
|
apps/etterlatte-gyldig-soeknad/src/main/kotlin/no/nav/etterlatte/gyldigsoeknad/pdf/PdfGeneratorKlient.kt
|
navikt
| 417,041,535
| false
|
{"Kotlin": 7015864, "TypeScript": 1686631, "Handlebars": 25499, "Shell": 12687, "HTML": 1734, "CSS": 598, "PLpgSQL": 556, "Dockerfile": 547}
|
package no.nav.etterlatte.gyldigsoeknad.pdf
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.content.TextContent
import io.ktor.http.contentType
import no.nav.etterlatte.libs.common.innsendtsoeknad.common.PDFMal
import no.nav.etterlatte.libs.common.logging.CORRELATION_ID
import no.nav.etterlatte.libs.common.logging.getCorrelationId
import no.nav.etterlatte.libs.common.toJsonNode
import org.slf4j.LoggerFactory
class PdfGeneratorKlient(
private val klient: HttpClient,
private val apiUrl: String,
) {
private val logger = LoggerFactory.getLogger(this::class.java)
suspend fun genererPdf(
payload: PDFMal,
mal: String,
) = genererPdf(TextContent(payload.toJsonNode().toPrettyString(), ContentType.Application.Json), mal, mal)
private suspend fun genererPdf(
body: Any,
mal: String,
sti: String,
): ByteArray {
logger.info("Genererer PDF med ey-pdfgen (mal=$mal)")
return klient
.post("$apiUrl/$sti") {
header(CORRELATION_ID, getCorrelationId())
contentType(ContentType.Application.Json)
setBody(body)
}.body()
}
}
| 12
|
Kotlin
|
0
| 6
|
4e3d0f08f81a7a7fb22af867160078c90c3337fd
| 1,358
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
app/src/main/java/team/studentlab/projects/ui/parts/NavigationBars.kt
|
Students-Lab
| 854,678,762
| false
|
{"Kotlin": 17837}
|
package team.studentlab.projects.ui.parts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.MailOutline
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.datasource.LoremIpsum
import androidx.compose.ui.unit.dp
import team.studentlab.projects.R
@Composable
fun Init() {
Column(
modifier = Modifier
.background(Color(238, 238, 238, 255))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(20.dp))
.size(130.dp)
.background(Color.White)
) {
Column(
modifier = Modifier
.padding(start = 20.dp, end = 20.dp, top = 10.dp)
) {
NavBar();
}
}
Column(
modifier = Modifier
.background(Color(238, 238, 238, 255))
.padding(top = 10.dp, start = 20.dp, end = 20.dp)
) {
RecentPost();
}
}
}
@Composable
fun TopBar(){
Column(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(20.dp))
.size(130.dp)
.background(Color.White)
) {
Column(
modifier = Modifier
.padding(start = 20.dp, end = 20.dp, top = 10.dp)
) {
NavBar();
}
}
}
@Composable
private fun NavBar() {
Row(
modifier = Modifier
.padding(top = 40.dp, bottom = 20.dp)
.fillMaxWidth()
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start,
modifier = Modifier.fillMaxWidth()
) {
Box(
modifier = Modifier
.size(60.dp)
.clip(RoundedCornerShape(50.dp))
) {
val image = painterResource(id = R.mipmap.images)
Image(
image, contentDescription = "My Profile Image", modifier = Modifier.size(100.dp)
)
}
Spacer(Modifier.size(25.dp))
Box(
modifier = Modifier
.clip(RoundedCornerShape(50.dp))
.border(
width = 2.dp,
color = Color(129, 129, 129, 57),
RoundedCornerShape(100.dp)
)
.size(250.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start,
modifier = Modifier.fillMaxWidth()
) {
Box(
modifier = Modifier.size(60.dp), contentAlignment = Alignment.Center
) {
Icon(Icons.Filled.Search, contentDescription = "Searching")
}
}
}
Box() {
Box(
modifier = Modifier.size(60.dp), contentAlignment = Alignment.Center
) {
Icon(
Icons.Filled.MailOutline,
contentDescription = "Notifications",
modifier = Modifier.size(32.dp)
)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ab8b867175a736e1c5a34d61341edcde24db0383
| 4,744
|
TechCommunity
|
MIT License
|
src/main/kotlin/app/xqaure/schedule/global/error/exception/ExceptionProperty.kt
|
team-xquare
| 443,502,429
| false
|
{"Kotlin": 37094, "Dockerfile": 420, "Shell": 165}
|
package app.xqaure.schedule.global.error.exception
import app.xqaure.schedule.global.error.ErrorCode
interface ExceptionProperty {
val errorCode: ErrorCode
}
| 0
|
Kotlin
|
0
| 3
|
856175a99c6a255c3a30798cda2a621a6cec5915
| 164
|
v1-service-schedule
|
MIT License
|
app/src/main/java/com/xtremedevx/gmail/ui/theme/Color.kt
|
silori-dev
| 528,319,260
| false
|
{"Kotlin": 41452}
|
package com.xtremedevx.gmail.ui.theme
import androidx.compose.ui.graphics.Color
val Teal200 = Color(0xFF03DAC5)
val LightBlue = Color(0xFFF0F8FF)
val SkyBlue = Color(0xFF89CFF0)
val DarkBlue = Color(0xFF2A52BE)
| 0
|
Kotlin
|
2
| 6
|
754f5c80b5eec728cdf5ca1816e86bf4e1a1ffad
| 213
|
Gmail-Compose
|
MIT License
|
common/src/main/java/ru/aasmc/petfinder/common/data/api/model/mappers/ApiPaginationMapper.kt
|
aasmc
| 407,974,629
| false
|
{"Kotlin": 171701}
|
package ru.aasmc.petfinder.common.data.api.model.mappers
import ru.aasmc.petfinder.common.data.api.model.ApiPagination
import ru.aasmc.petfinder.common.data.api.model.mappers.ApiMapper
import ru.aasmc.petfinder.common.domain.model.pagination.Pagination
import javax.inject.Inject
class ApiPaginationMapper @Inject constructor(): ApiMapper<ApiPagination?, Pagination> {
override fun mapToDomain(apiEntity: ApiPagination?): Pagination {
return Pagination(
currentPage = apiEntity?.currentPage ?: 0,
totalPages = apiEntity?.totalPages ?: 0
)
}
}
| 0
|
Kotlin
|
0
| 0
|
00f5122bfb476f3b6037fd4f2a6f696f0d2461d3
| 573
|
PetFinder
|
The Unlicense
|
libraries/data/src/main/java/com/data/keyvaluedatasource/AppDataStore.kt
|
rahul-lohra
| 526,939,055
| false
|
{"Kotlin": 134844}
|
package com.data.keyvaluedatasource
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
open class AppDataStore constructor(private val context: Context, fileName: String) :
KeyValueStorage {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = fileName)
override suspend fun saveString(key: String, data: String) {
context.dataStore.edit {
it[stringPreferencesKey(key)] = data
}
}
override suspend fun saveInt(key: String, data: Int) {
context.dataStore.edit {
it[intPreferencesKey(key)] = data
}
}
override suspend fun saveDouble(key: String, data: Double) {
context.dataStore.edit {
it[doublePreferencesKey(key)] = data
}
}
override suspend fun getString(key: String): Flow<String> {
return context.dataStore.data.map {
it[stringPreferencesKey(key)] ?: ""
}
}
}
| 0
|
Kotlin
|
0
| 0
|
de076b0546f1ab3b838ecf79cfd20537206cf40b
| 1,150
|
Wallpaper-App
|
Apache License 2.0
|
app/src/main/java/com/randos/doctorsapp/di/AndroidComponentModule.kt
|
vsnappy1
| 861,083,705
| false
|
{"Kotlin": 168318}
|
package com.randos.doctorsapp.di
import android.app.Application
import android.app.DownloadManager
import android.content.Context
import android.hardware.SensorManager
import android.location.LocationManager
import android.os.Looper
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object AndroidComponentModule {
@Provides
fun provideLocationManager(application: Application): LocationManager {
return application.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
@Provides
fun provideDownloadManager(application: Application): DownloadManager {
return application.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
}
@Provides
fun provideSensorManager(application: Application): SensorManager {
return application.getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
@Provides
fun provideMainLooper(): Looper {
return Looper.getMainLooper()
}
}
| 0
|
Kotlin
|
0
| 0
|
b5526df15bf137603bfa297d4e2d2224e48f2e11
| 1,083
|
Doctors-App
|
Apache License 2.0
|
app/data/src/main/java/com/nab/data/exceptionParser/DailyWeatherForecastErrorParser.kt
|
MinhPD92
| 367,825,601
| false
| null |
package com.nab.data.exceptionParser
import android.accounts.NetworkErrorException
import com.nab.domain.DailyWeatherForecastResult
import com.nab.data.constants.NO_DATA_FOUND_ERROR_CODE
import retrofit2.HttpException
import java.io.IOException
import java.net.UnknownHostException
fun <T : Any> Throwable.parseException(): DailyWeatherForecastResult<T> {
return when (this) {
is NetworkErrorException, is IOException, is UnknownHostException -> {
DailyWeatherForecastResult.NetWorkError
}
is HttpException -> {
if (code() == NO_DATA_FOUND_ERROR_CODE) {
DailyWeatherForecastResult.NoDataFoundError
} else {
DailyWeatherForecastResult.UnCatchError(errorMessage = message, errorCode = code())
}
}
else -> DailyWeatherForecastResult.UnCatchError(errorMessage = message)
}
}
| 0
|
Kotlin
|
0
| 0
|
a7d26d65f520e959d4dfda9f5391d57c7bdcf665
| 901
|
Weather-Forecast
|
MIT License
|
kafkistry-service-logic/src/main/kotlin/com/infobip/kafkistry/service/topic/TopicExternalInspector.kt
|
infobip
| 456,885,171
| false
|
{"Kotlin": 2628950, "FreeMarker": 812501, "JavaScript": 297269, "CSS": 7204}
|
package com.infobip.kafkistry.service.topic
import com.infobip.kafkistry.service.NamedTypeCauseDescription
/**
* Allows for custom topic inspection to be performed.
* Output of inspection is done via [TopicExternalInspectCallback].
* Multiple (or none) [TopicInspectionResultType] can be added as result of single external inspector invocation.
* Extra information can (optional) be added with [#setExternalInfo] and result will be kept in
* [TopicClusterStatus.externInspectInfo] under the key of [TopicExternalInspector.name].
* Such exported extra info can then be used in custom UI template
* (see: [com.infobip.kafkistry.webapp.TopicInspectExtensionProperties])
*/
interface TopicExternalInspector {
val name: String get() = javaClass.name
fun inspectTopic(ctx: TopicInspectCtx, outputCallback: TopicExternalInspectCallback)
}
interface TopicExternalInspectCallback {
fun addStatusType(statusType: TopicInspectionResultType)
fun addDescribedStatusType(statusTypeDescription: NamedTypeCauseDescription<TopicInspectionResultType>)
fun setExternalInfo(info: Any)
}
| 1
|
Kotlin
|
6
| 42
|
62403993a76fdf60b4cae3a87c5be0abe4fb3a88
| 1,103
|
kafkistry
|
Apache License 2.0
|
box/src/main/kotlin/com/mrt/box/core/BoxPackage.kt
|
myrealtrip
| 237,138,426
| false
| null |
package com.mrt.box.core
/**
* Created by jaehochoe on 2020-01-29.
*/
interface BoxPackage : BoxEvent, BoxSideEffect
| 1
|
Kotlin
|
3
| 40
|
516c142a4234a8b9b5b468b23bb9cbfd65eaf8d6
| 119
|
box
|
The Unlicense
|
src/test/kotlin/no/nav/syfo/veileder/VeilederApiTest.kt
|
navikt
| 650,618,614
| false
|
{"Kotlin": 146755, "Dockerfile": 132}
|
package no.nav.syfo.veileder
import io.kotest.assertions.ktor.client.shouldHaveStatus
import io.kotest.core.spec.style.DescribeSpec
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.testApplication
import no.nav.syfo.db.EmbeddedDatabase
import no.nav.syfo.mockdata.ExternalMockEnvironment
import no.nav.syfo.mockdata.UserConstants
import no.nav.syfo.mockdata.testApiModule
import no.nav.syfo.util.NAV_PERSONIDENT_HEADER
import no.nav.syfo.util.validVeilederToken
class VeilederApiTest : DescribeSpec({
val embeddedDatabase = EmbeddedDatabase()
afterSpec { embeddedDatabase.stop() }
describe("Happy path") {
it("Returns OK with valid token") {
testApplication {
application {
testApiModule(ExternalMockEnvironment.instance, embeddedDatabase)
}
val response = client.get(VEILEDER_LPS_METADATA_PATH) {
bearerAuth(validVeilederToken())
header(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_PERSONIDENT.value)
}
response shouldHaveStatus HttpStatusCode.OK
}
}
}
describe("Unhappy path") {
it("Returns status Unauthorized if no token is supplied") {
testApplication {
application {
testApiModule(ExternalMockEnvironment.instance, embeddedDatabase)
}
val response = client.get(VEILEDER_LPS_METADATA_PATH)
response shouldHaveStatus HttpStatusCode.Unauthorized
}
}
}
})
| 9
|
Kotlin
|
0
| 0
|
812112047ac21946c441d384db4cc7b86658184e
| 1,726
|
lps-oppfolgingsplan-mottak
|
MIT License
|
eudi-wallet-oidc-android/src/main/java/com/ewc/eudi_wallet_oidc_android/services/did/DIDService.kt
|
EWC-consortium
| 749,764,479
| false
|
{"Kotlin": 100658}
|
package com.ewc.eudi_wallet_oidc_android.services.did
import com.mediaparkpk.base58android.Base58
import com.nimbusds.jose.jwk.Curve
import com.nimbusds.jose.jwk.ECKey
import com.nimbusds.jose.jwk.OctetKeyPair
import com.nimbusds.jose.jwk.gen.OctetKeyPairGenerator
import com.nimbusds.jose.util.Base64URL
import java.nio.charset.StandardCharsets
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.PrivateKey
import java.security.PublicKey
import java.security.SecureRandom
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey
import java.security.spec.ECPublicKeySpec
import java.security.spec.PKCS8EncodedKeySpec
import java.util.UUID
class DIDService : DIDServiceInterface {
/**
* Generate a did:key:jcs-pub decentralised identifier.
* @param jwk - DID is created using the JWK
* @return DID
*/
override fun createDID(jwk: ECKey): String {
val publicKey = jwk.toPublicJWK()
val compactJson =
"{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"${publicKey?.x}\",\"y\":\"${publicKey?.y}\"}"
// UTF-8 encode the string
val encodedBytes: ByteArray? = compactJson.toByteArray(StandardCharsets.UTF_8)
// Add multiCodec byte
val multiCodecBytes = addMultiCodecByte(encodedBytes)
// Apply multiBase base58-btc encoding
val multiBaseEncoded = multiBaseEncode(multiCodecBytes!!)
// Prefix the string with "did:key"
return "did:key:z$multiBaseEncoded"
}
/**
* Generate JWK of curve P-256 for an optional seed value. (ECKey)
* @param seed is optional, if seed is present then the JWK will be created with the seed
* if seed is not present, then will create a new JWK
*
* @return JWK
*/
override fun createJWK(seed: String?): ECKey {
val keyPairGenerator = KeyPairGenerator.getInstance("EC")
if (seed != null) {
val seedBytes = seed.toByteArray(StandardCharsets.UTF_8)
keyPairGenerator.initialize(256, SecureRandom(seedBytes))
} else {
keyPairGenerator.initialize(256)
}
val keyPair: KeyPair = keyPairGenerator.generateKeyPair()
val publicKey = convertToECPublicKey(keyPair.public)
val privateKey = convertToECPrivateKey(keyPair.private)
val ecKey = ECKey.Builder(Curve.P_256, publicKey)
.privateKey(privateKey).build()
return ecKey
}
/**
* Generate JWK of curve Ed25519
*
* @return JWK
*/
override fun createED25519JWK(): OctetKeyPair? {
val jwk = OctetKeyPairGenerator(Curve.Ed25519)
.keyID(UUID.randomUUID().toString())
.generate()
return jwk
}
/**
* Generate DID for the ED25519
* @param privateKeyX - X value of the ED25519 jwk
*
* @return DID
*/
override fun createDidED25519(privateKeyX: Base64URL): String {
val startArray = byteArrayOf(0xed.toByte(), 0x01)
val newArray = startArray + Base64URL(privateKeyX.toString()).decode()
// 3. base58 encode the prefixed public key bytes.
var encoded = Base58.encode(newArray)
// 4. prefix the output with ‘z’
encoded = "did:key:z$encoded"
return encoded
}
/**
* Convert the PrivateKey to ECPrivateKey
* @param privateKey
*
* @return ECPrivateKey
*/
private fun convertToECPrivateKey(privateKey: PrivateKey): ECPrivateKey? {
return if (privateKey is ECPrivateKey) {
// If the PrivateKey is already an ECPrivateKey, simply cast and return it
privateKey
} else try {
val privateKeyBytes = privateKey.encoded
val keySpec = PKCS8EncodedKeySpec(privateKeyBytes)
var keyFactory = KeyFactory.getInstance("EC")
val ecPrivateKey = keyFactory.generatePrivate(keySpec) as ECPrivateKey
// Get EC parameters (curve) from the ECPrivateKey
val params: java.security.spec.ECParameterSpec = ecPrivateKey.params
// Set the EC parameters on the ECPrivateKey (required for some operations)
val privateKeySpec = java.security.spec.ECPrivateKeySpec(ecPrivateKey.s, params)
keyFactory = KeyFactory.getInstance("EC")
keyFactory.generatePrivate(privateKeySpec) as ECPrivateKey
} catch (e: java.lang.Exception) {
e.printStackTrace()
null
}
}
/**
* Convert the PublicKey to ECPublicKey
* @param publicKey
*
* @return ECPublicKey
*/
private fun convertToECPublicKey(publicKey: PublicKey): ECPublicKey? {
return if (publicKey is ECPublicKey) {
// If the PublicKey is already an ECPublicKey, simply cast and return it
publicKey
} else try {
val w = (publicKey as ECPublicKey).w
val params = (publicKey as java.security.interfaces.ECKey).params
val spec = ECPublicKeySpec(w, params)
val kf = KeyFactory.getInstance("EC")
kf.generatePublic(spec) as ECPublicKey
} catch (e: Exception) {
e.printStackTrace()
null
}
}
private fun addMultiCodecByte(input: ByteArray?): ByteArray? {
val multiCodecPrefix = byteArrayOf(0xd1.toByte(), 0xd6.toByte(), 0x03)
return multiCodecPrefix.plus(input!!)
}
private fun multiBaseEncode(input: ByteArray): String? {
return Base58.encode(input)
}
}
| 0
|
Kotlin
|
1
| 0
|
fa35bea79a369e1da448d3f749d8a356fd3f20d5
| 5,617
|
eudi-wallet-oid4vc-android
|
Apache License 2.0
|
playground/app/src/main/kotlin/io/github/composegears/valkyrie/playground/icons/lazy/colored/Videocam.kt
|
ComposeGears
| 778,162,113
| false
| null |
package io.github.composegears.valkyrie.playground.icons.lazy.colored
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import io.github.composegears.valkyrie.playground.icons.lazy.LazyIcons
val LazyIcons.Colored.Videocam: ImageVector by lazy(LazyThreadSafetyMode.NONE) {
ImageVector.Builder(
name = "Colored.Videocam",
defaultWidth = 24.dp,
defaultHeight = 24.dp,
viewportWidth = 24f,
viewportHeight = 24f,
).apply {
path(fill = SolidColor(Color(0xFF2CA5D1))) {
moveTo(15f, 8f)
verticalLineToRelative(8f)
horizontalLineTo(5f)
verticalLineTo(8f)
horizontalLineToRelative(10f)
moveToRelative(1f, -2f)
horizontalLineTo(4f)
curveToRelative(-0.55f, 0f, -1f, 0.45f, -1f, 1f)
verticalLineToRelative(10f)
curveToRelative(0f, 0.55f, 0.45f, 1f, 1f, 1f)
horizontalLineToRelative(12f)
curveToRelative(0.55f, 0f, 1f, -0.45f, 1f, -1f)
verticalLineToRelative(-3.5f)
lineToRelative(4f, 4f)
verticalLineToRelative(-11f)
lineToRelative(-4f, 4f)
verticalLineTo(7f)
curveToRelative(0f, -0.55f, -0.45f, -1f, -1f, -1f)
close()
}
}.build()
}
| 27
| null |
6
| 321
|
f0647081b15b907ad92b38c33eb62179ffd0f969
| 1,495
|
Valkyrie
|
Apache License 2.0
|
src/main/kotlin/core/handlers/ModuleHandler.kt
|
0x5Penis
| 789,484,646
| false
|
{"Kotlin": 26817}
|
package git.overlord.core.handlers
import git.overlord.core.defaults.DefaultModule
import git.overlord.core.modules.*
import javax.swing.JOptionPane
class ModuleHandler {
companion object {
var moduleList: MutableList<DefaultModule> = mutableListOf()
init {
initDefault()
organizeAddons()
moduleList = moduleList.sortedBy { it.name.lowercase() }.toMutableList()
}
private fun initDefault() {
moduleList.add(AllFilesModule())
moduleList.add(BackupAndOldFilesModule())
moduleList.add(ConfigurationFilesModule())
moduleList.add(DatabaseFilesModule())
moduleList.add(DirectoryListingModule())
moduleList.add(GitFolderModule())
moduleList.add(LogFilesModule())
moduleList.add(LoginPagesModule())
moduleList.add(OpenRedirectsModule())
moduleList.add(PdfModule())
moduleList.add(PHPErrorsModule())
moduleList.add(PHPInfoModule())
moduleList.add(PublicDocsModule())
moduleList.add(SQLErrorsModule())
moduleList.add(TrelloModule())
moduleList.add(WordpressFilesModule())
moduleList.add(WordpressModule())
moduleList.add(XAMPPDashboardModule())
moduleList.add(WordpressOEmbedAPIModule())
moduleList.add(SensitiveJavaDataModule())
moduleList.add(InsecureModule())
moduleList.add(SetupFilesModule())
}
fun getSelectedModule(moduleName: String): DefaultModule? {
return moduleList.find { it.name == moduleName }
}
private fun organizeAddons() {
AddonsHandler.moduleList.forEach() { module ->
if (moduleList.any { it.name == module.name }) {
JOptionPane.showMessageDialog(
null,
"Found plugin matching default module name: ${module.name}\nThis plugin will not be added.",
"Warning",
JOptionPane.WARNING_MESSAGE
)
} else if (AddonsHandler.moduleList.count { it.name == module.name } < 1) {
JOptionPane.showMessageDialog(
null,
"Found duplicate plugin: ${module.name}\nThis plugin will not be added.",
"Warning",
JOptionPane.WARNING_MESSAGE
)
} else {
moduleList.add(module)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
1b50958e1f2200f00a17e04c5cc7fa6ad8bb76a9
| 2,646
|
BugBountyDorker
|
MIT License
|
commands/src/main/kotlin/tech/carcadex/kotlinbukkitkit/commands/annotations/TabComplete.kt
|
CarcadeX
| 681,093,300
| false
| null |
package tech.carcadex.kotlinbukkitkit.commands.annotations
@Retention(AnnotationRetention.RUNTIME)
annotation class TabComplete(val complete: Array<String>)
| 0
|
Kotlin
|
0
| 0
|
51ae06d7cdf27e37473e2ab208110db8c5d57004
| 158
|
KotlinBukkitKit
|
MIT License
|
02/kotlinclasses/app/src/main/java/com/lfg/kotlinclasses/entities/Contact.kt
|
leonelgomez1990
| 402,218,277
| false
| null |
package com.lfg.kotlinclasses.entities
class Contact (
var email : String,
var pass : String
){
}
| 0
|
Kotlin
|
0
| 0
|
ce39f62befef83d53a3809411dbf60c2dcd410cc
| 115
|
kotlin1
|
MIT License
|
app/src/main/java/com/ralphmarondev/pixly/home/components/HomeContent.kt
|
ralphmarondev
| 846,034,273
| false
|
{"Kotlin": 14524}
|
package com.ralphmarondev.pixly.home.components
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun HomeContent(
appTheme: Boolean,
toggleAppTheme: () -> Unit,
openDrawer: () -> Unit
) {
Scaffold(
topBar = {
HomeTopBar(
appTheme = appTheme,
toggleAppTheme = toggleAppTheme,
openDrawer = openDrawer
)
}
) { innerPadding ->
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
) {
}
}
}
| 0
|
Kotlin
|
0
| 0
|
cc61d3d9dd70e08ad1023893aee217705a9b88ff
| 825
|
pixly
|
MIT License
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_STROOPWAFEL.kt
|
msrd0
| 363,665,023
| false
| null |
/* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
object FA_STROOPWAFEL: Icon {
override val name get() = "Stroopwafel"
override val unicode get() = "f551"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M188.12 210.74L142.86 256l45.25 45.25L233.37 256l-45.25-45.26zm113.13-22.62L256 142.86l-45.25 45.25L256 233.37l45.25-45.25zm-90.5 135.76L256 369.14l45.26-45.26L256 278.63l-45.25 45.25zM256 0C114.62 0 0 114.62 0 256s114.62 256 256 256 256-114.62 256-256S397.38 0 256 0zm186.68 295.6l-11.31 11.31c-3.12 3.12-8.19 3.12-11.31 0l-28.29-28.29-45.25 45.25 33.94 33.94 16.97-16.97c3.12-3.12 8.19-3.12 11.31 0l11.31 11.31c3.12 3.12 3.12 8.19 0 11.31l-16.97 16.97 16.97 16.97c3.12 3.12 3.12 8.19 0 11.31l-11.31 11.31c-3.12 3.12-8.19 3.12-11.31 0l-16.97-16.97-16.97 16.97c-3.12 3.12-8.19 3.12-11.31 0l-11.31-11.31c-3.12-3.12-3.12-8.19 0-11.31l16.97-16.97-33.94-33.94-45.26 45.26 28.29 28.29c3.12 3.12 3.12 8.19 0 11.31l-11.31 11.31c-3.12 3.12-8.19 3.12-11.31 0L256 414.39l-28.29 28.29c-3.12 3.12-8.19 3.12-11.31 0l-11.31-11.31c-3.12-3.12-3.12-8.19 0-11.31l28.29-28.29-45.25-45.26-33.94 33.94 16.97 16.97c3.12 3.12 3.12 8.19 0 11.31l-11.31 11.31c-3.12 3.12-8.19 3.12-11.31 0l-16.97-16.97-16.97 16.97c-3.12 3.12-8.19 3.12-11.31 0l-11.31-11.31c-3.12-3.12-3.12-8.19 0-11.31l16.97-16.97-16.97-16.97c-3.12-3.12-3.12-8.19 0-11.31l11.31-11.31c3.12-3.12 8.19-3.12 11.31 0l16.97 16.97 33.94-33.94-45.25-45.25-28.29 28.29c-3.12 3.12-8.19 3.12-11.31 0L69.32 295.6c-3.12-3.12-3.12-8.19 0-11.31L97.61 256l-28.29-28.29c-3.12-3.12-3.12-8.19 0-11.31l11.31-11.31c3.12-3.12 8.19-3.12 11.31 0l28.29 28.29 45.25-45.26-33.94-33.94-16.97 16.97c-3.12 3.12-8.19 3.12-11.31 0l-11.31-11.31c-3.12-3.12-3.12-8.19 0-11.31l16.97-16.97-16.97-16.97c-3.12-3.12-3.12-8.19 0-11.31l11.31-11.31c3.12-3.12 8.19-3.12 11.31 0l16.97 16.97 16.97-16.97c3.12-3.12 8.19-3.12 11.31 0l11.31 11.31c3.12 3.12 3.12 8.19 0 11.31l-16.97 16.97 33.94 33.94 45.26-45.25-28.29-28.29c-3.12-3.12-3.12-8.19 0-11.31l11.31-11.31c3.12-3.12 8.19-3.12 11.31 0L256 97.61l28.29-28.29c3.12-3.12 8.19-3.12 11.31 0l11.31 11.31c3.12 3.12 3.12 8.19 0 11.31l-28.29 28.29 45.26 45.25 33.94-33.94-16.97-16.97c-3.12-3.12-3.12-8.19 0-11.31l11.31-11.31c3.12-3.12 8.19-3.12 11.31 0l16.97 16.97 16.97-16.97c3.12-3.12 8.19-3.12 11.31 0l11.31 11.31c3.12 3.12 3.12 8.19 0 11.31l-16.97 16.97 16.97 16.97c3.12 3.12 3.12 8.19 0 11.31l-11.31 11.31c-3.12 3.12-8.19 3.12-11.31 0l-16.97-16.97-33.94 33.94 45.25 45.26 28.29-28.29c3.12-3.12 8.19-3.12 11.31 0l11.31 11.31c3.12 3.12 3.12 8.19 0 11.31L414.39 256l28.29 28.28a8.015 8.015 0 0 1 0 11.32zM278.63 256l45.26 45.25L369.14 256l-45.25-45.26L278.63 256z"/></svg>"""
else -> null
}
}
| 0
|
Kotlin
|
0
| 0
|
2fc4755051325e730e9d012c9dfe94f5ea800fdd
| 3,609
|
fontawesome-kt
|
Apache License 2.0
|
src/day05/Day05.kt
|
seastco
| 574,758,881
| false
|
{"Kotlin": 72220}
|
package day05
import readText
import java.util.*
fun main() {
fun getCrateStacks(input: List<String>): MutableList<Stack<Char>> {
var crates = input[0].split("\n")
val numStacks = crates.last().last()
val stacks = MutableList<Stack<Char>>(numStacks.digitToInt()) { Stack() }
crates = crates.dropLast(1).reversed()
for (row in crates) {
// skip over any whitespace
var i = row.indexOfFirst { !it.isWhitespace() }
while (i < row.length) {
// hop 4 indices at a time to check for a value
while (row[i].isWhitespace()) {
i += 4
}
val crate = row[i + 1]
stacks[i/4].push(crate)
i += 4
}
}
return stacks
}
fun part1(input: List<String>): String {
var stacks = getCrateStacks(input)
var instructions = input[1].split("\n")
for (instruction in instructions) {
val splitInstruction = instruction.split(" ")
var amount = splitInstruction[1].toInt()
val stack1 = splitInstruction[3].toInt() - 1 // translate to index
val stack2 = splitInstruction[5].toInt() - 1 // translate to index
while (amount > 0) {
var crate = stacks[stack1].pop()
stacks[stack2].push(crate)
amount -= 1
}
}
var answer = ""
for (stack in stacks) {
answer += stack.peek()
}
return answer
}
fun part2(input: List<String>): String {
val stacks = getCrateStacks(input)
val instructions = input[1].split("\n")
for (instruction in instructions) {
val splitInstruction = instruction.split(" ")
var amount = splitInstruction[1].toInt()
val stack1 = splitInstruction[3].toInt() - 1 // translate to index
val stack2 = splitInstruction[5].toInt() - 1 // translate to index
var tempStack = Stack<Char>()
while (amount > 0) {
var crate = stacks[stack1].pop()
tempStack.push(crate)
amount -= 1
}
while (tempStack.isNotEmpty()) {
stacks[stack2].push(tempStack.pop())
}
}
var answer = ""
for (stack in stacks) {
answer += stack.peek()
}
return answer
}
var testInput = readText("day05/test").split("\n\n")
println(part1(testInput))
println(part2(testInput))
var input = readText("day05/input").split("\n\n")
println(part1(input))
println(part2(input))
}
| 0
|
Kotlin
|
0
| 0
|
2d8f796089cd53afc6b575d4b4279e70d99875f5
| 2,731
|
aoc2022
|
Apache License 2.0
|
src/main/kotlin/io/github/gaming32/mckt/blocks/DoorBlockHandler.kt
|
mckt-Minecraft
| 532,076,162
| false
| null |
package io.github.gaming32.mckt.blocks
import io.github.gaming32.mckt.BLOCK_PROPERTIES
import io.github.gaming32.mckt.GlobalPalette.DEFAULT_BLOCKSTATES
import io.github.gaming32.mckt.PlayClient
import io.github.gaming32.mckt.items.BlockItemHandler
import io.github.gaming32.mckt.objects.*
import io.github.gaming32.mckt.packet.play.s2c.WorldEventPacket
import io.github.gaming32.mckt.world.Blocks
import io.github.gaming32.mckt.world.Materials
import io.github.gaming32.mckt.world.SetBlockFlags
import io.github.gaming32.mckt.world.World
object DoorBlockHandler : BlockHandler() {
override suspend fun getStateForNeighborUpdate(
state: BlockState,
direction: Direction,
neighborState: BlockState,
world: World,
pos: BlockPosition,
neighborPos: BlockPosition
): BlockState {
val half = state["half"]
return if (direction.axis != Axis.Y || (half == "lower") != (direction == Direction.UP)) {
if (half == "lower" && direction == Direction.DOWN && !state.canPlaceAt(world, pos)) {
Blocks.AIR
} else {
state
}
} else {
if (neighborState.blockId == state.blockId && neighborState["half"] != half) {
state.with(mapOf(
"facing" to neighborState["facing"],
"open" to neighborState["open"],
"hinge" to neighborState["hinge"],
"powered" to neighborState["powered"]
))
} else {
Blocks.AIR
}
}
}
override suspend fun onBreak(
world: World,
pos: BlockPosition,
state: BlockState,
client: PlayClient
) {
if (client.creativeMode) {
TallPlantBlockHandler.onBreakInCreative(world, pos, state, client)
}
super.onBreak(world, pos, state, client)
}
override suspend fun getPlacementState(
block: Identifier,
ctx: BlockItemHandler.ItemPlacementContext
): BlockState? {
val pos = ctx.location
val world = ctx.world
return if (pos.y < 2031 && world.getBlock(pos.up()).canReplace(ctx)) {
DEFAULT_BLOCKSTATES[block]?.with(mapOf(
"facing" to ctx.playerFacing.name.lowercase(),
"hinge" to getHinge(block, ctx),
"half" to "lower"
))
} else {
null
}
}
override suspend fun onPlaced(
world: World,
pos: BlockPosition,
state: BlockState,
client: PlayClient,
stack: ItemStack
) {
world.setBlock(pos.up(), state.with("half", "upper"), SetBlockFlags.PERFORM_NEIGHBOR_UPDATE)
}
private suspend fun getHinge(block: Identifier, ctx: BlockItemHandler.ItemPlacementContext): String {
val blockView = ctx.world
val blockPos = ctx.location
val direction = ctx.playerFacing
val blockPos2 = blockPos.up()
val direction2 = direction.rotateYCounterclockwise()
val blockPos3 = blockPos + direction2.vector
val blockState = blockView.getBlock(blockPos3)
val blockPos4 = blockPos2 + direction2.vector
val blockState2 = blockView.getBlock(blockPos4)
val direction3 = direction.rotateYClockwise()
val blockPos5 = blockPos + direction3.vector
val blockState3 = blockView.getBlock(blockPos5)
val blockPos6 = blockPos2 + direction3.vector
val blockState4 = blockView.getBlock(blockPos6)
val i = ((if (blockState != Blocks.AIR) -1 else 0)
+ (if (blockState2 != Blocks.AIR) -1 else 0)
+ (if (blockState3 != Blocks.AIR) 1 else 0)
+ if (blockState4 != Blocks.AIR) 1 else 0)
val bl = blockState.blockId == block && blockState["half"] == "lower"
val bl2 = blockState3.blockId == block && blockState3["half"] == "lower"
return if ((!bl || bl2) && i <= 0) {
if ((!bl2 || bl) && i >= 0) {
val j = direction.vector.x
val k = direction.vector.z
val vec3d = ctx.hit.position
val d = vec3d.x - blockPos.x
val e = vec3d.z - blockPos.z
if ((j >= 0 || e >= 0.5) && (j <= 0 || e <= 0.5) && (k >= 0 || d <= 0.5) && (k <= 0 || d >= 0.5)) {
"left"
} else {
"right"
}
} else {
"left"
}
} else {
"right"
}
}
override suspend fun onUse(
state: BlockState,
world: World,
pos: BlockPosition,
client: PlayClient,
hand: Hand,
hit: BlockHitResult
) = if (BLOCK_PROPERTIES[state.blockId]?.material == Materials.METAL) {
ActionResult.PASS
} else {
val newState = state.cycle("open")
world.setBlock(pos, newState, 0)
playSound(world, pos, state.blockId, newState["open"] == "true", client)
ActionResult.success(false)
}
override suspend fun canPlaceAt(state: BlockState, world: World, pos: BlockPosition): Boolean {
val down = pos.down()
val downState = world.getBlock(down)
return if (state["half"] == "lower") {
downState != Blocks.AIR
} else {
downState.blockId == state.blockId
}
}
private suspend fun playSound(
world: World,
pos: BlockPosition,
block: Identifier,
open: Boolean,
exclude: PlayClient? = null
) {
val isMetal = BLOCK_PROPERTIES[block]?.material == Materials.METAL
world.server.broadcast(WorldEventPacket(
if (open) {
if (isMetal) {
WorldEventPacket.CLOSE_METAL_DOOR
} else {
WorldEventPacket.CLOSE_DOOR
}
} else {
if (isMetal) {
WorldEventPacket.OPEN_METAL_DOOR
} else {
WorldEventPacket.OPEN_DOOR
}
}, pos
)) { it !== exclude }
}
}
| 0
|
Kotlin
|
0
| 2
|
98e88af4f54a12faeea2543c4bbdc950dd744092
| 6,193
|
mckt
|
MIT License
|
app/src/main/java/com/egbuna/cocktailapp/domain/usecase/DeleteLocalCocktail.kt
|
egbuna
| 427,371,964
| false
|
{"Kotlin": 48093}
|
package com.egbuna.cocktailapp.domain.usecase
import com.egbuna.cocktailapp.domain.model.Cocktail
import com.egbuna.cocktailapp.domain.repository.CocktailRepository
import javax.inject.Inject
class DeleteLocalCocktail @Inject constructor(
private val cocktailRepository: CocktailRepository
) {
suspend operator fun invoke(cocktail: Cocktail) {
cocktailRepository.deleteCocktail(cocktail)
}
}
| 0
|
Kotlin
|
0
| 6
|
062f21004667a3dcadaf19c9576301952debc010
| 414
|
Cocktail-App
|
MIT License
|
feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/authorizedDApps/di/AuthorizedDAppsModule.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 7667438, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.feature_dapp_impl.presentation.authorizedDApps.di
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import io.novafoundation.nova.common.di.scope.ScreenScope
import io.novafoundation.nova.common.di.viewmodel.ViewModelKey
import io.novafoundation.nova.common.di.viewmodel.ViewModelModule
import io.novafoundation.nova.common.mixin.actionAwaitable.ActionAwaitableMixin
import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountRepository
import io.novafoundation.nova.feature_account_api.presenatation.account.wallet.WalletUiUseCase
import io.novafoundation.nova.feature_dapp_api.data.repository.DAppMetadataRepository
import io.novafoundation.nova.feature_dapp_impl.DAppRouter
import io.novafoundation.nova.feature_dapp_impl.domain.authorizedDApps.AuthorizedDAppsInteractor
import io.novafoundation.nova.feature_dapp_impl.presentation.authorizedDApps.AuthorizedDAppsViewModel
import io.novafoundation.nova.feature_dapp_impl.web3.session.Web3Session
@Module(includes = [ViewModelModule::class])
class AuthorizedDAppsModule {
@Provides
@ScreenScope
fun provideInteractor(
accountRepository: AccountRepository,
metadataRepository: DAppMetadataRepository,
web3Session: Web3Session
) = AuthorizedDAppsInteractor(
accountRepository = accountRepository,
metadataRepository = metadataRepository,
web3Session = web3Session
)
@Provides
@ScreenScope
internal fun provideViewModel(fragment: Fragment, factory: ViewModelProvider.Factory): AuthorizedDAppsViewModel {
return ViewModelProvider(fragment, factory).get(AuthorizedDAppsViewModel::class.java)
}
@Provides
@IntoMap
@ViewModelKey(AuthorizedDAppsViewModel::class)
fun provideViewModel(
router: DAppRouter,
interactor: AuthorizedDAppsInteractor,
walletUiUseCase: WalletUiUseCase,
actionAwaitableMixinFactory: ActionAwaitableMixin.Factory
): ViewModel {
return AuthorizedDAppsViewModel(
router = router,
interactor = interactor,
walletUiUseCase = walletUiUseCase,
actionAwaitableMixinFactory = actionAwaitableMixinFactory
)
}
}
| 13
|
Kotlin
|
6
| 9
|
dea9f1144c1cbba1d876a9bb753f8541da38ebe0
| 2,381
|
nova-wallet-android
|
Apache License 2.0
|
frontend-android/app/src/main/java/de/flyndre/flat/composables/settingScreen/SettingScreen.kt
|
flyndre
| 772,483,060
| false
|
{"Kotlin": 196392, "Vue": 175284, "TypeScript": 63383, "C#": 53527, "Dockerfile": 1533, "HTML": 1249, "CSS": 669, "JavaScript": 361}
|
package de.flyndre.flat.composables.settingScreen
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingScreen(
onNavigateToInitialScreen: () -> Unit,
settingScreenViewModel: SettingScreenViewModel
){
val basePath = settingScreenViewModel.basePath.collectAsState()
val userName = settingScreenViewModel.userName.collectAsState()
val userId = settingScreenViewModel.userId.collectAsState()
Scaffold(
topBar = {
CenterAlignedTopAppBar(title = { Text(text = "Einstellungen") },
navigationIcon = {
IconButton(onClick = { onNavigateToInitialScreen() }) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = "back to start screen"
)
}
})
}
){innerPadding ->
Column(
Modifier
.padding(innerPadding)
.padding(10.dp)
.verticalScroll(rememberScrollState())
) {
TextField(
modifier = Modifier.padding(10.dp),
value = basePath.value,
onValueChange = { settingScreenViewModel.updateBasePath(it) },
label = { Text("Serveradresse:") }
)
TextField(
modifier = Modifier.padding(10.dp),
value = userName.value,
onValueChange = { settingScreenViewModel.updateUserName(it) },
label = { Text("Username:") }
)
TextField(
modifier = Modifier.padding(10.dp),
value = userId.value,
onValueChange = {},
label = { Text(text = "UserId:")},
readOnly = true
)
ExtendedFloatingActionButton(
modifier = Modifier.padding(10.dp),
onClick = {settingScreenViewModel.updateUserId()},
) {
Icon(Icons.Filled.Refresh, contentDescription = "refresh userId")
Text(text = "UserId erneuern")
}
}
}
}
| 6
|
Kotlin
|
0
| 1
|
6e38a2e39bdee1376a7e9adb8d9098730ad85914
| 3,116
|
Flat
|
The Unlicense
|
src/main/kotlin/com/github/locxter/bkndmvrgnzr/backend/movie/api/MovieController.kt
|
locxter
| 625,164,400
| false
| null |
package com.github.locxter.bkndmvrgnzr.backend.movie.api
import com.github.locxter.bkndmvrgnzr.backend.contributor.db.ContributorId
import com.github.locxter.bkndmvrgnzr.backend.contributor.db.ContributorRepository
import com.github.locxter.bkndmvrgnzr.backend.genre.db.Genre
import com.github.locxter.bkndmvrgnzr.backend.genre.db.GenreId
import com.github.locxter.bkndmvrgnzr.backend.genre.db.GenreRepository
import com.github.locxter.bkndmvrgnzr.backend.movie.db.Isan
import com.github.locxter.bkndmvrgnzr.backend.movie.db.Movie
import com.github.locxter.bkndmvrgnzr.backend.movie.db.MovieRepository
import com.github.locxter.bkndmvrgnzr.backend.moviecontributor.db.MovieContributor
import com.github.locxter.bkndmvrgnzr.backend.moviecontributor.db.MovieContributorId
import com.github.locxter.bkndmvrgnzr.backend.moviecontributor.db.MovieContributorRepository
import com.github.locxter.bkndmvrgnzr.backend.user.db.UserRepository
import me.xdrop.fuzzywuzzy.FuzzySearch
import org.springframework.http.HttpStatus
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.security.core.Authentication
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ResponseStatusException
@RestController
@RequestMapping("/api/movie")
class MovieController(
private val movieRepository: MovieRepository,
private val movieContributorRepository: MovieContributorRepository,
private val userRepository: UserRepository,
private val genreRepository: GenreRepository,
private val contributorRepository: ContributorRepository
) {
@GetMapping
@PreAuthorize("hasRole('USER')")
fun getAllMovies(): List<MovieResponseDto> {
val movies = movieRepository.findAll(Movie.getSort())
return movies.map { it.toDto() }
}
@PostMapping
@PreAuthorize("hasRole('EDITOR')")
fun createMovie(@RequestBody movieCreateDto: MovieCreateDto): MovieResponseDto {
if (movieCreateDto.isan.isBlank() || movieCreateDto.title.isBlank() || movieCreateDto.year < 0 ||
movieCreateDto.playTime < 0 || movieCreateDto.ageRestriction < 0 || movieCreateDto.ageRestriction > 18
) {
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Sent movie not valid")
}
try {
Isan(movieCreateDto.isan)
} catch (exception: IllegalArgumentException) {
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Sent movie not valid")
}
if (movieRepository.existsById(Isan(movieCreateDto.isan))) {
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Sent movie not valid")
}
val genres = mutableListOf<Genre>()
for (genreId in movieCreateDto.genreIds) {
val genre = genreRepository.findById(GenreId(genreId)).orElse(null) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND, "Requested genre not found"
)
genres.add(genre)
}
val movieContributors = mutableListOf<MovieContributor>()
for (movieContributorId in movieCreateDto.movieContributorIds) {
val movieContributor =
movieContributorRepository.findById(MovieContributorId(movieContributorId)).orElse(null)
?: throw ResponseStatusException(
HttpStatus.NOT_FOUND, "Requested movie contributor not found"
)
movieContributors.add(movieContributor)
}
val movie = Movie(
Isan(movieCreateDto.isan),
movieCreateDto.title,
movieCreateDto.description,
movieCreateDto.year,
movieCreateDto.playTime,
movieCreateDto.ageRestriction,
genres,
movieContributors
)
movieRepository.save(movie)
return movie.toDto()
}
@GetMapping("/{isan}")
@PreAuthorize("hasRole('USER')")
fun getMovie(@PathVariable(name = "isan") isan: String): MovieResponseDto {
val movie = movieRepository.findById(Isan(isan)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested movie not found")
return movie.toDto()
}
@PutMapping("/{isan}")
@PreAuthorize("hasRole('EDITOR')")
fun updateMovie(
@PathVariable(name = "isan") isan: String,
@RequestBody movieUpdateDto: MovieUpdateDto
): MovieResponseDto {
val movie = movieRepository.findById(Isan(isan)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested movie not found")
if (movieUpdateDto.year < 0 || movieUpdateDto.playTime < 0 ||
(movieUpdateDto.ageRestriction != -1 && (movieUpdateDto.ageRestriction < 0 || movieUpdateDto.ageRestriction > 18))
) {
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Sent movie not valid")
}
val genres = mutableListOf<Genre>()
for (genreId in movieUpdateDto.genreIds) {
val genre = genreRepository.findById(GenreId(genreId)).orElse(null) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND, "Requested genre not found"
)
genres.add(genre)
}
val movieContributors = mutableListOf<MovieContributor>()
for (movieContributorId in movieUpdateDto.movieContributorIds) {
val movieContributor =
movieContributorRepository.findById(MovieContributorId(movieContributorId)).orElse(null)
?: throw ResponseStatusException(
HttpStatus.NOT_FOUND, "Requested movie contributor not found"
)
movieContributors.add(movieContributor)
}
val updatedMovie = movie.copy(
title = movieUpdateDto.title.ifBlank { movie.title },
description = movieUpdateDto.description.ifBlank { movie.description },
year = if (movieUpdateDto.year != 0) movieUpdateDto.year else movie.year,
playTime = if (movieUpdateDto.playTime != 0) movieUpdateDto.playTime else movie.playTime,
ageRestriction = if (movieUpdateDto.ageRestriction != -1) movieUpdateDto.ageRestriction else movie.ageRestriction,
genres = genres.ifEmpty { movie.genres },
movieContributors = movieContributors.ifEmpty { movie.movieContributors }
)
movieRepository.save(updatedMovie)
return updatedMovie.toDto()
}
@DeleteMapping("/{isan}")
@PreAuthorize("hasRole('EDITOR')")
fun deleteMovie(@PathVariable(name = "isan") isan: String): MovieResponseDto {
val movie = movieRepository.findById(Isan(isan)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested movie not found")
val movieDto = movie.toDto()
movieRepository.delete(movie)
return movieDto
}
@GetMapping("/genre/{genreId}")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfGenre(@PathVariable(name = "genreId") genreId: String): List<MovieResponseDto> {
val genre = genreRepository.findById(GenreId(genreId)).orElse(null) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested genre not found"
)
val movies = movieRepository.findByGenresId(genre.id, Movie.getSort())
return movies.map { it.toDto() }
}
@GetMapping("/movie-contributor/{movieContributorId}")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfMovieContributor(@PathVariable(name = "movieContributorId") movieContributorId: String): List<MovieResponseDto> {
val movieContributor =
movieContributorRepository.findById(MovieContributorId(movieContributorId)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested movie contributor not found")
val movies =
movieRepository.findByMovieContributorsId(movieContributor.id, Movie.getSort())
return movies.map { it.toDto() }
}
@GetMapping("/contributor/{contributorId}")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfContributor(@PathVariable(name = "contributorId") contributorId: String): List<MovieResponseDto> {
val contributor = contributorRepository.findById(ContributorId(contributorId)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested contributor not found")
val movieContributors = movieContributorRepository.findByContributorId(contributor.id)
val movies = mutableListOf<Movie>()
for (movieContributor in movieContributors) {
movies.addAll(movieRepository.findByMovieContributorsId(movieContributor.id))
}
movies.sortWith(Movie)
return movies.map { it.toDto() }
}
@GetMapping("/search/{query}")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfSearchQuery(@PathVariable(name = "query") query: String): List<MovieResponseDto> {
val movies = movieRepository.findAll(Movie.getSort())
val iterator = movies.iterator()
while (iterator.hasNext()) {
val movie = iterator.next()
var containsQuery = false
if (FuzzySearch.weightedRatio(movie.title, query) >= 90 ||
FuzzySearch.weightedRatio(movie.description, query) >= 90 ||
movie.year == query.toIntOrNull() || movie.playTime == query.toIntOrNull() ||
movie.ageRestriction == query.toIntOrNull()
) {
containsQuery = true
} else {
for (genre in movie.genres) {
if (FuzzySearch.weightedRatio(genre.name, query) >= 90) {
containsQuery = true
break
}
}
for (movieContributor in movie.movieContributors) {
if (FuzzySearch.weightedRatio(movieContributor.contributor.firstName, query) >= 90 ||
FuzzySearch.weightedRatio(movieContributor.contributor.lastName, query) >= 90 ||
FuzzySearch.weightedRatio(
movieContributor.contributor.firstName + ' ' + movieContributor.contributor.lastName,
query
) >= 90 ||
FuzzySearch.weightedRatio(movieContributor.movieRole.name, query) >= 90
) {
containsQuery = true
break
}
}
}
if (!containsQuery) {
iterator.remove()
}
}
return movies.map { it.toDto() }
}
@GetMapping("/user")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfUser(authentication: Authentication): List<MovieResponseDto> {
val user = userRepository.findByUsername(authentication.name) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested user not found"
)
val movies = movieRepository.findByUsersId(user.id, Movie.getSort())
return movies.map { it.toDto() }
}
@PostMapping("/user/{isan}")
@PreAuthorize("hasRole('USER')")
fun addMovieToUser(
authentication: Authentication,
@PathVariable(name = "isan") isan: String
): List<MovieResponseDto> {
val user = userRepository.findByUsername(authentication.name) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested user not found"
)
val movie = movieRepository.findById(Isan(isan)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested movie not found")
val userMovies = user.movies.sortedWith(Movie).toMutableList()
if (!userMovies.contains(movie)) {
userMovies.add(movie)
userMovies.sortWith(Movie)
val updatedUser = user.copy(movies = userMovies)
userRepository.save(updatedUser)
}
return userMovies.map { it.toDto() }
}
@DeleteMapping("/user/{isan}")
@PreAuthorize("hasRole('USER')")
fun removeMovieFromUser(
authentication: Authentication,
@PathVariable(name = "isan") isan: String
): List<MovieResponseDto> {
val user = userRepository.findByUsername(authentication.name) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested user not found"
)
val movie = movieRepository.findById(Isan(isan)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested movie not found")
val userMovies = user.movies.sortedWith(Movie).toMutableList()
if (userMovies.contains(movie)) {
userMovies.remove(movie)
val updatedUser = user.copy(movies = userMovies)
userRepository.save(updatedUser)
}
return userMovies.map { it.toDto() }
}
@GetMapping("/user/genre/{genreId}")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfGenreFromUser(
authentication: Authentication,
@PathVariable(name = "genreId") genreId: String
): List<MovieResponseDto> {
val user = userRepository.findByUsername(authentication.name) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested user not found"
)
val genre = genreRepository.findById(GenreId(genreId)).orElse(null) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested genre not found"
)
val movies = movieRepository.findByUsersId(user.id, Movie.getSort()).toMutableList()
val iterator = movies.iterator()
while (iterator.hasNext()) {
val movie = iterator.next()
if (!movie.genres.contains(genre)) {
iterator.remove()
}
}
return movies.map { it.toDto() }
}
@GetMapping("/user/movie-contributor/{movieContributorId}")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfMoviesContributorFromUser(
authentication: Authentication,
@PathVariable(name = "movieContributorId") movieContributorId: String
): List<MovieResponseDto> {
val user = userRepository.findByUsername(authentication.name) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested user not found"
)
val movieContributor =
movieContributorRepository.findById(MovieContributorId(movieContributorId)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested movie contributor not found")
val movies = movieRepository.findByUsersId(user.id, Movie.getSort()).toMutableList()
val iterator = movies.iterator()
while (iterator.hasNext()) {
val movie = iterator.next()
if (!movie.movieContributors.contains(movieContributor)) {
iterator.remove()
}
}
return movies.map { it.toDto() }
}
@GetMapping("/user/contributor/{contributorId}")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfContributorFromUser(
authentication: Authentication,
@PathVariable(name = "contributorId") contributorId: String
): List<MovieResponseDto> {
val user = userRepository.findByUsername(authentication.name) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested user not found"
)
val contributor = contributorRepository.findById(ContributorId(contributorId)).orElse(null)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Requested contributor not found")
val movieContributors = movieContributorRepository.findByContributorId(contributor.id)
val movies = movieRepository.findByUsersId(user.id, Movie.getSort()).toMutableList()
val iterator = movies.iterator()
while (iterator.hasNext()) {
val movie = iterator.next()
var containsMovieContributor = false
for (movieContributor in movieContributors) {
if (movie.movieContributors.contains(movieContributor)) {
containsMovieContributor = true
break
}
}
if (!containsMovieContributor) {
iterator.remove()
}
}
return movies.map { it.toDto() }
}
@GetMapping("/user/search/{query}")
@PreAuthorize("hasRole('USER')")
fun getAllMoviesOfSearchQueryFromUser(
authentication: Authentication,
@PathVariable(name = "query") query: String
): List<MovieResponseDto> {
val user = userRepository.findByUsername(authentication.name) ?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"Requested user not found"
)
val movies = movieRepository.findByUsersId(user.id, Movie.getSort()).toMutableList()
val iterator = movies.iterator()
while (iterator.hasNext()) {
val movie = iterator.next()
var containsQuery = false
if (FuzzySearch.weightedRatio(movie.title, query) >= 90 ||
FuzzySearch.weightedRatio(movie.description, query) >= 90 ||
movie.year == query.toIntOrNull() || movie.playTime == query.toIntOrNull() ||
movie.ageRestriction == query.toIntOrNull()
) {
containsQuery = true
} else {
for (genre in movie.genres) {
if (FuzzySearch.weightedRatio(genre.name, query) >= 90) {
containsQuery = true
break
}
}
for (movieContributor in movie.movieContributors) {
if (FuzzySearch.weightedRatio(movieContributor.contributor.firstName, query) >= 90 ||
FuzzySearch.weightedRatio(movieContributor.contributor.lastName, query) >= 90 ||
FuzzySearch.weightedRatio(
movieContributor.contributor.firstName + ' ' + movieContributor.contributor.lastName,
query
) >= 90 ||
FuzzySearch.weightedRatio(movieContributor.movieRole.name, query) >= 90
) {
containsQuery = true
break
}
}
}
if (!containsQuery) {
iterator.remove()
}
}
return movies.map { it.toDto() }
}
}
| 0
|
Kotlin
|
0
| 1
|
eb3969c9be51196670788c43683b739aa0ce5083
| 18,734
|
bkndmvrgnzr-backend
|
MIT License
|
core/android/src/main/kotlin/com/reown/android/internal/utils/Expiration.kt
|
reown-com
| 851,466,242
| false
|
{"Kotlin": 2055654, "Java": 4294, "Shell": 1676}
|
@file:JvmName("Expiration")
package com.reown.android.internal.utils
val PROPOSAL_EXPIRY: Long get() = currentTimeInSeconds + fiveMinutesInSeconds
val ACTIVE_SESSION: Long get() = currentTimeInSeconds + weekInSeconds
| 6
|
Kotlin
|
1
| 8
|
893084b3df91b47daa77f8f964e37f84a02843b1
| 218
|
reown-kotlin
|
Apache License 2.0
|
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/api/chat/ChatAction.kt
|
vendelieu
| 496,567,172
| false
|
{"Kotlin": 460733, "CSS": 356}
|
@file:Suppress("MatchingDeclarationName")
package eu.vendeli.tgbot.api.chat
import eu.vendeli.tgbot.interfaces.Action
import eu.vendeli.tgbot.interfaces.ActionState
import eu.vendeli.tgbot.interfaces.TgAction
import eu.vendeli.tgbot.types.chat.ChatAction
import eu.vendeli.tgbot.types.internal.TgMethod
import eu.vendeli.tgbot.utils.getReturnType
class SendChatAction(action: ChatAction, messageThreadId: Int? = null) : Action<Boolean>, ActionState() {
override val TgAction<Boolean>.method: TgMethod
get() = TgMethod("sendChatAction")
override val TgAction<Boolean>.returnType: Class<Boolean>
get() = getReturnType()
init {
parameters["action"] = action
if (messageThreadId != null) parameters["message_thread_id"] = messageThreadId
}
}
fun chatAction(messageThreadId: Int? = null, block: () -> ChatAction) = SendChatAction(block(), messageThreadId)
fun chatAction(action: ChatAction, messageThreadId: Int? = null) = SendChatAction(action, messageThreadId)
| 1
|
Kotlin
|
2
| 98
|
f466e59c663d7319d1bcb9fd526e52c666c5927f
| 1,011
|
telegram-bot
|
Apache License 2.0
|
app/src/main/kotlin/com/mounacheikhna/nearby/ui/venues/VenuesScreen.kt
|
chemouna
| 47,512,499
| false
| null |
package com.mounacheikhna.nearby.ui.venues
import com.mounacheikhna.nearby.ui.base.PresenterScreen
import rx.Observable
/**
* Venues screen contract.
*/
interface VenuesScreen : PresenterScreen {
fun onNewLocationUpdate()
fun cancelRefreshForLocation(): Observable<Void>
}
| 3
|
Kotlin
|
6
| 40
|
08ffa6a851bf07866b34de2961fa9d1fbc9f9413
| 285
|
Nearby
|
Apache License 2.0
|
src/test/kotlin/adventofcode/year2021/Day09SmokeBasinSpec.kt
|
pfolta
| 573,956,675
| false
|
{"Kotlin": 186054, "Dockerfile": 227}
|
package adventofcode.year2021
import adventofcode.PuzzleBaseSpec
class Day09SmokeBasinSpec : PuzzleBaseSpec(15, 1134)
| 0
|
Kotlin
|
0
| 0
|
20cccd8cbf44a1e3b798636b9c9a9fd5df2ecf9c
| 120
|
AdventOfCode
|
MIT License
|
app/src/test/java/com/holiday/domain/repository/FakeLongWeekendRepository.kt
|
kelvinkioko
| 595,959,798
| false
| null |
package com.holiday.domain.repository
import com.holiday.domain.model.LongWeekendModel
import com.holiday.util.Response
import com.holiday.util.longWeekendModel
class FakeLongWeekendRepository : LongWeekendRepository {
var returnError = false
override suspend fun fetchAllLongWeekends(
year: Int,
countryCode: String
): Response<List<LongWeekendModel>> {
return if (returnError) {
Response.Error(errorMessage = "Could not load long weekends")
} else {
Response.Success(responseData = longWeekendModel)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
183d6e084e1803f8ea818697885fa0c51027aa2d
| 592
|
Public-Holiday
|
Apache License 2.0
|
src/test/kotlin/org/sheinbergon/dremio/udf/gis/STOverlapsTests.kt
|
sheinbergon
| 479,823,237
| false
| null |
package org.sheinbergon.dremio.udf.gis
import org.apache.arrow.vector.holders.NullableBitHolder
import org.apache.arrow.vector.holders.NullableVarBinaryHolder
import org.sheinbergon.dremio.udf.gis.spec.GeometryRelationFunSpec
internal class STOverlapsTests : GeometryRelationFunSpec.NullableBitOutput<STOverlaps>() {
init {
testFalseGeometryRelation(
"Calling ST_Overlaps on a POINT within a POLYGON",
"POINT(0.5 0.5)",
"POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))"
)
testFalseGeometryRelation(
"Calling ST_Overlaps on a POLYGON containing a POINT",
"POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))",
"POINT(0.5 0.5)"
)
testFalseGeometryRelation(
"Calling ST_Overlaps on a POINT outside of a POLYGON",
"POINT(22.5 0.5)",
"POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))"
)
testFalseGeometryRelation(
"Calling ST_Overlaps on a POINT touching a POLYGON",
"POINT(0.0 0.5)",
"POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))"
)
testFalseGeometryRelation(
"Calling ST_Overlaps on a LINESTRING intersecting with a POLYGON",
"LINESTRING(2.0 0.0,0.0 1.0)",
"POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))"
)
testTrueGeometryRelation(
"Calling ST_Overlaps on 2 overlapping LINESTRINGSs",
"LINESTRING(3.0 0.7,2.0 0.5,-2.0 0.6,-3.0 0.7)",
"LINESTRING(0.5 0.0,2.0 0.5,-2.0 0.6,-2.5 0.3)"
)
testTrueGeometryRelation(
"Calling ST_Overlaps on 2 overlapping POLYGONs",
"POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))",
"POLYGON((0.9 0.0,0.9 1.0,1.5 1.0,1.5 0.0,0.9 0.0))",
)
testNullGeometryRelation(
"Calling ST_Overlaps with one or two null geometries",
"LINESTRING(-0.5 0.5,0.5 0.5)",
null,
)
testDifferentSRIDGeometryRelation(
"Calling ST_Overlaps on geometries specified using different SRID",
"POINT(0 0)",
"POLYGON((0 0,111319.49079327357 0,111319.49079327357 111325.14286638486,0 111325.14286638486,0 0))",
4326
)
}
override val function = STOverlaps().apply {
binaryInput1 = NullableVarBinaryHolder()
binaryInput2 = NullableVarBinaryHolder()
output = NullableBitHolder()
}
override val STOverlaps.wkbInput1: NullableVarBinaryHolder get() = function.binaryInput1
override val STOverlaps.wkbInput2: NullableVarBinaryHolder get() = function.binaryInput2
override val STOverlaps.output: NullableBitHolder get() = function.output
}
| 0
| null |
0
| 23
|
91dc5268662b2925b2adca05061eb05bd9467ded
| 2,522
|
dremio-udf-gis
|
Apache License 2.0
|
src/main/kotlin/ua/rainbow/exam/concurrency/atomic/Atomics.kt
|
vdvorak83
| 125,437,077
| false
|
{"Gradle": 2, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 3, "Ignore List": 1, "Kotlin": 10, "Java": 20, "INI": 3, "Java Properties": 1}
|
package ua.rainbow.exam.concurrency.atomic
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicLong
class Atomics {
private var incrementer: AtomicLong = AtomicLong(0);
fun run() {
var executorService: ExecutorService? = null;
try {
executorService = Executors.newFixedThreadPool(10);
for (i in 0..19) {
executorService.submit { print(" ".plus(incrementer.incrementAndGet())) };
}
} finally {
executorService?.shutdown();
}
}
}
fun main(args: Array<String>) {
Atomics().run();
}
| 1
| null |
1
| 1
|
42d070193025821a604ffd913cdaa656126213c4
| 670
|
1Z0-809
|
MIT License
|
vector/src/main/java/im/vector/app/features/spaces/SpaceListBottomSheet.kt
|
tchapgouv
| 340,329,238
| false
| null |
/*
* Copyright (c) 2022 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.app.features.spaces
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import im.vector.app.R
import im.vector.app.core.extensions.replaceChildFragment
import im.vector.app.core.platform.VectorBaseBottomSheetDialogFragment
import im.vector.app.databinding.FragmentSpacesBottomSheetBinding
import im.vector.app.features.analytics.plan.MobileScreen
class SpaceListBottomSheet : VectorBaseBottomSheetDialogFragment<FragmentSpacesBottomSheetBinding>() {
override fun getBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentSpacesBottomSheetBinding {
return FragmentSpacesBottomSheetBinding.inflate(inflater, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
analyticsScreenName = MobileScreen.ScreenName.SpaceBottomSheet
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
replaceChildFragment(R.id.space_list, SpaceListFragment::class.java)
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply {
setPeekHeightAsScreenPercentage(0.75f)
}
}
companion object {
const val TAG = "SpacesBottomSheet"
}
}
| 4
|
Kotlin
|
4
| 9
|
9bd50a49e0a5a2a17195507ef3fe96594ddd739e
| 2,038
|
tchap-android
|
Apache License 2.0
|
app/src/main/java/iammert/com/androidarchitecture/data/Resource.kt
|
omjoonkim
| 97,355,249
| true
|
{"Kotlin": 24896, "Java": 1621}
|
package iammert.com.androidarchitecture.data
import iammert.com.androidarchitecture.data.Status.ERROR
import iammert.com.androidarchitecture.data.Status.LOADING
import iammert.com.androidarchitecture.data.Status.SUCCESS
/**
* A generic class that holds a value with its loading status.
* @param <T>
</T> */
class Resource<out T> private constructor(val status: Status, val data: T?, val message: String?) {
companion object {
fun <T> success(data: T): Resource<T> {
return Resource(SUCCESS, data, null)
}
fun <T> error(msg: String, data: T?): Resource<T> {
return Resource(ERROR, data, msg)
}
fun <T> loading(data: T?): Resource<T> {
return Resource(LOADING, data, null)
}
}
}
| 1
|
Kotlin
|
1
| 3
|
24a92887b82874a296eb1e25d538a923824fcea1
| 777
|
AndroidArchitecture
|
Apache License 2.0
|
android/app/src/main/java/com/stasbar/app/android/features/quotes/QuotesAdapter.kt
|
stanbar
| 162,640,520
| false
| null |
package com.stasbar.app.android.features.quotes
import android.graphics.Typeface
import android.text.SpannableString
import android.text.style.StyleSpan
import android.view.View
import android.widget.TextView
import com.stasbar.app.android.R
import com.stasbar.app.android.core.platform.ItemsAdapter
import com.stasbar.app.models.Quote
class QuotesAdapter() : ItemsAdapter<Quote, QuotesAdapter.QuoteVH>(QuoteVH::class, R.layout.quote_view_holder) {
class QuoteVH(itemView: View) : ItemViewHolder<Quote>(itemView) {
private val tvQuoteText: TextView = itemView.findViewById(R.id.tvQuoteText)
override fun bind(item: Quote) {
tvQuoteText.text = SpannableString("${item.text} ~${item.author}").apply {
setSpan(StyleSpan(Typeface.ITALIC), 0, item.text.length, 0)
}
}
}
}
| 8
| null |
1
| 1
|
3869ac8147d854b9fde6442398d89cfc51f5b401
| 808
|
stasbar-app
|
Apache License 2.0
|
fgithub/src/main/kotlin/org/flaxo/github/githubExceptions.kt
|
tcibinan
| 112,068,459
| false
| null |
package org.flaxo.github
/**
* Base github exception.
*/
class GithubException(message: String, cause: Throwable? = null)
: Throwable(message, cause)
| 30
|
Kotlin
|
6
| 9
|
a745d82604737699699210267ad5d2aa552f92d8
| 156
|
flaxo
|
Apache License 2.0
|
analysis/low-level-api-fir/testData/lazyResolve/noRuntime/arrayOfCall.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}
|
// ISSUE: KTIJ-26465
// TODO: arrayOf() should be resolved because it's from builtins that are always presented
<caret>annotation class Ann(vararg val a: String = ["/"])
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 170
|
kotlin
|
Apache License 2.0
|
fotoapparat-adapters/rxjava2/src/main/java/io/fotoapparat/result/adapter/rxjava2/SingleAdapter.kt
|
RedApparat
| 85,997,051
| false
|
{"Gradle": 7, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Markdown": 5, "Proguard": 2, "XML": 18, "Java": 9, "Kotlin": 163, "INI": 1}
|
package io.fotoapparat.result.adapter.rxjava2
import android.annotation.SuppressLint
import io.fotoapparat.result.PendingResult
import io.reactivex.Single
import java.util.concurrent.Future
/**
* Adapter for [Single].
*/
object SingleAdapter {
/**
* @return Adapter which adapts result to [Single].
*/
@JvmStatic
@SuppressLint("CheckResult")
fun <T> toSingle(): (Future<T>) -> Single<T> {
return { future -> Single.fromFuture(future) }
}
}
/**
* @return A [Single] from the given [PendingResult].
*/
@SuppressLint("CheckResult")
fun <T> PendingResult<T>.toSingle(): Single<T> {
return adapt { future -> Single.fromFuture(future) }
}
| 91
|
Kotlin
|
418
| 3,813
|
9454f3e4d1d222799049b00f3d84b274c3e02ee6
| 684
|
Fotoapparat
|
Apache License 2.0
|
liveVideoBroadcasterSDK/src/main/kotlin/io/antmedia/android/broadcaster/network/RTMPStreamer.kt
|
yoshi991
| 241,602,208
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 35, "XML": 15, "Kotlin": 3}
|
package io.antmedia.android.broadcaster.network
import android.util.Log
import io.antmedia.android.BuildConfig
import net.butterflytv.rtmp_client.RTMPMuxer
class RTMPStreamer : MediaMuxer {
private val TAG = RTMPStreamer::class.java.name
private val muxer = RTMPMuxer()
private var frameCount = 0
private var lastVideoFrameTimeStamp = -1
private var lastAudioFrameTimeStamp = -1
private var lastReceivedVideoFrameTimeStamp = -1
private var lastReceivedAudioFrameTimeStamp = -1
private var lastSentFrameTimeStamp = -1
private var isConnected = false
private val audioFrameList = mutableListOf<StreamFrame>()
private val videoFrameList = mutableListOf<StreamFrame>()
private val frameSynchronized = Any()
init {
initialize()
}
override fun open(url: String): Boolean {
if (BuildConfig.DEBUG) Log.d(TAG, "open rtmp connection")
initialize()
muxer.open(url, 0, 0).also {
if (it > 0) isConnected = true
}
return isConnected
}
override fun close() {
if (BuildConfig.DEBUG) Log.d(TAG, "close rtmp connection")
isConnected = false
muxer.close()
}
override fun isConnected(): Boolean {
return isConnected
}
override fun getLastVideoFrameTimeStamp(): Int {
return lastVideoFrameTimeStamp
}
override fun getLastAudioFrameTimeStamp(): Int {
return lastAudioFrameTimeStamp
}
override fun writeAudio(data: ByteArray, length: Int, timestamp: Int) {
handleMessage(MediaMuxer.Type.SEND_AUDIO, data, length, timestamp)
synchronized(frameSynchronized) {
frameCount++
}
if (BuildConfig.DEBUG) Log.d(TAG, "writeAudio size: $length time: $timestamp")
}
override fun writeVideo(data: ByteArray, length: Int, timestamp: Int) {
handleMessage(MediaMuxer.Type.SEND_VIDEO, data, length, timestamp)
synchronized(frameSynchronized) {
frameCount++
}
if (BuildConfig.DEBUG) Log.d(TAG, "writeVideo size: $length time: $timestamp")
}
private fun initialize() {
frameCount = 0
lastVideoFrameTimeStamp = 0
lastAudioFrameTimeStamp = 0
lastReceivedVideoFrameTimeStamp = -1
lastReceivedAudioFrameTimeStamp = -1
lastSentFrameTimeStamp = -1
isConnected = false
}
private fun finishFrames() {
var videoFrameListSize = 0
var audioFrameListSize = 0
do {
sendFrames()
videoFrameListSize = videoFrameList.size
audioFrameListSize = audioFrameList.size
// one of the frame list should be exhausted while the other have frames
} while (videoFrameListSize > 0 && audioFrameListSize > 0)
if (videoFrameListSize > 0) {
// send all video frames remained in the list
sendVideoFrames(videoFrameList.last().timestamp)
} else if (audioFrameListSize > 0) {
// send all audio frames remained in the list
sendAudioFrames(audioFrameList.last().timestamp)
}
}
override fun stop() {
handleMessage(MediaMuxer.Type.STOP_STREAMING)
}
override fun getFrameCountInQueue(): Int {
synchronized(frameSynchronized) {
return frameCount
}
}
override fun getVideoFrameCountInQueue(): Int {
synchronized(frameSynchronized) {
return videoFrameList.size
}
}
@Synchronized
fun handleMessage(
type: MediaMuxer.Type,
data: ByteArray? = null,
length: Int = -1,
timestamp: Int = -1
) {
when (type) {
MediaMuxer.Type.SEND_AUDIO -> {
/**
* data aac data,
* length length of the data
* timestamp timestamp
*/
data ?: return
if (timestamp >= lastReceivedAudioFrameTimeStamp && length > 0) {
lastReceivedAudioFrameTimeStamp = timestamp
audioFrameList.add(StreamFrame(data, length, timestamp))
} else {
Log.w(TAG, "discarding audio packet because time stamp is older than last packet or data lenth equal to zero")
}
sendFrames()
}
MediaMuxer.Type.SEND_VIDEO -> {
/**
* data h264 nal unit,
* length length of the data
* timestamp
*/
data ?: return
if (timestamp >= lastReceivedVideoFrameTimeStamp && length > 0) {
lastReceivedVideoFrameTimeStamp = timestamp
videoFrameList.add(StreamFrame(data, length, timestamp))
} else {
Log.w(TAG, "discarding videp packet because time stamp is older than last packet or data lenth equal to zero")
}
sendFrames()
}
MediaMuxer.Type.STOP_STREAMING -> {
finishFrames()
close()
}
}
}
/**
* this is a simple sorting algorithm.
* we do not know the audio or video frames timestamp in advance and they are not
* deterministic. So we send video frames with the timestamp is less than the first one in the list
* and the same algorithm applies for audio frames.
*/
private fun sendFrames() {
if (videoFrameList.size > 0) {
sendAudioFrames(videoFrameList.first().timestamp)
}
if (audioFrameList.size > 0) {
sendVideoFrames(audioFrameList.first().timestamp)
}
}
@Synchronized
private fun sendAudioFrames(timestamp: Int) {
val iterator = audioFrameList.iterator()
while (iterator.hasNext()) {
val frame = iterator.next()
// if timestamp is bigger than the audio frame timestamp
// it will be sent later so break the loop
if (frame.timestamp > timestamp) break
// frame time stamp should be equal or less than the previous timestamp
// in some cases timestamp of audio and video frames may be equal
if (frame.timestamp >= lastSentFrameTimeStamp) {
if (frame.timestamp == lastSentFrameTimeStamp) {
frame.timestamp++
}
if (isConnected) {
val result = muxer.writeAudio(frame.data, 0, frame.length, frame.timestamp.toLong())
if (BuildConfig.DEBUG) {
Log.d(TAG, "send audio result: $result, time: ${frame.timestamp}, length: ${frame.length}")
}
if (result < 0) {
close()
}
}
lastAudioFrameTimeStamp = frame.timestamp
lastSentFrameTimeStamp = frame.timestamp
synchronized(frameSynchronized) {
frameCount--
}
}
iterator.remove()
}
}
@Synchronized
private fun sendVideoFrames(timestamp: Int) {
val iterator = videoFrameList.iterator()
while (iterator.hasNext()) {
val frame = iterator.next()
// if frame timestamp is not smaller than the timestamp
// break the loop, it will be sent later
if (frame.timestamp > timestamp) break
// frame time stamp should be equal or less than timestamp
// in some cases timestamp of audio and video frames may be equal
if (frame.timestamp >= lastSentFrameTimeStamp) {
if (frame.timestamp == lastSentFrameTimeStamp) {
frame.timestamp++
}
if (isConnected) {
val result = muxer.writeVideo(frame.data, 0, frame.length, frame.timestamp.toLong())
if (BuildConfig.DEBUG) {
Log.d(TAG, "send video result: $result, time: ${frame.timestamp}, length: ${frame.length}")
}
if (result < 0) {
close()
}
}
lastVideoFrameTimeStamp = frame.timestamp
lastSentFrameTimeStamp = frame.timestamp
synchronized(frameSynchronized) {
frameCount--
}
}
iterator.remove()
}
}
}
| 1
| null |
1
| 1
|
bae7d8b16ed01924dbc45dec8e293916e643ccf4
| 8,608
|
LiveVideoBroadcaster
|
Apache License 2.0
|
DroidMedia/medialibs/playerLib/src/main/java/com/me/harris/playerLibrary/video/player/subordinates/MediaCodecThreadManner.kt
|
Haldir65
| 55,217,175
| false
|
{"Markdown": 61, "Dockerfile": 3, "Text": 47, "Ignore List": 34, "YAML": 32, "JSON": 3, "Gradle Kotlin DSL": 17, "Java Properties": 6, "Shell": 89, "Batchfile": 20, "EditorConfig": 1, "Makefile": 41, "INI": 26, "Gradle": 19, "Proguard": 27, "Kotlin": 348, "XML": 264, "TOML": 1, "Java": 594, "GLSL": 110, "Motorola 68K Assembly": 7, "C++": 411, "Unix Assembly": 10, "CMake": 37, "C": 599, "Roff Manpage": 3, "M4Sugar": 8, "Microsoft Visual Studio Solution": 4, "Awk": 3, "Module Management System": 1, "DIGITAL Command Language": 3, "Microsoft Developer Studio Project": 3, "GN": 6, "Python": 34, "Soong": 1, "Git Attributes": 1, "CoffeeScript": 1, "AIDL": 2, "Objective-C": 1, "Assembly": 4, "JSON with Comments": 3}
|
package com.me.harris.playerLibrary.video.player.subordinates
import com.me.harris.playerLibrary.video.player.decode.AudioDecodeThread
import com.me.harris.playerLibrary.video.player.video.VideoDecodeThread
import com.me.harris.playerLibrary.video.player.MediaCodecPlayerContext
/**
* 管理线程吧
*/
class MediaCodecThreadManner(val context: MediaCodecPlayerContext) {
private var videoDecodeThread: VideoDecodeThread? = null
private var audioDecodeThread: AudioDecodeThread? = null
fun start() {
stop()
videoDecodeLoop()
audioDecodeLoop()
}
fun stop() {
videoDecodeThread?.stop = true
audioDecodeThread?.stop = true
videoDecodeThread?.interrupt()
audioDecodeThread?.interrupt()
videoDecodeThread = null
audioDecodeThread = null
}
fun pause() {
audioDecodeThread?.pause()
videoDecodeThread?.pause()
}
fun resume(){
audioDecodeThread?.wakeUp()
videoDecodeThread?.wakeUp()
}
fun release(){
audioDecodeThread?.wakeUp()
videoDecodeThread?.wakeUp()
stop()
}
private fun videoDecodeLoop() {
val path = requireNotNull(context.getDataSource())
val surface = requireNotNull(context.getSurface())
VideoDecodeThread(path = path,context = context).apply {
videoDecodeThread = this
start()
}
}
private fun audioDecodeLoop() {
val path = requireNotNull(context.getDataSource())
AudioDecodeThread(path = path,context = context).apply {
audioDecodeThread = this
start()
}
}
fun setMute(mute:Boolean){
requireNotNull(audioDecodeThread).mute = mute
}
}
| 1
| null |
1
| 1
|
f117ab6ef4a6c8874030cb5cd78aa72259158cf9
| 1,758
|
Camera2Training
|
MIT License
|
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/tracing/ui/details/items/behavior/BehaviorItem.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.tracing.ui.details.items.behavior
import de.rki.coronawarnapp.tracing.ui.details.items.DetailsItem
interface BehaviorItem : DetailsItem {
override val stableId: Long
get() = BehaviorItem::class.java.name.hashCode().toLong()
}
| 6
|
Kotlin
|
514
| 2,495
|
d3833a212bd4c84e38a1fad23b282836d70ab8d5
| 269
|
cwa-app-android
|
Apache License 2.0
|
incubator/clients/kroviz/src/main/kotlin/org/apache/isis/client/kroviz/App.kt
|
dsp-testing
| 371,001,549
| false
| null |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.isis.client.kroviz
import org.apache.isis.client.kroviz.ui.core.RoApp
import io.kvision.Application
import io.kvision.pace.Pace
import io.kvision.panel.root
import io.kvision.panel.vPanel
import io.kvision.startApplication
import io.kvision.utils.px
import io.kvision.require
class App : Application() {
init {
require("css/kroviz.css")
}
override fun start() {
Pace.init()
root("kroviz") {
vPanel(spacing = 0) {
padding = 0.px
add(RoApp)
}
}
}
override fun dispose(): Map<String, Any> {
return mapOf()
}
}
fun main() {
startApplication(::App)
}
| 13
| null |
1
| 1
|
6272860133001030c6a7442a394b84dcd782d816
| 1,521
|
isis
|
Apache License 2.0
|
parser/src/main/kotlin/org/actorlang/ast/Node.kt
|
422404
| 371,440,848
| false
|
{"Java": 174885, "Kotlin": 156913, "ANTLR": 3771, "Shell": 991}
|
package org.actorlang.ast
import org.actorlang.parser.Position
abstract class Node(
val startPosition: Position,
val endPosition: Position
)
| 23
|
Java
|
1
| 3
|
bccf9c554e2dc2ad9c946cf8f38cacdd7002b555
| 151
|
ActorLang
|
MIT License
|
gemini-core/src/test/kotlin/com/haroncode/gemini/common/TestEventProducer.kt
|
Hazer
| 250,288,460
| true
|
{"Kotlin": 46858, "Groovy": 7411}
|
package com.haroncode.gemini.common
import com.haroncode.gemini.core.elements.EventProducer
class TestEventProducer : EventProducer<TestState, TestEffect, TestViewEvent> {
override fun invoke(state: TestState, effect: TestEffect): TestViewEvent? {
return if (effect is TestEffect.EffectForEvent) {
TestViewEvent.SimpleEvent
} else {
null
}
}
}
| 0
| null |
0
| 0
|
59ae07daa4ceb2d43c2a87ba1db662dfc4b12408
| 403
|
Gemini
|
MIT License
|
openai/api/src/main/kotlin/io/bluetape4k/openai/api/models/moderation/ModerationCategories.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.openai.api.models.moderation
import com.fasterxml.jackson.annotation.JsonProperty
import java.io.Serializable
/**
* An object containing the flags for each moderation category
*
* 참고: [Moderations Create](https://beta.openai.com/docs/api-reference/moderations/create)
*/
data class ModerationCategories(
/**
* Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual
* orientation, disability status, or caste.
*/
val hate: Boolean,
/**
* Hateful content that also includes violence or serious harm towards the targeted group.
*/
@get:JsonProperty("hate/threatening")
val hateThreatening: Boolean,
/**
* Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders.
*/
@get:JsonProperty("self-harm")
val selfHarm: Boolean,
/**
* Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual
* services (excluding sex education and wellness).
*/
val sexual: Boolean,
/**
* Sexual content that includes an individual who is under 18 years old.
*/
@get:JsonProperty("sexual/minors")
val sexualMinors: Boolean,
/**
* Content that promotes or glorifies violence or celebrates the suffering or humiliation of others.
*/
val violence: Boolean,
/**
* Violent content that depicts death, violence, or serious physical injury in extreme graphic detail.
*/
@get:JsonProperty("violence/graphic")
val violenceGraphic: Boolean,
): Serializable
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 1,675
|
bluetape4k
|
MIT License
|
app/src/main/java/com/my_1st/fincalc/ui/dep/DepScheduleFragment.kt
|
Tigran-Khachikyan
| 234,118,867
| false
| null |
package com.my_1st.fincalc.ui.dep
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.my_1st.fincalc.R
import com.my_1st.fincalc.data.db.dep.DepFrequencyConverter
import com.my_1st.fincalc.data.db.dep.Deposit
import com.my_1st.fincalc.models.deposit.TableDep
import com.my_1st.fincalc.models.rates.arrayCurCodes
import com.my_1st.fincalc.ui.*
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.InterstitialAd
import kotlinx.android.synthetic.main.fragment_dep_schedule.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*
import kotlin.coroutines.CoroutineContext
/**
* A simple [Fragment] subclass.
*/
class DepScheduleFragment : Fragment(), CoroutineScope {
private lateinit var mInterstitialAd: InterstitialAd
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Main + job
private lateinit var adapterRec: AdapterRecViewDep
private lateinit var depViewModel: DepositViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
mInterstitialAd = InterstitialAd(requireContext())
mInterstitialAd.adUnitId = requireContext().getString(R.string.interstitial_ad_unit_id)
mInterstitialAd.loadAd(AdRequest.Builder().build())
depViewModel = ViewModelProvider(this).get(DepositViewModel::class.java)
return inflater.inflate(R.layout.fragment_dep_schedule, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
job = Job()
val bundle = this.arguments
bundle?.let {
val amount = bundle.getLong(KEY_AMOUNT, 0)
val months = bundle.getInt(KEY_TERM, 0)
val rate = bundle.getFloat(KEY_RATE, 0.0F)
val capitalize = bundle.getBoolean(KEY_CAPITALIZATION, false)
val taxRate = bundle.getFloat(KEY_TAX_RATE, 0F)
val freqString = bundle.getString(KEY_FREQUENCY, "")
val frequency = DepFrequencyConverter().fromStringToEnum(freqString)
val dep = Deposit(amount, months, rate, capitalize, taxRate, frequency)
val scheduleDep = TableDep(dep)
fabSaveDep.setSvgColor(requireContext(), android.R.color.white)
adapterRec = AdapterRecViewDep(scheduleDep)
recyclerDepReport.setHasFixedSize(true)
recyclerDepReport.layoutManager =
LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
recyclerDepReport.adapter = adapterRec
val effectiveRate = decimalFormatter2p.format(scheduleDep.effectiveRate).replace(',','.') + "%"
val totalIncome = decimalFormatter1p.format(scheduleDep.totalPerAfterTax)
tvTotalIncomeResDep.text = totalIncome
tvEffRateResDep.text = effectiveRate
fabSaveDep.setOnClickListener {
showDialogSaveDeposit(requireContext(), it, dep, depViewModel)
hideKeyboard(requireActivity())
}
}
}
//Deposit save
@SuppressLint("InflateParams")
private fun showDialogSaveDeposit(
context: Context, view: View, dep: Deposit, depViewModel: DepositViewModel
) {
val dialogBuilder = AlertDialog.Builder(context)
val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_save, null)
dialogBuilder.setView(dialogView)
dialogBuilder.setTitle(R.string.savingOptions)
val etBank: EditText = dialogView.findViewById(R.id.etDialBank)
//spinner Currency
val spinnerCur: Spinner = dialogView.findViewById(R.id.spinDialCurrency)
val adapterSpinCur = AdapterSpinnerRates(
context, R.layout.spinner_currencies, arrayCurCodes
)
adapterSpinCur.setDropDownViewResource(R.layout.spinner_currencies)
spinnerCur.adapter = adapterSpinCur
//spinner LoanType
val spinnerType: Spinner = dialogView.findViewById(R.id.spinnerDialLoanType)
spinnerType.visibility = View.GONE
val tvSpinner: TextView = dialogView.findViewById(R.id.tvDialLoanType)
tvSpinner.visibility = View.GONE
//click SAVE
dialogBuilder.setPositiveButton(
context.getString(R.string.save)
) { _, _ ->
dep.bank = etBank.text.toString()
dep.currency = spinnerCur.selectedItem.toString()
dep.date = formatterShort.format(Date())
depViewModel.addDep(dep)
showSnackBar(R.string.successSaved, view)
launch {
delay(1500)
if (mInterstitialAd.isLoaded)
mInterstitialAd.show()
}
}
//click CANCEL
dialogBuilder.setNeutralButton(
getString(R.string.cancel)
) { _, _ -> }
val alertDialog = dialogBuilder.create()
alertDialog.show()
alertDialog.setCustomView()
}
override fun onDestroyView() {
super.onDestroyView()
job.cancel()
}
}
| 0
|
Kotlin
|
0
| 0
|
68480517fc7465d3b4052664e98fba0192a832c5
| 5,762
|
FinCalc
|
Apache License 2.0
|
app/src/main/java/com/aslapps/quickcheetsheet/adapters/CheatAdapter.kt
|
adityad1729
| 129,621,768
| false
| null |
package com.aslapps.quickcheetsheet.adapters
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.LayoutInflater
import android.view.LayoutInflater.*
import android.view.ViewGroup
import com.aslapps.quickcheetsheet.R
import com.aslapps.quickcheetsheet.database.Cheat
import kotlinx.android.synthetic.main.activity_cheat_sheet.view.*
import java.lang.reflect.Array.set
/**
* Created by aditya on 15/4/18.
*/
class CheatAdapter : RecyclerView.Adapter<ViewHolder>(val context: Context){
var cheatsList : ArrayList<Cheat> = ArrayList()
set(value) {
field = value
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItemCount(): Int {
return cheatsList.size
}
override fun onCreateViewHoldler(parent: ViewGroup?, viewType: Int): ViewHolder {
return ViewHolder(from(context).inflate(R.layout.cheatsview, parent, false))
}
}
| 4
|
Kotlin
|
0
| 0
|
06af6418a7d4828f7d96bda0930138f061a7b562
| 1,117
|
quickcheatsheet
|
MIT License
|
androidx/app/src/main/java/com/dxn/agventure/features/consumer/ui/home/ConsumerHomeViewModel.kt
|
pallavi-sahu
| 607,486,054
| false
| null |
package com.dxn.agventure.features.consumer.ui.home
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dxn.agventure.features.consumer.domain.Repository
import com.dxn.data.models.CatalogueProduct
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ConsumerHomeViewModel
@Inject
constructor(
private val repository: Repository
) : ViewModel() {
private val _products = MutableStateFlow<HomeUiState>(HomeUiState.Loading)
val products: StateFlow<HomeUiState> get() = _products
init {
loadProducts()
}
private fun loadProducts() {
viewModelScope.launch {
try {
repository.getProducts().onEach {
_products.value = HomeUiState.Success(it)
}.launchIn(viewModelScope)
} catch (e: Exception) {
_products.value =
HomeUiState.Error(if (e.localizedMessage != null) e.localizedMessage else "Something went wrong")
}
}
}
sealed class HomeUiState {
object Loading : HomeUiState()
data class Success(val products: List<CatalogueProduct>) : HomeUiState()
data class Error(val error: String) : HomeUiState()
}
companion object {
const val TAG = "HOME_VIEW_MODEL"
}
}
| 0
|
Kotlin
|
0
| 0
|
8b4c6c7a53752bf9017a46dd566cf23bfcd36148
| 1,591
|
Agventure
|
MIT License
|
domain/src/main/java/com/ila/domain/usecase/GetCountriesUseCase.kt
|
droider91
| 592,275,935
| false
| null |
package com.ila.domain.usecase
import com.ila.domain.entities.CountriesDomain
import com.ila.domain.repository.CountryRepository
import com.ila.domain.util.Result
/**
* Created by devendra on 17/01/2023
**/
open class GetCountriesUseCase(
private val countrysRepository: CountryRepository
) {
suspend fun execute(): Result<CountriesDomain> = countrysRepository.getCountries()
}
| 0
|
Kotlin
|
0
| 0
|
85e1d668fd7f633cdd73eba97c735993bd0c4386
| 390
|
country-language-list
|
Apache License 2.0
|
app/src/main/java/com/app/marvelapp/data/model/comics/ComicsResults.kt
|
onurbarman
| 372,486,502
| false
| null |
package com.app.marvelapp.data.model.comics
data class ComicsResults(
val description: String,
val id: Int,
val thumbnail: ComicsThumbnail,
val title: String,
)
| 0
|
Kotlin
|
0
| 0
|
c05bdc78663d82c542bca8cc13180ec3d4feee50
| 177
|
MarvelApp
|
Apache License 2.0
|
app/src/androidTest/java/com/amarinag/amgmoviedb/db/FavoriteDaoTest.kt
|
AMarinaG
| 181,779,271
| false
| null |
package com.amarinag.amgmoviedb.db
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.persistence.room.Room
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.amarinag.amgmoviedb.model.Favorite
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.assertNotNull
/**
* AMGMovieDB.
*
* @author - AMarinaG
* @since - 29/4/18
*/
@RunWith(AndroidJUnit4::class)
class FavoriteDaoTest {
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var database: AppDatabase
@Before
fun setUp() {
database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), AppDatabase::class.java)
.allowMainThreadQueries()
.build()
}
@After
fun tearDown() {
database.close()
}
@Test
fun addFavoriteAndGetFavorite() {
database.favoriteDao().addFavorite(FAVORITE)
val favorite = database.favoriteDao().getFavoriteById(FAVORITE.movieId)
assertNotNull(favorite, "Not Null Required!")
assert(favorite?.movieId == FAVORITE.movieId)
assert(favorite?.isFavorite == FAVORITE.isFavorite)
}
companion object {
private val FAVORITE = Favorite(1, true)
}
}
| 0
|
Kotlin
|
1
| 1
|
00166b030d5eea3cafa0008aedb764b8143580ec
| 1,413
|
AMGMovieDB
|
MIT License
|
src/sharedTest/kotlin/us/frollo/frollosdk/model/TestDataReport.kt
|
frollous
| 261,670,220
| false
| null |
/*
* Copyright 2019 Frollo
*
* 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 us.frollo.frollosdk.model
import us.frollo.frollosdk.model.api.reports.AccountBalanceReportResponse
import us.frollo.frollosdk.model.api.reports.ReportsResponse
import us.frollo.frollosdk.model.api.reports.ReportsResponse.ReportResponse
import us.frollo.frollosdk.model.api.reports.ReportsResponse.ReportResponse.GroupReportResponse
import us.frollo.frollosdk.model.coredata.reports.ReportAccountBalance
import us.frollo.frollosdk.model.coredata.reports.ReportPeriod
import us.frollo.frollosdk.testutils.randomBoolean
import us.frollo.frollosdk.testutils.randomNumber
import java.math.BigDecimal
internal fun testAccountBalanceReportResponseData(): AccountBalanceReportResponse {
val accounts = listOf(
AccountBalanceReportResponse.Report.BalanceReport(
id = 1,
currency = "AUD",
value = randomNumber().toBigDecimal()
)
)
val data = listOf(
AccountBalanceReportResponse.Report(
date = "2019-03",
value = randomNumber().toBigDecimal(),
accounts = accounts
)
)
return AccountBalanceReportResponse(data = data)
}
internal fun testReportsResponseData(): ReportsResponse {
return ReportsResponse(listOf(testReportResponseData()))
}
internal fun testReportResponseData(): ReportResponse {
val groups = listOf(testGroupReportResponseData())
return ReportResponse(
date = "2019-03-01",
value = randomNumber().toBigDecimal(),
income = randomBoolean(),
groups = groups
)
}
internal fun testGroupReportResponseData(): GroupReportResponse {
return GroupReportResponse(
id = 1,
name = "living",
value = randomNumber().toBigDecimal(),
income = randomBoolean(),
transactionIds = listOf(1093435, 2959945)
)
}
internal fun testReportAccountBalanceData(
date: String,
accountId: Long? = null,
period: ReportPeriod,
id: Long? = null,
value: BigDecimal? = null
): ReportAccountBalance {
val report = ReportAccountBalance(
date = date,
accountId = accountId ?: randomNumber().toLong(),
currency = "AUD",
value = value ?: BigDecimal(34.67),
period = period
)
id?.let { report.reportId = it }
return report
}
| 5
|
Kotlin
|
0
| 2
|
f77c427387b11a751f5ed4b23db87eeab3c8fdff
| 2,890
|
frollo-android-sdk
|
Apache License 2.0
|
common/compose/src/main/kotlin/team/duckie/app/android/common/compose/ui/icon/v2/Clock.kt
|
duckie-team
| 503,869,663
| false
|
{"Kotlin": 1819917}
|
package team.duckie.app.android.common.compose.ui.icon.v2
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import team.duckie.quackquack.material.icon.QuackIcon
public val QuackIcon.Clock: ImageVector
get() {
if (_vector != null) {
return _vector!!
}
_vector = Builder(
name = "Vector",
defaultWidth = 12.0.dp,
defaultHeight = 12.0.dp,
viewportWidth = 12.0f,
viewportHeight = 12.0f,
).apply {
path(
fill = SolidColor(Color(0xFF222222)),
stroke = null,
strokeLineWidth = 0.0f,
strokeLineCap = Butt,
strokeLineJoin = Miter,
strokeLineMiter = 4.0f,
pathFillType = NonZero,
) {
moveTo(6.0f, 1.2f)
curveTo(4.727f, 1.2f, 3.5061f, 1.7057f, 2.6059f, 2.6059f)
curveTo(1.7057f, 3.5061f, 1.2f, 4.727f, 1.2f, 6.0f)
curveTo(1.2f, 7.273f, 1.7057f, 8.4939f, 2.6059f, 9.3941f)
curveTo(3.5061f, 10.2943f, 4.727f, 10.8f, 6.0f, 10.8f)
curveTo(7.273f, 10.8f, 8.4939f, 10.2943f, 9.3941f, 9.3941f)
curveTo(10.2943f, 8.4939f, 10.8f, 7.273f, 10.8f, 6.0f)
curveTo(10.8f, 4.727f, 10.2943f, 3.5061f, 9.3941f, 2.6059f)
curveTo(8.4939f, 1.7057f, 7.273f, 1.2f, 6.0f, 1.2f)
close()
moveTo(0.0f, 6.0f)
curveTo(0.0f, 2.6862f, 2.6862f, 0.0f, 6.0f, 0.0f)
curveTo(9.3138f, 0.0f, 12.0f, 2.6862f, 12.0f, 6.0f)
curveTo(12.0f, 9.3138f, 9.3138f, 12.0f, 6.0f, 12.0f)
curveTo(2.6862f, 12.0f, 0.0f, 9.3138f, 0.0f, 6.0f)
close()
moveTo(6.0f, 2.4f)
curveTo(6.1591f, 2.4f, 6.3117f, 2.4632f, 6.4243f, 2.5757f)
curveTo(6.5368f, 2.6883f, 6.6f, 2.8409f, 6.6f, 3.0f)
verticalLineTo(5.7516f)
lineTo(8.2242f, 7.3758f)
curveTo(8.3335f, 7.489f, 8.394f, 7.6405f, 8.3926f, 7.7978f)
curveTo(8.3912f, 7.9552f, 8.3281f, 8.1056f, 8.2169f, 8.2169f)
curveTo(8.1056f, 8.3281f, 7.9552f, 8.3912f, 7.7978f, 8.3926f)
curveTo(7.6405f, 8.394f, 7.489f, 8.3335f, 7.3758f, 8.2242f)
lineTo(5.5758f, 6.4242f)
curveTo(5.4633f, 6.3117f, 5.4f, 6.1591f, 5.4f, 6.0f)
verticalLineTo(3.0f)
curveTo(5.4f, 2.8409f, 5.4632f, 2.6883f, 5.5757f, 2.5757f)
curveTo(5.6883f, 2.4632f, 5.8409f, 2.4f, 6.0f, 2.4f)
close()
}
}
.build()
return _vector!!
}
private var _vector: ImageVector? = null
| 32
|
Kotlin
|
1
| 8
|
5dbd5b7a42c621931d05a96e66431f67a3a50762
| 3,219
|
duckie-android
|
MIT License
|
plugins/kotlin/gradle/code-insight-common/src/org/jetbrains/kotlin/idea/gradleCodeInsightCommon/GradleBuildScriptSupport.kt
|
ingokegel
| 72,937,917
| false
| null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleCodeInsightCommon
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.psi.PsiFile
interface GradleBuildScriptSupport {
companion object {
val EP_NAME: ExtensionPointName<GradleBuildScriptSupport> =
ExtensionPointName.create("org.jetbrains.kotlin.idea.gradleBuildScriptSupport")
fun findManipulator(file: PsiFile, preferNewSyntax: Boolean = true): GradleBuildScriptManipulator<*>? {
for (extension in EP_NAME.extensionList) {
return extension.createManipulator(file, preferNewSyntax) ?: continue
}
return null
}
fun getManipulator(file: PsiFile, preferNewSyntax: Boolean = true): GradleBuildScriptManipulator<*> {
return findManipulator(file, preferNewSyntax) ?: error("Unknown build script file type (${file::class.qualifiedName})!")
}
}
fun createManipulator(file: PsiFile, preferNewSyntax: Boolean): GradleBuildScriptManipulator<*>?
fun createScriptBuilder(file: PsiFile): SettingsScriptBuilder<*>?
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 1,228
|
intellij-community
|
Apache License 2.0
|
lycoris/src/main/java/ru/spektrit/lycoris/viewdocument/PdfViewer.kt
|
arcanegolem
| 691,509,528
| false
|
{"Kotlin": 57032}
|
package ru.spektrit.lycoris.viewdocument
import android.graphics.pdf.PdfRenderer
import android.net.Uri
import androidx.annotation.RawRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import retrofit2.http.Url
import ru.spektrit.lycoris.network.provideDownloadInterface
import ru.spektrit.lycoris.utils.PfdHelper
/**
* PDF document viewer (via [LazyColumn]) from [RawRes]
*
* @param [modifier] [Modifier]
* @param [pdfResId] Raw resource id of a PDF document
* @param [pagesVerticalArrangement] Page arrangement
* @param [iconTint] Tint for controls icons
* @param [accentColor] Accent color for zoom controls background; NOTE: Color will be applied with 40% opacity
* @param [controlsAlignment] Alignment of zoom controls inside PdfViewer's box
* @param [bitmapScale] Pages bitmap scale, can be used for upscaling or downscaling quality of document's pages for optimizing visibility or/and performance
*/
@Composable
fun PdfViewer(
modifier: Modifier = Modifier,
@RawRes pdfResId: Int,
pagesVerticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(8.dp),
iconTint : Color = Color.Black,
accentColor : Color = Color.DarkGray,
controlsAlignment: Alignment = Alignment.BottomEnd,
bitmapScale : Int = 1
) {
val documentIdentifier = pdfResId.toString()
val rendererScope = rememberCoroutineScope()
val mutex = remember { Mutex() }
val context = LocalContext.current
val renderer by produceState<PdfRenderer?>(null, pdfResId) {
rendererScope.launch(Dispatchers.IO) {
val pfdHelper = PfdHelper()
value = PdfRenderer(pfdHelper.getPfd(context, pdfResId, documentIdentifier))
}
awaitDispose {
val currentRenderer = value
rendererScope.launch(Dispatchers.IO) {
mutex.withLock {
currentRenderer?.close()
}
}
}
}
PdfViewerDisplay(
accentColor = accentColor,
modifier = modifier,
context = context,
renderer = renderer,
documentIdentifier = documentIdentifier,
pagesVerticalArrangement = pagesVerticalArrangement,
mutex = mutex,
controlsAlignment = controlsAlignment,
iconTint = iconTint,
bitmapScale = bitmapScale
)
}
/**
* PDF document viewer (via [LazyColumn]) from [Uri]
*
* @param [modifier] [Modifier] interface for the whole composable, by default fills max size available
* @param [uri] [Uri] from which document should be retrieved
* @param [pagesVerticalArrangement] Page arrangement
* @param [iconTint] Tint for controls icons
* @param [accentColor] Accent color for zoom controls background; NOTE: Color will be applied with 40% opacity
* @param [controlsAlignment] Alignment of zoom controls inside PdfViewer's box
* @param [bitmapScale] Pages bitmap scale, can be used for upscaling or downscaling quality of document's pages for optimizing visibility or/and performance
*/
@Composable
fun PdfViewer(
modifier: Modifier = Modifier,
uri: Uri,
pagesVerticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(8.dp),
accentColor: Color = Color.DarkGray,
iconTint: Color = Color.Black,
controlsAlignment: Alignment = Alignment.BottomEnd,
bitmapScale : Int = 1
) {
val rendererScope = rememberCoroutineScope()
val mutex = remember { Mutex() }
val context = LocalContext.current
val renderer by produceState<PdfRenderer?>(null, uri) {
rendererScope.launch(Dispatchers.IO) {
val pfdHelper = PfdHelper()
value = PdfRenderer(pfdHelper.getPfd(uri))
}
awaitDispose {
val currentRenderer = value
rendererScope.launch(Dispatchers.IO) {
mutex.withLock { currentRenderer?.close() }
}
}
}
PdfViewerDisplay(
accentColor = accentColor,
modifier = modifier,
context = context,
renderer = renderer,
documentIdentifier = uri.toString(),
pagesVerticalArrangement = pagesVerticalArrangement,
mutex = mutex,
controlsAlignment = controlsAlignment,
iconTint = iconTint,
bitmapScale = bitmapScale
)
}
/**
* PDF document viewer (via [LazyColumn]) from [Url]
*
* @param [modifier] [Modifier] interface for the whole composable, by default fills max size available
* @param [url] [Url] where PDF document is stored at
* @param [headers] optional http headers
* @param [pagesVerticalArrangement] Page arrangement
* @param [iconTint] Tint for controls icons
* @param [accentColor] Accent color for zoom controls background; NOTE: Color will be applied with 40% opacity
* @param [controlsAlignment] Alignment of zoom controls inside PdfViewer's box
* @param [bitmapScale] Pages bitmap scale, can be used for upscaling or downscaling quality of document's pages for optimizing visibility or/and performance
*/
@Composable
fun PdfViewer(
modifier: Modifier = Modifier,
@Url url: String,
headers: HashMap<String, String>? = null,
pagesVerticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(8.dp),
accentColor: Color = Color.DarkGray,
iconTint: Color = Color.Black,
controlsAlignment: Alignment = Alignment.BottomEnd,
bitmapScale : Int = 1
) {
val rendererScope = rememberCoroutineScope()
val mutex = remember { Mutex() }
val context = LocalContext.current
val renderer by produceState<PdfRenderer?>(null, url) {
rendererScope.launch(Dispatchers.IO) {
val pfdHelper = PfdHelper()
value = PdfRenderer(pfdHelper.getPfd(url.split("/").last(), context, provideDownloadInterface(headers).downloadFile(url)))
}
awaitDispose {
val currentRenderer = value
rendererScope.launch(Dispatchers.IO) { mutex.withLock { currentRenderer?.close() } }
}
}
PdfViewerDisplay(
accentColor = accentColor,
modifier = modifier,
context = context,
renderer = renderer,
documentIdentifier = url,
pagesVerticalArrangement = pagesVerticalArrangement,
mutex = mutex,
controlsAlignment = controlsAlignment,
iconTint = iconTint,
bitmapScale = bitmapScale
)
}
| 1
|
Kotlin
|
1
| 9
|
b1d5c02ef3815379e1f2f9f91924beff32ca6205
| 6,759
|
Lycoris
|
Apache License 2.0
|
zeroframe/src/main/java/com/zero/zeroframe/ktx/TextViewKtx.kt
|
tao3634398
| 781,380,649
| false
|
{"Kotlin": 38187, "Java": 6049}
|
package com.zero.zeroframe.ktx
import android.graphics.drawable.Drawable
import android.widget.TextView
/**
* TextView相关扩展方法
* @author zero
* @since 2023/03/16
*/
fun TextView.setDrawableLeft(drawable: Drawable?) {
drawable?:return
setCompoundDrawablesRelativeWithIntrinsicBounds(drawable,null,null,null)
}
| 0
|
Kotlin
|
0
| 0
|
3661a349a825c1ed69f579ca5274ed8ac66b47a5
| 321
|
zeroframe
|
MIT License
|
logging/src/main/kotlin/dtmlibs/logging/LoggerCache.kt
|
dumptruckman
| 101,685,357
| false
|
{"Java": 349413, "Kotlin": 28164}
|
/*
* This file is part of dtmlibs.
*
* Copyright (c) 2017 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dtmlibs.logging
import mu.KLogger
/**
* A simple interface for providing [KLogger] objects for [Loggable]s from some sort of cache mechanism.
*/
interface LoggerCache {
/**
* Returns the cached logger for the given loggable. If no logger exists in the cache, one is created using
* the defaultValue and stored in the cache.
*/
fun getOrPut(loggable: Loggable, defaultValue: (Loggable) -> KLogger): KLogger
/**
* Returns the cached logger for the given class. If no logger exists in the cache, one is created using the
* defaultValue and stored in the cache.
*/
fun getOrPut(clazz: Class<*>, defaultValue: (Class<*>) -> KLogger): KLogger
/**
* Removes any cached logger for the given class.
*/
fun remove(clazz: Class<*>)
}
| 1
| null |
1
| 1
|
338be3010ce3947be1e6073d446dec44d592c658
| 1,948
|
dtmlibs
|
MIT License
|
app/shared/src/commonMain/kotlin/io/github/tscholze/cmpsample/model/SectionMapper.kt
|
Gauravprakash
| 668,161,668
| false
| null |
package io.github.tscholze.cmpsample.model
data class SectionMapper(
val title:String,
val subtitle:String,
val image:String,
val cta:String,
val ctaText:String,
val preference:String,
val resCom:String
)
| 0
|
Kotlin
|
0
| 0
|
12def96a895e0d178358110636ea5c241ee18c33
| 233
|
KotlinJetComposableUI
|
MIT License
|
SantanderDevWeek-App/app/src/main/java/com/example/santanderdevweek/data/Client.kt
|
GabrielFraga962
| 406,156,328
| false
|
{"Kotlin": 4083}
|
package com.example.santanderdevweek.data
data class Client(
val name: String
)
| 0
|
Kotlin
|
0
| 0
|
c3a0f66b6b9cba26134f273eabb6588f4c19636f
| 84
|
Santander_Dev_Week2021
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.