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/dev/fastmc/modsetup/ModSetupPlugin.kt
|
FastMinecraft
| 574,376,130
| false
|
{"Kotlin": 48962}
|
package dev.fastmc.modsetup
import org.gradle.api.Plugin
import org.gradle.api.Project
class ModSetupPlugin : Plugin<Project> {
override fun apply(project: Project) {
RootConfigure(project).configure()
}
}
| 0
|
Kotlin
|
0
| 8
|
17ee2db67a3d87e2e0681f70bf221a8ec84a3870
| 223
|
mod-setup
|
MIT License
|
app/src/main/java/com/theapache64/tvplayground/utils/JawwyGlideModule.kt
|
anoopmaddasseri
| 316,386,537
| false
| null |
package com.theapache64.tvplayground.utils
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
/**
* Created by theapache64 : Nov 23 Mon,2020 @ 19:00
*/
@GlideModule
class JawwyGlideModule : AppGlideModule() {
}
| 0
|
Kotlin
|
0
| 0
|
66a18e264cbc35d3ea5aacc93d6c062a09b7fdf9
| 260
|
TVProgramBarPlayGround
|
Apache License 2.0
|
spring-cloud-task/src/main/kotlin/com/livk/task/TaskExample.kt
|
livk-cloud
| 441,105,335
| false
|
{"Kotlin": 91905}
|
package com.livk.task
import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.cloud.task.configuration.EnableTask
import org.springframework.context.annotation.Bean
/**
* <p>
* TaskExample
* </p>
*
* @author livk
* @date 2022/12/10
*/
@EnableTask
@SpringBootApplication
open class TaskExample {
@Bean
open fun commandLineRunner(): CommandLineRunner {
return HelloWorldCommandLineRunner();
}
class HelloWorldCommandLineRunner : CommandLineRunner {
private val logger = LoggerFactory.getLogger(HelloWorldCommandLineRunner::class.java)
override fun run(vararg args: String?) {
logger.info("{}", "hello,world!")
}
}
}
fun main(args: Array<String>) {
runApplication<TaskExample>(*args)
}
| 2
|
Kotlin
|
7
| 26
|
24a5ed3d575787e65bd20860323e9e668c3bfaea
| 933
|
spring-cloud-kotlin
|
Apache License 2.0
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/battle/event/AiSkillCdInfo.kt
|
Anime-Game-Servers
| 642,871,918
| false
|
{"Kotlin": 1651536}
|
package data.battle.event
import org.anime_game_servers.core.base.Version.GI_1_2_0
import org.anime_game_servers.core.base.Version.GI_CB1
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.ProtoModel
@AddedIn(GI_CB1)
@ProtoModel
internal interface AiSkillCdInfo {
var skillCdMap: Map<Int, Int>
@AddedIn(GI_1_2_0)
var skillGroupCdMap: Map<Int, Int>
}
| 1
|
Kotlin
|
3
| 6
|
b342ff34dfb0f168a902498b53682c315c40d44e
| 431
|
anime-game-multi-proto
|
MIT License
|
reflekt-plugin/src/test/resources/io/reflekt/plugin/analysis/util/data/several_filters_test/project/test/Main.kt
|
altavir
| 408,735,983
| true
|
{"Kotlin": 257342}
|
package io.reflekt.test
import io.reflekt.SmartReflekt
import org.jetbrains.kotlin.psi.KtClass
fun main() {
val smartClasses = SmartReflekt.classes<AInterface1Test>()
.filter { it.isInterface() }
.filter { true }
.filter { klass: KtClass -> klass.isInterface() }
.filter { klass -> klass.isInterface() }
.resolve()
}
| 0
| null |
0
| 0
|
d8938ad12beeb2b53a4abe647ae6f875a1157d29
| 363
|
reflekt
|
Apache License 2.0
|
app/src/main/java/com/rmoralf/marveltest/presentation/search/components/SearchRow.kt
|
rmoralf
| 515,890,655
| false
|
{"Kotlin": 81685}
|
package com.rmoralf.marveltest.presentation.search.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import com.rmoralf.marveltest.R
import com.rmoralf.marveltest.presentation.search.SearchViewModel
@Composable
fun SearchRow(
viewModel: SearchViewModel = hiltViewModel()
) {
var searchTxt by remember { mutableStateOf(viewModel.lastSearch) }
val focusManager = LocalFocusManager.current
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
TextField(
value = searchTxt,
onValueChange = { searchTxt = it },
singleLine = true,
placeholder = {
Text(
text = stringResource(id = R.string.search_screen_textfield)
)
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.White
),
modifier = Modifier
.weight(1f)
)
IconButton(
onClick = {
viewModel.searchCharacter(searchTxt)
focusManager.clearFocus()
}
) {
Icon(
Icons.Default.Search,
stringResource(id = R.string.search_screen_btn)
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f0872db0656d302af8bbc011e654309e1b252bca
| 1,812
|
marvel-test
|
Apache License 2.0
|
src/integration-test/kotlin/com/betomorrow/gradle/appcenter/AppCenterProperties.kt
|
oliviergauthier
| 166,103,947
| false
| null |
package com.betomorrow.gradle.appcenter
import java.util.*
/**
* AppCenter API properties used for integration tests.
*/
class AppCenterProperties {
private val props = ClassLoader.getSystemResourceAsStream("integration-test.properties").use { inputStream ->
Properties().apply {
load(inputStream)
}
}
/** AppCenter API token. */
val apiToken : String = props.getProperty("apiToken")
/** AppCenter owner name. */
val ownerName : String = props.getProperty("ownerName")
/** AppCenter app name. */
val appName : String = props.getProperty("appName")
}
| 17
|
Kotlin
|
50
| 79
|
5f263d074368d9ec7ce0dd833343758cc5be2154
| 618
|
gradle-appcenter-plugin
|
MIT License
|
tracer/src/util/Misc.kt
|
WingCorp
| 139,587,913
| false
|
{"Kotlin": 27425}
|
package util
import basics.Colour
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.math.min
/**
* Created by Jon on 21-07-2017.
*/
object Misc {
fun<T> id(it: T): T = it
//Standard background color
val BG_COLOR: Colour = Colour.BLACK
//Material util.Misc
val DEF_MAT_COLOR: Colour = Colour.WHITE
val DEF_MAT_REFL = 0.0f
//GAMMA SETTINGS
val GAMMA_Sdec = 1.0f
val GAMMA_Senc = 0.45f
val GAMMA_MY = 1.8f
//FLOATING POINT ARITHMETIC
val SMALL_NUM = 0.00000001f
val SMALL_NUM2 = 0.0001f
val SMALL_NUM3 = 0.01f
val SMALL_ONE = 1.0f + 1E-5f
val SMALL_ZERO = 1E-5f
//RENDER NUMBER OF REFLECTIONS
val DEFAULT_REFL_COUNT = 4
//LIGHT DIFFUSION COEFFICIENT
val DIFF_COEF = 2.0f
fun <T> Sequence<T>.papply(
numberOfThreads: Int = Runtime.getRuntime().availableProcessors(),
executorService: ExecutorService = Executors.newFixedThreadPool(numberOfThreads),
procedure: (T) -> Unit) {
for (element in this) {
executorService.submit { procedure.invoke(element) }
}
executorService.shutdown()
executorService.awaitTermination(1, TimeUnit.DAYS)
}
fun floatEquals(a: Float, b: Float, tolerance: Float = SMALL_NUM2): Boolean {
return Math.abs(a - b) < tolerance
}
fun <T1, T2, R> Collection<T1>.fold2(otherCollection: Collection<T2>, initial: R, folder: (R, T1, T2) -> R): R {
val smallestSize = min(this.size, otherCollection.size)
var currentState = initial
for (i in (0..smallestSize)) {
currentState = folder(currentState, this.elementAt(i), otherCollection.elementAt(i))
}
return currentState
}
}
| 0
|
Kotlin
|
0
| 1
|
9961c7820ccf4561b832ac9896bdb4ba9a67ff5b
| 1,824
|
jart
|
MIT License
|
app/src/main/java/douglasspgyn/com/github/desafiostone/application/ApplicationConfig.kt
|
douglasspgyn
| 110,436,838
| true
|
{"Kotlin": 46535}
|
package douglasspgyn.com.github.desafiostone.application
/**
* Created by Douglas on 12/11/17.
*/
object ApplicationConfig {
val API_URL = "https://raw.githubusercontent.com"
val APIARY_URL = "https://private-f1493e-stonedesafiomobile1.apiary-mock.com"
}
| 0
|
Kotlin
|
0
| 0
|
f5bfc3400c56dec7a70f08aeeeccd79feb250fe2
| 266
|
desafio-mobile
|
MIT License
|
src/main/java/com/nativedevps/google/delegate/AuthContractor.kt
|
merlinJeyakumar
| 660,900,490
| false
| null |
package com.nativedevps.google.delegate
import androidx.fragment.app.FragmentActivity
interface AuthContractor {
fun retrieveActivity(): FragmentActivity
}
| 0
|
Kotlin
|
0
| 0
|
44f0d53f5f8e5e38e85dad80f5351dbc6f72b132
| 161
|
JGoogleAuth
|
MIT License
|
sdk/src/main/java/com/mapbox/maps/renderer/RenderHandlerThread.kt
|
mapbox
| 330,365,289
| false
|
{"Kotlin": 3277457, "Java": 88976, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2847, "CMake": 1201, "EJS": 1194}
|
package com.mapbox.maps.renderer
import android.os.Handler
import android.os.HandlerThread
import android.os.Message
import android.os.Process.THREAD_PRIORITY_DISPLAY
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import com.mapbox.maps.logW
@RestrictTo(RestrictTo.Scope.LIBRARY)
internal class RenderHandlerThread {
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal val handlerThread: HandlerThread =
HandlerThread(HANDLE_THREAD_NAME, THREAD_PRIORITY_DISPLAY)
internal var handler: Handler? = null
internal val isRunning
get() = handler != null && handlerThread.isAlive
fun post(task: () -> Unit) {
postDelayed(task, 0)
}
fun postDelayed(task: () -> Unit, delayMillis: Long) {
handler?.let {
val message = Message.obtain(it, task)
it.sendMessageDelayed(message, delayMillis)
} ?: logW(TAG, "Thread $HANDLE_THREAD_NAME was not started, ignoring event")
}
fun start(): Handler {
handlerThread.start()
return Handler(handlerThread.looper).also {
handler = it
}
}
fun stop() {
handlerThread.quit()
handler = null
}
/**
* Clears all messages.
*/
fun clearRenderEventQueue() {
handler?.removeCallbacksAndMessages(null)
}
companion object {
private const val HANDLE_THREAD_NAME = "MapboxRenderThread"
private const val TAG = "Mbgl-$HANDLE_THREAD_NAME"
}
}
| 196
|
Kotlin
|
120
| 404
|
83a3dcc9212f2426d80435615d484b0cb147b187
| 1,423
|
mapbox-maps-android
|
Apache License 2.0
|
app/src/main/java/com/vicky7230/cayennekt/data/network/ApiHelper.kt
|
pranaypatel512
| 122,066,604
| false
| null |
package com.vicky7230.cayennekt.data.network
import com.vicky7230.cayennekt.data.network.model.recipes.Recipes
import com.vicky7230.cayennekt.data.network.model.singleRecipe.SingleRecipe
import io.reactivex.Observable
import retrofit2.http.Field
/**
* Created by vicky on 31/12/17.
*/
interface ApiHelper {
fun getRecipes(key: String, page: String, count: String): Observable<Recipes>
fun getRecipe(key: String, rId: String): Observable<SingleRecipe>
fun searchRecipes(key: String, query: String, page: String): Observable<Recipes>
}
| 0
|
Kotlin
|
0
| 0
|
7d99b4be5ed025010fcdaae4cd1f6ec7bbfe2255
| 552
|
Cayenne-Kt
|
Apache License 2.0
|
kotlin-electron/src/jsMain/generated/electron/utility/BrowserWindowConstructorOptions.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12159121, "JavaScript": 330528}
|
// Generated by Karakum - do not modify it manually!
package electron.utility
typealias BrowserWindowConstructorOptions = electron.core.BrowserWindowConstructorOptions
| 40
|
Kotlin
|
165
| 1,319
|
a8a1947d73e3ed26426f1e27b641bff427dfd6a0
| 172
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/java/com/vladsch/md/nav/editor/util/HtmlScriptResource.kt
|
vsch
| 32,095,357
| false
| null |
// Copyright (c) 2015-2023 Vladimir Schneider <vladimir.schneider@gmail.com> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.util
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.vladsch.flexmark.util.data.MutableDataHolder
import com.vladsch.flexmark.util.data.MutableDataSet
import com.vladsch.md.nav.settings.MdApplicationSettings
import com.vladsch.md.nav.settings.MdRenderingProfile
import java.util.*
open class HtmlScriptResource(
override val providerInfo: HtmlScriptResourceProvider.Info // providerInfo for this script resource
, val sourceJs: String // resource path for js script source
, val initializationHtml: String // initialization script with <script></script> wrapper, or any other HTML to be inserted at the bottom of body
, val data: MutableDataHolder = MutableDataSet()
) : HtmlResource(), MutableDataHolder by data {
open val sourceJsUrl: String = resourceFileUrl(sourceJs, javaClass)
override fun injectHtmlResource(project: Project, applicationSettings: MdApplicationSettings, renderingProfile: MdRenderingProfile, injections: ArrayList<InjectHtmlResource?>, forHtmlExport: Boolean, dataContext: DataContext) {
injectScriptUrl(injections, true, true, false, getInjectionUrl(project, sourceJsUrl, sourceJs, renderingProfile, forHtmlExport, dataContext))
injectScriptInitializationHtml(injections, true, false, true, initializationHtml)
}
}
| 134
| null |
131
| 809
|
ec413c0e1b784ff7309ef073ddb4907d04345073
| 1,636
|
idea-multimarkdown
|
Apache License 2.0
|
src/main/kotlin/ru/ozon/ideplugin/kelp/demoApp/OpenDsComponentInDemoAppIntention.kt
|
ozontech
| 728,178,660
| false
|
{"Kotlin": 79988, "HTML": 210}
|
package ru.ozon.ideplugin.kelp
import com.android.ddmlib.IDevice
import com.android.ddmlib.MultiLineReceiver
import com.android.ddmlib.NullOutputReceiver
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.PriorityAction
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.android.sdk.AndroidSdkUtils
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.toUElement
import ru.ozon.ideplugin.kelp.pluginConfig.KelpConfig
import ru.ozon.ideplugin.kelp.pluginConfig.kelpConfig
import java.nio.file.Path
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.io.path.div
/**
* If you place the cursor on one of the functions (components of the design system) and summon the
* Intention Actions list, a new action will be available.
*
* - When called, the plugin checks whether there is a running Android device; if not, it offers to launch it.
* - If launched, checks how many. If there are more than one, then a menu ([chooseFromManyDevices]) is offered for
* selecting the Android device on which you'd like to open the demo app. If there is only one Android device,
* it is selected by default.
* - Turns on the screen of the Android device
* - Acquires the intended latest version of the demo app from name of the demo app apk file.
* - Checks whether the demo app is installed on the Android device, and if so, whether it is the latest
* version. If not, the apk file is installed on the Android device from the predefined path: [apkPath].
* - Next, an intent is launched with a deeplink leading to the component page in demo app.
*/
@Suppress("IntentionDescriptionNotFoundInspection")
internal class OpenDsComponentInDemoAppIntention : PsiElementBaseIntentionAction(), IntentionAction, PriorityAction {
private val logger = thisLogger()
override fun getFamilyName(): String = KelpBundle.message("kelpIntentionsFamilyName")
override fun generatePreview(project: Project, editor: Editor, file: PsiFile) = IntentionPreviewInfo.EMPTY!!
override fun getPriority(): PriorityAction.Priority = PriorityAction.Priority.HIGH
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean {
val config = project.kelpConfig()?.demoApp ?: return false
if (editor == null ||
element.toUElement() !is UIdentifier ||
config.functionSimpleNamePrefix?.let { !element.text.startsWith(it) } == true
) {
return false
}
val isAvailable = element.parent.reference?.resolve()?.isDsComponentFunction(config) == true ||
(element.parent as? KtNamedFunction)?.isDsComponentFunction(config) == true
if (isAvailable) text = config.intentionName
return isAvailable
}
override fun invoke(project: Project, editor: Editor, element: PsiElement) {
val notificationGroup = NotificationGroupManager.getInstance().getNotificationGroup(
KelpBundle.message("kelpNotificationGroup"),
)
val componentFqn = getDsComponentFQN(element) ?: run {
showNoDSComponentFQN(project, notificationGroup)
return
}
val debugBridge = AndroidSdkUtils.getDebugBridge(project) ?: run {
showNoSdkError(project, notificationGroup)
return
}
val taskName = KelpBundle.message("openingInDemoAppMessage")
object : Task.Backgroundable(project, taskName, false) {
override fun run(progressIndicator: ProgressIndicator) {
runCatching {
val config = project.kelpConfig()?.demoApp ?: return
val devices = debugBridge.devices.filter { it.isOnline }.toList().ifEmpty {
showNoDevicesError(project, notificationGroup)
activateDeviceManagerToolWindow(project)
return
}
val device = if (devices.size == 1) {
devices.first()
} else {
chooseFromManyDevices(devices, editor) ?: return
}
val receiver = NullOutputReceiver.getReceiver()
progressIndicator.text = KelpBundle.message("turningOnScreenMessage")
device.executeShellCommand(
UNLOCK_SCREEN_COMMAND, receiver, SHELL_TIMEOUT_MS, SHELL_TIMEOUT_MS, TimeUnit.MILLISECONDS
)
apkInstallingStep(project, config, progressIndicator, device)
progressIndicator.text = taskName
val command = openComponentInDemoAppCommand(
config = config,
componentFqn = componentFqn.asString(),
)
device.executeShellCommand(
command, receiver, SHELL_TIMEOUT_MS, SHELL_TIMEOUT_MS, TimeUnit.MILLISECONDS
)
showOpenedNotification(componentFqn.shortName().asString(), project, notificationGroup)
}.onFailure {
showGeneralError(it, project)
}
}
}.queue()
}
/**
* @return null, if device was not selected
*/
private fun chooseFromManyDevices(devices: List<IDevice>, editor: Editor): IDevice? {
val latch = CountDownLatch(1)
var device: IDevice? = null
val step = object : BaseListPopupStep<IDevice>(KelpBundle.message("chooseDevicePopupTitle"), devices) {
override fun getTextFor(value: IDevice): String = value.name
override fun onChosen(selectedValue: IDevice, finalChoice: Boolean): PopupStep<*>? {
if (!finalChoice) return null
device = selectedValue
latch.countDown()
return FINAL_CHOICE
}
override fun canceled() = latch.countDown()
}
invokeLater { showPopup(step, editor) }
latch.await()
return device
}
private fun apkInstallingStep(
project: Project,
config: KelpConfig.DemoApp,
progressIndicator: ProgressIndicator,
device: IDevice,
) {
if (config.apkInstallation != true) return
progressIndicator.text = KelpBundle.message("checkingInstalledAppVersionMessage")
logger.info(progressIndicator.text)
val latestVersion = getLatestVersion(project)
val isLatestVersionInstalled = isLatestVersionInstalled(device, latestVersion, config.appPackageName)
if (isLatestVersionInstalled) return
progressIndicator.text = KelpBundle.message("uninstallingPreviousAppMessage")
logger.info(progressIndicator.text)
device.uninstallPackage(config.appPackageName)
progressIndicator.text = KelpBundle.message("installingAppMessage")
logger.info(progressIndicator.text)
val apkPath = apkPath(project)
device.installPackage(apkPath.toString(), true)
}
private fun getLatestVersion(project: Project): String {
val apkFileName = apkPath(project).toFile().name
val latestVersion = apkFileNameRegex.matchEntire(apkFileName)?.groups?.get("version")?.value
logger.info("Latest version acquired from the $apkFileName fileName is $latestVersion")
return latestVersion ?: error(KelpBundle.message("demoAppLatestVersionNotFoundErrorMessage", apkFileName))
}
private fun apkPath(project: Project): Path {
val apkFolderPath = pluginConfigDirPath(project) / "apk"
return runReadAction {
VirtualFileManager.getInstance()
.findFileByNioPath(apkFolderPath)
?.children
?.find { it.name.matches(apkFileNameRegex) }
?.toNioPath()
?: error(KelpBundle.message("apkFileNotFoundErrorMessage", apkFolderPath))
}
}
private val apkFileNameRegex = "demoApp-(?<version>.+?).apk".toRegex()
private fun isLatestVersionInstalled(device: IDevice, latestVersion: String, demoAppPackageName: String): Boolean {
val isLatestVersionInstalled = AtomicBoolean(false)
val latch = CountDownLatch(1)
logger.info("Searching for already installed demoApp with pkgName=$demoAppPackageName")
device.executeShellCommand(
"dumpsys package $demoAppPackageName | grep versionName",
object : MultiLineReceiver() {
override fun isCancelled(): Boolean = false
override fun processNewLines(lines: Array<String>) {
val installedVersion = lines
.map { it.substringAfterLast("versionName=", missingDelimiterValue = "") }
.firstOrNull { it.isNotBlank() }
logger.info("Already installed demoApp version is ${installedVersion.toString()}")
isLatestVersionInstalled.compareAndSet(false, installedVersion == latestVersion)
latch.countDown()
}
},
SHELL_TIMEOUT_MS, SHELL_TIMEOUT_MS, TimeUnit.MILLISECONDS,
)
if (!latch.await(SHELL_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
logger.info("Search failed, nothing found")
}
return isLatestVersionInstalled.get().also {
logger.info("Latest demoApp version is ${if (!it) "not " else ""}installed")
}
}
private fun getDsComponentFQN(element: PsiElement): FqName? {
val name =
if (element.parent is KtNamedFunction) element.parent.kotlinFqName
else element.parent.reference?.resolve()?.kotlinFqName
return name?.takeUnless { it.asString().isBlank() }
}
// adb shell am start
// -W -a android.intent.action.VIEW
// -d "yourscheme://component/com.your.designsystem.package.components.Badge"
// com.your.designsystem.package
private fun openComponentInDemoAppCommand(config: KelpConfig.DemoApp, componentFqn: String): String {
val packageName = config.appPackageName
val deeplink = config.componentDeeplink.replace(DS_COMPONENT_FQN_DEEPLINK_PLACEHOLDER, componentFqn)
return "am start -W -a android.intent.action.VIEW -d \"$deeplink\" $packageName"
}
private fun showPopup(step: ListPopupStep<*>, editor: Editor) {
val popup = JBPopupFactory.getInstance().createListPopup(step)
popup.showInBestPositionFor(editor)
}
private fun activateDeviceManagerToolWindow(project: Project) = invokeLater {
ToolWindowManager.getInstance(project).getToolWindow("Device Manager 2")?.activate(null)
}
private fun showOpenedNotification(funSimpleName: String, project: Project, notificationGroup: NotificationGroup) =
notificationGroup
.createNotification(
content = KelpBundle.message("openedNotificationContent", funSimpleName),
type = NotificationType.INFORMATION,
)
.notify(project)
private fun showGeneralError(throwable: Throwable, project: Project) = invokeLater {
Messages.showErrorDialog(
project,
throwable.localizedMessage + "\n" + throwable.stackTraceToString(),
KelpBundle.message("componentOpeningErrorTitle"),
)
}
private fun showNoDSComponentFQN(project: Project, notificationGroup: NotificationGroup) = notificationGroup
.createNotification(
content = KelpBundle.message("noSuchComponentNotificationContent"),
type = NotificationType.ERROR,
)
.notify(project)
private fun showNoSdkError(project: Project, notificationGroup: NotificationGroup) = notificationGroup
.createNotification(
content = KelpBundle.message("noAndroidSdkNotificationContent"),
type = NotificationType.ERROR,
)
.notify(project)
private fun showNoDevicesError(project: Project, notificationGroup: NotificationGroup) = notificationGroup
.createNotification(
title = KelpBundle.message("noRunningDevicesNotificationTitle"),
content = KelpBundle.message("noRunningDevicesNotificationContent"),
type = NotificationType.ERROR,
)
.notify(project)
private companion object {
private const val DS_COMPONENT_FQN_DEEPLINK_PLACEHOLDER = "DS_COMPONENT_FQN_DEEPLINK_PLACEHOLDER"
private const val UNLOCK_SCREEN_COMMAND = "input keyevent 82"
private const val SHELL_TIMEOUT_MS = 6000L
}
}
| 0
|
Kotlin
|
1
| 97
|
7110df10d83afacd2444808ff8525d6fecef2a7a
| 13,868
|
kelp
|
Apache License 2.0
|
composesensors/src/main/java/com/mutualmobile/composesensors/StationaryDetectSensorState.kt
|
mutualmobile
| 618,044,998
| false
| null |
package com.mutualmobile.composesensors
import android.hardware.Sensor
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
/**
* The Stationary Detect sensor ([Sensor.TYPE_STATIONARY_DETECT]) is used to detect whether the
* device is stationary or in motion. This sensor provides a binary output, with a value of either
* false or true, indicating the device's motion state.
*
* For more info, please refer the [Android Documentation Reference](https://developer.android.com/reference/android/hardware/SensorEvent#sensor.type_stationary_detect:)
*
* @param isDeviceStationary Whether the device is stationary or not. Defaults to false.
* @param isAvailable Whether the current device has a heart beat sensor. Defaults to false.
* @param accuracy Accuracy factor of the heart beat sensor. Defaults to 0.
*/
@RequiresApi(Build.VERSION_CODES.N)
@Immutable
class StationaryDetectSensorState internal constructor(
val isDeviceStationary: Boolean = false,
val isAvailable: Boolean = false,
val accuracy: Int = 0,
private val startListeningEvents: (() -> Unit)? = null,
private val stopListeningEvents: (() -> Unit)? = null
) : SensorStateListener {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is StationaryDetectSensorState) return false
if (isDeviceStationary != other.isDeviceStationary) return false
if (isAvailable != other.isAvailable) return false
if (accuracy != other.accuracy) return false
if (startListeningEvents != other.startListeningEvents) return false
if (stopListeningEvents != other.stopListeningEvents) return false
return true
}
override fun hashCode(): Int {
var result = isDeviceStationary.hashCode()
result = 31 * result + isAvailable.hashCode()
result = 31 * result + accuracy.hashCode()
result = 31 * result + startListeningEvents.hashCode()
result = 31 * result + stopListeningEvents.hashCode()
return result
}
override fun toString(): String {
return "StationaryDetectSensorState(isDeviceStationary=$isDeviceStationary," +
" isAvailable=$isAvailable, accuracy=$accuracy)"
}
override fun startListening() {
startListeningEvents?.invoke()
}
override fun stopListening() {
stopListeningEvents?.invoke()
}
}
/**
* Creates and [remember]s an instance of [StationaryDetectSensorState].
* @param autoStart Start listening to sensor events as soon as sensor state is initialised.
* Defaults to true.
* @param sensorDelay The rate at which the raw sensor data should be received.
* Defaults to [SensorDelay.Normal].
* @param onError Callback invoked on every error state.
*/
@RequiresApi(Build.VERSION_CODES.N)
@Composable
fun rememberStationaryDetectSensorState(
autoStart: Boolean = true,
sensorDelay: SensorDelay = SensorDelay.Normal,
onError: (throwable: Throwable) -> Unit = {}
): StationaryDetectSensorState {
val sensorState = rememberSensorState(
sensorType = SensorType.StationaryDetect,
sensorDelay = sensorDelay,
autoStart = autoStart,
onError = onError
)
val confidenceSensorState = remember { mutableStateOf(StationaryDetectSensorState()) }
LaunchedEffect(
key1 = sensorState,
block = {
val sensorStateValues = sensorState.data
if (sensorStateValues.isNotEmpty()) {
confidenceSensorState.value = StationaryDetectSensorState(
isDeviceStationary = sensorStateValues[0] == 1f,
isAvailable = sensorState.isAvailable,
accuracy = sensorState.accuracy,
startListeningEvents = sensorState::startListening,
stopListeningEvents = sensorState::stopListening
)
}
}
)
return confidenceSensorState.value
}
| 3
| null |
7
| 208
|
777b5ab0a8971c8539fba8d72b21401b7e5f7641
| 4,187
|
ComposeSensors
|
Apache License 2.0
|
adapter-out/rdb/src/main/kotlin/com/yapp/bol/terms/TermsAgreeRepository.kt
|
YAPP-Github
| 634,125,780
| false
| null |
package com.yapp.bol.terms
import org.springframework.data.jpa.repository.JpaRepository
internal interface TermsAgreeRepository : JpaRepository<TermsAgreeEntity, Long> {
fun findByUserId(userId: Long): List<TermsAgreeEntity>
fun findByUserIdAndCode(userId: Long, code: TermsCode): TermsAgreeEntity?
}
| 4
|
Kotlin
|
0
| 13
|
9391cc9c45d7446c977517231f367f32ff4c4991
| 312
|
onboard-server
|
Apache License 2.0
|
android/app/src/main/kotlin/io/quang/datingsample/MainActivity.kt
|
quangIO
| 169,837,359
| false
| null |
package io.quang.datingsample
import android.os.Bundle
import android.view.ViewGroup
import android.widget.*
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
import com.mapbox.mapboxsdk.*
import com.mapbox.mapboxsdk.maps.*
import com.mapbox.mapboxsdk.camera.*
import com.mapbox.mapboxsdk.geometry.*
import com.mapbox.mapboxsdk.constants.*
import com.mapbox.mapboxsdk.annotations.*
class MainActivity(): FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
Mapbox.getInstance(this, BuildConfig.MAPBOX_ACCESS_TOKEN)
}
}
| 0
|
Dart
|
24
| 59
|
60e31720c33b2bb8d9255327e66d890de2e99a07
| 679
|
dating-app-concept-flutter
|
MIT License
|
app/src/main/java/app/re_eddit/api/response/topic/TopicPostDataResponse.kt
|
thi-feonir
| 280,704,691
| false
| null |
package app.re_eddit.api.response.topic
import app.re_eddit.core.ext.toDate
import app.re_eddit.domain.entity.Post
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class TopicPostDataResponse(
val title: String? = "",
val subreddit_name_prefixed: String? = "",
val url: String?,
val selftext: String?,
val downs: Int = 0,
val ups: Int = 0,
val num_comments: Int = 0,
val author: String? = "",
val created_utc: Long = 0L,
val created: Long = 0L,
val permalink: String?
)
internal fun TopicPostDataResponse.toDomainLayer() =
Post(
title = title?: "",
subredditNamePrefixed = subreddit_name_prefixed?: "",
body = selftext?: "",
downs = downs.toString(),
ups = ups.toString(),
commentsCount = num_comments.toString(),
postInfo = "u/" + author + " • " + created_utc.toDate(),
url = "$permalink.json",
thumbnail = url,
after = ""
)
| 0
|
Kotlin
|
0
| 0
|
be95572522267db7a38707268f590ae8fd3af920
| 987
|
re-eddit
|
Apache License 2.0
|
openapi-parser/src/test/kotlin/io/openapiparser/model/v3x/OperationSpec.kt
|
openapi-processor
| 418,185,783
| false
|
{"Java": 629502, "Kotlin": 243428, "Just": 441}
|
/*
* Copyright 2021 https://github.com/openapi-processor/openapi-parser
* PDX-License-Identifier: Apache-2.0
*/
package io.openapiparser.model.v3x
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.maps.shouldBeEmpty
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.openapiparser.model.v30.operation as operation30
import io.openapiparser.model.v31.operation as operation31
class OperationSpec: StringSpec({
"gets operation tags" {
operation30("tags: [foo, bar]").tags.shouldContainExactly("foo", "bar")
operation31("tags: [foo, bar]").tags.shouldContainExactly("foo", "bar")
}
"gets operation tags is empty if missing" {
operation30().tags.isEmpty()
operation31().tags.isEmpty()
}
"gets operation summary" {
operation30("summary: a summary").summary shouldBe "a summary"
operation31("summary: a summary").summary shouldBe "a summary"
}
"gets operation summary is null if missing" {
operation30().summary.shouldBeNull()
operation31().summary.shouldBeNull()
}
include(testDescription("operation 30", ::operation30) { it.description })
include(testDescription("operation 31", ::operation30) { it.description })
"gets operation external docs object" {
operation30("externalDocs: {}").externalDocs.shouldNotBeNull()
operation31("externalDocs: {}").externalDocs.shouldNotBeNull()
}
"gets operation external docs object is null if it missing" {
operation30().externalDocs.shouldBeNull()
operation31().externalDocs.shouldBeNull()
}
"gets operation operationId" {
operation30("operationId: anId").operationId shouldBe "anId"
operation31("operationId: anId").operationId shouldBe "anId"
}
"gets operation operationId is null if missing" {
operation30().operationId.shouldBeNull()
operation31().operationId.shouldBeNull()
}
"gets operation parameters" {
val source = """parameters: [{}, {}]"""
operation30(source).parameters.size shouldBe 2
operation31(source).parameters.size shouldBe 2
}
"gets operation parameters is empty if missing" {
operation30().parameters.shouldBeEmpty()
operation31().parameters.shouldBeEmpty()
}
"gets operation requestBody" {
operation30("requestBody: {}").requestBody.shouldNotBeNull()
operation31("requestBody: {}").requestBody.shouldNotBeNull()
}
"gets operation requestBody is null if it missing" {
operation30().requestBody.shouldBeNull()
operation31().requestBody.shouldBeNull()
}
"gets operation callbacks" {
val source = """
callbacks:
foo: {}
bar: {}
"""
val c30 = operation30(source).callbacks
c30.size shouldBe 2
c30["foo"].shouldNotBeNull()
c30["bar"].shouldNotBeNull()
val c31 = operation31(source).callbacks
c31.size shouldBe 2
c31["foo"].shouldNotBeNull()
c31["bar"].shouldNotBeNull()
}
"gets operation callbacks is empty if missing" {
operation30().callbacks.shouldBeEmpty()
operation31().callbacks.shouldBeEmpty()
}
"gets operation deprecated" {
operation30("deprecated: true").deprecated.shouldBeTrue()
operation30("deprecated: false").deprecated.shouldBeFalse()
operation31("deprecated: true").deprecated.shouldBeTrue()
operation31("deprecated: false").deprecated.shouldBeFalse()
}
"gets operation deprecated is false if missing" {
operation30().deprecated.shouldBeFalse()
operation31().deprecated.shouldBeFalse()
}
"gets operation security requirements" {
val s30 = operation30("security: [{}, {}]").security
s30.shouldNotBeNull()
s30.size shouldBe 2
val s31 = operation31("security: [{}, {}]").security
s31.shouldNotBeNull()
s31.size shouldBe 2
}
"gets operation empty security requirements if it is missing" {
operation30().security.shouldBeEmpty()
operation31().security.shouldBeEmpty()
}
"gets server objects" {
val s30 = operation30("servers: [{}, {}]").servers
s30.shouldNotBeNull()
s30.size shouldBe 2
val s31 = operation31("servers: [{}, {}]").servers
s31.shouldNotBeNull()
s31.size shouldBe 2
}
"gets empty server objects if it is missing" {
operation30().servers.shouldBeEmpty()
operation31().servers.shouldBeEmpty()
}
})
| 15
|
Java
|
1
| 12
|
3d17243e662b1bdb5c6a2d7237a117f7a0238c2d
| 4,893
|
openapi-parser
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/reporting/ndmis/ComplexityProcessorTest.kt
|
ministryofjustice
| 312,544,431
| false
| null |
package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.reporting.ndmis
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.Complexity
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.ComplexityLevel
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.reporting.ndmis.performance.ComplexityProcessor
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.ReferralFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.ServiceCategoryFactory
import java.util.UUID
internal class ComplexityProcessorTest {
private val processor = ComplexityProcessor()
private val referralFactory = ReferralFactory()
private val serviceCategoryFactory = ServiceCategoryFactory()
@Test
fun `referral with single selected service category correctly returns a complexityData object`() {
val complexityLevel = ComplexityLevel(UUID.randomUUID(), "high", "description1", Complexity.HIGH)
val serviceCategory1 = serviceCategoryFactory.create(complexityLevels = listOf(complexityLevel))
val referral = referralFactory.createSent(selectedServiceCategories = mutableSetOf(serviceCategory1))
referral.complexityLevelIds = mutableMapOf(serviceCategory1.id to complexityLevel.id)
val result = processor.process(referral)!!
assertThat(result.size).isEqualTo(1)
assertThat(result[0].referralReference).isEqualTo("JS18726AC")
assertThat(result[0].referralId).isEqualTo(referral.id)
assertThat(result[0].interventionTitle).isEqualTo("Sheffield Housing Services")
assertThat(result[0].serviceCategoryId).isEqualTo(serviceCategory1.id)
assertThat(result[0].serviceCategoryName).isEqualTo("accommodation")
assertThat(result[0].complexityLevelTitle).isEqualTo("high")
}
@Test
fun `referral with multiple selected service category correctly returns a complexityData object`() {
val complexityLevel1 = ComplexityLevel(UUID.randomUUID(), "high", "description1", Complexity.HIGH)
val complexityLevel2 = ComplexityLevel(UUID.randomUUID(), "medium", "description1", Complexity.MEDIUM)
val serviceCategory1 = serviceCategoryFactory.create(complexityLevels = listOf(complexityLevel1))
val serviceCategory2 = serviceCategoryFactory.create(name = "Lifestyle and Associates", complexityLevels = listOf(complexityLevel2))
val referral = referralFactory.createSent(selectedServiceCategories = mutableSetOf(serviceCategory1, serviceCategory2))
referral.complexityLevelIds = mutableMapOf(serviceCategory1.id to complexityLevel1.id, serviceCategory2.id to complexityLevel2.id)
val result = processor.process(referral)!!
assertThat(result.size).isEqualTo(2)
assertThat(result[0].referralReference).isEqualTo("JS18726AC")
assertThat(result[0].referralId).isEqualTo(referral.id)
assertThat(result[0].interventionTitle).isEqualTo("Sheffield Housing Services")
assertThat(result[0].serviceCategoryId).isEqualTo(serviceCategory1.id)
assertThat(result[0].serviceCategoryName).isEqualTo("accommodation")
assertThat(result[0].complexityLevelTitle).isEqualTo("high")
assertThat(result[1].referralReference).isEqualTo("JS18726AC")
assertThat(result[1].referralId).isEqualTo(referral.id)
assertThat(result[1].interventionTitle).isEqualTo("Sheffield Housing Services")
assertThat(result[1].serviceCategoryId).isEqualTo(serviceCategory2.id)
assertThat(result[1].serviceCategoryName).isEqualTo("Lifestyle and Associates")
assertThat(result[1].complexityLevelTitle).isEqualTo("medium")
}
}
| 4
|
Kotlin
|
1
| 2
|
256cf1e182f5a9d730a61bacdaee944cbc680c48
| 3,652
|
hmpps-interventions-service
|
MIT License
|
custom-vu/src/main/kotlin/jces1209/vu/page/bars/topBar/dc/DcTopBar.kt
|
wyrzyk
| 240,481,378
| true
|
{"Kotlin": 326577}
|
package jces1209.vu.page.bars.topBar.dc
import jces1209.vu.page.AbstractIssuePage
import jces1209.vu.page.FalliblePage
import jces1209.vu.page.bars.topBar.TopBar
import jces1209.vu.wait
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.support.ui.ExpectedConditions
class DcTopBar(
private val driver: WebDriver
) : TopBar {
private val page = FalliblePage.Builder(
webDriver = driver,
expectedContent = listOf(
By.id("quickSearchInput"),
By.id("filter-projects"),
By.id("projects"),
By.xpath("//*[@data-project-id]")
)
)
.cloudErrors()
.build()
override fun waitForTopBar(): DcTopBar {
page.waitForPageToLoad()
return this
}
override fun quickSearch(issueKey: String): DcTopBar {
Actions(driver)
.sendKeys("/")
.perform()
driver
.wait(
ExpectedConditions.and(
ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[@class='quick-search-section-heading' and contains(text(),'Issues')]")),
ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[@aria-tooltip='View all issues']")),
ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[@aria-tooltip='View all projects']"))
)
)
return this
}
override fun selectItem(issueKey: String): AbstractIssuePage {
TODO("Not yet implemented")
}
}
| 0
|
Kotlin
|
0
| 0
|
6a42116dfd1613dc30df7dacda7f8d2fd8d8096f
| 1,626
|
JCES-1314
|
Apache License 2.0
|
app/src/main/java/pl/sienczykm/templbn/utils/ExternalDisplaysHandler.kt
|
mat-sienczyk
| 193,071,707
| false
| null |
package pl.sienczykm.templbn.utils
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Icon
import android.location.Location
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.WorkerThread
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import pl.sienczykm.templbn.R
import pl.sienczykm.templbn.db.AppDb
import pl.sienczykm.templbn.db.model.AirStationModel
import pl.sienczykm.templbn.db.model.BaseStationModel
import pl.sienczykm.templbn.db.model.WeatherStationModel
import pl.sienczykm.templbn.ui.main.MainActivity
import pl.sienczykm.templbn.ui.station.StationActivity
import pl.sienczykm.templbn.widget.OldWeatherWidget
// TODO refactor this somehow?
object ExternalDisplaysHandler {
fun cancelAllNotifications(context: Context) {
NotificationManagerCompat.from(context).cancelAll()
}
private fun cancelNotification(
context: Context,
notificationId: Int,
) {
NotificationManagerCompat.from(context).cancel(notificationId)
}
private fun sendNotification(
context: Context,
notificationId: Int,
notification: Notification,
) {
if (NotificationManagerCompat.from(context).areNotificationsEnabled()) {
NotificationManagerCompat.from(context).notify(notificationId, notification)
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(
context: Context,
channel: NotificationChannel,
) {
(context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.createNotificationChannel(channel)
}
fun updateExternalDisplays(context: Context) {
setWeatherNotification(context)
updateOldWeatherWidget(context)
}
fun checkAirQuality(context: Context) {
val notificationId = 70
if (context.showAirQualityNotification()) {
CoroutineScope(Dispatchers.IO).launch {
getNearestAirStationId(context)?.let {
val airStation = AppDb.getDatabase(context).airStationDao().getStationById(it)
if (airStation?.airQualityIndex != null && airStation.airQualityIndex!! >= context.getAirQualityLevel()) {
val airChannelId = "air_quality_notification"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
airChannelId,
context.getString(R.string.air_index_notification_channel_name),
NotificationManager.IMPORTANCE_LOW
).apply {
description =
context.getString(R.string.air_index_notification_channel_description)
}
createNotificationChannel(context, channel)
}
val builder = NotificationCompat.Builder(context, airChannelId)
.setContentTitle(airStation.getFullStationName())
.setContentText(context.getString(R.string.air_index_notification_content))
.setContentIntent(MainActivity.openAirPendingIntent(context))
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_app_icon)
sendNotification(context, notificationId, builder.build())
} else {
cancelNotification(context, notificationId)
}
}
cancel()
}
}
}
fun updateOldWeatherWidget(context: Context) {
val widgetUpdateIntent = Intent(context, OldWeatherWidget::class.java).apply {
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
putExtra(
AppWidgetManager.EXTRA_APPWIDGET_IDS,
AppWidgetManager.getInstance(context).getAppWidgetIds(
ComponentName(
context,
OldWeatherWidget::class.java
)
)
)
putExtra(OldWeatherWidget.OLD_KEY, false)
}
context.sendBroadcast(widgetUpdateIntent)
}
fun setWeatherNotification(context: Context) {
val notificationId = 69
if (context.showWeatherNotification()) {
CoroutineScope(Dispatchers.IO).launch {
val weatherStation = getProperWeatherStation(context)
val temperatureString = weatherStation?.getParsedTemperature()?.let {
"$it${context.getString(R.string.celsius_degree)}"
}
val hourString = "${weatherStation?.date?.let { dateFormat("HH:mm").format(it) }}"
val weatherChannelId = "weather_notification"
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
weatherChannelId,
context.getString(R.string.weather_notification_channel_name),
NotificationManager.IMPORTANCE_LOW
).apply {
description =
context.getString(R.string.weather_notification_channel_description)
}
createNotificationChannel(context, channel)
Notification.Builder(context, weatherChannelId)
} else {
Notification.Builder(context) // NotificationCompact do not allow pass Icon via setSmallIcon()
}
.setContentTitle("$temperatureString - $hourString")
.setContentText(weatherStation?.getFullStationName())
.setContentIntent(
if (context.openWeatherStation())
StationActivity.openWeatherStationPendingIntent(
context,
weatherStation?.stationId
)
else
MainActivity.openWeatherPendingIntent(context)
)
.setOngoing(true)
.apply {
temperatureString?.let { text ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.createIconForNotification()) {
setSmallIcon(getNotificationIcon(text, context))
} else {
setSmallIcon(R.drawable.ic_temperature)
}
} ?: setSmallIcon(R.drawable.ic_temperature)
}
sendNotification(context, notificationId, builder.build())
cancel()
}
} else {
cancelNotification(context, notificationId)
}
}
@RequiresApi(Build.VERSION_CODES.M)
fun getNotificationIcon(text: String, context: Context): Icon = Icon.createWithBitmap(
drawTextOnBitmap(
context = context,
width = 28,
height = 28,
textXScale = 1.03f - (text.length * 0.1f),
textSize = 22,
scalable = true,
text = text
)
)
@WorkerThread
fun getProperWeatherStation(context: Context) =
AppDb.getDatabase(context).weatherStationDao()
.getStationById(getProperWeatherStationId(context))
.let { station ->
if (station?.isDateObsoleteOrNull() == false) station
else //TODO find next closest station with valid data?
AppDb.getDatabase(context).weatherStationDao()
.getStationById(context.getDefaultWeatherStationId())
}
private fun getProperWeatherStationId(context: Context): Int {
val defaultStationId = context.getDefaultWeatherStationId()
return if (context.useLocationToUpdateWeather()) {
context.getLastKnownLocation()?.let { getNearestWeatherStationId(it) }
?: defaultStationId
} else {
defaultStationId
}
}
private fun getNearestAirStationId(context: Context): Int? {
val nearestStation = context.getLastKnownLocation()?.let {
AirStationModel.getAllStations()
.minWithOrNull(distanceComparator(it)) // since AirStationModel.getStations() is list of static objects, minWithOrNull will never returns null
} ?: return null
// distance is not null if we run distanceComparator()
return if (nearestStation.distance!! <= 10) { // TODO: move this 10 km into options perhaps?
nearestStation.stationId
} else null
}
private fun getNearestWeatherStationId(location: Location): Int =
WeatherStationModel.getAllStations()
.minWithOrNull(distanceComparator(location))!!.stationId // since WeatherStationModel.getStations() is list of static objects, minWithOrNull will never returns null
private fun distanceComparator(it: Location): Comparator<BaseStationModel> {
return Comparator { station1, station2 ->
station1.distance =
haversine(
it.latitude,
it.longitude,
station1.latitude,
station1.longitude
)
station2.distance =
haversine(
it.latitude,
it.longitude,
station2.latitude,
station2.longitude
)
if (station1.distance!! > station2.distance!!) 1 else 0
}
}
}
| 0
|
Kotlin
|
1
| 2
|
d3fff36942a72981ab8ba93865426b44029eb365
| 10,388
|
LubelskieStacjePogodowe
|
Apache License 2.0
|
app/src/main/java/com/example/alexmelnikov/coinspace/ui/statistics/StatisticsPresenter.kt
|
vovaksenov99
| 143,032,036
| true
|
{"Kotlin": 193222}
|
package com.example.alexmelnikov.coinspace.ui.statistics
import android.util.Log
import com.example.alexmelnikov.coinspace.BaseApp
import com.example.alexmelnikov.coinspace.model.entities.Account
import com.example.alexmelnikov.coinspace.model.entities.OperationType
import com.example.alexmelnikov.coinspace.model.getCategoryByString
import com.example.alexmelnikov.coinspace.model.getCurrencyByString
import com.example.alexmelnikov.coinspace.model.interactors.CurrencyConverter
import com.example.alexmelnikov.coinspace.model.interactors.IUserBalanceInteractor
import com.example.alexmelnikov.coinspace.model.interactors.Money
import com.example.alexmelnikov.coinspace.model.repositories.AccountsRepository
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class StatisticsPresenter : StatisticsContract.Presenter {
private lateinit var view: StatisticsContract.View
@Inject
lateinit var accountsRepository: AccountsRepository
@Inject
lateinit var userBalanceInteractor: IUserBalanceInteractor
@Inject
lateinit var currencyConverter: CurrencyConverter
private var accounts: List<Account> = ArrayList()
override fun attach(view: StatisticsContract.View) {
this.view = view
BaseApp.instance.component.inject(this)
}
override fun chartDataRequest() {
accountsDataRequest()
}
private fun accountsDataRequest() {
accountsRepository.getAccountsOffline()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ accountsList -> handleSuccessAccountsRequest(accountsList) },
{ handleErrorAccountsRequest() })
}
private fun handleSuccessAccountsRequest(accounts: List<Account>) {
this.accounts = accounts
updateCategoryChart()
}
private fun handleErrorAccountsRequest() {
Log.d("mytag", "cant't get data from db")
}
private fun updateCategoryChart() {
val chartEntries: ArrayList<PieEntry> = ArrayList()
val categorySums: HashMap<String, Float> = HashMap()
var operationSum = 0f
var overallSum = 0f
val mainCurrency = userBalanceInteractor.getUserBalance().currency
accounts.forEach {
it.operations.forEach {
val from = view.getFromDate().time.time
val to = view.getToDate().time.time
if (it.date in from..to) {
if (it.type == OperationType.EXPENSE.toString()) {
operationSum = currencyConverter.convertCurrency(Money(it.sum,
getCurrencyByString(it.currency)), mainCurrency).count
overallSum += operationSum
if (!categorySums.contains(it.category)) {
categorySums[it.category] = operationSum
}
else {
var prevSum = categorySums[it.category]!!
prevSum += operationSum
categorySums[it.category] = prevSum
}
}
}
}
}
categorySums.forEach {
val name = BaseApp.instance.getString(getCategoryByString(it.key).getStringResource())
chartEntries.add(PieEntry(it.value, name))
}
val dataSet = PieDataSet(chartEntries, "")
view.setupChartData(dataSet)
}
}
| 0
|
Kotlin
|
0
| 0
|
6907306ad96bac7e47588e8237cd1f6d5986fb8b
| 3,679
|
CoinSpace
|
MIT License
|
SocialDistance/src/main/java/tw/gov/cdc/exposurenotifications/common/PreferenceManager.kt
|
ailabstw
| 378,797,655
| false
| null |
package tw.gov.cdc.exposurenotifications.common
import android.content.Context
import androidx.core.content.edit
import tw.gov.cdc.exposurenotifications.BaseApplication
import java.util.*
object PreferenceManager {
private const val PREF_NAME = "PREF_NAME_TW_CDC_EN"
private const val PREF_KEY_FIRST_LAUNCH_TIME = "PREF_KEY_FIRST_LAUNCH_TIME"
private const val PREF_KEY_ACCUMULATED_DISABLE_TIME = "PREF_KEY_ACCUMULATED_DISABLE_TIME"
private const val PREF_KEY_LAST_DISABLE_TIME = "PREF_KEY_LAST_DISABLE_TIME"
private const val PREF_KEY_LAST_CHECK_TIME = "PREF_KEY_LAST_CHECK_TIME"
private const val PREF_KEY_LAST_ENTER_MAIN_PAGE_TIME = "PREF_KEY_LAST_ENTER_MAIN_PAGE_TIME"
private const val PREF_KEY_REVISION_TOKEN = "PREF_KEY_REVISION_TOKEN"
private const val PREF_KEY_MOST_RECENT_SUCCESSFUL_DOWNLOAD = "PREF_KEY_MOST_RECENT_SUCCESSFUL_DOWNLOAD"
private const val PREF_KEY_SAFE_SUMMARY = "PREF_KEY_SAFE_SUMMARY"
private const val PREF_KEY_NOT_FOUND_NOTIFICATION_TIME = "PREF_KEY_NOT_FOUND_NOTIFICATION_TIME"
private const val PREF_KEY_STATE_UPDATED_NOTIFICATION_TIME = "PREF_KEY_STATE_UPDATED_NOTIFICATION_TIME"
private const val PREF_KEY_PRESENTED_FEATURES = "PREF_KEY_INTRODUCTION_HISTORY"
private val sharedPreferences =
BaseApplication.instance.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
var lastEnterMainPageTime: Long
get() {
return sharedPreferences.getLong(PREF_KEY_LAST_ENTER_MAIN_PAGE_TIME, 0L)
}
set(value) {
sharedPreferences.edit {
putLong(PREF_KEY_LAST_ENTER_MAIN_PAGE_TIME, value)
}
}
var lastStateUpdatedNotificationTime: Long
get() {
return sharedPreferences.getLong(PREF_KEY_STATE_UPDATED_NOTIFICATION_TIME, Long.MAX_VALUE)
}
set(value) {
sharedPreferences.edit {
putLong(PREF_KEY_STATE_UPDATED_NOTIFICATION_TIME, value)
}
}
var lastNotFoundNotificationTime: Long
get() {
return sharedPreferences.getLong(PREF_KEY_NOT_FOUND_NOTIFICATION_TIME, 0L)
}
set(value) {
sharedPreferences.edit {
putLong(PREF_KEY_NOT_FOUND_NOTIFICATION_TIME, value)
}
}
var lastCheckTime: Long
get() {
return sharedPreferences.getLong(PREF_KEY_LAST_CHECK_TIME, 0L)
}
set(value) {
sharedPreferences.edit {
putLong(PREF_KEY_LAST_CHECK_TIME, value)
}
}
var revisionToken: String
get() {
return sharedPreferences.getString(PREF_KEY_REVISION_TOKEN, "") ?: ""
}
set(value) {
sharedPreferences.edit {
putString(PREF_KEY_REVISION_TOKEN, value)
}
}
var mostRecentSuccessfulDownload: String
get() {
return sharedPreferences.getString(PREF_KEY_MOST_RECENT_SUCCESSFUL_DOWNLOAD, "") ?: ""
}
set(value) {
sharedPreferences.edit {
putString(PREF_KEY_MOST_RECENT_SUCCESSFUL_DOWNLOAD, value)
}
}
val isFirstTimeEnableNeeded: Boolean
get() {
return firstEnabledTime == 0L
}
var firstEnabledTime: Long
get() {
return sharedPreferences.getLong(PREF_KEY_FIRST_LAUNCH_TIME, 0L)
}
set(value) {
if (isFirstTimeEnableNeeded) {
sharedPreferences.edit {
putLong(PREF_KEY_FIRST_LAUNCH_TIME, value)
}
}
}
var lastDisableTime: Long
get() {
return sharedPreferences.getLong(PREF_KEY_LAST_DISABLE_TIME, 0L)
}
set(value) {
if (lastDisableTime == 0L) {
sharedPreferences.edit {
putLong(PREF_KEY_LAST_DISABLE_TIME, value)
}
}
}
var accumulatedDisableTime: Long
get() {
val currentDisableDurationTime = if (lastDisableTime == 0L) {
0L
} else {
Date().time - maxOf(lastDisableTime, firstEnabledTime)
}
return currentDisableDurationTime +
sharedPreferences.getLong(PREF_KEY_ACCUMULATED_DISABLE_TIME, 0L)
}
private set(value) {
sharedPreferences.edit {
putLong(PREF_KEY_ACCUMULATED_DISABLE_TIME, value)
}
}
fun clearLastDisableTime() {
val nowTime = Date().time
firstEnabledTime = nowTime
if (lastDisableTime != 0L) {
accumulatedDisableTime = nowTime - maxOf(lastDisableTime, firstEnabledTime) +
// Don't use accumulatedDisableTime directly
sharedPreferences.getLong(PREF_KEY_ACCUMULATED_DISABLE_TIME, 0L)
sharedPreferences.edit {
putLong(PREF_KEY_LAST_DISABLE_TIME, 0L)
}
}
}
var safeSummaries: Map<DaysSinceEpoch, WeightedDurationSum>
get() {
return sharedPreferences.getStringSet(PREF_KEY_SAFE_SUMMARY, setOf())?.map {
val data = it.split(",")
data[0].toInt() to data[1].toDouble()
}?.toMap() ?: mapOf()
}
set(value) {
sharedPreferences.edit {
putStringSet(PREF_KEY_SAFE_SUMMARY, value.map {
"${it.key},${it.value}"
}.toSet())
}
}
var presentedFeatures: Set<String>
get() {
return sharedPreferences.getStringSet(PREF_KEY_PRESENTED_FEATURES, setOf())!!.toSet()
}
set(value) {
sharedPreferences.edit {
putStringSet(PREF_KEY_PRESENTED_FEATURES, value)
}
}
}
typealias DaysSinceEpoch = Int
typealias WeightedDurationSum = Double
| 9
|
Kotlin
|
51
| 62
|
e34f11f8ea3c9e08d33c82c1b001590381ea4749
| 5,980
|
social-distancing-android
|
MIT License
|
app/src/main/java/com/bossed/waej/javebean/VinSearchBean.kt
|
Ltow
| 710,230,789
| false
|
{"Kotlin": 2304560, "Java": 395495, "HTML": 71364}
|
package com.bossed.waej.javebean
import com.google.gson.annotations.SerializedName
data class VinSearchBean(
@SerializedName("content")
val content: String,
@SerializedName("name")
val name: String
)
| 0
|
Kotlin
|
0
| 0
|
8c2e9928f6c47484bec7a5beca32ed4b10200f9c
| 217
|
wananexiu
|
Mulan Permissive Software License, Version 2
|
MobileLoggingSdk/MobileSdk/src/main/java/com/ivoafsilva/mobiweb/mobilesdk/network/model/RequestBody.kt
|
iafsilva
| 847,307,039
| false
|
{"Kotlin": 34845}
|
package com.ivoafsilva.mobiweb.mobilesdk.network.model
import com.google.gson.annotations.SerializedName
internal data class RequestBody(
@SerializedName("myString")
val myString: String
)
| 0
|
Kotlin
|
0
| 1
|
0d7ec1185f3a4dc0c339f4c343bc98e9b080db90
| 198
|
mobiweb-challenge
|
MIT License
|
bot/connector-messenger/src/main/kotlin/model/send/Element.kt
|
theopenconversationkit
| 84,538,053
| false
| null |
/*
* Copyright (C) 2017/2020 e-voyageurs technologies
*
* 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 ai.tock.bot.connector.messenger.model.send
import ai.tock.bot.engine.action.SendAttachment.AttachmentType.image
import ai.tock.bot.engine.message.GenericElement
import ai.tock.shared.mapNotNullValues
import ai.tock.shared.security.StringObfuscatorMode
import ai.tock.shared.security.TockObfuscatorService.obfuscate
import com.fasterxml.jackson.annotation.JsonProperty
/**
* List or generic template subElements.
*/
data class Element(val title: String,
@JsonProperty("image_url") val imageUrl: String? = null,
val subtitle: String? = null,
val buttons: List<Button>? = null) {
internal constructor(
title: CharSequence,
subtitle: CharSequence?,
imageUrl: String?,
buttons: List<Button>?
) : this(title.toString(), imageUrl, subtitle?.toString(), buttons?.takeUnless { it.isEmpty() })
fun toGenericElement(): GenericElement {
return GenericElement(
choices = buttons?.map { it.toChoice() } ?: emptyList(),
texts = mapNotNullValues(
Element::title.name to title,
Element::subtitle.name to subtitle
),
attachments = imageUrl
?.let { listOf(ai.tock.bot.engine.message.Attachment(imageUrl, image)) }
?: emptyList()
)
}
fun obfuscate(mode: StringObfuscatorMode): Element {
return Element(obfuscate(title, mode)!!, imageUrl, obfuscate(subtitle, mode), buttons)
}
}
| 163
| null |
127
| 475
|
890f69960997ae9146747d082d808d92ee407fcb
| 2,135
|
tock
|
Apache License 2.0
|
compensation/wow-compensation-domain/src/main/kotlin/me/ahoo/wow/compensation/domain/FindNextRetry.kt
|
Ahoo-Wang
| 628,167,080
| false
|
{"Kotlin": 1902621, "Java": 34050, "TypeScript": 31834, "HTML": 11619, "Lua": 3978, "JavaScript": 2288, "Dockerfile": 820, "SCSS": 500, "Less": 342}
|
/*
* Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].
* 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 me.ahoo.wow.compensation.domain
import me.ahoo.wow.compensation.api.IExecutionFailedState
import reactor.core.publisher.Flux
interface FindNextRetry {
/**
* @see IExecutionFailedState.canNextRetry
*/
fun findNextRetry(limit: Int = 10): Flux<out IExecutionFailedState>
}
| 6
|
Kotlin
|
10
| 98
|
eed438bab2ae009edf3a1db03396de402885c681
| 946
|
Wow
|
Apache License 2.0
|
app/src/main/java/com/qingmei2/sample/http/service/UserService.kt
|
ngima
| 234,334,329
| false
| null |
package com.qingmei2.sample.http.service
import com.qingmei2.sample.entity.ReceivedEvent
import com.qingmei2.sample.entity.Repo
import com.qingmei2.sample.entity.UserInfo
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface UserService {
@GET("user")
suspend fun fetchUserOwner(): Response<UserInfo>
@GET("users/{username}/received_events?")
suspend fun queryReceivedEvents(@Path("username") username: String,
@Query("page") pageIndex: Int,
@Query("per_page") perPage: Int): Response<List<ReceivedEvent>>
@GET("users/{username}/repos?")
suspend fun queryRepos(@Path("username") username: String,
@Query("page") pageIndex: Int,
@Query("per_page") perPage: Int,
@Query("sort") sort: String): Response<List<Repo>>
}
| 1
| null |
1
| 1
|
da57f583c1cedd860b7c6abc39092413c133c245
| 918
|
MVVM-Architecture
|
Apache License 2.0
|
embrace-android-sdk/src/main/java/io/embrace/android/embracesdk/internal/utils/StreamUtils.kt
|
embrace-io
| 704,537,857
| false
|
{"Kotlin": 2867942, "C": 190133, "Java": 177132, "C++": 13140, "CMake": 4261}
|
package io.embrace.android.embracesdk.internal.utils
/**
* Backwards compatibility streaming for Java, implemented via Kotlin.
*/
internal inline fun <T> stream(
collection: Collection<T>,
function: (T) -> Unit
) = collection.toList().forEach(function)
/**
* Backwards compatibility filtering for Java, implemented via Kotlin.
*/
internal inline fun <T> filter(
collection: Collection<T>,
function: (T) -> Boolean
) = collection.toList().filter(function)
/**
* Backwards compatibility mapping for Java, implemented via Kotlin.
*/
internal inline fun <T, R> map(
collection: Collection<T>,
function: (T) -> R
) = collection.toList().map(function)
| 16
|
Kotlin
|
7
| 133
|
a7d76f379f1e190c0deaddbb783d63ac953fd1df
| 679
|
embrace-android-sdk
|
Apache License 2.0
|
API/src/main/kotlin/uk/tldcode/extraterrestrialprobemachine/api/utils/Plurality.kt
|
Thelonedevil
| 83,298,868
| false
|
{"Maven POM": 9, "Text": 1, "Ignore List": 1, "YAML": 1, "Kotlin": 13, "HTML": 1, "Java": 1, "Scala": 1}
|
package uk.tldcode.extraterrestrialprobemachine.api.utils
enum class Plurality {
Singular,
Plural,
CouldBeEither
}
| 1
| null |
1
| 1
|
c4da69518d716b744c71e618341096562b5190dc
| 127
|
Extra-Terrestrial-Probe-Machine
|
Apache License 2.0
|
commonMain/src/mock/java/com/rayliu/commonmain/di/DataModule.kt
|
YuanLiou
| 111,275,765
| false
|
{"Kotlin": 249032, "Shell": 1384}
|
package com.rayliu.commonmain.di
import com.rayliu.commonmain.data.BookSearchApi
import com.rayliu.commonmain.data.api.BookSearchService
import kotlinx.serialization.json.Json
import org.koin.android.ext.koin.androidApplication
import org.koin.dsl.module
val dataModule = module {
// Provide: BookSearchService
factory<BookSearchService> {
BookSearchApi(
androidApplication().assets,
get<Json>()
)
}
}
| 0
|
Kotlin
|
4
| 40
|
d767ad0d5b778b14fc68809e265bec5633b2aaed
| 457
|
TaiwanEbookSearch
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/spreadsheet/LockoutMovesSheet.kt
|
uk-gov-mirror
| 356,783,334
| true
|
{"Kotlin": 428549, "HTML": 83335, "CSS": 12598, "Shell": 6092, "Mustache": 4485, "Dockerfile": 945}
|
package uk.gov.justice.digital.hmpps.pecs.jpc.spreadsheet
import org.apache.poi.ss.usermodel.Workbook
import uk.gov.justice.digital.hmpps.pecs.jpc.move.Move
class LockoutMovesSheet(workbook: Workbook, header: Header) : PriceSheet(workbook.getSheet("Lockouts")!!, header) {
override fun writeMove(move: Move) {
writeMoveRow(move)
writeJourneyRows(move.journeys)
}
}
| 0
|
Kotlin
|
0
| 0
|
448660ac4b18cc4c8cf3c137a902ed7a99a9fff4
| 380
|
ministryofjustice.calculate-journey-variable-payments
|
MIT License
|
app/src/test/java/reach52/marketplace/community/persistence/logistic_resident/LogisticResidentMapperTestSuite.kt
|
reach52
| 422,514,975
| false
|
{"Kotlin": 1436380, "Java": 18303}
|
package reach52.marketplace.community.persistence.logistic_resident
import org.junit.runner.RunWith
import org.junit.runners.Suite
@RunWith(Suite::class)
@Suite.SuiteClasses(
CreatedByTest::class,
LogisticResidentTest::class
)
class LogisticResidentMapperTestSuite
| 0
|
Kotlin
|
0
| 0
|
629c52368d06f978f19238d0bd865f4ef84c23d8
| 283
|
Marketplace-Community-Edition
|
MIT License
|
kiwi-core/src/commonTest/kotlin/org/fromsource/kiwi/core/bool/BooleanShouldTest.kt
|
from-source
| 215,532,120
| false
| null |
package org.fromsource.kiwi.core.bool
import org.fromsource.kiwi.core.should
import kotlin.test.Test
internal class BooleanShouldTest {
@Test
fun `should guarantee true is equal to true`() {
true.should.beEqual(true)
}
@Test
fun `should guarantee false is equal to false`() {
false.should.beEqual(false)
}
@Test
fun `should fail when true is not equal to false`() {
runCatching {
true.should.beEqual(false)
}.should
.beFailure(AssertionError::class)
.haveFailureMessage("true should == false")
}
@Test
fun `should fail when false is not equal to true`() {
runCatching {
false.should.beEqual(true)
}.should
.beFailure(AssertionError::class)
.haveFailureMessage("false should == true")
}
@Test
fun `should guarantee true is true`() {
true.should.beTrue()
}
@Test
fun `should guarantee false is false`() {
false.should.beFalse()
}
@Test
fun `should fail when false is not true`() {
runCatching {
false.should.beTrue()
}.should
.beFailure(AssertionError::class)
.haveFailureMessage("false should == true")
}
@Test
fun `should guarantee true should be true`() {
true.should be true
}
}
| 5
|
Kotlin
|
2
| 17
|
f984d09af9aff043793ade2187330645d3be16c3
| 1,382
|
kiwi
|
MIT License
|
kotlin-electron/src/jsMain/generated/electron/core/ProgressBarOptionsMode.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11691809, "JavaScript": 168519}
|
package electron.core
@Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
@JsName("""(/*union*/{none: 'none', normal: 'normal', indeterminate: 'indeterminate', error: 'error', paused: 'paused'}/*union*/)""")
sealed external interface ProgressBarOptionsMode {
companion object {
val none: ProgressBarOptionsMode
val normal: ProgressBarOptionsMode
val indeterminate: ProgressBarOptionsMode
val error: ProgressBarOptionsMode
val paused: ProgressBarOptionsMode
}
}
| 32
|
Kotlin
|
174
| 1,252
|
8f788651776064a30ce1688160b7ef9c314a6fe9
| 549
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/ar/edu/unq/pds03backend/service/impl/PasswordService.kt
|
cassa10
| 478,695,193
| false
|
{"Kotlin": 387344, "Shell": 2326, "Dockerfile": 168}
|
package ar.edu.unq.pds03backend.service.impl
import ar.edu.unq.pds03backend.service.IPasswordService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import java.util.*
@Service
class PasswordService(
@Autowired private val passwordEncoder: PasswordEncoder,
): IPasswordService {
companion object {
private const val PASSWORD_SIZE = 8
}
override fun encryptPassword(password: String): String =
passwordEncoder.encode(password)
override fun matches(plainPassword: String, password: String): Boolean =
passwordEncoder.matches(plainPassword, password)
override fun generatePassword(): String {
val charSet = "0123456789!abcdefghijkl)%&mnopqrstuvwxyz#ABCDEFGHIJKLMNOPQRSTUVWXYZ=(+-_"
val random = Random(System.nanoTime())
val password = StringBuilder()
for (i in 0 until PASSWORD_SIZE) {
val ranIndex = random.nextInt(charSet.length)
password.append(charSet[ranIndex])
}
return password.toString()
}
}
| 0
|
Kotlin
|
1
| 0
|
2e61373e3b06ba75399dc429683eec6281f405e9
| 1,157
|
pds03-backend
|
MIT License
|
src/main/kotlin/com/cosmic_jewelry/common/world/level/block/BuriedGemBlock.kt
|
AugustoMegener
| 807,287,719
| false
|
{"Kotlin": 53321}
|
package com.cosmic_jewelry.common.world.level.block
import net.minecraft.core.BlockPos
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.EntityBlock
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.state.BlockState
class BuriedGemBlock(properties: Properties) : Block(properties), EntityBlock {
override fun newBlockEntity(pPos: BlockPos, pState: BlockState): BlockEntity? {
TODO("Not yet implemented")
}
}
| 0
|
Kotlin
|
0
| 0
|
c652ad67ced1456ab1c553a8f378f64c5d8346ba
| 506
|
cosmicjewlery
|
MIT License
|
domain/src/main/java/com/example/moviedatabase/domain/usecase/movie/GetGenresUseCase.kt
|
hungan1409
| 490,214,907
| false
|
{"Kotlin": 165975, "Java": 16338}
|
package com.example.moviedatabase.domain.usecase.movie
import com.example.moviedatabase.domain.model.EmptyParams
import com.example.moviedatabase.domain.model.Genre
import com.example.moviedatabase.domain.repository.MovieRepository
import com.example.moviedatabase.domain.usecase.UseCase
import javax.inject.Inject
class GetGenresUseCase @Inject constructor(
private val movieRepository: MovieRepository
) : UseCase<EmptyParams, List<Genre>>() {
override suspend fun createObservable(params: EmptyParams?): List<Genre> {
return movieRepository.getMovieGenres()
}
}
| 0
|
Kotlin
|
1
| 2
|
b682fdc811b43e794a261e01eeb99ad6cfebab31
| 588
|
The-Movie-Database-Clean-Architecture-v2
|
Apache License 2.0
|
android-example/src/main/kotlin/org/rewedigital/katana/android/example/main/view/MainActivity.kt
|
rewe-digital-incubator
| 155,181,363
| false
| null |
package org.rewedigital.katana.android.example.main.view
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import org.rewedigital.katana.KatanaTrait
import org.rewedigital.katana.android.example.KatanaApp
import org.rewedigital.katana.android.example.R
import org.rewedigital.katana.android.example.main.Modules
import org.rewedigital.katana.android.example.main.createMainModule
import org.rewedigital.katana.android.example.main.presenter.MainPresenter
import org.rewedigital.katana.android.modules.createActivityModule
import org.rewedigital.katana.createComponent
import org.rewedigital.katana.inject
class MainActivity : AppCompatActivity(),
KatanaTrait,
MainView {
// Component is created and referenced only from this Activity
override val component = createComponent(
modules = listOf(createActivityModule(this), createMainModule(this)) + Modules.modules,
dependsOn = listOf(KatanaApp.applicationComponent)
)
private val presenter: MainPresenter by inject()
private var dialog: AlertDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.remoteButton).setOnClickListener { presenter.onRemoteButtonClick() }
findViewById<Button>(R.id.exitButton).setOnClickListener { presenter.onExitButtonClick() }
presenter.onCreate()
}
override fun onDestroy() {
presenter.onDestroy()
dialog?.dismiss()
super.onDestroy()
}
override fun addButton(id: String, label: String) {
findViewById<ViewGroup>(R.id.rootView).let { root ->
val button = Button(this).apply {
text = label
setOnClickListener {
presenter.onButtonClick(id)
}
}
root.addView(button, 0)
}
}
override fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
override fun showDialog() {
dialog = AlertDialog.Builder(this)
.setView(R.layout.dialog_remote)
.setPositiveButton(android.R.string.ok) { _, _ -> presenter.onDialogOkClick() }
.setOnDismissListener { dialog = null }
.show()
}
override fun setDialogResult(result: String) {
dialog?.let { dlg ->
dlg.findViewById<ProgressBar>(R.id.progressBar)?.visibility = View.GONE
dlg.findViewById<TextView>(R.id.textView)?.let { textView ->
textView.text = result
textView.visibility = View.VISIBLE
}
}
}
override fun dismissDialog() {
dialog?.dismiss()
}
}
| 1
| null |
9
| 183
|
4c55f29f793a35f77dff96ede2204fde12fc1cb4
| 3,036
|
katana
|
MIT License
|
integration/common/taskpool-sender/src/main/kotlin/io/holunda/camunda/taskpool/EnableTaskpoolSender.kt
|
margue
| 384,111,593
| true
|
{"Kotlin": 647631}
|
package io.holunda.camunda.taskpool
import io.holunda.camunda.taskpool.sender.SenderConfiguration
import org.springframework.context.annotation.Import
/**
* Enables the taskpool sender.
*/
@MustBeDocumented
@Import(SenderConfiguration::class)
annotation class EnableTaskpoolSender
| 0
| null |
0
| 0
|
d5797861e5d7126dcdfd5e5b9cca8478f887cf68
| 285
|
camunda-bpm-taskpool
|
Apache License 2.0
|
clef-workflow-api/clef-workflow-api-usecase/clef-workflow-api-usecase-workflow/src/main/java/io/arkitik/clef/workflow/api/usecase/workflow/main/EnableWorkflowUseCase.kt
|
arkitik
| 443,436,455
| false
|
{"Kotlin": 433170, "Shell": 268, "Dockerfile": 244}
|
package io.arkitik.clef.workflow.api.usecase.workflow.main
import io.arkitik.clef.workflow.api.common.error.WorkflowResponses
import io.arkitik.clef.workflow.api.common.response.SharedResponse
import io.arkitik.clef.workflow.api.domain.shared.embedded.IdentityStatus
import io.arkitik.clef.workflow.api.function.shared.IdentityStatusValidation
import io.arkitik.clef.workflow.api.store.workflow.WorkflowStore
import io.arkitik.clef.workflow.api.usecase.factory.domain.WorkflowDomainUseCaseFactory
import io.arkitik.clef.workflow.api.usecase.factory.domain.request.FindDomainByKeyRequest
import io.arkitik.clef.workflow.api.usecase.factory.workflow.request.workflow.WorkflowRequest
import io.arkitik.radix.develop.store.storeUpdater
import io.arkitik.radix.develop.usecase.functional
import io.arkitik.radix.develop.usecase.process
import io.arkitik.radix.develop.usecase.validation.functional.ValidationFunctionalUseCase
/**
* Created By [**<NAME> **](https://www.linkedin.com/in/iloom/)<br></br>
* Created At **14**, **Sat Mar, 2020**
* Project **clef-workflow** [arkitik.IO](https://arkitik.io/)<br></br>
*/
class DisableWorkflowUseCase(
private val workflowStore: WorkflowStore,
private val identityStatusValidation: IdentityStatusValidation,
private val workflowDomainUseCaseFactory: WorkflowDomainUseCaseFactory,
) : ValidationFunctionalUseCase<WorkflowRequest, SharedResponse>() {
override fun WorkflowRequest.doProcess(): SharedResponse {
val workflow = workflowDomainUseCaseFactory.functional {
findWorkflowByKeyUseCase
}.process(FindDomainByKeyRequest(workflowKey, false)).response
workflow.identityStatus.validate()
with(workflowStore) {
storeUpdater(workflow.identityUpdater()) {
disable()
update()
}.save()
}
return WorkflowResponses.WORKFLOW_DISABLED_SUCCESS
}
private fun IdentityStatus.validate() {
identityStatusValidation.run {
validate(IdentityStatus.DISABLED)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
785e1b4ee583b6a6e3ea01e656eecd8365f171ef
| 2,066
|
clef-workflow
|
Apache License 2.0
|
jvm-debugger/test/testData/continuation/suspendFunWithInner.kt
|
JetBrains
| 278,369,660
| false
| null |
package continuation
// ATTACH_LIBRARY: maven(org.jetbrains.kotlinx:kotlinx-coroutines-debug:1.3.8)-javaagent
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
fun main() {
val mainTestVal = ""
runBlocking {
val rootCoroutineVal = mainTestVal
TestSuspendA().a()
print(rootCoroutineVal)
}
}
class TestSuspendA {
val classField = ""
suspend fun a() {
val methodVal = ""
InClassB().b()
print(methodVal)
}
class InClassB {
val inClassBField = ""
suspend fun b() {
val inClassBMethodVal = ""
InClassC().c()
print(inClassBMethodVal)
}
inner class InClassC {
val inClassCField = inClassBField
suspend fun c() {
yield()
val inClassCMethodVal = ""
//Breakpoint!
print(inClassCMethodVal)
}
}
}
}
| 284
| null |
5162
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 969
|
intellij-kotlin
|
Apache License 2.0
|
common/auth/src/main/kotlin/no/nav/amt/tiltak/common/auth/AuthService.kt
|
navikt
| 393,356,849
| false
|
{"Kotlin": 763267, "PLpgSQL": 635, "Dockerfile": 160}
|
package no.nav.amt.tiltak.common.auth
import no.nav.amt.tiltak.core.exceptions.NotAuthenticatedException
import no.nav.security.token.support.core.context.TokenValidationContextHolder
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException
import java.util.*
@Service
open class AuthService(
private val tokenValidationContextHolder: TokenValidationContextHolder
) {
@Value("\${ad_gruppe_tilgang_til_egne_ansatte}")
lateinit var tilgangTilNavAnsattGroupId: String
@Value("\${ad_gruppe_tiltak_ansvarlig}")
lateinit var tiltakAnsvarligGroupId: String
@Value("\${ad_gruppe_endringsmelding}")
lateinit var endringsmeldingGroupId: String
open fun hentPersonligIdentTilInnloggetBruker(): String {
val context = tokenValidationContextHolder.tokenValidationContext
val token = context.firstValidToken.orElseThrow {
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "User is not authorized, valid token is missing")
}
return token.jwtTokenClaims["pid"]?.toString() ?: throw ResponseStatusException(
HttpStatus.UNAUTHORIZED,
"PID is missing or is not a string"
)
}
open fun hentNavIdentTilInnloggetBruker(): String = tokenValidationContextHolder
.tokenValidationContext
.getClaims(Issuer.AZURE_AD)
.get("NAVident")
?.toString()
?: throw NotAuthenticatedException("NAV ident is missing")
open fun harTilgangTilSkjermedePersoner() = harTilgangTilADGruppe(tilgangTilNavAnsattGroupId)
open fun harTilgangTilTiltaksansvarligflate() = harTilgangTilADGruppe(tiltakAnsvarligGroupId)
open fun harTilgangTilEndringsmeldinger() = harTilgangTilADGruppe(endringsmeldingGroupId)
open fun hentAzureIdTilInnloggetBruker(): UUID = tokenValidationContextHolder
.tokenValidationContext
.getClaims(Issuer.AZURE_AD)
.getStringClaim("oid").let { UUID.fromString(it) }
?: throw ResponseStatusException(
HttpStatus.UNAUTHORIZED,
"oid is missing"
)
fun hentAdGrupperTilInnloggetBruker(): List<AdGruppe> = tokenValidationContextHolder
.tokenValidationContext
.getClaims(Issuer.AZURE_AD)
.getAsList("groups")
.mapNotNull(this::mapIdTilAdGruppe)
private fun harTilgangTilADGruppe(id: String): Boolean = tokenValidationContextHolder
.tokenValidationContext
.getClaims(Issuer.AZURE_AD)
.getAsList("groups")
.let { groups -> groups.any { it == id }}
private fun mapIdTilAdGruppe(id: String?): AdGruppe? {
return when(id) {
tiltakAnsvarligGroupId -> AdGruppe.TILTAKSANSVARLIG_FLATE_GRUPPE
endringsmeldingGroupId -> AdGruppe.TILTAKSANSVARLIG_ENDRINGSMELDING_GRUPPE
tilgangTilNavAnsattGroupId -> AdGruppe.TILTAKSANSVARLIG_EGNE_ANSATTE_GRUPPE
else -> null
}
}
enum class AdGruppe {
TILTAKSANSVARLIG_FLATE_GRUPPE,
TILTAKSANSVARLIG_ENDRINGSMELDING_GRUPPE,
TILTAKSANSVARLIG_EGNE_ANSATTE_GRUPPE,
}
}
| 4
|
Kotlin
|
3
| 4
|
7d3177f915332a8aea5d4fcd14bd5072531cbfb8
| 2,929
|
amt-tiltak
|
MIT License
|
acornui-core/src/commonMain/kotlin/com/acornui/component/Image.kt
|
fuzzyweapon
| 130,889,917
| true
|
{"Kotlin": 2963922, "JavaScript": 15366, "HTML": 5956, "Java": 4507}
|
/*
* Copyright 2015 <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 com.acornui.component
import com.acornui.component.layout.SingleElementLayoutContainerImpl
import com.acornui.component.layout.algorithm.ScaleLayout
import com.acornui.component.layout.algorithm.ScaleLayoutData
import com.acornui.component.layout.algorithm.ScaleLayoutStyle
import com.acornui.core.di.Owned
import com.acornui.core.graphic.Texture
/**
* A scale box layout
*/
open class Image(owner: Owned) : SingleElementLayoutContainerImpl<ScaleLayoutStyle, ScaleLayoutData>(owner, ScaleLayout()), SingleElementContainer<UiComponent> {
override fun onElementChanged(oldElement: UiComponent?, newElement: UiComponent?) {
super.onElementChanged(oldElement, newElement)
oldElement?.layoutData = null
if (newElement != null && newElement.layoutData == null) {
val layoutData = ScaleLayoutData()
layoutData.maxScaleX = 1f
layoutData.maxScaleY = 1f
newElement.layoutData = layoutData
}
}
}
fun Owned.image(init: ComponentInit<Image> = {}): Image {
val i = Image(this)
i.init()
return i
}
fun Owned.image(path: String, init: ComponentInit<Image> = {}): Image {
val i = Image(this)
i.init()
i.contentsImage(path)
return i
}
fun Owned.image(atlasPath: String, region: String, init: ComponentInit<Image> = {}): Image {
val i = Image(this)
i.init()
i.contentsAtlas(atlasPath, region)
return i
}
/**
* Creates a texture component and uses it as the element of a single element container.
*/
fun SingleElementContainer<UiComponent>.contentsImage(value: String) {
createOrReuseElement { textureC() }.path = value
}
/**
* Creates a texture component and uses it as the element of a single element container.
*/
fun SingleElementContainer<UiComponent>.contentsTexture(value: Texture?) {
createOrReuseElement { textureC() }.texture = value
}
| 0
|
Kotlin
|
1
| 0
|
a57100f894721ee342d23fe8cacb3fcbcedbe6dc
| 2,373
|
acornui
|
Apache License 2.0
|
app/src/main/java/com/gmail/eamosse/imdb/ui/listMovies/ListMoviesFragment.kt
|
GuillaumeLagouy
| 242,684,476
| true
|
{"Kotlin": 67858}
|
package com.gmail.eamosse.imdb.ui.listMovies
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.gmail.eamosse.imdb.databinding.FragmentListMoviesBinding
import org.koin.androidx.viewmodel.ext.android.viewModel
class ListMoviesFragment : Fragment() {
private val viewModel: ListMoviesViewModel by viewModel()
private lateinit var binding: FragmentListMoviesBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentListMoviesBinding.inflate(inflater, container, false).apply {
lifecycleOwner = this@ListMoviesFragment
viewModel = this@ListMoviesFragment.viewModel
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(viewModel){
getListMovie(ListMoviesFragmentArgs.fromBundle(arguments!!).categoryId)
movies.observe(viewLifecycleOwner, Observer {
binding.movieList.adapter = MovieAdapter(it) { movie ->
val action = ListMoviesFragmentDirections.actionListMoviesFragmentToMovieDetailFragment(movie.id)
findNavController().navigate(action)
}
})
}
}
}
| 0
|
Kotlin
|
0
| 0
|
45c9cd2a73d1d00dc4cc15e88f9fc8e3cd29e41c
| 1,562
|
the-movie-app
|
Apache License 2.0
|
src/test/kotlin/ch/sourcemotion/vertx/kinesis/consumer/orchestra/impl/cluster/RedisNodeScoreVerticleTest.kt
|
wem
| 253,237,315
| false
| null |
package ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl.cluster
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl.OrchestraClusterName
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl.OrchestraClusterNodeId
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.internal.service.NodeScoreDto
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.internal.service.NodeScoreService
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.testing.AbstractRedisTest
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.collections.shouldContain
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
import io.vertx.core.json.JsonObject
import io.vertx.junit5.VertxTestContext
import io.vertx.kotlin.core.deploymentOptionsOf
import io.vertx.kotlin.coroutines.await
import io.vertx.redis.client.Command
import io.vertx.redis.client.Request
import io.vertx.serviceproxy.ServiceException
import kotlinx.coroutines.delay
import org.junit.jupiter.api.Test
import java.util.*
internal class RedisNodeScoreVerticleTest : AbstractRedisTest() {
private companion object {
const val DEFAULT_NODE_KEEP_ALIVE_MILLIS = 100L
}
@Test
internal fun this_node_score_on_deploy(testContext: VertxTestContext) = testContext.async {
val (_, nodeId) = deployNodeScoreVerticle()
val sut = NodeScoreService.createService(vertx)
val nodeScores = sut.getNodeScores().await()
val thisNodeScore = nodeScores.shouldHaveSize(1).first()
thisNodeScore.score.shouldBe(0)
thisNodeScore.clusterNodeId.shouldBe(nodeId)
}
@Test
internal fun multiple_nodes_deployment(testContext: VertxTestContext) = testContext.async {
// Deploy main node and create service
val remoteNodeCount = 11
val (_, mainNodeId) = deployNodeScoreVerticle()
val sut = NodeScoreService.createService(vertx)
// Deploy some remote nodes and safe their deployment id
val otherNodeStatesDeploymentIds = buildList {
repeat(remoteNodeCount) {
add(deployNodeScoreVerticle().first)
}
}
// Verify node states
val allNodeScores = sut.getNodeScores().await()
allNodeScores.shouldHaveSize(remoteNodeCount + 1).forEach {
it.score.shouldBe(0)
}
allNodeScores.shouldContain(NodeScoreDto(mainNodeId, 0))
// Remove remote notes
otherNodeStatesDeploymentIds.forEach { vertx.undeploy(it).await() }
// Verify node scores after other nodes are shutdown
val nodeScores = sut.getNodeScores().await()
val thisNodeScore = nodeScores.shouldHaveSize(1).first()
thisNodeScore.score.shouldBe(0)
thisNodeScore.clusterNodeId.shouldBe(mainNodeId)
}
@Test
internal fun update_this_node_score(testContext: VertxTestContext) = testContext.async {
val expectedScore = 10
val (_, nodeId) = deployNodeScoreVerticle()
val sut = NodeScoreService.createService(vertx)
sut.getNodeScores().await().let { nodeScores ->
val nodeScoreDto = nodeScores.shouldHaveSize(1).first()
nodeScoreDto.score.shouldBe(0)
nodeScoreDto.clusterNodeId.shouldBe(nodeId)
}
sut.setThisNodeScore(expectedScore).await()
val nodeScores = sut.getNodeScores().await()
val thisNodeScore = nodeScores.shouldHaveSize(1).first()
thisNodeScore.score.shouldBe(expectedScore)
thisNodeScore.clusterNodeId.shouldBe(nodeId)
}
@Test
internal fun cleanup_unhealthy_node_scores_even_score(testContext: VertxTestContext) = testContext.async {
val (_, nodeId) = deployNodeScoreVerticle()
val sut = NodeScoreService.createService(vertx)
val nodeScoreSetName = "${nodeId.clusterName}-node-scores"
// We add a score of some nodes for them the keep alive state is missing
repeat(10) {
val otherNodeId = OrchestraClusterNodeId(nodeId.clusterName, "${UUID.randomUUID()}")
redisClient.send(Request.cmd(Command.ZADD).arg(nodeScoreSetName).arg("0").arg("$otherNodeId"))
}
val nodeScore = sut.getNodeScores().await().shouldHaveSize(1).first()
nodeScore.clusterNodeId.shouldBe(nodeId)
nodeScore.score.shouldBe(0)
}
@Test
internal fun cleanup_unhealthy_node_scores_uneven_score(testContext: VertxTestContext) = testContext.async {
val (_, nodeId) = deployNodeScoreVerticle()
val sut = NodeScoreService.createService(vertx)
val nodeScoreSetName = "${nodeId.clusterName}-node-scores"
// We add a score of some nodes for them the keep alive state is missing
repeat(10) {
val otherNodeId = OrchestraClusterNodeId(nodeId.clusterName, "${UUID.randomUUID()}")
redisClient.send(Request.cmd(Command.ZADD).arg(nodeScoreSetName).arg("$it").arg("$otherNodeId"))
}
val nodeScore = sut.getNodeScores().await().shouldHaveSize(1).first()
nodeScore.clusterNodeId.shouldBe(nodeId)
nodeScore.score.shouldBe(0)
}
@Test
internal fun self_healing_score(testContext: VertxTestContext) = testContext.async {
val (_, nodeId) = deployNodeScoreVerticle()
val expectedScore = 10
val sut = NodeScoreService.createService(vertx)
closeConnectionToRedis()
delay(DEFAULT_NODE_KEEP_ALIVE_MILLIS * 3) // Ensure PX reached
shouldThrow<ServiceException> { sut.getNodeScores().await() }
shouldThrow<ServiceException> { sut.setThisNodeScore(expectedScore).await() }
removeRedisToxies()
delay((redisHeimdallOptions.reconnectInterval * 3) + DEFAULT_NODE_KEEP_ALIVE_MILLIS * 3) // Ensure reconnected
val thisNodeScore = sut.getNodeScores().await().shouldHaveSize(1).first()
thisNodeScore.score.shouldBe(expectedScore)
thisNodeScore.clusterNodeId.shouldBe(nodeId)
}
private suspend fun deployNodeScoreVerticle(
nodeId: OrchestraClusterNodeId = orchestraClusterNodeId(),
nodeKeepAliveMillis: Long = DEFAULT_NODE_KEEP_ALIVE_MILLIS
): Pair<String, OrchestraClusterNodeId> {
val options = RedisNodeScoreVerticle.Options(nodeId, redisHeimdallOptions, nodeKeepAliveMillis)
val deploymentId = vertx.deployVerticle(
RedisNodeScoreVerticle::class.java,
deploymentOptionsOf(config = JsonObject.mapFrom(options))
).await()
return deploymentId to nodeId
}
private fun orchestraClusterNodeId() = OrchestraClusterNodeId(
OrchestraClusterName("OrchestraNodeStateVerticleTest", "some-stream"),
"${UUID.randomUUID()}"
)
}
| 6
|
Kotlin
|
0
| 4
|
026f06f31457f0ba99b688864ea5d4cfde3c2f4d
| 6,759
|
vertx-kinesis-consumer-orchestra
|
MIT License
|
library/src/jvmCommonMain/kotlin/nativex/WKClientTransferBundle.kt
|
DrewCarlson
| 228,961,452
| false
| null |
/*
* Created by <NAME>.
* Copyright (c) 2020 Breadwinner AG. All right reserved.
*
* See the LICENSE file at the project root for license information.
* See the CONTRIBUTORS file at the project root for a list of contributors.
*/
package com.blockset.walletkit.nativex
import com.blockset.walletkit.nativex.library.WKNativeLibraryIndirect.wkClientTransferBundleCreate
import com.blockset.walletkit.nativex.utility.SizeT
import com.google.common.primitives.UnsignedLong
import com.sun.jna.Pointer
import com.sun.jna.PointerType
internal class WKClientTransferBundle : PointerType {
constructor() : super()
constructor(address: Pointer?) : super(address)
companion object {
fun create(
status: WKTransferStateType,
hash: String?,
identifier: String?,
uids: String?,
from: String?,
to: String?,
amount: String?,
currency: String?,
fee: String?,
transferIndex: UnsignedLong,
blockTimestamp: UnsignedLong,
blockHeight: UnsignedLong,
blockConfirmations: UnsignedLong,
blockTransactionIndex: UnsignedLong,
blockHash: String?,
meta: Map<String, String>): WKClientTransferBundle {
val metaCount = meta.size
val metaKeys = meta.keys.toTypedArray()
val metaVals = meta.values.toTypedArray()
val pointer: Pointer = wkClientTransferBundleCreate(
status.toCore(),
hash,
identifier,
uids,
from,
to,
amount,
currency,
fee,
transferIndex.toLong(),
blockTimestamp.toLong(),
blockHeight.toLong(),
blockConfirmations.toLong(),
blockTransactionIndex.toLong(),
blockHash,
SizeT(metaCount),
metaKeys,
metaVals)
return WKClientTransferBundle(pointer)
}
}
}
| 4
|
Kotlin
|
1
| 1
|
6a6b20a69e6307d89ad7ce3494fb794411fb7e76
| 2,250
|
WalletKit-Kotlin
|
The Unlicense
|
Export/src/me/anno/export/idea/IdeaModule.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.export.idea
import me.anno.io.files.FileReference
import me.anno.io.xml.generic.XMLNode
import me.anno.io.xml.generic.XMLReader
import kotlin.test.assertEquals
class IdeaModule(val project: IdeaProject) {
val moduleDependencies = ArrayList<String>()
val libraryDependencies = ArrayList<String>()
companion object {
fun loadModule(project: IdeaProject, source: FileReference): IdeaModule {
val result = IdeaModule(project)
val root = source.inputStreamSync().use {
XMLReader().read(it) as XMLNode
}
assertEquals("module", root.type)
val modManager = root.children
.filterIsInstance<XMLNode>()
.first { it.type == "component" && it["name"] == "NewModuleRootManager" }
val orderEntries = modManager.children
.filterIsInstance<XMLNode>()
.filter { it.type == "orderEntry" }
for (entry in orderEntries) {
when (entry["type"]) {
"library" -> result.libraryDependencies.add(entry["name"]!!)
"module" -> result.moduleDependencies.add(entry["module-name"]!!)
}
}
return result
}
}
}
| 0
| null |
3
| 24
|
013af4d92e0f89a83958008fbe1d1fdd9a10e992
| 1,284
|
RemsEngine
|
Apache License 2.0
|
mobile_app1/module346/src/main/java/module346packageKt0/Foo655.kt
|
uber-common
| 294,831,672
| false
| null |
package module346packageKt0;
annotation class Foo655Fancy
@Foo655Fancy
class Foo655 {
fun foo0(){
module346packageKt0.Foo654().foo5()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
}
| 6
| null |
6
| 72
|
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
| 297
|
android-build-eval
|
Apache License 2.0
|
android/quest/src/main/java/org/smartregister/fhircore/quest/configuration/view/QuestBottomNavigationActions.kt
|
opensrp
| 339,242,809
| false
| null |
/*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.quest.configuration.view
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.smartregister.fhircore.engine.configuration.view.NavigationAction
@Serializable
@SerialName("questionnaire")
data class QuestionnaireNavigationAction(val form: String, val readOnly: Boolean) :
NavigationAction
@Serializable
@SerialName("questionnaire_data_details")
data class QuestionnaireDataDetailsNavigationAction(val classification: String) : NavigationAction
@Serializable
@SerialName("switch_fragment")
data class ActionSwitchFragment(
val tag: String,
val isRegisterFragment: Boolean,
val isFilterVisible: Boolean,
val toolbarTitle: String?
) : NavigationAction
| 158
|
Kotlin
|
8
| 18
|
9d7044a12ef2726705a3019cb26ab03bc48bc28c
| 1,340
|
fhircore
|
Apache License 2.0
|
app/src/main/java/com/junnanhao/next/data/model/ClusterMembership.kt
|
jonashao
| 92,558,408
| false
| null |
package com.junnanhao.next.data.model
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.relation.ToOne
/**
* Created by jonashao on 2017/9/26.
* relationship between cluster and song, and their membership
*/
@Entity
data class ClusterMembership(
@Id private var id: Long,
val cluster: ToOne<Cluster>,
val song: ToOne<Song>,
var membership: Double
) {
companion object {
val MIN_MEMBERSHIP: Double = 0.001
}
}
//@Entity
//data class ClusterFriendship(
// @Id private var id: Long,
// private val one: ToOne<Cluster>,
// private var friendship: Double,
// private val another: ToOne<Cluster>
//)
| 1
| null |
2
| 12
|
cccaebc170f8515d63ece94f169512696f0b1149
| 717
|
next-kotlin
|
Apache License 2.0
|
app/src/main/java/com/kasuminotes/ui/components/SearchBar.kt
|
chilbi
| 399,723,451
| false
| null |
package com.kasuminotes.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.isImeVisible
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
@Composable
fun SearchBar(
searchText: String,
onSearchTextChange: (String) -> Unit,
onClear: (() -> Unit)? = null
) {
val focusManager = LocalFocusManager.current
val isImeVisible = WindowInsets.isImeVisible
LaunchedEffect(isImeVisible) {
if (!isImeVisible) focusManager.clearFocus()
}
BasicTextField(
value = searchText,
onValueChange = onSearchTextChange,
modifier = Modifier
.fillMaxSize()
.padding(vertical = 12.dp)
.background(
MaterialTheme.colorScheme.onSurface.copy(0.12f),
CircleShape
),
textStyle = TextStyle.Default.copy(color = LocalContentColor.current),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
singleLine = true,
cursorBrush = SolidColor(LocalContentColor.current),
decorationBox = @Composable { innerTextField ->
Box {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = null,
modifier = Modifier
.align(Alignment.CenterStart)
.padding(start = 12.dp),
tint = LocalContentColor.current.copy(0.5f)
)
Box(Modifier.align(Alignment.CenterStart).padding(start = 42.dp)) {
innerTextField()
}
if (onClear != null && searchText != "") {
Icon(
imageVector = Icons.Filled.Clear,
contentDescription = null,
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = 12.dp)
.clickable(onClick = onClear),
tint = LocalContentColor.current.copy(0.5f)
)
}
}
}
)
}
| 0
| null |
0
| 1
|
6a432d3f2820e59bdbe7f939ad9e1af3bbd1a1de
| 3,358
|
KasumiNotes
|
Apache License 2.0
|
src/main/kotlin/com/empowerops/getoptk/Converters.kt
|
EmpowerOperations
| 72,069,047
| false
| null |
package com.empowerops.getoptk
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import kotlin.reflect.KClass
import kotlin.reflect.full.companionObject
import kotlin.reflect.full.companionObjectInstance
import java.lang.Enum as JavaEnum
//looks up strategies to convert strings to T's, eg "Double.parseDouble", "Boolean.parseBoolean", etc.
// please note this object returns a closed converter, which might be weird
// Could just as easily return a T instead of a (String) -> T
typealias Converter<T> = (String) -> T
object DefaultConverters {
@Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_ANY") //unfortunately I'm moving from dynamic back into static types here.
//AFAIK there is no way to tell kotlin that if type == Int::class, then T == Int
operator fun <T: Any> get(type: KClass<T>): Converter<T>? = when {
type.hasStaticMethod("valueOf", returnType = type, paramTypes = listOf(String::class)) ->
StaticMethodCallConverter(type, "valueOf")
type.companionObject?.hasLocalMethod("valueOf", returnType = type, paramTypes = listOf(String::class)) ?: false ->
CompanionMethodCallConverter(type, "valueOf")
type.hasStaticMethod("parse", returnType = type, paramTypes = listOf(String::class)) ->
StaticMethodCallConverter(type, "parse")
type.companionObject?.hasLocalMethod("parse", returnType = type, paramTypes = listOf(String::class)) ?: false ->
CompanionMethodCallConverter(type, "parse")
type == String::class -> StringConverter
type == Int::class -> IntConverter
type == Long::class -> LongConverter
type == Float::class -> FloatConverter
type == Double::class -> DoubleConverter
type == Char::class -> CharConverter
type.java.isEnum -> EnumConverter(type.java as Class<Nothing>)
//Nothing is a bottom type, only way I could think to satisfy the Enum<Enum<Enum...>>> problem
else -> null
} as Converter<T>?
}
object InvalidConverter: Converter<Nothing>{
override fun invoke(text: String) = throw UnsupportedOperationException("not implemented")
}
object DoubleConverter: DelegatingConverter<Double>(String::toDouble), Primative
object FloatConverter: DelegatingConverter<Float>(String::toFloat), Primative
object IntConverter: DelegatingConverter<Int>(String::toInt), Primative
object LongConverter: DelegatingConverter<Long>(String::toLong), Primative
object StringConverter: Converter<String>{ override fun invoke(text: String) = text }
object CharConverter: Converter<Char>{
override fun invoke(text: String): Char {
require(text.length == 1){ "char variables must be exactly 1 character" }
return text[0]
}
}
class EnumConverter<T: Enum<T>>(val enumType: Class<T>): Converter<T>{
override fun invoke(text: String): T {
val generatedEnum = JavaEnum.valueOf(enumType, text)
return enumType.cast(generatedEnum)
}
}
class StaticMethodCallConverter<T: Any>(val type: KClass<T>, methodName: String) : Converter<T>{
val method = type.java.getMethod(methodName, String::class.java).apply {
require(Modifier.isStatic(modifiers))
}
override fun invoke(text: String) = type.java.cast(method.invoke(null, text))
}
class CompanionMethodCallConverter<T: Any>(val type: KClass<T>, methodName: String): Converter<T>{
init {
require(type.companionObject != null)
}
val companionInstance = type.companionObjectInstance!!
val method = type.companionObject!!.getMethod(methodName, listOf(String::class))!!
override fun invoke(text: String): T = type.java.cast(method.invoke(companionInstance, text))
}
interface Primative {}
abstract class DelegatingConverter<out T>(val convertActual: (String) -> T): Converter<T> by convertActual
fun KClass<*>.hasStaticMethod(name: String, returnType: KClass<*>, paramTypes: List<KClass<*>>)
= getMethod(name, paramTypes)?.let { it.isStatic && it.returnType == returnType.java } ?: false
private fun KClass<*>.getMethod(name: String, paramTypes: List<KClass<*>>)
= try { this.java.getMethod(name, *paramTypes.map { it.java }.toTypedArray()) }
catch (ex: NoSuchMethodException) { null }
val Method.isStatic: Boolean get() = Modifier.isStatic(modifiers)
fun KClass<*>.hasLocalMethod(name: String, returnType: KClass<*>, paramTypes: List<KClass<*>>)
= getMethod(name, paramTypes)?.let { it.returnType == returnType.java }
| 0
| null |
2
| 8
|
06442978011da80c818f363508fdf9d230a8ca30
| 4,497
|
getoptk
|
Apache License 2.0
|
compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/builder/FirErrorTypeRefBuilder.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.types.builder
import kotlin.contracts.*
import org.jetbrains.kotlin.KtSourceElement
import org.jetbrains.kotlin.fir.builder.FirAnnotationContainerBuilder
import org.jetbrains.kotlin.fir.builder.FirBuilderDsl
import org.jetbrains.kotlin.fir.diagnostics.ConeDiagnostic
import org.jetbrains.kotlin.fir.expressions.FirAnnotation
import org.jetbrains.kotlin.fir.types.ConeErrorType
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.FirErrorTypeRef
import org.jetbrains.kotlin.fir.types.FirTypeRef
import org.jetbrains.kotlin.fir.types.impl.FirErrorTypeRefImpl
import org.jetbrains.kotlin.fir.visitors.*
/*
* This file was generated automatically
* DO NOT MODIFY IT MANUALLY
*/
@FirBuilderDsl
class FirErrorTypeRefBuilder : FirAnnotationContainerBuilder {
override var source: KtSourceElement? = null
var type: ConeKotlinType? = null
var delegatedTypeRef: FirTypeRef? = null
lateinit var diagnostic: ConeDiagnostic
override fun build(): FirErrorTypeRef {
val type = this.type
return if (type != null) {
FirErrorTypeRefImpl(
source,
type,
delegatedTypeRef,
diagnostic
)
} else {
FirErrorTypeRefImpl(
source,
delegatedTypeRef,
diagnostic,
)
}
}
@Deprecated("Modification of 'annotations' has no impact for FirErrorTypeRefBuilder", level = DeprecationLevel.HIDDEN)
override val annotations: MutableList<FirAnnotation> = mutableListOf()
}
@OptIn(ExperimentalContracts::class)
inline fun buildErrorTypeRef(init: FirErrorTypeRefBuilder.() -> Unit): FirErrorTypeRef {
contract {
callsInPlace(init, kotlin.contracts.InvocationKind.EXACTLY_ONCE)
}
return FirErrorTypeRefBuilder().apply(init).build()
}
@OptIn(ExperimentalContracts::class)
inline fun buildErrorTypeRefCopy(original: FirErrorTypeRef, init: FirErrorTypeRefBuilder.() -> Unit): FirErrorTypeRef {
contract {
callsInPlace(init, kotlin.contracts.InvocationKind.EXACTLY_ONCE)
}
val copyBuilder = FirErrorTypeRefBuilder()
copyBuilder.source = original.source
copyBuilder.type = original.type
copyBuilder.delegatedTypeRef = original.delegatedTypeRef
copyBuilder.diagnostic = original.diagnostic
return copyBuilder.apply(init).build()
}
| 163
| null |
5686
| 46,039
|
f98451e38169a833f60b87618db4602133e02cf2
| 2,656
|
kotlin
|
Apache License 2.0
|
app/src/androidTest/java/com/muratcangzm/valorantstore/api/ValorantApiTest.kt
|
NecroEye
| 719,144,732
| false
|
{"Kotlin": 58763}
|
package com.muratcangzm.valorantstore.api
import com.muratcangzm.valorantstore.model.remote.AgentModel
import com.muratcangzm.valorantstore.model.remote.CurrencyModel
import com.muratcangzm.valorantstore.model.remote.WeaponSkinModel
import com.muratcangzm.valorantstore.utils.Constans
import org.junit.runner.RunWith
import retrofit2.http.GET
import retrofit2.http.Query
interface ValorantApiTest {
@GET(Constans.CURRENCY)
suspend fun getCurrency(
@Query("language")
language: String = "tr-TR"
)
: CurrencyModel
@GET(Constans.AGENTS)
suspend fun getAgent(
@Query("language")
language: String = "tr-TR",
@Query("isPlayableCharacter")
isPlayableCharacter: Boolean = true
)
: AgentModel
@GET(Constans.SKINS)
suspend fun getSkins(
@Query("language")
language: String = "tr-TR",
)
: WeaponSkinModel
}
| 0
|
Kotlin
|
0
| 0
|
867318d628110dcaa3432fe024ea77affe9630b7
| 940
|
Valorant_Store
|
Apache License 2.0
|
src/main/kotlin/com/nitramite/gamescoreapi/dao/GameEntity.kt
|
norkator
| 441,637,075
| false
| null |
package com.nitramite.gamescoreapi.dao
import javax.persistence.*
@Entity(name = "game")
class GameEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
val id: Long? = null,
val name: String,
val description: String?,
val enabled: Boolean = true,
@Column(name = "userid", nullable = false)
val userId: Long
)
| 0
|
Kotlin
|
1
| 0
|
eb4b79d8c905660258a8f7225cc7dafa9708a737
| 388
|
game-score-api
|
MIT License
|
domain/src/main/java/com/sample/tmdb/domain/model/DetailWrapper.kt
|
alirezaeiii
| 544,156,630
| false
|
{"Kotlin": 230111}
|
package com.sample.tmdb.domain.model
class DetailWrapper<T : TMDbItemDetails>(
val cast: List<Cast>,
val crew: List<Crew>,
val details: T
)
| 0
|
Kotlin
|
3
| 8
|
12a8a4fa953d6d84f2bd33b7807a097ea708ab42
| 152
|
TMDb-Compose-Playground
|
The Unlicense
|
app/src/main/java/com/bunkalogic/bunkalist/Utils/InputFilterMinMax.kt
|
bunkalogic
| 171,318,735
| false
|
{"Kotlin": 544892}
|
package com.bunkalogic.bunkalist.Utils
import android.text.Spanned
import android.text.InputFilter
class InputFilterMinMax(private val min: Double, private val max: Double) : InputFilter {
override fun filter(
source: CharSequence,
start: Int,
end: Int,
dest: Spanned,
dstart: Int,
dend: Int
): CharSequence? {
try {
val input =
Integer.parseInt(dest.subSequence(0, dstart).toString() + source + dest.subSequence(dend, dest.length))
if (isInRange(min.toInt(), max.toInt(), input))
return null
} catch (nfe: NumberFormatException) {
}
return ""
}
private fun isInRange(a: Int, b: Int, c: Int): Boolean {
return if (b > a) c in a..b else c in b..a
}
}
| 0
|
Kotlin
|
0
| 2
|
1b5c1d40f0e7514de3a666614cdf6fe88e21ca3f
| 820
|
BunkaList-Replaced-
|
Apache License 2.0
|
src/main/kotlin/id/walt/model/dif/DisclosureLimitation.kt
|
walt-id
| 392,607,264
| false
| null |
package id.walt.model.dif
enum class DisclosureLimitation {
required,
preferred
}
| 6
| null |
34
| 97
|
1a8776a899ac97aa32f58d2f70aba23683d2c9b3
| 91
|
waltid-ssikit
|
Apache License 2.0
|
javapoet-ktx/tests/src/com/hendraanggrian/javapoet/collections/ParameterSpecCollectionTest.kt
|
hendraanggrian
| 169,205,951
| false
| null |
package com.hendraanggrian.javapoet.collections
import com.google.common.truth.Truth.assertThat
import com.hendraanggrian.javapoet.asTypeName
import com.squareup.javapoet.ParameterSpec
import kotlin.test.Test
class ParameterSpecCollectionTest {
private val list = ParameterSpecCollection(mutableListOf())
private fun list(configuration: ParameterSpecCollectionScope.() -> Unit) =
ParameterSpecCollectionScope(list).configuration()
private class Parameter1
private class Parameter2
private class Parameter3
private class Parameter4
@Test
fun add() {
list.add(Parameter1::class.asTypeName(), "parameter1")
list.add(Parameter2::class.java, "parameter2")
list.add(Parameter3::class, "parameter3")
list.add<Parameter4>("parameter4")
assertThat(list).containsExactly(
ParameterSpec.builder(Parameter1::class.java, "parameter1").build(),
ParameterSpec.builder(Parameter2::class.java, "parameter2").build(),
ParameterSpec.builder(Parameter3::class.java, "parameter3").build(),
ParameterSpec.builder(Parameter4::class.java, "parameter4").build()
)
}
@Test
fun set() {
list["parameter1"] = Parameter1::class.asTypeName()
list["parameter2"] = Parameter2::class.java
list["parameter3"] = Parameter3::class
assertThat(list).containsExactly(
ParameterSpec.builder(Parameter1::class.java, "parameter1").build(),
ParameterSpec.builder(Parameter2::class.java, "parameter2").build(),
ParameterSpec.builder(Parameter3::class.java, "parameter3").build(),
)
}
@Test
fun invoke() {
list {
"parameter1"(Parameter1::class.asTypeName()) { }
"parameter2"(Parameter2::class.java) { }
"parameter3"(Parameter3::class) { }
"parameter4"<Parameter4> { }
}
assertThat(list).containsExactly(
ParameterSpec.builder(Parameter1::class.java, "parameter1").build(),
ParameterSpec.builder(Parameter2::class.java, "parameter2").build(),
ParameterSpec.builder(Parameter3::class.java, "parameter3").build(),
ParameterSpec.builder(Parameter4::class.java, "parameter4").build()
)
}
}
| 1
|
Kotlin
|
1
| 5
|
5ec5a9704c32e3eba34b6d1acc22739d9f571bb9
| 2,313
|
javapoet-ktx
|
Apache License 2.0
|
app/src/main/java/com/kylecorry/trail_sense/tools/light/ui/ToolLightFragment.kt
|
kylecorry31
| 215,154,276
| false
| null |
package com.kylecorry.trail_sense.tools.light.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.kylecorry.andromeda.fragments.BoundFragment
import com.kylecorry.andromeda.fragments.observe
import com.kylecorry.sol.science.optics.Optics
import com.kylecorry.trail_sense.R
import com.kylecorry.trail_sense.databinding.FragmentToolLightBinding
import com.kylecorry.trail_sense.shared.DistanceUtils
import com.kylecorry.trail_sense.shared.FormatService
import com.kylecorry.trail_sense.shared.sensors.SensorService
import kotlin.math.max
class ToolLightFragment : BoundFragment<FragmentToolLightBinding>() {
private val lightSensor by lazy { SensorService(requireContext()).getLightSensor() }
private val formatService by lazy { FormatService.getInstance(requireContext()) }
private var maxLux = 0f
override fun generateBinding(
layoutInflater: LayoutInflater,
container: ViewGroup?
): FragmentToolLightBinding {
return FragmentToolLightBinding.inflate(layoutInflater, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observe(lightSensor) { updateLight() }
binding.resetBtn.setOnClickListener {
maxLux = 0f
updateLight()
}
binding.beamDistance.setOnValueChangeListener {
maxLux = 0f
if (it != null) {
binding.lightChart.setDistanceUnits(it.units)
}
updateLight()
}
binding.beamDistance.units =
formatService.sortDistanceUnits(DistanceUtils.hikingDistanceUnits)
}
private fun updateLight() {
binding.lightTitle.title.text = formatService.formatLux(lightSensor.illuminance)
maxLux = max(lightSensor.illuminance, maxLux)
val distance = binding.beamDistance.value
if (distance == null) {
binding.lightTitle.subtitle.text = ""
binding.beamDistanceText.text = ""
binding.lightChart.setCandela(0f)
return
}
val candela = Optics.luxToCandela(maxLux, distance)
val beamDist = Optics.lightBeamDistance(candela).convertTo(distance.units)
binding.lightTitle.subtitle.text = formatService.formatCandela(candela)
binding.beamDistanceText.text =
getString(R.string.beam_distance, formatService.formatDistance(beamDist))
binding.lightChart.setCandela(candela)
}
}
| 456
| null |
66
| 989
|
41176d17b498b2dcecbbe808fbe2ac638e90d104
| 2,582
|
Trail-Sense
|
MIT License
|
src/test/kotlin/com/github/michaelbull/advent2023/day6/Day6Test.kt
|
michaelbull
| 726,012,340
| false
|
{"Kotlin": 82295}
|
package com.github.michaelbull.advent2023.day6
import com.github.michaelbull.advent2023.day6.Day6.part1
import com.github.michaelbull.advent2023.day6.Day6.part2
import kotlin.test.Test
import kotlin.test.assertEquals
class Day6Test {
@Test
fun `example 1`() {
assertEquals(288, Day6.solve(::part1, EXAMPLE))
}
@Test
fun `example 2`() {
assertEquals(71503, Day6.solve(::part2, EXAMPLE))
}
@Test
fun `answer 1`() {
assertEquals(1660968, Day6.solve(::part1))
}
@Test
fun `answer 2`() {
assertEquals(26499773, Day6.solve(::part2))
}
private companion object {
private const val EXAMPLE = """
Time: 7 15 30
Distance: 9 40 200
"""
}
}
| 0
|
Kotlin
|
0
| 1
|
5b81ff2c8f8a2a77aaef3f1bcf2ad8e819f88436
| 775
|
advent-2023
|
ISC License
|
app/src/main/java/dk/itu/moapd/copenhagenbuzz/fcag/fragments/MapsFragment.kt
|
FrankCaglianone
| 753,609,912
| false
|
{"Kotlin": 21210}
|
package dk.itu.moapd.copenhagenbuzz.fcag.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dk.itu.moapd.copenhagenbuzz.fcag.databinding.FragmentMapsBinding
class MapsFragment : Fragment() {
private var _binding: FragmentMapsBinding? = null
private val binding
get() = requireNotNull(_binding) {
"Cannot access binding because it is null. Is the view visible?"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View = FragmentMapsBinding.inflate(inflater, container, false).also {
_binding = it
}.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply { }
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
8382845ddb0262aa38f59ad07d3cba0bdc8cbe50
| 1,119
|
CopenaghenBuzz
|
MIT License
|
magic/core/src/main/java/link/magic/android/core/relayer/urlBuilder/BaseOptions.kt
|
magiclabs
| 589,703,550
| false
| null |
package link.magic.android.core.relayer.urlBuilder
import androidx.annotation.Keep
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import java.io.Serializable
@Keep
open class BaseOptions(
@SerializedName("API_KEY") @Expose val apiKey: String,
val host: String,
val locale: String,
val bundleId: String,
val meta: Map<String, Any>
): Serializable {
val sdk = "magic-sdk-android"
}
| 1
|
Kotlin
|
2
| 3
|
9f50321e17233817219cda3c04509b1af2aad599
| 451
|
magic-android
|
Apache License 2.0
|
core/database/src/main/java/com/whakaara/database/alarm/AlarmDatabase.kt
|
ahudson20
| 531,856,934
| false
| null |
package com.whakaara.database.alarm
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.whakaara.database.alarm.converters.AlarmConverter
import com.whakaara.database.alarm.entity.AlarmEntity
@Database(entities = [AlarmEntity::class], version = 1, exportSchema = false)
@TypeConverters(AlarmConverter::class)
abstract class AlarmDatabase : RoomDatabase() {
abstract fun alarmDao(): AlarmDao
}
| 1
| null |
3
| 30
|
f63a8f59815bec094a6d0c19d0368a87a2b87923
| 458
|
whakaara
|
MIT License
|
compiler/testData/codegen/box/ranges/forInProgressionWithIndex/forInStepReversedWithIndex.kt
|
JetBrains
| 3,432,266
| false
| null |
// DONT_TARGET_EXACT_BACKEND: WASM
// WASM_MUTE_REASON: STDLIB_COLLECTIONS
// KJS_WITH_FULL_RUNTIME
// WITH_RUNTIME
import kotlin.test.assertEquals
fun box(): String {
val indexList = mutableListOf<Int>()
val valueList = mutableListOf<Int>()
for ((i, v) in (4..11 step 2).reversed().withIndex()) {
indexList += i
valueList += v
}
assertEquals(listOf(0, 1, 2, 3), indexList)
assertEquals(listOf(10, 8, 6, 4), valueList)
return "OK"
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 479
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/dirtydish/app/dirtydish/SuppliesRecyclerAdapter.kt
|
giulioco
| 151,326,825
| false
|
{"Kotlin": 130277, "JavaScript": 11025}
|
package com.dirtydish.app.dirtydish
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.dirtydish.app.dirtydish.data.Supply
import com.dirtydish.app.dirtydish.singletons.Session
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import org.jetbrains.anko.doAsync
private val tag = "SUPPLIES_RECYCLER_ADAPTER"
class SupplyRecyclerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener, View.OnLongClickListener {
var supply_name: TextView
var availability: TextView
private var itemClickListener: ItemClickListener? = null
init {
supply_name = itemView.findViewById<View>(R.id.chore_name) as TextView
availability = itemView.findViewById<View>(R.id.availability) as TextView
itemView.setOnClickListener(this)
itemView.setOnLongClickListener(this)
}
fun setItemClickListener(itemClickListener: ItemClickListener) {
this.itemClickListener = itemClickListener
}
override fun onClick(v: View) {
itemClickListener!!.onClick(v, adapterPosition, false)
}
override fun onLongClick(v: View): Boolean {
itemClickListener!!.onClick(v, adapterPosition, true)
return true
}
}
class SuppliesRecyclerAdapter(private val listData: MutableList<Supply>, private val context: Context) : RecyclerView.Adapter<SupplyRecyclerViewHolder>() {
private lateinit var db: FirebaseDatabase
private lateinit var houseRef: DatabaseReference
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SupplyRecyclerViewHolder {
db = FirebaseDatabase.getInstance()
//choreRef = db.getReference("chores")
houseRef = db.getReference("houses").child(Session.userHouse!!.id)
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.supply_row, parent, false)
return SupplyRecyclerViewHolder(itemView)
}
override fun onBindViewHolder(holder: SupplyRecyclerViewHolder, position: Int) {
val currentSupply = listData[position]
holder.supply_name.text = currentSupply.name
if (currentSupply.missing)
holder.availability.text = "Missing"
else
holder.availability.text = "Available"
holder.setItemClickListener(object : ItemClickListener {
override fun onClick(view: View, position: Int, isLongClick: Boolean) {
listData[position].missing = !currentSupply.missing
notifyItemChanged(position)
doAsync { houseRef.child("supplies").setValue(listData) }
}
})
}
fun removeAt(position: Int) {
listData.removeAt(position)
notifyItemRemoved(position)
reindexSupplies()
}
private fun reindexSupplies() {
for(i in 0 until listData.size) {
listData[i].id = i.toString()
}
doAsync { houseRef.child("supplies").setValue(listData) }
}
override fun getItemCount(): Int {
return listData.size
}
}
| 4
|
Kotlin
|
0
| 0
|
d57f002cf21eeae42ba9e3b76447f418a51845cd
| 3,259
|
dirtydish
|
MIT License
|
analysis/analysis-api-impl-base/tests/org/jetbrains/kotlin/analysis/api/impl/base/test/cases/annotations/AbstractAnalysisApiAnnotationsOnDeclarationsTest.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.impl.base.test.cases.annotations
import org.jetbrains.kotlin.analysis.api.KaSession
import org.jetbrains.kotlin.analysis.api.annotations.KaAnnotationsList
import org.jetbrains.kotlin.analysis.api.symbols.markers.KaAnnotatedSymbol
import org.jetbrains.kotlin.analysis.test.framework.base.AbstractAnalysisApiBasedTest
import org.jetbrains.kotlin.analysis.test.framework.project.structure.KtTestModule
import org.jetbrains.kotlin.analysis.test.framework.services.expressionMarkerProvider
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.services.TestServices
import org.jetbrains.kotlin.test.services.assertions
abstract class AbstractAnalysisApiAnnotationsOnDeclarationsTest : AbstractAnalysisApiBasedTest() {
open fun renderAnnotations(analysisSession: KaSession, annotations: KaAnnotationsList): String {
return TestAnnotationRenderer.renderAnnotations(analysisSession, annotations)
}
override fun doTestByMainFile(mainFile: KtFile, mainModule: KtTestModule, testServices: TestServices) {
val ktDeclaration = testServices.expressionMarkerProvider.getElementOfTypeAtCaret<KtDeclaration>(mainFile)
val actual = analyseForTest(ktDeclaration) {
val declarationSymbol = ktDeclaration.getSymbol() as KaAnnotatedSymbol
buildString {
appendLine("${KtDeclaration::class.simpleName}: ${ktDeclaration::class.simpleName} ${ktDeclaration.name}")
append(renderAnnotations(analysisSession, declarationSymbol.annotationsList))
}
}
testServices.assertions.assertEqualsToTestDataFileSibling(actual)
}
}
| 182
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,935
|
kotlin
|
Apache License 2.0
|
data/src/main/kotlin/io/github/zeyomir/extremesportssos/data/sensors/LocationService.kt
|
zeyomir
| 123,106,859
| false
| null |
package io.github.zeyomir.extremesportssos.data.sensors
import io.github.zeyomir.extremesportssos.domain.entity.Coordinates
import io.reactivex.Single
interface LocationService {
fun current(): Single<Coordinates>
}
| 11
|
Kotlin
|
0
| 2
|
7acba35531f48f488c954405e82f0409b2cca579
| 223
|
ExtremeSportsSOS
|
MIT License
|
paymentsheet/src/test/java/com/stripe/android/paymentsheet/TestViewModelFactory.kt
|
stripe
| 6,926,049
| false
|
{"Kotlin": 13814299, "Java": 102588, "Ruby": 45779, "HTML": 42045, "Shell": 23905, "Python": 21891}
|
package com.stripe.android.paymentsheet
import androidx.lifecycle.SavedStateHandle
import com.stripe.android.link.LinkConfigurationCoordinator
import com.stripe.android.paymentsheet.viewmodels.BaseSheetViewModel
import com.stripe.android.utils.FakeLinkConfigurationCoordinator
import org.mockito.kotlin.mock
internal object TestViewModelFactory {
fun <T : BaseSheetViewModel> create(
linkConfigurationCoordinator: LinkConfigurationCoordinator = FakeLinkConfigurationCoordinator(),
savedStateHandle: SavedStateHandle = SavedStateHandle(),
viewModelFactory: (
linkHandler: LinkHandler,
linkConfigurationCoordinator: LinkConfigurationCoordinator,
savedStateHandle: SavedStateHandle,
) -> T
): T {
val linkHandler = LinkHandler(
linkLauncher = mock(),
linkConfigurationCoordinator = linkConfigurationCoordinator,
savedStateHandle = savedStateHandle,
linkAnalyticsComponentBuilder = mock(),
linkStore = mock(),
)
return viewModelFactory(linkHandler, linkConfigurationCoordinator, savedStateHandle)
}
}
| 91
|
Kotlin
|
644
| 1,277
|
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
| 1,163
|
stripe-android
|
MIT License
|
reporter/src/test/kotlin/reporters/fossid/FossIdReporterTest.kt
|
oss-review-toolkit
| 107,540,288
| false
| null |
/*
* Copyright (C) 2022 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>)
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.plugins.reporters.fossid
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.collections.shouldBeSingleton
import io.kotest.matchers.result.shouldBeSuccess
import io.kotest.matchers.throwable.shouldHaveMessage
import io.mockk.clearAllMocks
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.coVerifyAll
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.spyk
import java.io.File
import org.ossreviewtoolkit.clients.fossid.FossIdRestService
import org.ossreviewtoolkit.clients.fossid.FossIdServiceWithVersion
import org.ossreviewtoolkit.clients.fossid.generateReport
import org.ossreviewtoolkit.clients.fossid.model.report.ReportType
import org.ossreviewtoolkit.clients.fossid.model.report.SelectionType
import org.ossreviewtoolkit.model.Identifier
import org.ossreviewtoolkit.model.OrtResult
import org.ossreviewtoolkit.model.Repository
import org.ossreviewtoolkit.model.ScanResult
import org.ossreviewtoolkit.model.ScanSummary
import org.ossreviewtoolkit.model.ScannerDetails
import org.ossreviewtoolkit.model.UnknownProvenance
import org.ossreviewtoolkit.model.VcsInfo
import org.ossreviewtoolkit.model.VcsType
import org.ossreviewtoolkit.model.config.Excludes
import org.ossreviewtoolkit.model.config.PluginConfiguration
import org.ossreviewtoolkit.model.config.RepositoryConfiguration
import org.ossreviewtoolkit.model.config.ScopeExclude
import org.ossreviewtoolkit.model.config.ScopeExcludeReason
import org.ossreviewtoolkit.reporter.ReporterInput
import org.ossreviewtoolkit.utils.common.Options
import org.ossreviewtoolkit.utils.test.scannerRunOf
private const val SERVER_URL_SAMPLE = "https://fossid.example.com/instance/"
private const val API_KEY_SAMPLE = "XYZ"
private const val USER_KEY_SAMPLE = "user"
private val DEFAULT_OPTIONS = mapOf(
FossIdReporter.SERVER_URL_PROPERTY to SERVER_URL_SAMPLE
)
private val DEFAULT_SECRETS = mapOf(
FossIdReporter.API_KEY_PROPERTY to API_KEY_SAMPLE,
FossIdReporter.USER_PROPERTY to USER_KEY_SAMPLE
)
private const val SCANCODE_1 = "scancode1"
private const val SCANCODE_2 = "scancode2"
private val FILE_SAMPLE = File("fake_file")
private val DIRECTORY_SAMPLE = File("fake_directory")
class FossIdReporterTest : WordSpec({
beforeSpec {
mockkStatic("org.ossreviewtoolkit.clients.fossid.ExtensionsKt")
}
afterTest {
clearAllMocks()
}
"generateReport of FossIdReport " should {
"check if a server URL was given" {
val reporter = FossIdReporter()
val exception = shouldThrow<IllegalArgumentException> {
val input = createReporterInput()
reporter.generateReport(
input,
DEFAULT_OPTIONS.filterNot { it.key == FossIdReporter.SERVER_URL_PROPERTY }
)
}
exception shouldHaveMessage "No FossID server URL configuration found."
}
"check if an API key was given" {
val reporter = FossIdReporter()
val exception = shouldThrow<IllegalArgumentException> {
val input = createReporterInput()
reporter.generateReport(
input,
secrets = DEFAULT_SECRETS.filterNot { it.key == FossIdReporter.API_KEY_PROPERTY }
)
}
exception shouldHaveMessage "No FossID API Key configuration found."
}
"check if a user was given" {
val reporter = FossIdReporter()
val exception = shouldThrow<IllegalArgumentException> {
val input = createReporterInput()
reporter.generateReport(
input,
secrets = DEFAULT_SECRETS.filterNot { it.key == FossIdReporter.USER_PROPERTY }
)
}
exception shouldHaveMessage "No FossID User configuration found."
}
"do nothing if no scancode is passed" {
val (serviceMock, reporterMock) = createReporterMock()
val input = createReporterInput()
reporterMock.generateReport(input)
coVerify(exactly = 0) {
serviceMock.generateReport(any(), any(), any(), any(), any(), any())
}
}
"use HTML_DYNAMIC as default report type" {
val (serviceMock, reporterMock) = createReporterMock()
val input = createReporterInput(SCANCODE_1)
reporterMock.generateReport(input)
coVerify(exactly = 1) {
serviceMock.generateReport(
USER_KEY_SAMPLE,
API_KEY_SAMPLE,
SCANCODE_1,
ReportType.HTML_DYNAMIC,
any(),
any()
)
}
}
"allow to specify a report type" {
val (serviceMock, reporterMock) = createReporterMock()
val input = createReporterInput(SCANCODE_1)
reporterMock.generateReport(
input,
DEFAULT_OPTIONS + (FossIdReporter.REPORT_TYPE_PROPERTY to ReportType.XLSX.name)
)
coVerify(exactly = 1) {
serviceMock.generateReport(
USER_KEY_SAMPLE,
API_KEY_SAMPLE,
SCANCODE_1,
ReportType.XLSX,
any(),
any()
)
}
}
"use INCLUDE_ALL_LICENSES as default selection type" {
val (serviceMock, reporterMock) = createReporterMock()
val input = createReporterInput(SCANCODE_1)
reporterMock.generateReport(input)
coVerify(exactly = 1) {
serviceMock.generateReport(
USER_KEY_SAMPLE,
API_KEY_SAMPLE,
SCANCODE_1,
any(),
SelectionType.INCLUDE_ALL_LICENSES,
any()
)
}
}
"allow to specify a selection type" {
val (serviceMock, reporterMock) = createReporterMock()
val input = createReporterInput(SCANCODE_1)
reporterMock.generateReport(
input,
DEFAULT_OPTIONS + (FossIdReporter.SELECTION_TYPE_PROPERTY to SelectionType.INCLUDE_COPYLEFT.name)
)
coVerify(exactly = 1) {
serviceMock.generateReport(
USER_KEY_SAMPLE,
API_KEY_SAMPLE,
SCANCODE_1,
any(),
SelectionType.INCLUDE_COPYLEFT,
any()
)
}
}
"generate a report for each given scancode" {
val (serviceMock, reporterMock) = createReporterMock()
val input = createReporterInput(SCANCODE_1, SCANCODE_2)
reporterMock.generateReport(input)
coVerifyAll {
serviceMock.generateReport(USER_KEY_SAMPLE, API_KEY_SAMPLE, SCANCODE_1, any(), any(), any())
serviceMock.generateReport(USER_KEY_SAMPLE, API_KEY_SAMPLE, SCANCODE_2, any(), any(), any())
}
}
"generate a report for merged scan results" {
val (serviceMock, reporterMock) = createReporterMock()
val input = createReporterInput("$SCANCODE_1,$SCANCODE_2")
reporterMock.generateReport(input)
coVerifyAll {
serviceMock.generateReport(USER_KEY_SAMPLE, API_KEY_SAMPLE, SCANCODE_1, any(), any(), any())
serviceMock.generateReport(USER_KEY_SAMPLE, API_KEY_SAMPLE, SCANCODE_2, any(), any(), any())
}
}
"return the generated file(s)" {
val (_, reporterMock) = createReporterMock()
val input = createReporterInput(SCANCODE_1)
val reportFileResults = reporterMock.generateReport(input)
reportFileResults.shouldBeSingleton {
it shouldBeSuccess FILE_SAMPLE
}
}
"ignore scan results without a scancode" {
val (serviceMock, reporterMock) = createReporterMock()
val input = createReporterInput(SCANCODE_1)
reporterMock.generateReport(input)
coVerify(exactly = 1) {
serviceMock.generateReport(any(), any(), any(), any(), any(), any())
}
}
}
})
private fun FossIdReporter.generateReport(
input: ReporterInput,
options: Options = DEFAULT_OPTIONS,
secrets: Options = DEFAULT_SECRETS
) = generateReport(input, DIRECTORY_SAMPLE, PluginConfiguration(options, secrets))
private fun createReporterMock(): Pair<FossIdRestService, FossIdReporter> {
mockkObject(FossIdRestService)
val serviceMock = mockk<FossIdServiceWithVersion>()
val reporterMock = spyk<FossIdReporter>()
every { FossIdRestService.create(any()) } returns serviceMock
coEvery {
serviceMock.generateReport(any(), any(), any(), any(), any(), any())
} returns Result.success(FILE_SAMPLE)
return serviceMock to reporterMock
}
private fun createReporterInput(vararg scanCodes: String): ReporterInput {
val analyzedVcs = VcsInfo(
type = VcsType.GIT,
revision = "master",
url = "https://github.com/path/first-project.git",
path = "sub/path"
)
val results = scanCodes.associateByTo(
destination = sortedMapOf(),
keySelector = { Identifier.EMPTY.copy(name = it) },
valueTransform = { code ->
val unmatchedScanResult = ScanResult(
provenance = UnknownProvenance,
scanner = ScannerDetails.EMPTY.copy(name = "otherScanner"),
summary = ScanSummary.EMPTY
)
listOf(createScanResult(code), unmatchedScanResult)
}
)
return ReporterInput(
OrtResult(
repository = Repository(
config = RepositoryConfiguration(
excludes = Excludes(
scopes = listOf(
ScopeExclude(
pattern = "test",
reason = ScopeExcludeReason.TEST_DEPENDENCY_OF,
comment = "Packages for testing only."
)
)
)
),
vcs = analyzedVcs,
vcsProcessed = analyzedVcs
),
scanner = scannerRunOf(*results.toList().toTypedArray())
)
)
}
private fun createScanResult(scanCode: String): ScanResult =
ScanResult(
provenance = UnknownProvenance,
scanner = ScannerDetails.EMPTY,
summary = ScanSummary.EMPTY,
additionalData = mapOf(FossIdReporter.SCAN_CODE_KEY to scanCode)
)
| 335
| null |
309
| 873
|
0546d450d3082cff0c685897bef4c23e56a3d73a
| 11,808
|
ort
|
Apache License 2.0
|
clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationIndexParams.kt
|
algolia
| 419,291,903
| false
| null |
/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */
package com.algolia.client.model.search
import kotlinx.serialization.*
import kotlinx.serialization.json.*
/**
* OperationIndexParams
*
* @param operation
* @param destination The Algolia index name.
* @param scope Scope of the data to copy. When absent, a full copy is performed. When present, only the selected scopes are copied.
*/
@Serializable
public data class OperationIndexParams(
@SerialName(value = "operation") val operation: OperationType,
/** The Algolia index name. */
@SerialName(value = "destination") val destination: String,
/** Scope of the data to copy. When absent, a full copy is performed. When present, only the selected scopes are copied. */
@SerialName(value = "scope") val scope: List<ScopeType>? = null,
)
| 40
|
PHP
|
8
| 25
|
f14b2b4e48702209dcb0c09561a2c1c3361f75eb
| 939
|
api-clients-automation
|
MIT License
|
src/datagen/main/kotlin/mekanism/patchouli/dsl/DSL.kt
|
Sinmis077
| 408,979,434
| false
|
{"Java Properties": 1, "Shell": 1, "Markdown": 7, "Batchfile": 1, "Java": 1919, "Kotlin": 34, "Perl": 1, "Python": 1, "INI": 1}
|
@file:Suppress("MemberVisibilityCanBePrivate", "unused")//its an api
package mekanism.patchouli.dsl
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import mekanism.api.providers.IBlockProvider
import mekanism.api.providers.IGasProvider
import mekanism.api.providers.IItemProvider
import mekanism.common.content.gear.Modules
import net.minecraft.client.settings.KeyBinding
import net.minecraft.item.ItemStack
import net.minecraft.util.ResourceLocation
import org.apache.logging.log4j.LogManager
fun JsonObject.addProperty(name: String, res: ResourceLocation) {
addProperty(name, res.toString())
}
fun JsonObject.addProperty(name: String, item: ItemStack) {
addProperty(name, ItemStackUtils.serializeStack(item))
}
fun jsonObject(receiver: JsonObject.() -> Unit): JsonObject {
return JsonObject().also(receiver)
}
fun jsonArray(receiver: JsonArray.() -> Unit): JsonArray {
return JsonArray().apply(receiver)
}
fun Array<String>.toJsonArray():JsonArray = JsonArray().also { array->
this.forEach {
array.add(it)
}
}
fun Array<Number>.toJsonArray():JsonArray = JsonArray().also { array->
this.forEach {
array.add(it)
}
}
fun Array<Int>.toJsonArray():JsonArray = JsonArray().also { array->
this.forEach {
array.add(it)
}
}
val IItemProvider.bookId: String get() {
val type = if (this is IBlockProvider) "block" else "item"
return type + "/" + this.registryName.path
}
val IGasProvider.bookId: String get() = "gas/" + this.registryName.path
val Modules.ModuleData<*>.bookId: String get() = "items/modules/"+this.stack.item.registryName!!
private fun link(id:String, text:String): String = "$(l:${id})${text}$(/l)"
@PatchouliDSL
fun link(item: IItemProvider, text: String): String = link(item.bookId, text)
@PatchouliDSL
fun link(item: IGasProvider, text: String): String = link(item.bookId, text)
@PatchouliDSL
fun link(guideEntry: IGuideEntry, text: String): String = link(guideEntry.entryId, text)
@PatchouliDSL
fun link(module: Modules.ModuleData<*>, text: String): String = link(module.bookId, text)
operator fun KeyBinding.invoke(): String {
return "$(k:${keyDescription})"
}
val LOGGER = LogManager.getLogger("PatchouliDSL")!!
@DslMarker
annotation class PatchouliDSL
| 1
| null |
1
| 1
|
c42191d9d5a4e8add654a6cf8720abc8af2896c3
| 2,280
|
Mekanism
|
MIT License
|
src/main/kotlin/com/namju/simple_todo/todo/TodoForm.kt
|
cmsong111
| 689,422,737
| false
|
{"Kotlin": 15592, "HTML": 12892}
|
package com.namju.simple_todo.todo
data class TodoForm (
var title: String,
var content: String,
)
| 0
|
Kotlin
|
0
| 0
|
bdd2a427e69a1c84da2ef1bf3f34c582eca2a3dc
| 108
|
Simple_todo
|
MIT License
|
plugins/kotlin/src/main/kotlin/com/github/softwareplace/springboot/kotlin/openapi/Configuration.kt
|
softwareplace
| 749,152,259
| false
|
{"Kotlin": 53227, "Mustache": 12026, "Java": 4400, "Shell": 943, "Makefile": 535}
|
package com.github.softwareplace.springboot.kotlin.openapi
import com.github.softwareplace.springboot.utils.toCamelCase
import org.gradle.api.Project
import org.gradle.kotlin.dsl.*
import org.jetbrains.kotlin.gradle.dsl.kotlinExtension
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.openapitools.generator.gradle.plugin.extensions.OpenApiGeneratorGenerateExtension
import java.io.File
private const val JAVA_LOCAL_DATE_TIME = "java.time.LocalDateTime"
private const val JAVA_LOCAL_DATE = "java.time.LocalDate"
private const val JAVA_LOCAL_TIME = "java.time.LocalTime"
fun OpenApiGeneratorGenerateExtension.apply(
openApiSettings: OpenApiSettings,
projectPath: String,
openApiYamlFilePath: String = "${projectPath}/src/main/resources/${openApiSettings.swaggerFileName}"
) {
val customImportingMapping: Map<String, String> = when (openApiSettings.overrideImportMapping) {
true -> openApiSettings.importMapping
else -> {
val customImporting = mutableMapOf(
"date" to JAVA_LOCAL_DATE,
"local-date-time" to JAVA_LOCAL_DATE_TIME,
"time" to JAVA_LOCAL_TIME
)
customImporting.putAll(openApiSettings.importMapping)
openApiSettings.addCustomFormats.forEach { (key, source) ->
customImporting[key] = "${source.second}.${source.first}".toCamelCase()
}
customImporting
}
}
schemaMappings.putAll(customImportingMapping)
importMappings.putAll(customImportingMapping)
typeMappings.putAll(customImportingMapping)
generatorName.set(openApiSettings.generator)
this.groupId.set("${openApiSettings.groupId}${openApiSettings.sourceFolder}")
packageName.set("${openApiSettings.groupId}${openApiSettings.sourceFolder}")
inputSpec.set(openApiYamlFilePath)
generateApiDocumentation.set(true)
outputDir.set("${projectPath}/build/generate-resources")
apiPackage.set("${openApiSettings.groupId}${openApiSettings.sourceFolder}${openApiSettings.controllerPackage}")
invokerPackage.set("${openApiSettings.groupId}${openApiSettings.sourceFolder}${openApiSettings.invokerPackage}")
apiNameSuffix.set(openApiSettings.apiNameSuffix)
modelNameSuffix.set(openApiSettings.modelNameSuffix)
modelPackage.set("${openApiSettings.groupId}${openApiSettings.sourceFolder}${openApiSettings.modelPackage}")
skipOperationExample.set(true)
val pluginConfigOptions: MutableMap<String, String> = mutableMapOf(
"additionalModelTypeAnnotations" to openApiSettings.additionalModelTypeAnnotations.joinToString(separator = "\n"),
"documentationProvider" to openApiSettings.documentationProvider.type,
"apiSuffix" to openApiSettings.apiNameSuffix,
"apiNameSuffix" to openApiSettings.apiNameSuffix,
"interfaceOnly" to "true",
"skipDefaultInterface" to "true",
"defaultInterfaces" to "false",
"delegatePattern" to "false",
"serializationLibrary" to "jackson",
"gradleBuildFile" to "false",
"enumPropertyNaming" to "original",
"exceptionHandler" to "false",
"useSpringBoot3" to "true",
"useSwaggerUI" to "true",
"useTags" to "true",
"generateApis" to "true",
"java8" to "true"
)
if (openApiSettings.reactive) {
pluginConfigOptions.putAll(mapOf("reactive" to "${openApiSettings.reactive}"))
}
pluginConfigOptions.putAll(openApiSettings.configOptions)
configOptions.set(pluginConfigOptions)
}
fun Project.openApiGenerateConfig(openApiSettings: OpenApiSettings) {
extensions.getByName<OpenApiGeneratorGenerateExtension>("openApiGenerate").apply {
openApiSettings.templateDir?.let {
templateDir.set(it)
}
}
if (openApiSettings.groupId.isBlank()) {
openApiSettings.groupId = group.toString()
}
extensions.getByName<OpenApiGeneratorGenerateExtension>("openApiGenerate").apply(
openApiSettings = openApiSettings,
projectPath = projectDir.path,
)
extra["snippetsDir"] = file("build/generated-snippets")
kotlinExtension.sourceSets["main"].kotlin {
srcDir("$projectDir/build/generate-resources/src/main/kotlin")
exclude(openApiSettings.filesExclude)
}
tasks {
register("openapiResourceValidation") {
revalidateFile(File("$projectDir/build/generate-resources/src/main/kotlin"), openApiSettings)
}
getByName("openApiGenerate") {
doLast { tasks.findByName("openapiResourceValidation") }
}
withType<KotlinCompile> {
dependsOn(tasks.findByName("openApiGenerate"))
}
}
}
private fun revalidateFile(directory: File, openApiSettings: OpenApiSettings) {
directory.walkTopDown().forEach { file ->
if (file.isFile) {
var didChange = false
var fileContent = file.readText()
if (fileContent.contains("@RequestMapping") && fileContent.contains("@Tag")) {
fileContent = replaceTagInContent(fileContent)
didChange = true
}
openApiSettings.addCustomFormats.forEach { (_, value) ->
val simpleClassNameKey =
"${value.second}.${value.first}${openApiSettings.modelNameSuffix}".toCamelCase()
val className = "${value.second}.${value.first}"
if (fileContent.contains(simpleClassNameKey)) {
fileContent = fileContent.replace(Regex("import.*$simpleClassNameKey"), "")
fileContent = fileContent.replace(simpleClassNameKey, className)
didChange = true
}
}
if (didChange) {
file.writeText(fileContent)
}
}
}
}
private fun replaceTagInContent(content: String): String {
val tagPattern = """\@Tag\([^)]*\)""".toRegex()
val matchingTag = tagPattern.find(content)?.value
if (!matchingTag.isNullOrBlank() && matchingTag.isNotBlank()) {
val namePattern = """name\s+=\s+\".*\"""".toRegex()
val nameValue = namePattern.find(matchingTag)?.value?.replace("""name\s+=\s+""".toRegex(), "")
if (!nameValue.isNullOrBlank() && nameValue.isNotBlank()) {
return content.replaceFirst(nameValue, camelCaseToSeparated(nameValue))
}
}
return content
}
fun camelCaseToSeparated(input: String): String {
val separated = input.replace(Regex("(\\p{Upper})")) { " ${it.value}" }
return separated.trim()
.replace("\" ", "\"")
}
| 0
|
Kotlin
|
0
| 1
|
9d4c43c97b41cf5d645f3540af43b20b208968fd
| 6,646
|
springboot
|
Apache License 2.0
|
feature/start/src/main/java/jp/kaleidot725/easycalc/feature/start/StartEvent.kt
|
kaleidot725
| 727,725,457
| false
|
{"Kotlin": 331989, "Ruby": 106}
|
package jp.kaleidot725.easycalc.feature.start
import jp.kaleidot725.easycalc.core.domain.model.text.MathText
sealed interface StartEvent {
data class ClickStart(val mathText: MathText) : StartEvent
object PopBack : StartEvent
}
| 3
|
Kotlin
|
0
| 0
|
dfac12510fcceab27755428a16368076fd5302fd
| 238
|
EasyCalc
|
MIT License
|
app/src/main/java/com/deathhit/myleetcodesolutions/question_model/QuestionModel.kt
|
Deathhit
| 444,368,316
| false
| null |
package com.deathhit.myleetcodesolutions.question_model
import android.content.Context
import android.text.Spanned
import com.deathhit.myleetcodesolutions.model.AnswerVO
abstract class QuestionModel(val context: Context) {
abstract val code: Spanned
abstract val description: String
abstract fun run(): AnswerVO
}
| 0
|
Kotlin
|
0
| 0
|
cde7915f837a2a677748716989b0818934567608
| 328
|
MyLeetCodeSolutions
|
Apache License 2.0
|
server/libs/src/main/kotlin/jetty/EndPoint.kt
|
glennneiger
| 205,309,986
| true
|
{"Kotlin": 94120, "TypeScript": 56880, "HTML": 13948, "JavaScript": 3774, "CSS": 2901, "Dockerfile": 1773, "Shell": 1070}
|
package jetty
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import objects.EndPointReply
import org.apache.commons.io.IOUtils
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.io.IOException
import java.time.LocalDateTime
import java.time.ZoneOffset
open class EndPoint : HttpServlet() {
var showTrace = false
var myEndPointName = ""
@Throws(ServletException::class, IOException::class)
public override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
resp.contentType = "application/json"
resp.characterEncoding = "UTF-8"
resp.status = HttpServletResponse.SC_OK
/* Current time */
val utcTime = LocalDateTime.now(ZoneOffset.UTC)
val endPointReply = EndPointReply()
val gson = GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.serializeNulls()
.create()
var str_request: String? = IOUtils.toString(req.inputStream, "UTF-8")
// Get a list of all active tournaments
try {
if (str_request == null || str_request == "") {
str_request = "{}"
}
val obj = gson.fromJson(str_request, JsonObject::class.java)
this.doAction(gson, obj, endPointReply, utcTime)
} catch (e: Exception) {
e.printStackTrace()
} finally {
val str_response = gson.toJson(endPointReply, EndPointReply::class.java)
if (showTrace) {
println(myEndPointName + "\n" + str_response)
}
resp.outputStream.print(str_response)
}
}
@Throws(Exception::class)
open fun doAction(gson: Gson, obj: JsonObject, endPointReply: EndPointReply, utcTime: LocalDateTime) {
//All endpoints replace this
}
}
| 0
|
Kotlin
|
0
| 0
|
e0e7c8e361abc88c332ffc2fca3e8778b69c30d2
| 2,023
|
user-login-flow
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/org/sam/app/pesentation/home/HomeScreen.kt
|
Usama-Aman
| 737,119,593
| false
|
{"Kotlin": 52440, "Swift": 532, "JavaScript": 475, "HTML": 280}
|
package org.sam.app.pesentation.home
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.koin.getScreenModel
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import org.sam.app.pesentation.home.components.MoviesListItem
import org.sam.app.pesentation.home.components.HomeTopBar
import org.sam.app.pesentation.movie_detail.MovieDetailScreen
class HomeScreen : Screen {
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
val viewModel: HomeScreenViewModel = getScreenModel<HomeScreenViewModel>()
val nowPlayingState by viewModel.nowPlayingState.collectAsState()
val popularMoviesState by viewModel.popularMoviesState.collectAsState()
val topRatedMoviesState by viewModel.topRatedMoviesState.collectAsState()
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
.padding(top = 20.dp)
) {
Column(
Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
HomeTopBar()
MoviesListItem(
movies = popularMoviesState.movies,
title = "Popular",
isLoading = popularMoviesState.isLoading,
onMovieClicked = {
navigator.push(MovieDetailScreen(it))
}
)
MoviesListItem(
movies = nowPlayingState.movies,
title = "Now Playing",
isLoading = nowPlayingState.isLoading,
onMovieClicked = {
navigator.push(MovieDetailScreen(it))
}
)
MoviesListItem(
movies = topRatedMoviesState.movies,
isLoading = topRatedMoviesState.isLoading,
title = "Top Rated",
onMovieClicked = {
navigator.push(MovieDetailScreen(it))
}
)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
98f3f06134bac50f7c502aebf2cc5f2e8332a924
| 2,847
|
compose-multiplatform-movies-app
|
Apache License 2.0
|
app/src/main/java/com/roadster/roam/basesetup/utils/SpannableUtils.kt
|
Atul206
| 510,028,347
| false
|
{"Kotlin": 118252}
|
package com.roadster.roam.basesetup.utils
import android.content.Context
import android.graphics.Paint
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.TypefaceSpan
import android.view.View
import androidx.annotation.ColorRes
import androidx.annotation.FontRes
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import com.roadster.roam.basesetup.R
import com.roadster.roam.basesetup.extensions.UNDEFINED_INT
fun CharSequence.applyClickSpan(
givenString: String?,
action: () -> Unit,
source: SpannableString = SpannableString(this)
): CharSequence {
givenString?.let {
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
action()
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = true
}
}
val startIndex = source.indexOf(givenString, ignoreCase = true)
val endIndex = startIndex + givenString.length
source.setSpan(clickableSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
return source
}
fun CharSequence.applyFontSpan(
context: Context,
@FontRes font: Int,
givenString: String?,
source: SpannableString = SpannableString(this)
): CharSequence {
givenString?.let {
val typeface = ResourcesCompat.getFont(context, font)
val startIndex = source.indexOf(givenString, ignoreCase = true)
val endIndex = startIndex + givenString.length
source.setSpan(
CustomTypefaceSpan(typeface),
startIndex,
endIndex,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
return source
}
fun CharSequence.applyColorSpan(
context: Context,
@ColorRes color: Int,
givenString: String?,
source: SpannableString = SpannableString(this)
): CharSequence {
givenString?.let {
val startIndex = source.indexOf(givenString, ignoreCase = true)
val endIndex = startIndex + givenString.length
source.setSpan(
ForegroundColorSpan(ContextCompat.getColor(context, color)),
startIndex,
endIndex,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
return source
}
class CustomTypefaceSpan(private val newType: Typeface?) : TypefaceSpan("") {
override fun updateDrawState(ds: TextPaint) {
applyCustomTypeFace(ds, newType)
}
override fun updateMeasureState(paint: TextPaint) {
applyCustomTypeFace(paint, newType)
}
private fun applyCustomTypeFace(paint: Paint, tf: Typeface?) {
tf?.let {
val oldStyle: Int
val old = paint.typeface
oldStyle = old?.style ?: 0
val fake = oldStyle and tf.style.inv()
if (fake and Typeface.BOLD != 0) {
paint.isFakeBoldText = true
}
if (fake and Typeface.ITALIC != 0) {
paint.textSkewX = -0.25f
}
paint.typeface = tf
}
}
}
| 0
|
Kotlin
|
1
| 0
|
46ed3bd53e40ec7edf5a6063c6f8f8e556dc2225
| 3,326
|
baserepo
|
MIT License
|
app/src/main/java/uz/pdp/dagger2nuntium/adapters/HomeRvAdapter.kt
|
mukhtorov712
| 518,228,649
| false
| null |
package uz.pdp.dagger2nuntium.adapters
import android.view.LayoutInflater
import android.view.OnReceiveContentListener
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import uz.pdp.dagger2nuntium.R
import uz.pdp.dagger2nuntium.database.entity.Article
import uz.pdp.dagger2nuntium.databinding.ItemNews1Binding
import uz.pdp.dagger2nuntium.utils.hide
import java.lang.Exception
class HomeRvAdapter(private val listener: OnNewsItemClickListener) :
ListAdapter<Article, HomeRvAdapter.Vh>(MyDiffUtil()) {
class MyDiffUtil : DiffUtil.ItemCallback<Article>() {
override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean {
return oldItem.publishedAt == newItem.publishedAt
}
override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean {
return oldItem == newItem
}
}
inner class Vh(private val itemBinding: ItemNews1Binding) :
RecyclerView.ViewHolder(itemBinding.root) {
fun onBind(article: Article) {
itemBinding.apply {
Picasso.get().load(article.urlToImage).resize(70, 70).centerCrop().into(image, object :Callback{
override fun onSuccess() {
placeholder.hide()
}
override fun onError(e: Exception?) {}
})
title.text = article.title
author.text = article.author
}
itemView.setOnClickListener {
listener.onItemClick(article)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Vh {
return Vh(ItemNews1Binding.inflate(LayoutInflater.from(parent.context), parent, false))
}
override fun onBindViewHolder(holder: Vh, position: Int) {
holder.onBind(getItem(position))
}
interface OnNewsItemClickListener {
fun onItemClick(article: Article)
}
}
| 0
|
Kotlin
|
0
| 2
|
f47da2dd71e007cd7c4644e4f99c1f82920e4ddb
| 2,178
|
NuntiumNews
|
MIT License
|
app/src/main/kotlin/me/xizzhu/android/joshua/core/repository/local/android/db/BookmarkDao.kt
|
xizzhu
| 173,533,770
| false
| null |
/*
* Copyright (C) 2020 <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 me.xizzhu.android.joshua.core.repository.local.android.db
import android.database.sqlite.SQLiteOpenHelper
import me.xizzhu.android.joshua.core.Bookmark
import me.xizzhu.android.joshua.core.VerseIndex
class BookmarkDao(sqliteHelper: SQLiteOpenHelper) : VerseAnnotationDao<Bookmark>(sqliteHelper, TABLE_BOOKMARK) {
companion object {
private const val TABLE_BOOKMARK = "bookmark"
}
override fun Map<String, Any?>.toVerseAnnotation(verseIndex: VerseIndex, timestamp: Long): Bookmark =
Bookmark(verseIndex, timestamp)
override fun defaultVerseAnnotation(verseIndex: VerseIndex): Bookmark = Bookmark(verseIndex, -1L)
}
| 23
|
Kotlin
|
8
| 26
|
db43163619c37fd7febd208eb7bde2ffefc4fa99
| 1,258
|
Joshua
|
Apache License 2.0
|
src/functionalTest/kotlin/com/autonomousapps/utils/runner.kt
|
tasomaniac
| 250,905,017
| true
|
{"Kotlin": 316360, "Java": 71861, "ANTLR": 68053, "Groovy": 18464, "Shell": 587}
|
@file:JvmName("Runner")
package com.autonomousapps.utils
import com.autonomousapps.fixtures.ProjectDirProvider
import org.gradle.testkit.runner.GradleRunner
import org.gradle.util.GradleVersion
internal fun build(
gradleVersion: GradleVersion,
projectDirProvider: ProjectDirProvider,
vararg args: String
) = runner(gradleVersion, projectDirProvider, *args).build()
internal fun buildAndFail(
gradleVersion: GradleVersion,
projectDirProvider: ProjectDirProvider,
vararg args: String
) = runner(gradleVersion, projectDirProvider, *args).buildAndFail()
internal fun runner(
gradleVersion: GradleVersion,
projectDirProvider: ProjectDirProvider,
vararg args: String
): GradleRunner = GradleRunner.create().apply {
forwardOutput()
withPluginClasspath()
withGradleVersion(gradleVersion.version)
withProjectDir(projectDirProvider.projectDir)
withArguments(*args)
//withDebug(true)
}
| 0
| null |
0
| 1
|
866161796c564fc19b6fcca2343f438e8ec9aeff
| 910
|
dependency-analysis-android-gradle-plugin
|
Apache License 2.0
|
src/main/kotlin/io/xmake/utils/Command.kt
|
xmake-io
| 108,999,121
| false
|
{"Kotlin": 78237, "HTML": 3740}
|
package io.xmake.utils
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessNotCreatedException
import com.intellij.execution.util.ExecUtil
import com.jetbrains.rd.util.Callable
import io.xmake.utils.interact.kSystemEnv
import io.xmake.utils.interact.kLineSeparator
import java.io.FileNotFoundException
import java.io.IOException
import java.util.concurrent.Executors
import java.util.concurrent.Future
/**
* [ioRunv]
*
* @param argv the command arguments
* @param workDir the working directory
* @return a List<String>, the all output of the command
*/
fun ioRunv(argv: List<String>, workDir: String? = null): List<String> {
val call = Callable {
val ret: List<String> = listOf("")
try {
val commandLine: GeneralCommandLine = GeneralCommandLine(argv)
.withWorkDirectory(workDir)
.withCharset(Charsets.UTF_8)
.withEnvironment(kSystemEnv)
.withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE)
commandLine.withEnvironment("COLORTERM", "nocolor")
val output = ExecUtil.execAndGetOutput(commandLine)
output.stdout.split(kLineSeparator)
} catch (e: Exception) {
ret
}
}
val executor = Executors.newSingleThreadExecutor()
val commandOutput: Future<List<String>> = executor.submit(call)
val result = commandOutput.get()
executor.shutdown()
return result
}
/**
* [ioRunvLine]
*
* @param argv the command arguments
* @param minLine return begin line
* @param maxLine return end line
* @param workDir the working directory
* @return a string containing the lines of output from the command,
* starting from the line number specified by `minLine` and ending at the line number specified by `maxLine`.
* If the command produces fewer lines than `minLine`, the return will be an empty string.
* If the command produces lines but fewer than `maxLine`, all lines from `minLine` to the end of output will be returned.
* Lines are returned as a single string, with each line separated by the system's line separator.
*/
fun ioRunvLine(argv: List<String>, minLine: Int, maxLine: Int = minLine, workDir: String? = null): String {
TODO()
}
/**
* [vRunv]
*
* output on console
* @param console the console
* @param argv the command arguments
* @param workDir the working directory
* @return void
*/
inline fun vRunv(console: String/*TODO()*/, argv: List<String>, workDir: String? = null) {
TODO()
}
| 12
|
Kotlin
|
15
| 70
|
30c11627caf051f9d131c48397fb37f66c7e5738
| 2,582
|
xmake-idea
|
Apache License 2.0
|
app/src/main/java/com/niceplaces/niceplaces/utils/StringUtils.kt
|
niceplaces
| 460,602,891
| false
| null |
package com.niceplaces.niceplaces.utils
import android.util.Log
import androidx.core.text.HtmlCompat
import java.text.SimpleDateFormat
import java.util.*
object StringUtils {
fun listToString(list: List<Int?>): String {
var string = ""
for (i in list.indices) {
string = string + Integer.toString(list[i]!!)
}
return string
}
fun printList(list: List<String>) {
for (i in list.indices) {
Log.i("STRING_ARRAY", "[" + i + "] " + list[i])
}
}
fun timestampToDate(l: Long?): String? {
return if (l != null){
try {
val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.ROOT)
val netDate = Date(l)
sdf.format(netDate)
} catch (e: Exception) {
e.toString()
}
} else {
l.toString()
}
}
fun html2text(html: String?): String? {
return html?.let { HtmlCompat.fromHtml(it, HtmlCompat.FROM_HTML_MODE_LEGACY).toString() }
}
}
| 3
|
Kotlin
|
2
| 3
|
71e4c002adb34ceda5145f1a3d0ee57b0190d06f
| 1,058
|
android-app
|
MIT License
|
app/src/main/java/com/mi/mvi/remote/service/BlogAPIService.kt
|
omar-adel
| 258,101,649
| true
|
{"Kotlin": 174763}
|
package com.mi.mvi.remote.service
import com.mi.mvi.remote.entity.BaseResponse
import com.mi.mvi.remote.entity.BlogListResponse
import com.mi.mvi.remote.entity.BlogPostResponse
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.http.*
interface BlogAPIService {
@GET("blog/list")
suspend fun searchListBlogPosts(
@Header("Authorization") authorization: String,
@Query("search") query: String,
@Query("ordering") ordering: String,
@Query("page") page: Int
): BlogListResponse
@GET("blog/{slug}/is_author")
suspend fun isAuthorOfBlogPost(
@Header("Authorization") authorization: String,
@Path("slug") slug: String
): BaseResponse
@DELETE("blog/{slug}/delete")
suspend fun deleteBlogPost(
@Header("Authorization") authorization: String,
@Path("slug") slug: String
): BaseResponse
@Multipart
@PUT("blog/{slug}/update")
suspend fun updateBlog(
@Header("Authorization") authorization: String,
@Path("slug") slug: String,
@Part("title") title: RequestBody,
@Part("body") body: RequestBody,
@Part image: MultipartBody.Part?
): BlogPostResponse
@Multipart
@POST("blog/create")
suspend fun createBlog(
@Header("Authorization") authorization: String,
@Part("title") title: RequestBody,
@Part("body") body: RequestBody,
@Part image: MultipartBody.Part?
): BlogPostResponse
}
| 0
| null |
0
| 0
|
f9ae471ef25e8b208b8439e7c51d446e72643b23
| 1,496
|
Android-Kotlin-MVI-CleanArchitecture
|
MIT License
|
weather/src/main/java/ru/androidpiraters/aiweather/data/model/weather/WeatherInfo.kt
|
Luckyss
| 135,089,769
| false
|
{"Kotlin": 111674}
|
package ru.androidpiraters.aiweather.data.model.weather
data class WeatherInfo(
val dt: Int,
val coord: Coord,
val visibility: Int,
val weather: List<WeatherItem?>,
val name: String,
val cod: Int,
val main: Main,
val clouds: Clouds,
val id: Int,
val sys: Sys,
val base: String,
val wind: Wind
) {
private constructor(builder: Builder) : this(
builder.dt,
builder.coord,
builder.visibility,
builder.weather,
builder.name,
builder.cod,
builder.main,
builder.clouds,
builder.id,
builder.sys,
builder.base,
builder.wind
)
companion object {
inline fun build(block: Builder.() -> Unit) = Builder().apply(block).build()
}
class Builder {
internal var dt: Int = 0
internal var coord: Coord = Coord()
internal var visibility: Int = 0
internal var weather: List<WeatherItem?> = ArrayList()
internal var name: String = ""
internal var cod: Int = 0
internal var main: Main = Main()
internal var clouds: Clouds = Clouds()
internal var id: Int = 0
internal var sys: Sys = Sys()
internal var base: String = ""
internal var wind: Wind = Wind()
fun dt(dt: Int): Builder {
this.dt = dt
return this
}
fun coord(coord: Coord): Builder {
this.coord = coord
return this
}
fun visibility(visibility: Int): Builder {
this.visibility = visibility
return this
}
fun weather(weather: List<WeatherItem?>): Builder {
this.weather = weather
return this
}
fun name(name: String): Builder {
this.name = name
return this
}
fun cod(cod: Int): Builder {
this.cod = cod
return this
}
fun main(main: Main): Builder {
this.main = main
return this
}
fun clouds(clouds: Clouds): Builder {
this.clouds = clouds
return this
}
fun id(id: Int): Builder {
this.id = id
return this
}
fun sys(sys: Sys): Builder {
this.sys = sys
return this
}
fun base(base: String): Builder {
this.base = base
return this
}
fun wind(wind: Wind): Builder {
this.wind = wind
return this
}
fun build() = WeatherInfo(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
e1f4e39a153de104f5983b48b478ae751feaa36d
| 2,735
|
aiweather
|
Apache License 2.0
|
apina-core/src/test/kotlin/fi/evident/apina/spring/TypeTranslatorTest.kt
|
EvidentSolutions
| 36,000,351
| false
| null |
@file:Suppress("PLUGIN_IS_NOT_ENABLED")
package fi.evident.apina.spring
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeName
import com.fasterxml.jackson.annotation.JsonUnwrapped
import fi.evident.apina.java.model.JavaClass
import fi.evident.apina.java.model.JavaModel
import fi.evident.apina.java.model.type.JavaType
import fi.evident.apina.java.model.type.TypeEnvironment
import fi.evident.apina.java.model.type.TypeSchema
import fi.evident.apina.java.reader.TestClassMetadataLoader
import fi.evident.apina.model.ApiDefinition
import fi.evident.apina.model.ClassDefinition
import fi.evident.apina.model.EnumDefinition
import fi.evident.apina.model.settings.OptionalTypeMode
import fi.evident.apina.model.settings.TranslationSettings
import fi.evident.apina.model.type.ApiType
import fi.evident.apina.model.type.ApiTypeName
import fi.evident.apina.spring.testclasses.*
import kotlinx.serialization.SerialName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.util.Collections.emptyList
import java.util.Collections.singletonMap
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlin.test.fail
class TypeTranslatorTest {
private val api = ApiDefinition()
private val settings = TranslationSettings()
private val loader = TestClassMetadataLoader()
private val model = JavaModel(loader)
private val translator = TypeTranslator(settings, model, api)
@Test
fun `translating class with value and inline classes`() {
val classDefinition = translateClass<ClassWithValueClasses>()
assertEquals(ApiTypeName(ClassWithValueClasses::class.java.simpleName), classDefinition.type)
assertHasProperties(
classDefinition,
"valueString" to ApiType.Primitive.STRING,
"valueInteger" to ApiType.Primitive.INTEGER,
"nestedValueInteger" to ApiType.Primitive.INTEGER,
"getterValue" to ApiType.Primitive.STRING
)
}
@Test
fun `translating class with field properties`() {
val classDefinition = translateClass<ClassWithFieldProperties>()
assertEquals(ApiTypeName(ClassWithFieldProperties::class.java.simpleName), classDefinition.type)
assertHasProperties(
classDefinition,
"intField" to ApiType.Primitive.INTEGER,
"floatField" to ApiType.Primitive.FLOAT,
"doubleField" to ApiType.Primitive.FLOAT,
"integerField" to ApiType.Primitive.INTEGER,
"stringField" to ApiType.Primitive.STRING,
"booleanField" to ApiType.Primitive.BOOLEAN,
"booleanNonPrimitiveField" to ApiType.Primitive.BOOLEAN,
"intArrayField" to ApiType.Array(ApiType.Primitive.INTEGER),
"rawCollectionField" to ApiType.Array(ApiType.Primitive.ANY),
"wildcardMapField" to ApiType.Dictionary(ApiType.Primitive.ANY),
"rawMapField" to ApiType.Dictionary(ApiType.Primitive.ANY),
"stringIntegerMapField" to ApiType.Dictionary(ApiType.Primitive.INTEGER),
"objectField" to ApiType.Primitive.ANY,
"stringCollectionField" to ApiType.Array(ApiType.Primitive.STRING)
)
}
@Test
fun `translating class with getter properties`() {
val classDefinition = translateClass<ClassWithGetters>()
assertEquals(ApiTypeName(ClassWithGetters::class.java.simpleName), classDefinition.type)
assertHasProperties(
classDefinition,
"int" to ApiType.Primitive.INTEGER,
"integer" to ApiType.Primitive.INTEGER,
"string" to ApiType.Primitive.STRING,
"boolean" to ApiType.Primitive.BOOLEAN,
"booleanNonPrimitive" to ApiType.Primitive.BOOLEAN
)
}
@Test
fun `translating class with overlapping field and getter`() {
val classDefinition = translateClass<TypeWithOverlappingFieldAndGetter>()
assertHasProperties(classDefinition, "foo" to ApiType.Primitive.STRING)
}
@Test
fun `translate void type`() {
assertEquals(ApiType.Primitive.VOID, translateType(JavaType.Basic.VOID))
}
@Test
fun `translate black-box type`() {
settings.blackBoxClasses.addPattern("foo\\..+")
assertEquals(ApiType.BlackBox(ApiTypeName("Baz")),
translateType(JavaType.Basic("foo.bar.Baz"))
)
}
@Test
fun `translating optional types`() {
val classDefinition = translateClass<ClassWithOptionalTypes>()
assertEquals(ApiTypeName(ClassWithOptionalTypes::class.java.simpleName), classDefinition.type)
assertHasProperties(
classDefinition,
"optionalString" to ApiType.Nullable(ApiType.Primitive.STRING),
"optionalInt" to ApiType.Nullable(ApiType.Primitive.INTEGER),
"optionalLong" to ApiType.Nullable(ApiType.Primitive.INTEGER),
"optionalDouble" to ApiType.Nullable(ApiType.Primitive.FLOAT)
)
}
@Test
fun `types with @JsonValue should be translated as aliased types`() {
loader.loadClassesFromInheritanceTree<ClassWithJsonValue>()
val apiType = translateType<ClassWithJsonValue>()
assertEquals(ApiType.BlackBox(ApiTypeName("ClassWithJsonValue")), apiType)
assertEquals(singletonMap(ApiTypeName("ClassWithJsonValue"), ApiType.Primitive.STRING), api.typeAliases)
}
@Test
fun `duplicate class names`() {
val class1 =
JavaClass(JavaType.Basic("foo.MyClass"), JavaType.Basic("java.lang.Object"), emptyList(), 0, TypeSchema())
val class2 =
JavaClass(JavaType.Basic("bar.MyClass"), JavaType.Basic("java.lang.Object"), emptyList(), 0, TypeSchema())
loader.addClass(class1)
loader.addClass(class2)
val env = TypeEnvironment.empty()
translator.translateType(class1.type, class1, env)
assertFailsWith<DuplicateClassNameException> {
translator.translateType(class2.type, class2, env)
}
}
@Nested
inner class `handling @JsonIgnore` {
@Test
fun `class hierarchy with ignores`() {
val classDefinition = translateClass<TypeWithIgnoresAndSuperClass>()
assertEquals(setOf("bar", "baz"), classDefinition.propertyNames)
}
@Test
fun `ignores can be overridden in sub classes`() {
val classDefinition = translateClass<TypeWithOverridingIgnore>()
assertEquals(setOf("foo"), classDefinition.propertyNames)
}
}
@Test
fun `ignore properties annotated with java beans Transient`() {
val classDefinition = translateClass<ClassWithTransientIgnore>()
assertEquals(setOf("bar"), classDefinition.propertyNames)
}
@Test
fun `ignore properties annotated with Spring Data Transient`() {
val classDefinition = translateClass<ClassWithSpringDataTransient>()
assertEquals(setOf("foo"), classDefinition.propertyNames)
}
@Test
fun `ignore transient fields`() {
val classDefinition = translateClass<ClassWithTransientFields>()
assertEquals(setOf("foo", "baz"), classDefinition.propertyNames)
}
@Test
fun `interface with properties`() {
val classDefinition = translateClass<TypeWithPropertiesFromInterface>()
assertHasProperties(
classDefinition,
"foo" to ApiType.Primitive.STRING,
"bar" to ApiType.Primitive.STRING
)
}
@Test
fun `enum translation`() {
val enumDefinition = translateEnum<TestEnum>()
assertEquals(listOf("FOO", "BAR", "BAZ"), enumDefinition.constants)
}
@Test
fun `generic type without known parameters`() {
val classDefinition = translateClass<GenericType<*>>()
assertHasProperties(classDefinition, "genericField" to ApiType.Primitive.ANY)
}
@Test
fun `generic type inherited by fixing parameters`() {
val classDefinition = translateClass<SubTypeOfGenericType>()
assertHasProperties(classDefinition, "genericField" to ApiType.Primitive.STRING)
}
@Test
fun `generic type inherited through middle type`() {
val classDefinition = translateClass<SecondOrderSubTypeOfGenericType>()
assertHasProperties(classDefinition, "genericField" to ApiType.Primitive.STRING)
}
@Test
fun `generic type inherited through middle type that parameterizes with variable`() {
val classDefinition = translateClass<SubTypeOfGenericTypeParameterizedWithVariable>()
assertHasProperties(classDefinition, "genericField" to ApiType.Array(ApiType.Primitive.STRING))
}
@Test
fun `generic type parameters are translated for unknown generic types`() {
class Foo
class Bar
@Suppress("unused")
class GenericType<T, S>
class Root {
@Suppress("unused")
lateinit var foo: GenericType<Foo, Bar>
}
loader.loadClassesFromInheritanceTree<Root>()
loader.loadClassesFromInheritanceTree<GenericType<*, *>>()
loader.loadClassesFromInheritanceTree<Foo>()
loader.loadClassesFromInheritanceTree<Bar>()
translator.translateType(JavaType.basic<Root>(), MockAnnotatedElement(), TypeEnvironment.empty())
assertTrue(api.classDefinitions.any { it.type.name == "Foo" }, "Class definition for Foo is created")
assertTrue(api.classDefinitions.any { it.type.name == "Bar" }, "Class definition for Bar is created")
}
@Test
fun `unbound type variable`() {
@Suppress("unused")
abstract class Bar<A>
class Foo<B> : Bar<B>()
assertEquals("Foo", translateClass<Foo<*>>().type.name)
}
interface GenericSuperType<out T> {
@Suppress("unused")
fun get(): T
}
interface GenericSubType<out T> : GenericSuperType<T>
@Test
fun `shadowed types should not prevent translation`() {
translateClass<GenericSubType<String>>()
}
@Nested
inner class `discriminated unions` {
@Test
fun `translating discriminated unions`() {
loader.loadClassesFromInheritanceTree<Vehicle>()
loader.loadClassesFromInheritanceTree<Vehicle.Car>()
loader.loadClassesFromInheritanceTree<Vehicle.Truck>()
translator.translateType(JavaType.basic<Vehicle>(), MockAnnotatedElement(), TypeEnvironment.empty())
assertEquals(1, api.discriminatedUnionDefinitions.size)
val definition = api.discriminatedUnionDefinitions.first()
assertEquals("Vehicle", definition.type.name)
assertEquals("type", definition.discriminator)
val types = definition.types
assertEquals(2, types.size)
assertEquals(setOf("car", "truck"), types.keys)
assertEquals("Car", types["car"]?.type?.name)
assertEquals("Truck", types["truck"]?.type?.name)
// ensure that subclasses themselves are not translated
assertEquals(0, api.classDefinitions.size)
}
@Test
fun `without @JsonSubtypes`() {
loader.loadClassesFromInheritanceTree<Vehicle2>()
loader.loadClassesFromInheritanceTree<Vehicle2.Car>()
loader.loadClassesFromInheritanceTree<Vehicle2.Truck>()
val translator = TypeTranslator(settings, model, api)
translator.translateType(JavaType.basic<Vehicle2>(), MockAnnotatedElement(), TypeEnvironment.empty())
assertEquals(1, api.discriminatedUnionDefinitions.size)
val definition = api.discriminatedUnionDefinitions.first()
assertEquals("Vehicle2", definition.type.name)
assertEquals("type", definition.discriminator)
val types = definition.types
assertEquals(2, types.size)
assertEquals(setOf("car", "truck"), types.keys)
assertEquals("Car", types["car"]?.type?.name)
assertEquals("Truck", types["truck"]?.type?.name)
// ensure that subclasses themselves are not translated
assertEquals(0, api.classDefinitions.size)
}
}
@Test
fun `translating unwrapped properties`() {
@Suppress("unused")
class Name(val first: String, val last: String)
@Suppress("unused")
class Person(@get:JsonUnwrapped val name: Name, val age: Int)
loader.loadClassesFromInheritanceTree<Name>()
loader.loadClassesFromInheritanceTree<Person>()
translator.translateType(JavaType.basic<Person>(), MockAnnotatedElement(), TypeEnvironment.empty())
assertEquals(1, api.classDefinitionCount)
val person = api.classDefinitions.find { it.type.name == "Person" } ?: error("no Person found")
assertEquals(setOf("age", "first", "last"), person.properties.map { it.name }.toSet())
}
@Test
fun `translating unwrapped with prefixes and suffixes`() {
@Suppress("unused")
class Name(val first: String, val last: String)
@Suppress("unused")
class Person(
@get:JsonUnwrapped(suffix = "Name") val name: Name,
@get:JsonUnwrapped(prefix = "foo", suffix = "bar") val name2: Name,
val age: Int
)
loader.loadClassesFromInheritanceTree<Name>()
loader.loadClassesFromInheritanceTree<Person>()
translator.translateType(JavaType.basic<Person>(), MockAnnotatedElement(), TypeEnvironment.empty())
assertEquals(1, api.classDefinitionCount)
val person = api.classDefinitions.find { it.type.name == "Person" } ?: error("no Person found")
assertEquals(
setOf("age", "firstName", "lastName", "foofirstbar", "foolastbar"),
person.properties.map { it.name }.toSet()
)
}
@Test
fun `override translated class name`() {
@Suppress("unused")
class Foo(val foo: String)
settings.nameTranslator.registerClassName(Foo::class.java.name, "MyOverriddenFoo")
assertEquals("MyOverriddenFoo", translateClass<Foo>().type.name)
}
@Nested
inner class `kotlin serialization` {
@Test
fun `basic class definition`() {
@Suppress("unused")
@kotlinx.serialization.Serializable
class Example(
val normalProperty: String,
@kotlinx.serialization.Transient val ignoredProperty: String = "",
@kotlinx.serialization.SerialName("overriddenName") val propertyWithOverriddenName: String,
val fieldWithDefaultWillBeNullable: Int = 42,
@kotlinx.serialization.Required val requiredFieldWithDefaultWillNotBeNullable: Int = 42,
val nullableParameter: Int?,
val valueString: ValueString
)
val classDefinition = translateClass<Example>()
assertHasProperties(
classDefinition,
"normalProperty" to ApiType.Primitive.STRING,
"overriddenName" to ApiType.Primitive.STRING,
"fieldWithDefaultWillBeNullable" to ApiType.Primitive.INTEGER.nullable(),
"nullableParameter" to ApiType.Primitive.INTEGER.nullable(),
"requiredFieldWithDefaultWillNotBeNullable" to ApiType.Primitive.INTEGER,
"valueString" to ApiType.Primitive.STRING
)
}
@Test
fun `discriminated unions`() {
loader.loadClassesFromInheritanceTree<KotlinSerializationDiscriminatedUnion>()
loader.loadClassesFromInheritanceTree<KotlinSerializationDiscriminatedUnion.SubClassWithCustomDiscriminator>()
loader.loadClassesFromInheritanceTree<KotlinSerializationDiscriminatedUnion.SubClassWithDefaultDiscriminator>()
translator.translateType(
JavaType.basic<KotlinSerializationDiscriminatedUnion>(),
MockAnnotatedElement(),
TypeEnvironment.empty()
)
val definition =
api.discriminatedUnionDefinitions.find { it.type.name == KotlinSerializationDiscriminatedUnion::class.simpleName }
?: fail("could not find union")
assertEquals("type", definition.discriminator)
assertEquals(
setOf(
"CustomDiscriminator",
KotlinSerializationDiscriminatedUnion.SubClassWithDefaultDiscriminator::class.qualifiedName
),
definition.types.keys
)
}
@Suppress("unused")
@Test
fun `inherited fields`() {
@kotlinx.serialization.Serializable
open class ParentClass(val parentParameter: Int) {
var parentProperty = "string"
@kotlinx.serialization.Required
var requiredParentProperty = "string"
val propertyWithoutBackingField: String
get() = "no-included"
}
@kotlinx.serialization.Serializable
class ChildClass(val ownParameter: Int) : ParentClass(42) {
var ownProperty = "string"
@kotlinx.serialization.Required
var requiredOwnProperty = "string"
@kotlinx.serialization.Transient
private var transientPrivateProperty = "42"
@SerialName("renamedPrivatePropertyNewName")
private var renamedPrivateProperty = "42"
private var privateProperty = "42"
@kotlinx.serialization.Required
private var requiredPrivateProperty = "42"
@kotlinx.serialization.Required
private var isProperty = false
}
loader.loadClassesFromInheritanceTree<ParentClass>()
loader.loadClassesFromInheritanceTree<ChildClass>()
translator.translateType(JavaType.basic<ChildClass>(), MockAnnotatedElement(), TypeEnvironment.empty())
val classDefinition = api.classDefinitions.find { it.type.name == ChildClass::class.simpleName }
?: fail("could not find class")
assertHasProperties(
classDefinition,
"ownParameter" to ApiType.Primitive.INTEGER,
"ownProperty" to ApiType.Primitive.STRING.nullable(),
"requiredOwnProperty" to ApiType.Primitive.STRING,
"privateProperty" to ApiType.Primitive.STRING.nullable(),
"renamedPrivatePropertyNewName" to ApiType.Primitive.STRING.nullable(),
"requiredPrivateProperty" to ApiType.Primitive.STRING,
"isProperty" to ApiType.Primitive.BOOLEAN,
"parentParameter" to ApiType.Primitive.INTEGER,
"parentProperty" to ApiType.Primitive.STRING.nullable(),
"requiredParentProperty" to ApiType.Primitive.STRING
)
}
}
@kotlinx.serialization.Serializable
sealed class KotlinSerializationDiscriminatedUnion {
@kotlinx.serialization.Serializable
class SubClassWithDefaultDiscriminator(val x: Int) : KotlinSerializationDiscriminatedUnion()
@kotlinx.serialization.Serializable
@kotlinx.serialization.SerialName("CustomDiscriminator")
class SubClassWithCustomDiscriminator(val y: Int) : KotlinSerializationDiscriminatedUnion()
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(value = Vehicle.Car::class, name = "car"),
JsonSubTypes.Type(value = Vehicle.Truck::class, name = "truck")
)
abstract class Vehicle {
class Car : Vehicle()
class Truck : Vehicle()
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
abstract class Vehicle2 {
@JsonTypeName("car")
class Car : Vehicle2()
@JsonTypeName("truck")
class Truck : Vehicle2()
}
private fun translateType(type: JavaType): ApiType =
translator.translateType(type, MockAnnotatedElement(), TypeEnvironment.empty()) // TODO: create environment from type
private inline fun <reified T : Any> translateType(): ApiType =
translateType(JavaType.basic<T>())
private inline fun <reified T : Any> translateClass(): ClassDefinition {
loader.loadClassesFromInheritanceTree<T>()
val apiType = translateType<T>()
return api.classDefinitions.find { d ->
apiType.toTypeScript(OptionalTypeMode.NULL).startsWith(d.type.toString())
} ?: fail("could not find definition for $apiType")
}
private inline fun <reified T : Enum<T>> translateEnum(): EnumDefinition {
loader.loadClassesFromInheritanceTree<T>()
val apiType = translateType<T>()
return api.enumDefinitions.find { d -> d.type.toString() == apiType.toTypeScript(OptionalTypeMode.NULL) }
?: fail("could not find definition for $apiType")
}
companion object {
private fun assertHasProperties(classDefinition: ClassDefinition, vararg properties: Pair<String, ApiType>) {
assertEquals(
classDefinition.properties.associate { it.name to it.type }.toSortedMap(),
properties.toMap().toSortedMap(),
"Properties don't match"
)
}
private val ClassDefinition.propertyNames: Set<String>
get() = properties.map { it.name }.toSet()
}
}
| 9
|
Kotlin
|
9
| 25
|
3c42abd3b5584138f7313fcb7605c3653120bbdd
| 21,729
|
apina
|
MIT License
|
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/RoomMemberSummaryMapper.kt
|
matrix-org
| 287,466,066
| false
| null |
/*
* Copyright 2020 The Matrix.org Foundation C.I.C.
*
* 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.matrix.android.sdk.internal.database.mapper
import org.matrix.android.sdk.api.session.room.model.RoomMemberSummary
import org.matrix.android.sdk.internal.database.model.RoomMemberSummaryEntity
internal object RoomMemberSummaryMapper {
fun map(roomMemberSummaryEntity: RoomMemberSummaryEntity): RoomMemberSummary {
return RoomMemberSummary(
userId = roomMemberSummaryEntity.userId,
avatarUrl = roomMemberSummaryEntity.avatarUrl,
displayName = roomMemberSummaryEntity.displayName,
membership = roomMemberSummaryEntity.membership
)
}
}
internal fun RoomMemberSummaryEntity.asDomain(): RoomMemberSummary {
return RoomMemberSummaryMapper.map(this)
}
| 75
| null |
27
| 97
|
55cc7362de34a840c67b4bbb3a14267bc8fd3b9c
| 1,366
|
matrix-android-sdk2
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/incentivesapi/service/NextReviewDateUpdaterService.kt
|
ministryofjustice
| 445,553,088
| false
|
{"Kotlin": 610272, "Python": 4467, "Dockerfile": 1357}
|
package uk.gov.justice.digital.hmpps.incentivesapi.service
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.incentivesapi.jpa.NextReviewDate
import uk.gov.justice.digital.hmpps.incentivesapi.jpa.PrisonerIepLevel
import uk.gov.justice.digital.hmpps.incentivesapi.jpa.repository.NextReviewDateRepository
import uk.gov.justice.digital.hmpps.incentivesapi.jpa.repository.PrisonerIepLevelRepository
import java.time.Clock
import java.time.LocalDate
import java.time.LocalDateTime
/**
* Recalculates and persists next review dates
*/
@Service
class NextReviewDateUpdaterService(
private val clock: Clock,
private val prisonerIepLevelRepository: PrisonerIepLevelRepository,
private val nextReviewDateRepository: NextReviewDateRepository,
private val prisonApiService: PrisonApiService,
private val snsService: SnsService,
) {
/**
* Update next review date for the given bookingId
*
* @param bookingId of the offender to update
*
* @return the nextReviewDate for the given bookingId
* */
suspend fun update(bookingId: Long): LocalDate {
val prisonerInfo = prisonApiService.getPrisonerExtraInfo(bookingId, useClientCredentials = true)
return updateMany(listOf(prisonerInfo))[prisonerInfo.bookingId]!!
}
/**
* Update next review date for the given offenders
*
* @param offenders is the list of offenders to update
*
* @return a map with bookingIds as keys and nextReviewDate as value
* */
suspend fun updateMany(offenders: List<PrisonerInfoForNextReviewDate>): Map<Long, LocalDate> {
if (offenders.isEmpty()) {
return emptyMap()
}
val offendersMap = offenders.associateBy(PrisonerInfoForNextReviewDate::bookingId)
val bookingIds = offendersMap.keys.toList()
val nextReviewDatesBeforeUpdate: Map<Long, LocalDate> = nextReviewDateRepository.findAllById(bookingIds).toList().toMapByBookingId()
// NOTE: This is to account for bookingIds potentially without any review record
val bookingIdsNoReviews = bookingIds.associateWith { emptyList<PrisonerIepLevel>() }
val reviewsMap = bookingIdsNoReviews + prisonerIepLevelRepository.findAllByBookingIdInOrderByReviewTimeDesc(bookingIds)
.toList()
.groupBy(PrisonerIepLevel::bookingId)
val nextReviewDateRecords = reviewsMap.map { (bookingId, incentiveRecords) ->
val offender = offendersMap[bookingId]!!
val nextReviewDate = NextReviewDateService(
NextReviewDateInput(
dateOfBirth = offender.dateOfBirth,
receptionDate = offender.receptionDate,
hasAcctOpen = offender.hasAcctOpen,
incentiveRecords = incentiveRecords,
),
).calculate()
NextReviewDate(
bookingId = bookingId,
nextReviewDate = nextReviewDate,
new = !nextReviewDateRepository.existsById(bookingId),
whenUpdated = LocalDateTime.now(clock),
)
}
val nextReviewDatesAfterUpdate: Map<Long, LocalDate> = nextReviewDateRepository.saveAll(nextReviewDateRecords).toList().toMapByBookingId()
// Determine which next review dates records actually changed
val bookingIdsChanged = bookingIds.filter { bookingId ->
nextReviewDatesBeforeUpdate[bookingId] != null && // only publish domain events when next review date changed
nextReviewDatesAfterUpdate[bookingId] != nextReviewDatesBeforeUpdate[bookingId]
}
publishDomainEvents(bookingIdsChanged, offendersMap, nextReviewDatesAfterUpdate)
return nextReviewDatesAfterUpdate
}
private suspend fun publishDomainEvents(
bookingIdsChanged: List<Long>,
offendersMap: Map<Long, PrisonerInfoForNextReviewDate>,
nextReviewDatesMap: Map<Long, LocalDate>,
) = runBlocking {
bookingIdsChanged.forEach { bookingId ->
launch {
snsService.publishDomainEvent(
eventType = IncentivesDomainEventType.PRISONER_NEXT_REVIEW_DATE_CHANGED,
description = "A prisoner's next incentive review date has changed",
occurredAt = LocalDateTime.now(clock),
additionalInformation = AdditionalInformation(
id = bookingId,
nomsNumber = offendersMap[bookingId]!!.prisonerNumber,
nextReviewDate = nextReviewDatesMap[bookingId],
),
)
}
}
}
}
interface PrisonerInfoForNextReviewDate {
val bookingId: Long
val prisonerNumber: String
val dateOfBirth: LocalDate
val receptionDate: LocalDate
val hasAcctOpen: Boolean
}
| 4
|
Kotlin
|
1
| 3
|
e0a4a4dd19900f4dc3e6cc6b4d15b16a93b0fafd
| 4,595
|
hmpps-incentives-api
|
MIT License
|
app/src/main/java/com/kickstarter/viewmodels/RewardsFragmentViewModel.kt
|
kickstarter
| 76,278,501
| false
| null |
package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.libs.Environment
import com.kickstarter.libs.FragmentViewModel
import com.kickstarter.libs.rx.transformers.Transformers.takeWhen
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.RewardUtils
import com.kickstarter.libs.utils.extensions.isBacked
import com.kickstarter.mock.factories.RewardFactory
import com.kickstarter.models.Backing
import com.kickstarter.models.Project
import com.kickstarter.models.Reward
import com.kickstarter.ui.data.PledgeData
import com.kickstarter.ui.data.PledgeFlowContext
import com.kickstarter.ui.data.PledgeReason
import com.kickstarter.ui.data.ProjectData
import com.kickstarter.ui.fragments.RewardsFragment
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
import java.util.Locale
class RewardsFragmentViewModel {
interface Inputs {
/** Configure with current [ProjectData]. */
fun configureWith(projectData: ProjectData)
/** Call when a reward is clicked. */
fun rewardClicked(reward: Reward)
/** Call when the Alert button has been pressed */
fun alertButtonPressed()
}
interface Outputs {
/** Emits the position of the backed reward. */
fun backedRewardPosition(): Observable<Int>
/** Emits the current [ProjectData]. */
fun projectData(): Observable<ProjectData>
/** Emits the count of the current project's rewards. */
fun rewardsCount(): Observable<Int>
/** Emits when we should show the [com.kickstarter.ui.fragments.PledgeFragment]. */
fun showPledgeFragment(): Observable<Pair<PledgeData, PledgeReason>>
/** Emits when we should show the [com.kickstarter.ui.fragments.BackingAddOnsFragment]. */
fun showAddOnsFragment(): Observable<Pair<PledgeData, PledgeReason>>
/** Emits if we have to show the alert in case any AddOns selection could be lost. */
fun showAlert(): Observable<Pair<PledgeData, PledgeReason>>
}
class ViewModel(@NonNull val environment: Environment) : FragmentViewModel<RewardsFragment>(environment), Inputs, Outputs {
private val projectDataInput = PublishSubject.create<ProjectData>()
private val rewardClicked = PublishSubject.create<Pair<Reward, Boolean>>()
private val alertButtonPressed = PublishSubject.create<Void>()
private val backedRewardPosition = PublishSubject.create<Int>()
private val projectData = BehaviorSubject.create<ProjectData>()
private val rewardsCount = BehaviorSubject.create<Int>()
private val showPledgeFragment = PublishSubject.create<Pair<PledgeData, PledgeReason>>()
private val showAddOnsFragment = PublishSubject.create<Pair<PledgeData, PledgeReason>>()
private val showAlert = PublishSubject.create<Pair<PledgeData, PledgeReason>>()
val inputs: Inputs = this
val outputs: Outputs = this
init {
this.projectDataInput
.map { filterOutNotStartedRewards(it) }
.compose(bindToLifecycle())
.subscribe(this.projectData)
val project = this.projectData
.map { it.project() }
project
.filter { it.isBacking }
.map { indexOfBackedReward(it) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.backedRewardPosition)
val backedReward = project
.map { it.backing()?.let { backing -> getReward(backing) } }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
val defaultRewardClicked = Pair(Reward.builder().id(0).minimum(0.0).build(), false)
Observable
.combineLatest(this.rewardClicked.startWith(defaultRewardClicked), this.projectDataInput) { rewardPair, projectData ->
if (!rewardPair.second) {
return@combineLatest null
} else {
return@combineLatest pledgeDataAndPledgeReason(projectData, rewardPair.first)
}
}
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
.compose(bindToLifecycle())
.subscribe {
val pledgeAndData = it
val newRw = it.first.reward()
val reason = it.second
when(reason) {
PledgeReason.PLEDGE -> {
if (newRw.hasAddons())
this.showAddOnsFragment.onNext(pledgeAndData)
else
this.showPledgeFragment.onNext(pledgeAndData)
}
}
this.rewardClicked.onNext(defaultRewardClicked)
}
Observable
.combineLatest(this.rewardClicked.startWith(defaultRewardClicked), this.projectDataInput, backedReward) { rewardPair, projectData, backedReward ->
if (!rewardPair.second) {
return@combineLatest null
} else {
return@combineLatest Pair(pledgeDataAndPledgeReason(projectData, rewardPair.first), backedReward)
}
}
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
.compose(bindToLifecycle())
.subscribe {
val pledgeAndData = it.first
val newRw = it.first.first.reward()
val prevRw = it.second
val reason = it.first.second
when(reason) {
PledgeReason.UPDATE_REWARD -> {
if (prevRw.hasAddons() && !newRw.hasAddons())
this.showAlert.onNext(pledgeAndData)
if (!prevRw.hasAddons() && !newRw.hasAddons())
this.showPledgeFragment.onNext(pledgeAndData)
if (prevRw.hasAddons() && newRw.hasAddons()) {
if (differentShippingTypes(prevRw, newRw)) this.showAlert.onNext(it.first)
else this.showAddOnsFragment.onNext(pledgeAndData)
}
if (!prevRw.hasAddons() && newRw.hasAddons()) {
this.showAddOnsFragment.onNext(pledgeAndData)
}
}
}
this.rewardClicked.onNext(defaultRewardClicked)
}
project
.map { it.rewards()?.size?: 0 }
.compose(bindToLifecycle())
.subscribe(this.rewardsCount)
this.showAlert
.compose<Pair<PledgeData, PledgeReason>>(takeWhen(alertButtonPressed))
.compose(bindToLifecycle())
.subscribe {
if (it.first.reward().hasAddons())
this.showAddOnsFragment.onNext(it)
else this.showPledgeFragment.onNext(it)
}
}
private fun filterOutNotStartedRewards(pData: ProjectData): ProjectData {
val rewards = pData.project().rewards()?.filter { RewardUtils.hasStarted(it) }
val modifiedProject = pData.project().toBuilder().rewards(rewards).build()
return pData.toBuilder()
.project(modifiedProject)
.build()
}
private fun getReward(backingObj: Backing): Reward {
return backingObj.reward()?.let { rw ->
if (backingObj.addOns().isNullOrEmpty()) rw
else rw.toBuilder().hasAddons(true).build()
} ?: RewardFactory.noReward()
}
private fun differentShippingTypes(newRW: Reward, backedRW: Reward): Boolean {
return if (newRW.id() == backedRW.id()) false
else {
newRW.shippingType()?.toLowerCase(Locale.getDefault()) ?: "" != backedRW.shippingType()?.toLowerCase(Locale.getDefault()) ?: ""
}
}
private fun pledgeDataAndPledgeReason(projectData: ProjectData, reward: Reward): Pair<PledgeData, PledgeReason> {
val pledgeReason = if (projectData.project().isBacking) PledgeReason.UPDATE_REWARD else PledgeReason.PLEDGE
val pledgeData = PledgeData.with(PledgeFlowContext.forPledgeReason(pledgeReason), projectData, reward)
return Pair(pledgeData, pledgeReason)
}
private fun indexOfBackedReward(project: Project): Int {
project.rewards()?.run {
for ((index, reward) in withIndex()) {
if (project.backing()?.isBacked(reward) == true) {
return index
}
}
}
return 0
}
override fun configureWith(projectData: ProjectData) {
this.projectDataInput.onNext(projectData)
}
override fun rewardClicked(reward: Reward) {
this.rewardClicked.onNext(Pair(reward, true))
}
override fun alertButtonPressed() = this.alertButtonPressed.onNext(null)
@NonNull
override fun backedRewardPosition(): Observable<Int> = this.backedRewardPosition
@NonNull
override fun projectData(): Observable<ProjectData> = this.projectData
@NonNull
override fun rewardsCount(): Observable<Int> = this.rewardsCount
@NonNull
override fun showPledgeFragment(): Observable<Pair<PledgeData, PledgeReason>> = this.showPledgeFragment
@NonNull
override fun showAddOnsFragment(): Observable<Pair<PledgeData, PledgeReason>> = this.showAddOnsFragment
@NonNull
override fun showAlert(): Observable<Pair<PledgeData, PledgeReason>> = this.showAlert
}
}
| 9
| null |
990
| 5,749
|
fdf3f19d094540e0c47626810f3f252a41ffdf2e
| 10,569
|
android-oss
|
Apache License 2.0
|
code generators/de.fhdo.lemma.model_processing.code_generation.springcloud/src/main/kotlin/de/fhdo/lemma/model_processing/code_generation/springcloud/handlers/aspects/ResourceSupportHandler.kt
|
SeelabFhdo
| 204,692,764
| false
| null |
package de.fhdo.lemma.model_processing.code_generation.springcloud.handlers.aspects
import com.github.javaparser.ast.Node
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import de.fhdo.lemma.data.intermediate.IntermediateDataStructure
import de.fhdo.lemma.data.intermediate.IntermediateImportedAspect
import de.fhdo.lemma.model_processing.code_generation.java_base.ast.ImportTargetElementType
import de.fhdo.lemma.model_processing.code_generation.java_base.ast.addDependency
import de.fhdo.lemma.model_processing.code_generation.java_base.ast.addImport
import de.fhdo.lemma.model_processing.code_generation.java_base.ast.setSuperclass
import de.fhdo.lemma.model_processing.code_generation.java_base.handlers.AspectHandler
import de.fhdo.lemma.model_processing.code_generation.java_base.handlers.AspectHandlerI
import de.fhdo.lemma.model_processing.code_generation.java_base.handlers.combinations
import org.eclipse.emf.ecore.EObject
/**
* Handler for the ResourceSupport aspect.
*
* @author [<NAME>](mailto:<EMAIL>)
*/
@AspectHandler
internal class ResourceSupportHandler : AspectHandlerI {
override fun handlesAspects() = setOf("java.ResourceSupport", "Spring.ResourceSupport")
override fun handlesEObjectNodeCombinations() = combinations {
IntermediateDataStructure::class.java with ClassOrInterfaceDeclaration::class.java
}
/**
* Execution logic of the handler
*/
override fun execute(eObject: EObject, node: Node, aspect: IntermediateImportedAspect) : Node {
val generatedClass = node as ClassOrInterfaceDeclaration
/* Extend ResourceSupport if class does not yet extend another class */
if (generatedClass.extendedTypes.isEmpty()) {
generatedClass.addDependency("org.springframework.hateoas:spring-hateoas")
generatedClass.addImport("org.springframework.hateoas.ResourceSupport", ImportTargetElementType.SUPER)
generatedClass.setSuperclass("ResourceSupport", isExternalSuperclass = true)
}
return node
}
}
| 32
| null |
8
| 31
|
2e9ccc882352116b253a7700b5ecf2c9316a5829
| 2,055
|
lemma
|
MIT License
|
code generators/de.fhdo.lemma.model_processing.code_generation.springcloud/src/main/kotlin/de/fhdo/lemma/model_processing/code_generation/springcloud/handlers/aspects/ResourceSupportHandler.kt
|
SeelabFhdo
| 204,692,764
| false
| null |
package de.fhdo.lemma.model_processing.code_generation.springcloud.handlers.aspects
import com.github.javaparser.ast.Node
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import de.fhdo.lemma.data.intermediate.IntermediateDataStructure
import de.fhdo.lemma.data.intermediate.IntermediateImportedAspect
import de.fhdo.lemma.model_processing.code_generation.java_base.ast.ImportTargetElementType
import de.fhdo.lemma.model_processing.code_generation.java_base.ast.addDependency
import de.fhdo.lemma.model_processing.code_generation.java_base.ast.addImport
import de.fhdo.lemma.model_processing.code_generation.java_base.ast.setSuperclass
import de.fhdo.lemma.model_processing.code_generation.java_base.handlers.AspectHandler
import de.fhdo.lemma.model_processing.code_generation.java_base.handlers.AspectHandlerI
import de.fhdo.lemma.model_processing.code_generation.java_base.handlers.combinations
import org.eclipse.emf.ecore.EObject
/**
* Handler for the ResourceSupport aspect.
*
* @author [<NAME>](mailto:<EMAIL>)
*/
@AspectHandler
internal class ResourceSupportHandler : AspectHandlerI {
override fun handlesAspects() = setOf("java.ResourceSupport", "Spring.ResourceSupport")
override fun handlesEObjectNodeCombinations() = combinations {
IntermediateDataStructure::class.java with ClassOrInterfaceDeclaration::class.java
}
/**
* Execution logic of the handler
*/
override fun execute(eObject: EObject, node: Node, aspect: IntermediateImportedAspect) : Node {
val generatedClass = node as ClassOrInterfaceDeclaration
/* Extend ResourceSupport if class does not yet extend another class */
if (generatedClass.extendedTypes.isEmpty()) {
generatedClass.addDependency("org.springframework.hateoas:spring-hateoas")
generatedClass.addImport("org.springframework.hateoas.ResourceSupport", ImportTargetElementType.SUPER)
generatedClass.setSuperclass("ResourceSupport", isExternalSuperclass = true)
}
return node
}
}
| 32
| null |
8
| 31
|
2e9ccc882352116b253a7700b5ecf2c9316a5829
| 2,055
|
lemma
|
MIT License
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestPathLength.kt
|
ashtanko
| 203,993,092
| false
| null |
/*
* 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.shtanko.algorithms.leetcode
import java.util.Queue
/**
* 847. Shortest Path Visiting All Nodes
* @see <a href="https://leetcode.com/problems/shortest-path-visiting-all-nodes">Source</a>
*/
fun interface ShortestPathLength {
operator fun invoke(graph: Array<IntArray>): Int
}
class ShortestPathLengthBFS : ShortestPathLength {
override fun invoke(graph: Array<IntArray>): Int {
val n = graph.size
val allVisitedMask = (1 shl n) - 1
val queue: Queue<Pair<Int, Pair<Int, Int>>> = java.util.LinkedList() // Pair<currNode, Pair<dist, mask>>
val seen = mutableSetOf<Pair<Int, Int>>() // Pair<currNode, mask as path>
// Initially push all nodes in the queue to start the path with all nodes
for (i in 0 until n) {
queue.offer(Pair(i, Pair(0, 1 shl i)))
seen.add(Pair(i, 1 shl i))
}
while (queue.isNotEmpty()) {
val curr = queue.poll()
val node = curr.first
val dist = curr.second.first
val mask = curr.second.second
// If all nodes are visited
if (mask == allVisitedMask) return dist
// Go through all neighbors
for (nei in graph[node]) {
val nextMask = mask or (1 shl nei)
if (Pair(nei, nextMask) !in seen) {
queue.offer(Pair(nei, Pair(dist + 1, nextMask)))
seen.add(Pair(nei, nextMask))
}
}
}
return 0
}
}
| 4
| null |
0
| 19
|
b60c6d88c6f1a04fe41d26aacb9b4f7a8bf10ff7
| 2,127
|
kotlab
|
Apache License 2.0
|
compiler/testData/codegen/box/jvmOverloads/primaryConstructor.kt
|
JakeWharton
| 99,388,807
| false
| null |
// IGNORE_BACKEND_FIR: JVM_IR
// TARGET_BACKEND: JVM
// WITH_RUNTIME
class C @kotlin.jvm.JvmOverloads constructor(s1: String, s2: String = "K") {
public val status: String = s1 + s2
}
fun box(): String {
val c = (C::class.java.getConstructor(String::class.java).newInstance("O"))
return c.status
}
| 181
| null |
5748
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 313
|
kotlin
|
Apache License 2.0
|
rabbit-ui/src/main/java/com/susion/rabbit/ui/page/RabbitMemoryPageAnalyzerPage.kt
|
SusionSuc
| 210,506,798
| false
| null |
package com.susion.rabbit.ui.page
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import com.susion.lifeclean.common.recyclerview.SimpleRvAdapter
import com.susion.rabbit.base.entities.RabbitMemoryInfo
import com.susion.rabbit.base.greendao.RabbitMemoryInfoDao
import com.susion.rabbit.base.ui.page.RabbitBasePage
import com.susion.rabbit.base.ui.utils.RabbitUiUtils
import com.susion.rabbit.storage.RabbitDbStorageManager
import com.susion.rabbit.ui.entities.RabbitMemoryAnalyzerPageInfo
import com.susion.rabbit.ui.monitor.R
import com.susion.rabbit.ui.view.RabbitMemPageInfoView
import kotlinx.android.synthetic.main.rabbbit_page_mem_analyzer_page_detail.view.*
/**
* susionwang at 2020-01-10
*/
class RabbitMemoryPageAnalyzerPage(context: Context) : RabbitBasePage(context) {
private val adapter = SimpleRvAdapter<RabbitMemoryAnalyzerPageInfo>(context).apply {
registerMapping(RabbitMemoryAnalyzerPageInfo::class.java, RabbitMemPageInfoView::class.java)
}
override fun getLayoutResId() = R.layout.rabbbit_page_mem_analyzer_page_detail
init {
setTitle("内存概览-页面")
mMemDetailPageRv.adapter = adapter
mMemDetailPageRv.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mMemDetailPageSRL.setOnRefreshListener {
loadData()
}
loadData()
}
private fun loadData() {
RabbitDbStorageManager.distinct(
RabbitMemoryInfo::class.java,
RabbitMemoryInfoDao.Properties.PageName.columnName
) { pages ->
adapter.data.clear()
if (pages.isEmpty()) {
showEmptyView()
} else {
hideEmptyView()
}
pages.forEachIndexed { index, page ->
adapter.data.add(loadMemAnalyzerInfoByPage(page))
}
mMemDetailPageSRL.isRefreshing = false
adapter.notifyDataSetChanged()
}
}
private fun loadMemAnalyzerInfoByPage(pageName: String): RabbitMemoryAnalyzerPageInfo {
val mems = RabbitDbStorageManager.getAllSync(
RabbitMemoryInfo::class.java,
Pair(RabbitMemoryInfoDao.Properties.PageName, pageName)
)
val memInfo = RabbitMemoryAnalyzerPageInfo()
memInfo.avgMem = RabbitUiUtils.formatFileSize(mems.map { it.totalSize }.average().toLong())
memInfo.avgVmMem = RabbitUiUtils.formatFileSize(mems.map { it.vmSize }.average().toLong())
memInfo.pageName = pageName
memInfo.recordCount = mems.size
return memInfo
}
}
| 9
|
Kotlin
|
146
| 998
|
f1d1faf9f69b4ec162ae2215e9338dd1d7bdc893
| 2,658
|
rabbit-client
|
MIT License
|
pcbridge-http/src/main/kotlin/com/projectcitybuild/pcbridge/http/services/pcb/PlayerGroupHttpService.kt
|
projectcitybuild
| 42,997,941
| false
|
{"Kotlin": 261041}
|
package com.projectcitybuild.pcbridge.http.services.pcb
import com.projectcitybuild.pcbridge.http.parsing.ResponseParser
import com.projectcitybuild.pcbridge.http.pcb
import com.projectcitybuild.pcbridge.http.responses.DonationPerk
import com.projectcitybuild.pcbridge.http.responses.Group
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import java.util.UUID
class PlayerGroupHttpService(
private val retrofit: Retrofit,
private val responseParser: ResponseParser,
) {
class NoLinkedAccountException : Exception()
@Throws(NoLinkedAccountException::class)
suspend fun getGroups(playerUUID: UUID): List<Group> =
withContext(Dispatchers.IO) {
val response =
try {
responseParser.parse {
retrofit.pcb().getUserGroups(
uuid = playerUUID.toString(),
)
}
} catch (e: ResponseParser.HTTPError) {
if (e.errorBody?.id == "account_not_linked") {
throw NoLinkedAccountException()
}
throw e
}
response.data?.groups ?: listOf()
}
@Throws(NoLinkedAccountException::class)
suspend fun getDonorPerks(playerUUID: UUID): List<DonationPerk> =
withContext(Dispatchers.IO) {
val response =
try {
responseParser.parse {
retrofit.pcb().getDonationTier(
uuid = playerUUID.toString(),
)
}
} catch (e: ResponseParser.HTTPError) {
if (e.errorBody?.id == "account_not_linked") {
throw NoLinkedAccountException()
}
throw e
}
response.data?.toList() ?: listOf()
}
}
| 9
|
Kotlin
|
0
| 3
|
16754fd7ab63023da86ae426d5e5c8ecb932c181
| 1,998
|
PCBridge
|
MIT License
|
src/main/kotlin/org/xpathqs/driver/page/Page.kt
|
xpathqs
| 366,703,320
| false
|
{"Kotlin": 230690}
|
package org.xpathqs.driver.page
import org.xpathqs.core.selector.NullSelector
import org.xpathqs.core.selector.base.BaseSelector
import org.xpathqs.core.selector.base.ISelector
import org.xpathqs.core.selector.block.Block
import org.xpathqs.core.selector.group.GroupSelector
import org.xpathqs.core.selector.selector.Selector
import org.xpathqs.core.selector.selector.SelectorProps
import org.xpathqs.core.selector.xpath.XpathSelector
open class Page(
base: ISelector = NullSelector(),
open val title: String = "",
) : Block(base) {
override val name: String
get() = title.ifEmpty { super.name }
override fun equals(other: Any?): Boolean {
return fullName == (other as? Page)?.fullName ?: false
}
override fun hashCode(): Int {
return fullName.hashCode()
}
}
| 0
|
Kotlin
|
0
| 2
|
60eccb672195d82f07bb4713c1018c2816cd0c71
| 815
|
driver
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.