path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/github/igorperikov/mightywatcher/service/OutputFormatter.kt | IgorPerikov | 100,801,260 | false | {"Kotlin": 37720, "Shell": 405, "Dockerfile": 273} | package com.github.igorperikov.mightywatcher.service
import com.github.igorperikov.mightywatcher.entity.IssueLine
import com.github.igorperikov.mightywatcher.entity.ResultLine
import com.github.igorperikov.mightywatcher.entity.TimestampLine
import j2html.TagCreator
import j2html.attributes.Attr
import j2html.tags.ContainerTag
interface OutputFormatter {
fun format(lines: List<ResultLine>): String
}
class PlainTextOutputFormatter : OutputFormatter {
override fun format(lines: List<ResultLine>): String {
return lines.joinToString("\r\n")
}
}
class HTMLOutputFormatter : OutputFormatter {
override fun format(lines: List<ResultLine>): String {
val outputTags: List<ContainerTag> = lines.map {
when (it) {
is TimestampLine -> TagCreator.tr(
TagCreator.td(TagCreator.b(it.toString()))
.withStyle("text-align:center")
.attr(Attr.COLSPAN, 2)
)
is IssueLine -> TagCreator.tr(
TagCreator.td(it.repoName).withClass("col-xs-4"),
TagCreator.td(TagCreator.a(it.title).withHref(it.htmlUrl)).withClass("col-xs-8")
)
}
}
return TagCreator.html(
TagCreator.head(
TagCreator.title("Issues report"),
TagCreator.link()
.withHref("https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css")
.withRel("stylesheet")
),
TagCreator.body(
TagCreator.h3("Issues report").withStyle("text-align: center"),
TagCreator.br(),
TagCreator.table(
*outputTags.toTypedArray()
).withClass("table table-striped")
)
).renderFormatted()
}
}
| 7 | Kotlin | 7 | 46 | 082791c2ac776e2b60c6037817ce034230959301 | 1,886 | mighty-watcher | MIT License |
scripts/Day13.kts | matthewm101 | 573,325,687 | false | {"Kotlin": 63435} | import java.io.File
import kotlin.math.max
sealed class Data {
data class Packet(val data: List<Data>) : Data(), Comparable<Packet> {
override fun toString() = data.joinToString(separator = ",", prefix = "[", postfix = "]") { it.toString() }
override fun compareTo(other: Packet): Int {
for (i in 0 until max(data.size, other.data.size)) {
if (i >= data.size) return -1
if (i >= other.data.size) return 1
val e1 = data[i]
val e2 = other.data[i]
when (e1) {
is Num -> when (e2) {
is Num -> if (e1.num != e2.num) return e1.num - e2.num
is Packet -> {
val result = Packet(listOf(e1)).compareTo(e2)
if (result != 0) return result
}
}
is Packet -> when (e2) {
is Num -> {
val result = e1.compareTo(Packet(listOf(e2)))
if (result != 0) return result
}
is Packet -> {
val result = e1.compareTo(e2)
if (result != 0) return result
}
}
}
}
return 0
}
}
data class Num(val num: Int) : Data(), Comparable<Num> {
override fun toString() = num.toString()
override fun compareTo(other: Num) = num - other.num
}
}
sealed class Token {
object In: Token()
object Out: Token()
data class Num(val num: Int): Token()
}
fun parsePacket(line: String): Data.Packet? {
val tokens: List<Token> = line.fold<List<Token?>>(listOf()) {
prev, c -> when(c) {
'[' -> prev.plus(Token.In)
']' -> prev.plus(Token.Out)
',' -> prev.plus(null)
else -> if (prev.last() != null && prev.last() is Token.Num)
prev.dropLast(1).plus(Token.Num((prev.last() as Token.Num).num * 10 + c.digitToInt()))
else prev.plus(Token.Num(c.digitToInt()))
}
}.filterNotNull()
val packetStack: MutableList<MutableList<Data>> = mutableListOf()
var finalPacket: Data.Packet? = null
tokens.forEach {
when(it) {
is Token.In -> packetStack.add(mutableListOf())
is Token.Out -> {
val p = packetStack.removeLast()
if (packetStack.isEmpty()) finalPacket = Data.Packet(p)
else packetStack.last().add(Data.Packet(p))
}
is Token.Num -> packetStack.last().add(Data.Num(it.num))
}
}
return finalPacket
}
data class PacketPair(val left: Data.Packet, val right: Data.Packet) {
fun ordered() = left < right
}
val packets = File("../inputs/13.txt").readLines().mapNotNull { parsePacket(it) }
val packetPairs = packets.chunked(2).map { PacketPair(it[0], it[1]) }
val indexSum = packetPairs.mapIndexed{ index, packetPair -> if (packetPair.ordered()) index + 1 else 0 }.sum()
println("There sum of the indices of the ordered pairs is $indexSum.")
val divider1 = Data.Packet(listOf(Data.Packet(listOf(Data.Num(2)))))
val divider2 = Data.Packet(listOf(Data.Packet(listOf(Data.Num(6)))))
val sortedPackets = packets.plus(divider1).plus(divider2).sorted()
val index1 = sortedPackets.indexOf(divider1)
val index2 = sortedPackets.indexOf(divider2)
println("The product of the indices of the divider packets is ${(index1 + 1) * (index2 + 1)}.") | 0 | Kotlin | 0 | 0 | bbd3cf6868936a9ee03c6783d8b2d02a08fbce85 | 3,612 | adventofcode2022 | MIT License |
app/src/main/java/com/mksoftware101/notes/features/noteList/ui/extensions/Extensions.kt | mksoftware101 | 357,660,329 | false | null | package com.mksoftware101.notes.features.noteList.ui.extensions | 0 | Kotlin | 0 | 0 | 0792a1b68d02229082d3faf6c984f9003822ce19 | 63 | yetanothernotes | Apache License 2.0 |
app/src/main/java/com/github/braillesystems/learnbraille/ui/screens/AbstractFragmentWithHelp.kt | braille-systems | 246,795,546 | false | null | package com.github.braillesystems.learnbraille.ui.screens
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import com.github.braillesystems.learnbraille.R
import com.github.braillesystems.learnbraille.ui.screens.help.HelpFragmentDirections
import com.github.braillesystems.learnbraille.utils.navigate
import timber.log.Timber
typealias HelpMsgId = Int
abstract class AbstractFragmentWithHelp(private val helpMsgId: HelpMsgId) : AbstractFragment() {
override fun iniHelper() {
setHasOptionsMenu(true)
}
protected open val helpMsg: String
get() = getString(helpMsgId)
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.help_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem) =
super
.onOptionsItemSelected(item)
.also { if (item.itemId == R.id.help) navigateToHelp() }
protected fun navigateToHelp() {
navigateToHelp(helpMsg)
}
private fun navigateToHelp(helpMsg: String) {
Timber.i("Navigate to help")
val action = HelpFragmentDirections.actionGlobalHelpFragment()
action.helpMessage = helpMsg
navigate(action)
}
}
| 35 | Kotlin | 3 | 9 | e7e41e88d814aa4f7dd118ed023cdd6f955d53e5 | 1,255 | learn-braille | Apache License 2.0 |
buildSrc/src/main/java/Library.kt | squaredcandy | 422,740,618 | false | {"Kotlin": 99379} | object Library {
object Android {
const val ApplicationId = "com.squaredcandy.lunar"
const val MinCompileVersion = 23
const val CompileVersion = 31
const val TargetVersion = 30
const val VersionCode = 1
const val VersionName = "1.0"
const val GradleVersion = "7.1.0-beta03"
const val JavaVersion = "11"
const val UseCompose = true
const val ApplicationPlugin = "com.android.application"
const val LibraryPlugin = "com.android.library"
}
object Kotlin {
const val LibraryVersion = "1.5.31"
const val AndroidPlugin = "kotlin-android"
object Coroutines {
const val Version = "1.5.2"
const val CoreArtifact = "org.jetbrains.kotlinx:kotlinx-coroutines-core:$Version"
const val AndroidArtifact =
"org.jetbrains.kotlinx:kotlinx-coroutines-android:$Version"
}
}
object AndroidX {
object Activity {
const val Version = "1.3.1"
const val KtxArtifact = "androidx.activity:activity-ktx:$Version"
const val ComposeArtifact = "androidx.activity:activity-compose:$Version"
}
object AppCompat {
const val Version = "1.4.0-rc01"
const val Artifact = "androidx.appcompat:appcompat:$Version"
}
object Compose {
const val Version = "1.1.0-beta01"
const val Material3Version = "1.0.0-alpha01"
const val AnimationArtifact = "androidx.compose.animation:animation:$Version"
const val CompilerArtifact = "androidx.compose.compiler:compiler:$Version"
const val FoundationArtifact = "androidx.compose.foundation:foundation:$Version"
const val MaterialArtifact = "androidx.compose.material:material:$Version"
const val Material3Artifact = "androidx.compose.material3:material3:$Material3Version"
const val MaterialIconsArtifact =
"androidx.compose.material:material-icons-extended:$Version"
const val RuntimeArtifact = "androidx.compose.runtime:runtime:$Version"
const val UiArtifact = "androidx.compose.ui:ui:$Version"
const val UiToolingArtifact = "androidx.compose.ui:ui-tooling:$Version"
const val UiToolingPreviewArtifact =
"androidx.compose.ui:ui-tooling-preview:$Version"
}
object Core {
const val Version = "1.7.0"
const val KtxArtifact = "androidx.core:core-ktx:$Version"
}
object Splashscreen {
const val Version = "1.0.0-alpha01"
const val Artifact = "androidx.core:core-splashscreen:$Version"
}
}
object Material {
const val Version = "1.5.0-alpha05"
const val Artifact = "com.google.android.material:material:$Version"
}
object ComposeDialog {
const val Version = "0.6.1"
const val DateTimeArtifact =
"io.github.vanpra.compose-material-dialogs:datetime:$Version"
}
object Maven {
const val Publish = "maven-publish"
}
} | 0 | Kotlin | 0 | 0 | ed5674e11b1a27281b37de73237869ab1c9d8bed | 3,159 | Lunar | MIT License |
tools/weixin/src/main/kotlin/top/bettercode/summer/tools/weixin/support/offiaccount/entity/CachedValue.kt | top-bettercode | 387,652,015 | false | null | package top.bettercode.summer.tools.weixin.support.offiaccount.entity
import java.time.LocalDateTime
/**
*
* @author Peter Wu
*/
data class CachedValue(val value: String, val expiresIn: LocalDateTime) {
val expired: Boolean by lazy { expiresIn <= LocalDateTime.now() }
} | 0 | Kotlin | 0 | 2 | 23ba7a8c61b0b7b7eb95926fc45f1f9127e443ea | 280 | summer | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/customerprofiles/CfnDomainDomainStatsPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.customerprofiles
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Number
import software.amazon.awscdk.services.customerprofiles.CfnDomain
/**
* Usage-specific statistics about the domain.
*
* 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.customerprofiles.*;
* DomainStatsProperty domainStatsProperty = DomainStatsProperty.builder()
* .meteringProfileCount(123)
* .objectCount(123)
* .profileCount(123)
* .totalSize(123)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-customerprofiles-domain-domainstats.html)
*/
@CdkDslMarker
public class CfnDomainDomainStatsPropertyDsl {
private val cdkBuilder: CfnDomain.DomainStatsProperty.Builder =
CfnDomain.DomainStatsProperty.builder()
/**
* @param meteringProfileCount The number of profiles that you are currently paying for in the
* domain. If you have more than 100 objects associated with a single profile, that profile
* counts as two profiles. If you have more than 200 objects, that profile counts as three,
* and so on.
*/
public fun meteringProfileCount(meteringProfileCount: Number) {
cdkBuilder.meteringProfileCount(meteringProfileCount)
}
/** @param objectCount The total number of objects in domain. */
public fun objectCount(objectCount: Number) {
cdkBuilder.objectCount(objectCount)
}
/** @param profileCount The total number of profiles currently in the domain. */
public fun profileCount(profileCount: Number) {
cdkBuilder.profileCount(profileCount)
}
/** @param totalSize The total size, in bytes, of all objects in the domain. */
public fun totalSize(totalSize: Number) {
cdkBuilder.totalSize(totalSize)
}
public fun build(): CfnDomain.DomainStatsProperty = cdkBuilder.build()
}
| 0 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 2,273 | awscdk-dsl-kotlin | Apache License 2.0 |
idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleRunner.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2017 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.console
import com.intellij.execution.Executor
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.console.ConsoleExecuteAction
import com.intellij.execution.console.LanguageConsoleBuilder
import com.intellij.execution.console.LanguageConsoleView
import com.intellij.execution.console.ProcessBackedConsoleExecuteActionHandler
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.runners.AbstractConsoleRunnerWithHistory
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.CommonShortcuts
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.PsiFileFactoryImpl
import com.intellij.testFramework.LightVirtualFile
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.console.actions.BuildAndRestartConsoleAction
import org.jetbrains.kotlin.console.actions.KtExecuteCommandAction
import org.jetbrains.kotlin.console.gutter.ConsoleGutterContentProvider
import org.jetbrains.kotlin.console.gutter.ConsoleIndicatorRenderer
import org.jetbrains.kotlin.console.gutter.IconWithTooltip
import org.jetbrains.kotlin.console.gutter.ReplIcons
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.caches.resolve.ModuleTestSourceInfo
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptor
import org.jetbrains.kotlin.idea.project.KOTLIN_CONSOLE_KEY
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.parsing.KotlinParserDefinition
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtScript
import org.jetbrains.kotlin.psi.moduleInfo
import org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyScriptDescriptor
import org.jetbrains.kotlin.resolve.repl.ReplState
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider
import java.awt.Color
import java.awt.Font
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.properties.Delegates
private val KOTLIN_SHELL_EXECUTE_ACTION_ID = "KotlinShellExecute"
class KotlinConsoleRunner(
val module: Module,
private val cmdLine: GeneralCommandLine,
internal val previousCompilationFailed: Boolean,
myProject: Project,
title: String,
path: String?
) : AbstractConsoleRunnerWithHistory<LanguageConsoleView>(myProject, title, path) {
private val replState = ReplState()
private val consoleTerminated = CountDownLatch(1)
override fun finishConsole() {
KotlinConsoleKeeper.getInstance(project).removeConsole(consoleView.virtualFile)
KotlinScriptDefinitionProvider.getInstance(project)!!.removeScriptDefinition(consoleScriptDefinition)
if (ApplicationManager.getApplication().isUnitTestMode) {
consoleTerminated.countDown()
// Ignore super with myConsoleView.setEditable(false)
return
}
super.finishConsole()
}
val commandHistory = CommandHistory()
var isReadLineMode: Boolean = false
set(value) {
if (value)
changeConsoleEditorIndicator(ReplIcons.EDITOR_READLINE_INDICATOR)
else
changeConsoleEditorIndicator(ReplIcons.EDITOR_INDICATOR)
field = value
}
fun changeConsoleEditorIndicator(newIconWithTooltip: IconWithTooltip) = WriteCommandAction.runWriteCommandAction(project) {
consoleEditorHighlighter.gutterIconRenderer = ConsoleIndicatorRenderer(newIconWithTooltip)
}
private var consoleEditorHighlighter by Delegates.notNull<RangeHighlighter>()
private var disposableDescriptor by Delegates.notNull<RunContentDescriptor>()
val executor = CommandExecutor(this)
var compilerHelper: ConsoleCompilerHelper by Delegates.notNull()
private val consoleScriptDefinition = object : KotlinScriptDefinition(Any::class) {
override val name = "Kotlin REPL"
override fun isScript(fileName: String): Boolean {
return fileName == consoleView.virtualFile.name
}
override fun getScriptName(script: KtScript) = Name.identifier("REPL")
}
override fun createProcess() = cmdLine.createProcess()
override fun createConsoleView(): LanguageConsoleView? {
val builder = LanguageConsoleBuilder()
val consoleView = builder.gutterContentProvider(ConsoleGutterContentProvider()).build(project, KotlinLanguage.INSTANCE)
consoleView.virtualFile.putUserData(KOTLIN_CONSOLE_KEY, true)
consoleView.prompt = null
val consoleEditor = consoleView.consoleEditor
setupPlaceholder(consoleEditor)
val historyKeyListener = HistoryKeyListener(module.project, consoleEditor, commandHistory)
consoleEditor.contentComponent.addKeyListener(historyKeyListener)
commandHistory.listeners.add(historyKeyListener)
val executeAction = KtExecuteCommandAction(consoleView.virtualFile)
executeAction.registerCustomShortcutSet(CommonShortcuts.CTRL_ENTER, consoleView.consoleEditor.component)
KotlinScriptDefinitionProvider.getInstance(project)!!.addScriptDefinition(consoleScriptDefinition)
enableCompletion(consoleView)
return consoleView
}
private fun enableCompletion(consoleView: LanguageConsoleView) {
val consoleKtFile = PsiManager.getInstance(project).findFile(consoleView.virtualFile) as? KtFile ?: return
consoleKtFile.moduleInfo = ModuleTestSourceInfo(module)
}
override fun createProcessHandler(process: Process): OSProcessHandler {
val processHandler = ReplOutputHandler(
this,
process,
cmdLine.commandLineString
)
val consoleFile = consoleView.virtualFile
val keeper = KotlinConsoleKeeper.getInstance(project)
keeper.putVirtualFileToConsole(consoleFile, this)
return processHandler
}
override fun createExecuteActionHandler() = object : ProcessBackedConsoleExecuteActionHandler(processHandler, false) {
override fun runExecuteAction(consoleView: LanguageConsoleView) = executor.executeCommand()
}
override fun fillToolBarActions(toolbarActions: DefaultActionGroup,
defaultExecutor: Executor,
contentDescriptor: RunContentDescriptor
): List<AnAction> {
disposableDescriptor = contentDescriptor
compilerHelper = ConsoleCompilerHelper(project, module, defaultExecutor, contentDescriptor)
val actionList = arrayListOf<AnAction>(
BuildAndRestartConsoleAction(this),
createConsoleExecAction(consoleExecuteActionHandler),
createCloseAction(defaultExecutor, contentDescriptor)
)
toolbarActions.addAll(actionList)
return actionList
}
override fun createConsoleExecAction(consoleExecuteActionHandler: ProcessBackedConsoleExecuteActionHandler)
= ConsoleExecuteAction(consoleView, consoleExecuteActionHandler, KOTLIN_SHELL_EXECUTE_ACTION_ID, consoleExecuteActionHandler)
override fun constructConsoleTitle(title: String) = "$title (in module ${module.name})"
private fun setupPlaceholder(editor: EditorEx) {
val executeCommandAction = ActionManager.getInstance().getAction(KOTLIN_SHELL_EXECUTE_ACTION_ID)
val executeCommandActionShortcutText = KeymapUtil.getFirstKeyboardShortcutText(executeCommandAction)
editor.setPlaceholder("<$executeCommandActionShortcutText> to execute")
editor.setShowPlaceholderWhenFocused(true)
val placeholderAttrs = TextAttributes()
placeholderAttrs.foregroundColor = ReplColors.PLACEHOLDER_COLOR
placeholderAttrs.fontType = Font.ITALIC
editor.setPlaceholderAttributes(placeholderAttrs)
}
fun setupGutters() {
fun configureEditorGutter(editor: EditorEx, color: Color, iconWithTooltip: IconWithTooltip): RangeHighlighter {
editor.settings.isLineMarkerAreaShown = true // hack to show gutter
editor.settings.isFoldingOutlineShown = true
editor.gutterComponentEx.setPaintBackground(true)
val editorColorScheme = editor.colorsScheme
editorColorScheme.setColor(EditorColors.GUTTER_BACKGROUND, color)
editor.colorsScheme = editorColorScheme
return addGutterIndicator(editor, iconWithTooltip)
}
val historyEditor = consoleView.historyViewer
val consoleEditor = consoleView.consoleEditor
configureEditorGutter(historyEditor, ReplColors.HISTORY_GUTTER_COLOR, ReplIcons.HISTORY_INDICATOR)
consoleEditorHighlighter = configureEditorGutter(consoleEditor, ReplColors.EDITOR_GUTTER_COLOR, ReplIcons.EDITOR_INDICATOR)
historyEditor.settings.isUseSoftWraps = true
historyEditor.settings.additionalLinesCount = 0
consoleEditor.settings.isCaretRowShown = true
consoleEditor.settings.additionalLinesCount = 2
}
fun addGutterIndicator(editor: EditorEx, iconWithTooltip: IconWithTooltip): RangeHighlighter {
val indicator = ConsoleIndicatorRenderer(iconWithTooltip)
val editorMarkup = editor.markupModel
val indicatorHighlighter = editorMarkup.addRangeHighlighter(
0, editor.document.textLength, HighlighterLayer.LAST, null, HighlighterTargetArea.LINES_IN_RANGE
)
return indicatorHighlighter.apply { gutterIconRenderer = indicator }
}
@TestOnly fun dispose() {
processHandler.destroyProcess()
consoleTerminated.await(1, TimeUnit.SECONDS)
Disposer.dispose(disposableDescriptor)
}
fun successfulLine(text: String) {
runReadAction {
val lineNumber = replState.successfulLinesCount + 1
val virtualFile =
LightVirtualFile("line$lineNumber${KotlinParserDefinition.STD_SCRIPT_EXT}", KotlinLanguage.INSTANCE, text).apply {
charset = CharsetToolkit.UTF8_CHARSET
isWritable = false
}
val psiFile = (PsiFileFactory.getInstance(project) as PsiFileFactoryImpl).trySetupPsiForFile(virtualFile, KotlinLanguage.INSTANCE, true, false) as KtFile?
?: error("Failed to setup PSI for file:\n$text")
replState.submitLine(psiFile)
psiFile.moduleInfo = ModuleTestSourceInfo(module)
val scriptDescriptor = psiFile.script!!.resolveToDescriptor() as? LazyScriptDescriptor ?: error("Failed to analyze line:\n$text")
ForceResolveUtil.forceResolveAllContents(scriptDescriptor)
replState.lineSuccess(psiFile, scriptDescriptor)
replState.submitLine(consoleFile) // reset file scope customizer
}
}
val consoleFile: KtFile
get() {
val consoleFile = consoleView.virtualFile
return PsiManager.getInstance(project).findFile(consoleFile) as KtFile
}
} | 284 | null | 5162 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 12,705 | kotlin | Apache License 2.0 |
app/src/main/java/cc/sovellus/vrcaa/api/helper/StatusHelper.kt | Nyabsi | 745,635,224 | false | null | package cc.sovellus.vrcaa.api.helper
import androidx.compose.ui.graphics.Color
class StatusHelper {
enum class Status {
JoinMe,
Active,
AskMe,
Busy,
Offline;
companion object {
fun toColor(status: Status): Color {
return when (status) {
JoinMe -> Color(66, 201, 255)
Active -> Color(81, 229, 125)
AskMe -> Color(232, 130, 52)
Busy -> Color(91, 11, 11)
else -> Color.Gray
}
}
fun toString(status: Status): String {
return when (status) {
JoinMe -> "Join Me"
Active -> "Online"
AskMe -> "Ask Me"
Busy -> "Busy"
else -> "Offline"
}
}
}
}
companion object {
fun getStatusFromString(status: String): Status {
return when (status) {
"join me" -> Status.JoinMe
"active" -> Status.Active
"ask me" -> Status.AskMe
"busy" -> Status.Busy
else -> Status.Offline
}
}
}
} | 1 | null | 3 | 8 | 69b3be86a31fba1bfea5180c82117b49fe31f90e | 1,266 | VRCAA | Apache License 2.0 |
core/src/androidMain/kotlin/com/lhwdev/ktui/graphics/Path.kt | lhwdev | 220,774,525 | false | null | package com.lhwdev.ktui.graphics
import android.graphics.Path as APath
actual typealias FrameworkPath = APath
internal actual fun Path.toFrameworkPathInternal(): FrameworkPath {
TODO()
}
| 0 | Kotlin | 1 | 6 | d1af81f1e4f6c0660dd0557868738d8df50c4da6 | 192 | kt-ui | Apache License 2.0 |
html-textview/src/main/java/com/saka/android/htmltextview/utility/ThumbnailLoader.kt | sakacyber | 259,229,776 | false | {"Kotlin": 48447} | package com.saka.android.htmltextview.utility
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.URL
suspend fun String?.loadBitmap(
onPostExecute: (Bitmap?) -> Unit
) {
val url = this ?: return
var bitmap: Bitmap? = null
withContext(Dispatchers.IO) {
if (VideoLoader.isYoutubeFormat(url)) {
try {
val link =
URL("http://img.youtube.com/vi/${VideoLoader.getYouTubeId(url)}/0.jpg")
bitmap = BitmapFactory.decodeStream(link.openConnection().getInputStream())
} catch (ex: Exception) {
ex.printStackTrace()
}
} else {
var mediaMetadataRetriever: MediaMetadataRetriever? = null
try {
mediaMetadataRetriever = MediaMetadataRetriever()
mediaMetadataRetriever.setDataSource(url, HashMap())
bitmap = mediaMetadataRetriever.getFrameAtTime(
6_000_000,
MediaMetadataRetriever.OPTION_CLOSEST
)
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
mediaMetadataRetriever?.release()
}
}
}
onPostExecute.invoke(bitmap)
}
fun <R> CoroutineScope.executeAsyncTask(
onPreExecute: () -> Unit,
doInBackground: () -> R,
onPostExecute: (R) -> Unit
) = launch {
onPreExecute()
val result =
withContext(Dispatchers.IO) { // runs in background thread without blocking the Main Thread
doInBackground()
}
onPostExecute(result)
}
| 2 | Kotlin | 2 | 18 | 0672db02272811e47c6adb9804a51432ef04aca5 | 1,838 | html-textview | MIT License |
src/day16/day16.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day16
import readInput
import java.util.UUID
import kotlin.math.max
fun parse(input: List<String>): Pair<Map<String, Map<String, Int>>, Map<String, Int>> {
val rates = HashMap<String, Int>()
val graph = HashMap<String, MutableMap<String, Int>>()
// create connections based on input
for (line in input) {
val parts = line.split("Valve ", " has flow rate=", "; tunnels lead to valves ", "; tunnel leads to valve ")
val key = parts[1]
val rate = parts[2].toInt()
val children = parts[3].split(", ").toMutableSet()
rates[key] = rate
graph[key] = children.associateWith { 1 }.toMutableMap()
graph[key]!![key] = 0
}
// check if can change
fun HashMap<String, MutableMap<String, Int>>.getHelper(start: String, end: String): Int {
val values = get(start).orEmpty()
return values[end] ?: Int.MAX_VALUE
}
fun HashMap<String, MutableMap<String, Int>>.checkCondition(i: String, j: String, k: String): Boolean {
if (getHelper(i, k) == Int.MAX_VALUE || getHelper(k, j) == Int.MAX_VALUE) {
return false
}
return getHelper(i, j) > getHelper(i, k) + getHelper(k, j)
}
// find all paths for all nodes
val keys = graph.keys
for (k in keys) {
for (i in keys) {
for (j in keys) {
if (graph.checkCondition(i, j, k)) {
graph[i]!![j] = graph.getHelper(i, k) + graph.getHelper(k, j)
}
}
}
}
// remove all insignificant paths
val result = graph.filter { it.key == "AA" || rates.getOrDefault(it.key, 0) > 0 }
.map { parent -> parent.key to parent.value.filter { it.key != parent.key && rates.getOrDefault(it.key, 0) > 0 } }
.filter { it.second.isNotEmpty() }
.toMap()
return Pair(result, rates)
}
private fun helper(
grid: Map<String, Map<String, Int>>,
rates: Map<String, Int>,
actors: Set<Actor>,
toVisit: Set<String>,
time: Int
): Int {
fun handleNewDestination(actor: Actor, node: String): Pair<Int, Actor> {
val moveTime = grid[actor.node]!![node]!!
val pressure = rates[node]!!
val newTime = max(0, time - moveTime - 1)
val value = newTime * pressure
val newActor = Actor(actor.id, node, newTime)
return Pair(value, newActor)
}
if (time <= 0) return 0
var max = 0
val actor = actors.first { it.time >= time }
val otherActors = actors - actor
for (node in toVisit) {
val destination = handleNewDestination(actor, node)
val newVisited = HashSet(toVisit).apply {
remove(destination.second.node)
}
val newActors = mutableSetOf<Actor>().apply {
addAll(otherActors)
add(destination.second)
}
val nextTime = newActors.maxBy { it.time }.time
val tempValue = destination.first + helper(
grid, rates, newActors, newVisited, nextTime
)
max = tempValue.coerceAtLeast(max)
}
return max
}
data class Actor(
val id: UUID = UUID.randomUUID(),
val node: String,
val time: Int,
)
private fun part1(input: List<String>): Int {
val parsesInput = parse(input)
val toVisit = parsesInput.second.filter { it.value > 0 }.keys
val actors = setOf(Actor(node = "AA", time = 30))
return helper(parsesInput.first, parsesInput.second, actors, toVisit, time = 30)
}
private fun part2(input: List<String>): Int {
val parsesInput = parse(input)
val toVisit = parsesInput.second.filter { it.value > 0 }.keys
val actors = setOf(Actor(node = "AA", time = 26), Actor(node = "AA", time = 26))
return helper(parsesInput.first, parsesInput.second, actors, toVisit, time = 26)
}
fun main() {
val input = readInput("day16/input")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 3,941 | aoc-2022 | Apache License 2.0 |
app/src/main/java/com/stocksexchange/android/database/model/DatabaseDeposit.kt | nscoincommunity | 277,168,471 | true | {"Kotlin": 2814235} | package com.stocksexchange.android.database.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.stocksexchange.api.model.rest.Deposit
import com.stocksexchange.android.database.model.DatabaseDeposit.Companion.TABLE_NAME
/**
* A Room database model for the [Deposit] class.
*/
@Entity(tableName = TABLE_NAME)
data class DatabaseDeposit(
@PrimaryKey @ColumnInfo(name = ID) var id: Long,
@ColumnInfo(name = CURRENCY_ID) var currencyId: Int,
@ColumnInfo(name = CURRENCY_SYMBOL) var currencySymbol: String,
@ColumnInfo(name = AMOUNT) var amount: Double,
@ColumnInfo(name = FEE) var fee: Double,
@ColumnInfo(name = FEE_CURRENCY_ID) var feeCurrencyId: Int,
@ColumnInfo(name = FEE_CURRENCY_SYMBOL) var feeCurrencySymbol: String,
@ColumnInfo(name = STATUS_ID) var statusId: Int,
@ColumnInfo(name = STATUS) var status: String,
@ColumnInfo(name = STATUS_COLOR) var statusColor: String,
@ColumnInfo(name = PROTOCOL_ID) var protocolId: Int,
@ColumnInfo(name = TIMESTAMP) var timestamp: Long,
@ColumnInfo(name = TRANSACTION_EXPLORER_ID) var transactionExplorerId: String?,
@ColumnInfo(name = CONFIRMATIONS_STR) var confirmationsStr: String
) {
companion object {
const val TABLE_NAME = "deposits"
const val ID = "id"
const val CURRENCY_ID = "currency_id"
const val CURRENCY_SYMBOL = "currency_symbol"
const val AMOUNT = "amount"
const val FEE = "fee"
const val FEE_CURRENCY_ID = "fee_currency_id"
const val FEE_CURRENCY_SYMBOL = "fee_currency_symbol"
const val STATUS_ID = "status_id"
const val STATUS = "status"
const val STATUS_COLOR = "status_color"
const val PROTOCOL_ID = "protocol_id"
const val TIMESTAMP = "timestamp"
const val TRANSACTION_EXPLORER_ID = "transaction_explorer_id"
const val CONFIRMATIONS_STR = "confirmations_str"
}
constructor(): this(
id = -1L,
currencyId = -1,
currencySymbol = "",
amount = -1.0,
fee = -1.0,
feeCurrencyId = -1,
feeCurrencySymbol = "",
statusId = -1,
status = "",
statusColor = "",
protocolId = -1,
timestamp = -1L,
transactionExplorerId = null,
confirmationsStr = ""
)
} | 0 | null | 0 | 0 | 52766afab4f96506a2d9ed34bf3564b6de7af8c3 | 2,372 | Android-app | MIT License |
test_runner/src/test/kotlin/ftl/cli/firebase/test/IosCommandTest.kt | rashiq | 267,499,333 | true | {"Kotlin": 418227, "Java": 298969, "HTML": 277221, "JavaScript": 5357, "TypeScript": 4809, "Shell": 3046, "CSS": 537, "Go": 159} | package ftl.cli.firebase.test
import com.google.common.truth.Truth
import ftl.test.util.FlankTestRunner
import ftl.test.util.TestHelper.normalizeLineEnding
import org.junit.Rule
import org.junit.Test
import org.junit.contrib.java.lang.system.SystemOutRule
import org.junit.runner.RunWith
@RunWith(FlankTestRunner::class)
class IosCommandTest {
@Rule
@JvmField
val systemOutRule: SystemOutRule = SystemOutRule().enableLog().muteForSuccessfulTests()
@Test
fun androidCommandPrintsHelp() {
IosCommand().run()
val output = systemOutRule.log.normalizeLineEnding()
Truth.assertThat(output).startsWith(
"ios [COMMAND]\n" +
"Commands:\n" +
" run Run tests on Firebase Test Lab\n" +
" doctor Verifies flank firebase is setup correctly\n"
)
}
}
| 1 | Kotlin | 1 | 1 | bd6e444bb95f9b05a6a28755948acec459a81f70 | 861 | flank | MIT License |
app-android/src/main/java/org/mtransit/android/data/AgencyBaseProperties.kt | mtransitapps | 24,649,585 | false | null | package org.mtransit.android.data
import androidx.room.ColumnInfo
import androidx.room.Embedded
import androidx.room.Ignore
import com.google.android.gms.maps.model.LatLngBounds
import org.mtransit.android.commons.data.Area
import org.mtransit.android.data.IAgencyProperties.Companion.DEFAULT_LONG_VERSION_CODE
// all these properties are not dynamic: only change when module updated / data changed
data class AgencyBaseProperties(
@ColumnInfo(name = "id")
val id: String,
@ColumnInfo(name = "type")
override val type: DataSourceType,
@ColumnInfo(name = "short_name")
override val shortName: String, // sort
@ColumnInfo(name = "color_int")
override val colorInt: Int? = null,
@Embedded(prefix = "area")
override val area: Area, // nearby
@ColumnInfo(name = "pkg")
override val pkg: String,
@ColumnInfo(name = "long_version_code")
val longVersionCode: Long = DEFAULT_LONG_VERSION_CODE, // #onModulesUpdated
@ColumnInfo(name = "is_installed")
val isInstalled: Boolean = true, // #onModulesUpdated
@ColumnInfo(name = "is_enabled")
override val isEnabled: Boolean = true, // #onModulesUpdated
@ColumnInfo(name = "is_rts")
override val isRTS: Boolean = false,
@ColumnInfo(name = "logo")
override val logo: JPaths? = null,
@ColumnInfo(name = "trigger")
val trigger: Int = 0, // #onModulesUpdated
@ColumnInfo(name = "extended_type")
override val extendedType: DataSourceType? = null,
) : IAgencyNearbyUIProperties {
@Ignore
override val authority = id
override fun isInArea(area: Area?): Boolean {
return IAgencyNearbyProperties.isInArea(this, area)
}
override fun isEntirelyInside(area: LatLngBounds?): Boolean {
return IAgencyNearbyProperties.isEntirelyInside(this, area)
}
override fun isInArea(area: LatLngBounds?): Boolean {
return IAgencyNearbyProperties.isInArea(this, area)
}
override fun isEntirelyInside(otherArea: Area?): Boolean {
return IAgencyNearbyProperties.isEntirelyInside(this, area)
}
} | 5 | null | 4 | 34 | dccaac0fe7f1604a191eaa63b936ba476a9a0682 | 2,081 | mtransit-for-android | Apache License 2.0 |
bindings/core/glib/src/nativeMain/kotlin/org/gtkkn/bindings/glib/OptionErrorException.kt | gtk-kn | 609,191,895 | false | {"Kotlin": 10448515, "Shell": 2740} | // This is a generated file. Do not modify.
package org.gtkkn.bindings.glib
import org.gtkkn.extensions.glib.GlibException
public class ConvertErrorException(
error: Error,
public val code: ConvertError,
) : GlibException(error)
| 0 | Kotlin | 0 | 13 | c033c245f1501134c5b9b46212cd153c61f7efea | 239 | gtk-kn | Creative Commons Attribution 4.0 International |
app/src/main/java/com/example/chat_bot/Room/Dao/SeedsDao.kt | SEEDS-learning-apps | 536,944,125 | false | null | package com.example.chat_bot.Room.Dao
import androidx.room.*
import com.example.chat_bot.Room.Relations.UserAndMessage
import com.example.chat_bot.data.R_Message
import com.example.chat_bot.data.User
import com.example.chat_bot.data.tryy.QuestItem
@Dao
interface SeedsDao{
@Transaction //Avoids Multithreading issues
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertMessage(message: R_Message)
@Transaction //Avoids Multithreading issues
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertUser(user: User)
@Transaction //Avoids Multithreading issues
@Query("SELECT * FROM user WHERE username = :username")
suspend fun getUser(username: String): List<User>
@Transaction //Avoids Multithreading issues
@Query("SELECT EXISTS(SELECT * FROM user WHERE username = :username)")
suspend fun isUserExists(username: String): Boolean
@Transaction //Avoids Multithreading issues
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertMaterial(questItem: ArrayList<QuestItem>)
@Transaction //Avoids Multithreading issues
@Query("SELECT * FROM user WHERE username = :username")
suspend fun getMessagesAndUserwithUsername(username: String): List<UserAndMessage>
@Query("UPDATE user SET preferredmaterialLanguage = :preferredmaterialLanguage WHERE username =:username")
fun updatedMaterialLanguage(preferredmaterialLanguage: String?, username: String?)
@Transaction //Avoids Multithreading issues
@Query("select * from QuestItem where _id = :id")
suspend fun checkMaterialsWithID(id: String): List<QuestItem>
@Transaction //Avoids Multithreading issues
@Query("select * from QuestItem where username = :username")
suspend fun getMaterialsWithUsername(username: String): List<QuestItem>
}
| 0 | Kotlin | 2 | 0 | f8245e8c608460bc95f00f7705a72bba5aa49a6f | 1,830 | learning-MobileApp | Educational Community License v2.0 |
app/src/main/java/com/herry/test/app/tflite/digitclassifier/DigitClassifierPresenter.kt | HerryPark | 273,154,769 | false | {"Kotlin": 1291945, "Java": 602} | package com.herry.test.app.tflite.digitclassifier
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.herry.libs.util.tuple.Tuple1
import io.reactivex.Observable
import kotlinx.coroutines.Dispatchers
import java.util.concurrent.atomic.AtomicReference
class DigitClassifierPresenter : DigitClassifierContract.Presenter() {
private var loadedImage: AtomicReference<Any?> = AtomicReference()
private var digitImageClassifier: DigitImageClassifier? = null
override fun onDetach() {
digitImageClassifier?.release()
super.onDetach()
}
override fun onResume(view: DigitClassifierContract.View, state: ResumeState) {
displayLoadedImage(loadedImage.get())
}
override fun loadedImage(loadedImage: Any?, onLoaded: ((image: Any?) -> Unit)?) {
launch(Dispatchers.IO) {
val image = if (loadedImage is ByteArray && loadedImage.size > 0) {
BitmapFactory.decodeByteArray(loadedImage, 0, loadedImage.size)
} else loadedImage
[email protected](image)
launch(Dispatchers.Main) {
onLoaded?.invoke(image)
}
}
}
private fun displayLoadedImage(loadedImage: Any?) {
launch(LaunchWhenPresenter.LAUNCHED) {
view?.onLoadedImage(loadedImage)
}
}
override fun classify(image: Bitmap) {
val context = view?.getViewContext() ?: return
subscribeObservable(
observable = Observable.fromCallable {
val classified = (digitImageClassifier ?: DigitImageClassifier().also { digitImageClassifier = it }).classify(context, image)
Tuple1(classified)
},
onError = {
view?.onError()
},
onNext = {
val classified = it.t1
view?.onClassified(classified.number.toString(), classified.accuracy)
},
loadView = true
)
}
override fun clear() {
loadedImage(null) { image ->
displayLoadedImage(image)
}
}
} | 0 | Kotlin | 0 | 0 | f7a9ced28da4ad6c49515e136114961aa45d45dd | 2,151 | HerryApiDemo | Apache License 2.0 |
library/src/test/java/com/github/skgmn/viewmodelevent/MultipleScreenHandleEvent.kt | skgmn | 392,284,310 | false | {"Kotlin": 61413} | package com.github.skgmn.viewmodelevent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModel
import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(AndroidJUnit4::class)
class MultipleScreenHandleEvent {
@get:Rule
val activityScenarioRule = activityScenarioRule<TestActivity>()
@Test
fun multipleHandling() = runBlockingTest {
val scenario = activityScenarioRule.scenario
val activity = scenario.getActivity()
activity.viewModel.normalEvent.post(1234)
activity.viewModel.normalEvent.post(5678)
activity.viewModel.normalEvent.post(9012)
assertEquals(3, activity.fragment1.eventResults.size)
assertEquals(1234, activity.fragment1.eventResults[0])
assertEquals(5678, activity.fragment1.eventResults[1])
assertEquals(9012, activity.fragment1.eventResults[2])
assertEquals(3, activity.fragment2.eventResults.size)
assertEquals(1234, activity.fragment2.eventResults[0])
assertEquals(5678, activity.fragment2.eventResults[1])
assertEquals(9012, activity.fragment2.eventResults[2])
}
@Test
fun differentLifecycle() = runBlockingTest {
val scenario = activityScenarioRule.scenario
val activity = scenario.getActivity()
activity.supportFragmentManager.beginTransaction()
.detach(activity.fragment2)
.commitNow()
activity.viewModel.normalEvent.post(1234)
activity.viewModel.normalEvent.post(5678)
activity.viewModel.normalEvent.post(9012)
assertEquals(3, activity.fragment1.eventResults.size)
assertEquals(1234, activity.fragment1.eventResults[0])
assertEquals(5678, activity.fragment1.eventResults[1])
assertEquals(9012, activity.fragment1.eventResults[2])
assertEquals(0, activity.fragment2.eventResults.size)
activity.supportFragmentManager.beginTransaction()
.attach(activity.fragment2)
.commitNow()
assertEquals(3, activity.fragment2.eventResults.size)
assertEquals(1234, activity.fragment2.eventResults[0])
assertEquals(5678, activity.fragment2.eventResults[1])
assertEquals(9012, activity.fragment2.eventResults[2])
}
class TestActivity : AppCompatActivity() {
val viewModel: TestViewModel by viewModels()
val fragment1 = TestFragment()
val fragment2 = TestFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager.beginTransaction()
.add(fragment1, null)
.add(fragment2, null)
.commitNow()
}
}
class TestFragment : Fragment() {
val viewModel: TestViewModel by activityViewModels()
val eventResults = mutableListOf<Any>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handle(viewModel.normalEvent, DeliveryMode.ALL) {
eventResults += it
}
}
}
class TestViewModel : ViewModel() {
val normalEvent = publicEvent<Any>()
}
} | 0 | Kotlin | 0 | 4 | c867a600434524b6c4caf1d7f8fdccf64494c487 | 3,677 | ViewModelEvent | MIT License |
src/test/kotlin/ch/leadrian/gradle/plugin/propertykeygenerator/model/PropertyKeyTest.kt | Double-O-Seven | 174,027,903 | false | null | package ch.leadrian.gradle.plugin.propertykeygenerator.model
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
internal class PropertyKeyTest {
@Test
fun `should compute segments`() {
val propertyKey = PropertyKey("foo.bar.baz")
val segments = propertyKey.segments
assertThat(segments)
.containsExactly("foo", "bar", "baz")
}
} | 1 | Kotlin | 1 | 1 | d9f6560eca4053149c444f7e70a71cd47c695b2f | 419 | property-key-generator | Apache License 2.0 |
sqlite-embedder-graalvm/src/jvmMain/kotlin/ru/pixnews/wasm/sqlite/open/helper/graalvm/host/emscripten/func/EmscriptenDateNow.kt | illarionov | 769,429,996 | false | null | /*
* Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary
import com.oracle.truffle.api.frame.VirtualFrame
import org.graalvm.wasm.WasmContext
import org.graalvm.wasm.WasmInstance
import org.graalvm.wasm.WasmLanguage
import org.graalvm.wasm.WasmModule
import ru.pixnews.wasm.sqlite.open.helper.graalvm.SqliteEmbedderHost
import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.BaseWasmNode
internal class EmscriptenDateNow(
language: WasmLanguage,
module: WasmModule,
host: SqliteEmbedderHost,
functionName: String = "emscripten_date_now",
) : BaseWasmNode(language, module, host, functionName) {
override fun executeWithContext(frame: VirtualFrame, context: WasmContext, instance: WasmInstance): Any {
return emscriptenDateNow()
}
@TruffleBoundary
@Suppress("MemberNameEqualsClassName")
private fun emscriptenDateNow(): Double = host.clock().inWholeMilliseconds.toDouble()
}
| 0 | null | 0 | 1 | 49bab6c6cd72999124e35ba009a1f8adfe9d8bb5 | 1,274 | wasm-sqlite-open-helper | Apache License 2.0 |
medolylibrary/src/main/java/com/wa2c/android/medoly/library/PropertyData.kt | wa2c | 134,095,731 | false | {"Kotlin": 63278, "Batchfile": 37} | package com.wa2c.android.medoly.library
import android.net.Uri
/**
* Property data.
*/
open class PropertyData : ExtraData {
/**
* Constructor.
*/
constructor() : super()
/**
* Constructor.
* @param capacity The capacity.
*/
constructor(capacity: Int) : super(capacity)
/**
* Copy constructor.
* @param propertyData A property data.
*/
constructor(propertyData: Map<String, MutableList<String?>?>) : super(propertyData)
/**
* Copy constructor.
* @param propertyData A property data.
*/
constructor(propertyData: PropertyData) : super(propertyData)
/**
* Returns true if this map contains a mapping for the specified key.
* @param key A property key.
* @return true if this map contains a mapping for the specified key.
*/
fun containsKey(key: IProperty?): Boolean {
return super.containsKey(key?.keyName)
}
/**
* Returns true if this map contains no key-value mappings.
* @return true if this map contains no key-value mappings.
*/
fun isEmpty(key: IProperty?): Boolean {
return this.isEmpty(key?.keyName)
}
/**
* Get property value list.
* @param key A property key.
* @return The property value list.
*/
operator fun get(key: IProperty?): MutableList<String?>? {
return super.get(key?.keyName)
}
/**
* Get the first property value.
* @param key A property key.
* @return The first property value.
*/
fun getFirst(key: IProperty?): String? {
return super.getFirst(key?.keyName)
}
/**
* Get the values concatenated by line breaks as text.
* @param key A property key.
* @return The concatenated property text.
*/
fun getText(key: IProperty?): String {
return super.getText(key?.keyName, "\n")
}
/**
* Get the values concatenated by separator as text.
* @param key A property key.
* @param separator A separator.
* @return The concatenated property text.
*/
fun getText(key: IProperty?, separator: String?): String {
return super.getText(key?.keyName, separator)
}
/**
* Set the new property value list. (indexed access operator)
* @param key A property key.
* @param value The property value.
*/
operator fun set(key: IProperty?, value: MutableList<String?>?): MutableList<String?>? {
return put(key, value)
}
/**
* Set the new property value list. (indexed access operator)
* @param key A property key.
* @param value The property value.
*/
operator fun set(key: IProperty?, value: String?): MutableList<String?>? {
return put(key, value)
}
/**
* Put the new property value list.
* @param key A property key.
* @param value The property value list.
*/
fun put(key: IProperty?, value: MutableList<String?>?): MutableList<String?>? {
return super.put(key?.keyName, value)
}
/**
* Put the new property value.
* @param key A property key.
* @param value The property value.
*/
fun put(key: IProperty?, value: String?): MutableList<String?>? {
return super.put(key?.keyName, value)
}
/**
* Insert the property value to first position.
* @param key A property key.
* @param value The property value.
*/
fun insertFirst(key: IProperty?, value: String?) {
return super.insertFirst(key?.keyName, value)
}
/**
* Insert the property value to last position.
* @param key A property key.
* @param value The property value.
*/
fun insertLast(key: IProperty?, value: String?) {
return super.insertLast(key?.keyName, value)
}
/**
* Removes the mapping for a key from this map if it is present (optional operation).
* @param key key whose mapping is to be removed from the map.
* @return the previous value associated with key, or null if there was no mapping for key.
*/
fun remove(key: IProperty?): MutableList<String?>? {
return super.remove(key?.keyName)
}
/**
* Compares the specified object with this map for equality.
* @param property A property key.
* @param list A property value list.
* @return true if the specified object is equal to this map.
*/
fun equals(property: IProperty?, list: MutableList<String?>?): Boolean {
return super.equals(property?.keyName, list)
}
/**
* Get the media URI.
* @return The media URI.
*/
val mediaUri: Uri?
get() {
val url = this.getFirst(MediaProperty.DATA_URI)
if (url.isNullOrEmpty())
return null
return try {
Uri.parse(url)
} catch (ignore: Exception) {
null
}
}
/**
* Get the album art URI.
* @return The album art URI.
*/
val albumArtUri: Uri?
get() {
val url = this.getFirst(AlbumArtProperty.DATA_URI)
if (url.isNullOrEmpty())
return null
return try {
Uri.parse(url)
} catch (ignore: Exception) {
null
}
}
/**
* Get the lyrics URI.
* @return The lyrics URI.
*/
val lyricsUri: Uri?
get() {
val url = this.getFirst(LyricsProperty.DATA_URI)
if (url.isNullOrEmpty())
return null
return try {
Uri.parse(url)
} catch (ignore: Exception) {
null
}
}
/**
* Returns true if this property has media data.
* @return true if this map has no media data.
*/
val isMediaEmpty: Boolean
get() = this.getFirst(MediaProperty.DATA_URI).isNullOrEmpty()
/**
* Returns true if this property has album art data.
* @return true if this map has no album art data.
*/
val isAlbumArtEmpty: Boolean
get() = this.getFirst(AlbumArtProperty.RESOURCE_TYPE).isNullOrEmpty()
/**
* Returns true if this property has lyrics data.
* @return true if this map has no lyrics data.
*/
val isLyricsEmpty: Boolean
get() = this.getFirst(LyricsProperty.RESOURCE_TYPE).isNullOrEmpty()
}
| 0 | Kotlin | 0 | 0 | c82f28bc43e18522be5a428ec1db94a960567018 | 6,399 | medoly-library | MIT License |
app/src/main/java/com/will/habit/ui/tab_bar/activity/TabBarActivity.kt | dcn01 | 274,296,030 | true | {"Kotlin": 222715, "Java": 215869} | package com.will.habit.ui.tab_bar.activity
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.will.habit.BR
import com.will.habit.R
import com.will.habit.databinding.ActivityTabBarBinding
import com.will.habit.ui.tab_bar.fragment.TabBar1Fragment
import com.will.habit.ui.tab_bar.fragment.TabBar2Fragment
import com.will.habit.ui.tab_bar.fragment.TabBar3Fragment
import com.will.habit.ui.tab_bar.fragment.TabBar4Fragment
import com.will.habit.base.BaseActivity
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener
import java.util.*
/**
* 底部tab按钮的例子
* 所有例子仅做参考,理解如何使用才最重要。
* Created by goldze on 2018/7/18.
*/
class TabBarActivity : BaseActivity<ActivityTabBarBinding, TabBarViewModel>() {
private var mFragments: MutableList<Fragment>? = null
override fun initContentView(savedInstanceState: Bundle?): Int {
return R.layout.activity_tab_bar
}
override fun initVariableId(): Int {
return BR.viewModel
}
override fun initData() {
//初始化Fragment
initFragment()
//初始化底部Button
initBottomTab()
}
private fun initFragment() {
mFragments = ArrayList()
mFragments!!.add(TabBar1Fragment())
mFragments!!.add(TabBar2Fragment())
mFragments!!.add(TabBar3Fragment())
mFragments!!.add(TabBar4Fragment())
//默认选中第一个
commitAllowingStateLoss(0)
}
private fun initBottomTab() {
val navigationController = binding!!.pagerBottomTab.material()
.addItem(R.mipmap.yingyong, "应用")
.addItem(R.mipmap.huanzhe, "工作")
.addItem(R.mipmap.xiaoxi_select, "消息")
.addItem(R.mipmap.wode_select, "我的")
.setDefaultColor(ContextCompat.getColor(this, R.color.textColorVice))
.build()
//底部按钮的点击事件监听
navigationController.addTabItemSelectedListener(object : OnTabItemSelectedListener {
override fun onSelected(index: Int, old: Int) {
// FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// transaction.replace(R.id.frameLayout, mFragments.get(index));
// transaction.commitAllowingStateLoss();
commitAllowingStateLoss(index)
}
override fun onRepeat(index: Int) {}
})
}
private fun commitAllowingStateLoss(position: Int) {
hideAllFragment()
val transaction = supportFragmentManager.beginTransaction()
var currentFragment = supportFragmentManager.findFragmentByTag(position.toString() + "")
if (currentFragment != null) {
transaction.show(currentFragment)
} else {
currentFragment = mFragments!![position]
transaction.add(R.id.frameLayout, currentFragment, position.toString() + "")
}
transaction.commitAllowingStateLoss()
}
//隐藏所有Fragment
private fun hideAllFragment() {
val transaction = supportFragmentManager.beginTransaction()
for (i in mFragments!!.indices) {
val currentFragment = supportFragmentManager.findFragmentByTag(i.toString() + "")
if (currentFragment != null) {
transaction.hide(currentFragment)
}
}
transaction.commitAllowingStateLoss()
}
} | 0 | null | 0 | 0 | 08d36bb62984f7321c295acb3286b561627b7e6d | 3,411 | MVVMWill | Apache License 2.0 |
java/java-impl/src/com/intellij/internal/statistic/libraryUsage/LibraryDescriptorFinderService.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.libraryUsage
import com.intellij.openapi.components.Service
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
@Service(Service.Level.APP)
class LibraryDescriptorFinderService {
private val lock = ReentrantReadWriteLock()
private var libraryDescriptorFinder: LibraryDescriptorFinder? = null
@RequiresBackgroundThread
fun libraryDescriptorFinder(): LibraryDescriptorFinder? {
cachedLibraryDescriptorFinder()?.let { return it }
lock.write {
if (libraryDescriptorFinder != null) return libraryDescriptorFinder
val descriptors = downloadLibraryDescriptors() ?: return null
libraryDescriptorFinder = LibraryLayer.create(descriptors)
return libraryDescriptorFinder
}
}
fun cachedLibraryDescriptorFinder(): LibraryDescriptorFinder? = lock.read { libraryDescriptorFinder }
}
| 191 | null | 4372 | 13,319 | 4d19d247824d8005662f7bd0c03f88ae81d5364b | 1,165 | intellij-community | Apache License 2.0 |
scanner/src/main/kotlin/Main.kt | jeffmcaffer | 114,395,628 | false | null | /*
* Copyright (c) 2017 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.ort.scanner
import ch.frankel.slf4k.*
import com.beust.jcommander.IStringConverter
import com.beust.jcommander.JCommander
import com.beust.jcommander.Parameter
import com.beust.jcommander.ParameterException
import com.here.ort.model.OutputFormat
import com.here.ort.model.Package
import com.here.ort.model.Project
import com.here.ort.model.AnalyzerResult
import com.here.ort.scanner.scanners.ScanCode
import com.here.ort.utils.collectMessages
import com.here.ort.utils.jsonMapper
import com.here.ort.utils.log
import com.here.ort.utils.yamlMapper
import java.io.File
import java.util.SortedSet
import kotlin.system.exitProcess
class ScanSummary(
val pkgSummary: PackageSummary,
val cacheStats: CacheStatistics
)
typealias PackageSummary = MutableMap<String, SummaryEntry>
class SummaryEntry(
val scopes: SortedSet<String> = sortedSetOf(),
val licenses: SortedSet<String> = sortedSetOf(),
val errors: MutableList<String> = mutableListOf()
)
/**
* The main entry point of the application.
*/
object Main {
private class OutputFormatConverter : IStringConverter<OutputFormat> {
override fun convert(name: String): OutputFormat {
try {
return OutputFormat.valueOf(name.toUpperCase())
} catch (e: IllegalArgumentException) {
if (stacktrace) {
e.printStackTrace()
}
throw ParameterException("Summary formats must be contained in ${OutputFormat.ALL}.")
}
}
}
private class ScannerConverter : IStringConverter<Scanner> {
override fun convert(scannerName: String): Scanner {
// TODO: Consider allowing to enable multiple scanners (and potentially running them in parallel).
return Scanner.ALL.find { it.javaClass.simpleName.toUpperCase() == scannerName.toUpperCase() } ?:
throw ParameterException("The scanner must be one of ${Scanner.ALL}.")
}
}
@Parameter(description = "The dependencies analysis file to use. Source code will be downloaded automatically if " +
"needed. This parameter and --input-path are mutually exclusive.",
names = ["--dependencies-file", "-d"],
order = 0)
private var dependenciesFile: File? = null
@Parameter(description = "The input directory or file to scan. This parameter and --dependencies-file are " +
"mutually exclusive.",
names = ["--input-path", "-i"],
order = 0)
private var inputPath: File? = null
@Parameter(description = "The output directory to store the scan results in.",
names = ["--output-dir", "-o"],
required = true,
order = 0)
@Suppress("LateinitUsage")
private lateinit var outputDir: File
@Parameter(description = "The output directory for downloaded source code. Defaults to <output-dir>/downloads.",
names = ["--download-dir"],
order = 0)
private var downloadDir: File? = null
@Parameter(description = "The scanner to use.",
names = ["--scanner", "-s"],
converter = ScannerConverter::class,
order = 0)
private var scanner: Scanner = ScanCode
@Parameter(description = "The path to the configuration file.",
names = ["--config", "-c"],
order = 0)
@Suppress("LateinitUsage")
private var configFile: File? = null
@Parameter(description = "The list of file formats for the summary files.",
names = ["--summary-format", "-f"],
converter = OutputFormatConverter::class,
order = 0)
private var summaryFormats = listOf(OutputFormat.YAML)
@Parameter(description = "Enable info logging.",
names = ["--info"],
order = 0)
private var info = false
@Parameter(description = "Enable debug logging and keep any temporary files.",
names = ["--debug"],
order = 0)
private var debug = false
@Parameter(description = "Print out the stacktrace for all exceptions.",
names = ["--stacktrace"],
order = 0)
var stacktrace = false
@Parameter(description = "Display the command line help.",
names = ["--help", "-h"],
help = true,
order = 100)
private var help = false
/**
* The entry point for the application.
*
* @param args The list of application arguments.
*/
@JvmStatic
fun main(args: Array<String>) {
val jc = JCommander(this)
jc.parse(*args)
jc.programName = "scanner"
if (info) {
log.level = ch.qos.logback.classic.Level.INFO
}
if (debug) {
log.level = ch.qos.logback.classic.Level.DEBUG
}
if (help) {
jc.usage()
exitProcess(1)
}
if ((dependenciesFile != null) == (inputPath != null)) {
throw IllegalArgumentException("Either --dependencies-file or --input-path must be specified.")
}
require(!outputDir.exists()) {
"The output directory '${outputDir.absolutePath}' must not exist yet."
}
downloadDir?.let {
require(!it.exists()) {
"The download directory '${it.absolutePath}' must not exist yet."
}
}
if (configFile != null) {
ScanResultsCache.configure(yamlMapper.readTree(configFile))
}
println("Using scanner '$scanner'.")
val pkgSummary: PackageSummary = mutableMapOf()
dependenciesFile?.let { dependenciesFile ->
require(dependenciesFile.isFile) {
"Provided path is not a file: ${dependenciesFile.absolutePath}"
}
val mapper = when (dependenciesFile.extension) {
OutputFormat.JSON.fileEnding -> jsonMapper
OutputFormat.YAML.fileEnding -> yamlMapper
else -> throw IllegalArgumentException("Provided input file is neither JSON nor YAML.")
}
val analyzerResult = mapper.readValue(dependenciesFile, AnalyzerResult::class.java)
val packages = mutableListOf(analyzerResult.project.toPackage())
packages.addAll(analyzerResult.packages)
packages.forEach { pkg ->
val entry = pkgSummary.getOrPut(pkg.identifier) { SummaryEntry() }
entry.scopes.addAll(findScopesForPackage(pkg, analyzerResult.project))
scanEntry(entry, pkg.identifier, pkg)
}
}
inputPath?.let { inputPath ->
require(inputPath.exists()) {
"Provided path does not exist: ${inputPath.absolutePath}"
}
val entry = pkgSummary.getOrPut(inputPath.absolutePath) { SummaryEntry() }
scanEntry(entry, inputPath.absolutePath, inputPath)
}
writeSummary(outputDir, ScanSummary(pkgSummary, ScanResultsCache.stats))
}
private fun findScopesForPackage(pkg: Package, project: Project) =
project.scopes.filter { it.contains(pkg) }.map { it.name }
private fun scanEntry(entry: SummaryEntry, identifier: String, input: Any) {
try {
println("Scanning package '$identifier'...")
val result = when (input) {
is Package -> {
entry.licenses.addAll(input.declaredLicenses)
scanner.scan(input, outputDir, downloadDir)
}
is File -> scanner.scan(input, outputDir)
else -> throw IllegalArgumentException("Unsupported scan input.")
}
entry.licenses.addAll(result.licenses)
println("Found licenses for '$identifier': ${entry.licenses.joinToString()}")
} catch (e: ScanException) {
if (stacktrace) {
e.printStackTrace()
}
log.error { "Could not scan '$identifier': ${e.message}" }
entry.errors.addAll(e.collectMessages())
}
}
private fun writeSummary(outputDirectory: File, scanSummary: ScanSummary) {
summaryFormats.forEach { format ->
val summaryFile = File(outputDirectory, "scan-summary.${format.fileEnding}")
val mapper = when (format) {
OutputFormat.JSON -> jsonMapper
OutputFormat.YAML -> yamlMapper
}
println("Writing scan summary to ${summaryFile.absolutePath}.")
mapper.writerWithDefaultPrettyPrinter().writeValue(summaryFile, scanSummary)
}
}
}
| 0 | null | 0 | 1 | c05c57e9eaff25249ff3c26c79aa140a5af1f0e8 | 9,363 | oss-review-toolkit | Apache License 2.0 |
ComponentImpl/src/main/java/com/xiaojinzi/component/impl/RouterDegrade.kt | xiaojinzi123 | 574,764,526 | false | null | package com.xiaojinzi.component.impl
import android.content.Intent
import com.xiaojinzi.component.anno.support.CheckClassNameAnno
/**
* 降级的一个接口, 使用 [com.xiaojinzi.component.anno.RouterDegradeAnno] 注解标记一个类为降级处理
*/
@CheckClassNameAnno
interface RouterDegrade {
/**
* 是否匹配这个路由
*
* @param request 路由请求对象
* @return
*/
fun isMatch(request: RouterRequest): Boolean
/**
* 当路由失败的时候, 如果路由匹配 [RouterDegrade.isMatch]
*
* @param request 路由请求对象
* @return
*/
fun onDegrade(request: RouterRequest): Intent
} | 5 | null | 284 | 99 | b575c031f91acadc0debbcc96cf96d8235026116 | 562 | KComponent | Apache License 2.0 |
core/src/main/java/io/github/kunal26das/core/gson/GsonImpl.kt | kunal26das | 283,553,926 | false | null | package io.github.kunal26das.core.gson
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import io.github.kunal26das.core.singleton.Singleton
abstract class GsonImpl(
private val builder: (GsonBuilder.() -> Unit)? = null
) : Singleton<Gson>() {
override fun initialize(): Gson {
return GsonBuilder().apply {
builder?.invoke(this)
}.create()
}
} | 0 | Kotlin | 0 | 1 | 9d7459f38693e881d8f8dd7bb725a7fb5b6447c9 | 399 | Yify | Apache License 2.0 |
app/src/main/java/com/amazonaws/services/chime/sdkdemo/data/JoinMeetingResponse.kt | aws | 249,543,698 | false | null | package com.nam.chime_sdk.data
import com.amazonaws.services.chime.sdk.meetings.session.Attendee
import com.amazonaws.services.chime.sdk.meetings.session.Meeting
import com.google.gson.annotations.SerializedName
data class JoinMeetingResponse(
@SerializedName("JoinInfo") val joinInfo: MeetingInfo
)
data class MeetingInfo(
@SerializedName("Meeting") val meetingResponse: MeetingResponse,
@SerializedName("Attendee") val attendeeResponse: AttendeeResponse
)
data class MeetingResponse(
@SerializedName("Meeting") val meeting: Meeting
)
data class AttendeeResponse(
@SerializedName("Attendee") val attendee: Attendee
)
| 30 | null | 52 | 98 | a63bff8018ab63f8d381f96cda231a28eec40181 | 643 | amazon-chime-sdk-android | Apache License 2.0 |
app/src/main/java/afkt/project/feature/ButtonItemActivity.kt | afkT | 147,776,221 | false | null | package afkt.project.feature
import afkt.project.R
import afkt.project.base.app.BaseActivity
import afkt.project.databinding.BaseViewRecyclerviewBinding
import afkt.project.model.item.ButtonList
import afkt.project.model.item.ButtonValue
import afkt.project.model.item.RouterPath
import com.therouter.router.Route
import dev.callback.DevItemClickCallback
/**
* detail: Button 列表 Activity
* @author Ttt
*/
@Route(path = RouterPath.ButtonItemActivity_PATH)
class ButtonItemActivity : BaseActivity<BaseViewRecyclerviewBinding>() {
override fun baseLayoutId(): Int = R.layout.base_view_recyclerview
override fun initValue() {
super.initValue()
// 初始化布局管理器、适配器
ButtonAdapter(ButtonList.getButtonValues(moduleType))
.setItemCallback(object : DevItemClickCallback<ButtonValue>() {
override fun onItemClick(
buttonValue: ButtonValue,
param: Int
) {
routerActivity(buttonValue)
}
}).bindAdapter(binding.vidRv)
// 注册观察者
registerAdapterDataObserver(binding.vidRv, true)
}
} | 1 | null | 299 | 882 | 2fd4c7582a97968d73d67124b6b2e57eda18e90f | 1,153 | DevUtils | Apache License 2.0 |
KotlinGames/app/src/main/java/com/mduranx64/kotlingames/ChessGame.kt | mduranx64 | 857,545,408 | false | {"Kotlin": 73326, "Ruby": 1269} | package com.mduranx64.kotlingames
import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
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.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.mduranx64.kotlingames.ui.theme.KotlinGamesTheme
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.lifecycle.viewmodel.compose.viewModel
import java.io.Serializable
enum class BoardTheme: Serializable {
Black,
Brown
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChessGame(navController: NavHostController) {
var showMenuAlert by rememberSaveable { mutableStateOf(false) }
var currentTheme by rememberSaveable { mutableStateOf(BoardTheme.Black) }
var showCustomAlert by rememberSaveable { mutableStateOf(false) }
val chessViewModel: ChessViewModel = viewModel()
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = "Chess",
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.titleLarge
)
},
navigationIcon = {
// Left button (Menu or Back button)
IconButton(onClick = {
// handle
showCustomAlert = true
}) {
Icon(Icons.Default.Close, contentDescription = "Back", tint = MaterialTheme.colorScheme.primary)
}
},
actions = {
// Right button (Settings or any action)
IconButton(onClick = {
showMenuAlert = true
}) {
Icon(Icons.Default.Settings, contentDescription = "Settings", tint = MaterialTheme.colorScheme.primary)
}
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.background
)
)
},
content = { paddingValues ->
ChessBoardView(
navController = navController,
viewModel = chessViewModel,
boardTheme = currentTheme,
modifier = Modifier
.padding(paddingValues)
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
)
}
)
if (showMenuAlert) {
MenuAlert(
onDismiss = { showMenuAlert = false },
theme = currentTheme,
onThemeChange = { newTheme -> currentTheme = newTheme }
)
}
if (showCustomAlert) {
CustomExitAlert(
onDismiss = { showCustomAlert = false },
onAccept = {
showCustomAlert = false
navController.popBackStack()
}
)
}
}
@Composable
fun ChessBoardView(navController: NavHostController, viewModel: ChessViewModel = viewModel(), boardTheme: BoardTheme, modifier: Modifier) {
val configuration = LocalConfiguration.current
val topPadding = WindowInsets.systemBars.getTop(LocalDensity.current)
val bottomPadding = WindowInsets.systemBars.getBottom(LocalDensity.current)
val squares = 8
val fullScreenSize = configuration.screenWidthDp.coerceAtMost(configuration.screenHeightDp)
val gridSize = if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) fullScreenSize.dp else (fullScreenSize - (topPadding + bottomPadding)).dp
val squareSize = gridSize / squares
var showWinAlert: Boolean by rememberSaveable { mutableStateOf(false) }
var showPawnAlert: Boolean by rememberSaveable { mutableStateOf(false) }
val letters = listOf("a", "b", "c", "d", "e", "f", "g", "h")
val numbers = listOf("8", "7", "6", "5", "4", "3", "2", "1")
val captureSize = squareSize / 2
if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// Top Captured pieces
LazyVerticalGrid(
columns = GridCells.Fixed(squares * 2),
modifier = Modifier.size(width = gridSize, height = captureSize)
) {
itemsIndexed(viewModel.board.whiteCapture) { _, piece ->
Image(
painter = painterResource(piece.pieceImage),
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = Modifier
.size(squareSize / 2)
)
}
}
Column(
modifier = Modifier.alpha(if (viewModel.board.currentTurn == PieceColor.BLACK) 1f else 0f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = "Game Controller",
tint = MaterialTheme.colorScheme.secondary
)
Text(
text = "Black moves",
fontSize = 16.sp,
color = MaterialTheme.colorScheme.secondary
)
}
// Board and Pieces
Box(
modifier = Modifier
.size(gridSize)
.background(Color.DarkGray)
) {
// Board
LazyHorizontalGrid(rows = GridCells.Fixed(squares)) {
items(64) { index ->
val row = index % squares
val column = index / squares
val isLight = (row + column) % 2 == 0
val finalTheme = when (boardTheme) {
BoardTheme.Black -> if (isLight) R.drawable.square_gray_light else R.drawable.square_gray_dark
BoardTheme.Brown -> if (isLight) R.drawable.square_brown_light else R.drawable.square_brown_dark
}
val color = if (isLight) Color.Black else Color.White
val numberGuide = if (index < numbers.size) numbers[index] else ""
val letterGuide = if (row == 7) letters[column] else ""
Box(
modifier = Modifier
.size(squareSize)
.padding(0.dp),
contentAlignment = Alignment.BottomEnd
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.TopStart
) {
Image(
painter = painterResource(id = finalTheme),
contentDescription = null,
modifier = Modifier.size(squareSize), // Adjust the size of each square
contentScale = ContentScale.Fit // Ensures the image covers the entire area
)
// Top-left number guide
Text(
text = numberGuide,
color = color,
fontSize = 14.sp,
modifier = Modifier.padding(start = 0.dp, top = 0.dp)
)
}
// Bottom-right letter guide
Text(
text = letterGuide,
color = color,
fontSize = 14.sp,
modifier = Modifier.padding(end = 0.dp, bottom = 0.dp)
)
}
}
}
// Pieces
LazyHorizontalGrid(
rows = GridCells.Fixed(squares)
) {
items(viewModel.board.pieces.size) { x ->
val row = viewModel.board.pieces[x]
Row {
row.forEachIndexed { y, piece ->
val pieceImage = row[y]?.pieceImage ?: R.drawable.empty
val position = Position(x, y)
val isLight = (x + y) % 2 == 0
val name = piece?.type?.name ?: "empty"
val color = piece?.color?.name
?: if (isLight) "white square" else "black square"
val numberGuide = numbers[x]
val letterGuide = letters[y]
val identifier = "$color $name $letterGuide$numberGuide"
Box(
modifier = Modifier
.size(squareSize)
.background(Color.Transparent)
.border(
2.dp,
if (viewModel.board.isSelected(position)) Color.Yellow else Color.Transparent
)
.clickable {
viewModel.board.selectPiece(position)
if (viewModel.board.isBlackKingCaptured || viewModel.board.isWhiteKingCaptured) {
showWinAlert = true
}
if (viewModel.board.isPiecePromoted) {
showPawnAlert = true
}
}
.semantics {
contentDescription =
if (piece == null) identifier else ""
}
) {
piece?.let {
Image(
painter = painterResource(pieceImage),
contentDescription = identifier,
modifier = Modifier
.fillMaxSize()
.padding(2.dp)
)
}
}
}
}
}
}
}
Column(
modifier = Modifier.alpha(if (viewModel.board.currentTurn == PieceColor.WHITE) 1f else 0f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = "Play",
tint = MaterialTheme.colorScheme.secondary
)
Text(
text = "White moves",
fontSize = 16.sp,
color = MaterialTheme.colorScheme.secondary
)
}
// Bottom captured pieces
LazyVerticalGrid(
columns = GridCells.Fixed(squares * 2),
modifier = Modifier.size(width = gridSize, height = captureSize)
) {
itemsIndexed(viewModel.board.blackCapture) { _, piece ->
Image(
painter = painterResource(piece.pieceImage),
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = Modifier
.size(squareSize / 2)
)
}
}
}
} else {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
// Top Captured pieces
LazyHorizontalGrid(
rows = GridCells.Fixed(squares * 2),
modifier = Modifier.size(width = captureSize, height = gridSize)
) {
itemsIndexed(viewModel.board.whiteCapture) { _, piece ->
Image(
painter = painterResource(piece.pieceImage),
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = Modifier
.size(squareSize / 2)
)
}
}
Spacer(modifier = Modifier.width(16.dp))
Column(
modifier = Modifier.alpha(if (viewModel.board.currentTurn == PieceColor.BLACK) 1f else 0f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = "Game Controller",
tint = MaterialTheme.colorScheme.secondary
)
Text(
text = "Black moves",
fontSize = 16.sp,
color = MaterialTheme.colorScheme.secondary
)
}
Spacer(modifier = Modifier.width(16.dp))
// Board and Pieces
Box(
modifier = Modifier
.size(gridSize)
.background(Color.DarkGray)
) {
// Board
LazyHorizontalGrid(rows = GridCells.Fixed(squares)) {
items(64) { index ->
val row = index % squares
val column = index / squares
val isLight = (row + column) % 2 == 0
val finalTheme = when (boardTheme) {
BoardTheme.Black -> if (isLight) R.drawable.square_gray_light else R.drawable.square_gray_dark
BoardTheme.Brown -> if (isLight) R.drawable.square_brown_light else R.drawable.square_brown_dark
}
val color = if (isLight) Color.Black else Color.White
val numberGuide = if (index < numbers.size) numbers[index] else ""
val letterGuide = if (row == 7) letters[column] else ""
Box(
modifier = Modifier
.size(squareSize)
.padding(0.dp),
contentAlignment = Alignment.BottomEnd
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.TopStart
) {
Image(
painter = painterResource(id = finalTheme),
contentDescription = null,
modifier = Modifier.size(squareSize), // Adjust the size of each square
contentScale = ContentScale.Fit // Ensures the image covers the entire area
)
// Top-left number guide
Text(
text = numberGuide,
color = color,
fontSize = 14.sp,
modifier = Modifier.padding(start = 0.dp, top = 0.dp)
)
}
// Bottom-right letter guide
Text(
text = letterGuide,
color = color,
fontSize = 14.sp,
modifier = Modifier.padding(end = 0.dp, bottom = 0.dp)
)
}
}
}
// Pieces
LazyHorizontalGrid(
rows = GridCells.Fixed(squares)
) {
items(viewModel.board.pieces.size) { x ->
val row = viewModel.board.pieces[x]
Row {
row.forEachIndexed { y, piece ->
val pieceImage = row[y]?.pieceImage ?: R.drawable.empty
val position = Position(x, y)
val isLight = (x + y) % 2 == 0
val name = piece?.type?.name ?: "empty"
val color = piece?.color?.name
?: if (isLight) "white square" else "black square"
val numberGuide = numbers[x]
val letterGuide = letters[y]
val identifier = "$color $name $letterGuide$numberGuide"
Box(
modifier = Modifier
.size(squareSize)
.background(Color.Transparent)
.border(
2.dp,
if (viewModel.board.isSelected(position)) Color.Yellow else Color.Transparent
)
.clickable {
viewModel.board.selectPiece(position)
if (viewModel.board.isBlackKingCaptured || viewModel.board.isWhiteKingCaptured) {
showWinAlert = true
}
if (viewModel.board.isPiecePromoted) {
showPawnAlert = true
}
}
.semantics {
contentDescription =
if (piece == null) identifier else ""
}
) {
piece?.let {
Image(
painter = painterResource(pieceImage),
contentDescription = identifier,
modifier = Modifier
.fillMaxSize()
.padding(2.dp)
)
}
}
}
}
}
}
}
Spacer(modifier = Modifier.width(16.dp))
Column(
modifier = Modifier.alpha(if (viewModel.board.currentTurn == PieceColor.WHITE) 1f else 0f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = "Play",
tint = MaterialTheme.colorScheme.secondary
)
Text(
text = "White moves",
fontSize = 16.sp,
color = MaterialTheme.colorScheme.secondary
)
}
Spacer(modifier = Modifier.width(16.dp))
// Bottom captured pieces
LazyHorizontalGrid(
rows = GridCells.Fixed(squares * 2),
modifier = Modifier.size(width = captureSize, height = gridSize)
) {
itemsIndexed(viewModel.board.blackCapture) { _, piece ->
Image(
painter = painterResource(piece.pieceImage),
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = Modifier
.size(squareSize / 2)
)
}
}
}
}
// Alerts (for example, when the game is won or a pawn promotion)
if (showWinAlert) {
val color = if (viewModel.board.isWhiteKingCaptured) PieceColor.WHITE else PieceColor.BLACK
WinAlert(
capturedColor = color,
onDismiss = {
showWinAlert = false
navController.popBackStack()
}
)
}
if (showPawnAlert) {
PawnPromotionDialog(
onDismiss = { showPawnAlert = false },
board = viewModel.board
)
}
}
@Composable
fun CustomExitAlert(onDismiss: () -> Unit, onAccept: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(text = "Confirm Exit", style = MaterialTheme.typography.titleLarge)
},
text = {
Text("Are you sure you want to exit the game?", style = MaterialTheme.typography.bodyLarge)
},
confirmButton = {
Button(onClick = onAccept) {
Text("Yes")
}
},
dismissButton = {
Button(onClick = onDismiss) {
Text("No")
}
}
)
}
@Composable
fun MenuAlert(
onDismiss: () -> Unit,
theme: BoardTheme,
onThemeChange: (BoardTheme) -> Unit
) {
AlertDialog(
onDismissRequest = { onDismiss() },
title = {
Text(
text = "Game settings",
style = MaterialTheme.typography.titleLarge
)
},
text = {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Board theme selection using a Dropdown (like a picker)
var expanded by remember { mutableStateOf(false) }
Box(
modifier = Modifier
.fillMaxWidth()
.background(
MaterialTheme.colorScheme.background,
shape = RoundedCornerShape(8.dp)
)
.clickable { expanded = !expanded }
.padding(12.dp)
) {
Text(
text = when (theme) {
BoardTheme.Black -> "Black"
BoardTheme.Brown -> "Brown"
},
style = MaterialTheme.typography.bodyLarge,
)
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
DropdownMenuItem(
text = { Text("Black") },
onClick = {
onThemeChange(BoardTheme.Black)
expanded = false
}
)
DropdownMenuItem(
text = { Text("Brown") },
onClick = {
onThemeChange(BoardTheme.Brown)
expanded = false
}
)
}
}
}
},
confirmButton = {
Button(onClick = { onDismiss() }) {
Text("Accept")
}
}
)
}
@Composable
fun PawnPromotionDialog(
onDismiss: () -> Unit,
board: Board
) {
var pieceTypeSelected: PieceType by remember { mutableStateOf( PieceType.QUEEN) }
AlertDialog(
onDismissRequest = { },
title = {
Text(
text = if (board.isWhiteKingCaptured) "Black pawn promotion!" else "White pawn promotion!",
style = MaterialTheme.typography.titleLarge
)
},
text = {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Promotion instruction
Text(text = "Select a piece type", style = MaterialTheme.typography.bodyLarge)
// Dropdown (Picker) for selecting piece type
var expanded by remember { mutableStateOf(false) }
Box(
modifier = Modifier
.fillMaxWidth()
.background(
MaterialTheme.colorScheme.background,
shape = RoundedCornerShape(8.dp)
)
.clickable { expanded = !expanded }
.padding(12.dp)
) {
Text(
text = when (pieceTypeSelected) {
PieceType.QUEEN -> "Queen"
PieceType.KNIGHT -> "Knight"
PieceType.BISHOP -> "Bishop"
PieceType.ROOK -> "Rook"
PieceType.KING -> ""
PieceType.PAWN -> ""
},
fontSize = 18.sp
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = { Text("Queen") },
onClick = {
pieceTypeSelected = PieceType.QUEEN
expanded = false
}
)
DropdownMenuItem(
text = { Text("Knight") },
onClick = {
pieceTypeSelected = PieceType.KNIGHT
expanded = false
}
)
DropdownMenuItem(
text = { Text("Bishop") },
onClick = {
pieceTypeSelected = PieceType.BISHOP
expanded = false
}
)
DropdownMenuItem(
text = { Text("Rook") },
onClick = {
pieceTypeSelected = PieceType.ROOK
expanded = false
}
)
}
}
}
},
confirmButton = {
Button(
onClick = {
board.promotePiece(pieceTypeSelected) // Promote the pawn
onDismiss() // Close the dialog
}
) {
Text("Accept")
}
}
)
}
@Preview(showBackground = true)
@Composable
fun DefaultPreviewLight() {
KotlinGamesTheme {
val navController = rememberNavController()
ChessGame(navController)
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreviewDark() {
KotlinGamesTheme(darkTheme = true) {
val navController = rememberNavController()
ChessGame(navController)
}
}
@Preview(showBackground = true)
@Composable
fun PreviewExitAlertLight() {
KotlinGamesTheme {
CustomExitAlert(onDismiss = {}, onAccept = {})
}
}
@Preview(showBackground = true)
@Composable
fun PreviewExitAlertDark() {
KotlinGamesTheme(darkTheme = true) {
CustomExitAlert(onDismiss = {}, onAccept = {})
}
}
@Preview(showBackground = true)
@Composable
fun PreviewMenuLight() {
KotlinGamesTheme(darkTheme = false) {
MenuAlert(
onDismiss = { },
theme = BoardTheme.Black,
onThemeChange = { }
)
}
}
@Preview(showBackground = true)
@Composable
fun PreviewMenuDark() {
KotlinGamesTheme(darkTheme = true) {
MenuAlert(
onDismiss = { },
theme = BoardTheme.Black,
onThemeChange = { }
)
}
}
@Preview(showBackground = true)
@Composable
fun PreviewPromotionLight() {
KotlinGamesTheme(darkTheme = false) {
PawnPromotionDialog(onDismiss = { }, board = Board())
}
}
@Preview(showBackground = true)
@Composable
fun PreviewPromotionDark() {
KotlinGamesTheme(darkTheme = true) {
PawnPromotionDialog(onDismiss = { }, board = Board())
}
} | 0 | Kotlin | 0 | 0 | cc0a00cc8d9d86b86b70937c62bed7e4fe0dd8c5 | 33,177 | kotlin-games | MIT License |
kontrolno1/src/main/kotlin/rali_transport/Coordinate.kt | rostislavdmrv | 874,437,529 | false | {"Kotlin": 3587} | package rali_transport
import java.lang.Math.pow
import kotlin.math.*
class Coordinate(private val longitude:Double,private val latitude:Double) {
private val radiusOfEarth = 6371.0
fun getDistance(other: Coordinate): Double {
val lat1 = Math. toRadians(this. latitude)
val lon1 = Math. toRadians(this. longitude)
val lat2 = Math. toRadians(other.latitude)
val lon2 = Math. toRadians(other.longitude)
val f = sin( lat2 - lat1/ 2) . pow(2.0) + cos(lat1) * cos(lat2) * sin(lon2 - lon1 / 2). pow(2.0)
val sqr = 2 * atan2(sqrt(f), sqrt(1 - f))
val result = radiusOfEarth * sqr
return result
}
} | 0 | Kotlin | 0 | 0 | 117442a798758b2c5d10f109d41d21c3f4dd4a64 | 674 | AndroidDevHub | MIT License |
ui/src/main/java/ru/tinkoff/acquiring/sdk/redesign/cards/list/ui/CardsListState.kt | itlogic | 293,802,517 | true | {"Kotlin": 1162428, "Java": 29422} | package ru.tinkoff.acquiring.sdk.redesign.cards.list.ui
import ru.tinkoff.acquiring.sdk.models.Card
import ru.tinkoff.acquiring.sdk.redesign.cards.list.models.CardItemUiModel
/**
* Created by <NAME>
*/
sealed class CardsListState(val mode: CardListMode, val isInternal: Boolean = false) {
object Shimmer : CardsListState(CardListMode.STUB)
object Empty : CardsListState(CardListMode.STUB)
class Error(val throwable: Throwable) : CardsListState(CardListMode.STUB)
object NoNetwork : CardsListState(CardListMode.STUB)
class Content(
mode: CardListMode,
isInternal: Boolean,
val cards: List<CardItemUiModel>
) : CardsListState(mode, isInternal)
}
sealed class CardListEvent {
class RemoveCardProgress(
val deletedCard: CardItemUiModel
) : CardListEvent()
class RemoveCardSuccess(
val deletedCard: CardItemUiModel,
val indexAt: Int?) : CardListEvent()
object ShowError : CardListEvent()
class ShowCardDeleteError(val it: Throwable) : CardListEvent()
class ShowCardAttachDialog(val it: String) : CardListEvent()
class SelectCard(val selectedCard: Card) : CardListEvent()
object SelectCancel : CardListEvent()
object SelectNewCard : CardListEvent()
}
sealed class CardListNav {
object ToAttachCard : CardListNav()
}
enum class CardListMode {
ADD, DELETE, STUB, CHOOSE
} | 0 | Kotlin | 0 | 0 | 8de009c2ae6ca40843c74799429346fcfa74820c | 1,396 | AcquiringSdkAndroid | Apache License 2.0 |
app/src/main/java/com/grumpyshoe/lumos/core/data/src/network/dto/ImageDto.kt | lumos-app | 179,739,531 | false | null | package com.grumpyshoe.lumos.core.data.src.network.dto
import android.os.Parcel
import android.os.Parcelable
import java.util.Date
/**
* Network object
*
* Created by <NAME> on 10.06.19.
* Copyright © 2019 <NAME>. All rights reserved.
*/
data class ImageDto(
val uuid: String? = null,
val filename: String? = null,
val uploadedFrom: String? = null,
val totalViewCount: Long? = null,
val createdDate: Date? = null,
val show: Boolean? = null,
val data: String? = null
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readValue(Long::class.java.classLoader) as? Long,
Date(parcel.readLong()),
parcel.readValue(Boolean::class.java.classLoader) as? Boolean,
parcel.readString()
)
/**
* check if entry is valid
*
*/
fun isValid(): Boolean {
return (!uuid.isNullOrEmpty() &&
!filename.isNullOrEmpty() &&
// !uploadedFrom.isNullOrEmpty() &&
totalViewCount != null &&
createdDate != null &&
show != null &&
!data.isNullOrEmpty()) // TODO : add flag to see if thumbnail has been created
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(uuid)
parcel.writeString(filename)
parcel.writeString(uploadedFrom)
parcel.writeValue(totalViewCount)
parcel.writeLong(createdDate?.time ?: 0L)
parcel.writeValue(show)
parcel.writeString(data)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<ImageDto> {
override fun createFromParcel(parcel: Parcel): ImageDto {
return ImageDto(parcel)
}
override fun newArray(size: Int): Array<ImageDto?> {
return arrayOfNulls(size)
}
}
} | 0 | Kotlin | 0 | 0 | 376a6363c669a324b52c6728ac6e834144a8e863 | 1,979 | lumos-android | MIT License |
src/test/kotlin/com/xrpn/immutable/flisttest/FListFilteringTest.kt | xrpn | 364,037,871 | false | null | package com.xrpn.immutable.flisttest
import com.xrpn.imapi.IMList
import com.xrpn.imapi.IMListFiltering
import com.xrpn.immutable.FLCons
import com.xrpn.immutable.FLNil
import com.xrpn.immutable.FList
import com.xrpn.immutable.emptyArrayOfInt
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private val intListOfNone: IMList<Int> = FList.of(*emptyArrayOfInt)
private val intListOfOne: IMList<Int> = FList.of(*arrayOf<Int>(1))
private val intListOfTwo: IMList<Int> = FList.of(*arrayOf<Int>(1,2))
private val intListOfThree: IMList<Int> = FList.of(*arrayOf<Int>(1,2,3))
private val intListOfFour: IMList<Int> = FList.of(*arrayOf<Int>(1,2,1,3))
private val intListOfFourA: IMList<Int> = FList.of(*arrayOf<Int>(1,2,2,3))
private val intListOfFourB: IMList<Int> = FList.of(*arrayOf<Int>(1,2,3,2))
class FListFilteringTest : FunSpec({
beforeTest {}
test("fdropFirst") {
intListOfNone.fdropFirst { it > 1 } shouldBe FLNil
intListOfOne.fdropFirst { it > 1 } shouldBe FLCons(1,FLNil)
FList.of(*arrayOf<Int>(2,1)).fdropFirst { it > 1 } shouldBe FLCons(1,FLNil)
FList.of(*arrayOf<Int>(3,2,1)).fdropFirst { it > 1 } shouldBe FLCons(2, FLCons(1,FLNil))
FList.of(*arrayOf<Int>(3,2,1,0)).fdropFirst { it == 2 } shouldBe FLCons(3, FLCons(1,FLCons(0,FLNil)))
FList.of(*arrayOf<Int>(3,2,1,0)).fdropFirst { it < 3 } shouldBe FLCons(3, FLCons(1,FLCons(0,FLNil)))
}
test("fdropRight") {
intListOfNone.fdropRight(1) shouldBe intListOfNone
intListOfOne.fdropRight(0) shouldBe intListOfOne
intListOfThree.fdropRight(1) shouldBe intListOfTwo
intListOfThree.fdropRight(2) shouldBe intListOfOne
intListOfThree.fdropRight(3) shouldBe intListOfNone
}
test("fdropRight negative") {
intListOfNone.fdropRight(-1) shouldBe FLNil
intListOfThree.fdropRight(-1) shouldBe FLNil
intListOfThree.fdropRight(-2) shouldBe FLNil
intListOfThree.fdropRight(-3) shouldBe FLNil
}
test("fdropWhile") {
intListOfNone.fdropWhile { it > 1 } shouldBe FLNil
intListOfOne.fdropWhile { it > 1 } shouldBe FLCons(1,FLNil)
FList.of(*arrayOf<Int>(2,1)).fdropWhile { it > 1 } shouldBe FLCons(1,FLNil)
FList.of(*arrayOf<Int>(3,2,1)).fdropWhile { it > 1 } shouldBe FLCons(1,FLNil)
FList.of(*arrayOf<Int>(3,2,1,0)).fdropWhile { it > 1 } shouldBe FLCons(1,FLCons(0,FLNil))
intListOfFour.fdropWhile { it > 1 } shouldBe intListOfFour
intListOfFourA.fdropWhile { it < 2 } shouldBe FLCons(2, FLCons(2, FLCons(3, FLNil)))
intListOfFourA.fdropWhile { it < 3 } shouldBe FLCons(3, FLNil)
intListOfFourB.fdropWhile { it < 3 } shouldBe FLCons(3, FLCons(2, FLNil))
}
test("ffind") {
intListOfNone.ffind { _ -> true } shouldBe null
intListOfNone.ffind { _ -> false } shouldBe null
intListOfOne.ffind { 0 < it } shouldBe 1
intListOfOne.ffind { _ -> false } shouldBe null
intListOfThree.ffind { 0 < it } shouldBe 1
intListOfThree.ffind { 1 < it } shouldBe 2
intListOfThree.ffind { 2 < it } shouldBe 3
intListOfThree.ffind { 3 < it } shouldBe null
intListOfThree.ffind { it < 3 } shouldBe 1
intListOfThree.ffind { it < 2 } shouldBe 1
}
test("ffindLast") {
intListOfNone.ffindLast { _ -> true } shouldBe null
intListOfNone.ffindLast { _ -> false } shouldBe null
intListOfOne.ffindLast { 0 < it } shouldBe 1
intListOfOne.ffindLast { _ -> false } shouldBe null
intListOfThree.ffindLast { 0 < it } shouldBe 3
intListOfThree.ffindLast { 1 < it } shouldBe 3
intListOfThree.ffindLast { 2 < it } shouldBe 3
intListOfThree.ffindLast { 3 < it } shouldBe null
intListOfThree.ffindLast { it < 3 } shouldBe 2
intListOfThree.ffindLast { it < 2 } shouldBe 1
}
test("fgetOrNull") {
intListOfNone.fgetOrNull(0) shouldBe null
intListOfOne.fgetOrNull(-1) shouldBe null
intListOfOne.fgetOrNull(0) shouldBe 1
intListOfOne.fgetOrNull(1) shouldBe null
intListOfThree.fgetOrNull(-1) shouldBe null
intListOfThree.fgetOrNull(0) shouldBe 1
intListOfThree.fgetOrNull(1) shouldBe 2
intListOfThree.fgetOrNull(2) shouldBe 3
intListOfThree.fgetOrNull(3) shouldBe null
}
test("fhasSubsequence") {
intListOfNone.fhasSubsequence(FList.of(*emptyArrayOfInt)) shouldBe true
intListOfNone.fhasSubsequence(intListOfOne) shouldBe false
intListOfOne.fhasSubsequence(intListOfNone) shouldBe true
intListOfOne.fhasSubsequence(intListOfOne) shouldBe true
intListOfOne.fhasSubsequence(intListOfTwo) shouldBe false
intListOfTwo.fhasSubsequence(intListOfNone) shouldBe true
intListOfTwo.fhasSubsequence(intListOfOne) shouldBe true
intListOfTwo.fhasSubsequence(FLCons(2, FLNil) as IMList<Int>) shouldBe true
intListOfTwo.fhasSubsequence(intListOfTwo) shouldBe true
intListOfTwo.fhasSubsequence(intListOfTwo.freverse()) shouldBe false
intListOfTwo.fhasSubsequence(intListOfThree) shouldBe false
intListOfThree.fhasSubsequence(intListOfNone) shouldBe true
intListOfThree.fhasSubsequence(intListOfOne) shouldBe true
intListOfThree.fhasSubsequence(FLCons(2, FLNil) as IMList<Int>) shouldBe true
intListOfThree.fhasSubsequence(FLCons(3, FLNil) as IMList<Int>) shouldBe true
intListOfThree.fhasSubsequence(intListOfTwo) shouldBe true
intListOfThree.fhasSubsequence(FLCons(2, FLCons(3, FLNil)) as IMList<Int>) shouldBe true
intListOfThree.fhasSubsequence(FLCons(1, FLCons(3, FLNil)) as IMList<Int>) shouldBe false
intListOfThree.fhasSubsequence(intListOfTwo.freverse()) shouldBe false
intListOfThree.fhasSubsequence(intListOfThree.freverse()) shouldBe false
intListOfThree.fhasSubsequence(intListOfThree) shouldBe true
}
test("fhead") {
intListOfNone.fhead() shouldBe null
intListOfOne.fhead() shouldBe 1
intListOfTwo.fhead() shouldBe 1
}
test("finit") {
intListOfNone.finit() shouldBe FLNil
intListOfOne.finit() shouldBe FLNil
intListOfTwo.finit() shouldBe FLCons(1,FLNil)
intListOfThree.finit() shouldBe FLCons(1,FLCons(2,FLNil))
}
test("flast") {
intListOfNone.flast() shouldBe null
intListOfOne.flast() shouldBe 1
intListOfTwo.flast() shouldBe 2
intListOfThree.flast() shouldBe 3
}
test("fslice (ix, ix)") {
intListOfNone.fslice(0, 0) shouldBe FLNil
intListOfOne.fslice(0, 0) shouldBe FLNil
intListOfOne.fslice(1, 0) shouldBe FLNil
intListOfOne.fslice(0, 1) shouldBe intListOfOne
intListOfTwo.fslice(1, 0) shouldBe FLNil
intListOfTwo.fslice(0, 1) shouldBe intListOfOne
intListOfTwo.fslice(0, 2) shouldBe intListOfTwo
intListOfThree.fslice(0, 0) shouldBe FLNil
intListOfThree.fslice(1, 1) shouldBe FLNil
intListOfThree.fslice(2, 2) shouldBe FLNil
intListOfThree.fslice(3, 3) shouldBe FLNil
intListOfThree.fslice(0, 1) shouldBe intListOfOne
intListOfThree.fslice(0, 2) shouldBe intListOfTwo
intListOfThree.fslice(0, 3) shouldBe intListOfThree
intListOfThree.fslice(1, 2) shouldBe FLCons(2, FLNil)
intListOfThree.fslice(1, 3) shouldBe FLCons(2, FLCons(3, FLNil))
intListOfThree.fslice(2, 3) shouldBe FLCons(3, FLNil)
}
test("fslice (IMList)") {
intListOfThree.fselect(FLNil) shouldBe FLNil
intListOfThree.fselect(FList.of(-1)) shouldBe FLNil
intListOfThree.fselect(FList.of(0)) shouldBe intListOfOne
intListOfThree.fselect(FList.of(1)) shouldBe FLCons(2, FLNil)
intListOfThree.fselect(FList.of(2)) shouldBe FLCons(3, FLNil)
intListOfThree.fselect(FList.of(3)) shouldBe FLNil
intListOfThree.fselect(FList.of(1, 2)) shouldBe FLCons(2, FLCons(3, FLNil))
intListOfThree.fselect(FList.of(-1, 1, 2, 5)) shouldBe FLCons(2, FLCons(3, FLNil))
intListOfThree.fselect(FList.of(2, -1, 1, 5)) shouldBe FLCons(3, FLCons(2, FLNil))
}
test("ftail") {
intListOfNone.ftail() shouldBe FLNil
intListOfOne.ftail() shouldBe FLNil
intListOfTwo.ftail() shouldBe FLCons(2,FLNil)
intListOfThree.ftail() shouldBe FLCons(2,FLCons(3,FLNil))
}
test("ftake 0") {
intListOfNone.ftake(0) shouldBe FLNil
intListOfOne.ftake(0) shouldBe FLNil
intListOfTwo.ftake(0) shouldBe FLNil
intListOfThree.ftake(0) shouldBe FLNil
}
test("ftake 1") {
intListOfNone.ftake(1) shouldBe FLNil
intListOfOne.ftake(1) shouldBe intListOfOne
intListOfTwo.ftake(1) shouldBe intListOfOne
intListOfThree.ftake(1) shouldBe intListOfOne
}
test("ftake 2") {
intListOfNone.ftake(2) shouldBe FLNil
intListOfOne.ftake(2) shouldBe intListOfOne
intListOfTwo.ftake(2) shouldBe intListOfTwo
intListOfThree.ftake(2) shouldBe intListOfTwo
FList.of(*arrayOf<Int>(1,2,3,4)).ftake(2) shouldBe intListOfTwo
}
test("ftake 3") {
intListOfNone.ftake(3) shouldBe FLNil
intListOfOne.ftake(3) shouldBe intListOfOne
intListOfTwo.ftake(3) shouldBe intListOfTwo
intListOfThree.ftake(3) shouldBe intListOfThree
FList.of(*arrayOf<Int>(1,2,3,4)).ftake(3) shouldBe intListOfThree
}
test("ftake (negative)") {
intListOfOne.ftake(-1) shouldBe FLNil
intListOfTwo.ftake(-1) shouldBe FLNil
intListOfTwo.ftake(-2) shouldBe FLNil
intListOfTwo.ftake(-3) shouldBe FLNil
intListOfThree.ftake(-1) shouldBe FLNil
intListOfThree.ftake(-2) shouldBe FLNil
intListOfThree.ftake(-3) shouldBe FLNil
}
test("ftakeRight") {
intListOfNone.ftakeRight(0) shouldBe intListOfNone
intListOfOne.ftakeRight(0) shouldBe intListOfNone
intListOfOne.ftakeRight(1) shouldBe intListOfOne
intListOfTwo.ftakeRight(0) shouldBe intListOfNone
intListOfTwo.ftakeRight(1) shouldBe FLCons(2, FLNil)
intListOfTwo.ftakeRight(2) shouldBe intListOfTwo
intListOfTwo.ftakeRight(3) shouldBe intListOfTwo
intListOfThree.ftakeRight(0) shouldBe intListOfNone
intListOfThree.ftakeRight(1) shouldBe FLCons(3, FLNil)
intListOfThree.ftakeRight(2) shouldBe FLCons(2, FLCons(3, FLNil))
intListOfThree.ftakeRight(3) shouldBe intListOfThree
}
test("ftakeRight (negative)") {
intListOfOne.ftakeRight(-1) shouldBe FLNil
intListOfTwo.ftakeRight(-1) shouldBe FLNil
intListOfTwo.ftakeRight(-2) shouldBe FLNil
intListOfTwo.ftakeRight(-3) shouldBe FLNil
intListOfThree.ftakeRight(-1) shouldBe FLNil
intListOfThree.ftakeRight(-2) shouldBe FLNil
intListOfThree.ftakeRight(-3) shouldBe FLNil
}
test("ftakeWhile") {
intListOfNone.ftakeWhile { it > 1 } shouldBe FLNil
intListOfOne.ftakeWhile { it == 1 } shouldBe FLCons(1,FLNil)
FList.of(*arrayOf<Int>(2,1)).ftakeWhile { it > 1 } shouldBe FLCons(2,FLNil)
FList.of(*arrayOf<Int>(3,2,1)).ftakeWhile { it > 1 } shouldBe FLCons(3,FLCons(2,FLNil))
FList.of(*arrayOf<Int>(3,2,1,0)).ftakeWhile { it != 1 } shouldBe FLCons(3,FLCons(2,FLNil))
}
})
| 0 | Kotlin | 1 | 3 | 09da19a3b49d41ae0679b853b4efe4605ba319f6 | 10,704 | immutable-kotlin | Apache License 2.0 |
AndroidBroadcastReceiverExample/app/src/main/java/com/waynestalk/broadcastreceiverexample/AirplaneModeBroadcastReceiver.kt | xhhuango | 262,588,464 | false | {"Jupyter Notebook": 49573021, "Kotlin": 265587, "Swift": 163046, "TypeScript": 14366, "Go": 8073, "Shell": 4571, "JavaScript": 3704, "HTML": 3547, "Ruby": 1806, "Objective-C": 908, "SCSS": 80, "CSS": 25} | package com.waynestalk.broadcastreceiverexample
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
class AirplaneModeBroadcastReceiver : BroadcastReceiver() {
companion object {
private const val TAG = "AirplaneModeBroadcast"
}
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_AIRPLANE_MODE_CHANGED) return
val isOn = intent.getBooleanExtra("state", false)
val message = "Airplane mode is ${if (isOn) "on" else "off"}."
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
} | 0 | Jupyter Notebook | 19 | 24 | c2702503ff55f221a58d6b384d87d8d12cb0be12 | 666 | waynestalk | MIT License |
app/src/main/java/com/thezayin/kainaclean/presentation/onboarding/OnBoardingScreen.kt | thezayin | 761,579,033 | false | {"Kotlin": 137350} | package com.thezayin.kainaclean.presentation.onboarding
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.thezayin.kainaclean.R
import com.thezayin.kainaclean.presentation.auth.AuthViewModel
import com.thezayin.kainaclean.presentation.destinations.HomeScreenDestination
import com.thezayin.kainaclean.presentation.destinations.LoginScreenDestination
@Composable
@Destination(start = true)
fun OnBoardingScreen(
navigator: DestinationsNavigator
) {
val authViewModel: AuthViewModel = hiltViewModel()
var isClicked by remember { mutableStateOf(false) }
Box(modifier = Modifier.fillMaxSize()) {
Image(
painter = painterResource(id = R.drawable.ic_onboarding),
contentDescription = "",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
}
Column(
modifier = Modifier
.fillMaxSize()
.background(
brush = Brush.linearGradient(
colors = listOf(
colorResource(id = R.color.color_starting),
colorResource(id = R.color.color_starting),
colorResource(id = R.color.color_mid),
colorResource(id = R.color.color_end)
)
)
),
verticalArrangement = Arrangement.Bottom,
) {
Text(
text = "Kaina Cleaner",
fontSize = 26.sp,
fontWeight = FontWeight.Bold,
color = colorResource(id = R.color.white),
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "The Best Cleaning Service Ever!",
fontSize = 26.sp,
fontWeight = FontWeight.Bold,
color = colorResource(id = R.color.white),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 27.dp)
)
Button(
onClick = {
isClicked = true
},
modifier = Modifier
.padding(24.dp, 44.dp)
.fillMaxWidth()
.height(50.dp),
colors = ButtonDefaults.buttonColors(
containerColor = colorResource(id = R.color.yellow),
contentColor = Color.White
),
shape = RoundedCornerShape(size = 6.dp)
) {
Text(
text = "Get Started", fontSize = 22.sp,
color = colorResource(id = R.color.white),
textAlign = TextAlign.Center,
)
}
}
if (isClicked) {
AuthState(navigator = navigator, authViewModel = authViewModel)
}
}
@Composable
private fun AuthState(
navigator: DestinationsNavigator,
authViewModel: AuthViewModel
) {
if (authViewModel.isUserAuthenticated) {
navigator.navigate(HomeScreenDestination)
} else {
navigator.navigate(LoginScreenDestination)
}
}
| 0 | Kotlin | 0 | 1 | 139ba23f2d10ec143154a328667df2bb71f97568 | 4,500 | Kaina_Clean | The Unlicense |
domain/src/main/java/tachiyomi/domain/items/episode/service/EpisodeSorter.kt | aniyomiorg | 358,887,741 | false | null | package tachiyomi.domain.items.episode.service
import tachiyomi.core.util.lang.compareToWithCollator
import tachiyomi.domain.entries.anime.model.Anime
import tachiyomi.domain.items.episode.model.Episode
fun getEpisodeSort(anime: Anime, sortDescending: Boolean = anime.sortDescending()): (
Episode,
Episode,
) -> Int {
return when (anime.sorting) {
Anime.EPISODE_SORTING_SOURCE -> when (sortDescending) {
true -> { e1, e2 -> e1.sourceOrder.compareTo(e2.sourceOrder) }
false -> { e1, e2 -> e2.sourceOrder.compareTo(e1.sourceOrder) }
}
Anime.EPISODE_SORTING_NUMBER -> when (sortDescending) {
true -> { e1, e2 -> e2.episodeNumber.compareTo(e1.episodeNumber) }
false -> { e1, e2 -> e1.episodeNumber.compareTo(e2.episodeNumber) }
}
Anime.EPISODE_SORTING_UPLOAD_DATE -> when (sortDescending) {
true -> { e1, e2 -> e2.dateUpload.compareTo(e1.dateUpload) }
false -> { e1, e2 -> e1.dateUpload.compareTo(e2.dateUpload) }
}
Anime.EPISODE_SORTING_ALPHABET -> when (sortDescending) {
true -> { e1, e2 -> e2.name.compareToWithCollator(e1.name) }
false -> { e1, e2 -> e1.name.compareToWithCollator(e2.name) }
}
else -> throw NotImplementedError("Invalid episode sorting method: ${anime.sorting}")
}
}
| 232 | null | 315 | 4,992 | 823099f775ef608b7c11f096da1f50762dab82df | 1,371 | aniyomi | Apache License 2.0 |
desktop/src/main/kotlin/app/softwork/composetodo/DesktopContainer.kt | hfhbd | 286,300,714 | false | null | package app.softwork.composetodo
import app.softwork.composetodo.repository.*
import app.softwork.composetodo.viewmodels.*
import com.squareup.sqldelight.db.*
import com.squareup.sqldelight.sqlite.driver.*
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.features.*
import io.ktor.http.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
class DesktopContainer(private val scope: CoroutineScope) : AppContainer {
override val driver: SqlDriver = JdbcSqliteDriver("jdbc:sqlite:composetodo.db")
override fun todoViewModel(api: API.LoggedIn): TodoViewModel =
TodoViewModel(scope, TodoRepository(api, driver) { schema ->
schema.create(driver)
})
override fun loginViewModel(api: API.LoggedOut) = LoginViewModel(scope, api) {
isLoggedIn.value = it
}
override fun registerViewModel(api: API.LoggedOut) = RegisterViewModel(scope, api) {
isLoggedIn.value = it
}
override val client = HttpClient(CIO) {
defaultRequest {
url {
protocol = URLProtocol.HTTPS
host = "api.todo.softwork.app"
}
}
}
override val isLoggedIn: MutableStateFlow<API> = MutableStateFlow(API.LoggedOut(client))
}
| 2 | Kotlin | 1 | 28 | d52fe552203bbfe1613c948c03ff7d104a15c08f | 1,274 | ComposeTodo | Apache License 2.0 |
app/src/main/java/org/jnanaprabodhini/happyteacherapp/util/LocaleManager.kt | HappyTeacher | 102,859,416 | false | null | package org.jnanaprabodhini.happyteacherapp.util
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import org.jnanaprabodhini.happyteacherapp.R
import java.util.*
/**
* A singleton object for managing language in the app.
*
* 🙏
* Thanks to this blog post:
* https://proandroiddev.com/change-language-programmatically-at-runtime-on-android-5e6bc15c758
*/
object LocaleManager {
fun changeLocale(newLocale: String, context: Context) {
val prefs = PreferencesManager.getInstance(context)
prefs.setCurrentLanguageCode(newLocale)
// Make user choose a new board (since current
// choice may not be available in this new locale):
prefs.resetBoardChoice()
}
fun setLocale(context: Context): Context {
val prefs = PreferencesManager.getInstance(context)
val language = prefs.getCurrentLanguageCode()
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val config = Configuration(resources.configuration)
if (Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale)
return context.createConfigurationContext(config)
} else {
config.locale = locale
resources.updateConfiguration(config, resources.displayMetrics)
}
return context
}
data class LocaleCodeWithTitle(val code: String, val title: String) {
override fun toString(): String = title
}
fun getSupportedLanguagesWithTitles(context: Context) = arrayOf(
LocaleCodeWithTitle("en", context.getString(R.string.english_in_english)),
LocaleCodeWithTitle("mr", context.getString(R.string.marathi_in_marathi))
)
fun getCurrentLocale(context: Context): Locale {
val prefs = PreferencesManager.getInstance(context)
return Locale(prefs.getCurrentLanguageCode())
}
} | 6 | null | 1 | 2 | 5487bcdefb8f0e8452d21e160a95b869290d4e23 | 1,961 | HappyTeacherAndroid | Apache License 2.0 |
app/src/main/java/com/weatherxm/usecases/ForecastUseCaseImpl.kt | WeatherXM | 728,657,649 | false | null | package com.weatherxm.usecases
import arrow.core.Either
import com.weatherxm.data.ApiError
import com.weatherxm.data.Failure
import com.weatherxm.data.HourlyWeather
import com.weatherxm.data.network.ErrorResponse.Companion.INVALID_TIMEZONE
import com.weatherxm.data.repository.WeatherForecastRepository
import com.weatherxm.ui.common.UIDevice
import com.weatherxm.ui.common.UIForecast
import com.weatherxm.ui.common.UIForecastDay
import com.weatherxm.util.isSameDayAndHour
import java.time.ZoneId
import java.time.ZonedDateTime
@Suppress("LongParameterList")
class ForecastUseCaseImpl(
private val weatherForecastRepository: WeatherForecastRepository
) : ForecastUseCase {
@Suppress("MagicNumber")
override suspend fun getForecast(
device: UIDevice,
forceRefresh: Boolean
): Either<Failure, UIForecast> {
if (device.timezone.isNullOrEmpty()) {
return Either.Left(ApiError.UserError.InvalidTimezone(INVALID_TIMEZONE))
}
val nowDeviceTz = ZonedDateTime.now(ZoneId.of(device.timezone))
val dateEndInDeviceTz = nowDeviceTz.plusDays(7)
return weatherForecastRepository.getDeviceForecast(
device.id,
nowDeviceTz,
dateEndInDeviceTz,
forceRefresh
).map { result ->
val nextHourlyWeatherForecast = mutableListOf<HourlyWeather>()
val forecastDays = result.map { weatherData ->
weatherData.hourly?.filter {
val isCurrentHour = it.timestamp.isSameDayAndHour(nowDeviceTz)
val isFutureHour = it.timestamp.isAfter(nowDeviceTz)
isCurrentHour || (isFutureHour && it.timestamp < nowDeviceTz.plusHours(24))
}?.apply {
nextHourlyWeatherForecast.addAll(this)
}
UIForecastDay(
weatherData.date,
icon = weatherData.daily?.icon,
maxTemp = weatherData.daily?.temperatureMax,
minTemp = weatherData.daily?.temperatureMin,
precipProbability = weatherData.daily?.precipProbability,
precip = weatherData.daily?.precipIntensity,
windSpeed = weatherData.daily?.windSpeed,
windDirection = weatherData.daily?.windDirection,
humidity = weatherData.daily?.humidity,
pressure = weatherData.daily?.pressure,
uv = weatherData.daily?.uvIndex,
hourlyWeather = weatherData.hourly
)
}
UIForecast(nextHourlyWeatherForecast, forecastDays)
}
}
}
| 2 | null | 2 | 13 | c3320ce6d0e5018da3868e14414ce9a723213b32 | 2,705 | wxm-android | Apache License 2.0 |
client/src/main/kotlin/com/lsdconsulting/exceptionhandling/client/exception/InternalServerException.kt | lsd-consulting | 463,933,707 | false | null | package com.lsdconsulting.exceptionhandling.client.exception
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.lsdconsulting.exceptionhandling.api.ErrorResponse
import org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
@JsonDeserialize(using = InternalServerExceptionDeserializer::class)
class InternalServerException : ErrorResponseException {
constructor(errorResponse: ErrorResponse?) : super(errorResponse, INTERNAL_SERVER_ERROR)
constructor(message: String) : super(message, INTERNAL_SERVER_ERROR)
}
class InternalServerExceptionDeserializer : JsonDeserializer<InternalServerException>() {
override fun deserialize(jp: JsonParser, dc: DeserializationContext): InternalServerException {
val errorResponse = jp.readValueAs(ErrorResponse::class.java)
return InternalServerException(errorResponse)
}
}
| 0 | Kotlin | 0 | 1 | 7e1f222ddc037dfe022abf23765de80ac781a2ea | 1,032 | spring-http-exception-handling-library | MIT License |
PreparationApp/app/src/main/java/com/jbavaji/preparationapp/presentation/screen/authentication/signup/UserInputType.kt | JBavaji | 508,955,291 | false | null | package com.jbavaji.preparationapp.presentation.screen.authentication.signup
enum class UserInputType {
EMAIL,
PASSWORD
}
| 0 | Kotlin | 0 | 0 | 8da4c4a3044535daffb8c96eed84c66b9b99681c | 131 | preparing-2022-tech-stack-application | MIT License |
javapoet-dsl/src/main/kotlin/com/hendraanggrian/javapoet/JavapoetSpecDsl.kt | hendraanggrian | 169,205,951 | false | {"Kotlin": 139216, "CSS": 1653} | package com.hanggrian.javapoet
/**
* Delimits spec builders' DSL. Code and javadoc builders are not tagged because some specs may
* implement them.
*/
@DslMarker
@Target(AnnotationTarget.CLASS)
public annotation class JavapoetDsl
| 1 | Kotlin | 1 | 5 | fd452bd62bc8b6a2f8e8ad11e42518515d39be0e | 234 | javapoet-dsl | Apache License 2.0 |
lib/geomaglocation/src/main/java/se/gustavkarlsson/skylight/android/lib/geomaglocation/GeomagLocationComponent.kt | gustavkarlsson | 128,669,768 | false | null | package se.gustavkarlsson.skylight.android.lib.geomaglocation
import se.gustavkarlsson.skylight.android.core.services.ChanceEvaluator
import se.gustavkarlsson.skylight.android.core.services.Formatter
interface GeomagLocationComponent {
fun geomagLocationChanceEvaluator(): ChanceEvaluator<GeomagLocation>
fun geomagLocationFormatter(): Formatter<GeomagLocation>
interface Setter {
fun setGeomagLocationComponent(component: GeomagLocationComponent) {
instance = component
}
}
companion object {
lateinit var instance: GeomagLocationComponent
private set
}
}
| 0 | Kotlin | 2 | 5 | 4726d86c7ae6c0333e78d1d8cde9a7658ff67cd7 | 635 | skylight-android | MIT License |
app-feature/home/src/iosMain/kotlin/dev/sergiobelda/todometer/app/feature/home/ui/HomeMoreDropdownMenu.kt | serbelga | 301,817,067 | false | {"Kotlin": 553475, "Swift": 763} | /*
* Copyright 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 dev.sergiobelda.todometer.common.compose.ui.home
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import dev.sergiobelda.todometer.common.resources.MR
import dev.sergiobelda.todometer.common.resources.ToDometerIcons
import dev.sergiobelda.todometer.common.resources.stringResource
@Composable
internal actual fun HomeMoreDropdownMenu(
expanded: Boolean,
onDismissRequest: () -> Unit,
onEditTaskListClick: () -> Unit,
onDeleteTaskListClick: () -> Unit
) {
DropdownMenu(
expanded = expanded,
onDismissRequest = onDismissRequest
) {
// TODO: Add icons and supportingText when use DropdownMenuItem from material3
DropdownMenuItem(
onClick = onEditTaskListClick,
leadingIcon = { Icon(ToDometerIcons.Edit, contentDescription = null) },
text = { Text(stringResource(MR.strings.edit_task_list)) }
)
DropdownMenuItem(
onClick = onDeleteTaskListClick,
leadingIcon = {
Icon(
ToDometerIcons.Delete,
contentDescription = null
)
},
text = { Text(stringResource(MR.strings.delete_task_list)) }
)
}
}
| 8 | Kotlin | 37 | 585 | 9a097cd4df924cbf66c0b6af6fa1fed667d30ca0 | 1,996 | Todometer-KMP | Apache License 2.0 |
app/shared/feature-flag/public/src/commonMain/kotlin/build/wallet/feature/flags/UtxoMaxConsolidationCountFeatureFlag.kt | proto-at-block | 761,306,853 | false | {"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.feature.flags
import build.wallet.feature.FeatureFlag
import build.wallet.feature.FeatureFlagDao
import build.wallet.feature.FeatureFlagValue
class UtxoMaxConsolidationCountFeatureFlag(
featureFlagDao: FeatureFlagDao,
) : FeatureFlag<FeatureFlagValue.DoubleFlag>(
identifier = "mobile-utxo-consolidation-max-count",
title = "Mobile UTXO Consolidation Max Count",
description = "Defines the maximum number of utxos that can be consolidated at once",
defaultFlagValue = FeatureFlagValue.DoubleFlag(-1.0),
featureFlagDao = featureFlagDao,
type = FeatureFlagValue.DoubleFlag::class
)
| 3 | C | 16 | 113 | 694c152387c1fdb2b6be01ba35e0a9c092a81879 | 631 | bitkey | MIT License |
moreapps/src/main/java/io/github/raghavsatyadev/moreapps/utils/MoreAppsPrefUtil.kt | raghavsatyadev | 163,333,560 | false | null | @file:Suppress("MemberVisibilityCanBePrivate")
package io.github.raghavsatyadev.moreapps.utils
import android.content.Context
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import io.github.raghavsatyadev.moreapps.kotlinFileName
import io.github.raghavsatyadev.moreapps.model.MoreAppsDetails
object MoreAppsPrefUtil {
fun getMoreApps(context: Context): ArrayList<MoreAppsDetails> {
return convertStringToModel(getMoreAppsString(context))
}
fun getMoreAppsString(context: Context): String {
return MoreAppsPrefHelper.getInstance(context)!![AppPrefStrings.MORE_APPS, ""]
}
fun convertStringToModel(json: String): ArrayList<MoreAppsDetails> {
val gson = Gson()
val moreAppsDetails = ArrayList<MoreAppsDetails>()
try {
val appModelsType = object : TypeToken<ArrayList<MoreAppsDetails?>?>() {}.type
val moreAppsModelsTemp = gson.fromJson<List<MoreAppsDetails>>(json, appModelsType)
if (moreAppsModelsTemp != null) {
moreAppsDetails.addAll(moreAppsModelsTemp)
}
} catch (e: JsonSyntaxException) {
AppLog.loge(false, kotlinFileName, "convertStringToModel", e, Exception())
}
return moreAppsDetails
}
fun setMoreApps(context: Context, moreAppsDetails: List<MoreAppsDetails?>?) {
val gson = Gson()
if (moreAppsDetails != null) {
val appModelsJson = gson.toJson(moreAppsDetails)
MoreAppsPrefHelper.getInstance(context)!!
.save(AppPrefStrings.MORE_APPS, appModelsJson)
}
}
fun setMoreApps(context: Context, moreAppsJSON: String) {
if (!TextUtils.isEmpty(moreAppsJSON)) {
MoreAppsPrefHelper.getInstance(context)!!
.save(AppPrefStrings.MORE_APPS, moreAppsJSON)
}
}
fun isFirstTimePeriodic(context: Context): Boolean {
return MoreAppsPrefHelper.getInstance(context)!![AppPrefStrings.IS_FIRST_TIME_PERIODIC, true]
}
fun setFirstTimePeriodic(context: Context, status: Boolean) {
MoreAppsPrefHelper.getInstance(context)!!
.save(AppPrefStrings.IS_FIRST_TIME_PERIODIC, status)
}
fun saveCurrentVersion(context: Context, currentVersion: Int) {
saveSoftUpdateShownTimes(context, 0)
saveSoftUpdateNotificationShownTimes(context, 0)
MoreAppsPrefHelper.getInstance(context)!!
.save(AppPrefStrings.CURRENT_VERSION, currentVersion)
}
private fun getCurrentVersion(context: Context): Int {
return MoreAppsPrefHelper.getInstance(context)!![AppPrefStrings.CURRENT_VERSION, 0]
}
fun shouldShowSoftUpdate(context: Context, dialogShowCount: Int, currentVersion: Int): Boolean {
val dialogShownTimes = getSoftUpdateShownTimes(context)
val savedCurrentVersion = getCurrentVersion(context)
if (currentVersion > savedCurrentVersion) {
saveCurrentVersion(context, currentVersion)
return true
}
return dialogShowCount == 0 || dialogShowCount > dialogShownTimes
}
private fun getSoftUpdateShownTimes(context: Context): Int {
return MoreAppsPrefHelper.getInstance(context)!![AppPrefStrings.DIALOG_SHOW_COUNT, 0]
}
fun saveSoftUpdateShownTimes(context: Context?, softUpdateShownTimes: Int) {
MoreAppsPrefHelper.getInstance(context!!)!!
.save(AppPrefStrings.DIALOG_SHOW_COUNT, softUpdateShownTimes)
}
fun increaseSoftUpdateShownTimes(context: Context) {
var softUpdateShownTimes = getSoftUpdateShownTimes(context)
softUpdateShownTimes++
saveSoftUpdateShownTimes(context, softUpdateShownTimes)
}
fun shouldShowSoftUpdateNotification(
context: Context,
notificationShowCount: Int,
currentVersion: Int,
): Boolean {
val notificationShownTimes = getSoftUpdateNotificationShownTimes(context)
val savedCurrentVersion = getCurrentVersion(context)
if (currentVersion > savedCurrentVersion) {
saveCurrentVersion(context, currentVersion)
return true
}
return notificationShowCount == 0 || notificationShowCount > notificationShownTimes
}
private fun getSoftUpdateNotificationShownTimes(context: Context): Int {
return MoreAppsPrefHelper.getInstance(context)!![AppPrefStrings.NOTIFICATION_SHOW_COUNT, 0]
}
fun saveSoftUpdateNotificationShownTimes(
context: Context?,
softUpdateNotificationShownTimes: Int,
) {
MoreAppsPrefHelper.getInstance(context!!)!!
.save(AppPrefStrings.NOTIFICATION_SHOW_COUNT, softUpdateNotificationShownTimes)
}
fun increaseSoftUpdateNotificationShownTimes(context: Context) {
var softUpdateNotificationShownTimes = getSoftUpdateNotificationShownTimes(context)
softUpdateNotificationShownTimes++
saveSoftUpdateNotificationShownTimes(context, softUpdateNotificationShownTimes)
}
internal interface AppPrefStrings {
companion object {
const val MORE_APPS = "MORE_APPS"
const val IS_FIRST_TIME_PERIODIC = "IS_FIRST_TIME_PERIODIC"
const val DIALOG_SHOW_COUNT = "DIALOG_SHOW_COUNT"
const val NOTIFICATION_SHOW_COUNT = "NOTIFICATION_SHOW_COUNT"
const val CURRENT_VERSION = "CURRENT_VERSION"
}
}
} | 0 | Kotlin | 5 | 4 | 5d90235d130a29d738d7adc9df213630b7607379 | 5,496 | MoreApps | Apache License 2.0 |
src/main/kotlin/com/palmlang/palm/frontend/palm/ast/Paths.kt | PalmLang | 241,457,986 | false | null | package com.palmlang.palm.frontend.palm.ast
import com.palmlang.palm.util.TokenIndex
sealed interface PathIdent {
val index: TokenIndex
data class This(override val index: TokenIndex) : PathIdent
data class Super(override val index: TokenIndex) : PathIdent
data class Error(override val index: TokenIndex) : PathIdent
}
data class PathSeg(val ident: PathIdent, val typeArgs: List<TypeArg>?) | 0 | Kotlin | 0 | 2 | e3e539d439be7e8a5b3f517eaa6fec3423c430de | 410 | Palm | Apache License 2.0 |
MyPayTemplate/app/src/main/java/br/uea/transirie/mypay/mypaytemplate2/model/ClienteMinimal.kt | gldnjmat17 | 438,400,051 | false | {"Kotlin": 501915} | package br.uea.transirie.mypay.mypaytemplate2.model
/**
* Esta classe é utilizada para simplificar o retorno de uma consulta por clientes. Ao invés de
* retornar a classe completa, retorna apenas os atributos mais relevantes.
* O nome das propriedades deve casar com o nome da classe que ela simplifica (nesse caso, Cliente)
*
*/
data class ClienteMinimal(val _id: String, val nome: String) | 0 | Kotlin | 0 | 0 | bef2b21101aee9c8f985498532385eee18cb0e05 | 396 | MyPets---Aplicativo | MIT License |
app/src/main/java/chat/rocket/android/helper/ImageHelper.kt | RocketChat | 48,179,404 | false | null | package chat.rocket.android.helper
import android.Manifest
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.media.MediaScannerConnection
import android.os.Environment
import android.text.TextUtils
import android.util.TypedValue
import android.view.ContextThemeWrapper
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.net.toUri
import androidx.core.view.setPadding
import chat.rocket.android.R
import com.facebook.binaryresource.FileBinaryResource
import com.facebook.cache.common.CacheKey
import com.facebook.imageformat.ImageFormatChecker
import com.facebook.imagepipeline.cache.DefaultCacheKeyFactory
import com.facebook.imagepipeline.core.ImagePipelineFactory
import com.facebook.imagepipeline.request.ImageRequest
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.google.android.material.appbar.AppBarLayout
import com.stfalcon.frescoimageviewer.ImageViewer
import timber.log.Timber
import java.io.File
object ImageHelper {
private var cacheKey: CacheKey? = null
// TODO - implement a proper image viewer with a proper Transition
// TODO - We should definitely write our own ImageViewer
fun openImage(context: Context, imageUrl: String, imageName: String) {
var imageViewer: ImageViewer? = null
val request =
ImageRequestBuilder.newBuilderWithSource(imageUrl.toUri())
.setLowestPermittedRequestLevel(ImageRequest.RequestLevel.DISK_CACHE)
.build()
cacheKey = DefaultCacheKeyFactory.getInstance()
.getEncodedCacheKey(request, null)
val pad = context.resources
.getDimensionPixelSize(R.dimen.viewer_toolbar_padding)
val lparams = AppBarLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
val toolbar = Toolbar(context).also {
it.inflateMenu(R.menu.image_actions)
it.setOnMenuItemClickListener {
return@setOnMenuItemClickListener when (it.itemId) {
R.id.action_save_image -> saveImage(context)
else -> true
}
}
val titleSize = context.resources
.getDimensionPixelSize(R.dimen.viewer_toolbar_title)
val titleTextView = TextView(context).also {
it.text = imageName
it.setTextColor(Color.WHITE)
it.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize.toFloat())
it.ellipsize = TextUtils.TruncateAt.END
it.setSingleLine()
it.typeface = Typeface.DEFAULT_BOLD
it.setPadding(pad)
}
val backArrowView = ImageView(context).also {
it.setImageResource(R.drawable.ic_arrow_back_white_24dp)
it.setOnClickListener { imageViewer?.onDismiss() }
it.setPadding(0, pad, pad, pad)
}
val layoutParams = AppBarLayout.LayoutParams(
AppBarLayout.LayoutParams.WRAP_CONTENT,
AppBarLayout.LayoutParams.WRAP_CONTENT
)
it.addView(backArrowView, layoutParams)
it.addView(titleTextView, layoutParams)
}
val appBarLayout = AppBarLayout(context).also {
it.layoutParams = lparams
it.setBackgroundColor(Color.BLACK)
it.addView(
toolbar, AppBarLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
)
}
val builder = ImageViewer.createPipelineDraweeControllerBuilder()
.setImageRequest(request)
.setAutoPlayAnimations(true)
imageViewer = ImageViewer.Builder(context, listOf(imageUrl))
.setOverlayView(appBarLayout)
.setStartPosition(0)
.hideStatusBar(false)
.setCustomDraweeControllerBuilder(builder)
.show()
}
private fun saveImage(context: Context): Boolean {
if (!canWriteToExternalStorage(context)) {
checkWritingPermission(context)
return false
}
if (ImagePipelineFactory.getInstance().mainFileCache.hasKey(cacheKey)) {
val resource = ImagePipelineFactory.getInstance().mainFileCache.getResource(cacheKey)
val cachedFile = (resource as FileBinaryResource).file
val imageFormat = ImageFormatChecker.getImageFormat(resource.openStream())
val imageDir = "${Environment.DIRECTORY_PICTURES}/Rocket.Chat Images/"
val imagePath = Environment.getExternalStoragePublicDirectory(imageDir)
val imageFile =
File(imagePath, "${cachedFile.nameWithoutExtension}.${imageFormat.fileExtension}")
imagePath.mkdirs()
imageFile.createNewFile()
try {
cachedFile.copyTo(imageFile, true)
MediaScannerConnection.scanFile(
context,
arrayOf(imageFile.absolutePath),
null
) { path, uri ->
Timber.i("Scanned $path:")
Timber.i("-> uri=$uri")
}
} catch (ex: Exception) {
Timber.e(ex)
val message = context.getString(R.string.msg_image_saved_failed)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
} finally {
val message = context.getString(R.string.msg_image_saved_successfully)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
return true
}
private fun canWriteToExternalStorage(context: Context): Boolean {
return AndroidPermissionsHelper.checkPermission(
context,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
}
private fun checkWritingPermission(context: Context) {
if (context is ContextThemeWrapper && context.baseContext is Activity) {
val activity = context.baseContext as Activity
AndroidPermissionsHelper.requestPermission(
activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
AndroidPermissionsHelper.WRITE_EXTERNAL_STORAGE_CODE
)
}
}
} | 283 | null | 6 | 877 | f832d59cb2130e5c058f5d9e9de5ff961d5d3380 | 6,626 | Rocket.Chat.Android | MIT License |
src/main/kotlin/no/nav/syfo/dialogmote/database/MotedeltakerArbeidsgiverVarselQuery.kt | navikt | 331,892,633 | false | null | package no.nav.syfo.dialogmote.database
import com.fasterxml.jackson.core.type.TypeReference
import no.nav.syfo.application.database.DatabaseInterface
import no.nav.syfo.application.database.toList
import no.nav.syfo.dialogmote.database.domain.PMotedeltakerArbeidsgiverVarsel
import no.nav.syfo.dialogmote.domain.*
import no.nav.syfo.util.configuredJacksonMapper
import java.sql.Connection
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Timestamp
import java.time.Instant
import java.time.LocalDateTime
import java.util.UUID
const val queryCreateMotedeltakerVarselArbeidsgiver =
"""
INSERT INTO MOTEDELTAKER_ARBEIDSGIVER_VARSEL (
id,
uuid,
created_at,
updated_at,
motedeltaker_arbeidsgiver_id,
varseltype,
pdf,
status,
fritekst,
document) VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb) RETURNING id
"""
private val mapper = configuredJacksonMapper()
fun Connection.createMotedeltakerVarselArbeidsgiver(
commit: Boolean = true,
motedeltakerArbeidsgiverId: Int,
status: String,
varselType: MotedeltakerVarselType,
pdf: ByteArray,
fritekst: String,
document: List<DocumentComponentDTO>,
): Pair<Int, UUID> {
val now = Timestamp.from(Instant.now())
val motedeltakerArbeidsgiverVarselUuid = UUID.randomUUID()
val motedeltakerArbeidsgiverVarselIdList = this.prepareStatement(queryCreateMotedeltakerVarselArbeidsgiver).use {
it.setString(1, motedeltakerArbeidsgiverVarselUuid.toString())
it.setTimestamp(2, now)
it.setTimestamp(3, now)
it.setInt(4, motedeltakerArbeidsgiverId)
it.setString(5, varselType.name)
it.setBytes(6, pdf)
it.setString(7, status)
it.setString(8, fritekst)
it.setObject(9, mapper.writeValueAsString(document))
it.executeQuery().toList { getInt("id") }
}
if (motedeltakerArbeidsgiverVarselIdList.size != 1) {
throw SQLException("Creating MotedeltakerVarselArbeidsgiver failed, no rows affected.")
}
if (commit) {
this.commit()
}
return Pair(motedeltakerArbeidsgiverVarselIdList.first(), motedeltakerArbeidsgiverVarselUuid)
}
const val queryGetMotedeltakerArbeidsgiverVarselForMotedeltaker =
"""
SELECT *
FROM MOTEDELTAKER_ARBEIDSGIVER_VARSEL
WHERE motedeltaker_arbeidsgiver_id = ?
ORDER BY created_at DESC
"""
fun DatabaseInterface.getMotedeltakerArbeidsgiverVarsel(
motedeltakerArbeidsgiverId: Int
): List<PMotedeltakerArbeidsgiverVarsel> {
return this.connection.use { connection ->
connection.prepareStatement(queryGetMotedeltakerArbeidsgiverVarselForMotedeltaker).use {
it.setInt(1, motedeltakerArbeidsgiverId)
it.executeQuery().toList { toPMotedeltakerArbeidsgiverVarsel() }
}
}
}
const val queryGetMotedeltakerArbeidsgiverVarselForMotedeltakerFromUuid =
"""
SELECT *
FROM MOTEDELTAKER_ARBEIDSGIVER_VARSEL
WHERE uuid = ?
ORDER BY created_at DESC
"""
fun DatabaseInterface.getMotedeltakerArbeidsgiverVarsel(
uuid: UUID
): List<PMotedeltakerArbeidsgiverVarsel> {
return this.connection.use { connection ->
connection.prepareStatement(queryGetMotedeltakerArbeidsgiverVarselForMotedeltakerFromUuid).use {
it.setString(1, uuid.toString())
it.executeQuery().toList { toPMotedeltakerArbeidsgiverVarsel() }
}
}
}
const val queryUpdateMotedeltakerArbeidsgiverVarselLestDato =
"""
UPDATE MOTEDELTAKER_ARBEIDSGIVER_VARSEL
SET lest_dato = ?
WHERE uuid = ? AND lest_dato IS NULL
"""
fun Connection.updateMotedeltakerArbeidsgiverVarselLestDato(
motedeltakerArbeidsgiverVarselUuid: UUID
) {
val now = LocalDateTime.now()
this.prepareStatement(queryUpdateMotedeltakerArbeidsgiverVarselLestDato).use {
it.setTimestamp(1, Timestamp.valueOf(now))
it.setString(2, motedeltakerArbeidsgiverVarselUuid.toString())
it.execute()
}
}
const val queryGetMotedeltakerArbeidsgiverVarselWithoutJournalpost =
"""
SELECT *
FROM MOTEDELTAKER_ARBEIDSGIVER_VARSEL
WHERE journalpost_id IS NULL
LIMIT 20
"""
fun DatabaseInterface.getMotedeltakerArbeidsgiverVarselWithoutJournalpost(): List<PMotedeltakerArbeidsgiverVarsel> {
return this.connection.use { connection ->
connection.prepareStatement(queryGetMotedeltakerArbeidsgiverVarselWithoutJournalpost).use {
it.executeQuery().toList { toPMotedeltakerArbeidsgiverVarsel() }
}
}
}
const val queryUpdateMotedeltakerArbeidsgiverVarselJournalpostId =
"""
UPDATE MOTEDELTAKER_ARBEIDSGIVER_VARSEL
SET journalpost_id = ?
WHERE id = ?
"""
fun DatabaseInterface.updateMotedeltakerArbeidsgiverVarselJournalpostId(
motedeltakerArbeidsgiverVarselId: Int,
journalpostId: Int,
) {
this.connection.use { connection ->
connection.prepareStatement(queryUpdateMotedeltakerArbeidsgiverVarselJournalpostId).use {
it.setInt(1, journalpostId)
it.setInt(2, motedeltakerArbeidsgiverVarselId)
it.execute()
}
connection.commit()
}
}
const val queryUpdateMotedeltakerArbeidsgiverVarselRespons =
"""
UPDATE MOTEDELTAKER_ARBEIDSGIVER_VARSEL
SET svar_type = ?, svar_tekst=?, svar_tidspunkt=?
WHERE uuid = ? AND svar_type IS NULL
"""
fun Connection.updateMotedeltakerArbeidsgiverVarselRespons(
motedeltakerArbeidsgiverVarselUuid: UUID,
svarType: DialogmoteSvarType,
svarTekst: String?,
): Int {
return this.prepareStatement(queryUpdateMotedeltakerArbeidsgiverVarselRespons).use {
it.setString(1, svarType.name)
it.setString(2, svarTekst)
it.setTimestamp(3, Timestamp.from(Instant.now()))
it.setString(4, motedeltakerArbeidsgiverVarselUuid.toString())
it.executeUpdate()
}
}
fun ResultSet.toPMotedeltakerArbeidsgiverVarsel(): PMotedeltakerArbeidsgiverVarsel =
PMotedeltakerArbeidsgiverVarsel(
id = getInt("id"),
uuid = UUID.fromString(getString("uuid")),
createdAt = getTimestamp("created_at").toLocalDateTime(),
updatedAt = getTimestamp("updated_at").toLocalDateTime(),
motedeltakerArbeidsgiverId = getInt("motedeltaker_arbeidsgiver_id"),
varselType = MotedeltakerVarselType.valueOf(getString("varseltype")),
pdf = getBytes("pdf"),
status = getString("status"),
lestDato = getTimestamp("lest_dato")?.toLocalDateTime(),
fritekst = getString("fritekst"),
document = mapper.readValue(getString("document"), object : TypeReference<List<DocumentComponentDTO>>() {}),
svarType = getString("svar_type"),
svarTekst = getString("svar_tekst"),
svarTidspunkt = getTimestamp("svar_tidspunkt")?.toLocalDateTime(),
)
| 6 | Kotlin | 1 | 0 | e7a334eebbbc5ce316772ba2a94fe62acfa6e1e6 | 6,959 | isdialogmote | MIT License |
app/src/main/java/com/karrar/movieapp/utilities/FormFieldState.kt | Salmon-family | 540,624,429 | false | {"Kotlin": 445900} | package com.karrar.movieapp.utilities
sealed class FormFieldState {
object Valid : FormFieldState()
data class InValid(val message: String) : FormFieldState()
fun errorMessage() = if (this is InValid) message else null
fun isValid(): Boolean {
return this is Valid
}
} | 1 | Kotlin | 26 | 76 | d8aa22e528208c42d89a3574f1da025a49f23aed | 300 | MovieApp | Apache License 2.0 |
android/configurations/testSrc/com/android/tools/idea/configurations/TargetMenuActionTest.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.configurations
import com.android.ide.common.resources.configuration.FolderConfiguration
import com.android.sdklib.AndroidVersion
import com.android.sdklib.IAndroidTarget
import com.android.testutils.MockitoKt.mock
import com.android.testutils.MockitoKt.whenever
import com.android.tools.adtui.actions.prettyPrintActions
import com.android.tools.idea.configurations.TargetMenuAction.SetTargetAction
import com.google.common.truth.Truth.assertThat
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.Toggleable
import com.intellij.testFramework.TestActionEvent
import com.intellij.testFramework.runInEdtAndGet
import org.jetbrains.android.AndroidTestCase
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.spy
class TargetMenuActionTest : AndroidTestCase() {
fun testUpdateTargets() {
val file = runInEdtAndGet { myFixture.addFileToProject("res/layout/layout.xml", "") }
val manager = createSpiedConfigurationManager()
val config = ConfigurationForFile(file.virtualFile, manager, FolderConfiguration())
val menuAction = TargetMenuAction { config }
menuAction.updateActions(DataContext.EMPTY_CONTEXT)
val expected = """30
✔ Automatically Pick Best
------------------------------------------------------
33
32
31
30
29
28
"""
val actual = prettyPrintActions(menuAction)
assertThat(actual).isEqualTo(expected)
}
fun testNoDuplicateActionForDifferentRevision() {
val file = runInEdtAndGet { myFixture.addFileToProject("res/layout/layout.xml", "") }
val manager = createSpiedConfigurationManager()
val config = ConfigurationForFile(file.virtualFile, manager, FolderConfiguration())
val menuAction = TargetMenuAction { config }
menuAction.updateActions(DataContext.EMPTY_CONTEXT)
val children = menuAction.getChildren(null)
// First child is TargetMenuAction.TogglePickBestAction, second child is Separator
val target = (children[2] as SetTargetAction).myTarget
assertThat(target.version.apiLevel).isEqualTo(33)
assertThat(target.revision).isEqualTo(2)
}
fun testNotSelectAutomaticallyPickupActionWhenSelectOtherTarget() {
// When switching the selected action from "Automatically Pick Best" to specified target, the "Automatically Pick Best" action should
// not be marked as selected.
val file = runInEdtAndGet { myFixture.addFileToProject("res/layout/layout.xml", "") }
val manager = createSpiedConfigurationManager()
val config = ConfigurationForFile(file.virtualFile, manager, FolderConfiguration())
val menuAction = TargetMenuAction { config }
manager.configModule.configurationStateManager.projectState.isPickTarget = true
menuAction.updateActions(DataContext.EMPTY_CONTEXT)
menuAction.getChildren(null).let { children ->
val presentation = Presentation()
children[0].update(TestActionEvent.createTestToolbarEvent(presentation))
assertTrue(Toggleable.isSelected(presentation))
for (child in children.drop(2)) {
assertFalse(Toggleable.isSelected(child.templatePresentation))
}
// Choose particular target
children[2].actionPerformed(TestActionEvent.createTestEvent())
}
menuAction.updateActions(DataContext.EMPTY_CONTEXT)
menuAction.getChildren(null).let { children ->
val presentation = Presentation()
// Automatically pick best should not be selected
children[0].update(TestActionEvent.createTestToolbarEvent(presentation))
assertFalse(Toggleable.isSelected(presentation))
// The performed action should be selected
assertTrue(Toggleable.isSelected(children[2].templatePresentation))
// Other action is not selected
for (child in children.drop(3)) {
assertFalse(Toggleable.isSelected(child.templatePresentation))
}
// Select Automatically Pick Best action
children[0].actionPerformed(TestActionEvent.createTestEvent())
}
menuAction.updateActions(DataContext.EMPTY_CONTEXT)
menuAction.getChildren(null).let { children ->
val presentation = Presentation()
// Automatically pick best should be selected
children[0].update(TestActionEvent.createTestToolbarEvent(presentation))
assertTrue(Toggleable.isSelected(presentation))
// Other actions should not be selected
for (child in children.drop(2)) {
assertFalse(Toggleable.isSelected(child.templatePresentation))
}
}
}
private fun createSpiedConfigurationManager(): ConfigurationManager {
val manager = ConfigurationManager.getOrCreateInstance(myModule)
val spied = spy(manager)
val highestApi = createApiTarget(30, 0)
val targets = arrayOf(createApiTarget(28),
createApiTarget(29),
highestApi,
createApiTarget(31),
createApiTarget(32),
createApiTarget(33),
createApiTarget(33, 1),
createApiTarget(33, 2)
)
doReturn(targets).whenever(spied).targets
doReturn(highestApi).whenever(spied).highestApiTarget
return spied
}
private fun createApiTarget(level: Int, revision: Int = 0): IAndroidTarget {
val target = mock<IAndroidTarget>()
whenever(target.version).thenReturn(AndroidVersion(level))
whenever(target.revision).thenReturn(revision)
whenever(target.hasRenderingLibrary()).thenReturn(true)
whenever(target.isPlatform).thenReturn(true)
return target
}
}
| 3 | null | 230 | 912 | d88742a5542b0852e7cb2dd6571e01576cb52841 | 6,291 | android | Apache License 2.0 |
app/src/main/java/com/frafio/myfinance/data/storage/UserStorage.kt | francescofiorella | 360,818,457 | false | {"Kotlin": 226836} | package com.frafio.myfinance.data.storage
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.frafio.myfinance.data.model.User
import com.google.firebase.auth.FirebaseUser
import java.util.Calendar
object MyFinanceStorage {
private var privateUser: User? = null
val user: User?
get() = privateUser
private val _monthlyBudget = MutableLiveData<Double>()
val monthlyBudget: LiveData<Double>
get() = _monthlyBudget
fun updateUser(fUser: FirebaseUser) {
var userPic = ""
fUser.providerId
fUser.photoUrl?.let { uri ->
userPic = uri.toString().replace("s96-c", "s400-c")
}
var provider = User.EMAIL_PROVIDER
for (user in fUser.providerData) {
if (user.providerId.contains("google.com"))
provider = User.GOOGLE_PROVIDER
}
var day: Int? = null
var month: Int? = null
var year: Int? = null
fUser.metadata?.let {
val calendar = Calendar.getInstance()
calendar.timeInMillis = it.creationTimestamp
day = calendar.get(Calendar.DAY_OF_MONTH)
month = calendar.get(Calendar.MONTH) + 1
year = calendar.get(Calendar.YEAR)
}
privateUser = User(fUser.displayName, fUser.email, userPic, provider, year, month, day)
}
fun resetUser() {
privateUser = null
}
fun resetBudget() {
_monthlyBudget.value = 0.0
}
fun updateBudget(value: Double) {
_monthlyBudget.value = value
}
} | 0 | Kotlin | 0 | 1 | a6d1f6b955ca386085a8e15f8a03fc2287761678 | 1,586 | MyFinance | MIT License |
cloudopt-next-web/src/test/kotlin/net/cloudopt/next/web/test/controller/SockController.kt | lhongjum | 337,297,274 | true | {"Kotlin": 321835, "Java": 20762, "HTML": 4306, "Handlebars": 149, "FreeMarker": 148, "CSS": 23} | /*
* Copyright 2017-2020 original 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
*
* 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 net.cloudopt.next.web.test.controller
import io.vertx.ext.web.handler.sockjs.SockJSSocket
import net.cloudopt.next.web.SockJSResource
import net.cloudopt.next.web.route.SocketJS
/*
* @author: Cloudopt
* @Time: 2020/4/1
* @Description: Test Socket Controller
*/
@SocketJS("/socket/api/*")
class SockController : SockJSResource {
override fun handler(userSocketConnection: SockJSSocket) {
println(userSocketConnection)
userSocketConnection.handler {
userSocketConnection.write("Hello world!")
}
}
} | 0 | null | 0 | 0 | b370d261955973fc5a23400ddc11c00dfc2094d3 | 1,159 | cloudopt-next | Apache License 2.0 |
jvm/src/main/kotlin/org/amshove/kluent/FileBacktick.kt | MarkusAmshove | 51,317,191 | false | null | package org.amshove.kluent
import java.io.File
fun File.`should exist`() = this.shouldExist()
fun File.`should not exist`() = this.shouldNotExist()
fun File.`should be dir`() = this.shouldBeDir()
fun File.`should not be dir`() = this.shouldNotBeDir()
fun File.`should be file`() = this.shouldBeFile()
fun File.`should not be file`() = this.shouldNotBeFile()
infix fun File.`should have extension`(other: String) = this shouldHaveExtension (other)
infix fun File.`should not have extension`(other: String) = this shouldNotHaveExtension (other)
infix fun File.`should have name`(other: String) = this shouldHaveName (other)
infix fun File.`should not have name`(other: String) = this shouldNotHaveName (other)
infix fun File.`should contain line with string`(other: String) = this shouldContainLineWithString (other)
infix fun File.`should not contain line with string`(other: String) = this shouldNotContainLineWithString (other)
| 12 | Kotlin | 65 | 836 | b714b62dec562682d25b2d0240814c9fb301464b | 936 | Kluent | MIT License |
test_runner/src/test/kotlin/ftl/util/StopWatchTest.kt | samtstern | 286,730,731 | false | null | package ftl.util
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class StopWatchTest {
@Test(expected = FlankGeneralError::class)
fun `stopWatch errorOnCheckWithoutStart`() {
StopWatch().check()
}
@Test
fun `stopWatch recordTime`() {
val watch = StopWatch().start()
assertThat(watch.check(alignSeconds = true)).isNotEmpty()
assertThat(watch.check()).isNotEmpty()
}
}
| 1 | null | 1 | 2 | 43c1635497a00bea465f5ff25029448506d46dfe | 449 | flank | Apache License 2.0 |
lib/android/src/main/java/cn/qiuxiang/react/baidumap/CoordinateTransformUtil.kt | MarkRunWu | 160,131,277 | true | {"Kotlin": 56095, "JavaScript": 54696, "Objective-C": 33450, "TypeScript": 16681, "Ruby": 1814, "Java": 1589} | package cn.qiuxiang.react.baidumap
import cn.qiuxiang.react.baidumap.CoordinateTransformUtil.gcj02tobd09
import cn.qiuxiang.react.baidumap.CoordinateTransformUtil.gcj02towgs84
import com.baidu.mapapi.model.LatLng
/**
* 百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换的工具
*
*
* 参考 https://github.com/wandergis/coordtransform 实现的Java版本
*
* @author geosmart
*/
object CoordinateTransformUtil {
internal var x_pi = 3.14159265358979324 * 3000.0 / 180.0
// π
internal var pi = 3.1415926535897932384626
// 长半轴
internal var a = 6378245.0
// 扁率
internal var ee = 0.00669342162296594323
/**
* 百度坐标系(BD-09)转WGS坐标
*
* @param lng 百度坐标纬度
* @param lat 百度坐标经度
* @return WGS84坐标数组
*/
fun bd09towgs84(location: LatLng): LatLng {
val gcj = bd09togcj02(location)
return gcj02towgs84(gcj)
}
/**
* WGS坐标转百度坐标系(BD-09)
*
* @param lng WGS84坐标系的经度
* @param lat WGS84坐标系的纬度
* @return 百度坐标数组
*/
fun wgs84tobd09(location: LatLng): LatLng {
val gcj = wgs84togcj02(location)
return gcj02tobd09(gcj)
}
/**
* 火星坐标系(GCJ-02)转百度坐标系(BD-09)
*
*
* 谷歌、高德——>百度
*
* @param lng 火星坐标经度
* @param lat 火星坐标纬度
* @return 百度坐标数组
*/
fun gcj02tobd09(location: LatLng): LatLng {
val lng = location.longitude
val lat = location.latitude
val z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi)
val theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi)
val bd_lng = z * Math.cos(theta) + 0.0065
val bd_lat = z * Math.sin(theta) + 0.006
return LatLng(bd_lat, bd_lng)
}
/**
* 百度坐标系(BD-09)转火星坐标系(GCJ-02)
*
*
* 百度——>谷歌、高德
*
* @param bd_lon 百度坐标纬度
* @param bd_lat 百度坐标经度
* @return 火星坐标数组
*/
fun bd09togcj02(location: LatLng): LatLng {
val bd_lat = location.latitude
val bd_lon = location.longitude
val x = bd_lon - 0.0065
val y = bd_lat - 0.006
val z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi)
val theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi)
val gg_lng = z * Math.cos(theta)
val gg_lat = z * Math.sin(theta)
return LatLng(gg_lat, gg_lng)
}
/**
* WGS84转GCJ02(火星坐标系)
*
* @param lng WGS84坐标系的经度
* @param lat WGS84坐标系的纬度
* @return 火星坐标数组
*/
fun wgs84togcj02(location: LatLng): LatLng {
if (out_of_china(location)) {
return location
}
val lng = location.longitude
val lat = location.latitude
var dlat = transformlat(LatLng(lat - 35.0, lng - 105.0))
var dlng = transformlng(LatLng(lat - 35.0, lng - 105.0))
val radlat = lat / 180.0 * pi
var magic = Math.sin(radlat)
magic = 1 - ee * magic * magic
val sqrtmagic = Math.sqrt(magic)
dlat = dlat * 180.0 / (a * (1 - ee) / (magic * sqrtmagic) * pi)
dlng = dlng * 180.0 / (a / sqrtmagic * Math.cos(radlat) * pi)
val mglat = lat + dlat
val mglng = lng + dlng
return LatLng(mglat, mglng)
}
/**
* GCJ02(火星坐标系)转GPS84
*
* @param lng 火星坐标系的经度
* @param lat 火星坐标系纬度
* @return WGS84坐标数组
*/
fun gcj02towgs84(location: LatLng): LatLng {
if (out_of_china(location)) {
return location
}
val lng = location.longitude
val lat = location.latitude
var dlat = transformlat(LatLng(lat - 35.0, lng - 105.0))
var dlng = transformlng(LatLng(lat - 35.0, lng - 105.0))
val radlat = lat / 180.0 * pi
var magic = Math.sin(radlat)
magic = 1 - ee * magic * magic
val sqrtmagic = Math.sqrt(magic)
dlat = dlat * 180.0 / (a * (1 - ee) / (magic * sqrtmagic) * pi)
dlng = dlng * 180.0 / (a / sqrtmagic * Math.cos(radlat) * pi)
val mglat = lat + dlat
val mglng = lng + dlng
return LatLng(lat * 2 - mglat, lng * 2 - mglng)
}
/**
* 纬度转换
*
* @param lng
* @param lat
* @return
*/
fun transformlat(location: LatLng): Double {
val lng = location.longitude
val lat = location.latitude
var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng))
ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0
ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0
ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0
return ret
}
/**
* 经度转换
*
* @param lng
* @param lat
* @return
*/
fun transformlng(location: LatLng): Double {
val lng = location.longitude
val lat = location.latitude
var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0
ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0
ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0
return ret
}
/**
* 判断是否在国内,不在国内不做偏移
*
* @param lng
* @param lat
* @return
*/
fun out_of_china(location: LatLng): Boolean {
val lng = location.longitude
val lat = location.latitude
if (lng < 72.004 || lng > 137.8347) {
return true
} else if (lat < 0.8293 || lat > 55.8271) {
return true
}
return false
}
}
| 0 | Kotlin | 0 | 0 | 1ff5324907ec37dfb614bdb879e9900016374465 | 5,734 | react-native-baidumap-sdk | MIT License |
palumu-lib/src/main/java/tw/invictus/palumu/ScalablePageFrame.kt | ivanisidrowu | 125,709,512 | false | null | package tw.invictus.palumu
import android.content.Context
import android.support.constraint.ConstraintLayout
import android.support.constraint.ConstraintSet
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.view.MotionEventCompat
import android.support.v4.view.ViewCompat
import android.support.v4.widget.ViewDragHelper
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import tw.invictus.palumu.extension.isViewHit
/**
* Copyright 2018 Wu Yu Hao (Ivan Wu)
* 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.
*
* Created by ivan on 04/01/2018.
*/
open class ScalablePageFrame(context: Context) : PageFrameBase(context) {
var isClosed = false
var bottomPadding = 0
var headRightMargin = 0
var headBottomMargin = 0
var isGestureEnabled = true
private val dxThreshold = 5
private val dyThreshold = 15
private val headScaleFactor = 2f
private val minScale = 1 / headScaleFactor
private val minSlidingClickDistance = 10
private val xViewReleaseThreshold = 0.25f
private val yViewReleaseThreshold = 0.5f
private val invalidPointer = -1
private val headRatio = "h,16:9"
private val dragHelper: ViewDragHelper
private var frame: ConstraintLayout
private var headView: FrameLayout
private var bodyView: FrameLayout
private var verticalDragRange: Int = 0
private var horizontalDragRange: Int = 0
private var mTop: Int = 0
private var mLeft: Int = 0
private var verticalDragOffset = 0f
private var activePointerId = invalidPointer
private var lastTouchActionDownXPosition = 0f
private var originHeadWidth = 0
private var originHeadHeight = 0
private var draggable = true
init {
inflate(context, R.layout.layout_scalable_page_frame, this)
headView = findViewById(R.id.video_page_frame_head)
bodyView = findViewById(R.id.video_page_frame_body)
frame = findViewById(R.id.frame)
dragHelper = ViewDragHelper.create(frame, 1f, DragHelperCallback())
}
override fun attach(root: ViewGroup) {
super.attach(root)
setPadding(0, 0, 0, bottomPadding)
}
open fun setHead(fragment: Fragment, fragmentManager: FragmentManager) {
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.video_page_frame_head, fragment)
transaction.commit()
}
open fun setHead(head: View) {
headView.addView(head, ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
open fun setBody(fragment: Fragment, fragmentManager: FragmentManager) {
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.video_page_frame_body, fragment)
transaction.commit()
}
open fun setBody(body: View) {
bodyView.addView(body, ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
open fun enterFullScreen() {
if (!isMinimized()) {
draggable = false
headView.layoutParams.apply {
width = ViewGroup.LayoutParams.MATCH_PARENT
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
}
bodyView.visibility = View.INVISIBLE
ConstraintSet().run {
clone(frame)
setDimensionRatio(R.id.video_page_frame_head, null)
applyTo(frame)
}
invalidate()
}
}
open fun leaveFullScreen() {
draggable = true
headView.layoutParams.run {
width = originHeadWidth
height = originHeadHeight
visibility = View.VISIBLE
}
bodyView.visibility = View.VISIBLE
ConstraintSet().run {
clone(frame)
setDimensionRatio(R.id.video_page_frame_head, headRatio)
applyTo(frame)
}
invalidate()
}
override fun maximize() {
visibility = View.VISIBLE
smoothSlideTo(0f)
super.maximize()
}
override fun minimize() {
visibility = View.VISIBLE
smoothSlideTo(1f)
super.minimize()
}
fun close() {
isClosed = true
headView.apply {
alpha = 1f
scaleX = 1f
scaleY = 1f
pivotX = 0f
pivotY = 0f
}
headView.removeAllViews()
bodyView.removeAllViews()
detach()
listener?.onClose()
listener = null
}
override fun isMinimized() = isHeadAtBottom() && isHeadAtRight()
override fun onFinishInflate() {
super.onFinishInflate()
originHeadWidth = headView.width
originHeadHeight = headView.height
}
override fun computeScroll() {
if (dragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this)
}
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
if (!isEnabled) return false
if (!isGestureEnabled) return super.onInterceptTouchEvent(ev)
when (ev.action and MotionEvent.ACTION_MASK) {
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
dragHelper.cancel()
return false
}
MotionEvent.ACTION_DOWN -> {
val index = MotionEventCompat.getActionIndex(ev)
activePointerId = MotionEventCompat.getPointerId(ev, index)
if (activePointerId == invalidPointer) {
return false
}
}
}
val interceptTap = dragHelper.isViewUnder(headView, ev.x.toInt(), ev.y.toInt())
return dragHelper.shouldInterceptTouchEvent(ev) || interceptTap
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
if (!isGestureEnabled) return super.onTouchEvent(ev)
if (ev.action and MotionEvent.ACTION_MASK == MotionEvent.ACTION_DOWN) {
activePointerId = ev.getPointerId(ev.action)
}
if (activePointerId == invalidPointer) {
return false
}
dragHelper.processTouchEvent(ev)
if (isClosed) {
return false
}
val isDragViewHit = isViewHit(headView, ev.x.toInt(), ev.y.toInt())
val isSecondViewHit = isViewHit(bodyView, ev.x.toInt(), ev.y.toInt())
analyzeTouchToMaximizeIfNeeded(ev, isDragViewHit)
if (!isMinimized()) {
headView.dispatchTouchEvent(ev)
} else {
headView.dispatchTouchEvent(cloneMotionEventWithAction(ev, MotionEvent.ACTION_CANCEL))
}
return isDragViewHit || isSecondViewHit
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l, t, r, b)
verticalDragRange = height - headView.height - bottomPadding
horizontalDragRange = (width - headView.width * headView.scaleX).toInt()
headView.layout(mLeft, mTop, mLeft + headView.measuredWidth, mTop + headView.measuredHeight)
bodyView.layout(0, mTop + headView.measuredHeight, r, mTop + b)
}
private fun smoothSlideTo(slideOffset: Float): Boolean {
val topBound = paddingTop
val y = (topBound + slideOffset * verticalDragRange).toInt()
if (dragHelper.smoothSlideViewTo(headView, headView.left, y)) {
ViewCompat.postInvalidateOnAnimation(this)
return true
}
return false
}
private fun analyzeTouchToMaximizeIfNeeded(ev: MotionEvent, isDragViewHit: Boolean) {
when (ev.action) {
MotionEvent.ACTION_DOWN -> lastTouchActionDownXPosition = ev.x
MotionEvent.ACTION_UP -> {
val clickOffset = ev.x - lastTouchActionDownXPosition
if (shouldMaximizeOnClick(ev, clickOffset, isDragViewHit)) {
if (isMinimized()) {
maximize()
}
}
}
}
}
private fun cloneMotionEventWithAction(event: MotionEvent, action: Int): MotionEvent {
return MotionEvent.obtain(event.downTime, event.eventTime, action, event.x,
event.y, event.metaState)
}
private fun shouldMaximizeOnClick(ev: MotionEvent, deltaX: Float, isDragViewHit: Boolean): Boolean {
return (Math.abs(deltaX) < minSlidingClickDistance
&& ev.action != MotionEvent.ACTION_MOVE
&& isDragViewHit)
}
private fun isHeadAtBottom() = headView.scaleX == minScale
private fun isHeadAtRight() = mLeft == 0
private inner class DragHelperCallback : ViewDragHelper.Callback() {
override fun tryCaptureView(child: View, pointerId: Int) = child === headView
override fun onViewPositionChanged(changedView: View, left: Int, top: Int, dx: Int, dy: Int) {
if (isHeadAtBottom() && isHeadAtRight()) {
if (Math.abs(dy) > dyThreshold) {
dragVertically(top)
} else if (Math.abs(dx) > dxThreshold) {
dragHorizontally(left)
}
} else if (isHeadAtBottom()) {
dragHorizontally(left)
} else {
dragVertically(top)
}
requestLayout()
}
override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
if (!draggable) return
if (isHeadAtBottom() && !isHeadAtRight()) {
if ((mLeft < 0 && mLeft > -measuredWidth * xViewReleaseThreshold)
|| (mLeft > 0 && mLeft < measuredWidth * xViewReleaseThreshold)) {
dragHelper.settleCapturedViewAt(0, releasedChild.top)
} else {
close()
}
} else {
var top = paddingTop
if (yvel > 0f || (yvel == 0f && verticalDragOffset > yViewReleaseThreshold)) {
top += verticalDragRange
}
dragHelper.settleCapturedViewAt(releasedChild.left, top)
}
invalidate()
}
override fun getViewVerticalDragRange(child: View) = verticalDragRange
override fun getViewHorizontalDragRange(child: View) = horizontalDragRange
override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
if ((isMinimized() && Math.abs(dy) >= dyThreshold)
|| (!isMinimized() && !isHeadAtBottom())) {
val topBound = paddingTop
val headHeight = headView.height
val headPaddingBottom = headView.paddingBottom
val bottomBound = height - headHeight - headPaddingBottom - bottomPadding
return Math.min(Math.max(top, topBound), bottomBound)
}
return (measuredHeight - (headView.measuredHeight * scaleX) - bottomPadding).toInt()
}
override fun clampViewPositionHorizontal(child: View, targetLeft: Int, dx: Int): Int {
var newLeft = headView.left
if ((isMinimized() && Math.abs(dx) > dxThreshold)
|| (isHeadAtBottom() && !isHeadAtRight())) {
newLeft = targetLeft
}
return newLeft
}
private fun dragVertically(top: Int) {
if (draggable) {
mTop = top
verticalDragOffset = top.toFloat() / verticalDragRange
headView.apply {
pivotX = width.toFloat() - headRightMargin
pivotY = height.toFloat() - headBottomMargin
scaleX = 1 - verticalDragOffset / headScaleFactor
scaleY = scaleX
}
bodyView.alpha = 1 - verticalDragOffset
}
}
private fun dragHorizontally(left: Int) {
if (draggable) {
mLeft = left
headView.x = left.toFloat()
if (mLeft < 0) {
val draggableRange = measuredWidth * (1 - minScale)
headView.alpha = 1 - (Math.abs(mLeft) / draggableRange)
} else {
headView.alpha = 1 - (mLeft / (measuredWidth * minScale))
}
if (headView.alpha <= 0) {
close()
}
}
}
}
} | 0 | Kotlin | 14 | 76 | 13140af519f50931584f519ea78b2d3c6e86231e | 13,046 | palumu | Apache License 2.0 |
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/harvest/sync/dto/HarvestDTO.kt | suomenriistakeskus | 78,840,058 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 2, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 4, "Gradle Kotlin DSL": 1, "Kotlin": 1344, "XML": 401, "Java": 161, "Protocol Buffer": 1, "JSON": 1} | package fi.riista.common.domain.harvest.sync.dto
import fi.riista.common.domain.dto.HarvestSpecimenDTO
import fi.riista.common.domain.dto.PersonWithHunterNumberDTO
import fi.riista.common.domain.dto.toHarvestSpecimen
import fi.riista.common.domain.dto.toPersonWithHunterNumber
import fi.riista.common.domain.groupHunting.model.GroupHuntingPerson
import fi.riista.common.domain.harvest.model.CommonHarvest
import fi.riista.common.domain.harvest.model.toHarvestSpecimenDTO
import fi.riista.common.domain.huntingclub.dto.HuntingClubNameAndCodeDTO
import fi.riista.common.domain.huntingclub.dto.toHuntingClubNameAndCodeDTO
import fi.riista.common.domain.huntingclub.dto.toOrganization
import fi.riista.common.domain.model.EntityImages
import fi.riista.common.domain.model.HarvestReportState
import fi.riista.common.domain.model.Species
import fi.riista.common.domain.model.toPersonWithHunterNumberDTO
import fi.riista.common.dto.ETRMSGeoLocationDTO
import fi.riista.common.dto.LocalDateTimeDTO
import fi.riista.common.dto.toETRMSGeoLocation
import fi.riista.common.dto.toLocalDateTime
import fi.riista.common.model.BackendEnum
import fi.riista.common.model.toBackendEnum
import fi.riista.common.model.toETRMSGeoLocationDTO
import kotlinx.serialization.Serializable
@Serializable
internal data class HarvestDTO(
val id: Long,
val rev: Int,
val type: String,
val geoLocation: ETRMSGeoLocationDTO,
val pointOfTime: LocalDateTimeDTO,
val gameSpeciesCode: Int? = null,
val description: String? = null,
val canEdit: Boolean,
val imageIds: List<String>,
val harvestReportRequired: Boolean,
val harvestReportState: String? = null,
val permitNumber: String? = null,
val permitType: String? = null,
val stateAcceptedToHarvestPermit: String? = null,
val specimens: List<HarvestSpecimenDTO>? = null,
val amount: Int,
val deerHuntingType: String? = null,
val deerHuntingOtherTypeDescription: String? = null,
val harvestReportDone: Boolean,
val feedingPlace: Boolean? = null,
val taigaBeanGoose: Boolean? = null,
val huntingMethod: String? = null,
val actorInfo: PersonWithHunterNumberDTO? = null,
val selectedHuntingClub: HuntingClubNameAndCodeDTO? = null,
val apiVersion: Int,
val mobileClientRefId: Long? = null,
val harvestSpecVersion: Int,
)
internal fun HarvestDTO.toCommonHarvest(
localId: Long? = null,
modified: Boolean = false,
deleted: Boolean = false,
): CommonHarvest? {
val pointOfTime = pointOfTime.toLocalDateTime() ?: return null
val harvestReportState: BackendEnum<HarvestReportState> = harvestReportState.toBackendEnum()
return CommonHarvest(
localId = localId,
localUrl = null,
id = id,
rev = rev,
species = when (gameSpeciesCode) {
null -> Species.Other
else -> Species.Known(gameSpeciesCode)
},
geoLocation = geoLocation.toETRMSGeoLocation(),
pointOfTime = pointOfTime,
description = description,
canEdit = canEdit,
modified = modified,
deleted = deleted,
images = EntityImages(
remoteImageIds = imageIds,
localImages = emptyList()
),
specimens = specimens?.map { it.toHarvestSpecimen() } ?: emptyList(),
amount = amount,
harvestSpecVersion = harvestSpecVersion,
harvestReportRequired = harvestReportRequired,
harvestReportState = harvestReportState,
permitNumber = permitNumber,
permitType = permitType,
stateAcceptedToHarvestPermit = stateAcceptedToHarvestPermit.toBackendEnum(),
deerHuntingType = deerHuntingType.toBackendEnum(),
deerHuntingOtherTypeDescription = deerHuntingOtherTypeDescription,
mobileClientRefId = mobileClientRefId,
harvestReportDone = harvestReportDone,
rejected = harvestReportState == HarvestReportState.REJECTED.toBackendEnum(),
feedingPlace = feedingPlace,
taigaBeanGoose = taigaBeanGoose,
greySealHuntingMethod = huntingMethod.toBackendEnum(),
actorInfo = actorInfo?.let {
GroupHuntingPerson.Guest(actorInfo.toPersonWithHunterNumber())
} ?: GroupHuntingPerson.Unknown,
selectedClub = selectedHuntingClub?.toOrganization(),
)
}
internal fun CommonHarvest.toHarvestDTO(): HarvestDTO? {
if (id == null || rev == null) {
return null
}
return HarvestDTO(
id = id,
rev = rev,
type = "HARVEST",
geoLocation = geoLocation.toETRMSGeoLocationDTO(),
pointOfTime = pointOfTime.toStringISO8601(),
gameSpeciesCode = species.knownSpeciesCodeOrNull(),
description = description,
canEdit = canEdit,
imageIds = images.remoteImageIds,
harvestReportRequired = harvestReportRequired,
harvestReportState = harvestReportState.rawBackendEnumValue,
permitNumber = permitNumber,
permitType = permitType,
stateAcceptedToHarvestPermit = stateAcceptedToHarvestPermit.rawBackendEnumValue,
specimens = specimens.map { it.toHarvestSpecimenDTO() },
amount = amount,
deerHuntingType = deerHuntingType.rawBackendEnumValue,
deerHuntingOtherTypeDescription = deerHuntingOtherTypeDescription,
harvestReportDone = harvestReportDone,
feedingPlace = feedingPlace,
taigaBeanGoose = taigaBeanGoose,
huntingMethod = greySealHuntingMethod.rawBackendEnumValue,
apiVersion = 2, // Depricated
mobileClientRefId = mobileClientRefId,
harvestSpecVersion = harvestSpecVersion,
actorInfo = when (actorInfo) {
is GroupHuntingPerson.Guest -> actorInfo.personInformation.toPersonWithHunterNumberDTO()
else -> null
},
selectedHuntingClub = selectedClub?.toHuntingClubNameAndCodeDTO(),
)
}
| 0 | Kotlin | 0 | 3 | 23645d1abe61c68d649b6d0ca1d16556aa8ffa16 | 5,908 | oma-riista-android | MIT License |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/remote_edit/RemoteEditViewModel.kt | Waboodoo | 34,525,124 | false | null | package ch.rmy.android.http_shortcuts.activities.remote_edit
import android.app.Application
import androidx.core.net.toUri
import androidx.lifecycle.viewModelScope
import ch.rmy.android.framework.extensions.context
import ch.rmy.android.framework.extensions.logException
import ch.rmy.android.framework.utils.localization.Localizable
import ch.rmy.android.framework.utils.localization.StringResLocalizable
import ch.rmy.android.framework.viewmodel.BaseViewModel
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent
import ch.rmy.android.http_shortcuts.http.HttpClientFactory
import ch.rmy.android.http_shortcuts.import_export.Exporter
import ch.rmy.android.http_shortcuts.import_export.ImportException
import ch.rmy.android.http_shortcuts.import_export.Importer
import ch.rmy.android.http_shortcuts.utils.Settings
import ch.rmy.android.http_shortcuts.utils.Validation
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.time.Duration.Companion.milliseconds
class RemoteEditViewModel(application: Application) : BaseViewModel<Unit, RemoteEditViewState>(application) {
@Inject
lateinit var settings: Settings
@Inject
lateinit var exporter: Exporter
@Inject
lateinit var importer: Importer
@Inject
lateinit var httpClientFactory: HttpClientFactory
init {
getApplicationComponent().inject(this)
}
private var currentJob: Job? = null
private var serverUrl: String
get() = settings.remoteEditServerUrl ?: REMOTE_BASE_URL
set(value) {
settings.remoteEditServerUrl = value
updateViewState {
copy(hostAddress = humanReadableEditorAddress)
}
}
private val humanReadableEditorAddress: String
get() = getRemoteBaseUrl().toString().replace("https://", "")
private val deviceId: String
get() = settings.remoteEditDeviceId
?: run {
generateDeviceId()
.also {
settings.remoteEditDeviceId = it
}
}
private var password: String
get() = settings.remoteEditPassword ?: ""
set(value) {
settings.remoteEditPassword = value
updateViewState {
copy(password = value)
}
}
private fun getRemoteBaseUrl() =
serverUrl.toUri()
override fun initViewState() = RemoteEditViewState(
hostAddress = humanReadableEditorAddress,
deviceId = deviceId,
password = <PASSWORD>,
)
fun onChangeRemoteHostButtonClicked() {
openChangeRemoteHostDialog()
}
private fun openChangeRemoteHostDialog() {
updateViewState {
copy(
dialogState = RemoteEditDialogState.EditServerUrl(
currentServerAddress = serverUrl,
)
)
}
}
fun onServerUrlChange(value: String) {
if (value.isNotEmpty() && !Validation.isValidHttpUrl(value.toUri())) {
showErrorDialog(StringResLocalizable(R.string.error_invalid_remote_edit_host_url))
return
}
serverUrl = value
hideDialog()
}
fun onPasswordChanged(password: String) {
this.password = <PASSWORD>
}
fun onUploadButtonClicked() {
doWithViewState { viewState ->
if (viewState.canUpload) {
startUpload()
}
}
}
private fun startUpload() {
currentJob?.cancel()
currentJob = viewModelScope.launch {
val dialogJob = showProgressDialogAsync(R.string.remote_edit_upload_in_progress)
try {
getRemoteEditManager().upload(deviceId, password)
showSnackbar(R.string.message_remote_edit_upload_successful)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logException(e)
showErrorDialog(StringResLocalizable(R.string.error_remote_edit_upload))
} finally {
dialogJob.cancel()
hideProgressDialog()
}
}
}
fun onDownloadButtonClicked() {
doWithViewState { viewState ->
if (viewState.canDownload) {
startDownload()
}
}
}
private fun startDownload() {
currentJob?.cancel()
currentJob = viewModelScope.launch {
val dialogJob = showProgressDialogAsync(R.string.remote_edit_download_in_progress)
try {
getRemoteEditManager().download(deviceId, password)
setResult(
intent = RemoteEditActivity.OpenRemoteEditor.createResult(changesImported = true),
)
showSnackbar(R.string.message_remote_edit_download_successful)
} catch (e: CancellationException) {
throw e
} catch (e: ImportException) {
showErrorDialog(Localizable.create { it.getString(R.string.error_remote_edit_download) + " " + e.message })
} catch (e: Exception) {
logException(e)
showErrorDialog(StringResLocalizable(R.string.error_remote_edit_download))
} finally {
dialogJob.cancel()
hideProgressDialog()
}
}
}
private fun getRemoteEditManager() =
RemoteEditManager(
context = context,
client = httpClientFactory.getClient(context),
baseUrl = getRemoteBaseUrl()
.buildUpon()
.appendEncodedPath(REMOTE_API_PATH)
.build(),
exporter = exporter,
importer = importer,
)
private fun CoroutineScope.showProgressDialogAsync(message: Int): Deferred<Unit> =
async {
delay(INVISIBLE_PROGRESS_THRESHOLD)
updateViewState {
copy(dialogState = RemoteEditDialogState.Progress(StringResLocalizable(message)))
}
}
private fun hideProgressDialog() {
updateViewState {
if (dialogState is RemoteEditDialogState.Progress) {
copy(dialogState = null)
} else this
}
}
fun onDialogDismissalRequested() {
currentJob?.cancel()
hideDialog()
}
private fun hideDialog() {
updateViewState {
copy(dialogState = null)
}
}
private fun showErrorDialog(message: Localizable) {
updateViewState {
copy(
dialogState = RemoteEditDialogState.Error(message),
)
}
}
companion object {
private val INVISIBLE_PROGRESS_THRESHOLD = 400.milliseconds
private const val REMOTE_BASE_URL = "https://http-shortcuts.rmy.ch/editor"
private const val REMOTE_API_PATH = "api/files/"
private const val DEVICE_ID_CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789"
private const val DEVICE_ID_LENGTH = 8
internal fun generateDeviceId(): String =
(0 until DEVICE_ID_LENGTH)
.map {
DEVICE_ID_CHARACTERS.random()
}
.joinToString(separator = "")
}
}
| 18 | Kotlin | 100 | 749 | 72abafd7e3bbe68647a109cb4d5a1d3b97a73d31 | 7,589 | HTTP-Shortcuts | MIT License |
payment-library/src/test/java/ru/modulkassa/payment/library/domain/PaymentTerminalImplTest.kt | modulkassa | 647,749,589 | false | null | package ru.modulkassa.payment.library.domain
import com.google.common.truth.Truth
import com.google.gson.Gson
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import io.reactivex.rxjava3.core.Single
import okhttp3.ResponseBody
import org.junit.Test
import retrofit2.HttpException
import retrofit2.Response
import ru.modulkassa.payment.library.SettingsRepository
import ru.modulkassa.payment.library.domain.entity.PaymentOptions
import ru.modulkassa.payment.library.domain.entity.result.PaymentResultSuccess
import ru.modulkassa.payment.library.network.PaymentApi
import ru.modulkassa.payment.library.network.dto.SbpPaymentLinkRequestDto
import ru.modulkassa.payment.library.network.dto.SbpPaymentLinkResponseDto
import ru.modulkassa.payment.library.network.dto.TransactionDto
import ru.modulkassa.payment.library.network.dto.TransactionResponseDto
import ru.modulkassa.payment.library.network.dto.TransactionStateDto.COMPLETE
import ru.modulkassa.payment.library.network.dto.TransactionStateDto.FAILED
import ru.modulkassa.payment.library.ui.NetworkException
import ru.modulkassa.payment.library.ui.PaymentFailedException
import ru.modulkassa.payment.library.ui.ValidationException
import java.math.BigDecimal
class PaymentTerminalImplTest {
@Test
fun CreateSbpPaymentLink_WrongOptions_ThrowsValidationException() {
val options = PaymentOptions.createSbpOptions("orderId", "description", BigDecimal.ONE)
val repository: SettingsRepository = mock {
on { getMerchantId() } doReturn null
}
val terminal = createTerminal(repository = repository)
terminal.createSbpPaymentLink(options)
.test()
.assertFailure(ValidationException::class.java)
}
@Test
fun CreateSbpPaymentLink_CorrectOptions_RequestSigned() {
val options = PaymentOptions.createSbpOptions("orderId", "description", BigDecimal.ONE)
val api: PaymentApi = mock {
on { createSbpPayment(any()) } doReturn Single.just(SbpPaymentLinkResponseDto("sbpLink"))
}
val terminal = createTerminal(api = api)
terminal.createSbpPaymentLink(options)
.test()
.assertComplete()
argumentCaptor<SbpPaymentLinkRequestDto>().apply {
verify(api).createSbpPayment(capture())
Truth.assertThat(firstValue.signature).isNotEmpty()
}
}
@Test
fun CreateSbpPaymentLink_Api200Error_ThrowsNetworkException() {
val options = PaymentOptions.createSbpOptions("orderId", "description", BigDecimal.ONE)
val response = "{\"sbpLink\":\"sbpLink\",\"status\":\"ERROR\",\"message\":\"message\"}"
val sbpPaymentLinkResponseDto = Gson().fromJson(response, SbpPaymentLinkResponseDto::class.java)
val api: PaymentApi = mock {
on { createSbpPayment(any()) } doReturn Single.just(sbpPaymentLinkResponseDto)
}
val terminal = createTerminal(api = api)
terminal.createSbpPaymentLink(options)
.test()
.assertError { error ->
Truth.assertThat(error).isInstanceOf(NetworkException::class.java)
Truth.assertThat(error.message).isEqualTo("message")
true
}
}
@Test
fun CreateSbpPaymentLink_ApiError_ThrowsNetworkException() {
val options = PaymentOptions.createSbpOptions("orderId", "description", BigDecimal.ONE)
val content = "{\"message\":\"message\"}"
val httpException = HttpException(Response.error<String>(400, ResponseBody.create(null, content)))
val api: PaymentApi = mock {
on { createSbpPayment(any()) } doReturn Single.error(httpException)
}
val terminal = createTerminal(api = api)
terminal.createSbpPaymentLink(options)
.test()
.assertError { error ->
Truth.assertThat(error).isInstanceOf(NetworkException::class.java)
Truth.assertThat(error.message).isEqualTo("message")
true
}
}
@Test
fun CreateSbpPaymentLink_UnknownApiError_ThrowsNetworkException() {
val options = PaymentOptions.createSbpOptions("orderId", "description", BigDecimal.ONE)
val api: PaymentApi = mock {
on { createSbpPayment(any()) } doReturn Single.error(Throwable())
}
val terminal = createTerminal(api = api)
terminal.createSbpPaymentLink(options)
.test()
.assertError { error ->
Truth.assertThat(error).isInstanceOf(Throwable::class.java)
true
}
}
@Test
fun CreateSbpPaymentLink_ApiCorrect_ReturnsSbpLink() {
val options = PaymentOptions.createSbpOptions("orderId", "description", BigDecimal.ONE)
val api: PaymentApi = mock {
on { createSbpPayment(any()) } doReturn Single.just(SbpPaymentLinkResponseDto("sbpLink"))
}
val terminal = createTerminal(api = api)
terminal.createSbpPaymentLink(options)
.test()
.assertValue("sbpLink")
}
@Test
fun GetPaymentStatus_NoMerchantId_ThrowsValidationException() {
val repository: SettingsRepository = mock {
on { getMerchantId() } doReturn null
}
val terminal = createTerminal(repository = repository)
terminal.getPaymentStatus("orderId")
.test()
.assertFailure(ValidationException::class.java)
}
@Test
fun GetPaymentStatus_ByDefault_RequestSigned() {
val api: PaymentApi = mock {
on { getTransaction(any(), any(), any(), any(), any()) } doReturn Single.just(
TransactionResponseDto(
TransactionDto(state = COMPLETE)
)
)
}
val terminal = createTerminal(api = api)
terminal.getPaymentStatus("orderId")
.test()
.assertComplete()
argumentCaptor<String>().apply {
verify(api).getTransaction(any(), any(), capture(), any(), any())
Truth.assertThat(firstValue).isNotEmpty()
}
}
@Test
fun GetPaymentStatus_Api200Error_ThrowsNetworkException() {
val response = "{\"state\":\"COMPLETE\",\"status\":\"ERROR\",\"message\":\"message\"}"
val transactionResponseDto = Gson().fromJson(response, TransactionResponseDto::class.java)
val api: PaymentApi = mock {
on { getTransaction(any(), any(), any(), any(), any()) } doReturn Single.just(transactionResponseDto)
}
val terminal = createTerminal(api = api)
terminal.getPaymentStatus("orderId")
.test()
.assertError { error ->
Truth.assertThat(error).isInstanceOf(NetworkException::class.java)
Truth.assertThat(error.message).isEqualTo("message")
true
}
}
@Test
fun GetPaymentStatus_UnknownApiError_ThrowsNetworkException() {
val api: PaymentApi = mock {
on { getTransaction(any(), any(), any(), any(), any()) } doReturn Single.error(Throwable())
}
val terminal = createTerminal(api = api)
terminal.getPaymentStatus("orderId")
.test()
.assertError { error ->
Truth.assertThat(error).isInstanceOf(Throwable::class.java)
true
}
}
@Test
fun GetPaymentStatus_StateComplete_PaymentResultSuccess() {
val api: PaymentApi = mock {
on { getTransaction(any(), any(), any(), any(), any()) } doReturn Single.just(
TransactionResponseDto(
TransactionDto(
state = COMPLETE,
transactionId = "transactionId",
sbpTransactionId = "sbpTransactionId"
)
)
)
}
val terminal = createTerminal(api = api)
terminal.getPaymentStatus("orderId")
.test()
.assertValue { value ->
Truth.assertThat(value).isInstanceOf(PaymentResultSuccess::class.java)
Truth.assertThat(value.transactionId).isEqualTo("transactionId")
Truth.assertThat(value.sbpTransactionId).isEqualTo("sbpTransactionId")
true
}
}
@Test
fun GetPaymentStatus_StateFailed_PaymentFailedException() {
val api: PaymentApi = mock {
on { getTransaction(any(), any(), any(), any(), any()) } doReturn Single.just(
TransactionResponseDto(
TransactionDto(
state = FAILED,
message = "message"
)
)
)
}
val terminal = createTerminal(api = api)
terminal.getPaymentStatus("orderId")
.test()
.assertError { error ->
Truth.assertThat(error).isInstanceOf(PaymentFailedException::class.java)
Truth.assertThat(error.message).isEqualTo("message")
true
}
}
private fun createTerminal(
api: PaymentApi = mock(),
gson: Gson = Gson(),
repository: SettingsRepository = mock {
on { getMerchantId() } doReturn "merchantId"
on { getSignatureKey() } doReturn "signatureKey"
}
): PaymentTerminal {
return PaymentTerminalImpl(api, gson, repository)
}
} | 0 | Kotlin | 0 | 1 | 66f0543e53bb38275157f882aac94f161bf54ab9 | 9,674 | payment-android-sdk | MIT License |
helm-plugin/src/test/kotlin/com/citi/gradle/plugins/helm/command/internal/FileUtilsTest.kt | 2lambda123 | 748,592,455 | false | {"Kotlin": 549953, "Batchfile": 87, "Shell": 80} | package com.citi.gradle.plugins.helm.command.internal
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.matchers.collections.beEmpty
import io.kotest.matchers.file.exist
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNot
import io.mockk.every
import io.mockk.justRun
import io.mockk.mockk
import java.io.File
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import org.slf4j.Logger
class FileUtilsTest {
@TempDir
private lateinit var temporaryFolder: File
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun shouldRemoveFileAfterException(createFile: Boolean) {
// given
val logger = mockk<Logger> {
justRun { info(any(), any<File>()) }
}
val fileToDelete = File(temporaryFolder, "file")
if (createFile) {
fileToDelete.createNewFile()
}
val exceptionToThrow = Exception();
// when
val actualException = shouldThrowAny {
deleteFileOnException(fileToDelete, logger) {
throw exceptionToThrow
}
}
// then
actualException shouldBe exceptionToThrow
actualException.suppressedExceptions should beEmpty()
fileToDelete shouldNot exist()
}
}
| 0 | Kotlin | 0 | 0 | 4335722bca8a61d605ee79e548758e2e2ebdba35 | 1,454 | Citi-gradle-helm-plugin | MIT License |
src/main/kotlin/io/digturtle/gradle/accu/yml/AccuYmlPlugin.kt | dig-turtle | 160,903,538 | false | null | package io.digturtle.gradle.accu.yml
import org.gradle.api.Plugin
import org.gradle.api.Project
import io.digturtle.gradle.accu.yml.Tasks.check
import io.digturtle.gradle.accu.yml.Tasks.accuYml
/**
* The main entry point to the AccuYmlPlugin.
*
* This plugin runs under the 'check' lifecycle phase by default.
* The properties group for this plugin is accuYml{}
*/
class AccuYmlPlugin : Plugin<Project> {
override fun apply(project: Project) {
with(project) {
val ymlPluginProperties = extensions.create("accuYml", YmlPluginProperties::class.java)
@Suppress("UnstableApiUsage") // this create() is incubating.
val accuYmlTask = tasks.create(accuYml, AccuYmlTask::class.java, ymlPluginProperties, ObjectFactory)
tasks.all {
if (it.name == check){
it.dependsOn(accuYmlTask)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 938f360cfb5018b5bbcef1894d8791615115a864 | 927 | accu-yml | Apache License 2.0 |
src/jvmMain/kotlin/prime/template/interpreter/IncludeInstruction.kt | fantaevroman | 415,853,010 | false | {"Kotlin": 21526} | package prime.template.interpreter
import prime.combinator.pasers.*
import prime.combinator.pasers.implementations.*
class IncludeInstruction() : BlockInstruction("Block") {
private val sequenceOf = SequenceOf(
Str("include"),
Spaces(),
DoubleQuote(),
CustomWord(EnglishLetter().asChar(), Character('/'), Character('.')),
DoubleQuote()
).map {
it.copy(
context = hashMapOf(
Pair(
"path",
(it.context["sequence"] as List<ParsingContext>)[3].context["word"].toString()
)
)
)
}
override fun processInstruction(templateInstructionContext: ParsingContext): ParsingContext {
return sequenceOf.parse(createContext((templateInstructionContext.context["body"] as String).trim()))
}
private fun getPath(templateInstructionContext: ParsingContext): List<String> {
return templateInstructionContext.context["path"]
.toString()
.splitToSequence("/")
.toList()
.filter { it.isNotEmpty() }
}
override fun generateNewText(processedInstructionContext: ParsingContext,
variables: Map<String, String>,
renderTemplate: RenderTemplateFnType,
renderText: RenderTextFnType
): String {
return renderTemplate(getPath(processedInstructionContext), variables)
.map { it.text }
.orElseGet { "Template not found" }
}
} | 0 | Kotlin | 0 | 0 | fe075627e403b7454e2accef50022eccabdd3206 | 1,581 | primeTemplate | Apache License 2.0 |
src/commonMain/kotlin/br/darthweigert/service/RoomService.kt | darth-weigert | 843,393,138 | false | {"Kotlin": 64971, "Shell": 3185, "Batchfile": 2989} | package br.darthweigert.service
import br.darthweigert.geometry.Polygon
import br.darthweigert.geometry.Triangle
import br.darthweigert.algorithm.Triangulation
import br.darthweigert.geometry.PolygonHole
import br.darthweigert.geometry.toVectorPath
import br.darthweigert.math.nextRandomGray
import korlibs.korge.view.Container
import korlibs.korge.view.solidRect
import korlibs.math.geom.Point
import korlibs.math.geom.Vector2I
import korlibs.math.geom.vector.VectorPath
import urbanistic.clipper.ClipType
import urbanistic.clipper.Clipper
import urbanistic.clipper.LongPoint
import urbanistic.clipper.Path
import urbanistic.clipper.Paths
import urbanistic.clipper.PolyFillType
import urbanistic.clipper.PolyNode
import urbanistic.clipper.PolyTree
import urbanistic.clipper.PolyType
import urbanistic.clipper.pathOf
import kotlin.math.max
import kotlin.math.min
import kotlin.random.Random
class RoomService(private val random: Random) {
companion object {
const val SCALE_LONG = 1L
const val SCALE_DOUBLE = SCALE_LONG.toDouble()
}
private val rooms = Paths()
fun clear() {
rooms.clear()
}
fun addRoom(start: Vector2I, end: Vector2I) {
val p1x: Long = start.x * SCALE_LONG
val p1y: Long = start.y * SCALE_LONG
val p2x: Long = end.x * SCALE_LONG
val p2y: Long = end.y * SCALE_LONG
val left = min(p1x, p2x)
val top = min(p1y, p2y)
val right = max(p1x, p2x)
val bottom = max(p1y, p2y)
rooms.add(pathOf(
LongPoint(left, top),
LongPoint(right, top),
LongPoint(right, bottom),
LongPoint(left, bottom)
))
}
fun draw(shapeContainer: Container) {
for (box in rooms) {
val left = box[0].x
val top = box[0].y
val right = box[2].x
val bottom = box[2].y
shapeContainer.solidRect((right - left).toDouble(), (bottom - top).toDouble(), random.nextRandomGray()) {
x = left.toDouble()
y = top.toDouble()
}
}
}
fun roomsOutlines(): List<VectorPath> {
val clipper = Clipper()
clipper.addPaths(rooms, PolyType.Subject, true)
val result = PolyTree()
clipper.execute(ClipType.Union, result, PolyFillType.Positive, PolyFillType.Negative)
return result.allChildren().map { it.contour.toPointList().toVectorPath() }.toList()
}
suspend fun createNavMesh(debug: Triangulation.Debug): List<Triangle> {
val clipper = Clipper()
clipper.addPaths(rooms, PolyType.Subject, true)
val result = PolyTree()
clipper.execute(ClipType.Union, result, PolyFillType.Positive, PolyFillType.Negative)
val triangles = mutableListOf<Triangle>()
for (polyNode in result.allChildren().filter { !it.isHole }) {
val points = polyNode.contour.toPointList()
val holes = polyNode.childs.asSequence()
.filter { it.isHole }
.map { PolygonHole(it.contour.toPointList()) }
.toList()
triangles.addAll(
Triangulation(debug).triangulate(
Polygon(
points,
holes
)
))
}
return triangles
}
private fun PolyNode.allChildren(): Sequence<PolyNode> {
return this.childs.asSequence().flatMap { sequenceOf(it) + it.allChildren() }
}
private fun LongPoint.toPoint(): Point {
return Point(x / SCALE_DOUBLE, y / SCALE_DOUBLE)
}
private fun Path.toPointList(): List<Point> {
return this.asSequence().map {
it.toPoint()
}.toList()
}
}
| 0 | Kotlin | 0 | 0 | cc6e156fc0a7b87162052e3c9c58434e6ee75878 | 3,775 | bot-algorithms | MIT License |
cpg-language-go/src/main/kotlin/de/fraunhofer/aisec/cpg/frontends/golang/GoLanguageFrontend.kt | Fraunhofer-AISEC | 225,386,107 | false | null | /*
* Copyright (c) 2021, Fraunhofer AISEC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $$$$$$\ $$$$$$$\ $$$$$$\
* $$ __$$\ $$ __$$\ $$ __$$\
* $$ / \__|$$ | $$ |$$ / \__|
* $$ | $$$$$$$ |$$ |$$$$\
* $$ | $$ ____/ $$ |\_$$ |
* $$ | $$\ $$ | $$ | $$ |
* \$$$$$ |$$ | \$$$$$ |
* \______/ \__| \______/
*
*/
package de.fraunhofer.aisec.cpg.frontends.golang
import de.fraunhofer.aisec.cpg.TranslationContext
import de.fraunhofer.aisec.cpg.frontends.Language
import de.fraunhofer.aisec.cpg.frontends.LanguageFrontend
import de.fraunhofer.aisec.cpg.frontends.SupportsParallelParsing
import de.fraunhofer.aisec.cpg.frontends.TranslationException
import de.fraunhofer.aisec.cpg.frontends.golang.GoStandardLibrary.Modfile
import de.fraunhofer.aisec.cpg.frontends.golang.GoStandardLibrary.Parser
import de.fraunhofer.aisec.cpg.graph.*
import de.fraunhofer.aisec.cpg.graph.declarations.DeclarationSequence
import de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration
import de.fraunhofer.aisec.cpg.graph.newNamespaceDeclaration
import de.fraunhofer.aisec.cpg.graph.statements.expressions.Literal
import de.fraunhofer.aisec.cpg.graph.types.FunctionType
import de.fraunhofer.aisec.cpg.graph.types.Type
import de.fraunhofer.aisec.cpg.graph.unknownType
import de.fraunhofer.aisec.cpg.passes.EvaluationOrderGraphPass
import de.fraunhofer.aisec.cpg.passes.GoEvaluationOrderGraphPass
import de.fraunhofer.aisec.cpg.passes.GoExtraPass
import de.fraunhofer.aisec.cpg.passes.order.RegisterExtraPass
import de.fraunhofer.aisec.cpg.passes.order.ReplacePass
import de.fraunhofer.aisec.cpg.sarif.PhysicalLocation
import de.fraunhofer.aisec.cpg.sarif.Region
import java.io.File
import java.net.URI
/**
* A language frontend for the [GoLanguage]. It makes use the internal
* [go/ast](https://pkg.go.dev/go/ast) package of the Go runtime to parse the AST of a Go program.
* We make use of JNA to call a dynamic library which exports C function wrappers around the Go API.
* This is needed because we cannot directly export Go structs and pointers to C.
*/
@SupportsParallelParsing(false)
@RegisterExtraPass(GoExtraPass::class)
@ReplacePass(
lang = GoLanguage::class,
old = EvaluationOrderGraphPass::class,
with = GoEvaluationOrderGraphPass::class
)
class GoLanguageFrontend(language: Language<GoLanguageFrontend>, ctx: TranslationContext) :
LanguageFrontend<GoStandardLibrary.Ast.Node, GoStandardLibrary.Ast.Expr>(language, ctx) {
private var currentFileSet: GoStandardLibrary.Ast.FileSet? = null
private var currentModule: GoStandardLibrary.Modfile.File? = null
private var commentMap: GoStandardLibrary.Ast.CommentMap? = null
var currentFile: GoStandardLibrary.Ast.File? = null
val declarationHandler = DeclarationHandler(this)
val specificationHandler = SpecificationHandler(this)
var statementHandler = StatementHandler(this)
var expressionHandler = ExpressionHandler(this)
@Throws(TranslationException::class)
override fun parse(file: File): TranslationUnitDeclaration {
// Make sure, that our top level is set either way
val topLevel =
if (config.topLevel != null) {
config.topLevel
} else {
file.parentFile
}!!
val std = GoStandardLibrary.INSTANCE
// Try to parse a possible go.mod
val goModFile = topLevel.resolve("go.mod")
if (goModFile.exists()) {
currentModule = Modfile.parse(goModFile.absolutePath, goModFile.readText())
}
val fset = std.NewFileSet()
val f = Parser.parseFile(fset, file.absolutePath, file.readText())
this.commentMap = std.NewCommentMap(fset, f, f.comments)
currentFile = f
currentFileSet = fset
val tu = newTranslationUnitDeclaration(file.absolutePath, rawNode = f)
scopeManager.resetToGlobal(tu)
currentTU = tu
for (spec in f.imports) {
val import = specificationHandler.handle(spec)
scopeManager.addDeclaration(import)
}
val p = newNamespaceDeclaration(f.name.name)
scopeManager.enterScope(p)
try {
// we need to construct the package "path" (e.g. "encoding/json") out of the
// module path as well as the current directory in relation to the topLevel
var packagePath = file.parentFile.relativeTo(topLevel)
// If we are in a module, we need to prepend the module path to it
currentModule?.let { packagePath = File(it.module.mod.path).resolve(packagePath) }
p.path = packagePath.path
} catch (ex: IllegalArgumentException) {
log.error(
"Could not relativize package path to top level. Cannot set package path.",
ex
)
}
for (decl in f.decls) {
// Retrieve all top level declarations. One "Decl" could potentially
// contain multiple CPG declarations.
val declaration = declarationHandler.handle(decl)
if (declaration is DeclarationSequence) {
declaration.declarations.forEach { scopeManager.addDeclaration(it) }
} else {
scopeManager.addDeclaration(declaration)
}
}
scopeManager.leaveScope(p)
scopeManager.addDeclaration(p)
return tu
}
override fun typeOf(type: GoStandardLibrary.Ast.Expr): Type {
return when (type) {
is GoStandardLibrary.Ast.Ident -> {
val name: String =
if (isBuiltinType(type.name)) {
// Definitely not an FQN type
type.name
} else {
// FQN'ize this name (with the current file)
"${currentFile?.name?.name}.${type.name}" // this.File.Name.Name
}
objectType(name)
}
is GoStandardLibrary.Ast.ArrayType -> {
return typeOf(type.elt).array()
}
is GoStandardLibrary.Ast.ChanType -> {
// Handle them similar to a map type (see below)
return objectType("chan", listOf(typeOf(type.value)))
}
is GoStandardLibrary.Ast.FuncType -> {
val paramTypes = type.params.list.map { typeOf(it.type) }
val returnTypes = type.results?.list?.map { typeOf(it.type) } ?: listOf()
val name = funcTypeName(paramTypes, returnTypes)
return FunctionType(name, paramTypes, returnTypes, this.language)
}
is GoStandardLibrary.Ast.MapType -> {
// We cannot properly represent Go's built-in map types, yet so we have
// to make a shortcut here and represent it as a Java-like map<K, V> type.
return objectType("map", listOf(typeOf(type.key), typeOf(type.value)))
}
is GoStandardLibrary.Ast.StarExpr -> {
typeOf(type.x).pointer()
}
else -> {
log.warn("Not parsing type of type ${type.goType} yet")
unknownType()
}
}
}
private fun isBuiltinType(name: String): Boolean {
return when (name) {
"bool",
"byte",
"complex128",
"complex64",
"error",
"float32",
"float64",
"int",
"int8",
"int16",
"int32",
"int64",
"rune",
"string",
"uint",
"uint8",
"uint16",
"uint32",
"uint64",
"uintptr" -> true
else -> false
}
}
override fun codeOf(astNode: GoStandardLibrary.Ast.Node): String? {
return currentFileSet?.code(astNode)
}
override fun locationOf(astNode: GoStandardLibrary.Ast.Node): PhysicalLocation? {
val start = currentFileSet?.position(astNode.pos) ?: return null
val end = currentFileSet?.position(astNode.end) ?: return null
val url = currentFileSet?.fileName(astNode.pos)?.let { URI(it) } ?: return null
return PhysicalLocation(url, Region(start.line, start.column, end.line, end.column))
}
override fun setComment(node: Node, astNode: GoStandardLibrary.Ast.Node) {
// Since we are potentially calling this function more than once on a node because of the
// way go is structured (one decl can contain multiple specs), we need to make sure, that we
// are not "overriding" more specific comments with more global ones.
if (node.comment == null) {
val comment = this.commentMap?.comment(astNode)
node.comment = comment
}
}
/**
* This function produces a Go-style function type name such as `func(int, string) string` or
* `func(int) (error, string)`
*/
private fun funcTypeName(paramTypes: List<Type>, returnTypes: List<Type>): String {
val rn = mutableListOf<String>()
val pn = mutableListOf<String>()
for (t in paramTypes) {
pn += t.name.toString()
}
for (t in returnTypes) {
rn += t.name.toString()
}
val rs =
if (returnTypes.size > 1) {
rn.joinToString(", ", prefix = " (", postfix = ")")
} else if (returnTypes.isNotEmpty()) {
rn.joinToString(", ", prefix = " ")
} else {
""
}
return pn.joinToString(", ", prefix = "func(", postfix = ")$rs")
}
fun getImportName(spec: GoStandardLibrary.Ast.ImportSpec): String {
val name = spec.name
if (name != null) {
return name.name
}
val path = expressionHandler.handle(spec.path) as? Literal<*>
val paths = (path?.value as? String)?.split("/") ?: listOf()
return paths.lastOrNull() ?: ""
}
}
| 85 | Kotlin | 52 | 177 | 4c54110cf2bb1d24230216bc6060fb93282528f6 | 10,802 | cpg | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/neptune/_BuildableLastArgumentExtensions.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.neptune
import kotlin.Unit
import software.amazon.awscdk.services.neptune.CfnDBCluster
/**
* Contains the scaling configuration of an Neptune Serverless DB cluster.
*/
public inline
fun CfnDBCluster.setServerlessScalingConfiguration(block: CfnDBClusterServerlessScalingConfigurationPropertyDsl.() -> Unit
= {}) {
val builder = CfnDBClusterServerlessScalingConfigurationPropertyDsl()
builder.apply(block)
return setServerlessScalingConfiguration(builder.build())
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 698 | awscdk-dsl-kotlin | Apache License 2.0 |
src/main/kotlin/dev/wigger/mood/entry/EntryRepository.kt | LukasW01 | 796,396,744 | false | {"Kotlin": 29446, "HTML": 28991, "Dockerfile": 652, "Shell": 221} | package dev.wigger.mood.entry
import io.quarkus.hibernate.orm.panache.PanacheRepository
import jakarta.enterprise.context.ApplicationScoped
import java.util.UUID
@ApplicationScoped
class EntryRepository : PanacheRepository<Entry> {
fun findByUserId(userId: Long): List<Entry>? = find("user.id = ?1", userId).list()
fun findByIdAndUserId(id: UUID, userId: Long): Entry? = find("id = ?1 and user.id = ?2", id, userId).firstResult()
fun persistOne(entry: Entry) = persistAndFlush(entry)
fun delete(id: UUID) = delete("id = ?1", id)
fun findByID(id: UUID): Entry? = find("id = ?1", id).firstResult()
fun updateOne(id: UUID, entry: Entry) {
findByID(id)?.apply {
mood = entry.mood
journal = entry.journal
date = entry.date
color = entry.color
persistAndFlush(this)
}
}
}
| 0 | Kotlin | 0 | 0 | f54a5b8336d01591c6f3f92af2de5fd510ab2a5e | 877 | mood-quarkus | MIT License |
ontrack-extension-gitlab/src/main/java/net/nemerosa/ontrack/extension/gitlab/property/GitLabProjectConfigurationProperty.kt | nemerosa | 19,351,480 | false | null | package net.nemerosa.ontrack.extension.gitlab.property
import net.nemerosa.ontrack.extension.gitlab.model.GitLabConfiguration
import net.nemerosa.ontrack.model.support.ConfigurationProperty
/**
* @property configuration Link to the GitLab configuration
* @property issueServiceConfigurationIdentifier ID to the [net.nemerosa.ontrack.extension.issues.model.IssueServiceConfiguration] associated
* with this repository.
* @property repository Repository name
* @property indexationInterval Indexation interval
*/
class GitLabProjectConfigurationProperty(
override val configuration: GitLabConfiguration,
val issueServiceConfigurationIdentifier: String?,
val repository: String,
val indexationInterval: Int
) : ConfigurationProperty<GitLabConfiguration>
| 57 | Kotlin | 27 | 97 | 7c71a3047401e088ba0c6d43aa3a96422024857f | 775 | ontrack | MIT License |
src/main/kotlin/Plane.kt | TommiDL | 768,012,759 | false | {"Kotlin": 100450} | package org.example
import kotlin.math.sqrt
import kotlin.math.truncate
/**
*A 3D infinite plane parallel to the x and y axis and passing through the origin
* */
class Plane(val trasformation:Transformation=Transformation()):Shape {
/**
* checks if a ray intersects the plane
* @param Ray
* @return HitRecord
*/
override fun ray_intersection(ray: Ray): HitRecord? {
val inv_ray:Ray = ray.transform(this.trasformation.inverse())
if (inv_ray.dir.z == 0f ) return null
val t:Float = - ((inv_ray.origin.z)/(inv_ray.dir.z))
if (t < inv_ray.tmin || t > inv_ray.tmax) return null // intersection is out the limits of the ray
val hit_point:Point=inv_ray.at(t)
return HitRecord (
world_point = this.trasformation * hit_point,
normal = _plane_normal(hit_point, inv_ray.dir),
surface_point = _plane_point_to_uv(hit_point),
t=t,
ray = ray,
)
}
/**
* Define the Normal of the plane
* @param Point, ray_dir
* @return Normal
*/
fun _plane_normal(point:Point, ray_dir:Vec):Normal
{
val res:Normal=this.trasformation*Normal(x = 0f, y = 0f, z = 1f)
return if ( ray_dir.z < 0f) res else res*(-1)
}
/**
* Return the 2D (u,v) coordinates of a pixel on the screen
* @param Point
* @return Vec2D
*/
fun _plane_point_to_uv(point:Point):Vec2D {
val u = point.x - truncate(point.x)
val v = point.y - truncate(point.y)
return Vec2D(u, v )
}
}
| 4 | Kotlin | 0 | 0 | 91460e40467bd55133f5189de7cba89098b813a5 | 1,585 | LITracer | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/OnboardingDialogButtons.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui.laf.darcula.ui
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.Nls
import java.awt.Color
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
object OnboardingDialogButtons {
fun createLinkButton(@Nls text: String, icon: Icon?, onClick: Runnable?): JButton {
val btn = createLinkButton()
onClick?.let {runnable ->
btn.action = object : AbstractAction(text, icon) {
override fun actionPerformed(e: ActionEvent) {
runnable.run()
}
}
}
return btn
}
fun createLinkButton(): JButton {
val btn = JButton()
btn.putClientProperty("ActionToolbar.smallVariant", true)
btn.setHorizontalTextPosition(SwingConstants.LEFT)
btn.setContentAreaFilled(false)
btn.setForeground(JBUI.CurrentTheme.Link.Foreground.ENABLED)
btn.isBorderPainted = false
btn.iconTextGap = 0
return btn
}
fun createHoveredLinkButton(): JButton {
val btn = createLinkButton()
btn.preferredSize = Dimension(280, 40)
btn.isBorderPainted = true
btn.putClientProperty("JButton.backgroundColor", JBUI.CurrentTheme.ActionButton.hoverBackground())
btn.putClientProperty("JButton.borderColor", Color(0, true))
val listener: MouseAdapter = object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
btn.setContentAreaFilled(true)
btn.repaint()
}
override fun mouseExited(e: MouseEvent) {
btn.setContentAreaFilled(false)
btn.repaint()
}
}
btn.addMouseMotionListener(listener)
btn.addMouseListener(listener)
return btn
}
@JvmStatic
fun createHoveredLinkButton(@Nls text: String, icon: Icon?, onClick: Runnable?): JButton {
val btn = createHoveredLinkButton()
onClick?.let {runnable ->
btn.action = object : AbstractAction(text, icon) {
override fun actionPerformed(e: ActionEvent) {
runnable.run()
}
}
}
return btn
}
val BUTTON_HOVER_BORDER_COLOR: Color = JBColor(0xa8adbd, 0x6f737a)
val DEFAULT_BUTTON_HOVER_BORDER_COLOR: Color = JBColor(0xa8adbd, 0x6f737a)
@JvmStatic
fun createMainButton(@Nls text: String, icon: Icon?, onClick: Runnable? = null): JButton {
return createButton(true, text, icon, onClick)
}
@JvmStatic
fun createButton(@Nls text: String, icon: Icon?, onClick: Runnable? = null): JButton {
return createButton(false, text, icon, onClick)
}
private fun createButton(isDefault: Boolean, @Nls text: String, icon: Icon?, onClick: Runnable? = null): JButton {
val btn = createButton(isDefault)
onClick?.let {runnable ->
btn.action = object : AbstractAction(text, icon) {
override fun actionPerformed(e: ActionEvent) {
runnable.run()
}
}
}
return btn
}
fun createButton(isDefault: Boolean): JButton {
val btn = JButton()
btn.putClientProperty("ActionToolbar.smallVariant", true)
btn.putClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY, isDefault)
val listener: MouseAdapter = object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
btn.putClientProperty("JButton.borderColor",
if (isDefault) DEFAULT_BUTTON_HOVER_BORDER_COLOR else BUTTON_HOVER_BORDER_COLOR)
btn.repaint()
}
override fun mouseExited(e: MouseEvent) {
btn.putClientProperty("JButton.borderColor", null)
btn.repaint()
}
}
btn.addMouseMotionListener(listener)
btn.addMouseListener(listener)
return btn
}
} | 7 | null | 5079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 3,819 | intellij-community | Apache License 2.0 |
codegen/src/main/kotlin/com/android/designcompose/codegen/BuilderProcessor.kt | google | 624,923,090 | false | null | /*
* Copyright 2023 Google LLC
*
* 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.android.designcompose.codegen
import com.android.designcompose.annotation.DesignMetaKey
import com.android.designcompose.annotation.DesignPreviewContent
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.closestClassDeclaration
import com.google.devtools.ksp.getAnnotationsByType
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Dependencies
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.processing.SymbolProcessorProvider
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.FunctionKind
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSCallableReference
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSClassifierReference
import com.google.devtools.ksp.symbol.KSDeclaration
import com.google.devtools.ksp.symbol.KSDeclarationContainer
import com.google.devtools.ksp.symbol.KSDynamicReference
import com.google.devtools.ksp.symbol.KSFile
import com.google.devtools.ksp.symbol.KSFunctionDeclaration
import com.google.devtools.ksp.symbol.KSModifierListOwner
import com.google.devtools.ksp.symbol.KSNode
import com.google.devtools.ksp.symbol.KSParenthesizedReference
import com.google.devtools.ksp.symbol.KSPropertyAccessor
import com.google.devtools.ksp.symbol.KSPropertyDeclaration
import com.google.devtools.ksp.symbol.KSPropertyGetter
import com.google.devtools.ksp.symbol.KSPropertySetter
import com.google.devtools.ksp.symbol.KSReferenceElement
import com.google.devtools.ksp.symbol.KSTypeAlias
import com.google.devtools.ksp.symbol.KSTypeArgument
import com.google.devtools.ksp.symbol.KSTypeParameter
import com.google.devtools.ksp.symbol.KSTypeReference
import com.google.devtools.ksp.symbol.KSValueArgument
import com.google.devtools.ksp.symbol.KSValueParameter
import com.google.devtools.ksp.symbol.KSVisitorVoid
import com.google.devtools.ksp.symbol.Nullability
import com.google.gson.GsonBuilder
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import java.io.OutputStream
import java.util.Vector
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.HashSet
fun OutputStream.appendText(str: String) {
this.write(str.toByteArray())
}
class BuilderProcessor(private val codeGenerator: CodeGenerator, val logger: KSPLogger) :
SymbolProcessor {
operator fun OutputStream.plusAssign(str: String) {
this.write(str.toByteArray())
}
fun createNewFile(
className: String,
packageName: String,
dependencies: Set<KSFile>
): OutputStream {
val fileName = className.replace('.', '_') + "_gen"
val file =
codeGenerator.createNewFile(
dependencies = Dependencies(false, *dependencies.toTypedArray()),
packageName = packageName,
fileName = fileName
)
file += "package $packageName\n\n"
file += "import androidx.compose.runtime.Composable\n"
file += "import androidx.compose.ui.text.TextStyle\n"
file += "import android.graphics.Bitmap\n"
file += "import androidx.compose.ui.graphics.Brush\n"
file += "import androidx.compose.ui.Modifier\n"
file += "import androidx.compose.ui.semantics.semantics\n"
file += "import androidx.compose.runtime.mutableStateOf\n"
file += "import androidx.compose.runtime.remember\n"
file += "import androidx.compose.ui.platform.ComposeView\n"
file += "import androidx.compose.runtime.CompositionLocalProvider\n"
file += "import androidx.compose.runtime.compositionLocalOf\n"
file += "import android.widget.FrameLayout\n"
file += "import android.util.DisplayMetrics\n"
file += "import android.app.Activity\n"
file += "import android.view.ViewGroup\n"
file += "import android.os.Build\n"
file += "import com.android.designcompose.annotation.DesignMetaKey\n"
file += "import com.android.designcompose.serdegen.NodeQuery\n"
file += "import com.android.designcompose.common.DocumentServerParams\n"
file += "import com.android.designcompose.ComponentReplacementContext\n"
file += "import com.android.designcompose.ImageReplacementContext\n"
file += "import com.android.designcompose.CustomizationContext\n"
file += "import com.android.designcompose.DesignDoc\n"
file += "import com.android.designcompose.DesignComposeCallbacks\n"
file += "import com.android.designcompose.DesignSwitcherPolicy\n"
file += "import com.android.designcompose.OpenLinkCallback\n"
file += "import com.android.designcompose.DesignNodeData\n"
file += "import com.android.designcompose.DesignInjectKey\n"
file += "import com.android.designcompose.ListContent\n"
file += "import com.android.designcompose.setKey\n"
file += "import com.android.designcompose.mergeFrom\n"
file += "import com.android.designcompose.setComponent\n"
file += "import com.android.designcompose.setContent\n"
file += "import com.android.designcompose.setListContent\n"
file += "import com.android.designcompose.setCustomComposable\n"
file += "import com.android.designcompose.setImage\n"
file += "import com.android.designcompose.setImageWithContext\n"
file += "import com.android.designcompose.setBrush\n"
file += "import com.android.designcompose.setBrushFunction\n"
file += "import com.android.designcompose.setMeterValue\n"
file += "import com.android.designcompose.setMeterFunction\n"
file += "import com.android.designcompose.setModifier\n"
file += "import com.android.designcompose.setTapCallback\n"
file += "import com.android.designcompose.setOpenLinkCallback\n"
file += "import com.android.designcompose.setText\n"
file += "import com.android.designcompose.setTextFunction\n"
file += "import com.android.designcompose.setVariantProperties\n"
file += "import com.android.designcompose.setVisible\n"
file += "import com.android.designcompose.TapCallback\n"
file += "import com.android.designcompose.ParentComponentInfo\n"
file += "import com.android.designcompose.sDocClass\n"
file += "import com.android.designcompose.LocalCustomizationContext\n\n"
return file
}
override fun process(resolver: Resolver): List<KSAnnotated> {
fun createJsonFile(packageName: String, dependencies: Set<KSFile>): OutputStream {
val fileName = packageName.replace('.', '_') + "_gen"
return codeGenerator.createNewFile(
dependencies = Dependencies(false, *dependencies.toTypedArray()),
packageName = packageName,
fileName = fileName,
extensionName = "json"
)
}
// DesignDoc annotation
val symbols =
resolver
.getSymbolsWithAnnotation("com.android.designcompose.annotation.DesignDoc")
.filterIsInstance<
KSClassDeclaration
>() // Making sure we take only class declarations.
if (!symbols.iterator().hasNext()) return emptyList()
// The Json output files are package-specific. Build a map of the package names to the
// files that contribute symbols to the package.
val perPackageSourceDependencies: HashMap<String, MutableSet<KSFile>> = HashMap()
symbols.forEach {
it.containingFile?.let(
perPackageSourceDependencies.getOrPut(it.packageName.asString()) {
mutableSetOf<KSFile>()
}::add
)
}
// Use that map to create files for each package
val jsonStreams: HashMap<String, OutputStream> = HashMap()
perPackageSourceDependencies.forEach {
jsonStreams[it.key] = createJsonFile(it.key, it.value.toSet())
}
// Visit each symbol and generate all files
symbols.forEach { it.accept(DesignDocVisitor(jsonStreams), Unit) }
// Finish up
jsonStreams.values.forEach { it.close() }
// val ret = symbols.filterNot { it.validate() }.toList()
// Return emptyList instead of ret to avoid re-processing the output file infinitely. This
// should be reverted once the output file is fully compilable, at which point `ret` should
// be an empty list.
return emptyList()
}
private enum class VisitPhase {
Queries,
NodeCustomizations,
IgnoredImages,
ComposableFunctions,
KeyActionFunctions,
}
private enum class CustomizationType {
Text,
TextFunction,
Image,
ImageWithContext,
Brush,
BrushFunction,
Modifier,
TapCallback,
ContentReplacement,
ComponentReplacement,
ListContent,
Visibility,
TextStyle,
VariantProperty,
Meter,
MeterFunction,
Unknown
}
inner class DesignDocVisitor(
private val jsonStreams: HashMap<String, OutputStream>,
) : KSVisitorVoid() {
private var docName: String = ""
private var docId: String = ""
private var currentFunc = ""
private var textCustomizations: HashMap<String, Vector<Pair<String, String>>> = HashMap()
private var textFunctionCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var imageCustomizations: HashMap<String, Vector<Pair<String, String>>> = HashMap()
private var brushCustomizations: HashMap<String, Vector<Pair<String, String>>> = HashMap()
private var brushFunctionCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var modifierCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var tapCallbackCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var contentCustomizations: HashMap<String, Vector<Pair<String, String>>> = HashMap()
private var listCustomizations: HashMap<String, Vector<Pair<String, String>>> = HashMap()
private var replacementCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var imageContextCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var visibleCustomizations: HashMap<String, Vector<Pair<String, String>>> = HashMap()
private var textStyleCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var meterCustomizations: HashMap<String, Vector<Pair<String, String>>> = HashMap()
private var meterFunctionCustomizations: HashMap<String, Vector<Pair<String, String>>> =
HashMap()
private var nodeNameBuilder: ArrayList<String> = ArrayList()
private var variantProperties: HashMap<String, String> = HashMap()
private var visitPhase: VisitPhase = VisitPhase.Queries
private var queriesNameSet: HashSet<String> = HashSet()
private var ignoredImages: HashMap<String, HashSet<String>> = HashMap()
private var overrideInterface: String = ""
private lateinit var out: OutputStream
private var currentJsonStream: OutputStream? = null
private var designDocJson: JsonObject = JsonObject()
private var jsonComponents: JsonArray = JsonArray()
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
if (classDeclaration.classKind != ClassKind.INTERFACE) {
logger.error("Invalid class kind with @DesignDoc", classDeclaration)
return
}
// Convenience
val packageName = classDeclaration.packageName.asString()
val className = classDeclaration.simpleName.asString()
// Create a new file for each @DesignDoc annotation
out = createNewFile(className, packageName, setOf(classDeclaration.containingFile!!))
currentJsonStream = jsonStreams[packageName]
// If the interface inherits from another interface, get the name of it
classDeclaration.superTypes.forEach {
val superType = it.resolve()
// All classes that don't declare a superclass inherit from "Any", so ignore it
if (superType.toString() != "Any") {
if (superType.isError)
logger.error("Invalid supertype for interface hg $classDeclaration")
overrideInterface = superType.declaration.qualifiedName?.asString() ?: ""
if (overrideInterface.endsWith("Gen"))
logger.error(
"Extending a generated interface $overrideInterface not supported"
)
}
}
// Get the @DesignDoc annotation object
val annotation: KSAnnotation =
classDeclaration.annotations.first { it.shortName.asString() == "DesignDoc" }
// Get the 'id' argument object from @DesignDoc.
val idArg: KSValueArgument =
annotation.arguments.first { arg -> arg.name?.asString() == "id" }
docName = className + "Doc"
docId = idArg.value as String
// Declare a global document ID that can be changed by the Design Switcher
val docIdVarName = className + "GenId"
out.appendText("private var $docIdVarName: String = \"$docId\"\n\n")
// Create an interface for each interface declaration
val interfaceName = className + "Gen"
// Inherit from the specified superclass interface if it exists
val overrideInterfaceDecl =
if (overrideInterface.isNotEmpty()) ": $overrideInterface " else ""
out.appendText("interface $interfaceName $overrideInterfaceDecl{\n")
// Create a list of all node names used in this interface
visitPhase = VisitPhase.Queries
out.appendText(" fun queries(): ArrayList<String> {\n")
out.appendText(" return arrayListOf(\n")
classDeclaration.getAllFunctions().forEach { it.accept(this, data) }
out.appendText(" )\n")
out.appendText(" }\n\n")
// Create a list of all customization node names used in this interface
visitPhase = VisitPhase.NodeCustomizations
classDeclaration.getAllFunctions().forEach { it.accept(this, data) }
// Iterate through all the functions and parameters and build up the ignoredImages
// HashMap
visitPhase = VisitPhase.IgnoredImages
classDeclaration.getAllFunctions().forEach { it.accept(this, data) }
// Output the list of all images to ignore using the ignoredImages HashMap
out.appendText(" fun ignoredImages(): HashMap<String, Array<String>> {\n")
out.appendText(" return hashMapOf(\n")
for ((node, images) in ignoredImages) {
out.appendText(" \"$node\" to arrayOf(\n")
for (image in images) {
out.appendText(" \"$image\",\n")
}
out.appendText(" ),\n")
}
out.appendText(" )\n")
out.appendText(" }\n\n")
// Add a @Composable function that can be used to show the design switcher
out.appendText(" @Composable\n")
out.appendText(" fun DesignSwitcher(modifier: Modifier = Modifier) {\n")
out.appendText(
" val (docId, setDocId) = remember { mutableStateOf(\"$docId\") }\n"
)
out.appendText(" DesignDoc(\"$docName\", docId, NodeQuery.NodeName(\"\"),\n")
out.appendText(" modifier = modifier,\n")
out.appendText(" setDocId = setDocId\n")
out.appendText(" )\n")
out.appendText(" }\n\n")
// Add a function that lets you add the Design Switcher to a view group at the top right
// corner
out.appendText(
" fun addDesignSwitcherToViewGroup(activity: Activity, view: ViewGroup) {\n"
)
out.appendText(
" val composeView = ComposeView(activity.applicationContext).apply {\n"
)
out.appendText(" setContent { DesignSwitcher() }\n")
out.appendText(" }\n")
out.appendText(" var width: Int\n")
out.appendText(" var height: Int\n")
out.appendText(" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n")
out.appendText(
" val displayMetrics = activity.windowManager.currentWindowMetrics\n"
)
out.appendText(" width = displayMetrics.bounds.width()\n")
out.appendText(" height = displayMetrics.bounds.height()\n")
out.appendText(" } else {\n")
out.appendText(" val displayMetrics = DisplayMetrics()\n")
out.appendText(
" activity.windowManager.defaultDisplay.getMetrics(displayMetrics)\n"
)
out.appendText(" height = displayMetrics.heightPixels\n")
out.appendText(" width = displayMetrics.widthPixels\n")
out.appendText(" }\n")
out.appendText(" val params = FrameLayout.LayoutParams(width, height)\n")
out.appendText(" params.leftMargin = 0\n")
out.appendText(" params.topMargin = 0\n")
out.appendText(" view.addView(composeView, params)\n")
out.appendText(" }\n\n")
visitPhase = VisitPhase.ComposableFunctions
classDeclaration.getAllFunctions().forEach { it.accept(this, data) }
visitPhase = VisitPhase.KeyActionFunctions
classDeclaration.getAllFunctions().forEach { it.accept(this, data) }
// Add a function that composes a component with variants given a node name that
// contains all the variant properties and values
out.appendText(" @Composable\n")
// Add an override declaration if this interface inherits from another
val overrideDecl = if (overrideInterface.isNotEmpty()) "override " else ""
out.appendText(" ${overrideDecl}fun CustomComponent(\n")
// Default parameters are not allowed when overriding a function
val defaultModifierDecl = if (overrideInterface.isEmpty()) " = Modifier" else ""
out.appendText(" modifier: Modifier$defaultModifierDecl,\n")
out.appendText(" nodeName: String,\n")
out.appendText(" rootNodeQuery: NodeQuery,\n")
out.appendText(" parentComponents: List<ParentComponentInfo>,\n")
out.appendText(" tapCallback: TapCallback?,\n")
out.appendText(" ) {\n")
out.appendText(" val customizations = remember { CustomizationContext() }\n")
out.appendText(" if (tapCallback != null)\n")
out.appendText(" customizations.setTapCallback(nodeName, tapCallback)\n")
out.appendText(" customizations.mergeFrom(LocalCustomizationContext.current)\n")
out.appendText(
" val (docId, setDocId) = remember { mutableStateOf(\"$docId\") }\n"
)
out.appendText(" val queries = queries()\n")
out.appendText(" queries.add(nodeName)\n")
out.appendText(
" CompositionLocalProvider(LocalCustomizationContext provides customizations) {\n"
)
out.appendText(" DesignDoc(\"$docName\", docId, rootNodeQuery,\n")
out.appendText(" customizations = customizations,\n")
out.appendText(" modifier = modifier,\n")
out.appendText(
" serverParams = DocumentServerParams(queries, ignoredImages()),\n"
)
out.appendText(" setDocId = setDocId,\n")
out.appendText(
" designSwitcherPolicy = DesignSwitcherPolicy.SHOW_IF_ROOT,\n"
)
out.appendText(" parentComponents = parentComponents\n")
out.appendText(" )\n")
out.appendText(" }\n")
out.appendText(" }\n\n")
out.appendText("}\n\n")
val objectName = className + "Doc"
out.appendText("object $objectName: $interfaceName {}\n\n")
// Write the design doc JSON for our plugin
designDocJson.addProperty("name", className)
designDocJson.add("components", jsonComponents)
val versionArg = annotation.arguments.find { arg -> arg.name?.asString() == "version" }
if (versionArg != null) {
val versionString = versionArg.value as String
designDocJson.addProperty("version", versionString)
}
val gson = GsonBuilder().setPrettyPrinting().create()
currentJsonStream?.appendText(gson.toJson(designDocJson))
// Close out the main file
out.close()
}
override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: Unit) {
if (function.functionKind != FunctionKind.MEMBER) {
logger.error(
"Invalid function kind ${function.functionKind} with @DesignDoc",
function
)
return
}
if (visitPhase == VisitPhase.KeyActionFunctions) {
// For the KeyActionFunctions visit phase, check for a @DesignKeyAction annotation
// and generate the function to inject a key event
val keyAnnotation: KSAnnotation? =
function.annotations.find { it.shortName.asString() == "DesignKeyAction" }
if (keyAnnotation != null) visitDesignKeyAction(function, keyAnnotation)
} else {
// Get the @DesignComponent annotation object, or return if none
val annotation: KSAnnotation? =
function.annotations.find { it.shortName.asString() == "DesignComponent" }
currentFunc = function.toString()
if (annotation != null) visitDesignComponent(function, data, annotation)
}
}
private fun visitDesignComponent(
function: KSFunctionDeclaration,
data: Unit,
annotation: KSAnnotation
) {
// Get the 'node' argument
val nodeArg: KSValueArgument =
annotation.arguments.first { arg -> arg.name?.asString() == "node" }
val nodeName = nodeArg.value as String
// Get the 'isRoot' argument
val isRootArg = annotation.arguments.find { arg -> arg.name?.asString() == "isRoot" }
val isRoot = if (isRootArg != null) isRootArg.value as Boolean else false
// Get the 'override' argument, which should be set if this interface inherits from
// another interface and this function overrides one of the base functions
val overrideArg: KSValueArgument? =
annotation.arguments.find { it.name?.asString() == "override" }
var override = false
if (overrideArg != null) override = overrideArg.value as Boolean
when (visitPhase) {
VisitPhase.Queries -> visitFunctionQueries(function, nodeName)
VisitPhase.NodeCustomizations ->
visitFunctionNodeCustomizations(function, nodeName, isRoot)
VisitPhase.IgnoredImages -> visitFunctionIgnoredImagesBuild(function, nodeName)
VisitPhase.ComposableFunctions ->
visitFunctionComposables(function, data, nodeName, override)
VisitPhase.KeyActionFunctions -> {}
}
}
private fun visitDesignKeyAction(
function: KSFunctionDeclaration,
annotation: KSAnnotation
) {
// Get the 'key' argument
val keyArg: KSValueArgument =
annotation.arguments.first { arg -> arg.name?.asString() == "key" }
val key = keyArg.value as Char
// Get the 'metaKeys' argument
val metaKeysArg: KSValueArgument =
annotation.arguments.first { arg -> arg.name?.asString() == "metaKeys" }
// Generate a comma separated list of metakeys
var metaKeysStr = ""
if (metaKeysArg.value != null) {
val metaKeys = metaKeysArg.value as ArrayList<DesignMetaKey>
metaKeysStr = metaKeys.joinToString(",")
}
out.appendText(" fun $function() {\n")
out.appendText(" DesignInjectKey('$key', listOf($metaKeysStr))\n ")
out.appendText(" }\n\n")
}
private fun visitFunctionQueries(function: KSFunctionDeclaration, nodeName: String) {
if (!queriesNameSet.contains(nodeName)) {
out.appendText(" \"$nodeName\",\n")
queriesNameSet.add(nodeName)
}
// If there are any @DesignVariant annotations, add the property names to the list of
// queries
function.parameters.forEach { param ->
val annotation: KSAnnotation? =
param.annotations.find { it.shortName.asString() == "DesignVariant" }
if (annotation != null) {
val propertyArg: KSValueArgument =
annotation.arguments.first { arg -> arg.name?.asString() == "property" }
val propertyName = propertyArg.value as String
if (!queriesNameSet.contains(propertyName)) {
out.appendText(" \"$propertyName\",\n")
queriesNameSet.add(propertyName)
}
}
}
}
@OptIn(KspExperimental::class)
private fun visitFunctionNodeCustomizations(
function: KSFunctionDeclaration,
node: String,
isRoot: Boolean
) {
// Add the node and function name to the json components list
val jsonComponent = JsonObject()
jsonComponent.addProperty("node", node)
jsonComponent.addProperty("name", function.toString())
jsonComponent.addProperty("isRoot", isRoot)
jsonComponents.add(jsonComponent)
val jsonCustomizations = JsonArray()
function.parameters.forEach { param ->
val annotation: KSAnnotation =
param.annotations.find {
it.shortName.asString() == "Design" ||
it.shortName.asString() == "DesignVariant"
} ?: return
val nodeArg: KSValueArgument =
annotation.arguments.first { arg ->
arg.name?.asString() == "node" || arg.name?.asString() == "property"
}
val nodeName = nodeArg.value as String
// Add a customization for this arg to the json list
val jsonHash = JsonObject()
val paramType = getParamCustomizationType(param)
jsonHash.addProperty("name", param.name?.asString())
jsonHash.addProperty("node", nodeName)
jsonHash.addProperty("kind", paramType.name)
// If there is a @DesignContentTypes annotation, use it to build a content list
// for this node. This represents all node names that could be placed into this
// node as a child.
val contentTypesAnnotation =
param.annotations.find { it.shortName.asString() == "DesignContentTypes" }
if (contentTypesAnnotation != null) {
@Suppress("UNCHECKED_CAST")
val nodes =
contentTypesAnnotation.arguments
.first { arg -> arg.name?.asString() == "nodes" }
.value as? ArrayList<String>
val jsonContentArray = JsonArray()
nodes?.forEach { jsonContentArray.add(it.trim()) }
jsonHash.add("content", jsonContentArray)
}
// To get data for the @DesignPreviewContent annotation, we need to use
// getAnnotationsByType() in order to parse out the custom class PreviewNode.
val designPreviewContentAnnotations =
param.getAnnotationsByType(DesignPreviewContent::class)
val previewContentArray = JsonArray()
designPreviewContentAnnotations.forEach { content ->
val previewPageHash = JsonObject()
val jsonContentArray = JsonArray()
content.nodes.forEach {
for (i in 1..it.count) {
jsonContentArray.add(it.node.trim())
}
}
if (!jsonContentArray.isEmpty) {
previewPageHash.addProperty("name", content.name)
previewPageHash.add("content", jsonContentArray)
previewContentArray.add(previewPageHash)
}
}
if (!previewContentArray.isEmpty)
jsonHash.add("previewContent", previewContentArray)
jsonCustomizations.add(jsonHash)
val classDecl = param.type.resolve().declaration.closestClassDeclaration()
if (classDecl != null && classDecl.classKind == ClassKind.ENUM_CLASS) {
val jsonVariantsArray = JsonArray()
classDecl.declarations.forEach {
val enumValue = it.simpleName.asString()
if (
enumValue != "valueOf" && enumValue != "values" && enumValue != "<init>"
) {
jsonVariantsArray.add(it.simpleName.asString())
}
}
jsonHash.add("values", jsonVariantsArray)
}
}
jsonComponent.add("customizations", jsonCustomizations)
}
private fun visitFunctionIgnoredImagesBuild(
function: KSFunctionDeclaration,
nodeName: String
) {
val nodeImageSet = ignoredImages[nodeName] ?: HashSet<String>()
function.parameters.forEach { param ->
val ignore =
when (getParamCustomizationType(param)) {
CustomizationType.Image -> true
CustomizationType.Brush -> true
CustomizationType.BrushFunction -> true
CustomizationType.ContentReplacement -> true
CustomizationType.ComponentReplacement -> true
CustomizationType.ListContent -> true
CustomizationType.ImageWithContext -> true
else -> false
}
// Get the 'node' argument
val annotation: KSAnnotation =
param.annotations.find { it.shortName.asString() == "Design" } ?: return
val nodeArg: KSValueArgument =
annotation.arguments.first { arg -> arg.name?.asString() == "node" }
val paramNodeName = nodeArg.value as String
if (ignore) nodeImageSet.add(paramNodeName)
}
ignoredImages[nodeName] = nodeImageSet
}
private fun getParamTypeString(param: KSValueParameter): String {
// Add any annotations specified for this type
val typeAnnotations = param.type.annotations
var typeName = ""
typeAnnotations.forEach { typeName += "$it " }
val ksType = param.type.resolve()
val qualifiedName = ksType.declaration.qualifiedName
val qualifier = qualifiedName?.getQualifier()
// For kotlin and android types, use just the typename without the qualifier. Otherwise,
// use the qualifier, since the macro specified an explicit qualifier
typeName +=
if (qualifier?.startsWith("kotlin")?.or(qualifier.startsWith("android")) == true)
param.type.toString()
else qualifiedName?.asString() ?: param.type.toString()
// Add template parameters if there are any
if (!ksType.isFunctionType && ksType.arguments.isNotEmpty()) {
typeName += "<${ksType.arguments.joinToString(",") { arg -> arg.type.toString() }}>"
}
// Add nullability operator to types in typeName that are nullable
ksType.arguments.forEach {
if (it.type?.resolve()?.nullability == Nullability.NULLABLE)
typeName = typeName.replace(it.type.toString(), "${it.type}?")
}
// Add Nullability operator if the type is nullable
if (param.type.resolve().nullability == Nullability.NULLABLE) typeName += "?"
return typeName
}
private fun getParamCustomizationType(param: KSValueParameter): CustomizationType {
val variantAnnotation: KSAnnotation? =
param.annotations.find { it.shortName.asString() == "DesignVariant" }
if (variantAnnotation != null) return CustomizationType.VariantProperty
return when (getParamTypeString(param)) {
"String" -> CustomizationType.Text
"@Composable () -> String" -> CustomizationType.TextFunction
"Brush" -> CustomizationType.Brush
"() -> Brush" -> CustomizationType.BrushFunction
"Bitmap?" -> CustomizationType.Image
"Modifier" -> CustomizationType.Modifier
"com.android.designcompose.TapCallback" -> CustomizationType.TapCallback
"@Composable () -> Unit" -> CustomizationType.ContentReplacement
"@Composable (ComponentReplacementContext) -> Unit" ->
CustomizationType.ComponentReplacement
"com.android.designcompose.ListContent" -> CustomizationType.ListContent
"@Composable (ImageReplacementContext) -> Bitmap?" ->
CustomizationType.ImageWithContext
"Boolean" -> CustomizationType.Visibility
"TextStyle" -> CustomizationType.TextStyle
"com.android.designcompose.Meter" -> CustomizationType.Meter
"com.android.designcompose.MeterFunction" -> CustomizationType.MeterFunction
else -> CustomizationType.Unknown
}
}
private fun visitFunctionComposables(
function: KSFunctionDeclaration,
data: Unit,
nodeName: String,
override: Boolean
) {
// Generate the function name and args
out.appendText(" @Composable\n")
val overrideKeyword = if (override) "override " else ""
out.appendText(" ${overrideKeyword}fun $function(\n")
// Collect arguments into a list so we can reuse them
val args: ArrayList<Pair<String, String>> = ArrayList()
// Add a modifier for the root item. Default params not allowed with override
val defaultModifier = if (override) "" else " = Modifier"
args.add(Pair("modifier", "Modifier$defaultModifier"))
// Add an option to register a function to handle open link callbacks
val defaultOpenLink = if (override) "" else " = null"
args.add(Pair("openLinkCallback", "OpenLinkCallback?$defaultOpenLink"))
// Add optional callbacks to be called on certain document events
val defaultCallbacks = if (override) "" else " = null"
args.add(Pair("designComposeCallbacks", "DesignComposeCallbacks?$defaultCallbacks"))
// Add optional key that can be used to uniquely identify this particular instance
val keyDefault = if (override) "" else " = null"
args.add(Pair("key", "String?$keyDefault"))
// Get the @DesignComponent annotation object, or return if none
val annotation: KSAnnotation =
function.annotations.find { it.shortName.asString() == "DesignComponent" } ?: return
// Get the 'designSwitcher' argument
val switcherArg: KSValueArgument? =
annotation.arguments.find { it.name?.asString() == "hideDesignSwitcher" }
var hideDesignSwitcher = false
if (switcherArg != null) hideDesignSwitcher = switcherArg.value as Boolean
// placeholder is a special name that gets mapped to a placeholder composable.
var placeholderComposable: String? = null
// variantFuncParameters accumulates a list of all the DesignVariant parameters and is
// used
// when generating the *Node function after this one.
var variantFuncParameters = ""
nodeNameBuilder.clear()
variantProperties.clear()
function.parameters.forEach { param ->
// Each parameter may have an annotation, so visit each one
param.accept(this, data)
val name = param.name!!.asString()
val customizationType = getParamCustomizationType(param)
val typeName = getParamTypeString(param)
args.add(Pair(name, typeName))
if (customizationType == CustomizationType.VariantProperty)
variantFuncParameters += " $name: $typeName,\n"
if (
name == "placeholder" &&
customizationType == CustomizationType.ContentReplacement
)
placeholderComposable = name
}
// Output all arguments
args.forEach { out.appendText(" ${it.first}: ${it.second},\n") }
// If there are any DesignVariant annotations on parameters, nodeNameBuilder would have
// been populated. If the node name matches a property in variantProperties, we assume
// that it is a component set, so we construct a node name that represents one of its
// child variants and make rootNodeQuery a NodeVariant.
val isComponentSet = variantProperties.containsKey(nodeName)
val nodeNameVar =
if (isComponentSet) {
nodeNameBuilder.joinToString(" + \",\"\n") + "\n"
} else {
""
}
// Generate the function body by filling out customizations and then returning
// the @Composable DesignDoc function
out.appendText(" ) {\n")
// Embed the Doc's class to allow matching on in tests
out.appendText(" val className = javaClass.name\n")
out.appendText(" val customizations = remember { CustomizationContext() }\n")
out.appendText(" customizations.setKey(key)\n")
out.appendText(" customizations.mergeFrom(LocalCustomizationContext.current)\n")
// Set the node name. If this is a component with variants, the node name has been built
// in the nodeNameVar variable. Otherwise, it's just the node name passed in.
if (isComponentSet) {
out.appendText(" var nodeName = \"\"\n")
out.appendText(nodeNameVar)
} else {
out.appendText(" var nodeName = \"$nodeName\"\n")
}
// Create a NodeQuery for the initial root node
if (isComponentSet)
out.appendText(
" val rootNodeQuery = NodeQuery.NodeVariant(nodeName, \"$nodeName\")\n"
)
else out.appendText(" val rootNodeQuery = NodeQuery.NodeName(nodeName)\n")
// Register the open link callback if one exists
out.appendText(" if (openLinkCallback != null)\n")
out.appendText(
" customizations.setOpenLinkCallback(nodeName, openLinkCallback)\n"
)
val textCustom =
textCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in textCustom) {
out.appendText(" customizations.setText(\"$node\", $value)\n")
}
val textFuncCustom =
textFunctionCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in textFuncCustom) {
out.appendText(" customizations.setTextFunction(\"$node\", $value)\n")
}
val imageCustom =
imageCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in imageCustom) {
out.appendText(" customizations.setImage(\"$node\", $value)\n")
}
val brushCustom =
brushCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in brushCustom) {
out.appendText(" customizations.setBrush(\"$node\", $value)\n")
}
val brushFunctionCustom =
brushFunctionCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in brushFunctionCustom) {
out.appendText(" customizations.setBrushFunction(\"$node\", $value)\n")
}
val modifierCustom =
modifierCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in modifierCustom) {
out.appendText(" customizations.setModifier(\"$node\", $value)\n")
}
val tapCallbackCustom =
tapCallbackCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in tapCallbackCustom) {
out.appendText(" customizations.setTapCallback(\"$node\", $value)\n")
}
val contentCustom =
contentCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in contentCustom) {
out.appendText(" customizations.setContent(\"$node\", $value)\n")
}
val listCustom =
listCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in listCustom) {
out.appendText(" customizations.setListContent(\"$node\", $value)\n")
}
val replacementCustom =
replacementCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in replacementCustom) {
out.appendText(" customizations.setComponent(\"$node\", $value)\n")
}
val imageContextCustom =
imageContextCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in imageContextCustom) {
out.appendText(" customizations.setImageWithContext(\"$node\", $value)\n")
}
val visibleCustom =
visibleCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in visibleCustom) {
out.appendText(" customizations.setVisible(\"$node\", $value)\n")
}
val textStyleCustom =
textStyleCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in textStyleCustom) {
out.appendText(" customizations.setTextStyle(\"$node\", $value)\n")
}
val meterCustom =
meterCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in meterCustom) {
out.appendText(" customizations.setMeterValue(\"$node\", $value)\n")
}
val meterFunctionCustom =
meterFunctionCustomizations[function.toString()] ?: Vector<Pair<String, String>>()
for ((node, value) in meterFunctionCustom) {
out.appendText(" customizations.setMeterFunction(\"$node\", $value)\n")
}
out.appendText("\n")
// Generate code to set variant properties if there are any @DesignVariant parameters
if (variantProperties.isNotEmpty()) {
out.appendText(" val variantProperties = HashMap<String, String>()\n")
variantProperties.forEach {
out.appendText(" variantProperties[\"${it.key}\"] = ${it.value}\n")
}
out.appendText(" customizations.setVariantProperties(variantProperties)\n")
}
out.appendText(
" customizations.setCustomComposable { mod, name, query, parentComponents, tapCallback ->\n"
)
out.appendText(
" CustomComponent(mod, name, query, parentComponents, tapCallback) }\n\n"
)
// Create a mutable state so that the Design Switcher can dynamically change the
// document ID
out.appendText(
" val (docId, setDocId) = remember { mutableStateOf(\"$docId\") }\n"
)
// If there are variants, add the variant name to the list of queries
out.appendText(" val queries = queries()\n")
if (isComponentSet) out.appendText(" queries.add(nodeName)\n")
out.appendText(
" CompositionLocalProvider(LocalCustomizationContext provides customizations) {\n"
)
out.appendText(" DesignDoc(\"$docName\", docId, rootNodeQuery,\n")
if (placeholderComposable != null) {
out.appendText(" placeholder = $placeholderComposable,")
}
out.appendText(" customizations = customizations,\n")
out.appendText(
" modifier = modifier.semantics { sDocClass = className},\n"
)
out.appendText(
" serverParams = DocumentServerParams(queries, ignoredImages()),\n"
)
out.appendText(" setDocId = setDocId,\n")
val switchPolicy =
if (hideDesignSwitcher) "DesignSwitcherPolicy.HIDE"
else "DesignSwitcherPolicy.SHOW_IF_ROOT"
out.appendText(" designSwitcherPolicy = $switchPolicy,\n")
out.appendText(" designComposeCallbacks = designComposeCallbacks,\n")
out.appendText(" )\n")
out.appendText(" }\n")
out.appendText(" }\n\n")
// New function for DesignNodeData
out.appendText(" ${overrideKeyword}fun ${function}DesignNodeData(\n")
out.appendText(variantFuncParameters)
out.appendText(" ): DesignNodeData {\n")
out.appendText(" val variantProperties = HashMap<String, String>()\n")
if (variantProperties.isNotEmpty()) {
variantProperties.forEach {
out.appendText(" variantProperties[\"${it.key}\"] = ${it.value}\n")
}
}
out.appendText(" return DesignNodeData(\"$nodeName\", variantProperties)\n")
out.appendText(" }\n\n")
}
// Visit a function parameter. For each parameter, check all parameter annotations
override fun visitValueParameter(valueParameter: KSValueParameter, data: Unit) {
val variantAnnotation: KSAnnotation? =
valueParameter.annotations.find { it.shortName.asString() == "DesignVariant" }
if (variantAnnotation != null) {
val propertyArg: KSValueArgument =
variantAnnotation.arguments.first { arg -> arg.name?.asString() == "property" }
val propertyName = propertyArg.value as String
val param = valueParameter.name!!.asString()
variantProperties[propertyName] = "$param.name"
nodeNameBuilder.add(" nodeName += \"$propertyName=\" + $param.name")
}
val annotation: KSAnnotation =
valueParameter.annotations.find { it.shortName.asString() == "Design" } ?: return
when (getParamCustomizationType(valueParameter)) {
CustomizationType.Text ->
addCustomization(valueParameter, annotation, textCustomizations)
CustomizationType.TextFunction ->
addCustomization(valueParameter, annotation, textFunctionCustomizations)
CustomizationType.Image ->
addCustomization(valueParameter, annotation, imageCustomizations)
CustomizationType.Brush ->
addCustomization(valueParameter, annotation, brushCustomizations)
CustomizationType.BrushFunction ->
addCustomization(valueParameter, annotation, brushFunctionCustomizations)
CustomizationType.Modifier ->
addCustomization(valueParameter, annotation, modifierCustomizations)
CustomizationType.TapCallback ->
addCustomization(valueParameter, annotation, tapCallbackCustomizations)
CustomizationType.ContentReplacement ->
addCustomization(valueParameter, annotation, contentCustomizations)
CustomizationType.ComponentReplacement ->
addCustomization(valueParameter, annotation, replacementCustomizations)
CustomizationType.ListContent ->
addCustomization(valueParameter, annotation, listCustomizations)
CustomizationType.ImageWithContext ->
addCustomization(valueParameter, annotation, imageContextCustomizations)
CustomizationType.Visibility ->
addCustomization(valueParameter, annotation, visibleCustomizations)
CustomizationType.TextStyle ->
addCustomization(valueParameter, annotation, textStyleCustomizations)
CustomizationType.Meter ->
addCustomization(valueParameter, annotation, meterCustomizations)
CustomizationType.MeterFunction ->
addCustomization(valueParameter, annotation, meterFunctionCustomizations)
else ->
logger.error(
"Invalid @Design parameter type ${getParamTypeString(valueParameter)}"
)
}
}
private fun addCustomization(
valueParameter: KSValueParameter,
annotation: KSAnnotation,
customizations: HashMap<String, Vector<Pair<String, String>>>
) {
val nodeArg: KSValueArgument =
annotation.arguments.first { arg -> arg.name?.asString() == "node" }
val node = nodeArg.value as String
val name = valueParameter.name!!.asString()
val vec = customizations[currentFunc] ?: Vector<Pair<String, String>>()
vec.add(Pair(node, name))
customizations[currentFunc] = vec
}
override fun visitNode(node: KSNode, data: Unit) {}
override fun visitAnnotated(annotated: KSAnnotated, data: Unit) {}
override fun visitAnnotation(annotation: KSAnnotation, data: Unit) {}
override fun visitModifierListOwner(modifierListOwner: KSModifierListOwner, data: Unit) {}
override fun visitDeclaration(declaration: KSDeclaration, data: Unit) {}
override fun visitDeclarationContainer(
declarationContainer: KSDeclarationContainer,
data: Unit
) {}
override fun visitDynamicReference(reference: KSDynamicReference, data: Unit) {}
override fun visitFile(file: KSFile, data: Unit) {}
override fun visitCallableReference(reference: KSCallableReference, data: Unit) {}
override fun visitParenthesizedReference(reference: KSParenthesizedReference, data: Unit) {}
override fun visitPropertyDeclaration(property: KSPropertyDeclaration, data: Unit) {}
override fun visitPropertyAccessor(accessor: KSPropertyAccessor, data: Unit) {}
override fun visitPropertyGetter(getter: KSPropertyGetter, data: Unit) {}
override fun visitPropertySetter(setter: KSPropertySetter, data: Unit) {}
override fun visitClassifierReference(reference: KSClassifierReference, data: Unit) {}
override fun visitReferenceElement(element: KSReferenceElement, data: Unit) {}
override fun visitTypeAlias(typeAlias: KSTypeAlias, data: Unit) {}
override fun visitTypeArgument(typeArgument: KSTypeArgument, data: Unit) {}
override fun visitTypeParameter(typeParameter: KSTypeParameter, data: Unit) {}
override fun visitTypeReference(typeReference: KSTypeReference, data: Unit) {}
override fun visitValueArgument(valueArgument: KSValueArgument, data: Unit) {}
}
}
class BuilderProcessorProvider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
return BuilderProcessor(environment.codeGenerator, environment.logger)
}
}
| 97 | null | 9 | 94 | 3d8f2e9f5e39ff32476e6d3ee3e576e9e612b339 | 56,009 | automotive-design-compose | Apache License 2.0 |
hazelnet-community/src/main/kotlin/io/hazelnet/community/controllers/DiscordGiveawayController.kt | nilscodes | 446,203,879 | false | {"TypeScript": 1045486, "Kotlin": 810416, "Dockerfile": 4476, "Shell": 1830, "JavaScript": 1384} | package io.hazelnet.community.controllers
import io.hazelnet.community.data.discord.giveaways.DiscordGiveaway
import io.hazelnet.community.data.discord.giveaways.DiscordGiveawayPartial
import io.hazelnet.community.services.DiscordGiveawayService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.support.ServletUriComponentsBuilder
import javax.validation.Valid
@RestController
@RequestMapping("/discord")
class DiscordGiveawayController(
private val discordGiveawayService: DiscordGiveawayService
) {
@GetMapping("/servers/{guildId}/giveaways")
@ResponseStatus(HttpStatus.OK)
fun listGiveaways(@PathVariable guildId: Long) = discordGiveawayService.listGiveaways(guildId)
@PostMapping("/servers/{guildId}/giveaways")
@ResponseStatus(HttpStatus.CREATED)
fun addGiveaway(@PathVariable guildId: Long, @RequestBody @Valid discordGiveaway: DiscordGiveaway): ResponseEntity<DiscordGiveaway> {
val newGiveaway = discordGiveawayService.addGiveaway(guildId, discordGiveaway)
return ResponseEntity
.created(
ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{giveawayId}")
.buildAndExpand(newGiveaway.id)
.toUri())
.body(newGiveaway)
}
@GetMapping("/servers/{guildId}/giveaways/{giveawayId}")
@ResponseStatus(HttpStatus.OK)
fun getGiveaway(@PathVariable guildId: Long, @PathVariable giveawayId: Int) = discordGiveawayService.getGiveaway(guildId, giveawayId)
@PatchMapping("/servers/{guildId}/giveaways/{giveawayId}")
@ResponseStatus(HttpStatus.OK)
fun updateGiveaway(@PathVariable guildId: Long, @PathVariable giveawayId: Int, @RequestBody @Valid discordGiveawayPartial: DiscordGiveawayPartial) = discordGiveawayService.updateGiveaway(guildId, giveawayId, discordGiveawayPartial)
@DeleteMapping("/servers/{guildId}/giveaways/{giveawayId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun deleteGiveaway(@PathVariable guildId: Long, @PathVariable giveawayId: Int) = discordGiveawayService.deleteGiveaway(guildId, giveawayId)
@GetMapping("/servers/{guildId}/giveaways/{giveawayId}/participation")
@ResponseStatus(HttpStatus.OK)
fun getParticipationForGiveaway(@PathVariable guildId: Long, @PathVariable giveawayId: Int) = discordGiveawayService.getParticipationForGiveaway(guildId, giveawayId)
@GetMapping("/servers/{guildId}/giveaways/{giveawayId}/participation/{externalAccountId}")
@ResponseStatus(HttpStatus.OK)
fun getParticipationOfUser(@PathVariable guildId: Long, @PathVariable giveawayId: Int, @PathVariable externalAccountId: Long) = discordGiveawayService.getParticipationOfUser(guildId, giveawayId, externalAccountId)
@PutMapping("/servers/{guildId}/giveaways/{giveawayId}/participation/{externalAccountId}")
@ResponseStatus(HttpStatus.OK)
fun participateAsUser(@PathVariable guildId: Long, @PathVariable giveawayId: Int, @PathVariable externalAccountId: Long) = discordGiveawayService.participateAsUser(guildId, giveawayId, externalAccountId)
@DeleteMapping("/servers/{guildId}/giveaways/{giveawayId}/participation/{externalAccountId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun removeParticipationAsUser(@PathVariable guildId: Long, @PathVariable giveawayId: Int, @PathVariable externalAccountId: Long) = discordGiveawayService.removeParticipationAsUser(guildId, giveawayId, externalAccountId)
@PostMapping("/servers/{guildId}/giveaways/{giveawayId}/winners")
@ResponseStatus(HttpStatus.OK)
fun drawWinners(@PathVariable guildId: Long, @PathVariable giveawayId: Int) = discordGiveawayService.drawWinners(guildId, giveawayId)
@GetMapping("/servers/{guildId}/giveaways/{giveawayId}/winners")
@ResponseStatus(HttpStatus.OK)
fun getWinnerList(@PathVariable guildId: Long, @PathVariable giveawayId: Int) = discordGiveawayService.getWinnerList(guildId, giveawayId)
@GetMapping("/servers/{guildId}/giveaways/{giveawayId}/tokenmetadata")
@ResponseStatus(HttpStatus.OK)
fun getTokenRegistryMetadataForGiveaway(@PathVariable guildId: Long, @PathVariable giveawayId: Int) = discordGiveawayService.getTokenRegistryMetadataForGiveaway(guildId, giveawayId)
@GetMapping("/giveaways/announcements")
@ResponseStatus(HttpStatus.OK)
fun listGiveawaysToBeAnnounced() = discordGiveawayService.listGiveawaysToBeAnnounced()
@GetMapping("/giveaways/resultupdates")
@ResponseStatus(HttpStatus.OK)
fun listGiveawayResultUpdates() = discordGiveawayService.listGiveawayResultUpdates()
} | 0 | TypeScript | 4 | 13 | 79f8b096f599255acb03cc809464d0570a51d82c | 4,687 | hazelnet | Apache License 2.0 |
app/src/main/java/com/vitorpamplona/amethyst/ui/components/UrlPreviewCard.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.ui.components
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
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.layout.ContentScale
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.vitorpamplona.amethyst.R
import com.vitorpamplona.amethyst.service.previews.UrlInfoItem
@Composable
fun UrlPreviewCard(
url: String,
previewInfo: UrlInfoItem
) {
val uri = LocalUriHandler.current
Row(
modifier = Modifier
.clickable { runCatching { uri.openUri(url) } }
.clip(shape = RoundedCornerShape(15.dp))
.border(
1.dp,
MaterialTheme.colors.onSurface.copy(alpha = 0.12f),
RoundedCornerShape(15.dp)
)
) {
Column {
AsyncImage(
model = previewInfo.imageUrlFullPath,
contentDescription = stringResource(R.string.preview_card_image_for, previewInfo.url),
contentScale = ContentScale.FillWidth,
modifier = Modifier.fillMaxWidth()
)
Text(
text = previewInfo.verifiedUrl?.host ?: previewInfo.url,
style = MaterialTheme.typography.caption,
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, end = 10.dp, top = 10.dp),
color = Color.Gray,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Text(
text = previewInfo.title,
style = MaterialTheme.typography.body2,
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, end = 10.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Text(
text = previewInfo.description,
style = MaterialTheme.typography.caption,
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, end = 10.dp, bottom = 10.dp),
color = Color.Gray,
maxLines = 3,
overflow = TextOverflow.Ellipsis
)
}
}
}
| 63 | null | 40 | 795 | 53a5d3e88e10bc5d5d181430ae7a82fb8ce56278 | 2,946 | amethyst | MIT License |
compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/nullabilitySmartcastWhenNullability.kt | JakeWharton | 99,388,807 | false | null | // !LANGUAGE: +AllowContractsForCustomFunctions +UseReturnsEffect
// !OPT_IN: kotlin.contracts.ExperimentalContracts
// !DIAGNOSTICS: -INVISIBLE_REFERENCE -INVISIBLE_MEMBER
import kotlin.contracts.*
fun nullWhenNull(x: Int?): Int? {
contract {
returnsNotNull() implies (x != null)
}
return x?.inc()
}
fun testNullWhenNull(x: Int?) {
if (nullWhenNull(x) == null) {
x<!UNSAFE_CALL!>.<!>dec()
}
else {
<!DEBUG_INFO_SMARTCAST!>x<!>.dec()
}
if (nullWhenNull(x) != null) {
<!DEBUG_INFO_SMARTCAST!>x<!>.dec()
}
else {
x<!UNSAFE_CALL!>.<!>dec()
}
x<!UNSAFE_CALL!>.<!>dec()
}
// NB. it is the same function as `nullWhenNull`, but annotations specifies other facet of the function behaviour
fun notNullWhenNotNull (x: Int?): Int? {
contract {
returns(null) implies (x == null)
}
return x?.inc()
}
fun testNotNullWhenNotNull (x: Int?) {
if (notNullWhenNotNull(x) == null) {
<!SENSELESS_COMPARISON!><!DEBUG_INFO_CONSTANT!>x<!> == null<!>
}
else {
x<!UNSAFE_CALL!>.<!>dec()
}
if (notNullWhenNotNull(x) != null) {
x<!UNSAFE_CALL!>.<!>dec()
}
else {
<!SENSELESS_COMPARISON!><!DEBUG_INFO_CONSTANT!>x<!> == null<!>
}
x<!UNSAFE_CALL!>.<!>dec()
}
| 34 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,313 | kotlin | Apache License 2.0 |
app/src/main/kotlin/io/element/android/x/initializer/TracingInitializer.kt | element-hq | 546,522,002 | false | {"Kotlin": 8692554, "Python": 57175, "Shell": 39911, "JavaScript": 20399, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44} | /*
* Copyright (c) 2022 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.x.initializer
import android.content.Context
import android.system.Os
import androidx.preference.PreferenceManager
import androidx.startup.Initializer
import io.element.android.features.preferences.impl.developer.tracing.SharedPrefTracingConfigurationStore
import io.element.android.features.preferences.impl.developer.tracing.TargetLogLevelMapBuilder
import io.element.android.libraries.architecture.bindings
import io.element.android.libraries.matrix.api.tracing.TracingConfiguration
import io.element.android.libraries.matrix.api.tracing.TracingFilterConfigurations
import io.element.android.libraries.matrix.api.tracing.WriteToFilesConfiguration
import io.element.android.x.BuildConfig
import io.element.android.x.di.AppBindings
import timber.log.Timber
class TracingInitializer : Initializer<Unit> {
override fun create(context: Context) {
val appBindings = context.bindings<AppBindings>()
val tracingService = appBindings.tracingService()
val bugReporter = appBindings.bugReporter()
Timber.plant(tracingService.createTimberTree())
val tracingConfiguration = if (BuildConfig.DEBUG) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val store = SharedPrefTracingConfigurationStore(prefs)
val builder = TargetLogLevelMapBuilder(store)
TracingConfiguration(
filterConfiguration = TracingFilterConfigurations.custom(builder.getCurrentMap()),
writesToLogcat = true,
writesToFilesConfiguration = WriteToFilesConfiguration.Disabled
)
} else {
val config = if (BuildConfig.BUILD_TYPE == "nightly") {
TracingFilterConfigurations.nightly
} else {
TracingFilterConfigurations.release
}
TracingConfiguration(
filterConfiguration = config,
writesToLogcat = false,
writesToFilesConfiguration = WriteToFilesConfiguration.Enabled(
directory = bugReporter.logDirectory().absolutePath,
filenamePrefix = "logs",
filenameSuffix = null,
// Keep a minimum of 1 week of log files.
numberOfFiles = 7 * 24,
)
)
}
bugReporter.setCurrentTracingFilter(tracingConfiguration.filterConfiguration.filter)
tracingService.setupTracing(tracingConfiguration)
// Also set env variable for rust back trace
Os.setenv("RUST_BACKTRACE", "1", true)
}
override fun dependencies(): List<Class<out Initializer<*>>> = mutableListOf()
}
| 263 | Kotlin | 67 | 955 | 31d0621fa15fe153bfd36104e560c9703eabe917 | 3,311 | element-x-android | Apache License 2.0 |
app/src/main/java/com/hulkrent/app/ui/profile/about/why_Host/SlidingImageAdapter.kt | Hulk-Cars | 772,120,218 | false | {"Kotlin": 2511410, "Java": 358761} | package com.hulkrent.app.ui.profile.about.why_Host
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import com.hulkrent.app.Constants
import com.hulkrent.app.R
import com.hulkrent.app.util.GlideApp
class SlidingImageAdapter(
private val context: Context,
private val imageModelArrayList: ArrayList<ImageModel>
) : PagerAdapter() {
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
override fun getCount(): Int {
return imageModelArrayList.size
}
override fun instantiateItem(view: ViewGroup, position: Int): Any {
val imageLayout =
LayoutInflater.from(context).inflate(R.layout.sliding_images, view, false)!!
val imageView = imageLayout.findViewById(R.id.image) as ImageView
val textView = imageLayout.findViewById(R.id.sliding_texts) as TextView
val buttonView = imageLayout.findViewById(R.id.button_text) as TextView
textView.setText(imageModelArrayList[position].getText_srings())
buttonView.setText(imageModelArrayList[position].getButton_srings())
GlideApp.with(imageView.context)
.load(Constants.imgWhyHost + imageModelArrayList[position].getImage_drawables())
.into(imageView)
view.addView(imageLayout, 0)
return imageLayout
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
} | 0 | Kotlin | 0 | 0 | 9886a3455e3d404110a85cdaaf5bbff449390814 | 1,659 | Hulk-Rent-Android | Artistic License 1.0 w/clause 8 |
src/main/kotlin/swyg/hollang/entity/TestResponse.kt | MOKY4 | 645,608,258 | false | null | package swyg.hollang.entity
import jakarta.persistence.*
import jakarta.persistence.CascadeType.ALL
import jakarta.persistence.FetchType.LAZY
import swyg.hollang.entity.common.BaseTimeEntity
@Entity
class TestResponse private constructor(
@OneToOne(fetch = LAZY, cascade = [ALL], orphanRemoval = true)
@JoinColumn(name = "user_id", nullable = false, updatable = false)
val user: User
) : BaseTimeEntity() {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "test_response_id")
val id: Long? = null
@OneToMany(mappedBy = "testResponse", cascade = [ALL], orphanRemoval = true)
var testResponseDetails: MutableList<TestResponseDetail> = mutableListOf()
@OneToOne(mappedBy = "testResponse", cascade = [ALL], orphanRemoval = true)
var recommendation: Recommendation? = null
protected set(value) {
field = value!!
value.testResponse = this
value.user = this.user
}
constructor(user: User, testResponseDetails: List<TestResponseDetail>, recommendation: Recommendation)
: this(user) {
this.testResponseDetails.addAll(testResponseDetails)
testResponseDetails.forEach { testResponseDetail ->
testResponseDetail.testResponse = this
}
this.recommendation = recommendation
}
}
| 0 | Kotlin | 0 | 0 | 26962b5afda62540e9177fe8a7194074fcec3093 | 1,349 | hollang-weeks52-api-server | MIT License |
plugins/kotlin/code-insight/inspections-shared/src/org/jetbrains/kotlin/idea/codeInsight/inspections/shared/collections/AbstractUselessCallInspection.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.inspections.shared.collections
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.analysis.api.KaSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.resolution.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.resolution.symbol
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.EmptinessCheckFunctionUtils
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtExpressionWithLabel
import org.jetbrains.kotlin.psi.KtLabeledExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtTreeVisitor
import org.jetbrains.kotlin.psi.KtVisitorVoid
abstract class AbstractUselessCallInspection : AbstractKotlinInspection() {
protected abstract val uselessFqNames: Map<CallableId, Conversion>
protected abstract val uselessNames: Set<String>
context(KaSession)
protected abstract fun QualifiedExpressionVisitor.suggestConversionIfNeeded(
expression: KtQualifiedExpression,
calleeExpression: KtExpression,
conversion: Conversion
)
abstract class ScopedLabelVisitor(private val label: String) : KtTreeVisitor<Unit>() {
private fun String.trimLabel() = trim('@').trim()
override fun visitLabeledExpression(expression: KtLabeledExpression, data: Unit?): Void? {
// The label has been overwritten, do not descend into children
if (expression.getLabelName() == label) return null
return super.visitLabeledExpression(expression, data)
}
override fun visitCallExpression(expression: KtCallExpression, data: Unit?): Void? {
// The label has been overwritten, do not descend into children
if (expression.calleeExpression?.text?.trimLabel() == label) return null
return super.visitCallExpression(expression, data)
}
}
inner class QualifiedExpressionVisitor internal constructor(val holder: ProblemsHolder, val isOnTheFly: Boolean) : KtVisitorVoid() {
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
super.visitQualifiedExpression(expression)
val selector = expression.selectorExpression as? KtCallExpression ?: return
val calleeExpression = selector.calleeExpression ?: return
if (calleeExpression.text !in uselessNames) return
analyze(calleeExpression) {
val resolvedCall = calleeExpression.resolveCallOld()?.singleFunctionCallOrNull() ?: return
val callableId = resolvedCall.symbol.callableId ?: return
val conversion = uselessFqNames[callableId] ?: return
suggestConversionIfNeeded(expression, calleeExpression, conversion)
}
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = QualifiedExpressionVisitor(holder, isOnTheFly)
protected fun KtExpression.isUsingLabelInScope(labelName: String): Boolean {
var usingLabel = false
accept(object : KtTreeVisitor<Unit>() {
override fun visitExpressionWithLabel(expression: KtExpressionWithLabel, data: Unit?): Void? {
if (expression.getLabelName() == labelName) {
usingLabel = true
}
return super.visitExpressionWithLabel(expression, data)
}
})
return usingLabel
}
protected sealed interface Conversion {
data class Replace(val replacementName: String) : Conversion
object Delete : Conversion
}
protected companion object {
fun topLevelCallableId(packagePath: String, functionName: String): CallableId {
return CallableId(FqName.topLevel(Name.identifier(packagePath)), Name.identifier(functionName))
}
fun Set<CallableId>.toShortNames() = mapTo(mutableSetOf()) { it.callableName.asString() }
context(KaSession)
fun KtQualifiedExpression.invertSelectorFunction(): KtQualifiedExpression? {
return EmptinessCheckFunctionUtils.invertFunctionCall(this) as? KtQualifiedExpression
}
}
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 4,621 | intellij-community | Apache License 2.0 |
combustion-android-ble/src/main/java/inc/combustion/framework/service/ProbeID.kt | combustion-inc | 463,664,807 | false | {"Kotlin": 607897} | /*
* Project: Combustion Inc. Android Framework
* File: ProbeID.kt
* Author: https://github.com/miwright2
*
* MIT License
*
* Copyright (c) 2022. Combustion Inc.
*
* 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 inc.combustion.framework.service
import inc.combustion.framework.ble.shl
import inc.combustion.framework.ble.shr
enum class ProbeID(val type: UByte) {
ID1(0x00u),
ID2(0x01u),
ID3(0x02u),
ID4(0x03u),
ID5(0x04u),
ID6(0x05u),
ID7(0x06u),
ID8(0x07u);
companion object {
private const val PROBE_ID_MASK = 0x07
private const val PROBE_ID_SHIFT = 5
fun fromUByte(byte: UByte) : ProbeID {
val rawProbeID = ((byte.toUShort() and (PROBE_ID_MASK.toUShort() shl PROBE_ID_SHIFT)) shr PROBE_ID_SHIFT).toUInt()
return fromRaw(rawProbeID)
}
fun fromRaw(raw: UInt) : ProbeID {
return when(raw) {
0x00u -> ID1
0x01u -> ID2
0x02u -> ID3
0x03u -> ID4
0x04u -> ID5
0x05u -> ID6
0x06u -> ID7
0x07u -> ID8
else -> ID1
}
}
fun stringValues() : List<String> {
return values().toList().map { it.toString() }
}
}
}
| 0 | Kotlin | 0 | 4 | 7b30d50974076c4f8355b5a8acd6f52d7c98f0f2 | 2,358 | combustion-android-ble | MIT License |
app/src/main/java/com/bruno13palhano/shopdanimanagement/ui/screens/catalog/CatalogScreen.kt | bruno13palhano | 670,001,130 | false | {"Kotlin": 1278676} | package com.bruno13palhano.shopdanimanagement.ui.screens.catalog
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.bruno13palhano.shopdanimanagement.R
import com.bruno13palhano.shopdanimanagement.ui.components.CatalogItemList
import com.bruno13palhano.shopdanimanagement.ui.components.MoreOptionsMenu
import com.bruno13palhano.shopdanimanagement.ui.screens.catalog.viewmodel.CatalogViewModel
import com.bruno13palhano.shopdanimanagement.ui.screens.common.ExtendedItem
import com.bruno13palhano.shopdanimanagement.ui.theme.ShopDaniManagementTheme
@Composable
fun CatalogScreen(
onItemClick: (id: Long) -> Unit,
navigateUp: () -> Unit,
viewModel: CatalogViewModel = hiltViewModel()
) {
LaunchedEffect(key1 = Unit) {
viewModel.getAll()
}
val catalogItems by viewModel.catalogItems.collectAsStateWithLifecycle()
val menuOptions = arrayOf(
stringResource(id = R.string.ordered_by_name_label),
stringResource(id = R.string.ordered_by_price_label),
stringResource(id = R.string.ordered_by_last_label)
)
var orderedByName by remember { mutableStateOf(false) }
var orderedByPrice by remember { mutableStateOf(false) }
CatalogContent(
catalogItems = catalogItems,
menuOptions = menuOptions,
onItemClick = onItemClick,
onMoreOptionsItemClick = { index ->
when (index) {
0 -> {
viewModel.getOrderedByName(isOrderedAsc = orderedByName)
orderedByName = toggleOrdered(orderedByName)
}
1 -> {
viewModel.getOrderedByPrice(isOrderedAsc = orderedByPrice)
orderedByPrice = toggleOrdered(orderedByPrice)
}
else -> { viewModel.getAll() }
}
},
navigateUp = navigateUp
)
}
private fun toggleOrdered(ordered: Boolean) = !ordered
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CatalogContent(
catalogItems: List<ExtendedItem>,
menuOptions: Array<String>,
onItemClick: (id: Long) -> Unit,
onMoreOptionsItemClick: (index: Int) -> Unit,
navigateUp: () -> Unit
) {
var expanded by remember { mutableStateOf(false) }
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = stringResource(id = R.string.catalog_label)) },
navigationIcon = {
IconButton(onClick = navigateUp) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.up_button_label)
)
}
},
actions = {
IconButton(onClick = { expanded = true }) {
Icon(
imageVector = Icons.Filled.MoreVert,
contentDescription = stringResource(id = R.string.more_options_label)
)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
MoreOptionsMenu(
items = menuOptions,
expanded = expanded,
onDismissRequest = { expandedValue -> expanded = expandedValue },
onClick = onMoreOptionsItemClick
)
}
}
}
)
}
) {
LazyVerticalStaggeredGrid(
modifier = Modifier
.semantics { contentDescription = "List of items" }
.padding(it),
columns = StaggeredGridCells.Adaptive(144.dp),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp)
) {
items(items = catalogItems, key = { item -> item.id }) { item ->
CatalogItemList(
modifier = Modifier.padding(8.dp),
photo = item.photo,
title = item.title,
firstSubtitle = item.firstSubtitle,
secondSubtitle = stringResource(
id = R.string.price_text_tag, item.secondSubtitle
),
description = item.description,
footer = stringResource(id = R.string.discount_tag, item.footer),
onClick = { onItemClick(item.id) }
)
}
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Preview(uiMode = UI_MODE_NIGHT_YES, showSystemUi = true)
@Composable
fun CatalogDynamicPreview() {
ShopDaniManagementTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
CatalogContent(
catalogItems = fakeCatalogItems,
menuOptions = arrayOf(),
onItemClick = {},
onMoreOptionsItemClick = {},
navigateUp = {}
)
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Preview(uiMode = UI_MODE_NIGHT_YES, showSystemUi = true)
@Composable
fun CatalogPreview() {
ShopDaniManagementTheme(
dynamicColor = false
) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
CatalogContent(
catalogItems = fakeCatalogItems,
menuOptions = arrayOf(),
onItemClick = {},
onMoreOptionsItemClick = {},
navigateUp = {}
)
}
}
}
private val fakeCatalogItems = listOf(
ExtendedItem(1L, byteArrayOf(), "Homem Del Parfum", "High quality", "98.99", "The most sale Parfum", "10"),
ExtendedItem(2L, byteArrayOf(), "Essencial", "High quality", "154.90", "Top 10 requested", "25"),
ExtendedItem(3L, byteArrayOf(), "Kaiak", "High quality", "122.44", "Top 10 requested", "5"),
ExtendedItem(4L, byteArrayOf(), "Luna", "High quality", "100.99", "Light fragrance", "5"),
ExtendedItem(5L, byteArrayOf(), "Una", "High quality", "88.99", "Light fragrance", "20"),
ExtendedItem(6L, byteArrayOf(), "Homem", "High quality", "110.90", "New fragrance", "15"),
) | 0 | Kotlin | 0 | 2 | c55b8f8f9fccb42ce9b5a99a309e41bd2ec0b5b2 | 8,280 | shop-dani-management | MIT License |
hexagon_core/src/main/kotlin/ResourceNotFoundException.kt | ramyaravindranath | 369,034,896 | true | {"Kotlin": 598350, "HTML": 22972, "CSS": 1770, "JavaScript": 1420} | package com.hexagonkt
import java.io.IOException
class ResourceNotFoundException(message: String) : IOException(message)
| 0 | null | 0 | 1 | 15cab055df5bc100e5dd1b79e74f2c24b2a4ea7c | 123 | hexagon | MIT License |
src/main/kotlin/com/hypto/iam/server/Constants.kt | hwslabs | 455,187,437 | false | null | package com.hypto.iam.server
import com.hypto.iam.server.models.PaginationOptions
class Constants private constructor() {
// Validation constants
companion object {
const val MIN_LENGTH = 2
const val MIN_USERNAME_LENGTH = 8
const val MIN_EMAIL_LENGTH = 4
const val MAX_NAME_LENGTH = 50
const val MAX_USERNAME_LENGTH = 50
const val MIN_DESC_LENGTH = 2
const val MAX_DESC_LENGTH = 100
const val MIN_POLICY_STATEMENTS = 1
const val MAX_POLICY_STATEMENTS = 50
const val MAX_POLICY_ASSOCIATIONS_PER_REQUEST = 20
const val MINIMUM_PHONE_NUMBER_LENGTH = 8
const val MINIMUM_PASSWORD_LENGTH = 8
const val PAGINATION_MAX_PAGE_SIZE = 50
const val PAGINATION_DEFAULT_PAGE_SIZE = 50
val PAGINATION_DEFAULT_SORT_ORDER = PaginationOptions.SortOrder.asc
const val NEWRELIC_METRICS_PUBLISH_INTERVAL = 30L // seconds
const val X_ORGANIZATION_HEADER = "X-Iam-User-Organization"
const val X_API_KEY_HEADER = "X-Api-Key"
const val AUTHORIZATION_HEADER = "Authorization"
const val SECRET_PREFIX = "$"
const val JOOQ_QUERY_NAME = "queryName"
const val SECONDS_IN_DAY = 24 * 60 * 60L
}
}
| 20 | null | 3 | 15 | b06cdd32d7b4080f887887bcc881bf38938de8eb | 1,256 | iam | MIT License |
test-suite-kotlin-ksp/src/test/kotlin/io/micronaut/jackson/JacksonNullableTest.kt | micronaut-projects | 124,230,204 | false | {"Java": 13018207, "Groovy": 7010109, "Kotlin": 1674872, "HTML": 143, "Shell": 14} | package io.micronaut.jackson
import com.fasterxml.jackson.databind.ObjectMapper
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
@MicronautTest
class JacksonNullableTest {
@Test
fun testDefaultValue(objectMapper: ObjectMapper) {
val result = objectMapper.writeValueAsString(NullConstructorDto())
val bean = objectMapper.readValue(result, NullConstructorDto::class.java)
Assertions.assertEquals(null, bean.longField)
}
@Test
fun testNonNullValue(objectMapper: ObjectMapper) {
val bean = objectMapper.readValue("{}", NonNullConstructorDto::class.java)
Assertions.assertEquals(0, bean.longField)
}
@Test
fun testNonNullValue2(objectMapper: ObjectMapper) {
val bean = objectMapper.readValue("{\"longField\":null}", NonNullConstructorDto::class.java)
Assertions.assertEquals(0, bean.longField)
}
@Test
fun testNullPropertyValue(objectMapper: ObjectMapper) {
val bean = objectMapper.readValue("{}", NullPropertyDto::class.java)
Assertions.assertEquals(null, bean.longField)
}
}
| 753 | Java | 1061 | 6,059 | c9144646b31b23bd3c4150dec8ddd519947e55cf | 1,192 | micronaut-core | Apache License 2.0 |
src/macosMain/kotlin/com/jetbrains/handson/handson/init/FileIO.kt | kotlin-hands-on | 254,169,194 | false | null | package com.jetbrains.handson.handson.init
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.toKString
import platform.posix.*
class FileIO() {
fun readFile(filename: String): String {
val file = fopen(filename, "r")
?: throw FileIOException(errno)
var contents = ""
try {
memScoped {
val bufferLength = 64 * 1024
val buffer = allocArray<ByteVar>(bufferLength)
var nextLine = fgets(buffer, bufferLength, file)?.toKString()
while (nextLine != null) {
contents += nextLine
nextLine = fgets(buffer, bufferLength, file)?.toKString()
}
}
} finally{
fclose(file)
}
return contents
}
fun createFolder(folderName: String) {
val result = mkdir(folderName, S_IRWXU)
if (result != 0 && result != -1) {
throw FileIOException(errno)
}
}
fun createFile(fileName: String, contents: String) {
val file = fopen(fileName, "w") ?: throw FileIOException(errno)
try {
fprintf(file, contents)
} finally {
fclose(file)
}
}
} | 1 | Kotlin | 2 | 9 | b3efa02c8a98d5fc6fe2f450b76d6f79e18b355a | 1,313 | hands-on-init | Apache License 2.0 |
platforms/hermes-kotlin/hermes-kotlin-test/src/test/kotlin/FfiTest.kt | elbywan | 209,998,549 | true | {"Rust": 368079, "Python": 216780, "Kotlin": 96118, "TypeScript": 86389, "C": 78170, "JavaScript": 20296, "Shell": 7261} | import ai.snips.hermes.AsrDecodingDuration
import ai.snips.hermes.AsrToken
import ai.snips.hermes.AsrTokenRange
import ai.snips.hermes.ContinueSessionMessage
import ai.snips.hermes.DialogueConfigureIntent
import ai.snips.hermes.DialogueConfigureMessage
import ai.snips.hermes.EndSessionMessage
import ai.snips.hermes.HermesComponent
import ai.snips.hermes.InjectionCompleteMessage
import ai.snips.hermes.InjectionKind.Add
import ai.snips.hermes.InjectionOperation
import ai.snips.hermes.InjectionRequestMessage
import ai.snips.hermes.InjectionResetCompleteMessage
import ai.snips.hermes.InjectionResetRequestMessage
import ai.snips.hermes.IntentAlternative
import ai.snips.hermes.IntentClassifierResult
import ai.snips.hermes.IntentMessage
import ai.snips.hermes.IntentNotRecognizedMessage
import ai.snips.hermes.SessionEndedMessage
import ai.snips.hermes.SessionInit
import ai.snips.hermes.SessionQueuedMessage
import ai.snips.hermes.SessionTermination
import ai.snips.hermes.StartSessionMessage
import ai.snips.hermes.TextCapturedMessage
import ai.snips.hermes.test.HermesTest
import ai.snips.nlu.ontology.Range
import ai.snips.nlu.ontology.Slot
import ai.snips.nlu.ontology.SlotValue
import ai.snips.nlu.ontology.SlotValue.CityValue
import ai.snips.nlu.ontology.SlotValue.MusicAlbumValue
import ai.snips.nlu.ontology.SlotValue.MusicArtistValue
import ai.snips.nlu.ontology.SlotValue.MusicTrackValue
import ai.snips.nlu.ontology.SlotValue.NumberValue
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class FfiTest {
@Test
fun roundTripSessionQueued() {
val input = SessionQueuedMessage(sessionId = "some session id",
siteId = "some site id",
customData = "some custom data")
assertThat(HermesTest().roundTripSessionQueuedJson(input)).isEqualTo(input)
}
@Test
fun roundTripStartSessionAction() {
val input = StartSessionMessage(
init = SessionInit.Action(
text = "smdlfk",
intentFilter = listOf("an intent filter", "another intent filter"),
canBeEnqueued = true,
sendIntentNotRecognized = true
),
customData = "yo",
siteId = "qlmskdfj"
)
assertThat(HermesTest().roundTripStartSession(input)).isEqualTo(input)
assertThat(HermesTest().roundTripStartSessionJson(input)).isEqualTo(input)
}
@Test
fun roundTripStartSessionNotification() {
val input = StartSessionMessage(
init = SessionInit.Notification(
text = "smdlfk"
),
customData = "yo",
siteId = "qlmskdfj"
)
assertThat(HermesTest().roundTripStartSession(input)).isEqualTo(input)
assertThat(HermesTest().roundTripStartSessionJson(input)).isEqualTo(input)
}
@Test
fun roundTripContinueSession() {
val input = ContinueSessionMessage(
text = "smdlfk",
intentFilter = listOf("an intent filter", "another intent filter"),
sessionId = "qsmd3711EAED",
sendIntentNotRecognized = true,
customData = "this is a test custom data",
slot = "some slot"
)
assertThat(HermesTest().roundTripContinueSession(input)).isEqualTo(input)
assertThat(HermesTest().roundTripContinueSessionJson(input)).isEqualTo(input)
}
@Test
fun roundTripEndSession() {
val input = EndSessionMessage(
text = "smdlfk",
sessionId = "qsmd3711EAED"
)
assertThat(HermesTest().roundTripEndSession(input)).isEqualTo(input)
assertThat(HermesTest().roundTripEndSessionJson(input)).isEqualTo(input)
}
@Test
fun roundIntentNotRecognized() {
val input = IntentNotRecognizedMessage(
input = "smdlfk",
sessionId = "qsmd3711EAED",
siteId = "msdklfj",
customData = "fslksk",
confidenceScore = 0.5f,
alternatives = listOf(IntentAlternative(intentName = "toqsfqs",
confidenceScore = 0.1234f,
slots = listOf()),
IntentAlternative(intentName = null, confidenceScore = 0.14f, slots = listOf()))
)
assertThat(HermesTest().roundTripIntentNotRecognized(input)).isEqualTo(input)
assertThat(HermesTest().roundTripIntentNotRecognizedJson(input)).isEqualTo(input)
val input2 = IntentNotRecognizedMessage(
input = null,
sessionId = "qsmd3711EAED",
siteId = "msdklfj",
customData = null,
confidenceScore = 0.5f,
alternatives = listOf()
)
assertThat(HermesTest().roundTripIntentNotRecognized(input2)).isEqualTo(input2)
assertThat(HermesTest().roundTripIntentNotRecognizedJson(input2)).isEqualTo(input2)
val input3 = IntentNotRecognizedMessage(
input = "smdlfk",
sessionId = "qsmd3711EAED",
siteId = "msdklfj",
customData = "fslksk",
confidenceScore = 0.5f,
alternatives = listOf(IntentAlternative(intentName = "toqsfqs",
confidenceScore = 0.1234f,
slots = listOf(Slot(entity = "qmldkfj",
confidenceScore = 0.9f,
range = Range(0, 1),
rawValue = "msqkfld",
slotName = "qslfkj",
value = MusicAlbumValue(value = "qmslkfdj"),
alternatives = mutableListOf(MusicArtistValue(value = "mqsklfj"),
MusicTrackValue(value = "fsdqlkdflkqmj"))),
Slot(entity = "qsdf",
confidenceScore = 0.89f,
range = Range(10, 43),
rawValue = "aaaaa",
slotName = "bbbb",
value = CityValue(value = "qmslkfdj"), alternatives = mutableListOf())
)),
IntentAlternative(intentName = null, confidenceScore = 0.14f, slots = listOf()))
)
// we're still missing a converter for CSlot for this one
//assertThat(HermesTest().roundTripIntentNotRecognized(input3)).isEqualTo(input3)
assertThat(HermesTest().roundTripIntentNotRecognizedJson(input3)).isEqualTo(input3)
}
@Test
fun roundTripInjectionRequest() {
val input = InjectionRequestMessage(
operations = listOf(),
lexicon = mutableMapOf(),
crossLanguage = null,
id = null
)
assertThat(HermesTest().roundTripInjectionRequest(input)).isEqualTo(input)
assertThat(HermesTest().roundTripInjectionRequestJson(input)).isEqualTo(input)
val input2 = InjectionRequestMessage(
operations = listOf(InjectionOperation(Add, mutableMapOf("hello" to listOf("hello", "world"),
"yop" to listOf(),
"foo" to listOf("bar", "baz")))),
lexicon = mutableMapOf("toto" to listOf("tutu", "tata"),
"" to listOf(),
"pif" to listOf("paf", "pouf")),
crossLanguage = "en",
id = "123foo"
)
assertThat(HermesTest().roundTripInjectionRequest(input2)).isEqualTo(input2)
//json is a bit tricky to deserialize properly
//assertThat(HermesTest().roundTripInjectionRequestJson(input2)).isEqualTo(input2)
}
@Test
fun roundTripInjectionComplete() {
val input = InjectionCompleteMessage(
requestId = "foobar"
)
assertThat(HermesTest().roundTripInjectionComplete(input)).isEqualTo(input)
assertThat(HermesTest().roundTripInjectionCompleteJson(input)).isEqualTo(input)
}
@Test
fun roundTripInjectionResetRequest() {
val input = InjectionResetRequestMessage(
requestId = "foobar"
)
assertThat(HermesTest().roundTripInjectionResetRequest(input)).isEqualTo(input)
assertThat(HermesTest().roundTripInjectionResetRequestJson(input)).isEqualTo(input)
}
@Test
fun roundTripInjectionResetComplete() {
val input = InjectionResetCompleteMessage(
requestId = "foobar"
)
assertThat(HermesTest().roundTripInjectionResetComplete(input)).isEqualTo(input)
assertThat(HermesTest().roundTripInjectionResetCompleteJson(input)).isEqualTo(input)
}
@Test
fun roundTripSessionEnded() {
val input = SessionEndedMessage(
"some session id",
"some custom data",
SessionTermination.AbortedByUser,
"some site id"
)
assertThat(HermesTest().roundTripSessionEnded(input)).isEqualTo(input)
val input2 = SessionEndedMessage(
"some session id",
"some custom data",
SessionTermination.Error(error = "some error"),
"some site id"
)
assertThat(HermesTest().roundTripSessionEnded(input2)).isEqualTo(input2)
val input3 = SessionEndedMessage(
"some session id",
"some custom data",
SessionTermination.Timeout(component = HermesComponent.ClientApp),
"some site id"
)
assertThat(HermesTest().roundTripSessionEnded(input3)).isEqualTo(input3)
val input4 = SessionEndedMessage(
"some session id",
"some custom data",
SessionTermination.Timeout(component = null),
"some site id"
)
assertThat(HermesTest().roundTripSessionEnded(input4)).isEqualTo(input4)
val input5 = SessionEndedMessage(
"some session id",
"some custom data",
SessionTermination.IntenNotRecognized,
"some site id"
)
assertThat(HermesTest().roundTripSessionEnded(input5)).isEqualTo(input5)
}
@Test
fun roundTripMapStringToStringArray() {
val map = mapOf("toto" to listOf("tutu", "tata"),
"" to listOf(),
"pif" to listOf("paf", "pouf"))
assertThat(HermesTest().roundTripMapStringToStringArray(map)).isEqualTo(map)
}
@Test
fun roundTripAsrToken() {
val input = AsrToken(value = "toto",
time = AsrDecodingDuration(start = 1.2f, end = 4.4f),
range = AsrTokenRange(start = 5, end = 10),
confidence = 0.8f)
assertThat(HermesTest().roundTripAsrToken(input)).isEqualTo(input)
}
@Test
fun roundTripAsrTokenArray() {
val input = listOf(AsrToken(value = "toto",
time = AsrDecodingDuration(start = 1.2f, end = 4.4f),
range = AsrTokenRange(start = 5, end = 10),
confidence = 0.8f))
assertThat(HermesTest().roundTripAsrTokenArray(input)).isEqualTo(input)
assertThat(HermesTest().roundTripAsrTokenArray(listOf())).isEqualTo(listOf<AsrToken>())
}
@Test
fun roundTripAsrTokenDoubleArray() {
val input = listOf(listOf(AsrToken(value = "toto",
time = AsrDecodingDuration(start = 1.2f, end = 4.4f),
range = AsrTokenRange(start = 5, end = 10),
confidence = 0.8f)), listOf())
assertThat(HermesTest().roundTripAsrTokenDoubleArray(input)).isEqualTo(input)
assertThat(HermesTest().roundTripAsrTokenArray(listOf())).isEqualTo(listOf<List<AsrToken>>())
}
@Test
fun roundTripTextCaptured() {
val input = TextCapturedMessage(
text = "hello world",
sessionId = "a session id",
siteId = "a site id",
seconds = 3.2f,
likelihood = 0.95f,
tokens = listOf(AsrToken(value = "hello",
time = AsrDecodingDuration(start = 0.2f, end = 1.2f),
range = AsrTokenRange(start = 0, end = 6),
confidence = 0.8f),
AsrToken(value = "world",
time = AsrDecodingDuration(start = 1.2f, end = 3.2f),
range = AsrTokenRange(start = 6, end = 10),
confidence = 0.85f))
)
assertThat(HermesTest().roundTripTextCaptured(input)).isEqualTo(input)
assertThat(HermesTest().roundTripTextCapturedJson(input)).isEqualTo(input)
val input2 = TextCapturedMessage(
text = "hello world",
sessionId = null,
siteId = "a site id",
seconds = 3.2f,
likelihood = 0.95f,
tokens = listOf())
assertThat(HermesTest().roundTripTextCaptured(input2)).isEqualTo(input2)
assertThat(HermesTest().roundTripTextCapturedJson(input2)).isEqualTo(input2)
}
@Test
fun roundTripIntent() {
val input = IntentMessage(
customData = null,
siteId = "some site id",
sessionId = "some session id",
asrTokens = mutableListOf(),
asrConfidence = null,
input = "some input string",
intent = IntentClassifierResult(
intentName = "Some intent",
confidenceScore = 0.5f
),
slots = listOf(),
alternatives = listOf(IntentAlternative(intentName = "toqsfqs",
confidenceScore = 0.1234f,
slots = listOf()),
IntentAlternative(intentName = null, confidenceScore = 0.14f, slots = listOf()))
)
assertThat(HermesTest().roundTripIntent(input)).isEqualTo(input)
assertThat(HermesTest().roundTripIntentJson(input)).isEqualTo(input)
val input2 = IntentMessage(
customData = "some custom data",
siteId = "some site id",
sessionId = "some session id",
asrTokens = mutableListOf(listOf(AsrToken(value = "hello",
time = AsrDecodingDuration(start = 0.2f, end = 1.2f),
range = AsrTokenRange(start = 0, end = 6),
confidence = 0.8f),
AsrToken(value = "world",
time = AsrDecodingDuration(start = 1.2f, end = 3.2f),
range = AsrTokenRange(start = 6, end = 10),
confidence = 0.85f))),
asrConfidence = 0.83f,
input = "some input string",
intent = IntentClassifierResult(
intentName = "Some intent",
confidenceScore = 0.5f
),
slots = listOf(Slot(rawValue = "some value",
confidenceScore = 1.0f,
range = Range(start = 1, end = 8),
value = SlotValue.CustomValue("toto"),
entity = "some entity",
slotName = "some slot",
alternatives = mutableListOf(NumberValue(value = 3.1415),
MusicTrackValue(value = "fsdqlkdflkqmj"))
)),
alternatives = listOf(IntentAlternative(intentName = "toqsfqs",
confidenceScore = 0.1234f,
slots = listOf(Slot(entity = "qmldkfj",
confidenceScore = 0.9f,
range = Range(0, 1),
rawValue = "msqkfld",
slotName = "qslfkj",
value = MusicAlbumValue(value = "qmslkfdj"),
alternatives = mutableListOf(MusicArtistValue(value = "mqsklfj"),
MusicTrackValue(value = "fsdqlkdflkqmj"))),
Slot(entity = "qsdf",
confidenceScore = 0.89f,
range = Range(10, 43),
rawValue = "aaaaa",
slotName = "bbbb",
value = CityValue(value = "qmslkfdj"),
alternatives = mutableListOf())
)),
IntentAlternative(intentName = null, confidenceScore = 0.14f, slots = listOf()))
)
// we're still missing a few converters to do that (slot)
//assertThat(HermesTest().roundTripIntent(input2)).isEqualTo(input2)
assertThat(HermesTest().roundTripIntentJson(input2)).isEqualTo(input2)
}
@Test
fun roundTripIntentAlternative() {
val input = IntentAlternative(intentName = "toqsfqs",
confidenceScore = 0.1234f,
slots = listOf())
assertThat(HermesTest().roundTripIntentAlternative(input)).isEqualTo(input)
val input2 = IntentAlternative(intentName = null,
confidenceScore = 0.1234f,
slots = listOf())
assertThat(HermesTest().roundTripIntentAlternative(input2)).isEqualTo(input2)
}
@Test
fun roundTripIntentAlternatives() {
val input = listOf(IntentAlternative(intentName = "toqsfqs",
confidenceScore = 0.1234f,
slots = listOf(/* we're still missing a few converters to do that (slot)
Slot(entity = "qmldkfj",
confidenceScore = 0.9f,
range = Range(0,1),
rawValue = "msqkfld",
slotName = "qslfkj",
value = MusicAlbumValue(value = "qmslkfdj")),
Slot(entity = "qsdf",
confidenceScore = 0.89f,
range = Range(10,43),
rawValue = "aaaaa",
slotName = "bbbb",
value = CityValue(value = "qmslkfdj"))*/
)),
IntentAlternative(intentName = null, confidenceScore = 0.14f, slots = listOf()))
assertThat(HermesTest().roundTripIntentAlternativeArray(input)).isEqualTo(input)
}
@Test
fun roundTripDialogueConfigure() {
val input = DialogueConfigureMessage(siteId = null, intents = listOf())
assertThat(HermesTest().roundTripDialogueConfigure(input)).isEqualTo(input)
assertThat(HermesTest().roundTripDialogueConfigureJson(input)).isEqualTo(input)
val input2 = DialogueConfigureMessage(siteId = "some site id",
intents = listOf(DialogueConfigureIntent(intentId = "some intent",
enable = true),
DialogueConfigureIntent(intentId = "some intent",
enable = null),
DialogueConfigureIntent(intentId = "some intent",
enable = false)))
assertThat(HermesTest().roundTripDialogueConfigure(input2)).isEqualTo(input2)
assertThat(HermesTest().roundTripDialogueConfigureJson(input2)).isEqualTo(input2)
}
}
| 0 | null | 0 | 0 | da23326f026fbfb8a23413c78383301e523188f3 | 23,062 | hermes-protocol | Apache License 2.0 |
simplified-tests/src/test/java/org/nypl/simplified/tests/http/refresh_token/time_tracking/TimeTrackingRefreshTokenTest.kt | ThePalaceProject | 367,082,997 | false | {"Kotlin": 3317583, "JavaScript": 853788, "Java": 374503, "CSS": 65407, "HTML": 49220, "Shell": 5017, "Ruby": 178} | package org.nypl.simplified.tests.http.refresh_token.time_tracking
import android.content.Context
import com.fasterxml.jackson.databind.ObjectMapper
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.librarysimplified.http.api.LSHTTPClientConfiguration
import org.librarysimplified.http.api.LSHTTPClientType
import org.librarysimplified.http.api.LSHTTPRequestConstants
import org.librarysimplified.http.vanilla.LSHTTPClients
import org.mockito.Mockito
import org.nypl.drm.core.AdobeDeviceID
import org.nypl.drm.core.AdobeUserID
import org.nypl.drm.core.AdobeVendorID
import org.nypl.simplified.accounts.api.AccountAuthenticationAdobeClientToken
import org.nypl.simplified.accounts.api.AccountAuthenticationAdobePostActivationCredentials
import org.nypl.simplified.accounts.api.AccountAuthenticationAdobePreActivationCredentials
import org.nypl.simplified.accounts.api.AccountAuthenticationCredentials
import org.nypl.simplified.accounts.api.AccountAuthenticationTokenInfo
import org.nypl.simplified.accounts.api.AccountID
import org.nypl.simplified.accounts.api.AccountLoginState
import org.nypl.simplified.accounts.api.AccountPassword
import org.nypl.simplified.accounts.api.AccountUsername
import org.nypl.simplified.books.book_registry.BookRegistry
import org.nypl.simplified.books.book_registry.BookRegistryType
import org.nypl.simplified.books.time.tracking.TimeTrackingHTTPCalls
import org.nypl.simplified.books.time.tracking.TimeTrackingInfo
import org.nypl.simplified.books.time.tracking.TimeTrackingResponse
import org.nypl.simplified.books.time.tracking.TimeTrackingResponseEntry
import org.nypl.simplified.books.time.tracking.TimeTrackingResponseSummary
import org.nypl.simplified.crashlytics.api.CrashlyticsServiceType
import org.nypl.simplified.tests.mocking.MockAccount
import java.net.URI
import java.util.concurrent.TimeUnit
class TimeTrackingRefreshTokenTest {
private lateinit var account: MockAccount
private lateinit var accountID: AccountID
private lateinit var bookRegistry: BookRegistryType
private lateinit var httpClient: LSHTTPClientType
private lateinit var webServer: MockWebServer
private val crashlytics = Mockito.mock(CrashlyticsServiceType::class.java)
@BeforeEach
fun testSetup() {
this.accountID =
AccountID.generate()
this.account = MockAccount(this.accountID)
val credentials = AccountAuthenticationCredentials.BasicToken(
userName = AccountUsername("1234"),
password = AccountPassword("<PASSWORD>"),
authenticationTokenInfo = AccountAuthenticationTokenInfo(
accessToken = "abcd",
authURI = URI("https://www.authrefresh.com")
),
adobeCredentials = AccountAuthenticationAdobePreActivationCredentials(
vendorID = AdobeVendorID("vendor"),
clientToken = AccountAuthenticationAdobeClientToken(
userName = "user",
password = "<PASSWORD>",
rawToken = "<PASSWORD>"
),
deviceManagerURI = URI.create("http://www.example.com"),
postActivationCredentials = AccountAuthenticationAdobePostActivationCredentials(
deviceID = AdobeDeviceID("ca887d21-a56c-4314-811e-952d885d2115"),
userID = AdobeUserID("19b25c06-8b39-4643-8813-5980bee45651")
)
),
authenticationDescription = "BasicToken",
annotationsURI = URI("https://www.example.com"),
deviceRegistrationURI = URI("https://www.example.com")
)
this.account.setLoginState(AccountLoginState.AccountLoggedIn(credentials))
this.bookRegistry =
BookRegistry.create()
this.webServer = MockWebServer()
this.webServer.start(20000)
val androidContext =
Mockito.mock(Context::class.java)
this.httpClient =
LSHTTPClients()
.create(
context = androidContext,
configuration = LSHTTPClientConfiguration(
applicationName = "simplified-tests",
applicationVersion = "999.999.0",
tlsOverrides = null,
timeout = Pair(5L, TimeUnit.SECONDS)
)
)
}
@AfterEach
fun tearDown() {
this.webServer.close()
}
@Test
fun testSendEntriesUpdateToken() {
val timeTrackingInfo = Mockito.mock(TimeTrackingInfo::class.java)
Mockito.`when`(timeTrackingInfo.timeTrackingUri)
.thenReturn(this.webServer.url("/timeTracking").toUri())
val httpCalls = TimeTrackingHTTPCalls(
objectMapper = ObjectMapper(),
http = httpClient,
crashlytics = crashlytics
)
val responseBody = TimeTrackingResponse(
responses = listOf(
TimeTrackingResponseEntry(
id = "id",
message = "success",
status = 201
)
),
summary = TimeTrackingResponseSummary(
successes = 1,
failures = 0,
total = 1
)
)
this.webServer.enqueue(
MockResponse()
.setResponseCode(200)
.setHeader(LSHTTPRequestConstants.PROPERTY_KEY_ACCESS_TOKEN, "ghij")
.setBody(ObjectMapper().writeValueAsString(responseBody))
)
val failedEntries = httpCalls.registerTimeTrackingInfo(
timeTrackingInfo = timeTrackingInfo,
account = account
)
Assertions.assertTrue(failedEntries.isEmpty())
Assertions.assertEquals(
"ghij",
(account.loginState.credentials as AccountAuthenticationCredentials.BasicToken)
.authenticationTokenInfo.accessToken
)
}
}
| 1 | Kotlin | 4 | 8 | f68b6907367e2213f1dcde700ca5c91f2f515ada | 5,610 | android-core | Apache License 2.0 |
src/main/kotlin/com/github/jyc228/keth/client/ApiResult.kt | jyc228 | 833,953,853 | false | {"Kotlin": 217816, "Solidity": 5515} | package com.github.jyc228.keth.client
import com.github.jyc228.jsonrpc.JsonRpcError
import com.github.jyc228.jsonrpc.JsonRpcException
import com.github.jyc228.jsonrpc.JsonRpcRequest
import com.github.jyc228.jsonrpc.JsonRpcResponse
import kotlinx.coroutines.channels.Channel
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
suspend fun <T> List<ApiResult<T>>.awaitAllOrThrow(): List<T> = map { it.awaitOrThrow() }
fun <T> ApiResult(
response: JsonRpcResponse,
decode: (JsonElement) -> T
): ApiResult<T> {
if (response.error != null) {
return ApiResultFail(response.id, response.error)
}
if (response.result is JsonNull) return ApiResultSuccess(null as T)
return ApiResultSuccess(decode(response.result))
}
interface ApiResult<out T> {
suspend fun awaitOrNull(): T?
suspend fun awaitOrThrow(): T
fun <R> map(transform: (T) -> R): ApiResult<R>
fun onFailure(handleError: (Throwable) -> Unit): ApiResult<T>
companion object
}
internal data class ApiResultSuccess<T>(val data: T) : ApiResult<T> {
override suspend fun awaitOrNull(): T? = data
override suspend fun awaitOrThrow(): T = data
override fun <R> map(transform: (T) -> R): ApiResult<R> = ApiResultSuccess(transform(data))
override fun onFailure(handleError: (Throwable) -> Unit): ApiResult<T> = this
override fun toString(): String = data.toString()
}
@Suppress("UNCHECKED_CAST")
internal class ApiResultFail<T>(
private val id: String,
val error: JsonRpcError
) : ApiResult<T> {
private fun exception() = JsonRpcException(id, error)
override suspend fun awaitOrNull(): T? = null
override suspend fun awaitOrThrow(): T = throw exception()
override fun <R> map(transform: (T) -> R): ApiResult<R> = this as ApiResult<R>
override fun onFailure(handleError: (Throwable) -> Unit): ApiResult<T> = apply { handleError(exception()) }
override fun toString(): String = error.toString()
}
class DeferredApiResult<T>(
val request: JsonRpcRequest,
val onResponse: Channel<JsonRpcResponse>,
val decode: suspend (JsonRpcResponse) -> ApiResult<T>
) : ApiResult<T> {
override suspend fun awaitOrThrow() = decode(onResponse.receive()).awaitOrThrow()
override suspend fun awaitOrNull() = decode(onResponse.receive()).awaitOrNull()
override fun <R> map(transform: (T) -> R): ApiResult<R> =
DeferredApiResult(request, onResponse) { decode(it).map(transform) }
override fun onFailure(handleError: (Throwable) -> Unit): ApiResult<T> =
DeferredApiResult(request, onResponse) { decode(it).onFailure(handleError) }
}
| 0 | Kotlin | 0 | 2 | 4fd6f900b4e80b5f731090f33c1ddc10c6ede9ca | 2,644 | keth-client | Apache License 2.0 |
compiler/testData/diagnostics/testsWithStdLib/when/noTypeArgumentsInConstructor.kt | JakeWharton | 99,388,807 | true | null | // !WITH_NEW_INFERENCE
import java.util.*
fun <T> nullable(x: T): T? = x
@Suppress("UNUSED_PARAMETER")
fun <T> select(x1: T, x2: T): T = x1
val test1 =
listOf(1, 2, 3).mapNotNullTo(ArrayList()) {
if (true) nullable(it) else null
}
val test2: MutableList<Int?> =
listOf(1, 2, 3).mapNotNullTo(ArrayList()) {
if (true) nullable(it) else null
}
val test3: MutableList<Int> =
listOf(1, 2, 3).mapNotNullTo(ArrayList()) {
if (true) nullable(it) else null
}
val test4: Collection<Int> =
listOf(1, 2, 3).flatMapTo(LinkedHashSet()) {
listOf(it)
}
val test5: Collection<Int> =
listOf(1, 2, 3).flatMapTo(LinkedHashSet()) { // TODO
if (true) listOf(it) else listOf(it)
}
val test6: Collection<Int> =
listOf(1, 2, 3).flatMapTo(LinkedHashSet<Int>()) {
if (true) listOf(it) else listOf(it)
}
val test7: Collection<Int> =
listOf(1, 2, 3).flatMapTo(LinkedHashSet()) {
select(listOf(it), listOf(it))
}
| 181 | Kotlin | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,089 | kotlin | Apache License 2.0 |
octicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/octicons/octicons/ShieldX16.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.octicons.octicons
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.octicons.Octicons
public val Octicons.ShieldX16: ImageVector
get() {
if (_shieldX16 != null) {
return _shieldX16!!
}
_shieldX16 = Builder(name = "ShieldX16", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp,
viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(8.533f, 0.133f)
lineToRelative(5.25f, 1.68f)
arcTo(1.75f, 1.75f, 0.0f, false, true, 15.0f, 3.48f)
lineTo(15.0f, 7.0f)
curveToRelative(0.0f, 1.566f, -0.32f, 3.182f, -1.303f, 4.682f)
curveToRelative(-0.983f, 1.498f, -2.585f, 2.813f, -5.032f, 3.855f)
arcToRelative(1.697f, 1.697f, 0.0f, false, true, -1.33f, 0.0f)
curveToRelative(-2.447f, -1.042f, -4.049f, -2.357f, -5.032f, -3.855f)
curveTo(1.32f, 10.182f, 1.0f, 8.566f, 1.0f, 7.0f)
lineTo(1.0f, 3.48f)
arcToRelative(1.75f, 1.75f, 0.0f, false, true, 1.217f, -1.667f)
lineToRelative(5.25f, -1.68f)
arcToRelative(1.748f, 1.748f, 0.0f, false, true, 1.066f, 0.0f)
close()
moveTo(7.923f, 1.562f)
lineTo(7.924f, 1.563f)
lineTo(2.674f, 3.243f)
arcToRelative(0.251f, 0.251f, 0.0f, false, false, -0.174f, 0.237f)
lineTo(2.5f, 7.0f)
curveToRelative(0.0f, 1.36f, 0.275f, 2.666f, 1.057f, 3.859f)
curveToRelative(0.784f, 1.194f, 2.121f, 2.342f, 4.366f, 3.298f)
arcToRelative(0.196f, 0.196f, 0.0f, false, false, 0.154f, 0.0f)
curveToRelative(2.245f, -0.957f, 3.582f, -2.103f, 4.366f, -3.297f)
curveTo(13.225f, 9.666f, 13.5f, 8.358f, 13.5f, 7.0f)
lineTo(13.5f, 3.48f)
arcToRelative(0.25f, 0.25f, 0.0f, false, false, -0.174f, -0.238f)
lineToRelative(-5.25f, -1.68f)
arcToRelative(0.25f, 0.25f, 0.0f, false, false, -0.153f, 0.0f)
close()
moveTo(6.78f, 5.22f)
lineTo(8.0f, 6.44f)
lineToRelative(1.22f, -1.22f)
arcToRelative(0.749f, 0.749f, 0.0f, false, true, 1.275f, 0.326f)
arcToRelative(0.749f, 0.749f, 0.0f, false, true, -0.215f, 0.734f)
lineTo(9.06f, 7.5f)
lineToRelative(1.22f, 1.22f)
arcToRelative(0.749f, 0.749f, 0.0f, false, true, -0.326f, 1.275f)
arcToRelative(0.749f, 0.749f, 0.0f, false, true, -0.734f, -0.215f)
lineTo(8.0f, 8.56f)
lineTo(6.78f, 9.78f)
arcToRelative(0.751f, 0.751f, 0.0f, false, true, -1.042f, -0.018f)
arcToRelative(0.751f, 0.751f, 0.0f, false, true, -0.018f, -1.042f)
lineTo(6.94f, 7.5f)
lineTo(5.72f, 6.28f)
arcToRelative(0.749f, 0.749f, 0.0f, false, true, 0.326f, -1.275f)
arcToRelative(0.749f, 0.749f, 0.0f, false, true, 0.734f, 0.215f)
close()
}
}
.build()
return _shieldX16!!
}
private var _shieldX16: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 4,031 | compose-icon-collections | MIT License |
app/src/main/java/com/weather/data/DataManager.kt | eltohamy | 251,126,528 | false | null | package com.weather.data
import com.weather.data.remote.RemoteApi
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by Tohamy on 30/03/2020
*/
@Singleton
class DataManager @Inject
constructor(val remoteApi: RemoteApi)
| 0 | Kotlin | 0 | 0 | 1adb3696d8dc744f89607301c4243a0db632f1f8 | 243 | weather | Apache License 2.0 |
app/src/main/java/com/ml512/mvp/demo/ui/fragment/TestFragmentDialog.kt | malong512 | 203,532,099 | false | {"Java": 12644, "Kotlin": 4611} | package com.ml512.mvp.demo.ui.fragment
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.ml512.base.BaseDialogFragment
import com.ml512.mvp.demo.R
import kotlinx.android.synthetic.main.dialog_fragment_test.*
/**
* 功能描述:测试弹窗
* Created by MaLong on 2019-08-21 18:09.
*/
class TestFragmentDialog : BaseDialogFragment(), View.OnClickListener {
private var onOperateClickListener:OnOperateClickListener? = null
fun setOnOperateClickListener(onOperateClickListener: OnOperateClickListener){
this.onOperateClickListener = onOperateClickListener
}
override fun getContentViewId(): Int = R.layout.dialog_fragment_test
override fun initAllMembersView(savedInstanceState: Bundle?) {
rootView.setOnClickListener(this)
tvCancel.setOnClickListener(this)
tvReport.setOnClickListener(this)
tvKickOut.setOnClickListener(this)
}
override fun onClick(v: View?) {
when(v?.id){
R.id.rootView,R.id.tvCancel -> {
dismiss()
}
R.id.tvReport->{
onOperateClickListener?.onReport()
dismiss()
}
R.id.tvKickOut->{
onOperateClickListener?.onKickOut()
dismiss()
}
}
}
/**
* 操作回调
* create by malong at 2017/7/26 18:05
*/
interface OnOperateClickListener {
fun onReport()
fun onKickOut()
}
} | 1 | null | 1 | 1 | 9fc34cd756e5d4c98d319382b15bf07c124da780 | 1,491 | mvp | Apache License 2.0 |
samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/User.kt | mooreliving777 | 608,792,838 | true | {"Ruby": 533, "Shell": 384, "Dockerfile": 32, "Batchfile": 112, "Markdown": 7416, "SQL": 71, "Kotlin": 1508, "INI": 208, "Java": 8970, "Scala": 284, "C#": 3015, "TypeScript": 1105, "Python": 3771, "Makefile": 16, "Rust": 188, "JavaScript": 462, "HTML": 116, "Swift": 963, "Perl": 148, "Gradle Kotlin DSL": 19, "Java Properties": 13, "CMake": 24, "C++": 417, "PowerShell": 186, "Apex": 29, "Julia": 22, "CSS": 21, "Lua": 24, "Haskell": 53, "Go": 270, "PHP": 691, "Ada": 8, "Proguard": 3, "Objective-C": 134, "MATLAB": 1, "QMake": 1, "C": 41, "F#": 49, "HTML+ERB": 4, "Blade": 2} | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.*
import javax.validation.Valid
/**
* A User who is purchasing from the pet store
* @param id
* @param username
* @param firstName
* @param lastName
* @param email
* @param password
* @param phone
* @param userStatus User Status
*/
data class User(
@get:JsonProperty("id") val id: kotlin.Long? = null,
@get:JsonProperty("username") val username: kotlin.String? = null,
@get:JsonProperty("firstName") val firstName: kotlin.String? = null,
@get:JsonProperty("lastName") val lastName: kotlin.String? = null,
@get:JsonProperty("email") val email: kotlin.String? = null,
@get:JsonProperty("password") val password: kotlin.String? = null,
@get:JsonProperty("phone") val phone: kotlin.String? = null,
@get:JsonProperty("userStatus") val userStatus: kotlin.Int? = null
) {
}
| 2 | null | 2 | 1 | 31c3a40b4c7982eed7e42c3759a82aed4ad77de4 | 973 | openapi-generator | Apache License 2.0 |
app/src/test/java/com/pierbezuhoff/clonium/models/animation/Generators.kt | pier-bezuhoff | 196,375,991 | false | {"Gradle": 3, "YAML": 1, "Java Properties": 2, "Shell": 14, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Java": 1, "Kotlin": 61, "XML": 36, "HTML": 1, "Emacs Lisp": 1} | @file:Suppress("TestFunctionName")
package com.pierbezuhoff.clonium.models.animation
import com.pierbezuhoff.clonium.utils.Milliseconds
import io.kotlintest.properties.Gen
fun <A> ConstAdvancer(result: A, duration: Milliseconds, blocking: Boolean): Advancer<A> =
object : Advancer<A>(duration, if (blocking) duration else 0L) {
override val blocking: Boolean = blocking
override fun advance(timeDelta: Milliseconds): A {
elapse(timeDelta)
return result
}
override fun toString(): String =
"ConstAdvancer($result) [${super.toString()}]"
}
fun <A> LambdaAdvancer(duration: Milliseconds, blocking: Boolean, getResult: (Progress) -> A): Advancer<A> =
object : Advancer<A>(duration, if (blocking) duration else 0L) {
override val blocking: Boolean = blocking
override fun advance(timeDelta: Milliseconds): A {
elapse(timeDelta)
return getResult(progress)
}
}
fun <A> ConstAdvancerGenerator(
results: List<A>,
minDuration: Milliseconds = 1L,
maxDuration: Milliseconds = 10_000L
): Gen<Advancer<A>> =
Gen.choose(minDuration, maxDuration)
.map { duration ->
val result = Gen.from(results).random().first()
val blocking = Gen.bool().random().first()
ConstAdvancer(result, duration, blocking)
}
fun BooleanAdvancerGenerator(
minDuration: Milliseconds = 1L,
maxDuration: Milliseconds = 10_000L
): Gen<Advancer<Boolean>> = ConstAdvancerGenerator(
listOf(true, false),
minDuration, maxDuration
)
fun BooleanPackGenerator(): Gen<AdvancerPack<Boolean>> =
Gen.list(BooleanAdvancerGenerator())
.map { AdvancerPack(it) } | 7 | Kotlin | 2 | 6 | aaa5dcef4f81c0d7630af2acace7d9daa633b7b6 | 1,737 | Clonium4Android | Apache License 2.0 |
app/src/main/java/uz/javokhirjambulov/notes/database/DeletedNoteDatabase.kt | JavokhirJambulov | 514,119,906 | false | null | package uz.javokhirjambulov.notes.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Note::class], version = 1)
abstract class DeletedNoteDatabase: RoomDatabase(){
companion object {
private var notesDataBase: DeletedNoteDatabase? = null
@Synchronized
fun getDataBase(context: Context? = null): DeletedNoteDatabase {
if (notesDataBase == null && context != null) {
notesDataBase = Room.databaseBuilder(context, DeletedNoteDatabase::class.java, "deleted_notes.db").build()
}
return notesDataBase!!
}
fun initDatabase(context: Context? = null) {
getDataBase(context = context)
}
}
abstract fun noteDao(): NotesDatabaseDao
} | 0 | null | 1 | 3 | 27e79c981969cb9b3dc9285181daebbdec37a484 | 852 | Notes-App-Android | Apache License 2.0 |
src/main/java/morefirework/mod/item/FirePasteItem.kt | Sparkierkan7 | 617,247,442 | false | null | package morefirework.mod.item
import net.minecraft.item.Item
class FirePasteItem : Item {
constructor(settings: Settings?) : super(settings) {
}
} | 0 | Kotlin | 0 | 0 | 298d3b06c408b2c93ef379b4ab693905d07270a7 | 161 | more_explosives_mod | MIT License |
src/test/kotlin/dev/monosoul/jooq/functional/PropertiesConfigurationJooqDockerPluginFunctionalTest.kt | monosoul | 497,003,599 | false | null | package dev.monosoul.jooq.functional
import dev.monosoul.jooq.container.PostgresContainer
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.junit.jupiter.api.Test
import strikt.api.expect
import strikt.assertions.isEqualTo
import strikt.java.exists
class PropertiesConfigurationJooqDockerPluginFunctionalTest : JooqDockerPluginFunctionalTestBase() {
@Test
fun `should ignore non-string properties`() {
// given
writeProjectFile("gradle.properties") {
"""
dev.monosoul.jooq.nonStringProperty=value-to-override
""".trimIndent()
}
prepareBuildGradleFile {
"""
project.setProperty("dev.monosoul.jooq.nonStringProperty", 123)
require(project.properties.get("dev.monosoul.jooq.nonStringProperty") !is String) {
"nonStringProperty should not be a string"
}
plugins {
id("dev.monosoul.jooq-docker")
}
repositories {
mavenCentral()
}
dependencies {
jooqCodegen("org.postgresql:postgresql:42.3.6")
}
""".trimIndent()
}
copyResource(from = "/V01__init.sql", to = "src/main/resources/db/migration/V01__init.sql")
// when
val result = runGradleWithArguments("generateJooqClasses")
// then
expect {
that(result).generateJooqClassesTask.outcome isEqualTo SUCCESS
that(
projectFile("build/generated-jooq/org/jooq/generated/tables/Foo.java")
).exists()
}
}
@Test
fun `should support with container override to without container`() {
// given
val postgresContainer = PostgresContainer().also { it.start() }
prepareBuildGradleFile {
"""
plugins {
id("dev.monosoul.jooq-docker")
}
jooq {
withContainer {
image {
command = "postgres -p 6666"
}
}
}
repositories {
mavenCentral()
}
dependencies {
jooqCodegen("org.postgresql:postgresql:42.3.6")
}
""".trimIndent()
}
copyResource(from = "/V01__init.sql", to = "src/main/resources/db/migration/V01__init.sql")
// when
val result = runGradleWithArguments(
"generateJooqClasses",
"-Pdev.monosoul.jooq.withoutContainer.db.username=${postgresContainer.username}",
"-Pdev.monosoul.jooq.withoutContainer.db.password=${postgresContainer.password}",
"-Pdev.monosoul.jooq.withoutContainer.db.name=${postgresContainer.databaseName}",
"-Pdev.monosoul.jooq.withoutContainer.db.port=${postgresContainer.firstMappedPort}"
)
postgresContainer.stop()
// then
expect {
that(result).generateJooqClassesTask.outcome isEqualTo SUCCESS
that(
projectFile("build/generated-jooq/org/jooq/generated/tables/Foo.java")
).exists()
}
}
@Test
fun `should support partial default configuration override via properties`() {
// given
prepareBuildGradleFile {
"""
plugins {
id("dev.monosoul.jooq-docker")
}
jooq {
withContainer {
image {
command = "postgres -p 6666"
}
}
}
repositories {
mavenCentral()
}
dependencies {
jooqCodegen("org.postgresql:postgresql:42.3.6")
}
""".trimIndent()
}
copyResource(from = "/V01__init.sql", to = "src/main/resources/db/migration/V01__init.sql")
// when
val result = runGradleWithArguments(
"generateJooqClasses",
"-Pdev.monosoul.jooq.withContainer.db.port=6666",
)
// then
expect {
that(result).generateJooqClassesTask.outcome isEqualTo SUCCESS
that(
projectFile("build/generated-jooq/org/jooq/generated/tables/Foo.java")
).exists()
}
}
@Test
fun `should support customized configuration override via properties`() {
// given
prepareBuildGradleFile {
"""
plugins {
id("dev.monosoul.jooq-docker")
}
jooq {
withContainer {
image {
command = "postgres -p 6666"
}
}
}
repositories {
mavenCentral()
}
dependencies {
jooqCodegen("org.postgresql:postgresql:42.3.6")
}
""".trimIndent()
}
copyResource(from = "/V01__init.sql", to = "src/main/resources/db/migration/V01__init.sql")
// when
val result = runGradleWithArguments(
"generateJooqClasses",
"-Pdev.monosoul.jooq.withContainer.image.command=",
)
// then
expect {
that(result).generateJooqClassesTask.outcome isEqualTo SUCCESS
that(
projectFile("build/generated-jooq/org/jooq/generated/tables/Foo.java")
).exists()
}
}
@Test
fun `should be possible to configure the plugin with properties to run with container`() {
// given
writeProjectFile("gradle.properties") {
"""
dev.monosoul.jooq.withContainer.db.username=root
dev.monosoul.jooq.withContainer.db.password=<PASSWORD>
dev.monosoul.jooq.withContainer.db.name=mysql
dev.monosoul.jooq.withContainer.db.port=3306
dev.monosoul.jooq.withContainer.db.jdbc.schema=jdbc:mysql
dev.monosoul.jooq.withContainer.db.jdbc.driverClassName=com.mysql.cj.jdbc.Driver
dev.monosoul.jooq.withContainer.db.jdbc.urlQueryParams=?useSSL=false
dev.monosoul.jooq.withContainer.image.name=mysql:8.0.29
dev.monosoul.jooq.withContainer.image.testQuery=SELECT 2
dev.monosoul.jooq.withContainer.image.command=--default-authentication-plugin=mysql_native_password
dev.monosoul.jooq.withContainer.image.envVars.MYSQL_ROOT_PASSWORD=<PASSWORD>
dev.monosoul.jooq.withContainer.image.envVars.MYSQL_DATABASE=mysql
""".trimIndent()
}
prepareBuildGradleFile {
"""
import dev.monosoul.jooq.RecommendedVersions
plugins {
id("dev.monosoul.jooq-docker")
}
repositories {
mavenCentral()
}
dependencies {
jooqCodegen("mysql:mysql-connector-java:8.0.29")
jooqCodegen("org.flywaydb:flyway-mysql:${'$'}{RecommendedVersions.FLYWAY_VERSION}")
}
""".trimIndent()
}
copyResource(from = "/V01__init_mysql.sql", to = "src/main/resources/db/migration/V01__init_mysql.sql")
// when
val result = runGradleWithArguments("generateJooqClasses")
// then
expect {
that(result).generateJooqClassesTask.outcome isEqualTo SUCCESS
that(
projectFile("build/generated-jooq/org/jooq/generated/tables/Foo.java")
).exists()
}
}
@Test
fun `should be possible to configure the plugin with properties to run without container`() {
// given
val postgresContainer = PostgresContainer().also { it.start() }
writeProjectFile("gradle.properties") {
"""
dev.monosoul.jooq.withoutContainer.db.username=${postgresContainer.username}
dev.monosoul.jooq.withoutContainer.db.password=${postgresContainer.password}
dev.monosoul.jooq.withoutContainer.db.name=${postgresContainer.databaseName}
dev.monosoul.jooq.withoutContainer.db.port=${postgresContainer.firstMappedPort}
dev.monosoul.jooq.withoutContainer.db.jdbc.schema=jdbc:postgresql
dev.monosoul.jooq.withoutContainer.db.jdbc.driverClassName=org.postgresql.Driver
dev.monosoul.jooq.withoutContainer.db.jdbc.urlQueryParams=?loggerLevel=OFF
""".trimIndent()
}
prepareBuildGradleFile {
"""
plugins {
id("dev.monosoul.jooq-docker")
}
repositories {
mavenCentral()
}
dependencies {
jooqCodegen("org.postgresql:postgresql:42.3.6")
}
""".trimIndent()
}
copyResource(from = "/V01__init_mysql.sql", to = "src/main/resources/db/migration/V01__init_mysql.sql")
// when
val result = runGradleWithArguments("generateJooqClasses")
postgresContainer.stop()
// then
expect {
that(result).generateJooqClassesTask.outcome isEqualTo SUCCESS
that(
projectFile("build/generated-jooq/org/jooq/generated/tables/Foo.java")
).exists()
}
}
}
| 2 | Kotlin | 5 | 9 | f3cc5cbaf77e3a2a22c767fee75de4f809cea477 | 9,906 | jooq-gradle-plugin | Apache License 2.0 |
java/src/main/java/trinsic/services/provider/v1/ProviderOuterClassGrpcKt.kt | trinsic-id | 361,889,702 | false | null | package trinsic.services.provider.v1
import io.grpc.CallOptions
import io.grpc.CallOptions.DEFAULT
import io.grpc.Channel
import io.grpc.Metadata
import io.grpc.MethodDescriptor
import io.grpc.ServerServiceDefinition
import io.grpc.ServerServiceDefinition.builder
import io.grpc.ServiceDescriptor
import io.grpc.Status
import io.grpc.Status.UNIMPLEMENTED
import io.grpc.StatusException
import io.grpc.kotlin.AbstractCoroutineServerImpl
import io.grpc.kotlin.AbstractCoroutineStub
import io.grpc.kotlin.ClientCalls.unaryRpc
import io.grpc.kotlin.ServerCalls.unaryServerMethodDefinition
import io.grpc.kotlin.StubFor
import kotlin.Deprecated
import kotlin.String
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
import trinsic.services.provider.v1.ProviderGrpc.getServiceDescriptor
/** Holder for Kotlin coroutine-based client and server APIs for services.provider.v1.Provider. */
object ProviderGrpcKt {
const val SERVICE_NAME: String = ProviderGrpc.SERVICE_NAME
@JvmStatic
val serviceDescriptor: ServiceDescriptor
get() = ProviderGrpc.getServiceDescriptor()
val createEcosystemMethod: MethodDescriptor<CreateEcosystemRequest, CreateEcosystemResponse>
@JvmStatic get() = ProviderGrpc.getCreateEcosystemMethod()
val updateEcosystemMethod: MethodDescriptor<UpdateEcosystemRequest, UpdateEcosystemResponse>
@JvmStatic get() = ProviderGrpc.getUpdateEcosystemMethod()
val addWebhookMethod: MethodDescriptor<AddWebhookRequest, AddWebhookResponse>
@JvmStatic get() = ProviderGrpc.getAddWebhookMethod()
val deleteWebhookMethod: MethodDescriptor<DeleteWebhookRequest, DeleteWebhookResponse>
@JvmStatic get() = ProviderGrpc.getDeleteWebhookMethod()
val ecosystemInfoMethod: MethodDescriptor<EcosystemInfoRequest, EcosystemInfoResponse>
@JvmStatic get() = ProviderGrpc.getEcosystemInfoMethod()
val getPublicEcosystemInfoMethod:
MethodDescriptor<GetPublicEcosystemInfoRequest, GetPublicEcosystemInfoResponse>
@JvmStatic get() = ProviderGrpc.getGetPublicEcosystemInfoMethod()
val inviteMethod: MethodDescriptor<InviteRequest, InviteResponse>
@JvmStatic get() = ProviderGrpc.getInviteMethod()
val invitationStatusMethod: MethodDescriptor<InvitationStatusRequest, InvitationStatusResponse>
@JvmStatic get() = ProviderGrpc.getInvitationStatusMethod()
val getOberonKeyMethod: MethodDescriptor<GetOberonKeyRequest, GetOberonKeyResponse>
@JvmStatic get() = ProviderGrpc.getGetOberonKeyMethod()
val upgradeDIDMethod: MethodDescriptor<UpgradeDidRequest, UpgradeDidResponse>
@JvmStatic get() = ProviderGrpc.getUpgradeDIDMethod()
val retrieveDomainVerificationRecordMethod:
MethodDescriptor<
RetrieveDomainVerificationRecordRequest, RetrieveDomainVerificationRecordResponse>
@JvmStatic get() = ProviderGrpc.getRetrieveDomainVerificationRecordMethod()
val refreshDomainVerificationStatusMethod:
MethodDescriptor<
RefreshDomainVerificationStatusRequest, RefreshDomainVerificationStatusResponse>
@JvmStatic get() = ProviderGrpc.getRefreshDomainVerificationStatusMethod()
val searchWalletConfigurationsMethod:
MethodDescriptor<SearchWalletConfigurationsRequest, SearchWalletConfigurationResponse>
@JvmStatic get() = ProviderGrpc.getSearchWalletConfigurationsMethod()
/**
* A stub for issuing RPCs to a(n) services.provider.v1.Provider service as suspending coroutines.
*/
@StubFor(ProviderGrpc::class)
class ProviderCoroutineStub
@JvmOverloads
constructor(channel: Channel, callOptions: CallOptions = DEFAULT) :
AbstractCoroutineStub<ProviderCoroutineStub>(channel, callOptions) {
override fun build(channel: Channel, callOptions: CallOptions): ProviderCoroutineStub =
ProviderCoroutineStub(channel, callOptions)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun createEcosystem(
request: CreateEcosystemRequest,
headers: Metadata = Metadata()
): CreateEcosystemResponse =
unaryRpc(channel, ProviderGrpc.getCreateEcosystemMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
@Deprecated("The underlying service method is marked deprecated.")
suspend fun updateEcosystem(
request: UpdateEcosystemRequest,
headers: Metadata = Metadata()
): UpdateEcosystemResponse =
unaryRpc(channel, ProviderGrpc.getUpdateEcosystemMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun addWebhook(
request: AddWebhookRequest,
headers: Metadata = Metadata()
): AddWebhookResponse =
unaryRpc(channel, ProviderGrpc.getAddWebhookMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun deleteWebhook(
request: DeleteWebhookRequest,
headers: Metadata = Metadata()
): DeleteWebhookResponse =
unaryRpc(channel, ProviderGrpc.getDeleteWebhookMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun ecosystemInfo(
request: EcosystemInfoRequest,
headers: Metadata = Metadata()
): EcosystemInfoResponse =
unaryRpc(channel, ProviderGrpc.getEcosystemInfoMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun getPublicEcosystemInfo(
request: GetPublicEcosystemInfoRequest,
headers: Metadata = Metadata()
): GetPublicEcosystemInfoResponse =
unaryRpc(
channel, ProviderGrpc.getGetPublicEcosystemInfoMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
@Deprecated("The underlying service method is marked deprecated.")
suspend fun invite(request: InviteRequest, headers: Metadata = Metadata()): InviteResponse =
unaryRpc(channel, ProviderGrpc.getInviteMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
@Deprecated("The underlying service method is marked deprecated.")
suspend fun invitationStatus(
request: InvitationStatusRequest,
headers: Metadata = Metadata()
): InvitationStatusResponse =
unaryRpc(channel, ProviderGrpc.getInvitationStatusMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun getOberonKey(
request: GetOberonKeyRequest,
headers: Metadata = Metadata()
): GetOberonKeyResponse =
unaryRpc(channel, ProviderGrpc.getGetOberonKeyMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun upgradeDID(
request: UpgradeDidRequest,
headers: Metadata = Metadata()
): UpgradeDidResponse =
unaryRpc(channel, ProviderGrpc.getUpgradeDIDMethod(), request, callOptions, headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun retrieveDomainVerificationRecord(
request: RetrieveDomainVerificationRecordRequest,
headers: Metadata = Metadata()
): RetrieveDomainVerificationRecordResponse =
unaryRpc(
channel,
ProviderGrpc.getRetrieveDomainVerificationRecordMethod(),
request,
callOptions,
headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun refreshDomainVerificationStatus(
request: RefreshDomainVerificationStatusRequest,
headers: Metadata = Metadata()
): RefreshDomainVerificationStatusResponse =
unaryRpc(
channel,
ProviderGrpc.getRefreshDomainVerificationStatusMethod(),
request,
callOptions,
headers)
/**
* Executes this RPC and returns the response message, suspending until the RPC completes with
* [`Status.OK`][Status]. If the RPC completes with another status, a corresponding
* [StatusException] is thrown. If this coroutine is cancelled, the RPC is also cancelled with
* the corresponding exception as a cause.
*
* @param request The request message to send to the server.
*
* @param headers Metadata to attach to the request. Most users will not need this.
*
* @return The single response from the server.
*/
suspend fun searchWalletConfigurations(
request: SearchWalletConfigurationsRequest,
headers: Metadata = Metadata()
): SearchWalletConfigurationResponse =
unaryRpc(
channel,
ProviderGrpc.getSearchWalletConfigurationsMethod(),
request,
callOptions,
headers)
}
/**
* Skeletal implementation of the services.provider.v1.Provider service based on Kotlin
* coroutines.
*/
abstract class ProviderCoroutineImplBase(
coroutineContext: CoroutineContext = EmptyCoroutineContext
) : AbstractCoroutineServerImpl(coroutineContext) {
/**
* Returns the response to an RPC for services.provider.v1.Provider.CreateEcosystem.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun createEcosystem(request: CreateEcosystemRequest): CreateEcosystemResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.CreateEcosystem is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.UpdateEcosystem.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
@Deprecated("The underlying service method is marked deprecated.")
open suspend fun updateEcosystem(request: UpdateEcosystemRequest): UpdateEcosystemResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.UpdateEcosystem is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.AddWebhook.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun addWebhook(request: AddWebhookRequest): AddWebhookResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.AddWebhook is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.DeleteWebhook.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun deleteWebhook(request: DeleteWebhookRequest): DeleteWebhookResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.DeleteWebhook is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.EcosystemInfo.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun ecosystemInfo(request: EcosystemInfoRequest): EcosystemInfoResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.EcosystemInfo is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.GetPublicEcosystemInfo.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun getPublicEcosystemInfo(
request: GetPublicEcosystemInfoRequest
): GetPublicEcosystemInfoResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.GetPublicEcosystemInfo is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.Invite.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
@Deprecated("The underlying service method is marked deprecated.")
open suspend fun invite(request: InviteRequest): InviteResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.Invite is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.InvitationStatus.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
@Deprecated("The underlying service method is marked deprecated.")
open suspend fun invitationStatus(request: InvitationStatusRequest): InvitationStatusResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.InvitationStatus is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.GetOberonKey.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun getOberonKey(request: GetOberonKeyRequest): GetOberonKeyResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.GetOberonKey is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.UpgradeDID.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun upgradeDID(request: UpgradeDidRequest): UpgradeDidResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.UpgradeDID is unimplemented"))
/**
* Returns the response to an RPC for
* services.provider.v1.Provider.RetrieveDomainVerificationRecord.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun retrieveDomainVerificationRecord(
request: RetrieveDomainVerificationRecordRequest
): RetrieveDomainVerificationRecordResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.RetrieveDomainVerificationRecord is unimplemented"))
/**
* Returns the response to an RPC for
* services.provider.v1.Provider.RefreshDomainVerificationStatus.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun refreshDomainVerificationStatus(
request: RefreshDomainVerificationStatusRequest
): RefreshDomainVerificationStatusResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.RefreshDomainVerificationStatus is unimplemented"))
/**
* Returns the response to an RPC for services.provider.v1.Provider.SearchWalletConfigurations.
*
* If this method fails with a [StatusException], the RPC will fail with the corresponding
* [Status]. If this method fails with a [java.util.concurrent.CancellationException], the RPC
* will fail with status `Status.CANCELLED`. If this method fails for any other reason, the RPC
* will fail with `Status.UNKNOWN` with the exception as a cause.
*
* @param request The request from the client.
*/
open suspend fun searchWalletConfigurations(
request: SearchWalletConfigurationsRequest
): SearchWalletConfigurationResponse =
throw StatusException(
UNIMPLEMENTED.withDescription(
"Method services.provider.v1.Provider.SearchWalletConfigurations is unimplemented"))
final override fun bindService(): ServerServiceDefinition =
builder(getServiceDescriptor())
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getCreateEcosystemMethod(),
implementation = ::createEcosystem))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getUpdateEcosystemMethod(),
implementation = ::updateEcosystem))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getAddWebhookMethod(),
implementation = ::addWebhook))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getDeleteWebhookMethod(),
implementation = ::deleteWebhook))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getEcosystemInfoMethod(),
implementation = ::ecosystemInfo))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getGetPublicEcosystemInfoMethod(),
implementation = ::getPublicEcosystemInfo))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getInviteMethod(),
implementation = ::invite))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getInvitationStatusMethod(),
implementation = ::invitationStatus))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getGetOberonKeyMethod(),
implementation = ::getOberonKey))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getUpgradeDIDMethod(),
implementation = ::upgradeDID))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getRetrieveDomainVerificationRecordMethod(),
implementation = ::retrieveDomainVerificationRecord))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getRefreshDomainVerificationStatusMethod(),
implementation = ::refreshDomainVerificationStatus))
.addMethod(
unaryServerMethodDefinition(
context = this.context,
descriptor = ProviderGrpc.getSearchWalletConfigurationsMethod(),
implementation = ::searchWalletConfigurations))
.build()
}
}
| 8 | Dart | 15 | 25 | fd7439f78b1bb2c72db8ca91c11659e618974694 | 29,407 | sdk | Apache License 2.0 |
Kuery/src/main/kotlin/com/sxtanna/db/struct/SqlType.kt | camdenorrb | 190,177,971 | true | {"Kotlin": 95560} | package com.sxtanna.db.struct
import com.sxtanna.db.struct.SqlType.Attribute.*
import com.sxtanna.db.type.Named
import kotlin.reflect.KClass
/**
* Defines the supported SQL Types of this DSL
* * These descriptions are 100% copy-pasted from my best friend "HeidiSQL", don't @ me if they are wrong, make an issue pls
*/
sealed class SqlType(name: String? = null) : Named {
override val name by lazy { requireNotNull(name ?: this::class.simpleName?.substring(3)?.toUpperCase()) }
operator fun get(vararg attributes: Attribute<*>?): Cache = Cache(attributes.filterNotNull().toMutableList())
final override fun toString() = "Type=$name"
final override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SqlType) return false
if (name != other.name) return false
return true
}
final override fun hashCode(): Int {
return name.hashCode()
}
/**
* Represents cached attributes for this [SqlType] at the column its created for
*/
open inner class Cache internal constructor(protected val attributes: MutableList<Attribute<*>>) {
constructor(attributes: Array<out Attribute<*>?>) : this(attributes.filterNotNull().toMutableList())
open fun name() = name
override fun toString(): String {
return "${name()}${if (attributes.has<SqlPrimary>()) " PRIMARY KEY" else ""}${if (attributes.has<SqlNotNull>()) " NOT NULL" else ""}"
}
protected inline fun <reified A : Attribute<*>> MutableList<Attribute<*>>.has() = any { it is A }
protected inline fun <reified A : Attribute<*>> MutableList<Attribute<*>>.rem() = removeAll { it is A }
}
// base implementations
/**
* Represents an [SqlType] with a size
*/
abstract class SizedType(name: String? = null) : SqlType(name) {
operator fun get(size: Int, vararg attributes: Attribute<*>?): Cache = SizedCache(size, attributes)
@JvmName("otherGet")
operator fun get(size: Int, attributes: Array<out Attribute<*>?>): Cache = SizedCache(size, attributes)
open inner class SizedCache internal constructor(protected val size: Int, attributes: Array<out Attribute<*>?>) : Cache(attributes) {
override fun name() = "$name($size)"
}
}
/**
* Represents an [SqlType] that is a number
*/
abstract class NumberType(name: String? = null) : SizedType(name) {
open inner class NumberCache internal constructor(protected val size: Int, attributes: Array<out Attribute<*>?>) : Cache(attributes) {
override fun name() = "${super.name()}${if (attributes.has<SqlUnsigned>()) " UNSIGNED" else ""}"
}
}
/**
* Represents an [SqlType] that is a floating point number
*/
abstract class DecimalType(name: String? = null) : NumberType(name) {
operator fun get(size: Int, places: Int, vararg attributes: Attribute<*>?): Cache = DecimalCache(size, places, attributes)
@JvmName("otherGet")
operator fun get(size: Int, places: Int, attributes: Array<out Attribute<*>?>): Cache = DecimalCache(size, places, attributes)
inner class DecimalCache internal constructor(size: Int, private val places: Int, attributes: Array<out Attribute<*>?>) : NumberCache(size, attributes) {
override fun name() = "$name($size, $places)${if (attributes.has<SqlUnsigned>()) " UNSIGNED" else ""}"
}
}
/**
* Represents an [SqlType] that holds a collection of some sort
*/
abstract class CollType(name: String? = null) : SqlType(name) {
operator fun get(values: Array<out Any>, vararg attributes: Attribute<*>?): Cache = CollCache(values, attributes)
@JvmName("otherGet")
operator fun get(values: Array<out Any>, attributes: Array<out Attribute<*>?>): Cache = CollCache(values, attributes)
inner class CollCache internal constructor(private val values: Array<out Any>, attributes: Array<out Attribute<*>?>) : Cache(attributes) {
override fun toString(): String {
val name = name()
return "$name(${values.joinToString { "'$it'" }})${super.toString().substringAfter(name)}"
}
}
}
// whole number types
/**
* Sql "TINYINT" data type, "A very small integer"
*
* **Range**
* * **Signed -128..127**
* * **Unsigned 0..255**
*/
object SqlTinyInt : NumberType()
/**
* Sql "SMALLINT" data type, "A small integer"
*
* **Range**
* * **Signed -32,768..32,767**
* * **Unsigned 0..65,535**
*/
object SqlSmallInt : NumberType()
/**
* Sql "MEDIUMINT" data type, "A medium-sized integer"
*
* **Range**
* * **Signed -8,388,608..8,388,607**
* * **Unsigned 0..16,777,215**
*/
object SqlMediumInt : NumberType()
/**
* Sql "INT" data type, "A normal-sized integer"
*
* **Range**
* * **Signed -2,147,483,648..2,147,483,647**
* * **Unsigned 0..4,294,967,295**
*/
object SqlInt : NumberType()
/**
* Sql "BIGINT" data type, "A large integer"
*
* **Range**
* * **Signed -9,223,372,036,854,775,808..9,223,372,036,854,775,807**
* * **Unsigned 0..18,446,744,073,709,551,615**
*/
object SqlBigInt : NumberType()
// floating point number types
/**
* Sql "FLOAT" data type, "A small (single-precision) floating-point number"
*
* **Range**
* * **Signed -3.402823466E+38..3.402823466E+38**
* * **Unsigned 0..3.402823466E+38**
*/
object SqlFloat : DecimalType()
/**
* Sql "DOUBLE" data type, "A normal sized (double-precision) floating-point number"
*
* **Range**
* * **Signed -1.7976931348623157E+308..1.7976931348623157E+308**
* * **Unsigned 0..1.7976931348623157E+308**
*/
object SqlDouble : DecimalType()
/**
* Sql "DECIMAL" data type, "A packed "exact" fixed-point number"
*/
object SqlDecimal : DecimalType()
// text types
/**
* Sql "CHAR" data type, "A fixed-length string"
* * Always right padded to specified length, automatically trimmed when retrieved
*
* **Length Range**
* * **0..255**
*/
object SqlChar : SizedType()
/**
* Sql "VARCHAR" data type, "A variable-length string"
* * Max length affected by character set and row size
*
* **Length Range**
* * **0..65,535**
*/
object SqlVarChar : SizedType()
/**
* Sql "TINYTEXT" data type, "A TEXT column with a maximum length of 255"
* * Max length affected by multi-byte characters
*/
object SqlTinyText : SqlType()
/**
* Sql "TEXT" data type, "A TEXT column with a maximum length of 65,535"
* * Max length affected by multi-byte characters
*/
object SqlText : SqlType()
/**
* Sql "MEDIUMTEXT" data type, "A TEXT column with a maximum length of 16,777,215"
* * Max length affected by multi-byte characters
*/
object SqlMediumText : SqlType()
/**
* Sql "LONGTEXT" data type, "A TEXT column with a maximum length of 4,294,967,295"
* * Max length affected by multi-byte characters
*/
object SqlLongText : SqlType()
// misc types
/**
* Sql "BOOL/TINYINT" data type, "A type that can take either true(1), false(0), or NULL"
*/
object SqlBoolean : SqlType()
/**
* Sql "DATE" data type, "A type that supports a range from '1000-01-01' to '9999-12-31'"
*/
object SqlDate : SqlType()
/**
* Sql "TIMESTAMP" data type, "A type that supports a range from '1970-01-01' to '2038-01-09'"
*/
object SqlTimestamp : SqlType()
/**
* Sql "SET" data type, "A set. A string object that can have zero or more values"
* * Each value must be chosen from the list of values specified
*
* **Maximum size**
* * **64 elements**
*/
object SqlSet : CollType() {
operator fun get(values: Collection<Any>, vararg attributes: Attribute<*>?): Cache {
return get(values.toTypedArray(), attributes)
}
@JvmName("otherGet")
operator fun get(values: Collection<Any>, attributes: Array<out Attribute<*>?>): Cache {
return get(values.toTypedArray(), attributes)
}
}
/**
* Sql "ENUM" data type, "An enumeration. A string object that can have only one value"
* * The value must be chosen from the list of values specified. or NULL
*
* **Maximum size**
* * **65,535 distinct elements**
*/
object SqlEnum : CollType() {
operator fun get(clazz: KClass<out Enum<*>>, vararg attributes: Attribute<*>?): Cache {
return get(clazz.java.enumConstants, attributes)
}
@JvmName("otherGet")
operator fun get(clazz: KClass<out Enum<*>>, attributes: Array<out Attribute<*>?>): Cache {
return get(clazz.java.enumConstants, attributes)
}
}
/**
* Represents row column specific attributes
*/
sealed class Attribute<out T : Any?>(override val name: String) : Named {
internal abstract val value: T
/**
* Represents the default value for rows in this column
* * You should like... never use this btw... this is an ORM, don't be a dumbo
* * Actually, I'm not even going to implement it... sue me.. ¯\_(-_-)_/¯
* * Also, I'm marking it as internal, I might revisit it later, idk..
*/
internal class SqlDefault<out T : Any?>(override val value: T) : Attribute<T>("DEFAULT")
/**
* Represents a column whose values cannot be NULL
*/
object SqlNotNull : Attribute<Boolean>("NOT NULL") {
override val value = true
}
/**
* Represents a column whose values are the PRIMARY KEY of the table
*/
object SqlPrimary : Attribute<Boolean>("PRIMARY KEY") {
override val value = true
}
/**
* Represents a column whose number values are UNSIGNED
*/
object SqlUnsigned : Attribute<Boolean>("UNSIGNED") {
override val value = true
}
}
} | 0 | Kotlin | 0 | 0 | 28388edf5a67889430246312d5b46db3b16f204b | 10,354 | KDatabases | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.