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/io/horizontalsystems/bankwallet/ui/compose/components/TextImportant.kt | horizontalsystems | 142,825,178 | false | {"Kotlin": 5050886, "Shell": 6112, "Ruby": 1350} | package io.horizontalsystems.bankwallet.ui.compose.components
import androidx.annotation.DrawableRes
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
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.unit.dp
import io.horizontalsystems.bankwallet.ui.compose.ComposeAppTheme
@Composable
fun TextImportantWarning(
modifier: Modifier = Modifier,
text: String,
title: String? = null,
@DrawableRes icon: Int? = null
) {
TextImportant(
modifier = modifier,
text = text,
title = title,
icon = icon,
borderColor = ComposeAppTheme.colors.jacob,
backgroundColor = ComposeAppTheme.colors.yellow20,
textColor = ComposeAppTheme.colors.jacob,
iconColor = ComposeAppTheme.colors.jacob
)
}
@Composable
fun TextImportantError(
modifier: Modifier = Modifier,
text: String,
title: String? = null,
@DrawableRes icon: Int? = null
) {
TextImportant(
modifier = modifier,
text = text,
title = title,
icon = icon,
borderColor = ComposeAppTheme.colors.lucian,
backgroundColor = ComposeAppTheme.colors.red20,
textColor = ComposeAppTheme.colors.lucian,
iconColor = ComposeAppTheme.colors.lucian
)
}
@Composable
fun TextImportant(
modifier: Modifier = Modifier,
text: String,
title: String? = null,
@DrawableRes icon: Int? = null,
borderColor: Color,
backgroundColor: Color,
textColor: Color,
iconColor: Color
) {
Column(
modifier = modifier
.fillMaxWidth()
.clip(RoundedCornerShape(8.dp))
.border(1.dp, borderColor, RoundedCornerShape(8.dp))
.background(backgroundColor)
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
if (title != null || icon != null) {
Row(
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
icon?.let {
Icon(
painter = painterResource(id = icon),
contentDescription = null,
tint = iconColor
)
}
title?.let {
Text(
text = it,
color = textColor,
style = ComposeAppTheme.typography.subhead1
)
}
}
}
if (text.isNotEmpty()) {
Text(
text = text,
color = ComposeAppTheme.colors.leah,
style = ComposeAppTheme.typography.subhead2
)
}
}
}
| 168 | Kotlin | 364 | 895 | 218cd81423c570cdd92b1d5161a600d07c35c232 | 3,096 | unstoppable-wallet-android | MIT License |
day13/src/main/kotlin/Computer.kt | rstockbridge | 225,212,001 | false | null | class Computer(private val state: Map<Long, Long>, private val ioProcessor: IOProcessor) {
fun run() {
val mutableState = state.toMutableMap()
var index = 0.toLong()
var instruction = mutableState.getValue(index)
var opcode = calculateOpcode(instruction)
var parameterModes = calculateParameterModes(instruction, opcode)
var relativeBase = 0.toLong()
while (true) {
if (opcode != 99) {
parameterModes = calculateParameterModes(instruction, opcode)
}
when (opcode) {
1 -> {
val parameter1 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
mutableState,
relativeBase
)
val parameter2 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 2),
parameterModes[1],
mutableState,
relativeBase
)
val outputPosition =
calculateWriteParameterUsingMode(
mutableState.getValue(index + 3),
parameterModes[2],
relativeBase
)
mutableState[outputPosition] = parameter1 + parameter2
index += 4
}
2 -> {
val parameter1 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
mutableState,
relativeBase
)
val parameter2 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 2),
parameterModes[1],
mutableState,
relativeBase
)
val outputPosition =
calculateWriteParameterUsingMode(
mutableState.getValue(index + 3),
parameterModes[2],
relativeBase
)
mutableState[outputPosition] = parameter1 * parameter2
index += 4
}
3 -> {
val outputPosition =
calculateWriteParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
relativeBase
)
mutableState[outputPosition] = ioProcessor.getInput()
index += 2
}
4 -> {
val parameter =
calculateReadParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
mutableState,
relativeBase
)
ioProcessor.shareOutput(parameter)
index += 2
}
5 -> {
val parameter1 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
mutableState,
relativeBase
)
if (parameter1 != 0.toLong()) {
val parameter2 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 2),
parameterModes[1],
mutableState,
relativeBase
)
index = parameter2
} else {
index += 3
}
}
6 -> {
val parameter1 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
mutableState,
relativeBase
)
if (parameter1 == 0.toLong()) {
val parameter2 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 2),
parameterModes[1],
mutableState,
relativeBase
)
index = parameter2
} else {
index += 3
}
}
7 -> {
val parameter1 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
mutableState,
relativeBase
)
val parameter2 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 2),
parameterModes[1],
mutableState,
relativeBase
)
val outputPosition =
calculateWriteParameterUsingMode(
mutableState.getValue(index + 3),
parameterModes[2],
relativeBase
)
if (parameter1 < parameter2) {
mutableState[outputPosition] = 1
} else {
mutableState[outputPosition] = 0
}
index += 4
}
8 -> {
val parameter1 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
mutableState,
relativeBase
)
val parameter2 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 2),
parameterModes[1],
mutableState,
relativeBase
)
val outputPosition =
calculateWriteParameterUsingMode(
mutableState.getValue(index + 3),
parameterModes[2],
relativeBase
)
if (parameter1 == parameter2) {
mutableState[outputPosition] = 1
} else {
mutableState[outputPosition] = 0
}
index += 4
}
9 -> {
val parameter1 =
calculateReadParameterUsingMode(
mutableState.getValue(index + 1),
parameterModes[0],
mutableState,
relativeBase
)
relativeBase += parameter1
index += 2
}
99 -> return
else -> throw IllegalStateException("This line should not be reached.")
}
instruction = mutableState.getValue(index)
opcode = calculateOpcode(instruction)
if (opcode != 99) {
parameterModes = calculateParameterModes(instruction, opcode)
}
}
}
fun calculateOpcode(instruction: Long): Int {
val instructionAsString = instruction.toString()
return if (instructionAsString.length == 1) {
instruction.toInt()
} else {
instructionAsString.substring(instructionAsString.length - 2 until instructionAsString.length).toInt()
}
}
private fun calculateParameterModes(instruction: Long, opcode: Int): List<Int> {
val instructionAsString = instruction.toString()
val length = instructionAsString.length
// one parameter
if (opcode == 3 || opcode == 4 || opcode == 9) {
val parameterMode: Int =
if (length <= 2) {
0
} else {
instructionAsString[length - 3].toString().toInt()
}
return listOf(parameterMode)
}
// two parameters
else if (opcode == 5 || opcode == 6) {
return when {
length <= 2 -> {
listOf(0, 0)
}
length == 3 -> {
val parameter1Mode = instructionAsString[length - 3].toString().toInt()
listOf(parameter1Mode, 0)
}
else -> {
val parameter1Mode = instructionAsString[length - 3].toString().toInt()
val parameter2Mode = instructionAsString[length - 4].toString().toInt()
listOf(parameter1Mode, parameter2Mode)
}
}
}
// three parameters
else if (opcode == 1 || opcode == 2 || opcode == 7 || opcode == 8) {
return when {
length <= 2 -> {
listOf(0, 0, 0)
}
length == 3 -> {
val parameter1Mode = instructionAsString[length - 3].toString().toInt()
listOf(parameter1Mode, 0, 0)
}
length == 4 -> {
val parameter1Mode = instructionAsString[length - 3].toString().toInt()
val parameter2Mode = instructionAsString[length - 4].toString().toInt()
listOf(parameter1Mode, parameter2Mode, 0)
}
else -> {
val parameter1Mode = instructionAsString[length - 3].toString().toInt()
val parameter2Mode = instructionAsString[length - 4].toString().toInt()
val parameter3Mode = instructionAsString[length - 5].toString().toInt()
listOf(parameter1Mode, parameter2Mode, parameter3Mode)
}
}
} else throw IllegalStateException("This line should not be reached.")
}
private fun calculateReadParameterUsingMode(
parameter: Long,
mode: Int,
instructions: Map<Long, Long>,
relativeBase: Long
): Long {
return when (mode) {
0 -> {
instructions.getOrDefault(parameter, 0)
}
1 -> {
parameter
}
2 -> {
instructions.getOrDefault(parameter + relativeBase, 0)
}
else -> throw IllegalStateException("This line should not be reached.")
}
}
private fun calculateWriteParameterUsingMode(
parameter: Long,
mode: Int,
relativeBase: Long
): Long {
return when (mode) {
0 -> {
parameter
}
2 -> {
parameter + relativeBase
}
else -> throw IllegalStateException("Trying parameter mode $mode")
}
}
}
| 0 | Kotlin | 0 | 0 | bcd6daf81787ed9a1d90afaa9646b1c513505d75 | 12,190 | AdventOfCode2019 | MIT License |
src/main/kotlin/test2/App.kt | skrinker | 341,874,860 | false | null | package test2
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import java.net.HttpURLConnection
import java.net.URL
private fun getWeather(cityName: String, token: String): String {
val url: URL = URL("https://api.openweathermap.org/data/2.5/weather?q=$cityName&appid=$token&units=metric")
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.connect()
val reader = conn.inputStream.reader()
var content: String
reader.use {
content = it.readText()
}
return content
}
fun main() = runBlocking {
val cityList = mutableListOf<String>("Moscow", "London", "Kazan")
val config = Config.parseJson("config.json")
cityList.forEach() {
async {
val result = Json.decodeFromString(WeatherResponse.serializer(), getWeather(it, config.token))
println("${result.name} ${result.main.temp}")
}
}
}
| 7 | Kotlin | 0 | 0 | 08f48726ca2e0d63992e933f6b3634aee4b0a785 | 969 | kotlin-spbu | Apache License 2.0 |
compose/src/main/java/androidx/ui/animation/StateAnimationWithInterruptionsDemo.kt | BlueLucky | 280,043,017 | true | {"Kotlin": 551590, "Shell": 5712, "HTML": 2737} | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.ui.animation.demos
import android.os.Handler
import android.os.Looper
import androidx.animation.FloatPropKey
import androidx.animation.TransitionState
import androidx.animation.transitionDefinition
import androidx.compose.Composable
import androidx.compose.getValue
import androidx.compose.mutableStateOf
import androidx.compose.setValue
import androidx.ui.animation.ColorPropKey
import androidx.ui.animation.Transition
import androidx.ui.core.Modifier
import androidx.ui.foundation.Box
import androidx.ui.foundation.Canvas
import androidx.ui.foundation.drawBackground
import androidx.ui.geometry.Offset
import androidx.ui.geometry.Size
import androidx.ui.graphics.Color
import androidx.ui.layout.fillMaxSize
@Composable
fun StateAnimationWithInterruptionsDemo() {
Box(Modifier.fillMaxSize()) {
ColorRect()
}
}
private val background = ColorPropKey()
private val y = FloatPropKey()
private enum class OverlayState {
Open,
Closed
}
private val definition = transitionDefinition {
state(OverlayState.Open) {
this[background] = Color(red = 128, green = 128, blue = 128, alpha = 255)
this[y] = 1f // percentage
}
state(OverlayState.Closed) {
this[background] = Color(red = 188, green = 222, blue = 145, alpha = 255)
this[y] = 0f // percentage
}
// Apply this transition to all state changes (i.e. Open -> Closed and Closed -> Open)
transition {
background using tween {
duration = 800
}
y using physics {
// Extremely low stiffness
stiffness = 40f
}
}
}
private val handler = Handler(Looper.getMainLooper())
@Composable
private fun ColorRect() {
var toState by mutableStateOf(OverlayState.Closed)
handler.postDelayed(object : Runnable {
override fun run() {
if ((0..1).random() == 0) {
toState = OverlayState.Open
} else {
toState = OverlayState.Closed
}
}
}, (200..800).random().toLong())
Transition(definition = definition, toState = toState) { state ->
ColorRectState(state = state)
}
}
@Composable
private fun ColorRectState(state: TransitionState) {
val color = state[background]
val scaleY = state[y]
Canvas(Modifier.fillMaxSize().drawBackground(color = color)) {
drawRect(
Color(alpha = 255, red = 255, green = 255, blue = 255),
topLeft = Offset(100f, 0f),
size = Size(size.width - 200f, scaleY * size.height)
)
}
}
| 0 | null | 0 | 0 | 899594173c878590dccc4cda25c64c5c53aeb27f | 3,193 | Jetpack-Compose-Playground | MIT License |
kirk-core/src/test/kotlin/com/automation/remarks/kirk/test/example/todo/TodoAngularTest.kt | ArtyomAnohin | 100,107,855 | true | {"Kotlin": 80781, "HTML": 2885, "Java": 1567} | package com.automation.remarks.kirk.test.example.todo
import com.automation.remarks.kirk.Kirk.Companion.open
import com.automation.remarks.kirk.conditions.exactText
import com.automation.remarks.kirk.conditions.size
import com.automation.remarks.kirk.conditions.text
import org.testng.annotations.Test
/**
* Created by sergey on 09.07.17.
*/
// tag::TodoAngularTest[]
class TodoAngularTest {
@Test fun testCanAddNewTaskAndDelete() {
open(::TodoPage) {
addTasks("Item0")
taskList.shouldHave(size(1))
deleteTask("Item0")
taskList.shouldHave(size(0))
}
}
@Test fun testCanDeactivateTask() {
open(::TodoPage) {
addTasks("A", "B", "C")
deactivateTask("A")
counter.shouldHave(text("2"))
goToCompletedTab()
taskList.shouldHave(exactText("A"))
}
}
}
// end::TodoAngularTest[] | 0 | Kotlin | 0 | 0 | 6042136a6686e1e9f9a974c9e8dd3176fde10986 | 928 | kirk | Apache License 2.0 |
android/src/main/java/org/ergoplatform/android/tokens/TokenUtils.kt | MrStahlfelge | 376,102,125 | false | null | package org.ergoplatform.android.tokens
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import org.ergoplatform.android.R
import org.ergoplatform.android.databinding.EntryWalletTokenBinding
import org.ergoplatform.android.databinding.EntryWalletTokenDetailsBinding
import org.ergoplatform.persistance.WalletToken
import org.ergoplatform.tokens.isSingularToken
import org.ergoplatform.utils.formatTokenAmounts
fun inflateAndBindTokenView(
walletToken: WalletToken,
linearLayout: LinearLayout,
layoutInflater: LayoutInflater
) {
val itemBinding =
EntryWalletTokenBinding.inflate(
layoutInflater,
linearLayout,
true
)
itemBinding.labelTokenName.text =
walletToken.name ?: layoutInflater.context.getString(R.string.label_unnamed_token)
itemBinding.labelTokenVal.text =
formatTokenAmounts(
walletToken.amount ?: 0,
walletToken.decimals,
)
}
fun inflateAndBindDetailedTokenEntryView(
walletToken: WalletToken,
linearLayout: LinearLayout,
layoutInflater: LayoutInflater
) {
val itemBinding =
EntryWalletTokenDetailsBinding.inflate(
layoutInflater,
linearLayout,
true
)
itemBinding.labelTokenName.text =
walletToken.name ?: layoutInflater.context.getString(R.string.label_unnamed_token)
itemBinding.labelTokenId.text = walletToken.tokenId
itemBinding.labelTokenVal.text =
formatTokenAmounts(
walletToken.amount ?: 0,
walletToken.decimals,
)
itemBinding.labelTokenVal.visibility =
if (walletToken.isSingularToken()) View.GONE else View.VISIBLE
} | 21 | null | 16 | 55 | fce2f952079f3becb81c0bc61f4cee17fe7807bb | 1,752 | ergo-wallet-android | Apache License 2.0 |
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/mpp/moduleContentRoots.kt | ingokegel | 72,937,917 | true | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration.mpp
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ContentRootData
import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import org.gradle.tooling.model.idea.IdeaContentRoot
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinSourceSetData
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinMppGradleProjectResolver
import org.jetbrains.kotlin.idea.gradleJava.configuration.kotlinGradleProjectDataOrFail
import org.jetbrains.kotlin.idea.gradleJava.configuration.mpp.KotlinMppGradleProjectResolverExtension.Result.Skip
import org.jetbrains.kotlin.idea.gradleJava.configuration.resourceType
import org.jetbrains.kotlin.idea.gradleJava.configuration.sourceType
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils
import org.jetbrains.kotlin.idea.gradleTooling.KotlinMPPGradleModel
import org.jetbrains.kotlin.idea.projectModel.KotlinSourceSet
import org.jetbrains.plugins.gradle.model.ExternalProject
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
internal fun KotlinMppGradleProjectResolver.Context.populateContentRoots(
) {
val extensionInstance = KotlinMppGradleProjectResolverExtension.buildInstance()
val sourceSetToPackagePrefix = mppModel.targets.flatMap { it.compilations }
.flatMap { compilation ->
compilation.declaredSourceSets.map { sourceSet -> sourceSet.name to compilation.kotlinTaskProperties.packagePrefix }
}
.toMap()
if (resolverCtx.getExtraProject(gradleModule, ExternalProject::class.java) == null) return
processSourceSets(gradleModule, mppModel, moduleDataNode, resolverCtx) { dataNode, sourceSet ->
if (dataNode == null || shouldDelegateToOtherPlugin(sourceSet)) return@processSourceSets
/* Execute all registered extension points and skip population of content roots if instructed by extensions */
if (extensionInstance.beforePopulateContentRoots(this, dataNode, sourceSet) == Skip) {
return@processSourceSets
}
createContentRootData(
sourceSet.sourceDirs,
sourceSet.sourceType,
sourceSetToPackagePrefix[sourceSet.name],
dataNode
)
createContentRootData(
sourceSet.resourceDirs,
sourceSet.resourceType,
null,
dataNode
)
extensionInstance.afterPopulateContentRoots(this, dataNode, sourceSet)
}
for (gradleContentRoot in gradleModule.contentRoots ?: emptySet<IdeaContentRoot?>()) {
if (gradleContentRoot == null) continue
val rootDirectory = gradleContentRoot.rootDirectory ?: continue
val ideContentRoot = ContentRootData(GradleConstants.SYSTEM_ID, rootDirectory.absolutePath).also { ideContentRoot ->
(gradleContentRoot.excludeDirectories ?: emptySet()).forEach { file ->
ideContentRoot.storePath(ExternalSystemSourceType.EXCLUDED, file.absolutePath)
}
}
moduleDataNode.createChild(ProjectKeys.CONTENT_ROOT, ideContentRoot)
}
val mppModelPureKotlinSourceFolders = mppModel.targets.flatMap { it.compilations }
.flatMap { it.kotlinTaskProperties.pureKotlinSourceFolders ?: emptyList() }
.map { it.absolutePath }
moduleDataNode.kotlinGradleProjectDataOrFail.pureKotlinSourceFolders.addAll(mppModelPureKotlinSourceFolders)
}
private fun processSourceSets(
gradleModule: IdeaModule,
mppModel: KotlinMPPGradleModel,
ideModule: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext,
processor: (DataNode<GradleSourceSetData>?, KotlinSourceSet) -> Unit
) {
val sourceSetsMap = HashMap<String, DataNode<GradleSourceSetData>>()
for (dataNode in ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)) {
if (dataNode.kotlinSourceSetData?.sourceSetInfo != null) {
sourceSetsMap[dataNode.data.id] = dataNode
}
}
for (sourceSet in mppModel.sourceSetsByName.values) {
val moduleId = KotlinModuleUtils.getKotlinModuleId(gradleModule, sourceSet, resolverCtx)
val moduleDataNode = sourceSetsMap[moduleId]
processor(moduleDataNode, sourceSet)
}
}
private fun createContentRootData(
sourceDirs: Set<File>,
sourceType: ExternalSystemSourceType,
packagePrefix: String?,
parentNode: DataNode<*>
) {
for (sourceDir in sourceDirs) {
val contentRootData = ContentRootData(GradleConstants.SYSTEM_ID, sourceDir.absolutePath)
contentRootData.storePath(sourceType, sourceDir.absolutePath, packagePrefix)
parentNode.createChild(ProjectKeys.CONTENT_ROOT, contentRootData)
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 5,328 | intellij-community | Apache License 2.0 |
idea/src/org/jetbrains/jet/plugin/findUsages/JetElementDescriptionProvider.kt | chashnikov | 14,658,474 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.findUsages
import com.intellij.psi.ElementDescriptionLocation
import com.intellij.psi.ElementDescriptionProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.util.RefactoringDescriptionLocation
import com.intellij.usageView.UsageViewLongNameLocation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.resolve.DescriptorUtils
import com.intellij.refactoring.util.CommonRefactoringUtil
public class JetElementDescriptionProvider : ElementDescriptionProvider {
public override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? {
val targetElement = element.unwrapped
fun elementKind() = when (targetElement) {
is JetClass -> if (targetElement.isTrait()) "trait" else "class"
is JetObjectDeclaration -> "object"
is JetNamedFunction -> "function"
is JetProperty -> "property"
is JetTypeParameter -> "type parameter"
is JetParameter -> "parameter"
else -> null
}
if (targetElement !is PsiNamedElement || targetElement !is JetElement) return null
val name = (targetElement as PsiNamedElement).getName()
return when(location) {
is UsageViewLongNameLocation ->
name
is RefactoringDescriptionLocation -> {
val kind = elementKind()
if (kind != null) {
val descriptor = (targetElement as JetDeclaration).descriptor
if (descriptor != null) {
val desc = if (location.includeParent() && targetElement !is JetTypeParameter && targetElement !is JetParameter) {
DescriptorUtils.getFqName(descriptor).asString()
}
else descriptor.getName().asString()
"$kind ${CommonRefactoringUtil.htmlEmphasize(desc)}"
}
else null
}
else null
}
else -> null
}
}
}
| 0 | null | 1 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 2,879 | kotlin | Apache License 2.0 |
app/src/test/java/fr/coppernic/transparent/robolectric/RobolectricTest.kt | Coppernic | 171,477,196 | false | null | package fr.coppernic.template.robolectric
import fr.bipi.tressence.console.SystemLogTree
import fr.coppernic.sdk.cpcutils.BuildConfig
import org.awaitility.Awaitility.await
import org.junit.AfterClass
import org.junit.Assert.assertTrue
import org.junit.BeforeClass
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLog
import timber.log.Timber
import java.util.concurrent.atomic.AtomicBoolean
/**
* Base class extended by every Robolectric test in this project.
* <p>
* Robolectric tests are done in a single thread !
*/
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class, sdk = [25])
abstract class RobolectricTest {
companion object {
@BeforeClass
@JvmStatic
fun beforeClass() {
//Configure robolectric
Timber.plant(SystemLogTree())
ShadowLog.stream = System.out
}
@AfterClass
@JvmStatic
fun afterClass() {
Timber.uprootAll()
}
}
private val unblock = AtomicBoolean(false)
fun sleep(ms: Long) {
try {
Thread.sleep(ms)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
fun unblock() {
unblock.set(true)
}
fun block() {
await().untilTrue(unblock)
}
fun doNotGoHere() {
assertTrue(false)
}
}
| 1 | null | 0 | 1 | 1d3116bceaaa1523dc18766799e77474519df69d | 1,477 | Serial | Apache License 2.0 |
features/series/src/main/java/com/chesire/nekome/app/series/collection/ui/CollectionScreen.kt | Chesire | 223,272,337 | false | null | @file:OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
package com.chesire.nekome.app.series.collection.ui
import android.content.Context
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BrokenImage
import androidx.compose.material.icons.filled.FilterAlt
import androidx.compose.material.icons.filled.InsertPhoto
import androidx.compose.material.icons.filled.PlusOne
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.SortByAlpha
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import com.chesire.nekome.app.series.R
import com.chesire.nekome.core.compose.composables.NekomeDialog
import com.chesire.nekome.core.compose.theme.NekomeTheme
import com.chesire.nekome.core.flags.Subtype
import com.chesire.nekome.core.flags.UserSeriesStatus
import com.chesire.nekome.core.preferences.flags.SortOption
@Composable
fun CollectionScreen(
viewModel: CollectionViewModel = hiltViewModel(),
navigateToItem: (Int, String) -> Unit
) {
val state = viewModel.uiState.collectAsState()
state.value.seriesDetails?.let {
LaunchedEffect(it.show) {
navigateToItem(it.seriesId, it.seriesTitle)
viewModel.execute(ViewAction.SeriesNavigationObserved)
}
}
Render(
state = state,
onRefresh = { viewModel.execute(ViewAction.PerformSeriesRefresh) },
onSelectSeries = { viewModel.execute(ViewAction.SeriesPressed(it)) },
onIncrementSeries = { viewModel.execute(ViewAction.IncrementSeriesPressed(it)) },
onRatingComplete = { series, rating ->
viewModel.execute(ViewAction.IncrementSeriesWithRating(series, rating))
},
onSnackbarShown = { viewModel.execute(ViewAction.ErrorSnackbarObserved) },
onSortPressed = { viewModel.execute(ViewAction.SortPressed) },
onSortResult = { viewModel.execute(ViewAction.PerformSort(it)) },
onFilterPressed = { viewModel.execute(ViewAction.FilterPressed) },
onFilterResult = { viewModel.execute(ViewAction.PerformFilter(it)) }
)
}
@Composable
private fun Render(
state: State<UIState>,
onRefresh: () -> Unit,
onSelectSeries: (Series) -> Unit,
onIncrementSeries: (Series) -> Unit,
onRatingComplete: (Series, Int?) -> Unit,
onSnackbarShown: () -> Unit,
onSortPressed: () -> Unit,
onSortResult: (SortOption?) -> Unit,
onFilterPressed: () -> Unit,
onFilterResult: (List<FilterOption>?) -> Unit
) {
val snackbarHostState = remember { SnackbarHostState() }
Scaffold(
topBar = {
TopAppBar(
title = {
Text(text = stringResource(id = state.value.screenTitle))
},
actions = {
IconButton(
onClick = onFilterPressed,
modifier = Modifier.semantics { testTag = SeriesCollectionTags.MenuFilter }
) {
Icon(
imageVector = Icons.Default.FilterAlt,
contentDescription = stringResource(id = R.string.menu_filter)
)
}
IconButton(
onClick = onSortPressed,
modifier = Modifier.semantics { testTag = SeriesCollectionTags.MenuSort }
) {
Icon(
imageVector = Icons.Default.SortByAlpha,
contentDescription = stringResource(id = R.string.menu_sort)
)
}
IconButton(
onClick = onRefresh,
modifier = Modifier.semantics { testTag = SeriesCollectionTags.MenuRefresh }
) {
Icon(
imageVector = Icons.Default.Refresh,
contentDescription = stringResource(id = R.string.series_list_refresh)
)
}
}
)
},
snackbarHost = {
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.semantics { testTag = SeriesCollectionTags.Snackbar }
)
},
modifier = Modifier.semantics { testTag = SeriesCollectionTags.Root }
) { paddingValues ->
if (state.value.isInitializing) {
CircularProgressIndicator()
} else {
SeriesCollection(
models = state.value.models,
isRefreshing = state.value.isRefreshing,
modifier = Modifier.padding(paddingValues),
onRefresh = onRefresh,
onSelectSeries = onSelectSeries,
onIncrementSeries = onIncrementSeries
)
}
}
SortDialog(
sortOptions = state.value.sortDialog,
onSortResult = onSortResult
)
RatingDialog(
ratingDialog = state.value.ratingDialog,
onRatingComplete = onRatingComplete
)
FilterDialog(
filterDialog = state.value.filterDialog,
onFilterResult = onFilterResult
)
RenderSnackbar(
snackbarData = state.value.errorSnackbar,
snackbarHostState = snackbarHostState,
onSnackbarShown = onSnackbarShown
)
}
@Composable
private fun SeriesCollection(
models: List<Series>,
isRefreshing: Boolean,
modifier: Modifier = Modifier,
onRefresh: () -> Unit,
onSelectSeries: (Series) -> Unit,
onIncrementSeries: (Series) -> Unit
) {
if (models.isNotEmpty()) {
val pullRefreshState = rememberPullRefreshState(
refreshing = isRefreshing,
onRefresh = onRefresh
)
Box(
modifier = modifier
.pullRefresh(pullRefreshState)
.semantics { testTag = SeriesCollectionTags.RefreshContainer }
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(
items = models,
key = { it.userId }
) {
SeriesItem(
model = it,
onSelectSeries = onSelectSeries,
onIncrementSeries = onIncrementSeries
)
}
}
PullRefreshIndicator(
refreshing = isRefreshing,
state = pullRefreshState,
modifier = Modifier.align(Alignment.TopCenter)
)
}
} else {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.semantics { testTag = SeriesCollectionTags.EmptyView }
) {
Text(
text = stringResource(id = R.string.series_list_empty),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.align(Alignment.Center)
)
}
}
}
@Composable
private fun SeriesItem(
model: Series,
onSelectSeries: (Series) -> Unit,
onIncrementSeries: (Series) -> Unit
) {
val context = LocalContext.current
val dateString = remember {
buildDateString(
context = context,
startDate = model.startDate,
endDate = model.endDate
)
}
Card(
onClick = { onSelectSeries(model) },
modifier = Modifier
.fillMaxWidth()
.height(125.dp)
.semantics { testTag = SeriesCollectionTags.SeriesItem }
) {
Box(modifier = Modifier.fillMaxSize()) {
if (model.isUpdating) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomCenter)
)
}
Row(modifier = Modifier.fillMaxSize()) {
AsyncImage(
model = model.posterImageUrl,
placeholder = rememberVectorPainter(image = Icons.Default.InsertPhoto),
error = rememberVectorPainter(image = Icons.Default.BrokenImage),
contentDescription = null,
modifier = Modifier
.fillMaxWidth(0.25f)
.aspectRatio(0.7f)
.align(Alignment.CenterVertically)
)
Column(
modifier = Modifier
.padding(8.dp)
.fillMaxHeight()
) {
Text(
text = model.title,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.padding(0.dp, 0.dp, 0.dp, 8.dp)
)
Text(
text = "${model.subtype} $dateString",
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.labelSmall,
modifier = Modifier
.fillMaxWidth()
.padding(0.dp, 0.dp, 0.dp, 16.dp)
)
Divider(
color = MaterialTheme.colorScheme.onSurface
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(0.dp, 8.dp, 0.dp, 0.dp),
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = model.progress,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.align(Alignment.CenterVertically)
)
if (model.showPlusOne) {
IconButton(
modifier = Modifier
.alpha(if (model.isUpdating) 0.3f else 1f)
.align(Alignment.CenterVertically)
.semantics { testTag = SeriesCollectionTags.PlusOne },
enabled = !model.isUpdating,
onClick = { onIncrementSeries(model) }
) {
Icon(
imageVector = Icons.Default.PlusOne,
contentDescription = stringResource(
id = R.string.series_list_plus_one
),
tint = MaterialTheme.colorScheme.primary
)
}
}
}
}
}
}
}
}
private fun buildDateString(context: Context, startDate: String, endDate: String): String {
return when {
startDate.isEmpty() && endDate.isEmpty() -> context.getString(R.string.series_list_unknown)
startDate == endDate -> startDate
endDate.isEmpty() -> context.getString(
R.string.series_list_date_range,
startDate,
context.getString(R.string.series_list_ongoing)
)
else -> context.getString(
R.string.series_list_date_range,
startDate,
endDate
)
}
}
@Composable
private fun SortDialog(sortOptions: Sort, onSortResult: (SortOption?) -> Unit) {
if (sortOptions.show) {
NekomeDialog(
title = R.string.sort_dialog_title,
confirmButton = R.string.ok,
cancelButton = R.string.cancel,
currentValue = sortOptions.currentSort,
allValues = sortOptions
.sortOptions
.associateWith { stringResource(id = it.stringId) }
.toList(),
onResult = onSortResult
)
}
}
@Composable
private fun RenderSnackbar(
snackbarData: SnackbarData?,
snackbarHostState: SnackbarHostState,
onSnackbarShown: () -> Unit
) {
snackbarData?.let { snackbar ->
val message = stringResource(id = snackbar.stringRes, snackbar.formatText)
LaunchedEffect(message) {
snackbarHostState.showSnackbar(message = message, duration = SnackbarDuration.Short)
onSnackbarShown()
}
}
}
@Composable
@Preview
private fun Preview() {
val initialState = UIState(
screenTitle = R.string.nav_anime,
isInitializing = false,
models = listOf(
Series(
userId = 0,
subtype = Subtype.Movie.name,
title = "Title",
progress = "0",
startDate = "2022-10-11",
endDate = "2022-12-27",
posterImageUrl = "",
rating = 1,
isUpdating = false,
showPlusOne = true
),
Series(
userId = 1,
subtype = Subtype.TV.name,
title = "Title 2",
progress = "3 / 5",
startDate = "2022-10-11",
endDate = "2022-12-27",
posterImageUrl = "",
rating = 2,
isUpdating = false,
showPlusOne = true
)
),
isRefreshing = false,
ratingDialog = null,
errorSnackbar = null,
seriesDetails = null,
sortDialog = Sort(
show = false,
currentSort = SortOption.Title,
sortOptions = listOf(
SortOption.Default,
SortOption.Title,
SortOption.StartDate,
SortOption.EndDate,
SortOption.Rating
)
),
filterDialog = Filter(
show = false,
filterOptions = listOf(
FilterOption(UserSeriesStatus.Current, true),
FilterOption(UserSeriesStatus.Completed, true),
FilterOption(UserSeriesStatus.OnHold, true),
FilterOption(UserSeriesStatus.Dropped, true),
FilterOption(UserSeriesStatus.Planned, true)
)
)
)
NekomeTheme(isDarkTheme = true) {
Render(
state = produceState(
initialValue = initialState,
producer = { value = initialState }
),
onRefresh = { /**/ },
onSelectSeries = { /**/ },
onIncrementSeries = { /**/ },
onRatingComplete = { _, _ -> /**/ },
onSnackbarShown = { /**/ },
onSortPressed = { /**/ },
onSortResult = { /**/ },
onFilterPressed = { /**/ },
onFilterResult = { /**/ }
)
}
}
object SeriesCollectionTags {
const val Root = "SeriesCollectionRoot"
const val EmptyView = "SeriesCollectionEmptyView"
const val RefreshContainer = "SeriesCollectionRefreshContainer"
const val SeriesItem = "SeriesCollectionSeriesItem"
const val PlusOne = "SeriesCollectionPlusOne"
const val Snackbar = "SeriesCollectionSnackbar"
const val MenuFilter = "SeriesCollectionMenuFilter"
const val MenuSort = "SeriesCollectionMenuSort"
const val MenuRefresh = "SeriesCollectionRefresh"
}
| 24 | null | 43 | 471 | 191def4011f659972951d3766bfb4e5af4076ab1 | 18,391 | Nekome | Apache License 2.0 |
src/main/kotlin/com/github/nanodesy/birthdayreminder/reminder/ReminderTask.kt | Nanodesy | 732,639,517 | false | {"Kotlin": 18214, "Dockerfile": 134} | package com.github.nanodesy.birthdayreminder.reminder
import com.github.nanodesy.birthdayreminder.person.Person
data class ReminderTask(
val telegramId: Long,
val person: Person
) | 0 | Kotlin | 0 | 0 | a6d41b7a461d679e85e5034bad92e6037052a59d | 185 | birthday-reminder | MIT License |
compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/FirTypeProjectionComparator.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.types
import org.jetbrains.kotlin.fir.render
object FirTypeProjectionComparator : Comparator<FirTypeProjection> {
private val FirTypeProjection.priority : Int
get() = when (this) {
is FirTypeProjectionWithVariance -> 2
is FirStarProjection -> 1
else -> 0
}
override fun compare(a: FirTypeProjection, b: FirTypeProjection): Int {
val priorityDiff = a.priority - b.priority
if (priorityDiff != 0) {
return priorityDiff
}
when (a) {
is FirTypeProjectionWithVariance -> {
require(b is FirTypeProjectionWithVariance) {
"priority is inconsistent: ${a.render()} v.s. ${b.render()}"
}
val typeRefDiff = FirTypeRefComparator.compare(a.typeRef, b.typeRef)
if (typeRefDiff != 0) {
return typeRefDiff
}
return a.variance.ordinal - b.variance.ordinal
}
is FirStarProjection -> {
return 0
}
else ->
error("Unsupported type projection comparison: ${a.render()} v.s. ${b.render()}")
}
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,464 | kotlin | Apache License 2.0 |
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/tiltaksgjennomforinger/TiltaksgjennomforingValidator.kt | navikt | 435,813,834 | false | {"Kotlin": 1491608, "TypeScript": 1375463, "SCSS": 42150, "JavaScript": 27837, "PLpgSQL": 14591, "HTML": 2263, "Dockerfile": 1430, "CSS": 1075, "Shell": 396} | package no.nav.mulighetsrommet.api.tiltaksgjennomforinger
import arrow.core.Either
import arrow.core.left
import arrow.core.nel
import arrow.core.raise.either
import arrow.core.right
import no.nav.mulighetsrommet.api.domain.dbo.AvtaleDbo
import no.nav.mulighetsrommet.api.domain.dbo.TiltaksgjennomforingDbo
import no.nav.mulighetsrommet.api.domain.dto.AvtaleAdminDto
import no.nav.mulighetsrommet.api.domain.dto.TiltaksgjennomforingAdminDto
import no.nav.mulighetsrommet.api.domain.dto.TiltakstypeAdminDto
import no.nav.mulighetsrommet.api.repositories.ArrangorRepository
import no.nav.mulighetsrommet.api.repositories.AvtaleRepository
import no.nav.mulighetsrommet.api.routes.v1.responses.ValidationError
import no.nav.mulighetsrommet.api.services.TiltakstypeService
import no.nav.mulighetsrommet.domain.Tiltakskode
import no.nav.mulighetsrommet.domain.Tiltakskoder
import no.nav.mulighetsrommet.domain.constants.ArenaMigrering
import no.nav.mulighetsrommet.domain.dbo.TiltaksgjennomforingOppstartstype
import no.nav.mulighetsrommet.domain.dto.AmoKategorisering
import no.nav.mulighetsrommet.domain.dto.AvtaleStatus
import no.nav.mulighetsrommet.domain.dto.Avtaletype
import no.nav.mulighetsrommet.domain.dto.TiltaksgjennomforingStatus
import java.time.LocalDate
class TiltaksgjennomforingValidator(
private val tiltakstyper: TiltakstypeService,
private val avtaler: AvtaleRepository,
private val arrangorer: ArrangorRepository,
) {
private val maksAntallTegnStedForGjennomforing = 100
fun validate(
dbo: TiltaksgjennomforingDbo,
previous: TiltaksgjennomforingAdminDto?,
): Either<List<ValidationError>, TiltaksgjennomforingDbo> = either {
var next = dbo
val tiltakstype = tiltakstyper.getById(next.tiltakstypeId)
?: raise(ValidationError.of(TiltaksgjennomforingDbo::tiltakstypeId, "Tiltakstypen finnes ikke").nel())
if (isTiltakstypeDisabled(previous, tiltakstype)) {
return ValidationError
.of(
TiltaksgjennomforingDbo::avtaleId,
"Opprettelse av tiltaksgjennomføring for tiltakstype: '${tiltakstype.navn}' er ikke skrudd på enda.",
)
.nel()
.left()
}
val avtale = avtaler.get(next.avtaleId)
?: raise(ValidationError.of(TiltaksgjennomforingDbo::avtaleId, "Avtalen finnes ikke").nel())
val errors = buildList {
if (avtale.tiltakstype.id != next.tiltakstypeId) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::tiltakstypeId,
"Tiltakstypen må være den samme som for avtalen",
),
)
}
if (next.administratorer.isEmpty()) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::administratorer,
"Du må velge minst én administrator",
),
)
}
if (avtale.avtaletype != Avtaletype.Forhaandsgodkjent && next.sluttDato == null) {
add(ValidationError.of(AvtaleDbo::sluttDato, "Du må legge inn sluttdato for gjennomføringen"))
}
if (next.sluttDato != null && next.startDato.isAfter(next.sluttDato)) {
add(ValidationError.of(TiltaksgjennomforingDbo::startDato, "Startdato må være før sluttdato"))
}
if (next.antallPlasser <= 0) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::antallPlasser,
"Du må legge inn antall plasser større enn 0",
),
)
}
if (Tiltakskoder.isKursTiltak(avtale.tiltakstype.tiltakskode)) {
validateKursTiltak(next)
} else {
if (next.oppstart == TiltaksgjennomforingOppstartstype.FELLES) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::oppstart,
"Tiltaket må ha løpende oppstartstype",
),
)
}
}
if (next.navEnheter.isEmpty()) {
add(ValidationError.of(TiltaksgjennomforingDbo::navEnheter, "Du må velge minst ett NAV-kontor"))
}
if (!avtale.kontorstruktur.any { it.region.enhetsnummer == next.navRegion }) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::navEnheter,
"NAV-region ${next.navRegion} mangler i avtalen",
),
)
}
val avtaleNavEnheter = avtale.kontorstruktur.flatMap { it.kontorer }.associateBy { it.enhetsnummer }
next.navEnheter.forEach { enhetsnummer ->
if (!avtaleNavEnheter.containsKey(enhetsnummer)) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::navEnheter,
"NAV-enhet $enhetsnummer mangler i avtalen",
),
)
}
}
val avtaleHasArrangor = avtale.arrangor.underenheter.any {
it.id == next.arrangorId
}
if (!avtaleHasArrangor) {
add(ValidationError.of(TiltaksgjennomforingDbo::arrangorId, "Du må velge en arrangør for avtalen"))
}
if (
tiltakstype.tiltakskode == Tiltakskode.GRUPPE_ARBEIDSMARKEDSOPPLAERING &&
avtale.amoKategorisering?.kurstype != null &&
avtale.amoKategorisering.kurstype !== AmoKategorisering.Kurstype.STUDIESPESIALISERING &&
next.amoKategorisering?.innholdElementer.isNullOrEmpty()
) {
add(ValidationError.ofCustomLocation("amoKategorisering.innholdElementer", "Du må velge minst ett element"))
}
next = validateOrResetTilgjengeligForArrangorDato(next)
if (previous == null) {
validateCreateGjennomforing(next, avtale)
} else {
validateUpdateGjennomforing(next, previous, avtale)
}
}
return errors.takeIf { it.isNotEmpty() }?.left() ?: next.right()
}
private fun validateOrResetTilgjengeligForArrangorDato(
next: TiltaksgjennomforingDbo,
): TiltaksgjennomforingDbo {
val nextTilgjengeligForArrangorDato = next.tilgjengeligForArrangorFraOgMedDato?.let { date ->
validateTilgjengeligForArrangorDato(date, next.startDato).fold({ null }, { it })
}
return next.copy(tilgjengeligForArrangorFraOgMedDato = nextTilgjengeligForArrangorDato)
}
fun validateTilgjengeligForArrangorDato(
tilgjengeligForArrangorDato: LocalDate,
startDato: LocalDate,
): Either<List<ValidationError>, LocalDate> {
val errors = buildList {
if (tilgjengeligForArrangorDato < LocalDate.now()) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::tilgjengeligForArrangorFraOgMedDato,
"Du må velge en dato som er etter dagens dato",
),
)
} else if (tilgjengeligForArrangorDato < startDato.minusMonths(2)) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::tilgjengeligForArrangorFraOgMedDato,
"Du må velge en dato som er tidligst to måneder før gjennomføringens oppstartsdato",
),
)
}
if (tilgjengeligForArrangorDato > startDato) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::tilgjengeligForArrangorFraOgMedDato,
"Du må velge en dato som er før gjennomføringens oppstartsdato",
),
)
}
}
return errors.takeIf { it.isNotEmpty() }?.left() ?: tilgjengeligForArrangorDato.right()
}
private fun MutableList<ValidationError>.validateCreateGjennomforing(
gjennomforing: TiltaksgjennomforingDbo,
avtale: AvtaleAdminDto,
) {
val arrangor = arrangorer.getById(gjennomforing.arrangorId)
if (arrangor.slettetDato != null) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::arrangorId,
"Arrangøren ${arrangor.navn} er slettet i Brønnøysundregistrene. Gjennomføringer kan ikke opprettes for slettede bedrifter.",
),
)
}
if (gjennomforing.startDato.isBefore(avtale.startDato)) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::startDato,
"Du må legge inn en startdato som er etter avtalens startdato",
),
)
}
if (gjennomforing.stedForGjennomforing != null && gjennomforing.stedForGjennomforing.length > maksAntallTegnStedForGjennomforing) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::stedForGjennomforing,
"Du kan bare skrive $maksAntallTegnStedForGjennomforing tegn i \"Sted for gjennomføring\"",
),
)
}
if (avtale.status != AvtaleStatus.AKTIV) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::avtaleId,
"Avtalen må være aktiv for å kunne opprette tiltak",
),
)
}
}
private fun MutableList<ValidationError>.validateUpdateGjennomforing(
gjennomforing: TiltaksgjennomforingDbo,
previous: TiltaksgjennomforingAdminDto,
avtale: AvtaleAdminDto,
) {
if (!previous.isAktiv()) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::navn,
"Du kan ikke gjøre endringer på en gjennomføring som ikke er aktiv",
),
)
}
if (gjennomforing.arrangorId != previous.arrangor.id) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::arrangorId,
"Du kan ikke endre arrangør når gjennomføringen er aktiv",
),
)
}
if (previous.status.status == TiltaksgjennomforingStatus.GJENNOMFORES) {
if (gjennomforing.avtaleId != previous.avtaleId) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::avtaleId,
"Du kan ikke endre avtalen når gjennomføringen er aktiv",
),
)
}
if (gjennomforing.startDato.isBefore(avtale.startDato)) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::startDato,
"Du må legge inn en startdato som er etter avtalens startdato",
),
)
}
if (gjennomforing.sluttDato != null &&
previous.sluttDato != null &&
gjennomforing.sluttDato.isBefore(LocalDate.now())
) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::sluttDato,
"Du kan ikke sette en sluttdato bakover i tid når gjennomføringen er aktiv",
),
)
}
}
if (isOwnedByArena(previous)) {
if (gjennomforing.navn != previous.navn) {
add(ValidationError.of(TiltaksgjennomforingDbo::navn, "Navn kan ikke endres utenfor Arena"))
}
if (gjennomforing.startDato != previous.startDato) {
add(ValidationError.of(TiltaksgjennomforingDbo::startDato, "Startdato kan ikke endres utenfor Arena"))
}
if (gjennomforing.sluttDato != previous.sluttDato) {
add(ValidationError.of(TiltaksgjennomforingDbo::sluttDato, "Sluttdato kan ikke endres utenfor Arena"))
}
if (gjennomforing.apentForInnsok != previous.apentForInnsok) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::apentForInnsok,
"Åpent for innsøk kan ikke endres utenfor Arena",
),
)
}
if (gjennomforing.antallPlasser != previous.antallPlasser) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::antallPlasser,
"Antall plasser kan ikke endres utenfor Arena",
),
)
}
if (gjennomforing.deltidsprosent != previous.deltidsprosent) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::deltidsprosent,
"Deltidsprosent kan ikke endres utenfor Arena",
),
)
}
}
}
private fun MutableList<ValidationError>.validateKursTiltak(dbo: TiltaksgjennomforingDbo) {
if (dbo.deltidsprosent <= 0) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::deltidsprosent,
"Du må velge en deltidsprosent større enn 0",
),
)
} else if (dbo.deltidsprosent > 100) {
add(
ValidationError.of(
TiltaksgjennomforingDbo::deltidsprosent,
"Du må velge en deltidsprosent mindre enn 100",
),
)
}
}
private fun isTiltakstypeDisabled(
previous: TiltaksgjennomforingAdminDto?,
tiltakstype: TiltakstypeAdminDto,
) = previous == null && !tiltakstyper.isEnabled(tiltakstype.tiltakskode)
private fun isOwnedByArena(previous: TiltaksgjennomforingAdminDto): Boolean {
return previous.opphav == ArenaMigrering.Opphav.ARENA && !tiltakstyper.isEnabled(previous.tiltakstype.tiltakskode)
}
}
| 8 | Kotlin | 2 | 7 | f64f29f5ad559115c0a6705f44f36bdffb273258 | 14,535 | mulighetsrommet | MIT License |
src/main/kotlin/kotlinmdl/components/IMdlMegaFooterMiddleSection.kt | sametkurumahmut | 119,988,311 | false | null | package kotlinmdl.components
import org.w3c.dom.Element
interface IMdlMegaFooterMiddleSection<out T : Element> : IMdlMegaFooterVerticalSection<T> {
companion object {
const val ELEMENT_NAME = "mdl-mega-footer__middle-section"
}
}
| 1 | Kotlin | 0 | 1 | 4ae2e6a03572aec5a8ea8bd3355ee031a4a3eb0e | 250 | kotlin-mdl-js | Apache License 2.0 |
generator/graphql-kotlin-federation/src/main/kotlin/com/expediagroup/graphql/generator/federation/FederatedSchemaGeneratorHooks.kt | ExpediaGroup | 148,706,161 | false | null | /*
* Copyright 2023 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.graphql.generator.federation
import com.apollographql.federation.graphqljava.printer.ServiceSDLPrinter.generateServiceSDL
import com.apollographql.federation.graphqljava.printer.ServiceSDLPrinter.generateServiceSDLV2
import com.expediagroup.graphql.generator.annotations.GraphQLName
import com.expediagroup.graphql.generator.directives.DirectiveMetaInformation
import com.expediagroup.graphql.generator.federation.directives.COMPOSE_DIRECTIVE_NAME
import com.expediagroup.graphql.generator.federation.directives.COMPOSE_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.EXTENDS_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.EXTERNAL_DIRECTIVE_NAME
import com.expediagroup.graphql.generator.federation.directives.EXTERNAL_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.EXTERNAL_DIRECTIVE_TYPE_V2
import com.expediagroup.graphql.generator.federation.directives.FEDERATION_SPEC_URL
import com.expediagroup.graphql.generator.federation.directives.FieldSet
import com.expediagroup.graphql.generator.federation.directives.INACCESSIBLE_DIRECTIVE_NAME
import com.expediagroup.graphql.generator.federation.directives.INACCESSIBLE_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.INTERFACE_OBJECT_DIRECTIVE_NAME
import com.expediagroup.graphql.generator.federation.directives.INTERFACE_OBJECT_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.KEY_DIRECTIVE_NAME
import com.expediagroup.graphql.generator.federation.directives.KEY_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.KEY_DIRECTIVE_TYPE_V2
import com.expediagroup.graphql.generator.federation.directives.LINK_DIRECTIVE_NAME
import com.expediagroup.graphql.generator.federation.directives.LINK_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.OVERRIDE_DIRECTIVE_NAME
import com.expediagroup.graphql.generator.federation.directives.OVERRIDE_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.PROVIDES_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.REQUIRES_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.SHAREABLE_DIRECTIVE_NAME
import com.expediagroup.graphql.generator.federation.directives.SHAREABLE_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.TAG_DIRECTIVE_TYPE
import com.expediagroup.graphql.generator.federation.directives.appliedLinkDirective
import com.expediagroup.graphql.generator.federation.exception.IncorrectFederatedDirectiveUsage
import com.expediagroup.graphql.generator.federation.execution.EntitiesDataFetcher
import com.expediagroup.graphql.generator.federation.execution.FederatedTypeResolver
import com.expediagroup.graphql.generator.federation.types.ANY_SCALAR_TYPE
import com.expediagroup.graphql.generator.federation.types.ENTITY_UNION_NAME
import com.expediagroup.graphql.generator.federation.types.FIELD_SET_SCALAR_NAME
import com.expediagroup.graphql.generator.federation.types.FIELD_SET_SCALAR_TYPE
import com.expediagroup.graphql.generator.federation.types.FieldSetTransformer
import com.expediagroup.graphql.generator.federation.types.SERVICE_FIELD_DEFINITION
import com.expediagroup.graphql.generator.federation.types._Service
import com.expediagroup.graphql.generator.federation.types.generateEntityFieldDefinition
import com.expediagroup.graphql.generator.federation.validation.FederatedSchemaValidator
import com.expediagroup.graphql.generator.hooks.SchemaGeneratorHooks
import graphql.TypeResolutionEnvironment
import graphql.schema.DataFetcher
import graphql.schema.FieldCoordinates
import graphql.schema.GraphQLCodeRegistry
import graphql.schema.GraphQLDirective
import graphql.schema.GraphQLObjectType
import graphql.schema.GraphQLSchema
import graphql.schema.GraphQLType
import graphql.schema.SchemaTransformer
import kotlin.reflect.KType
import kotlin.reflect.full.findAnnotation
/**
* Hooks for generating federated GraphQL schema.
*/
open class FederatedSchemaGeneratorHooks(
private val resolvers: List<FederatedTypeResolver>,
private val optInFederationV2: Boolean = true
) : SchemaGeneratorHooks {
private val validator = FederatedSchemaValidator()
private val federationV2OnlyDirectiveNames: Set<String> = setOf(
COMPOSE_DIRECTIVE_NAME,
INACCESSIBLE_DIRECTIVE_NAME,
INTERFACE_OBJECT_DIRECTIVE_NAME,
LINK_DIRECTIVE_NAME,
OVERRIDE_DIRECTIVE_NAME,
SHAREABLE_DIRECTIVE_NAME
)
private val federatedDirectiveV1List: List<GraphQLDirective> = listOf(
EXTENDS_DIRECTIVE_TYPE,
EXTERNAL_DIRECTIVE_TYPE,
KEY_DIRECTIVE_TYPE,
PROVIDES_DIRECTIVE_TYPE,
REQUIRES_DIRECTIVE_TYPE
)
private val federatedDirectiveV2List: List<GraphQLDirective> = listOf(
COMPOSE_DIRECTIVE_TYPE,
EXTENDS_DIRECTIVE_TYPE,
EXTERNAL_DIRECTIVE_TYPE_V2,
INACCESSIBLE_DIRECTIVE_TYPE,
INTERFACE_OBJECT_DIRECTIVE_TYPE,
KEY_DIRECTIVE_TYPE_V2,
LINK_DIRECTIVE_TYPE,
OVERRIDE_DIRECTIVE_TYPE,
PROVIDES_DIRECTIVE_TYPE,
REQUIRES_DIRECTIVE_TYPE,
SHAREABLE_DIRECTIVE_TYPE,
TAG_DIRECTIVE_TYPE
)
/**
* Add support for _FieldSet scalar to the schema.
*/
override fun willGenerateGraphQLType(type: KType): GraphQLType? = when (type.classifier) {
FieldSet::class -> FIELD_SET_SCALAR_TYPE
else -> super.willGenerateGraphQLType(type)
}
override fun willGenerateDirective(directiveInfo: DirectiveMetaInformation): GraphQLDirective? =
if (optInFederationV2) {
willGenerateFederatedDirectiveV2(directiveInfo)
} else {
willGenerateFederatedDirective(directiveInfo)
}
private fun willGenerateFederatedDirective(directiveInfo: DirectiveMetaInformation): GraphQLDirective? = when {
federationV2OnlyDirectiveNames.contains(directiveInfo.effectiveName) -> throw IncorrectFederatedDirectiveUsage(directiveInfo.effectiveName)
EXTERNAL_DIRECTIVE_NAME == directiveInfo.effectiveName -> EXTERNAL_DIRECTIVE_TYPE
KEY_DIRECTIVE_NAME == directiveInfo.effectiveName -> KEY_DIRECTIVE_TYPE
else -> super.willGenerateDirective(directiveInfo)
}
private fun willGenerateFederatedDirectiveV2(directiveInfo: DirectiveMetaInformation): GraphQLDirective? = when (directiveInfo.effectiveName) {
EXTERNAL_DIRECTIVE_NAME -> EXTERNAL_DIRECTIVE_TYPE_V2
KEY_DIRECTIVE_NAME -> KEY_DIRECTIVE_TYPE_V2
LINK_DIRECTIVE_NAME -> LINK_DIRECTIVE_TYPE
else -> super.willGenerateDirective(directiveInfo)
}
override fun didGenerateGraphQLType(type: KType, generatedType: GraphQLType): GraphQLType {
validator.validateGraphQLType(generatedType)
return super.didGenerateGraphQLType(type, generatedType)
}
override fun willBuildSchema(builder: GraphQLSchema.Builder): GraphQLSchema.Builder {
val originalSchema = builder.build()
val originalQuery = originalSchema.queryType
findMissingFederationDirectives(originalSchema.directives).forEach {
builder.additionalDirective(it)
}
if (optInFederationV2) {
val fed2Imports = federatedDirectiveV2List.map { "@${it.name}" }
.minus("@$LINK_DIRECTIVE_NAME")
.plus(FIELD_SET_SCALAR_NAME)
builder.withSchemaDirective(LINK_DIRECTIVE_TYPE)
.withSchemaAppliedDirective(appliedLinkDirective(FEDERATION_SPEC_URL, fed2Imports))
}
val federatedCodeRegistry = GraphQLCodeRegistry.newCodeRegistry(originalSchema.codeRegistry)
val entityTypeNames = getFederatedEntities(originalSchema)
// Add the _entities field to the query and register all the _Entity union types
if (entityTypeNames.isNotEmpty()) {
val federatedQuery = GraphQLObjectType.newObject(originalQuery)
val entityField = generateEntityFieldDefinition(entityTypeNames)
federatedQuery.field(entityField)
federatedCodeRegistry.dataFetcher(FieldCoordinates.coordinates(originalQuery.name, entityField.name), EntitiesDataFetcher(resolvers))
federatedCodeRegistry.typeResolver(ENTITY_UNION_NAME) { env: TypeResolutionEnvironment -> env.schema.getObjectType(env.getObjectName()) }
builder.query(federatedQuery)
.codeRegistry(federatedCodeRegistry.build())
.additionalType(ANY_SCALAR_TYPE)
}
val federatedBuilder = if (optInFederationV2) {
builder
} else {
// transform schema to rename FieldSet to _FieldSet
GraphQLSchema.newSchema(SchemaTransformer.transformSchema(builder.build(), FieldSetTransformer()))
}
// Register the data fetcher for the _service query
val sdl = getFederatedServiceSdl(federatedBuilder.build())
federatedCodeRegistry.dataFetcher(FieldCoordinates.coordinates(originalQuery.name, SERVICE_FIELD_DEFINITION.name), DataFetcher { _Service(sdl) })
return federatedBuilder.codeRegistry(federatedCodeRegistry.build())
}
private fun findMissingFederationDirectives(existingDirectives: List<GraphQLDirective>): List<GraphQLDirective> {
val existingDirectiveNames = existingDirectives.map { it.name }
return federatedDirectiveList().filter {
!existingDirectiveNames.contains(it.name)
}
}
private fun federatedDirectiveList(): List<GraphQLDirective> = if (optInFederationV2) {
federatedDirectiveV2List
} else {
federatedDirectiveV1List
}
/**
* Federated service may not have any regular queries but will have federated queries. In order to ensure that we
* have a valid GraphQL schema that can be modified in the [willBuildSchema], query has to have at least one single field.
*
* Add federated _service query to ensure it is a valid GraphQL schema.
*/
override fun didGenerateQueryObject(type: GraphQLObjectType): GraphQLObjectType = GraphQLObjectType.newObject(type)
.field(SERVICE_FIELD_DEFINITION)
.also {
if (!optInFederationV2) {
it.withAppliedDirective(EXTENDS_DIRECTIVE_TYPE.toAppliedDirective())
}
}
.build()
/**
* Get the modified SDL returned by _service field
*
* It should NOT contain:
* - default schema definition
* - empty Query type
* - any directive definitions
* - any custom directives
* - new federated scalars
*
* See the federation spec for more details:
* https://www.apollographql.com/docs/apollo-server/federation/federation-spec/#query_service
*/
private fun getFederatedServiceSdl(schema: GraphQLSchema): String {
return if (optInFederationV2) {
generateServiceSDLV2(schema)
} else {
generateServiceSDL(schema, false)
}
}
/**
* Get all the federation entities in the _Entity union, aka all the types with the @key directive.
*
* See the federation spec:
* https://www.apollographql.com/docs/apollo-server/federation/federation-spec/#union-_entity
*/
private fun getFederatedEntities(originalSchema: GraphQLSchema): Set<String> {
return originalSchema.allTypesAsList
.asSequence()
.filterIsInstance<GraphQLObjectType>()
.filter { type -> type.hasAppliedDirective(KEY_DIRECTIVE_NAME) }
.map { it.name }
.toSet()
}
private fun TypeResolutionEnvironment.getObjectName(): String? {
val kClass = this.getObject<Any>().javaClass.kotlin
return kClass.findAnnotation<GraphQLName>()?.value
?: kClass.simpleName
}
}
| 32 | Kotlin | 329 | 1,640 | 405255427937306dc1e6326d92b236966476e79b | 12,543 | graphql-kotlin | Apache License 2.0 |
common/src/commonMain/kotlin/com/artemchep/keyguard/feature/passkeys/directory/PasskeysServicesRoute.kt | AChep | 669,697,660 | false | {"Kotlin": 5254408, "HTML": 45810} | package com.artemchep.keyguard.feature.passkeys.directory
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.outlined.Key
import androidx.compose.runtime.Composable
import com.artemchep.keyguard.feature.navigation.NavigationIntent
import com.artemchep.keyguard.feature.navigation.Route
import com.artemchep.keyguard.feature.navigation.state.TranslatorScope
import com.artemchep.keyguard.res.Res
import com.artemchep.keyguard.ui.FlatItemAction
import com.artemchep.keyguard.ui.icons.ChevronIcon
import com.artemchep.keyguard.ui.icons.iconSmall
object PasskeysServicesRoute : Route {
const val ROUTER_NAME = "passkeys_services"
fun actionOrNull(
translator: TranslatorScope,
navigate: (NavigationIntent) -> Unit,
) = action(
translator = translator,
navigate = navigate,
)
fun action(
translator: TranslatorScope,
navigate: (NavigationIntent) -> Unit,
) = FlatItemAction(
leading = iconSmall(Icons.Outlined.Folder, Icons.Outlined.Key),
title = translator.translate(Res.strings.passkeys_directory_title),
text = translator.translate(Res.strings.passkeys_directory_text),
trailing = {
ChevronIcon()
},
onClick = {
val route = PasskeysServicesRoute
val intent = NavigationIntent.NavigateToRoute(route)
navigate(intent)
},
)
@Composable
override fun Content() {
TwoFaServicesScreen()
}
}
| 57 | Kotlin | 22 | 735 | 4e9809d0252257b9e918e44050570769d9326bc2 | 1,575 | keyguard-app | Linux Kernel Variant of OpenIB.org license |
app/src/main/java/com/example/newsapp/common/Constants.kt | milosursulovic | 577,638,138 | false | {"Kotlin": 29536} | package com.example.newsapp.common
object Constants {
const val API_URL = "https://newsapi.org"
} | 0 | Kotlin | 0 | 0 | 8f099dd0a4aab91879303caa85838de3f4676874 | 102 | news-app | MIT License |
app/src/main/java/com/concordium/wallet/ui/bakerdelegation/delegation/introflow/DelegationRemoveIntroFlowActivity.kt | Concordium | 358,250,608 | false | null | package com.concordium.wallet.ui.bakerdelegation.delegation.introflow
import android.content.Intent
import com.concordium.wallet.R
import com.concordium.wallet.ui.bakerdelegation.common.BaseDelegationBakerFlowActivity
import com.concordium.wallet.ui.bakerdelegation.common.DelegationBakerViewModel.Companion.EXTRA_DELEGATION_BAKER_DATA
import com.concordium.wallet.ui.bakerdelegation.delegation.DelegationRemoveActivity
class DelegationRemoveIntroFlowActivity :
BaseDelegationBakerFlowActivity(R.string.delegation_intro_flow_title) {
override fun getTitles(): IntArray {
return intArrayOf(
R.string.delegation_remove_subtitle1,
R.string.delegation_remove_subtitle2
)
}
override fun gotoContinue() {
val intent = Intent(this, DelegationRemoveActivity::class.java)
intent.putExtra(EXTRA_DELEGATION_BAKER_DATA, bakerDelegationData)
startActivityForResultAndHistoryCheck(intent)
}
override fun getLink(position: Int): String {
return "file:///android_asset/delegation_remove_flow_en_" + (position + 1) + ".html"
}
}
| 77 | null | 3 | 9 | 779eaefb28511102c93d37381283c6d2e7f54c43 | 1,117 | concordium-reference-wallet-android | Apache License 2.0 |
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/finance/ExchangeFundsLine.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.remix.remix.finance
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.FinanceGroup
public val FinanceGroup.ExchangeFundsLine: ImageVector
get() {
if (_exchangeFundsLine != null) {
return _exchangeFundsLine!!
}
_exchangeFundsLine = Builder(name = "ExchangeFundsLine", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.379f, 15.106f)
curveTo(20.926f, 11.442f, 19.537f, 7.114f, 16.004f, 5.075f)
curveTo(13.451f, 3.6f, 10.423f, 3.694f, 8.035f, 5.056f)
lineTo(7.042f, 3.319f)
curveTo(10.028f, 1.616f, 13.813f, 1.5f, 17.004f, 3.342f)
curveTo(21.495f, 5.935f, 23.214f, 11.485f, 21.122f, 16.112f)
lineTo(22.463f, 16.887f)
lineTo(18.298f, 19.101f)
lineTo(18.133f, 14.387f)
lineTo(19.379f, 15.106f)
close()
moveTo(4.63f, 8.9f)
curveTo(3.083f, 12.563f, 4.471f, 16.891f, 8.004f, 18.931f)
curveTo(10.557f, 20.405f, 13.585f, 20.312f, 15.974f, 18.95f)
lineTo(16.966f, 20.687f)
curveTo(13.98f, 22.389f, 10.196f, 22.506f, 7.004f, 20.663f)
curveTo(2.514f, 18.07f, 0.795f, 12.521f, 2.887f, 7.893f)
lineTo(1.545f, 7.119f)
lineTo(5.71f, 4.905f)
lineTo(5.875f, 9.619f)
lineTo(4.63f, 8.9f)
close()
moveTo(13.418f, 14.831f)
lineTo(10.59f, 12.003f)
lineTo(7.762f, 14.831f)
lineTo(6.347f, 13.417f)
lineTo(10.59f, 9.174f)
lineTo(13.418f, 12.003f)
lineTo(16.247f, 9.174f)
lineTo(17.661f, 10.589f)
lineTo(13.418f, 14.831f)
close()
}
}
.build()
return _exchangeFundsLine!!
}
private var _exchangeFundsLine: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,832 | compose-icon-collections | MIT License |
pushnotifications/src/main/java/com/pusher/pushnotifications/logging/Logger.kt | pusher | 109,729,032 | false | {"Kotlin": 225529, "Java": 17735} | package com.eventflit.pushnotifications.logging
import java.util.concurrent.ConcurrentHashMap
import android.util.Log
import kotlin.reflect.KClass
class Logger(private val name: String) {
fun v(msg: String, t: Throwable? = null) {
if (logLevel <= Log.VERBOSE) {
if (t != null) {
Log.v(name, msg, t)
} else {
Log.v(name, msg)
}
}
}
fun d(msg: String, t: Throwable? = null) {
if (logLevel <= Log.DEBUG) {
if (t != null) {
Log.d(name, msg, t)
} else {
Log.d(name, msg)
}
}
}
fun i(msg: String, t: Throwable? = null) {
if (logLevel <= Log.INFO) {
if (t != null) {
Log.i(name, msg, t)
} else {
Log.i(name, msg)
}
}
}
fun w(msg: String, t: Throwable? = null) {
if (logLevel <= Log.WARN) {
if (t != null) {
Log.w(name, msg, t)
} else {
Log.w(name, msg)
}
}
}
fun e(msg: String, t: Throwable? = null) {
if (logLevel <= Log.ERROR) {
if (t != null) {
Log.e(name, msg, t)
} else {
Log.e(name, msg)
}
}
}
companion object {
private val loggers = ConcurrentHashMap<KClass<*>, Logger>()
var logLevel = Log.DEBUG
fun get(cl: KClass<*>): Logger {
return loggers.getOrPut(cl, {
return if (cl.java.name.endsWith("\$Companion")) {
// strip out the `$Companion` part and get the actual class simpleName
Logger(cl.java.name.dropLast("\$Companion".length).split('.').last())
} else {
Logger(cl.java.simpleName)
}
})
}
}
}
| 21 | Kotlin | 22 | 22 | 868326f4181bfe493c75a1a95aae395c4afba8bc | 1,626 | push-notifications-android | MIT License |
app/src/main/kotlin/com/akinci/doggo/ui/ds/components/CachedImage.kt | AttilaAKINCI | 440,251,794 | false | {"Kotlin": 136691} | package com.akinci.doggo.ui.ds.components
import androidx.annotation.DrawableRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import coil.compose.AsyncImage
import coil.request.CachePolicy
import coil.request.ImageRequest
import kotlinx.coroutines.Dispatchers
/**
* CachedImage is a variation of [AsyncImage] which automatically cache it's content.
*
* @property [modifier] compose modifier
* @property [imageUrl] image url to load
* @property [placeHolderId] placeholder resource Id in case of any error, fallback or etc.
*
* **/
@Composable
fun CachedImage(
modifier: Modifier = Modifier,
imageUrl: String,
@DrawableRes placeHolderId: Int,
) {
val imageRequest = ImageRequest.Builder(LocalContext.current)
.data(imageUrl)
.dispatcher(Dispatchers.IO)
.memoryCacheKey(imageUrl)
.diskCacheKey(imageUrl)
.diskCachePolicy(CachePolicy.ENABLED)
.memoryCachePolicy(CachePolicy.ENABLED)
.placeholder(placeHolderId)
.error(placeHolderId)
.fallback(placeHolderId)
.build()
AsyncImage(
modifier = modifier,
model = imageRequest,
contentScale = ContentScale.Crop,
contentDescription = null,
)
}
| 0 | Kotlin | 0 | 2 | c1e46241b922365a7cab954cc916a989415ac15e | 1,364 | Doggo | Apache License 2.0 |
app/src/main/java/com/trawlbens/reift/e_commerce/MyApplication.kt | ReihanFatilla | 702,794,881 | false | {"Kotlin": 71803} | package com.trawlbens.reift.e_commerce
import android.app.Application
import com.trawlbens.reift.e_commerce.di.listModules
import com.trawlbens.reift.e_commerce.utils.NotificationWorker
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.GlobalContext.startKoin
import org.koin.core.logger.Level
class MyApplication : Application(){
override fun onCreate() {
super.onCreate()
NotificationWorker.scheduleNotificationWorker(this)
startKoin {
androidLogger(Level.NONE)
androidContext(this@MyApplication)
modules(
listModules
)
}
}
} | 0 | Kotlin | 0 | 0 | 274e8ab8b7d517845f22708d1cb26410e268b6a2 | 707 | ECommerce-Compose | MIT License |
app/src/main/java/org/simple/clinic/summary/PatientSummaryScreenController.kt | pratul | 151,071,054 | false | null | package org.simple.clinic.summary
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.ofType
import io.reactivex.rxkotlin.withLatestFrom
import org.simple.clinic.ReportAnalyticsEvents
import org.simple.clinic.analytics.Analytics
import org.simple.clinic.bp.BloodPressureRepository
import org.simple.clinic.drugs.PrescriptionRepository
import org.simple.clinic.medicalhistory.MedicalHistory
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion.HAS_DIABETES
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion.HAS_HAD_A_HEART_ATTACK
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion.HAS_HAD_A_KIDNEY_DISEASE
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion.HAS_HAD_A_STROKE
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion.IS_ON_TREATMENT_FOR_HYPERTENSION
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion.NONE
import org.simple.clinic.medicalhistory.MedicalHistoryRepository
import org.simple.clinic.patient.PatientRepository
import org.simple.clinic.summary.PatientSummaryCaller.NEW_PATIENT
import org.simple.clinic.summary.PatientSummaryCaller.SEARCH
import org.simple.clinic.util.Just
import org.simple.clinic.util.exhaustive
import org.simple.clinic.widgets.UiEvent
import javax.inject.Inject
typealias Ui = PatientSummaryScreen
typealias UiChange = (Ui) -> Unit
class PatientSummaryScreenController @Inject constructor(
private val patientRepository: PatientRepository,
private val bpRepository: BloodPressureRepository,
private val prescriptionRepository: PrescriptionRepository,
private val medicalHistoryRepository: MedicalHistoryRepository,
private val timestampGenerator: RelativeTimestampGenerator
) : ObservableTransformer<UiEvent, UiChange> {
override fun apply(events: Observable<UiEvent>): ObservableSource<UiChange> {
val replayedEvents = events.compose(ReportAnalyticsEvents()).replay().refCount()
return Observable.mergeArray(
reportViewedPatientEvent(replayedEvents),
populatePatientProfile(replayedEvents),
constructListDataSet(replayedEvents),
updateMedicalHistory(replayedEvents),
openBloodPressureBottomSheet(replayedEvents),
openPrescribedDrugsScreen(replayedEvents),
handleBackAndDoneClicks(replayedEvents),
exitScreenAfterSchedulingAppointment(replayedEvents))
}
private fun reportViewedPatientEvent(events: Observable<UiEvent>): Observable<UiChange> {
return events.ofType<PatientSummaryScreenCreated>()
.take(1L)
.doOnNext { (patientUuid, caller) -> Analytics.reportViewedPatient(patientUuid, caller.name) }
.flatMap { Observable.empty<UiChange>() }
}
private fun populatePatientProfile(events: Observable<UiEvent>): Observable<UiChange> {
val patientUuid = events
.ofType<PatientSummaryScreenCreated>()
.map { it.patientUuid }
val sharedPatients = patientUuid
.flatMap { patientRepository.patient(it) }
.map {
// We do not expect the patient to get deleted while this screen is already open.
(it as Just).value
}
.replay(1)
.refCount()
val addresses = sharedPatients
.flatMap { patient -> patientRepository.address(patient.addressUuid) }
.map { (it as Just).value }
val phoneNumbers = patientUuid
.flatMap { patientRepository.phoneNumbers(it) }
return Observables.combineLatest(sharedPatients, addresses, phoneNumbers)
.map { (patient, address, phoneNumber) -> { ui: Ui -> ui.populatePatientProfile(patient, address, phoneNumber) } }
}
private fun constructListDataSet(events: Observable<UiEvent>): Observable<UiChange> {
val patientUuids = events
.ofType<PatientSummaryScreenCreated>()
.map { it.patientUuid }
val prescriptionItems = patientUuids
.flatMap { prescriptionRepository.newestPrescriptionsForPatient(it) }
.map(::SummaryPrescribedDrugsItem)
val bloodPressureItems = patientUuids
.flatMap { bpRepository.newest100MeasurementsForPatient(it) }
.map { measurements ->
measurements.map { measurement ->
val timestamp = timestampGenerator.generate(measurement.updatedAt)
SummaryBloodPressureListItem(measurement, timestamp)
}
}
val medicalHistoryItems = patientUuids
.flatMap { medicalHistoryRepository.historyForPatient(it) }
.map { history ->
val lastSyncTimestamp = timestampGenerator.generate(history.updatedAt)
SummaryMedicalHistoryItem(history, lastSyncTimestamp)
}
// combineLatest() is important here so that the first data-set for the list
// is dispatched in one go instead of them appearing one after another on the UI.
return Observables.combineLatest(prescriptionItems, bloodPressureItems, medicalHistoryItems)
.map { (prescriptions, bp, history) ->
{ ui: Ui ->
ui.populateList(prescriptions, bp, history)
}
}
}
private fun updateMedicalHistory(events: Observable<UiEvent>): Observable<UiChange> {
val patientUuids = events
.ofType<PatientSummaryScreenCreated>()
.map { it.patientUuid }
val medicalHistories = patientUuids
.flatMap { medicalHistoryRepository.historyForPatient(it) }
val updateHistory = { medicalHistory: MedicalHistory, question: MedicalHistoryQuestion, selected: Boolean ->
when (question) {
HAS_HAD_A_HEART_ATTACK -> medicalHistory.copy(hasHadHeartAttack = selected)
HAS_HAD_A_STROKE -> medicalHistory.copy(hasHadStroke = selected)
HAS_HAD_A_KIDNEY_DISEASE -> medicalHistory.copy(hasHadKidneyDisease = selected)
IS_ON_TREATMENT_FOR_HYPERTENSION -> medicalHistory.copy(isOnTreatmentForHypertension = selected)
HAS_DIABETES -> medicalHistory.copy(hasDiabetes = selected)
NONE -> throw AssertionError("There's no none question in summary")
}
}
return events.ofType<SummaryMedicalHistoryAnswerToggled>()
.withLatestFrom(medicalHistories)
.map { (toggleEvent, medicalHistory) ->
updateHistory(medicalHistory, toggleEvent.question, toggleEvent.selected)
}
.flatMap {
medicalHistoryRepository
.update(it)
.andThen(Observable.never<UiChange>())
}
}
private fun openBloodPressureBottomSheet(events: Observable<UiEvent>): Observable<UiChange> {
val patientUuid = events
.ofType<PatientSummaryScreenCreated>()
.map { it.patientUuid }
val autoShows = events
.ofType<PatientSummaryScreenCreated>()
.filter { it.caller == NEW_PATIENT }
.withLatestFrom(patientUuid)
.map { (_, patientUuid) -> { ui: Ui -> ui.showBloodPressureEntrySheetIfNotShownAlready(patientUuid) } }
val newBpClicks = events
.ofType<PatientSummaryNewBpClicked>()
.withLatestFrom(patientUuid)
.map { (_, patientUuid) -> { ui: Ui -> ui.showBloodPressureEntrySheet(patientUuid) } }
return autoShows.mergeWith(newBpClicks)
}
private fun openPrescribedDrugsScreen(events: Observable<UiEvent>): Observable<UiChange> {
val patientUuid = events
.ofType<PatientSummaryScreenCreated>()
.map { it.patientUuid }
return events
.ofType<PatientSummaryUpdateDrugsClicked>()
.withLatestFrom(patientUuid)
.map { (_, patientUuid) -> { ui: Ui -> ui.showUpdatePrescribedDrugsScreen(patientUuid) } }
}
private fun handleBackAndDoneClicks(events: Observable<UiEvent>): Observable<UiChange> {
val callers = events
.ofType<PatientSummaryScreenCreated>()
.map { it.caller }
val patientUuids = events
.ofType<PatientSummaryScreenCreated>()
.map { it.patientUuid }
val bloodPressureSaves = events
.ofType<PatientSummaryBloodPressureClosed>()
.startWith(PatientSummaryBloodPressureClosed(false))
.map { it.wasBloodPressureSaved }
val bloodPressureSaveRestores = events
.ofType<PatientSummaryRestoredWithBPSaved>()
.map { it.wasBloodPressureSaved }
val mergedBpSaves = Observable.merge(bloodPressureSaves, bloodPressureSaveRestores)
val backClicks = events
.ofType<PatientSummaryBackClicked>()
val doneClicks = events
.ofType<PatientSummaryDoneClicked>()
val doneOrBackClicksWithBpSaved = Observable.merge(doneClicks, backClicks)
.withLatestFrom(mergedBpSaves, patientUuids)
.filter { (_, saved, _) -> saved }
.map { (_, _, uuid) -> { ui: Ui -> ui.showScheduleAppointmentSheet(patientUuid = uuid) } }
val backClicksWithBpNotSaved = backClicks
.withLatestFrom(mergedBpSaves, callers)
.filter { (_, saved, _) -> saved.not() }
.map { (_, _, caller) ->
{ ui: Ui ->
when (caller!!) {
SEARCH -> ui.goBackToPatientSearch()
NEW_PATIENT -> ui.goBackToHome()
}.exhaustive()
}
}
val doneClicksWithBpNotSaved = doneClicks
.withLatestFrom(mergedBpSaves)
.filter { (_, saved) -> saved.not() }
.map { { ui: Ui -> ui.goBackToHome() } }
return Observable.mergeArray(
doneOrBackClicksWithBpSaved,
backClicksWithBpNotSaved,
doneClicksWithBpNotSaved)
}
private fun exitScreenAfterSchedulingAppointment(events: Observable<UiEvent>): Observable<UiChange> {
val callers = events
.ofType<PatientSummaryScreenCreated>()
.map { it.caller }
val scheduleAppointmentCloses = events
.ofType<ScheduleAppointmentSheetClosed>()
val backClicks = events
.ofType<PatientSummaryBackClicked>()
val doneClicks = events
.ofType<PatientSummaryDoneClicked>()
val afterBackClicks = scheduleAppointmentCloses
.withLatestFrom(backClicks, callers)
.map { (_, _, caller) ->
{ ui: Ui ->
when (caller!!) {
SEARCH -> ui.goBackToPatientSearch()
NEW_PATIENT -> ui.goBackToHome()
}.exhaustive()
}
}
val afterDoneClicks = scheduleAppointmentCloses
.withLatestFrom(doneClicks)
.map { { ui: Ui -> ui.goBackToHome() } }
return afterBackClicks.mergeWith(afterDoneClicks)
}
}
| 0 | Kotlin | 0 | 1 | fa311d989cac0a167070f2e1e466191919b659b8 | 10,538 | citest | MIT License |
app/src/main/java/com/example/apisample/ui/AnimeListAdapter.kt | bitua79 | 482,442,412 | false | {"Kotlin": 16014} | package com.example.apisample.ui
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.apisample.data.entity.AnimeEntity
import com.example.apisample.databinding.ItemAnimeBinding
class AnimeListAdapter(
) : ListAdapter<AnimeEntity, AnimeListAdapter.CryptocurrencyViewHolder>(
object : DiffUtil.ItemCallback<AnimeEntity>() {
// Id should be unique
override fun areItemsTheSame(
oldItem: AnimeEntity,
newItem: AnimeEntity
): Boolean {
// TODO : replace with id
return oldItem.name == newItem.name
}
override fun areContentsTheSame(
oldItem: AnimeEntity,
newItem: AnimeEntity
): Boolean {
return oldItem.hashCode() == newItem.hashCode()
}
}
) {
// view holder class
inner class CryptocurrencyViewHolder(private val binding: ItemAnimeBinding) :
RecyclerView.ViewHolder(binding.root) {
//bind data and handle rate color
fun bind(animeEntity: AnimeEntity) {
with(binding) {
anime = animeEntity
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CryptocurrencyViewHolder {
val binding = ItemAnimeBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return CryptocurrencyViewHolder(binding)
}
override fun onBindViewHolder(holder: CryptocurrencyViewHolder, position: Int) {
holder.bind(currentList[position])
}
override fun getItemCount(): Int {
return currentList.size
}
public override fun getItem(position: Int): AnimeEntity {
return currentList[position]
}
} | 0 | Kotlin | 0 | 0 | 693efe34bcb25efb4adfdbf7542c41bae7f0c9db | 1,924 | simple-api-mvvm-app | MIT License |
src/main/kotlin/maliwan/mcbl/weapons/gun/behaviour/rifle/Shredifier.kt | HannahSchellekens | 868,217,631 | false | {"Kotlin": 634570} | package maliwan.mcbl.weapons.gun.behaviour.rifle
import maliwan.mcbl.weapons.gun.*
import maliwan.mcbl.weapons.gun.behaviour.PostGenerationBehaviour
import maliwan.mcbl.weapons.gun.behaviour.UniqueGun
import maliwan.mcbl.weapons.gun.parts.AssaultRifleParts
/**
* @author <NAME> */
open class Shredifier : UniqueGun, PostGenerationBehaviour {
override val baseName = "Shredifier"
override val redText = "Speed Kills."
override fun onFinishGeneration(properties: GunProperties, assembly: WeaponAssembly) {
AssaultRifleParts.Barrel.VLADOF_MINIGUN.applyStatModifiers(properties)
statModifiers.applyAll(properties)
}
companion object {
val statModifiers = statModifierList {
multiply(1.03, StatModifier.Property.BASE_DAMAGE)
add(0.05, StatModifier.Property.ACCURACY)
multiply(1.2, StatModifier.Property.FIRE_RATE)
multiply(1.45, StatModifier.Property.MAGAZINE_SIZE)
}
}
} | 0 | Kotlin | 0 | 1 | 98b5fd966705a3087a98f0aede0c0551cca9687b | 977 | MCBorderlands | MIT License |
app/src/main/java/com/app/khajaghar/data/model/MenuItemModel.kt | samundrak | 359,170,668 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 3, "XML": 135, "Kotlin": 82, "JSON": 5} | package com.app.khajaghar.data.model
import com.google.gson.annotations.SerializedName
data class MenuItemModel(
@SerializedName("category")
val category: String,
@SerializedName("_id")
val id: String,
@SerializedName("isAvailable")
val isAvailable: Int,
@SerializedName("isVeg")
val isVeg: Int,
@SerializedName("name")
val name: String,
@SerializedName("images")
val images: ArrayList<String>,
@SerializedName("photoUrl")
val photoUrl: String,
@SerializedName("price")
val price: Int,
@SerializedName("shopModel")
val shopModel: ShopModel?,
var quantity: Int = 0,
var shopId: Int?,
var shopName: String?,
var isDish: Boolean = true
)
| 1 | null | 1 | 1 | 53e048764c3ed1dcd01e4687e235abf043cb3b5b | 813 | khajaGhar-android | MIT License |
app/src/main/java/com/yangbw/libtest/module/userInfo/NewPhoneActivity.kt | shanshzh | 297,868,193 | true | {"Kotlin": 278774, "FreeMarker": 21922, "Java": 1744} | package com.yangbw.libtest.module.userInfo
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.library.common.base.BaseActivity
import com.yangbw.libtest.R
import com.yangbw.libtest.databinding.ActivityNewPhoneBinding
import kotlinx.android.synthetic.main.activity_new_phone.*
/**
* 验证新手机号
*
* @author :yangbw
* @date :2020/9/22
*/
class NewPhoneActivity : BaseActivity<NewPhoneViewModel, ActivityNewPhoneBinding>() {
companion object {
fun launch(context: Context) {
context.startActivity(Intent().apply {
setClass(context, NewPhoneActivity::class.java)
})
}
}
override fun getLayoutId() = R.layout.activity_new_phone
override fun getReplaceView(): View = activity_new_phone
override fun init(savedInstanceState: Bundle?) {
}
}
| 0 | null | 0 | 0 | 274a61f4c0e597ce859f6214c3e91252d006a534 | 893 | MvvmLib | Apache License 2.0 |
java/kotlin/src/main/kotlin/cosmos/distribution/v1beta1/ValidatorSlashEventsKt.kt | dimitar-petrov | 575,395,653 | false | null | //Generated by the protocol buffer compiler. DO NOT EDIT!
// source: cosmos/distribution/v1beta1/distribution.proto
package cosmos.distribution.v1beta1;
@kotlin.jvm.JvmSynthetic
inline fun validatorSlashEvents(block: cosmos.distribution.v1beta1.ValidatorSlashEventsKt.Dsl.() -> Unit): cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvents =
cosmos.distribution.v1beta1.ValidatorSlashEventsKt.Dsl._create(cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvents.newBuilder()).apply { block() }._build()
object ValidatorSlashEventsKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
class Dsl private constructor(
@kotlin.jvm.JvmField private val _builder: cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvents.Builder
) {
companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvents.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvents = _builder.build()
/**
* An uninstantiable, behaviorless type to represent the field in
* generics.
*/
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
class ValidatorSlashEventsProxy private constructor() : com.google.protobuf.kotlin.DslProxy()
/**
* <code>repeated .cosmos.distribution.v1beta1.ValidatorSlashEvent validator_slash_events = 1 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"validator_slash_events\""];</code>
*/
val validatorSlashEvents: com.google.protobuf.kotlin.DslList<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent, ValidatorSlashEventsProxy>
@kotlin.jvm.JvmSynthetic
get() = com.google.protobuf.kotlin.DslList(
_builder.getValidatorSlashEventsList()
)
/**
* <code>repeated .cosmos.distribution.v1beta1.ValidatorSlashEvent validator_slash_events = 1 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"validator_slash_events\""];</code>
* @param value The validatorSlashEvents to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addValidatorSlashEvents")
fun com.google.protobuf.kotlin.DslList<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent, ValidatorSlashEventsProxy>.add(value: cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent) {
_builder.addValidatorSlashEvents(value)
}/**
* <code>repeated .cosmos.distribution.v1beta1.ValidatorSlashEvent validator_slash_events = 1 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"validator_slash_events\""];</code>
* @param value The validatorSlashEvents to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignValidatorSlashEvents")
inline operator fun com.google.protobuf.kotlin.DslList<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent, ValidatorSlashEventsProxy>.plusAssign(value: cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent) {
add(value)
}/**
* <code>repeated .cosmos.distribution.v1beta1.ValidatorSlashEvent validator_slash_events = 1 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"validator_slash_events\""];</code>
* @param values The validatorSlashEvents to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addAllValidatorSlashEvents")
fun com.google.protobuf.kotlin.DslList<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent, ValidatorSlashEventsProxy>.addAll(values: kotlin.collections.Iterable<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent>) {
_builder.addAllValidatorSlashEvents(values)
}/**
* <code>repeated .cosmos.distribution.v1beta1.ValidatorSlashEvent validator_slash_events = 1 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"validator_slash_events\""];</code>
* @param values The validatorSlashEvents to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignAllValidatorSlashEvents")
inline operator fun com.google.protobuf.kotlin.DslList<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent, ValidatorSlashEventsProxy>.plusAssign(values: kotlin.collections.Iterable<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent>) {
addAll(values)
}/**
* <code>repeated .cosmos.distribution.v1beta1.ValidatorSlashEvent validator_slash_events = 1 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"validator_slash_events\""];</code>
* @param index The index to set the value at.
* @param value The validatorSlashEvents to set.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("setValidatorSlashEvents")
operator fun com.google.protobuf.kotlin.DslList<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent, ValidatorSlashEventsProxy>.set(index: kotlin.Int, value: cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent) {
_builder.setValidatorSlashEvents(index, value)
}/**
* <code>repeated .cosmos.distribution.v1beta1.ValidatorSlashEvent validator_slash_events = 1 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"validator_slash_events\""];</code>
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("clearValidatorSlashEvents")
fun com.google.protobuf.kotlin.DslList<cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvent, ValidatorSlashEventsProxy>.clear() {
_builder.clearValidatorSlashEvents()
}}
}
@kotlin.jvm.JvmSynthetic
inline fun cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvents.copy(block: cosmos.distribution.v1beta1.ValidatorSlashEventsKt.Dsl.() -> Unit): cosmos.distribution.v1beta1.Distribution.ValidatorSlashEvents =
cosmos.distribution.v1beta1.ValidatorSlashEventsKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| 0 | Kotlin | 0 | 0 | ddd9cd1abce2d51cf273be478c2b614960ace761 | 6,065 | terra.proto | Apache License 2.0 |
slf4j/src/main/kotlin/kr/jadekim/logger/integration/slf4j/Slf4jLogger.kt | jdekim43 | 222,454,147 | false | null | package kr.jadekim.logger.integration.slf4j
import kr.jadekim.logger.JLog
import kr.jadekim.logger.LogLevel
import org.slf4j.Logger
import org.slf4j.Marker
class Slf4jLogger(
private val name: String
) : Logger {
private val logger = JLog.get(name)
override fun getName(): String = name
override fun isTraceEnabled(): Boolean = logger.level.isPrintable(LogLevel.TRACE)
override fun isTraceEnabled(marker: Marker): Boolean = logger.level.isPrintable(LogLevel.TRACE)
override fun trace(msg: String) = logger.trace(msg)
override fun trace(format: String, arg: Any?) = logger.trace(format.format(arg))
override fun trace(format: String, arg1: Any?, arg2: Any?) = logger.trace(format.format(arg1, arg2))
override fun trace(format: String, vararg arguments: Any?) = logger.trace(format.format(*arguments))
override fun trace(msg: String, t: Throwable?) = logger.trace(msg, t)
override fun trace(marker: Marker, msg: String) = logger.trace(msg)
override fun trace(marker: Marker, format: String, arg: Any?) = logger.trace(format.format(arg))
override fun trace(marker: Marker, format: String, arg1: Any?, arg2: Any?) = logger.trace(format.format(arg1, arg2))
override fun trace(marker: Marker, format: String, vararg argArray: Any?) = logger.trace(format.format(*argArray))
override fun trace(marker: Marker, msg: String, t: Throwable?) = logger.trace(msg, t)
override fun isDebugEnabled(): Boolean = logger.level.isPrintable(LogLevel.DEBUG)
override fun isDebugEnabled(marker: Marker): Boolean = logger.level.isPrintable(LogLevel.DEBUG)
override fun debug(msg: String) = logger.debug(msg)
override fun debug(format: String, arg: Any?) = logger.debug(format.format(arg))
override fun debug(format: String, arg1: Any?, arg2: Any?) = logger.debug(format.format(arg1, arg2))
override fun debug(format: String, vararg arguments: Any?) = logger.debug(format.format(*arguments))
override fun debug(msg: String, t: Throwable?) = logger.debug(msg, t)
override fun debug(marker: Marker, msg: String) = logger.debug(msg)
override fun debug(marker: Marker, format: String, arg: Any?) = logger.debug(format.format(arg))
override fun debug(marker: Marker, format: String, arg1: Any?, arg2: Any?) = logger.debug(format.format(arg1, arg2))
override fun debug(marker: Marker, format: String, vararg argArray: Any?) = logger.debug(format.format(*argArray))
override fun debug(marker: Marker, msg: String, t: Throwable?) = logger.debug(msg, t)
override fun isInfoEnabled(): Boolean = logger.level.isPrintable(LogLevel.INFO)
override fun isInfoEnabled(marker: Marker): Boolean = logger.level.isPrintable(LogLevel.INFO)
override fun info(msg: String) = logger.info(msg)
override fun info(format: String, arg: Any?) = logger.info(format.format(arg))
override fun info(format: String, arg1: Any?, arg2: Any?) = logger.info(format.format(arg1, arg2))
override fun info(format: String, vararg arguments: Any?) = logger.info(format.format(*arguments))
override fun info(msg: String, t: Throwable?) = logger.info(msg, t)
override fun info(marker: Marker, msg: String) = logger.info(msg)
override fun info(marker: Marker, format: String, arg: Any?) = logger.info(format.format(arg))
override fun info(marker: Marker, format: String, arg1: Any?, arg2: Any?) = logger.info(format.format(arg1, arg2))
override fun info(marker: Marker, format: String, vararg argArray: Any?) = logger.info(format.format(*argArray))
override fun info(marker: Marker, msg: String, t: Throwable?) = logger.info(msg, t)
override fun isWarnEnabled(): Boolean = logger.level.isPrintable(LogLevel.WARNING)
override fun isWarnEnabled(marker: Marker): Boolean = logger.level.isPrintable(LogLevel.WARNING)
override fun warn(msg: String) = logger.warning(msg)
override fun warn(format: String, arg: Any?) = logger.warning(format.format(arg))
override fun warn(format: String, arg1: Any?, arg2: Any?) = logger.warning(format.format(arg1, arg2))
override fun warn(format: String, vararg arguments: Any?) = logger.warning(format.format(*arguments))
override fun warn(msg: String, t: Throwable?) = logger.warning(msg, t)
override fun warn(marker: Marker, msg: String) = logger.warning(msg)
override fun warn(marker: Marker, format: String, arg: Any?) = logger.warning(format.format(arg))
override fun warn(marker: Marker, format: String, arg1: Any?, arg2: Any?) {
logger.warning(format.format(arg1, arg2))
}
override fun warn(marker: Marker, format: String, vararg argArray: Any?) = logger.warning(format.format(*argArray))
override fun warn(marker: Marker, msg: String, t: Throwable?) = logger.warning(msg, t)
override fun isErrorEnabled(): Boolean = logger.level.isPrintable(LogLevel.ERROR)
override fun isErrorEnabled(marker: Marker): Boolean = logger.level.isPrintable(LogLevel.ERROR)
override fun error(msg: String) = logger.error(msg)
override fun error(format: String, arg: Any?) = logger.error(format.format(arg))
override fun error(format: String, arg1: Any?, arg2: Any?) = logger.error(format.format(arg1, arg2))
override fun error(format: String, vararg arguments: Any?) = logger.error(format.format(*arguments))
override fun error(msg: String, t: Throwable?) = logger.error(msg, t)
override fun error(marker: Marker, msg: String) = logger.error(msg)
override fun error(marker: Marker, format: String, arg: Any?) = logger.error(format.format(arg))
override fun error(marker: Marker, format: String, arg1: Any?, arg2: Any?) = logger.error(format.format(arg1, arg2))
override fun error(marker: Marker, format: String, vararg argArray: Any?) = logger.error(format.format(*argArray))
override fun error(marker: Marker, msg: String, t: Throwable?) = logger.error(msg, t)
} | 0 | Kotlin | 0 | 0 | e9ab69cc672cd95cda4a6ec8bd89a8c99129e1fa | 5,936 | j-logger | Apache License 2.0 |
model-server-api/src/commonMain/kotlin/org/modelix/model/server/api/ModelQueryBuilder.kt | modelix | 533,211,353 | false | {"Kotlin": 2516761, "JetBrains MPS": 274458, "TypeScript": 55129, "Java": 9941, "JavaScript": 6875, "Mustache": 5974, "CSS": 2898, "Shell": 2811, "Dockerfile": 389, "Procfile": 76} | /*
* Copyright (c) 2022.
*
* 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.modelix.model.server.api
fun buildModelQuery(body: ModelQueryBuilder.() -> Unit): ModelQuery {
return ModelQueryBuilder().also(body).build()
}
class ModelQueryBuilder {
private val rootQueries = ArrayList<RootQuery>()
fun build() = ModelQuery(rootQueries)
fun root(body: RootNodeBuilder.() -> Unit) {
rootQueries += RootNodeBuilder().also(body).build()
}
fun resolve(nodeId: NodeId, body: ByIdBuilder.() -> Unit = {}) {
rootQueries += ByIdBuilder(nodeId).also(body).build()
}
}
open class FilterListBuilder {
protected val filters = ArrayList<Filter>()
protected fun addFilter(filter: Filter) {
filters.add(filter)
}
fun whereProperty(role: String) = StringFilterBuilder { FilterByProperty(role, it) }
fun whereConceptName() = StringFilterBuilder { FilterByConceptLongName(it) }
fun whereConcept(conceptUID: String?) {
addFilter(FilterByConceptId(conceptUID))
}
fun and(body: FilterListBuilder.() -> Unit) {
addFilter(AndFilter(FilterListBuilder().also(body).filters))
}
fun or(body: FilterListBuilder.() -> Unit) {
addFilter(OrFilter(FilterListBuilder().also(body).filters))
}
fun not(body: FilterListBuilder.() -> Unit) {
val childFilters = FilterListBuilder().also(body).filters
addFilter(if (childFilters.size == 1) NotFilter(childFilters.first()) else NotFilter(AndFilter(childFilters)))
}
inner class StringFilterBuilder(val filterBuilder: (StringOperator) -> Filter) {
fun startsWith(prefix: String) { addFilter(filterBuilder(StartsWithOperator(prefix))) }
fun endsWith(suffix: String) { addFilter(filterBuilder(EndsWithOperator(suffix))) }
fun contains(substring: String) { addFilter(filterBuilder(ContainsOperator(substring))) }
fun equalTo(value: String) { addFilter(filterBuilder(EqualsOperator(value))) }
fun matches(pattern: Regex) { addFilter(filterBuilder(MatchesRegexOperator(pattern.pattern))) }
fun isNotNull() { addFilter(filterBuilder(IsNotNullOperator)) }
fun isNull() { addFilter(filterBuilder(IsNullOperator)) }
}
}
abstract class QueryOwnerBuilder : FilterListBuilder() {
protected val subqueries = ArrayList<Subquery>()
protected fun addSubquery(sq: Subquery) {
subqueries.add(sq)
}
fun children(role: String?, body: ChildrenBuilder.() -> Unit) {
addSubquery(ChildrenBuilder(role).also(body).build())
}
fun reference(role: String, body: ReferenceBuilder.() -> Unit) {
addSubquery(ReferenceBuilder(role).also(body).build())
}
fun references(body: ReferencesBuilder.() -> Unit) {
addSubquery(ReferencesBuilder().also(body).build())
}
fun referencesAndChildren(body: ReferencesAndChildrenBuilder.() -> Unit) {
addSubquery(ReferencesAndChildrenBuilder(false).also(body).build())
}
fun referencesAndChildrenRecursive(body: ReferencesAndChildrenBuilder.() -> Unit) {
addSubquery(ReferencesAndChildrenBuilder(true).also(body).build())
}
fun allChildren(body: AllChildrenBuilder.() -> Unit) {
addSubquery(AllChildrenBuilder().also(body).build())
}
fun descendants(body: DescendantsBuilder.() -> Unit) {
addSubquery(DescendantsBuilder().also(body).build())
}
fun ancestors(body: AncestorsBuilder.() -> Unit) {
addSubquery(AncestorsBuilder().also(body).build())
}
fun parent(body: ParentBuilder.() -> Unit) {
addSubquery(ParentBuilder().also(body).build())
}
}
sealed class RootQueryBuilder : QueryOwnerBuilder() {
abstract fun build(): RootQuery
}
sealed class SubqueryBuilder : QueryOwnerBuilder() {
abstract fun build(): Subquery
}
class RootNodeBuilder() : RootQueryBuilder() {
override fun build() = QueryRootNode(subqueries)
}
class ByIdBuilder(val id: String) : RootQueryBuilder() {
override fun build() = QueryById(id, subqueries)
}
class ChildrenBuilder(val role: String?) : SubqueryBuilder() {
override fun build() = QueryChildren(role, subqueries, filters)
}
class ReferenceBuilder(val role: String) : SubqueryBuilder() {
override fun build() = QueryReference(role, subqueries, filters)
}
class ReferencesBuilder() : SubqueryBuilder() {
override fun build() = QueryReferences(subqueries, filters)
}
class ReferencesAndChildrenBuilder(private val recursive: Boolean) : SubqueryBuilder() {
override fun build() = QueryReferencesAndChildren(recursive, subqueries, filters)
}
class AllChildrenBuilder() : SubqueryBuilder() {
override fun build() = QueryAllChildren(subqueries, filters)
}
class DescendantsBuilder() : SubqueryBuilder() {
override fun build() = QueryDescendants(subqueries, filters)
}
class AncestorsBuilder() : SubqueryBuilder() {
override fun build() = QueryAncestors(subqueries, filters)
}
class ParentBuilder() : SubqueryBuilder() {
override fun build() = QueryParent(subqueries, filters)
}
private val sandbox = buildModelQuery {
resolve("mps-module:5622e615-959d-4843-9df6-ef04ee578c18(org.modelix.model.mpsadapters)") {
children("models") {
or {
and {
whereProperty("name").isNotNull()
whereConcept(null)
}
}
descendants {
whereConcept(null)
}
}
reference("target") {
}
}
}
| 45 | Kotlin | 9 | 6 | de456ab2338ccf7c0418227e3c1a4cf16c204784 | 6,040 | modelix.core | Apache License 2.0 |
benchmark/benchmark-macro/src/androidTest/java/androidx/benchmark/macro/MacrobenchmarkTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark.macro
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
@SmallTest
class MacrobenchmarkTest {
@Test
fun macrobenchmarkWithStartupMode_emptyMetricList() {
val exception = assertFailsWith<IllegalArgumentException> {
macrobenchmarkWithStartupMode(
uniqueName = "uniqueName", // ignored, uniqueness not important
className = "className",
testName = "testName",
packageName = "com.ignored",
metrics = emptyList(), // invalid
compilationMode = CompilationMode.None,
iterations = 1,
startupMode = null,
setupBlock = {},
measureBlock = {}
)
}
assertTrue(exception.message!!.contains("Empty list of metrics"))
}
@Test
fun macrobenchmarkWithStartupMode_iterations() {
val exception = assertFailsWith<IllegalArgumentException> {
macrobenchmarkWithStartupMode(
uniqueName = "uniqueName", // ignored, uniqueness not important
className = "className",
testName = "testName",
packageName = "com.ignored",
metrics = listOf(FrameTimingMetric()),
compilationMode = CompilationMode.None,
iterations = 0, // invalid
startupMode = null,
setupBlock = {},
measureBlock = {}
)
}
assertTrue(exception.message!!.contains("Require iterations > 0"))
}
@SdkSuppress(maxSdkVersion = 28)
@Test
fun macrobenchmarkWithStartupMode_sdkVersion() {
val exception = assertFailsWith<IllegalArgumentException> {
macrobenchmarkWithStartupMode(
uniqueName = "uniqueName", // ignored, uniqueness not important
className = "className",
testName = "testName",
packageName = "com.ignored",
metrics = listOf(FrameTimingMetric()),
compilationMode = CompilationMode.None,
iterations = 1,
startupMode = null,
setupBlock = {},
measureBlock = {}
)
}
assertTrue(exception.message!!.contains("requires Android 10 (API 29) or greater"))
}
} | 6 | null | 448 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 3,230 | androidx | Apache License 2.0 |
src/main/kotlin/siosio/jsr352/jsl/JobLevelListener.kt | siosio | 81,662,843 | false | null | package siosio.jsr352.jsl
import javax.batch.api.listener.*
import kotlin.reflect.*
class JobLevelListener(override val listener: KClass<out JobListener>) : Listener<JobListener> {
override val properties: MutableList<Property> = mutableListOf()
init {
verifyNamedAnnotation(listener)
}
}
| 0 | Kotlin | 0 | 0 | cfc32eec43e9019d3cb74345fbb2e7425b7fda7a | 313 | kotlin-jsr352-jsl | MIT License |
kpref-activity/src/main/kotlin/ca/allanwang/kau/kpref/activity/items/KPrefText.kt | hardikm9850 | 139,406,928 | true | {"Kotlin": 384825, "Java": 118097, "Groovy": 5617, "HTML": 3366, "Shell": 573, "Ruby": 25} | package ca.allanwang.kau.kpref.activity.items
import android.widget.TextView
import ca.allanwang.kau.kpref.activity.GlobalOptions
import ca.allanwang.kau.kpref.activity.KClick
import ca.allanwang.kau.kpref.activity.R
import ca.allanwang.kau.utils.toast
/**
* Created by Allan Wang on 2017-06-14.
*
* Text preference
* Holds a textview to display data on the right
* This is still a generic preference
*
*/
open class KPrefText<T>(open val builder: KPrefTextContract<T>) : KPrefItemBase<T>(builder) {
/**
* Automatically reload on set
*/
override var pref: T
get() = base.getter()
set(value) {
base.setter(value)
builder.reloadSelf()
}
override fun KClick<T>.defaultOnClick() {
context.toast("No click function set")
}
override fun bindView(holder: ViewHolder, payloads: List<Any>) {
super.bindView(holder, payloads)
val textView = holder.bindInnerView<TextView>(R.layout.kau_pref_text)
withTextColor(textView::setTextColor)
textView.text = builder.textGetter(pref)
}
/**
* Extension of the base contract with an optional text getter
*/
interface KPrefTextContract<T> : BaseContract<T> {
var textGetter: (T) -> String?
}
/**
* Default implementation of [KPrefTextContract]
*/
class KPrefTextBuilder<T>(
globalOptions: GlobalOptions,
titleId: Int,
getter: () -> T,
setter: (value: T) -> Unit
) : KPrefTextContract<T>, BaseContract<T> by BaseBuilder<T>(globalOptions, titleId, getter, setter) {
override var textGetter: (T) -> String? = { it?.toString() }
}
override fun getType(): Int = R.id.kau_item_pref_text
} | 0 | Kotlin | 0 | 0 | 5c870486a1162ea18014d66fd42e8d6de3ef2069 | 1,764 | KAU | Apache License 2.0 |
kmp-calendar/src/commonMain/kotlin/io/github/ronjunevaldoz/kmp_calendar/CalendarPicker.kt | ronjunevaldoz | 762,163,741 | false | {"Kotlin": 25612} | package io.github.ronjunevaldoz.kmp_calendar
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
@Composable
fun CalendarPicker(
modifier: Modifier = Modifier,
state: CalendarState = rememberCalendarState(),
onDismiss: () -> Unit = {},
onDaySelected: (CalendarDay) -> Unit = {},
onRangeSelected: (start: CalendarDay?, end: CalendarDay?) -> Unit = {_,_->},
content: @Composable () -> Unit = {
DefaultCalendar(state, onSelectDay = {
when (state.selection) {
CalendarSelection.Single -> {
// dismiss immediately on selection
onDaySelected(it)
onDismiss()
}
CalendarSelection.Range -> {
val start = state.start
val end = state.end
onRangeSelected(start, end)
}
}
})
}
) {
Dialog(onDismissRequest = onDismiss, DialogProperties(usePlatformDefaultWidth = false)) {
Card(
modifier = modifier,
colors = CardDefaults.cardColors(
containerColor = Color.White
),
shape = RoundedCornerShape(16.dp),
) {
content()
}
}
}
@Composable
fun DefaultCalendar(
state: CalendarState,
onSelectDay: (day: CalendarDay) -> Unit
) {
Calendar(
modifier = Modifier.padding(vertical = 12.dp),
state = state,
colors = CalendarDefaults.calendarColors(),
onSelectDay = {
onSelectDay(it)
},
calendarDay = { day, onDaySelected ->
val start = state.start?.date
val end = state.end?.date
val inRange = if(start != null && end != null) {
val range = start..end
day.date in range
} else {
false
}
DefaultCalendarDayItem(
inRange = inRange,
start = state.start,
end = state.end,
colors = CalendarDefaults.calendarColors(),
hideTodayHighlight = state.hideTodayHighlight,
selectedDate = state.selected,
day = day,
onSelect = onDaySelected
)
}
)
} | 0 | Kotlin | 2 | 2 | 6266274b2e71eaba80b5c98affd79b3728997a77 | 2,702 | KMPCalendar | Apache License 2.0 |
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/LargeClass.kt | redwarp | 158,261,983 | true | {"Kotlin": 658863, "Groovy": 1433, "HTML": 698} | package io.gitlab.arturbosch.detekt.rules.complexity
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Metric
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.ThresholdRule
import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell
import io.gitlab.arturbosch.detekt.rules.asBlockExpression
import org.jetbrains.kotlin.com.intellij.psi.PsiFile
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtLoopExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtTryExpression
import org.jetbrains.kotlin.psi.KtWhenEntry
import org.jetbrains.kotlin.psi.KtWhenExpression
import java.util.ArrayDeque
/**
* This rule reports large classes. Classes should generally have one responsibility. Large classes can indicate that
* the class does instead handle multiple responsibilities. Instead of doing many things at once prefer to
* split up large classes into smaller classes. These smaller classes are then easier to understand and handle less
* things.
*
* @configuration threshold - maximum size of a class (default: 150)
*
* @active since v1.0.0
* @author <NAME>
* @author <NAME>
*/
class LargeClass(config: Config = Config.empty,
threshold: Int = DEFAULT_ACCEPTED_CLASS_LENGTH) : ThresholdRule(config, threshold) {
private var containsClassOrObject = false
override val issue = Issue("LargeClass",
Severity.Maintainability,
"One class should have one responsibility. Large classes tend to handle many things at once. " +
"Split up large classes into smaller classes that are easier to understand.")
private val locStack = ArrayDeque<Int>()
private fun incHead() {
addToHead(1)
}
private fun addToHead(amount: Int) {
if (containsClassOrObject) {
locStack.push(locStack.pop() + amount)
}
}
override fun visitFile(file: PsiFile?) { //TODO
locStack.clear()
super.visitFile(file)
}
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
containsClassOrObject = true
locStack.push(0)
classOrObject.getBody()?.let {
addToHead(it.declarations.size)
}
incHead() // for class body
super.visitClassOrObject(classOrObject)
val loc = locStack.pop()
if (loc > threshold) {
report(ThresholdedCodeSmell(issue,
Entity.from(classOrObject),
Metric("SIZE", loc, threshold),
"Class ${classOrObject.name} is too large. Consider splitting it into smaller pieces."))
}
}
/**
* Top level members must be skipped as loc stack can be empty. See #64 for more info.
*/
override fun visitProperty(property: KtProperty) {
if (property.isTopLevel) return
super.visitProperty(property)
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (function.isTopLevel) return
val body: KtBlockExpression? = function.bodyExpression.asBlockExpression()
body?.let { addToHead(body.statements.size) }
super.visitNamedFunction(function)
}
override fun visitIfExpression(expression: KtIfExpression) {
expression.then?.let { addToHead(it.children.size) }
expression.`else`?.let { addToHead(it.children.size) }
super.visitIfExpression(expression)
}
override fun visitLoopExpression(loopExpression: KtLoopExpression) {
loopExpression.body?.let { addToHead(it.children.size) }
super.visitLoopExpression(loopExpression)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
addToHead(expression.children.filter { it is KtWhenEntry }.size)
super.visitWhenExpression(expression)
}
override fun visitTryExpression(expression: KtTryExpression) {
addToHead(expression.tryBlock.statements.size)
addToHead(expression.catchClauses.size)
expression.catchClauses.map { it.catchBody?.children?.size }.forEach { addToHead(it ?: 0) }
expression.finallyBlock?.finalExpression?.statements?.size?.let { addToHead(it) }
super.visitTryExpression(expression)
}
override fun visitCallExpression(expression: KtCallExpression) {
val lambdaArguments = expression.lambdaArguments
if (lambdaArguments.size > 0) {
val lambdaArgument = lambdaArguments[0]
lambdaArgument.getLambdaExpression().bodyExpression?.let {
addToHead(it.statements.size)
}
}
super.visitCallExpression(expression)
}
}
private const val DEFAULT_ACCEPTED_CLASS_LENGTH = 70
| 3 | Kotlin | 2 | 1 | ef0416cae794782d00fbc358d12fa5f24fed9bd3 | 4,599 | detekt | Apache License 2.0 |
app/src/main/java/ru/luckycactus/steamroulette/presentation/navigation/Screens.kt | luckycactus | 196,364,852 | false | null | package ru.luckycactus.steamroulette.presentation.navigation
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabColorSchemeParams
import androidx.browser.customtabs.CustomTabsIntent
import androidx.fragment.app.Fragment
import ru.luckycactus.steamroulette.R
import ru.luckycactus.steamroulette.domain.games.entity.GameHeader
import ru.luckycactus.steamroulette.domain.games.entity.SystemRequirements
import ru.luckycactus.steamroulette.presentation.features.about.AboutFragment
import ru.luckycactus.steamroulette.presentation.features.about.AppLibrariesFragment
import ru.luckycactus.steamroulette.presentation.features.detailed_description.DetailedDescriptionFragment
import ru.luckycactus.steamroulette.presentation.features.game_details.GameDetailsFragment
import ru.luckycactus.steamroulette.presentation.features.games.LibraryFragment
import ru.luckycactus.steamroulette.presentation.features.login.LoginFragment
import ru.luckycactus.steamroulette.presentation.features.roulette.RouletteFragment
import ru.luckycactus.steamroulette.presentation.features.system_reqs.SystemReqsFragment
import ru.luckycactus.steamroulette.presentation.utils.customtabs.CustomTabsHelper
import ru.luckycactus.steamroulette.presentation.utils.extensions.getThemeColorOrThrow
import ru.luckycactus.steamroulette.presentation.utils.isAppInstalled
import ru.terrakok.cicerone.android.support.SupportAppScreen
sealed class Screens : SupportAppScreen() {
object Login : Screens() {
override fun getFragment(): Fragment = LoginFragment.newInstance()
}
object Roulette : Screens() {
override fun getFragment(): Fragment = RouletteFragment.newInstance()
}
data class GameDetails(
val game: GameHeader,
val color: Int,
val waitForImage: Boolean
) : Screens() {
override fun getFragment(): Fragment =
GameDetailsFragment.newInstance(game, color, waitForImage)
}
data class SystemReqs(
val appName: String,
val systemReqs: List<SystemRequirements>
) : Screens() {
override fun getFragment(): Fragment = SystemReqsFragment.newInstance(appName, systemReqs)
}
data class DetailedDescription(
val appName: String,
val detailedDescription: String
) : Screens() {
override fun getFragment(): Fragment =
DetailedDescriptionFragment.newInstance(appName, detailedDescription)
}
object About : Screens() {
override fun getFragment(): Fragment = AboutFragment.newInstance()
}
object UsedLibraries : Screens() {
override fun getFragment(): Fragment = AppLibrariesFragment.newInstance()
}
object Library : Screens() {
override fun getFragment(): Fragment? = LibraryFragment.newInstance()
}
object HiddenGames : Screens() {
override fun getFragment(): Fragment = LibraryFragment.newInstance(true)
}
data class ExternalBrowserFlow(
val url: String,
val trySteamApp: Boolean = false
) : Screens() {
override fun getActivityIntent(context: Context): Intent {
if (trySteamApp) {
val intent = getSteamAppIntent(context)
if (intent != null)
return intent
}
return if (CustomTabsHelper.isCustomTabsSupported(context)) {
createCustomTabsIntent(context)
} else {
createDefaultIntent()
}
}
private fun createCustomTabsIntent(context: Context): Intent {
return CustomTabsIntent.Builder().apply {
val defaultParams = CustomTabColorSchemeParams.Builder()
.setToolbarColor(context.getThemeColorOrThrow(R.attr.colorSurface))
.setSecondaryToolbarColor(context.getThemeColorOrThrow(R.attr.colorSurface))
.setNavigationBarColor(context.getThemeColorOrThrow(R.attr.colorSurface))
.build()
setDefaultColorSchemeParams(defaultParams)
setExitAnimations(
context,
R.anim.anim_fragment_pop_enter,
R.anim.anim_fragment_pop_exit
)
}.build().intent.apply {
data = Uri.parse(url)
}
}
private fun getSteamAppIntent(context: Context): Intent? {
if (isAppInstalled(context, "com.valvesoftware.android.steam.community")) {
val intent = createDefaultIntent()
with(intent) {
flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
`package` = "com.valvesoftware.android.steam.community"
}
if (intent.resolveActivity(context.packageManager) != null) {
return intent
}
}
return null
}
private fun createDefaultIntent() = Intent(Intent.ACTION_VIEW, Uri.parse(url))
}
} | 0 | Kotlin | 0 | 5 | 285530179743f1274595eebb07211cd470ef7928 | 5,133 | steam-roulette | Apache License 2.0 |
lib/kore/src/main/kotlin/dev/buijs/klutter/kore/tasks/project/ProjectBuilderActions.kt | buijs-dev | 436,644,099 | false | null | /* Copyright (c) 2021 - 2023 Buijs Software
*
* 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 dev.buijs.klutter.kore.tasks.project
import dev.buijs.klutter.kore.KlutterException
internal inline fun <reified T: ProjectBuilderAction> findProjectBuilderAction(
options: ProjectBuilderOptions
): ProjectBuilderAction {
return when(T::class.java) {
RunFlutterCreate::class.java ->
options.toRunFlutterAction()
InitKlutter::class.java ->
options.toInitKlutterAction()
DownloadFlutter::class.java ->
options.toDowloadFlutterTask()
else -> throw KlutterException("Unknown ProjectBuilderAction: ${T::class.java}")
}
}
internal sealed interface ProjectBuilderAction {
fun doAction()
}
// Used for UT only!
@Suppress("unused")
private object GroovyHelper {
@JvmStatic
fun findProjectBuilderAction(options: ProjectBuilderOptions): ProjectBuilderAction =
findProjectBuilderAction<ProjectBuilderAction>(options)
} | 4 | null | 5 | 220 | 93d360ce7e391c0b60d7a1c63f7ba949df09f44e | 2,046 | klutter | MIT License |
matugr/src/main/java/com/matugr/token_request/external/TokenGrantType.kt | judegpinto | 453,862,040 | false | {"Kotlin": 154494} | /*
* Copyright 2022 The Matugr Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.matugr.token_request.external
/**
* Domain class wraps different token requests clients are allowed to make
*/
sealed class TokenGrantType {
data class AuthorizationCode(val authorizationCode: String, val codeVerifier: String): TokenGrantType()
data class RefreshToken(val refreshToken: String): TokenGrantType()
} | 0 | Kotlin | 0 | 3 | 08859ae76fb74f83f78e99339755df022d2f0122 | 935 | matugr | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/aktivitetskrav/cronjob/PublishExpiredVarslerCronJob.kt | navikt | 554,767,872 | false | {"Kotlin": 423385, "Dockerfile": 226} | package no.nav.syfo.aktivitetskrav.cronjob
import net.logstash.logback.argument.StructuredArguments
import no.nav.syfo.aktivitetskrav.AktivitetskravVarselService
import no.nav.syfo.infrastructure.cronjob.Cronjob
import no.nav.syfo.infrastructure.cronjob.CronjobResult
import org.slf4j.LoggerFactory
class PublishExpiredVarslerCronJob(
private val aktivitetskravVarselService: AktivitetskravVarselService,
override val intervalDelayMinutes: Long
) : Cronjob {
override val initialDelayMinutes: Long = 2
override suspend fun run() {
val result = runJob()
log.info(
"Completed publishing of aktivitetskrav-expired-varsel with result: {}, {}",
StructuredArguments.keyValue("failed", result.failed),
StructuredArguments.keyValue("updated", result.updated),
)
}
suspend fun runJob(): CronjobResult {
val result = CronjobResult()
val expiredVarsler = aktivitetskravVarselService.getExpiredVarsler()
expiredVarsler.forEach { varsel ->
try {
aktivitetskravVarselService.publishExpiredVarsel(varsel)
result.updated++
} catch (e: Exception) {
log.error(
"Exception caught while attempting publishing of expired varsler",
e
)
result.failed++
}
}
return result
}
companion object {
private val log = LoggerFactory.getLogger(PublishExpiredVarslerCronJob::class.java)
}
}
| 2 | Kotlin | 1 | 0 | 79515446fe9a8e69cb303d0731f47e4ef641afa1 | 1,563 | isaktivitetskrav | MIT License |
src/ii_collections/n16FlatMap.kt | textbook | 139,580,449 | true | {"Kotlin": 61224, "Java": 4952} | package ii_collections
val Customer.orderedProducts: Set<Product> get() = orders.flatMap { it.products }.toSet()
val Shop.allOrderedProducts: Set<Product> get() = customers.flatMap { it.orders }.flatMap { it.products }.toSet()
| 0 | Kotlin | 0 | 0 | 96abd46966f30f58e5e67564759d937ad34769c5 | 229 | kotlin-koans | MIT License |
src/main/java/io/ejekta/kambrik/gui/widgets/KWidget.kt | ejektaflex | 400,948,749 | false | null | package io.ejekta.kambrik.gui.widgets
import io.ejekta.kambrik.gui.drawing.DrawingScope
import io.ejekta.kambrik.text.textLiteral
interface KWidget {
val width: Int
val height: Int
fun doDraw(dsl: DrawingScope) {
dsl {
area(width, height) {
onDraw(this)
if (drawDebug && isHovered) {
rect(0x4287f5, 0x33)
text(0, -9, textLiteral(
"${this@KWidget::class.simpleName ?: "???"} ($width x $height)"
) {
color = 0x4287f5
})
}
}
}
}
/**
* A callback that allows the widget to draw to the screen.
*/
fun onDraw(area: DrawingScope.AreaScope) {
/* No-op
return dsl {
...
}
*/
}
} | 0 | Kotlin | 0 | 0 | e500e561288d7b012be02895a8e09efe60f62855 | 874 | Posta | MIT License |
domain/src/main/java/com/test/grability/domain/repository/MarvelRepository.kt | andresbelt | 294,603,846 | false | null | package com.test.grability.domain.repository
import androidx.paging.DataSource
import com.test.grability.domain.entities.Characters
import com.test.grability.domain.vo.HttpResult
interface MarvelRepository {
suspend fun getAllCharacters(page: Int, onSuccessAction : () -> Unit,
onErrorAction: (cause : HttpResult, code : Int, errorMessage : String) -> Unit)
fun findAll() : DataSource.Factory<Int, Characters>
}
| 0 | Kotlin | 0 | 0 | 8d805d195481cb19179d272186c307e18369ea76 | 458 | MarvelExample | MIT License |
src/main/kotlin/com/piashcse/utils/AppConstants.kt | piashcse | 410,331,425 | false | null | package com.piashcse.utils
object AppConstants {
object SuccessMessage {
object Password {
const val PASSWORD_CHANGE_SUCCESS = "Password change successful"
}
object VerificationCode {
const val VERIFICATION_CODE_SENT_TO = "verification code sent to"
const val VERIFICATION_CODE_IS_NOT_VALID = "Verification code is not valid"
}
}
object DataBaseTransaction {
const val FOUND = 1
const val NOT_FOUND = 2
}
object SmtpServer {
const val HOST_NAME = "smtp.googlemail.com"
const val PORT = 465
const val DEFAULT_AUTHENTICATOR = "[email protected]"
const val DEFAULT_AUTHENTICATOR_PASSWORD = "qfzjsvdborylnaqh"
const val EMAIL_SUBJECT = "Forget Password"
}
object Image {
const val PROFILE_IMAGE_LOCATION = "src/main/resources/profile-image/"
const val PRODUCT_IMAGE_LOCATION = "src/main/resources/product-image/"
}
object ProductVariant {
const val COLOR = "COLOR"
const val SIZE = "SIZE"
}
object Page {
const val LIMIT_ITEM = 2
}
} | 0 | Kotlin | 5 | 26 | 74b152e2dc10238197a0fb99595730edd55621fd | 1,157 | ktor-E-Commerce | PostgreSQL License |
src/test/kotlin/no/nav/arbeidsgiver/sykefravarsstatistikk/api/infrastruktur/database/SykefraværStatistikkNæringskodeMedVarighetRepositoryJdbcTest.kt | navikt | 201,881,144 | false | {"Kotlin": 760611, "Shell": 1600, "Dockerfile": 213} | package no.nav.arbeidsgiver.sykefravarsstatistikk.api.infrastruktur.database
import config.AppConfigForJdbcTesterConfig
import ia.felles.definisjoner.bransjer.Bransje
import io.kotest.matchers.equality.shouldBeEqualToComparingFields
import io.kotest.matchers.equals.shouldBeEqual
import io.kotest.matchers.shouldBe
import no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.aggregertOgKvartalsvisSykefraværsstatistikk.domene.Varighetskategori
import no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.fellesdomene.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.exposed.sql.deleteAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
import java.math.BigDecimal
@ActiveProfiles("db-test")
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [AppConfigForJdbcTesterConfig::class])
@DataJdbcTest(excludeAutoConfiguration = [TestDatabaseAutoConfiguration::class])
open class SykefraværStatistikkNæringskodeMedVarighetRepositoryJdbcTest {
@Autowired
private lateinit var sykefraværStatistikkNæringskodeMedVarighetRepository: SykefraværStatistikkNæringskodeMedVarighetRepository
@Autowired
private lateinit var sykefravarStatistikkVirksomhetRepository: SykefravarStatistikkVirksomhetRepository
@BeforeEach
fun setUp() {
with(sykefravarStatistikkVirksomhetRepository) { transaction { deleteAll() } }
with(sykefraværStatistikkNæringskodeMedVarighetRepository) { transaction { deleteAll() } }
}
@Test
fun hentSykefraværForEttKvartalMedVarighet__skal_returnere_riktig_sykefravær() {
val barnehage = Underenhet.Næringsdrivende(
orgnr = Orgnr("999999999"),
overordnetEnhetOrgnr = Orgnr("1111111111"),
navn = "test Barnehage",
næringskode = Næringskode("88911"),
antallAnsatte = 10
)
sykefravarStatistikkVirksomhetRepository.settInn(
listOf(
SykefraværsstatistikkVirksomhet(
årstall = 2019,
kvartal = 2,
orgnr = barnehage.orgnr.verdi,
tapteDagsverk = BigDecimal(4),
muligeDagsverk = BigDecimal(0),
antallPersoner = 0,
varighet = Varighetskategori._1_DAG_TIL_7_DAGER.kode,
rectype = "2"
),
SykefraværsstatistikkVirksomhet(
årstall = 2019,
kvartal = 2,
orgnr = barnehage.orgnr.verdi,
varighet = Varighetskategori.TOTAL.kode,
rectype = "2",
antallPersoner = 6,
tapteDagsverk = 0.toBigDecimal(),
muligeDagsverk = 100.toBigDecimal()
)
)
)
val resultat =
sykefravarStatistikkVirksomhetRepository.hentKorttidsfravær(barnehage.orgnr)
resultat.size shouldBe 2
resultat[0] shouldBeEqual
UmaskertSykefraværForEttKvartal(
årstallOgKvartal = ÅrstallOgKvartal(2019, 2),
dagsverkTeller = BigDecimal("4.0"),
dagsverkNevner = BigDecimal("0.0"),
antallPersoner = 0,
)
resultat[1] shouldBeEqual
UmaskertSykefraværForEttKvartal(
årstallOgKvartal = ÅrstallOgKvartal(2019, 2),
dagsverkTeller = BigDecimal("0.0"),
dagsverkNevner = BigDecimal("100.0"),
antallPersoner = 6,
)
}
@Test
fun hentSykefraværForEttKvartalMedVarighet_for_næring__skal_returnere_riktig_sykefravær() {
val barnehager = Næringskode(femsifferIdentifikator = "88911")
val årstallOgKvartal = ÅrstallOgKvartal(årstall = 2019, kvartal = 2)
sykefraværStatistikkNæringskodeMedVarighetRepository.settInn(
listOf(
SykefraværsstatistikkNæringMedVarighet(
årstall = årstallOgKvartal.årstall,
kvartal = årstallOgKvartal.kvartal,
næringkode = barnehager.femsifferIdentifikator,
varighet = Varighetskategori.TOTAL.kode,
antallPersoner = 1,
tapteDagsverk = 0.toBigDecimal(),
muligeDagsverk = 10.toBigDecimal()
),
SykefraværsstatistikkNæringMedVarighet(
årstall = årstallOgKvartal.årstall,
kvartal = årstallOgKvartal.kvartal,
næringkode = barnehager.femsifferIdentifikator,
varighet = Varighetskategori._1_DAG_TIL_7_DAGER.kode,
antallPersoner = 0,
tapteDagsverk = 4.toBigDecimal(),
muligeDagsverk = 0.toBigDecimal()
)
)
)
val resultat =
sykefraværStatistikkNæringskodeMedVarighetRepository.hentKorttidsfravær(barnehager.næring)
resultat.size shouldBe 2
resultat[0] shouldBeEqualToComparingFields
UmaskertSykefraværForEttKvartal(
årstallOgKvartal = ÅrstallOgKvartal(2019, 2),
dagsverkTeller = BigDecimal("4.0"),
dagsverkNevner = BigDecimal("0.0"),
antallPersoner = 0,
)
resultat[1] shouldBeEqualToComparingFields
UmaskertSykefraværForEttKvartal(
årstallOgKvartal = ÅrstallOgKvartal(2019, 2),
dagsverkTeller = BigDecimal("0.0"),
dagsverkNevner = BigDecimal("10.0"),
antallPersoner = 1,
)
}
@Test
fun hentSykefraværForEttKvartalMedVarighet_for_bransje__skal_returnere_riktig_sykefravær() {
val sykehus = Næringskode("86101")
val legetjeneste = Næringskode("86211")
val årstallOgKvartal = ÅrstallOgKvartal(2019, 2)
sykefraværStatistikkNæringskodeMedVarighetRepository.settInn(
listOf(
SykefraværsstatistikkNæringMedVarighet(
årstall = årstallOgKvartal.årstall,
kvartal = årstallOgKvartal.kvartal,
næringkode = sykehus.femsifferIdentifikator,
varighet = Varighetskategori.TOTAL.kode,
antallPersoner = 1,
tapteDagsverk = 0.toBigDecimal(),
muligeDagsverk = 10.toBigDecimal()
),
SykefraværsstatistikkNæringMedVarighet(
årstall = årstallOgKvartal.årstall,
kvartal = årstallOgKvartal.kvartal,
næringkode = sykehus.femsifferIdentifikator,
varighet = Varighetskategori._1_DAG_TIL_7_DAGER.kode,
antallPersoner = 0,
tapteDagsverk = 4.toBigDecimal(),
muligeDagsverk = 0.toBigDecimal()
),
SykefraværsstatistikkNæringMedVarighet(
årstall = årstallOgKvartal.årstall,
kvartal = årstallOgKvartal.kvartal,
næringkode = legetjeneste.femsifferIdentifikator,
varighet = Varighetskategori.TOTAL.kode,
antallPersoner = 5,
tapteDagsverk = 0.toBigDecimal(),
muligeDagsverk = 50.toBigDecimal()
),
SykefraværsstatistikkNæringMedVarighet(
årstall = årstallOgKvartal.årstall,
kvartal = årstallOgKvartal.kvartal,
næringkode = legetjeneste.femsifferIdentifikator,
varighet = Varighetskategori._1_DAG_TIL_7_DAGER.kode,
antallPersoner = 0,
tapteDagsverk = 8.toBigDecimal(),
muligeDagsverk = 0.toBigDecimal()
),
)
)
val resultat =
sykefraværStatistikkNæringskodeMedVarighetRepository.hentKorttidsfravær(Bransje.SYKEHUS.bransjeId)
resultat.size shouldBe 2
resultat[0] shouldBeEqualToComparingFields
UmaskertSykefraværForEttKvartal(
årstallOgKvartal = ÅrstallOgKvartal(2019, 2),
dagsverkTeller = BigDecimal("4.0"),
dagsverkNevner = BigDecimal("0.0"),
antallPersoner = 0,
)
resultat[1] shouldBeEqualToComparingFields
UmaskertSykefraværForEttKvartal(
årstallOgKvartal = ÅrstallOgKvartal(2019, 2),
dagsverkTeller = BigDecimal("0.0"),
dagsverkNevner = BigDecimal("10.0"),
antallPersoner = 1,
)
}
@Test
fun `hent sykefravær med varighet for næring burde returnere sykefraværsstatistikk for alle inkluderte næringskoder`() {
val næringskode1 = Næringskode("84300")
val næringskode2 = Næringskode("84999")
// Populer databasen med statistikk for to næringskoder, som har felles næring
sykefraværStatistikkNæringskodeMedVarighetRepository.settInn(
listOf(
SykefraværsstatistikkNæringMedVarighet(
årstall = 2023,
kvartal = 1,
næringkode = næringskode1.femsifferIdentifikator,
varighet = 'E',
antallPersoner = 20,
tapteDagsverk = 100.toBigDecimal(),
muligeDagsverk = 1000.toBigDecimal()
),
SykefraværsstatistikkNæringMedVarighet(
årstall = 2023,
kvartal = 1,
næringkode = næringskode2.femsifferIdentifikator,
varighet = 'E',
antallPersoner = 20,
tapteDagsverk = 400.toBigDecimal(),
muligeDagsverk = 1000.toBigDecimal()
)
)
)
val resultat =
sykefraværStatistikkNæringskodeMedVarighetRepository.hentLangtidsfravær(næringskode1.næring)
// Resultatet skal bli statistikk for BEGGE de to næringskodene
assertThat(resultat.size).isEqualTo(2)
}
}
| 0 | Kotlin | 2 | 0 | df545731bbecd66e2854a9ebc0a0bd7002b323ca | 10,859 | sykefravarsstatistikk-api | MIT License |
Base/src/main/java/com/xy/base/assembly/common/lauch/CommonLaunchAssemblyView.kt | xiuone | 291,512,847 | false | null | package com.xy.base.assembly.common.lauch
import android.view.View
import android.widget.TextView
import com.xy.base.assembly.base.BaseAssemblyView
interface CommonLaunchAssemblyView : BaseAssemblyView {
/**
* 同意按钮
*/
fun agreeButtonView():View?
/**
* 拒绝按钮
*/
fun refuseButtonView():View?
/**
* 隐私政策所有的显示或者隐藏
*/
fun privacyContentView():View?
fun agreeLaunchPrivacy()
} | 0 | Kotlin | 1 | 2 | f0778a53355f36d09bf01104d58458232872f223 | 431 | ajinlib | Apache License 2.0 |
idea/testData/refactoring/move/kotlin/moveFile/internalReferences/after/target/some.kt | JakeWharton | 99,388,807 | false | null | package target
fun test2() = test(A()) | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 39 | kotlin | Apache License 2.0 |
shared/src/iosMain/kotlin/com/prof18/feedflow/di/KoinIOS.kt | prof18 | 600,257,020 | false | null | package com.prof18.feedflow.di
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.native.NativeSqliteDriver
import co.touchlab.kermit.Logger
import com.prof18.feedflow.data.DatabaseHelper
import com.prof18.feedflow.db.FeedFlowDB
import com.prof18.feedflow.domain.DateFormatter
import com.prof18.feedflow.domain.HtmlParser
import com.prof18.feedflow.domain.HtmlRetriever
import com.prof18.feedflow.domain.IosDateFormatter
import com.prof18.feedflow.domain.IosHtmlRetriever
import com.prof18.feedflow.domain.browser.BrowserSettingsRepository
import com.prof18.feedflow.domain.opml.OpmlFeedHandler
import com.prof18.feedflow.presentation.AddFeedViewModel
import com.prof18.feedflow.presentation.BaseViewModel
import com.prof18.feedflow.presentation.FeedSourceListViewModel
import com.prof18.feedflow.presentation.HomeViewModel
import com.prof18.feedflow.presentation.ImportExportViewModel
import com.prof18.feedflow.utils.AppEnvironment
import com.prof18.feedflow.utils.DispatcherProvider
import com.russhwolf.settings.ExperimentalSettingsImplementation
import com.russhwolf.settings.KeychainSettings
import com.russhwolf.settings.Settings
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import org.koin.core.KoinApplication
import org.koin.core.component.KoinComponent
import org.koin.core.definition.Definition
import org.koin.core.definition.KoinDefinition
import org.koin.core.module.Module
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.Qualifier
import org.koin.dsl.module
fun initKoinIos(
htmlParser: HtmlParser,
appEnvironment: AppEnvironment,
): KoinApplication = initKoin(
appEnvironment = appEnvironment,
modules = listOf(
module {
factory { htmlParser }
},
),
)
internal actual inline fun <reified T : BaseViewModel> Module.viewModel(
qualifier: Qualifier?,
noinline definition: Definition<T>,
): KoinDefinition<T> = single(qualifier, definition = definition)
@OptIn(ExperimentalSettingsImplementation::class)
internal actual val platformModule: Module = module {
single<SqlDriver> {
NativeSqliteDriver(FeedFlowDB.Schema, DatabaseHelper.DATABASE_NAME)
}
single<DispatcherProvider> {
object : DispatcherProvider {
override val main: CoroutineDispatcher = Dispatchers.Main
override val default: CoroutineDispatcher = Dispatchers.Default
override val io: CoroutineDispatcher = Dispatchers.IO
}
}
factory {
OpmlFeedHandler(
dispatcherProvider = get(),
)
}
single<Settings> {
KeychainSettings(service = "FeedFlow")
}
single<DateFormatter> {
IosDateFormatter(
logger = getWith("DateFormatter"),
)
}
factory<HtmlRetriever> {
IosHtmlRetriever(
dispatcherProvider = get(),
)
}
}
@Suppress("unused") // Called from Swift
object KotlinDependencies : KoinComponent {
fun getHomeViewModel() = getKoin().get<HomeViewModel>()
fun getFeedSourceListViewModel() = getKoin().get<FeedSourceListViewModel>()
fun getAddFeedViewModel() = getKoin().get<AddFeedViewModel>()
fun getBrowserSettingsRepository() = getKoin().get<BrowserSettingsRepository>()
fun getLogger(tag: String? = null) = getKoin().get<Logger> { parametersOf(tag) }
fun getImportExportViewModel() = getKoin().get<ImportExportViewModel>()
}
| 9 | Kotlin | 8 | 97 | e3d2ae617a067c0484d414c34fc4ae87630e3b7a | 3,499 | feed-flow | Apache License 2.0 |
app/src/main/java/com/fanrong/frwallet/ui/dialog/LoginOutDialog.kt | iamprivatewallet | 464,003,911 | false | {"JavaScript": 2822760, "Kotlin": 1140535, "Java": 953177, "HTML": 17003} | package com.fanrong.frwallet.ui.dialog
import android.content.Context
import android.view.Gravity
import com.fanrong.frwallet.R
import kotlinx.android.synthetic.main.logout_dialog.*
import xc.common.viewlib.view.customview.FullScreenDialog
class LoginOutDialog(context: Context) : FullScreenDialog(context) {
override var contentGravity: Int? = Gravity.BOTTOM
override fun getContentView(): Int {
return R.layout.logout_dialog
}
override fun initView() {
iv_close.setOnClickListener {
dismiss()
}
btn_logout.setOnClickListener {
dismiss()
onConfrim?.confirm(null)
}
}
} | 0 | JavaScript | 0 | 1 | be8003e419afbe0429f2eb3fd757866e2e4b9152 | 672 | PrivateWallet.Android | MIT License |
drivers/dynamodb/dynamodb-springboot-driver/src/main/kotlin/io/mongock/driver/dynamodb/springboot/config/DynamoDBSpringbootContext.kt | mongock | 130,605,698 | false | {"Java": 1101769, "Kotlin": 61702, "Shell": 294} | package io.mongock.driver.dynamodb.springboot.config
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient
import io.mongock.api.config.MongockConfiguration
import io.mongock.driver.api.driver.ConnectionDriver
import io.mongock.driver.dynamodb.driver.DynamoDBDriver
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.boot.context.properties.EnableConfigurationProperties
@Configuration
@ConditionalOnExpression("\${mongock.enabled:true}")
@ConditionalOnBean(MongockConfiguration::class)
@EnableConfigurationProperties(DynamoDBConfiguration::class)
open class DynamoDBSpringbootContext {
@Bean
open fun connectionDriver(
client: AmazonDynamoDBClient,
mongockConfig: MongockConfiguration,
dynamoDBConfig: DynamoDBConfiguration?
): ConnectionDriver {
val driver = DynamoDBDriver.withLockStrategy(
client,
mongockConfig.lockAcquiredForMillis,
mongockConfig.lockQuitTryingAfterMillis,
mongockConfig.lockTryFrequencyMillis
)
driver.provisionedThroughput = dynamoDBConfig?.provisionedThroughput
return driver;
}
} | 17 | Java | 63 | 451 | c58a80a21d1c536059cb3f82f3ff5e05748c9061 | 1,381 | mongock | Apache License 2.0 |
src/main/kotlin/dev/jpruitt/spellcraft/Scroll.kt | Rapdorian | 841,209,207 | false | {"Kotlin": 6339, "Dockerfile": 304} | package dev.jpruitt.spellcraft
import dev.jpruitt.spellcraft.SpellEffect
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.Level
import net.minecraft.world.InteractionHand
import net.minecraft.world.InteractionResultHolder
import net.minecraft.world.entity.player.Player
import net.minecraft.world.entity.projectile.ProjectileUtil
import net.minecraft.world.phys.EntityHitResult
import net.minecraft.world.phys.BlockHitResult
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.item.Items
import net.minecraft.core.component.DataComponents
import net.minecraft.world.level.block.Blocks
import org.slf4j.LoggerFactory
import eu.pb4.polymer.core.api.item.PolymerItem
class Scroll(effect: SpellEffect) : Item(Item.Properties().durability(effect.getCharges()).stacksTo(1)), PolymerItem {
private val effect = effect
private val logger = LoggerFactory.getLogger("spellcraft")
fun getEffect(): SpellEffect {
return effect
}
fun isInert(item: ItemStack): Boolean {
return item.getMaxDamage() - item.damageValue < getEffect().getCost()
}
override fun isFoil(item: ItemStack): Boolean {
return !isInert(item)
}
fun setMaxDamage(item: ItemStack, max: Int) {
item.set(DataComponents.MAX_DAMAGE, max)
}
fun restoreCharges(user: Player, item: ItemStack, charges: Int) {
if (user.experienceLevel < charges) {
logger.info("Player does'nt have enough XP to restore charges")
return Unit
}
val remainder = item.getMaxDamage() - item.damageValue
if (item.getMaxDamage() < remainder + charges) {
setMaxDamage(item, remainder + charges)
item.damageValue = 0
user.giveExperienceLevels(0-charges)
}else if (item.damageValue > 0){
item.damageValue -= charges
user.giveExperienceLevels(0-charges)
}
}
override fun use(world: Level, user: Player, hand: InteractionHand): InteractionResultHolder<ItemStack> {
var scroll = user.getItemInHand(hand)
if (!world.isClientSide()) {
val range = 20.0
val ray_result = ProjectileUtil.getHitResultOnViewVector(user, {e -> true}, range)
// check if we are trying to restore charges
if (ray_result is BlockHitResult) {
// check if the block is an altar
val block = world.getBlockState(ray_result.getBlockPos())
logger.info("Found a ${block.getBlock()} block")
if (block.getBlock() == Blocks.ENCHANTING_TABLE) {
logger.info("Trying to restore charges")
restoreCharges(user, scroll, 1)
}else if (!isInert(scroll)){
if (getEffect().effect_block(world, user, ray_result.getBlockPos())) {
scroll.damageValue += getEffect().getCost()
}
}
} else if (ray_result is EntityHitResult) {
if (!isInert(scroll)) {
if (getEffect().effect_entity(world, user, ray_result.entity)) {
scroll.damageValue += getEffect().getCost()
}
}
}
}
return InteractionResultHolder.success(scroll)
}
override fun getPolymerItem(itemStack: ItemStack, player: ServerPlayer?): Item {
return Items.PAPER
}
} | 0 | Kotlin | 0 | 0 | 078a612f24ab08c94d757233b165d70a52c4aed8 | 3,435 | spellcraft | Creative Commons Zero v1.0 Universal |
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonperson/jpa/PrisonerHealth.kt | ministryofjustice | 805,355,441 | false | {"Kotlin": 402602, "Dockerfile": 1365} | package uk.gov.justice.digital.hmpps.prisonperson.jpa
import jakarta.persistence.CascadeType.ALL
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.FetchType.LAZY
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.MapKey
import jakarta.persistence.OneToMany
import jakarta.persistence.Table
import org.hibernate.Hibernate
import org.hibernate.annotations.SortNatural
import uk.gov.justice.digital.hmpps.prisonperson.dto.ReferenceDataSimpleDto
import uk.gov.justice.digital.hmpps.prisonperson.dto.response.HealthDto
import uk.gov.justice.digital.hmpps.prisonperson.dto.response.ValueWithMetadata
import uk.gov.justice.digital.hmpps.prisonperson.enums.PrisonPersonField
import uk.gov.justice.digital.hmpps.prisonperson.enums.PrisonPersonField.SMOKER_OR_VAPER
import uk.gov.justice.digital.hmpps.prisonperson.enums.Source
import uk.gov.justice.digital.hmpps.prisonperson.enums.Source.DPS
import uk.gov.justice.digital.hmpps.prisonperson.mapper.toSimpleDto
import java.time.ZonedDateTime
import java.util.SortedSet
import kotlin.reflect.KMutableProperty0
@Entity
@Table(name = "health")
class PrisonerHealth(
@Id
@Column(name = "prisoner_number", updatable = false, nullable = false)
override val prisonerNumber: String,
@ManyToOne
@JoinColumn(name = "smoker_or_vaper", referencedColumnName = "id")
var smokerOrVaper: ReferenceDataCode? = null,
// Stores snapshots of each update to a prisoner's health information
@OneToMany(mappedBy = "prisonerNumber", fetch = LAZY, cascade = [ALL], orphanRemoval = true)
@SortNatural
override val fieldHistory: SortedSet<FieldHistory> = sortedSetOf(),
// Stores timestamps of when each individual field was changed
@OneToMany(mappedBy = "prisonerNumber", fetch = LAZY, cascade = [ALL], orphanRemoval = true)
@MapKey(name = "field")
override val fieldMetadata: MutableMap<PrisonPersonField, FieldMetadata> = mutableMapOf(),
) : WithFieldHistory<PrisonerHealth>() {
override fun fieldAccessors(): Map<PrisonPersonField, KMutableProperty0<*>> = mapOf(
SMOKER_OR_VAPER to ::smokerOrVaper,
)
fun toDto(): HealthDto = HealthDto(
smokerOrVaper = getRefDataValueWithMetadata(::smokerOrVaper, SMOKER_OR_VAPER),
)
override fun updateFieldHistory(
lastModifiedAt: ZonedDateTime,
lastModifiedBy: String,
) = updateFieldHistory(lastModifiedAt, null, lastModifiedAt, lastModifiedBy, DPS, allFields)
override fun publishUpdateEvent(source: Source, now: ZonedDateTime) {
// No-op for now
}
private fun getRefDataValueWithMetadata(
value: KMutableProperty0<ReferenceDataCode?>,
field: PrisonPersonField,
): ValueWithMetadata<ReferenceDataSimpleDto?>? =
fieldMetadata[field]?.let {
ValueWithMetadata(
value.get()?.toSimpleDto(),
it.lastModifiedAt,
it.lastModifiedBy,
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false
other as PrisonerHealth
if (prisonerNumber != other.prisonerNumber) return false
if (smokerOrVaper != other.smokerOrVaper) return false
return true
}
override fun hashCode(): Int {
var result = prisonerNumber.hashCode()
result = 31 * result + smokerOrVaper.hashCode()
return result
}
companion object {
val allFields = listOf(
SMOKER_OR_VAPER,
)
}
}
| 4 | Kotlin | 0 | 1 | c790d98025319a8a9af1c2f46d164e9eda2ff76a | 3,524 | hmpps-prison-person-api | MIT License |
anvil/src/gen-sdk-21/kotlin/dev/inkremental/dsl/android/widget/DatePicker.kt | inkremental | 205,363,267 | true | null | @file:Suppress("DEPRECATION", "UNCHECKED_CAST", "MemberVisibilityCanBePrivate", "unused")
package dev.inkremental.dsl.android.widget
import android.widget.DatePicker
import dev.inkremental.Inkremental
import dev.inkremental.attr
import dev.inkremental.bind
import dev.inkremental.dsl.android.CustomSdkSetter
import dev.inkremental.dsl.android.SdkSetter
import dev.inkremental.v
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.Suppress
import kotlin.Unit
fun datePicker(configure: DatePickerScope.() -> Unit = {}) =
v<DatePicker>(configure.bind(DatePickerScope))
abstract class DatePickerScope : FrameLayoutScope() {
fun calendarViewShown(arg: Boolean): Unit = attr("calendarViewShown", arg)
fun firstDayOfWeek(arg: Int): Unit = attr("firstDayOfWeek", arg)
fun maxDate(arg: Long): Unit = attr("maxDate", arg)
fun minDate(arg: Long): Unit = attr("minDate", arg)
fun spinnersShown(arg: Boolean): Unit = attr("spinnersShown", arg)
companion object : DatePickerScope() {
init {
Inkremental.registerAttributeSetter(SdkSetter)
Inkremental.registerAttributeSetter(CustomSdkSetter)
}
}
}
| 20 | Kotlin | 5 | 58 | 6e6241a0e9ac80a1edd1f0e100ad6bf0c4f8175e | 1,145 | inkremental | MIT License |
plugins/kotlin/idea/tests/testData/resolve/references/SyntheticProperty.kt | ingokegel | 72,937,917 | false | null | fun JavaClass.foo(javaClass: JavaClass) {
print(javaClass.<caret>something)
javaClass.<caret>something = 1
javaClass.<caret>something += 1
javaClass.<caret>something++
--javaClass.<caret>something
<caret>something++
(<caret>something)++
(<caret>something) = 1
(javaClass.<caret>something) = 1
}
// MULTIRESOLVE
// REF1: of JavaClass.getSomething()
// REF2: of JavaClass.setSomething(int)
// REF3: of JavaClass.getSomething()
// REF3: of JavaClass.setSomething(int)
// REF4: of JavaClass.getSomething()
// REF4: of JavaClass.setSomething(int)
// REF5: of JavaClass.getSomething()
// REF5: of JavaClass.setSomething(int)
// REF6: of JavaClass.getSomething()
// REF6: of JavaClass.setSomething(int)
// REF7: of JavaClass.getSomething()
// REF7: of JavaClass.setSomething(int)
// REF8: of JavaClass.setSomething(int)
// REF9: of JavaClass.setSomething(int)
| 191 | null | 4372 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 891 | intellij-community | Apache License 2.0 |
app/src/main/kotlin/com/fevziomurtekin/hackernewsapp/data/room/NewEntity.kt | fevziomurtekin | 177,758,353 | false | null | package com.fevziomurtekin.hackernewsapp.data.room
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.fevziomurtekin.hackernewsapp.data.domain.ItemModel
@Entity(tableName = "job")
data class JobEntity(
@PrimaryKey
val id:Int?,
val by:String?,
val descendants:Int??,
val deleted:Boolean?,
val dead:Boolean?,
val kids:MutableList<Int>?=null,
val score:Int?,
val time:Long?,
val text:String?,
val title:String?,
val type:String?,
val part:MutableList<Int>?=null,
val parent:MutableList<Int>?=null,
val poll:Int?,
val url:String?
){
companion object {
fun from(item: ItemModel)=JobEntity(
item.id,
item.by,
item.descendants,
item.deleted,
item.dead,
item.kids,
item.score,
item.time,
item.text,
item.title,
item.type,
item.part,
item.parent,
item.poll,
item.url
)
}
} | 1 | Kotlin | 4 | 19 | dc44e960d2fbe0126c52dfc99320de8406be3184 | 1,053 | hackernewsapp | MIT License |
prettyprinter/src/main/kotlin/org/mock/duck/smartlog/printer/PrettyPrinter.kt | mock-duck | 83,891,666 | false | {"Gradle": 6, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Proguard": 4, "Java": 8, "Kotlin": 13, "XML": 16} | package org.mock.duck.smartlog.printer
import android.util.Log
import com.google.gson.Gson
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import org.mock.duck.smartlog.core.*
class PrettyPrinter : Printer {
private val defaultShift: String = " "
override fun print(priority: Int, logData: Data, tag: String) {
val threadInfo: ThreadInfo = ThreadInfo()
logThreadInfo(priority, threadInfo, tag)
logInvokers(priority, threadInfo, tag)
logMessage(priority, logData, tag)
logExtras(priority, logData, tag)
}
private fun logThreadInfo(priority: Int, threadInfo: ThreadInfo, tag: String) {
log(priority, tag, "Thread: " + threadInfo.currentThreadName())
log(priority, tag, "Thread-Id: " + threadInfo.currentThreadId())
}
private fun logInvokers(priority: Int, threadInfo: ThreadInfo, tag: String) {
log(priority, tag, "Invokers: ")
threadInfo.invokers().forEach { log(priority, tag, defaultShift + it) }
}
private fun logMessage(priority: Int, logData: Data, tag: String) {
log(priority, tag, "Message: " + logData.message)
}
private fun logExtras(priority: Int, logData: Data, tag: String) {
log(priority, tag, "Extras: ")
logData.extras?.forEach {
if (it.type == Type.THROWABLE) {
log(priority, tag, Log.getStackTraceString(it.value as Throwable))
} else {
logJsonPretty(priority, it, tag)
}
}
}
private fun logJsonPretty(priority: Int, extra: LogExtras, tag: String) {
if (extra.type == Type.JSON) {
val json: String = extra.value as String
if (json.startsWith("{") && json.endsWith("}")) {
try {
val jsonAsObject: JSONObject = JSONObject(json)
log(priority, tag, jsonAsObject.toString(1))
} catch (e: JSONException) {
log(priority, tag, Log.getStackTraceString(e))
}
} else if (json.startsWith("[") && json.endsWith("]")) {
try {
val jsonArray: JSONArray = JSONArray(json)
log(priority, tag, jsonArray.toString(1))
} catch (e: JSONException) {
log(priority, tag, Log.getStackTraceString(e))
}
}
} else {
try {
val jsonAsObject: JSONObject = JSONObject(Gson().toJson(extra))
log(priority, tag, jsonAsObject.toString(1))
} catch (e: JSONException) {
log(priority, tag, Log.getStackTraceString(e))
}
}
}
private fun log(priority: Int, tag: String, message: String) {
synchronized(this) {
Log.println(priority, tag, message)
}
}
} | 0 | Kotlin | 0 | 0 | 0d9c919c66ebf4562c62f669ec03138600adbe5e | 2,905 | SmartLog | Apache License 2.0 |
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/selection/SelectionHandles.kt | virendersran01 | 343,676,031 | false | null | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.selection
import androidx.compose.runtime.Composable
import androidx.compose.runtime.emptyContent
import androidx.compose.runtime.remember
import androidx.compose.ui.AbsoluteAlignment
import androidx.compose.ui.Alignment
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.text.InternalTextApi
import androidx.compose.ui.text.style.ResolvedTextDirection
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntBounds
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.height
import androidx.compose.ui.unit.width
import androidx.compose.ui.util.annotation.VisibleForTesting
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import kotlin.math.max
import kotlin.math.roundToInt
internal val HANDLE_WIDTH = 25.dp
internal val HANDLE_HEIGHT = 25.dp
private val HANDLE_COLOR = Color(0xFF2B28F5.toInt())
/**
* @suppress
*/
@InternalTextApi
@Composable
fun SelectionHandle(
startHandlePosition: Offset?,
endHandlePosition: Offset?,
isStartHandle: Boolean,
directions: Pair<ResolvedTextDirection, ResolvedTextDirection>,
handlesCrossed: Boolean,
modifier: Modifier,
handle: (@Composable () -> Unit)?
) {
SelectionHandlePopup(
startHandlePosition = startHandlePosition,
endHandlePosition = endHandlePosition,
isStartHandle = isStartHandle,
directions = directions,
handlesCrossed = handlesCrossed
) {
if (handle == null) {
DefaultSelectionHandle(
modifier = modifier,
isStartHandle = isStartHandle,
directions = directions,
handlesCrossed = handlesCrossed
)
} else handle()
}
}
/**
* Adjust coordinates for given text offset.
*
* Currently [android.text.Layout.getLineBottom] returns y coordinates of the next
* line's top offset, which is not included in current line's hit area. To be able to
* hit current line, move up this y coordinates by 1 pixel.
*
* @suppress
*/
@InternalTextApi
fun getAdjustedCoordinates(position: Offset): Offset {
return Offset(position.x, position.y - 1f)
}
/**
* @suppress
*/
@InternalTextApi
@Composable
@VisibleForTesting
internal fun DefaultSelectionHandle(
modifier: Modifier,
isStartHandle: Boolean,
directions: Pair<ResolvedTextDirection, ResolvedTextDirection>,
handlesCrossed: Boolean
) {
val selectionHandleCache = remember { SelectionHandleCache() }
HandleDrawLayout(modifier = modifier, width = HANDLE_WIDTH, height = HANDLE_HEIGHT) {
drawPath(
selectionHandleCache.createPath(
this,
isLeft(isStartHandle, directions, handlesCrossed)
),
HANDLE_COLOR
)
}
}
/**
* Class used to cache a Path object to represent a selection handle
* based on the given handle direction
*/
private class SelectionHandleCache {
private var path: Path? = null
private var left: Boolean = false
fun createPath(density: Density, left: Boolean): Path {
return with(density) {
val current = path
if ([email protected] == left && current != null) {
// If we have already created the Path for the correct handle direction
// return it
current
} else {
[email protected] = left
// Otherwise, if this is the first time we are creating the Path
// or the current handle direction is different than the one we
// previously created, recreate the path and cache the result
(current ?: Path().also { path = it }).apply {
reset()
addRect(
Rect(
top = 0f,
bottom = 0.5f * HANDLE_HEIGHT.toPx(),
left = if (left) {
0.5f * HANDLE_WIDTH.toPx()
} else {
0f
},
right = if (left) {
HANDLE_WIDTH.toPx()
} else {
0.5f * HANDLE_WIDTH.toPx()
}
)
)
addOval(
Rect(
top = 0f,
bottom = HANDLE_HEIGHT.toPx(),
left = 0f,
right = HANDLE_WIDTH.toPx()
)
)
}
}
}
}
}
/**
* Simple container to perform drawing of selection handles. This layout takes size on the screen
* according to [width] and [height] params and performs drawing in this space as specified in
* [onCanvas]
*/
@Composable
private fun HandleDrawLayout(
modifier: Modifier,
width: Dp,
height: Dp,
onCanvas: DrawScope.() -> Unit
) {
Layout(emptyContent(), modifier.drawBehind(onCanvas)) { _, _ ->
// take width and height space of the screen and allow draw modifier to draw inside of it
layout(width.toIntPx(), height.toIntPx()) {
// this layout has no children, only draw modifier.
}
}
}
/**
* @suppress
*/
@InternalTextApi
@Composable
private fun SelectionHandlePopup(
startHandlePosition: Offset?,
endHandlePosition: Offset?,
isStartHandle: Boolean,
directions: Pair<ResolvedTextDirection, ResolvedTextDirection>,
handlesCrossed: Boolean,
content: @Composable () -> Unit
) {
val offset = (if (isStartHandle) startHandlePosition else endHandlePosition) ?: return
SimpleLayout(AllowZeroSize) {
val left = isLeft(
isStartHandle = isStartHandle,
directions = directions,
handlesCrossed = handlesCrossed
)
val alignment = if (left) AbsoluteAlignment.TopRight else AbsoluteAlignment.TopLeft
val intOffset = IntOffset(offset.x.roundToInt(), offset.y.roundToInt())
val popupPositioner = remember(alignment, intOffset) {
SelectionHandlePositionProvider(alignment, intOffset)
}
Popup(
popupPositionProvider = popupPositioner,
content = content
)
}
}
/**
* This modifier allows the content to measure at its desired size without regard for the incoming
* measurement [minimum width][Constraints.minWidth] or [minimum height][Constraints.minHeight]
* constraints.
*
* The same as "wrapContentSize" in foundation-layout, which we cannot use in this module.
*/
private object AllowZeroSize : LayoutModifier {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0))
return layout(
max(constraints.minWidth, placeable.width),
max(constraints.minHeight, placeable.height)
) {
placeable.place(0, 0)
}
}
}
/**
* This is a copy of "AlignmentOffsetPositionProvider" class in Popup, with some
* change at "resolvedOffset" value.
*
* This is for [SelectionHandlePopup] only.
*/
@VisibleForTesting
internal class SelectionHandlePositionProvider(
val alignment: Alignment,
val offset: IntOffset
) : PopupPositionProvider {
override fun calculatePosition(
parentGlobalBounds: IntBounds,
windowGlobalBounds: IntBounds,
layoutDirection: LayoutDirection,
popupContentSize: IntSize
): IntOffset {
// TODO: Decide which is the best way to round to result without reimplementing Alignment.align
var popupGlobalPosition = IntOffset(0, 0)
// Get the aligned point inside the parent
val parentAlignmentPoint = alignment.align(
IntSize.Zero,
IntSize(parentGlobalBounds.width, parentGlobalBounds.height),
layoutDirection
)
// Get the aligned point inside the child
val relativePopupPos = alignment.align(
IntSize.Zero,
IntSize(popupContentSize.width, popupContentSize.height),
layoutDirection
)
// Add the global position of the parent
popupGlobalPosition += IntOffset(parentGlobalBounds.left, parentGlobalBounds.top)
// Add the distance between the parent's top left corner and the alignment point
popupGlobalPosition += parentAlignmentPoint
// Subtract the distance between the children's top left corner and the alignment point
popupGlobalPosition -= IntOffset(relativePopupPos.x, relativePopupPos.y)
// Add the user offset
val resolvedOffset = IntOffset(offset.x, offset.y)
popupGlobalPosition += resolvedOffset
return popupGlobalPosition
}
}
/**
* Computes whether the handle's appearance should be left-pointing or right-pointing.
*/
private fun isLeft(
isStartHandle: Boolean,
directions: Pair<ResolvedTextDirection, ResolvedTextDirection>,
handlesCrossed: Boolean
): Boolean {
return if (isStartHandle) {
isHandleLtrDirection(directions.first, handlesCrossed)
} else {
!isHandleLtrDirection(directions.second, handlesCrossed)
}
}
/**
* This method is to check if the selection handles should use the natural Ltr pointing
* direction.
* If the context is Ltr and the handles are not crossed, or if the context is Rtl and the handles
* are crossed, return true.
*
* In Ltr context, the start handle should point to the left, and the end handle should point to
* the right. However, in Rtl context or when handles are crossed, the start handle should point to
* the right, and the end handle should point to left.
*/
@VisibleForTesting
internal fun isHandleLtrDirection(
direction: ResolvedTextDirection,
areHandlesCrossed: Boolean
): Boolean {
return direction == ResolvedTextDirection.Ltr && !areHandlesCrossed ||
direction == ResolvedTextDirection.Rtl && areHandlesCrossed
}
| 1 | null | 1 | 1 | fa4711838092061ca02409b998a59f12ef0b7143 | 11,588 | androidx | Apache License 2.0 |
library/src/main/java/com/panoramagl/PLSurfaceView.kt | hannesa2 | 42,790,543 | false | null | package com.panoramagl
import android.annotation.SuppressLint
import android.content.Context
import android.opengl.GLSurfaceView
@SuppressLint("ViewConstructor")
internal class PLSurfaceView(context: Context, renderer: Renderer) : GLSurfaceView(context) {
init {
setRenderer(renderer)
renderMode = RENDERMODE_WHEN_DIRTY
}
} | 11 | null | 60 | 169 | ebc1808a5758415be00fb1503e019cfebd810c2b | 349 | panoramaGL | Apache License 2.0 |
src/test/kotlin/ch/unil/pafanalysis/analysis/steps/transformation/TransformationRunnerTests.kt | UNIL-PAF | 419,229,519 | false | {"Kotlin": 443542, "R": 1119} | package ch.unil.pafanalysis.analysis.steps.transformation
import ch.unil.pafanalysis.analysis.service.ColumnMappingParser
import ch.unil.pafanalysis.analysis.steps.imputation.ImputationComputation
import ch.unil.pafanalysis.analysis.steps.imputation.ImputationParams
import ch.unil.pafanalysis.analysis.steps.imputation.ImputationType
import ch.unil.pafanalysis.analysis.steps.imputation.NormImputationParams
import ch.unil.pafanalysis.analysis.steps.log_transformation.LogTransformationComputation
import ch.unil.pafanalysis.analysis.steps.log_transformation.LogTransformationParams
import ch.unil.pafanalysis.analysis.steps.log_transformation.TransformationType
import ch.unil.pafanalysis.analysis.steps.normalization.NormalizationComputation
import ch.unil.pafanalysis.analysis.steps.normalization.NormalizationParams
import ch.unil.pafanalysis.analysis.steps.normalization.NormalizationType
import ch.unil.pafanalysis.common.*
import ch.unil.pafanalysis.results.model.ResultType
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import java.io.File
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.io.path.pathString
@SpringBootTest
class TransformationRunnerTests {
@Autowired
private val imputation: ImputationComputation? = null
@Autowired
private val normalization: NormalizationComputation? = null
@Autowired
private val transformation: LogTransformationComputation? = null
@Autowired
val colParser: ColumnMappingParser? = null
private val readTableData = ReadTableData()
private val writeTableData = WriteTableData()
private var ints: List<List<Double>>? = null
private var table: Table? = null
@BeforeEach
fun init() {
val resPath = "./src/test/resources/results/maxquant/Grepper-13695-710/"
val filePath = resPath + "proteinGroups.txt"
val commonRes = colParser!!.parse(filePath, resPath, ResultType.MaxQuant).second
table = readTableData.getTable(filePath, commonRes.headers)
ints = readTableData.getDoubleMatrix(table, "LFQ.intensity", null).second
}
@Test
fun defaultTransformationChain() {
val transParams = LogTransformationParams(transformationType = TransformationType.LOG2.value)
val res1 = transformation?.runTransformation(ints!!, transParams)
val normParams = NormalizationParams(normalizationType = NormalizationType.MEDIAN.value)
val res2 = normalization?.runNormalization(res1!!, normParams)
val imputParams = ImputationParams(imputationType = ImputationType.NORMAL.value, normImputationParams = NormImputationParams())
val res3 = imputation?.runImputation(res2!!, imputParams)
val oneRes = BigDecimal(res3!!.first[0][22]).setScale(5, RoundingMode.HALF_EVEN).toDouble()
assert(ints!![0][22] == 0.0)
assert(oneRes == -4.55469)
}
@Test
fun writeTransformationChain(){
val transParams = LogTransformationParams(transformationType = TransformationType.LOG2.value)
val res1 = transformation?.runTransformation(ints!!, transParams)
val normParams = NormalizationParams(normalizationType = NormalizationType.MEDIAN.value)
val res2 = normalization?.runNormalization(res1!!, normParams)
val imputParams = ImputationParams(imputationType = ImputationType.NORMAL.value, normImputationParams = NormImputationParams())
val res3 = imputation?.runImputation(res2!!, imputParams)?.first
val oneRes = BigDecimal(res3!![0][22]).setScale(5, RoundingMode.HALF_EVEN).toDouble()
val selHeaders = readTableData.getDoubleMatrix(table, "LFQ.intensity", null).first
val newCols: List<List<Any>>? = table?.cols?.mapIndexed{ i, c ->
val selHeader = selHeaders.withIndex().find{ it.value.idx == i }
if (selHeader != null) {
res3!![selHeader.index]
}else c
}
val tempFile = kotlin.io.path.createTempFile()
val fileName = writeTableData.write(tempFile.pathString, table!!.copy(cols = newCols))
val fileHash = Crc32HashComputations().computeFileHash(File(fileName))
assert(fileHash == (458642479).toLong())
}
}
| 0 | Kotlin | 0 | 0 | adce71c3b2d29b5ab647735747a19050cccd6cf7 | 4,354 | paf-analysis-backend | MIT License |
src/main/kotlin/extensions/Array.kt | HMCore | 356,832,463 | false | {"Java": 26193, "Kotlin": 1395} | package extensions
/**
* Map a Java array to another Java array
*/
inline fun <T, reified I> Array<T>.map(crossinline transform: (T) -> I) =
Array(size) { transform(this[it]) } | 6 | Java | 1 | 1 | febd3d63d22efe5b3cb34fe293ef318c29678f23 | 183 | Core | MIT License |
entity/src/commonMain/kotlin/tech/antibytes/keather/entity/RealtimeData.kt | bitPogo | 762,226,385 | false | {"Kotlin": 372822, "MDX": 11276, "TypeScript": 8443, "JavaScript": 8164, "Swift": 6863, "CSS": 2415, "XS": 819, "C": 194, "HTML": 184, "SCSS": 91} | /*
* Copyright (c) 2024 <NAME> (bitPogo) / All rights reserved.
*
* Use of this source code is governed by Apache v2.0
*/
package io.bitpogo.keather.entity
data class RealtimeData(
val temperatureInCelsius: TemperatureInCelsius,
val windSpeedInKilometerPerHour: WindSpeedInKpH,
val precipitationInMillimeter: PrecipitationInMillimeter,
)
| 0 | Kotlin | 0 | 0 | 7e0b2d1d800f835b0afc2bbeedb708f393668c64 | 356 | keather | Apache License 2.0 |
app/src/main/java/me/colinmarsch/dawn/receiver/AlarmReceiver.kt | colinmarsch | 203,884,903 | false | {"Kotlin": 67277} | package me.colinmarsch.dawn.receiver
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.graphics.Color
import android.os.Bundle
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat.startActivity
import me.colinmarsch.dawn.*
import me.colinmarsch.dawn.NotificationHelper.Companion.ALARM_CHANNEL_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.ALARM_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.BREATHER_CANCEL_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.Channel.ALARM
import me.colinmarsch.dawn.NotificationHelper.Companion.Channel.STREAK
import me.colinmarsch.dawn.NotificationHelper.Companion.DELAY_NOTIF_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.NOTIF_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.NO_IMPACT_NOTIF_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.SNOOZE_NOTIF_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.STAY_NOTIF_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.STREAK_CHANNEL_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.SUCCESS_STREAK_NOTIF_ID
import me.colinmarsch.dawn.NotificationHelper.Companion.TIME_NOTIF_ID
import me.colinmarsch.dawn.utils.cancelAlarm
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val prefsHelper = RealPreferencesHelper(context)
when (intent.getStringExtra("CASE")) {
"ALARM" -> {
NotificationHelper.createNotificationChannel(context, ALARM)
MediaHandler.startAlarm(context)
val alarmIntent = Intent(context, AlarmActivity::class.java)
val pendingIntent =
PendingIntent.getActivity(context, 0, alarmIntent, FLAG_UPDATE_CURRENT)
val stopIntent = Intent(context, AlarmReceiver::class.java).apply {
putExtra("CASE", "STOP")
}
val pendingStopIntent =
PendingIntent.getBroadcast(context, 0, stopIntent, FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(context, ALARM_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notif)
.setColor(Color.argb(1, 221, 182, 57))
.setContentTitle("Good Morning!")
.setContentText("Tap to stop the alarm")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setAutoCancel(true)
.setFullScreenIntent(pendingIntent, true)
.addAction(R.drawable.ic_launcher_foreground, "Stop Alarm", pendingStopIntent)
with(NotificationManagerCompat.from(context)) {
cancel(TIME_NOTIF_ID)
cancel(SNOOZE_NOTIF_ID)
notify(NOTIF_ID, builder.build())
}
}
"STAY" -> {
NotificationHelper.createNotificationChannel(context, ALARM)
val breatherTime = System.currentTimeMillis() + 30000L
val stayInIntent = Intent(context, InAppActivity::class.java).apply {
putExtra("WHEN_TIME", breatherTime)
}
val pendingIntent =
PendingIntent.getActivity(context, 0, stayInIntent, FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(context, ALARM_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notif)
.setColor(Color.argb(1, 221, 182, 57))
.setContentTitle("Get back to Dawn")
.setContentText("30 seconds left to get back to Dawn!")
.setContentIntent(pendingIntent)
.setWhen(breatherTime)
.setExtras(Bundle()) // TODO(colinmarsch) figure out a better way to solve issue of mExtras being null
.setUsesChronometer(true)
.setChronometerCountDown(true)
with(NotificationManagerCompat.from(context)) {
cancel(DELAY_NOTIF_ID)
notify(STAY_NOTIF_ID, builder.build())
}
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val breatherIntent = Intent(context, AlarmReceiver::class.java)
breatherIntent.putExtra("CASE", "BREATHER")
val alarmPendingIntent =
PendingIntent.getBroadcast(context, BREATHER_CANCEL_ID, breatherIntent, 0)
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
breatherTime + 5000L,
alarmPendingIntent
)
}
"STREAK" -> {
NotificationHelper.createNotificationChannel(context, STREAK)
val builder = NotificationCompat.Builder(context, STREAK_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notif)
.setColor(Color.argb(1, 221, 182, 57))
.setContentTitle("Congrats!")
.setContentText("Congrats! You can now use your phone!")
val currentStreak = prefsHelper.getStreak()
val c: Date = Calendar.getInstance().time
val df = SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault())
val currentDay: String = df.format(c)
val newSuccessfulDaysSet = prefsHelper.getSuccessfulDays()
val newFailedDaysSet = prefsHelper.getFailedDays()
if (!newFailedDaysSet.contains(currentDay)
&& !newSuccessfulDaysSet.contains(currentDay)
) {
with(NotificationManagerCompat.from(context)) {
notify(SUCCESS_STREAK_NOTIF_ID, builder.build())
}
prefsHelper.recordSuccessfulDay()
prefsHelper.setStreak(currentStreak + 1)
} else {
val noImpactBuilder = NotificationCompat.Builder(context, STREAK_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notif)
.setColor(Color.argb(1, 221, 182, 57))
.setContentTitle("You already used Dawn today")
.setContentText("Only the first alarm per day counts!")
with(NotificationManagerCompat.from(context)) {
notify(NO_IMPACT_NOTIF_ID, noImpactBuilder.build())
}
}
}
"BREATHER" -> {
NotificationHelper.createNotificationChannel(context, STREAK)
val builder = NotificationCompat.Builder(context, STREAK_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notif)
.setColor(Color.argb(1, 221, 182, 57))
.setContentTitle("Day missed")
.setContentText("You didn't open Dawn!")
with(NotificationManagerCompat.from(context)) {
cancel(STAY_NOTIF_ID)
notify(NotificationHelper.BROKE_STREAK_NOTIF_ID, builder.build())
}
prefsHelper.recordFailedDay()
prefsHelper.setStreak(0)
}
"STOP" -> {
NotificationHelper.createNotificationChannel(context, STREAK)
MediaHandler.stopAlarm(context)
val getUpDelayTime = prefsHelper.getGetUpDelayTime()
val whenTime = System.currentTimeMillis() + getUpDelayTime
val inAppIntent = Intent(context, InAppActivity::class.java).apply {
putExtra("WHEN_TIME", whenTime)
addFlags(FLAG_ACTIVITY_NEW_TASK)
}
val contentIntent = PendingIntent.getActivity(
context,
NotificationHelper.STAY_IN_APP_ID,
inAppIntent,
FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(context, STREAK_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notif)
.setColor(Color.argb(1, 221, 182, 57))
.setContentTitle("Countdown to get up!")
.setContentText("You can use your phone for a bit!")
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setOngoing(true)
.setContentIntent(contentIntent)
.setExtras(Bundle()) // TODO(colinmarsch) figure out a better way to solve issue of mExtras being null
.setUsesChronometer(true)
.setChronometerCountDown(true)
.setWhen(whenTime)
with(NotificationManagerCompat.from(context)) {
cancel(NOTIF_ID)
notify(DELAY_NOTIF_ID, builder.build())
}
val stayIntent = Intent(context, AlarmReceiver::class.java).apply {
putExtra("CASE", "STAY")
}
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pendingIntent = PendingIntent.getBroadcast(
context,
NotificationHelper.STAY_ALARM_ID,
stayIntent,
0
)
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
whenTime - 30000L,
pendingIntent
)
startActivity(context, inAppIntent, null)
}
"SNOOZE" -> {
NotificationHelper.createNotificationChannel(context, ALARM)
MediaHandler.stopAlarm(context)
val snoozeDuration = prefsHelper.getSnoozeDuration()
val whenTime = System.currentTimeMillis() + snoozeDuration
val alarmDismissIntent = Intent(context, AlarmReceiver::class.java).also {
it.putExtra("CASE", "DISMISS")
}
val pendingDismissIntent = PendingIntent.getBroadcast(
context,
NotificationHelper.DISMISS_ALARM_ID,
alarmDismissIntent,
0
)
val builder = NotificationCompat.Builder(context, ALARM_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notif)
.setColor(Color.argb(1, 221, 182, 57))
.setContentTitle("Alarm Snoozed")
.setContentText("Alarm snoozed for ${snoozeDuration / 60000L} minutes")
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setOngoing(true)
.setExtras(Bundle()) // TODO(colinmarsch) figure out a better way to solve issue of mExtras being null
.setUsesChronometer(true)
.setChronometerCountDown(true)
.setWhen(whenTime)
.addAction(R.drawable.ic_launcher_foreground, "Dismiss", pendingDismissIntent)
with(NotificationManagerCompat.from(context)) {
cancel(NOTIF_ID)
notify(SNOOZE_NOTIF_ID, builder.build())
}
val alarmIntent = Intent(context, AlarmReceiver::class.java)
alarmIntent.putExtra("CASE", "ALARM")
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pendingIntent = PendingIntent.getBroadcast(context, ALARM_ID, alarmIntent, 0)
alarmManager.setAlarmClock(
AlarmManager.AlarmClockInfo(whenTime, pendingIntent),
pendingIntent
)
}
"DISMISS" -> {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancelAlarm(context, ALARM_ID)
with(NotificationManagerCompat.from(context)) {
cancel(TIME_NOTIF_ID)
cancel(SNOOZE_NOTIF_ID)
}
}
}
}
} | 2 | Kotlin | 1 | 5 | 49a3b30408a2ec9107afd527f92b03ff0f99a1a5 | 12,812 | Dawn | Apache License 2.0 |
canvas/src/main/java/com/angcyo/canvas/core/component/SmartAssistant.kt | angcyo | 229,037,615 | false | null | package com.angcyo.canvas.core.component
import android.graphics.Matrix
import android.graphics.PointF
import android.graphics.RectF
import android.view.MotionEvent
import android.view.VelocityTracker
import com.angcyo.canvas.CanvasDelegate
import com.angcyo.canvas.core.ICanvasListener
import com.angcyo.canvas.core.IRenderer
import com.angcyo.canvas.items.renderer.BaseItemRenderer
import com.angcyo.canvas.utils.isLineShape
import com.angcyo.library.L
import com.angcyo.library.component.pool.acquireTempRectF
import com.angcyo.library.component.pool.release
import com.angcyo.library.ex.*
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
/**
* 智能提示助手
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2022/04/22
*/
class SmartAssistant(val canvasDelegate: CanvasDelegate) : BaseComponent(), ICanvasListener {
companion object {
/**X的智能提示*/
const val SMART_TYPE_X = 0x01
/**Y的智能提示*/
const val SMART_TYPE_Y = 0x02
/**W的智能提示*/
const val SMART_TYPE_W = 0x04
/**H的智能提示*/
const val SMART_TYPE_H = 0x08
/**R的智能提示*/
const val SMART_TYPE_R = 0x10
}
//region ---field---
/**智能提示的数据*/
var lastXAssistant: SmartAssistantData? = null
var lastYAssistant: SmartAssistantData? = null
var lastRotateAssistant: SmartAssistantData? = null
var lastWidthAssistant: SmartAssistantData? = null
var lastHeightAssistant: SmartAssistantData? = null
//---阈值
/**吸附阈值, 当距离推荐线的距离小于等于此值时, 自动吸附
* 值越小, 不容易吸附. 就会导致频繁计算推荐点.
*
* 当距离推荐值, 小于等于这个值, 就选取这个推荐值
* */
var translateAdsorbThreshold: Float = 10f * dp
/**旋转吸附角度, 当和目标角度小于这个值时, 自动吸附到目标*/
var rotateAdsorbThreshold: Float = 5f
/**改变bounds时, 吸附大距离大小*/
var boundsAdsorbThreshold: Float = 10f * dp
/**当速率<=此值时, 才激活智能吸附*/
var velocityAdsorbThreshold: Float = 100f
//---temp
val rotateMatrix = Matrix()
/**矩形左上角的点*/
val rectLTPoint = PointF()
/**矩形右下角的点*/
val rectRBPoint = PointF()
//---参考数据
/**x值所有有效的参考值*/
val xRefValueList = mutableListOf<SmartAssistantValueData>()
/**y值所有有效的参考值*/
val yRefValueList = mutableListOf<SmartAssistantValueData>()
/**旋转角度所有有效的参考值*/
val rotateRefValueList = mutableListOf<SmartAssistantValueData>()
/**每隔15°推荐一次角度*/
var rotateSmartAngle: Int = 15
var enableXSmart: Boolean = true
var enableYSmart: Boolean = true
var enableWidthSmart: Boolean = true
var enableHeightSmart: Boolean = true
var enableRotateSmart: Boolean = true
/**速率计算*/
val velocityTracker: VelocityTracker = VelocityTracker.obtain()
//endregion ---field---
init {
enable = true
canvasDelegate.addCanvasListener(this)
}
override fun onCanvasTouchEvent(canvasDelegate: CanvasDelegate, event: MotionEvent): Boolean {
if (enable) {
velocityTracker.addMovement(event)
}
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
//初始化智能提示数据
if (enable) {
initSmartAssistantData(canvasDelegate)
}
} else if (event.actionMasked == MotionEvent.ACTION_CANCEL ||
event.actionMasked == MotionEvent.ACTION_UP
) {
lastXAssistant = null
lastYAssistant = null
lastRotateAssistant = null
lastWidthAssistant = null
lastHeightAssistant = null
velocityTracker.clear()
canvasDelegate.refresh()
}
if (enable) {
velocityTracker.computeCurrentVelocity(1000)//计算1秒内的速率
//L.i(velocityTracker.xVelocity, velocityTracker.yVelocity)
}
return super.onCanvasTouchEvent(canvasDelegate, event)
}
override fun onCanvasBoxMatrixChanged(matrix: Matrix, oldValue: Matrix, isEnd: Boolean) {
super.onCanvasBoxMatrixChanged(matrix, oldValue, isEnd)
}
/**初始化智能数据*/
fun initSmartAssistantData(canvasDelegate: CanvasDelegate) {
//x的参考点
xRefValueList.clear()
if (enableXSmart) {
canvasDelegate.xAxis.eachAxisPixelList { index, axisPoint ->
if (axisPoint.isMasterRule()) {
xRefValueList.add(
SmartAssistantValueData(
axisPoint.pixel - canvasDelegate.getCanvasViewBox()
.getCoordinateSystemX()
)
)
}
}
canvasDelegate.itemsRendererList.forEach {
if (it.isVisible()) {
val bounds = it.getBounds()
xRefValueList.add(SmartAssistantValueData(bounds.left, it))
xRefValueList.add(SmartAssistantValueData(bounds.right, it))
}
}
canvasDelegate.limitRenderer.apply {
if (!_limitPathBounds.isEmpty) {
xRefValueList.add(SmartAssistantValueData(_limitPathBounds.left, this))
xRefValueList.add(SmartAssistantValueData(_limitPathBounds.right, this))
}
}
}
//y的参考点
yRefValueList.clear()
if (enableYSmart) {
canvasDelegate.yAxis.eachAxisPixelList { index, axisPoint ->
if (axisPoint.isMasterRule()) {
yRefValueList.add(
SmartAssistantValueData(
axisPoint.pixel - canvasDelegate.getCanvasViewBox()
.getCoordinateSystemY()
)
)
}
}
canvasDelegate.itemsRendererList.forEach {
if (it.isVisible()) {
val bounds = it.getBounds()
yRefValueList.add(SmartAssistantValueData(bounds.top, it))
yRefValueList.add(SmartAssistantValueData(bounds.bottom, it))
}
}
canvasDelegate.limitRenderer.apply {
if (!_limitPathBounds.isEmpty) {
yRefValueList.add(SmartAssistantValueData(_limitPathBounds.top, this))
yRefValueList.add(SmartAssistantValueData(_limitPathBounds.bottom, this))
}
}
}
//旋转的参考点
rotateRefValueList.clear()
if (enableRotateSmart) {
for (i in 0 until 360 step rotateSmartAngle) {
rotateRefValueList.add(SmartAssistantValueData(i.toFloat(), null))
}
canvasDelegate.itemsRendererList.forEach {
if (it.isVisible()) {
val rotate = it.rotate
rotateRefValueList.add(SmartAssistantValueData(rotate, it))
}
}
}
}
//region ---smart---
/**智能推荐算法平移
* @return true 表示消耗了此次手势操作, x, y*/
fun smartTranslateItemBy(
itemRenderer: BaseItemRenderer<*>,
distanceX: Float = 0f,
distanceY: Float = 0f
): BooleanArray {
if (!enable || (distanceX == 0f && distanceY == 0f)) {
canvasDelegate.translateItemBy(itemRenderer, distanceX, distanceY)
return booleanArrayOf(true, true)
}
L.i("智能平移请求: dx:${distanceX} dy:${distanceY}")
val rotateBounds = itemRenderer.getRotateBounds()
var dx = distanceX
var dy = distanceY
val left = rotateBounds.left
val top = rotateBounds.top
val right = rotateBounds.right
val bottom = rotateBounds.bottom
//吸附判断
var adsorbDx: Float? = null
var adsorbDy: Float? = null
//震动反馈
var feedback = false
//x吸附
lastXAssistant?.let {
if (dx.absoluteValue <= translateAdsorbThreshold) {
//需要吸附
adsorbDx = 0f
L.d("智能提示吸附X:${it.smartValue.refValue}")
} else {
lastXAssistant = null
}
}
//y吸附
lastYAssistant?.let {
if (dy.absoluteValue <= translateAdsorbThreshold) {
//需要吸附
adsorbDy = 0f
L.d("智能提示吸附Y:${it.smartValue.refValue}")
} else {
lastYAssistant = null
}
}
if (adsorbDx == null &&
itemRenderer.isSupportSmartAssistant(SMART_TYPE_X) &&
velocityTracker.xVelocity.absoluteValue <= velocityAdsorbThreshold
) {
//x未吸附
val xRef = findSmartXValue(itemRenderer, left, right, dx)?.apply {
dx = smartValue.refValue - fromValue
}
if (xRef != null) {
//找到的推荐点
L.i("找到推荐点:fromX:->${xRef.fromValue} ->${xRef.smartValue.refValue}")
lastXAssistant = xRef
feedback = true
}
}
if (adsorbDy == null &&
itemRenderer.isSupportSmartAssistant(SMART_TYPE_Y) &&
velocityTracker.yVelocity.absoluteValue <= velocityAdsorbThreshold
) {
//y未吸附
val yRef = findSmartYValue(itemRenderer, top, bottom, dy)?.apply {
dy = smartValue.refValue - fromValue
}
if (yRef != null) {
//找到的推荐点
L.i("找到推荐点:fromY:->${yRef.fromValue} ->${yRef.smartValue.refValue}")
lastYAssistant = yRef
feedback = true
}
}
dx = adsorbDx ?: dx
dy = adsorbDy ?: dy
if (feedback) {
//震动反馈
canvasDelegate.longFeedback()
L.i("智能提示: dx:${distanceX} dy:${distanceY} -> ndx:${dx} ndy:${dy}")
}
canvasDelegate.translateItemBy(itemRenderer, dx, dy)
return booleanArrayOf(dx != 0f, dy != 0f)
}
/**智能旋转算法
* @return true 表示消耗了此次手势操作*/
fun smartRotateBy(
itemRenderer: BaseItemRenderer<*>,
angle: Float,
rotateFlag: Int
): Boolean {
if (!enable) {
canvasDelegate.rotateItemBy(itemRenderer, angle, rotateFlag)
return true
}
val rotate = itemRenderer.rotate
L.i("智能旋转请求: from:$rotate dr:${angle}")
var result = angle
//吸附判断
var adsorbAngle: Float? = null
//震动反馈
var feedback = false
lastRotateAssistant?.let {
if (angle.absoluteValue <= rotateAdsorbThreshold) {
//需要吸附
adsorbAngle = 0f
L.d("智能提示吸附Rotate:${it.smartValue.refValue}")
} else {
lastRotateAssistant = null
}
}
if (adsorbAngle == null &&
itemRenderer.isSupportSmartAssistant(SMART_TYPE_R) &&
velocityTracker.xVelocity.absoluteValue <= velocityAdsorbThreshold &&
velocityTracker.yVelocity.absoluteValue <= velocityAdsorbThreshold
) {
//未吸附, 查找推荐点
val rotateRef = findSmartRotateValue(itemRenderer, rotate, angle)?.apply {
result = smartValue.refValue - fromValue
}
if (rotateRef != null) {
//找到的推荐点
L.i("找到推荐点:fromRotate:->${rotate} ->${rotateRef.smartValue.refValue}")
lastRotateAssistant = rotateRef
feedback = true
}
}
result = adsorbAngle ?: result
if (feedback) {
//找到了 震动反馈
canvasDelegate.longFeedback()
L.w("智能提示: angle:${angle} -> $result")
}
canvasDelegate.rotateItemBy(itemRenderer, result, rotateFlag)
return result != 0f
}
/**智能算法改变矩形的宽高
* [anchor] 旋转后的锚点*/
fun smartChangeBounds(
itemRenderer: BaseItemRenderer<*>,
equalRatio: Boolean, //等比缩放
width: Float,
height: Float,
dx: Float,
dy: Float,
anchor: PointF
): BooleanArray {
if (!enable || itemRenderer.rotate != 0f /*旋转之后不支持*/) {
canvasDelegate.changeItemBounds(
itemRenderer,
width,
height,
anchor
)
return booleanArrayOf(true, true)
}
val rotate = itemRenderer.rotate
val rotateBounds = itemRenderer.getBounds()
val originWidth = rotateBounds.width()
val originHeight = rotateBounds.height()
val dw = width - originWidth
val dh = height - originHeight
L.i("智能宽高请求: dx:$dx dy:$dy dw:$dw dh:$dh")
var newWidth = width
var newHeight = height
//吸附判断
var adsorbWidth: Float? = null
var adsorbHeight: Float? = null
//震动反馈
var feedback = false
//去掉宽度智能
//!itemRenderer.isLineShape() && equalRatio && dy.absoluteValue > dx.absoluteValue
var notSmartWidth = false
//去掉高度智能
//!itemRenderer.isLineShape() && equalRatio && dx.absoluteValue > dy.absoluteValue
var notSmartHeight = false //equalRatio //2022-9-2 暂且只支持宽度智能提示
/*if (originWidth > originHeight) {
//宽图, 只使用宽度智能
notSmartHeight = true
} else {
//长图, 只使用高度智能
notSmartWidth = true
}*/
//w吸附
lastWidthAssistant?.let {
if (dw.absoluteValue <= boundsAdsorbThreshold) {
//需要吸附
adsorbWidth = it.smartValue.refValue
L.d("智能提示吸附W:${adsorbWidth}")
} else {
lastWidthAssistant = null
}
}
//h吸附
lastHeightAssistant?.let {
if (dh.absoluteValue <= boundsAdsorbThreshold) {
//需要吸附
adsorbHeight = it.smartValue.refValue
L.d("智能提示吸附H:${adsorbHeight}")
} else {
lastHeightAssistant = null
}
}
if (notSmartWidth) {
//no op
} else if (adsorbWidth == null &&
itemRenderer.isSupportSmartAssistant(SMART_TYPE_W) &&
velocityTracker.xVelocity.absoluteValue <= velocityAdsorbThreshold
) {
//x未吸附
val wRef = findSmartWidthValue(itemRenderer, width, dx)?.apply {
newWidth = smartValue.refValue
}
if (wRef != null) {
//找到的推荐点
L.i("找到推荐宽度:from:${originWidth} ->${newWidth}")
lastWidthAssistant = wRef
feedback = true
}
}
if (notSmartHeight) {
//no op
} else if (adsorbHeight == null &&
itemRenderer.isSupportSmartAssistant(SMART_TYPE_H) &&
velocityTracker.yVelocity.absoluteValue <= velocityAdsorbThreshold
) {
//y未吸附
val hRef = findSmartHeightValue(itemRenderer, height, dy)?.apply {
newHeight = smartValue.refValue
}
if (hRef != null) {
//找到的推荐点
L.i("找到推荐高度:from:${originHeight} ->${newHeight}")
lastHeightAssistant = hRef
feedback = true
}
}
newWidth = adsorbWidth ?: newWidth
newHeight = adsorbHeight ?: newHeight
if (itemRenderer.isLineShape()) {
//line
} else if (equalRatio) {
//等比调整
//原先的缩放比
val originScale = originWidth / originHeight
val newScale = newWidth / newHeight
if ((newScale - originScale).absoluteValue <= 0.00001) {
//已经是等比
} else {
//无推荐
val isNoAssistant = lastWidthAssistant == null && lastHeightAssistant == null
//都有推荐
val isAllAssistant = lastWidthAssistant == null && lastHeightAssistant == null
var widthPriority = false //是否宽度优先
if (isNoAssistant || isAllAssistant) {
if ((newWidth - originWidth).absoluteValue > (newHeight - originHeight).absoluteValue) {
//宽度变化比高度大
widthPriority = true
}
} else if (lastWidthAssistant != null) {
//宽度有推荐
widthPriority = true
}
if (widthPriority) {
//优先使用宽度计算出高度
newHeight = originHeight * newWidth / originWidth
lastHeightAssistant?.apply {
smartValue.refValue = newHeight
drawRect = null
}
} else {
//优先使用高度计算出宽度
newWidth = originWidth * newHeight / originHeight
lastWidthAssistant?.apply {
smartValue.refValue = newWidth
drawRect = null
}
}
}
}
if (feedback) {
//震动反馈
canvasDelegate.longFeedback()
L.i("智能提示: w:${originWidth} h:${originHeight} -> nw:${newWidth} nh:${newHeight}")
}
canvasDelegate.changeItemBounds(
itemRenderer,
newWidth,
newHeight,
anchor
)
return booleanArrayOf(originWidth != newWidth, originHeight != newHeight)
}
//endregion ---smart---
//region ---find---
/**
* 查找[left] [right] 附近最优的推荐点
* [dx] 想要偏移的量
* */
fun findSmartXValue(
itemRenderer: BaseItemRenderer<*>,
left: Float,
right: Float,
dx: Float,
adsorbThreshold: Float = translateAdsorbThreshold
): SmartAssistantData? {
var result: SmartAssistantData?
if (dx > 0) {
//向右平移, 优先查找right的推荐点
result = _findSmartRefValue(
itemRenderer,
xRefValueList,
right,
dx,
adsorbThreshold
)
if (result == null && right != left) {
//如果没有找到, 则考虑找left的推荐点
result = _findSmartRefValue(
itemRenderer,
xRefValueList,
left,
dx,
adsorbThreshold
)
}
} else {
//向左平移
result = _findSmartRefValue(
itemRenderer,
xRefValueList,
left,
dx,
adsorbThreshold
)
if (result == null && right != left) {
//如果没有找到, 则考虑找left的推荐点
result = _findSmartRefValue(
itemRenderer,
xRefValueList,
right,
dx,
adsorbThreshold
)
}
}
result?.apply {
//x横向推荐点 提示框
drawRect = _getXSmartDrawRect(itemRenderer, smartValue.refValue, smartValue.refRenderer)
}
return result
}
/**
* 查找[top] [bottom] 附近最优的推荐点
* */
fun findSmartYValue(
itemRenderer: BaseItemRenderer<*>,
top: Float,
bottom: Float,
dy: Float,
adsorbThreshold: Float = translateAdsorbThreshold
): SmartAssistantData? {
var result: SmartAssistantData?
if (dy > 0) {
//向下平移, 优先查找bottom的推荐点
result = _findSmartRefValue(
itemRenderer,
yRefValueList,
bottom,
dy,
adsorbThreshold
)
if (result == null) {
//如果没有找到, 则考虑找top的推荐点
result = _findSmartRefValue(
itemRenderer,
yRefValueList,
top,
dy,
adsorbThreshold
)
}
} else {
//向上平移
result = _findSmartRefValue(
itemRenderer,
yRefValueList,
top,
dy,
adsorbThreshold
)
if (result == null) {
result = _findSmartRefValue(
itemRenderer,
yRefValueList,
bottom,
dy,
adsorbThreshold
)
}
}
result?.apply {
//y纵向推荐点 提示框
drawRect = _getYSmartDrawRect(itemRenderer, smartValue.refValue, smartValue.refRenderer)
}
return result
}
/**
* 查找[rotate]附近最优的推荐点, [forward]正向查找or负向查找
* */
fun findSmartRotateValue(
itemRenderer: BaseItemRenderer<*>,
rotate: Float,
angle: Float
): SmartAssistantData? {
val result: SmartAssistantData? = _findSmartRefValue(
itemRenderer,
rotateRefValueList,
if (rotate < 0) rotate + 360 else rotate,
angle,
rotateAdsorbThreshold
)
result?.apply {
//旋转推荐角度 提示框
val canvasViewBox = canvasDelegate.getCanvasViewBox()
val refRenderer = smartValue.refRenderer
val viewRect = canvasViewBox
.mapCoordinateSystemRect(canvasDelegate.viewBounds, acquireTempRectF())
val renderBounds = itemRenderer.getRenderBounds()
var left = viewRect.left - renderBounds.centerX()
var right = viewRect.right + canvasViewBox.getContentRight() - renderBounds.centerX()
var top = renderBounds.centerY()
var bottom = top
if (refRenderer != null) {
val refBounds = refRenderer.getRenderBounds()
left = renderBounds.centerX() - refBounds.width() / 2
right = renderBounds.centerX() + refBounds.width() / 2
}
rotateMatrix.reset()
rotateMatrix.postRotate(
smartValue.refValue,
renderBounds.centerX(),
renderBounds.centerY()
)
rotateMatrix.mapPoint(left, top).apply {
left = x
top = y
}
rotateMatrix.mapPoint(right, bottom).apply {
right = x
bottom = y
}
drawRect = RectF(
left - canvasViewBox.getCoordinateSystemX(),
top - canvasViewBox.getCoordinateSystemY(),
right - canvasViewBox.getCoordinateSystemX(),
bottom - canvasViewBox.getCoordinateSystemY()
)
viewRect.release()
}
return result
}
fun findSmartWidthValue(
itemRenderer: BaseItemRenderer<*>,
width: Float,
dx: Float
): SmartAssistantData? {
if (!enableWidthSmart) {
return null
}
var result: SmartAssistantData? = null
val bounds = itemRenderer.getBounds()
val flipBounds = acquireTempRectF()
bounds.adjustFlipRect(flipBounds)
//增加宽度, 还是减少宽度
val isAdd = width.absoluteValue >= bounds.width().absoluteValue
val dw = width - bounds.width()
val left = flipBounds.left
val right = flipBounds.right
rectLTPoint.set(bounds.left, bounds.top)
itemRenderer.mapRotatePoint(bounds.centerX(), bounds.centerY(), rectLTPoint, rectLTPoint)
rectRBPoint.set(bounds.right, bounds.bottom)
itemRenderer.mapRotatePoint(bounds.centerX(), bounds.centerY(), rectRBPoint, rectRBPoint)
//最后计算宽度时的参考值
var rectRefValue = 0f
val xSmartValue = if (rectRBPoint.x >= rectLTPoint.x) {
rectRefValue = left
if (isAdd) {
findSmartXValue(itemRenderer, right, right, dw.absoluteValue, boundsAdsorbThreshold)
} else {
findSmartXValue(
itemRenderer,
right,
right,
-dw.absoluteValue,
boundsAdsorbThreshold
)
}
} else {
rectRefValue = right
if (isAdd) {
findSmartXValue(itemRenderer, left, left, -dw.absoluteValue, boundsAdsorbThreshold)
} else {
findSmartXValue(
itemRenderer,
left,
left,
dw.absoluteValue,
boundsAdsorbThreshold
)
}
}
xSmartValue?.apply {
//通过推荐的值, 计算推荐的width
val smartWidth = smartValue.refValue - rectRefValue
result = SmartAssistantData(
width,
SmartAssistantValueData(smartWidth, smartValue.refRenderer),
drawRect
)
}
flipBounds.release()
return result
}
fun findSmartHeightValue(
itemRenderer: BaseItemRenderer<*>,
height: Float,
dy: Float
): SmartAssistantData? {
if (!enableHeightSmart) {
return null
}
var result: SmartAssistantData? = null
val bounds = itemRenderer.getBounds()
val flipBounds = acquireTempRectF()
bounds.adjustFlipRect(flipBounds)
//增加宽度, 还是减少宽度
val isAdd = height.absoluteValue >= bounds.height().absoluteValue
val dh = height - bounds.height()
val top = flipBounds.top
val bottom = flipBounds.bottom
rectLTPoint.set(bounds.left, bounds.top)
itemRenderer.mapRotatePoint(bounds.centerX(), bounds.centerY(), rectLTPoint, rectLTPoint)
rectRBPoint.set(bounds.right, bounds.bottom)
itemRenderer.mapRotatePoint(bounds.centerX(), bounds.centerY(), rectRBPoint, rectRBPoint)
//最后计算高度时的参考值
var rectRefValue = 0f
val ySmartValue = if (rectRBPoint.y >= rectLTPoint.y) {
rectRefValue = top
if (isAdd) {
findSmartYValue(
itemRenderer,
bottom,
bottom,
dh.absoluteValue,
boundsAdsorbThreshold
)
} else {
findSmartYValue(
itemRenderer,
bottom,
bottom,
-dh.absoluteValue,
boundsAdsorbThreshold
)
}
} else {
rectRefValue = bottom
if (isAdd) {
findSmartYValue(itemRenderer, top, top, -dh.absoluteValue, boundsAdsorbThreshold)
} else {
findSmartYValue(
itemRenderer,
top,
top,
dh.absoluteValue,
boundsAdsorbThreshold
)
}
}
ySmartValue?.apply {
//通过推荐的值, 计算推荐的height
val smartHeight = smartValue.refValue - rectRefValue
result = SmartAssistantData(
height,
SmartAssistantValueData(smartHeight, smartValue.refRenderer),
drawRect
)
}
return result
}
//endregion ---find---
//region ---assist---
/**查找推荐点
* [refValueList] 推荐点池子
* [originValue] 原始的点位值
* [dValue] 本次更新的差值
* [adsorbThreshold] 吸附的阈值, 值越大, 越容易吸附到推荐值
* */
fun _findSmartRefValue(
itemRenderer: BaseItemRenderer<*>,
refValueList: List<SmartAssistantValueData>,
originValue: Float,
dValue: Float,
adsorbThreshold: Float
): SmartAssistantData? {
var smartValue: SmartAssistantValueData? = null
//差值越小越好
var diffValue = adsorbThreshold
for (refValue in refValueList) {
if (refValue.refRenderer != null && refValue.refRenderer == itemRenderer) {
//自身
} else {
if (refValue.refValue == originValue && dValue.absoluteValue <= diffValue) {
//吸附值
smartValue = refValue
break
} else {
val vAbs = (refValue.refValue - (originValue + dValue)).absoluteValue
if (vAbs <= diffValue) {
diffValue = vAbs
smartValue = refValue
}
}
}
}
if (smartValue != null) {
return SmartAssistantData(originValue, smartValue)
}
return null
}
/**x横向推荐点 提示框.
* 是一根竖线
* */
fun _getXSmartDrawRect(
itemRenderer: BaseItemRenderer<*>,
refValue: Float,
refRenderer: IRenderer?
): RectF {
val canvasViewBox = canvasDelegate.getCanvasViewBox()
val top = if (refRenderer == null) {
canvasViewBox.mapCoordinateSystemPoint(0f, 0f).y
} else {
min(refRenderer.getRenderBounds().top, itemRenderer.getRenderBounds().top)
}
val bottom = if (refRenderer == null) {
canvasViewBox.mapCoordinateSystemPoint(0f, canvasViewBox.getContentBottom()).y
} else {
max(refRenderer.getRenderBounds().bottom, itemRenderer.getRenderBounds().bottom)
}
return RectF(
refValue,
top - canvasViewBox.getCoordinateSystemY(),
refValue,
bottom - canvasViewBox.getCoordinateSystemY()
)
}
/** y纵向推荐点 提示框
* 是一根竖线横线
* */
fun _getYSmartDrawRect(
itemRenderer: BaseItemRenderer<*>,
refValue: Float,
refRenderer: IRenderer?
): RectF {
val canvasViewBox = canvasDelegate.getCanvasViewBox()
val left = if (refRenderer == null) {
canvasViewBox.mapCoordinateSystemPoint(0f, 0f).x
} else {
min(refRenderer.getRenderBounds().left, itemRenderer.getRenderBounds().left)
}
val right = if (refRenderer == null) {
canvasViewBox.mapCoordinateSystemPoint(canvasViewBox.getContentRight(), 0f).x
} else {
max(refRenderer.getRenderBounds().right, itemRenderer.getRenderBounds().right)
}
return RectF(
left - canvasViewBox.getCoordinateSystemX(),
refValue,
right - canvasViewBox.getCoordinateSystemX(),
refValue
)
}
//endregion ---assist---
} | 0 | Kotlin | 4 | 3 | 23dfbb16196872844ebcd9c64064dad64a0493ca | 30,628 | UICore | MIT License |
src/main/kotlin/com/github/cpjinan/plugin/akarilevel/AkariLevel.kt | CPJiNan | 672,557,565 | false | null | package com.github.cpjinan.plugin.akaricdk
import taboolib.common.env.RuntimeDependencies
import taboolib.common.env.RuntimeDependency
import taboolib.common.platform.Plugin
import taboolib.platform.BukkitPlugin
@RuntimeDependencies(
RuntimeDependency(
value = "org.jetbrains.kotlinx:kotlinx-serialization-core:1.6.2",
test = "!kotlinx.serialization.Serializer",
relocate = ["!kotlin.", "!kotlin1922."]
),
RuntimeDependency(
value = "org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2",
relocate = ["!kotlin.", "!kotlin1922."]
),
RuntimeDependency(
value = "org.jetbrains.kotlinx:kotlinx-serialization-cbor:1.6.2",
relocate = ["!kotlin.", "!kotlin1922."]
)
)
object AkariCDK : Plugin() {
val plugin by lazy { BukkitPlugin.getInstance() }
} | 3 | null | 4 | 6 | 4421f71d49d82844bad7f007269003cb1035be82 | 829 | AkariLevel | Creative Commons Zero v1.0 Universal |
web/src/main/java/no/nav/modiapersonoversikt/rest/dialog/salesforce/SfLegacyDialogMerkController.kt | navikt | 218,512,058 | false | null | package no.nav.modiapersonoversikt.rest.dialog.salesforce
import no.nav.modiapersonoversikt.rest.dialog.apis.*
import no.nav.modiapersonoversikt.service.oppgavebehandling.OppgaveBehandlingService
import no.nav.modiapersonoversikt.service.sfhenvendelse.SfHenvendelseService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import java.util.*
class SfLegacyDialogMerkController(
private val sfHenvendelseService: SfHenvendelseService,
private val oppgaveBehandlingService: OppgaveBehandlingService,
) : DialogMerkApi {
override fun merkSomFeilsendt(request: MerkSomFeilsendtRequest): ResponseEntity<Void> {
require(request.behandlingsidListe.size == 1) {
"Man forventer en enkelt kjedeId"
}
sfHenvendelseService.merkSomFeilsendt(request.behandlingsidListe.first())
return ResponseEntity(HttpStatus.OK)
}
override fun sendTilSladding(request: SendTilSladdingRequest): ResponseEntity<Void> {
sfHenvendelseService.sendTilSladding(request.traadId, request.arsak, request.meldingId)
return ResponseEntity(HttpStatus.OK)
}
override fun hentSladdeArsaker(kjedeId: String): List<String> {
return sfHenvendelseService.hentSladdeArsaker(kjedeId)
}
override fun lukkTraad(request: LukkTraadRequest): ResponseEntity<Void> {
sfHenvendelseService.lukkTraad(request.traadId)
if (request.oppgaveId != null && !oppgaveBehandlingService.oppgaveErFerdigstilt(request.oppgaveId)) {
oppgaveBehandlingService.ferdigstillOppgaveIGsak(
request.oppgaveId,
Optional.empty(),
request.saksbehandlerValgtEnhet,
"Dialog avsluttet fra modiapersonoversikt.",
)
}
return ResponseEntity(HttpStatus.OK)
}
override fun avsluttGosysOppgave(request: AvsluttGosysOppgaveRequest): ResponseEntity<Void> {
oppgaveBehandlingService.ferdigstillOppgaveIGsak(
request.oppgaveid,
Optional.empty(),
request.saksbehandlerValgtEnhet,
request.beskrivelse,
)
return ResponseEntity(HttpStatus.OK)
}
}
| 2 | null | 1 | 3 | 975d55e476360b2d03467033f1ff620f37011bfe | 2,201 | modiapersonoversikt-api | MIT License |
app/src/main/java/com/starts/movieguide/scene/TabChildScene.kt | ZhaoSiBo | 278,286,809 | false | null | package com.starts.movieguide.scene
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bytedance.scene.ui.template.AppCompatScene
import com.starts.movieguide.R
import timber.log.Timber
class TabChildScene : AppCompatScene() {
companion object {
fun newInstance(index: Int): TabChildScene {
return TabChildScene().apply {
val bundle = Bundle()
bundle.putInt("index", index)
setArguments(bundle)
}
}
}
override fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View {
return TextView(requireSceneContext()).apply {
val index = requireArguments()["index"] as Int
background = ContextCompat.getDrawable(requireSceneContext() , R.drawable.primary_background)
gravity = Gravity.CENTER
text = "Child Scene #$index"
setTextColor(ContextCompat.getColor(requireSceneContext() , R.color.white))
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setToolbarVisible(false)
setStatusBarVisible(true)
}
override fun onResume() {
super.onResume()
Timber.d("onResume")
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
toolbar?.navigationIcon = null
}
} | 0 | Kotlin | 0 | 1 | 0b663068a9eb1df32f76f60272d2bc3579e47196 | 1,665 | MovieGuide | MIT License |
api/src/main/kotlin/io/github/wulkanowy/api/service/ServiceManager.kt | wulkanowy | 145,134,008 | false | null | package io.github.wulkanowy.api.service
import RxJava2ReauthCallAdapterFactory
import com.google.gson.GsonBuilder
import io.github.wulkanowy.api.Api
import io.github.wulkanowy.api.ApiException
import io.github.wulkanowy.api.OkHttpClientBuilderFactory
import io.github.wulkanowy.api.grades.DateDeserializer
import io.github.wulkanowy.api.grades.GradeDate
import io.github.wulkanowy.api.interceptor.ErrorInterceptor
import io.github.wulkanowy.api.interceptor.NotLoggedInErrorInterceptor
import io.github.wulkanowy.api.interceptor.StudentAndParentInterceptor
import io.github.wulkanowy.api.interceptor.UserAgentInterceptor
import io.github.wulkanowy.api.login.LoginHelper
import io.github.wulkanowy.api.login.NotLoggedInException
import io.github.wulkanowy.api.register.SendCertificateResponse
import io.reactivex.Flowable
import okhttp3.Interceptor
import okhttp3.JavaNetCookieJar
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import pl.droidsonroids.retrofit2.JspoonConverterFactory
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.create
import java.net.CookieManager
import java.net.CookiePolicy
import java.util.concurrent.TimeUnit.SECONDS
class ServiceManager(
private val okHttpClientBuilderFactory: OkHttpClientBuilderFactory,
logLevel: HttpLoggingInterceptor.Level,
private val loginType: Api.LoginType,
private val schema: String,
private val host: String,
private val symbol: String,
private val email: String,
private val password: String,
private val schoolSymbol: String,
private val studentId: Int,
private val diaryId: Int,
androidVersion: String,
buildTag: String
) {
private val cookies by lazy {
CookieManager().apply {
setCookiePolicy(CookiePolicy.ACCEPT_ALL)
}
}
private val loginHelper by lazy {
LoginHelper(loginType, schema, host, symbol, cookies, getLoginService())
}
val urlGenerator by lazy {
UrlGenerator(schema, host, symbol, schoolSymbol)
}
private val interceptors: MutableList<Pair<Interceptor, Boolean>> = mutableListOf(
Pair(HttpLoggingInterceptor().setLevel(logLevel), true),
Pair(ErrorInterceptor(), false),
Pair(NotLoggedInErrorInterceptor(loginType), false),
Pair(UserAgentInterceptor(androidVersion, buildTag), false)
)
fun setInterceptor(interceptor: Interceptor, network: Boolean = false, index: Int = -1) {
if (index == -1) interceptors.add(Pair(interceptor, network))
else interceptors.add(index, Pair(interceptor, network))
}
fun getCookieManager(): CookieManager {
return cookies
}
fun getLoginService(): LoginService {
if (email.isBlank() && password.isBlank()) throw ApiException("Email and password are not set")
if (email.isBlank()) throw ApiException("Email is not set")
if (password.isBlank()) throw ApiException("Password is not set")
return getRetrofit(getClientBuilder(loginIntercept = false), urlGenerator.generate(UrlGenerator.Site.LOGIN), false).create()
}
fun getRegisterService(): RegisterService {
return getRetrofit(getClientBuilder(errIntercept = false, loginIntercept = false, separateJar = true),
urlGenerator.generate(UrlGenerator.Site.LOGIN),
false
).create()
}
fun getStudentService(withLogin: Boolean = true, interceptor: Boolean = true): StudentService {
if (withLogin && schoolSymbol.isBlank()) throw ApiException("School id is not set")
val client = getClientBuilder()
if (interceptor) {
if (0 == diaryId || 0 == studentId) throw ApiException("Student or/and diaryId id are not set")
client.addInterceptor(StudentAndParentInterceptor(cookies, schema, host, diaryId, studentId))
}
return getRetrofit(client, urlGenerator.generate(UrlGenerator.Site.STUDENT), withLogin, true).create()
}
fun getSnpService(withLogin: Boolean = true, interceptor: Boolean = true): StudentAndParentService {
if (withLogin && schoolSymbol.isBlank()) throw ApiException("School id is not set")
val client = getClientBuilder(loginIntercept = withLogin)
if (interceptor) {
if (0 == diaryId || 0 == studentId) throw ApiException("Student or/and diaryId id are not set")
client.addInterceptor(StudentAndParentInterceptor(cookies, schema, host, diaryId, studentId))
}
return getRetrofit(client, urlGenerator.generate(UrlGenerator.Site.SNP), withLogin).create()
}
fun getMessagesService(): MessagesService {
return getRetrofit(getClientBuilder(), urlGenerator.generate(UrlGenerator.Site.MESSAGES), login = true, gson = true).create()
}
fun getHomepageService(): HomepageService {
return getRetrofit(getClientBuilder(), urlGenerator.generate(UrlGenerator.Site.HOME), login = true, gson = true).create()
}
private fun getRetrofit(client: OkHttpClient.Builder, baseUrl: String, login: Boolean = true, gson: Boolean = false): Retrofit {
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(client.build())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(if (gson) GsonConverterFactory.create(GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.serializeNulls()
.registerTypeAdapter(GradeDate::class.java, DateDeserializer(GradeDate::class.java))
.create()) else JspoonConverterFactory.create())
.addCallAdapterFactory(if (!login) RxJava2CallAdapterFactory.create() else
RxJava2ReauthCallAdapterFactory.create(
getLoginHelper(),
{ it is NotLoggedInException }
)
).build()
}
private fun getClientBuilder(errIntercept: Boolean = true, loginIntercept: Boolean = true, separateJar: Boolean = false): OkHttpClient.Builder {
return okHttpClientBuilderFactory.create()
.callTimeout(25, SECONDS)
.cookieJar(if (!separateJar) JavaNetCookieJar(cookies) else JavaNetCookieJar(CookieManager()))
.apply {
interceptors.forEach {
if (it.first is ErrorInterceptor || it.first is NotLoggedInErrorInterceptor) {
if (it.first is NotLoggedInErrorInterceptor && loginIntercept) addInterceptor(it.first)
if (it.first is ErrorInterceptor && errIntercept) addInterceptor(it.first)
} else {
if (it.second) addNetworkInterceptor(it.first)
else addInterceptor(it.first)
}
}
}
}
private fun getLoginHelper(): Flowable<SendCertificateResponse> {
return loginHelper
.login(email, password)
.toFlowable()
.share()
}
class UrlGenerator(private val schema: String, private val host: String, var symbol: String, var schoolId: String) {
enum class Site {
LOGIN, HOME, SNP, STUDENT, MESSAGES
}
fun generate(type: Site): String {
return "$schema://${getSubDomain(type)}.$host/$symbol/${if (type == Site.SNP || type == Site.STUDENT) "$schoolId/" else ""}"
}
private fun getSubDomain(type: Site): String {
return when (type) {
Site.LOGIN -> "cufs"
Site.HOME -> "uonetplus"
Site.SNP -> "uonetplus-opiekun"
Site.STUDENT -> "uonetplus-uczen"
Site.MESSAGES -> "uonetplus-uzytkownik"
}
}
}
}
| 0 | null | 1 | 12 | 3e8cdb8a27cdfcd734000d54c946f4b4e2002794 | 7,903 | api | Apache License 2.0 |
src/main/kotlin/io/apono/sdk/model/UpdateAccessFlowModelV3.kt | apono-io | 644,303,210 | false | null | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package io.apono.sdk.model
import io.apono.sdk.model.AccessFlowModelV3Timeframe
import io.apono.sdk.model.AccessTargetModelV3
import io.apono.sdk.model.ApproverModel
import io.apono.sdk.model.GranteeModel
import io.apono.sdk.model.TriggerType
import com.fasterxml.jackson.annotation.JsonProperty
/**
*
*
* @param name
* @param active
* @param triggerType
* @param grantees
* @param accessTargets
* @param approvers
* @param revokeAfterInSec
* @param justificationRequired
* @param timeframe
*/
data class UpdateAccessFlowModelV3 (
@field:JsonProperty("name")
val name: kotlin.String,
@field:JsonProperty("active")
val active: kotlin.Boolean,
@field:JsonProperty("trigger_type")
val triggerType: TriggerType,
@field:JsonProperty("grantees")
val grantees: kotlin.collections.List<GranteeModel>,
@field:JsonProperty("access_targets")
val accessTargets: kotlin.collections.List<AccessTargetModelV3>,
@field:JsonProperty("approvers")
val approvers: kotlin.collections.List<ApproverModel>,
@field:JsonProperty("revoke_after_in_sec")
val revokeAfterInSec: kotlin.Int,
@field:JsonProperty("justification_required")
val justificationRequired: kotlin.Boolean,
@field:JsonProperty("timeframe")
val timeframe: AccessFlowModelV3Timeframe? = null
)
| 0 | Kotlin | 0 | 0 | de5346cdfcd8fbdcd56849e4edcfd5490980f9b0 | 1,617 | apono-sdk-kotlin | Apache License 2.0 |
apps/etterlatte-behandling/src/test/kotlin/behandling/BehandlingStatusServiceTest.kt | navikt | 417,041,535 | false | {"Kotlin": 5224679, "TypeScript": 1253274, "Handlebars": 21854, "Shell": 10666, "HTML": 1776, "CSS": 598, "Dockerfile": 587} | package no.nav.etterlatte.behandling
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import no.nav.etterlatte.Context
import no.nav.etterlatte.DatabaseKontekst
import no.nav.etterlatte.Kontekst
import no.nav.etterlatte.SaksbehandlerMedEnheterOgRoller
import no.nav.etterlatte.behandling.generellbehandling.GenerellBehandlingService
import no.nav.etterlatte.behandling.hendelse.HendelseType
import no.nav.etterlatte.foerstegangsbehandling
import no.nav.etterlatte.funksjonsbrytere.FeatureToggleService
import no.nav.etterlatte.grunnlagsendring.GrunnlagsendringshendelseService
import no.nav.etterlatte.inTransaction
import no.nav.etterlatte.libs.common.behandling.BehandlingStatus
import no.nav.etterlatte.libs.common.behandling.BoddEllerArbeidetUtlandet
import no.nav.etterlatte.libs.common.generellbehandling.GenerellBehandling
import no.nav.etterlatte.libs.common.grunnlag.Grunnlagsopplysning
import no.nav.etterlatte.libs.common.tidspunkt.Tidspunkt
import no.nav.etterlatte.vedtaksvurdering.VedtakHendelse
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import java.sql.Connection
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class BehandlingStatusServiceTest {
private val user = mockk<SaksbehandlerMedEnheterOgRoller>()
@BeforeEach
fun before() {
Kontekst.set(
Context(
user,
object : DatabaseKontekst {
override fun activeTx(): Connection {
throw IllegalArgumentException()
}
override fun <T> inTransaction(block: () -> T): T {
return block()
}
},
),
)
}
@Test
fun `iverksettNasjonal behandling`() {
val sakId = 1L
val behandling = foerstegangsbehandling(sakId = sakId, status = BehandlingStatus.ATTESTERT)
val behandlingId = behandling.id
val iverksettVedtak = VedtakHendelse(1L, Tidspunkt.now(), "sbl")
val behandlingdao =
mockk<BehandlingDao> {
every { lagreStatus(any(), any(), any()) } just runs
}
val behandlingService =
mockk<BehandlingService> {
every { registrerVedtakHendelse(behandlingId, iverksettVedtak, HendelseType.IVERKSATT) } just runs
every { hentBehandling(behandlingId) } returns behandling
}
val grlService = mockk<GrunnlagsendringshendelseService>()
val featureToggleService =
mockk<FeatureToggleService> {
every { isEnabled(any(), any()) } returns true
}
val generellBehandlingService = mockk<GenerellBehandlingService>()
val sut =
BehandlingStatusServiceImpl(
behandlingdao,
behandlingService,
grlService,
featureToggleService,
generellBehandlingService,
)
inTransaction {
sut.settIverksattVedtak(behandlingId, iverksettVedtak)
}
verify {
behandlingdao.lagreStatus(behandlingId, BehandlingStatus.IVERKSATT, any())
behandlingService.hentBehandling(behandlingId)
behandlingService.registrerVedtakHendelse(behandlingId, iverksettVedtak, HendelseType.IVERKSATT)
}
confirmVerified(behandlingdao, behandlingService, grlService)
}
@Test
fun `iverksett utlandstilsnitt behandling`() {
val sakId = 1L
val behandling =
foerstegangsbehandling(
sakId = sakId,
status = BehandlingStatus.ATTESTERT,
boddEllerArbeidetUtlandet =
BoddEllerArbeidetUtlandet(
boddEllerArbeidetUtlandet = true,
skalSendeKravpakke = true,
begrunnelse = "beg",
kilde = Grunnlagsopplysning.Saksbehandler.create("navIdent"),
),
)
val behandlingId = behandling.id
val saksbehandler = "sbl"
val iverksettVedtak = VedtakHendelse(1L, Tidspunkt.now(), saksbehandler)
val behandlingdao =
mockk<BehandlingDao> {
every { lagreStatus(any(), any(), any()) } just runs
}
val behandlingService =
mockk<BehandlingService> {
every { registrerVedtakHendelse(behandlingId, iverksettVedtak, HendelseType.IVERKSATT) } just runs
every { hentBehandling(behandlingId) } returns behandling
}
val grlService = mockk<GrunnlagsendringshendelseService>()
val generellBehandlingUtland =
GenerellBehandling.opprettUtland(
sakId,
behandlingId,
)
val generellBehandlingService =
mockk<GenerellBehandlingService> {
every { opprettBehandling(any(), any()) } returns generellBehandlingUtland
}
val featureToggleService =
mockk<FeatureToggleService> {
every { isEnabled(any(), any()) } returns true
}
val sut =
BehandlingStatusServiceImpl(
behandlingdao,
behandlingService,
grlService,
featureToggleService,
generellBehandlingService,
)
inTransaction {
sut.settIverksattVedtak(behandlingId, iverksettVedtak)
}
verify {
behandlingdao.lagreStatus(behandlingId, BehandlingStatus.IVERKSATT, any())
behandlingService.hentBehandling(behandlingId)
behandlingService.registrerVedtakHendelse(behandlingId, iverksettVedtak, HendelseType.IVERKSATT)
generellBehandlingService.opprettBehandling(any(), any())
}
confirmVerified(behandlingdao, behandlingService, grlService, generellBehandlingService)
}
}
| 8 | Kotlin | 0 | 6 | aa6b1757cdd96526892ad4a04d3886037f968735 | 6,139 | pensjon-etterlatte-saksbehandling | MIT License |
protocol/notify/src/main/kotlin/com/walletconnect/notify/common/UtilFunctions.kt | WalletConnect | 435,951,419 | false | {"Kotlin": 1987986, "Java": 4358, "Shell": 1892} | @file:JvmSynthetic
package com.walletconnect.notify.common
import com.walletconnect.android.internal.common.model.Expiry
import com.walletconnect.android.internal.utils.monthInSeconds
import java.util.concurrent.TimeUnit
@JvmSynthetic
internal fun calcExpiry(): Expiry {
val currentTimeMs = System.currentTimeMillis()
val currentTimeSeconds = TimeUnit.SECONDS.convert(currentTimeMs, TimeUnit.MILLISECONDS)
val expiryTimeSeconds = currentTimeSeconds + monthInSeconds
return Expiry(expiryTimeSeconds)
} | 156 | Kotlin | 74 | 172 | 35372892c35f461ca69612fac835ac1365fd1157 | 520 | WalletConnectKotlinV2 | Apache License 2.0 |
idea/tests/testData/intentions/replaceExplicitFunctionLiteralParamWithIt/notApplicable_inWhenEntry.kt | JetBrains | 278,369,660 | false | null | fun test(v: Boolean): (String) -> Int {
return when (v) {
true -> <caret>{ { x -> taskOne(x) } }
false -> { x -> taskTwo(x) }
}
}
fun taskOne(s: String) = s.length
fun taskTwo(s: String) = 42 | 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 216 | intellij-kotlin | Apache License 2.0 |
app/src/main/java/com/orange/ods/app/ui/AppBarActions.kt | Orange-OpenSource | 440,548,737 | false | {"Kotlin": 937712, "HTML": 14150, "CSS": 1444, "Shell": 587, "JavaScript": 197} | /*
*
* Copyright 2021 Orange
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* /
*/
package com.orange.ods.app.ui
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.TextFieldValue
import com.orange.ods.app.R
import com.orange.ods.app.ui.AppBarAction.Companion.defaultActions
import com.orange.ods.app.ui.utilities.UiString
import com.orange.ods.app.ui.utilities.extension.isDarkModeEnabled
import com.orange.ods.compose.component.appbar.top.OdsTopAppBarActionButton
import com.orange.ods.compose.component.appbar.top.OdsTopAppBarOverflowMenuActionItem
import com.orange.ods.compose.component.content.OdsComponentContent
import com.orange.ods.compose.component.textfield.search.OdsSearchTextField
enum class AppBarAction {
Search, ChangeTheme, ChangeMode;
companion object {
val defaultActions = listOf(ChangeTheme, ChangeMode)
}
@Composable
fun getOdsTopAppBarAction(onActionClick: (AppBarAction) -> Unit) = when (this) {
ChangeTheme -> getChangeThemeAction(onActionClick)
ChangeMode -> getChangeModeAction(onActionClick)
Search -> getSearchAction(onActionClick)
}
}
data class AppBarOverflowMenuAction(
val title: UiString,
val onClick: () -> Unit
) {
@Composable
fun getOdsTopAppBarOverflowMenuAction() = OdsTopAppBarOverflowMenuActionItem(
text = title.asString(),
onClick = onClick
)
}
@Composable
fun getDefaultActions(onActionClick: (AppBarAction) -> Unit): List<OdsTopAppBarActionButton> =
defaultActions.map { it.getOdsTopAppBarAction(onActionClick = onActionClick) }
@Composable
fun getHomeActions(onActionClick: (AppBarAction) -> Unit): List<OdsTopAppBarActionButton> =
listOf(getSearchAction(onActionClick)) + getDefaultActions(onActionClick = onActionClick)
@Composable
fun getSearchFieldAction(onTextChange: (TextFieldValue) -> Unit): OdsComponentContent<Nothing> {
return object : OdsComponentContent<Nothing>() {
@Composable
override fun Content(modifier: Modifier) {
val focusRequester = remember { FocusRequester() }
OdsSearchTextField(
value = LocalAppBarManager.current.searchedText,
onValueChange = onTextChange,
placeholder = stringResource(id = R.string.search_text_field_hint),
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester)
)
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
}
}
@Composable
private fun getSearchAction(onClick: (AppBarAction) -> Unit) = OdsTopAppBarActionButton(
onClick = { onClick(AppBarAction.Search) },
painter = painterResource(id = R.drawable.ic_search),
contentDescription = stringResource(id = R.string.search_content_description)
)
@Composable
private fun getChangeThemeAction(onClick: (AppBarAction) -> Unit) = OdsTopAppBarActionButton(
onClick = { onClick(AppBarAction.ChangeTheme) },
painter = painterResource(id = R.drawable.ic_palette),
contentDescription = stringResource(id = R.string.top_app_bar_action_change_mode_to_dark_desc)
)
@Composable
private fun getChangeModeAction(onClick: (AppBarAction) -> Unit): OdsTopAppBarActionButton {
val configuration = LocalConfiguration.current
val painterRes = if (configuration.isDarkModeEnabled) R.drawable.ic_ui_light_mode else R.drawable.ic_ui_dark_mode
val iconDesc =
if (configuration.isDarkModeEnabled) R.string.top_app_bar_action_change_mode_to_light_desc else R.string.top_app_bar_action_change_mode_to_dark_desc
return OdsTopAppBarActionButton(
onClick = { onClick(AppBarAction.ChangeMode) },
painter = painterResource(id = painterRes),
contentDescription = stringResource(id = iconDesc)
)
}
| 83 | Kotlin | 5 | 16 | af1ab4b393de041c1f9037053c567d7c7a663b37 | 4,397 | ods-android | MIT License |
compiler/testData/diagnostics/tests/thisAndSuper/unqualifiedSuper/unqualifiedSuperWithInterfaces.fir.kt | android | 263,405,600 | false | null | // Interface AnotherInterface
// \ /
// \/
// DerivedInterface
//
interface Interface {
fun foo() {}
fun ambiguous() {}
val ambiguousProp: Int
get() = 222
}
interface AnotherInterface {
fun ambiguous() {}
val ambiguousProp: Int
get() = 333
}
interface DerivedInterface: Interface, AnotherInterface {
override fun foo() { super.foo() }
override fun ambiguous() {
super.<!AMBIGUITY!>ambiguous<!>()
}
override val ambiguousProp: Int
get() = super.<!AMBIGUITY!>ambiguousProp<!>
}
| 0 | null | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 574 | kotlin | Apache License 2.0 |
src/main/kotlin/com/yapp/itemfinder/domain/item/dto/ItemWithDueDateResponse.kt | YAPP-Github | 561,172,653 | false | null | package com.yapp.itemfinder.domain.item.dto
import com.yapp.itemfinder.api.exception.InternalServerException
import com.yapp.itemfinder.common.DateTimeFormatter.YYYYMMDD
import com.yapp.itemfinder.domain.item.ItemEntity
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
data class ItemWithDueDateResponse(
val id: Long,
val name: String,
val itemType: String,
val useByDate: String,
val remainDate: Long
) {
companion object {
fun from(item: ItemEntity, targetDate: LocalDate): ItemWithDueDateResponse {
val dueDate: LocalDateTime = item.dueDate ?: throw InternalServerException(message = "해당 아이템은 소비기한이 존재하지 않습니다. id: ${item.id}")
val remainDueDateFromTargetDate = ChronoUnit.DAYS.between(targetDate, dueDate.toLocalDate())
return ItemWithDueDateResponse(
id = item.id,
name = item.name,
itemType = item.type.name,
useByDate = dueDate.format(YYYYMMDD),
remainDate = remainDueDateFromTargetDate
)
}
}
}
| 0 | Kotlin | 0 | 2 | abc2ec81c76cbaad4a08e140bf94d28d10f06d5a | 1,124 | 21st-Android-Team-2-BE | Apache License 2.0 |
src/main/kotlin/cloud/fastreport/model/UpdateEmailTaskVM.kt | FastReports | 761,180,912 | false | {"Kotlin": 1252211} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package cloud.fastreport.model
import cloud.fastreport.model.CreateTransportTaskBaseVM
import cloud.fastreport.model.InputFileVM
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
*
*
* @param dollarT
* @param inputFile
* @param cronExpression
* @param delayedRunTime
* @param name
* @param subscriptionId
*/
interface CreateEmailTaskVM : CreateTransportTaskBaseVM {
@Json(name = "\$t")
override val dollarT: kotlin.String
@Json(name = "body")
val body: kotlin.String?
@Json(name = "enableSsl")
val enableSsl: kotlin.Boolean?
@Json(name = "from")
val from: kotlin.String?
@Json(name = "isBodyHtml")
val isBodyHtml: kotlin.Boolean?
@Json(name = "password")
val password: kotlin.String?
@Json(name = "port")
val port: kotlin.Int?
@Json(name = "server")
val server: kotlin.String?
@Json(name = "subject")
val subject: kotlin.String?
@Json(name = "to")
val to: kotlin.collections.List<kotlin.String>?
@Json(name = "username")
val username: kotlin.String?
}
| 0 | Kotlin | 1 | 0 | f75976bb5651bc4875ce7c8b1973b6e4d9eab6b4 | 1,356 | FastReport-Cloud-Kotlin | MIT License |
src/main/java/ro/dob/materialicons/Resizer.kt | andob | 144,163,102 | false | {"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 19, "Java": 1} | package ro.dob.materialicons
import java.awt.Image
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
fun resizePNGIcon(file : File, widthInDp : Int, heightInDp : Int)
{
val image=ImageIO.read(file)
val widthInPx=(image.width*widthInDp)/48
val heightInPx=(image.height*heightInDp)/48
val tmpImage=image.getScaledInstance(widthInPx, widthInPx, Image.SCALE_SMOOTH)
val resizedImage=BufferedImage(widthInPx, heightInPx, BufferedImage.TYPE_INT_ARGB)
val graphics=resizedImage.createGraphics()
graphics.drawImage(tmpImage, 0, 0, null)
graphics.dispose()
ImageIO.write(resizedImage, "png", file)
}
| 1 | null | 1 | 1 | 7f638119e319a8395c48c9d5818b43eb13eaa244 | 664 | materialicons_cli | Apache License 2.0 |
aws-sdk-android-iot-ktx/src/main/java/io/github/crow_misia/aws/iot/AWSIoTSecurityTokenServiceClient.kt | crow-misia | 429,544,850 | false | {"Kotlin": 174562} | /**
* Copyright (C) 2023 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.crow_misia.aws.iot
import com.amazonaws.AmazonClientException
import com.amazonaws.AmazonServiceException
import com.amazonaws.ClientConfiguration
import com.amazonaws.auth.AWSCredentialsProvider
import com.amazonaws.auth.AnonymousAWSCredentials
import com.amazonaws.http.HttpClient
import com.amazonaws.http.JsonErrorResponseHandler
import com.amazonaws.http.JsonResponseHandler
import com.amazonaws.internal.StaticCredentialsProvider
import com.amazonaws.mobileconnectors.iot.AWSIotKeystoreHelper
import com.amazonaws.services.iot.AWSIotClient
import com.amazonaws.services.securitytoken.model.AssumeRoleWithCredentialsRequest
import com.amazonaws.services.securitytoken.model.AssumeRoleWithCredentialsResult
import com.amazonaws.services.securitytoken.model.transform.AssumeRoleWithCredentialsRequestMarshaller
import com.amazonaws.services.securitytoken.model.transform.AssumeRoleWithCredentialsResponseJsonMarshaller
import io.github.crow_misia.aws.core.Okhttp3HttpClient
import io.github.crow_misia.aws.core.createNewClient
import okhttp3.OkHttpClient
import java.security.KeyStore
/**
* STS Client.
*/
@Suppress("unused")
class AWSIoTSecurityTokenServiceClient @JvmOverloads constructor(
stsEndpoint: String,
awsCredentialsProvider: AWSCredentialsProvider = StaticCredentialsProvider(AnonymousAWSCredentials()),
clientConfiguration: ClientConfiguration = ClientConfiguration(),
httpClient: HttpClient,
) : AWSIotClient(awsCredentialsProvider, clientConfiguration, httpClient) {
@JvmOverloads
constructor(
stsEndpoint: String,
okHttpClient: OkHttpClient,
clientConfiguration: ClientConfiguration = ClientConfiguration(),
): this(
stsEndpoint = stsEndpoint,
clientConfiguration = clientConfiguration,
httpClient = Okhttp3HttpClient(okHttpClient, clientConfiguration),
)
@JvmOverloads
constructor(
keyStore: KeyStore,
password: String = AWSIotKeystoreHelper.AWS_IOT_INTERNAL_KEYSTORE<PASSWORD>,
caCertificatesProvider: X509CertificatesProvider,
stsEndpoint: String,
okHttpClient: OkHttpClient,
clientConfiguration: ClientConfiguration = ClientConfiguration(),
): this(
keyStore = keyStore,
password = password.toCharArray(),
caCertificatesProvider = caCertificatesProvider,
stsEndpoint = stsEndpoint,
okHttpClient = okHttpClient,
clientConfiguration = clientConfiguration,
)
@JvmOverloads
constructor(
keyStore: KeyStore,
password: CharArray,
caCertificatesProvider: X509CertificatesProvider,
stsEndpoint: String,
okHttpClient: OkHttpClient,
clientConfiguration: ClientConfiguration = ClientConfiguration(),
): this(
stsEndpoint = stsEndpoint,
clientConfiguration = clientConfiguration,
okHttpClient = okHttpClient.createNewClient(
keyStore = keyStore,
password = <PASSWORD>,
caCertificates = caCertificatesProvider.provide(),
),
)
init {
setEndpoint(stsEndpoint)
}
@Throws(AmazonServiceException::class, AmazonClientException::class)
fun assumeRoleWithCredentials(
assumeRoleRequest: AssumeRoleWithCredentialsRequest,
): AssumeRoleWithCredentialsResult {
val executionContext = createExecutionContext(assumeRoleRequest)
val request = AssumeRoleWithCredentialsRequestMarshaller.marshall(assumeRoleRequest)
request.endpoint = endpoint
request.timeOffset = timeOffset
val responseHandler = JsonResponseHandler(AssumeRoleWithCredentialsResponseJsonMarshaller)
val errorResponseHandler = JsonErrorResponseHandler(jsonErrorUnmarshallers)
return client.execute(request, responseHandler, errorResponseHandler, executionContext).awsResponse
}
}
| 1 | Kotlin | 0 | 0 | cf78440c45485513c4abe3fbbb0f3268eee3f682 | 4,481 | aws-sdk-android-ktx | Apache License 2.0 |
room/room-runtime/src/test/java/androidx/room/InvalidationLiveDataContainerTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room
import androidx.lifecycle.LiveData
import java.util.concurrent.Callable
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito
@RunWith(JUnit4::class)
class InvalidationLiveDataContainerTest {
private lateinit var container: InvalidationLiveDataContainer
@Before
fun init() {
container = InvalidationLiveDataContainer(
Mockito.mock(RoomDatabase::class.java)
)
}
@Test
fun add() {
val liveData = createLiveData()
assertThat(container.liveDataSet, `is`(emptySet()))
container.onActive(liveData)
assertThat(container.liveDataSet, `is`(setOf(liveData)))
}
@Test
fun add_twice() {
val liveData = createLiveData()
container.onActive(liveData)
container.onActive(liveData)
assertThat(container.liveDataSet, `is`(setOf(liveData)))
}
@Test
fun remove() {
val liveData = createLiveData()
container.onActive(liveData)
container.onInactive(liveData)
assertThat(container.liveDataSet, `is`(emptySet()))
}
@Test
fun remove_twice() {
val liveData = createLiveData()
container.onActive(liveData)
container.onInactive(liveData)
container.onInactive(liveData)
assertThat(container.liveDataSet, `is`(emptySet()))
}
@Test
fun addRemoveMultiple() {
val ld1 = createLiveData()
val ld2 = createLiveData()
assertThat(container.liveDataSet, `is`(emptySet()))
container.onActive(ld1)
container.onActive(ld2)
assertThat(container.liveDataSet, `is`(setOf(ld1, ld2)))
container.onInactive(ld1)
assertThat(container.liveDataSet, `is`(setOf(ld2)))
container.onInactive(ld1) // intentional
assertThat(container.liveDataSet, `is`(setOf(ld2)))
container.onActive(ld1)
assertThat(container.liveDataSet, `is`(setOf(ld1, ld2)))
container.onActive(ld1) // intentional
assertThat(container.liveDataSet, `is`(setOf(ld1, ld2)))
container.onInactive(ld2)
assertThat(container.liveDataSet, `is`(setOf(ld1)))
container.onInactive(ld1)
assertThat(container.liveDataSet, `is`(emptySet()))
container.onActive(ld1)
assertThat(container.liveDataSet, `is`(setOf(ld1)))
container.onActive(ld2)
assertThat(container.liveDataSet, `is`(setOf(ld1, ld2)))
}
private fun createLiveData(): LiveData<Any> {
return container.create(
arrayOf("a", "b"),
false,
createComputeFunction()
)
}
private fun <T> createComputeFunction(): Callable<T> {
return Callable<T> { null }
}
}
| 29 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 3,520 | androidx | Apache License 2.0 |
mulighetsrommet-api/src/test/kotlin/no/nav/mulighetsrommet/api/avtaler/AvtaleValidatorTest.kt | navikt | 435,813,834 | false | {"Kotlin": 1643844, "TypeScript": 1436808, "SCSS": 40738, "JavaScript": 27458, "PLpgSQL": 14591, "Handlebars": 3189, "HTML": 2263, "Dockerfile": 1423, "CSS": 1145, "Shell": 396} | package no.nav.mulighetsrommet.api.avtaler
import io.kotest.assertions.arrow.core.shouldBeLeft
import io.kotest.assertions.arrow.core.shouldBeRight
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldContainAll
import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder
import io.mockk.coEvery
import io.mockk.mockk
import no.nav.mulighetsrommet.api.clients.norg2.Norg2Type
import no.nav.mulighetsrommet.api.createDatabaseTestConfig
import no.nav.mulighetsrommet.api.domain.dbo.AvtaleDbo
import no.nav.mulighetsrommet.api.domain.dbo.NavEnhetDbo
import no.nav.mulighetsrommet.api.domain.dbo.NavEnhetStatus
import no.nav.mulighetsrommet.api.domain.dbo.UtdanningslopDbo
import no.nav.mulighetsrommet.api.domain.dto.OpsjonLoggEntry
import no.nav.mulighetsrommet.api.fixtures.*
import no.nav.mulighetsrommet.api.repositories.*
import no.nav.mulighetsrommet.api.responses.ValidationError
import no.nav.mulighetsrommet.api.routes.v1.OpsjonLoggRequest
import no.nav.mulighetsrommet.api.routes.v1.Opsjonsmodell
import no.nav.mulighetsrommet.api.services.EndringshistorikkService
import no.nav.mulighetsrommet.api.services.NavEnhetService
import no.nav.mulighetsrommet.api.services.OpsjonLoggService
import no.nav.mulighetsrommet.api.services.TiltakstypeService
import no.nav.mulighetsrommet.api.utils.DatoUtils.formaterDatoTilEuropeiskDatoformat
import no.nav.mulighetsrommet.database.kotest.extensions.FlywayDatabaseTestListener
import no.nav.mulighetsrommet.database.kotest.extensions.truncateAll
import no.nav.mulighetsrommet.domain.Tiltakskode
import no.nav.mulighetsrommet.domain.constants.ArenaMigrering
import no.nav.mulighetsrommet.domain.dto.*
import no.nav.mulighetsrommet.unleash.UnleashService
import java.time.LocalDate
import java.util.*
class AvtaleValidatorTest : FunSpec({
val database = extension(FlywayDatabaseTestListener(createDatabaseTestConfig()))
val unleash: UnleashService = mockk(relaxed = true)
coEvery { unleash.isEnabled(any()) } returns true
val domain = MulighetsrommetTestDomain(
enheter = listOf(
NavEnhetDbo(
navn = "NAV Oslo",
enhetsnummer = "0300",
status = NavEnhetStatus.AKTIV,
type = Norg2Type.FYLKE,
overordnetEnhet = null,
),
NavEnhetDbo(
navn = "NAV Innlandet",
enhetsnummer = "0400",
status = NavEnhetStatus.AKTIV,
type = Norg2Type.FYLKE,
overordnetEnhet = null,
),
NavEnhetDbo(
navn = "NAV Gjøvik",
enhetsnummer = "0502",
status = NavEnhetStatus.AKTIV,
type = Norg2Type.LOKAL,
overordnetEnhet = "0400",
),
),
ansatte = listOf(),
arrangorer = listOf(
ArrangorFixtures.hovedenhet,
ArrangorFixtures.underenhet1,
ArrangorFixtures.underenhet2,
ArrangorFixtures.Fretex.hovedenhet,
ArrangorFixtures.Fretex.underenhet1,
),
tiltakstyper = listOf(
TiltakstypeFixtures.AFT,
TiltakstypeFixtures.VTA,
TiltakstypeFixtures.Oppfolging,
TiltakstypeFixtures.Jobbklubb,
TiltakstypeFixtures.GruppeAmo,
TiltakstypeFixtures.GruppeFagOgYrkesopplaering,
TiltakstypeFixtures.Arbeidstrening,
TiltakstypeFixtures.Avklaring,
),
avtaler = listOf(),
)
val avtaleDbo = AvtaleDbo(
id = UUID.randomUUID(),
navn = "Avtale",
tiltakstypeId = TiltakstypeFixtures.Oppfolging.id,
arrangorId = ArrangorFixtures.hovedenhet.id,
arrangorUnderenheter = listOf(ArrangorFixtures.underenhet1.id),
arrangorKontaktpersoner = emptyList(),
avtalenummer = "123456",
websaknummer = Websaknummer("24/1234"),
startDato = LocalDate.now().minusDays(1),
sluttDato = LocalDate.now().plusMonths(1),
administratorer = listOf(NavIdent("B123456")),
avtaletype = Avtaletype.Rammeavtale,
prisbetingelser = null,
navEnheter = listOf("0400", "0502"),
antallPlasser = null,
beskrivelse = null,
faneinnhold = Faneinnhold(kurstittel = "Min kurstittel"),
personopplysninger = emptyList(),
personvernBekreftet = false,
amoKategorisering = null,
opsjonMaksVarighet = LocalDate.now().plusYears(3),
opsjonsmodell = Opsjonsmodell.TO_PLUSS_EN,
customOpsjonsmodellNavn = null,
utdanningslop = null,
)
lateinit var navEnheterService: NavEnhetService
lateinit var tiltakstyper: TiltakstypeService
lateinit var avtaler: AvtaleRepository
lateinit var opsjonslogg: OpsjonLoggRepository
lateinit var gjennomforinger: TiltaksgjennomforingRepository
lateinit var arrangorer: ArrangorRepository
beforeEach {
domain.initialize(database.db)
tiltakstyper = TiltakstypeService(TiltakstypeRepository(database.db), Tiltakskode.entries)
navEnheterService = NavEnhetService(NavEnhetRepository(database.db))
avtaler = AvtaleRepository(database.db)
opsjonslogg = OpsjonLoggRepository(database.db)
gjennomforinger = TiltaksgjennomforingRepository(database.db)
arrangorer = ArrangorRepository(database.db)
}
afterEach {
database.db.truncateAll()
}
test("skal feile når tiltakstypen ikke er aktivert") {
tiltakstyper = TiltakstypeService(
TiltakstypeRepository(database.db),
emptyList(),
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dbo = avtaleDbo.copy(
tiltakstypeId = TiltakstypeFixtures.Oppfolging.id,
)
validator.validate(dbo, null).shouldBeLeft().shouldContainAll(
ValidationError(
"tiltakstypeId",
"Opprettelse av avtale for tiltakstype: 'Oppfølging' er ikke skrudd på enda.",
),
)
}
test("skal ikke feile når tiltakstypen er AFT, VTA, eller aktivert") {
tiltakstyper = TiltakstypeService(
TiltakstypeRepository(database.db),
listOf(Tiltakskode.OPPFOLGING),
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
validator.validate(AvtaleFixtures.AFT, null).shouldBeRight()
validator.validate(AvtaleFixtures.VTA, null).shouldBeRight()
validator.validate(AvtaleFixtures.oppfolging, null).shouldBeRight()
}
test("should accumulate errors when dbo has multiple issues") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dbo = avtaleDbo.copy(
startDato = LocalDate.of(2023, 1, 1),
sluttDato = LocalDate.of(2020, 1, 1),
navEnheter = emptyList(),
arrangorUnderenheter = emptyList(),
)
validator.validate(dbo, null).shouldBeLeft().shouldContainAll(
listOf(
ValidationError("startDato", "Startdato må være før sluttdato"),
ValidationError("navEnheter", "Du må velge minst én NAV-region"),
ValidationError("arrangorUnderenheter", "Du må velge minst én underenhet for tiltaksarrangør"),
),
)
}
test("Avtalenavn må være minst 5 tegn når avtalen er opprettet i Admin-flate") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dbo = avtaleDbo.copy(navn = "Avt")
validator.validate(dbo, null).shouldBeLeft().shouldContainExactlyInAnyOrder(
listOf(
ValidationError("navn", "Avtalenavn må være minst 5 tegn langt"),
),
)
}
test("Avtalens startdato må være før eller lik som sluttdato") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dagensDato = LocalDate.now()
val dbo = avtaleDbo.copy(startDato = dagensDato, sluttDato = dagensDato)
validator.validate(dbo, null).shouldBeRight()
val dbo2 = avtaleDbo.copy(startDato = dagensDato.plusDays(5), sluttDato = dagensDato)
validator.validate(dbo2, null).shouldBeLeft().shouldContainExactlyInAnyOrder(
listOf(ValidationError("startDato", "Startdato må være før sluttdato")),
)
}
test("Avtalens lengde er maks 5 år for ikke AFT/VTA") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dagensDato = LocalDate.now()
val dbo = avtaleDbo.copy(startDato = dagensDato, sluttDato = dagensDato.plusYears(5))
validator.validate(dbo, null).shouldBeRight()
val dbo2 = avtaleDbo.copy(startDato = dagensDato, sluttDato = dagensDato.plusYears(6))
validator.validate(dbo2, null).shouldBeLeft().shouldContainExactlyInAnyOrder(
listOf(
ValidationError(
"sluttDato",
"Avtaleperioden kan ikke vare lenger enn 5 år for anskaffede tiltak",
),
),
)
}
test("Avtalens sluttdato være lik eller etter startdato") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dagensDato = LocalDate.now()
val dbo = avtaleDbo.copy(startDato = dagensDato, sluttDato = dagensDato.minusDays(5))
validator.validate(dbo, null).shouldBeLeft().shouldContainExactlyInAnyOrder(
listOf(ValidationError("startDato", "Startdato må være før sluttdato")),
)
val dbo2 = avtaleDbo.copy(startDato = dagensDato, sluttDato = dagensDato)
validator.validate(dbo2, null).shouldBeRight()
}
test("skal validere at NAV-enheter må være koblet til NAV-fylke") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dbo = avtaleDbo.copy(
navEnheter = listOf("0300", "0502"),
)
validator.validate(dbo, null).shouldBeLeft().shouldContainExactlyInAnyOrder(
listOf(
ValidationError("navEnheter", "NAV-enheten 0502 passer ikke i avtalens kontorstruktur"),
),
)
}
test("sluttDato er påkrevd hvis ikke forhåndsgodkjent") {
val forhaandsgodkjent = AvtaleFixtures.AFT.copy(sluttDato = null)
val rammeAvtale = AvtaleFixtures.oppfolging.copy(sluttDato = null)
val avtale = AvtaleFixtures.oppfolgingMedAvtale.copy(sluttDato = null)
val offentligOffentlig = AvtaleFixtures.gruppeAmo.copy(
sluttDato = null,
amoKategorisering = AmoKategorisering.Studiespesialisering,
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
validator.validate(forhaandsgodkjent, null).shouldBeRight()
validator.validate(rammeAvtale, null).shouldBeLeft(
listOf(ValidationError("sluttDato", "Du må legge inn sluttdato for avtalen")),
)
validator.validate(avtale, null).shouldBeLeft(
listOf(ValidationError("sluttDato", "Du må legge inn sluttdato for avtalen")),
)
validator.validate(offentligOffentlig, null).shouldBeLeft(
listOf(ValidationError("sluttDato", "Du må legge inn sluttdato for avtalen")),
)
}
test("amoKategorisering er påkrevd hvis gruppe amo") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val gruppeAmo = AvtaleFixtures.gruppeAmo.copy(amoKategorisering = null)
validator.validate(gruppeAmo, null).shouldBeLeft(
listOf(ValidationError("amoKategorisering.kurstype", "Du må velge en kurstype")),
)
}
test("Opsjonsdata må være satt hvis ikke avtaletypen er forhåndsgodkjent") {
val forhaandsgodkjent = AvtaleFixtures.AFT
val rammeAvtale = AvtaleFixtures.oppfolging.copy(opsjonsmodell = null, opsjonMaksVarighet = null)
val avtale = AvtaleFixtures.oppfolgingMedAvtale.copy(opsjonsmodell = null, opsjonMaksVarighet = null)
val offentligOffentlig = AvtaleFixtures.gruppeAmo.copy(
opsjonsmodell = null,
opsjonMaksVarighet = null,
amoKategorisering = AmoKategorisering.Studiespesialisering,
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
validator.validate(forhaandsgodkjent, null).shouldBeRight()
validator.validate(rammeAvtale, null).shouldBeLeft(
listOf(
ValidationError("opsjonMaksVarighet", "Du må legge inn maks varighet for opsjonen"),
ValidationError("opsjonsmodell", "Du må velge en opsjonsmodell"),
),
)
validator.validate(avtale, null).shouldBeLeft(
listOf(
ValidationError("opsjonMaksVarighet", "Du må legge inn maks varighet for opsjonen"),
ValidationError("opsjonsmodell", "Du må velge en opsjonsmodell"),
),
)
validator.validate(offentligOffentlig, null).shouldBeLeft(
listOf(
ValidationError("opsjonMaksVarighet", "Du må legge inn maks varighet for opsjonen"),
ValidationError("opsjonsmodell", "Du må velge en opsjonsmodell"),
),
)
}
test("Custom navn for opsjon må være satt hvis opsjonsmodell er ANNET") {
val rammeAvtale = AvtaleFixtures.oppfolging.copy(
opsjonsmodell = Opsjonsmodell.ANNET,
opsjonMaksVarighet = LocalDate.now(),
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
validator.validate(rammeAvtale, null).shouldBeLeft(
listOf(
ValidationError("customOpsjonsmodellNavn", "Du må beskrive opsjonsmodellen"),
),
)
}
test("avtaletype må være allowed") {
val aft = AvtaleFixtures.AFT.copy(
avtaletype = Avtaletype.Rammeavtale,
opsjonMaksVarighet = LocalDate.now(),
opsjonsmodell = Opsjonsmodell.TO_PLUSS_EN,
)
val vta = AvtaleFixtures.VTA.copy(
avtaletype = Avtaletype.Avtale,
opsjonMaksVarighet = LocalDate.now(),
opsjonsmodell = Opsjonsmodell.TO_PLUSS_EN,
)
val oppfolging = AvtaleFixtures.oppfolging.copy(avtaletype = Avtaletype.OffentligOffentlig)
val gruppeAmo = AvtaleFixtures.gruppeAmo.copy(
avtaletype = Avtaletype.Forhaandsgodkjent,
amoKategorisering = AmoKategorisering.Studiespesialisering,
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
validator.validate(aft, null).shouldBeLeft(
listOf(
ValidationError(
"avtaletype",
"Rammeavtale er ikke tillatt for tiltakstype Arbeidsforberedende trening (AFT)",
),
),
)
validator.validate(vta, null).shouldBeLeft(
listOf(
ValidationError(
"avtaletype",
"Avtale er ikke tillatt for tiltakstype Varig tilrettelagt arbeid i skjermet virksomhet",
),
),
)
validator.validate(oppfolging, null).shouldBeLeft(
listOf(ValidationError("avtaletype", "OffentligOffentlig er ikke tillatt for tiltakstype Oppfølging")),
)
validator.validate(gruppeAmo, null).shouldBeLeft(
listOf(ValidationError("avtaletype", "Forhaandsgodkjent er ikke tillatt for tiltakstype Gruppe amo")),
)
val aftForhaands = AvtaleFixtures.AFT.copy(avtaletype = Avtaletype.Forhaandsgodkjent)
val vtaForhaands = AvtaleFixtures.AFT.copy(avtaletype = Avtaletype.Forhaandsgodkjent)
val oppfolgingRamme = AvtaleFixtures.oppfolging.copy(avtaletype = Avtaletype.Rammeavtale)
val gruppeAmoOffentlig = AvtaleFixtures.gruppeAmo.copy(
avtaletype = Avtaletype.OffentligOffentlig,
amoKategorisering = AmoKategorisering.Studiespesialisering,
)
validator.validate(aftForhaands, null).shouldBeRight()
validator.validate(vtaForhaands, null).shouldBeRight()
validator.validate(oppfolgingRamme, null).shouldBeRight()
validator.validate(gruppeAmoOffentlig, null).shouldBeRight()
}
test("Websak-referanse må være med når avtalen er avtale eller rammeavtale") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val rammeavtale = AvtaleFixtures.oppfolging.copy(avtaletype = Avtaletype.Rammeavtale, websaknummer = null)
validator.validate(rammeavtale, null).shouldBeLeft(
listOf(ValidationError("websaknummer", "Du må skrive inn Websaknummer til avtalesaken")),
)
val avtale = AvtaleFixtures.oppfolging.copy(avtaletype = Avtaletype.Avtale, websaknummer = null)
validator.validate(avtale, null).shouldBeLeft(
listOf(ValidationError("websaknummer", "Du må skrive inn Websaknummer til avtalesaken")),
)
val offentligOffentligSamarbeid = AvtaleFixtures.gruppeAmo.copy(
avtaletype = Avtaletype.OffentligOffentlig,
websaknummer = null,
amoKategorisering = AmoKategorisering.Studiespesialisering,
)
validator.validate(offentligOffentligSamarbeid, null).shouldBeRight()
}
test("arrangørens underenheter må tilhøre hovedenhet i Brreg") {
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val avtale1 = AvtaleFixtures.oppfolging.copy(
arrangorId = ArrangorFixtures.Fretex.hovedenhet.id,
arrangorUnderenheter = listOf(ArrangorFixtures.underenhet1.id),
)
validator.validate(avtale1, null).shouldBeLeft().shouldContainExactlyInAnyOrder(
ValidationError(
"arrangorUnderenheter",
"Arrangøren Underenhet 1 AS er ikke en gyldig underenhet til hovedenheten FRETEX AS.",
),
)
val avtale2 = AvtaleFixtures.oppfolging.copy(
arrangorId = ArrangorFixtures.Fretex.hovedenhet.id,
arrangorUnderenheter = listOf(ArrangorFixtures.Fretex.underenhet1.id),
)
validator.validate(avtale2, null).shouldBeRight()
}
test("arrangøren må være aktiv i Brreg") {
arrangorer.upsert(ArrangorFixtures.Fretex.hovedenhet.copy(slettetDato = LocalDate.of(2024, 1, 1)))
arrangorer.upsert(ArrangorFixtures.Fretex.underenhet1.copy(slettetDato = LocalDate.of(2024, 1, 1)))
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val avtale1 = AvtaleFixtures.oppfolging.copy(
arrangorId = ArrangorFixtures.Fretex.hovedenhet.id,
arrangorUnderenheter = listOf(ArrangorFixtures.Fretex.underenhet1.id),
)
validator.validate(avtale1, null).shouldBeLeft().shouldContainExactlyInAnyOrder(
ValidationError(
"arrangorId",
"Arrangøren FRETEX AS er slettet i Brønnøysundregistrene. Avtaler kan ikke opprettes for slettede bedrifter.",
),
ValidationError(
"arrangorUnderenheter",
"Arrangøren FRETEX AS AVD OSLO er slettet i Brønnøysundregistrene. Avtaler kan ikke opprettes for slettede bedrifter.",
),
)
}
test("utdanningsprogram er påkrevd når tiltakstypen er Gruppe Fag- og yrkesopplæring") {
val avtaleMedEndringer = avtaleDbo.copy(
tiltakstypeId = TiltakstypeFixtures.GruppeFagOgYrkesopplaering.id,
utdanningslop = null,
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
validator.validate(avtaleMedEndringer, null).shouldBeLeft(
listOf(
ValidationError("utdanningslop", "Du må velge et utdanningsprogram og minst ett lærefag"),
),
)
}
test("minst én utdanning er påkrevd når tiltakstypen er Gruppe Fag- og yrkesopplæring") {
val avtaleMedEndringer = avtaleDbo.copy(
tiltakstypeId = TiltakstypeFixtures.GruppeFagOgYrkesopplaering.id,
utdanningslop = UtdanningslopDbo(
utdanningsprogram = UUID.randomUUID(),
utdanninger = emptyList(),
),
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
validator.validate(avtaleMedEndringer, null).shouldBeLeft(
listOf(
ValidationError("utdanningslop", "Du må velge minst ett lærefag"),
),
)
}
context("når avtalen allerede eksisterer") {
test("skal kunne endre felter med opphav fra Arena når vi har tatt eierskap til tiltakstypen") {
tiltakstyper = TiltakstypeService(
TiltakstypeRepository(database.db),
listOf(Tiltakskode.OPPFOLGING, Tiltakskode.ARBEIDSFORBEREDENDE_TRENING),
)
val avtaleMedEndringer = AvtaleDbo(
id = avtaleDbo.id,
navn = "Nytt navn",
tiltakstypeId = TiltakstypeFixtures.AFT.id,
arrangorId = ArrangorFixtures.underenhet1.id,
arrangorUnderenheter = listOf(ArrangorFixtures.underenhet1.id),
arrangorKontaktpersoner = emptyList(),
avtalenummer = "123456",
websaknummer = Websaknummer("24/1234"),
startDato = LocalDate.now(),
sluttDato = LocalDate.now().plusYears(1),
administratorer = listOf(NavIdent("B123456")),
avtaletype = Avtaletype.Forhaandsgodkjent,
prisbetingelser = null,
navEnheter = listOf("0300"),
antallPlasser = null,
beskrivelse = null,
faneinnhold = Faneinnhold(kurstittel = "Min kurstittel"),
personopplysninger = emptyList(),
personvernBekreftet = false,
amoKategorisering = null,
opsjonMaksVarighet = LocalDate.now().plusYears(3),
opsjonsmodell = Opsjonsmodell.TO_PLUSS_EN,
customOpsjonsmodellNavn = null,
utdanningslop = null,
)
avtaler.upsert(avtaleDbo.copy(administratorer = listOf()))
avtaler.setOpphav(avtaleDbo.id, ArenaMigrering.Opphav.ARENA)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val previous = avtaler.get(avtaleDbo.id)
validator.validate(avtaleMedEndringer, previous).shouldBeRight()
}
test("skal ikke kunne endre felter med opphav fra Arena når vi ikke har tatt eierskap til tiltakstypen") {
tiltakstyper = TiltakstypeService(
TiltakstypeRepository(database.db),
emptyList(),
)
val avtaleMedEndringer = AvtaleDbo(
id = avtaleDbo.id,
navn = "Nytt navn",
tiltakstypeId = TiltakstypeFixtures.Jobbklubb.id,
arrangorId = ArrangorFixtures.underenhet1.id,
arrangorUnderenheter = listOf(ArrangorFixtures.underenhet1.id),
arrangorKontaktpersoner = emptyList(),
avtalenummer = "123456",
websaknummer = Websaknummer("24/1234"),
startDato = LocalDate.now(),
sluttDato = LocalDate.now().plusYears(1),
administratorer = listOf(NavIdent("B123456")),
avtaletype = Avtaletype.Avtale,
prisbetingelser = null,
navEnheter = listOf("0300"),
antallPlasser = null,
beskrivelse = null,
faneinnhold = Faneinnhold(kurstittel = "Min kurstittel"),
personopplysninger = emptyList(),
personvernBekreftet = false,
amoKategorisering = null,
opsjonMaksVarighet = LocalDate.now().plusYears(3),
opsjonsmodell = Opsjonsmodell.TO_PLUSS_EN,
customOpsjonsmodellNavn = null,
utdanningslop = null,
)
avtaler.upsert(
avtaleDbo.copy(
administratorer = listOf(),
tiltakstypeId = TiltakstypeFixtures.Jobbklubb.id,
),
)
avtaler.setOpphav(avtaleDbo.id, ArenaMigrering.Opphav.ARENA)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val previous = avtaler.get(avtaleDbo.id)
validator.validate(avtaleMedEndringer, previous).shouldBeLeft().shouldContainExactlyInAnyOrder(
ValidationError("navn", "Navn kan ikke endres utenfor Arena"),
ValidationError("startDato", "Startdato kan ikke endres utenfor Arena"),
ValidationError("sluttDato", "Sluttdato kan ikke endres utenfor Arena"),
ValidationError("avtaletype", "Avtaletype kan ikke endres utenfor Arena"),
ValidationError("arrangorId", "Tiltaksarrangøren kan ikke endres utenfor Arena"),
)
}
test("Skal ikke kunne endre opsjonsmodell når opsjon er registrert") {
val endringshistorikkService: EndringshistorikkService = mockk(relaxed = true)
val opsjonValidator = OpsjonLoggValidator()
val opsjonLoggService =
OpsjonLoggService(database.db, opsjonValidator, avtaler, opsjonslogg, endringshistorikkService)
val avtaleMedEndringer = AvtaleDbo(
id = avtaleDbo.id,
navn = "Nytt navn",
tiltakstypeId = TiltakstypeFixtures.Jobbklubb.id,
arrangorId = ArrangorFixtures.underenhet1.id,
arrangorUnderenheter = listOf(ArrangorFixtures.underenhet1.id),
arrangorKontaktpersoner = emptyList(),
avtalenummer = "123456",
websaknummer = Websaknummer("24/1234"),
startDato = LocalDate.of(2024, 5, 7),
sluttDato = LocalDate.of(2024, 5, 7).plusYears(1),
administratorer = listOf(NavIdent("B123456")),
avtaletype = Avtaletype.Avtale,
prisbetingelser = null,
navEnheter = listOf("0300"),
antallPlasser = null,
beskrivelse = null,
faneinnhold = Faneinnhold(kurstittel = "Min kurstittel"),
personopplysninger = emptyList(),
personvernBekreftet = false,
amoKategorisering = null,
opsjonMaksVarighet = LocalDate.of(2024, 5, 7).plusYears(3),
opsjonsmodell = Opsjonsmodell.TO_PLUSS_EN,
customOpsjonsmodellNavn = null,
utdanningslop = null,
)
avtaler.upsert(
avtaleDbo.copy(
administratorer = listOf(),
tiltakstypeId = TiltakstypeFixtures.Jobbklubb.id,
opsjonsmodell = Opsjonsmodell.TO_PLUSS_EN_PLUSS_EN,
opsjonMaksVarighet = LocalDate.of(2024, 5, 7).plusYears(3),
startDato = LocalDate.of(2024, 5, 7),
sluttDato = LocalDate.of(2024, 5, 7).plusYears(1),
),
)
avtaler.setOpphav(avtaleDbo.id, ArenaMigrering.Opphav.MR_ADMIN_FLATE)
opsjonLoggService.lagreOpsjonLoggEntry(
OpsjonLoggEntry(
avtaleId = avtaleDbo.id,
sluttdato = avtaleDbo.sluttDato?.plusYears(1),
forrigeSluttdato = avtaleDbo.sluttDato,
status = OpsjonLoggRequest.OpsjonsLoggStatus.OPSJON_UTLØST,
registrertAv = NavIdent("M123456"),
),
)
val previous = avtaler.get(avtaleDbo.id)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
validator.validate(avtaleMedEndringer, previous).shouldBeLeft(
listOf(
ValidationError("opsjonsmodell", "Du kan ikke endre opsjonsmodell når opsjoner er registrert"),
),
)
}
context("når avtalen har gjennomføringer") {
val startDatoForGjennomforing = avtaleDbo.startDato
val gjennomforing = TiltaksgjennomforingFixtures.Oppfolging1.copy(
avtaleId = avtaleDbo.id,
administratorer = emptyList(),
navRegion = "0400",
startDato = startDatoForGjennomforing,
)
beforeAny {
avtaler.upsert(avtaleDbo.copy(administratorer = listOf()))
}
afterAny {
gjennomforinger.delete(TiltaksgjennomforingFixtures.Oppfolging1.id)
}
test("skal validere at data samsvarer med avtalens gjennomføringer") {
gjennomforinger.upsert(
gjennomforing.copy(arrangorId = ArrangorFixtures.underenhet2.id),
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dbo = avtaleDbo.copy(
tiltakstypeId = TiltakstypeFixtures.AFT.id,
avtaletype = Avtaletype.Forhaandsgodkjent,
startDato = avtaleDbo.startDato.plusDays(4),
)
val previous = avtaler.get(avtaleDbo.id)
val formatertDato = startDatoForGjennomforing.formaterDatoTilEuropeiskDatoformat()
validator.validate(dbo, previous).shouldBeLeft().shouldContainExactlyInAnyOrder(
listOf(
ValidationError(
"tiltakstypeId",
"Tiltakstype kan ikke endres fordi det finnes gjennomføringer for avtalen",
),
ValidationError(
"avtaletype",
"Avtaletype kan ikke endres fordi det finnes gjennomføringer for avtalen",
),
ValidationError(
"arrangorUnderenheter",
"Arrangøren Underenhet 2 AS er i bruk på en av avtalens gjennomføringer, men mangler blant tiltaksarrangørens underenheter",
),
ValidationError(
"startDato",
"Startdato kan ikke være før startdatoen til gjennomføringer koblet til avtalen. Minst en gjennomføring har startdato: $formatertDato",
),
),
)
}
test("skal godta at gjennomføring har andre NAV-enheter enn avtalen") {
gjennomforinger.upsert(
gjennomforing.copy(navRegion = "0400"),
)
val validator = AvtaleValidator(tiltakstyper, gjennomforinger, navEnheterService, arrangorer, unleash)
val dbo = avtaleDbo.copy(
navEnheter = listOf("0400"),
)
val previous = avtaler.get(avtaleDbo.id)
validator.validate(dbo, previous).shouldBeRight()
}
}
}
})
| 4 | Kotlin | 2 | 7 | f8fd04c7473bc676b019bbd39f578758b6451801 | 32,200 | mulighetsrommet | MIT License |
app/src/main/kotlin/com/zaiming/android/gallery/databse/converters/Converters.kt | qiuzaiming | 456,448,337 | false | {"Kotlin": 295953} | package com.zaiming.android.gallery.databse.converters
import android.net.Uri
import androidx.room.TypeConverter
/**
* @author zaiming
*/
class Converters {
@TypeConverter
fun stringToUri(value: String?): Uri? = value?.let { Uri.parse(it) }
@TypeConverter
fun uriToString(uri: Uri?) = uri?.toString()
}
| 1 | Kotlin | 0 | 1 | 1c47caffb2063c3e7ccd5c4b32893d06cf11ffdb | 317 | gallery | Apache License 2.0 |
shared/src/commonMain/kotlin/by/game/binumbers/base/movement/MoveDirection.kt | alexander-kulikovskii | 565,271,232 | false | {"Kotlin": 454229, "Swift": 3274, "Ruby": 2480, "Shell": 622} | package by.game.binumbers.base.movement
import by.game.binumbers.base.model.Area
import by.game.binumbers.base.movement.action.MoveToDownAction
import by.game.binumbers.base.movement.action.MoveToLeftAction
import by.game.binumbers.base.movement.action.MoveToRightAction
import by.game.binumbers.base.movement.action.MoveToUpAction
enum class MoveDirection {
MOVE_LEFT,
MOVE_RIGHT,
MOVE_UP,
MOVE_DOWN
}
fun MoveDirection.getMovingAction(prevArea: Area): MoveAction {
return when (this) {
MoveDirection.MOVE_LEFT -> MoveToLeftAction(prevArea, this)
MoveDirection.MOVE_RIGHT -> MoveToRightAction(prevArea, this)
MoveDirection.MOVE_DOWN -> MoveToDownAction(prevArea, this)
MoveDirection.MOVE_UP -> MoveToUpAction(prevArea, this)
}
}
| 0 | Kotlin | 0 | 10 | 66b1678b47a96a52ebef467111d1d4854a37486a | 789 | 2048-kmm | Apache License 2.0 |
app/src/main/java/com/umidsafarov/pokehead/domain/use_case/GetPokemonUseCase.kt | umidsafarov | 598,935,453 | false | null | package com.umidsafarov.pokehead.domain.use_case
import com.umidsafarov.pokehead.common.Resource
import com.umidsafarov.pokehead.domain.model.Pokemon
import com.umidsafarov.pokehead.domain.repository.PokeheadRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GetPokemonUseCase @Inject constructor(
private val repository: PokeheadRepository,
) {
operator fun invoke(
pokemonId: Int
): Flow<Resource<Pokemon>> {
return repository.getPokemon(pokemonId)
}
} | 0 | Kotlin | 0 | 0 | b956b62cbff7c577522cefe5f88876cebddfc690 | 517 | pokehead | MIT License |
stream_component/src/main/java/com/xyoye/stream_component/ui/activities/smb_file/SmbFileActivity.kt | kaedei | 395,177,024 | false | null | package com.xyoye.stream_component.ui.activities.smb_file
import android.content.Intent
import android.view.KeyEvent
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.xyoye.common_component.adapter.addItem
import com.xyoye.common_component.adapter.buildAdapter
import com.xyoye.common_component.base.BaseActivity
import com.xyoye.common_component.config.RouteTable
import com.xyoye.common_component.databinding.ItemFileManagerPathBinding
import com.xyoye.common_component.extension.*
import com.xyoye.common_component.services.ScreencastProvideService
import com.xyoye.common_component.utils.dp2px
import com.xyoye.common_component.utils.view.FilePathItemDecoration
import com.xyoye.common_component.weight.StorageAdapter
import com.xyoye.common_component.weight.ToastCenter
import com.xyoye.data_component.bean.FilePathBean
import com.xyoye.data_component.entity.MediaLibraryEntity
import com.xyoye.data_component.enums.MediaType
import com.xyoye.stream_component.BR
import com.xyoye.stream_component.R
import com.xyoye.stream_component.databinding.ActivitySmbFileBinding
@Route(path = RouteTable.Stream.SmbFile)
class SmbFileActivity : BaseActivity<SmbFileViewModel, ActivitySmbFileBinding>() {
companion object {
private const val PLAY_REQUEST_CODE = 1001
}
@Autowired
@JvmField
var smbData: MediaLibraryEntity? = null
private val fileAdapter = StorageAdapter.newInstance(
this,
MediaType.SMB_SERVER,
refreshDirectory = { viewModel.refreshDirectoryWithHistory() },
openFile = { viewModel.playItem(it.uniqueKey ?: "") },
castFile = { data, device ->
viewModel.castItem(data.uniqueKey ?: "", device)
},
openDirectory = { viewModel.openChildDirectory(it.filePath) }
)
override fun initViewModel() =
ViewModelInit(
BR.viewModel,
SmbFileViewModel::class.java
)
override fun getLayoutId() = R.layout.activity_smb_file
override fun initView() {
ARouter.getInstance().inject(this)
if (smbData == null) {
ToastCenter.showError("媒体库数据错误,请重试")
title = "SMB媒体库"
return
}
title = smbData!!.displayName
dataBinding.refreshLayout.setOnRefreshListener {
viewModel.refreshDirectory()
}
initRv()
initObserver()
viewModel.initFtp(smbData!!)
}
override fun onResume() {
super.onResume()
viewModel.refreshDirectoryWithHistory()
}
override fun observeLoadingDialog() {
//替换弹窗观察者
viewModel.loadingObserver.observe(this) {
if (dataBinding.refreshLayout.isRefreshing) {
dataBinding.refreshLayout.isRefreshing = false
}
if (it.first > 0) {
dataBinding.refreshLayout.isRefreshing = true
}
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (viewModel.openParentDirectory()) {
return true
}
}
return super.onKeyDown(keyCode, event)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == PLAY_REQUEST_CODE) {
viewModel.closeStream()
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onDestroy() {
viewModel.closeSMB()
super.onDestroy()
}
private fun initRv() {
dataBinding.pathRv.apply {
layoutManager = horizontal()
adapter = buildAdapter {
addItem<FilePathBean, ItemFileManagerPathBinding>(R.layout.item_file_manager_path) {
initView { data, position, _ ->
itemBinding.apply {
dirNameTv.text = data.name
dirNameTv.setTextColorRes(
if (data.isOpened) R.color.text_black else R.color.text_gray
)
dirNameTv.setOnClickListener {
viewModel.openPositionDirectory(position)
}
}
}
}
}
val dividerSize = dp2px(16)
val divider = R.drawable.ic_file_manager_arrow.toResDrawable()
if (divider != null) {
addItemDecoration(FilePathItemDecoration(divider, dividerSize))
}
}
dataBinding.fileRv.apply {
layoutManager = vertical()
adapter = fileAdapter
}
}
private fun initObserver() {
viewModel.pathLiveData.observe(this) {
dataBinding.pathRv.setData(it)
}
viewModel.fileLiveData.observe(this) {
dataBinding.fileRv.setData(it)
}
viewModel.playLiveData.observe(this) {
ARouter.getInstance()
.build(RouteTable.Player.Player)
.navigation(this, PLAY_REQUEST_CODE)
}
viewModel.castLiveData.observe(this) {
ARouter.getInstance()
.navigation(ScreencastProvideService::class.java)
.startService(this, it)
}
}
} | 57 | null | 67 | 8 | 1e2bbe520287c3ebf056ffdb3d00c07edf7946fb | 5,482 | DanDanPlayForAndroid | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/lex/CfnBotBotAliasLocaleSettingsPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.lex
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Boolean
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.lex.CfnBot
/**
* Specifies settings that are unique to a locale.
*
* For example, you can use different Lambda function depending on the bot's locale.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.lex.*;
* BotAliasLocaleSettingsProperty botAliasLocaleSettingsProperty =
* BotAliasLocaleSettingsProperty.builder()
* .enabled(false)
* // the properties below are optional
* .codeHookSpecification(CodeHookSpecificationProperty.builder()
* .lambdaCodeHook(LambdaCodeHookProperty.builder()
* .codeHookInterfaceVersion("codeHookInterfaceVersion")
* .lambdaArn("lambdaArn")
* .build())
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lex-bot-botaliaslocalesettings.html)
*/
@CdkDslMarker
public class CfnBotBotAliasLocaleSettingsPropertyDsl {
private val cdkBuilder: CfnBot.BotAliasLocaleSettingsProperty.Builder =
CfnBot.BotAliasLocaleSettingsProperty.builder()
/**
* @param codeHookSpecification Specifies the Lambda function that should be used in the locale.
*/
public fun codeHookSpecification(codeHookSpecification: IResolvable) {
cdkBuilder.codeHookSpecification(codeHookSpecification)
}
/**
* @param codeHookSpecification Specifies the Lambda function that should be used in the locale.
*/
public fun codeHookSpecification(codeHookSpecification: CfnBot.CodeHookSpecificationProperty) {
cdkBuilder.codeHookSpecification(codeHookSpecification)
}
/**
* @param enabled Determines whether the locale is enabled for the bot. If the value is `false`
* , the locale isn't available for use.
*/
public fun enabled(enabled: Boolean) {
cdkBuilder.enabled(enabled)
}
/**
* @param enabled Determines whether the locale is enabled for the bot. If the value is `false`
* , the locale isn't available for use.
*/
public fun enabled(enabled: IResolvable) {
cdkBuilder.enabled(enabled)
}
public fun build(): CfnBot.BotAliasLocaleSettingsProperty = cdkBuilder.build()
}
| 4 | null | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 2,672 | awscdk-dsl-kotlin | Apache License 2.0 |
app/shared/sqldelight/testing/src/commonMain/kotlin/build/wallet/sqldelight/dummy/DummyDataEntityQueries.kt | proto-at-block | 761,306,853 | false | {"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.sqldelight.dummy
import app.cash.sqldelight.Query
import app.cash.sqldelight.db.SqlCursor
import app.cash.sqldelight.db.SqlDriver
import build.wallet.sqldelight.ThrowingSqlDriver
/**
* Imitates SqlDelight's generated queries class, if we had a `dummy.sq` and used SqlDelight plugin.
*/
class DummyDataEntityQueries(val sqlDriver: SqlDriver) {
/**
* Inserts a row into `dummy` table.
*/
suspend fun insertDummyData(
id: Long,
value: String,
) {
sqlDriver.execute(
identifier = null,
sql =
"""
INSERT INTO dummy (id, value)
VALUES (?, ?)
""".trimIndent(),
parameters = 2,
binders = {
bindLong(0, id)
bindString(1, value)
}
).await()
}
/**
* Deletes all rows from `dummy` table.
*/
fun clear() {
sqlDriver.execute(identifier = null, sql = "DELETE FROM dummy", parameters = 0)
}
/**
* Returns all rows from `dummy` table.
*/
fun getDummyData(throwError: Boolean = false): Query<DummyDataEntity> =
Query(
identifier = 0,
queryKeys = arrayOf("dummyDataEntity"),
driver = if (throwError) ThrowingSqlDriver else sqlDriver,
fileName = "dummy",
label = "queryDummyData",
query = "SELECT * FROM dummy",
mapper = mapper
)
private val mapper = { cursor: SqlCursor ->
DummyDataEntity(
cursor.getLong(0)!!,
cursor.getString(1)!!
)
}
}
| 0 | C | 10 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 1,456 | bitkey | MIT License |
compPaccounts/src/main/java/com/effective/android/component/paccounts/vm/ArticleViewModel.kt | YummyLau | 118,240,800 | false | null | package com.effective.android.component.paccounts.vm
import androidx.lifecycle.ViewModel
import com.effective.android.base.rxjava.RxSchedulers
import com.effective.android.component.blog.bean.Article
import com.effective.android.component.paccounts.data.PaccountsRepository
import com.effective.android.service.net.BaseListResult
import io.reactivex.Flowable
class ArticleViewModel : ViewModel() {
/**
* 默认 pageCount 从1开始
*/
fun getArticles(id: Long, pageCount: Int): Flowable<BaseListResult<Article>> {
return PaccountsRepository.get().getArticles(id.toString(), pageCount.toString())
.compose(RxSchedulers.flowableIoToMain())
}
} | 1 | null | 32 | 187 | f9bad2216051e5b848b2d862cab7958f1bcdc5e8 | 680 | AndroidModularArchiteture | MIT License |
app/src/main/java/ac/uk/hope/osmviewerjetpack/data/network/musicbrainz/responses/SearchArtistsResponse.kt | movedaccount-droid | 796,686,976 | false | {"Kotlin": 153945, "TeX": 15257} | package ac.uk.hope.osmviewerjetpack.data.network.musicbrainz.responses
import ac.uk.hope.osmviewerjetpack.data.network.musicbrainz.model.ArtistNetwork
import ac.uk.hope.osmviewerjetpack.data.network.musicbrainz.model.toLocal
import kotlinx.serialization.Serializable
// model for the api response, which we will then pass to the repository mappers for parsing
@Serializable
data class SearchArtistsResponse (
val created: String,
val count: Int,
val offset: Int,
val artists: List<ArtistNetwork>
)
fun SearchArtistsResponse.toLocal() = artists.toLocal() | 0 | Kotlin | 0 | 0 | 74c785bdf9eb6b2b3e3be78fae1024469f16b8d9 | 573 | osmviewerjetpack2 | Creative Commons Zero v1.0 Universal |
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/solid/BxsBookmarkAltMinus.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.boxicons.boxicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.boxicons.boxicons.SolidGroup
public val SolidGroup.BxsBookmarkAltMinus: ImageVector
get() {
if (_bxsBookmarkAltMinus != null) {
return _bxsBookmarkAltMinus!!
}
_bxsBookmarkAltMinus = Builder(name = "BxsBookmarkAltMinus", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.5f, 2.0f)
horizontalLineToRelative(-12.0f)
curveTo(4.57f, 2.0f, 3.0f, 3.57f, 3.0f, 5.5f)
lineTo(3.0f, 22.0f)
lineToRelative(7.0f, -3.5f)
lineToRelative(7.0f, 3.5f)
verticalLineToRelative(-9.0f)
horizontalLineToRelative(5.0f)
lineTo(22.0f, 5.5f)
curveTo(22.0f, 3.57f, 20.43f, 2.0f, 18.5f, 2.0f)
close()
moveTo(13.0f, 11.0f)
lineTo(7.0f, 11.0f)
lineTo(7.0f, 9.0f)
horizontalLineToRelative(6.0f)
verticalLineToRelative(2.0f)
close()
moveTo(20.0f, 11.0f)
horizontalLineToRelative(-3.0f)
lineTo(17.0f, 5.5f)
curveToRelative(0.0f, -0.827f, 0.673f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.673f, 1.5f, 1.5f)
lineTo(20.0f, 11.0f)
close()
}
}
.build()
return _bxsBookmarkAltMinus!!
}
private var _bxsBookmarkAltMinus: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,382 | compose-icon-collections | MIT License |
newm-server/src/main/kotlin/io/newm/server/features/earnings/EarningsKoinModule.kt | projectNEWM | 447,979,150 | false | {"Kotlin": 2401222, "HTML": 185274, "Dockerfile": 2535, "Shell": 1986, "Procfile": 60} | package io.newm.server.features.earnings
import io.newm.server.features.earnings.repo.EarningsRepository
import io.newm.server.features.earnings.repo.EarningsRepositoryImpl
import org.koin.dsl.module
val earningsKoinModule =
module {
single<EarningsRepository> { EarningsRepositoryImpl(get(), get(), get(), get(), get()) }
}
| 3 | Kotlin | 4 | 10 | 2815acb9d967f4008c43c60f2a58a01f58f4fe45 | 343 | newm-server | Apache License 2.0 |
apps/etterlatte-gyldig-soeknad/src/test/kotlin/no/nav/etterlatte/gyldigsoeknad/OpprettBehandlingRiverTest.kt | navikt | 417,041,535 | false | {"Kotlin": 6969414, "TypeScript": 1668616, "Handlebars": 25499, "Shell": 12687, "HTML": 1734, "CSS": 598, "PLpgSQL": 556, "Dockerfile": 547} | package no.nav.etterlatte.gyldigsoeknad
import io.kotest.matchers.shouldBe
import io.mockk.clearAllMocks
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import no.nav.etterlatte.behandling.randomSakId
import no.nav.etterlatte.behandling.tilSakId
import no.nav.etterlatte.common.Enheter
import no.nav.etterlatte.gyldigsoeknad.client.BehandlingClient
import no.nav.etterlatte.libs.common.behandling.SakType
import no.nav.etterlatte.libs.common.event.GyldigSoeknadVurdert
import no.nav.etterlatte.libs.common.event.SoeknadInnsendtHendelseType
import no.nav.etterlatte.libs.common.gyldigSoeknad.GyldighetsResultat
import no.nav.etterlatte.libs.common.gyldigSoeknad.VurderingsResultat
import no.nav.etterlatte.libs.common.rapidsandrivers.EVENT_NAME_KEY
import no.nav.etterlatte.libs.common.sak.Sak
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import java.util.UUID
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class OpprettBehandlingRiverTest {
private val behandlingClientMock = mockk<BehandlingClient>()
@AfterEach
fun afterEach() {
clearAllMocks()
}
@Test
fun `OMSTILLINGSSTOENAD - Skal opprette sak og behandling`() {
val soeker = "13848599411"
val sakId = randomSakId()
val behandlingId = UUID.randomUUID()
every {
behandlingClientMock.finnEllerOpprettSak(any(), any())
} returns Sak(soeker, SakType.OMSTILLINGSSTOENAD, sakId, Enheter.PORSGRUNN.enhetNr)
every { behandlingClientMock.opprettBehandling(any(), any(), any()) } returns behandlingId
every { behandlingClientMock.lagreGyldighetsVurdering(any(), any()) } returns ""
val inspector = testRapid().apply { sendTestMessage(getJson("/behandlingsbehov/omstillingsstoenad.json")) }.inspektør
val message = inspector.message(0)
assertEquals(1, inspector.size)
assertEquals(
SoeknadInnsendtHendelseType.EVENT_NAME_BEHANDLINGBEHOV.lagEventnameForType(),
message.get(EVENT_NAME_KEY).asText(),
)
assertEquals(sakId, message.get(GyldigSoeknadVurdert.sakIdKey).tilSakId())
assertEquals(behandlingId.toString(), message.get(GyldigSoeknadVurdert.behandlingIdKey).asText())
coVerify(exactly = 1) { behandlingClientMock.finnEllerOpprettSak(soeker, SakType.OMSTILLINGSSTOENAD) }
coVerify(exactly = 1) { behandlingClientMock.opprettBehandling(sakId, any(), any()) }
}
@Test
fun `BARNEPENSJON - Skal opprette sak og behandling`() {
val soeker = "24111258054"
val sakId = randomSakId()
val behandlingId = UUID.randomUUID()
every {
behandlingClientMock.finnEllerOpprettSak(any(), any())
} returns Sak(soeker, SakType.BARNEPENSJON, sakId, Enheter.PORSGRUNN.enhetNr)
every { behandlingClientMock.opprettBehandling(any(), any(), any()) } returns behandlingId
every { behandlingClientMock.lagreGyldighetsVurdering(any(), any()) } returns ""
val inspector = testRapid().apply { sendTestMessage(getJson("/behandlingsbehov/barnepensjon.json")) }.inspektør
val message = inspector.message(0)
assertEquals(
SoeknadInnsendtHendelseType.EVENT_NAME_BEHANDLINGBEHOV.lagEventnameForType(),
message.get(EVENT_NAME_KEY).asText(),
)
assertEquals(sakId, message.get(GyldigSoeknadVurdert.sakIdKey).tilSakId())
assertEquals(behandlingId.toString(), message.get(GyldigSoeknadVurdert.behandlingIdKey).asText())
assertEquals(1, inspector.size)
val actualGyldighet = slot<GyldighetsResultat>()
verify { behandlingClientMock.lagreGyldighetsVurdering(behandlingId, capture(actualGyldighet)) }
actualGyldighet.captured.resultat shouldBe VurderingsResultat.KAN_IKKE_VURDERE_PGA_MANGLENDE_OPPLYSNING
coVerify(exactly = 1) { behandlingClientMock.finnEllerOpprettSak(soeker, SakType.BARNEPENSJON) }
coVerify(exactly = 1) { behandlingClientMock.opprettBehandling(sakId, any(), any()) }
}
private fun testRapid() =
TestRapid().apply {
OpprettBehandlingRiver(this, behandlingClientMock)
}
private fun getJson(file: String) = javaClass.getResource(file)!!.readText()
}
| 8 | Kotlin | 0 | 6 | cb383baf7c3c2ddf3d2a41e6c3eca4310f5c6d0a | 4,479 | pensjon-etterlatte-saksbehandling | MIT License |
croppylib/src/main/java/com/lyrebirdstudio/croppylib/ui/ImageCropViewModel.kt | lyrebirdstudio | 212,750,589 | false | null | package com.lyrebirdstudio.croppylib.ui
import android.app.Application
import android.graphics.RectF
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.lyrebirdstudio.aspectratiorecyclerviewlib.aspectratio.model.AspectRatio
import com.lyrebirdstudio.croppylib.main.CropRequest
import com.lyrebirdstudio.croppylib.state.CropFragmentViewState
import com.lyrebirdstudio.croppylib.util.bitmap.BitmapUtils
import com.lyrebirdstudio.croppylib.util.bitmap.ResizedBitmap
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
class ImageCropViewModel(val app: Application) : AndroidViewModel(app) {
private val compositeDisposable = CompositeDisposable()
private var cropRequest: CropRequest? = null
private val cropViewStateLiveData = MutableLiveData<CropFragmentViewState>()
.apply {
value = CropFragmentViewState(aspectRatio = AspectRatio.ASPECT_FREE)
}
private val resizedBitmapLiveData = MutableLiveData<ResizedBitmap>()
fun setCropRequest(cropRequest: CropRequest) {
this.cropRequest = cropRequest
BitmapUtils
.resize(cropRequest.sourceUri, app.applicationContext)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Consumer { resizedBitmapLiveData.value = it })
.also { compositeDisposable.add(it) }
cropViewStateLiveData.value =
cropViewStateLiveData.value?.onThemeChanged(croppyTheme = cropRequest.croppyTheme)
}
fun getCropRequest(): CropRequest? = cropRequest
fun getCropViewStateLiveData(): LiveData<CropFragmentViewState> = cropViewStateLiveData
fun getResizedBitmapLiveData(): LiveData<ResizedBitmap> = resizedBitmapLiveData
fun updateCropSize(cropRect: RectF) {
cropViewStateLiveData.value =
cropViewStateLiveData.value?.onCropSizeChanged(cropRect = cropRect)
}
fun onAspectRatioChanged(aspectRatio: AspectRatio) {
cropViewStateLiveData.value =
cropViewStateLiveData.value?.onAspectRatioChanged(aspectRatio = aspectRatio)
}
override fun onCleared() {
super.onCleared()
if (compositeDisposable.isDisposed.not()) {
compositeDisposable.dispose()
}
}
} | 15 | null | 70 | 989 | 6f8115f4a8a1d632b12ad61e0f9b91a9eae9cdef | 2,488 | Croppy | Apache License 2.0 |
ui/src/main/java/com/doordeck/sdk/common/manager/Doordeck.kt | sgerogia | 497,347,433 | false | null | package com.doordeck.sdk.common.manager
import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.doordeck.sdk.BuildConfig
import com.doordeck.sdk.common.events.EventsManager
import com.doordeck.sdk.common.events.IEventCallback
import com.doordeck.sdk.common.events.UnlockCallback
import com.doordeck.sdk.common.models.DDEVENT
import com.doordeck.sdk.common.models.EventAction
import com.doordeck.sdk.common.models.JWTHeader
import com.doordeck.sdk.common.utils.JWTContentUtils
import com.doordeck.sdk.common.utils.LOG
import com.doordeck.sdk.dto.certificate.CertificateChain
import com.doordeck.sdk.dto.device.Device
import com.doordeck.sdk.dto.operation.Operation
import com.doordeck.sdk.http.DoordeckClient
import com.doordeck.sdk.signer.Ed25519KeyGenerator
import com.doordeck.sdk.signer.util.JWTUtils
import com.doordeck.sdk.ui.nfc.NFCActivity
import com.doordeck.sdk.ui.qrcode.QRcodeActivity
import com.doordeck.sdk.ui.unlock.UnlockActivity
import com.doordeck.sdk.ui.verify.VerifyDeviceActivity
import com.google.common.base.Preconditions
import io.reactivex.Observable
import java.net.URI
import java.security.GeneralSecurityException
import java.security.KeyPair
import java.util.*
import kotlin.properties.Delegates.observable
object Doordeck {
private const val USER_AGENT_PREFIX = "Doordeck SDK - "
private const val LOG_SDK = "Doordeck"
// usage of the light theme boolean
internal var darkMode: Boolean = true
// current api key
private var apiKey: String? = null
internal var jwtToken: JWTHeader? = null
internal var status: AuthStatus = AuthStatus.UNAUTHORIZED
// HTTP client
internal var client: DoordeckClient? = null
// pub/priv key
private var keys: KeyPair? = null
// Android keychain
private val datastore = Datastore()
// callbacks for the user
internal var callback: IEventCallback? = null
// certificates associated to the current user
internal var certificateChain: CertificateChain? = null
// unlock callback
internal var unlockCallback: UnlockCallback? = null
// get
internal fun getKeys(): KeyPair {
return keys!!
}
// device to unlock
private var deviceToUnlock: Device? = null
// Shared Preferences
@SuppressLint("StaticFieldLeak")
internal var sharedPreference: SharedPreference? = null
// Observable to catch async certificate loading
internal var certificateLoaded: Boolean by observable(false) { _, oldValue, newValue ->
onCertLoaded?.invoke(oldValue, newValue)
}
// Check if certificates are loaded
var onCertLoaded : ((Boolean, Boolean) -> Unit)? = null
// Sdk Mode
private var sdkMode: Boolean = false
// public //
/**
* Initialize the Doordeck SDK with your valid auth token
* This is the first method to call from the your Android Application class. The reason for this being in the Application class is
* for the SDK to be able to initialize and unlock from NFC touch, even when the parent app is not running in the background yet.
*
* @param ctx Your application context! Warning, providing non-application context might break the app or cause memory leaks.
* @param authToken (Nullable) A valid auth token. Make sure you refresh the auth token if needed before initializing the SDK.
* If you don't have an auth token yet because the user is logged out, initiate the sdk with authToken = null and set the auth token after logging in with updateToken method.
* @param darkmode (Optional) set dark or light theme of the sdk.
* @param unlockCallback provides a callback mainly for Auth purposes
* @return Doordeck the current instance of the SDK
*/
@JvmOverloads
fun initialize(
ctx: Context,
authToken: String? = null,
darkMode: Boolean = false,
unlockCallback: UnlockCallback? = null
): Doordeck {
Preconditions.checkNotNull(ctx!!, "Context can't be null")
if (authToken != null) {
if (this.apiKey == null) {
val jwtToken = JWTContentUtils.getContentHeaderFromJson(authToken)
Preconditions.checkNotNull(jwtToken!!, "Api key is invalid")
Preconditions.checkArgument(isValidityApiKey(jwtToken), "Api key has expired")
this.jwtToken = jwtToken
this.apiKey = authToken
this.darkMode = darkMode
this.sharedPreference = SharedPreference(ctx)
createHttpClient()
generateKeys(ctx)
this.storeTheme(darkMode)
if (getStoredAuthToken(ctx) != authToken) {
storeToken(ctx, authToken)
keys?.public?.let { CertificateManager.getCertificatesAsync(it, unlockCallback) }
} else {
if (certificateChain == null) {
certificateChain = getStoredCertificateChain()
if (certificateChain == null) {
keys?.public?.let { CertificateManager.getCertificatesAsync(it, unlockCallback) }
var lastStatus = getLastStatus()
if (lastStatus != null) Doordeck.status = lastStatus
} else {
if (checkIfValidCertificate(certificateChain!!)) {
status = AuthStatus.AUTHORIZED
certificateLoaded = true
} else {
keys?.public?.let { CertificateManager.getCertificatesAsync(it, unlockCallback) }
}
}
} else {
if (checkIfValidCertificate(certificateChain!!)) {
status = AuthStatus.AUTHORIZED
certificateLoaded = true
} else {
keys?.public?.let { CertificateManager.getCertificatesAsync(it, unlockCallback) }
}
}
}
} else Log.d(LOG_SDK, "Doordeck already initialized")
} else {
this.darkMode = darkMode
this.sharedPreference = SharedPreference(ctx)
createHttpClient()
this.storeTheme(darkMode)
}
return this
}
private fun checkIfValidCertificate(certificateChain: CertificateChain): Boolean {
return certificateChain.isValid() && certificateChain.userId().toString() == this.jwtToken!!.sub()
}
/**
* Update your authToken
* Call this method after logging in to update the token.
* @param authToken new valid auth token
* @param unlockCallback provides a callback mainly for Auth purposes
*/
@JvmOverloads
fun updateToken(authToken: String, ctx: Context, unlockCallback: UnlockCallback? = null) {
Preconditions.checkNotNull(sharedPreference!!, "Doordeck not initiated. Make sure to call initialize first.")
Preconditions.checkArgument(!TextUtils.isEmpty(authToken), "Token needs to be provided")
val jwtToken = JWTContentUtils.getContentHeaderFromJson(authToken)
Preconditions.checkNotNull(jwtToken!!, "Api key is invalid")
Preconditions.checkArgument(isValidityApiKey(jwtToken), "Api key has expired")
this.jwtToken = jwtToken
this.apiKey = authToken
this.darkMode = darkMode
generateKeys(ctx)
storeToken(ctx, authToken)
storeTheme(darkMode)
createHttpClient()
keys?.public?.let { CertificateManager.getCertificatesAsync(it, unlockCallback) }
}
/**
* Update the theme
* @param darkMode set dark or light theme
*/
fun setDarkMode(darkMode: Boolean) {
this.darkMode = darkMode
this.storeTheme(darkMode)
}
/**
* Observable to subscribe to, to be able to listen to the events sent by the SDK
* @return Observable of events
*/
fun eventsObservable(): Observable<DDEVENT> {
return EventsManager.eventsObservable()
}
/**
* Set a callback to listen to the events sent by the SDK
*/
fun withEventsCallback(callback: IEventCallback) {
this.callback = callback
}
/**
* Unlock method for unlocking via button unlock
*
* @param ctx current context
* @param device a valid device.
* @param callback (optional) callback function for catching async response after unlock.
* @return Doordeck the current instance of the SDK
*/
@JvmOverloads
fun unlock(ctx: Context, device: Device, callback: UnlockCallback? = null){
this.deviceToUnlock = device
showUnlock(ctx, ScanType.UNLOCK, callback)
}
/**
* Show the unlock screen given the Scan type given in parameter
*
* @param context current context
* @param type type of scan to use (NFC or QR) , NFC by default if not provided, optional
* @param callback callback of the method, optional
*/
@JvmOverloads
fun showUnlock(context: Context, type: ScanType = ScanType.NFC, callback: UnlockCallback? = null) {
if (status == AuthStatus.UNAUTHORIZED) {
callback?.notAuthenticated()
return
}
if (status == AuthStatus.TWO_FACTOR_AUTH_NEEDED) {
callback?.verificationNeeded()
return
}
jwtToken?.let { header ->
if (isValidityApiKey(header) && apiKey != null) {
if (!sdkMode) {
when (type) {
ScanType.QR -> QRcodeActivity.start(context)
ScanType.NFC -> NFCActivity.start(context)
ScanType.UNLOCK -> UnlockActivity.start(context, deviceToUnlock!!)
}
}
this.unlockCallback = callback
} else
callback?.invalidAuthToken()
}
}
/**
* getSigned JWT
*
* @param deviceId
* @param operation operation of the signed key
*/
fun getSignedJWT(deviceId: UUID, operation: Operation): String {
Doordeck.certificateChain?.let { chain ->
return JWTUtils.getSignedJWT(chain.certificateChain(),
Doordeck.getKeys().private,
deviceId,
chain.userId(),
operation
)
} ?: return ""
}
/**
* Cleanup the data internally
* Call when you log out a user.
*/
fun logout(context: Context) {
this.apiKey = null
this.certificateChain = null
this.datastore.clean(context)
this.keys = null
}
/**
* Shows the verification screen
*/
fun showVerificationScreen(context: Context) {
VerifyDeviceActivity.start(context)
}
// private //
internal fun hasUserLoggedIn (ctx: Context): Boolean {
if (this.apiKey != null) return true
else {
val token = getStoredAuthToken(ctx)
if (token !== null) {
try {
initialize(ctx, token, getSavedTheme())
return true
} catch (e: IllegalArgumentException) {
return false
}
} else return false
}
}
/**
* Create the network HTTP client
*/
internal fun createHttpClient() {
this.client = DoordeckClient.Builder()
.baseUrl(URI.create(BuildConfig.BASE_URL_API))
.userAgent(USER_AGENT_PREFIX + BuildConfig.VERSION_NAME)
.authToken(apiKey)
.build()
}
/**
* Verify if the expiry date provided inside the JWT token is valid
* @return true if valid, false otherwise
*/
private fun isValidityApiKey(jwtToken: JWTHeader): Boolean {
val currentDate = Date().time
if (jwtToken.exp() * 1000L > currentDate)
return true
return false
}
/**
* Generate the private/public key and store them in the keychains
*/
private fun generateKeys(context: Context) {
val keys = datastore.getKeyPair(context)
if (keys == null || keys.private == null || keys.public == null) {
try {
val keyPair = Ed25519KeyGenerator.generate()
datastore.saveKeyPair(context, keyPair)
this.keys = keyPair
} catch (e: GeneralSecurityException) {
LOG.e(LOG_SDK, e.localizedMessage)
EventsManager.sendEvent(EventAction.SDK_ERROR, e)
}
} else
this.keys = keys
}
/**
* Store certificates them in the keychains
*/
internal fun storeCertificates(certificateChain: CertificateChain) {
datastore.saveCertificates(certificateChain)
}
/**
* get stored certificates from keychains
*/
internal fun getStoredCertificateChain(): CertificateChain? {
return datastore.getSavedCertificates()
}
/**
* Store certificates them in the keychains
*/
internal fun storeToken(context: Context, authToken: String) {
datastore.saveAuthToken(context, authToken)
}
/**
* get stored certificates from keychains
*/
internal fun getStoredAuthToken(context: Context): String? {
return datastore.getAuthToken(context)
}
/**
* Store certificates them in the keychains
*/
internal fun storeLaststatus(status: AuthStatus) {
datastore.saveStatus(status)
}
/**
* get stored certificates from keychains
*/
internal fun getLastStatus(): AuthStatus? {
return datastore.getStoredStatus()
}
/**
* Store certificates them in the keychains
*/
internal fun storeTheme(darkMode: Boolean) {
datastore.saveTheme(darkMode)
}
/**
* get stored certificates from keychains
*/
internal fun getSavedTheme(): Boolean {
val darkMode = datastore.getSavedTheme()
if (darkMode != null) return darkMode
else return false
}
} | 1 | null | 3 | 1 | e7e9aabfeda8f3ce371fa621607ab92676f833d8 | 14,349 | doordeck-sdk-java | Apache License 2.0 |
modulecheck-api/src/main/kotlin/modulecheck/api/context/ManifestFiles.kt | RBusarow | 316,627,145 | false | null | /*
* Copyright (C) 2021-2022 Rick Busarow
* 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 modulecheck.api.context
import modulecheck.model.dependency.isAndroid
import modulecheck.model.dependency.withUpstream
import modulecheck.model.sourceset.SourceSetName
import modulecheck.parsing.android.XmlFile
import modulecheck.project.McProject
import modulecheck.project.ProjectContext
import modulecheck.utils.cache.SafeCache
import modulecheck.utils.existsOrNull
data class ManifestFiles(
private val delegate: SafeCache<SourceSetName, XmlFile.ManifestFile?>,
private val project: McProject
) : ProjectContext.Element {
override val key: ProjectContext.Key<ManifestFiles>
get() = Key
suspend fun get(sourceSetName: SourceSetName): XmlFile.ManifestFile? {
val platformPlugin = project.platformPlugin
if (!platformPlugin.isAndroid()) return null
return delegate.getOrPut(sourceSetName) {
sourceSetName
.withUpstream(project)
.firstNotNullOfOrNull { sourceSetOrUpstream ->
platformPlugin.manifests[sourceSetOrUpstream]?.existsOrNull()
}
?.let { file -> XmlFile.ManifestFile(file) }
}
}
companion object Key : ProjectContext.Key<ManifestFiles> {
override suspend operator fun invoke(project: McProject): ManifestFiles {
return ManifestFiles(SafeCache(listOf(project.path, ManifestFiles::class)), project)
}
}
}
suspend fun ProjectContext.manifestFiles(): ManifestFiles = get(ManifestFiles)
suspend fun ProjectContext.manifestFileForSourceSetName(
sourceSetName: SourceSetName
): XmlFile.ManifestFile? = manifestFiles().get(sourceSetName)
| 8 | null | 7 | 95 | 24e7c7667490630d30cf8b59cd504cd863cd1fba | 2,162 | ModuleCheck | Apache License 2.0 |
stencil/src/main/kotlin/io/ight/gradle/stencil/properties/Property.kt | WOCOMLABS | 796,096,413 | false | {"Kotlin": 36246} | package io.ight.stencil.properties
/**
* This object holds the properties related to different components of the application.
*/
object Property {
/**
* This object holds the properties related to Docker Compose.
*/
object DockerCompose {
/**
* The name of the Docker container.
*/
const val containerName : String = "io.ight.docker.compose.name"
/**
* The volume of the Docker container.
*/
const val containerVolume : String = "io.ight.docker.compose.volume"
/**
* The port of the Docker container.
*/
const val containerPort : String = "io.ight.docker.compose.port"
}
/**
* This object holds the properties related to Surrealdb.
*/
object Surrealdb {
/**
* The user of the Surrealdb.
*/
const val user : String = "io.ight.surrealdb.root.user"
/**
* The secret of the Surrealdb.
*/
const val secret : String = "io.ight.surrealdb.root.secret"
/**
* The port of the Surrealdb.
*/
const val port : String = "io.ight.surrealdb.port"
/**
* The namespace of the Surrealdb.
*/
const val namespace : String = "io.ight.surrealdb.namespace"
/**
* The database of the Surrealdb.
*/
const val database : String = "io.ight.surrealdb.database"
/**
* The test user of the Surrealdb.
*/
const val testUser : String = "io.ight.surrealdb.test.user"
/**
* The test secret of the Surrealdb.
*/
const val testSecret : String = "io.ight.surrealdb.test.secret"
}
/**
* This object holds the properties related to OpenApi.
*/
object OpenApi {
/**
* The file of the OpenApi.
*/
const val file : String = "io.ight.surrealdb.openapi.yaml"
/**
* The generator of the OpenApi.
*/
const val generator : String = "io.ight.surrealdb.openapi.generator"
}
} | 3 | Kotlin | 0 | 0 | eb5afa7cfe7187297787539721d50ea4891b8767 | 2,117 | artesano | MIT License |
opensrp-path-zeir/src/main/java/org/smartregister/path/reporting/monthly/indicator/ReportIndicatorFragment.kt | opensrp | 306,545,484 | false | null | package org.smartregister.uniceftunisia.reporting.monthly.indicator
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import org.smartregister.uniceftunisia.R
/**
* Main [Fragment] subclass for ReportIndicator.
* create an instance of this fragment.
*/
class ReportIndicatorFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?,
): View = inflater.inflate(R.layout.fragment_report_indicator, container, false)
} | 24 | null | 5 | 1 | e2fe71b921186d8944d863f3be2d5522a899dfc3 | 614 | opensrp-client-path-zeir | Apache License 2.0 |
kotlin-ffmpeg-thumbnails/src/main/java/com/cleveroad/bootstrap/kotlin_ffmpeg_thumbnails/model/Thumbnail.kt | Cleveroad | 114,619,348 | false | null | package com.cleveroad.bootstrap.kotlin_ffmpeg_thumbnails.model
import android.graphics.Bitmap
data class Thumbnail(var fileLength: Long,
var filePath: String,
var imageFormat: String,
var timeFromVideo: Long,
var bitmap: Bitmap) | 3 | Kotlin | 6 | 38 | 7bc51f35e26b1f0ca600422a57fc37b2231b726a | 314 | Bootstrap | The Unlicense |
app/src/main/java/at/spiceburg/roarfit/features/auth/AuthActivity.kt | alex-burghuber | 198,246,710 | false | {"Kotlin": 131929, "Java": 4897} | package at.spiceburg.roarfit.features.auth
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricConstants
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import at.spiceburg.roarfit.MyApplication
import at.spiceburg.roarfit.R
import at.spiceburg.roarfit.data.LoginData
import at.spiceburg.roarfit.data.NetworkError
import at.spiceburg.roarfit.features.main.MainActivity
import at.spiceburg.roarfit.utils.Constants
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputLayout
import kotlinx.android.synthetic.main.activity_auth.*
import java.nio.charset.Charset
import java.security.Key
import java.security.KeyStore
import java.util.concurrent.Executor
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
class AuthActivity : AppCompatActivity() {
private lateinit var viewModel: AuthViewModel
private lateinit var sp: SharedPreferences
private lateinit var executor: Executor
private lateinit var decryptPrompt: BiometricPrompt
override fun onCreate(savedInstanceState: Bundle?) {
// replaces the launcher theme with the normal one
setTheme(R.style.AppTheme_White)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_auth)
// create notification channel
createNotificationChannel()
// setup viewModel
val appContainer = (application as MyApplication).appContainer
viewModel = ViewModelProvider(
this,
AuthViewModel.Factory(appContainer.userRepository)
).get(AuthViewModel::class.java)
sp = getSharedPreferences(Constants.PREFERENCES_FILE, Context.MODE_PRIVATE)
// biometric
executor = ContextCompat.getMainExecutor(this)
decryptPrompt = BiometricPrompt(this, executor, DecryptCallback())
// setup login click listener
button_auth_login.setOnClickListener {
hideKeyboard()
val username = input_username.text.toString()
val password = <PASSWORD>()
if (!username.isBlank() && !password.isBlank()) {
viewModel.login(username, password).observe(this) { res ->
when {
res.isSuccess() -> {
val data: LoginData = res.data!!
// check if biometric authentication can be set up
val remindBiometric =
sp.getBoolean(Constants.DONT_REMIND_BIOMETRIC, false)
val encryptedPwdExists = sp.contains(Constants.ENCRYPTED_PWD)
if (!encryptedPwdExists && !remindBiometric && checkBiometricRequirements()) {
// setup biometric encryption
val promptInfo = createEncryptPromptInfo()
val cipher = getCipherInstance()
cipher.init(Cipher.ENCRYPT_MODE, createKey())
// open biometric encryption prompt
val encryptPrompt =
BiometricPrompt(this, executor, EncryptCallback(data))
encryptPrompt.authenticate(
promptInfo,
BiometricPrompt.CryptoObject(cipher)
)
} else {
// finish login normally
finishLogin(data)
}
}
res.isLoading() -> {
setLoading(true)
}
else -> {
val msg: String = when (res.error) {
NetworkError.SERVER_UNREACHABLE -> getString(R.string.networkerror_server_unreachable)
NetworkError.USERNAME_PASSWORD_WRONG -> getString(R.string.networkerror_username_pwd_wrong)
NetworkError.TIMEOUT -> getString(R.string.networkerror_timeout)
else -> getString(R.string.networkerror_unexpected)
}
displaySnackbar(msg)
setLoading(false)
}
}
}
} else {
displaySnackbar(getString(R.string.auth_fill_all_fields))
}
}
}
override fun onStart() {
super.onStart()
val username = sp.getString(Constants.USERNAME, null)
if (username != null) {
input_username.setText(username)
}
// activate biometric decryption if the requirements are met
if (username != null && sp.contains(Constants.ENCRYPTED_PWD)) {
val ivString: String? = sp.getString(Constants.INITIALIZATION_VECTOR, null)
val key: Key? = getKey()
if (ivString != null && key != null) {
// setup biometric decryption
val iv = Base64.decode(ivString, Base64.DEFAULT)
val cipher = getCipherInstance()
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
val promptInfo = createDecryptPromptInfo(username/*, customerNum*/)
// setup button to reopen prompt
textinputlayout_auth_password.apply {
endIconDrawable = getDrawable(R.drawable.ic_fingerprint_black_24dp)
endIconMode = TextInputLayout.END_ICON_CUSTOM
endIconContentDescription = getString(R.string.auth_endicon_desc)
setEndIconOnClickListener {
// re-init cipher because it could have been used before and that will make it non-functional
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
decryptPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
}
}
// open biometric decryption prompt
decryptPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
} else {
throw RuntimeException("Parameters for Biometric Decryption are null")
}
}
}
private fun finishLogin(data: LoginData) {
val jwt: String = data.token
sp.edit()
.putString(Constants.JWT, jwt)
.putString(Constants.USERNAME, data.username)
.apply()
setLoading(false)
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
private fun checkBiometricRequirements(): Boolean {
val biometricManager = BiometricManager.from(this)
return biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS
}
private fun createEncryptPromptInfo(): BiometricPrompt.PromptInfo {
return BiometricPrompt.PromptInfo.Builder()
.setTitle(getString(R.string.auth_biometric_encrypt_title))
.setDescription(getString(R.string.auth_biometric_encrypt_desc))
.setNegativeButtonText(getString(R.string.auth_biometric_encrypt_negative_button))
.build()
}
private fun createDecryptPromptInfo(username: String): BiometricPrompt.PromptInfo {
return BiometricPrompt.PromptInfo.Builder()
.setTitle(getString(R.string.auth_biometric_decrypt_title))
.setSubtitle("Username: $username")
.setNegativeButtonText(getString(R.string.auth_biometric_decrypt_close))
.setConfirmationRequired(false)
.build()
}
private fun createKey(): SecretKey {
val algorithm = KeyProperties.KEY_ALGORITHM_AES
val keyGenerator = KeyGenerator.getInstance(algorithm, Constants.PROVIDER)
val purposes = KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
val keyGenParameterSpec = KeyGenParameterSpec.Builder(Constants.KEY_NAME, purposes)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.setUserAuthenticationRequired(true)
.build()
keyGenerator.init(keyGenParameterSpec)
return keyGenerator.generateKey()
}
private fun getKey(): Key? {
val keyStore = KeyStore.getInstance(Constants.PROVIDER)
keyStore.load(null)
return keyStore.getKey(Constants.KEY_NAME, null)
}
private fun getCipherInstance(): Cipher {
return Cipher.getInstance(
KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7
)
}
private fun hideKeyboard() {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(
currentFocus?.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
}
private fun setLoading(isLoading: Boolean) {
input_username.isEnabled = !isLoading
input_password.isEnabled = !isLoading
button_auth_login.isEnabled = !isLoading
if (isLoading) {
button_auth_login.visibility = View.INVISIBLE
progress_auth.visibility = View.VISIBLE
} else {
button_auth_login.visibility = View.VISIBLE
progress_auth.visibility = View.INVISIBLE
}
}
private fun displaySnackbar(text: String) {
Snackbar.make(constraintlayout_auth, text, Snackbar.LENGTH_LONG)
.setAction("Dismiss") {}
.show()
}
private fun createNotificationChannel() {
// on Android 8.0+ a notification channel must be registered and should be done as soon as possible
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
Constants.CHANNEL_ID,
"Exercise",
NotificationManager.IMPORTANCE_LOW
).apply {
enableVibration(false)
enableLights(false)
setSound(null, null)
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
inner class EncryptCallback(private val data: LoginData) :
BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
val cipher: Cipher? = result.cryptoObject?.cipher
if (cipher != null) {
// encrypt the password
val encryptedBytes: ByteArray =
cipher.doFinal(data.password.toByteArray(Charset.defaultCharset()))
// save encrypted password & init vector in sharedPreferences
val encryptedPassword = Base64.encodeToString(encryptedBytes, Base64.DEFAULT)
val iv = Base64.encodeToString(cipher.iv, Base64.DEFAULT)
sp.edit()
.putString(Constants.ENCRYPTED_PWD, encryptedPassword)
.putString(Constants.INITIALIZATION_VECTOR, iv)
.apply()
finishLogin(data)
} else {
throw RuntimeException("CryptoObject or Cipher is null")
}
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
when (errorCode) {
BiometricConstants.ERROR_NEGATIVE_BUTTON -> {
sp.edit()
.putBoolean(Constants.DONT_REMIND_BIOMETRIC, true)
.apply()
// finish login normally
finishLogin(data)
}
else -> {
Toast.makeText(this@AuthActivity, errString, Toast.LENGTH_LONG).show()
setLoading(false)
}
}
}
}
inner class DecryptCallback : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
setLoading(true)
val cipher: Cipher? = result.cryptoObject?.cipher
if (cipher != null) {
val encryptedPassword: String? = sp.getString(Constants.ENCRYPTED_PWD, null)
if (encryptedPassword != null) {
// decrypt the password
val encryptedBytes: ByteArray = Base64.decode(encryptedPassword, Base64.DEFAULT)
val decryptedBytes: ByteArray = cipher.doFinal(encryptedBytes)
val password = String(decryptedBytes, Charset.defaultCharset())
// do login
val username: String? = sp.getString(Constants.USERNAME, null)
if (username != null) {
viewModel.login(username, password).observe(this@AuthActivity) { res ->
when {
res.isSuccess() -> {
val data: LoginData = res.data!!
finishLogin(data)
}
res.isLoading() -> {
setLoading(true)
}
else -> {
val msg: String = when (res.error!!) {
NetworkError.SERVER_UNREACHABLE -> getString(R.string.networkerror_server_unreachable)
NetworkError.USERNAME_PASSWORD_WRONG -> getString(R.string.networkerror_username_pwd_wrong)
NetworkError.TIMEOUT -> getString(R.string.networkerror_timeout)
else -> getString(R.string.networkerror_unexpected)
}
displaySnackbar(msg)
setLoading(false)
}
}
}
} else {
throw RuntimeException("Username is null")
}
} else {
throw RuntimeException("Encrypted password was not found")
}
} else {
throw RuntimeException("CryptoObject or Cipher is null")
}
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
if (errorCode == BiometricConstants.ERROR_NEGATIVE_BUTTON) {
decryptPrompt.cancelAuthentication()
} else if (errorCode != BiometricConstants.ERROR_USER_CANCELED) {
Toast.makeText(this@AuthActivity, errString, Toast.LENGTH_LONG).show()
}
}
}
companion object {
private val TAG = AuthActivity::class.java.simpleName
}
}
| 0 | Kotlin | 0 | 0 | be33da0b3fe027a85ea301a784b0e6605b0bb3ac | 16,362 | RoarFit-Android | Apache License 2.0 |
apollo-integration/src/test/java/com/apollographql/apollo/ApolloCancelCallTest.kt | apollostack | 69,469,299 | false | null | package com.apollographql.apollo
import com.apollographql.apollo.Utils.immediateExecutor
import com.apollographql.apollo.Utils.immediateExecutorService
import com.apollographql.apollo.Utils.readFileToString
import com.apollographql.apollo.api.Input.Companion.fromNullable
import com.apollographql.apollo.api.Response
import com.apollographql.apollo.cache.http.ApolloHttpCache
import com.apollographql.apollo.cache.http.DiskLruHttpCacheStore
import com.apollographql.apollo.exception.ApolloCanceledException
import com.apollographql.apollo.exception.ApolloException
import com.apollographql.apollo.integration.normalizer.EpisodeHeroNameQuery
import com.apollographql.apollo.integration.normalizer.type.Episode
import com.google.common.truth.Truth
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import kotlin.test.fail
class ApolloCancelCallTest {
private lateinit var apolloClient: ApolloClient
private lateinit var cacheStore: MockHttpCacheStore
@get:Rule
val server = MockWebServer()
@Before
fun setup() {
cacheStore = MockHttpCacheStore()
cacheStore.delegate = DiskLruHttpCacheStore(InMemoryFileSystem(), File("/cache/"), Int.MAX_VALUE.toLong())
val okHttpClient = OkHttpClient.Builder()
.dispatcher(Dispatcher(immediateExecutorService()))
.build()
apolloClient = ApolloClient.builder()
.serverUrl(server.url("/"))
.okHttpClient(okHttpClient)
.httpCache(ApolloHttpCache(cacheStore, null))
.build()
}
class TestableCallback<T> : ApolloCall.Callback<T>() {
val lock = Object()
var completed = false
val responses = mutableListOf<Response<T>>()
val errors = mutableListOf<ApolloException>()
override fun onResponse(response: Response<T>) {
synchronized(lock) {
responses.add(response)
}
}
override fun onFailure(e: ApolloException) {
synchronized(lock) {
errors.add(e)
// Runtime doesn't send the COMPLETED status event
completed = true
lock.notifyAll()
}
}
override fun onStatusEvent(event: ApolloCall.StatusEvent) {
super.onStatusEvent(event)
if (event == ApolloCall.StatusEvent.COMPLETED) {
synchronized(lock) {
completed = true
lock.notifyAll()
}
}
}
fun waitForCompletion(timeoutDuration: Long, unit: TimeUnit) {
val start = System.currentTimeMillis()
while (true) {
val timeoutMillis = TimeUnit.MILLISECONDS.convert(timeoutDuration, unit) - (System.currentTimeMillis() - start)
if (timeoutMillis < 0) {
throw TimeoutException("Timeout reached")
}
if (completed) {
break
}
synchronized(lock) {
try {
lock.wait(timeoutMillis)
} catch (e: InterruptedException) {
}
}
}
}
}
class TestablePrefetchCallback : ApolloPrefetch.Callback() {
val lock = Object()
var completed = false
val errors = mutableListOf<ApolloException>()
override fun onFailure(e: ApolloException) {
synchronized(lock) {
errors.add(e)
// Runtime doesn't send the COMPLETED status event
completed = true
lock.notifyAll()
}
}
override fun onSuccess() {
synchronized(lock) {
completed = true
lock.notifyAll()
}
}
fun waitForCompletion(timeoutDuration: Long, unit: TimeUnit) {
val start = System.currentTimeMillis()
while (true) {
val timeoutMillis = TimeUnit.MILLISECONDS.convert(timeoutDuration, unit) - (System.currentTimeMillis() - start)
if (timeoutMillis < 0) {
throw TimeoutException("Timeout reached")
}
if (completed) {
break
}
synchronized(lock) {
try {
lock.wait(timeoutMillis)
} catch (e: InterruptedException) {
}
}
}
}
}
@Test
@Throws(Exception::class)
fun cancelCallBeforeEnqueueCanceledException() {
server.enqueue(mockResponse("EpisodeHeroNameResponse.json"))
val call: ApolloCall<EpisodeHeroNameQuery.Data> = apolloClient.query(EpisodeHeroNameQuery(fromNullable(Episode.EMPIRE)))
val callback = TestableCallback<EpisodeHeroNameQuery.Data>()
call.cancel()
call.enqueue(callback)
callback.waitForCompletion(1, TimeUnit.SECONDS)
Truth.assertThat(callback.responses.size).isEqualTo(0)
Truth.assertThat(callback.errors.size).isEqualTo(1)
Truth.assertThat(callback.errors[0]).isInstanceOf(ApolloCanceledException::class.java)
}
@Test
@Throws(Exception::class)
fun cancelCallAfterEnqueueNoCallback() {
val okHttpClient = OkHttpClient.Builder()
.dispatcher(Dispatcher(immediateExecutorService()))
.build()
apolloClient = ApolloClient.builder()
.serverUrl(server.url("/"))
.okHttpClient(okHttpClient)
.httpCache(ApolloHttpCache(cacheStore, null))
.build()
server.enqueue(mockResponse("EpisodeHeroNameResponse.json").setHeadersDelay(500, TimeUnit.MILLISECONDS))
val call: ApolloCall<EpisodeHeroNameQuery.Data> = apolloClient.query(EpisodeHeroNameQuery(fromNullable(Episode.EMPIRE)))
val callback = TestableCallback<EpisodeHeroNameQuery.Data>()
call.enqueue(callback)
call.cancel()
try {
callback.waitForCompletion(1, TimeUnit.SECONDS)
fail("TimeoutException expected")
} catch (e: TimeoutException) {
}
Truth.assertThat(callback.responses.size).isEqualTo(0)
Truth.assertThat(callback.errors.size).isEqualTo(0)
}
@Test
@Throws(Exception::class)
fun cancelPrefetchBeforeEnqueueCanceledException() {
server.enqueue(mockResponse("EpisodeHeroNameResponse.json"))
val call = apolloClient.prefetch(EpisodeHeroNameQuery(fromNullable(Episode.EMPIRE)))
val callback = TestablePrefetchCallback()
call.cancel()
call.enqueue(callback)
callback.waitForCompletion(1, TimeUnit.SECONDS)
Truth.assertThat(callback.errors.size).isEqualTo(1)
Truth.assertThat(callback.errors[0]).isInstanceOf(ApolloCanceledException::class.java)
}
@Test
@Throws(Exception::class)
fun cancelPrefetchAfterEnqueueNoCallback() {
server.enqueue(mockResponse("EpisodeHeroNameResponse.json").setHeadersDelay(500, TimeUnit.MILLISECONDS))
val call = apolloClient.prefetch(EpisodeHeroNameQuery(fromNullable(Episode.EMPIRE)))
val callback = TestablePrefetchCallback()
call.enqueue(callback)
call.cancel()
try {
callback.waitForCompletion(1, TimeUnit.SECONDS)
fail("TimeoutException expected")
} catch (e: TimeoutException) {
}
Truth.assertThat(callback.errors.size).isEqualTo(0)
}
@Throws(IOException::class)
private fun mockResponse(fileName: String): MockResponse {
return MockResponse().setChunkedBody(readFileToString(javaClass, "/$fileName"), 32)
}
} | 22 | null | 531 | 2,897 | f16ef0f4020af7a07c200f0fdcf1dac977d63637 | 7,205 | apollo-android | MIT License |
solar/src/main/java/com/chiksmedina/solar/lineduotone/videoaudiosound/UploadTrack2.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.lineduotone.videoaudiosound
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.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.lineduotone.VideoAudioSoundGroup
val VideoAudioSoundGroup.UploadTrack2: ImageVector
get() {
if (_uploadTrack2 != null) {
return _uploadTrack2!!
}
_uploadTrack2 = Builder(
name = "UploadTrack2", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(13.0f, 15.0f)
verticalLineTo(11.0f)
verticalLineTo(7.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(11.0f, 15.0f)
moveToRelative(-2.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, true, 4.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, true, -4.0f, 0.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(16.0f, 10.0f)
curveTo(14.3431f, 10.0f, 13.0f, 8.6568f, 13.0f, 7.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(18.0f, 22.0f)
verticalLineTo(15.0f)
moveTo(18.0f, 15.0f)
lineTo(20.5f, 17.5f)
moveTo(18.0f, 15.0f)
lineTo(15.5f, 17.5f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 1.5f, strokeLineCap =
Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(12.0f, 12.0f)
moveToRelative(-10.0f, 0.0f)
arcToRelative(10.0f, 10.0f, 0.0f, true, true, 20.0f, 0.0f)
arcToRelative(10.0f, 10.0f, 0.0f, true, true, -20.0f, 0.0f)
}
}
.build()
return _uploadTrack2!!
}
private var _uploadTrack2: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 3,584 | SolarIconSetAndroid | MIT License |
http4k-multipart/src/test/kotlin/org/http4k/lens/MultipartFormTest.kt | http4k | 86,003,479 | false | null | package org.http4k.lens
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.hasSize
import com.natpryce.hamkrest.isEmpty
import com.natpryce.hamkrest.throws
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion
import org.http4k.core.ContentType.Companion.MultipartFormWithBoundary
import org.http4k.core.ContentType.Companion.MultipartMixedWithBoundary
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.with
import org.http4k.lens.Validator.Feedback
import org.http4k.lens.Validator.Strict
import org.http4k.multipart.DiskLocation
import org.http4k.testing.ApprovalTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.nio.file.Files
private const val DEFAULT_BOUNDARY = "hello"
@ExtendWith(ApprovalTest::class)
class MultipartFormTest {
private val emptyRequest = Request(GET, "")
private val stringRequiredField = MultipartFormField.string().required("hello")
private val intRequiredField = MultipartFormField.string().int().required("another")
private val fieldWithHeaders = MultipartFormField.required("fieldWithHeaders")
private val requiredFile = MultipartFormFile.required("file")
private val message = javaClass.getResourceAsStream("fullMessage.txt")!!.reader().use { it.readText() }
private fun validFile() = MultipartFormFile("hello.txt", ContentType.TEXT_HTML, "bits".byteInputStream())
@Test
fun `multipart form serialized into request`() {
val populatedRequest = emptyRequest.with(
multipartFormLens(Strict, ::MultipartMixedWithBoundary) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile(),
fieldWithHeaders of MultipartFormField(
"someValue",
listOf("MyHeader" to "myHeaderValue")
)
)
)
assertThat(populatedRequest.toMessage().replace("\r\n", "\n"), equalTo(message.replace("\r\n", "\n")))
}
@Test
fun `multipart form blows up if not correct content type`() {
val request = emptyRequest.with(
multipartFormLens(Strict) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile()
)
).replaceHeader("Content-Type", "unknown; boundary=hello")
assertThat({
multipartFormLens(Strict)(request)
}, throws(lensFailureWith<Any?>(Unsupported(Header.CONTENT_TYPE.meta), overallType = Failure.Type.Unsupported)))
}
@Test
fun `multipart form extracts ok form values`() {
val request = emptyRequest.with(
multipartFormLens(Strict) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile()
)
)
val expected = MultipartForm(
mapOf(
"hello" to listOf(MultipartFormField("world")),
"another" to listOf(MultipartFormField("123"))
),
mapOf("file" to listOf(validFile()))
)
assertThat(multipartFormLens(Strict)(request), equalTo(expected))
}
@Test
fun `feedback multipart form extracts ok form values and errors`() {
val request = emptyRequest.with(
multipartFormLens(Feedback) of MultipartForm().with(
intRequiredField of 123,
requiredFile of validFile()
)
)
val requiredString = MultipartFormField.string().required("hello")
assertThat(
multipartFormLens(Feedback)(request), equalTo(
MultipartForm(
mapOf("another" to listOf(MultipartFormField("123"))),
mapOf("file" to listOf(validFile())),
listOf(Missing(requiredString.meta))
)
)
)
}
@Test
fun `strict multipart form blows up with invalid form values`() {
val intStringField = MultipartFormField.string().required("another")
val request = emptyRequest.with(
Body.multipartForm(
Strict,
stringRequiredField,
intStringField,
requiredFile,
defaultBoundary = DEFAULT_BOUNDARY,
contentTypeFn = ::MultipartFormWithBoundary
).toLens() of
MultipartForm().with(
stringRequiredField of "hello",
intStringField of "world",
requiredFile of validFile()
)
)
assertThat(
{ multipartFormLens(Strict)(request) },
throws(lensFailureWith<Any?>(Invalid(intRequiredField.meta), overallType = Failure.Type.Invalid))
)
}
@Test
fun `can set multiple values on a form`() {
val stringField = MultipartFormField.string().required("hello")
val intField = MultipartFormField.string().int().required("another")
val populated = MultipartForm()
.with(
stringField of "world",
intField of 123
)
assertThat(stringField(populated), equalTo("world"))
assertThat(intField(populated), equalTo(123))
}
private fun multipartFormLens(
validator: Validator,
contentTypeFn: (String) -> ContentType = Companion::MultipartFormWithBoundary
) = Body.multipartForm(
validator,
stringRequiredField,
intRequiredField,
requiredFile,
defaultBoundary = DEFAULT_BOUNDARY,
contentTypeFn = contentTypeFn
).toLens()
@Test
fun `backing disk location deleted after close`() {
val tempDir = Files.createTempDirectory("http4k-override").toFile().apply { deleteOnExit() }
val lens = Body.multipartForm(Strict, diskThreshold = 1, getDiskLocation = { DiskLocation.Temp(tempDir) }).toLens()
val request = emptyRequest.with(
lens of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile()
)
)
assertThat(tempDir.listFiles()!!.toList(), isEmpty)
lens(request).use {
assertThat(tempDir.listFiles()!!.toList(), hasSize(equalTo(3)))
}
assertThat(tempDir.listFiles(), absent())
}
}
| 34 | null | 250 | 2,615 | 7ad276aa9c48552a115a59178839477f34d486b1 | 6,719 | http4k | Apache License 2.0 |
ychat/src/commonMain/kotlin/co/yml/ychat/domain/mapper/ChatCompletionsMapper.kt | yml-org | 590,561,356 | false | null | package co.yml.ychat.domain.mapper
import co.yml.ychat.data.dto.ChatCompletionParamsDto
import co.yml.ychat.data.dto.ChatCompletionsDto
import co.yml.ychat.data.dto.ChatMessageDto
import co.yml.ychat.domain.model.ChatCompletionsParams
import co.yml.ychat.domain.model.ChatMessage
internal fun ChatCompletionsDto.toChatMessages(): List<ChatMessage> {
return this.choices.map {
ChatMessage(it.message.role, it.message.content)
}
}
internal fun ChatCompletionsParams.toChatCompletionParamsDto(): ChatCompletionParamsDto {
return ChatCompletionParamsDto(
model = this.model,
messages = this.messages.map { ChatMessageDto(it.role, it.content) },
maxTokens = this.maxTokens,
temperature = this.temperature,
topP = this.topP,
maxResults = this.maxResults,
)
}
| 1 | Kotlin | 2 | 72 | 0da7ababedec465eefcdf3608b6c3e8f6dc36c16 | 828 | ychat | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.