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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
core/camera/src/main/java/com/google/jetpackcamera/core/camera/effects/EGLSpecV14ES3.kt | google | 591,101,391 | false | {"Kotlin": 640681, "C++": 2189, "CMake": 1010, "Shell": 724} | /*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jetpackcamera.core.camera.effects
import android.opengl.EGL14
import android.opengl.EGLConfig
import android.opengl.EGLContext
import androidx.graphics.opengl.egl.EGLSpec
val EGLSpec.Companion.V14ES3: EGLSpec
get() = object : EGLSpec by V14 {
private val contextAttributes = intArrayOf(
// GLES VERSION 3
EGL14.EGL_CONTEXT_CLIENT_VERSION,
3,
// HWUI provides the ability to configure a context priority as well but that only
// seems to be configured on SystemUIApplication. This might be useful for
// front buffer rendering situations for performance.
EGL14.EGL_NONE
)
override fun eglCreateContext(config: EGLConfig): EGLContext {
return EGL14.eglCreateContext(
EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY),
config,
// not creating from a shared context
EGL14.EGL_NO_CONTEXT,
contextAttributes,
0
)
}
}
| 39 | Kotlin | 26 | 141 | f79336788a80bf2d7e35393bde6470db3ea548e7 | 1,695 | jetpack-camera-app | Apache License 2.0 |
src/backend/ci/core/store/api-store-image/src/main/kotlin/com/tencent/devops/store/pojo/image/enums/LabelTypeEnum.kt | SoftwareDevTest | 227,287,802 | true | {"Kotlin": 10220155, "Vue": 2132727, "JavaScript": 614337, "CSS": 363782, "TSQL": 278000, "Lua": 135524, "Go": 127459, "Shell": 108349, "Java": 74466, "TypeScript": 32981, "HTML": 21413, "Python": 10390, "PLSQL": 2341, "Batchfile": 2144} | package com.tencent.devops.store.pojo.image.enums
enum class LabelTypeEnum(val status: Int) {
ATOM(0), // 插件
TEMPLATE(1), // 模板
IMAGE(2); // 镜像
companion object {
fun getLabelType(name: String): LabelTypeEnum? {
LabelTypeEnum.values().forEach { enumObj ->
if (enumObj.name == name) {
return enumObj
}
}
return null
}
fun getLabelType(type: Int): String {
return when (type) {
0 -> ATOM.name
1 -> TEMPLATE.name
2 -> IMAGE.name
else -> ATOM.name
}
}
}
}
| 0 | null | 0 | 0 | 28e2440f3fd2654cf288c487d3c872ae55f460a3 | 684 | bk-ci | MIT License |
app/src/main/java/com/example/perfpuppy/ui/dashboard/DashboardFragment.kt | mauriziopinotti | 481,169,433 | false | null | package com.example.perfpuppy.ui.dashboard
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.perfpuppy.R
import com.example.perfpuppy.data.CollectorService
import com.example.perfpuppy.databinding.FragmentDashboardBinding
import timber.log.Timber
class DashboardFragment : Fragment() {
private var _binding: FragmentDashboardBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// val dashboardViewModel =
// ViewModelProvider(this).get(DashboardViewModel::class.java)
_binding = FragmentDashboardBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.serviceToggleButtonGroup.addOnButtonCheckedListener { _, _, isChecked ->
toggleCollectorService(isChecked)
setServiceToggleButtonText(isChecked)
}
return root
}
override fun onResume() {
super.onResume()
// Service enabled button
CollectorService.isServiceRunning(requireContext()).also {
Timber.d("Checking collector service running: $it")
if (it) binding.serviceToggleButtonGroup.check(binding.serviceToggleButton.id)
// else binding.serviceToggleButtonGroup.clearChecked()
setServiceToggleButtonText(it)
}
}
private fun setServiceToggleButtonText(enabled: Boolean) {
Timber.d("setServiceToggleButtonText: enabled=$enabled")
binding.serviceToggleButton.text =
if (enabled) getString(R.string.disable_data_collection)
else getString(R.string.enable_data_collection)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun toggleCollectorService(enable: Boolean) {
val intent = Intent(context, CollectorService::class.java)
if (enable) {
// Start collector service
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
activity?.startForegroundService(intent)
} else {
activity?.startService(intent)
}
} else {
// Stop collector service
activity?.stopService(intent)
}
}
}
| 0 | Kotlin | 0 | 0 | 75cc946f17c4affb4933f01da41d8b6e17d342b7 | 2,516 | perfpuppy | Apache License 2.0 |
core/src/main/java/com/infiniteset/notifications/notification/MvpNotification.kt | ruslancpp | 218,507,898 | false | null | package com.infiniteset.notifications.notification
import com.infiniteset.notifications.manager.NotificationManager
import com.infiniteset.notifications.presenter.BasePresenter
import com.infiniteset.notifications.presenter.BaseView
/**
* A base view for MVP notification.
*/
abstract class MvpNotification<V : BaseView, P : BasePresenter<V>>(
isForeground: Boolean = false
) : BaseNotification(isForeground) {
protected lateinit var presenter: P
private set
protected abstract fun createPresenter(): P
override fun onAttach(notificationManager: NotificationManager) {
super.onAttach(notificationManager)
presenter = createPresenter()
@Suppress("UNCHECKED_CAST")
presenter.attachView(this as V)
}
override fun onDetach() {
presenter.detachView()
super.onDetach()
}
}
| 0 | Kotlin | 0 | 1 | 9ed4662cc0ef9a82c619a0cfc8a013fe49212ad5 | 859 | notifications_architecture | Apache License 2.0 |
messaging-ui/src/main/java/com/nabla/sdk/messaging/ui/scene/messages/adapter/viewholders/PatientImageMessageViewHolder.kt | nabla | 478,468,099 | false | null | package com.nabla.sdk.messaging.ui.scene.messages.adapter.viewholders
import android.view.LayoutInflater
import android.view.ViewGroup
import com.nabla.sdk.messaging.ui.R
import com.nabla.sdk.messaging.ui.databinding.NablaConversationTimelineItemPatientMessageBinding
import com.nabla.sdk.messaging.ui.scene.messages.TimelineItem
import com.nabla.sdk.messaging.ui.scene.messages.adapter.content.ImageMessageContentBinder
import com.nabla.sdk.messaging.ui.scene.messages.adapter.inflatePatientMessageContentCard
internal class PatientImageMessageViewHolder(
binding: NablaConversationTimelineItemPatientMessageBinding,
contentBinder: ImageMessageContentBinder,
) : PatientMessageViewHolder<TimelineItem.Message.Image, ImageMessageContentBinder>(binding, contentBinder) {
companion object {
fun create(inflater: LayoutInflater, parent: ViewGroup): PatientImageMessageViewHolder {
val binding = NablaConversationTimelineItemPatientMessageBinding.inflate(inflater, parent, false)
return PatientImageMessageViewHolder(
binding,
inflatePatientMessageContentCard(inflater, binding.chatPatientMessageContentContainer) { contentParent ->
ImageMessageContentBinder.create(R.attr.nablaMessaging_conversationPatientMessageAppearance, inflater, contentParent)
}
)
}
}
}
| 0 | null | 1 | 18 | ca83926d41a2028ca992d4aa66f4d387152c6cb4 | 1,395 | nabla-android | MIT License |
app/src/main/java/com/flowfoundation/wallet/utils/debug/DebugLogManager.kt | Outblock | 692,942,645 | false | {"Kotlin": 2429248, "Java": 104150} | package com.flowfoundation.wallet.utils.debug
object DebugLogManager {
private const val MAX_TWEAKS_SIZE = 50
val tweaks: MutableList<DebugTweak<Any>> = object : ArrayList<DebugTweak<Any>>() {
override fun add(element: DebugTweak<Any>): Boolean {
if (size >= MAX_TWEAKS_SIZE) {
removeAt(0)
}
return super.add(element)
}
}
fun addDebugTweak(tag: String?, msg: Any?) {
val debugTweak = DebugTweak(
category = "Log",
name = tag ?: "",
defaultValue = msg
)
tweaks.add(debugTweak as DebugTweak<Any>)
}
} | 62 | Kotlin | 5 | 0 | 8ad633b7bccc02ae6b3005ca3989379ed8fb248d | 650 | FRW-Android | Apache License 2.0 |
src/main/kotlin/me/zhengjin/common/utils/FileUtils.kt | zhengjin-me | 522,420,626 | false | {"Kotlin": 44868} | /*
* MIT License
*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.zhengjin.common.utils
import org.slf4j.LoggerFactory
import org.springframework.core.io.DefaultResourceLoader
import java.io.File
import java.io.InputStream
object FileUtils {
@JvmStatic
private val logger = LoggerFactory.getLogger(FileUtils::class.java)!!
// JAR包外部文件优先使用
@JvmStatic
fun getFile(filePath: String): File? {
return try {
val template = File(filePath.removePrefix("classpath:"))
return if (template.exists()) {
template
} else null
} catch (ignore: Exception) {
logger.error("load file $filePath error")
null
}
}
// JAR包内外文件使用
@JvmStatic
fun getFileAsInputStream(filePath: String): InputStream? {
return try {
val file = getFile(filePath)
if (file != null && file.exists()) {
return file.inputStream()
}
val resource = DefaultResourceLoader().getResource(filePath)
if (resource.exists()) {
resource.inputStream
} else null
} catch (ignore: Exception) {
logger.error("load file $filePath by inputStream error")
null
}
}
}
| 0 | Kotlin | 0 | 0 | c957852a377fe4c7780c20764e65f34c6348646f | 2,372 | common-utils | MIT License |
SERVER/src/main/kotlin/com/konix/data/dto/response/PortfolioResponseDTO.kt | singhtwenty2 | 809,094,089 | false | {"Kotlin": 369846, "Dockerfile": 414} | package com.konix.data.dto.response
import kotlinx.serialization.Serializable
@Serializable
data class PortfolioResponseDTO(
val companyId: Int,
val companyName: String,
val quantity: Int
)
| 0 | Kotlin | 0 | 1 | b744b0797548d2c1dbec21ba684b4691471dbfc4 | 204 | konix-TEP | MIT License |
src/main/kotlin/com/cherryperry/gfe/base/PlainFilesAware.kt | CherryPerry | 139,057,804 | false | {"Kotlin": 49502} | package com.cherryperry.gfe.base
import org.gradle.api.file.FileCollection
interface PlainFilesAware {
val plainFiles: FileCollection
}
| 4 | Kotlin | 3 | 14 | 5cd86ad93d1b55c50d4a591d3d0e51a4368a55a0 | 142 | GradleFileEncrypt | Apache License 2.0 |
src/main/kotlin/com/github/cubefoxexe/skyblock/errors/CommandError.kt | cubefoxexe | 844,259,683 | false | {"Kotlin": 12037, "Java": 2755} | package com.github.cubefoxexe.skyblock.errors
class CommandError(message: String, cause: Throwable) : Error(message, cause) | 0 | Kotlin | 0 | 0 | 0f4fab33f4d9c760537bd84f9f415e97c599dc5e | 124 | skyblock | The Unlicense |
features/voice/voice-collection/src/main/java/ir/mehdiyari/krypt/voice/collection/AudiosListComponents.kt | mehdiyari | 459,064,107 | false | {"Kotlin": 470699, "Java": 87170} | package ir.mehdiyari.krypt.voice.collection
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import ir.mehdiyari.krypt.core.designsystem.theme.KryptTheme
import ir.mehdiyari.krypt.voice.player.entity.MusicPlayerEntity
import ir.mehdiyari.krypt.voice.shared.entity.AudioEntity
@Composable
internal fun AudioList(
modifier: Modifier,
audios: State<List<AudioEntity>>,
currentAudioPlaying: State<MusicPlayerEntity?>,
onActionClicked: (AudioEntity) -> Unit,
openMusicPlayerBottomSheet: () -> Unit,
topPadding: Dp,
isMusicPlayerSheetOpened: Boolean
) {
LazyColumn(
modifier = modifier.padding(top = topPadding),
content = {
items(audios.value.size, key = {
audios.value[it].id
}) {
AudioItem(
modifier,
audios.value[it],
currentAudioPlaying,
onActionClicked,
openMusicPlayerBottomSheet,
isMusicPlayerSheetOpened
)
}
}, contentPadding = PaddingValues(top = 8.dp, bottom = 70.dp, start = 6.dp, end = 6.dp)
)
}
@SuppressLint("StateFlowValueCalledInComposition")
@Composable
internal fun AudioItem(
modifier: Modifier,
audioEntity: AudioEntity,
playingAudioState: State<MusicPlayerEntity?>,
onActionClicked: (AudioEntity) -> Unit,
openMusicPlayerBottomSheet: () -> Unit,
isMusicPlayerSheetOpened: Boolean
) {
Card(
modifier = modifier
.fillMaxWidth()
.padding(4.dp),
shape = RoundedCornerShape(8.dp),
elevation = CardDefaults.cardElevation()
) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = {
onActionClicked.invoke(audioEntity)
openMusicPlayerBottomSheet()
}) {
val playPauseIcon =
if (playingAudioState.value?.id == audioEntity.id && isMusicPlayerSheetOpened) {
painterResource(id = R.drawable.ic_pause)
} else {
painterResource(id = R.drawable.ic_audio_play)
}
Icon(
painter = playPauseIcon,
contentDescription = ""
)
}
ConstraintLayout(
modifier = modifier.fillMaxWidth()
) {
val (columnRef, dateText) = createRefs()
Column(
modifier = modifier
.padding(start = 4.dp, end = 4.dp)
.constrainAs(columnRef) {}
) {
Text(text = audioEntity.name, fontWeight = FontWeight.Bold)
Text(text = audioEntity.duration, fontSize = 12.sp)
}
Text(text = audioEntity.dateTime, fontSize = 10.sp, modifier = modifier
.padding(end = 4.dp)
.constrainAs(dateText) {
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
})
}
}
}
}
@SuppressLint("UnrememberedMutableState")
@Composable
@Preview
internal fun AudioListPreview(
@PreviewParameter(AudioPreviewParameterProvider::class) audios: List<AudioEntity>
) {
KryptTheme {
AudioList(
modifier = Modifier,
audios = mutableStateOf(audios),
currentAudioPlaying = mutableStateOf(
MusicPlayerEntity(
1L,
"Voice #60",
5646,
54,
)
),
onActionClicked = {},
{},
topPadding = 0.dp,
false
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnrememberedMutableState")
@Composable
@Preview
internal fun AudioItemPreview(
@PreviewParameter(AudioPreviewParameterProvider::class) audios: List<AudioEntity>
) {
KryptTheme {
AudioItem(
modifier = Modifier,
audioEntity = audios[0],
playingAudioState = mutableStateOf(
MusicPlayerEntity(
1L,
"Voice #60",
5646,
54,
)
),
onActionClicked = {},
{},
true
)
}
}
internal class AudioPreviewParameterProvider :
PreviewParameterProvider<List<AudioEntity>> {
override val values: Sequence<List<AudioEntity>>
get() = sequenceOf(
listOf(
AudioEntity(1L, "Voice #60", "08:30", "2023/01/26 18:00:00"),
AudioEntity(2L, "Voice #61", "23:03", "2023/12/10 19:11:00"),
AudioEntity(3L, "Voice #62", "16:30", "2022/12/12 10:00:00")
)
)
} | 16 | Kotlin | 1 | 3 | c1f569aa11e647d1403975b5dcf9a0dff33f6fb0 | 6,332 | krypt | Apache License 2.0 |
wear/src/main/java/ca/joshstagg/slate/Ambient.kt | stagg | 28,216,539 | false | null | package ca.joshstagg.slate
/**
* Slate ca.joshstagg.slate
* Copyright 2018 <NAME>
*/
enum class Ambient {
NORMAL, // Not in ambient mode
AMBIENT, // In ambient mode
AMBIENT_LOW_BIT,
AMBIENT_BURN_IN,
AMBIENT_LOW_BIT_BURN_IN
} | 1 | Kotlin | 1 | 1 | b16c7ef8c5956f6e2d4c3bf4ff32fdc0e4cf1dee | 256 | slatewatchface | Apache License 2.0 |
src/main/kotlin/org/generousg/fruitylib/client/gui/TextureUtils.kt | wingertge | 95,062,948 | false | null | package org.generousg.fruitylib.client.gui
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.util.ResourceLocation
import net.minecraftforge.fluids.Fluid
import net.minecraftforge.fluids.FluidStack
class TextureUtils {
companion object {
val TEXTURE_MAP_BLOCKS = 0
val TEXTURE_MAP_ITEMS = 1
fun bindTextureToClient(texture: ResourceLocation) {
val mc = Minecraft.getMinecraft()
mc?.renderEngine?.bindTexture(texture)
}
fun getStillTexture(fluid: FluidStack?): TextureAtlasSprite? {
if (fluid == null || fluid.fluid == null) {
return null
}
return getStillTexture(fluid.fluid)
}
fun getStillTexture(fluid: Fluid): TextureAtlasSprite? {
val iconKey = fluid.still ?: return null
return Minecraft.getMinecraft().textureMapBlocks.getTextureExtry(iconKey.toString())
}
}
} | 0 | Kotlin | 0 | 1 | c7d0d67c07b0b47c3a3ae8371795d2b6f59687aa | 1,018 | FruityLib | MIT License |
framework/src/main/kotlin/me/wieku/framework/utils/CPair.kt | Wieku | 173,530,017 | false | null | package me.wieku.framework.utils
import java.io.Serializable
import java.util.*
data class CPair<out A, out B>(
val first: A,
val second: B
) : Serializable {
/**
* Returns string representation of the [Pair] including its [first] and [second] values.
*/
override fun toString(): String = "($first, $second)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Pair<*, *>) return false
return first == other.first && second == other.second
}
override fun hashCode(): Int = Objects.hash(first, second)
} | 3 | Kotlin | 10 | 75 | a7b594becb304d8f96d8ca587461e9c90767919e | 607 | danser | MIT License |
core/designsystem/src/main/java/com/example/designsystem/component/SnackBar.kt | KanuKim97 | 428,755,782 | false | {"Kotlin": 153590} | package com.example.designsystem.component
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Snackbar
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.designsystem.icons.EatIcons
import com.example.designsystem.theme.EatShape
import com.example.designsystem.theme.EatTheme
import com.example.designsystem.theme.EatTypography
@Composable
fun NoticeSnackBar(
modifier: Modifier = Modifier,
dismissAction: () -> Unit,
shape: Shape = EatShape.medium,
text: String,
) {
Snackbar(
modifier = modifier,
dismissAction = {
IconButton(
onClick = dismissAction,
content = {
Icon(
imageVector = EatIcons.CloseOutlined,
contentDescription = "Warning"
)
}
)
},
shape = shape,
content = {
Row(
verticalAlignment = Alignment.CenterVertically,
content = {
Icon(
imageVector = EatIcons.WarningOutlined,
contentDescription = "Warning"
)
Spacer(modifier = modifier.size(8.dp))
Text(
text = text,
style = EatTypography.labelLarge
)
}
)
}
)
}
@Preview(showSystemUi = true)
@Composable
fun PreviewSnackBar() {
EatTheme {
NoticeSnackBar(dismissAction = { /*TODO*/ }, text = "데이터를 켜주세요!")
}
} | 0 | Kotlin | 0 | 3 | 67d81baede597ccb19732a9c20868955be31bb5e | 2,049 | whats_eat | Apache License 2.0 |
core/navigation/navigation-compose/src/main/kotlin/com/pantelisstampoulis/androidtemplateproject/navigation/di/ComposeNavigationModule.kt | pantstamp | 832,056,554 | false | {"Kotlin": 172395} | package com.pantelisstampoulis.androidtemplateproject.navigation.di
import androidx.navigation.NavHostController
import com.pantelisstampoulis.androidtemplateproject.navigation.AndroidComposeNavigator
import com.pantelisstampoulis.androidtemplateproject.navigation.NavigationConstants
import com.pantelisstampoulis.androidtemplateproject.navigation.Navigator
import org.koin.core.module.Module
import org.koin.dsl.bind
import org.koin.dsl.module
val navigationModule: Module = module {
factory<NavHostController> { getProperty(NavigationConstants.NAVIGATION_CONTROLLER) }
factory {
AndroidComposeNavigator(get())
} bind Navigator::class
}
| 0 | Kotlin | 1 | 8 | 444d283290ae37404e0bcc0b88fe9ee776d60b21 | 663 | android-template-project | MIT License |
tea-time-travel-plugin/src/test/unit/kotlin/io/github/xlopec/tea/time/travel/plugin/feature/storage/ExportImportTest.kt | Xlopec | 188,455,731 | false | null | package io.github.xlopec.tea.time.travel.plugin.feature.storage
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import io.github.xlopec.tea.time.travel.plugin.data.TestAppStateValue
import io.github.xlopec.tea.time.travel.plugin.data.TestSnapshotId1
import io.github.xlopec.tea.time.travel.plugin.data.TestSnapshotId2
import io.github.xlopec.tea.time.travel.plugin.data.TestTimestamp1
import io.github.xlopec.tea.time.travel.plugin.data.TestTimestamp2
import io.github.xlopec.tea.time.travel.plugin.data.TestUserValue
import io.github.xlopec.tea.time.travel.plugin.model.Filter
import io.github.xlopec.tea.time.travel.plugin.model.FilterOption
import io.github.xlopec.tea.time.travel.plugin.model.CollectionWrapper
import io.github.xlopec.tea.time.travel.plugin.model.DebuggableComponent
import io.github.xlopec.tea.time.travel.plugin.model.Null
import io.github.xlopec.tea.time.travel.plugin.model.OriginalSnapshot
import io.github.xlopec.tea.time.travel.plugin.model.SnapshotMeta
import io.github.xlopec.tea.time.travel.plugin.model.toFiltered
import io.github.xlopec.tea.time.travel.plugin.model.updateFilter
import io.github.xlopec.tea.time.travel.protocol.ComponentId
import kotlin.test.assertEquals
import kotlinx.collections.immutable.persistentListOf
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ExportImportSerializationTest {
@Test
fun `when serialize and deserialize a debug session, it's restored properly`() {
val gson = GsonBuilder().serializeNulls().create()
val snapshotWithoutMessage = OriginalSnapshot(
meta = SnapshotMeta(
id = TestSnapshotId1,
timestamp = TestTimestamp1
),
message = null,
state = TestAppStateValue,
commands = CollectionWrapper(listOf(TestUserValue, TestUserValue, TestUserValue))
)
val snapshotWithNullMessage = OriginalSnapshot(
meta = SnapshotMeta(
id = TestSnapshotId2,
timestamp = TestTimestamp2
),
message = Null,
state = TestAppStateValue,
commands = CollectionWrapper(listOf(TestUserValue, TestUserValue, TestUserValue))
)
// null and Null are different values and should be serialized-deserialized accordingly
val state = DebuggableComponent(
id = TestComponentId,
state = TestAppStateValue,
filter = Filter.new("filter", FilterOption.WORDS, ignoreCase = true),
snapshots = persistentListOf(snapshotWithoutMessage, snapshotWithNullMessage),
filteredSnapshots = persistentListOf(snapshotWithoutMessage.toFiltered())
)
val expectedJsonObject = state.toJsonObject()
val actualJsonObject = gson.fromJson(gson.toJson(expectedJsonObject), JsonObject::class.java)
// the following assert should always hold: `deserialize(serialize(t)) == t`
assertEquals(expectedJsonObject, actualJsonObject)
val actualDebugState = actualJsonObject.toComponentDebugState()
// For restored session filter should be reset
val expectedDebugState = state.updateFilter(Filter.empty())
assertEquals(actualDebugState, expectedDebugState)
}
}
private val TestComponentId = ComponentId("some id")
| 0 | Kotlin | 1 | 10 | 28f37bfe3baeaa721da02c61308b6e1dbc199852 | 3,396 | Tea-bag | MIT License |
business/src/main/kotlin/com/isystk/sample/domain/dao/AdminDao.kt | isystk | 328,037,305 | false | {"Kotlin": 462354, "TypeScript": 88591, "HTML": 77276, "SCSS": 24557, "FreeMarker": 21801, "JavaScript": 5293, "Shell": 3607, "Dockerfile": 1581, "CSS": 942} | package com.isystk.sample.domain.dao;
import com.isystk.sample.domain.dto.AdminCriteria;
import com.isystk.sample.domain.entity.Admin
import org.seasar.doma.*
import org.seasar.doma.boot.ConfigAutowireable
import org.seasar.doma.jdbc.SelectOptions
import java.util.*
import java.util.stream.Collector
/**
*/
@ConfigAutowireable
@Dao
interface AdminDao {
/**
* @param entity
* @return affected rows
*/
@Insert
fun insert(entity: Admin): Int
/**
* @param entity
* @return affected rows
*/
@Update
fun update(entity: Admin): Int
/**
* @param entity
* @return affected rows
*/
@Delete
fun delete(entity: Admin): Int
/**
* @param criteria
* @param options
* @return
*/
@Select(strategy = SelectType.COLLECT)
fun <R> findAll(criteria: AdminCriteria, options: SelectOptions, collector: Collector<Admin, *, R>): R
/**
* @param criteria
* @return
*/
@Select
fun findAll(criteria: AdminCriteria): List<Admin>
/**
* @param id
* @return the Admin entity
*/
@Select
fun selectById(id: Long): Admin?
/**
* @param id
* @param version
* @return the Admin entity
*/
@Select(ensureResult = true)
fun selectByIdAndVersion(id: Long, version: Long): Admin?
/**
* @param criteria
* @return
*/
@Select
fun findOne(criteria: AdminCriteria): Admin?
} | 0 | Kotlin | 0 | 2 | 2e4e0c62af22c05403e5d3452ba08eb09c05a7f1 | 1,464 | kotlin-springboot-boilerplate | MIT License |
router/src/main/java/com/speakerboxlite/router/command/CommandBufferImpl.kt | AlexExiv | 688,805,446 | false | {"Kotlin": 438264} | package com.speakerboxlite.router.command
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.speakerboxlite.router.View
import com.speakerboxlite.router.controllers.AnimationController
import com.speakerboxlite.router.ext.checkMainThread
import com.speakerboxlite.router.ext.getSerializables
import com.speakerboxlite.router.ext.putSerializables
interface ViewFactoryInterface
{
fun createView(key: String): View?
fun createAnimation(view: View): AnimationController?
}
internal class CommandBufferImpl(val factory: ViewFactoryInterface?): CommandBuffer
{
private var executor: CommandExecutor? = null
private val buffer = mutableListOf<Command>()
private val mainHandler = Handler(Looper.getMainLooper())
private var executingCommands = false
override fun bind(executor: CommandExecutor)
{
if (this.executor != null)
unbind()
this.executor = executor
executor.onBind(factory)
executeCommands()
}
override fun unbind()
{
executor?.onUnbind()
executor = null
}
override fun apply(command: Command)
{
//checkMainThread("Applying of the commands only possible on the main thread.")
if (executor == null)
buffer.add(command)
else
tryExecuteCommand(command)
}
override fun sync(items: List<String>): List<String>
{
val itemsRet = executor?.sync(items)?.toMutableList() ?: error("Try to sync executor that hasn't been set")
for (b in buffer)
{
val key = b.getViewKey()
if (key != null)
itemsRet.remove(key)
}
return itemsRet
}
override fun performSave(bundle: Bundle)
{
val root = Bundle()
root.putSerializables(BUFFER, buffer)
bundle.putBundle(ROOT, root)
}
override fun performRestore(bundle: Bundle)
{
val root = bundle.getBundle(ROOT)
buffer.clear()
buffer.addAll(root!!.getSerializables(BUFFER) as? List<Command> ?: listOf())
}
private fun executeCommands()
{
if (executor == null)
return
executingCommands = false
var removeCount = 0
for (c in buffer)
{
try
{
executor!!.execute(c)
removeCount += 1
}
catch (e: IllegalStateException)
{
/*
if command has been executed with IllegalStateException stop the loop and restart it from this position on the next loop
It could be the exception from transaction manager due to already executing something
*/
tryEnqueueExecuteCommands()
break
}
}
while (removeCount > 0) // remove executed commands
{
buffer.removeFirst()
removeCount -= 1
}
}
private fun tryExecuteCommand(command: Command)
{
checkMainThread("Executing of the commands only possible on the main thread.")
try
{
executor!!.execute(command)
}
catch (e: IllegalStateException)
{
/*
if command has been executed with IllegalStateException try to execute it on the next loop
It could be the exception from transaction manager due to already executing something
*/
buffer.add(command)
tryEnqueueExecuteCommands()
}
}
private fun tryEnqueueExecuteCommands()
{
if (executingCommands)
return
executingCommands = true
mainHandler.postDelayed({ executeCommands() }, 1)
}
companion object
{
const val ROOT = "com.speakerboxlite.router.command.CommandBufferImpl"
const val BUFFER = "com.speakerboxlite.router.command.CommandBufferImpl.buffer"
}
} | 8 | Kotlin | 2 | 3 | 5ecc382454908f6f0ad2a72c81edff79ff71763e | 3,983 | Router-Android | MIT License |
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/one_tap/add_new_card/OtherPaymentMethodDynamicFragment.kt | ETS-Android5 | 497,641,294 | true | {"Java Properties": 1, "Markdown": 7, "Gradle": 15, "Shell": 1, "INI": 4, "YAML": 2, "Batchfile": 1, "Text": 1, "Ignore List": 7, "Proguard": 5, "XML": 228, "Kotlin": 655, "Java": 446, "JSON": 45, "HTML": 309, "JavaScript": 14, "CSS": 6, "SVG": 2, "Python": 2} | package com.mercadopago.android.px.internal.features.one_tap.add_new_card
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.mercadopago.android.px.R
import com.mercadopago.android.px.internal.viewmodel.drawables.OtherPaymentMethodFragmentItem
class OtherPaymentMethodDynamicFragment : OtherPaymentMethodFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.px_fragment_other_payment_method_large_dynamic, container, false)
}
companion object {
fun getInstance(model: OtherPaymentMethodFragmentItem) = OtherPaymentMethodDynamicFragment().also {
it.storeModel(model)
}
}
}
| 0 | Java | 0 | 0 | 99f1433c4147dfd8646420fefacc688f23fc390f | 837 | px-android | MIT License |
materialize/taptarget.M.module_definitely-typed.kt | Jolanrensen | 224,876,635 | false | null | @file:JsQualifier("M")
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION")
package M
import Cash
import JQuery
import kotlin.js.*
import kotlin.js.Json
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
external open class TapTarget : Component<TapTargetOptions> {
open var isOpen: Boolean
open fun open()
open fun close()
companion object {
fun getInstance(elem: Element): TapTarget
fun init(els: Element, options: TapTargetOptionsPartial? = definedExternally): TapTarget
fun init(els: NodeList, options: TapTargetOptionsPartial? = definedExternally): Array<TapTarget>
fun init(els: JQuery, options: TapTargetOptionsPartial? = definedExternally): Array<TapTarget>
fun init(els: Cash, options: TapTargetOptionsPartial? = definedExternally): Array<TapTarget>
}
}
external interface TapTargetOptions {
var onOpen: (`this`: TapTarget, origin: Element) -> Unit
var onClose: (`this`: TapTarget, origin: Element) -> Unit
}
external interface TapTargetOptionsPartial {
var onOpen: ((`this`: TapTarget, origin: Element) -> Unit)?
get() = definedExternally
set(value) = definedExternally
var onClose: ((`this`: TapTarget, origin: Element) -> Unit)?
get() = definedExternally
set(value) = definedExternally
} | 0 | Kotlin | 0 | 0 | 6865eacb00ddee4417ace11de847be008e9e28bc | 1,670 | materializecss-kotlin-types | MIT License |
ziti/src/main/kotlin/org/openziti/util/Info.kt | openziti | 214,175,575 | false | null | /*
* Copyright (c) 2018-2021 NetFoundry Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openziti.util
import org.openziti.Ziti
import java.io.Writer
class ZtxInfoProvider: DebugInfoProvider {
override fun names(): Iterable<String> = Ziti.getContexts().map{ it.name() }
override fun dump(name: String, output: Writer) {
val ztx = Ziti.getContexts().find { it.name() == name }
ztx?.dump(output) ?: output.appendLine("ziti context[$name] not found")
}
}
class DnsInfoProvider: DebugInfoProvider {
override fun names() = listOf("ziti_dns.info")
override fun dump(name: String, output: Writer) {
Ziti.getDNSResolver().dump(output)
}
}
class ThreadDumpProvider: DebugInfoProvider {
override fun names() = listOf("thread_dump.txt")
override fun dump(name: String, output: Writer) {
Thread.getAllStackTraces().forEach { t, trace ->
output.appendLine("Thread: ${t}")
trace.forEach {
output.appendLine(" $it")
}
output.appendLine()
}
}
} | 9 | Kotlin | 4 | 9 | 4f561799f9d47e209e802ad46e23b308131b949c | 1,612 | ziti-sdk-jvm | Apache License 2.0 |
bitgouel-api/src/main/kotlin/team/msg/domain/withdraw/presentation/data/response/WithdrawStudentResponse.kt | School-of-Company | 700,741,727 | false | {"Kotlin": 653824, "Shell": 2040, "Dockerfile": 206} | package team.msg.domain.withdraw.presentation.data.response
import team.msg.domain.withdraw.model.WithdrawStudent
import java.util.UUID
data class WithdrawStudentResponse(
val withdrawId: Long,
val userId: UUID,
val name: String,
val email: String,
val phoneNumber: String
) {
companion object {
fun of(withdraw: WithdrawStudent) = WithdrawStudentResponse(
withdrawId = withdraw.id,
userId = withdraw.student.user!!.id,
name = withdraw.student.user!!.name,
email = withdraw.student.user!!.email,
phoneNumber = withdraw.student.user!!.phoneNumber
)
fun listOf(students: List<WithdrawStudent>) = WithdrawStudentResponses(
students.map { of(it) }
)
}
}
data class WithdrawStudentResponses(
val students: List<WithdrawStudentResponse>
)
| 3 | Kotlin | 0 | 17 | 90d788c3e7393290e0f09860af78aebc084ef571 | 873 | Bitgouel-Server | MIT License |
src/main/kotlin/com/github/creeper123123321/viaaas/packet/status/StatusPing.kt | Camotoy | 340,811,792 | true | {"Kotlin": 108622, "JavaScript": 18139, "HTML": 6912, "CSS": 35} | package com.github.creeper123123321.viaaas.packet.status
import com.github.creeper123123321.viaaas.packet.Packet
import io.netty.buffer.ByteBuf
import kotlin.properties.Delegates
class StatusPing : Packet {
var number by Delegates.notNull<Long>()
override fun decode(byteBuf: ByteBuf, protocolVersion: Int) {
number = byteBuf.readLong()
}
override fun encode(byteBuf: ByteBuf, protocolVersion: Int) {
byteBuf.writeLong(number)
}
} | 0 | null | 0 | 0 | 738997f12a01e2cf3a4d408e627896571b08850b | 469 | VIAaaS | MIT License |
lib_utils/src/main/java/com/ndhzs/lib/utils/utils/VibratorUtil.kt | VegetableChicken-Group | 497,243,579 | false | {"Kotlin": 315359, "Shell": 8775} | package com.ndhzs.lib.utils.utils
import android.content.Context
import android.os.*
import android.os.Vibrator
import com.ndhzs.lib.utils.extensions.appContext
/**
* 用于触发震动的工具类
*
* @author 985892345 (Guo Xiangrui)
* @email [email protected]
* @date 2022/2/2 10:24
*/
object VibratorUtil {
/**
* 根据不同的 Android 版本调用不同的震动方法
*/
fun start(milliseconds: Long) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val vibrator = appContext.getSystemService(VibratorManager::class.java)
vibrator.vibrate(
CombinedVibration.createParallel(
VibrationEffect.createOneShot(
milliseconds,
VibrationEffect.DEFAULT_AMPLITUDE
)
)
)
} else {
val vibrator = appContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vibrator.vibrate(
VibrationEffect.createOneShot(
milliseconds,
VibrationEffect.DEFAULT_AMPLITUDE
)
)
} else {
vibrator.vibrate(milliseconds)
}
}
}
} | 0 | Kotlin | 14 | 30 | 3455309ef00ecbe61dbc2c80b8871f8981b412e2 | 1,117 | WanAndroid_Multi | MIT License |
app/src/main/kotlin/br/com/test/claro/net/embratel/listshot/ListShotViewPresenter.kt | flipnovidade | 144,781,670 | false | null | package listshot
interface ListShotViewPresenter {
fun onCreate(page: Int)
fun onDestroy()
} | 0 | Kotlin | 0 | 0 | 5cd9545f5119e3554db2aa89c5c86f33d3587ee4 | 101 | kotlin-dagger2-test-room-etc | Apache License 2.0 |
src/main/kotlin/pl/brightinventions/kequality/EqualsEquality.kt | bright | 285,881,048 | false | null | package pl.brightinventions.kequality
class EqualsEquality<T> : Equality<T> {
override fun areEqual(o1: T, o2: T): Boolean {
return if (o1 == null && o2 == null) {
true
} else {
o1?.equals(o2) ?: false
}
}
} | 0 | Kotlin | 1 | 5 | 86f88e4dbb5f310b7245291aa35383d8d8c241e9 | 264 | kequality | MIT License |
app/src/main/java/com/gabrielthecode/unsplashed/core/usecases/SavePhoto.kt | gabriel-TheCode | 694,800,884 | false | {"Kotlin": 44292} | package com.gabrielthecode.unsplashed.core.usecases
import android.graphics.Bitmap
import android.net.Uri
import com.gabrielthecode.unsplashed.core.domain.Resource
import com.gabrielthecode.unsplashed.core.repositories.SavePhotoRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class SavePhoto @Inject constructor(
private val repository: SavePhotoRepository
) {
operator fun invoke(bitmap: Bitmap): Flow<Resource<Uri>> = flow {
emit(Resource.loading())
try {
val uri = repository.savePhoto(bitmap)
emit(Resource.success(uri))
} catch (e: Exception) {
emit(Resource.failure(e))
}
}
} | 0 | Kotlin | 1 | 1 | 2e5a635f18f87ae7ce524a14b71bb93feefe7f94 | 665 | Unsplashed | MIT License |
services/hanke-service/src/main/kotlin/fi/hel/haitaton/hanke/hakemus/HakemusMigrationService.kt | City-of-Helsinki | 300,534,352 | false | {"Kotlin": 2023322, "Mustache": 89170, "Shell": 23444, "Batchfile": 5169, "PLpgSQL": 1115, "Dockerfile": 371} | package fi.hel.haitaton.hanke.hakemus
import fi.hel.haitaton.hanke.HankeRepository
import fi.hel.haitaton.hanke.application.ApplicationData
import fi.hel.haitaton.hanke.application.ApplicationEntity
import fi.hel.haitaton.hanke.application.CableReportApplicationData
import fi.hel.haitaton.hanke.application.Contact
import fi.hel.haitaton.hanke.application.ExcavationNotificationData
import fi.hel.haitaton.hanke.permissions.HankekayttajaEntity
import fi.hel.haitaton.hanke.permissions.HankekayttajaRepository
import fi.hel.haitaton.hanke.permissions.KayttajakutsuEntity
import fi.hel.haitaton.hanke.permissions.KayttajakutsuRepository
import fi.hel.haitaton.hanke.permissions.PermissionService
import mu.KotlinLogging
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
private val logger = KotlinLogging.logger {}
@Service
class HakemusMigrationService(
val hankeRepository: HankeRepository,
val hankekayttajaRepository: HankekayttajaRepository,
val kayttajakutsuRepository: KayttajakutsuRepository,
val hakemusyhteystietoRepository: HakemusyhteystietoRepository,
val hakemusyhteyshenkiloRepository: HakemusyhteyshenkiloRepository,
val permissionService: PermissionService,
) {
@Transactional
fun migrateOneHanke(hankeId: Int) {
val hanke = hankeRepository.getReferenceById(hankeId)
hanke.hakemukset.singleOrNull()?.let { hakemus: ApplicationEntity ->
logger.info { "Migrating hakemus. ${hakemus.logString()}, ${hanke.logString()}" }
val existingKayttajat = hankekayttajaRepository.findByHankeId(hanke.id)
logger.info {
if (existingKayttajat.isNotEmpty()) {
"Hanke already has users. ${existingKayttajat.size} users with IDs: " +
existingKayttajat.map { it.id }.joinToString()
} else {
"Hanke does not have users."
}
}
val existingKayttajaEmails = existingKayttajat.map { it.sahkoposti }.toMutableSet()
val founder =
createFounderKayttaja(hanke.id, hakemus.applicationData, existingKayttajaEmails)
if (founder != null) {
logger.info { "Created founder with id ${founder.id}" }
existingKayttajaEmails.add(founder.sahkoposti)
} else {
logger.info { "No founder found in hakemus data." }
}
val otherKayttajat =
createOtherKayttajat(hanke.id, hakemus.applicationData, existingKayttajaEmails)
logger.info {
"Created hankekayttajat for other contacts. ${otherKayttajat.size} users with IDs: " +
otherKayttajat.map { it.id }.joinToString()
}
createYhteystiedot(
hakemus,
(otherKayttajat + founder + existingKayttajat).filterNotNull()
)
hakemus.applicationData = clearCustomers(hakemus.applicationData)
} ?: logger.info { "No hakemus for hanke. ${hanke.logString()}" }
}
private fun createYhteystiedot(
applicationEntity: ApplicationEntity,
kayttajat: List<HankekayttajaEntity>
) {
val customersByRoles = applicationEntity.applicationData.customersByRole()
for ((rooli, customerWithContacts) in customersByRoles) {
val customer = customerWithContacts.customer
val yhteystieto =
hakemusyhteystietoRepository.save(
HakemusyhteystietoEntity(
tyyppi = customer.type ?: continue,
rooli = rooli,
nimi = customer.name.defaultIfNullOrBlank(),
sahkoposti = customer.email.defaultIfNullOrBlank(),
puhelinnumero = customer.phone.defaultIfNullOrBlank(),
ytunnus = customer.registryKey,
application = applicationEntity
)
)
logger.info {
"Created an yhteystieto for the hakemus. yhteystietoId=${yhteystieto.id}, ${applicationEntity.logString()}"
}
val yhteyshenkilot =
customerWithContacts.contacts
.filter { !it.email.isNullOrBlank() }
.groupBy { it.email }
.mapNotNull { (email, contacts) ->
val contact = contacts.contactWithLeastMissingFields()
contact?.let {
HakemusyhteyshenkiloEntity(
hakemusyhteystieto = yhteystieto,
hankekayttaja = kayttajat.find { it.sahkoposti == email }!!,
tilaaja = contact.orderer,
)
}
}
val saved = hakemusyhteyshenkiloRepository.saveAll(yhteyshenkilot)
if (customerWithContacts.contacts.size != saved.size) {
logger.info {
"From ${customerWithContacts.contacts.size} contacts we got ${saved.size} yhteystiedot."
}
}
logger.info { "Created yhteystiedot. IDs: ${saved.map { it.id }.joinToString()}" }
}
}
/** Until now, the founder has been marked as the orderer. */
fun createFounderKayttaja(
hankeId: Int,
applicationData: ApplicationData,
existingKayttajaEmails: Set<String>
): HankekayttajaEntity? {
val orderer: Contact =
findOrderer(applicationData) ?: return null.also { logger.warn { "No founder found." } }
if (orderer.email.isNullOrBlank()) {
logger.warn { "Founder has no email, skipping creating kayttaja." }
return null
}
if (orderer.email in existingKayttajaEmails) {
logger.info { "Founder already has a hankekayttaja." }
return null
}
val permission = permissionService.findByHankeId(hankeId).singleOrNull()
val kayttaja =
HankekayttajaEntity(
hankeId = hankeId,
etunimi = orderer.firstName.defaultIfNullOrBlank(),
sukunimi = orderer.lastName.defaultIfNullOrBlank(),
sahkoposti = orderer.email,
// In production, there's an orderer with a blank phone number
puhelin = orderer.phone.defaultIfNullOrBlank(),
permission = permission,
)
return hankekayttajaRepository.save(kayttaja)
}
@Transactional
fun createOtherKayttajat(
hankeId: Int,
applicationData: ApplicationData,
existingKayttajaEmails: Set<String>,
): List<HankekayttajaEntity> {
val byEmail: Map<String, List<Contact>> =
applicationData
.customersWithContacts()
.flatMap { it.contacts }
.filter { !it.email.isNullOrBlank() }
.filter { it.email !in existingKayttajaEmails }
.groupBy { it.email!! }
logger.info { "Found ${byEmail.size} other contacts to migrate." }
val entities =
byEmail.map { (email, contacts) ->
val etunimi = contacts.mapNotNull { it.firstName }.mode().defaultIfNullOrBlank()
val sukunimi = contacts.mapNotNull { it.lastName }.mode().defaultIfNullOrBlank()
HankekayttajaEntity(
hankeId = hankeId,
etunimi = etunimi,
sukunimi = sukunimi,
puhelin = contacts.mapNotNull { it.phone }.mode().defaultIfNullOrBlank(),
sahkoposti = email,
kutsuttuEtunimi = etunimi,
kutsuttuSukunimi = sukunimi,
permission = null,
)
}
val saved = hankekayttajaRepository.saveAll(entities)
for (entity in saved) {
val kutsu = kayttajakutsuRepository.save(KayttajakutsuEntity.create(entity))
entity.kayttajakutsu = kutsu
}
return saved
}
companion object {
internal fun clearCustomers(applicationData: ApplicationData): ApplicationData =
when (applicationData) {
is CableReportApplicationData ->
applicationData.copy(
customerWithContacts = null,
contractorWithContacts = null,
propertyDeveloperWithContacts = null,
representativeWithContacts = null,
)
is ExcavationNotificationData ->
applicationData.copy(
customerWithContacts = null,
contractorWithContacts = null,
propertyDeveloperWithContacts = null,
representativeWithContacts = null,
)
}
/**
* Find the contact with the orderer flag set.
*
* If there are several orderers, find the contact with the most filled fields from those.
*/
internal fun findOrderer(applicationData: ApplicationData): Contact? {
val orderers =
applicationData
.customersWithContacts()
.flatMap { it.contacts }
.filter { it.orderer }
return orderers.contactWithLeastMissingFields()
}
internal fun List<Contact>.contactWithLeastMissingFields(): Contact? = minByOrNull {
var missingFields = 0
if (it.firstName.isNullOrBlank()) {
missingFields += 1
}
if (it.lastName.isNullOrBlank()) {
missingFields += 1
}
if (it.email.isNullOrBlank()) {
missingFields += 1
}
if (it.phone.isNullOrBlank()) {
missingFields += 1
}
missingFields
}
internal fun String?.defaultIfNullOrBlank(): String = if (isNullOrBlank()) "-" else this
internal fun List<String>.mode(): String? =
filter { it.isNotBlank() }.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key
}
}
| 4 | Kotlin | 5 | 4 | c2c04891485439e52600f4b02710af5d4a547ac1 | 10,421 | haitaton-backend | MIT License |
app/src/main/java/com/dladukedev/wordle/theme/Theme.kt | dladukedev | 454,392,939 | false | null | package com.dladukedev.wordle.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.*
import com.dladukedev.wordle.game.domain.ColorThemePreference
@Composable
private fun ThemeProvider(
colors: Colors,
// TODO: typography: Typography = MaterialTheme.typography,
content: @Composable () -> Unit
) {
val rememberedColors = remember {
// Explicitly creating a new object here so we don't mutate the initial [colors]
// provided, and overwrite the values set in it.
colors.copy()
}.apply { updateColorsFrom(colors) }
CompositionLocalProvider(
LocalColors provides rememberedColors,
) {
content()
}
}
internal val LocalColors = staticCompositionLocalOf { lightTheme }
@Composable
fun WordleTheme(themePreference: ColorThemePreference, isColorBlindMode: Boolean = false, content: @Composable () -> Unit) {
val isNightMode = when(themePreference) {
ColorThemePreference.Dark -> true
ColorThemePreference.Light -> false
ColorThemePreference.System -> isSystemInDarkTheme()
}
val colors = when {
isNightMode && isColorBlindMode -> colorBlindDarkTheme
!isNightMode && isColorBlindMode -> colorBlindLightTheme
isNightMode && !isColorBlindMode -> darkTheme
!isNightMode && !isColorBlindMode -> lightTheme
else -> lightTheme
}
ThemeProvider(
colors = colors,
content = content,
)
}
object Theme {
val colors: Colors
@Composable
@ReadOnlyComposable
get() = LocalColors.current
} | 0 | Kotlin | 0 | 5 | d6cd901921605e3aa4d11e406f4df46789694614 | 1,615 | wordle-clone-android | MIT License |
src/main/kotlin/no/nav/fo/veilarbregistrering/registrering/sykmeldt/SykmeldtRegistrering.kt | navikt | 131,013,336 | false | {"Kotlin": 892366, "PLpgSQL": 853, "PLSQL": 546, "Dockerfile": 87} | package no.nav.fo.veilarbregistrering.registrering.bruker
import no.nav.fo.veilarbregistrering.besvarelse.Besvarelse
import no.nav.fo.veilarbregistrering.registrering.BrukerRegistreringType
import no.nav.fo.veilarbregistrering.registrering.manuell.Veileder
import java.time.LocalDateTime
data class SykmeldtRegistrering(
override val id: Long = 0,
val opprettetDato: LocalDateTime = LocalDateTime.now(),
val besvarelse: Besvarelse,
val teksterForBesvarelse: List<TekstForSporsmal>,
override var manueltRegistrertAv: Veileder? = null,
) : BrukerRegistrering() {
override fun hentType(): BrukerRegistreringType {
return BrukerRegistreringType.SYKMELDT
}
override fun toString(): String {
return "SykmeldtRegistrering(id=" + id + ", opprettetDato=" + opprettetDato + ", besvarelse=" + besvarelse + ", teksterForBesvarelse=" + teksterForBesvarelse + ")"
}
} | 8 | Kotlin | 5 | 6 | 68dabd12cfa5af1eb0a3af33fd422a3e755ad433 | 908 | veilarbregistrering | MIT License |
app/src/main/java/bg/zahov/app/util/MonthValueFormatter.kt | HauntedMilkshake | 698,074,119 | false | {"Kotlin": 390308} | package bg.zahov.app.util
import com.github.mikephil.charting.formatter.ValueFormatter
import java.time.LocalDate
class MonthValueFormatter : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
return "${value.toInt()} ${
LocalDate.now().month.name.substring(0, 3).lowercase()
}"
}
}
| 0 | Kotlin | 1 | 2 | 0aaba6d6f4392cb034d20b94e178ebe916ae78e6 | 344 | fitness_app | MIT License |
src/test/kotlin/me/exerro/test.kt | exerro | 483,199,425 | false | null | package me.exerro
import me.exerro.colour.Colour
import me.exerro.colour.ColourPalette
import me.exerro.colour.fromHex
import org.lwjgl.glfw.GLFW
import org.lwjgl.nanovg.NVGColor
import org.lwjgl.nanovg.NanoVG
import org.lwjgl.nanovg.NanoVGGL3
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL46C
import org.lwjgl.system.MemoryUtil.NULL
fun rect(
context: Long,
colour: Colour,
x: Float,
y: Float,
width: Float,
height: Float,
) {
val c = NVGColor.calloc()
NanoVG.nvgRGBAf(colour.red, colour.green, colour.blue, colour.alpha, c)
NanoVG.nvgBeginPath(context)
NanoVG.nvgRect(context, x, y, width, height)
NanoVG.nvgClosePath(context)
NanoVG.nvgFillColor(context, c)
NanoVG.nvgFill(context)
c.free()
}
fun drawPalette(
context: Long,
palette: ColourPalette,
) {
// background0
// background1
// background2
// background3
// grey0
// grey1
// grey2
// foreground0
// foreground1
// foreground2
// foreground3
// shadow
rect(context, palette.purple, 32f, 128f, 128f, 64f)
rect(context, palette.red, 192f, 128f, 128f, 64f)
rect(context, palette.orange, 352f, 128f, 128f, 64f)
rect(context, palette.yellow, 512f, 128f, 128f, 64f)
rect(context, palette.green, 672f, 128f, 128f, 64f)
rect(context, palette.blue, 832f, 128f, 128f, 64f)
rect(context, palette.teal, 32f, 256f, 128f, 64f)
rect(context, palette.burgundy, 192f, 256f, 128f, 64f)
rect(context, palette.pink, 352f, 256f, 128f, 64f)
rect(context, palette.salmon, 512f, 256f, 128f, 64f)
rect(context, palette.brown, 672f, 256f, 128f, 64f)
rect(context, palette.cream, 832f, 256f, 128f, 64f)
rect(context, palette.grey0, 32f, 384f, 128f, 64f)
rect(context, palette.grey1, 192f, 384f, 128f, 64f)
rect(context, palette.grey2, 352f, 384f, 128f, 64f)
rect(context, palette.foreground0, 512f, 384f, 128f, 64f)
rect(context, palette.foreground1, 672f, 384f, 128f, 64f)
rect(context, palette.foreground2, 832f, 384f, 128f, 64f)
rect(context, palette.foreground3, 992f, 384f, 128f, 64f)
}
fun drawWindow(context: Long) {
val colours = listOf(
"#efe8c5",
"#6e362f",
"#eedc8e",
"#552a3f",
"#d6b858",
"#d37dad",
)
GL46C.glClearColor(ColourPalette.background1.red, ColourPalette.background1.green, ColourPalette.background1.blue, 1f)
GL46C.glClear(GL46C.GL_COLOR_BUFFER_BIT)
drawPalette(context, ColourPalette)
for ((i, v) in colours.withIndex()) {
rect(context, Colour.fromHex(v), 64f * i, 0f, 64f, 32f)
}
}
fun main() {
GLFW.glfwInit()
val window = GLFW.glfwCreateWindow(1080, 720, "Colour test", NULL, NULL)
assert(window != NULL)
GLFW.glfwMakeContextCurrent(window)
GL.createCapabilities()
val context = NanoVGGL3.nvgCreate(0)
assert(context != NULL)
while (!GLFW.glfwWindowShouldClose(window)) {
val width = intArrayOf(0)
val height = intArrayOf(0)
GLFW.glfwGetWindowSize(window, width, height)
GL46C.glViewport(0, 0, width[0], height[0])
NanoVG.nvgBeginFrame(context, width[0].toFloat(), height[0].toFloat(), 1f)
drawWindow(context)
NanoVG.nvgEndFrame(context)
GLFW.glfwSwapBuffers(window)
GLFW.glfwWaitEvents()
}
}
| 0 | Kotlin | 0 | 0 | 6093cc52ed027dc2aeacdd375fff200fff984e80 | 3,362 | colour | MIT License |
src/org/jetbrains/projector/plugins/markdown/lang/index/MarkdownHeadersIndex.kt | JetBrains | 267,844,876 | false | null | /*
* MIT License
*
* Copyright (c) 2019-2020 JetBrains s.r.o.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.jetbrains.projector.plugins.markdown.lang.index
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import com.intellij.util.CommonProcessors
import org.jetbrains.projector.plugins.markdown.lang.psi.impl.MarkdownHeaderImpl
class MarkdownHeadersIndex : StringStubIndexExtension<MarkdownHeaderImpl>() {
override fun getKey(): StubIndexKey<String, MarkdownHeaderImpl> = KEY
companion object {
val KEY: StubIndexKey<String, MarkdownHeaderImpl> = StubIndexKey.createIndexKey<String, MarkdownHeaderImpl>("markdown.header")
fun collectFileHeaders(suggestHeaderRef: String, project: Project, psiFile: PsiFile?): Collection<PsiElement> {
val list = mutableListOf<PsiElement>()
StubIndex.getInstance().processElements(
MarkdownHeadersIndex.KEY, suggestHeaderRef, project,
psiFile?.let { GlobalSearchScope.fileScope(it) },
MarkdownHeaderImpl::class.java,
CommonProcessors.CollectProcessor(list)
)
return list
}
}
}
| 0 | null | 5 | 7 | 835f143670df6a1ff2499f65b63899a5f4ae6264 | 2,384 | projector-markdown-plugin | MIT License |
src/commonMain/kotlin/no/dossier/libraries/amqpconnector/primitives/AmqpQueueSpec.kt | dossiersolutions | 560,785,521 | false | {"Kotlin": 140817} | package no.dossier.libraries.amqpconnector.primitives
data class AmqpQueueSpec(
val name: String,
val durable: Boolean,
val exclusive: Boolean,
val autoDelete: Boolean,
) | 0 | Kotlin | 1 | 3 | 939a02fc57468d75a9848dff99b92547d28534da | 187 | amqp-connector | MIT License |
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/auth/User.kt | agaro1121 | 128,481,943 | true | {"Kotlin": 1591579, "Scala": 1124254, "Batchfile": 17450, "Shell": 8834, "Java": 1758, "Swift": 1555, "HTML": 303, "CSS": 35, "JavaScript": 28} | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: <NAME>
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.auth
/**
* Represents a user for authentication purposes
* @param id : User id
* @param fullName : Full name of user
* @param firstName : First name
* @param lastName : Last name
* @param email : Email
* @param phone : Primary phone
* @param isPhoneVerified : Whether the phone is verified
* @param isDeviceVerified : Whether the device is verified
* @param isEmailVerified : Whether the email is verified
* @param city : The city where user is in
* @param state : The state where user is in
* @param zip : The zip where user is in
* @param country : The country where user is in ( 2 digit county code )
* @param region : The region of the user ( can use as a shard )
* @param tag : A tag used for external links
* @param version : The schema version of this model
*/
data class User (
val id :String = "" ,
val fullName :String = "" ,
val firstName :String = "" ,
val lastName :String = "" ,
val email :String = "" ,
val phone :String = "" ,
val isPhoneVerified :Boolean = false ,
val isDeviceVerified:Boolean = false ,
val isEmailVerified :Boolean = false ,
val city :String = "" ,
val state :String = "" ,
val zip :String = "" ,
val country :String = "" ,
val region :String = "" ,
val tag :String = "" ,
val version :String = "" ,
val token :String = ""
)
{
fun isMatch(user:User):Boolean = user.id == this.id
}
| 0 | Kotlin | 0 | 0 | 8a9257a8c789bd0383370916f66c8f830e60125c | 2,419 | slatekit | Apache License 2.0 |
app/src/main/java/com/digitalmid/seograph_webmasters_tool/CompareRes.kt | parth-samcom2018 | 155,720,919 | false | null | package com.digitalmid.seograph_webmasters_tool.com.digitalmid.seograph_webmasters_tool
import com.google.gson.annotations.SerializedName
data class CompareData(
@SerializedName("currentweek")
var currentweek: List<Currentweek>,
@SerializedName("diff")
var diff: List<Diff>,
@SerializedName("error")
var error: Boolean,
@SerializedName("lastweek")
var lastweek: List<Lastweek>,
@SerializedName("message")
var message: String
) {
data class Currentweek(
@SerializedName("clicks")
var clicks: String,
@SerializedName("date")
var date: String
)
data class Lastweek(
@SerializedName("clicks")
var clicks: String,
@SerializedName("date")
var date: String
)
data class Diff(
@SerializedName("different")
var different: Int
)
} | 0 | Kotlin | 0 | 0 | 859c3d04e91aff7a1f3843888d185ad761de292c | 949 | Webmaster | Creative Commons Attribution 3.0 Unported |
reactivestate-core/src/commonMain/kotlin/com/ensody/reactivestate/WhileUsed.kt | ensody | 246,103,397 | false | null | package com.ensody.reactivestate
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.invoke
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
/**
* A reference-counted value that is created on-demand and freed once nobody uses it (whereas `by lazy` is never freed).
*
* [WhileUsed] is useful for e.g. caches or other resource-consuming values that shouldn't live forever, but only
* exist while they're in use. Sometimes this can also be helpful for dealing with security-critical data.
*
* This can be a great combination with [SharingStarted.WhileSubscribed] and either [derived] or
* [Flow.stateIn]/[Flow.shareIn], for example.
*
* In order to request the value with [invoke] you need a [CoroutineScope] or a [DisposableGroup].
* Note: Your [builder] function is also passed a [DisposableGroup] for accessing other [WhileUsed] instances.
* The [CoroutineScope]/[DisposableGroup] is used to track the requester's lifetime and in turn the reference count.
* As an alternative when you don't have a [CoroutineScope] you can also use [disposableValue], but this is more
* error-prone because it's easier to forget.
*
* Typically you'd place such values in your DI system and have one or more ViewModels or UI screens or widgets
* requesting the value. Once these screens/widgets/ViewModels are destroyed (e.g. because the user pressed on the back
* button) the value is freed again.
*
* Example:
*
* ```kotlin
* val createDatabase = WhileUsed { Database() }
* val createCache = WhileUsed { DbCache(createDatabase(it)) }
*
* class MyViewModel : ViewModel() {
* val cache = createCache(viewModelScope)
* }
* ```
*
* @param retentionMillis Defines a retention period in milliseconds in which to still keep the value in RAM
* although the reference count returned to 0. If the value is requested again within
* this retention period, the old value is reused. Defaults to 0 (immediately frees the value).
* @param destructor Optional destructor which can clean up the object before it gets freed.
* Defaults to `null` in which case, if the value is a [Disposable], its `dispose()` method is called.
* Pass an empty lambda function if you don't want this behavior.
* @param builder Should create and return the value. The builder gets a [DisposableGroup] as its argument for
* retrieving other [WhileUsed] values or for adding other [Disposable]s which must be cleaned up
* together with this value (as an alternative to using [destructor]).
*/
public class WhileUsed<T>(
private val retentionMillis: Long = 0,
private val destructor: ((T) -> Unit)? = null,
private val builder: (WhileUsedReferenceToken) -> T,
) {
private val mutex = Mutex()
private var value: Wrapped<T>? = null
private var disposables = WhileUsedReferenceToken()
private var references = 0
private var cleaner: Job? = null
/**
* Creates or returns the existing value while incrementing the reference count.
*
* When the given [userScope] is canceled the reference count is decremented.
* Once the count is 0 the value is freed.
*/
public operator fun invoke(userScope: CoroutineScope): T =
disposableValue().apply {
disposeOnCompletionOf(userScope)
}.value
/**
* Creates or returns the existing value while incrementing the reference count.
*
* When the given [referenceToken] is disposed the reference count is decremented.
* Once the count is 0 the value is freed.
*/
public operator fun invoke(referenceToken: DisposableGroup): T =
disposableValue().also {
referenceToken.add(it)
}.value
/**
* Creates or returns the existing value while incrementing the reference count. You really want [invoke] instead.
*
* IMPORTANT: You have to call `dispose()` on the returned value once you stop using it.
*/
public fun disposableValue(): DisposableValue<T> =
mutex.withSpinLock {
val result = value ?: Wrapped(builder(disposables))
cleaner?.cancel()
cleaner = null
value = result
references++
DisposableValue(result.value, ::release)
}
@OptIn(DelicateCoroutinesApi::class)
private fun release() {
mutex.withSpinLock {
references--
if (references > 0) {
return@withSpinLock
}
if (retentionMillis <= 0) {
clear()
return@withSpinLock
}
// While usually it's not ok to use the GlobalScope we really want to make this transparent.
cleaner = GlobalScope.launch {
delay(retentionMillis)
mutex.withSpinLock {
if (references == 0) {
clear()
}
}
}
}
}
private fun clear() {
value?.also { destructor?.invoke(it.value) }
?: (value?.value as? Disposable)?.dispose()
value = null
disposables.dispose()
}
}
/** The reference token passed to the [WhileUsed] builder function. */
public class WhileUsedReferenceToken : DisposableGroup by DisposableGroup() {
/** A lazily created [MainScope] that lives only as long as the [WhileUsed] value. */
public val scope: CoroutineScope
get() =
lazyScope ?: MainScope().also {
lazyScope = it
add(
OnDispose {
lazyScope = null
it.cancel()
},
)
}
private var lazyScope: CoroutineScope? = null
}
| 3 | null | 2 | 38 | aee5e749799fc542d23c39cd6862a12e7b8831ae | 6,227 | ReactiveState-Kotlin | Apache License 2.0 |
drm-blockchain/src/main/kotlin/service/RightService.kt | Smileslime47 | 738,883,139 | false | {"Kotlin": 191453, "Vue": 52721, "Java": 42412, "TypeScript": 19613, "Solidity": 18053, "CSS": 1622, "Shell": 773, "Dockerfile": 440, "HTML": 390} | package moe._47saikyo.service
import moe._47saikyo.annotation.ViewFunction
import moe._47saikyo.contract.Right
import moe._47saikyo.models.RightData
import moe._47saikyo.models.RightDeployForm
import org.web3j.tx.TransactionManager
import java.math.BigInteger
/**
* 版权合约Service接口
*
* @author 刘一邦
*/
interface RightService {
/**
* 通过版权标题搜索版权合约地址
*
* @param title 版权标题
* @return 版权合约地址列表
*/
@ViewFunction
fun searchByTitle(
callerAddr: String,
title: String
): List<String>
/**
* 估算部署合约所需的gas
*
* @param form 版权部署表单
* @return 估算的gas
*/
fun estimateDeploy(
callerAddr: String,
form: RightDeployForm
): BigInteger
/**
* 添加版权合约
*
* @param transactionManager 交易管理器
* @param form 版权部署表单
* @return 版权合约
*/
fun addRight(
transactionManager: TransactionManager,
form: RightDeployForm
): Right
/**
* 添加授权
*
* @param transactionManager 交易管理器
* @param rightAddr 版权合约地址
* @param licenseAddr 授权合约地址
* @return 版权合约
*/
fun addLicense(
transactionManager: TransactionManager,
rightAddr: String,
licenseAddr: String
)
/**
* 获取版权合约的纯数据对象
*
* @param rightAddr 版权合约地址
* @return 纯数据对象
*/
@ViewFunction
fun getPureData(
callerAddr: String,
rightAddr: String
): RightData
/**
* 获取用户的版权
*
* @param owner 用户地址
* @return 版权合约列表
*/
@ViewFunction
fun getRights(
owner: String
): List<RightData>
} | 0 | Kotlin | 0 | 2 | 8ef270753c3f0cc520f0befcde8d60cb97c25f75 | 1,622 | Digital-Rights-Management | MIT License |
src/commonMain/kotlin/com/github/andreypfau/raptorq/core/ObjectTransmissionInformation.kt | andreypfau | 531,010,252 | false | {"Kotlin": 182365} | package com.github.andreypfau.raptorq.core
import kotlin.math.ceil
import kotlin.math.floor
// As defined in section 3.3.2 and 3.3.3
data class ObjectTransmissionInformation(
val transferLength: ULong,
val symbolSize: UShort,
val numSourceBlocks: UByte,
val numSubBlocks: UShort,
val symbolAlignment: UByte
) {
init {
require(transferLength <= 942574504275u)
require(symbolSize in 16u..65535u)
require(numSourceBlocks in 1u..255u)
require(numSubBlocks in 1u..65535u)
require(symbolAlignment in 1u..255u)
}
companion object {
fun generateEncodingParameters(
transferLength: ULong,
maxPacketSize: UShort,
decoderMemoryRequirement: ULong = 10uL * 1024uL * 1024uL
): ObjectTransmissionInformation {
val alignment = 8.toUShort()
require(maxPacketSize >= alignment)
val symbolSize = (maxPacketSize - (maxPacketSize % alignment)).toUShort()
val subSymbolSize = 8u
val kt = ceil(transferLength.toDouble() / symbolSize.toDouble())
val nMax = floor(symbolSize.toDouble() / (subSymbolSize * alignment).toDouble()).toInt()
fun kl(n: Int): Int {
SYSTEMATIC_INDICES_AND_PARAMETERS.reversed().forEach { (kPrime, _, _, _, _) ->
val x = ceil(symbolSize.toDouble() / (alignment * n.toUInt()).toDouble())
if (kPrime <= (decoderMemoryRequirement.toDouble() / (alignment.toDouble() * x))) {
return kPrime
}
}
error("No k' found")
}
val numSourceBlocks = ceil(kt / kl(nMax).toDouble()).toInt()
var n = 1
for (i in 1..nMax) {
n = i
if (ceil(kt / numSourceBlocks.toDouble()).toInt() <= kl(n)) {
break
}
}
return ObjectTransmissionInformation(
transferLength,
symbolSize,
numSourceBlocks.toUByte(),
n.toUShort(),
alignment.toUByte()
)
}
}
}
| 0 | Kotlin | 0 | 0 | e0364bfd0ceae46c30993db72424802b7553a02b | 2,208 | raptorq-kotlin | Apache License 2.0 |
app/src/main/java/com/bulletapps/candypricer/domain/usecase/supply/UpdateSupplyUseCase.kt | jvsena42 | 485,055,339 | false | {"Kotlin": 265086} | package com.bulletapps.candypricer.domain.usecase.supply
import com.bulletapps.candypricer.data.parameters.UpdateSupplyParameters
import com.bulletapps.candypricer.data.repository.CandyPricerRepository
import com.bulletapps.candypricer.data.response.SupplyResponse
import com.google.gson.annotations.SerializedName
import javax.inject.Inject
class UpdateSupplyUseCase @Inject constructor(
private val repository: CandyPricerRepository
) {
suspend operator fun invoke(
id: Int,
name: String,
quantity: Double,
price: Double,
unitId: Int,
) = repository.updateSupply(
UpdateSupplyParameters(
id = id,
name = name,
quantity = quantity,
price = price,
unitId = unitId
)
)
} | 18 | Kotlin | 0 | 2 | c89da3d248d32f976ad7f0d918815822787ae33a | 803 | baking_calculator | MIT License |
app/src/main/java/polinema/ac/id/pinar_app_astar/presentation/scan/ScanFragment.kt | AR-Navigation | 738,644,223 | false | {"Kotlin": 99336} | package hackfest.ac.id.arnav.presentation.scan
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.budiyev.android.codescanner.CodeScanner
import com.budiyev.android.codescanner.DecodeCallback
import com.budiyev.android.codescanner.ScanMode
import com.google.zxing.BarcodeFormat
import hackfest.ac.id.arnav.data.model.POI
import hackfest.ac.id.arnav.databinding.FragmentScanBinding
import hackfest.ac.id.arnav.utils.PermissionHelper.hasCameraPermission
import hackfest.ac.id.arnav.utils.PermissionHelper.requestCameraPermission
import hackfest.ac.id.arnav.utils.UIHelper.alertBuilder
import hackfest.ac.id.arnav.utils.UIHelper.popBackFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
class ScanFragment : Fragment() {
private var _binding: FragmentScanBinding? = null
private val binding get() = _binding as FragmentScanBinding
private val args: ScanFragmentArgs by navArgs()
private val destination: POI? by lazy { args.destination }
private val viewModel: ScanViewModel by viewModel()
// QR Reader
private val codeScanner by lazy { CodeScanner(requireContext(), binding.scannerView) }
private var isFound = false
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentScanBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.fabBack.setOnClickListener { popBackFragment(it) }
alertBuilder(
requireContext(),
"Scan QR Code!",
"QR Code usually in the center of lobby each level of Building."
).setPositiveButton("OK") { dialog, _ -> dialog.dismiss()
}.show()
if (hasCameraPermission(requireContext())) setupQRCamera()
else requestCameraPermission(requireActivity())
viewModel.qrValue.observe(viewLifecycleOwner) {
if (!it.hasBeenHandled) {
val data = it.peekContent()
if (data != null) {
if (!isFound) {
isFound = true
if (destination != null) {
if (destination!!.floor != data) {
alertBuilder(
requireContext(),
"Different Floor",
"Please scan in the same floor as destination"
).setNeutralButton("OK") { dialog, _ ->
isFound = false
dialog.dismiss()
}.show()
} else {
alertBuilder(
requireContext(),
"Match",
"You are on level ${destination!!.floor}"
).setPositiveButton("OK") {dialog, _ ->
findNavController().navigate(ScanFragmentDirections
.toSceneFragment(destination!!)
)
dialog.dismiss()
}.show()
}
} else {
alertBuilder(
requireContext(),
"Found Level",
"You are on level $data"
).setPositiveButton("OK") {dialog, _ ->
findNavController().navigate(ScanFragmentDirections
.toAddNodeFragment(data)
)
dialog.dismiss()
}.show()
}
}
} else {
alertBuilder(
requireContext(),
"Different QRCode",
"Please scan ARNAV QRCode Only"
).setNeutralButton("OK") {dialog, _ ->
dialog.dismiss()
}.show()
}
}
}
}
private fun setupQRCamera() = with(codeScanner) {
camera = CodeScanner.CAMERA_BACK
formats = listOf(BarcodeFormat.QR_CODE)
scanMode = ScanMode.CONTINUOUS
decodeCallback = DecodeCallback {
lifecycleScope.launch(Dispatchers.IO) {
viewModel.onQrRecognized(it.text.toIntOrNull())
}
}
}
override fun onResume() {
super.onResume()
codeScanner.startPreview()
}
override fun onPause() {
codeScanner.releaseResources()
super.onPause()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 1 | 0 | 59756d2a9932424c241762153296327e02183d75 | 5,410 | ar-nav-mobile | BSD Source Code Attribution |
coroutines/src/main/kotlin/br/com/devsrsouza/kotlinbukkitapi/coroutines/flow/Extensions.kt | DevSrSouza | 123,673,532 | false | null | package br.com.devsrsouza.kotlinbukkitapi.coroutines.flow
import br.com.devsrsouza.kotlinbukkitapi.architecture.extensions.WithPlugin
import br.com.devsrsouza.kotlinbukkitapi.extensions.SimpleKListener
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filter
import org.bukkit.entity.Player
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerEvent
import org.bukkit.plugin.Plugin
/**
* Creates a event flow for [PlayerEvent] that auto filter for only events from [player].
*/
public inline fun <reified T : PlayerEvent> WithPlugin<*>.playerEventFlow(
player: Player,
priority: EventPriority = EventPriority.NORMAL,
ignoreCancelled: Boolean = false,
channel: Channel<T> = Channel<T>(Channel.CONFLATED),
listener: Listener = SimpleKListener(plugin),
): Flow<T> = plugin.playerEventFlow(player, priority, ignoreCancelled, channel, listener)
public inline fun <reified T : PlayerEvent> Plugin.playerEventFlow(
player: Player,
priority: EventPriority = EventPriority.NORMAL,
ignoreCancelled: Boolean = false,
channel: Channel<T> = Channel<T>(Channel.CONFLATED),
listener: Listener = SimpleKListener(this),
): Flow<T> = playerEventFlow(player, this, priority, ignoreCancelled, channel, listener)
public inline fun <reified T : PlayerEvent> playerEventFlow(
player: Player,
plugin: Plugin,
priority: EventPriority = EventPriority.NORMAL,
ignoreCancelled: Boolean = false,
channel: Channel<T> = Channel<T>(Channel.CONFLATED),
listener: Listener = SimpleKListener(plugin),
): Flow<T> = eventFlow<T>(T::class, plugin, player, priority, ignoreCancelled, channel, listener)
.filter { it.player.name == player.name }
| 11 | Kotlin | 22 | 144 | 14874b92734a0273b4e7a748391a6e449bbaae1d | 1,795 | KotlinBukkitAPI | MIT License |
applivery-base/src/main/java/com/applivery/base/domain/model/AppData.kt | applivery | 40,442,532 | false | {"Java": 180078, "Kotlin": 112284} | package com.applivery.base.domain.model
data class AppData(
val id: String,
val name: String,
val description: String,
val slug: String,
val appConfig: AppConfig
)
| 5 | Java | 14 | 19 | 5513bad15744a214024ae3e437917150f80764f2 | 185 | applivery-android-sdk | Apache License 2.0 |
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package61/Foo06118.kt | yamamotoj | 163,851,411 | false | null | package com.github.yamamotoj.module3.package61
class Foo06118 {
fun method0() {
Foo06117().method5()
}
fun method1() {
method0()
}
fun method2() {
method1()
}
fun method3() {
method2()
}
fun method4() {
method3()
}
fun method5() {
method4()
}
}
| 0 | Kotlin | 0 | 9 | 2a771697dfebca9201f6df5ef8441578b5102641 | 347 | android_multi_module_experiment | Apache License 2.0 |
video/ai-extensions/video-18-ai-app-kotlin-glowby/AiExtensions.kt | glowbom | 255,726,838 | false | {"HTML": 1537747, "Swift": 170997, "Kotlin": 32976, "Dart": 24882, "TypeScript": 10191, "C#": 2965, "JavaScript": 2299} | package com.glowbom.custom
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
class AiExtensions {
companion object {
// Flag to enable or disable the GlowbyScreen
var enabled = true
// Title for the GlowbyScreen
var title = "InspirARTion"
/**
* Composable function that displays the AI Art generation screen when enabled is set to true.
* It allows users to input a phrase and generates art based on that phrase.
*
* @param modifier Modifier to be applied to the Box layout
*/
@Composable
fun GlowbyScreen(
modifier: Modifier = Modifier
) {
var inputText by remember { mutableStateOf("") }
var apiKey by remember { mutableStateOf("") }
var imageBitmap by remember { mutableStateOf<Bitmap?>(null) }
var isLoading by remember { mutableStateOf(false) }
Column(
modifier = modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
BasicTextField(
value = apiKey,
onValueChange = { apiKey = it },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
decorationBox = { innerTextField ->
if (apiKey.isEmpty()) {
Text("Enter your OpenAI API Key here")
}
innerTextField()
}
)
BasicTextField(
value = inputText,
onValueChange = { inputText = it },
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
decorationBox = { innerTextField ->
if (inputText.isEmpty()) {
Text("Enter your inspirational phrase here")
}
innerTextField()
}
)
// Inside the Composable function
val coroutineScope = rememberCoroutineScope() // Remember a CoroutineScope tied to the Composable's lifecycle
Button(
onClick = {
coroutineScope.launch {
isLoading = true
imageBitmap = fetchArt(apiKey, inputText)
isLoading = false
}
},
modifier = Modifier.padding(16.dp)
) {
Text(if (isLoading) "Generating..." else "Generate Art")
}
imageBitmap?.let { bitmap ->
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = "Generated Art",
modifier = Modifier
.height(300.dp)
.fillMaxWidth()
.align(Alignment.CenterHorizontally)
)
}
}
}
// Placeholder function to simulate fetching art from an API
private suspend fun fetchArt(apiKey: String, inputPhrase: String): Bitmap? {
if (apiKey.isBlank() || inputPhrase.isBlank()) {
// Handle case where API key or input phrase is not provided
return null
}
// Endpoint for DALL-E 3 API
val apiUrl = URL("https://api.openai.com/v1/images/generations")
// Create the JSON payload with the prompt
val jsonPayload = JSONObject()
jsonPayload.put("prompt", inputPhrase)
jsonPayload.put("n", 1)
jsonPayload.put("model", "dall-e-3") // Use DALL-E 3 model
return withContext(Dispatchers.IO) {
try {
val connection = apiUrl.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("Content-Type", "application/json")
connection.setRequestProperty("Authorization", "Bearer $apiKey")
connection.doOutput = true
// Send the POST request
connection.outputStream.use { os ->
os.write(jsonPayload.toString().toByteArray())
}
// Check the response code and proceed accordingly
if (connection.responseCode == HttpURLConnection.HTTP_OK) {
// Read the response to get the URL of the generated image
val jsonResponse = JSONObject(connection.inputStream.bufferedReader().use { it.readText() })
val imageUrls = jsonResponse.getJSONArray("data").getJSONObject(0).getString("url")
// Fetch the image from the provided URL
val imageUrl = URL(imageUrls)
val imageConnection = imageUrl.openConnection() as HttpURLConnection
imageConnection.connect()
val imageStream = imageConnection.inputStream
val generatedBitmap = BitmapFactory.decodeStream(imageStream)
imageStream.close()
imageConnection.disconnect()
generatedBitmap // Placeholder for the Bitmap you will return
} else {
// Handle errors as needed
null
}
} catch (e: Exception) {
// Handle exceptions as needed
null
}
}
}
}
} | 0 | HTML | 6 | 31 | ebb10823c014590b32c8e998900747debae812a9 | 6,950 | Glowbom | MIT License |
part-02/src/test/kotlin/eu/luminis/workshop/smallsteps/api/LegoStockReportRoutesTest.kt | nkrijnen | 557,352,579 | false | {"Kotlin": 49450} | package eu.luminis.workshop.smallsteps.api
import eu.luminis.workshop.smallsteps.api.helper.TestLegoStockRepository
import eu.luminis.workshop.smallsteps.api.helper.setupLegoTestApp
import eu.luminis.workshop.smallsteps.logic.domainModel.valueObjects.LegoSetNumber
import eu.luminis.workshop.smallsteps.logic.domainService.helper.TestUsers
import eu.luminis.workshop.smallsteps.logic.domainService.state.IncompleteReturn
import eu.luminis.workshop.smallsteps.logic.domainService.state.LegoBox
import eu.luminis.workshop.smallsteps.logic.domainService.state.StockState
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.Test
import kotlin.test.assertEquals
internal class LegoStockReportRoutesTest {
private val millenniumFalcon = LegoSetNumber(75192)
private val atAt = LegoSetNumber(75288)
private val r2d2 = LegoSetNumber(75308)
@Test
fun `should return missing parts report`() = testApplication {
// given
val stockRepository = TestLegoStockRepository(
StockState(
incompleteStock = listOf(
LegoBox(millenniumFalcon, 42, mapOf("3022" to 7, "20105" to 1)),
LegoBox(millenniumFalcon, 37, mapOf("3022" to 3, "60581" to 1)),
LegoBox(atAt, 5, mapOf("3022" to 2, "18674" to 1)),
LegoBox(r2d2, 8, mapOf("3666" to 2, "64799" to 1)),
)
)
)
val client = setupLegoTestApp(stockRepository)
client.get("/stock/report/current-missing-parts") {
header("X-API-GATEWAY-AUTH", "${TestUsers.bussum}")
header("X-SELECTED-LEGO-STORE", "${TestUsers.bussum}")
}.apply {
assertEquals(HttpStatusCode.OK, status)
val response = body<List<Pair<String, Int>>>()
assertEquals(
listOf(
"3022" to 12,
"3666" to 2,
"18674" to 1,
"20105" to 1,
"60581" to 1,
"64799" to 1
),
response
)
}
}
@Test
fun `should return historic most lost parts report`() = testApplication {
// given
val stockRepository = TestLegoStockRepository(
StockState(
incompleteReturnHistory = listOf(
IncompleteReturn(millenniumFalcon, mapOf("3022" to 5, "20105" to 1)),
IncompleteReturn(millenniumFalcon, mapOf("3022" to 3, "60581" to 1)),
IncompleteReturn(atAt, mapOf("3022" to 2, "18674" to 1)),
IncompleteReturn(r2d2, mapOf("3666" to 2, "64799" to 1)),
)
)
)
val client = setupLegoTestApp(stockRepository)
client.get("/stock/report/historicly-most-lost") {
header("X-API-GATEWAY-AUTH", "${TestUsers.bussum}")
header("X-SELECTED-LEGO-STORE", "${TestUsers.bussum}")
}.apply {
assertEquals(HttpStatusCode.OK, status)
val response = body<List<Pair<String, Int>>>()
assertEquals(
listOf(
"3022" to 10,
"3666" to 2,
"18674" to 1,
"20105" to 1,
"60581" to 1,
"64799" to 1
),
response
)
}
}
} | 0 | Kotlin | 1 | 0 | 2d168640126c39d2a13d5dc85d05cd6ab534b6d1 | 3,521 | workshop-ddd-nl-2022-11 | MIT License |
app/src/main/java/com/example/foodsatellite/domain/util/Constants.kt | ozkantuncel | 627,822,442 | false | null | package com.example.foodsatellite.domain.util
object BaseUrl{
val BASE_URL = "http://kasimadalan.pe.hu/yemekler/"
} | 0 | Kotlin | 0 | 5 | f5733aff663cf51ab53f63caf28e83dcdf0da7f6 | 121 | Food_Satellite | The Unlicense |
src/main/kotlin/SpecialScore.kt | josh-watcha | 382,850,115 | false | null | enum class SpecialScore(val score: Int, val displayName: String) {
LOVE(0, "Love"),
FIFTEEN(1, "Fifteen"),
THIRTY(2, "Thirty"),
FORTY(3, "Forty");
companion object {
fun getScore(score: Int): SpecialScore {
return values().first { it.score == score }
}
}
} | 0 | Kotlin | 0 | 0 | 4e6f4c2a9981638860c40bbc27aa21f2e9ac0534 | 309 | Tennis-refactoring-kata-kotlin | MIT License |
src/main/kotlin/twentytwentytwo/Structures.kt | JanGroot | 317,476,637 | false | {"Kotlin": 80906} | package twentytwentytwo
import kotlin.math.abs
import kotlin.math.absoluteValue
import kotlin.math.sign
typealias Visitor<T> = (Structures.TreeNode<T>) -> Unit
class Structures {
interface Queue<T> {
val count: Int
val isEmpty: Boolean
fun enqueue(element: T): Boolean
fun dequeue(): T?
fun peek(): T?
}
class ArrayListQueue<T> : Queue<T> {
private val storage = arrayListOf<T>()
override val count: Int
get() = storage.size
override val isEmpty: Boolean
get() = count == 0
override fun enqueue(element: T): Boolean = storage.add(element)
override fun dequeue(): T? = if (isEmpty) null else storage.removeAt(0)
override fun peek(): T? = storage.getOrNull(0)
}
class TreeNode<T>(private val value: T) {
private val children: MutableList<TreeNode<T>> = mutableListOf()
fun add(child: TreeNode<T>) = children.add(child)
fun forEachDepthFirst(visit: Visitor<T>) {
visit(this)
children.forEach {
it.forEachDepthFirst(visit)
}
}
fun forEachLevelOrder(visit: Visitor<T>) {
visit(this)
val queue = ArrayListQueue<TreeNode<T>>()
children.forEach {
queue.enqueue(it)
var node = queue.dequeue()
while (node != null) {
visit(node)
node.children.forEach { queue.enqueue(it) }
node = queue.dequeue()
}
}
}
fun search(predicate: (T) -> Boolean): TreeNode<T>? {
var result: TreeNode<T>? = null
forEachDepthFirst {
if (predicate(it.value)) {
result = it
}
}
return result
}
}
data class Point3d(val x: Int, val y: Int, val z: Int) {
fun neighbors() =
listOf(
Point3d(x, y + 1, z),
Point3d(x, y - 1, z),
Point3d(x + 1, y, z),
Point3d(x - 1, y, z),
Point3d(x, y, z + 1),
Point3d(x, y, z - 1),
)
}
data class Point2d(val x: Int, val y: Int, var value: Char = ' ') {
infix fun sameRow(that: Point2d): Boolean =
y == that.y
infix fun sameColumn(that: Point2d): Boolean =
x == that.x
fun distanceTo(other: Point2d) = abs(x - other.x) + abs(y - other.y)
fun manRanges(dist: Int, row: Int): IntRange? {
val width = dist - abs(y - row)
// if negative this sensor has registered a beacon closer than this row is far :-)
return if (width > 0) x - width..x + width else null
}
fun neighbors() =
listOf(
Point2d(x, y + 1),
Point2d(x, y - 1),
Point2d(x + 1, y),
Point2d(x - 1, y)
)
private fun corners() = listOf(
Point2d(x - 1, y - 1),
Point2d(x - 1, y + 1),
Point2d(x + 1, y - 1),
Point2d(x + 1, y + 1)
)
infix fun lineTo(that: Point2d): List<Point2d> {
val xDelta = (that.x - x).sign
val yDelta = (that.y - y).sign
val steps = maxOf((x - that.x).absoluteValue, (y - that.y).absoluteValue)
return (1..steps).scan(this) { last, _ -> Point2d(last.x + xDelta, last.y + yDelta) }
}
val down by lazy { Point2d(x, y + 1) }
val downLeft by lazy { Point2d(x - 1, y + 1) }
val downRight by lazy { Point2d(x + 1, y + 1) }
private fun allNeighbors() = neighbors() + corners()
fun move(dir: String): Point2d {
return when (dir) {
"U" -> Point2d(x, y + 1)
"D" -> Point2d(x, y - 1)
"L" -> Point2d(x - 1, y)
"R" -> Point2d(x + 1, y)
else -> {
this
}
}
}
fun follow(other: Point2d): Point2d {
val right = other.x > x
val up = other.y > y
return when {
other in allNeighbors() + this -> this
sameRow(other) -> if (right) move("R") else move("L")
sameColumn(other) -> if (up) move("U") else move("D")
else -> {
val step1 = if (right) move("R") else move("L")
if (up) step1.move("U") else step1.move("D")
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 04a9531285e22cc81e6478dc89708bcf6407910b | 4,660 | aoc202xkotlin | The Unlicense |
sdk/src/main/java/com/qonversion/android/sdk/internal/QAttributionManager.kt | qonversion | 224,974,105 | false | {"Kotlin": 604976, "Java": 9442, "Ruby": 2698} | package com.qonversion.android.sdk.internal
import com.qonversion.android.sdk.dto.QAttributionProvider
import com.qonversion.android.sdk.internal.provider.AppStateProvider
import com.qonversion.android.sdk.internal.repository.QRepository
internal class QAttributionManager internal constructor(
private val repository: QRepository,
private val appStateProvider: AppStateProvider
) {
private var pendingAttributionProvider: QAttributionProvider? = null
private var pendingData: Map<String, Any>? = null
fun onAppForeground() {
val source = pendingAttributionProvider
val info = pendingData
if (source != null && !info.isNullOrEmpty()) {
repository.attribution(info, source.id)
pendingData = null
pendingAttributionProvider = null
}
}
fun attribution(data: Map<String, Any>, provider: QAttributionProvider) {
if (appStateProvider.appState.isBackground()) {
pendingAttributionProvider = provider
pendingData = data
return
}
repository.attribution(data, provider.id)
}
}
| 2 | Kotlin | 21 | 122 | 619465b65dbf2612486ec3adad9b0a8750d76c7b | 1,133 | android-sdk | MIT License |
ViewBindingAptDemo/processor/src/main/java/com/sukaidev/processor/binding/BindingFragment.kt | sukaidev | 382,867,457 | false | {"C": 491569, "Kotlin": 94124, "CMake": 7048, "Java": 6545, "C++": 966} | package com.sukaidev.processor.binding
import com.sukaidev.processor.binding.entity.BindingView
import java.util.*
import javax.lang.model.element.Modifier
import javax.lang.model.element.TypeElement
/**
* Created by sukaidev on 2021/07/02.
* @author sukaidev
*/
class BindingFragment(val typeElement: TypeElement) {
val bindingViews = TreeSet<BindingView>()
val simpleName: String = typeElement.simpleName.toString()
val packageName: String = typeElement.enclosingElement.asType().toString()
val isAbstract = typeElement.modifiers.contains(Modifier.ABSTRACT)
val isKotlin = typeElement.getAnnotation(Metadata::class.java) != null
val builder = BindingFragmentBuilder(this)
override fun toString(): String {
return "$packageName.$simpleName[${bindingViews.joinToString()}]"
}
} | 0 | C | 0 | 3 | 505872e4fa137454b42dc68c2bb765800633fb50 | 829 | BestPractices | MIT License |
app/src/main/java/com/stevesoltys/seedvault/ui/files/FileSelectionFragment.kt | LineageOS | 293,909,131 | false | {"Kotlin": 1368164, "Java": 12059, "Shell": 6142} | /*
* SPDX-FileCopyrightText: 2020 The Calyx Institute
* SPDX-License-Identifier: Apache-2.0
*/
package com.stevesoltys.seedvault.ui.files
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.stevesoltys.seedvault.R
import com.stevesoltys.seedvault.settings.SettingsViewModel
import org.calyxos.backup.storage.ui.backup.BackupContentFragment
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class FileSelectionFragment : BackupContentFragment() {
override val viewModel by viewModel<FileSelectionViewModel>()
private val settingsViewModel by sharedViewModel<SettingsViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
requireActivity().setTitle(R.string.settings_backup_files_title)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onDestroy() {
super.onDestroy()
// reload files summary when we navigate away (it might have changed)
settingsViewModel.loadFilesSummary()
}
}
| 1 | Kotlin | 16 | 28 | c906fd7834ed027fbc6c4dacea1b15525a882013 | 1,228 | android_packages_apps_Seedvault | Apache License 2.0 |
test-app/src/main/java/name/wildswift/testapp/views/CryptoCardViewDelegate.kt | wild-swift | 222,104,173 | false | {"Gradle": 9, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Groovy": 3, "Proguard": 1, "XML": 32, "Kotlin": 62, "Java": 52} | package name.wildswift.testapp.views
import android.animation.LayoutTransition
import android.graphics.Outline
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RoundRectShape
import android.util.TypedValue
import android.view.View
import android.view.ViewOutlineProvider
import android.widget.FrameLayout
import kotlinx.android.synthetic.main.view_crypto_card.view.*
import name.wildswift.android.kannotations.*
import name.wildswift.android.kannotations.interfaces.ViewDelegate
import name.wildswift.testapp.IdRNames
import java.util.concurrent.TimeUnit
import kotlin.time.TimedValue
@ViewWithDelegate(
parent = FrameLayout::class
)
@Fields(
ViewField(name = "cryptoCurAmount", type = Float::class),
ViewField(name = "countryCurAmount", type = Float::class),
ViewField(name = "ticker", childName = IdRNames.vccTicker, byProperty = ViewProperty.text),
ViewField(name = "cryptoName", type = String::class),
ViewField(name = "iconRef", byProperty = ViewProperty.imageResource, childName = IdRNames.vccCoinImage),
ViewField(name = "coinColor", type = Int::class),
ViewField(name = "hideButtons", type = Boolean::class),
ViewField(name = "buyButtonName", byProperty = ViewProperty.text, childName = IdRNames.vccBuyButton, rwType = ReadWriteMode.Private),
ViewField(name = "sellButtonName", byProperty = ViewProperty.text, childName = IdRNames.vccSellButton, rwType = ReadWriteMode.Private),
ViewField(name = "topRowColor", byProperty = ViewProperty.backgroundColor, childName = IdRNames.vccTopBorder, rwType = ReadWriteMode.Private),
ViewField(name = "cryptoCurText", byProperty = ViewProperty.text, childName = IdRNames.vccCryptoCurAmount, rwType = ReadWriteMode.Private),
ViewField(name = "countryCurText", byProperty = ViewProperty.text, childName = IdRNames.vccCountryCurAmount, rwType = ReadWriteMode.Private),
ViewField(name = "sellTextColor", byProperty = ViewProperty.textColor, childName = IdRNames.vccSellButton, rwType = ReadWriteMode.Private),
ViewField(name = "buyButtonBackground", byProperty = ViewProperty.backgroundDrawable, childName = IdRNames.vccBuyButton, rwType = ReadWriteMode.Private),
ViewField(name = "sellButtonBackground", byProperty = ViewProperty.backgroundDrawable, childName = IdRNames.vccSellButton, rwType = ReadWriteMode.Private),
ViewField(name = "buttonsVisible", byProperty = ViewProperty.visibility, childName = IdRNames.vccButtonContainer, rwType = ReadWriteMode.Private)
)
@Events(
ViewEvent(name = "buyClick", childName = IdRNames.vccBuyButton, listener = ViewListener.onClick),
ViewEvent(name = "sellClick", childName = IdRNames.vccSellButton, listener = ViewListener.onClick)
)
class CryptoCardViewDelegate(view: CryptoCardView) : ViewDelegate<CryptoCardView, CryptoCardViewIntState>(view) {
override fun setupView() {
super.setupView()
view.outlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
outline.setRoundRect(0, 0, view.width, view.height, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 7f, view.resources.displayMetrics))
}
}
view.clipToOutline = true
view.setBackgroundColor(0xFFFFFFFF.toInt())
view.elevation = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5f, context.resources.displayMetrics)
view.layoutTransition = LayoutTransition()
}
override fun validateStateForNewInput(data: CryptoCardViewIntState): CryptoCardViewIntState {
return data.copy(
buyButtonName = "Buy ${data.cryptoName}",
sellButtonName = "Sell ${data.cryptoName}",
topRowColor = data.coinColor,
cryptoCurText = String.format("%.7f", data.cryptoCurAmount),
countryCurText = String.format("£%.2f", data.countryCurAmount),
sellTextColor = data.coinColor,
buyButtonBackground = GradientDrawable().apply {
shape = GradientDrawable.RECTANGLE
colors = intArrayOf(data.coinColor, data.coinColor)
cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, view.resources.displayMetrics)
},
sellButtonBackground = GradientDrawable().apply {
shape = GradientDrawable.RECTANGLE
cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, view.resources.displayMetrics)
setStroke(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1f, view.resources.displayMetrics).toInt(), data.coinColor)
},
buttonsVisible = if (data.hideButtons) View.GONE else View.VISIBLE
)
}
} | 0 | Kotlin | 0 | 1 | 75bd30c8068d24df91f68269bdc9b5ee8ce06d8e | 4,994 | tiger-navigation | Apache License 2.0 |
src/main/kotlin/xyz/helloyunho/dtja_mcserver_plugin/DtjaMCServerPlugin.kt | Helloyunho | 723,026,285 | false | {"Kotlin": 19000} | package xyz.helloyunho.dtja_mcserver_plugin
import org.bukkit.Bukkit
import org.bukkit.plugin.java.JavaPlugin
import xyz.helloyunho.dtja_mcserver_plugin.back.BackCommand
import xyz.helloyunho.dtja_mcserver_plugin.back.BackListener
import xyz.helloyunho.dtja_mcserver_plugin.home.*
import xyz.helloyunho.dtja_mcserver_plugin.motd.MOTDListener
import xyz.helloyunho.dtja_mcserver_plugin.nick.NickCommand
import xyz.helloyunho.dtja_mcserver_plugin.nick.NickListener
import xyz.helloyunho.dtja_mcserver_plugin.utils.UserConfig
import java.util.*
class DtjaMCServerPlugin : JavaPlugin() {
val userConfigPath = dataFolder.resolve("users/")
override fun onEnable() {
// ensure config file exists
saveDefaultConfig()
// ensure user config directory exists
if (!userConfigPath.exists()) {
userConfigPath.mkdirs()
}
// for-each user config file
userConfigPath.listFiles()?.forEach {
val player = Bukkit.getPlayer(UUID.fromString(it.nameWithoutExtension))
if (player != null) {
// load user config
val userConfig = UserConfig(this, player)
if (userConfig.nick != null) {
player.setDisplayName(userConfig.nick)
}
}
}
// register commands
getCommand("sethome")?.setExecutor(SethomeCommand(this))
getCommand("home")?.setExecutor(HomeCommand(this))
getCommand("nick")?.setExecutor(NickCommand(this))
getCommand("back")?.setExecutor(BackCommand(this))
getCommand("homelist")?.setExecutor(HomeListCommand(this))
getCommand("delhome")?.setExecutor(DelhomeCommand(this))
// register tab completers
getCommand("sethome")?.tabCompleter = SethomeCompleter()
getCommand("home")?.tabCompleter = HomeCompleter(this)
getCommand("delhome")?.tabCompleter = DelhomeCompleter(this)
// register event listeners
server.pluginManager.registerEvents(BackListener(this), this)
server.pluginManager.registerEvents(NickListener(this), this)
server.pluginManager.registerEvents(SethomeListener(this), this)
server.pluginManager.registerEvents(MOTDListener(this), this)
logger.info("${description.name} version ${description.version} enabled!")
}
override fun onDisable() {
logger.info("${description.name} disabled.")
}
}
| 0 | Kotlin | 0 | 0 | 3609a3522ba46de3d25dc7d5acfb86bfe5eacf4d | 2,448 | dtja-mcserver-plugin | Apache License 2.0 |
wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt | zhxnlai | 274,538,232 | false | null | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.google.protobuf.ListValue
import com.google.protobuf.NullValue
import com.google.protobuf.util.JsonFormat
import com.squareup.moshi.Moshi
import com.squareup.wire.json.assertJsonEquals
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.fail
import org.junit.Ignore
import org.junit.Test
import squareup.proto3.kotlin.alltypes.AllStructsOuterClass
import squareup.proto3.java.alltypes.AllStructs as AllStructsJ
import squareup.proto3.kotlin.alltypes.AllStructs as AllStructsK
class StructTest {
@Test fun nullValue() {
val googleMessage = null.toValue()
val wireMessage = null
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun doubleValue() {
val googleMessage = 0.25.toValue()
val wireMessage = 0.25
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun specialDoubleValues() {
val googleMessage = listOf(
Double.NEGATIVE_INFINITY,
-0.0,
0.0,
Double.POSITIVE_INFINITY,
Double.NaN
).toListValue()
val wireMessage = listOf(
Double.NEGATIVE_INFINITY,
-0.0,
0.0,
Double.POSITIVE_INFINITY,
Double.NaN
)
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_LIST.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_LIST.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun booleanTrue() {
val googleMessage = true.toValue()
val wireMessage = true
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun booleanFalse() {
val googleMessage = false.toValue()
val wireMessage = false
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun stringValue() {
val googleMessage = "Cash App!".toValue()
val wireMessage = "Cash App!"
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun emptyStringValue() {
val googleMessage = "".toValue()
val wireMessage = ""
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun utf8StringValue() {
val googleMessage = "На берегу пустынных волн".toValue()
val wireMessage = "На берегу пустынных волн"
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun map() {
val googleMessage = mapOf("a" to "android", "c" to "cash").toStruct()
val wireMessage = mapOf("a" to "android", "c" to "cash")
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_MAP.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_MAP.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun mapOfAllTypes() {
val googleMessage = mapOf(
"a" to null,
"b" to 0.5,
"c" to true,
"d" to "cash",
"e" to listOf("g", "h"),
"f" to mapOf("i" to "j", "k" to "l")
).toStruct()
val wireMessage = mapOf(
"a" to null,
"b" to 0.5,
"c" to true,
"d" to "cash",
"e" to listOf("g", "h"),
"f" to mapOf("i" to "j", "k" to "l")
)
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_MAP.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_MAP.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun mapWithoutEntries() {
val googleMessage = emptyStruct()
val wireMessage = mapOf<String, Any?>()
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_MAP.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_MAP.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun unsupportedKeyType() {
@Suppress("UNCHECKED_CAST") // Totally unsafe.
val wireMessage = mapOf(5 to "android") as Map<String, Any?>
try {
ProtoAdapter.STRUCT_MAP.encode(wireMessage)
fail()
} catch (_: ClassCastException) {
}
try {
ProtoAdapter.STRUCT_MAP.encodedSize(wireMessage)
fail()
} catch (_: ClassCastException) {
}
try {
ProtoAdapter.STRUCT_MAP.redact(wireMessage)
fail()
} catch (_: IllegalArgumentException) {
}
}
@Test fun unsupportedValueType() {
val wireMessage = mapOf("a" to StringBuilder("android"))
try {
ProtoAdapter.STRUCT_MAP.encode(wireMessage)
fail()
} catch (_: IllegalArgumentException) {
}
try {
ProtoAdapter.STRUCT_MAP.encodedSize(wireMessage)
fail()
} catch (_: IllegalArgumentException) {
}
try {
ProtoAdapter.STRUCT_MAP.redact(wireMessage)
fail()
} catch (_: IllegalArgumentException) {
}
}
@Test fun list() {
val googleMessage = listOf("android", "cash").toListValue()
val wireMessage = listOf("android", "cash")
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_LIST.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_LIST.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun listOfAllTypes() {
val googleMessage = listOf(
null,
0.5,
true,
"cash",
listOf("a", "b"),
mapOf("c" to "d", "e" to "f")
).toListValue()
val wireMessage = listOf(
null,
0.5,
true,
"cash",
listOf("a", "b"),
mapOf("c" to "d", "e" to "f")
)
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_LIST.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_LIST.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun unsupportedListElement() {
val wireMessage = listOf(StringBuilder())
try {
ProtoAdapter.STRUCT_LIST.encode(wireMessage)
fail()
} catch (_: IllegalArgumentException) {
}
try {
ProtoAdapter.STRUCT_LIST.encodedSize(wireMessage)
fail()
} catch (_: IllegalArgumentException) {
}
try {
ProtoAdapter.STRUCT_LIST.redact(wireMessage)
fail()
} catch (_: IllegalArgumentException) {
}
}
@Test fun listValueWithoutElements() {
val googleMessage = ListValue.newBuilder().build()
val wireMessage = listOf<Any?>()
val googleMessageBytes = googleMessage.toByteArray()
assertThat(ProtoAdapter.STRUCT_LIST.encode(wireMessage)).isEqualTo(googleMessageBytes)
assertThat(ProtoAdapter.STRUCT_LIST.decode(googleMessageBytes)).isEqualTo(wireMessage)
}
@Test fun nullMapAndListAsFields() {
val protocAllStruct = AllStructsOuterClass.AllStructs.newBuilder().build()
val wireAllStructJava = AllStructsJ.Builder().build()
val wireAllStructKotlin = AllStructsK()
val protocAllStructBytes = protocAllStruct.toByteArray()
assertThat(AllStructsJ.ADAPTER.encode(wireAllStructJava)).isEqualTo(protocAllStructBytes)
assertThat(AllStructsJ.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructJava)
assertThat(AllStructsK.ADAPTER.encode(wireAllStructKotlin)).isEqualTo(protocAllStructBytes)
assertThat(AllStructsK.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructKotlin)
}
@Test fun emptyMapAndListAsFields() {
val protocAllStruct = AllStructsOuterClass.AllStructs.newBuilder()
.setStruct(emptyStruct())
.setList(emptyListValue())
.build()
val wireAllStructJava = AllStructsJ.Builder()
.struct(emptyMap<String, Any?>())
.list(emptyList<Any?>())
.build()
val wireAllStructKotlin = AllStructsK(
struct = emptyMap<String, Any?>(),
list = emptyList<Any?>())
val protocAllStructBytes = protocAllStruct.toByteArray()
assertThat(AllStructsJ.ADAPTER.encode(wireAllStructJava)).isEqualTo(protocAllStructBytes)
assertThat(AllStructsJ.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructJava)
assertThat(AllStructsK.ADAPTER.encode(wireAllStructKotlin)).isEqualTo(protocAllStructBytes)
assertThat(AllStructsK.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructKotlin)
}
// Note: We are not testing nulls because while protoc emits `NULL_VALUE`s, Wire doesn't.
@Test fun structRoundTripWithData() {
val protocAllStruct = AllStructsOuterClass.AllStructs.newBuilder()
.setStruct(mapOf("a" to 1.0).toStruct())
.setList(listOf("a", 3.0).toListValue())
.setNullValue(NullValue.NULL_VALUE)
.setValueA("a".toValue())
.setValueB(33.0.toValue())
.setValueC(true.toValue())
.setValueE(mapOf("a" to 1.0).toValue())
.setValueF(listOf("a", 3.0).toValue())
.build()
val wireAllStructJava = AllStructsJ.Builder()
.struct(mapOf("a" to 1.0))
.list(listOf("a", 3.0))
.null_value(null)
.value_a("a")
.value_b(33.0)
.value_c(true)
.value_e(mapOf("a" to 1.0))
.value_f(listOf("a", 3.0))
.build()
val wireAllStructKotlin = AllStructsK(
struct = mapOf("a" to 1.0),
list = listOf("a", 3.0),
null_value = null,
value_a = "a",
value_b = 33.0,
value_c = true,
value_e = mapOf("a" to 1.0),
value_f = listOf("a", 3.0)
)
val protocAllStructBytes = protocAllStruct.toByteArray()
assertThat(AllStructsJ.ADAPTER.encode(wireAllStructJava)).isEqualTo(protocAllStructBytes)
assertThat(AllStructsJ.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructJava)
assertThat(AllStructsK.ADAPTER.encode(wireAllStructKotlin)).isEqualTo(protocAllStructBytes)
assertThat(AllStructsK.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructKotlin)
}
@Test fun structJsonRoundTrip() {
val json = """{
| "struct": {"a": 1.0},
| "list": ["a", 3.0],
| "valueA": "a",
| "valueB": 33.0,
| "valueC": true,
| "valueE": {"a": 1.0},
| "valueF": ["a", 3.0],
| "repStruct": [],
| "repList": [],
| "repValueA": [],
| "repNullValue": [],
| "mapInt32Struct": {},
| "mapInt32List": {},
| "mapInt32ValueA": {},
| "mapInt32NullValue": {},
| "oneofStruct": null,
| "oneofList": null
|}""".trimMargin()
val wireAllStructJava = AllStructsJ.Builder()
.struct(mapOf("a" to 1.0))
.list(listOf("a", 3.0))
.null_value(null)
.value_a("a")
.value_b(33.0)
.value_c(true)
.value_d(null)
.value_e(mapOf("a" to 1.0))
.value_f(listOf("a", 3.0))
.build()
val wireAllStructKotlin = AllStructsK(
struct = mapOf("a" to 1.0),
list = listOf("a", 3.0),
null_value = null,
value_a = "a",
value_b = 33.0,
value_c = true,
value_d = null,
value_e = mapOf("a" to 1.0),
value_f = listOf("a", 3.0)
)
val moshi = Moshi.Builder().add(WireJsonAdapterFactory()).build()
val allStructAdapterJava = moshi.adapter(AllStructsJ::class.java)
assertJsonEquals(allStructAdapterJava.toJson(wireAllStructJava), json)
assertThat(allStructAdapterJava.fromJson(json)).isEqualTo(wireAllStructJava)
val allStructAdapterKotlin = moshi.adapter(AllStructsK::class.java)
assertJsonEquals(allStructAdapterKotlin.toJson(wireAllStructKotlin), json)
assertThat(allStructAdapterKotlin.fromJson(json)).isEqualTo(wireAllStructKotlin)
}
@Test fun structJsonRoundTripWithEmptyOrNestedMapAndList() {
val protocJson = """{
| "struct": {"a": null},
| "list": [],
| "valueA": {"a": ["b", 2.0, {"c": false}]},
| "valueB": [{"d": null, "e": "trois"}],
| "valueC": [],
| "valueD": {},
| "valueE": null,
| "valueF": null
|}""".trimMargin()
// Protoc doesn't print those unless explicitly set.
val moshiJson = """{
| "repStruct": [],
| "repList": [],
| "repValueA": [],
| "repNullValue": [],
| "mapInt32Struct": {},
| "mapInt32List": {},
| "mapInt32ValueA": {},
| "mapInt32NullValue": {},
| "oneofStruct": null,
| "oneofList": null,
| "struct": {"a": null},
| "list": [],
| "valueA": {"a": ["b", 2.0, {"c": false}]},
| "valueB": [{"d": null, "e": "trois"}],
| "valueC": [],
| "valueD": {}
|}""".trimMargin()
val protocAllStruct = AllStructsOuterClass.AllStructs.newBuilder()
.setStruct(mapOf("a" to null).toStruct())
.setList(emptyListValue())
.setValueA(mapOf("a" to listOf("b", 2.0, mapOf("c" to false))).toValue())
.setValueB(listOf(mapOf("d" to null, "e" to "trois")).toValue())
.setValueC(emptyList<Any>().toValue())
.setValueD(emptyMap<String, Any>().toValue())
.setValueE(null.toValue())
.setValueF(null.toValue())
.build()
val jsonPrinter = JsonFormat.printer()
assertJsonEquals(jsonPrinter.print(protocAllStruct), protocJson)
val jsonParser = JsonFormat.parser()
val protocParsed = AllStructsOuterClass.AllStructs.newBuilder()
.apply { jsonParser.merge(protocJson, this) }
.build()
assertThat(protocParsed).isEqualTo(protocAllStruct)
val wireAllStructJava = AllStructsJ.Builder()
.struct(mapOf("a" to null))
.list(emptyList<Any>())
.value_a(mapOf("a" to listOf("b", 2.0, mapOf("c" to false))))
.value_b(listOf(mapOf("d" to null, "e" to "trois")))
.value_c(emptyList<Any>())
.value_d(emptyMap<String, Any>())
.build()
val wireAllStructKotlin = AllStructsK(
struct = mapOf("a" to null),
list = emptyList<Any>(),
value_a = mapOf("a" to listOf("b", 2.0, mapOf("c" to false))),
value_b = listOf(mapOf("d" to null, "e" to "trois")),
value_c = emptyList<Any>(),
value_d = emptyMap<String, Any>()
)
val moshi = Moshi.Builder().add(WireJsonAdapterFactory()).build()
val allStructAdapterJava = moshi.adapter(AllStructsJ::class.java)
assertJsonEquals(allStructAdapterJava.toJson(wireAllStructJava), moshiJson)
assertThat(allStructAdapterJava.fromJson(protocJson)).isEqualTo(wireAllStructJava)
assertThat(allStructAdapterJava.fromJson(moshiJson)).isEqualTo(wireAllStructJava)
val allStructAdapterKotlin = moshi.adapter(AllStructsK::class.java)
assertJsonEquals(allStructAdapterKotlin.toJson(wireAllStructKotlin), moshiJson)
assertThat(allStructAdapterKotlin.fromJson(protocJson)).isEqualTo(wireAllStructKotlin)
assertThat(allStructAdapterKotlin.fromJson(moshiJson)).isEqualTo(wireAllStructKotlin)
}
}
| 0 | null | 0 | 1 | cc4f1379dd5d24497e57e033801efa52d017c461 | 16,601 | wire | Apache License 2.0 |
webui/src/main/kotlin/com/simiacryptus/skyenet/apps/plan/RunShellCommandTask.kt | SimiaCryptus | 619,329,127 | false | {"Kotlin": 781804, "JavaScript": 60230, "SCSS": 31588, "HTML": 5642, "Scala": 5538, "Java": 2053} | package com.simiacryptus.skyenet.apps.plan
import com.simiacryptus.jopenai.API
import com.simiacryptus.jopenai.ApiModel
import com.simiacryptus.jopenai.util.JsonUtil
import com.simiacryptus.skyenet.TabbedDisplay
import com.simiacryptus.skyenet.apps.coding.CodingAgent
import com.simiacryptus.skyenet.apps.plan.PlanningTask.TaskBreakdownInterface
import com.simiacryptus.skyenet.core.actors.CodingActor
import com.simiacryptus.skyenet.interpreter.ProcessInterpreter
import com.simiacryptus.skyenet.webui.session.SessionTask
import org.slf4j.LoggerFactory
import java.io.File
import java.util.concurrent.Semaphore
import kotlin.reflect.KClass
class RunShellCommandTask(
planSettings: PlanSettings,
planTask: PlanningTask.PlanTask
) : AbstractTask(planSettings, planTask) {
val shellCommandActor by lazy {
CodingActor(
name = "RunShellCommand",
interpreterClass = ProcessInterpreter::class,
details = """
Execute the following shell command(s) and provide the output. Ensure to handle any errors or exceptions gracefully.
|
Note: This task is for running simple and safe commands. Avoid executing commands that can cause harm to the system or compromise security.
""".trimMargin(),
symbols = mapOf<String, Any>(
"env" to (planSettings.env ?: emptyMap()),
"workingDir" to (planTask.workingDir?.let { File(it).absolutePath } ?: File(planSettings.workingDir).absolutePath),
"language" to (planSettings.language ?: "bash"),
"command" to planSettings.command,
),
model = planSettings.model,
temperature = planSettings.temperature,
)
}
override fun promptSegment(): String {
return """
RunShellCommand - Execute shell commands and provide the output
** Specify the command to be executed, or describe the task to be performed
** List input files/tasks to be examined when writing the command
** Optionally specify a working directory for the command execution
""".trimMargin()
}
override fun run(
agent: PlanCoordinator,
taskId: String,
userMessage: String,
plan: TaskBreakdownInterface,
planProcessingState: PlanProcessingState,
task: SessionTask,
taskTabs: TabbedDisplay,
api: API
) {
if (!agent.planSettings.shellCommandTaskEnabled) throw RuntimeException("Shell command task is disabled")
val semaphore = Semaphore(0)
object : CodingAgent<ProcessInterpreter>(
api = api,
dataStorage = agent.dataStorage,
session = agent.session,
user = agent.user,
ui = agent.ui,
interpreter = shellCommandActor.interpreterClass as KClass<ProcessInterpreter>,
symbols = shellCommandActor.symbols,
temperature = shellCommandActor.temperature,
details = shellCommandActor.details,
model = shellCommandActor.model,
mainTask = task,
) {
override fun displayFeedback(
task: SessionTask,
request: CodingActor.CodeRequest,
response: CodingActor.CodeResult
) {
val formText = StringBuilder()
var formHandle: StringBuilder? = null
formHandle = task.add(
"""
|<div style="display: flex;flex-direction: column;">
|${if (!super.canPlay) "" else super.playButton(task, request, response, formText) { formHandle!! }}
|${acceptButton(response)}
|</div>
|${super.reviseMsg(task, request, response, formText) { formHandle!! }}
""".trimMargin(), className = "reply-message"
)
formText.append(formHandle.toString())
formHandle.toString()
task.complete()
}
fun acceptButton(
response: CodingActor.CodeResult
): String {
return ui.hrefLink("Accept", "href-link play-button") {
planProcessingState.taskResult[taskId] = response.let {
"""
|## Shell Command Output
|
|$TRIPLE_TILDE
|${response.code}
|$TRIPLE_TILDE
|
|$TRIPLE_TILDE
|${response.renderedResponse}
|$TRIPLE_TILDE
""".trimMargin()
}
semaphore.release()
}
}
}.apply<CodingAgent<ProcessInterpreter>> {
start(
codeRequest(
listOf(
userMessage to ApiModel.Role.user,
JsonUtil.toJson(plan) to ApiModel.Role.assistant,
getPriorCode(planProcessingState) to ApiModel.Role.assistant,
getInputFileCode() to ApiModel.Role.assistant,
)
)
)
}
try {
semaphore.acquire()
} catch (e: Throwable) {
log.warn("Error", e)
}
log.debug("Completed shell command: $taskId")
}
companion object {
private val log = LoggerFactory.getLogger(RunShellCommandTask::class.java)
}
} | 1 | Kotlin | 0 | 1 | 68fc3756084f30fd5a5c64200abd55b1b4fe7c11 | 5,588 | SkyeNet | Apache License 2.0 |
plugin/src/main/kotlin/ru/astrainteractive/astrashop/di/RootModule.kt | Astra-Interactive | 562,599,158 | false | {"Kotlin": 72924} | package ru.astrainteractive.astrashop.di
import ru.astrainteractive.astralibs.async.AsyncComponent
import ru.astrainteractive.astralibs.async.BukkitDispatchers
import ru.astrainteractive.astralibs.economy.EconomyProvider
import ru.astrainteractive.astralibs.logging.Logger
import ru.astrainteractive.astrashop.AstraShop
import ru.astrainteractive.astrashop.domain.SpigotShopApi
import ru.astrainteractive.astrashop.util.PluginTranslation
import ru.astrainteractive.klibs.kdi.Lateinit
import ru.astrainteractive.klibs.kdi.Module
import ru.astrainteractive.klibs.kdi.Reloadable
import ru.astrainteractive.klibs.kdi.Single
interface RootModule : Module {
val plugin: Lateinit<AstraShop>
val translation: Reloadable<PluginTranslation>
val spigotShopApi: Single<SpigotShopApi>
val economyProvider: Single<EconomyProvider>
val logger: Single<Logger>
val dispatchers: Single<BukkitDispatchers>
val scope: Single<AsyncComponent>
}
| 3 | Kotlin | 1 | 0 | ddad585065465555a50822aaeba0264be6e1dbc5 | 953 | AstraShop | MIT License |
lib-user/src/main/java/com/flyjingfish/user/Utils.kt | FlyJingFish | 738,834,494 | false | {"Kotlin": 135830, "Java": 2944} | package com.flyjingfish.user
//inline fun UserActivity.getXParams1(){
//
//} | 0 | Kotlin | 0 | 8 | bf94c7bdc0825d0015b2559187c20a49bffc9ee3 | 78 | ModuleCommunication | Apache License 2.0 |
shared/src/commonMain/kotlin/repository/UserRepository.kt | S6AVI | 670,592,043 | false | {"Kotlin": 107952, "Swift": 708, "Shell": 228, "Ruby": 101} | package repository
import data.Salesman
import dev.gitlive.firebase.auth.AuthResult
import kotlinx.coroutines.flow.Flow
import util.SuitsResource
interface UserRepository {
fun createUser(email: String): Flow<SuitsResource<String>>
fun updateUserInfo(salesman: Salesman): Flow<SuitsResource<String>>
suspend fun getCurrentUserInfo(): Salesman
} | 0 | Kotlin | 0 | 0 | 8cd87a5005f234333ebd226a5a2d6ed86ce5a1dc | 359 | Suits | Apache License 2.0 |
code/number_theory/GCD.kt | hakiobo | 397,069,173 | false | {"Kotlin": 39568} | private fun gcd(p: Int, q: Int): Int {
return if (p < 0) gcd(-p, q)
else if (q < 0) gcd(p, -q)
else if (p == 0) q
else if (q == 0) p
else if (p and 1 == 0 && q and 1 == 0) gcd(p shr 1, q shr 1) shl 1
else if (p and 1 == 0) gcd(p shr 1, q)
else if (q and 1 == 0) gcd(p, q shr 1)
else if (p > q) gcd((p - q) shr 1, q)
else gcd(p, (q - p) shr 1)
}
private fun gcd(p: Long, q: Long): Long {
return if (p < 0) gcd(-p, q)
else if (q < 0) gcd(p, -q)
else if (p == 0L) q
else if (q == 0L) p
else if (p and 1L == 0L && q and 1L == 0L) gcd(p shr 1, q shr 1) shl 1
else if (p and 1L == 0L) gcd(p shr 1, q)
else if (q and 1L == 0L) gcd(p, q shr 1)
else if (p > q) gcd((p - q) shr 1, q)
else gcd(p, (q - p) shr 1)
}
| 0 | Kotlin | 1 | 2 | 96d5e2fb1a13650ef974cbca06554b4e0f3d926c | 778 | Kotlinaughts | MIT License |
module_app_manager/src/main/java/com/imooc/module_app_manager/base/AppManagerApp.kt | Fam044 | 470,788,723 | false | null | package com.imooc.module_app_manager.base
import com.imooc.lib_base.base.BaseApp
class AppManagerApp: BaseApp() | 0 | Kotlin | 0 | 0 | a44c351864432ffe28658c6dbe582f43df83fd66 | 113 | LifeAssistant | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/HorseshoeBroken.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.HorseshoeBroken: ImageVector
get() {
if (_horseshoeBroken != null) {
return _horseshoeBroken!!
}
_horseshoeBroken = Builder(name = "HorseshoeBroken", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.0f, 3.245f)
curveToRelative(0.0f, -0.637f, 0.599f, -1.123f, 1.216f, -0.964f)
curveToRelative(1.21f, 0.312f, 2.349f, 0.875f, 3.338f, 1.657f)
curveToRelative(0.567f, 0.448f, 0.433f, 1.349f, -0.218f, 1.662f)
horizontalLineToRelative(0.0f)
curveToRelative(-0.356f, 0.171f, -0.768f, 0.102f, -1.08f, -0.141f)
curveToRelative(-0.755f, -0.587f, -1.616f, -1.01f, -2.537f, -1.245f)
curveToRelative(-0.428f, -0.109f, -0.719f, -0.503f, -0.719f, -0.944f)
verticalLineToRelative(-0.025f)
close()
moveTo(12.0f, 0.0f)
curveTo(5.935f, 0.0f, 1.0f, 4.935f, 1.0f, 11.0f)
curveToRelative(0.0f, 4.162f, 1.591f, 8.74f, 2.492f, 11.0f)
horizontalLineToRelative(-0.492f)
curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f)
horizontalLineToRelative(0.0f)
curveToRelative(0.0f, 0.552f, 0.448f, 1.0f, 1.0f, 1.0f)
lineTo(7.469f, 24.0f)
curveToRelative(0.99f, 0.0f, 1.718f, -0.923f, 1.488f, -1.885f)
curveToRelative(-0.686f, -2.859f, -1.957f, -8.26f, -1.957f, -11.115f)
curveToRelative(0.0f, -2.761f, 2.239f, -5.0f, 5.0f, -5.0f)
curveToRelative(1.367f, 0.0f, 2.595f, 0.558f, 3.494f, 1.45f)
curveToRelative(0.303f, 0.301f, 0.724f, 0.447f, 1.15f, 0.412f)
curveToRelative(0.583f, -0.048f, 1.403f, -0.122f, 2.004f, -0.177f)
curveToRelative(0.495f, -0.045f, 0.933f, -0.332f, 1.173f, -0.767f)
lineToRelative(0.727f, -1.312f)
curveToRelative(0.298f, -0.537f, 0.245f, -1.208f, -0.148f, -1.681f)
curveToRelative(-0.053f, -0.064f, -0.107f, -0.127f, -0.162f, -0.19f)
curveTo(18.222f, 1.451f, 15.28f, 0.0f, 12.0f, 0.0f)
horizontalLineToRelative(0.0f)
close()
moveTo(6.85f, 3.632f)
curveToRelative(0.876f, -0.615f, 1.866f, -1.079f, 2.931f, -1.351f)
curveToRelative(0.618f, -0.158f, 1.219f, 0.327f, 1.219f, 0.965f)
verticalLineToRelative(0.024f)
curveToRelative(0.0f, 0.443f, -0.285f, 0.842f, -0.709f, 0.949f)
curveToRelative(-0.839f, 0.211f, -1.618f, 0.572f, -2.307f, 1.055f)
curveToRelative(-0.333f, 0.234f, -0.784f, 0.207f, -1.115f, -0.03f)
horizontalLineToRelative(0.0f)
curveToRelative(-0.55f, -0.393f, -0.572f, -1.225f, -0.02f, -1.613f)
close()
moveTo(3.069f, 9.886f)
curveToRelative(0.127f, -1.023f, 0.427f, -1.993f, 0.87f, -2.88f)
curveToRelative(0.269f, -0.541f, 0.967f, -0.706f, 1.458f, -0.355f)
lineToRelative(0.026f, 0.018f)
curveToRelative(0.387f, 0.276f, 0.527f, 0.792f, 0.314f, 1.217f)
curveToRelative(-0.35f, 0.7f, -0.588f, 1.466f, -0.685f, 2.274f)
curveToRelative(-0.059f, 0.484f, -0.48f, 0.84f, -0.967f, 0.84f)
horizontalLineToRelative(-0.025f)
curveToRelative(-0.599f, 0.0f, -1.062f, -0.524f, -0.989f, -1.114f)
close()
moveTo(18.218f, 12.087f)
curveToRelative(-0.583f, -0.291f, -1.266f, 0.093f, -1.339f, 0.74f)
curveToRelative(-0.334f, 2.937f, -1.318f, 6.926f, -1.84f, 9.257f)
curveToRelative(-0.22f, 0.983f, 0.53f, 1.915f, 1.537f, 1.915f)
horizontalLineToRelative(4.424f)
curveToRelative(0.552f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f)
horizontalLineToRelative(0.0f)
curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-0.492f)
curveToRelative(0.733f, -1.839f, 1.911f, -5.212f, 2.326f, -8.647f)
curveToRelative(0.084f, -0.698f, -0.616f, -1.232f, -1.27f, -0.973f)
lineToRelative(-1.522f, 0.602f)
curveToRelative(-0.015f, 0.007f, -0.982f, -0.473f, -1.825f, -0.893f)
close()
}
}
.build()
return _horseshoeBroken!!
}
private var _horseshoeBroken: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,487 | icons | MIT License |
cache-kmp/src/commonMain/kotlin/com/dropbox/kmp/external/cache3/CacheBuilder.kt | aclassen | 449,278,522 | true | {"Kotlin": 92199, "Swift": 20019, "Ruby": 1707} | /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* KMP conversion
* Copyright (C) 2022 André Claßen
*/
package com.dropbox.kmp.external.cache3
import kotlin.time.Duration
@DslMarker
annotation class CacheBuilderDsl
fun <K : Any, V : Any> cacheBuilder(lambda: CacheBuilder<K, V>.() -> Unit) =
CacheBuilder<K, V>().apply(lambda).build()
@CacheBuilderDsl
class CacheBuilder<K : Any, V : Any> {
internal var concurrencyLevel = 4
private set
internal val initialCapacity = 16
internal var maximumSize = UNSET_LONG
private set
internal var maximumWeight = UNSET_LONG
private set
internal var expireAfterAccess: Duration = Duration.INFINITE
private set
internal var expireAfterWrite: Duration = Duration.INFINITE
private set
internal var weigher: Weigher<K, V>? = null
private set
internal var ticker: Ticker? = null
private set
fun concurrencyLevel(lambda: () -> Int) {
concurrencyLevel = lambda()
}
fun maximumSize(size: Long) {
maximumSize = size
.apply {
if (this < 0) throw IllegalArgumentException("maximum size must not be negative")
}
}
fun expireAfterAccess(duration: Duration) {
expireAfterAccess = duration
.apply {
if (this.isNegative()) throw IllegalArgumentException("expireAfterAccess duration must be positive")
}
}
fun expireAfterWrite(duration: Duration) {
expireAfterWrite = duration.apply {
if (this.isNegative()) throw IllegalArgumentException("expireAfterWrite duration must be positive")
}
}
fun ticker(ticker: Ticker) {
this.ticker = ticker
}
fun weigher(maximumWeight: Long, weigher: Weigher<K, V>) {
this.maximumWeight = maximumWeight.apply {
if (this < 0) throw IllegalArgumentException("maximum weight must not be negative")
}
this.weigher = weigher
}
fun build(): Cache<K, V> {
if (maximumSize != -1L && weigher != null) {
throw IllegalStateException("maximum size can not be combined with weigher")
}
return LocalCache.LocalManualCache(this)
}
companion object {
private const val UNSET_LONG = -1L
}
}
| 0 | Kotlin | 0 | 4 | 8659ba0329a22701335a4bac9821007adb812f6d | 2,868 | Store | Apache License 2.0 |
cache-kmp/src/commonMain/kotlin/com/dropbox/kmp/external/cache3/CacheBuilder.kt | aclassen | 449,278,522 | true | {"Kotlin": 92199, "Swift": 20019, "Ruby": 1707} | /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* KMP conversion
* Copyright (C) 2022 André Claßen
*/
package com.dropbox.kmp.external.cache3
import kotlin.time.Duration
@DslMarker
annotation class CacheBuilderDsl
fun <K : Any, V : Any> cacheBuilder(lambda: CacheBuilder<K, V>.() -> Unit) =
CacheBuilder<K, V>().apply(lambda).build()
@CacheBuilderDsl
class CacheBuilder<K : Any, V : Any> {
internal var concurrencyLevel = 4
private set
internal val initialCapacity = 16
internal var maximumSize = UNSET_LONG
private set
internal var maximumWeight = UNSET_LONG
private set
internal var expireAfterAccess: Duration = Duration.INFINITE
private set
internal var expireAfterWrite: Duration = Duration.INFINITE
private set
internal var weigher: Weigher<K, V>? = null
private set
internal var ticker: Ticker? = null
private set
fun concurrencyLevel(lambda: () -> Int) {
concurrencyLevel = lambda()
}
fun maximumSize(size: Long) {
maximumSize = size
.apply {
if (this < 0) throw IllegalArgumentException("maximum size must not be negative")
}
}
fun expireAfterAccess(duration: Duration) {
expireAfterAccess = duration
.apply {
if (this.isNegative()) throw IllegalArgumentException("expireAfterAccess duration must be positive")
}
}
fun expireAfterWrite(duration: Duration) {
expireAfterWrite = duration.apply {
if (this.isNegative()) throw IllegalArgumentException("expireAfterWrite duration must be positive")
}
}
fun ticker(ticker: Ticker) {
this.ticker = ticker
}
fun weigher(maximumWeight: Long, weigher: Weigher<K, V>) {
this.maximumWeight = maximumWeight.apply {
if (this < 0) throw IllegalArgumentException("maximum weight must not be negative")
}
this.weigher = weigher
}
fun build(): Cache<K, V> {
if (maximumSize != -1L && weigher != null) {
throw IllegalStateException("maximum size can not be combined with weigher")
}
return LocalCache.LocalManualCache(this)
}
companion object {
private const val UNSET_LONG = -1L
}
}
| 0 | Kotlin | 0 | 4 | 8659ba0329a22701335a4bac9821007adb812f6d | 2,868 | Store | Apache License 2.0 |
proxy/src/main/kotlin/org/authlab/http/proxy/Transaction.kt | AuthLab | 116,606,960 | false | null | /*
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.authlab.http.proxy
import org.authlab.http.Request
import org.authlab.http.Response
import java.time.Instant
data class Transaction(val request: Request, val response: Response,
val startInstant: Instant, val stopInstant: Instant,
val scheme: String) {
fun toHar(): Map<String, *> {
return mapOf(
"request" to request.toHar(scheme),
"response" to response.toHar(),
"startedDateTime" to startInstant.toString())
}
}
| 1 | Kotlin | 1 | 1 | b35f95e4fd220e811db63736a29c82ca3ddfe499 | 1,669 | http | MIT License |
service/src/main/kotlin/com/r3/corda/finance/cash/issuer/service/flows/RedeemCashHandler.kt | vitalrev | 161,639,757 | true | {"Kotlin": 144825} | package com.r3.corda.finance.cash.issuer.service.flows
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.finance.cash.issuer.common.contracts.NodeTransactionContract
import com.r3.corda.finance.cash.issuer.common.flows.AbstractRedeemCash
import com.r3.corda.finance.cash.issuer.common.states.NodeTransactionState
import com.r3.corda.finance.cash.issuer.common.types.NodeTransactionType
import com.r3.corda.finance.cash.issuer.common.utilities.GenerationScheme
import com.r3.corda.finance.cash.issuer.common.utilities.generateRandomString
import net.corda.core.contracts.Amount
import net.corda.core.contracts.AmountTransfer
import net.corda.core.contracts.InsufficientBalanceException
import net.corda.core.contracts.Issued
import net.corda.core.flows.*
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.unwrap
import net.corda.finance.contracts.asset.Cash
import net.corda.finance.flows.CashException
import net.corda.finance.utils.sumCash
import java.time.Instant
import java.util.*
@InitiatedBy(AbstractRedeemCash::class)
class RedeemCashHandler(val otherSession: FlowSession) : FlowLogic<SignedTransaction>() {
@Suspendable
override fun call(): SignedTransaction {
logger.info("Starting redeem handler flow.")
val cashStateAndRefsToRedeem = subFlow(ReceiveStateAndRefFlow<Cash.State>(otherSession))
val redemptionAmount = otherSession.receive<Amount<Issued<Currency>>>().unwrap { it }
logger.info("Received cash states to redeem.")
logger.info("redemptionAmount: $redemptionAmount")
// Add create a node transaction state by adding the linearIds of all teh bank account states
val amount = cashStateAndRefsToRedeem.map { it.state.data }.sumCash()
val notary = serviceHub.networkMapCache.notaryIdentities.first()
val transactionBuilder = TransactionBuilder(notary = notary)
val signers = try {
Cash().generateExit(
tx = transactionBuilder,
amountIssued = redemptionAmount,
assetStates = cashStateAndRefsToRedeem,
payChangeTo = otherSession.counterparty
)
} catch (e: InsufficientBalanceException) {
throw CashException("Exiting more cash than exists", e)
}
val nodeTransactionState = NodeTransactionState(
amountTransfer = AmountTransfer(
quantityDelta = -redemptionAmount.quantity,
token = amount.token.product,
source = ourIdentity,
destination = otherSession.counterparty
),
notes = generateRandomString(10, GenerationScheme.NUMBERS),
createdAt = Instant.now(),
participants = listOf(ourIdentity),
type = NodeTransactionType.REDEMPTION
)
val ledgerTx = transactionBuilder.toLedgerTransaction(serviceHub)
ledgerTx.inputStates.forEach { logger.info((it as Cash.State).toString()) }
transactionBuilder.addOutputState(nodeTransactionState, NodeTransactionContract.CONTRACT_ID)
logger.info(transactionBuilder.toWireTransaction(serviceHub).toString())
val partiallySignedTransaction = serviceHub.signInitialTransaction(transactionBuilder, serviceHub.keyManagementService.filterMyKeys(signers))
val signedTransaction = subFlow(CollectSignaturesFlow(partiallySignedTransaction, listOf(otherSession)))
return subFlow(FinalityFlow(signedTransaction, listOf(otherSession)))
}
} | 0 | Kotlin | 0 | 1 | b18738612ce3300c701a62774b39479a414f0eda | 3,667 | cash-issuer | Apache License 2.0 |
app/src/main/java/com/it/pulltozoomlistview/MainActivity.kt | chendeqiang | 108,229,203 | false | null | package com.it.pulltozoomlistview
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ImageView
class MainActivity : AppCompatActivity() {
private var lv: PullToZoomListView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar!!.hide()
//以下代码用于去除阴影
if (Build.VERSION.SDK_INT >= 21) {
supportActionBar!!.elevation = 0f
}
lv = findViewById(R.id.main_lv) as PullToZoomListView?
val header = View.inflate(this, R.layout.layout_lv_header, null)
lv!!.addHeaderView(header)
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayOf("腾讯", "阿里巴巴", "百度", "新浪", "c语言", "java", "php", "FaceBook", "Twiter", "xml", "html"))
lv!!.adapter = adapter
val iv = header.findViewById<ImageView>(R.id.header_img)
lv!!.setPullToZoomListView(iv)
}
// 当界面显示出来的时候回调
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
lv!!.setViewBounds()
}
}
}
| 0 | Kotlin | 0 | 0 | 9978a55ac0d66cc84a72a9e93c0b92ff4cd68ee4 | 1,302 | PullToZoomListView | Apache License 2.0 |
app/src/main/kotlin/com/kevlina/budgetplus/app/book/BookSnackbarSender.kt | kevinguitar | 517,537,183 | false | {"Kotlin": 669900} | package com.kevlina.budgetplus.app.book
import com.kevlina.budgetplus.core.common.EventFlow
import com.kevlina.budgetplus.core.common.MutableEventFlow
import com.kevlina.budgetplus.core.common.sendEvent
import com.kevlina.budgetplus.core.ui.SnackbarData
import com.kevlina.budgetplus.core.ui.SnackbarSender
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BookSnackbarSender @Inject constructor() : SnackbarSender {
private val _snackbarEvent = MutableEventFlow<SnackbarData>()
val snackbarEvent: EventFlow<SnackbarData> get() = _snackbarEvent
override fun showSnackbar(snackbarData: SnackbarData) {
_snackbarEvent.sendEvent(snackbarData)
}
} | 0 | Kotlin | 0 | 7 | 2e561376a92f08b15617ff6290b43dd5a5309e06 | 695 | budgetplus-android | MIT License |
app/src/main/java/cz/palda97/lpclient/view/settings/NotificationInfoDialog.kt | Palda97 | 280,530,029 | false | null | package cz.palda97.lpclient.view.settings
import android.app.Dialog
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import cz.palda97.lpclient.Injector
import cz.palda97.lpclient.R
import cz.palda97.lpclient.databinding.DialogNotificationInfoBinding
import cz.palda97.lpclient.viewmodel.settings.SettingsViewModel
/**
* Dialog window for informing user about notification refresh rate.
*/
class NotificationInfoDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding: DialogNotificationInfoBinding =
DataBindingUtil.inflate(layoutInflater, R.layout.dialog_notification_info, null, false)
val viewModel = SettingsViewModel.getInstance(this)
binding.automaticRefreshRate = viewModel.automaticRefreshRate
val builder = MaterialAlertDialogBuilder(requireContext())
.setView(binding.root)
.setNeutralButton(R.string.stop_reminding) { _, _ ->
viewModel.stopRemindingMonitorBackground = true
}
.setPositiveButton(R.string.ok) { _, _ ->
//
}
return builder.create()
}
companion object {
private val l = Injector.generateLogFunction(this)
private const val FRAGMENT_TAG = "notificationInfoDialog"
/**
* Creates an instance of [NotificationInfoDialog] and shows it.
*/
fun appear(fragmentManager: FragmentManager) {
NotificationInfoDialog().show(fragmentManager, FRAGMENT_TAG)
}
}
} | 0 | Kotlin | 0 | 0 | e2e1c188a21dac4cd78d9242633dc094ba50ef64 | 1,743 | LinkedPipesAndroidClient | MIT License |
src/test/kotlin/unq/edu/remotetrainer/persistence/repository/AbstractRepositoryTest.kt | guidomarchini | 253,071,697 | false | {"Kotlin": 132885, "HTML": 77035, "JavaScript": 12972, "CSS": 1290} | package unq.edu.remotetrainer.persistence.repository
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
import org.springframework.data.repository.CrudRepository
import org.springframework.data.repository.findByIdOrNull
/**
* Abstract Repository test.
* It contains the basic tests for basic CRUD methods.
* The implementations should define the update operation, along with the custom repository's methods.
* The repository is cleaned after each test, to maintain consistency on further tests.
* If instances are created inside the test context, be sure to override afterEach method and delete them.
* Generics:
* * E = Entity object.
*/
@DataJpaTest
abstract class AbstractRepositoryTest<E> {
abstract val entityManager: TestEntityManager
abstract val repository: CrudRepository<E, Int> // for now, Int as id is ok
@AfterEach
fun afterEach() {
repository.deleteAll()
}
@Test
fun `it creates an instance`() {
val newInstance: E = sampleEntity()
// act
val savedInstance: E = repository.save(newInstance)
// assert
newInstanceAssertions(savedInstance, newInstance)
}
@Test
fun `it returns a saved entity`() {
// arrange
val entity: E = entityManager.persistAndFlush(sampleEntity())
// act
val found = repository.findByIdOrNull(id(entity))
// assert
Assertions.assertThat(found).isEqualTo(entity)
}
@Test
fun `it removes an entity`() {
// arrange
val entity: E = entityManager.persistAndFlush(sampleEntity())
val entityId: Int = id(entity)
// act
repository.deleteById(entityId)
// assert
Assertions.assertThat(repository.findByIdOrNull(entityId)).isNull()
}
/** Assertions to be done for a new instance */
abstract fun newInstanceAssertions(savedInstance: E, newInstance: E)
/** Returns the Entity id */
abstract fun id(entity: E): Int
/** Creates a new sample Entity to perform basic CRUD operations */
abstract fun sampleEntity(): E
} | 0 | Kotlin | 0 | 0 | d675545e9135211e4daab0f7fa06616ce6458e28 | 2,301 | remotetrainer | Apache License 2.0 |
app/src/main/java/com/apaluk/streamtheater/ui/common/composable/MediaTitle.kt | apaluk | 651,545,506 | false | {"Kotlin": 401053, "Java": 15022} | package com.apaluk.streamtheater.ui.common.composable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@Composable
fun MediaTitle(
title: String,
originalTitle: String?,
modifier: Modifier = Modifier,
titleTextStyle: TextStyle = MaterialTheme.typography.headlineMedium,
originalTitleTextStyle: TextStyle = MaterialTheme.typography.bodyLarge,
showOriginalTitleIfSame: Boolean = false
) {
Row(modifier = modifier) {
Text(
modifier = Modifier.alignByBaseline(),
text = title,
style = titleTextStyle,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
if (originalTitle != null && (originalTitle != title || showOriginalTitleIfSame)) {
Text(
modifier = Modifier.padding(start = 6.dp).alignByBaseline(),
text = "($originalTitle)",
style = originalTitleTextStyle,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
} | 0 | Kotlin | 0 | 0 | a431523e40b1d975fc3e4a264dedaa8744c6649e | 1,649 | stream-theater | MIT License |
src/main/kotlin/com/sudodevoss/modules/networking/data/common/exceptions/UnAuthorizedException.kt | omar-bizreh | 370,787,892 | false | null | package com.sudodevoss.easysignin.networking.data.common.exceptions
class UnAuthorizedException(message: String? = null) : Throwable(message) | 0 | Kotlin | 0 | 0 | bbec69edb29d8762940811831ae097a5ad518dc4 | 142 | easy-signin-kotlin | MIT License |
roboquant/src/main/kotlin/org/roboquant/backtest/Optimizer.kt | neurallayer | 406,929,056 | false | null | package org.roboquant.backtest
import org.roboquant.Roboquant
import org.roboquant.brokers.sim.SimBroker
import org.roboquant.common.ParallelJobs
import org.roboquant.common.TimeSpan
import org.roboquant.common.Timeframe
import org.roboquant.common.minus
import org.roboquant.feeds.Feed
import org.roboquant.loggers.MemoryLogger
import java.util.*
data class RunResult(val params: Params, val score: Double, val timeframe: Timeframe, val name: String)
/**
* Create a mutable synchronized list
*/
fun <T> mutableSynchronisedListOf(): MutableList<T> = Collections.synchronizedList(mutableListOf<T>())
/**
* Optimizer that implements different back-test optimization strategies to find a set of optimal parameter
* values.
*
* An optimizing back test has two phases, and each phase has up to two periods.
* The warmup periods are optional and by default [TimeSpan.ZERO].
*
* Training phase:
* - warmup period; get required data for strategies, policies and metrics loaded
* - training period; optimize the hyperparameters
*
* Validation phase
* - warmup period; get required data for strategies, policies and metrics loaded
* - validation period; see how a run is performing, based on unseen data
*
*
* @property space search space
* @property score scoring function
* @property getRoboquant function that returns an instance of roboquant based on passed parameters
*
*/
open class Optimizer(
private val space: SearchSpace,
private val score: Score,
private val getRoboquant: (Params) -> Roboquant
) {
private var run = 0
/**
* Using the default objective to maximize a metric. The default objective will use the last entry of the
* provided [evalMetric] as the value to optimize.
*/
constructor(space: SearchSpace, evalMetric: String, getRoboquant: (Params) -> Roboquant) : this(
space, MetricScore(evalMetric), getRoboquant
)
fun walkForward(
feed: Feed,
period: TimeSpan,
warmup: TimeSpan = TimeSpan.ZERO,
anchored: Boolean = false
): List<RunResult> {
require(!feed.timeframe.isInfinite()) { "feed needs known timeframe" }
val start = feed.timeframe.start
val results = mutableListOf<RunResult>()
feed.timeframe.split(period).forEach {
val timeframe = if (anchored) Timeframe(start, it.end, it.inclusive) else it
val result = train(feed, timeframe, warmup)
results.addAll(result)
}
return results
}
/**
* Run a walk forward
*/
fun walkForward(
feed: Feed,
period: TimeSpan,
validation: TimeSpan,
warmup: TimeSpan = TimeSpan.ZERO,
anchored: Boolean = false
): List<RunResult> {
val timeframe = feed.timeframe
require(timeframe.isFinite()) { "feed needs known timeframe" }
val feedStart = feed.timeframe.start
val results = mutableListOf<RunResult>()
timeframe.split(period + validation, period).forEach {
val trainEnd = it.end - validation
val trainStart = if (anchored) feedStart else it.start
val trainTimeframe = Timeframe(trainStart, trainEnd)
val result = train(feed, trainTimeframe, warmup)
results.addAll(result)
val best = result.maxBy { entry -> entry.score }
// println("phase=training timeframe=$timeframe equity=${best.second} params=${best.first}")
val validationTimeframe = Timeframe(trainEnd, it.end, it.inclusive)
val score = validate(feed, validationTimeframe, best.params, warmup)
results.add(score)
}
return results
}
/**
* Run a Monte Carlo simulation
*/
fun monteCarlo(feed: Feed, period: TimeSpan, samples: Int, warmup: TimeSpan = TimeSpan.ZERO): List<RunResult> {
val results = mutableSynchronisedListOf<RunResult>()
require(!feed.timeframe.isInfinite()) { "feed needs known timeframe" }
feed.timeframe.sample(period, samples).forEach {
val result = train(feed, it, warmup)
results.addAll(result)
// val best = result.maxBy { it.score }
// println("timeframe=$it equity=${best.score} params=${best.params}")
}
return results
}
/**
* The logger to use for training phase. By default, this logger is discarded after the run and score is
* calculated
*/
open fun getTrainLogger() = MemoryLogger(false)
/**
* Train the solution in parallel
*/
fun train(feed: Feed, tf: Timeframe = Timeframe.INFINITE, warmup: TimeSpan = TimeSpan.ZERO): List<RunResult> {
val jobs = ParallelJobs()
val results = mutableSynchronisedListOf<RunResult>()
for (params in space) {
jobs.add {
val rq = getRoboquant(params).copy(logger = getTrainLogger())
require(rq.broker is SimBroker) { "Only a SimBroker can be used for back testing" }
val name = "train-${run++}"
rq.runAsync(feed, tf, name, warmup)
val s = score.calculate(rq, name, tf)
val result = RunResult(params, s, tf, name)
results.add(result)
}
}
jobs.joinAllBlocking()
return results
}
private fun validate(feed: Feed, timeframe: Timeframe, params: Params, warmup: TimeSpan): RunResult {
val rq = getRoboquant(params)
require(rq.broker is SimBroker) { "Only a SimBroker can be used for back testing" }
val name = "validate-${run++}"
rq.run(feed, timeframe, name = name, warmup)
val s = score.calculate(rq, name, timeframe)
// println("phase=validation result=$result")
return RunResult(params, s, timeframe, name)
}
} | 18 | null | 29 | 224 | 13c2db8399f64d3286b388d81536488cb588c04d | 5,840 | roboquant | Apache License 2.0 |
src/main/kotlin/com/strack/firstspringboot/GreetingController.kt | gbrlstrack | 702,705,586 | false | {"Kotlin": 1103} | package com.strack.firstspringboot
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.concurrent.atomic.AtomicLong
@RestController
class GreetingController {
val count: AtomicLong = AtomicLong()
@RequestMapping("/greeting")
fun greeting(@RequestParam(value="name", defaultValue = "World") name: String?): Greeting {
return Greeting(count.incrementAndGet(), "Hello $name!")
}
} | 0 | Kotlin | 0 | 0 | 0bd372d7fb14ff2b0486a9003fe4864b1cf600b3 | 554 | rest-with-springboot | Apache License 2.0 |
app/src/main/java/dev/borisochieng/gitrack/ui/adapters/RepositoryAdapter.kt | slowburn-404 | 777,819,284 | false | {"Kotlin": 42832} | package dev.borisochieng.gitrack.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.RecyclerView
import dev.borisochieng.gitrack.databinding.ItemRepositoryBinding
import dev.borisochieng.gitrack.ui.models.Repository
import dev.borisochieng.gitrack.utils.RVDiffUtil
class RepositoryAdapter(private val onRepositoryClickListener: OnRepositoryClickListener) : RecyclerView.Adapter<RepositoryAdapter.ViewHolder>() {
inner class ViewHolder(private val binding : ItemRepositoryBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind (item: Repository) {
binding.apply {
repositoryTitle.text = item.title
repositoryDesc.text = item.desc
issueCount.text = item.issueCount.toString()
starsCount.text = item.starCount.toString()
//lastUpdated.text = item.lastUpdated
root.setOnClickListener {
onRepositoryClickListener.onItemClick(item)
}
}
}
}
private val asyncListDiffer = AsyncListDiffer(this, RVDiffUtil())
fun setList(list: List<Repository>) {
asyncListDiffer.submitList(list)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemBinding = ItemRepositoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(itemBinding)
}
override fun getItemCount(): Int = asyncListDiffer.currentList.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = asyncListDiffer.currentList[position]
holder.bind(item)
}
} | 0 | Kotlin | 0 | 0 | d207e85c4ee1afc5b6b98b3831cb8682d4d36bc1 | 1,774 | GiTrack | MIT License |
Scanner/Android/app/src/main/java/ca/snmc/scanner/data/network/responses/EventsResponse.kt | snmcCode | 272,461,777 | false | {"C#": 420531, "Kotlin": 263098, "HTML": 148679, "TSQL": 22187, "CSS": 9706, "JavaScript": 920} | package ca.snmc.scanner.data.network.responses
import ca.snmc.scanner.models.Event
class EventsResponse : ArrayList<Event>() | 29 | C# | 1 | 6 | f1bb550397b4e959beb501e77c27110d439a64b3 | 126 | covidTracking | MIT License |
src/main/kotlin/com/rose/gateway/minecraft/chat/processing/tokens/TextTokenProcessor.kt | nicholasgrose | 377,028,896 | false | null | package com.rose.gateway.minecraft.chat.processing.tokens
import com.rose.gateway.minecraft.chat.processing.tokens.result.TokenProcessingResult
import com.rose.gateway.minecraft.component.component
import com.rose.gateway.shared.parsing.TokenProcessor
import guru.zoroark.tegral.niwen.lexer.Token
import guru.zoroark.tegral.niwen.lexer.TokenType
import org.intellij.lang.annotations.Language
/**
* Defines and processes a piece of plaintext
*
* @constructor Create a text token processor
*/
class TextTokenProcessor : TokenProcessor<TokenProcessingResult, Unit> {
override fun tokenType(): TokenType {
return ChatComponent.TEXT
}
@Language("RegExp")
override fun regexPattern(): String {
return ".[^@]*"
}
override suspend fun process(
token: Token,
additionalData: Unit,
): TokenProcessingResult {
val text = token.string
return TokenProcessingResult(text.component(), text)
}
}
| 26 | null | 1 | 4 | 896a6e99b74c97128c74fd166b80c31d183fb36c | 969 | Gateway | MIT License |
generics/src/main/java/cn/chriswood/kotlincourse/unsafevariances/KotlinUnsafeVariances.kt | chriswoodcn | 743,412,011 | false | {"Kotlin": 53695, "Java": 12434} | package com.bennyhuo.kotlin.generics.unsafevariances
fun main() {
val numbers: Map<String, Number> = mapOf("a" to 1)
val num = numbers.getOrDefault("b", 0.1)
println(num)
val dustbinForAny = Dustbin<Any>()
val dustbinFotInt: Dustbin<Int> = dustbinForAny
dustbinFotInt.put(2)
dustbinForAny.put("Hello")
// val int: Int = dustbinFotInt.list[1]
// println(int)
}
class Dustbin<in T>{
private val list = mutableListOf<@UnsafeVariance T>()
fun put(t: T){
list += t
}
}
sealed class List<out T> {
operator fun contains(t: @UnsafeVariance T): Boolean {
fun containsInner(list: List<T>, t: T): Boolean = when (list) {
Nil -> false
is Cons -> if (list.head == t) true
else containsInner(list.tail, t)
}
return containsInner(this, t)
}
object Nil : List<Nothing>() {
override fun toString(): String {
return "Nil"
}
}
data class Cons<T>(val head: T, val tail: List<T>) : List<T>() {
override fun toString(): String {
return "$head, $tail"
}
}
fun joinToString(sep: Char = ','): String {
return when (this) {
Nil -> "Nil"
is Cons -> "${this.head}$sep${this.tail.joinToString(sep)}"
}
}
}
| 0 | Kotlin | 0 | 0 | e4f5a443613d51d9f035d461cc04e41e35c74e4e | 1,330 | kotlinCourse | MIT License |
app/src/main/java/com/tuttle80/app/dionysus/ui/account/SignUpFragment.kt | tuttle80 | 355,957,951 | false | null | package com.tuttle80.app.dionysus.ui.account
import android.content.res.ColorStateList
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.text.method.PasswordTransformationMethod
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatImageButton
import androidx.core.widget.addTextChangedListener
import androidx.navigation.Navigation
import com.tuttle80.app.dionysus.R
import com.tuttle80.app.dionysus.db.AccountRepo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import java.util.regex.Pattern
class SignUpFragment : Fragment() {
private lateinit var viewModel: SignUpViewModel
private lateinit var checkImageEmail: ImageView
private lateinit var checkImagePassword: ImageView
private lateinit var checkImagePassword2: ImageView
private var flagSubmit = 0
private val FLAG_CHECK_OK_EMAIL = 0x01
private val FLAG_CHECK_OK_PASSWORD = 0x02
private val FLAG_CHECK_OK_PASSWORD2 = 0x04
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_signup, container, false)
initWidget(root)
return root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(SignUpViewModel::class.java)
}
private fun initWidget(rootView : View) {
// Back button
rootView.findViewById<AppCompatImageButton>(R.id.backButton).setOnClickListener {
activity?.onBackPressed()
}
val editEmail = rootView.findViewById<AppCompatEditText>(R.id.signInEmail)
editEmail.addTextChangedListener { text ->
// EMail 정규식을 보고 버튼 활성화를 결정한다.
val pattern = "\\w+@\\w+\\.\\w+(\\.\\w+)?" // email 정규식
// 상태에 따라 색상을 지정한다.
val color = if (Pattern.matches(pattern, text.toString())) {
flagSubmit = flagSubmit or FLAG_CHECK_OK_EMAIL;
requireContext().getColor(R.color.check_color_ok)
}
else {
flagSubmit = flagSubmit and (FLAG_CHECK_OK_EMAIL.inv());
requireContext().getColor(R.color.check_color_fail)
}
if (::checkImageEmail.isInitialized == true) {
checkImageEmail.imageTintList = ColorStateList.valueOf(color)
}
}
val editPassword = rootView.findViewById<AppCompatEditText>(R.id.signInPassword)
editPassword.addTextChangedListener { text ->
// 상태에 따라 색상을 지정한다.
val textLength = text?.length ?: 0
val color = if (4 <= textLength) {
flagSubmit = flagSubmit or FLAG_CHECK_OK_PASSWORD;
requireContext().getColor(R.color.check_color_ok)
}
else {
flagSubmit = flagSubmit and (FLAG_CHECK_OK_PASSWORD.inv());
requireContext().getColor(R.color.check_color_fail)
}
if (::checkImagePassword.isInitialized == true) {
checkImagePassword.imageTintList = ColorStateList.valueOf(color)
}
}
val editPassword2 = rootView.findViewById<AppCompatEditText>(R.id.signInPassword2)
editPassword2.addTextChangedListener { text ->
// 상태에 따라 색상을 지정한다.
val textLength = text?.length ?: 0
val compare = editPassword.text != editPassword2.text
val color = if (4 <= textLength && compare) {
flagSubmit = flagSubmit or FLAG_CHECK_OK_PASSWORD2;
requireContext().getColor(R.color.check_color_ok)
}
else {
flagSubmit = flagSubmit and (FLAG_CHECK_OK_PASSWORD2.inv());
requireContext().getColor(R.color.check_color_fail)
}
if (::checkImagePassword2.isInitialized == true) {
checkImagePassword2.imageTintList = ColorStateList.valueOf(color)
}
}
checkImageEmail = rootView.findViewById(R.id.checkEmail)
checkImagePassword = rootView.findViewById(R.id.checkPassword)
checkImagePassword2 = rootView.findViewById(R.id.checkPassword2)
// 비밀번호 표시
rootView.findViewById<AppCompatCheckBox>(R.id.showPasswordChkBox).setOnCheckedChangeListener { _, isChecked ->
editPassword.transformationMethod = if (!isChecked) PasswordTransformationMethod() else null
editPassword.setSelection(editPassword.length())
editPassword2.transformationMethod = if (!isChecked) PasswordTransformationMethod() else null
editPassword2.setSelection(editPassword2.length())
}
// 로그인 버튼
rootView.findViewById<AppCompatButton>(R.id.submitButton).setOnClickListener {
if (flagSubmit != (FLAG_CHECK_OK_EMAIL or FLAG_CHECK_OK_PASSWORD or FLAG_CHECK_OK_PASSWORD2)) {
return@setOnClickListener
}
// if (editPassword.text != editPassword2.text) {
// return@setOnClickListener
// }
/* 새로운 객체를 생성, id 이외의 값을 지정 후 DB에 추가 */
CoroutineScope(Dispatchers.IO).launch {
val accountRepo = AccountRepo()
val isExist = accountRepo.isExistAccount(requireContext(), editEmail.text.toString())
if (isExist) {
Toast.makeText(requireContext(), "등록된 사용자 입니다.", Toast.LENGTH_LONG).show()
return@launch
}
accountRepo.addAccount(requireContext(), editEmail.text.toString(), editPassword.text.toString())
CoroutineScope(Dispatchers.Main).launch {
Toast.makeText(requireContext(), "등록 되었습니다.", Toast.LENGTH_LONG).show()
activity?.onBackPressed()
}
}.start()
}
// // 비밀번호 찾기
// rootView.findViewById<AppCompatButton>(R.id.forgotPasswordButton).setOnClickListener {
// Toast.makeText(requireContext(), "비밀번호 찾기", Toast.LENGTH_LONG).show()
// //Toast.makeText(context, "Verified OK", Toast.LENGTH_LONG).show()
// }
//
// // 새로 가입하기
// rootView.findViewById<AppCompatButton>(R.id.singUpButton).setOnClickListener {
// Navigation.findNavController(rootView).navigate(R.id.action_navigation_signin_to_navigation_signup)
// }
}
} | 1 | Kotlin | 0 | 0 | 6264aba5965e2b0516221b63ee1c65152b122459 | 6,964 | SignInExample | Apache License 2.0 |
ocpi-toolkit-2.1.1/src/main/kotlin/com/izivia/ocpi/toolkit/modules/locations/domain/EnergyMix.kt | IZIVIA | 497,830,391 | false | null | package com.izivia.ocpi.toolkit.modules.locations.domain
import com.izivia.ocpi.toolkit.annotations.Partial
/**
* This type is used to specify the energy mix and environmental impact of the supplied energy at a location or in a
* tariff.
*
* @property is_green_energy True if 100% from regenerative sources. (CO2 and nuclear waste is zero)
* @property energy_sources Key-value pairs (enum + percentage) of energy sources of this location's tariff.
* @property environ_impact Key-value pairs (enum + percentage) of nuclear waste and CO2 exhaust of this location's
* tariff.
* @property supplier_name (max-length=64) Name of the energy supplier, delivering the energy for this location or
* tariff. **
* @property energy_product_name (max-length=64) Name of the energy suppliers product/tariff plan used at this
* location. **
*
* ** These fields can be used to look-up energy qualification or to show it directly to the customer (for well-known
* brands like Greenpeace Energy, etc.)
*/
@Partial
data class EnergyMix(
val is_green_energy: Boolean,
val energy_sources: List<EnergySource>?,
val environ_impact: List<EnvironmentalImpact>?,
val supplier_name: String?,
val energy_product_name: String?
) | 0 | Kotlin | 0 | 7 | a109ba5c37fe55be2cbc22832db8ef0da9755533 | 1,235 | ocpi-toolkit | MIT License |
src/main/kotlin/snyk/iac/IacIssue.kt | snyk | 117,852,067 | false | null | package snyk.iac
import io.snyk.plugin.Severity
data class IacIssue(
val id: String,
val title: String,
private val severity: String,
val publicId: String,
val documentation: String,
val lineNumber: Int,
val issue: String,
val impact: String,
val resolve: String? = null,
val references: List<String> = emptyList(),
val path: List<String> = emptyList(),
val lineStartOffset: Int = 0
) {
var ignored = false
var obsolete = false
fun getSeverity(): Severity = Severity.getFromName(severity)
}
| 6 | null | 34 | 54 | 170f7da4c648b9201c07818810e04ba73fe2e567 | 554 | snyk-intellij-plugin | Apache License 2.0 |
app/src/main/java/com/malandev/cryptotrackpro/data/remote/dto/LinksExtended.kt | MalanDev | 747,308,253 | false | {"Kotlin": 22646} | package com.malandev.cryptotrackpro.data.remote.dto
data class LinksExtended(
val stats: Stats,
val type: String, // blog
val url: String // https://bitcoin.org/en/blog
) | 0 | Kotlin | 0 | 0 | ddad3b339966daa67267a2da8511b1c841093b22 | 184 | cryptotrackpro | MIT License |
Chapter09/Lock.kt | PacktPublishing | 136,562,920 | false | {"Kotlin": 30303, "Java": 6690} | package mastering.kotlin.performance.chapter9
class Lock {
private val lock = java.lang.Object()
fun unlock() {
synchronized(lock) {
lock.notify()
}
}
fun lock() {
synchronized(lock) {
lock.wait()
}
}
} | 1 | Kotlin | 9 | 26 | 63f0ee27c7b703db0e97b067a3c2f966f5d8f252 | 282 | Mastering-High-Performance-with-Kotlin | MIT License |
src/androidMain/kotlin/com/shepeliev/webrtckmp/MediaStreamTrack.kt | cloudwise-solutions | 413,005,519 | true | {"Objective-C": 456849, "Kotlin": 171448, "Python": 11133, "C": 5349, "Ruby": 949} | package com.shepeliev.webrtckmp
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import org.webrtc.MediaSource
import org.webrtc.AudioTrack as AndroidAudioTrack
import org.webrtc.MediaStreamTrack as AndroidMediaStreamTrack
import org.webrtc.VideoTrack as AndroidVideoTrack
actual open class MediaStreamTrack internal constructor(
val android: AndroidMediaStreamTrack,
private val mediaSource: MediaSource?,
) {
protected val scope = MainScope()
actual val id: String
get() = android.id()
actual val kind: MediaStreamTrackKind
get() = when (android.kind()) {
AndroidMediaStreamTrack.AUDIO_TRACK_KIND -> MediaStreamTrackKind.Audio
AndroidMediaStreamTrack.VIDEO_TRACK_KIND -> MediaStreamTrackKind.Video
else -> throw IllegalStateException("Unknown track kind: ${android.kind()}")
}
actual val label: String
get() = when (kind) {
// TODO(shepeliev): get real capturing device (front/back camera, internal microphone, headset)
MediaStreamTrackKind.Audio -> "microphone"
MediaStreamTrackKind.Video -> "camera"
}
actual val muted: Boolean
get() = !enabled
actual var enabled: Boolean
get() = android.enabled()
set(value) {
android.setEnabled(value)
if (value) {
scope.launch { onUnmuteInternal.emit(Unit) }
} else {
scope.launch { onMuteInternal.emit(Unit) }
}
}
actual val readyState: MediaStreamTrackState
get() = android.state().asCommon()
private val onEndedInternal = MutableSharedFlow<Unit>()
actual val onEnded: Flow<Unit> = onEndedInternal.asSharedFlow()
private val onMuteInternal = MutableSharedFlow<Unit>()
actual val onMute: Flow<Unit> = onMuteInternal.asSharedFlow()
private val onUnmuteInternal = MutableSharedFlow<Unit>()
actual val onUnmute: Flow<Unit> = onUnmuteInternal.asSharedFlow()
actual open fun stop() {
if (readyState == MediaStreamTrackState.Ended) return
scope.launch {
onEndedInternal.emit(Unit)
scope.cancel()
}
mediaSource?.dispose()
}
}
internal fun AndroidMediaStreamTrack.asCommon(): MediaStreamTrack {
return when (this) {
is AndroidAudioTrack -> AudioStreamTrack(this)
is AndroidVideoTrack -> VideoStreamTrack(this)
else -> error("Unknown native MediaStreamTrack: $this")
}
}
private fun AndroidMediaStreamTrack.State.asCommon(): MediaStreamTrackState {
return when (this) {
AndroidMediaStreamTrack.State.LIVE -> MediaStreamTrackState.Live
AndroidMediaStreamTrack.State.ENDED -> MediaStreamTrackState.Ended
}
}
| 0 | null | 0 | 0 | 06b881cef5bc88e52bc510134e4ec936f522029f | 2,948 | webrtc-kmp | Apache License 2.0 |
src/main/kotlin/com/tankobon/manga/library/FileRouter.kt | AcetylsalicylicAcid | 445,686,330 | false | null | package com.tankobon.manga.library
import com.tankobon.utils.archive.unRAR
import com.tankobon.utils.archive.unZIP
import com.tankobon.utils.imageConverter
import com.tankobon.utils.logger
import com.tankobon.utils.unsupported
import java.io.File
enum class FileRouterType { ARCHIVE, IMAGES, ALL, UNSUPPORTED }
fun fileRouter(
file: File,
type: FileRouterType = FileRouterType.ALL,
increaseHierarchy: Boolean = false,
): File? {
val log = logger("file-router")
// skip macos .DS_Store file
if (file.name.contains(".DS_Store")) {
return null
}
when {
// archives
Regex("^(zip|cbz)\$").matches(file.extension) -> {
if (type == FileRouterType.ALL || type == FileRouterType.ARCHIVE) {
log.trace("unzip ${file.path}")
return unZIP(file, increaseHierarchy)
}
}
Regex("^(rar|cbr)\$").matches(file.extension) -> {
if (type == FileRouterType.ALL || type == FileRouterType.ARCHIVE) {
log.trace("unrar ${file.path}")
return unRAR(file, increaseHierarchy)
}
}
// images
Regex("^(jpg)\$").matches(file.extension) -> {
log.trace("jpg do nothing ${file.path}")
// do nothing
}
Regex("^(png|PNG)\$").matches(file.extension) -> {
if (type == FileRouterType.ALL || type == FileRouterType.IMAGES) {
log.trace("png convert ${file.path}")
imageConverter(file)
}
}
Regex("^(jpeg|jpe|JPEG|JPE|JPG)\$").matches(file.extension) -> {
if (type == FileRouterType.ALL || type == FileRouterType.IMAGES) {
log.trace("jpg but with wrong extension ${file.path}")
file.renameTo(File("${file.parentFile.path}/${file.nameWithoutExtension}.jpg"))
}
}
// unsupported
else -> {
log.debug("unsupported file ${file.path}")
unsupported(file)
}
}
return null
}
| 0 | Kotlin | 0 | 4 | fa63eb8eed91dd4a9177a3644c105c66b8ca8c3d | 2,069 | tankobon-backend-kotlin | MIT License |
src/test/kotlin/de/ordermatching/planning/DefaultPlanningCalculatorLongDistanceTest.kt | dominikstampa | 862,796,663 | false | {"Kotlin": 183945} | package de.ordermatching.planning
import de.ordermatching.Configuration
import de.ordermatching.INetworkInfo
import de.ordermatching.distance.EmissionProperty
import de.ordermatching.helper.*
import de.ordermatching.model.*
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.time.OffsetDateTime
import java.time.ZoneOffset
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
internal class DefaultPlanningCalculatorLongDistanceTest {
@MockK
private lateinit var networkInfo: INetworkInfo
private val calculator = DefaultPlanningCalculator()
private val distantOrder = Order(
senderPosition = GeoPosition(40.0, 10.0),
recipientPosition = GeoPosition(50.0, 10.0),
packageSize = PackageSize.SMALL,
startTime = OffsetDateTime.of(2023, 11, 21, 8, 0, 0, 0, ZoneOffset.UTC) //Tuesday
)
private val endNode = getEndNode(distantOrder)
private val startNode = getStartNode(distantOrder)
private val secondNode = Node(
position = GeoPosition(45.0, 10.0),
transferPoint = TransferPoint(GeoPosition(45.0, 10.0)),
lspOwner = null,
type = NodeType.NEUTRAL
)
private val thirdNode = Node(
position = GeoPosition(45.1, 10.0),
transferPoint = TransferPoint(GeoPosition(45.1, 10.0)),
lspOwner = null,
type = NodeType.NEUTRAL
)
private val allNodes = listOf(startNode, secondNode, thirdNode, endNode)
private lateinit var input: PlanningInput
private val allTps = listOf(startNode.transferPoint!!, secondNode.transferPoint!!, thirdNode.transferPoint!!)
@BeforeEach
fun setUp() {
MockKAnnotations.init(this, relaxUnitFun = true)
input = PlanningInput(
endNode,
allNodes,
EmissionProperty(ignoreLongDistance = false),
networkInfo,
distantOrder,
Configuration()
)
}
// forbidden route: startNode ->(testLsp) midNode ->(cw) endTp ->(testLsp) endNode
// should be route: start -> startTp ->(testLSP) -> endNode
@Test
fun `test no long distance transportation after short one`() {
val serviceInfo = ServiceInfo(
deliveryDateEstimate = distantOrder.startTime.plusDays(1),
priceEstimate = 2.0,
emissionsEstimate = 100.0
)
val routeTimeslot = CrowdworkerRouteTimeslot(testCwRoute.timeslots[0], testCwRoute)
every { networkInfo.findLSPsWithPositionInDeliveryRegion(startNode.position) } returns listOf(testLsp)
every { networkInfo.findLSPsWithPositionInDeliveryRegion(secondNode.position) } returns listOf(testLsp)
every { networkInfo.findLSPsWithPositionInDeliveryRegion(thirdNode.position) } returns listOf(testLsp) //add another?
every { networkInfo.findTransferPointsInLSPDeliveryRegion(testLsp) } returns allTps
every { networkInfo.getServiceInfo(testLsp, any(), distantOrder.packageSize) } returns serviceInfo
every { networkInfo.findSuitedCWRoutesNearPosition(any(), any()) } returns emptyList()
every { networkInfo.findSuitedCWRoutesNearPosition(secondNode.position, any()) } returns listOf(routeTimeslot)
every {
networkInfo.findTransferPointsNearCWRouteBetweenPackageAndEndpoint(
testCwRoute,
secondNode.position
)
} returns listOf(thirdNode.transferPoint!!)
calculator.calculate(input)
assertNotNull(endNode.predecessor)
assertEquals(startNode, endNode.predecessor)
}
} | 0 | Kotlin | 0 | 0 | 4f35f0f1c37754fc636b4f73566feb5b6cc2fd28 | 3,694 | order-matching | MIT License |
app/src/main/java/com/martino/jasiu/learnkotlin/mainmenu/presentation/ui/MainMenuActivity.kt | CodeOnThePomp | 106,590,662 | false | {"Kotlin": 19173, "CMake": 1715, "C++": 277} | package com.martino.jasiu.learnkotlin.mainmenu.presentation.ui
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.view.Menu
import android.view.MenuItem
import com.martino.jasiu.learnkotlin.R
import com.martino.jasiu.learnkotlin.db.dao.WordDao
import com.martino.jasiu.learnkotlin.general.presentation.CommonActivity
import com.martino.jasiu.learnkotlin.mainmenu.presentation.viewmodel.MainMenuActivityViewModel
import com.martino.jasiu.learnkotlin.manage.presentation.ui.ManageActivity
import kotlinx.android.synthetic.main.activity_main_menu.*
import kotlinx.android.synthetic.main.app_bar_main.*
import javax.inject.Inject
class MainMenuActivity : CommonActivity<MainMenuActivityViewModel>(), NavigationView.OnNavigationItemSelectedListener {
@Inject
lateinit var dao: WordDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_menu)
setSupportActionBar(toolbar)
var list = dao.findAllWords()
initFloatingActionButton()
initDrawer()
nav_view.setNavigationItemSelectedListener(this@MainMenuActivity)
}
private fun initDrawer() {
val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
}
private fun initFloatingActionButton() {
fab.setOnClickListener { view ->
Snackbar.make(view, "Function do not work, yet :D", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav_settings -> {
// Handle the camera action
}
R.id.nav_send -> {
}
R.id.nav_share -> {
}
R.id.nav_manage -> {
startActivity(Intent(this@MainMenuActivity, ManageActivity::class.java))
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
}
| 1 | Kotlin | 0 | 0 | 9cde4f0b5a15971325c0134d07e5579c6f61de22 | 3,304 | TheArtOfEnglish | Apache License 2.0 |
src/main/kotlin/com/intershop/gradle/icm/extension/ProjectConfiguration.kt | IntershopCommunicationsAG | 202,111,872 | false | {"Kotlin": 159788, "Groovy": 125109} | /*
* Copyright 2019 Intershop Communications AG.
*
* 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.intershop.gradle.icm.extension
import com.intershop.gradle.icm.project.TargetConf
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Project
import org.gradle.api.file.ProjectLayout
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import java.io.File
import javax.inject.Inject
/**
* Extension of an Intershop ICM project.
*
* @constructor creates the extension of a project configuration.
*/
open class ProjectConfiguration
@Inject constructor(
val project: Project,
objectFactory: ObjectFactory,
projectLayout: ProjectLayout) {
val containerConfig: File = TargetConf.PRODUCTION.config(projectLayout).get().asFile
val testcontainerConfig: File = TargetConf.TEST.config(projectLayout).get().asFile
val config: File = TargetConf.DEVELOPMENT.config(projectLayout).get().asFile
/**
* Base project configuration for final project.
*
* @property base
*/
val base: CartridgeProject = objectFactory.newInstance(CartridgeProject::class.java, project)
/**
* Configures a binary base project (This is also connected to
* a Docker image.).
*
* @param action Action to configure Cartridge project (ICM)
*/
fun base(action: Action<in CartridgeProject>) {
action.execute(base)
}
/**
* Configures a binary base project (This is also connected to
* a Docker image.).
*
* @param closure Closure to configure Cartridge project (ICM)
*/
fun base(closure: Closure<CartridgeProject>) {
project.configure(base, closure)
}
val modules: NamedDomainObjectContainer<NamedCartridgeProject> =
objectFactory.domainObjectContainer(
NamedCartridgeProject::class.java,
NamedCartridgeProjectFactory(project, objectFactory))
val libFilterFileDependency: Property<String> = objectFactory.property(String::class.java)
}
| 0 | Kotlin | 1 | 3 | 4a3a5df22a779cf76aa9d4d9147a1c8f96f5dc78 | 2,633 | icm-gradle-plugin | Apache License 2.0 |
app/src/main/java/com/example/pi_5_semestre/EventsFragment.kt | FelippePacomio | 778,455,554 | false | {"Kotlin": 14145, "Java": 8590} | package com.example.associacao_jardim_eucaliptos
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class EventsFragment : Fragment() {
private lateinit var eventsRecyclerView: RecyclerView
private lateinit var eventsAdapter: EventsAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_events, container, false)
val eventsList = generateEventsItems()
eventsRecyclerView = rootView.findViewById(R.id.eventsRecyclerView)
eventsRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
eventsRecyclerView.setHasFixedSize(true)
eventsAdapter = EventsAdapter(eventsList)
eventsRecyclerView.adapter = eventsAdapter
return rootView
}
private fun generateEventsItems(): List<EventsItem> {
val eventsItems = mutableListOf<EventsItem>()
eventsItems.add(
EventsItem(
R.drawable.ferias,
"As férias escolares estão chegando. Dê uma espiada na programação para a criançada no próximo mês de junho!"
)
)
eventsItems.add(
EventsItem(
R.drawable.facaparte,
"Tem vontade de fazer parte da equipe? Junte-se a nós!"
)
)
eventsItems.add(
EventsItem(
R.drawable.psocial,
"Confira nossos próximos projetos sociais na comunidade do Jardim dos Eucaliptos"
)
)
eventsItems.add(
EventsItem(
R.drawable.cestabasica,
"Entrega de Cestas Básicas Maio 2024"
)
)
return eventsItems
}
}
| 0 | Kotlin | 0 | 0 | ac98477e6abf2b7d7ecf9825ea9cd606fa8402ce | 2,016 | kotlin-jardim-dos-eucaliptos | MIT License |
src/util/image/opencvMat/ScalarUtil.kt | JBWills | 291,822,812 | false | null | package util.image.opencvMat
import org.opencv.core.Scalar
import util.iterators.mapArray
val Scalar.values: DoubleArray get() = `val`
val Scalar.first: Double get() = values[0]
fun Scalar.toFloatArray() = values.mapArray { it.toFloat() }.toFloatArray()
fun DoubleArray.toScalar() = Scalar(this)
| 0 | Kotlin | 0 | 0 | 569b27c1cb1dc6b2c37e79dfa527b9396c7a2f88 | 301 | processing-sketches | MIT License |
app/src/main/java/com/goldenowl/ecommerce/adapter/BottomSheetSizeAdapter.kt | longnghia | 490,517,031 | false | {"Kotlin": 599604, "Shell": 367} | package com.goldenowl.ecommerce.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.goldenowl.ecommerce.R
import com.goldenowl.ecommerce.utils.Constants.listSize
import com.goldenowl.ecommerce.utils.Utils
class BottomSheetSizeAdapter : RecyclerView.Adapter<BottomSheetSizeAdapter.ViewHolder>() {
private var checkItem = -1
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var tv: TextView? = null
init {
tv = view.findViewById(R.id.tv_size)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_bottom_sheet_size, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val text = listSize[position]
holder.tv?.apply {
this.text = text
this.setOnClickListener {
refresh(position)
}
if (position == checkItem) {
this.isSelected = true
this.setTextColor(Utils.getColor(holder.itemView.context, R.color.white) ?: 0xFFFFFF) // todo not work
} else {
this.isSelected = false
this.setTextColor(Utils.getColor(holder.itemView.context, R.color.black_light) ?: 0x222222)
}
}
}
fun refresh(position: Int) {
checkItem = position
notifyDataSetChanged()
}
fun getCheckedSize() = listSize[checkItem]
override fun getItemCount() = listSize.size
companion object {
val TAG = "BottomSheetSizeAdapter"
}
}
| 0 | Kotlin | 1 | 3 | 2fce27c406981cac795c8dce80ffac832abf14e3 | 1,805 | E-Commerce-Application | MIT License |
src/main/kotlin/no/nav/rekrutteringsbistand/api/support/config/JdbcConfig.kt | navikt | 214,435,826 | false | null | package no.nav.rekrutteringsbistand.api.support.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.simple.SimpleJdbcInsert
@Configuration
class JdbcConfig {
@Bean
fun simpleJdbcInsert(jdbcTemplate: JdbcTemplate): SimpleJdbcInsert {
return SimpleJdbcInsert(jdbcTemplate)
}
}
| 25 | Kotlin | 0 | 0 | 4c61eb16ed9aa0e5f08fe968077dfebd4c8b938d | 452 | rekrutteringsbistand-stilling-api | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2023/Day12.kt | stravag | 572,872,641 | false | {"Kotlin": 180324} | package ch.ranil.aoc.aoc2023
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.Ignore
import kotlin.test.assertEquals
import kotlin.time.measureTimedValue
class Day12 : AbstractDay() {
@Test
fun part1Test() {
assertEquals(1, countArrangements("???.### 1,1,3"))
assertEquals(4, countArrangements(".??..??...?##. 1,1,3"))
assertEquals(1, countArrangements("?#?#?#?#?#?#?#? 1,3,1,6"))
assertEquals(1, countArrangements("????.#...#... 4,1,1"))
assertEquals(4, countArrangements("????.######..#####. 1,6,5"))
assertEquals(10, countArrangements("?###???????? 3,2,1"))
}
@Test
fun part1TestOptimized() {
assertEquals(1, countArrangementsOptimized("???.### 1,1,3"))
assertEquals(4, countArrangementsOptimized(".??..??...?##. 1,1,3"))
assertEquals(1, countArrangementsOptimized("?#?#?#?#?#?#?#? 1,3,1,6"))
assertEquals(1, countArrangementsOptimized("????.#...#... 4,1,1"))
assertEquals(4, countArrangementsOptimized("????.######..#####. 1,6,5"))
assertEquals(10, countArrangementsOptimized("?###???????? 3,2,1"))
}
@Test
@Ignore("brute-forced")
fun part1Puzzle() {
assertEquals(7169, compute1(puzzleInput))
}
@Test
fun part2Test() {
assertEquals(1, countArrangementsOptimized("???.### 1,1,3".unfold()))
assertEquals(16384, countArrangementsOptimized(".??..??...?##. 1,1,3".unfold()))
assertEquals(1, countArrangementsOptimized("?#?#?#?#?#?#?#? 1,3,1,6".unfold()))
assertEquals(16, countArrangementsOptimized("????.#...#... 4,1,1".unfold()))
assertEquals(2500, countArrangementsOptimized("????.######..#####. 1,6,5".unfold()))
assertEquals(506250, countArrangementsOptimized("?###???????? 3,2,1".unfold()))
}
@Test
fun part2Puzzle() {
assertEquals(0, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
return input.sumOf {
countArrangements(it)
}
}
private fun compute2(input: List<String>): Long {
input.forEach {
}
return 0
}
private fun countArrangements(s: String): Int {
val (puzzle, groupSizes) = parse(s)
val puzzleArray = puzzle.toMutableList()
val variablePositions = puzzle.mapIndexedNotNull { index, c ->
if (c == '?') index else null
}
val bruteForcePermutations = 1 shl (variablePositions.size)
var arrangements = 0
println("$bruteForcePermutations permutations in... ")
val (_, duration) = measureTimedValue {
repeat(bruteForcePermutations) { iteration ->
val variableAttempt = iteration.toDotHashRepresentation(variablePositions.size)
variablePositions.forEachIndexed { attemptPosition, puzzleIndex ->
puzzleArray[puzzleIndex] = variableAttempt[attemptPosition]
}
if (isValidArrangement(puzzleArray, groupSizes)) {
arrangements++
}
}
}
println("... $duration")
return arrangements
}
private fun countArrangementsOptimized(s: String): Int {
val (puzzle, groupSizes) = parse(s)
val puzzleArray = puzzle.toMutableList()
val hashesMissing = groupSizes.sum() - puzzle.count { it == '#' }
val dotsMissing = groupSizes.size - puzzle.split("\\.+".toRegex()).count { it.isNotBlank() }
val possiblePositionsForRequiredDots = puzzle
.mapIndexedNotNull { index, c ->
if (c == '?') index else null
}
.filter { variablePos ->
if (dotsMissing > 0) {
// needed dots cannot be placed at edge of puzzle
// or next to an existing dot
val precededByDot = puzzle.getOrNull(variablePos - 1) == '.'
val followedByDot = puzzle.getOrNull(variablePos + 1) == '.'
!precededByDot && !followedByDot && variablePos != 0 && variablePos != (puzzle.length - 1)
} else {
// if the groups are already split correctly
// any variable could be a dot
true
}
}
/**
* better solution:
* - always have at least `dotsMissing` dots
* - always have at least `hashesMissing` hashes
* - permutate that
*/
val bruteForcePermutations = 1 shl (possiblePositionsForRequiredDots.size - 1)
var arrangements = 0
println("$bruteForcePermutations permutations in... ")
val (_, duration) = measureTimedValue {
repeat(bruteForcePermutations) { iteration ->
val variableAttempt = iteration.toDotHashRepresentation(possiblePositionsForRequiredDots.size)
possiblePositionsForRequiredDots.forEachIndexed { attemptPosition, puzzleIndex ->
puzzleArray[puzzleIndex] = variableAttempt[attemptPosition]
}
if (isValidArrangement(puzzleArray, groupSizes)) {
arrangements++
}
}
}
println("... $duration")
return arrangements
}
private fun isValidArrangement(puzzle: List<Char>, groupSizes: List<Int>): Boolean {
val puzzleString = puzzle.joinToString("").replace("?", "#")
val sizes = puzzleString
.split("\\.+".toRegex())
.filter { it.isNotBlank() }
.map { it.length }
val isValidArrangement = sizes == groupSizes
if (isValidArrangement) {
// printlnColor(PrintColor.GREEN, puzzleString)
} else {
// printlnColor(PrintColor.RED, puzzleString)
}
return isValidArrangement
}
private fun Int.toDotHashRepresentation(size: Int): String {
val binaryString = Integer.toBinaryString(this).padStart(size, '0')
val springString = binaryString
.replace('1', '.')
.replace('0', '#')
return springString
}
private fun parse(s: String): Pair<String, List<Int>> {
val (puzzle, groups) = s.split(" ")
val groupSizes = groups.split(",").map { it.toInt() }
return puzzle to groupSizes
}
private fun String.unfold(): String {
val (puzzle, groups) = this.split(" ")
val unfoldedPuzzle = List(5) { puzzle }.joinToString("?")
val unfoldedGroupSizes = List(5) { groups }.joinToString(",")
return "$unfoldedPuzzle $unfoldedGroupSizes"
}
}
| 0 | Kotlin | 1 | 0 | 4f06a4e1cc45ade43d00c4862782dcda2137f063 | 6,701 | aoc | Apache License 2.0 |
plugins/kotlin/compiler-plugins/assignment/maven/src/org/jetbrains/kotlin/idea/compilerPlugin/assignment/maven/AssignmentMavenProjectImportHandler.kt | ingokegel | 72,937,917 | false | null | /*
* Copyright 2010-2022 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.idea.compilerPlugin.assignment.maven
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.kotlin.assignment.plugin.AssignmentPluginNames.ANNOTATION_OPTION_NAME
import org.jetbrains.kotlin.assignment.plugin.AssignmentPluginNames.PLUGIN_ID
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath
import org.jetbrains.kotlin.idea.maven.compilerPlugin.AbstractMavenImportHandler
class AssignmentMavenProjectImportHandler : AbstractMavenImportHandler() {
private companion object {
const val ANNOTATION_PARAMETER_PREFIX = "assignment:$ANNOTATION_OPTION_NAME="
}
override val compilerPluginId = PLUGIN_ID
override val pluginName = "assignment"
override val mavenPluginArtifactName = "kotlin-maven-assignment"
override val pluginJarFileFromIdea = KotlinArtifacts.assignmentCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath()
override fun getOptions(
mavenProject: MavenProject,
enabledCompilerPlugins: List<String>,
compilerPluginOptions: List<String>
): List<PluginOption>? {
if ("assignment" !in enabledCompilerPlugins) {
return null
}
val annotations = mutableListOf<String>()
annotations.addAll(compilerPluginOptions.mapNotNull { text ->
if (!text.startsWith(ANNOTATION_PARAMETER_PREFIX)) return@mapNotNull null
text.substring(ANNOTATION_PARAMETER_PREFIX.length)
})
return annotations.map { PluginOption(ANNOTATION_OPTION_NAME, it) }
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,939 | intellij-community | Apache License 2.0 |
string-annotations/common/internal/src/main/java/com/mmolosay/stringannotations/internal/StringAnnotation.kt | mmolosay | 519,758,730 | false | null | package com.mmolosay.stringannotations.internal
import android.text.Annotation
/*
* Copyright 2022 Mikhail Malasai
*
* 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.
*/
/**
* [Annotation] which has [start] and [end] positions in terms of some string.
* It allows to work with annotation placement data without context of specific string.
*/
internal data class StringAnnotation(
val annotation: Annotation,
val start: Int,
val end: Int,
val index: Int
)
/**
* Determines if [other] annotation is "inside" `this` one.
* "Inside" means that it may be direct or inderect (nested) child.
*
* @return `true`, if [other] is inside, or `false`, if it's not or ([other] === `this`).
*/
internal fun StringAnnotation.has(other: StringAnnotation): Boolean {
val a = (this !== other) // is not the same exact object
val b = (other.start >= this.start) // other is not starting earlier
val c = (other.end <= this.end) // other is not ending later
return (a && b && c)
} | 0 | Kotlin | 0 | 1 | 8b07132f0e923768bee413a3815914043f852ea8 | 1,528 | StringAnnotations | Apache License 2.0 |
reword/src/main/java/dev/b3nedikt/reword/creator/ViewCreator.kt | B3nedikt | 230,898,085 | false | null | package dev.b3nedikt.reword.creator
import android.content.Context
import android.util.AttributeSet
import android.view.View
/**
* Creates views of type [T] given its [viewName].
*/
interface ViewCreator<out T : View> {
/**
* The name of the view of type [T] this [ViewCreator] will create.
*/
val viewName: String
/**
* Creates a view of type [T].
*
* @param context The context the view is being created in.
* @param attrs Inflation attributes as specified in XML file.
*/
fun createView(context: Context, attrs: AttributeSet?): T
} | 1 | Kotlin | 6 | 27 | 3a1334b681dc0a83b3efe01ce20ea423513ddbe1 | 591 | reword | Apache License 2.0 |
src/main/kotlin/branchandbound/api/Solution.kt | sujeevraja | 196,775,908 | false | null | package branchandbound.api
/**
* Data class to hold the solution of a branch-and-bound algorithm
*
* @property objective objective value
* @property incumbent branch and bound node corresponding to the incumbent
* @property numCreatedNodes number of nodes in the branch-and-bound algorithm
* @property numFeasibleNodes number of nodes that had a feasible LP solution
* @property maxParallelSolves maximum number of parallel solves performed by algorithm
*/
data class Solution(
val optimalityReached: Boolean,
val solvedRootNode: INode,
val upperBound: Double,
val objective: Double,
val incumbent: INode?,
val numCreatedNodes: Int,
val numFeasibleNodes: Int,
val maxParallelSolves: Int
) {
val lowerBound: Double
get() = incumbent?.mipObjective ?: -Double.MAX_VALUE
} | 2 | Kotlin | 1 | 1 | 6a2b0899aa216d2697082ceb62004b7676f26b75 | 821 | fixed-wing-drone-orienteering | MIT License |
src/main/kotlin/com/norrisboat/data/models/network/Response.kt | norrisboat | 746,358,636 | false | {"Kotlin": 51182, "HTML": 72} | package com.norrisboat.data.models.network
import kotlinx.serialization.Serializable
@Serializable
data class Response<T>(val success: Boolean, val message: String, val data: T?) | 0 | Kotlin | 2 | 3 | 2a4c6b2a62857bc4512a3bc159f56c518b8995dc | 180 | ZiuqServer | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/Autosum.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.Autosum: ImageVector
get() {
if (_autosum != null) {
return _autosum!!
}
_autosum = fluentIcon(name = "Regular.Autosum") {
fluentPath {
moveTo(5.06f, 4.46f)
arcTo(0.75f, 0.75f, 0.0f, false, true, 5.75f, 4.0f)
horizontalLineToRelative(12.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineTo(7.52f)
lineToRelative(5.36f, 5.54f)
curveToRelative(0.27f, 0.28f, 0.28f, 0.71f, 0.03f, 1.0f)
lineTo(7.38f, 18.5f)
horizontalLineToRelative(10.87f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineTo(5.75f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.57f, -1.24f)
lineToRelative(6.15f, -7.17f)
lineTo(5.2f, 5.27f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.15f, -0.81f)
close()
}
}
return _autosum!!
}
private var _autosum: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 1,387 | compose-fluent-ui | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.