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/worker/src/main/java/com/niyaj/core/worker/status/MonitorWorkManager.kt
skniyajali
644,752,474
false
{"Kotlin": 2028840}
package com.niyaj.core.worker.status import android.content.Context import androidx.work.WorkInfo import androidx.work.WorkManager import com.niyaj.core.worker.initializers.enqueueDeletionWorker import com.niyaj.core.worker.initializers.enqueueReportWorker import com.niyaj.core.worker.workers.DELETE_DATA_WORKER_TAG import com.niyaj.core.worker.workers.GENERATE_REPORT_WORKER_TAG import com.niyaj.data.utils.WorkMonitor import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.map import javax.inject.Inject class MonitorWorkManager @Inject constructor( @ApplicationContext private val context: Context, ) : WorkMonitor { private val workManager = WorkManager.getInstance(context) override val isGeneratingReport: Flow<Boolean> = workManager .getWorkInfosForUniqueWorkFlow(GENERATE_REPORT_WORKER_TAG) .map(List<WorkInfo>::anyRunning) .conflate() override val isDeletingData: Flow<Boolean> = workManager .getWorkInfosForUniqueWorkFlow(DELETE_DATA_WORKER_TAG) .map(List<WorkInfo>::anyRunning) .conflate() override fun requestGenerateReport() { workManager.enqueueReportWorker() } override fun requestDeletingData() { workManager.enqueueDeletionWorker() } } private fun List<WorkInfo>.anyRunning() = any { it.state == WorkInfo.State.RUNNING }
12
Kotlin
0
3
f068f418b7691ab2959e12ff6ec900c4bd92bfb5
1,453
PoposRoom
Apache License 2.0
feature_book/src/main/java/com/ly/book/components/XSheetDialog.kt
972223177
540,360,587
false
null
@file:Suppress("unused") package com.ly.book.components import androidx.activity.compose.BackHandler import androidx.compose.animation.* import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.unit.IntOffset import com.ly.book.utils.clickWithoutRipple import kotlin.math.roundToInt private const val DEFAULT_ANIM_DURATION = 300 /** * 弹窗 * 必须与Page级别的Composable同级,保证约束是允许填充整个屏幕 */ @Immutable class XSheetDialogProperties( val cancelable: Boolean = true, val dimAmount: Float = 0.5f, val canceledOnTouchOutside: Boolean = true ) @Composable fun TopSheetDialog( modifier: Modifier = Modifier, visible: Boolean, properties: XSheetDialogProperties = XSheetDialogProperties(), onDismissRequest: () -> Unit, content: @Composable () -> Unit ) { DialogBg( visible = visible, cancelable = properties.cancelable, dimAmount = properties.dimAmount, canceledOnTouchOutside = properties.canceledOnTouchOutside, onDismissRequest = onDismissRequest ) { AnimatedVisibility( visible = visible, enter = slideInVertically( animationSpec = tween( durationMillis = DEFAULT_ANIM_DURATION, easing = LinearOutSlowInEasing ), initialOffsetY = { -it } ), exit = slideOutVertically( animationSpec = tween( durationMillis = DEFAULT_ANIM_DURATION, easing = LinearOutSlowInEasing ), targetOffsetY = { -it } ), modifier = modifier.clickWithoutRipple { } ) { content() } } } @Composable fun BottomSheetDialog( modifier: Modifier = Modifier, visible: Boolean, properties: XSheetDialogProperties = XSheetDialogProperties(), onDismissRequest: () -> Unit, content: @Composable () -> Unit ) { DialogBg( visible = visible, cancelable = properties.cancelable, dimAmount = properties.dimAmount, canceledOnTouchOutside = properties.canceledOnTouchOutside, onDismissRequest = onDismissRequest ) { var offsetY by remember { mutableStateOf(0f) } val offsetYAnim by animateFloatAsState(targetValue = offsetY) var bottomSheetHeight by remember { mutableStateOf(0f) } DisposableEffect(visible) { onDispose { offsetY = 0f } } AnimatedVisibility( modifier = modifier.clickWithoutRipple { } .align(Alignment.BottomCenter) .offset { IntOffset(0, offsetYAnim.roundToInt()) } .onGloballyPositioned { bottomSheetHeight = it.size.height.toFloat() } .draggable(state = rememberDraggableState { offsetY = (offsetY + it.toInt()).coerceAtLeast(0f) }, orientation = Orientation.Vertical, onDragStopped = { if (properties.cancelable && offsetY > bottomSheetHeight / 2) { onDismissRequest() } else { offsetY = 0f } }), visible = visible, enter = slideInVertically( animationSpec = tween( durationMillis = DEFAULT_ANIM_DURATION, easing = LinearOutSlowInEasing, ), initialOffsetY = { it } ), exit = slideOutVertically( animationSpec = tween( durationMillis = DEFAULT_ANIM_DURATION, easing = LinearOutSlowInEasing ), targetOffsetY = { it } ) ) { content() } } } @Composable private fun DialogBg( visible: Boolean, cancelable: Boolean, dimAmount: Float, canceledOnTouchOutside: Boolean, onDismissRequest: () -> Unit, content: @Composable BoxScope.() -> Unit ) { BackHandler(enabled = visible) { if (cancelable) { onDismissRequest() } } Box(modifier = Modifier.fillMaxSize()) { AnimatedVisibility( visible = visible, enter = fadeIn( animationSpec = tween( durationMillis = DEFAULT_ANIM_DURATION, easing = LinearEasing ) ), exit = fadeOut( animationSpec = tween( durationMillis = DEFAULT_ANIM_DURATION, easing = LinearEasing ) ) ) { Box( modifier = Modifier.fillMaxSize() .background(color = Color.Black.copy(alpha = dimAmount)).clickWithoutRipple { if (canceledOnTouchOutside) { onDismissRequest() } }) } content() } }
0
Kotlin
0
0
501453c0582d24ab11d203cc1c4adb6b96b36437
6,088
BookStore
Apache License 2.0
mercado-livro/src/main/kotlin/com/mercadolivro/controller/request/PostCustomerRequest.kt
juliocarvalho2019
633,990,981
false
null
package com.mercadolivro.controller.request import com.mercadolivro.validation.EmailAvailable import javax.validation.constraints.Email import javax.validation.constraints.NotEmpty data class PostCustomerRequest ( @field:NotEmpty(message = "Campo nome não pode ser vazio!") var name: String, @field:Email(message = "Digite um e-mail válido!") @EmailAvailable var email: String )
0
Kotlin
0
0
eb2d81969ef373db05460ad93973ebb87c4701fe
400
Mercado-livro
Apache License 2.0
client/composeApp/src/commonMain/kotlin/presentation/screens/profileScreen/ProfileScreen.kt
poetofcode
782,463,531
false
{"Kotlin": 93235, "JavaScript": 30142, "Handlebars": 4184, "CSS": 2731, "Dockerfile": 197}
package presentation.screens.profileScreen import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.Button import androidx.compose.material.OutlinedButton import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import presentation.Tabs import presentation.navigation.BaseScreen import presentation.navigation.HideBottomSheetEffect import presentation.navigation.ShowModalBottomSheetEffect import presentation.navigation.postSideEffect class ProfileScreen : BaseScreen<ProfileViewModel>() { override val screenId: String get() = Tabs.PROFILE.key override val viewModel: ProfileViewModel get() = viewModelStore.getViewModel<ProfileViewModel>() override val isMenuVisible: Boolean = true val state get() = viewModel.state.value @Composable override fun Content() { val isAuth = state.profile != null // MaterialTheme { Column { TopAppBar( title = { Text(text = "Профиль") }, navigationIcon = {}, actions = { // if (readyState !is LoadingResource) { // IconButton(onClick = { // viewModel.fetchFeed() // }) { // Icon( // imageVector = Icons.Default.Refresh, // contentDescription = "Reload", // ) // } // } } ) Box(modifier = Modifier.fillMaxWidth().weight(1f)) { if (!isAuth) { UnsignedProfile() } else { SignedProfile() } } } } // } @Composable fun UnsignedProfile() { Box(Modifier.fillMaxSize()) { Column(Modifier.wrapContentSize().align(Alignment.Center)) { Text( text = "Войдите в аккаунт, чтобы получить доступ ко всем функциям приложения", color = Color.Gray, modifier = Modifier.align(Alignment.CenterHorizontally) ) Button( modifier = Modifier.align(Alignment.CenterHorizontally) .padding(vertical = 30.dp), onClick = { viewModel.onSignInToAccountButtonClick() } ) { Text(text = "Войти в аккаунт") } } } } @Composable fun SignedProfile() { Box(Modifier.fillMaxSize()) { Column(Modifier.wrapContentSize().align(Alignment.Center)) { Row(modifier = Modifier.align(Alignment.CenterHorizontally)) { Text( text = "Вы авторизованы", color = Color.Gray, ) Text( text = state.profile?.email.orEmpty(), color = Color.Black, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 6.dp), ) } ClickableItem( modifier = Modifier.fillMaxWidth().padding(10.dp), text = "Выйти из аккаунта" ) { postSideEffect(ShowModalBottomSheetEffect { ConfirmContent() }) } } } } @Composable fun ConfirmContent() { Column( Modifier.fillMaxWidth().padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text("Вы действительно хотите выйти из аккаунта?") Row(Modifier.padding(top = 16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) { OutlinedButton( modifier = Modifier, onClick = { postSideEffect(HideBottomSheetEffect) } ) { Text(text = "Отмена") } Button( modifier = Modifier, onClick = { viewModel.onConfirmQuit() } ) { Text(text = "Да") } } } } @Composable fun ClickableItem(modifier: Modifier = Modifier, text: String, onClick: () -> Unit) { Box(modifier.clickable { onClick() }.fillMaxWidth().padding(10.dp)) { Text( text = text, color = Color.Black, textDecoration = TextDecoration.Underline, modifier = Modifier.align(Alignment.Center), ) } } }
0
Kotlin
0
0
f95c52c0a35c2af9ccf077917b547406de5c4f83
5,834
sprout
Apache License 2.0
travako-core/travako-core-adapter/travako-core-adapter-leader/src/main/java/io/arkitik/travako/adapter/leader/creator/LeaderCreatorImpl.kt
arkitik
441,685,610
false
{"Kotlin": 322279, "Shell": 91}
package io.arkitik.travako.adapter.leader.creator import io.arkitik.radix.develop.store.creator.StoreIdentityCreator import io.arkitik.travako.core.domain.leader.LeaderDomain import io.arkitik.travako.core.domain.runner.SchedulerRunnerDomain import io.arkitik.travako.core.domain.server.ServerDomain import io.arkitik.travako.entity.leader.TravakoLeader import io.arkitik.travako.entity.runner.TravakoSchedulerRunner import io.arkitik.travako.entity.server.TravakoServer import io.arkitik.travako.store.leader.creator.LeaderCreator import java.util.* /** * Created By [*<NAME> *](https://www.linkedin.com/in/iloom/) * Created At 28 12:57 AM, **Tue, December 2021** * Project *travako* [arkitik.io](https://arkitik.io) */ class LeaderCreatorImpl : LeaderCreator { private lateinit var server: ServerDomain private lateinit var runner: SchedulerRunnerDomain private var uuid: String = UUID.randomUUID().toString().replace("-", "") override fun ServerDomain.server(): LeaderCreator { server = this return this@LeaderCreatorImpl } override fun SchedulerRunnerDomain.runner(): LeaderCreator { runner = this return this@LeaderCreatorImpl } override fun String.uuid(): StoreIdentityCreator<String, LeaderDomain> { uuid = this return this@LeaderCreatorImpl } override fun create(): LeaderDomain { return TravakoLeader( uuid = uuid, server = server as TravakoServer, runner = runner as TravakoSchedulerRunner ) } }
1
Kotlin
0
3
913e9b17c479329022dd67f77d35efe1300877c5
1,561
travako
Apache License 2.0
plugins/kotlin/idea/tests/testData/intentions/convertBlockCommentToLineComment/simple.kt
ingokegel
72,937,917
true
null
// AFTER-WARNING: Variable 'foo' is never used fun test() { /* comment1 comment2 comment3 */<caret> val foo = 1 }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
144
intellij-community
Apache License 2.0
src/test/kotlin/com/roscopeco/jasm/asserts/MemberAssert.kt
roscopeco
487,298,845
false
{"Gradle Kotlin DSL": 2, "Markdown": 5, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Java": 40, "Kotlin": 62, "ANTLR": 2, "YAML": 1}
/* * Copyright (c)2022 <NAME> & Contributors * * Licensed under the MIT license. See LICENSE.md for details. */ package com.roscopeco.jasm.asserts import com.roscopeco.jasm.antlr.JasmParser.MemberContext import org.assertj.core.api.AbstractAssert class MemberAssert internal constructor(actual: MemberContext) : AbstractAssert<MemberAssert, MemberContext>(actual, MemberAssert::class.java) { fun isField(): FieldAssert { isNotNull if (actual!!.field() == null) { failWithMessage("Expected member to be a field, but it is not - it is " + actual.text) } return FieldAssert(actual.field()) } fun isMethod(): MethodAssert { isNotNull if (actual!!.method() == null) { failWithMessage("Expected member to be a method, but it is not - it is " + actual.text) } return MethodAssert(actual.method()) } }
3
Java
13
426
1196bfc641a33eb8b701d4bd0c87dcd0ce1d0d47
913
jasm
MIT License
dashboard/dashboard_domain/src/main/java/com/nstudiosappdev/stocker/dashboard/domain/DeleteCurrencyInteractor.kt
harrunisk
186,485,023
false
null
package com.nstudiosappdev.stocker.dashboard.domain import com.nstudiosappdev.core.coroutines.AsyncManager import com.nstudiosappdev.core.domain.BaseInteractor import com.nstudiosappdev.core.domain.Interactor import com.nstudiosappdev.core.error.ErrorFactory import com.nstudiosappdev.core.injection.modules.CoroutineManagerModule import com.nstudiosappdev.core.model.DataHolder import javax.inject.Inject import javax.inject.Named import kotlinx.coroutines.Deferred class DeleteCurrencyInteractor @Inject constructor( private val currenciesRepository: CurrenciesRepository, private val errorFactory: ErrorFactory, @Named(CoroutineManagerModule.AM_NAME_INTERACTOR) asyncManager: AsyncManager ) : BaseInteractor(asyncManager), Interactor.DeferredInteractor<DeleteCurrencyInteractor.Params, Boolean> { override suspend fun executeAsync(postParams: Params): Deferred<DataHolder<Boolean>> = handleAsync { return@handleAsync when (val response = currenciesRepository.deleteCurrency( postParams.bankName, postParams.currencyType ).await()) { is DataHolder.Success -> DataHolder.Success(response.data) else -> DataHolder.Fail(errorFactory.createUnknownError()) } } class Params( val bankName: String, val currencyType: String ) : Interactor.Params() }
0
null
6
37
dca907383ca09c86c6a81b06820ef7ace3e45a5c
1,366
Stocker
MIT License
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/datatypes/VimString.kt
JetBrains
1,459,486
false
null
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.datatypes import java.util.* public data class VimString(val value: String) : VimDataType() { // todo refactoring override fun asDouble(): Double { val text: String = value.lowercase(Locale.getDefault()) val intString = StringBuilder() if (text.startsWith("0x")) { var i = 2 while (i < text.length && (text[i].isDigit() || text[i] in 'a'..'f')) { intString.append(text[i]) ++i } return if (intString.isEmpty()) 0.0 else Integer.parseInt(intString.toString(), 16).toDouble() } else if (text.startsWith("-0x")) { var i = 3 while (i < text.length && (text[i].isDigit() || text[i] in 'a'..'f')) { intString.append(text[i]) ++i } return if (intString.isEmpty()) 0.0 else -Integer.parseInt(intString.toString(), 16).toDouble() } else if (text.startsWith("0")) { var i = 1 while (i < text.length && text[i].isDigit()) { intString.append(text[i]) ++i } return if (intString.isEmpty()) 0.0 else Integer.parseInt(intString.toString(), 8).toDouble() } else if (text.startsWith("-0")) { var i = 2 while (i < text.length && text[i].isDigit()) { intString.append(text[i]) ++i } return if (intString.isEmpty()) 0.0 else -Integer.parseInt(intString.toString(), 8).toDouble() } else if (text.startsWith("-")) { var i = 1 while (i < text.length && text[i].isDigit()) { intString.append(text[i]) ++i } return if (intString.isEmpty()) 0.0 else -Integer.parseInt(intString.toString()).toDouble() } else { var i = 0 while (i < text.length && text[i].isDigit()) { intString.append(text[i]) ++i } return if (intString.isEmpty()) 0.0 else Integer.parseInt(intString.toString()).toDouble() } } override fun asString(): String { return value } override fun toVimNumber(): VimInt = VimInt(this.value) override fun toString(): String { return value } override fun deepCopy(level: Int): VimString { return copy() } override fun lockVar(depth: Int) { this.isLocked = true } override fun unlockVar(depth: Int) { this.isLocked = false } public companion object { public val EMPTY: VimString = VimString("") } }
8
null
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
2,576
ideavim
MIT License
kzen-auto-common/src/commonMain/kotlin/tech/kzen/auto/common/paradigm/dataflow/model/structure/cell/EdgeDirection.kt
alexoooo
131,353,826
false
null
package tech.kzen.auto.common.paradigm.dataflow.model.structure.cell enum class EdgeDirection( val rowOffset: Int, val columnOffset: Int ) { Top(-1, 0), Right(0, 1), Bottom(1, 0), Left(0, -1); fun reverse(): EdgeDirection { return when (this) { Top -> Bottom Right -> Left Bottom -> Top Left -> Right } } }
1
Kotlin
1
1
ffdd5bb5dcc541b884d887a01d7dbbf1d506b610
481
kzen-auto
MIT License
jipp-pdl/src/main/kotlin/com/hp/jipp/pdl/pwg/PwgHeader.kt
HPInc
129,298,798
false
null
// Copyright 2018 HP Development Company, L.P. // SPDX-License-Identifier: MIT package com.hp.jipp.pdl.pwg import java.io.DataInputStream import java.io.DataOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream /** * All elements of a PWG Raster header as described in section 4.3 of * [PWG-5102.4](https://ftp.pwg.org/pub/pwg/candidates/cs-ippraster10-20120420-5102.4.pdf). */ @Suppress("MagicNumber") data class PwgHeader( val mediaColor: String = "", val mediaType: String = "", val printContentOptimize: String = "", val cutMedia: When = When.Never, /** True if printing two-sided. */ val duplex: Boolean = false, val hwResolutionX: Int, val hwResolutionY: Int, val insertSheet: Boolean = false, val jog: When = When.Never, val leadingEdge: Edge = Edge.ShortEdgeFirst, val mediaPosition: MediaPosition = MediaPosition.Auto, val mediaWeightMetric: Int = 0, val numCopies: Int = 0, val orientation: Orientation = Orientation.Portrait, /** Media width in points. */ val pageSizeX: Int = 0, /** Media height in points. */ val pageSizeY: Int = 0, /** True if two-sided printing should be flipped along the short-edge. */ val tumble: Boolean = false, /** Full-bleed page width in pixels. */ val width: Int, /** Full-bleed page height in pixels. */ val height: Int, val bitsPerColor: Int, val bitsPerPixel: Int, val colorOrder: ColorOrder = ColorOrder.Chunky, val colorSpace: ColorSpace, val totalPageCount: Int = 0, val crossFeedTransform: Int = 1, val feedTransform: Int = 1, /** Left position of non-blank area in pixels, if image box is known. */ val imageBoxLeft: Int = 0, /** Top position of non-blank area in pixels, if image box is known. */ val imageBoxTop: Int = 0, /** Right position of non-blank area in pixels, if image box is known. */ val imageBoxRight: Int = 0, /** Bottom position of non-blank area in pixels, if image box is known. */ val imageBoxBottom: Int = 0, /** An sRGB color field containing 24 bits of color data. Default: WHITE */ val alternatePrimary: Int = WHITE, val printQuality: PrintQuality = PrintQuality.Default, /** USB vendor identification number or 0. */ val vendorIdentifier: Int = 0, /** Octets containing 0-1088 bytes of vendor-specific data. */ val vendorData: ByteArray = byteArrayOf(), val renderingIntent: String = "", val pageSizeName: String = "" ) { /** Number of bytes per line, always based on [width] and [bitsPerPixel]. */ val bytesPerLine: Int = ((bitsPerPixel * width + 7) / 8) /** Number of colors supported. */ val numColors: Int = bitsPerPixel / bitsPerColor /** PackBits object used for encoding/decoding pixels of data. */ val packBits = PackBits(bytesPerPixel = bitsPerPixel / PwgSettings.BITS_PER_BYTE, pixelsPerLine = width) init { if (vendorData.size > MAX_VENDOR_DATA_SIZE) { throw IllegalArgumentException("vendorData.size of ${vendorData.size} must not be > $MAX_VENDOR_DATA_SIZE") } } /** Something that has an integer value. */ interface HasValue { val value: Int } /** Converts from an integer value to a T. */ interface ValueConverter<T : HasValue> { fun from(value: Int): T } /** Points during print when another operation should take place. */ enum class When(override val value: Int) : HasValue { Never(0), AfterDocument(1), AfterJob(2), AfterSet(3), AfterPage(4); companion object : ValueConverter<When> { override fun from(value: Int) = values().firstOrNull { it.value == value } ?: Never } } /** Kinds of duplexing. */ enum class Edge(override val value: Int) : HasValue { ShortEdgeFirst(0), LongEdgeFirst(1); companion object : ValueConverter<Edge> { override fun from(value: Int) = values().firstOrNull { it.value == value } ?: ShortEdgeFirst } } /** Output orientation of a page. */ enum class Orientation(override val value: Int) : HasValue { Portrait(0), Landscape(1), ReversePortrait(2), ReverseLandscape(3); companion object : ValueConverter<Orientation> { override fun from(value: Int) = values().firstOrNull { it.value == value } ?: Portrait } } enum class ColorOrder(override val value: Int) : HasValue { Chunky(0); companion object : ValueConverter<ColorOrder> { override fun from(value: Int) = values().firstOrNull { it.value == value } ?: Chunky } } /** Meaning of color values provided for each pixel. */ enum class ColorSpace(override val value: Int) : HasValue { Rgb(1), Black(3), Cmyk(6), Sgray(18), Srgb(19), AdobeRgb(20), Device1(48), Device2(49), Device3(50), Device4(51), Device5(52), Device6(53), Device7(54), Device8(55), Device9(56), Device10(57), Device11(58), Device12(59), Device13(60), Device14(61), Device15(62); /** Return the [com.hp.jipp.pdl.ColorSpace] corresponding to this one or throw if no match. */ fun toPdlColorSpace() = when (this) { Rgb, Srgb -> com.hp.jipp.pdl.ColorSpace.Rgb Sgray -> com.hp.jipp.pdl.ColorSpace.Grayscale else -> throw IOException("No conversion available for $this") } companion object : ValueConverter<ColorSpace> { override fun from(value: Int) = values().firstOrNull { it.value == value } ?: Srgb /** Given a [com.hp.jipp.pdl.ColorSpace] return the corresponding [PwgHeader.ColorSpace]. */ fun from(from: com.hp.jipp.pdl.ColorSpace) = when (from) { com.hp.jipp.pdl.ColorSpace.Rgb -> Srgb com.hp.jipp.pdl.ColorSpace.Grayscale -> Sgray else -> throw IOException("No conversion available for $from") } } } /** Media input source. */ enum class MediaPosition(override val value: Int) : HasValue { Auto(0), Main(1), Alternate(2), LargeCapacity(3), Manual(4), Envelope(5), Disc(6), Photo(7), Hagaki(8), MainRoll(9), AlternateRoll(10), Top(11), Middle(12), Bottom(13), Side(14), Left(15), Right(16), Center(17), Rear(18), ByPassTray(19), Tray1(20), Tray2(21), Tray3(22), Tray4(23), Tray5(24), Tray6(25), Tray7(26), Tray8(27), Tray9(28), Tray10(29), Tray11(30), Tray12(31), Tray13(32), Tray14(33), Tray15(34), Tray16(35), Tray17(36), Tray18(37), Tray19(38), Tray20(39), Roll1(40), Roll2(41), Roll3(42), Roll4(43), Roll5(44), Roll6(45), Roll7(46), Roll8(47), Roll9(48), Roll10(49); companion object : ValueConverter<MediaPosition> { override fun from(value: Int) = values().firstOrNull { it.value == value } ?: Auto } } /** Requested output quality. */ enum class PrintQuality(override val value: Int) : HasValue { Default(0), Draft(3), Normal(4), High(5); companion object : ValueConverter<PrintQuality> { override fun from(value: Int) = values().firstOrNull { it.value == value } ?: Default } } /** Writes a PWG header containing exactly 1796 octets. */ fun write(output: OutputStream) { ((output as? DataOutputStream) ?: DataOutputStream(output)).apply { writeCString(PWG_RASTER_NAME) // Always the same writeCString(mediaColor) writeCString(mediaType) writeCString(printContentOptimize) writeReserved(12) writeInt(cutMedia) writeInt(duplex) writeInt(hwResolutionX) writeInt(hwResolutionY) writeReserved(16) writeInt(insertSheet) writeInt(jog) writeInt(leadingEdge) writeReserved(12) writeInt(mediaPosition) writeInt(mediaWeightMetric) writeReserved(8) writeInt(numCopies) writeInt(orientation) writeReserved(4) writeInt(pageSizeX) writeInt(pageSizeY) writeReserved(8) writeInt(tumble) writeInt(width) writeInt(height) writeReserved(4) writeInt(bitsPerColor) writeInt(bitsPerPixel) writeInt(bytesPerLine) writeInt(colorOrder) writeInt(colorSpace) writeReserved(16) writeInt(numColors) writeReserved(28) writeInt(totalPageCount) writeInt(crossFeedTransform) writeInt(feedTransform) writeInt(imageBoxLeft) writeInt(imageBoxTop) writeInt(imageBoxRight) writeInt(imageBoxBottom) writeInt(alternatePrimary) writeInt(printQuality) writeReserved(20) writeInt(vendorIdentifier) writeInt(vendorData.size) write(vendorData, 0, vendorData.size) // Pad with 0 writeReserved(MAX_VENDOR_DATA_SIZE - vendorData.size) writeReserved(64) writeCString(renderingIntent) writeCString(pageSizeName) } } @Suppress("ComplexMethod") override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PwgHeader if (mediaColor != other.mediaColor) return false if (mediaType != other.mediaType) return false if (printContentOptimize != other.printContentOptimize) return false if (cutMedia != other.cutMedia) return false if (duplex != other.duplex) return false if (hwResolutionX != other.hwResolutionX) return false if (hwResolutionY != other.hwResolutionY) return false if (insertSheet != other.insertSheet) return false if (jog != other.jog) return false if (leadingEdge != other.leadingEdge) return false if (mediaPosition != other.mediaPosition) return false if (mediaWeightMetric != other.mediaWeightMetric) return false if (numCopies != other.numCopies) return false if (orientation != other.orientation) return false if (pageSizeX != other.pageSizeX) return false if (pageSizeY != other.pageSizeY) return false if (tumble != other.tumble) return false if (width != other.width) return false if (height != other.height) return false if (bitsPerColor != other.bitsPerColor) return false if (bitsPerPixel != other.bitsPerPixel) return false if (colorOrder != other.colorOrder) return false if (colorSpace != other.colorSpace) return false if (totalPageCount != other.totalPageCount) return false if (crossFeedTransform != other.crossFeedTransform) return false if (feedTransform != other.feedTransform) return false if (imageBoxLeft != other.imageBoxLeft) return false if (imageBoxTop != other.imageBoxTop) return false if (imageBoxRight != other.imageBoxRight) return false if (imageBoxBottom != other.imageBoxBottom) return false if (alternatePrimary != other.alternatePrimary) return false if (printQuality != other.printQuality) return false if (vendorIdentifier != other.vendorIdentifier) return false if (!vendorData.contentEquals(other.vendorData)) return false if (renderingIntent != other.renderingIntent) return false if (pageSizeName != other.pageSizeName) return false return true } override fun hashCode(): Int { var result = mediaColor.hashCode() result = 31 * result + mediaType.hashCode() result = 31 * result + printContentOptimize.hashCode() result = 31 * result + cutMedia.hashCode() result = 31 * result + duplex.hashCode() result = 31 * result + hwResolutionX result = 31 * result + hwResolutionY result = 31 * result + insertSheet.hashCode() result = 31 * result + jog.hashCode() result = 31 * result + leadingEdge.hashCode() result = 31 * result + mediaPosition.hashCode() result = 31 * result + mediaWeightMetric result = 31 * result + numCopies result = 31 * result + orientation.hashCode() result = 31 * result + pageSizeX result = 31 * result + pageSizeY result = 31 * result + tumble.hashCode() result = 31 * result + width result = 31 * result + height result = 31 * result + bitsPerColor result = 31 * result + bitsPerPixel result = 31 * result + colorOrder.hashCode() result = 31 * result + colorSpace.hashCode() result = 31 * result + totalPageCount result = 31 * result + crossFeedTransform result = 31 * result + feedTransform result = 31 * result + imageBoxLeft result = 31 * result + imageBoxTop result = 31 * result + imageBoxRight result = 31 * result + imageBoxBottom result = 31 * result + alternatePrimary result = 31 * result + printQuality.hashCode() result = 31 * result + vendorIdentifier result = 31 * result + vendorData.contentHashCode() result = 31 * result + renderingIntent.hashCode() result = 31 * result + pageSizeName.hashCode() return result } companion object { const val PWG_RASTER_NAME = "PwgRaster" const val MAX_VENDOR_DATA_SIZE = 1088 const val HEADER_SIZE = 1796 const val WHITE = 0xFFFFFF private const val CSTRING_LENGTH = 64 /** * Read the input stream to construct a PwgHeader, throwing [IOException] if input data is invalid. * * The input stream MUST contain 1796 octets. It MAY contain invalid enums (which will be silently converted * to default values). */ @Suppress("ComplexMethod") fun read(input: InputStream): PwgHeader = ((input as? DataInputStream) ?: DataInputStream(input)).run { // Discard the initial PwgRaster string readCString().also { if (it != PWG_RASTER_NAME) throw IOException("Header $it is not $PWG_RASTER_NAME") } // Read everything parameter-by-parameter PwgHeader( mediaColor = readCString(), mediaType = readCString(), printContentOptimize = readCString().also { skip(12) }, cutMedia = readValue(When), duplex = readInt().toBoolean(), hwResolutionX = readInt(), hwResolutionY = readInt().also { skip(16) }, insertSheet = readInt().toBoolean(), jog = readValue(When), leadingEdge = readValue(Edge).also { skip(12) }, mediaPosition = readValue(MediaPosition), mediaWeightMetric = readInt().also { skip(8) }, numCopies = readInt(), orientation = readValue(Orientation).also { skip(4) }, pageSizeX = readInt(), pageSizeY = readInt().also { skip(8) }, tumble = readInt().toBoolean(), width = readInt(), height = readInt().also { skip(4) }, bitsPerColor = readInt(), bitsPerPixel = readInt().also { skip(4) // bytesPerLine (ignore) }, colorOrder = readValue(ColorOrder), colorSpace = readValue(ColorSpace).also { skip(16) skip(4) // numColors (ignore) skip(28) // Space after numColors }, totalPageCount = readInt(), crossFeedTransform = readInt(), feedTransform = readInt(), imageBoxLeft = readInt(), imageBoxTop = readInt(), imageBoxRight = readInt(), imageBoxBottom = readInt(), alternatePrimary = readInt(), printQuality = readValue(PrintQuality).also { skip(20) }, vendorIdentifier = readInt(), vendorData = ByteArray(readInt()).also { read(it) skip(64L + (1088 - it.size)) }, renderingIntent = readCString(), pageSizeName = readCString() ) } /** * Write 0-bytes into the output string, [bytes] long. */ private fun DataOutputStream.writeReserved(bytes: Int) { write(ByteArray(bytes)) } /** * Write the specified string, up to [width] bytes, zero-padded to exactly [width]. */ private fun DataOutputStream.writeCString(string: String) { val bytes = string.toByteArray() write(bytes, 0, Math.min(CSTRING_LENGTH, bytes.size)) writeReserved(CSTRING_LENGTH - bytes.size) } /** * Write an enum value object. */ private fun DataOutputStream.writeInt(hasValue: HasValue) { writeInt(hasValue.value) } /** * Read a zero-padded fixed-width string */ private fun DataInputStream.readCString() = ByteArray(CSTRING_LENGTH).let { read(it) String(it).split('\u0000')[0] } /** * Convert back to an enum value object. */ private fun <T : HasValue> DataInputStream.readValue(converter: ValueConverter<T>): T = converter.from(readInt()) /** * A regular writeBoolean only writes one byte. But PWG is very thorough and uses four bytes to encode a * single true/false bit. */ private fun DataOutputStream.writeInt(value: Boolean) { writeInt(if (value) 1 else 0) } private fun Int.toBoolean() = this != 0 } }
7
null
40
99
f1f96d5da88d24197e7b0f90eec4ceee0fe66550
18,414
jipp
MIT License
app/src/main/java/com/reggar/todomvp/feature/main/adapter/AdapterConstants.kt
REggar
101,867,587
false
null
package com.reggar.todomvp.feature.main.adapter object AdapterConstants { val TODO = 1 val HEADER = 2 }
0
Kotlin
0
0
fb091a629e7b374facbc3c04e4a782f5c05d6be2
112
TodoMVP
Apache License 2.0
Common/src/main/java/at/petrak/hexcasting/common/casting/actions/rw/OpWrite.kt
FallingColors
441,721,272
false
null
package at.petrak.hexcasting.common.casting.actions.rw import at.petrak.hexcasting.api.addldata.ADIotaHolder import at.petrak.hexcasting.api.casting.RenderedSpell import at.petrak.hexcasting.api.casting.castables.SpellAction import at.petrak.hexcasting.api.casting.eval.CastingEnvironment import at.petrak.hexcasting.api.casting.iota.Iota import at.petrak.hexcasting.api.casting.mishaps.MishapBadOffhandItem import at.petrak.hexcasting.api.casting.mishaps.MishapOthersName import at.petrak.hexcasting.xplat.IXplatAbstractions import net.minecraft.world.item.ItemStack // we make this a spell cause imo it's a little ... anticlimactic for it to just make no noise object OpWrite : SpellAction { override val argc = 1 override fun execute( args: List<Iota>, ctx: CastingEnvironment ): SpellAction.Result { val datum = args[0] val (handStack, hand) = ctx.getHeldItemToOperateOn { val datumHolder = IXplatAbstractions.INSTANCE.findDataHolder(it) datumHolder != null && datumHolder.writeIota(datum, true) } ?: throw MishapBadOffhandItem.of(ItemStack.EMPTY.copy(), null, "iota.write") // TODO: hack val datumHolder = IXplatAbstractions.INSTANCE.findDataHolder(handStack) ?: throw MishapBadOffhandItem.of(handStack, hand, "iota.write") if (!datumHolder.writeIota(datum, true)) throw MishapBadOffhandItem.of(handStack, hand, "iota.readonly", datum.display()) val trueName = MishapOthersName.getTrueNameFromDatum(datum, ctx.caster) if (trueName != null) throw MishapOthersName(trueName) return SpellAction.Result( Spell(datum, datumHolder), 0, listOf() ) } private data class Spell(val datum: Iota, val datumHolder: ADIotaHolder) : RenderedSpell { override fun cast(ctx: CastingEnvironment) { datumHolder.writeIota(datum, false) } } }
173
null
86
97
1aa53ca97faebc7e8fcca3215c58239ab35ad428
1,971
HexMod
MIT License
app/src/main/java/com/example/walletease/components/SplitComponent/dataclasses/Payment.kt
yigitozman
794,238,533
false
{"Kotlin": 135388, "JavaScript": 2539}
package com.example.walletease.components.SplitComponent.dataclasses data class Payment( val description: String, val amount: Double, val excludedParticipants: List<String> = listOf() )
0
Kotlin
0
1
7211f0ddc31c65e2b76272bfc488c1944b956539
198
WalletEase
MIT License
k9mail/src/main/java/com/fsck/k9/ui/settings/KoinModule.kt
robopsi
134,199,306
true
{"Git Config": 1, "Gradle": 8, "INI": 2, "Shell": 4, "Text": 5, "Ignore List": 4, "Batchfile": 1, "Git Attributes": 1, "YAML": 1, "Markdown": 7, "XML": 335, "SVG": 63, "PostScript": 1, "Java": 637, "AIDL": 2, "Java Properties": 1, "Kotlin": 68, "Proguard": 1, "E-mail": 8, "HTML": 1}
package com.fsck.k9.ui.settings import com.fsck.k9.helper.FileBrowserHelper import com.fsck.k9.helper.NamedThreadFactory import com.fsck.k9.ui.account.AccountsLiveData import com.fsck.k9.ui.settings.general.GeneralSettingsDataStore import org.koin.android.architecture.ext.viewModel import org.koin.dsl.module.applicationContext import java.util.concurrent.Executors val settingsUiModule = applicationContext { bean { AccountsLiveData(get()) } viewModel { SettingsViewModel(get()) } bean { FileBrowserHelper.getInstance() } bean { GeneralSettingsDataStore(get(), get(), get("GeneralSettingsExecutor")) } bean("GeneralSettingsExecutor") { Executors.newSingleThreadExecutor(NamedThreadFactory("GeneralSettingsDataStore")) } }
0
Java
1
0
8521e39e99dac6dd4744712daf7ede27092a4a67
758
k-9
Apache License 2.0
src/me/anno/ui/base/groups/PanelFlipper.kt
AntonioNoack
456,513,348
false
null
package me.anno.ui.base.groups import me.anno.Engine import me.anno.ecs.annotations.Range import me.anno.ecs.prefab.PrefabSaveable import me.anno.input.Input import me.anno.maths.Maths import me.anno.maths.Maths.length import me.anno.maths.Maths.mix import me.anno.ui.Panel import me.anno.ui.style.Style import kotlin.math.* // todo test it // like ViewFlipper in Android open class PanelFlipper(sorter: Comparator<Panel>?, style: Style) : PanelList(sorter, style) { constructor(style: Style) : this(null, style) enum class TransitionType(val swipeXAxis: Boolean, val swipeYAxis: Boolean) { INSTANT(true, true), SWIPE_HORIZONTAL(true, false), SWIPE_VERTICAL(false, true), ROTATE_HORIZONTAL(true, false), // todo requires perspective/skewed drawing of UI, needs to be implemented ROTATE_VERTICAL(false, true) // we could add a few more animations // todo implement them all } var transitionType = TransitionType.SWIPE_HORIZONTAL var useLeftMouseButton = true var useRightMouseButton = true var useMouseWheel = false // allows the user to turn farther than possible for a spring like effect, [0,1] @Range(0.0, 1.0) var leftBounce = 0f @Range(0.0, 1.0) var rightBounce = 0f var position = 0f var targetPosition = 0f @Range(0.0, Double.POSITIVE_INFINITY) var smoothingPerSeconds = 3f override fun calculateSize(w: Int, h: Int) { super.calculateSize(w, h) minW = 0 minH = 0 for (child in children) { child.calculateSize(w, h) minW = max(minW, child.minW) minH = max(minH, child.minH) } } fun updatePosition() { val oldPosition = position position = mix(position, targetPosition, Maths.dtTo01(Engine.deltaTime * smoothingPerSeconds)) if (abs(position - oldPosition) > 1e-4) { invalidateDrawing() } // if not is controller down, then clamp targetPosition smoothly into an integer value val correction = if ((Input.isLeftDown && useLeftMouseButton) || (Input.isRightDown && useRightMouseButton)) 0f else if (useMouseWheel) (abs(Engine.gameTime - lastMouseWheel) * 1e-9f) else 1f if (correction > 0f) { val int = round(targetPosition) targetPosition = mix(targetPosition, int, Engine.deltaTime * smoothingPerSeconds) } } private fun swipe(dt: Float) { if (dt == 0f) return val oldPosition = targetPosition.roundToInt() invalidateDrawing() val newPosition = targetPosition.roundToInt() if (oldPosition != newPosition) { invalidateLayout() } } override fun setPosition(x: Int, y: Int) { super.setPosition(x, y) when (transitionType) { TransitionType.INSTANT -> { val posIndex = position.roundToInt() for ((index, child) in children.withIndex()) { if (index == posIndex) { child.setPosSize(x, y, w, h) } else { child.setPosSize(x, y, 0, 0) } } } TransitionType.SWIPE_HORIZONTAL, TransitionType.ROTATE_HORIZONTAL -> { for ((index, child) in children.withIndex()) { val offset = (w * (position - index)).roundToInt() child.setPosSize(x + offset, y, w, h) } } TransitionType.SWIPE_VERTICAL, TransitionType.ROTATE_VERTICAL -> { for ((index, child) in children.withIndex()) { val offset = (h * (position - index)).roundToInt() child.setPosSize(x, y + offset, w, h) } } } } // if they are overlapping, we need to redraw the others as well override fun capturesChildEvents(lx0: Int, ly0: Int, lx1: Int, ly1: Int): Boolean { return false // not really, I think... // todo ok so? // return children.count { it.visibility == Visibility.VISIBLE } > 1 } override fun onDraw(x0: Int, y0: Int, x1: Int, y1: Int) { updatePosition() setPosition(x, y) super.onDraw(x0, y0, x1, y1) } override fun onMouseMoved(x: Float, y: Float, dx: Float, dy: Float) { if ((Input.isLeftDown && useLeftMouseButton) || (Input.isRightDown && useRightMouseButton)) { val type = transitionType val ws = windowStack val dt = (if (type.swipeXAxis) dx / min(w, ws.width) else 0f) + (if (type.swipeYAxis) dy / min(h, ws.height) else 0f) swipe(dt) if (!type.swipeXAxis || !type.swipeYAxis) { super.onMouseMoved(x, y, if (type.swipeXAxis) 0f else dx, if (type.swipeYAxis) 0f else dy) } } else super.onMouseMoved(x, y, dx, dy) } private var lastMouseWheel = 0L override fun onMouseWheel(x: Float, y: Float, dx: Float, dy: Float, byMouse: Boolean) { if (useMouseWheel) { swipe(dx + dy) if (length(dx, dy) > 1e-3f) lastMouseWheel = Engine.gameTime } else super.onMouseWheel(x, y, dx, dy, byMouse) } override fun clone(): PanelFlipper { val clone = PanelFlipper(sorter, style) copyInto(clone) return clone } override fun copyInto(dst: PrefabSaveable) { super.copyInto(dst) dst as PanelFlipper dst.transitionType = transitionType dst.useLeftMouseButton = useLeftMouseButton dst.useRightMouseButton = useRightMouseButton dst.useMouseWheel = useMouseWheel dst.position = position dst.targetPosition = targetPosition dst.smoothingPerSeconds = smoothingPerSeconds dst.leftBounce = leftBounce dst.rightBounce = rightBounce } override val className: String get() = "PanelFlipper" }
0
Kotlin
3
9
b2532f7d40527eb2c9e24e3659dd904aa725a1aa
6,031
RemsEngine
Apache License 2.0
ktor-io/common/src/io/ktor/utils/io/core/Input.kt
ktorio
40,136,600
false
null
package io.ktor.utils.io.core import io.ktor.utils.io.bits.* import io.ktor.utils.io.core.internal.* import io.ktor.utils.io.pool.* /** * Usually shouldn't be implemented directly. Inherit [Input] instead. */ public abstract class Input( head: ChunkBuffer = ChunkBuffer.Empty, remaining: Long = head.remainingAll(), public val pool: ObjectPool<ChunkBuffer> = ChunkBuffer.Pool ) : Closeable { /** * It is `true` when it is known that no more bytes will be available. When it is `false` then this means that * it is not known yet or there are available bytes. * Please note that `false` value doesn't guarantee that there are available bytes so `readByte()` may fail. */ public val endOfInput: Boolean get() = headRemaining == 0 && tailRemaining == 0L && (noMoreChunksAvailable || doFill() == null) /** * Read the next bytes into the [destination] starting at [offset] at most [length] bytes. * May block until at least one byte is available. * Usually bypass all exceptions from the underlying source. * * @param offset in bytes where result should be written * @param length should be at least one byte * * @return number of bytes were copied or `0` if EOF encountered */ protected abstract fun fill(destination: Memory, offset: Int, length: Int): Int /** * Should close the underlying bytes source. Could do nothing or throw exceptions. */ protected abstract fun closeSource() /** * Current head chunk reference */ private var _head: ChunkBuffer = head set(newHead) { field = newHead headMemory = newHead.memory headPosition = newHead.readPosition headEndExclusive = newHead.writePosition } @PublishedApi internal val head: ChunkBuffer get() = _head.also { it.discardUntilIndex(headPosition) } @PublishedApi internal var headMemory: Memory = head.memory @PublishedApi internal var headPosition: Int = head.readPosition @PublishedApi internal var headEndExclusive: Int = head.writePosition @PublishedApi internal var tailRemaining: Long = remaining - (headEndExclusive - headPosition) set(newValue) { require(newValue >= 0) { "tailRemaining shouldn't be negative: $newValue" } field = newValue } @PublishedApi internal val headRemaining: Int inline get() = headEndExclusive - headPosition internal fun prefetch(min: Long): Boolean { if (min <= 0) return true val headRemaining = headRemaining if (headRemaining >= min || headRemaining + tailRemaining >= min) return true return doPrefetch(min) } /** * Try to copy at least [min] but up to [max] bytes to the specified [destination] buffer from this input * skipping [offset] bytes. If there are not enough bytes available to provide [min] bytes after skipping [offset] * bytes then it will trigger the underlying source reading first and after that will * simply copy available bytes even if EOF encountered so [min] is not a requirement but a desired number of bytes. * It is safe to specify [max] greater than the destination free space. * `min` shouldn't be bigger than the [destination] free space. * This function could trigger the underlying source reading that may lead to blocking I/O. * It is allowed to specify too big [offset] so in this case this function will always return `0` after prefetching * all underlying bytes but note that it may lead to significant memory consumption. * This function usually copy more bytes than [min] (unless `max = min`) but it is not guaranteed. * When `0` is returned with `offset = 0` then it makes sense to check [endOfInput]. * * @param destination to write bytes * @param offset to skip input * @param min bytes to be copied, shouldn't be greater than the buffer free space. Could be `0`. * @param max bytes to be copied even if there are more bytes buffered, could be [Int.MAX_VALUE]. * @return number of bytes copied to the [destination] possibly `0` */ public fun peekTo( destination: Memory, destinationOffset: Long, offset: Long = 0, min: Long = 1, max: Long = Long.MAX_VALUE ): Long { prefetch(min + offset) var current: ChunkBuffer = head var copied = 0L var skip = offset var writePosition = destinationOffset val maxCopySize = minOf(max, destination.size - destinationOffset) while (copied < min && copied < maxCopySize) { val chunkSize = current.readRemaining if (chunkSize > skip) { val size = minOf(chunkSize - skip, maxCopySize - copied) current.memory.copyTo( destination, current.readPosition + skip, size, writePosition ) skip = 0 copied += size writePosition += size } else { skip -= chunkSize } current = current.next ?: break } return copied } /** * @see doFill for similar logic * @see appendView for similar logic */ private fun doPrefetch(min: Long): Boolean { var tail = _head.findTail() var available = headRemaining + tailRemaining do { val next = fill() if (next == null) { noMoreChunksAvailable = true return false } val chunkSize = next.readRemaining if (tail === ChunkBuffer.Empty) { _head = next tail = next } else { tail.next = next tailRemaining += chunkSize } available += chunkSize } while (available < min) return true } /** * Number of bytes available for read */ public val remaining: Long get() = headRemaining.toLong() + tailRemaining /** * @return `true` if there is at least one byte to read */ public fun canRead(): Boolean = headPosition != headEndExclusive || tailRemaining != 0L /** * @return `true` if there are at least [n] bytes to read */ public fun hasBytes(n: Int): Boolean = headRemaining + tailRemaining >= n private var noMoreChunksAvailable = false /** * Release packet. After this function invocation the packet becomes empty. * If it has been copied via [ByteReadPacket.copy] * then the copy should be released as well. */ public fun release() { val head = head val empty = ChunkBuffer.Empty if (head !== empty) { this._head = empty tailRemaining = 0 head.releaseAll(pool) } } /** * Close input including the underlying source. All pending bytes will be discarded. * It is not recommended to invoke it with read operations in-progress concurrently. */ override fun close() { release() if (!noMoreChunksAvailable) { noMoreChunksAvailable = true } closeSource() } internal fun stealAll(): ChunkBuffer? { val head = head val empty = ChunkBuffer.Empty if (head === empty) return null this._head = empty tailRemaining = 0 return head } internal fun steal(): ChunkBuffer? { val head = head val next = head.next val empty = ChunkBuffer.Empty if (head === empty) return null if (next == null) { this._head = empty this.tailRemaining = 0 } else { this._head = next this.tailRemaining -= next.readRemaining } head.next = null return head } internal fun append(chain: ChunkBuffer) { if (chain === ChunkBuffer.Empty) return val size = chain.remainingAll() if (_head === ChunkBuffer.Empty) { _head = chain tailRemaining = size - headRemaining } else { _head.findTail().next = chain tailRemaining += size } } internal fun tryWriteAppend(chain: ChunkBuffer): Boolean { val tail = head.findTail() val size = chain.readRemaining if (size == 0 || tail.writeRemaining < size) return false tail.writeBufferAppend(chain, size) if (head === tail) { headEndExclusive = tail.writePosition } else { tailRemaining += size } return true } /** * Read the next upcoming byte * @throws EOFException if no more bytes available. */ public fun readByte(): Byte { val index = headPosition val nextIndex = index + 1 if (nextIndex < headEndExclusive) { // fast-path when we are not reading the last byte headPosition = nextIndex return headMemory[index] } return readByteSlow() } private fun readByteSlow(): Byte { val index = headPosition if (index < headEndExclusive) { val value = headMemory[index] headPosition = index val head = _head head.discardUntilIndex(index) ensureNext(head) return value } val head = prepareRead(1) ?: prematureEndOfStream(1) val byte = head.readByte() completeReadHead(head) return byte } /** * Discards at most [n] bytes * @return number of bytes has been discarded */ public fun discard(n: Int): Int { require(n >= 0) { "Negative discard is not allowed: $n" } return discardAsMuchAsPossible(n, 0) } /** * Discards exactly [n] bytes or fails with [EOFException] */ public fun discardExact(n: Int) { if (discard(n) != n) throw EOFException("Unable to discard $n bytes due to end of packet") } /** * Returns next byte (unsigned) or `-1` if no more bytes available */ public fun tryPeek(): Int { val head = head if (headRemaining > 0) { return head.tryPeekByte() } if (tailRemaining == 0L && noMoreChunksAvailable) return -1 return prepareReadLoop(1, head)?.tryPeekByte() ?: -1 } public fun peekTo(buffer: ChunkBuffer): Int { val head = prepareReadHead(1) ?: return -1 val size = minOf(buffer.writeRemaining, head.readRemaining) (buffer as Buffer).writeFully(head, size) return size } /** * Discard at most [n] bytes */ public fun discard(n: Long): Long { if (n <= 0) return 0L return discardAsMuchAsPossible(n, 0) } internal fun readAvailableCharacters(destination: CharArray, off: Int, len: Int): Int { if (endOfInput) return -1 val out = object : Appendable { private var idx = off override fun append(value: Char): Appendable { destination[idx++] = value return this } override fun append(value: CharSequence?): Appendable { if (value is String) { value.getCharsInternal(destination, idx) idx += value.length } else if (value != null) { for (i in 0 until value.length) { destination[idx++] = value[i] } } return this } override fun append(value: CharSequence?, startIndex: Int, endIndex: Int): Appendable { throw UnsupportedOperationException() } } return readText(out, 0, len) } /** * Read at least [min] and at most [max] characters and append them to [out] * @return number of characters appended */ public fun readText(out: Appendable, min: Int = 0, max: Int = Int.MAX_VALUE): Int { if (max.toLong() >= remaining) { val s = readTextExactBytes(bytesCount = remaining.toInt()) out.append(s) return s.length } return readASCII(out, min, max) } /** * Read exactly [exactCharacters] characters and append them to [out] */ public fun readTextExact(out: Appendable, exactCharacters: Int) { readText(out, exactCharacters, exactCharacters) } /** * Read a string at last [min] and at most [max] characters length */ public fun readText(min: Int = 0, max: Int = Int.MAX_VALUE): String { if (min == 0 && (max == 0 || endOfInput)) return "" val remaining = remaining if (remaining > 0 && max.toLong() >= remaining) return readTextExactBytes(bytesCount = remaining.toInt()) return buildString(min.coerceAtLeast(16).coerceAtMost(max)) { readASCII(this, min, max) } } /** * Read a string exactly [exactCharacters] length */ public fun readTextExact(exactCharacters: Int): String { return readText(exactCharacters, exactCharacters) } private fun readASCII(out: Appendable, min: Int, max: Int): Int { when { max == 0 && min == 0 -> return 0 endOfInput -> if (min == 0) return 0 else atLeastMinCharactersRequire(min) max < min -> minShouldBeLess(min, max) } var copied = 0 var utf8 = false takeWhile { buffer -> val rc = buffer.decodeASCII { if (copied == max) false else { out.append(it) copied++ true } } when { rc -> true copied == max -> false else -> { utf8 = true false } } } if (utf8) { return copied + readUtf8(out, min - copied, max - copied) } if (copied < min) prematureEndOfStreamChars(min, copied) return copied } private fun atLeastMinCharactersRequire(min: Int): Nothing = throw EOFException("at least $min characters required but no bytes available") private fun minShouldBeLess(min: Int, max: Int): Nothing = throw IllegalArgumentException("min should be less or equal to max but min = $min, max = $max") private fun prematureEndOfStreamChars(min: Int, copied: Int): Nothing = throw MalformedUTF8InputException( "Premature end of stream: expected at least $min chars but had only $copied" ) private fun readUtf8(out: Appendable, min: Int, max: Int): Int { var copied = 0 takeWhileSize { buffer -> val size = buffer.decodeUTF8 { if (copied == max) false else { out.append(it) copied++ true } } when { size == 0 -> 1 size > 0 -> size else -> 0 } } if (copied < min) prematureEndOfStreamChars(min, copied) return copied } private tailrec fun discardAsMuchAsPossible(n: Long, skipped: Long): Long { if (n == 0L) return skipped val current = prepareRead(1) ?: return skipped val size = minOf(current.readRemaining.toLong(), n).toInt() current.discardExact(size) headPosition += size afterRead(current) return discardAsMuchAsPossible(n - size, skipped + size) } private fun discardAsMuchAsPossible(n: Int, skipped: Int): Int { var currentCount = n var currentSkipped = skipped while (true) { if (currentCount == 0) { return currentSkipped } val current = prepareRead(1) ?: return currentSkipped val size = minOf(current.readRemaining, currentCount) current.discardExact(size) headPosition += size afterRead(current) currentCount -= size currentSkipped += size } } private tailrec fun readAsMuchAsPossible(array: ByteArray, offset: Int, length: Int, copied: Int): Int { if (length == 0) return copied val current = prepareRead(1) ?: return copied val size = minOf(length, current.readRemaining) current.readFully(array, offset, size) headPosition = current.readPosition return if (size != length || current.readRemaining == 0) { afterRead(current) readAsMuchAsPossible(array, offset + size, length - size, copied + size) } else { copied + size } } private fun notEnoughBytesAvailable(n: Int): Nothing { throw EOFException("Not enough data in packet ($remaining) to read $n byte(s)") } internal fun prepareReadHead(minSize: Int): ChunkBuffer? = prepareReadLoop(minSize, head) internal fun ensureNextHead(current: ChunkBuffer): ChunkBuffer? = ensureNext(current) @PublishedApi internal fun ensureNext(current: ChunkBuffer): ChunkBuffer? = ensureNext( current, ChunkBuffer.Empty ) internal fun fixGapAfterRead(current: ChunkBuffer) { val next = current.next ?: return fixGapAfterReadFallback(current) val remaining = current.readRemaining val overrunSize = minOf(remaining, Buffer.ReservedSize - current.endGap) if (next.startGap < overrunSize) { return fixGapAfterReadFallback(current) } next.restoreStartGap(overrunSize) if (remaining > overrunSize) { current.releaseEndGap() this.headEndExclusive = current.writePosition this.tailRemaining += overrunSize } else { this._head = next this.tailRemaining -= next.readRemaining - overrunSize current.cleanNext() current.release(pool) } } private fun fixGapAfterReadFallback(current: ChunkBuffer) { if (noMoreChunksAvailable && current.next == null) { this.headPosition = current.readPosition this.headEndExclusive = current.writePosition this.tailRemaining = 0 return } val size = current.readRemaining val overrun = minOf(size, Buffer.ReservedSize - current.endGap) if (size > overrun) { fixGapAfterReadFallbackUnreserved(current, size, overrun) } else { val new = pool.borrow() new.reserveEndGap(Buffer.ReservedSize) new.next = current.cleanNext() new.writeBufferAppend(current, size) this._head = new } current.release(pool) } private fun fixGapAfterReadFallbackUnreserved(current: ChunkBuffer, size: Int, overrun: Int) { // if we have a chunk with no end reservation // we can split it into two to fix it val chunk1 = pool.borrow() val chunk2 = pool.borrow() chunk1.reserveEndGap(Buffer.ReservedSize) chunk2.reserveEndGap(Buffer.ReservedSize) chunk1.next = chunk2 chunk2.next = current.cleanNext() chunk1.writeBufferAppend(current, size - overrun) chunk2.writeBufferAppend(current, overrun) this._head = chunk1 this.tailRemaining = chunk2.remainingAll() } private tailrec fun ensureNext(current: ChunkBuffer, empty: ChunkBuffer): ChunkBuffer? { if (current === empty) { return doFill() } val next = current.cleanNext() current.release(pool) return when { next == null -> { this._head = empty this.tailRemaining = 0L ensureNext(empty, empty) } next.canRead() -> { _head = next tailRemaining -= next.readRemaining next } else -> ensureNext(next, empty) } } /** * Reads the next chunk suitable for reading or `null` if no more chunks available. It is also allowed * to return a chain of chunks linked through [ChunkBuffer.next]. The last chunk should have `null` next reference. * Could rethrow exceptions from the underlying source. */ protected open fun fill(): ChunkBuffer? { val buffer = pool.borrow() try { buffer.reserveEndGap(Buffer.ReservedSize) val copied = fill(buffer.memory, buffer.writePosition, buffer.writeRemaining) if (copied == 0) { noMoreChunksAvailable = true if (!buffer.canRead()) { buffer.release(pool) return null } } buffer.commitWritten(copied) return buffer } catch (t: Throwable) { buffer.release(pool) throw t } } protected fun markNoMoreChunksAvailable() { if (!noMoreChunksAvailable) { noMoreChunksAvailable = true } } /** * see [prefetch] for similar logic */ private fun doFill(): ChunkBuffer? { if (noMoreChunksAvailable) return null val chunk = fill() if (chunk == null) { noMoreChunksAvailable = true return null } appendView(chunk) return chunk } private fun appendView(chunk: ChunkBuffer) { val tail = _head.findTail() if (tail === ChunkBuffer.Empty) { _head = chunk require(tailRemaining == 0L) { throw IllegalStateException("It should be no tail remaining bytes if current tail is EmptyBuffer") } tailRemaining = chunk.next?.remainingAll() ?: 0L } else { tail.next = chunk tailRemaining += chunk.remainingAll() } } @PublishedApi internal fun prepareRead(minSize: Int): ChunkBuffer? { val head = head if (headEndExclusive - headPosition >= minSize) return head return prepareReadLoop(minSize, head) } @PublishedApi internal fun prepareRead(minSize: Int, head: ChunkBuffer): ChunkBuffer? { if (headEndExclusive - headPosition >= minSize) return head return prepareReadLoop(minSize, head) } private tailrec fun prepareReadLoop(minSize: Int, head: ChunkBuffer): ChunkBuffer? { val headSize = headRemaining if (headSize >= minSize) return head val next = head.next ?: doFill() ?: return null if (headSize == 0) { if (head !== ChunkBuffer.Empty) { releaseHead(head) } return prepareReadLoop(minSize, next) } else { val desiredExtraBytes = minSize - headSize val copied = head.writeBufferAppend(next, desiredExtraBytes) headEndExclusive = head.writePosition tailRemaining -= copied if (!next.canRead()) { head.next = null head.next = next.cleanNext() next.release(pool) } else { next.reserveStartGap(copied) } } if (head.readRemaining >= minSize) return head if (minSize > Buffer.ReservedSize) minSizeIsTooBig(minSize) return prepareReadLoop(minSize, head) } private fun minSizeIsTooBig(minSize: Int): Nothing { throw IllegalStateException("minSize of $minSize is too big (should be less than ${Buffer.ReservedSize})") } private fun afterRead(head: ChunkBuffer) { if (head.readRemaining == 0) { releaseHead(head) } } internal fun releaseHead(head: ChunkBuffer): ChunkBuffer { val next = head.cleanNext() ?: ChunkBuffer.Empty this._head = next this.tailRemaining -= next.readRemaining head.release(pool) return next } public companion object } /** * Discard all remaining bytes. * @return number of bytes were discarded */ public fun Input.discard(): Long { return discard(Long.MAX_VALUE) } /** * Discard exactly [n] bytes or fail if not enough bytes in the input to be discarded. */ public fun Input.discardExact(n: Long) { val discarded = discard(n) if (discarded != n) { throw IllegalStateException("Only $discarded bytes were discarded of $n requested") } } /** * Discard exactly [n] bytes or fail if not enough bytes in the input to be discarded. */ @Suppress("EXTENSION_SHADOWED_BY_MEMBER") public fun Input.discardExact(n: Int) { discardExact(n.toLong()) } /** * Invoke [block] function for every chunk until end of input or [block] function return `false` * [block] function returns `true` to request more chunks or `false` to stop loop * * It is not guaranteed that every chunk will have fixed size but it will be never empty. * [block] function should never release provided buffer and should not write to it otherwise an undefined behaviour * could be observed */ public inline fun Input.takeWhile(block: (Buffer) -> Boolean) { var release = true var current = prepareReadFirstHead(1) ?: return try { do { if (!block(current)) { break } release = false val next = prepareReadNextHead(current) ?: break current = next release = true } while (true) } finally { if (release) { completeReadHead(current) } } } /** * Invoke [block] function for every chunk until end of input or [block] function return zero * [block] function returns number of bytes required to read next primitive and shouldn't require too many bytes at once * otherwise it could fail with an exception. * It is not guaranteed that every chunk will have fixed size but it will be always at least requested bytes length. * [block] function should never release provided buffer and should not write to it otherwise an undefined behaviour * could be observed */ internal inline fun Input.takeWhileSize(initialSize: Int = 1, block: (Buffer) -> Int) { var release = true var current = prepareReadFirstHead(initialSize) ?: return var size = initialSize try { do { val before = current.readRemaining val after: Int if (before >= size) { try { size = block(current) } finally { after = current.readRemaining } } else { after = before } release = false val next = when { after == 0 -> prepareReadNextHead(current) after < size || current.endGap < Buffer.ReservedSize -> { completeReadHead(current) prepareReadFirstHead(size) } else -> current } ?: break current = next release = true } while (size > 0) } finally { if (release) { completeReadHead(current) } } } public fun Input.peekCharUtf8(): Char { val rc = tryPeek() if (rc and 0x80 == 0) return rc.toChar() if (rc == -1) throw EOFException("Failed to peek a char: end of input") return peekCharUtf8Impl(rc) } /** * For every byte from this input invokes [block] function giving it as parameter. */ internal inline fun Input.forEach(block: (Byte) -> Unit) { takeWhile { buffer -> buffer.forEach(block) true } } private fun Input.peekCharUtf8Impl(first: Int): Char { var rc = '?' var found = false takeWhileSize(byteCountUtf8(first)) { it.decodeUTF8 { ch -> found = true rc = ch false } } if (!found) { throw MalformedUTF8InputException("No UTF-8 character found") } return rc }
302
null
958
9,709
9e0eb99aa2a0a6bc095f162328525be1a76edb21
28,334
ktor
Apache License 2.0
app/src/main/java/net/vapormusic/animexstream/ui/main/settings/SettingsFragment.kt
androiddevnotesforks
337,019,411
false
null
package net.vapormusic.animexstream.ui.main.settings import android.content.Intent import android.content.res.Configuration import android.media.audiofx.Virtualizer import android.net.Uri import android.os.Bundle import android.provider.Settings import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AppCompatDelegate import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.axiel7.moelist.utils.PkceGenerator import io.realm.Realm import io.realm.Realm.getDefaultInstance import kotlinx.android.synthetic.main.fragment_settings.view.* import net.vapormusic.animexstream.MainActivity import net.vapormusic.animexstream.Private import net.vapormusic.animexstream.R import net.vapormusic.animexstream.utils.constants.C import net.vapormusic.animexstream.utils.model.SettingsModel import net.vapormusic.animexstream.utils.realm.InitalizeRealm import timber.log.Timber class SettingsFragment: Fragment(), View.OnClickListener { private lateinit var rootView: View private lateinit var codeVerifier: String private lateinit var codeChallenge: String override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_settings, container, false) setupClickListeners() setupToggleText() return rootView } override fun onResume() { setupToggleText() super.onResume() } private fun setupToggleText() { val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()); /// realm.beginTransaction() realm.executeTransaction { realm1: Realm -> val settings = realm1.where(SettingsModel::class.java).findFirst() if (settings == null ) { if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_NO) { rootView.toggleMode.text = getString(R.string.toggle_to_night_mode) } else { rootView.toggleMode.text = getString(R.string.toggle_to_light_mode) } val settings2 = realm.createObject(SettingsModel::class.java) realm1.insertOrUpdate(settings2) rootView.toggleMode2.text = getString(R.string.animepahe_on) // set the fields here // Toast.makeText(context, "new realm", Toast.LENGTH_SHORT).show() } else { if (settings?.paheanimeon == true){ // Toast.makeText(context, "old realm on", Toast.LENGTH_SHORT).show() rootView.toggleMode2.text = getString(R.string.animepahe_off) }else{ // Toast.makeText(context, "old realm off", Toast.LENGTH_SHORT).show() rootView.toggleMode2.text = getString(R.string.animepahe_on) } if (settings?.nightmodeon == true){ // Toast.makeText(context, "old realm on", Toast.LENGTH_SHORT).show() rootView.toggleMode.text = getString(R.string.toggle_to_light_mode) }else{ // Toast.makeText(context, "old realm off", Toast.LENGTH_SHORT).show() rootView.toggleMode.text = getString(R.string.toggle_to_night_mode) } if (settings?.malsyncon == true){ // Toast.makeText(context, "old realm on", Toast.LENGTH_SHORT).show() rootView.toggleMode3.text = getString(R.string.mal_on) }else{ // Toast.makeText(context, "old realm off", Toast.LENGTH_SHORT).show() rootView.toggleMode3.text = getString(R.string.mal_off) } if (settings?.playercontrolson == true){ // Toast.makeText(context, "old realm on", Toast.LENGTH_SHORT).show() rootView.toggleMode4.text = getString(R.string.advancedcontrols_on) }else{ // Toast.makeText(context, "old realm off", Toast.LENGTH_SHORT).show() rootView.toggleMode4.text = getString(R.string.advancedcontrols_off) } if (settings?.googlecdn == true){ // Toast.makeText(context, "old realm on", Toast.LENGTH_SHORT).show() rootView.toggleMode5.text = getString(R.string.googlecdn_on) }else{ // Toast.makeText(context, "old realm off", Toast.LENGTH_SHORT).show() rootView.toggleMode5.text = getString(R.string.googlecdn_off) } } } /// realm.commitTransaction() } private fun setupClickListeners() { rootView.back.setOnClickListener(this) rootView.toggleMode.setOnClickListener(this) rootView.toggleMode2.setOnClickListener(this) rootView.toggleMode3.setOnClickListener(this) rootView.toggleMode4.setOnClickListener(this) rootView.toggleMode5.setOnClickListener(this) } override fun onClick(v: View?) { when (v?.id) { R.id.back -> findNavController().popBackStack() R.id.toggleMode -> setupToggle() R.id.toggleMode2 -> togglePahe() R.id.toggleMode3 -> MALSync() R.id.toggleMode4 -> toggleAdvancedControls() R.id.toggleMode5 -> toggleGoogleCDN() } } private fun setupToggle() { val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()); /// realm.beginTransaction() realm.executeTransaction { realm1: Realm -> val settings = realm1.where(SettingsModel::class.java).findFirst() if (settings == null ) { val settings2 = realm.createObject(SettingsModel::class.java) realm1.insertOrUpdate(settings2) } else { if (settings.nightmodeon == true) { settings.nightmodeon = false AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) // rootView.toggleMode.text = getString(R.string.toggle_to_night_mode) Toast.makeText(context, "Light Mode", Toast.LENGTH_SHORT).show() } else { settings.nightmodeon = true AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) // rootView.toggleMode.text = getString(R.string.toggle_to_light_mode) Toast.makeText(context, "Night Mode", Toast.LENGTH_SHORT).show() } } } } private fun togglePahe() { val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()); try { realm.executeTransaction { realm1: Realm -> val settings = realm1.where(SettingsModel::class.java).findFirst() if (settings == null) { val settings2 = realm1.createObject(SettingsModel::class.java) realm1.insertOrUpdate(settings2) settings2.paheanimeon = true rootView.toggleMode2.text = getString(R.string.animepahe_off) // set the fields here // Toast.makeText(context, "on", Toast.LENGTH_SHORT).show() } else { if (settings.paheanimeon == true) { settings.paheanimeon = false rootView.toggleMode2.text = getString(R.string.animepahe_on) // Toast.makeText(context, "off", Toast.LENGTH_SHORT).show() } else { settings.paheanimeon = true rootView.toggleMode2.text = getString(R.string.animepahe_off) // Toast.makeText(context, "on", Toast.LENGTH_SHORT).show() } }} } catch (ignored: Exception) { } } private fun toggleAdvancedControls() { val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()); try { realm.executeTransaction { realm1: Realm -> val settings = realm1.where(SettingsModel::class.java).findFirst() if (settings == null) { val settings2 = realm1.createObject(SettingsModel::class.java) realm1.insertOrUpdate(settings2) settings2.playercontrolson = true rootView.toggleMode4.text = getString(R.string.advancedcontrols_on) // set the fields here // Toast.makeText(context, "on", Toast.LENGTH_SHORT).show() } else { if (settings.playercontrolson == true) { settings.playercontrolson = false rootView.toggleMode4.text = getString(R.string.advancedcontrols_off) // Toast.makeText(context, "off", Toast.LENGTH_SHORT).show() } else { settings.playercontrolson = true rootView.toggleMode4.text = getString(R.string.advancedcontrols_on) // Toast.makeText(context, "on", Toast.LENGTH_SHORT).show() } }} } catch (ignored: Exception) { } } fun toggleGoogleCDN(){ val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()); try { realm.executeTransaction { realm1: Realm -> val settings = realm1.where(SettingsModel::class.java).findFirst() if (settings == null) { val settings2 = realm1.createObject(SettingsModel::class.java) realm1.insertOrUpdate(settings2) settings2.googlecdn= false rootView.toggleMode5.text = getString(R.string.googlecdn_off) // set the fields here // Toast.makeText(context, "on", Toast.LENGTH_SHORT).show() } else { if (settings.googlecdn == true) { settings.googlecdn = false rootView.toggleMode5.text = getString(R.string.googlecdn_off) // Toast.makeText(context, "off", Toast.LENGTH_SHORT).show() } else { settings.googlecdn = true rootView.toggleMode5.text = getString(R.string.googlecdn_on) // Toast.makeText(context, "on", Toast.LENGTH_SHORT).show() } }} } catch (ignored: Exception) { } } fun MALSync(){ val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()); try { realm.executeTransaction { realm1: Realm -> val settings = realm1.where(SettingsModel::class.java).findFirst() if (settings == null) { val settings2 = realm1.createObject(SettingsModel::class.java) settings2.malsyncon = true realm1.insertOrUpdate(settings2) rootView.toggleMode3.text = getString(R.string.mal_on) codeVerifier = PkceGenerator.generateVerifier(128) codeChallenge = codeVerifier val loginUrl = Uri.parse(C.MAL_OAUTH2_BASE + "authorize" + "?response_type=code" + "&client_id=" + Private.MAL_CLIENT_ID + "&code_challenge=" + codeVerifier + "&state=" + codeVerifier + "&redirect_uri=" +C.AUTH_DEEP_LINK ) Timber.e("""mal :${codeVerifier}""") val intent = Intent(Intent.ACTION_VIEW, loginUrl) startActivity(intent) } else { if (settings.malsyncon == true) { rootView.toggleMode3.text = getString(R.string.mal_off) settings.malsyncon = false settings.malaccesstoken = "" settings.malrefreshtoken = "" settings.malrefreshtoken = "" } else { settings.malsyncon = true rootView.toggleMode3.text = getString(R.string.mal_on) codeVerifier = PkceGenerator.generateVerifier(128) codeChallenge = codeVerifier val loginUrl = Uri.parse(C.MAL_OAUTH2_BASE + "authorize" + "?response_type=code" + "&client_id=" + Private.MAL_CLIENT_ID + "&code_challenge=" + codeVerifier + "&state=" + codeVerifier + "&redirect_uri=" +C.AUTH_DEEP_LINK ) Timber.e("""mal :${codeVerifier}""") val intent = Intent(Intent.ACTION_VIEW, loginUrl) startActivity(intent) } }} } catch (ignored: Exception) { } } fun addDataInRealm(settings : SettingsModel ) { val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()) try { realm.executeTransaction { realm1: Realm -> realm1.insertOrUpdate(settings) } } catch (ignored: Exception) { } } }
0
null
6
9
ea8a900769abaff526f934be65eafe871209ca66
13,604
AnimeXStream
MIT License
domain/src/test/java/com/example/domain/TestUtils.kt
cobeisfresh
197,172,826
false
null
package com.example.domain const val OSIJEK_CITY_NAME = "Osijek"
0
Kotlin
26
108
6a86cfeed4060a37db6c06b6b948a37a38b7307f
65
CleanArchitecture-Android-Showcase
MIT License
src/test/kotlin/io/sip3/salto/ce/recording/RecordingHandlerTest.kt
sip3io
212,591,485
false
null
/* * Copyright 2018-2024 SIP3.IO, Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sip3.salto.ce.recording import io.sip3.commons.PacketTypes import io.sip3.commons.domain.media.Recording import io.sip3.commons.domain.payload.RecordingPayload import io.sip3.commons.util.getBytes import io.sip3.commons.vertx.test.VertxTest import io.sip3.commons.vertx.util.localSend import io.sip3.salto.ce.RoutesCE import io.sip3.salto.ce.domain.Address import io.sip3.salto.ce.domain.Packet import io.vertx.core.json.JsonObject import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class RecordingHandlerTest : VertxTest() { val RECORDING_1 = RecordingPayload().apply { callId = "<EMAIL>" type = PacketTypes.RTP mode = Recording.FULL payload = byteArrayOf( 0x80.toByte(), 0x08.toByte(), 0x1c.toByte(), 0xf9.toByte(), 0x99.toByte(), 0x75.toByte(), 0xd5.toByte(), 0x78.toByte(), 0x30.toByte(), 0xe8.toByte(), 0x71.toByte(), 0x2d.toByte(), 0xcc.toByte(), 0xf5.toByte(), 0xf7.toByte(), 0xf1.toByte(), 0xf1.toByte(), 0xf1.toByte(), 0xf0.toByte(), 0xf1.toByte(), 0xf1.toByte(), 0xf0.toByte(), 0xf3.toByte(), 0xf3.toByte(), 0xf2.toByte(), 0xfc.toByte(), 0xf2.toByte(), 0xfd.toByte(), 0xfd.toByte(), 0xf0.toByte(), 0xf6.toByte(), 0xca.toByte(), 0xc5.toByte(), 0xd0.toByte(), 0x5c.toByte(), 0x4e.toByte(), 0x70.toByte(), 0x79.toByte(), 0x64.toByte(), 0x66.toByte(), 0x61.toByte(), 0x63.toByte(), 0x60.toByte(), 0x66.toByte(), 0x67.toByte(), 0x7b.toByte(), 0x72.toByte(), 0x75.toByte(), 0x44.toByte(), 0x57.toByte(), 0xdd.toByte(), 0xc1.toByte(), 0xcb.toByte(), 0xf4.toByte(), 0xf6.toByte(), 0xf0.toByte(), 0xf1.toByte(), 0xf1.toByte(), 0xf1.toByte(), 0xf6.toByte(), 0xf6.toByte(), 0xf1.toByte(), 0xf6.toByte(), 0xf1.toByte(), 0xf3.toByte(), 0xf0.toByte(), 0xf3.toByte(), 0xf3.toByte(), 0xf1.toByte(), 0xf7.toByte(), 0xc8.toByte(), 0xc1.toByte(), 0xdd.toByte(), 0x51.toByte(), 0x40.toByte(), 0x74.toByte(), 0x7d.toByte(), 0x7b.toByte(), 0x64.toByte(), 0x67.toByte(), 0x61.toByte(), 0x61.toByte(), 0x66.toByte(), 0x64.toByte(), 0x79.toByte(), 0x73.toByte(), 0x75.toByte(), 0x44.toByte(), 0x56.toByte(), 0xd2.toByte(), 0xc7.toByte(), 0xce.toByte(), 0xf5.toByte(), 0xf7.toByte(), 0xf6.toByte(), 0xf7.toByte(), 0xf7.toByte(), 0xf7.toByte(), 0xf4.toByte(), 0xf5.toByte(), 0xf5.toByte(), 0xf4.toByte(), 0xf4.toByte(), 0xf7.toByte(), 0xf7.toByte(), 0xf6.toByte(), 0xf6.toByte(), 0xf7.toByte(), 0xf4.toByte(), 0xf5.toByte(), 0xc3.toByte(), 0xdb.toByte(), 0xd6.toByte(), 0x5e.toByte(), 0x4c.toByte(), 0x71.toByte(), 0x7f.toByte(), 0x65.toByte(), 0x66.toByte(), 0x61.toByte(), 0x60.toByte(), 0x61.toByte(), 0x66.toByte(), 0x65.toByte(), 0x7e.toByte(), 0x71.toByte(), 0x4c.toByte(), 0x5c.toByte(), 0xd0.toByte(), 0xc1.toByte(), 0xca.toByte(), 0xf1.toByte(), 0xf2.toByte(), 0xfc.toByte(), 0xff.toByte(), 0xff.toByte(), 0xfd.toByte(), 0xf3.toByte(), 0xf0.toByte(), 0xf1.toByte(), 0xf7.toByte(), 0xf4.toByte(), 0xf5.toByte(), 0xf5.toByte(), 0xcb.toByte(), 0xca.toByte(), 0xce.toByte(), 0xcf.toByte(), 0xc2.toByte(), 0xc5.toByte(), 0xdc.toByte(), 0xd4.toByte(), 0x5c.toByte(), 0x40.toByte(), 0x75.toByte(), 0x72.toByte(), 0x7e.toByte(), 0x65.toByte(), 0x64.toByte(), 0x67.toByte(), 0x67.toByte(), 0x64.toByte(), 0x65.toByte(), 0x79.toByte(), 0x72.toByte(), 0x75.toByte(), 0x46.toByte(), 0x51.toByte(), 0xd3.toByte(), 0xc6.toByte(), 0xc8.toByte(), 0xf4.toByte() ) } val PACKET_1 = Packet().apply { createdAt = System.currentTimeMillis() srcAddr = Address().apply { addr = "127.0.0.1" port = 10000 host = "SRC_HOST" } dstAddr = Address().apply { addr = "127.0.0.2" port = 20000 } source = "sip3" protocolCode = PacketTypes.REC payload = RECORDING_1.encode().getBytes() } val RECORDING_2 = RecordingPayload().apply { callId = "<EMAIL>" type = PacketTypes.RTCP mode = Recording.FULL payload = "rtcp packet payload".toByteArray() } val PACKET_2 = Packet().apply { createdAt = System.currentTimeMillis() srcAddr = Address().apply { addr = "127.0.0.1" port = 10000 host = "SRC_HOST" } dstAddr = Address().apply { addr = "127.0.0.2" port = 20000 } source = "sip3" protocolCode = PacketTypes.REC payload = RECORDING_2.encode().getBytes() } @Test fun `Receive 'RTP' packet and write to DB`() { runTest( deploy = { vertx.deployTestVerticle(RecordingHandler::class, JsonObject().apply { put("recording", JsonObject().apply { put("bulk_size", 1) }) }) }, execute = { vertx.eventBus().localSend(RoutesCE.rec, PACKET_1) }, assert = { vertx.eventBus().consumer<Pair<String, JsonObject>>(RoutesCE.mongo_bulk_writer) { event -> val (collection, operation) = event.body() val document = operation.getJsonObject("document") context.verify { assertTrue(collection.startsWith("rec_raw")) assertEquals(PACKET_1.createdAt, document.getLong("created_at")) assertEquals(PACKET_1.srcAddr.addr, document.getString("src_addr")) assertEquals(PACKET_1.srcAddr.port, document.getInteger("src_port")) assertEquals(PACKET_1.srcAddr.host, document.getString("src_host")) assertEquals(PACKET_1.dstAddr.addr, document.getString("dst_addr")) assertEquals(PACKET_1.dstAddr.port, document.getInteger("dst_port")) assertEquals(RECORDING_1.callId, document.getString("call_id")) assertEquals(1, document.getJsonArray("packets").size()) val packet = document.getJsonArray("packets").first() as JsonObject assertEquals(PacketTypes.RTP.toInt(), packet.getInteger("type")) assertEquals(RECORDING_1.payload.toString(Charsets.ISO_8859_1), packet.getString("raw_data")) } context.completeNow() } } ) } @Test fun `Receive packets and write to DB as bulk`() { runTest( deploy = { vertx.deployTestVerticle(RecordingHandler::class, JsonObject().apply { put("recording", JsonObject().apply { put("bulk_size", 3) }) }) }, execute = { repeat(4) { vertx.eventBus().localSend(RoutesCE.rec, PACKET_1) } }, assert = { vertx.eventBus().consumer<Pair<String, JsonObject>>(RoutesCE.mongo_bulk_writer) { event -> val (collection, operation) = event.body() val document = operation.getJsonObject("document") context.verify { assertTrue(collection.startsWith("rec_raw")) assertEquals(PACKET_1.createdAt, document.getLong("created_at")) assertEquals(PACKET_1.srcAddr.addr, document.getString("src_addr")) assertEquals(PACKET_1.srcAddr.port, document.getInteger("src_port")) assertEquals(PACKET_1.srcAddr.host, document.getString("src_host")) assertEquals(PACKET_1.dstAddr.addr, document.getString("dst_addr")) assertEquals(PACKET_1.dstAddr.port, document.getInteger("dst_port")) assertEquals(RECORDING_1.callId, document.getString("call_id")) assertEquals(3, document.getJsonArray("packets").size()) val packet = document.getJsonArray("packets").first() as JsonObject assertEquals(PacketTypes.RTP.toInt(), packet.getInteger("type")) assertEquals(RECORDING_1.payload.toString(Charsets.ISO_8859_1), packet.getString("raw_data")) } context.completeNow() } } ) } @Test fun `Receive 'RTCP' packet and send to RtcpHandler`() { runTest( deploy = { vertx.deployTestVerticle(RecordingHandler::class) }, execute = { vertx.eventBus().localSend(RoutesCE.rec, PACKET_2) }, assert = { vertx.eventBus().consumer<Packet>(RoutesCE.rtcp) { event -> val packet = event.body() context.verify { assertEquals(PACKET_2.createdAt, packet.createdAt) assertEquals(PACKET_2.srcAddr, packet.srcAddr) assertEquals(PACKET_2.dstAddr, packet.dstAddr) assertEquals(PacketTypes.RTCP, packet.protocolCode) assertEquals("sip3", packet.source) assertArrayEquals(RECORDING_2.payload, packet.payload) } context.completeNow() } } ) } }
3
null
2
76
f7e4d932c58d8ef18627444d552d4ea2980b57e0
10,271
sip3-salto-ce
Apache License 2.0
app/src/main/java/com/educatorapp/ui/main/MainActivity.kt
manishpatelgt
265,855,771
false
null
package com.educatorapp.ui.main import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.viewModels import androidx.lifecycle.Observer import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.setupWithNavController import com.educatorapp.R import com.educatorapp.application.App import com.educatorapp.application.App.Companion.appContext import com.educatorapp.databinding.ActivityMainBinding import com.educatorapp.ui.base.BaseActivity import com.educatorapp.utils.constants.Constants import com.google.android.material.bottomnavigation.BottomNavigationView import es.dmoral.toasty.Toasty /** * Created by <NAME> on 5/21/2020. */ class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() { override fun getViewBinding(): ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater) override val mViewModel: MainViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(mViewBinding.root) setupUI() } private fun setupUI() { /** Set action bar */ setSupportActionBar(mViewBinding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) /** Set observers*/ setObservers() val navView: BottomNavigationView = findViewById(R.id.nav_view) val navController = findNavController(R.id.nav_host_fragment) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration( setOf( R.id.navigation_subject, R.id.navigation_favorite, R.id.navigation_profile ) ) //NavigationUI.setupWithNavController(mViewBinding.toolbar, navController) navView.setupWithNavController(navController) mViewBinding.toolbar?.setupWithNavController(navController, appBarConfiguration) /*mViewBinding.navView.setOnNavigationItemReselectedListener { "Reselect blocked." }*/ /*mViewBinding.toolbar.setNavigationOnClickListener { when (navController.currentDestination?.id) { R.id.navigation_subject, R.id.navigation_favorite, R.id.navigation_profile -> { Log.e("Main", "current destination id: ${navController.currentDestination?.id} ") if (onBackPressedDispatcher.hasEnabledCallbacks()) onBackPressedDispatcher.onBackPressed() else navController.navigateUp() } else -> navController.navigateUp() } }*/ /** Setup fragment state observer */ val fragmentStateObserver = Observer<String> { state -> when (state) { Constants.FRAGMENT_SUBJECTS -> navController.navigate(R.id.navigation_subject) Constants.FRAGMENT_FAVORITE -> navController.navigate(R.id.navigation_favorite) Constants.FRAGMENT_PROFILE -> navController.navigate(R.id.navigation_profile) } } mViewModel.fragmentState.observe(this, fragmentStateObserver) } private fun setObservers() { /** Set observer for a toast message */ mViewModel.showToast.observe(this, Observer { showToastMessage(it) }) } companion object { val TAG = MainActivity::class.simpleName fun getIntent() = Intent(appContext, MainActivity::class.java) } }
0
Kotlin
1
5
daab7558a301c82dbd363c857f0cb36d9f3ebf40
3,769
EducatorApp
The Unlicense
src/main/kotlin/com/developerphil/adbidea/adb/AdbFacade.kt
longforus
146,382,514
true
{"Markdown": 4, "Gradle": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "INI": 1, "Kotlin": 97, "XML": 6, "Java": 4}
package com.developerphil.adbidea.adb import com.android.ddmlib.IDevice import com.developerphil.adbidea.ObjectGraph import com.developerphil.adbidea.adb.command.* import com.developerphil.adbidea.bean.BoundItemBean import com.developerphil.adbidea.ui.NotificationHelper import com.google.common.util.concurrent.ThreadFactoryBuilder import com.intellij.openapi.project.Project import org.eclipse.xtext.xbase.lib.Functions import java.io.File import java.util.concurrent.Executors object AdbFacade { internal val EXECUTOR = Executors.newCachedThreadPool(ThreadFactoryBuilder().setNameFormat("AdbIdea-%d").build()) fun uninstall(project: Project) = executeOnDevice(project, UninstallCommand()) fun uninstall(project: Project, packageName: String) { executeOnDevice(project, UninstallCommand(packageName)) } fun kill(project: Project) = executeOnDevice(project, KillCommand()) fun grantPermissions(project: Project) = executeOnDevice(project, GrantPermissionsCommand()) fun revokePermissions(project: Project) = executeOnDevice(project, RevokePermissionsCommand()) fun revokePermissionsAndRestart(project: Project) = executeOnDevice(project, RevokePermissionsAndRestartCommand()) fun startDefaultActivity(project: Project) = executeOnDevice(project, StartDefaultActivityCommand(false)) fun startDefaultActivityWithDebugger(project: Project) = executeOnDevice(project, StartDefaultActivityCommand(true)) fun restartDefaultActivity(project: Project) = executeOnDevice(project, RestartPackageCommand()) fun restartDefaultActivityWithDebugger(project: Project) = executeOnDevice(project, CommandList(KillCommand(), StartDefaultActivityCommand(true))) fun clearData(project: Project) = executeOnDevice(project, ClearDataCommand()) fun clearDataAndRestart(project: Project) = executeOnDevice(project, ClearDataAndRestartCommand()) fun installApk(project: Project, apks: List<File>) { executeOnDevice(project, InstallApkCommand(apks)) } fun getPackageDetail(project: Project, packageName: String, callback: Function1<String, Unit>) { executeOnDevice(project, PackageDetailCommand(packageName, callback)) } fun forceStop(project: Project, packageName: String) { executeOnDevice(project, ForceStopCommand(packageName)) } fun getPackagePath(project: Project, packageName: String, callback: Function1<String, Unit>) { executeOnDevice(project, PackagePathCommand(packageName, callback)) } fun getActivityService(project: Project, packageName: String, callback: Function1<String, Unit>) { executeOnDevice(project, ActivityServiceCommand(packageName, callback)) } fun getAllApplicationList(project: Project, parameter: String, callback: Function1<List<String>, Unit>) { executeOnDevice(project, GetApplicationListCommand(parameter, callback)) } fun clearDataAndRestartWithDebugger(project: Project) = executeOnDevice(project, ClearDataAndRestartWithDebuggerCommand()) fun enableWifi(project: Project) = executeOnDevice(project, ToggleSvcCommand(SvcCommand.WIFI, true)) fun disableWifi(project: Project) = executeOnDevice(project, ToggleSvcCommand(SvcCommand.WIFI, false)) fun enableMobile(project: Project) = executeOnDevice(project, ToggleSvcCommand(SvcCommand.MOBILE, true)) fun disableMobile(project: Project) = executeOnDevice(project, ToggleSvcCommand(SvcCommand.MOBILE, false)) private fun executeOnDevice(project: Project, runnable: Command,dev: IDevice? = null) { if (AdbUtil.isGradleSyncInProgress(project)) { NotificationHelper.error("Gradle sync is in progress") return } val result = project.getComponent(ObjectGraph::class.java) .deviceResultFetcher .fetch(dev) if (result != null) { for (device in result.devices) { EXECUTOR.submit { runnable.run(project, device, result.facet, result.packageName) } } } else { NotificationHelper.error("No Device found") } } fun clearData(project: Project, realPackageName: String) { executeOnDevice(project, ClearDataCommand(realPackageName)) } fun showForegroundActivity(project: Project, callback: Function1<String, Unit>) { executeOnDevice(project, ForegroundActivityCommand(callback)) } fun monkeyTest(project: Project, packageName: String, count: Int, callback: Function1<String, Unit>) { executeOnDevice(project, MonkeyTestCommand(packageName, count, callback)) } fun putStringToDevice(project: Project?, str: String) { executeOnDevice(project!!, PutStringToDeviceCommand(str)) } fun interacting(project: Project, type: Int, action: String, category: String, name: String, boundData: MutableList<BoundItemBean>) { executeOnDevice(project, getInteractingCommand(type, action, category, name, boundData)) } @JvmOverloads fun getSimpleInfo(project: Project?, command: String, desc: String,dev: IDevice? = null, callback: Function2<String,IDevice, Unit>) { executeOnDevice(project!!, CommonStringResultCommand(command, desc, callback),dev) } fun captureScreen(project: Project?, localDir: File, fileName: String) { executeOnDevice(project!!, CaptureScreenCommand(localDir, fileName)) } /** * "bad result" * @param project * @param localFile * @param videoName * @param length * @param showTouches */ @Deprecated("") fun recordScreen(project: Project?, localFile: File, videoName: String, length: Int, showTouches: Boolean) { executeOnDevice(project!!, ScreenRecordCommand(localFile, videoName, length, showTouches)) } fun pullFile(project: Project?, remotePath: String, localFile: File, deleteRemoteFile: Boolean) { executeOnDevice(project!!, PullFileCommand(remotePath, localFile, deleteRemoteFile)) } fun getDeviceModel(project: Project?, function: Function1<String, Unit>) { getSimpleInfo(project, "getprop ro.product.model", "get Device model ") { s,d -> function.invoke(s.replace("\n", "").replace("\r", "").replace(" ", "")) } } }
2
Kotlin
3
31
8e3c405ca80b9d341b419d65693d4c4d4e0c546e
6,275
adb-idea-plus
Apache License 2.0
src/main/kotlin/no/skatteetaten/aurora/boober/feature/RouteFeature.kt
Skatteetaten
84,482,382
false
null
package no.skatteetaten.aurora.boober.feature import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import com.fkorotkov.kubernetes.newObjectMeta import com.fkorotkov.openshift.metadata import com.fkorotkov.openshift.newRoute import com.fkorotkov.openshift.port import com.fkorotkov.openshift.spec import com.fkorotkov.openshift.tls import com.fkorotkov.openshift.to import io.fabric8.kubernetes.api.model.EnvVar import io.fabric8.kubernetes.api.model.IntOrString import io.fabric8.openshift.api.model.Route import no.skatteetaten.aurora.boober.model.ApplicationDeploymentRef import no.skatteetaten.aurora.boober.model.AuroraConfigException import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler import no.skatteetaten.aurora.boober.model.AuroraConfigFile import no.skatteetaten.aurora.boober.model.AuroraContextCommand import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec import no.skatteetaten.aurora.boober.model.AuroraResource import no.skatteetaten.aurora.boober.model.ConfigFieldErrorDetail import no.skatteetaten.aurora.boober.model.addEnvVarsToMainContainers import no.skatteetaten.aurora.boober.model.findSubHandlers import no.skatteetaten.aurora.boober.model.findSubKeys import no.skatteetaten.aurora.boober.model.findSubKeysExpanded import no.skatteetaten.aurora.boober.model.openshift.AuroraCname import no.skatteetaten.aurora.boober.model.openshift.AuroraAzureCname import no.skatteetaten.aurora.boober.model.openshift.CnameSpec import no.skatteetaten.aurora.boober.model.openshift.AzureCnameSpec import no.skatteetaten.aurora.boober.utils.addIfNotNull import no.skatteetaten.aurora.boober.utils.boolean import no.skatteetaten.aurora.boober.utils.ensureEndsWith import no.skatteetaten.aurora.boober.utils.ensureStartWith import no.skatteetaten.aurora.boober.utils.int import no.skatteetaten.aurora.boober.utils.isValidDns import no.skatteetaten.aurora.boober.utils.oneOf import no.skatteetaten.aurora.boober.utils.startsWith private const val ROUTE_CONTEXT_KEY = "route" private const val APPLICATION_DEPLOYMENT_REF_CONTEXT_KEY = "applicationDeploymentRef" private val FeatureContext.routes: List<ConfiguredRoute> get() = this.getContextKey( ROUTE_CONTEXT_KEY ) private val FeatureContext.applicationDeploymentRef: ApplicationDeploymentRef get() = this.getContextKey( APPLICATION_DEPLOYMENT_REF_CONTEXT_KEY ) const val WEMBLEY_EXTERNAL_HOST_ANNOTATION_NAME = "wembley.sits.no|externalHost" const val WEBMLEY_API_PATHS_ANNOTATION_NAME = "wembley.sits.no|apiPaths" const val ROUTE_FEATURE_FIELD = "route" const val ROUTE_DEFAULTS_FEATURE_FIELD = "routeDefaults" @Service class RouteFeature( @Value("\${boober.route.suffix}") val routeSuffix: String, @Value("\${boober.azureRoute.suffix}") val azureRouteSuffix: String ) : Feature { override fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> { return findDefaultRouteHandlers(header) + findRouteHandlers(cmd.applicationFiles) + findRouteAnnotationHandlers(ROUTE_DEFAULTS_FEATURE_FIELD, cmd.applicationFiles) } override fun createContext( spec: AuroraDeploymentSpec, cmd: AuroraContextCommand, validationContext: Boolean ): Map<String, Any> { val routes = parseConfiguredRoutes(spec) return mapOf( ROUTE_CONTEXT_KEY to routes, APPLICATION_DEPLOYMENT_REF_CONTEXT_KEY to cmd.applicationDeploymentRef ) } override fun validate( adc: AuroraDeploymentSpec, fullValidation: Boolean, context: FeatureContext ): List<Exception> { val routes = context.routes val applicationDeploymentRef = context.applicationDeploymentRef val tlsErrors = validateTlsForRoutes(routes, applicationDeploymentRef) val duplicateRouteErrors = validateUniquenessOfRoutenames(routes, applicationDeploymentRef) val duplicateHostError = validateUniqueRouteHost(routes, applicationDeploymentRef) val dnsErrors = validateHostCompliesToDns(routes, applicationDeploymentRef) return tlsErrors .addIfNotNull(dnsErrors) .addIfNotNull(duplicateRouteErrors) .addIfNotNull(duplicateHostError) } override fun generate(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> { val routes = context.routes val auroraCnames = routes.generateCnames(adc.namespace) val auroraAzureCnames = routes.generateAzureCnames(adc.namespace) val openshiftRoutes = routes.generateOpenshiftRoutes(adc.namespace, adc.name) return openshiftRoutes + auroraCnames + auroraAzureCnames } override fun modify( adc: AuroraDeploymentSpec, resources: Set<AuroraResource>, context: FeatureContext ) { val route = context.routes.firstOrNull() ?: return val envVars = route.getEnvVars(routeSuffix) resources.addEnvVarsToMainContainers(envVars, this::class.java) } fun parseConfiguredRoutes( adc: AuroraDeploymentSpec ): List<ConfiguredRoute> { if (adc.isJob) return emptyList() val isSimplifiedRoute = adc.isSimplifiedConfig(ROUTE_FEATURE_FIELD) val defaultRoute = getDefaultRoute(adc) if (isSimplifiedRoute) { if (!adc.isRouteEnabled()) return emptyList() return listOf(defaultRoute) } val routeNames = adc.findSubKeysRaw(ROUTE_FEATURE_FIELD) val configuredRoutes = routeNames.mapNotNull { routeName -> getRoute(adc, routeName, defaultRoute) } return configuredRoutes } private fun getCname(adc: AuroraDeploymentSpec, host: String, objectName: String, routeName: String = ""): Cname? { if (!adc.isMsDnsCnameEnabled(routeName)) { return null } return Cname( routeHost = host, ttl = adc.getRouteFieldOrDefault(routeName = routeName, suffix = "cname/ttl"), objectName = objectName ) } private fun getAzureCname(adc: AuroraDeploymentSpec, host: String, objectName: String, routeName: String = ""): AzureCname? { if (!adc.isAzureConfigured(routeName)) { return null } return AzureCname( routeHost = host, ttl = adc.getRouteFieldOrDefault(routeName = routeName, suffix = "azure/cnameTtl"), objectName = objectName ) } private fun getDefaultRoute( adc: AuroraDeploymentSpec ): ConfiguredRoute { val defaultAnnotations = adc.getRouteAnnotations("$ROUTE_DEFAULTS_FEATURE_FIELD/annotations/") val shouldGenerateAzureRoute = adc.isAzureConfigured() val isFullyQualifiedHost = adc.isMsDnsCnameEnabled() || adc.isAzureConfigured() val host: String = adc["$ROUTE_DEFAULTS_FEATURE_FIELD/host"] val defaultCname = getCname(adc, host, adc.name) val defaultAzureCname = getAzureCname(adc, host, adc.name) return ConfiguredRoute( host = host, objectName = adc.name, tls = getTlsOrNull(adc), fullyQualifiedHost = isFullyQualifiedHost, annotations = defaultAnnotations, shouldGenerateAzureRoute = shouldGenerateAzureRoute, cname = defaultCname, azureCname = defaultAzureCname ) } private fun getRoute( adc: AuroraDeploymentSpec, routeName: String, defaultRoute: ConfiguredRoute ): ConfiguredRoute? { if (!adc.isRouteEnabled(routeName)) return null val secure = getTlsOrNull(adc, routeName) val annotations = adc.getRouteAnnotations("$ROUTE_FEATURE_FIELD/$routeName/annotations/") val objectname = adc.replacer.replace(routeName).ensureStartWith(adc.name, "-") val isMsDnsCnameConfigured = adc.isMsDnsCnameEnabled(routeName) val fullyQualifiedHost: Boolean = adc["$ROUTE_FEATURE_FIELD/$routeName/fullyQualifiedHost"] || isMsDnsCnameConfigured || adc.isAzureConfigured(routeName) val host = adc.getOrNull("$ROUTE_FEATURE_FIELD/$routeName/host") ?: defaultRoute.host val cname = getCname(adc, host, objectname, routeName) val azureCname = getAzureCname(adc, host, objectname, routeName) return ConfiguredRoute( objectName = objectname, host = host, path = adc.getOrNull("$ROUTE_FEATURE_FIELD/$routeName/path"), annotations = defaultRoute.annotations + annotations, tls = secure, fullyQualifiedHost = fullyQualifiedHost, shouldGenerateAzureRoute = adc.isAzureConfigured(routeName), cname = cname, azureCname = azureCname ) } private fun getTlsOrNull(adc: AuroraDeploymentSpec, routeName: String = ""): SecureRoute? { return if (adc.isTlsEnabled(routeName)) { SecureRoute( adc.getRouteFieldOrDefault(routeName, "tls/insecurePolicy"), adc.getRouteFieldOrDefault(routeName, "tls/termination") ) } else null } private fun findDefaultRouteHandlers(header: AuroraDeploymentSpec): Set<AuroraConfigFieldHandler> { val applicationPlatform = header.applicationPlatform return setOf( AuroraConfigFieldHandler( ROUTE_FEATURE_FIELD, defaultValue = false, validator = { it.boolean() }, canBeSimplifiedConfig = true ), AuroraConfigFieldHandler( "$ROUTE_DEFAULTS_FEATURE_FIELD/host", defaultValue = "@name@-@affiliation@-@env@" ), AuroraConfigFieldHandler( "$ROUTE_DEFAULTS_FEATURE_FIELD/tls/enabled", validator = { it.boolean() }, defaultValue = false ), AuroraConfigFieldHandler( "$ROUTE_DEFAULTS_FEATURE_FIELD/cname/enabled", validator = { it.boolean() }, defaultValue = false ), AuroraConfigFieldHandler( "$ROUTE_DEFAULTS_FEATURE_FIELD/azure/enabled", validator = { it.boolean() }, defaultValue = false ), AuroraConfigFieldHandler( "$ROUTE_DEFAULTS_FEATURE_FIELD/azure/cnameTtl", validator = { it.int(false) }, defaultValue = 300 ), AuroraConfigFieldHandler( "$ROUTE_DEFAULTS_FEATURE_FIELD/cname/ttl", validator = { it.int() }, defaultValue = 300 ), AuroraConfigFieldHandler( "$ROUTE_DEFAULTS_FEATURE_FIELD/tls/insecurePolicy", defaultValue = InsecurePolicy.valueOf(applicationPlatform.insecurePolicy), validator = { it.oneOf(InsecurePolicy.values().map { v -> v.name }) } ), AuroraConfigFieldHandler( "$ROUTE_DEFAULTS_FEATURE_FIELD/tls/termination", defaultValue = TlsTermination.edge, validator = { it.oneOf(TlsTermination.values().map { v -> v.name }) } ) ) } fun findRouteHandlers(applicationFiles: List<AuroraConfigFile>): Set<AuroraConfigFieldHandler> { val routeHandlers = applicationFiles.findSubKeysExpanded(ROUTE_FEATURE_FIELD) return routeHandlers.flatMap { key -> listOf( AuroraConfigFieldHandler( "$key/enabled", validator = { it.boolean() }, defaultValue = true ), AuroraConfigFieldHandler( "$key/azure/enabled", validator = { it.boolean() } ), AuroraConfigFieldHandler( "$key/azure/cnameTtl", validator = { it.int(false) } ), AuroraConfigFieldHandler( "$key/cname/enabled", validator = { it.boolean(false) } ), AuroraConfigFieldHandler( "$key/cname/ttl", validator = { it.int(false) } ), AuroraConfigFieldHandler( "$key/host" ), AuroraConfigFieldHandler( "$key/fullyQualifiedHost", validator = { it.boolean(false) }, defaultValue = false ), // since this is internal I do not want default value on it. AuroraConfigFieldHandler( "$key/path", validator = { it?.startsWith("/", "Path must start with /") } ), AuroraConfigFieldHandler("$key/tls/enabled", validator = { it.boolean() }), AuroraConfigFieldHandler( "$key/tls/insecurePolicy", validator = { it.oneOf(InsecurePolicy.values().map { v -> v.name }, required = false) } ), AuroraConfigFieldHandler( "$key/tls/termination", validator = { it.oneOf(TlsTermination.values().map { v -> v.name }, required = false) } ) ) + findRouteAnnotationHandlers(key, applicationFiles) }.toSet() } fun willCreateResource( adc: AuroraDeploymentSpec, cmd: AuroraContextCommand ): Boolean { val simplified = adc.isSimplifiedConfig(ROUTE_FEATURE_FIELD) if (simplified) { return adc[ROUTE_FEATURE_FIELD] } return cmd.applicationFiles.findSubKeys(ROUTE_FEATURE_FIELD).any { adc.isRouteEnabled(it) } } fun fetchExternalHostsAndPaths(adc: AuroraDeploymentSpec): List<String> { val routes = parseConfiguredRoutes(adc) val annotationeExternalPath = routes.filter { it.annotations[WEMBLEY_EXTERNAL_HOST_ANNOTATION_NAME] != null && it.annotations[WEBMLEY_API_PATHS_ANNOTATION_NAME] != null }.flatMap { val paths = it.annotations[WEBMLEY_API_PATHS_ANNOTATION_NAME]?.split(",") ?: emptyList() val name = it.annotations[WEMBLEY_EXTERNAL_HOST_ANNOTATION_NAME] paths.map { path -> "$name${path.trim()}" } } val fqdnRoute = routes.filter { it.fullyQualifiedHost }.map { it.url() } return annotationeExternalPath + fqdnRoute } private fun List<ConfiguredRoute>.generateCnames(namespace: String) = this.filter { it.cname != null } .mapNotNull { configuredRoute -> configuredRoute.cname?.generateAuroraCname( routeNamespace = namespace, routeSuffix = routeSuffix )?.let { generateResource(it) } }.toSet() private fun List<ConfiguredRoute>.generateAzureCnames(namespace: String) = this.filter { it.azureCname != null } .mapNotNull { configuredRoute -> configuredRoute.azureCname?.generateAuroraCname( routeNamespace = namespace, azureRouteSuffix = azureRouteSuffix )?.let { generateResource(it) } }.toSet() private fun List<ConfiguredRoute>.generateOpenshiftRoutes( namespace: String, name: String ): Set<AuroraResource> = this.flatMap { configuredRoute: ConfiguredRoute -> val openshiftRoute = configuredRoute.generateOpenShiftRoute( routeNamespace = namespace, serviceName = name, routeSuffix = configuredRoute.suffix(routeSuffix) ) val routeResource = generateResource(openshiftRoute) if (configuredRoute.shouldGenerateAzureRoute) { val azureRoute = configuredRoute.copy( objectName = configuredRoute.objectName.ensureEndsWith("-azure"), labels = mapOf("type" to "azure"), fullyQualifiedHost = true, tls = SecureRoute(InsecurePolicy.None, TlsTermination.edge) ) val azureRouteSuffix = configuredRoute.suffix(routeSuffix) val azureOpenshiftRoute = azureRoute.generateOpenShiftRoute( routeNamespace = namespace, serviceName = name, routeSuffix = azureRouteSuffix ) val azureRouteResource = generateResource(azureOpenshiftRoute) if (routeResource.resource.metadata.name == azureRouteResource.resource.metadata.name) { listOf(azureRouteResource) } else { listOf(routeResource, azureRouteResource) } } else { listOf(routeResource) } }.toSet() private fun validateHostCompliesToDns( routes: List<ConfiguredRoute>, applicationDeploymentRef: ApplicationDeploymentRef ): List<AuroraConfigException> { return routes .filter { !it.host.isValidDns() } .map { AuroraConfigException( "Application ${applicationDeploymentRef.application} in environment ${applicationDeploymentRef.environment} has invalid dns name \"${it.host}\"", errors = listOf( ConfigFieldErrorDetail.illegal(message = "host=${it.host} must be a valid dns entry.") ) ) } } private fun validateUniqueRouteHost( routes: List<ConfiguredRoute>, applicationDeploymentRef: ApplicationDeploymentRef ): AuroraConfigException? { val duplicatedHosts = routes.groupBy { listOf(it.host, it.path, it.labels?.get("type")) }.filter { it.value.size > 1 } return if (duplicatedHosts.isNotEmpty()) { AuroraConfigException( "Application ${applicationDeploymentRef.application} in environment ${applicationDeploymentRef.environment} have duplicated host+path configurations", errors = duplicatedHosts.map { route -> val (host, path, _) = route.key val pathField = path ?: "" val routesValues = route.value.joinToString(",") { it.objectName } ConfigFieldErrorDetail.illegal(message = "host=$host$pathField is not unique. Remove the configuration from one of the following routes $routesValues") } ) } else null } private fun validateUniquenessOfRoutenames( routes: List<ConfiguredRoute>, applicationDeploymentRef: ApplicationDeploymentRef ): AuroraConfigException? { val routeNames = routes.groupBy { it.objectName } val duplicateRoutes = routeNames.filter { it.value.size > 1 }.map { it.key } return if (duplicateRoutes.isNotEmpty()) { AuroraConfigException( "Application ${applicationDeploymentRef.application} in environment ${applicationDeploymentRef.environment} have routes with duplicate names", errors = duplicateRoutes.map { ConfigFieldErrorDetail.illegal(message = "Route name=$it is duplicated") } ) } else null } private fun validateTlsForRoutes( routes: List<ConfiguredRoute>, applicationDeploymentRef: ApplicationDeploymentRef ) = routes.mapNotNull { if (it.tls != null && it.host.contains('.') && !it.fullyQualifiedHost) { AuroraConfigException( "Application ${applicationDeploymentRef.application} in environment ${applicationDeploymentRef.environment} have a tls enabled route with a '.' in the host", errors = listOf(ConfigFieldErrorDetail.illegal(message = "Route name=${it.objectName} with tls uses '.' in host name")) ) } else { null } } } data class Cname( val routeHost: String, val ttl: Int, val objectName: String ) { fun generateAuroraCname(routeNamespace: String, routeSuffix: String) = AuroraCname( _metadata = newObjectMeta { name = objectName namespace = routeNamespace }, spec = CnameSpec( cname = routeHost, host = routeSuffix.removePrefix("."), ttl = ttl ) ) } data class AzureCname( val routeHost: String, val ttl: Int, val objectName: String ) { fun generateAuroraCname(routeNamespace: String, azureRouteSuffix: String) = AuroraAzureCname( _metadata = newObjectMeta { name = objectName namespace = routeNamespace }, spec = AzureCnameSpec( cname = routeHost, host = azureRouteSuffix.removePrefix("."), ttl = ttl ) ) } data class ConfiguredRoute( val objectName: String, val host: String, val path: String? = null, val annotations: Map<String, String> = emptyMap(), val labels: Map<String, String>? = null, val tls: SecureRoute? = null, val fullyQualifiedHost: Boolean = false, val shouldGenerateAzureRoute: Boolean = false, val cname: Cname? = null, val azureCname: AzureCname? = null ) { val target: String get(): String = if (path != null) "$host$path" else host val protocol: String get(): String = if (tls != null) "https://" else "http://" fun suffix(urlSuffix: String) = if (fullyQualifiedHost) "" else urlSuffix fun url(urlSuffix: String = ""): String { return "$host${suffix(urlSuffix)}".let { if (path != null) "$it${path.ensureStartWith("/")}" else it } } fun generateOpenShiftRoute( routeNamespace: String, serviceName: String, routeSuffix: String ): Route { val route = this return newRoute { metadata { name = route.objectName namespace = routeNamespace if (route.annotations.isNotEmpty()) { annotations = route.annotations.mapKeys { kv -> kv.key.replace("|", "/") } } labels = route.labels } spec { to { kind = "Service" name = serviceName } route.tls?.let { tls { insecureEdgeTerminationPolicy = it.insecurePolicy.name termination = it.termination.name.lowercase() } } port { targetPort = IntOrString("http") } host = if (routeSuffix.isEmpty()) { route.host } else { "${route.host}$routeSuffix" } route.path?.let { path = it } } } } fun getEnvVars(routeSuffix: String): List<EnvVar> { val urlSuffix = if (!fullyQualifiedHost) routeSuffix else "" val url = url(urlSuffix) return mapOf( "ROUTE_NAME" to url, "ROUTE_URL" to "${this.protocol}$url" ).toEnvVars() } } enum class InsecurePolicy { Redirect, None, Allow } enum class TlsTermination { edge, passthrough } data class SecureRoute( val insecurePolicy: InsecurePolicy, val termination: TlsTermination ) fun findRouteAnnotationHandlers( prefix: String, applicationFiles: List<AuroraConfigFile>, annotationsKey: String = "annotations" ): Set<AuroraConfigFieldHandler> { return applicationFiles.findSubHandlers("$prefix/$annotationsKey", validatorFn = { key -> { if (key.contains("/")) { IllegalArgumentException("Annotation $key cannot contain '/'. Use '|' instead") } else null } }).toSet() } private fun AuroraDeploymentSpec.isRouteEnabled(routeName: String = ""): Boolean { val isSimplified = routeName.isEmpty() return if (!isSimplified) { this["$ROUTE_FEATURE_FIELD/$routeName/enabled"] } else { this[ROUTE_FEATURE_FIELD] } } private fun AuroraDeploymentSpec.isAzureConfigured(routeName: String = ""): Boolean = this.isFieldEnabled(routeName, "azure") private fun AuroraDeploymentSpec.isTlsEnabled(routeName: String = ""): Boolean = this.isFieldEnabled(routeName, "tls") private fun AuroraDeploymentSpec.isFieldEnabled(routeName: String, field: String): Boolean { val isEnabledDefault: Boolean = this["$ROUTE_DEFAULTS_FEATURE_FIELD/$field/enabled"] if (routeName.isEmpty()) { return isEnabledDefault } val hasSubKeys = hasSubKeys("$ROUTE_FEATURE_FIELD/$routeName/$field") val isEnabled = this.getOrNull<Boolean>("$ROUTE_FEATURE_FIELD/$routeName/$field/enabled") if (isEnabled != null) { return isEnabled } return hasSubKeys || isEnabledDefault } private fun AuroraDeploymentSpec.isMsDnsCnameEnabled(routeName: String = "") = this.isFieldEnabled(routeName, "cname") private inline fun <reified T> AuroraDeploymentSpec.getRouteFieldOrDefault(routeName: String, suffix: String): T = this.getOrDefault(ROUTE_FEATURE_FIELD, routeName, suffix)
6
Kotlin
5
18
5a9e91f6f52d959395af7314c2f592074010d635
25,840
boober
Apache License 2.0
data/src/test/java/com/movie/data/mapper/mapperimpl/ArtistMapperImplTest.kt
kaminiprasad
729,903,395
false
{"Kotlin": 97578}
package com.movie.data.mapper.mapperimpl import com.movie.data.EXECUTIVE_PRODUCER import com.movie.data.MIKE_KELSON_CAST_ID import com.movie.data.getMovieCastDto import com.movie.data.getMovieCrewDto import com.movie.data.model.artist.ArtistDto import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class ArtistMapperImplTest { private lateinit var mapper: ArtistMapperImpl @Before fun setUp() { mapper = ArtistMapperImpl() } @OptIn(ExperimentalCoroutinesApi::class) @Test fun artistDtoTest() = runTest { val artist = mapper.map(data = ArtistDto(cast = getMovieCastDto(), crew = getMovieCrewDto(), -1)) assertEquals(MIKE_KELSON_CAST_ID, artist.cast.first().castId) assertEquals(EXECUTIVE_PRODUCER, artist.crew.first().job) assertEquals(2, artist.cast.size) assertEquals(2, artist.crew.size) } }
0
Kotlin
0
0
78507cb8306559be222925573f8575428967f694
1,012
MovieApplication
Apache License 2.0
src/test/kotlin/org/rust/ide/hints/RsQuickDefinitionTest.kt
mattsse
211,165,404
false
{"Gradle": 1, "Shell": 3, "YAML": 2, "Gradle Kotlin DSL": 1, "INI": 2, "Markdown": 5, "TOML": 5, "Text": 86, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Kotlin": 642, "Rust": 226, "XML": 62, "RenderScript": 1, "Java": 2, "HTML": 75, "SVG": 2, "JFlex": 3}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.hints import com.intellij.codeInsight.hint.ImplementationViewComponent import com.intellij.codeInsight.hint.actions.ShowImplementationsAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.intellij.lang.annotations.Language import org.rust.lang.RsTestBase class RsQuickDefinitionTest : RsTestBase() { fun `test struct`() = doTest(""" struct Foo { bar: i32 } fn bar(foo: Foo/*caret*/) {} """, """ struct Foo { bar: i32 } """) fun `test enum`() = doTest(""" enum Foo { L, R(i32) } fn bar(foo: Foo/*caret*/) {} """, """ enum Foo { L, R(i32) } """) fun `test trait`() = doTest(""" trait Foo { fn bar(&self); } fn bar<T: Foo/*caret*/>(foo: T) {} """, """ trait Foo { fn bar(&self); } """) fun `test type alias`() = doTest(""" type Foo = &'static str; fn bar(foo: Foo/*caret*/) {} """, """ type Foo = &'static str; """) fun `test const`() = doTest(""" const FOO: &'static [&str] = [ "some test text", "another test text" ]; fn main() { FOO/*caret*/; } """, """ const FOO: &'static [&str] = [ "some test text", "another test text" ]; """) fun `test function`() = doTest(""" fn foo() { } fn main() { foo/*caret*/(); } """, """ fn foo() { } """) fun `test method`() = doTest(""" struct Foo; impl Foo { fn foo(&self) { } } fn bar(foo: Foo) { foo.foo/*caret*/(); } """, """ fn foo(&self) { } """) fun `test field`() = doTest(""" struct Foo { bar: i32 } fn bar(foo: Foo) { foo.bar/*caret*/; } """, """ bar: i32 """) fun `test let binding`() = doTest(""" fn main() { let a = " Some text "; a/*caret*/; } """, """ let a = " Some text "; """) fun `test destructuring let binding`() = doTest(""" fn main() { let (a, b) = (" Some text ", 123); a/*caret*/; } """, """ let (a, b) = (" Some text ", 123); """) fun `test match arm`() = doTest(""" enum Foo { L, R(i32) } fn bar(foo: Foo) { match foo { L => {}, R(x) => { x/*caret*/; } } } """, """ R(x) => { x; } """) private fun doTest(@Language("Rust") code: String, expectedRaw: String) { InlineFile(code) var actualText: String? = null val action = object : ShowImplementationsAction() { override fun showImplementations(impls: Array<out PsiElement>, project: Project, text: String?, editor: Editor?, file: PsiFile?, element: PsiElement?, invokedFromEditor: Boolean, invokedByShortcut: Boolean) { if (impls.isEmpty()) return actualText = ImplementationViewComponent.getNewText(impls[0].navigationElement) } } action.performForContext((myFixture.editor as EditorEx).dataContext) checkNotNull(actualText) val expected = expectedRaw.lines() .dropWhile { it.isBlank() } .dropLastWhile { it.isBlank() } .joinToString("\n") check(actualText == expected) } }
1
null
1
1
fd96ed4524a6365ea89bfad3e761954a1361edbc
4,193
intellij-rust
MIT License
dbinspector/src/main/kotlin/com/infinum/dbinspector/data/models/local/proto/input/HistoryTask.kt
infinum
17,116,181
false
null
package com.infinum.dbinspector.data.models.local.proto.input import com.infinum.dbinspector.data.models.local.proto.output.HistoryEntity internal data class HistoryTask( val databasePath: String? = null, val execution: HistoryEntity.ExecutionEntity? = null, )
0
Kotlin
93
936
10b9ac5013ca01e602976a615e754dff7001f11d
271
android_dbinspector
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/problems/arrayandstrings/ContiguousSubarraysCount.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.problems.arrayandstrings fun main(args : Array<String>) { // Call countSubarrays() with test cases here println(countSubarrays(arrayOf(3,4,1,6,2))) println(countSubarrays(arrayOf(2, 4, 7, 1, 5, 3))) assert(countSubarrays(arrayOf(2, 4, 7, 1, 5, 3)) == listOf(1, 2, 6, 1, 3, 1)) } fun countSubarrays(args: Array<Int>): List<Int> { val outPut = mutableListOf<Int>() for ((idx, ele) in args.withIndex()) { var leftArray = 0 var rightArray = 0 var left = idx - 1 var right = idx + 1 while (left >= 0 && args[idx] > args[left]) { left-- } while ((right < args.size) && args[idx] > args[right]) { right++ } leftArray = idx - left rightArray = right - idx outPut.add(idx, leftArray + rightArray - 1) } return outPut }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
913
DS_Algo_Kotlin
MIT License
src/main/kotlin/com/rainbow/server/rest/dto/board/BoardResponse.kt
DDD-Community
649,288,543
false
null
package com.rainbow.server.rest.dto.board import com.rainbow.server.domain.board.entity.Board import java.time.ZonedDateTime /*** * 예시 Response * */ data class BoardResponse (var id:Long?, var writer:String, var title:String, var createdAt: ZonedDateTime, var updatedAt: ZonedDateTime, ) { companion object { fun from(board: Board): BoardResponse { return BoardResponse( id = board.id, writer = board.writer, title = board.title, createdAt=board.createdAt, updatedAt = board.updatedAt ) } } }
1
Kotlin
0
3
8e4d19ad0c63fc9e0c9b40c72df4c93773760ccc
764
Rainbow-Server
MIT License
03-testing/src/main/kotlin/com.jjh.util/DivideByZeroException.kt
johnehunt
328,627,201
false
null
package com.midmarsh.util class DivideByZeroException(val numerator: Double) : RuntimeException()
0
Kotlin
0
1
75f172d7f1127c5ec4062299409f9151945d6985
98
KotlinAdvanced
Apache License 2.0
shared/src/commonMain/kotlin/com/olympusblog/domain/util/DatetimeUtil.kt
sentrionic
551,827,184
false
null
package com.olympusblog.domain.util import kotlinx.datetime.* import kotlinx.datetime.TimeZone class DatetimeUtil { companion object { private const val SECOND_MILLIS: Long = 1000 private const val MINUTE_MILLIS = 60 * SECOND_MILLIS private const val HOUR_MILLIS = 60 * MINUTE_MILLIS private const val DAY_MILLIS = 24 * HOUR_MILLIS } fun humanizeDatetime(date: String): String { val time = Instant.parse(date) val diff = (Clock.System.now() - time).inWholeMilliseconds return when { diff < MINUTE_MILLIS -> "just now" diff < 2 * MINUTE_MILLIS -> "a minute ago" diff < 50 * MINUTE_MILLIS -> (diff / MINUTE_MILLIS).toString() + " minutes ago" diff < 90 * MINUTE_MILLIS -> "1 hour ago" diff < 24 * HOUR_MILLIS -> (diff / HOUR_MILLIS).toString() + " hours ago" diff < 48 * HOUR_MILLIS -> "yesterday" diff < 30 * DAY_MILLIS -> (diff / DAY_MILLIS).toString() + " days ago" else -> formatDate(time) } } private fun formatDate(time: Instant): String { val dateTimeUTC = time.toLocalDateTime(TimeZone.UTC) val datesList = dateTimeUTC.toString().split("-").asReversed() return datesList.joinToString(".") } }
0
Kotlin
0
0
bb61f26adcdded63b83c505d2f67c50715e8b859
1,313
OlympusKMM
MIT License
app/src/main/java/com/serma/dionysus/model/WebAppUserTableItemDtoWebAppTableDtoWebAppUserTableItemDtoWebAppResponseWithTableDto.kt
asuka1211
350,113,092
false
null
/** * Party maker API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.serma.dionysus.model import kotlinx.serialization.SerialName import java.io.Serializable /** * * @param isSuccess * @param isTimeout * @param isNotFound * @param message * @param errors * @param isInvalid * @param result */ data class WebAppImageResponseDtoWebAppResponseWithEntityDto ( @SerialName("isSuccess") val isSuccess: kotlin.Boolean? = null, @SerialName("isTimeout") val isTimeout: kotlin.Boolean? = null, @SerialName("isNotFound") val isNotFound: kotlin.Boolean? = null, @SerialName("message") val message: kotlin.String? = null, @SerialName("errors") val errors: kotlin.collections.List<WebAppErrorDto>? = null, @SerialName("isInvalid") val isInvalid: kotlin.Boolean? = null, @SerialName("result") val result: WebAppImageResponseDto? = null ) : Serializable { companion object { private const val serialVersionUID: Long = 123 } }
0
Kotlin
0
0
92c1a65d5b52e4d14907f32a3d7d10028aca783e
1,289
DionysusProject
Apache License 2.0
testutils/src/main/java/com/google/firebase/messaging/FirebaseMessagingService.kt
mParticle
42,615,957
false
{"Java": 1377154, "Kotlin": 1051457, "Groovy": 8314, "Shell": 4130, "JavaScript": 2582}
package com.google.firebase.messaging import android.content.Context object FirebaseMessagingServiceTestContext { var appContext: Context? = null } open class FirebaseMessagingService { var applicationContext: Context? get() = FirebaseMessagingServiceTestContext.appContext set(value) { FirebaseMessagingServiceTestContext.appContext = value } open fun onNewToken(token: String?) {} }
26
Java
62
58
94284f5f789f19872b21d75e063f9362675e217a
437
mparticle-android-sdk
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/iam/LazyRoleProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 140726596}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.iam import io.cloudshiftdev.awscdk.Duration import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.collections.Map /** * Properties for defining a LazyRole. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.*; * import io.cloudshiftdev.awscdk.services.iam.*; * ManagedPolicy managedPolicy; * PolicyDocument policyDocument; * IPrincipal principal; * LazyRoleProps lazyRoleProps = LazyRoleProps.builder() * .assumedBy(principal) * // the properties below are optional * .description("description") * .externalIds(List.of("externalIds")) * .inlinePolicies(Map.of( * "inlinePoliciesKey", policyDocument)) * .managedPolicies(List.of(managedPolicy)) * .maxSessionDuration(Duration.minutes(30)) * .path("path") * .permissionsBoundary(managedPolicy) * .roleName("roleName") * .build(); * ``` */ public interface LazyRoleProps : RoleProps { /** * A builder for [LazyRoleProps] */ @CdkDslMarker public interface Builder { /** * @param assumedBy The IAM principal (i.e. `new ServicePrincipal('sns.amazonaws.com')`) which * can assume this role. * You can later modify the assume role policy document by accessing it via * the `assumeRolePolicy` property. */ public fun assumedBy(assumedBy: IPrincipal) /** * @param description A description of the role. * It can be up to 1000 characters long. */ public fun description(description: String) /** * @param externalIds List of IDs that the role assumer needs to provide one of when assuming * this role. * If the configured and provided external IDs do not match, the * AssumeRole operation will fail. */ public fun externalIds(externalIds: List<String>) /** * @param externalIds List of IDs that the role assumer needs to provide one of when assuming * this role. * If the configured and provided external IDs do not match, the * AssumeRole operation will fail. */ public fun externalIds(vararg externalIds: String) /** * @param inlinePolicies A list of named policies to inline into this role. * These policies will be * created with the role, whereas those added by `addToPolicy` are added * using a separate CloudFormation resource (allowing a way around circular * dependencies that could otherwise be introduced). */ public fun inlinePolicies(inlinePolicies: Map<String, PolicyDocument>) /** * @param managedPolicies A list of managed policies associated with this role. * You can add managed policies later using * `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`. */ public fun managedPolicies(managedPolicies: List<IManagedPolicy>) /** * @param managedPolicies A list of managed policies associated with this role. * You can add managed policies later using * `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`. */ public fun managedPolicies(vararg managedPolicies: IManagedPolicy) /** * @param maxSessionDuration The maximum session duration that you want to set for the specified * role. * This setting can have a value from 1 hour (3600sec) to 12 (43200sec) hours. * * Anyone who assumes the role from the AWS CLI or API can use the * DurationSeconds API parameter or the duration-seconds CLI parameter to * request a longer session. The MaxSessionDuration setting determines the * maximum duration that can be requested using the DurationSeconds * parameter. * * If users don't specify a value for the DurationSeconds parameter, their * security credentials are valid for one hour by default. This applies when * you use the AssumeRole* API operations or the assume-role* CLI operations * but does not apply when you use those operations to create a console URL. */ public fun maxSessionDuration(maxSessionDuration: Duration) /** * @param path The path associated with this role. * For information about IAM paths, see * Friendly Names and Paths in IAM User Guide. */ public fun path(path: String) /** * @param permissionsBoundary AWS supports permissions boundaries for IAM entities (users or * roles). * A permissions boundary is an advanced feature for using a managed policy * to set the maximum permissions that an identity-based policy can grant to * an IAM entity. An entity's permissions boundary allows it to perform only * the actions that are allowed by both its identity-based policies and its * permissions boundaries. */ public fun permissionsBoundary(permissionsBoundary: IManagedPolicy) /** * @param roleName A name for the IAM role. * For valid values, see the RoleName parameter for * the CreateRole action in the IAM API Reference. * * IMPORTANT: If you specify a name, you cannot perform updates that require * replacement of this resource. You can perform updates that require no or * some interruption. If you must replace the resource, specify a new name. * * If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to * acknowledge your template's capabilities. For more information, see * Acknowledging IAM Resources in AWS CloudFormation Templates. */ public fun roleName(roleName: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.iam.LazyRoleProps.Builder = software.amazon.awscdk.services.iam.LazyRoleProps.builder() /** * @param assumedBy The IAM principal (i.e. `new ServicePrincipal('sns.amazonaws.com')`) which * can assume this role. * You can later modify the assume role policy document by accessing it via * the `assumeRolePolicy` property. */ override fun assumedBy(assumedBy: IPrincipal) { cdkBuilder.assumedBy(assumedBy.let(IPrincipal.Companion::unwrap)) } /** * @param description A description of the role. * It can be up to 1000 characters long. */ override fun description(description: String) { cdkBuilder.description(description) } /** * @param externalIds List of IDs that the role assumer needs to provide one of when assuming * this role. * If the configured and provided external IDs do not match, the * AssumeRole operation will fail. */ override fun externalIds(externalIds: List<String>) { cdkBuilder.externalIds(externalIds) } /** * @param externalIds List of IDs that the role assumer needs to provide one of when assuming * this role. * If the configured and provided external IDs do not match, the * AssumeRole operation will fail. */ override fun externalIds(vararg externalIds: String): Unit = externalIds(externalIds.toList()) /** * @param inlinePolicies A list of named policies to inline into this role. * These policies will be * created with the role, whereas those added by `addToPolicy` are added * using a separate CloudFormation resource (allowing a way around circular * dependencies that could otherwise be introduced). */ override fun inlinePolicies(inlinePolicies: Map<String, PolicyDocument>) { cdkBuilder.inlinePolicies(inlinePolicies.mapValues{PolicyDocument.unwrap(it.value)}) } /** * @param managedPolicies A list of managed policies associated with this role. * You can add managed policies later using * `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`. */ override fun managedPolicies(managedPolicies: List<IManagedPolicy>) { cdkBuilder.managedPolicies(managedPolicies.map(IManagedPolicy.Companion::unwrap)) } /** * @param managedPolicies A list of managed policies associated with this role. * You can add managed policies later using * `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`. */ override fun managedPolicies(vararg managedPolicies: IManagedPolicy): Unit = managedPolicies(managedPolicies.toList()) /** * @param maxSessionDuration The maximum session duration that you want to set for the specified * role. * This setting can have a value from 1 hour (3600sec) to 12 (43200sec) hours. * * Anyone who assumes the role from the AWS CLI or API can use the * DurationSeconds API parameter or the duration-seconds CLI parameter to * request a longer session. The MaxSessionDuration setting determines the * maximum duration that can be requested using the DurationSeconds * parameter. * * If users don't specify a value for the DurationSeconds parameter, their * security credentials are valid for one hour by default. This applies when * you use the AssumeRole* API operations or the assume-role* CLI operations * but does not apply when you use those operations to create a console URL. */ override fun maxSessionDuration(maxSessionDuration: Duration) { cdkBuilder.maxSessionDuration(maxSessionDuration.let(Duration.Companion::unwrap)) } /** * @param path The path associated with this role. * For information about IAM paths, see * Friendly Names and Paths in IAM User Guide. */ override fun path(path: String) { cdkBuilder.path(path) } /** * @param permissionsBoundary AWS supports permissions boundaries for IAM entities (users or * roles). * A permissions boundary is an advanced feature for using a managed policy * to set the maximum permissions that an identity-based policy can grant to * an IAM entity. An entity's permissions boundary allows it to perform only * the actions that are allowed by both its identity-based policies and its * permissions boundaries. */ override fun permissionsBoundary(permissionsBoundary: IManagedPolicy) { cdkBuilder.permissionsBoundary(permissionsBoundary.let(IManagedPolicy.Companion::unwrap)) } /** * @param roleName A name for the IAM role. * For valid values, see the RoleName parameter for * the CreateRole action in the IAM API Reference. * * IMPORTANT: If you specify a name, you cannot perform updates that require * replacement of this resource. You can perform updates that require no or * some interruption. If you must replace the resource, specify a new name. * * If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to * acknowledge your template's capabilities. For more information, see * Acknowledging IAM Resources in AWS CloudFormation Templates. */ override fun roleName(roleName: String) { cdkBuilder.roleName(roleName) } public fun build(): software.amazon.awscdk.services.iam.LazyRoleProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.iam.LazyRoleProps, ) : CdkObject(cdkObject), LazyRoleProps { /** * The IAM principal (i.e. `new ServicePrincipal('sns.amazonaws.com')`) which can assume this * role. * * You can later modify the assume role policy document by accessing it via * the `assumeRolePolicy` property. */ override fun assumedBy(): IPrincipal = unwrap(this).getAssumedBy().let(IPrincipal::wrap) /** * A description of the role. * * It can be up to 1000 characters long. * * Default: - No description. */ override fun description(): String? = unwrap(this).getDescription() /** * List of IDs that the role assumer needs to provide one of when assuming this role. * * If the configured and provided external IDs do not match, the * AssumeRole operation will fail. * * Default: No external ID required */ override fun externalIds(): List<String> = unwrap(this).getExternalIds() ?: emptyList() /** * A list of named policies to inline into this role. * * These policies will be * created with the role, whereas those added by `addToPolicy` are added * using a separate CloudFormation resource (allowing a way around circular * dependencies that could otherwise be introduced). * * Default: - No policy is inlined in the Role resource. */ override fun inlinePolicies(): Map<String, PolicyDocument> = unwrap(this).getInlinePolicies()?.mapValues{PolicyDocument.wrap(it.value)} ?: emptyMap() /** * A list of managed policies associated with this role. * * You can add managed policies later using * `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`. * * Default: - No managed policies. */ override fun managedPolicies(): List<IManagedPolicy> = unwrap(this).getManagedPolicies()?.map(IManagedPolicy::wrap) ?: emptyList() /** * The maximum session duration that you want to set for the specified role. * * This setting can have a value from 1 hour (3600sec) to 12 (43200sec) hours. * * Anyone who assumes the role from the AWS CLI or API can use the * DurationSeconds API parameter or the duration-seconds CLI parameter to * request a longer session. The MaxSessionDuration setting determines the * maximum duration that can be requested using the DurationSeconds * parameter. * * If users don't specify a value for the DurationSeconds parameter, their * security credentials are valid for one hour by default. This applies when * you use the AssumeRole* API operations or the assume-role* CLI operations * but does not apply when you use those operations to create a console URL. * * Default: Duration.hours(1) */ override fun maxSessionDuration(): Duration? = unwrap(this).getMaxSessionDuration()?.let(Duration::wrap) /** * The path associated with this role. * * For information about IAM paths, see * Friendly Names and Paths in IAM User Guide. * * Default: / */ override fun path(): String? = unwrap(this).getPath() /** * AWS supports permissions boundaries for IAM entities (users or roles). * * A permissions boundary is an advanced feature for using a managed policy * to set the maximum permissions that an identity-based policy can grant to * an IAM entity. An entity's permissions boundary allows it to perform only * the actions that are allowed by both its identity-based policies and its * permissions boundaries. * * Default: - No permissions boundary. */ override fun permissionsBoundary(): IManagedPolicy? = unwrap(this).getPermissionsBoundary()?.let(IManagedPolicy::wrap) /** * A name for the IAM role. * * For valid values, see the RoleName parameter for * the CreateRole action in the IAM API Reference. * * IMPORTANT: If you specify a name, you cannot perform updates that require * replacement of this resource. You can perform updates that require no or * some interruption. If you must replace the resource, specify a new name. * * If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to * acknowledge your template's capabilities. For more information, see * Acknowledging IAM Resources in AWS CloudFormation Templates. * * Default: - AWS CloudFormation generates a unique physical ID and uses that ID * for the role name. */ override fun roleName(): String? = unwrap(this).getRoleName() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): LazyRoleProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.iam.LazyRoleProps): LazyRoleProps = CdkObjectWrappers.wrap(cdkObject) as? LazyRoleProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: LazyRoleProps): software.amazon.awscdk.services.iam.LazyRoleProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.iam.LazyRoleProps } }
1
Kotlin
0
4
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
16,815
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/chat/rocket/android/server/domain/ChatRoomsInteractor.kt
RocketChat
48,179,404
false
null
package chat.rocket.android.server.domain import chat.rocket.core.model.ChatRoom import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject class ChatRoomsInteractor @Inject constructor(private val repository: ChatRoomsRepository) { /** * Get all [ChatRoom]. * * @param url The server url. * * @return All the [ChatRoom] objects. */ fun getAll(url: String) = repository.get(url) /** * Get a list of chat rooms that contains the name parameter. * * @param url The server url. * @param name The name of chat room to look for or a chat room that contains this name. * @return A list of ChatRoom objects with the given name. */ suspend fun getAllByName(url: String, name: String): List<ChatRoom> = withContext(Dispatchers.IO) { val allChatRooms = repository.get(url) if (name.isEmpty()) { return@withContext allChatRooms } return@withContext allChatRooms.filter { it.name.contains(name, true) } } /** * Get a specific [ChatRoom] by its id. * * @param serverUrl The server url where the room is. * @param roomId The id of the room to get. * @return The [ChatRoom] object or null if we couldn't find any. */ suspend fun getById(serverUrl: String, roomId: String): ChatRoom? = withContext(Dispatchers.IO) { return@withContext repository.get(serverUrl).find { it.id == roomId } } /** * Get a specific [ChatRoom] by its name. * * @param serverUrl The server url where the room is. * @param name The name of the room to get. * @return The [ChatRoom] object or null if we couldn't find any. */ fun getByName(serverUrl: String, name: String): ChatRoom? { return getAll(serverUrl).firstOrNull { it.name == name || it.fullName == name } } /** * Add a [ChatRoom]. * * @param url The server url. * @param chatRoom The [ChatRoom] to be added to the list. */ fun add(url: String, chatRoom: ChatRoom) { val chatRooms: MutableList<ChatRoom> = getAll(url).toMutableList() synchronized(this) { chatRooms.add(chatRoom) } repository.save(url, chatRooms) } /** * Removes a [ChatRoom]. * * @param url The server url. * @param chatRoom The [ChatRoom] to be removed from the list. */ fun remove(url: String, chatRoom: ChatRoom) { val chatRooms: MutableList<ChatRoom> = getAll(url).toMutableList() synchronized(this) { chatRooms.removeAll { chatRoom_ -> chatRoom_.id == chatRoom.id } } repository.save(url, chatRooms) } }
283
Kotlin
6
877
f832d59cb2130e5c058f5d9e9de5ff961d5d3380
2,834
Rocket.Chat.Android
MIT License
app/src/main/java/edu/cmu/sportsmatching/ui/login/LoginViewModelFactory.kt
ychu824
469,257,524
false
null
package edu.cmu.sportsmatching.ui.login import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import edu.cmu.sportsmatching.data.LoginDataSource import edu.cmu.sportsmatching.data.LoginRepository import java.lang.IllegalArgumentException class LoginViewModelFactory : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(LoginViewModel::class.java)) { return LoginViewModel( loginRepository = LoginRepository( dataSource = LoginDataSource() ) ) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
0
Kotlin
0
1
513ed0b226fc26c6eb07a70afd73c87ec9d2c1b2
752
SportsMatchingApp
MIT License
src/main/kotlin/homework_8/views/StartView.kt
al-volkov
340,614,622
false
{"Kotlin": 124832}
package homework_8.views import homework_8.GameController import homework_8.GameStylesheet import homework_8.model.Player import javafx.geometry.Pos import tornadofx.Fragment import tornadofx.View import tornadofx.action import tornadofx.addClass import tornadofx.button import tornadofx.vbox class StartView : View("Tic Tac Toe") { private val controller: GameController by inject() override val root = vbox { addClass(GameStylesheet.menuWindow) this.alignment = Pos.CENTER this.apply { button("Play with yourself") { addClass(GameStylesheet.menuButton) action { controller.isBotEnabled = false controller.isMultiplayerMode = false controller.startGame() } } button("Play with bot") { addClass(GameStylesheet.menuButton) action { controller.isBotEnabled = true controller.isMultiplayerMode = false find<ChooseSideFragment>().openModal() } } button("Play with other player") { addClass(GameStylesheet.menuButton) action { controller.isBotEnabled = false controller.isMultiplayerMode = true controller.startGame() } } } } } class ChooseSideFragment : Fragment() { private val fragment = this private val controller: GameController by inject() override val root = vbox { addClass(GameStylesheet.menuFragment) this.alignment = Pos.CENTER button(Player.FIRST.symbol.toString()) { addClass(GameStylesheet.menuFragmentButton) action { controller.player = Player.FIRST find<ChooseDifficultyFragment>().openModal() fragment.close() } } button(Player.SECOND.symbol.toString()) { addClass(GameStylesheet.menuFragmentButton) action { controller.player = Player.SECOND find<ChooseDifficultyFragment>().openModal() fragment.close() } } } } class ChooseDifficultyFragment : Fragment() { private val controller: GameController by inject() private val fragment = this override val root = vbox { this.alignment = Pos.CENTER addClass(GameStylesheet.menuFragment) button("Easy bot") { addClass(GameStylesheet.menuFragmentButton) action { controller.isBotDifficult = false controller.startGame() fragment.close() } } button("Difficult bot") { addClass(GameStylesheet.menuFragmentButton) action { controller.isBotDifficult = true controller.startGame() fragment.close() } } } }
0
Kotlin
0
0
5049681dd2a57625309584a6e50b9a6e0b65948a
3,065
spbu_2020_kotlin_homeworks
Apache License 2.0
src/main/kotlin/net/petrabarus/pdfwatermarker/App.kt
petrabarus
138,038,699
false
{"Kotlin": 11073}
package net.petrabarus.pdfwatermarker import com.beust.jcommander.JCommander import com.beust.jcommander.Parameter import com.beust.jcommander.ParameterException import java.io.File fun main(args: Array<String>) { val app = App(args) try { app.parseArgs() } catch (e: ParameterException) { System.err.println(e.message) app.printUsage() return } if (app.help) { app.printUsage() return } app.run() } class App(private val args: Array<String>) { @Parameter(names = ["-o", "--output"], required = false, description = "Output of the result, if empty will overwrite the PDF file") var outputFilePath: String? = null @Parameter(names = ["--help"], help = true) var help = false //TODO: Validator @Parameter(arity = 2, description = "<Path to PDF file> <Path to PNG stamp file>") lateinit var params: List<String> private var jCommander: JCommander = JCommander.newBuilder() .addObject(this) .build() val pdfFile: File get() = File(params[0]) val stampFile: File get() = File(params[1]) val outputFile: File get() = if (outputFilePath != null) File(outputFilePath) else pdfFile fun parseArgs() { jCommander.parse(*args) } fun printUsage() { jCommander.usage() } fun run () { val watermarker = Watermarker(pdfFile, stampFile, outputFile) watermarker.watermark() } }
0
Kotlin
0
1
ec1a94c7d17d64553520e4ccbdf7397bb5ef7878
1,501
pdfwatermarker
MIT License
nats-core/src/commonMain/kotlin/nats/core/protocol/ktor.kt
dimensional-fun
669,184,682
false
{"Kotlin": 234897}
package dimensional.knats.protocol import dimensional.knats.tools.CRLF import dimensional.knats.tools.SPACE import dimensional.knats.tools.ktor.readFully import dimensional.knats.tools.ktor.readUntilDelimitersTo import io.ktor.utils.io.* import io.ktor.utils.io.core.* import naibu.common.pool.use import naibu.io.SmallMemoryPool import naibu.io.slice.Slice import naibu.io.slice.contentEquals import naibu.io.slice.get import naibu.text.charset.Charset import naibu.text.charset.Charsets import naibu.text.charset.decodeIntoString import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract internal fun Byte.estimateOpLength(): Int? = when (toInt().toChar().uppercaseChar()) { 'M', '+' -> 3 'I', 'H', 'P', '-' -> 4 else -> null } internal suspend fun ByteReadChannel.ensureCRLF() = SmallMemoryPool.use { crlf -> readFully(crlf, 0, 2) require(crlf[0..1] eq CRLF) { "Didn't read CRLF, got ${crlf[0..1].decodeIntoString()}" } } @OptIn(ExperimentalContracts::class) internal suspend inline fun <T> ByteReadChannel.ensureCRLF(block: (ByteReadChannel) -> T): T { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return try { block(this) } finally { ensureCRLF() } } public suspend fun ByteReadChannel.readUntilCRLF(): ByteReadPacket = buildPacket { readUntilDelimitersTo(CRLF, this) } internal inline infix fun Slice.eq(other: ByteArray) = contentEquals(other) internal suspend fun ByteWriteChannel.writeAsText(value: Any) = writeStringUtf8(value.toString()) internal suspend fun ByteWriteChannel.writeSubject(value: String) = writeTextNaibu(value, charset = Charsets.US_ASCII) internal suspend fun <T> ByteWriteChannel.writeArgument(value: T?, block: suspend ByteWriteChannel.(T) -> Unit) { if (value == null) return writeByte(SPACE) block(value) } internal fun Output.writeCRLF() = writeFully(CRLF) internal suspend fun ByteWriteChannel.writeCRLF() = writeFully(CRLF) internal suspend fun ByteWriteChannel.writeTextNaibu(value: CharSequence, charset: Charset) { val bytes = charset.encode(value.toString(), value.indices) writeFully(bytes) }
1
Kotlin
0
2
049e0e32a292272a7eae0bfca99ecf8c8b690cb3
2,225
nats.kt
Apache License 2.0
data/src/main/java/base/smartservices/com/data/source/MinionCacheDataStore.kt
cnabilou
148,243,647
false
null
package base.smartservices.com.data.source import base.smartservices.com.data.model.MinionEntity import base.smartservices.com.data.repository.MinionCache import base.smartservices.com.data.repository.MinionDataStore import io.reactivex.Completable import io.reactivex.Single import javax.inject.Inject /** * Implementation of the [MinionDataStore] interface to provide a means of communicating * with the local data source */ open class MinionCacheDataStore @Inject constructor( private val minionCache: MinionCache): MinionDataStore { /** * Clear all the minions from the cache */ override fun clearMinions(): Completable { return minionCache.clearMinions() } /** * Save a given [List] of [MinionEntity] instances to the cache */ override fun saveMinions(minions: List<MinionEntity>): Completable { return minionCache.saveMinions(minions) } override fun saveMinion(minion: MinionEntity): Completable { return minionCache.saveMinion(minion) } /** * Retrieve a list of [MinionEntity] instance from the cache. */ override fun getMinions(): Single<List<MinionEntity>> { return minionCache.getMinions() } }
0
Kotlin
0
2
2edde45c61f779f1e34980d3cc590b1098507891
1,222
android-clean-architecture
MIT License
azure-storage-common/src/main/kotlin/jetbrains/buildServer/serverSide/artifacts/azure/AzureConstants.kt
JetBrains
87,163,663
false
null
package jetbrains.buildServer.serverSide.artifacts.azure import jetbrains.buildServer.agent.Constants object AzureConstants { const val STORAGE_TYPE = "azure-storage" const val SETTINGS_PATH = "azure_storage_settings" const val PARAM_ACCOUNT_NAME = "account-name" const val PARAM_ACCOUNT_KEY = Constants.SECURE_PROPERTY_PREFIX + "account-key" const val PARAM_CONTAINER_NAME = "container-name" const val PATH_PREFIX_ATTR = "azure_path_prefix" const val PATH_PREFIX_SYSTEM_PROPERTY = "storage.azure.path.prefix" const val URL_LIFETIME_SEC = "storage.azure.url.expiration.time.seconds" const val DEFAULT_URL_LIFETIME_SEC = 120 const val URL_HTTP_CACHE_MAX_AGE_SEC = "storage.azure.url.http.cache.max.age.seconds" const val DEFAULT_URL_HTTP_CACHE_MAX_AGE_SEC = 60 const val WRITE_BUFFER_SIZE_PROPERTY = "storage.azure.write.buffer.size" const val DEFAULT_WRITE_BUFFER_SIZE = 0x40_0000 const val WRITE_CONCURRENT_REQUEST_COUNT_PROPERTY = "storage.azure.write.concurrent.request.count" const val DEFAULT_TIMEOUT_INTERVAL_IN_MS = 60_000 const val TIMEOUT_INTERVAL_PROPERTY = "storage.azure.write.timeout" }
6
null
7
15
1971f1cf71392c4fa6e274d2d48d43d8b1accf3d
1,167
teamcity-azure-storage
Apache License 2.0
app/src/main/java/com/c22_pc383/wacayang/data/AppPreference.kt
Wacayang-Bangkit-2022
493,616,059
false
{"Kotlin": 91881}
package com.c22_pc383.wacayang.data import android.content.Context import android.content.SharedPreferences internal class AppPreference(ctx: Context) { private var pref: SharedPreferences = ctx.getSharedPreferences(APP_PREF_NAME, Context.MODE_PRIVATE) fun setCameraFlashPref(isFlashOn: Boolean) = pref.edit().putBoolean(CAM_FLASH_PREF, isFlashOn).apply() fun getCameraFlashPref(): Boolean = pref.getBoolean(CAM_FLASH_PREF, false) fun setToken(token: String) = pref.edit().putString(USER_TOKEN, token).apply() fun getToken(): String = pref.getString(USER_TOKEN, "") ?: "" fun clearToken() = pref.edit().remove(USER_TOKEN).apply() companion object { private const val APP_PREF_NAME = "wacayang_preference" private const val CAM_FLASH_PREF = "camera_flash" private const val USER_TOKEN = "user_token" } }
0
Kotlin
0
1
c1043c6395e85c7c52d854aea6b1c54460d8793f
863
Wacayang-MobileDev
Microsoft Public License
ui/src/main/java/com/youhajun/ui/models/states/LoginState.kt
YeonjunNotPed
757,175,597
false
{"Kotlin": 433776}
package com.youhajun.ui.models.states data class LoginState( val onProgress: Boolean = false, val onError: Boolean = false, )
0
Kotlin
0
0
6d8fa3166287b81908dcda09034995c5e6ceac43
134
MyTask
Apache License 2.0
AppRefil/app/src/main/java/es/refil/presentation/auth/registration/GoogleAuthUiClient.kt
Mj-br
637,882,177
false
{"Kotlin": 97361}
package es.refil.presentation.auth.registration import android.content.Context import android.content.Intent import android.content.IntentSender import com.google.android.gms.auth.api.identity.BeginSignInRequest import com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions import com.google.android.gms.auth.api.identity.SignInClient import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.GoogleAuthProvider import com.google.firebase.firestore.FirebaseFirestore import es.refil.R import es.refil.data.models.SignInResult import es.refil.data.models.User import es.refil.data.network.await import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ExperimentalCoroutinesApi import javax.inject.Inject //TODO: NEED TO DO MVVM, ALL OF THIS IS HAS TO BE IN AUTH REPOSITORY AND THEN IMPL //Class to sign in and to sign out with Google and also to get the user information about the user that is signed in class GoogleAuthUiClient @Inject constructor( private val context: Context, //The oneTapClient show us the dialog to sign in private val oneTapClient: SignInClient, ) { private val auth: FirebaseAuth = FirebaseAuth.getInstance() @OptIn(ExperimentalCoroutinesApi::class) suspend fun signIn(): IntentSender? { val result = try { oneTapClient.beginSignIn( buildSignInRequest() ).await() } catch (e: Exception) { e.printStackTrace() if(e is CancellationException) throw e null } return result?.pendingIntent?.intentSender } @OptIn(ExperimentalCoroutinesApi::class) suspend fun signInWithIntent(intent: Intent): SignInResult { val credential = oneTapClient.getSignInCredentialFromIntent(intent) val googleIdToken = credential.googleIdToken val googleCredentials = GoogleAuthProvider.getCredential(googleIdToken, null) return try { val user = auth.signInWithCredential(googleCredentials).await().user createFirestoreTable(user) SignInResult( data = user?.run { User( uid = uid, email = email, name = displayName, points = 0, // TODO: (POINTS DATA) CHANGE IF OVERWRITES OTHER POINTS bottles = 0, favorites = emptyList() ) }, errorMessage = null ) } catch (e: Exception){ e.printStackTrace() if(e is CancellationException) throw e SignInResult( data = null, errorMessage = e.message ) } //TODO: IMPLEMENTAR CREACION DE FIRESTORE CON GOOGLE } @OptIn(ExperimentalCoroutinesApi::class) suspend fun signOut(){ try { oneTapClient.signOut().await() auth.signOut() } catch (e: Exception){ e.printStackTrace() if (e is CancellationException) throw e } } fun getSignedInUser(): User? = auth.currentUser?.run { User( uid = uid, name = displayName, //TODO: (DO THE FUNCTION TO SEPARATE @ FROM NAME) email = email, points = 0, //TODO: (OVERWRITE TO 0??) bottles = 0 ) } private fun buildSignInRequest(): BeginSignInRequest { return BeginSignInRequest.Builder() .setGoogleIdTokenRequestOptions( GoogleIdTokenRequestOptions.builder() .setSupported(true) .setFilterByAuthorizedAccounts(false) .setServerClientId(context.getString(R.string.web_client_id)) .build() ) .setAutoSelectEnabled(true) .build() } } private fun createFirestoreTable(user: FirebaseUser?) { // Aquí debes implementar la lógica para crear la tabla en Firestore utilizando los datos del usuario // Puedes acceder a los datos del usuario como user.uid, user.email, etc. // Ejemplo: val firestore = FirebaseFirestore.getInstance() val newUserDocRef = firestore.collection("users").document(user?.uid!!) val userData = hashMapOf( "uid" to user.uid, "email" to user.email, "name" to user.displayName, "points" to 0, "bottles" to 0, "favorites" to emptyList<String>() ) newUserDocRef.set(userData) }
0
Kotlin
0
3
d4f9ff5b3652245334451255f445c0c4364252be
4,657
RefilApp
MIT License
compose-app/src/main/java/com/mapbox/maps/compose/testapp/examples/style/GenericStylePositionsActivity.kt
mapbox
330,365,289
false
null
package com.mapbox.maps.compose.testapp.examples.style import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.FloatingActionButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.mapbox.bindgen.Value import com.mapbox.maps.Style import com.mapbox.maps.compose.testapp.ExampleScaffold import com.mapbox.maps.compose.testapp.examples.utils.CityLocations import com.mapbox.maps.compose.testapp.examples.utils.offset import com.mapbox.maps.compose.testapp.ui.theme.MapboxMapComposeTheme import com.mapbox.maps.extension.compose.MapboxMap import com.mapbox.maps.extension.compose.animation.viewport.rememberMapViewportState import com.mapbox.maps.extension.compose.annotation.generated.CircleAnnotation import com.mapbox.maps.extension.compose.style.ColorValue import com.mapbox.maps.extension.compose.style.DoubleValue import com.mapbox.maps.extension.compose.style.GenericStyle import com.mapbox.maps.extension.compose.style.MapboxStyleComposable import com.mapbox.maps.extension.compose.style.Transition import com.mapbox.maps.extension.compose.style.layerPositionedContent import com.mapbox.maps.extension.compose.style.layers.generated.BackgroundLayer import com.mapbox.maps.extension.compose.style.layers.generated.CircleLayer import com.mapbox.maps.extension.compose.style.rememberStyleState import com.mapbox.maps.extension.compose.style.slotsContent import com.mapbox.maps.extension.compose.style.sources.GeoJSONData import com.mapbox.maps.extension.compose.style.sources.generated.rememberGeoJsonSourceState import com.mapbox.maps.extension.compose.style.styleImportsConfig /** * Example to showcase the usage of [slotsContent] and [layerPositionedContent] to arrange contents within the * base style using [GenericStyle] API. */ public class GenericStylePositionsActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { var styleUri by remember { mutableStateOf(Style.LIGHT) } var showTopSlotContent by remember { mutableStateOf(true) } var showMiddleSlotContent by remember { mutableStateOf(true) } var showLayerPositionedContent by remember { mutableStateOf(true) } var lightPresetConfig by remember { mutableStateOf("day") } var showBottomAnnotation by remember { mutableStateOf(true) } var showMiddleCircleLayer by remember { mutableStateOf(true) } val mapViewportState = rememberMapViewportState { setCameraOptions { zoom(ZOOM) center(CityLocations.HELSINKI) } } MapboxMapComposeTheme { ExampleScaffold( floatingActionButton = { Column { if (styleUri == Style.STANDARD) { FloatingActionButton( modifier = Modifier.padding(bottom = 10.dp), backgroundColor = if (styleUri == Style.STANDARD) MaterialTheme.colors.secondary else Color.LightGray, onClick = { showTopSlotContent = !showTopSlotContent }, shape = RoundedCornerShape(16.dp), ) { Text( modifier = Modifier.padding(10.dp), text = "Toggle top slot content - current: $showTopSlotContent" ) } FloatingActionButton( modifier = Modifier.padding(bottom = 10.dp), backgroundColor = if (styleUri == Style.STANDARD) MaterialTheme.colors.secondary else Color.LightGray, onClick = { showMiddleSlotContent = !showMiddleSlotContent }, shape = RoundedCornerShape(16.dp), ) { Text( modifier = Modifier.padding(10.dp), text = "Toggle middle slot content - current: $showMiddleSlotContent" ) } FloatingActionButton( modifier = Modifier.padding(bottom = 10.dp), backgroundColor = if (styleUri == Style.STANDARD) MaterialTheme.colors.secondary else Color.LightGray, onClick = { lightPresetConfig = if (lightPresetConfig == "day") "night" else "day" }, shape = RoundedCornerShape(16.dp), ) { Text( modifier = Modifier.padding(10.dp), text = "Toggle light preset - current: $lightPresetConfig" ) } } else { FloatingActionButton( modifier = Modifier.padding(bottom = 10.dp), backgroundColor = if (styleUri != Style.STANDARD) MaterialTheme.colors.secondary else Color.LightGray, onClick = { showLayerPositionedContent = !showLayerPositionedContent }, shape = RoundedCornerShape(16.dp), ) { Text( modifier = Modifier.padding(10.dp), text = "Toggle positioned layer content - current $showLayerPositionedContent" ) } } FloatingActionButton( modifier = Modifier.padding(bottom = 10.dp), onClick = { styleUri = if (styleUri == Style.LIGHT) { Style.STANDARD } else { Style.LIGHT } }, shape = RoundedCornerShape(16.dp), ) { Text( modifier = Modifier.padding(10.dp), text = "Toggle Style - current: ${styleUri.substringAfterLast('/')}" ) } FloatingActionButton( modifier = Modifier.padding(bottom = 10.dp), onClick = { showBottomAnnotation = !showBottomAnnotation }, shape = RoundedCornerShape(16.dp), ) { Text( modifier = Modifier.padding(10.dp), text = "Toggle bottom annotation - current: $showBottomAnnotation" ) } FloatingActionButton( modifier = Modifier.padding(bottom = 10.dp), onClick = { showMiddleCircleLayer = !showMiddleCircleLayer }, shape = RoundedCornerShape(16.dp), ) { Text( modifier = Modifier.padding(10.dp), text = "Toggle middle annotation - current: $showMiddleCircleLayer" ) } } } ) { MapboxMap( Modifier.fillMaxSize(), mapViewportState = mapViewportState, style = { MyStyle( styleUri = styleUri, showTopSlotContent = showTopSlotContent, showMiddleSlotContent = showMiddleSlotContent, showLayerPositionedContent = showLayerPositionedContent, lightPresetConfig = lightPresetConfig, ) } ) { if (showBottomAnnotation) { CircleAnnotation( point = CityLocations.HELSINKI.offset(0.005), ) { circleRadius = 30.0 circleColor = Color.Red } } if (showMiddleCircleLayer) { CircleLayer( sourceState = rememberGeoJsonSourceState { data = GeoJSONData(CityLocations.HELSINKI) } ) { circleColor = ColorValue(Color.Yellow) circleRadius = DoubleValue(30.0) } } CircleAnnotation( point = CityLocations.HELSINKI.offset(-0.005) ) { circleRadius = 30.0 circleColor = Color.Blue } } } } } } @Composable @MapboxStyleComposable private fun MyStyle( styleUri: String, showTopSlotContent: Boolean, showMiddleSlotContent: Boolean, showLayerPositionedContent: Boolean, lightPresetConfig: String ) { val geoJsonSource = rememberGeoJsonSourceState { data = GeoJSONData(CityLocations.HELSINKI) } GenericStyle( style = styleUri, slotsContent = slotsContent { // Only add background layer in slots for standard style, where the top and middle slot // are available. if (styleUri == Style.STANDARD) { if (showTopSlotContent) { slot("top") { CircleLayer( sourceState = geoJsonSource, ) { circleColor = ColorValue(Color.Cyan) circleRadius = DoubleValue(50.0) circleColorTransition = Transition(durationMillis = 1000L) } } } if (showMiddleSlotContent) { slot("middle") { BackgroundLayer { backgroundColor = ColorValue(Color.Red) backgroundOpacity = DoubleValue(0.3) } } } } }, layerPositionedContent = layerPositionedContent { // only add background layer below building layer if the style is not standard // style, where layers are available in runtime styling. if (styleUri != Style.STANDARD) { if (showLayerPositionedContent) { belowLayer("building") { BackgroundLayer { backgroundColor = ColorValue(Color.Yellow) backgroundOpacity = DoubleValue(0.3) } } } } }, styleState = rememberStyleState { styleImportsConfig = styleImportsConfig { importConfig("basemap") { config("lightPreset", Value(lightPresetConfig)) } } } ) } private companion object { const val ZOOM: Double = 9.0 } }
225
null
131
472
2700dcaf18e70d23a19fc35b479bff6a2d490475
10,990
mapbox-maps-android
Apache License 2.0
source/Goal-API/src/main/kotlin/br/lopes/goalapi/goal/api/GoalApiApplication.kt
thiagoolsilva
339,903,272
false
null
/* * Copyright (c) 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.lopes.goalapi.goal.api import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.data.web.config.EnableSpringDataWebSupport import springfox.documentation.swagger2.annotations.EnableSwagger2 @SpringBootApplication @EnableSpringDataWebSupport @EnableSwagger2 class GoalApiApplication fun main(args: Array<String>) { runApplication<GoalApiApplication>(*args) }
0
Kotlin
0
2
b2682c262c97d897bf7c878678a612a8d9aec346
1,075
goal_api
Apache License 2.0
econtext/src/main/java/com/adyen/checkout/econtext/internal/ui/DefaultEContextDelegate.kt
Adyen
91,104,663
false
null
/* * Copyright (c) 2023 Adyen N.V. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by ozgur on 13/1/2023. */ package com.adyen.checkout.econtext.internal.ui import androidx.annotation.VisibleForTesting import androidx.lifecycle.LifecycleOwner import com.adyen.checkout.components.core.Order import com.adyen.checkout.components.core.PaymentComponentData import com.adyen.checkout.components.core.PaymentComponentState import com.adyen.checkout.components.core.PaymentMethod import com.adyen.checkout.components.core.PaymentMethodTypes import com.adyen.checkout.components.core.internal.PaymentComponentEvent import com.adyen.checkout.components.core.internal.PaymentObserverRepository import com.adyen.checkout.components.core.internal.data.api.AnalyticsRepository import com.adyen.checkout.components.core.internal.ui.model.ButtonComponentParams import com.adyen.checkout.components.core.internal.ui.model.FieldState import com.adyen.checkout.components.core.internal.ui.model.Validation import com.adyen.checkout.components.core.internal.util.ValidationUtils import com.adyen.checkout.components.core.paymentmethod.EContextPaymentMethod import com.adyen.checkout.core.AdyenLogLevel import com.adyen.checkout.core.internal.util.adyenLog import com.adyen.checkout.econtext.R import com.adyen.checkout.econtext.internal.ui.model.EContextInputData import com.adyen.checkout.econtext.internal.ui.model.EContextOutputData import com.adyen.checkout.ui.core.internal.ui.ButtonComponentViewType import com.adyen.checkout.ui.core.internal.ui.ComponentViewType import com.adyen.checkout.ui.core.internal.ui.PaymentComponentUIEvent import com.adyen.checkout.ui.core.internal.ui.PaymentComponentUIState import com.adyen.checkout.ui.core.internal.ui.SubmitHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch @Suppress("TooManyFunctions", "LongParameterList") internal class DefaultEContextDelegate< EContextPaymentMethodT : EContextPaymentMethod, EContextComponentStateT : PaymentComponentState<EContextPaymentMethodT> >( private val observerRepository: PaymentObserverRepository, override val componentParams: ButtonComponentParams, private val paymentMethod: PaymentMethod, private val order: Order?, private val analyticsRepository: AnalyticsRepository, private val submitHandler: SubmitHandler<EContextComponentStateT>, private val typedPaymentMethodFactory: () -> EContextPaymentMethodT, private val componentStateFactory: ( data: PaymentComponentData<EContextPaymentMethodT>, isInputValid: Boolean, isReady: Boolean ) -> EContextComponentStateT ) : EContextDelegate<EContextPaymentMethodT, EContextComponentStateT> { private val inputData: EContextInputData = EContextInputData() private val _outputDataFlow = MutableStateFlow(createOutputData()) override val outputDataFlow: Flow<EContextOutputData> = _outputDataFlow override val outputData: EContextOutputData get() = _outputDataFlow.value private val _componentStateFlow = MutableStateFlow(createComponentState()) override val componentStateFlow: Flow<EContextComponentStateT> = _componentStateFlow private val _viewFlow: MutableStateFlow<ComponentViewType?> = MutableStateFlow(EContextComponentViewType) override val viewFlow: Flow<ComponentViewType?> = _viewFlow override val submitFlow: Flow<EContextComponentStateT> = submitHandler.submitFlow override val uiStateFlow: Flow<PaymentComponentUIState> = submitHandler.uiStateFlow override val uiEventFlow: Flow<PaymentComponentUIEvent> = submitHandler.uiEventFlow override fun initialize(coroutineScope: CoroutineScope) { submitHandler.initialize(coroutineScope, componentStateFlow) setupAnalytics(coroutineScope) } private fun setupAnalytics(coroutineScope: CoroutineScope) { adyenLog(AdyenLogLevel.VERBOSE) { "setupAnalytics" } coroutineScope.launch { analyticsRepository.setupAnalytics() } } override fun updateInputData(update: EContextInputData.() -> Unit) { inputData.update() onInputDataChanged() } private fun onInputDataChanged() { val outputData = createOutputData() _outputDataFlow.tryEmit(outputData) updateComponentState(outputData) } private fun createOutputData(): EContextOutputData { return EContextOutputData( firstNameState = validateFirstName(inputData.firstName), lastNameState = validateLastName(inputData.lastName), phoneNumberState = validatePhoneNumber(inputData.mobileNumber, inputData.countryCode), emailAddressState = validateEmailAddress(inputData.emailAddress), ) } @VisibleForTesting internal fun updateComponentState(outputData: EContextOutputData) { val componentState = createComponentState(outputData) _componentStateFlow.tryEmit(componentState) } private fun createComponentState( outputData: EContextOutputData = this.outputData ): EContextComponentStateT { val eContextPaymentMethod = typedPaymentMethodFactory().apply { type = getPaymentMethodType() checkoutAttemptId = analyticsRepository.getCheckoutAttemptId() firstName = outputData.firstNameState.value lastName = outputData.lastNameState.value telephoneNumber = outputData.phoneNumberState.value shopperEmail = outputData.emailAddressState.value } val isInputValid = outputData.isValid val paymentComponentData = PaymentComponentData( paymentMethod = eContextPaymentMethod, order = order, amount = componentParams.amount, ) return componentStateFactory(paymentComponentData, isInputValid, true) } private fun validateFirstName(firstName: String): FieldState<String> { val validation = if (firstName.isNotBlank()) { Validation.Valid } else { Validation.Invalid(R.string.checkout_econtext_first_name_invalid) } return FieldState(firstName, validation) } private fun validateLastName(lastName: String): FieldState<String> { val validation = if (lastName.isNotBlank()) { Validation.Valid } else { Validation.Invalid(R.string.checkout_econtext_last_name_invalid) } return FieldState(lastName, validation) } private fun validatePhoneNumber(phoneNumber: String, countryCode: String): FieldState<String> { val sanitizedNumber = phoneNumber.trimStart('0') val fullPhoneNumber = countryCode + sanitizedNumber val validation = if (fullPhoneNumber.isNotEmpty() && ValidationUtils.isPhoneNumberValid(fullPhoneNumber)) { Validation.Valid } else { Validation.Invalid(R.string.checkout_econtext_phone_number_invalid) } return FieldState(fullPhoneNumber, validation) } private fun validateEmailAddress(emailAddress: String): FieldState<String> { val validation = if (emailAddress.isNotEmpty() && ValidationUtils.isEmailValid(emailAddress)) { Validation.Valid } else { Validation.Invalid(R.string.checkout_econtext_shopper_email_invalid) } return FieldState(emailAddress, validation) } override fun getPaymentMethodType(): String { return paymentMethod.type ?: PaymentMethodTypes.UNKNOWN } override fun observe( lifecycleOwner: LifecycleOwner, coroutineScope: CoroutineScope, callback: (PaymentComponentEvent<EContextComponentStateT>) -> Unit ) { observerRepository.addObservers( stateFlow = componentStateFlow, exceptionFlow = null, submitFlow = submitFlow, lifecycleOwner = lifecycleOwner, coroutineScope = coroutineScope, callback = callback, ) } override fun removeObserver() { observerRepository.removeObservers() } override fun onCleared() { removeObserver() } override fun onSubmit() { val state = _componentStateFlow.value submitHandler.onSubmit(state) } override fun isConfirmationRequired(): Boolean { return _viewFlow.value is ButtonComponentViewType } override fun shouldShowSubmitButton(): Boolean { return isConfirmationRequired() && componentParams.isSubmitButtonVisible } override fun setInteractionBlocked(isInteractionBlocked: Boolean) { submitHandler.setInteractionBlocked(isInteractionBlocked) } }
31
null
66
96
1f000e27e07467f3a30bb3a786a43de62be003b2
8,839
adyen-android
MIT License
app/src/main/java/com/aquatic/lucre/repositories/VaultStore.kt
kingsleyzissou
324,988,352
false
null
package com.aquatic.lucre.repositories import androidx.core.util.Predicate import com.aquatic.lucre.models.Vault import com.google.firebase.firestore.CollectionReference import io.reactivex.rxjava3.core.Observable import kotlinx.coroutines.tasks.await /** * VaultStore for storing and retrieving * vault items. The store is saved to a * json file. */ class VaultStore(store: CollectionReference) : CRUDStore<Vault>(store) { /** * List all the items for a given model */ override suspend fun all(): List<Vault> { return store.get().await().map { it.toObject(Vault::class.java) } } /** * Specific function for filtering the Vault items * by a custom predicate. In the app, this is generally * by a date and a vault id */ suspend fun where(key: String, value: Any): List<Vault> { return store.whereEqualTo(key, value).get().await().map { it.toObject(Vault::class.java) } } /** * Find a specific entry by the entry id */ override suspend fun find(id: String): Vault? { return store.document(id).get().await().toObject(Vault::class.java) } /** * Subscribe to live updates from the vault store */ override fun subscribe(predicate: Predicate<Vault>?): Observable<List<Vault>> { return Observable.create { store.addSnapshotListener { snapshot, _ -> val vaults = snapshot?.toObjects(Vault::class.java)?.filter { if (predicate == null) true else predicate.test(it) } it.onNext(vaults) } } } }
0
Kotlin
0
0
f52a075869e1bf5159569e46d0ef276cd8944130
1,623
lucre
Apache License 2.0
app/src/main/java/com/tungnui/abccomputer/adapter/ProductsLinearAdapter.kt
ngthtung2805
105,776,185
false
null
package com.tungnui.abccomputer.adapter import android.graphics.Paint import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.tungnui.abccomputer.R import com.tungnui.abccomputer.SettingsMy import com.tungnui.abccomputer.models.Product import com.tungnui.abccomputer.utils.* import kotlinx.android.synthetic.main.list_item_product_grid.view.* import java.util.ArrayList /** * Adapter handling list of product items. */ class ProductsGridAdapter(val listener: (Product) -> Unit) : RecyclerView.Adapter<ProductsGridAdapter.ViewHolder>() { private val products = ArrayList<Product>() override fun getItemCount(): Int { return products.size } fun addProducts(productList: List<Product>) { products.addAll(productList) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductsGridAdapter.ViewHolder = ViewHolder(parent.inflate(R.layout.list_item_product_grid)) override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.blind(products[position],listener) } fun clear() { products.clear() } // Provide a reference to the views for each data item class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { fun blind(item:Product,listener: (Product) -> Unit)=with(itemView){ var user = SettingsMy.getActiveUser() product_item_name.text = item.name product_item_image.loadGlideImg(item.images?.getFeaturedImage()?.src) if(user != null && user.role =="administrator"){ layoutAdmin.visibility= View.VISIBLE layoutUser.visibility = View.GONE capital_price.text = "V: ${item.metaData?.getCapitalPrice()?.formatPrice()}" regular_price.text = "B: ${item.regularPrice?.formatPrice()}" sale_price.text = "KM: ${item.salePrice?.formatPrice()}" stock_quantity.text ="Tồn :${item.stockQuantity.toString()}" sale_quantity.text = "Bán :${item.totalSales.toString()}" }else{ layoutAdmin.visibility= View.GONE layoutUser.visibility = View.VISIBLE item.averageRating?.toFloat()?.let{product_item_rating.rating = it } product_item_rating_count.text = "(" + item.ratingCount + ")" if(item.onSale){ product_item_price.visibility = View.VISIBLE product_item_regular_price.visibility = View.VISIBLE product_item_price.text = item.price?.formatPrice() product_item_regular_price.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG product_item_regular_price.text = item.regularPrice?.formatPrice() }else{ product_item_price.visibility = View.VISIBLE product_item_regular_price.visibility = View.GONE product_item_price.text =item.price?.formatPrice() } } setOnClickListener { listener(item) } } } }
1
Kotlin
1
1
f80905971310015cc4444b838395f70432a71c8b
3,194
dalatlaptop
MIT License
time/src/commonMain/kotlin/com/merseyside/merseyLib/time/ext/TimeRangeExt.kt
Merseyside
396,607,192
false
null
package com.merseyside.merseyLib.time.ext import com.merseyside.merseyLib.kotlin.logger.Logger import com.merseyside.merseyLib.time.* import com.merseyside.merseyLib.time.ranges.MonthRange import com.merseyside.merseyLib.time.ranges.TimeRange import com.merseyside.merseyLib.time.ranges.TimeUnitRange import com.merseyside.merseyLib.time.ranges.inc import com.merseyside.merseyLib.time.units.* import com.merseyside.merseyLib.time.utils.Pattern fun TimeRange.isEmpty(): Boolean { return start.isEmpty() && end.isEmpty() } fun TimeRange.toTimeUnitRange(): TimeUnitRange { return if (this is TimeUnitRange) this else TimeUnitRange(start, end) } fun <T : TimeRange> List<T>.findEdge(): TimeUnitRange { if (isEmpty()) throw IllegalArgumentException("List can not be empty!") val mutList = this.toMutableList() return if (size > 1) { val first = mutList.removeFirst() var min: TimeUnit = first.start var max: TimeUnit = first.end mutList.forEach { timeUnit -> timeUnit.start.let { if (it < min) min = it } timeUnit.end.let { if (it > max) max = it } } TimeUnitRange(min, max) } else { TimeUnitRange(first().start, first().end) } } fun <T : TimeRange> List<T>.findEdge(block: (TimeUnitRange) -> T): T { val range = findEdge() return block(range) } fun <T : TimeRange> T.toDaysOfWeek(): List<DayOfWeek> { return if (getGap() > Weeks(1)) { DayOfWeek.values().toList() } else { val startDay = start.toDayOfWeek() val endDay = end.toDayOfWeek() if (startDay == endDay) { if (getGap() < Days(1)) { return listOf(startDay) } else { DayOfWeek.values().toList() } } else { val list = DayOfWeek.values().toMutableList() if (endDay.index < startDay.index) { val indexRange = (endDay.index + 1 until startDay.index) list.filter { !indexRange.contains(it.index) }.toList() } else { val indexRange = (startDay.index..endDay.index) list.filter { indexRange.contains(it.index) }.toList() } } } } fun <T : TimeRange> List<T>.toDaysOfWeek(): List<DayOfWeek> { val range = findEdge() return range.toDaysOfWeek() } fun TimeRange.toRangeList(gap: TimeUnit): List<TimeRange> { val list = mutableListOf<TimeRange>() var newRange: TimeRange = TimeUnitRange(start, start + gap) list.add(intersect(newRange) ?: throw Exception("Should never happened")) while(newRange.end < end) { newRange = newRange.shift(gap) list.add(newRange) } return list } fun TimeRange.toTimeUnitList(gap: TimeUnit): List<TimeUnit> { val list = mutableListOf<TimeUnit>() var timeUnit: TimeUnit = start list.add(timeUnit) while(timeUnit < end) { timeUnit += gap if (contains(timeUnit)) { list.add(timeUnit) } else { end } } return list } fun TimeRange.toMonthRanges(): List<MonthRange> { val monthRanges = ArrayList<MonthRange>() var tempRange = start.toMonthRange() while(tempRange.end <= this.end) { monthRanges.add(tempRange) ++tempRange } return monthRanges } fun TimeRange.toDayRanges(): List<TimeRange> { var nextDay = start.getNextDay() val dayRanges = mutableListOf<TimeRange>() dayRanges.add(TimeUnitRange(start, nextDay.excludeMilli())) while (nextDay < end) { val tempNextDay = nextDay.getNextDay() val endTime = if (tempNextDay < end) tempNextDay.excludeMilli() else end dayRanges.add(TimeUnitRange(nextDay, endTime)) nextDay = tempNextDay } return dayRanges } @Throws(IllegalArgumentException::class) fun TimeRange.toHoursMinutesOfDay(): TimeUnitRange { val start = start.toHoursMinutesOfDay() var end = end.toHoursMinutesOfDay() if (end.isEmpty()) { end = Days(1).excludeMilli() } return TimeUnitRange(start, end) } fun TimeRange.isIntersect(other: TimeRange, includeLastMilli: Boolean = false): Boolean { return contains(other.start, includeLastMilli) || contains(other.end, includeLastMilli) || other.contains(start, includeLastMilli) || other.contains(end, includeLastMilli) } fun TimeRange.contains(other: TimeRange, includeLastMilli: Boolean = true): Boolean { return start <= other.start && getEndValue(includeLastMilli) >= other.getEndValue(includeLastMilli) } fun TimeRange.contains(timeUnit: TimeUnit, includeLastMilli: Boolean = true): Boolean { return timeUnit in start..getEndValue(includeLastMilli) } fun TimeRange.getGap(): TimeUnit { return end - start } fun TimeRange.shift(timeUnit: TimeUnit): TimeRange { return TimeUnitRange(start + timeUnit, end + timeUnit) } fun TimeRange.shiftBack(timeUnit: TimeUnit): TimeRange { return TimeUnitRange(start - timeUnit, end - timeUnit) } fun TimeRange.shiftOnGap(): TimeRange { val gap = getGap() return TimeUnitRange(start + gap, end + gap) } fun TimeRange.shiftBackOnGap(): TimeRange { val gap = getGap() return TimeUnitRange(start - gap, end - gap) } fun TimeRange.uniteWith(other: TimeRange): TimeRange { checkIntersection(other) val start = min(start, other.start) val end = max(end, other.end) return TimeUnitRange(start, end) } fun TimeRange.intersect(other: TimeRange, includeLastMilli: Boolean = true): TimeRange? { return if (isIntersect(other, includeLastMilli)) { when { contains(other, includeLastMilli) -> other other.contains(this, includeLastMilli) -> this else -> { val start = if (contains(other.start, includeLastMilli)) other.start else this.start val end = if (contains(other.end, includeLastMilli)) other.end else this.end TimeUnitRange(start, end) } } } else null } fun TimeRange.roundByDivider(divider: TimeUnit): TimeRange { return TimeUnitRange(start.roundByDivider(divider), end.roundByDivider(divider)) } /** * Use $1 and $2 for start and end values accordingly. */ fun TimeRange.toHumanString( format: String = "$1 - $2", pattern: Pattern = Time.configuration.defaultPattern, includeLastMilli: Boolean = true ): String { return format.replace("$1", start.toFormattedDate(pattern).date) .replace("$2", getEndValue(includeLastMilli).toFormattedDate(pattern).date) } fun TimeRange.toHumanString( format: String = "$1 - $2", pattern: String, includeLastMilli: Boolean = true ): String { return toHumanString(format, Pattern.CUSTOM(pattern), includeLastMilli) } fun <T : TimeRange> T.logHuman( tag: String = this::class.simpleName ?: "ITimeRange", prefix: String = "", suffix: String = "" ): T { Logger.log( tag, "$prefix start = ${start.getHumanDate()} end = ${end.getHumanDate()} $suffix" ) return this } fun <T : TimeRange> List<T>.logHuman( tag: String = this::class.simpleName ?: "ITimeRange", prefix: String = "" ): List<T> { forEach { it.logHuman(tag, prefix) } return this } fun TimeRange.getEndValue(includeLastMilli: Boolean = true): TimeUnit { return end.includeMilli(includeLastMilli) } fun TimeRange.excludeMilli(): TimeRange { return TimeUnitRange(start, end.excludeMilli()) } private fun TimeRange.checkIntersection(other: TimeRange) { if (!isIntersect(other)) throw IllegalArgumentException("Ranges don't intersect!") }
0
Kotlin
0
0
ebef4db3b924440bdeaf0711164cab446e41ec5b
7,630
mersey-kmp-time
Apache License 2.0
features/task/impl/src/main/java/wottrich/github/io/smartchecklist/domain/usecase/GetSortItemListUseCase.kt
Wottrich
295,605,540
false
{"Kotlin": 354976}
package wottrich.github.io.smartchecklist.domain.usecase import wottrich.github.io.smartchecklist.coroutines.KotlinResultUseCase import wottrich.github.io.smartchecklist.coroutines.UseCase import wottrich.github.io.smartchecklist.coroutines.base.Result import wottrich.github.io.smartchecklist.domain.repository.SortItemRepository import wottrich.github.io.smartchecklist.presentation.ui.sort.SortItem class GetSortItemListUseCase( private val sortItemRepository: SortItemRepository ) : KotlinResultUseCase<UseCase.None, List<SortItem>>() { override suspend fun execute(params: UseCase.None): Result<List<SortItem>> { return try { val result = sortItemRepository.getSortItemTypeList().map { SortItem( it, it.name == sortItemRepository.getSelectedSortItem().name ) } Result.success(result) } catch (ex: Exception) { Result.failure(ex) } } }
12
Kotlin
0
8
5d4e9f6fc83d657a1ec7ecf067227aeb8855c7a8
997
android-smart-checklist
MIT License
transport/transport-serialization/src/commonMain/kotlin/io/github/vooft/kafka/transport/serialization/SerializationExtensions.kt
vooft
802,782,830
false
{"Kotlin": 216560, "Makefile": 643}
package io.github.vooft.kafka.transport.serialization import io.github.vooft.kafka.serialization.KafkaSerde import kotlinx.io.Sink import kotlinx.io.Source import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.SerializationStrategy import kotlinx.serialization.serializer inline fun <reified T> Source.decode(): T = KafkaSerde.decode(serializer(), this) fun <T> Source.decode(deserializer: DeserializationStrategy<T>): T = KafkaSerde.decode(deserializer, this) inline fun <reified T> Sink.encode(value: T) = encode(serializer(), value) fun <T> Sink.encode(serializer: SerializationStrategy<T>, value: T) = KafkaSerde.encode(serializer, value, this)
0
Kotlin
0
1
6c7941ad829f2a2f74b934269432d753ffda306e
680
kotlin-kafka-client
Apache License 2.0
app/src/main/java/com/ramezmikhael/mvibasicexample/model/MessageViewState.kt
ramez-mikhael-dexcom
480,050,600
false
{"Kotlin": 8981}
package com.ramezmikhael.mvibasicexample.model data class MessageViewState( val message: String = "", val errorMessage: String = "", val errorMessageVisible: Boolean = false, val progressBarVisible: Boolean = false, val sendButtonEnabled: Boolean = false, )
0
Kotlin
1
1
1cd6d3fc1035e331984c4f6e0b13c450f98d8978
278
basic-mvi
MIT License
hyd-compiler/src/main/kotlin/hyd/dsl/DslDependencies.kt
shumy
353,477,837
false
null
package hyd.dsl import kotlin.reflect.KClass data class DslDependencies( val checkers: Map<String, ICheck> = emptyMap() ) interface ICheck interface ICheckEntity: ICheck { fun Entity.check() } interface ICheckValue<T: Any>: ICheck { fun EValue<T>.check() }
0
Kotlin
0
0
b0b900d9168450f349ff4790f030f1b17bafb20a
267
dsl-hydrater
MIT License
libs/canvas-api-2/src/main/java/com/instructure/canvasapi2/managers/CalendarEventManager.kt
instructure
179,290,947
false
null
/* * Copyright (C) 2017 - present Instructure, 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.instructure.canvasapi2.managers import com.instructure.canvasapi2.StatusCallback import com.instructure.canvasapi2.apis.CalendarEventAPI import com.instructure.canvasapi2.builders.RestBuilder import com.instructure.canvasapi2.builders.RestParams import com.instructure.canvasapi2.models.ScheduleItem import com.instructure.canvasapi2.utils.ExhaustiveListCallback import com.instructure.canvasapi2.utils.weave.apiAsync import java.io.IOException object CalendarEventManager { @JvmStatic fun getCalendarEventsExhaustive( allEvents: Boolean, type: CalendarEventAPI.CalendarEventType, startDate: String?, endDate: String?, canvasContexts: List<String>, callback: StatusCallback<List<ScheduleItem>>, forceNetwork: Boolean ) { val adapter = RestBuilder(callback) val params = RestParams(usePerPageQueryParam = true, isForceReadFromNetwork = forceNetwork) val depaginatedCallback = object : ExhaustiveListCallback<ScheduleItem>(callback) { override fun getNextPage(callback: StatusCallback<List<ScheduleItem>>, nextUrl: String, isCached: Boolean) { CalendarEventAPI.getCalendarEvents( allEvents, type, startDate, endDate, canvasContexts, adapter, callback, params ) } } adapter.statusCallback = depaginatedCallback CalendarEventAPI.getCalendarEvents( allEvents, type, startDate, endDate, canvasContexts, adapter, depaginatedCallback, params ) } @JvmStatic fun getCalendarEventsExhaustiveAsync( allEvents: Boolean, type: CalendarEventAPI.CalendarEventType, startDate: String?, endDate: String?, canvasContexts: List<String>, forceNetwork: Boolean ) = apiAsync<List<ScheduleItem>> { CalendarEventManager.getCalendarEventsExhaustive(allEvents, type, startDate, endDate, canvasContexts, it, forceNetwork) } @Throws(IOException::class) @JvmStatic fun getUpcomingEventsSynchronous(forceNetwork: Boolean): List<ScheduleItem> { val adapter = RestBuilder() val params = RestParams(usePerPageQueryParam = true, isForceReadFromNetwork = forceNetwork) val response = CalendarEventAPI.getUpcomingEventsSynchronous(adapter, params) return response.body()?.let { if (response.isSuccessful) it else emptyList() } ?: emptyList() } @JvmStatic fun getCalendarEvent(eventId: Long, callback: StatusCallback<ScheduleItem>, forceNetwork: Boolean) { val adapter = RestBuilder(callback) val params = RestParams(isForceReadFromNetwork = forceNetwork) CalendarEventAPI.getCalendarEvent(eventId, adapter, params, callback) } @JvmStatic fun deleteCalendarEvent(eventId: Long, cancelReason: String, callback: StatusCallback<ScheduleItem>) { val adapter = RestBuilder(callback) val params = RestParams() CalendarEventAPI.deleteCalendarEvent(eventId, cancelReason, adapter, params, callback) } @JvmStatic fun createCalendarEvent( contextCode: String, title: String, description: String, startDate: String, endDate: String, location: String, callback: StatusCallback<ScheduleItem> ) { val adapter = RestBuilder(callback) val params = RestParams() CalendarEventAPI.createCalendarEvent( contextCode, title, description, startDate, endDate, location, adapter, params, callback ) } }
2
Kotlin
85
99
1bac9958504306c03960bdce7fbb87cc63bc6845
4,548
canvas-android
Apache License 2.0
app/src/androidTest/java/uk/ryanwong/skycatnews/storydetail/data/remote/MockStoryService.kt
ryanwong-uk
531,291,511
false
null
/* * Copyright (c) 2022. <NAME> (<EMAIL>) */ package uk.ryanwong.skycatnews.storydetail.data.remote import uk.ryanwong.skycatnews.storydetail.data.remote.model.ContentDto import uk.ryanwong.skycatnews.storydetail.data.remote.model.HeroImageDto import uk.ryanwong.skycatnews.storydetail.data.remote.model.StoryDto class MockStoryService : StoryService { private val mockImageUrl = listOf( "https://ryanwong.co.uk/sample-resources/skycatnews/cat1_hero.jpg", "https://ryanwong.co.uk/sample-resources/skycatnews/cat2_hero.jpg", "https://ryanwong.co.uk/sample-resources/skycatnews/cat3_hero.jpg", "https://ryanwong.co.uk/sample-resources/skycatnews/cat4_hero.jpg", "https://ryanwong.co.uk/sample-resources/skycatnews/cat5_hero.jpg", "https://ryanwong.co.uk/sample-resources/skycatnews/cat6_hero.jpg", ) override suspend fun getStory(storyId: Int): Result<StoryDto> { return Result.success( StoryDto( contents = listOf( ContentDto( accessibilityText = null, text = "some-paragraph-1", type = "paragraph", url = null ), ContentDto( accessibilityText = "some-accessibility-text-2", text = null, type = "image", url = mockImageUrl[0] ), ContentDto( accessibilityText = null, text = "some-paragraph-3", type = "paragraph", url = null ), ), creationDate = "2020-11-18T00:00:00Z", headline = "some-headline", heroImage = HeroImageDto( accessibilityText = "some-hero-image-accessibility-text", imageUrl = mockImageUrl[2] ), id = storyId, modifiedDate = "2020-11-19T00:00:00Z" ) ) } }
8
Kotlin
1
1
22314aa6ceee4eec993fa11e5284dba270a669c5
2,157
cat-news
Apache License 2.0
0909.Snakes and Ladders.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
import java.util.* internal class Solution { fun snakesAndLadders(board: Array<IntArray>): Int { val n = board.size val q: Deque<Int> = ArrayDeque() q.offer(1) val m = n * n val vis = BooleanArray(m + 1) vis[1] = true var ans = 0 while (!q.isEmpty()) { for (k in q.size() downTo 1) { val x = q.poll() if (x == m) { return ans } for (y in x + 1..min(x + 6, m)) { var i = (y - 1) / n var j = (y - 1) % n if (i % 2 == 1) { j = n - j - 1 } i = n - i - 1 val z = if (board[i][j] == -1) y else board[i][j] if (!vis[z]) { vis[z] = true q.offer(z) } } } ++ans } return -1 } }
0
Kotlin
0
0
17a80985d970c8316fb694e4952692e598d700af
797
kotlin-leetcode
MIT License
domain/src/main/java/dev/baseio/slackclone/domain/repository/ChannelsRepository.kt
Anmol92verma
451,777,565
false
null
package dev.baseio.slackclone.domain.repository import androidx.paging.PagingData import dev.baseio.slackclone.domain.model.channel.DomainLayerChannels import dev.baseio.slackclone.domain.model.users.DomainLayerUsers import kotlinx.coroutines.flow.Flow interface ChannelsRepository { fun fetchChannels(): Flow<List<DomainLayerChannels.SlackChannel>> fun fetchChannelsPaged(params: String?): Flow<PagingData<DomainLayerChannels.SlackChannel>> suspend fun saveChannel(params: DomainLayerChannels.SlackChannel): DomainLayerChannels.SlackChannel? suspend fun getChannel(uuid: String): DomainLayerChannels.SlackChannel? suspend fun channelCount(): Int suspend fun saveOneToOneChannels(params: List<DomainLayerUsers.SlackUser>) }
0
Kotlin
9
93
29173bb4f9ddd39de1e9facc34251986fdab81e6
739
SlackAndroidClone
Apache License 2.0
app/src/main/java/codenevisha/com/cleanarchitecture/domain/model/Article.kt
abbasiehsan1991
162,987,405
false
null
package codenevisha.com.cleanarchitecture.domain.model import android.arch.persistence.room.Embedded import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize data class ArticleModel( @SerializedName("status") var status: String?, @SerializedName("totalResults") var totalResults: Int?, @SerializedName("articles") var articles: MutableList<Article>? ) { constructor() : this(null, null, null) } @Entity @Parcelize data class Article( @PrimaryKey(autoGenerate = true) var id: Long, @SerializedName("author") var author: String?, @SerializedName("title") var title: String = "No Title", @SerializedName("description") var description: String ="No Description", @SerializedName("url") var url: String?, @SerializedName("urlToImage") var urlToImage: String?, @SerializedName("publishedAt") var publishedAt: String?, @SerializedName("content") var content: String?, @Embedded @SerializedName("source") var source: Source ) : Parcelable { var atricleAuthor = "Author: $author" } @Parcelize class Source constructor( @SerializedName("id") var sourceId: String?, @SerializedName("name") var sourceNname: String? ) : Parcelable
1
Kotlin
1
4
00f5b4063cbf3795e42df4fe3a976aeb8add5d17
1,353
AndroidCleanArchitecture
Apache License 2.0
app/src/main/java/com/example/nijatahmadli/blockchainwallet/presentation/base/viewmodel/ViewModel.kt
nijat-ahmadli
158,304,687
false
null
package com.example.nijatahmadli.blockchainwallet.presentation.base.viewmodel interface ViewModel { fun initialize() fun clean() }
0
Kotlin
0
1
65c2656e94f87c949712822ae66fc08a1a99d03c
141
blockchain-wallet
MIT License
commons-crypto/src/test/kotlin/com/healthmetrix/connector/commons/crypto/RsaTest.kt
smart4health
593,624,617
false
null
package com.healthmetrix.connector.commons.crypto import com.healthmetrix.connector.commons.decodeBase64 import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.security.interfaces.RSAPublicKey private const val ADD_CASE_ENCRYPTION_KEY_B64 = "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF3MHNOMHlSeFMyZ2JidlR5czBIegpjaTJoYnBYdjIrSUF6bG90UWZEc0VTUzJzVzU1aEtwbDhnUmJHaTZXbXYzbGN1M2lyZ3h5bDkxem1BV1V4NXNxCm94U3dCZHg5dlNBWFpBdjBHQjJxeHdDSFh6Yk5RdVdBQlZmM2pIby9wSXhlMkNlSk9ZVVZHUUJIa1QrMDVFT2kKRi9mUXpUeTR5ZjlsWVRsSEVMU2xiTHhVNjlSK0QzUzM1V2dBV2FRWVBCY1ZmWkpJY3o5SVUydVJNaGFYbFNFbApjRW5yZFB5QkNsVk9oTitmaWpwZmtpL3NhbjdLMUU0MG9oWDVVRTNmbzVLSzhqMXUyYnI0bndNcUUyUWFEakc4ClQ5T3J5eXFvZWtrU2tHMy9ZYW1yM1BOM2h3dlkxQWMrWjloNlNYbUFHanNOMGprcERaamRrRUYwR1hjMzdGa20KTndJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==" private const val ADD_CASE_DECRYPTION_KEY_B64 = "LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcEFJQkFBS0NBUUVBdzBzTjB5UnhTMmdiYnZUeXMwSHpjaTJoYnBYdjIrSUF6bG90UWZEc0VTUzJzVzU1CmhLcGw4Z1JiR2k2V212M2xjdTNpcmd4eWw5MXptQVdVeDVzcW94U3dCZHg5dlNBWFpBdjBHQjJxeHdDSFh6Yk4KUXVXQUJWZjNqSG8vcEl4ZTJDZUpPWVVWR1FCSGtUKzA1RU9pRi9mUXpUeTR5ZjlsWVRsSEVMU2xiTHhVNjlSKwpEM1MzNVdnQVdhUVlQQmNWZlpKSWN6OUlVMnVSTWhhWGxTRWxjRW5yZFB5QkNsVk9oTitmaWpwZmtpL3NhbjdLCjFFNDBvaFg1VUUzZm81S0s4ajF1MmJyNG53TXFFMlFhRGpHOFQ5T3J5eXFvZWtrU2tHMy9ZYW1yM1BOM2h3dlkKMUFjK1o5aDZTWG1BR2pzTjBqa3BEWmpka0VGMEdYYzM3RmttTndJREFRQUJBb0lCQVFDd1RXVmhvNWlUMXB4TgpndHhIYjlaeTBUYlhPb3liR0dCWjZaYkozTkdBZUlCbGxiSW1UaDVTYWhSRWdxSjdzWkllT3h0VXZQQUdvV2psCmFNUnpubVRUYksycjNPMjJldTRpNTVlbzNiOTZmOE8xOVNkQXFTYjFyQUJTMVZuM0ZySFl1WGhzY1BRbTZkV3kKRHEwakZOdVVmNmdFWURrQ1Fvb25SeW9jcnJoWWUrakJ6YU4vdVRrdDAxblJPSTN2bTF2NmNtZlhIdXBmMVc4YQpNZCtzY2lpbTI3UDhWZFJsRjFFbG1tNFZLZDM1bWRzUTBwMVhDbTI1cFhWNjNNSWRFWW1McmJCaDhzdHRMVldtClRndkNCK2U3b0NUdXFYazg4bnh4ald1MEtZSWVuVDFTOUliaFZhVHFFZC80Q2xVTUtPVENiQ1l2SWRHdVVBNi8KV2o2eEhhNEJBb0dCQU9mK0ErMGdGb2U2TTMvS0ZZL3VOTDVqU1U0MEpkeVpOVWZLV3R3OVZ3bDNhZkRQRzlBUApQUDF0YmtNMUV2ejlwQk1ocU9zMFBjUXVtSEU1bTl6M0NJZzRkOTNoSUZGbG4zUEcreGFQdy85UTVRdGhNc3ZFCnEzZEpaVW5VdFNSaTZUMU9rK2pEMEZXbUs0Wmxld0hvdUZKN3JGUytYaDRnZ1RIZUxwaXZoRXozQW9HQkFOZUEKekxmYXU5OGFZU3piai8xczhqSXRZZkZjYUNYS3VYd1JHbnZxd25SWGJROW1YaERuekVxSEpqcVJHNzJhdWRVdwpNdnJ5ZDc4UUhNUndqRUlEUUxmUDZXa1liODkzQ1dNOVkyb1BSMzltT2NyRmR0bWVRRlFrWkp1NGNjc1pETGhUCkZIWTFUWW5CVVQ4OWxqVm5PY3JyQjYxNVRnWnpNQkFLbkJzcUZlREJBb0dBRDBqL1BUcG1BWjlWRVZCaFIxQnMKalRiQmQ3T2I0d0w5TGJPNWROVmR6TFBmZVF4TVN0TVdNNlJvSldsenpOTnhZZ2xQdGQrRlNrMi9vWVlvTE5EaAo4UWUzYmhrTkpnL0tCN2pPaGxnR2srWGlrWE5nQTJqNzJ5b3MwRWFCZ05vN2Y5eVRoanlRbDNRUlhoT0ZuVVNXCkVHa3htNHZIYTdpOGltcVhLMXcxSFZVQ2dZRUFrRW9FeC9VRVpWVGNTNVNXekMvdDJmclk0U25sOGFmU21XYzYKUEUzcTlNcTBrdU1QaUhJckxwdGUxVWZqTXdndDlMZlk2bnorQUVkaGU0Vi80NU1aK2ZpVFozS2RLbU9oUFhrVQozeVpyMExrNWFMTGQ2TWMwZXlJQzJ1Q2NFRWd0WkJ6OFRrbFNLVEh1bkZFNENYbWNFR2xkTXFGTnhMUExNbkpvCkl5Z0NqZ0VDZ1lCTlNkU3A0UXlIYVJhMVJpdndUZllOT2o0VkJoeTQ2VTZxaGVKR3EzU2dYZTJtNEVJaVB6ai8KU2cxZ1pmSktUQjk1RDJDTFJYNU9yUmQvdnVBeUxNWG9lc0k4b3BKV1pLcXR5dGdSZGVmbWNEOTh6NjBTMm9YVQpwZ1lXTERXM0FkYk9ib1ZJVnNqS0p5QTFhZDdCckMxTS9DZzAxR2xoOHlIV094WGswUFlrNVE9PQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=" internal class RsaTest { private val invalidB64 = "aW52YWxpZAo=" @Nested @DisplayName("Public Key deserialization") inner class PublicKey { @Test fun `buildFromB64String should return instance of RsaPublicKey for valid input`() { assertThat(RsaPublicKey.buildFromB64String(ADD_CASE_ENCRYPTION_KEY_B64)).isInstanceOf(RSAPublicKey::class.java) } @Test fun `buildFromB64String should throw Exception for non b64 input`() { assertThrows<java.lang.NullPointerException> { RsaPublicKey.buildFromB64String("invalid") } } @Test fun `buildFromB64String should throw Exception for invalid b64String as input`() { assertThrows<java.lang.NullPointerException> { RsaPublicKey.buildFromB64String(invalidB64) } } } @Nested @DisplayName("Private Key deserialization") inner class PrivateKey { @Test fun `buildFromB64String should return instance of RsaPrivateKey for valid input`() { assertThat(RsaPrivateKey.buildFromB64String(ADD_CASE_DECRYPTION_KEY_B64)).isInstanceOf(RsaPrivateKey::class.java) } @Test fun `buildFromB64String should throw Exception for non b64 input`() { assertThrows<NullPointerException> { RsaPrivateKey.buildFromB64String("invalid") } } @Test fun `buildFromB64String should throw Exception for invalid b64String as input`() { assertThrows<NullPointerException> { RsaPrivateKey.buildFromB64String(invalidB64) } } @Test fun `toPemKeyString should make a string that looks approximately correct`() { val key = ADD_CASE_DECRYPTION_KEY_B64.decodeBase64()!! val result = RsaPrivateKey.toPemKeyString(key) assertThat(result).startsWith("-----BEGIN RSA PRIVATE KEY-----") assertThat(result).endsWith("-----END RSA PRIVATE KEY-----\n") } } @Nested @DisplayName("Encryption roundtrip") inner class EncryptionRoundtrip { @Test fun `encryption roundtrip should work`() { val publicKey = RsaPublicKey(RsaPublicKey.buildFromB64String(ADD_CASE_ENCRYPTION_KEY_B64)!!) val privateKey = RsaPrivateKey.buildFromB64String(ADD_CASE_DECRYPTION_KEY_B64)!! val expected = "test" val encrypted = publicKey.encrypt(expected.toByteArray(Charsets.UTF_8))!! val result = privateKey.decrypt(encrypted)?.toString(Charsets.UTF_8) assertThat(result).isEqualTo(expected) } } }
0
Kotlin
0
1
976d36079fa4171da0f78ad5812181cb6e3da6bc
5,911
connector-service
MIT License
app/src/googlePlay/java/io/keepalive/android/LocationHelper.kt
keepalivedev
718,764,639
false
{"Kotlin": 183606, "HTML": 4485, "Ruby": 3040, "Python": 2486, "Java": 645}
package io.keepalive.android import android.annotation.SuppressLint import android.content.Context import android.location.Location import android.util.Log import com.google.android.gms.location.CurrentLocationRequest import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.google.android.gms.tasks.CancellationTokenSource import com.google.android.gms.tasks.Task // implementation for use with Google Play Services Location APIs class LocationHelper( context: Context, myCallback: (Context, String) -> Unit ) : LocationHelperBase(context, myCallback) { private val fusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context) // cancellation token for use with fusedLocationClient.getCurrentLocation() private val cancellationTokenSource = CancellationTokenSource() // override the global timeout function so we can cancel the cancellationTokenSource override val globalTimeoutRunnable = Runnable { // cancel the token, may or may not still be in use cancellationTokenSource.cancel() DebugLogger.d("globalTimeoutRunnable", "Timeout reached while getting " + "location from google play?!") myCallback(context, context.getString(R.string.location_invalid_message)) } // get the current location the Google Play Services location API @SuppressLint("MissingPermission") override fun getCurrentLocation() { // was originally done like this because we thought we needed to customize // the options but we really don't? // https://developers.google.com/android/reference/com/google/android/gms/location/CurrentLocationRequest.Builder val currentLocReq = CurrentLocationRequest.Builder() .setPriority(Priority.PRIORITY_HIGH_ACCURACY) // timeout isn't respected in doze mode??? .setDurationMillis(locationRequestTimeoutLength) //.setMaxUpdateAgeMillis(5000) .build() // this is more accurate and up to date than .lastLocation fusedLocationClient.getCurrentLocation(currentLocReq, cancellationTokenSource.token) .addOnCompleteListener { task -> processLocationResult(task, "current") } } @SuppressLint("MissingPermission") override fun getLastLocation() { DebugLogger.d("getLastLocation", "Attempting to get lastLocation...") try { fusedLocationClient.lastLocation.addOnCompleteListener { task -> processLocationResult(task, "last") } } catch (e: Exception) { DebugLogger.d("getLastLocation", "Failed while getting last location:", e) // if we failed to get the last location then just send the error message executeCallback(context.getString(R.string.location_invalid_message)) } } // process the result from getting either the Last or the Current location private fun processLocationResult(task: Task<Location>, locationSource: String) { // This block will be executed whether the task was successful or not if (task.isSuccessful && task.result != null) { val location = task.result // it doesn't matter where we get the location from, if we get one then we can // geocode it and send it to the callback Log.d( "processLocationResult", "$locationSource Location from ${location.provider} is " + "(${location.latitude}, ${location.longitude}) ${location.accuracy}acc" ) // try to geocode the location and then execute the callback GeocodingHelper().geocodeLocationAndExecute(location) } else { DebugLogger.d( "processLocationResult", "Failed while trying to get the $locationSource location", task.exception ) // if we just failed to get the current location then try to get the last location if (locationSource == "current") { getLastLocation() // otherwise if we fail to get the last location then just send the error message } else { Log.d("processLocationResult", "Unable to determine location, executing callback") executeCallback(context.getString(R.string.location_invalid_message)) } } } }
6
Kotlin
5
81
f5d84066b41a1cebaf9ce962e09e6c340220d9ca
4,631
KeepAlive
Apache License 2.0
plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/multiDeclarations/list.kt
ingokegel
72,937,917
true
null
// WITH_STDLIB fun foo() { <selection>listOf(1, 2, 3)</selection> }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
71
intellij-community
Apache License 2.0
core/src/main/kotlin/dev/syncended/kube/components/Text.kt
syncended
819,147,468
false
{"Kotlin": 54274, "Dockerfile": 297}
package dev.syncended.kube.components import dev.syncended.kube.core.component.Widget import dev.syncended.kube.core.component.Modifier import dev.syncended.kube.core.model.Color import dev.syncended.kube.core.model.FontSize import dev.syncended.kube.core.model.FontStyle import dev.syncended.kube.core.model.Size import dev.syncended.kube.core.model.toCssColor import kotlinx.css.CssBuilder import kotlinx.css.color import kotlinx.css.fontSize import kotlinx.css.fontStyle import kotlinx.css.fontWeight abstract class AbstractText<M : TextModifier>(modifier: M) : Widget<M>(modifier) { override fun applyModifierStyling(builder: CssBuilder) { super.applyModifierStyling(builder) modifier.color?.let { builder.color = it.toCssColor() } modifier.textSize?.let { builder.fontSize = it.toDimension() } modifier.fontSize?.let { builder.fontWeight = it.mapping } modifier.fontStyle?.let { builder.fontStyle = it.mapping } } } class Text(modifier: TextModifier) : AbstractText<TextModifier>(modifier) { override fun render() = p { +modifier.text.orEmpty() } } open class TextModifier : Modifier() { internal var text: String? = null internal var color: Color? = null internal var textSize: Size? = null internal var fontSize: FontSize? = null internal var fontStyle: FontStyle? = null } fun <T : TextModifier> T.text(text: String): T { this.text = text return this } fun <T : TextModifier> T.textColor(color: Color): T { this.color = color return this } fun <T : TextModifier> T.textSize(value: Size): T { textSize = value return this } fun <T : TextModifier> T.fontSize(fontSize: FontSize): T { this.fontSize = fontSize return this } fun <T : TextModifier> T.fontStyle(fontStyle: FontStyle): T { this.fontStyle = fontStyle return this }
0
Kotlin
0
0
2fd6fbafbab29b4444632bdc4b8e1fcbff907832
1,805
kube
Apache License 2.0
src/main/kotlin/org/teamvoided/dusk_debris/data/gen/tags/BiomeTagsProvider.kt
TeamVoided
814,767,803
false
{"Kotlin": 153037, "Java": 3724}
package org.teamvoided.dusk_debris.data.gen.tags import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider import net.minecraft.registry.HolderLookup import net.minecraft.registry.RegistryKeys import net.minecraft.world.biome.Biome import java.util.concurrent.CompletableFuture class BiomeTagsProvider(o: FabricDataOutput, r: CompletableFuture<HolderLookup.Provider>) : FabricTagProvider<Biome>(o, RegistryKeys.BIOME, r) { override fun configure(arg: HolderLookup.Provider) { duskTags() vanillaTags() conventionTags() } fun duskTags() { } fun vanillaTags() { } fun conventionTags() { } }
0
Kotlin
0
0
7973b474b08276fc01cb6222ceadf235004c29f3
722
Dusk-Debris
MIT License
paginator/src/commonMain/kotlin/symphony/internal/AbstractPaginationManager.kt
aSoft-Ltd
632,021,007
false
{"Kotlin": 208035, "HTML": 296, "JavaScript": 200}
package symphony.internal import cinematic.MutableLive import cinematic.mutableLiveOf import kase.Bag import kase.Failure import kase.LazyState import kase.Loading import kase.Pending import kase.Success import kase.toLazyState import koncurrent.FailedLater import koncurrent.Later import koncurrent.later.finally import koncurrent.later.then import symphony.AbstractPage import symphony.PageFindResult import symphony.PageLoader import symphony.PaginationManager import symphony.internal.memory.PageMemoryManager @PublishedApi internal abstract class AbstractPaginationManager<T, P : AbstractPage, R : PageFindResult<T>>( override var capacity: Int ) : PaginationManager<T, P, R> { abstract val loader: Bag<PageLoader<P>> abstract val memory: PageMemoryManager<T, P, R> override val current: MutableLive<LazyState<P>> = mutableLiveOf(Pending) override val currentPageOrNull get() = current.value.data override val currentPageSize get() = currentPageOrNull?.size ?: 0 override val hasMore: Boolean get() = currentPageOrNull?.hasMore == true override fun wipeMemory() = memory.clear() override fun setPageCapacity(cap: Int) { capacity = cap } override fun clearPages() { wipeMemory() current.value = Pending } protected fun load(page: Int): Later<P> { if (current.value is Loading) return FailedLater(LOADING_ERROR) val memorizedPage = memory.load(page, capacity) current.value = Loading("Loading", memorizedPage) return try { loader.getOrThrow().load(page, capacity) } catch (err: Throwable) { FailedLater(err) }.then { memory.save(it) }.finally { current.value = it.toLazyState(memorizedPage) } } override fun loadNextPage() = when (val state = current.value) { is Pending -> loadPage(1) is Loading -> Later(Unit) is Failure -> loadPage(1) is Success -> when { state.data.isEmpty -> Later(state.data) state.data.isLastPage -> Later(state.data) else -> loadPage(state.data.number + 1) } } override fun loadPreviousPage() = when (val state = current.value) { is Pending -> loadPage(1) is Loading -> Later(Unit) is Failure -> loadPage(1) is Success -> when { state.data.number > 1 -> loadPage(state.data.number - 1) else -> loadPage(1) } } override fun refreshAllPages(): Later<Any?> { clearPages() return loadFirstPage() } override fun refreshCurrentPage() = when (val state = current.value) { is Pending -> loadPage(1) is Loading -> Later(Unit) is Failure -> loadPage(1) is Success -> loadPage(state.data.number) } private fun loadNothing() = Later(Unit) override fun loadFirstPage() = loadPage(1) override fun loadLastPage() = loadPage(-1) override fun find(item: T) = memory.load(item, capacity) override fun find(row: Int, page: Int) = memory.load(row, page, capacity) override fun find(page: Int) = memory.load(page, capacity) companion object { val LOADING_ERROR = Throwable("Can't load page while paginator is still loading") } }
0
Kotlin
0
0
ff4303dcc3a220afa7ea2f673ed71e4c76d97f3c
3,311
symphony
MIT License
backend/src/main/kotlin/com/github/davinkevin/podcastserver/manager/ItemDownloadManager.kt
davinkevin
13,350,152
false
null
@file:Suppress("SpringJavaInjectionPointsAutowiringInspection") package com.github.davinkevin.podcastserver.manager import com.github.davinkevin.podcastserver.download.DownloadRepository import com.github.davinkevin.podcastserver.entity.Status import com.github.davinkevin.podcastserver.manager.downloader.Downloader import com.github.davinkevin.podcastserver.manager.downloader.DownloadingItem import com.github.davinkevin.podcastserver.manager.selector.DownloaderSelector import com.github.davinkevin.podcastserver.manager.selector.ExtractorSelector import com.github.davinkevin.podcastserver.messaging.MessagingTemplate import com.github.davinkevin.podcastserver.service.properties.PodcastServerParameters import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Qualifier import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor import org.springframework.stereotype.Service import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.toFlux import java.util.* import java.util.concurrent.locks.ReentrantLock @Service class ItemDownloadManager ( private val template: MessagingTemplate, private val downloadRepository: DownloadRepository, private val podcastServerParameters: PodcastServerParameters, private val downloaderSelector: DownloaderSelector, private val extractorSelector: ExtractorSelector, @param:Qualifier("DownloadExecutor") private val downloadExecutor: ThreadPoolTaskExecutor ) { private val log = LoggerFactory.getLogger(ItemDownloadManager::class.java)!! private val mainLock = ReentrantLock() var waitingQueue = ArrayDeque<DownloadingItem>() var downloadingQueue = mapOf<DownloadingItem, Downloader>() val queue: Flux<DownloadingItem> get() = waitingQueue.toFlux() val downloading: Flux<DownloadingItem> get() = this.downloadingQueue.values .map { it.downloadingInformation.item } .toFlux() /* GETTER & SETTER */ val limitParallelDownload: Int get() = downloadExecutor.corePoolSize fun setLimitParallelDownload(limitParallelDownload: Int) { downloadExecutor.corePoolSize = limitParallelDownload manageDownload() } private fun manageDownload() { val manageDownloadLock = this.mainLock manageDownloadLock.lock() try { while (this.downloadingQueue.size < downloadExecutor.corePoolSize && !waitingQueue.isEmpty()) { val (currentItem, newQueue) = waitingQueue.dequeue() waitingQueue = newQueue if (!isStartedOrFinished(currentItem)) { launchDownloadFor(currentItem) } } } finally { manageDownloadLock.unlock() } this.convertAndSendWaitingQueue() } private fun isStartedOrFinished(currentItem: DownloadingItem) = Status.STARTED == currentItem.status || Status.FINISH == currentItem.status private fun initDownload(): Mono<List<DownloadingItem>> { return downloadRepository.findAllToDownload(podcastServerParameters.limitDownloadDate().toOffsetDateTime(), podcastServerParameters.numberOfTry) .filter { it !in waitingQueue } .collectList() } fun launchDownload() { initDownload().subscribe { log.info("add ${it.size} to waiting queue") waitingQueue = waitingQueue.enqueueAll(it) manageDownload() } } fun stopAllDownload() = this.downloadingQueue.values.forEach { it.stopDownload() } fun stopDownload(id: UUID) = findDownloaderOfItem(id)?.stopDownload() private fun findDownloaderOfItem(id: UUID): Downloader? { return downloadingQueue .filterKeys { it.id == id } .values .firstOrNull() } fun addItemToQueue(id: UUID) { downloadRepository.findDownloadingItemById(id).subscribe { addItemToQueue(it) } } internal fun addItemToQueue(item: DownloadingItem) { if (item in waitingQueue || isInDownloadingQueue(item)) { return } waitingQueue = waitingQueue.enqueue(item) manageDownload() } fun removeItemFromQueue(id: UUID, stopItem: Boolean) { removeItemFromQueue(id) if (stopItem) { downloadRepository .stopItem(id) .subscribe() } convertAndSendWaitingQueue() } private fun removeItemFromQueue(id: UUID) { waitingQueue = waitingQueue.delete(id) } fun removeACurrentDownload(id: UUID) { val pairs = this.downloadingQueue.map { it.toPair() }.filter { it.first.id != id }.toTypedArray() this.downloadingQueue = mapOf(*pairs) manageDownload() } private fun launchDownloadFor(item: DownloadingItem) { val dlItem = try { extractorSelector.of(item.url).extract(item) } catch (e: Exception) { log.error("Error during extraction of {}", item.url, e) manageDownload() return } val downloader = downloaderSelector.of(dlItem) .apply { with(dlItem, this@ItemDownloadManager) } this.downloadingQueue = downloadingQueue.filterKeys { it != item } + Pair(item, downloader) downloadExecutor.execute(downloader) } fun removeItemFromQueueAndDownload(id: UUID) { when { isInDownloadingQueueById(id) -> stopDownload(id) isInWaitingQueueById(id) -> removeItemFromQueue(id) } this.convertAndSendWaitingQueue() } private fun convertAndSendWaitingQueue() = template.sendWaitingQueue(waitingQueue.toList()) fun isInDownloadingQueue(item: DownloadingItem) = this.downloadingQueue.containsKey(item) fun isInDownloadingQueueById(id: UUID) = this.downloadingQueue.keys.asSequence().map { it.id }.any { it == id } fun isInWaitingQueueById(id: UUID) = waitingQueue.asSequence().map { it.id }.any { it == id } fun moveItemInQueue(itemId: UUID, position: Int) { val itemToMove = waitingQueue .firstOrNull { it.id == itemId } ?: error("Moving element in waiting list not authorized : Element wasn't in the list") waitingQueue = waitingQueue .filter { it.id != itemId } .toMutableList() .apply { add(position, itemToMove) } .let { ArrayDeque(it) } convertAndSendWaitingQueue() } } private fun <T> ArrayDeque<T>.dequeue(): Pair<T, ArrayDeque<T>> { val i = this.first val newQueue = ArrayDeque(this.filter { it !== i }) return Pair(i, newQueue) } private fun <T> ArrayDeque<T>.enqueueAll(e: Collection<T>): ArrayDeque<T> { val joined = this.toMutableList() joined.addAll(e) return ArrayDeque(joined) } private fun <T> ArrayDeque<T>.enqueue(item: T): ArrayDeque<T> { val joined = this.toMutableList() joined.add(item) return ArrayDeque(joined) } private fun ArrayDeque<DownloadingItem>.delete(id: UUID): ArrayDeque<DownloadingItem> { val joined = this.toMutableList().filter { it.id != id } return ArrayDeque(joined) }
0
HTML
39
165
88374e6242f01b7eeda99350fb078cc07393f6b7
7,306
Podcast-Server
Apache License 2.0
idea/testData/quickfix/override/typeMismatchOnOverride/cantChangePropertyTypeToMatchOverridenProperties.kt
JakeWharton
99,388,807
true
null
// "class org.jetbrains.kotlin.idea.quickfix.ChangeVariableTypeFix" "false" // ERROR: Type of 'x' doesn't match the type of the overridden var-property 'public abstract var x: String defined in A' interface A { var x: String } interface B { var x: Any } interface C : A, B { override var x: Int<caret> }
1
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
318
kotlin
Apache License 2.0
chat-components/database/src/main/java/com/pubnub/components/repository/message/DefaultMessageRepository.kt
pubnub
419,258,609
false
{"Kotlin": 472962}
package com.pubnub.components.repository.message import androidx.paging.PagingSource import androidx.room.RoomDatabase import androidx.sqlite.db.SimpleSQLiteQuery import com.pubnub.components.data.message.DBMessage import com.pubnub.components.data.message.MessageDao import com.pubnub.components.data.message.action.DBMessageWithActions import com.pubnub.components.repository.util.Query import com.pubnub.components.repository.util.Sorted import com.pubnub.framework.data.ChannelId import com.pubnub.framework.data.MessageId import com.pubnub.framework.util.Timetoken import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.firstOrNull /** * Message Repository Implementation * * Parameters: * @param messageDao MessageDao implementation */ class DefaultMessageRepository( private val database: RoomDatabase, private val messageDao: MessageDao<DBMessage, DBMessageWithActions>, ) : MessageRepository<DBMessage, DBMessageWithActions> { /** * Returns Message with Channel list * * @param id Message ID to match * @return DBMessageWithActions if exists, null otherwise */ override suspend fun get(id: MessageId): DBMessageWithActions? = messageDao.get(id) /** * Returns list of Messages with Channels * * @param id ID of Channel to get Message from * @param count Count of Messages to return * @param before If true, returns the Messages before passed Timestamp. Otherwise returns messages after Timestamp * @param timestamp Timestamp to get Messages before or after * @return List of DBMessageWithActions */ override suspend fun getList( id: ChannelId, count: Int, before: Boolean, timestamp: Timetoken, ): List<DBMessageWithActions> = if (before) messageDao.getBefore( id = id, count = count, timestamp = timestamp ) else messageDao.getAfter(id = id, count = count, timestamp = timestamp) /** * Checks if database contains Message with passed id * * @param id ID of Message to check * * @return True if Message exists, False otherwise */ override suspend fun has(id: MessageId): Boolean = get(id) != null /** * Returns Paginated Source of Message list * * @param id When not null, returned list contains only Messages from passed channel. * Otherwise all the Messages are returned. * @param contentType Type of the message content. When not null, returned list contains only * messages with passed type. Otherwise all the Messages are returned. * Null by default. * @param filter Room filter query * @param sorted Array of Sorted objects, result will be sorted by it. * @return PagingSource of DBChannelWithMembers */ override fun getAll( id: ChannelId?, contentType: String?, filter: Query?, vararg sorted: Sorted, ): PagingSource<Int, DBMessageWithActions> { val stringQuery: MutableList<String> = mutableListOf("SELECT * FROM `message`") val arguments: MutableList<Any> = mutableListOf() // Where clause if (filter != null || id != null) stringQuery += "WHERE" // Filter by userId if (id != null) { stringQuery += "channel LIKE ?" arguments.add(id) } // Filter by contentType if (contentType != null) { if (arguments.isNotEmpty()) stringQuery += " AND " stringQuery += "contentType LIKE ?" arguments.add(contentType) } // Filtering if (filter != null) { if (arguments.isNotEmpty()) stringQuery += " AND " stringQuery += filter.first arguments.addAll(filter.second) } // Ordering if (sorted.isNotEmpty()) stringQuery += "ORDER BY ${sorted.joinToString(", ")}" val query = SimpleSQLiteQuery(stringQuery.joinToString(" "), arguments.toTypedArray()) return messageDao.getAll(query) } /** * Returns last Message for passed Channel ID * * @param id ID of Channel to get last Message from * @return DBMessageWithActions or null */ override suspend fun getLast(id: ChannelId): DBMessageWithActions? = messageDao.getLast(id).firstOrNull() /** * Returns list of last Messages for passed Channel ID * * @param id ID of Channel to get last Message from * @param count Count of Messages to return * @return Flow of List<DBMessageWithActions> */ override fun getLastByChannel( id: ChannelId, count: Long, ): Flow<List<DBMessageWithActions>> = messageDao.getLastByChannel(id, count) /** * Checks if there is more Messages before passed Timestamp * * @param id ID of Channel to check Messages from * @param timestamp Timestamp to check * @return True if there are Messages before passed Timestamp, False otherwise */ override suspend fun hasMoreBefore(id: ChannelId, timestamp: Timetoken): Boolean = messageDao.getBefore(id, 1, timestamp).isNotEmpty() /** * Checks if there is more Messages after passed Timestamp * * @param id ID of Channel to check Messages from * @param timestamp Timestamp to check * @return True if there are Messages after passed Timestamp, False otherwise */ override suspend fun hasMoreAfter(id: ChannelId, timestamp: Timetoken): Boolean = messageDao.getAfter(id, 1, timestamp).isNotEmpty() /** * Removes passed Message from database * * @param message DBMessage object do remove */ override suspend fun remove(message: DBMessage) { messageDao.delete(message) } /** * Removes all Messages from passed Channel * * @param id ID of Channel to remove Messages from */ override suspend fun removeAll(id: ChannelId) { messageDao.deleteAll(id) } /** * Inserts the new message, or updates if it's already exists * * @param message DBMessage object to update */ override suspend fun insertOrUpdate(vararg message: DBMessage) { messageDao.insertOrUpdate(*message) } /** * Sets SENT status to Message * * @param id Id of Message to set status to * @param timestamp Timestamp of update, or null */ override suspend fun setSent(id: MessageId, timestamp: Timetoken?) { setStatus( id = id, isSent = true, exception = null, timestamp = timestamp, ) } /** * Sets ERROR status to Message * * @param id Id of Message to set status to * @param exception Exception of sending Message, or null * @param timestamp Timestamp of update, or null */ override suspend fun setSendingError( id: MessageId, exception: String?, timestamp: Timetoken?, ) { setStatus( id = id, isSent = false, exception = exception, timestamp = timestamp, ) } /** * Returns last message Timestamp * * @param id ID of Channel to get Messages from * @return last Message Timestamp or 1, when not exists */ override suspend fun getLastTimestamp(id: ChannelId): Timetoken = messageDao.getLast(id).firstOrNull()?.message?.timetoken ?: 1L /** * Sets status of Message * * @param id Id of Message to set status to * @param isSent True if Message is sent, False otherwise * @param exception Exception of sending Message, or null * @param timestamp Timestamp of update, or null */ private suspend fun setStatus( id: MessageId, isSent: Boolean, exception: String?, timestamp: Timetoken?, ) { val message = get(id) ?: throw Exception("Message not found exception") val updatedMessage = message.message.copy( isSent = isSent, exception = exception, published = timestamp ?: message.message.published, ) messageDao.insertOrUpdate(updatedMessage) } override fun runInTransaction(body: ()-> Unit){ database.runInTransaction { body() } } }
2
Kotlin
2
3
5c534e2ae97189e4174f4a75d963528c3f71b0cf
8,459
chat-components-android
MIT License
injector/src/main/java/com/iwdael/methodinjector/injector/ChainInjector.kt
iwdael
625,182,407
false
null
package com.iwdael.methodinjector.injector import com.android.build.api.instrumentation.ClassContext import com.iwdael.methodinjector.constant.Class import com.iwdael.methodinjector.constant.Class.C_LOG import com.iwdael.methodinjector.constant.Class.C_STRING_BUILDER import com.iwdael.methodinjector.constant.Class.C_THREAD import com.iwdael.methodinjector.constant.Log import com.iwdael.methodinjector.constant.Method.C_APPEND import com.iwdael.methodinjector.constant.Method.C_CURRENT_THREAD import com.iwdael.methodinjector.constant.Method.C_GET_NAME import com.iwdael.methodinjector.constant.Method.C_HASH_CODE import com.iwdael.methodinjector.constant.Method.C_INIT import com.iwdael.methodinjector.constant.Method.C_TO_STRING import com.iwdael.methodinjector.entity.Method import com.iwdael.methodinjector.properties.Properties import com.iwdael.methodinjector.utils.* import org.objectweb.asm.Label import org.objectweb.asm.MethodVisitor /** * @author : iwdael * @mail : iwdael@outlook.com * @project : https://github.com/iwdael/MethodInjector */ class ChainInjector(classContext: ClassContext, api: Int, visitor: MethodVisitor, access: Int, name: String, descriptor: String, properties: Properties, fileName: String, method: Method) : Injector(classContext, api, visitor, access, name, descriptor, properties, fileName, method) { override fun intercept(): Boolean { if (!properties.enableChain) return false return name.matcher(properties.methodChainInternalMatcher) && name.matcher(properties.methodChainMatcher) && !name.matcher2(properties.methodChainInternalUnMatcher) && !name.matcher2(properties.methodChainUnMatcher) && (method.argc == method.args.size).apply { if (!this) Logger.error("method:${methodName} args:${method.args}") } } override fun onMethodEnter() { if (!intercept()) return if (properties.simpleChain) { mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitTypeInsn(NEW, C_STRING_BUILDER) mv.visitInsn(DUP) mv.visitMethodInsn(INVOKESPECIAL, C_STRING_BUILDER, C_INIT, "()V", false) mv.visitLdcInsn("${name}(${fileName}:${method.lineNumber})") mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) method.args.forEachIndexed { index, arg -> if (index>0) { mv.visitLdcInsn(",") mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) } mv.visitLdcInsn(" ${arg}: ") mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) loadArg(index) mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(${argumentTypes[index].appendDescriptor})Ljava/lang/StringBuilder;", false) } mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_TO_STRING, "()Ljava/lang/String;", false) mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) } else { val attrOffset = Language.offset(properties.useEnglish, method) val header = "%-${attrOffset}s" mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitLdcInsn(Log.SQUARE_TOP) mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitLdcInsn("${Log.SQUARE_LEFT} ${String.format(header, Language.get(properties.useEnglish, Language.CLASS))}: $className") mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitTypeInsn(NEW, C_STRING_BUILDER) mv.visitInsn(DUP) mv.visitMethodInsn(INVOKESPECIAL, C_STRING_BUILDER, C_INIT, "()V", false) mv.visitLdcInsn("${Log.SQUARE_LEFT} ${String.format(header, Language.get(properties.useEnglish, Language.THREAD))}: ") mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) mv.visitMethodInsn(INVOKESTATIC, C_THREAD, C_CURRENT_THREAD, "()Ljava/lang/Thread;", false) mv.visitMethodInsn(INVOKEVIRTUAL, C_THREAD, C_GET_NAME, "()Ljava/lang/String;", false) mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_TO_STRING, "()Ljava/lang/String;", false) mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) if (!isStatic && name != "<init>" && name != "<clinit>" && !properties.simpleChain) { mv.visitLdcInsn(properties.tagChain) mv.visitTypeInsn(NEW, C_STRING_BUILDER) mv.visitInsn(DUP) mv.visitMethodInsn(INVOKESPECIAL, C_STRING_BUILDER, C_INIT, "()V", false) mv.visitLdcInsn("${Log.SQUARE_LEFT} ${String.format(header, Language.get(properties.useEnglish, Language.HASHCODE))}: ") mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) loadThis() mv.visitMethodInsn(INVOKEVIRTUAL, Class.C_OBJECT, C_HASH_CODE, "()I", false) mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(I)Ljava/lang/StringBuilder;", false) mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_TO_STRING, "()Ljava/lang/String;", false) mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) } mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitLdcInsn(Log.SQUARE_MIDDLE) mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitLdcInsn("${Log.SQUARE_LEFT} ${String.format(header, Language.get(properties.useEnglish, Language.METHOD))}: ${name}(${fileName}:${method.lineNumber})") mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitLdcInsn("${Log.SQUARE_LEFT} ${String.format(header, Language.get(properties.useEnglish, Language.DESCRIPTOR))}: $descriptor") mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) method.args.forEachIndexed { index, arg -> mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitTypeInsn(NEW, C_STRING_BUILDER) mv.visitInsn(DUP) mv.visitMethodInsn(INVOKESPECIAL, C_STRING_BUILDER, C_INIT, "()V", false) mv.visitLdcInsn("${Log.SQUARE_LEFT} ${String.format(header, (Language.get(properties.useEnglish, Language.ARG) + "[" + arg + "]"))}: ") mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) loadArg(index) mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_APPEND, "(${argumentTypes[index].appendDescriptor})Ljava/lang/StringBuilder;", false) mv.visitMethodInsn(INVOKEVIRTUAL, C_STRING_BUILDER, C_TO_STRING, "()Ljava/lang/String;", false) mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) } mv.visitLabel(Label()) mv.visitLdcInsn(properties.tagChain) mv.visitLdcInsn(Log.SQUARE_BOTTOM) mv.visitMethodInsn(INVOKESTATIC, C_LOG, properties.levelChain, "(Ljava/lang/String;Ljava/lang/String;)I", false) mv.visitInsn(POP) } } }
0
Kotlin
0
0
9735dbf7fb332d1c7beef052207eb272d74efefe
8,859
MethodInjector
Apache License 2.0
projetos/arquivado/CursoAndroid/app/src/main/java/br/com/koruthos/cursoandroid/network/NetworkManager.kt
chaua
517,803,177
false
{"Kotlin": 69622, "C++": 416}
package br.com.koruthos.cursoandroid.network import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory // Padrão de projetos: Singleton // - Garante que seja criado somente 1 objeto da classe no projeto todo // - Para criar uma classe Singleton, em kotlin declaramos com object object NetworkManager { // URL base da API // - Importante - precisa da / no final private val URL = "https://dummyjson.com/" lateinit var client: OkHttpClient val service: DummyJsonService by lazy { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY client = OkHttpClient.Builder().addInterceptor(interceptor).build() val retrofit = Retrofit.Builder() .baseUrl(URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() return@lazy retrofit.create(DummyJsonService::class.java) } fun stop() { client.dispatcher().cancelAll() } }
0
Kotlin
1
9
aa4e2f61580920cb0585b611f4a91650dc2b3f15
1,111
programacao-mobile
MIT License
stream-raw-video-and-audio/src/main/java/io/agora/raw_video_audio_manager/RawVideoAudioManager.kt
AgoraIO
623,043,738
false
{"Kotlin": 141696}
package io.agora.raw_video_audio_manager import android.content.Context import io.agora.authentication_manager.AuthenticationManager import io.agora.base.VideoFrame import io.agora.rtc2.Constants import io.agora.rtc2.IAudioFrameObserver import io.agora.rtc2.audio.AudioParams import io.agora.rtc2.video.IVideoFrameObserver import java.nio.ByteBuffer class RawVideoAudioManager(context: Context?) : AuthenticationManager(context) { private var isZoomed = false // Set the format of the captured raw audio data. private val sampleRate = 16000 private val numberOfChannels = 1 private val samplesPerCall = 1024 private val iAudioFrameObserver: IAudioFrameObserver = object : IAudioFrameObserver { override fun onRecordAudioFrame( channelId: String?, type: Int, samplesPerChannel: Int, bytesPerSample: Int, channels: Int, samplesPerSec: Int, buffer: ByteBuffer?, renderTimeMs: Long, avsync_type: Int ): Boolean { // Gets the captured audio frame. // Add code here to process the recorded audio. return false } override fun onPlaybackAudioFrame( channelId: String?, type: Int, samplesPerChannel: Int, bytesPerSample: Int, channels: Int, samplesPerSec: Int, buffer: ByteBuffer?, renderTimeMs: Long, avsync_type: Int ): Boolean { // Gets the audio frame for playback. // Add code here to process the playback audio. // return true to indicate that Data has been processed return false } override fun onMixedAudioFrame( channelId: String?, type: Int, samplesPerChannel: Int, bytesPerSample: Int, channels: Int, samplesPerSec: Int, buffer: ByteBuffer?, renderTimeMs: Long, avsync_type: Int ): Boolean { // Retrieves the mixed captured and playback audio frame. return false } override fun onEarMonitoringAudioFrame( type: Int, samplesPerChannel: Int, bytesPerSample: Int, channels: Int, samplesPerSec: Int, buffer: ByteBuffer?, renderTimeMs: Long, avsync_type: Int ): Boolean { return false } override fun onPlaybackAudioFrameBeforeMixing( channelId: String?, userId: Int, type: Int, samplesPerChannel: Int, bytesPerSample: Int, channels: Int, samplesPerSec: Int, buffer: ByteBuffer?, renderTimeMs: Long, avsync_type: Int ): Boolean { // Retrieves the audio frame of a specified user before mixing. return false } override fun getObservedAudioFramePosition(): Int { return 0 } override fun getRecordAudioParams(): AudioParams { return AudioParams(sampleRate,numberOfChannels, 0 ,samplesPerCall) } override fun getPlaybackAudioParams(): AudioParams { return AudioParams(sampleRate,numberOfChannels, 0 ,samplesPerCall) } override fun getMixedAudioParams(): AudioParams { return AudioParams(sampleRate,numberOfChannels, 0 ,samplesPerCall) } override fun getEarMonitoringAudioParams(): AudioParams { return AudioParams(sampleRate,numberOfChannels, 0 ,samplesPerCall) } } private val iVideoFrameObserver: IVideoFrameObserver = object : IVideoFrameObserver { override fun onCaptureVideoFrame(sourceType: Int, videoFrame: VideoFrame): Boolean { if (isZoomed) { // Read the videoFrame buffer var buffer = videoFrame.buffer val w = buffer.width val h = buffer.height val cropX = (w - 320) / 2 val cropY = (h - 240) / 2 val cropWidth = 320 val cropHeight = 240 val scaleWidth = 320 val scaleHeight = 240 // modify the buffer buffer = buffer.cropAndScale( cropX, cropY, cropWidth, cropHeight, scaleWidth, scaleHeight ) // replace the videoFrame buffer with the modified buffer videoFrame.replaceBuffer(buffer, 270, videoFrame.timestampNs) } return true } override fun onPreEncodeVideoFrame(sourceType: Int, videoFrame: VideoFrame?): Boolean { return false } override fun onMediaPlayerVideoFrame(videoFrame: VideoFrame, i: Int): Boolean { return false } override fun onRenderVideoFrame(s: String, i: Int, videoFrame: VideoFrame): Boolean { return true } override fun getVideoFrameProcessMode(): Int { // The process mode of the video frame. 0 means read-only, and 1 means read-and-write. return 1 } override fun getVideoFormatPreference(): Int { return 1 } override fun getRotationApplied(): Boolean { return false } override fun getMirrorApplied(): Boolean { return false } override fun getObservedFramePosition(): Int { return 0 } } override fun joinChannel(channelName: String, token: String?): Int { // Register the video frame observer agoraEngine!!.registerVideoFrameObserver(iVideoFrameObserver) // Register the audio frame observer agoraEngine!!.registerAudioFrameObserver(iAudioFrameObserver) agoraEngine!!.setRecordingAudioFrameParameters( sampleRate, numberOfChannels, Constants.RAW_AUDIO_FRAME_OP_MODE_READ_WRITE, samplesPerCall ) agoraEngine!!.setPlaybackAudioFrameParameters( sampleRate, numberOfChannels, Constants.RAW_AUDIO_FRAME_OP_MODE_READ_WRITE, samplesPerCall ) agoraEngine!!.setMixedAudioFrameParameters( sampleRate, numberOfChannels, samplesPerCall ) return super.joinChannel(channelName, token) } override fun leaveChannel() { agoraEngine!!.registerVideoFrameObserver(null) agoraEngine!!.registerAudioFrameObserver(null) super.leaveChannel() } fun setZoom(enable: Boolean) { isZoomed = enable } }
1
Kotlin
3
5
75e53677ee7f1febbb8278d391d5632abecb3b0b
6,827
video-sdk-samples-android
MIT License
SharedCode/src/commonMain/kotlin/api/IdeaApi.kt
dmitrish
214,333,630
false
null
package com.kinsight.kinsightmultiplatform.api import com.kinsight.kinsightmultiplatform.models.GraphModel import com.kinsight.kinsightmultiplatform.models.IdeaModel import com.kinsight.kinsightmultiplatform.models.TickModel import com.kinsight.kinsightmultiplatform.models.TickerModel import io.ktor.client.HttpClient import io.ktor.client.features.json.JsonFeature import io.ktor.client.features.json.serializer.KotlinxSerializer import io.ktor.client.request.get import io.ktor.client.request.url import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonConfiguration import kotlinx.serialization.list import io.ktor.client.features.websocket.WebSockets import io.ktor.client.features.websocket.ws import io.ktor.client.request.post import io.ktor.http.HttpMethod import io.ktor.http.cio.websocket.Frame import io.ktor.http.cio.websocket.readText class IdeaApi(val baseUrl: String = "https://alphacapture.appspot.com") { private val client by lazy { HttpClient() { install(JsonFeature) { serializer = KotlinxSerializer(Json(JsonConfiguration(strictMode = false))).apply { setMapper(IdeaModel::class, IdeaModel.serializer()) setMapper(TickerModel::class, TickerModel.serializer()) setMapper(TickModel::class, TickModel.serializer()) setMapper(GraphModel::class, GraphModel.serializer()) } } } } private val wsclient by lazy { HttpClient() { install(WebSockets) { install(JsonFeature) { serializer = KotlinxSerializer(Json(JsonConfiguration(strictMode = false))).apply { setMapper(IdeaModel::class, IdeaModel.serializer()) } } } } } suspend fun receive(hostn: String, portn: Int, onReceive: (String)-> Unit){ try { wsclient.ws ( method = HttpMethod.Get, host = hostn, port = portn, path = "/ws" ) { send(Frame.Text("Android client connecting")) /* val frame = incoming.receive() when (frame) { is Frame.Text -> println(frame.readText()) is Frame.Binary -> println(frame.readBytes()) }*/ while (true) { val frame = incoming.receive() if (frame is Frame.Text) { val text = frame.readText() println("Android client received: $text") onReceive(text) } } } } catch(e: Throwable){ println(e.message) } println("exited ws listener") } suspend fun fetchIdeas(): List<IdeaModel> { val jsonArrayString = client.get<String> { url("$baseUrl/api/ideas") } return Json.nonstrict.parse(IdeaModel.serializer().list, jsonArrayString) } suspend fun fetchTickers(tickerFilter: String): List<TickerModel> { val jsonArrayString = client.get<String> { url("$baseUrl/api/ticker/$tickerFilter") } return Json.nonstrict.parse(TickerModel.serializer().list, jsonArrayString) } suspend fun fetchIdea(id: Int): IdeaModel { val jsonString = client.get<String> { url("$baseUrl/api/ideas/${id}") } return Json.nonstrict.parse(IdeaModel.serializer(), jsonString) } suspend fun fetchGraph(id: Int): GraphModel { val jsonString = client.get<String> { url("$baseUrl/api/graph/${id}") } return Json.nonstrict.parse(GraphModel.serializer(), jsonString) } suspend fun saveIdea(ideaModel: IdeaModel){ val json = io.ktor.client.features.json.defaultSerializer() client.post<Unit>() { url("$baseUrl/api/postidea") body = json.write(ideaModel) // Generates an OutgoingContent } } }
0
null
11
42
b2fd162b28e46a09983346efcfd16674f923cd02
4,158
kinsight-multiplatform
Apache License 2.0
app/src/main/java/com/lagradost/quicknovel/providers/WuxiaWorldOnlineProvider.kt
LagradOst
351,162,779
false
null
package com.lagradost.quicknovel.providers import com.lagradost.quicknovel.* import org.jsoup.Jsoup import org.jsoup.nodes.Element import java.lang.Exception import java.util.* import kotlin.collections.ArrayList class WuxiaWorldOnlineProvider : MainAPI() { override val mainUrl: String get() = "https://wuxiaworld.online" override val name: String get() = "WuxiaWorldOnline" override val hasMainPage: Boolean get() = true override val iconId: Int get() = R.drawable.icon_wuxiaworldonline override val iconBackgroundId: Int get() = R.color.wuxiaWorldOnlineColor override val tags: ArrayList<Pair<String, String>> get() = arrayListOf( Pair("All", ""), Pair("Chinese", "Chinese"), Pair("Action", "Action"), Pair("Adventure", "Adventure"), Pair("Fantasy", "Fantasy"), Pair("Martial Arts", "Martial Arts"), Pair("Romance", "Romance"), Pair("Xianxia", "Xianxia"), //Pair("Editor's choice", "Editor's choice"), Pair("Original", "Original"), Pair("Korean", "Korean"), Pair("Comedy", "Comedy"), Pair("Japanese", "Japanese"), Pair("Xuanhuan", "Xuanhuan"), Pair("Mystery", "Mystery"), Pair("Supernatural", "Supernatural"), Pair("Drama", "Drama"), Pair("Historical", "Historical"), Pair("Horror", "Horror"), Pair("Sci-Fi", "Sci-Fi"), Pair("Thriller", "Thriller"), Pair("Futuristic", "Futuristic"), Pair("Academy", "Academy"), Pair("Completed", "Completed"), Pair("Harem", "Harem"), Pair("School Life", "Schoollife"), Pair("Martial Arts", "Martialarts"), Pair("Slice of Life", "Sliceoflife"), Pair("English", "English"), Pair("Reincarnation", "Reincarnation"), Pair("Psychological", "Psychological"), Pair("Sci-fi", "Scifi"), Pair("Mature", "Mature"), Pair("Ghosts", "Ghosts"), Pair("Demons", "Demons"), Pair("Gods", "Gods"), Pair("Cultivation", "Cultivation"), ) override val orderBys: ArrayList<Pair<String, String>> get() = arrayListOf( Pair("Recents Updated", "recents"), Pair("Most Viewed", "popularity"), Pair("Lastest Releases", "date_added"), ) override fun loadMainPage(page: Int, mainCategory: String?, orderBy: String?, tag: String?): HeadMainPageResponse { val url = "$mainUrl/wuxia-list?sort=$orderBy&genres_include=$tag&page=$page" // TAGS val response = khttp.get(url) val document = Jsoup.parse(response.text) val headers = document.select("div.manga-grid > div.itemupdate") if (headers.size <= 0) return HeadMainPageResponse(url, ArrayList()) val returnValue: ArrayList<SearchResponse> = ArrayList() for (h in headers) { val a = h.selectFirst("> a") val cUrl = a.attr("href") val name = a.attr("title") val posterUrl = a.selectFirst("> img").attr("src") val latestChap = h.select("> ul > li")[1].selectFirst("> span > a").text() returnValue.add(SearchResponse(name, fixUrl(cUrl), fixUrl(posterUrl), null, latestChap, this.name)) } return HeadMainPageResponse(url, returnValue) } override fun loadHtml(url: String): String? { return try { val response = khttp.get(url) val document = Jsoup.parse(response.text) val res = document.selectFirst("div.content-area") if (res.html() == "") { return null } res.html() } catch (e: Exception) { null } } override fun search(query: String): ArrayList<SearchResponse> { val response = khttp.get("https://wuxiaworld.online/search.ajax?type=&query=$query") // AJAX, MIGHT ADD QUICK SEARCH val document = Jsoup.parse(response.text) val headers = document.select("ul > li") if (headers.size <= 0) return ArrayList() val returnValue: ArrayList<SearchResponse> = ArrayList() for (h in headers) { val hInfo = h.selectFirst("> span > a") val name = hInfo.text() val url = hInfo.attr("href") val posterUrl = h.selectFirst("> img").attr("src") val latestChapter = h.selectFirst("> span > a > span").text() returnValue.add(SearchResponse(name, url, fixUrl(posterUrl), null, latestChapter, this.name)) } return returnValue } override fun load(url: String): LoadResponse { val response = khttp.get(url) val document = Jsoup.parse(response.text) val infoHeaders = document.select("ul.truyen_info_right > li") fun getInfoHeader(startWidth: String): Element? { for (a in infoHeaders) { val sel = a.selectFirst("> span") if (sel != null && sel.hasText() && sel.text().startsWith(startWidth)) return a } return null } val name = document.selectFirst("li > h1.entry-title").text() val auth = getInfoHeader("Author") var author: String? = null if (auth != null) { author = auth.selectFirst("a").text() } val posterUrl = document.select("span.info_image > img").attr("src") val tags: ArrayList<String> = ArrayList() val gen = getInfoHeader("Genres") if (gen != null) { val tagsHeader = gen.select("> a") for (t in tagsHeader) { tags.add(t.text()) } } val synopsis = document.select("div.entry-header > div")[1].text() val data: ArrayList<ChapterData> = ArrayList() val chapterHeaders = document.select("div.chapter-list > div") for (c in chapterHeaders) { val spans = c.select("> span") val text = spans[0].selectFirst("> a") val cUrl = text.attr("href") val cName = text.text() val added = spans[1].text() val views = null data.add(ChapterData(cName, cUrl, added, views)) } data.reverse() var rating = 0 var peopleVoted = 0 try { rating = (document.selectFirst("span#averagerate").text().toFloat() * 200).toInt() peopleVoted = document.selectFirst("span#countrate").text().toInt() } catch (e: Exception) { // NO RATING } val viewHeader = getInfoHeader("Views") var views: Int? = null if (viewHeader != null) { var hString = viewHeader.text().replace(",", ".") .replace("\"", "") .substring("View : ".length).toLowerCase(Locale.getDefault()) var multi = 1 if (hString.contains('k')) { // YE THIS CAN BE IMPROVED multi = 1000 hString = hString.substring(0, hString.indexOf('k') - 1) } if (hString.contains('m')) { multi = 1000000 hString = hString.substring(0, hString.indexOf('m') - 1) } views = (hString.toFloat() * multi).toInt() } val statusHeader = getInfoHeader("Status") val status = if (statusHeader == null) null else when (statusHeader.selectFirst("> a").text() .toLowerCase(Locale.getDefault())) { "ongoing" -> 1 "completed" -> 2 else -> 0 } return LoadResponse( url, name, data, author, fixUrl(posterUrl), rating, peopleVoted, views, synopsis, tags, status) } }
96
null
57
867
149a4340e37010fa7a86b3224a4e930398f770d4
8,137
QuickNovel
MIT License
erikflowers-weather-icons/src/commonMain/kotlin/compose/icons/weathericons/DirectionLeft.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.weathericons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.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 compose.icons.WeatherIcons public val WeatherIcons.DirectionLeft: ImageVector get() { if (_directionLeft != null) { return _directionLeft!! } _directionLeft = Builder(name = "DirectionLeft", defaultWidth = 30.0.dp, defaultHeight = 30.0.dp, viewportWidth = 30.0f, viewportHeight = 30.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.09f, 14.96f) curveToRelative(0.0f, 0.37f, 0.12f, 0.68f, 0.37f, 0.92f) lineToRelative(3.84f, 3.75f) curveToRelative(0.22f, 0.25f, 0.51f, 0.38f, 0.85f, 0.38f) curveToRelative(0.35f, 0.0f, 0.65f, -0.12f, 0.89f, -0.35f) reflectiveCurveToRelative(0.37f, -0.53f, 0.37f, -0.88f) reflectiveCurveToRelative(-0.12f, -0.65f, -0.37f, -0.89f) lineToRelative(-1.64f, -1.64f) horizontalLineToRelative(10.3f) curveToRelative(0.35f, 0.0f, 0.64f, -0.12f, 0.87f, -0.37f) reflectiveCurveToRelative(0.34f, -0.55f, 0.34f, -0.9f) reflectiveCurveToRelative(-0.11f, -0.65f, -0.34f, -0.9f) reflectiveCurveToRelative(-0.52f, -0.38f, -0.87f, -0.39f) horizontalLineTo(11.4f) lineToRelative(1.64f, -1.66f) curveToRelative(0.24f, -0.24f, 0.37f, -0.53f, 0.37f, -0.86f) curveToRelative(0.0f, -0.35f, -0.12f, -0.65f, -0.37f, -0.89f) reflectiveCurveTo(12.5f, 9.9f, 12.14f, 9.9f) curveToRelative(-0.32f, 0.0f, -0.61f, 0.14f, -0.85f, 0.41f) lineToRelative(-3.84f, 3.75f) curveTo(7.21f, 14.31f, 7.09f, 14.6f, 7.09f, 14.96f) close() } } .build() return _directionLeft!! } private var _directionLeft: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,559
compose-icons
MIT License
Themes/src/commonMain/kotlin/io/nacular/doodle/theme/native/NativeTextFieldBehavior.kt
nacular
108,631,782
false
{"Kotlin": 3150677}
package io.nacular.doodle.theme.native import io.nacular.doodle.controls.text.TextField import io.nacular.doodle.controls.text.TextFieldBehavior import io.nacular.doodle.core.Behavior import io.nacular.doodle.drawing.Canvas /** * Behavior that modifies the background and foreground of a [TextField]. */ public interface NativeTextFieldBehaviorModifier: Behavior<TextField> { /** * Allows custom rendering for [textField]'s background * NOTE: implementations should most likely update [TextField.backgroundColor] to * ensure the results of this call are visible. * * @param textField being rendered * @param canvas to render onto */ public fun renderBackground(textField: TextField, canvas: Canvas) {} /** * Allows custom rendering for [textField]'s foreground. * * @param textField being rendered * @param canvas to render onto */ public fun renderForeground(textField: TextField, canvas: Canvas) {} } /** * Allows more control over how [TextField]s are styled while still applying native treatments. The given behavior * has the ability to render any background or foreground along with the native implementation's layer. */ public interface NativeTextFieldStyler { /** * Wraps [behavior] with other native styling for text fields. * * @param textField to apply [behavior] to * @param behavior to be "wrapped" * @return a new Behavior for the text field */ public operator fun invoke(textField: TextField, behavior: NativeTextFieldBehaviorModifier): TextFieldBehavior }
3
Kotlin
26
613
f7414d4c30cdd7632992071234223653e52b978c
1,594
doodle
MIT License
ui-components/src/main/java/com/mapbox/navigation/ui/components/maneuver/model/ManeuverSubOptions.kt
mapbox
87,455,763
false
null
package com.mapbox.navigation.ui.maneuver.model import androidx.annotation.StyleRes import androidx.core.widget.TextViewCompat import com.mapbox.navigation.ui.maneuver.R import com.mapbox.navigation.ui.maneuver.view.MapboxExitText import com.mapbox.navigation.ui.maneuver.view.MapboxSecondaryManeuver /** * Specifies options for styling [MapboxSecondaryManeuver]. * * @param textAppearance change the text appearance of secondary maneuver. * @see [TextViewCompat.setTextAppearance] * @param exitOptions options to style [MapboxExitText] in [MapboxSecondaryManeuver] */ class ManeuverSecondaryOptions private constructor( @StyleRes val textAppearance: Int, val exitOptions: ManeuverExitOptions ) { /** * @return the [Builder] that created the [ManeuverSecondaryOptions] */ fun toBuilder() = Builder() .textAppearance(textAppearance) .exitOptions(exitOptions) /** * Regenerate whenever a change is made */ override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ManeuverSecondaryOptions if (textAppearance != other.textAppearance) return false if (exitOptions != other.exitOptions) return false return true } /** * Regenerate whenever a change is made */ override fun hashCode(): Int { var result = textAppearance.hashCode() result = 31 * result + exitOptions.hashCode() return result } /** * Regenerate whenever a change is made */ override fun toString(): String { return "ManeuverSecondaryOptions(" + "textAppearance=$textAppearance, " + "exitOptions=$exitOptions" + ")" } /** * Builder of [ManeuverSecondaryOptions] */ class Builder { private var textAppearance = R.style.MapboxStyleSecondaryManeuver private var exitOptions = ManeuverExitOptions .Builder() .textAppearance(R.style.MapboxStyleExitTextForSecondary) .build() /** * Allows you to change the text appearance of [SecondaryManeuver] * * @see [TextViewCompat.setTextAppearance] * @param textAppearance text settings * @return Builder */ fun textAppearance(@StyleRes textAppearance: Int) = apply { this.textAppearance = textAppearance } /** * Allows you to specify the options for styling of [MapboxExitText] in * [MapboxSecondaryManeuver] * * @param exitOptions settings to exit properties * @return Builder */ fun exitOptions(exitOptions: ManeuverExitOptions) = apply { this.exitOptions = exitOptions } /** * Build a new instance of [ManeuverSecondaryOptions] * * @return ManeuverSecondaryOptions */ fun build() = ManeuverSecondaryOptions( textAppearance = textAppearance, exitOptions = exitOptions ) } }
508
null
319
621
ad73c6011348cb9b24b92a369024ca06f48845ab
3,127
mapbox-navigation-android
Apache License 2.0
utbot-framework/src/main/kotlin/org/utbot/fuzzer/FallbackModelProvider.kt
UnitTestBot
480,810,501
false
null
package org.utbot.fuzzer import org.utbot.common.isPublic import org.utbot.instrumentation.instrumentation.execution.constructors.UtModelConstructor import org.utbot.framework.plugin.api.ClassId import org.utbot.framework.plugin.api.UtArrayModel import org.utbot.framework.plugin.api.UtAssembleModel import org.utbot.framework.plugin.api.UtCompositeModel import org.utbot.framework.plugin.api.UtExecutableCallModel import org.utbot.framework.plugin.api.UtModel import org.utbot.framework.plugin.api.UtNullModel import org.utbot.framework.plugin.api.util.defaultValueModel import org.utbot.framework.plugin.api.util.executableId import org.utbot.framework.plugin.api.util.id import org.utbot.framework.plugin.api.util.isArray import org.utbot.framework.plugin.api.util.isClassType import org.utbot.framework.plugin.api.util.isEnum import org.utbot.framework.plugin.api.util.isIterable import org.utbot.framework.plugin.api.util.isPrimitive import org.utbot.framework.plugin.api.util.jClass import org.utbot.framework.plugin.api.util.kClass import org.utbot.fuzzer.providers.AbstractModelProvider import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.reflect.KClass /** * Provides some simple default models of any class. * * Used as a fallback implementation until other providers cover every type. */ open class FallbackModelProvider( private val idGenerator: IdGenerator<Int> ): AbstractModelProvider() { override fun toModel(classId: ClassId): UtModel { return createModelByClassId(classId) } fun toModel(klazz: KClass<*>): UtModel = createSimpleModelByKClass(klazz) private fun createModelByClassId(classId: ClassId): UtModel { val modelConstructor = UtModelConstructor(IdentityHashMap()) val defaultConstructor = classId.jClass.constructors.firstOrNull { it.parameters.isEmpty() && it.isPublic } return when { classId.isPrimitive || classId.isEnum || classId.isClassType -> classId.defaultValueModel() classId.isArray -> UtArrayModel( id = idGenerator.createId(), classId, length = 0, classId.elementClassId!!.defaultValueModel(), mutableMapOf() ) classId.isIterable -> { @Suppress("RemoveRedundantQualifierName") // ArrayDeque must be taken from java, not from kotlin val defaultInstance = when { defaultConstructor != null -> defaultConstructor.newInstance() classId.jClass.isAssignableFrom(java.util.ArrayList::class.java) -> ArrayList<Any>() classId.jClass.isAssignableFrom(java.util.TreeSet::class.java) -> TreeSet<Any>() classId.jClass.isAssignableFrom(java.util.HashMap::class.java) -> HashMap<Any, Any>() classId.jClass.isAssignableFrom(java.util.ArrayDeque::class.java) -> java.util.ArrayDeque<Any>() classId.jClass.isAssignableFrom(java.util.BitSet::class.java) -> BitSet() else -> null } if (defaultInstance != null) modelConstructor.construct(defaultInstance, classId) else createSimpleModelByKClass(classId.kClass) } else -> createSimpleModelByKClass(classId.kClass) } } private fun createSimpleModelByKClass(kclass: KClass<*>): UtModel { val defaultConstructor = kclass.java.constructors.firstOrNull { it.parameters.isEmpty() && it.isPublic // check constructor is public } return when { kclass.isAbstract -> { // sealed class is abstract by itself UtNullModel(kclass.java.id) } kclass.java.isEnum || kclass == java.lang.Class::class -> { // No sensible fallback solution for these classes except returning default `null` value UtNullModel(kclass.java.id) } defaultConstructor != null -> { UtAssembleModel( id = idGenerator.createId(), kclass.id, kclass.id.toString(), UtExecutableCallModel(instance = null, defaultConstructor.executableId, listOf()) ) } else -> { UtCompositeModel( id = idGenerator.createId(), kclass.id, isMock = false ) } } } }
337
Kotlin
25
70
d93fd5656645b55d3cece6eb13de8835bd0496d3
4,710
UTBotJava
Apache License 2.0
buildSrc/src/main/java/Versions.kt
tuan08t2
135,238,206
true
{"Kotlin": 172311, "Java": 12422, "Shell": 446}
/* * Copyright 2018 <NAME> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @Suppress("unused") internal object Versions { const val kotlin = "1.2.21" const val bintray = "1.7.3" const val maven = "1.5" const val buildTools = "27.0.3" const val compileSdk = 27 const val minSdk = 19 const val targetSdk = 27 const val easyCrypt = "1.3.4" const val easyCryptCode = 134 const val easyCryptSample = "2.3.3" const val easyCryptSampleCode = 233 const val support = "27.0.2" const val anko = "0.10.1" const val retrofit = "2.3.0" const val junit = "4.12" const val mockito = "1.10.19" const val transitionsEverywhere = "1.7.8" const val zxcvbn = "1.2.3" const val aboutPage = "1.2.2" }
0
Kotlin
0
0
b40f9dd40d926b8231e5e7405908e98cce69c444
1,268
EasyCrypt
Apache License 2.0
gameserver/src/main/kotlin/simulation/models/Card.kt
flofriday
750,336,268
false
{"Kotlin": 524281, "TypeScript": 149533, "Python": 32297, "Scheme": 3611, "Dockerfile": 608, "CSS": 580, "JavaScript": 221, "PowerShell": 185}
package simulation.models import java.io.Serializable enum class Color { CYAN, ORANGE, GREEN, PURPLE, ANY, } enum class CardType { NUMBER_CARD, SWITCH, SKIP, DRAW_TWO, CHOOSE, CHOOSE_DRAW, } data class Card( val type: CardType, val color: Color, val number: Int?, ) : Serializable { fun match(next: Card): Boolean { // Match if both colors are the same if (color == next.color) { return true } // Choose cards can always be played if (next.type == CardType.CHOOSE || next.type == CardType.CHOOSE_DRAW) { return true } // Anything can be played on a choosecard with the color any if (color == Color.ANY) { return true } // Number cards only match if the numbers are the same if (type == CardType.NUMBER_CARD && next.type == CardType.NUMBER_CARD) { return number == next.number } // All other types of cards can mach only in their types return type == next.type } fun name(): String { var colorName = color.toString().lowercase() val typeName = when (type) { CardType.NUMBER_CARD -> number.toString() CardType.SWITCH -> "switch" CardType.SKIP -> "skip" CardType.DRAW_TWO -> "draw(+2)" CardType.CHOOSE -> "choose" CardType.CHOOSE_DRAW -> "choose-draw(+4)" else -> throw Exception("Invalid case") } if (typeName.startsWith("choose")) { if (color == Color.ANY) { colorName = "no specific color)" } return "$typeName card (wishing $colorName)" } return "$colorName $typeName card" } }
0
Kotlin
0
0
6fc0a6dc80bd4b6adf6d7fee7921af8a361d03eb
1,850
CardLabs
Apache License 2.0
src/main/kotlin/xyz/neziw/pass4j/Pass4J.kt
neziw
594,821,586
false
null
package xyz.neziw.pass4j import java.awt.GridLayout import java.awt.Toolkit import java.awt.datatransfer.StringSelection import java.util.* import java.util.concurrent.Executors import javax.swing.* class Pass4J : JFrame() { private val executor = Executors.newSingleThreadExecutor() private val passwordField = JPasswordField() private val lengthField = JTextField() private val additionalCharsField = JTextField() private val includeAdditionalChars = JCheckBox("Include additional characters") init { title = "Password Generator" defaultCloseOperation = JFrame.EXIT_ON_CLOSE setSize(450, 340) isResizable = false layout = GridLayout(5, 2) add(JLabel("Password length:")) add(lengthField) add(JLabel("Additional characters:")) add(additionalCharsField) add(includeAdditionalChars) add(JButton("Generate").apply { addActionListener { executor.submit { val length = lengthField.text.toInt() val additionalChars = additionalCharsField.text val include = includeAdditionalChars.isSelected val password = generatePassword(length, additionalChars, include) SwingUtilities.invokeLater { passwordField.text = password } } } }) add(passwordField) add(JButton("Copy").apply { addActionListener { val password = passwordField.text val clipboard = Toolkit.getDefaultToolkit().systemClipboard val selection = StringSelection(password) clipboard.setContents(selection, selection) } }) isVisible = true } private fun generatePassword(length: Int, additionalChars: String, include: Boolean): String { val characters = if (include) "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$additionalChars" else "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" val password = StringBuilder() val random = Random() for (i in 0 until length) { password.append(characters[random.nextInt(characters.length)]) } return password.toString() } } fun main() { SwingUtilities.invokeLater { Pass4J() } }
0
Kotlin
0
2
636616ec01b4f5948a870df56c9352f811d870c6
2,377
Pass4J
MIT License
data/src/main/kotlin/com/vultisig/wallet/data/common/StringExtensions.kt
vultisig
789,965,982
false
{"Kotlin": 1403983, "Ruby": 1713}
package com.vultisig.wallet.common import com.google.protobuf.ByteString import com.vultisig.wallet.data.utils.Numeric fun String.toHexBytes(): ByteArray { return Numeric.hexStringToByteArray(this) } fun String.toHexByteArray(): ByteArray { return Numeric.hexStringToByteArray(this) } fun String.toByteString(): ByteString { return ByteString.copyFrom(this, Charsets.UTF_8) } fun String.toHexBytesInByteString(): ByteString { return ByteString.copyFrom(this.toHexBytes()) } internal fun String.stripHexPrefix(): String { return if (startsWith("0x")) { substring(2) } else { this } }
44
Kotlin
2
6
98e6a0754d4872ce4d44fa4a631488d4f805397f
633
vultisig-android
Apache License 2.0
sykepenger-model/src/main/kotlin/no/nav/helse/person/inntekt/Inntektshistorikk.kt
navikt
193,907,367
false
{"Kotlin": 6612297, "PLpgSQL": 2738, "Dockerfile": 168}
package no.nav.helse.person.inntekt import java.time.LocalDate import no.nav.helse.dto.deserialisering.InntektshistorikkInnDto import no.nav.helse.dto.serialisering.InntektshistorikkUtDto import no.nav.helse.person.InntekthistorikkVisitor import no.nav.helse.person.inntekt.AvklarbarSykepengegrunnlag.Companion.avklarSykepengegrunnlag internal class Inntektshistorikk private constructor(private val historikk: MutableList<Inntektsmelding>) { internal constructor() : this(mutableListOf()) internal companion object { internal fun gjenopprett(dto: InntektshistorikkInnDto) = Inntektshistorikk( historikk = dto.historikk.map { Inntektsmelding.gjenopprett(it) }.toMutableList() ) } internal fun accept(visitor: InntekthistorikkVisitor) { visitor.preVisitInntekthistorikk(this) historikk.forEach { it.accept(visitor) } visitor.postVisitInntekthistorikk(this) } internal fun leggTil(inntekt: Inntektsmelding): Boolean { if (historikk.any { !it.kanLagres(inntekt) }) return false historikk.add(0, inntekt) return true } internal fun avklarSykepengegrunnlag(skjæringstidspunkt: LocalDate, førsteFraværsdag: LocalDate?, skattSykepengegrunnlag: SkattSykepengegrunnlag?): Inntektsopplysning? = historikk.avklarSykepengegrunnlag(skjæringstidspunkt, førsteFraværsdag, skattSykepengegrunnlag) internal fun dto() = InntektshistorikkUtDto( historikk = historikk.map { it.dto() } ) }
2
Kotlin
7
3
a521d8ace1254484491a0cd86ef6690390dae3d7
1,538
helse-spleis
MIT License
commons-ktx/src/main/java/com/paulrybitskyi/commons/ktx/DrawableExtensions.kt
mars885
285,931,745
false
null
/* * Copyright 2020 <NAME>, <EMAIL> * * 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. */ @file:JvmName("DrawableUtils") package com.paulrybitskyi.commons.ktx import android.content.res.ColorStateList import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.graphics.drawable.RippleDrawable import androidx.annotation.ColorInt import androidx.core.graphics.drawable.DrawableCompat fun Drawable.setColor(@ColorInt color: Int): Drawable { return when (val newDrawable = mutate()) { is RippleDrawable -> newDrawable.apply { setColor(color.toColorStateList()) } is GradientDrawable -> newDrawable.apply { setColor(color) } else -> newDrawable.apply { colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN) } } } fun Drawable.setGradientColors( @ColorInt startColor: Int, @ColorInt endColor: Int ): Drawable { return if (this is GradientDrawable) { mutate().apply { colors = intArrayOf(startColor, endColor) } } else { this } } fun Drawable.setSize(size: Int) { applyBounds( left = 0, top = 0, right = size, bottom = size ) } fun Drawable.applyBounds( left: Int, top: Int, right: Int, bottom: Int ): Drawable { return apply { setBounds(left, top, right, bottom) } } fun Drawable.setTintList(states: Array<IntArray>, colors: IntArray) { DrawableCompat.setTintList( DrawableCompat.wrap(this), ColorStateList(states, colors) ) } fun Drawable.toBitmap( config: Bitmap.Config = Bitmap.Config.ARGB_8888 ): Bitmap { return Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, config) .also { bitmap -> val canvas = Canvas(bitmap) applyBounds( left = 0, top = 0, right = canvas.width, bottom = canvas.height ) draw(canvas) } }
0
Kotlin
0
8
3ba7f80ab8c76fe7c7a984aac3d0f5c39a698778
2,628
android-commons
Apache License 2.0
app/src/main/java/org/futo/voiceinput/settings/Help.kt
lrq3000
715,067,641
false
{"Kotlin": 269156, "HTML": 81553, "Shell": 699}
package org.futo.voiceinput.settings import android.app.PendingIntent import android.content.Intent import android.speech.RecognizerIntent import android.widget.Toast import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import org.futo.voiceinput.R import org.futo.voiceinput.RecognizeWindow import org.futo.voiceinput.Screen import org.futo.voiceinput.ui.theme.Typography @Composable @Preview fun HelpScreen() { val textItem: @Composable (text: String) -> Unit = { text -> Text(text, style = Typography.bodyMedium, modifier = Modifier.padding(2.dp, 4.dp)) } val context = LocalContext.current val antiConfusionText = stringResource(R.string.just_a_demonstration) val showAntiConfusionToast = { val toast = Toast.makeText( context, antiConfusionText, Toast.LENGTH_SHORT ) toast.show() } Screen(stringResource(R.string.help_title)) { ScrollableList { textItem(stringResource(R.string.help_paragraph_1)) textItem(stringResource(R.string.help_paragraph_2)) Column(modifier = Modifier.fillMaxWidth()) { Box(modifier = Modifier.align(CenterHorizontally)) { RecognizeWindow(onClose = showAntiConfusionToast, forceNoUnpaidNotice = true) { Text( stringResource(R.string.voice_input_will_look_like_this), modifier = Modifier.align(CenterHorizontally), textAlign = TextAlign.Center ) Text( stringResource(R.string.look_for_the_big_off_center_futo_logo_in_the_background), style = Typography.bodyMedium, modifier = Modifier .padding(2.dp, 4.dp) .align(CenterHorizontally), textAlign = TextAlign.Center ) } } } Spacer(modifier = Modifier.height(16.dp)) Column(modifier = Modifier.fillMaxWidth()) { Box(modifier = Modifier.align(CenterHorizontally)) { RecognizeWindow(onClose = showAntiConfusionToast, forceNoUnpaidNotice = true) { IconButton( onClick = showAntiConfusionToast, modifier = Modifier.align(CenterHorizontally) ) { Icon( painter = painterResource(R.drawable.mic_2_), contentDescription = stringResource(R.string.stop_recording), modifier = Modifier.size(48.dp), tint = MaterialTheme.colorScheme.onSecondary ) } Spacer(modifier = Modifier.height(8.dp)) Text( stringResource(R.string.once_you_re_done_talking_you_can_hit_the_microphone_button_to_stop), style = Typography.bodyMedium, modifier = Modifier .padding(2.dp, 4.dp) .align(CenterHorizontally), textAlign = TextAlign.Center ) } } } Spacer(modifier = Modifier.height(16.dp)) textItem(stringResource(R.string.help_paragraph_3)) Column(modifier = Modifier.padding(16.dp, 0.dp)) { textItem(stringResource(R.string.aosp_keyboard_included_in_aosp_based_roms)) textItem(stringResource(R.string.openboard_available_on_f_droid)) textItem(stringResource(R.string.anysoftkeyboard_available_on_f_droid_and_google_play)) textItem(stringResource(R.string.unexpected_keyboard)) } Spacer(modifier = Modifier.height(24.dp)) Tip(stringResource(R.string.help_paragraph_5)) Spacer(modifier = Modifier.height(4.dp)) textItem(stringResource(R.string.help_paragraph_6)) Column(modifier = Modifier.padding(16.dp, 0.dp)) { textItem(stringResource(R.string.grammarly_keyboard)) textItem(stringResource(R.string.microsoft_swiftkey)) } Spacer(modifier = Modifier.height(24.dp)) Tip(stringResource(R.string.help_paragraph_7)) Spacer(modifier = Modifier.height(4.dp)) textItem(stringResource(R.string.help_paragraph_8)) Column(modifier = Modifier.padding(16.dp, 0.dp)) { textItem(stringResource(R.string.gboard)) textItem(stringResource(R.string.samsung_keyboard_one_ui_5)) textItem(stringResource(R.string.typewise)) textItem(stringResource(R.string.simple_keyboard)) } Spacer(modifier = Modifier.height(16.dp)) Tip(stringResource(R.string.help_paragraph_9)) Spacer(modifier = Modifier.height(16.dp)) textItem(stringResource(R.string.wrong_voice_input_body)) Column(modifier = Modifier.fillMaxWidth()) { Button( onClick = { openImeOptions(context) }, modifier = Modifier.align(CenterHorizontally) ) { Text(stringResource(R.string.open_input_method_settings)) } } Spacer(modifier = Modifier.height(32.dp)) textItem(stringResource(R.string.help_with_email)) ShareFeedbackOption() Spacer(modifier = Modifier.height(100.dp)) } } }
0
Kotlin
0
8
d67d85681a02da52d91c09846af121b1f5756bf5
6,879
futo-voiceinput-whisper
Freetype Project License
signer/src/main/java/com/uport/sdk/signer/encryption/FingerprintAsymmetricProtection.kt
uport-project
119,370,347
false
null
@file:Suppress("DEPRECATION", "TooGenericExceptionCaught") package com.uport.sdk.signer.encryption import android.annotation.TargetApi import android.content.Context import android.hardware.fingerprint.FingerprintManager import android.os.Build import androidx.fragment.app.DialogFragment import androidx.appcompat.app.AppCompatActivity import com.uport.sdk.signer.DecryptionCallback import com.uport.sdk.signer.EncryptionCallback import com.uport.sdk.signer.R import com.uport.sdk.signer.UportSigner import com.uport.sdk.signer.UportSigner.Companion.ERR_ACTIVITY_DOES_NOT_EXIST import com.uport.sdk.signer.encryption.AndroidKeyStoreHelper.generateWrappingKey import com.uport.sdk.signer.encryption.AndroidKeyStoreHelper.getWrappingCipher import com.uport.sdk.signer.encryption.KeyProtection.Companion.encryptRaw import com.uport.sdk.signer.unpackCiphertext import javax.crypto.Cipher class FingerprintAsymmetricProtection : KeyProtection { override val alias = "__fingerprint_asymmetric_key_alias__" override fun genKey(context: Context) { generateWrappingKey(context, alias, true) } override fun encrypt(context: Context, purpose: String, blob: ByteArray, callback: EncryptionCallback) { try { val ciphertext = encryptRaw(blob, alias) callback(null, ciphertext) } catch (ex: Exception) { callback(ex, "") } } @TargetApi(Build.VERSION_CODES.M) override fun decrypt( context: Context, purpose: String, ciphertext: String, callback: DecryptionCallback ) { try { val (_, encryptedBytes) = unpackCiphertext(ciphertext) val cipher = getWrappingCipher(Cipher.DECRYPT_MODE, alias) if (context is AppCompatActivity) { showFingerprintDialog(context, purpose, cipher) { err, cryptoObject -> if (err != null) { callback(err, ByteArray(0)) } else { val cleartextBytes = cryptoObject.cipher.doFinal(encryptedBytes) callback(null, cleartextBytes) } } } else { callback(IllegalStateException(ERR_ACTIVITY_DOES_NOT_EXIST), ByteArray(0)) } } catch (ex: Exception) { callback(ex, ByteArray(0)) } } private lateinit var fingerprintDialog: FingerprintDialog @TargetApi(Build.VERSION_CODES.M) private fun showFingerprintDialog( activity: AppCompatActivity, purpose: String, cipher: Cipher, callback: (err: Exception?, FingerprintManager.CryptoObject) -> Unit ) { fingerprintDialog = FingerprintDialog.create(purpose) fingerprintDialog.setStyle(DialogFragment.STYLE_NO_TITLE, R.style.uport_AppDialogTheme) if (activity.fragmentManager.findFragmentByTag(FingerprintDialog.TAG_FINGERPRINT_DIALOG) == null) { val cryptoObject = FingerprintManager.CryptoObject(cipher) fingerprintDialog.init( cryptoObject, object : FingerprintDialog.FingerprintDialogCallbacks { override fun onFingerprintSuccess(cryptoObject: FingerprintManager.CryptoObject) { callback(null, cryptoObject) fingerprintDialog.dismiss() } override fun onFingerprintCancel() { callback(RuntimeException(UportSigner.ERR_AUTH_CANCELED), cryptoObject) fingerprintDialog.dismiss() } } ) fingerprintDialog.show( activity.supportFragmentManager, FingerprintDialog.TAG_FINGERPRINT_DIALOG ) } } }
1
Kotlin
3
9
ae1593e5b19c3637f85e88515dd7ae8c376af192
3,872
uport-android-signer
Apache License 2.0
js/js.translator/testData/incremental/invalidation/companionFunction/lib1/l1.1.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
interface MyInterface { fun interfaceFunction(): String } class MyClass1 { companion object { fun companionFunction() = 1 } } class MyClass2 { companion object { fun companionFunction() = "1" } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
234
kotlin
Apache License 2.0
src/main/kotlin/rule/other/Iterator.kt
tmdgh1592
615,902,014
false
null
package rule.other internal interface Iterator<T> { fun hasNext(): Boolean fun next(): T }
1
Kotlin
3
7
965e277ea8a70d18c2d5c52056e1df3335d770fb
100
budool-omok-rule
MIT License
im-lib/src/main/java/vip/qsos/im/lib/server/model/WebSocketResponse.kt
hslooooooool
228,559,198
false
{"Kotlin": 205520}
package vip.qsos.im.lib.server.model import vip.qsos.im.lib.server.config.IMConstant /**Websocket 响应结果实体 * @author : 华清松 */ class WebSocketResponse(private val token: String) : IProtobufAble { override val type: Byte = IMConstant.ProtobufType.WEBSOCKET override val byteArray: ByteArray get() = this.toString().toByteArray() override fun toString(): String { val builder = StringBuilder() builder.append("HTTP/1.1 101 Switching Protocols") builder.append("\r\n") builder.append("Upgrade: websocket") builder.append("\r\n") builder.append("Connection: Upgrade") builder.append("\r\n") builder.append("Sec-WebSocket-Accept:$token") builder.append("\r\n") builder.append("\r\n") return builder.toString() } }
4
Kotlin
1
1
659119b3fe5e51bf84a45e22209cb1d9f1285138
825
im-netty-server
MIT License
ok-deskshare-be-common/src/main/kotlin/com/deskshare/common/context/query/FindByIdQueryRequest.kt
otuskotlin
378,049,296
false
null
package com.deskshare.common.context.query import com.deskshare.common.models.ReservationIdModel import com.deskshare.common.models.ReservationModel class FindByIdQueryRequest( var reservationId: ReservationIdModel = ReservationIdModel.NONE, var responseModels: MutableList<ReservationModel> = mutableListOf() ) : QueryRequestInterface
1
Kotlin
0
1
baa39cc2b6c54bfd735992a91906817dd99082b0
346
ok-202105-deskshare-gl
MIT License
app/src/main/java/me/antonio/noack/elementalcommunity/NewsView.kt
AntonioNoack
181,624,015
false
null
package me.antonio.noack.elementalcommunity import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.View import me.antonio.noack.elementalcommunity.GroupsEtc.GroupColors import me.antonio.noack.elementalcommunity.GroupsEtc.drawElement import me.antonio.noack.elementalcommunity.api.WebServices import me.antonio.noack.elementalcommunity.api.web.News import java.lang.StrictMath.pow import java.util.* import kotlin.math.max import kotlin.math.min import kotlin.math.sin class NewsView(ctx: Context, attributeSet: AttributeSet?): View(ctx, attributeSet) { private val noise = NoiseMap2D() var news = ArrayList<News>(10) private val relativeWidth = 4f override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) setMeasuredDimension(measuredWidth, measuredHeight) } private val random = Random(System.nanoTime()) private val bgPaint = Paint() private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG) override fun onDraw(canvas: Canvas) { super.onDraw(canvas) GroupsEtc.tick() val save0 = canvas.save() textPaint.textAlign = Paint.Align.CENTER val size = GroupColors.size val width = measuredWidth * 1f val widthPerNode = width / relativeWidth val time = sin(System.nanoTime() * 1e-10).toFloat() val hasNews = news.isNotEmpty() val offline = AllManager.offlineMode for(i in 0 until max(10, news.size)){ val candidate = news.getOrNull(i) val store = canvas.save() canvas.rotate((noise.getNoise(time, i)-.5f) * 50, width/2, widthPerNode/2) drawElement(canvas, -1, 0f, 0f, 0f, widthPerNode, true, candidate?.a?.name ?: if(hasNews) "God" else if(offline) "Offline Mode" else "App", candidate?.a?.group ?: (noise.getNoise(time, 78+i*100).times(size).toInt()), -1, bgPaint, textPaint) drawElement(canvas, -1, widthPerNode*(relativeWidth-1f)/2, 0f, 0f, widthPerNode, true, candidate?.b?.name ?: if(hasNews) "Magic" else if(offline) "No WLAN" else "No WLAN", candidate?.b?.group ?: (noise.getNoise(time, 156+i*1020).times(size).toInt()), -1, bgPaint, textPaint) drawElement(canvas, -1, widthPerNode*(relativeWidth-1f), 0f, 0f, widthPerNode, true, candidate?.result ?: if(hasNews) "Elements" else if(offline) "Game" else "No Game", candidate?.resultGroup ?: (noise.getNoise(time, 23+i*950).times(size).toInt()), -1, bgPaint, textPaint) textPaint.textAlign = Paint.Align.CENTER textPaint.textSize = widthPerNode*.5f textPaint.color = 0xff777777.toInt() val dy = (textPaint.ascent() + textPaint.descent())/2 canvas.drawText("+", widthPerNode*((relativeWidth-1f)/4 + 0.5f), widthPerNode/2-dy, textPaint) canvas.drawText("->", widthPerNode*((relativeWidth-1f)*3/4 + 0.5f), widthPerNode/2-dy, textPaint) /*bgPaint.color = bgPaint.color and 0x50ffffff.toInt() canvas.drawRect(0f, 0f, width, widthPerNode, bgPaint) */ textPaint.color = 0xff000000.toInt() textPaint.textSize = widthPerNode*.21f val dy2 = (textPaint.ascent() + textPaint.descent())/2 canvas.drawText("${timeString(candidate?.dt ?: (pow(2.0, 1.0 + 20.0 * random.nextDouble())).toInt())} ago ${if((candidate?.w ?: 0) > 0) "liked" else "disliked"}", widthPerNode*relativeWidth/2, widthPerNode + 1.5f * dy2, textPaint) canvas.restoreToCount(store) canvas.translate(0f, widthPerNode * 0.85f) } canvas.restoreToCount(save0) textPaint.color = -1 textPaint.textSize = widthPerNode * 0.2f textPaint.textAlign = Paint.Align.CENTER val padding = textPaint.descent() val text = "Server: ${WebServices.serverName}" val x0 = min(padding * 3f + 0.5f * textPaint.measureText(text), measuredWidth * 0.5f) val y0 = padding * 2 + 0.5f * (textPaint.textSize - (textPaint.ascent() + textPaint.descent())) bgPaint.color = 0xff555555.toInt() canvas.drawRect(padding, padding, x0*2-padding, padding*3+textPaint.textSize, bgPaint) canvas.drawText(text, x0, y0, textPaint) } private fun timeString(sec: Int): String { return if(sec < 30){ sec.toString()+"s" } else if(sec < 180){ ((sec+5)/10*10).toString()+"s" } else { val min = (sec+30) / 60 if(min < 30){ min.toString()+"min" } else if(min < 180){ ((min+5)/10*10).toString()+"min" } else { val hour = (min+30) / 60 if(hour < 72){ hour.toString()+"h" } else { val days = (hour + 12) / 24 days.toString()+"d" } } } } }
0
null
0
3
fe0cfa574f82884e832b5736e1f88cba9eb2e8d3
5,170
ElementalCommunity
Apache License 2.0
solar/src/main/java/com/chiksmedina/solar/lineduotone/time/Alarm.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.lineduotone.time import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.lineduotone.TimeGroup val TimeGroup.Alarm: ImageVector get() { if (_alarm != null) { return _alarm!! } _alarm = Builder( name = "Alarm", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(12.0f, 13.0f) moveToRelative(-9.0f, 0.0f) arcToRelative(9.0f, 9.0f, 0.0f, true, true, 18.0f, 0.0f) arcToRelative(9.0f, 9.0f, 0.0f, true, true, -18.0f, 0.0f) } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(12.0f, 9.0f) verticalLineTo(13.0f) lineTo(14.5f, 15.5f) } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(3.5f, 4.5f) lineTo(7.5f, 2.0f) } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(20.5f, 4.5f) lineTo(16.5f, 2.0f) } } .build() return _alarm!! } private var _alarm: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
2,833
SolarIconSetAndroid
MIT License
composeApp/src/commonMain/kotlin/io/github/snd_r/komelia/ui/MainScreen.kt
Snd-R
775,064,249
false
{"Kotlin": 797189, "CMake": 18341, "C": 5383, "Dockerfile": 767, "Shell": 116}
package io.github.snd_r.komelia.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.material3.DrawerValue.Closed import androidx.compose.material3.DrawerValue.Open import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.rememberCoroutineScope import cafe.adriel.voyager.core.model.rememberScreenModel import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.CurrentScreen import cafe.adriel.voyager.navigator.Navigator import io.github.snd_r.komelia.platform.WindowWidth import io.github.snd_r.komelia.platform.WindowWidth.FULL import io.github.snd_r.komelia.ui.book.BookScreen import io.github.snd_r.komelia.ui.library.DashboardScreen import io.github.snd_r.komelia.ui.library.LibraryScreen import io.github.snd_r.komelia.ui.navigation.AppBar import io.github.snd_r.komelia.ui.navigation.NavBarContent import io.github.snd_r.komelia.ui.search.SearchScreen import io.github.snd_r.komelia.ui.series.SeriesScreen import io.github.snd_r.komelia.ui.settings.SettingsScreen import kotlinx.coroutines.launch class MainScreen( private val defaultScreen: Screen = DashboardScreen() ) : Screen { @Composable override fun Content() { val viewModelFactory = LocalViewModelFactory.current val width = LocalWindowWidth.current Navigator( screen = defaultScreen, onBackPressed = null ) { navigator -> val vm = rememberScreenModel { viewModelFactory.getNavigationViewModel(navigator) } LaunchedEffect(width) { when (width) { FULL -> vm.navBarState.snapTo(Open) else -> vm.navBarState.snapTo(Closed) } } Column { AppBar( onMenuButtonPress = { vm.toggleNavBar() }, query = vm.searchBarState.currentQuery(), onQueryChange = vm.searchBarState::onQueryChange, isLoading = vm.searchBarState.isLoading, onSearchAllClick = { navigator.push(SearchScreen(it)) }, searchResults = vm.searchBarState.searchResults(), libraryById = vm.searchBarState::getLibraryById, onBookClick = { navigator.replaceAll(BookScreen(it)) }, onSeriesClick = { navigator.replaceAll(SeriesScreen(it)) }, ) when (width) { // is not working properly https://issuetracker.google.com/issues/218286829#comment6 // FULL -> DismissibleNavigationDrawer( // drawerState = vm.navBarState, // drawerContent = { NavBar(vm, navigator) }, // content = { CurrentScreen() } // ) FULL -> Row { if (vm.navBarState.targetValue == Open) NavBar(vm, navigator, width) CurrentScreen() } else -> ModalNavigationDrawer( drawerState = vm.navBarState, drawerContent = { NavBar(vm, navigator, width) }, content = { CurrentScreen() } ) } } } } @Composable private fun NavBar( vm: MainScreenViewModel, navigator: Navigator, width: WindowWidth ) { val coroutineScope = rememberCoroutineScope() NavBarContent( currentScreen = navigator.lastItem, libraries = vm.libraries.collectAsState().value, libraryActions = vm.getLibraryActions(), onHomeClick = { navigator.replaceAll(DashboardScreen()) if (width != FULL) coroutineScope.launch { vm.navBarState.snapTo(Closed) } }, onLibrariesClick = { navigator.replaceAll(LibraryScreen()) if (width != FULL) coroutineScope.launch { vm.navBarState.snapTo(Closed) } }, onLibraryClick = { navigator.replaceAll(LibraryScreen(it)) if (width != FULL) coroutineScope.launch { vm.navBarState.snapTo(Closed) } }, onSettingsClick = { navigator.parent!!.push(SettingsScreen()) }, taskQueueStatus = vm.komgaTaskQueueStatus.collectAsState().value ) } }
0
Kotlin
0
2
a2acfae425fa125596f7fd531396ea8725fb1e9e
4,651
Komelia
Apache License 2.0
data/remote/user/src/main/kotlin/no/kij/tsuki/data/remote/user/di/UserBindingModule.kt
kissorjeyabalan
578,978,416
false
null
/* * Copyright (C) 2022 Kissor Jeyabalan * * 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 no.kij.tsuki.data.remote.user.di import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import no.kij.tsuki.data.remote.user.UserRemoteSource import no.kij.tsuki.data.remote.user.UserRemoteSourceImpl import no.kij.tsuki.data.remote.user.manager.UserIdManagerImpl import no.kij.tsuki.data.remote.user.repository.UserRepositoryImpl import no.kij.tsuki.domain.user.manager.UserIdManager import no.kij.tsuki.domain.user.repository.UserRepository @Module @InstallIn(SingletonComponent::class) internal sealed interface UserBindingModule { @Binds fun bindUserIdManager(impl: UserIdManagerImpl): UserIdManager @Binds fun bindUserRepository(impl: UserRepositoryImpl): UserRepository @Binds fun bindUserRemoteSource(impl: UserRemoteSourceImpl): UserRemoteSource }
9
Kotlin
0
2
b69c5d47945336f264c8f09ed2930ccf0e50f45d
1,463
tsuki
Apache License 2.0
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/CoroutineAgentConnector.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine import com.intellij.execution.JavaTestConfigurationWithDiscoverySupport import com.intellij.execution.configurations.JavaParameters import com.intellij.execution.configurations.ModuleBasedConfiguration import com.intellij.execution.configurations.RunConfigurationBase import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JdkUtil import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem import com.intellij.psi.JavaPsiFacade import org.apache.maven.artifact.versioning.DefaultArtifactVersion import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode enum class CoroutineDebuggerMode { DISABLED, VERSION_UP_TO_1_3_5, VERSION_1_3_6_AND_UP, VERSION_1_3_8_AND_UP, } internal object CoroutineAgentConnector { private data class KotlinxCoroutinesSearchResult(val jarPath: String?, val debuggerMode: CoroutineDebuggerMode) private const val kotlinxCoroutinesCoreName = "kotlinx-coroutines-core" private const val kotlinStdlibName = "kotlin-stdlib" private const val kotlinxCoroutinesPackageName = "kotlinx.coroutines" private const val jarSeparator = "!/" private val versionToCompareTo = DefaultArtifactVersion("1.3.7-255") private val kotlinxCoroutinesCoreJarRegex = Regex(""".+\W$kotlinxCoroutinesCoreName(-jvm)?-(\d[\w.\-]+)?\.jar""") fun attachCoroutineAgent(project: Project, params: JavaParameters, configuration: RunConfigurationBase<*>?): Boolean { val searchResult = findKotlinxCoroutinesCoreJar(project, configuration) if (searchResult.debuggerMode == CoroutineDebuggerMode.VERSION_1_3_8_AND_UP && searchResult.jarPath != null) { return initializeCoroutineAgent(params, searchResult.jarPath) } return false } private fun findKotlinxCoroutinesCoreJar(project: Project, configuration: RunConfigurationBase<*>?): KotlinxCoroutinesSearchResult { val matchResult = project .getJarVirtualFiles(configuration, kotlinxCoroutinesPackageName) .asSequence() .mapNotNull { kotlinxCoroutinesCoreJarRegex.matchEntire(it) } .firstOrNull() if (matchResult == null || matchResult.groupValues.size < 3) { return KotlinxCoroutinesSearchResult(null, CoroutineDebuggerMode.DISABLED) } return KotlinxCoroutinesSearchResult( matchResult.value, determineCoreVersionMode(matchResult.groupValues[2]) ) } private fun Project.getJarVirtualFiles( configuration: RunConfigurationBase<*>?, packageName: String ): List<String> { if (configuration !is ModuleBasedConfiguration<*, *>) return emptyList() val scope = configuration.configurationModule.module?.getModuleRuntimeScope( configuration is JavaTestConfigurationWithDiscoverySupport ) ?: return emptyList() val kotlinxCoroutinesPackage = runReadActionInSmartMode { JavaPsiFacade.getInstance(this).findPackage(packageName) } ?: return emptyList() return kotlinxCoroutinesPackage.getDirectories(scope).mapNotNull { it.virtualFile.path.getParentJarPath() } } private fun String.getParentJarPath(): String? { val i = indexOf(jarSeparator) if (i != -1) { return substring(0, i) } return null } private fun determineCoreVersionMode(version: String) = if (DefaultArtifactVersion(version) > versionToCompareTo) CoroutineDebuggerMode.VERSION_1_3_8_AND_UP else CoroutineDebuggerMode.DISABLED private fun initializeCoroutineAgent(params: JavaParameters, jarPath: String): Boolean { val vmParametersList = params.vmParametersList ?: return false vmParametersList.add("-javaagent:$jarPath") // Fix for NoClassDefFoundError: kotlin/collections/AbstractMutableMap via CommandLineWrapper. // If classpathFile used in run configuration - kotlin-stdlib should be included in the -classpath if (params.isClasspathFile) { params.classPath.rootDirs.filter { it.path.contains(kotlinStdlibName) }.forEach { val path = when (val fs = it.fileSystem) { is ArchiveFileSystem -> fs.getLocalByEntry(it)?.path else -> it.path } it.putUserData(JdkUtil.AGENT_RUNTIME_CLASSPATH, path) } } return true } }
191
null
4372
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
4,703
intellij-community
Apache License 2.0
src/main/kotlin/io/emeraldpay/dshackle/upstream/ApiSource.kt
emeraldpay
191,297,773
false
null
/** * Copyright (c) 2020 EmeraldPay, Inc * Copyright (c) 2019 ETCDEV GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.emeraldpay.dshackle.upstream import org.reactivestreams.Publisher interface ApiSource : Publisher<Upstream> { /** * Total size of the available upstreams list, including the upstreams that may be not available (not matched) at the moment. * Because otherwise a matcher for "fresh upstreams" Matcher it may limit to the size of one, and a Quorum processor * may not work properly thinking that the whole ApiSource is based on a single upstream. */ val size: Int fun resolve() /** * Must be called before actual use, it spins off control flow of the API Source */ fun request(tries: Int) }
76
null
63
292
8076c81dd6e8213b107718764ec9e094b7653f04
1,295
dshackle
Apache License 2.0
android/app/src/main/java/com/algorand/android/utils/walletconnect/WCWalletConnectClient.kt
AllanMangeni
412,352,101
true
{"Kotlin": 1709104}
/* * Copyright 2019 Algorand, 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.algorand.android.utils.walletconnect import com.algorand.android.models.WalletConnectSession import com.algorand.android.models.WalletConnectSessionMeta import com.algorand.android.models.WalletConnectTransactionErrorResponse import com.algorand.android.utils.exception.InvalidWalletConnectUrlException import org.walletconnect.Session import org.walletconnect.Session.MethodCall.Custom import org.walletconnect.Session.MethodCall.SessionRequest import org.walletconnect.Session.MethodCall.SessionUpdate import org.walletconnect.impls.WCSession class WCWalletConnectClient( private val sessionBuilder: WalletConnectSessionBuilder, private val walletConnectMapper: WCWalletConnectMapper, private val sessionCachedDataHandler: WalletConnectSessionCachedDataHandler ) : WalletConnectClient { private var listener: WalletConnectClientListener? = null private val sessionCacheDataCallback = object : WalletConnectSessionCachedData.Callback { override fun onSessionRequest(sessionId: Long, requestId: Long, call: SessionRequest) { listener?.onSessionRequest(sessionId, requestId, getWalletConnectSession(sessionId) ?: return) } override fun onSessionUpdate(sessionId: Long, call: SessionUpdate) { if (!call.params.approved) { listener?.onSessionKilled(sessionId) } } override fun onCustomRequest(sessionId: Long, call: Custom) { listener?.onCustomRequest(sessionId, call.id, call.params ?: return) } override fun onSessionConnected(sessionId: Long) { listener?.onConnected(sessionId, getWalletConnectSession(sessionId)) } override fun onSessionDisconnected(sessionId: Long) { deleteSessionById(sessionId) listener?.onDisconnected(sessionId) } override fun onSessionApproved(sessionId: Long) { val walletConnectSession = getWalletConnectSession(sessionId) ?: return listener?.onSessionApproved(sessionId, walletConnectSession) } override fun onSessionError(sessionId: Long, error: Session.Status.Error) { listener?.onFailure(sessionId, error) } } override fun connect(uri: String) { val session = sessionBuilder.createSession(uri) ?: run { listener?.onFailure(-1, Session.Status.Error(InvalidWalletConnectUrlException)) return } connectToSession(session) } override fun connect(sessionId: Long, sessionMeta: WalletConnectSessionMeta) { if (sessionCachedDataHandler.isSessionCached(sessionMeta.topic)) return val session = sessionBuilder.createSession(sessionId, sessionMeta) ?: return connectToSession(session) } override fun setListener(listener: WalletConnectClientListener) { this.listener = listener } override fun approveSession(id: Long, accountAddress: String) { getSessionById(id)?.approve(listOf(accountAddress), ALGO_CHAIN_ID) } override fun rejectSession(id: Long) { getSessionById(id)?.reject() deleteSessionById(id) } override fun killSession(id: Long) { getSessionById(id)?.kill() deleteSessionById(id) listener?.onSessionKilled(id) } override fun disconnectFromSession(id: Long) { listener?.onDisconnected(id) deleteSessionById(id) } override fun rejectRequest(sessionId: Long, requestId: Long, errorResponse: WalletConnectTransactionErrorResponse) { getSessionById(sessionId)?.rejectRequest(requestId, errorResponse.responseCode, errorResponse.message) } override fun approveRequest(sessionId: Long, requestId: Long, payload: Any) { getSessionById(sessionId)?.approveRequest(requestId, payload) } private fun connectToSession(sessionCacheData: WalletConnectSessionCachedData) { with(sessionCacheData) { addCallback(sessionCacheDataCallback) session.offer() } sessionCachedDataHandler.addNewCachedData(sessionCacheData) } override fun getWalletConnectSession(sessionId: Long): WalletConnectSession? { val sessionCacheData = sessionCachedDataHandler.getCachedDataById(sessionId) ?: return null return walletConnectMapper.createWalletConnectSession(sessionCacheData) } private fun getSessionById(id: Long): WCSession? { return sessionCachedDataHandler.getSessionById(id) } private fun deleteSessionById(id: Long) { sessionCachedDataHandler.deleteCachedData(id) { it.removeCallback() } } companion object { const val CACHE_STORAGE_NAME = "session_store.json" } }
1
Kotlin
0
1
d47f08026fa797ea6474622ce5d1990666a241e9
5,318
algorand-wallet
Apache License 2.0
lib/src/main/kotlin/me/eugeniomarletti/kotlin/metadata/KotlinClassHeader.kt
Takhion
98,124,910
false
null
package me.eugeniomarletti.kotlin.metadata import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAnnotationNames.BYTECODE_VERSION_FIELD_NAME import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAnnotationNames.KIND_FIELD_NAME import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAnnotationNames.METADATA_DATA_FIELD_NAME import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAnnotationNames.METADATA_EXTRA_INT_FIELD_NAME import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAnnotationNames.METADATA_EXTRA_STRING_FIELD_NAME import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAnnotationNames.METADATA_PACKAGE_NAME_FIELD_NAME import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAnnotationNames.METADATA_STRINGS_FIELD_NAME import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAnnotationNames.METADATA_VERSION_FIELD_NAME import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmBytecodeBinaryVersion import me.eugeniomarletti.kotlin.metadata.shadow.load.kotlin.JvmMetadataVersion import me.eugeniomarletti.kotlin.metadata.shadow.load.kotlin.header.KotlinClassHeader import me.eugeniomarletti.kotlin.metadata.shadow.load.kotlin.header.KotlinClassHeader.Kind.CLASS import me.eugeniomarletti.kotlin.metadata.shadow.load.kotlin.header.KotlinClassHeader.Kind.FILE_FACADE import me.eugeniomarletti.kotlin.metadata.shadow.load.kotlin.header.KotlinClassHeader.Kind.MULTIFILE_CLASS_PART import me.eugeniomarletti.kotlin.metadata.shadow.load.kotlin.header.ReadKotlinClassHeaderAnnotationVisitor import javax.lang.model.element.AnnotationValue import javax.lang.model.element.Element import javax.lang.model.element.TypeElement /** * @see ReadKotlinClassHeaderAnnotationVisitor */ //TODO create a proper visitor internal val Element.kotlinClassHeader: KotlinClassHeader? get() { var metadataVersion: JvmMetadataVersion? = null var bytecodeVersion: JvmBytecodeBinaryVersion? = null var extraString: String? = null var extraInt = 0 var data: Array<String>? = null var strings: Array<String>? = null var incompatibleData: Array<String>? = null var headerKind: KotlinClassHeader.Kind? = null var packageName: String? = null for (annotation in annotationMirrors) { if ((annotation.annotationType.asElement() as TypeElement).qualifiedName.toString() != kotlinMetadataAnnotation) continue for ((element, _value) in annotation.elementValues) { val name = element.simpleName.toString().takeIf { it.isNotEmpty() } ?: continue val value: Any? = unwrapAnnotationValue(_value) when { KIND_FIELD_NAME == name && value is Int -> headerKind = KotlinClassHeader.Kind.getById(value) METADATA_VERSION_FIELD_NAME == name -> metadataVersion = JvmMetadataVersion(*@Suppress("UNCHECKED_CAST") (value as List<Int>).toIntArray()) BYTECODE_VERSION_FIELD_NAME == name -> bytecodeVersion = JvmBytecodeBinaryVersion(*@Suppress("UNCHECKED_CAST") (value as List<Int>).toIntArray()) METADATA_EXTRA_STRING_FIELD_NAME == name && value is String -> extraString = value METADATA_EXTRA_INT_FIELD_NAME == name && value is Int -> extraInt = value METADATA_DATA_FIELD_NAME == name -> data = @Suppress("UNCHECKED_CAST") (value as List<String>).toTypedArray() METADATA_STRINGS_FIELD_NAME == name -> strings = @Suppress("UNCHECKED_CAST") (value as List<String>).toTypedArray() METADATA_PACKAGE_NAME_FIELD_NAME == name && value is String -> packageName = value } } } if (headerKind == null) { return null } if (metadataVersion == null || !metadataVersion.isCompatible()) { incompatibleData = data data = null } else if ((headerKind == CLASS || headerKind == FILE_FACADE || headerKind == MULTIFILE_CLASS_PART) && data == null) { // This means that the annotation is found and its ABI version is compatible, but there's no "data" string array in it. // We tell the outside world that there's really no annotation at all return null } return KotlinClassHeader( headerKind, metadataVersion ?: JvmMetadataVersion.INVALID_VERSION, bytecodeVersion ?: JvmBytecodeBinaryVersion.INVALID_VERSION, data, incompatibleData, strings, extraString, extraInt, packageName ) } private tailrec fun unwrapAnnotationValue(value: Any?): Any? = when (value) { is AnnotationValue -> unwrapAnnotationValue(value.value) is List<*> -> value.map(::unwrapAnnotationValue) else -> value }
7
Kotlin
15
115
756ff8e82499d59481681860cfda5baa79c3af3c
5,109
kotlin-metadata
MIT License
ok-marketplace-be-business-logic/src/main/kotlin/ru/otus/otuskotlin/marketplace/business/logic/backend/pipelines/ProposalCreate.kt
otuskotlin
323,966,359
false
null
package ru.otus.otuskotlin.marketplace.business.logic.backend.pipelines import ru.otus.otuskotlin.marketplace.business.logic.backend.helpers.validation import ru.otus.otuskotlin.marketplace.business.logic.backend.operations.CompletePipeline import ru.otus.otuskotlin.marketplace.business.logic.backend.operations.stubs.DemandCreateStub import ru.otus.otuskotlin.marketplace.business.logic.backend.operations.InitializePipeline import ru.otus.otuskotlin.marketplace.business.logic.backend.operations.QuerySetWorkMode import ru.otus.otuskotlin.marketplace.business.logic.backend.operations.stubs.ProposalCreateStub import ru.otus.otuskotlin.marketplace.common.backend.context.MpBeContext import ru.otus.otuskotlin.marketplace.common.backend.context.MpBeContextStatus import ru.otus.otuskotlin.marketplace.common.backend.models.MpError import ru.otus.otuskotlin.marketplace.common.kmp.validation.validators.ValidatorStringNonEmpty import ru.otus.otuskotlin.marketplace.pipelines.kmp.IOperation import ru.otus.otuskotlin.marketplace.pipelines.kmp.operation import ru.otus.otuskotlin.marketplace.pipelines.kmp.pipeline object ProposalCreate : IOperation<MpBeContext> by pipeline({ execute(InitializePipeline) // Установка параметров контекста в зависимости от режима работы в запросе execute(QuerySetWorkMode) // Обработка стабового запроса execute(ProposalCreateStub) // Валидация параметров запроса validation { validate<String?> { validator(ValidatorStringNonEmpty(field = "title", message = "You must provide non-empty title for the proposal")) on { requestProposal.title } } validate<String?> { validator(ValidatorStringNonEmpty(field = "description", message = "You must provide non-empty description for the proposal")) on { requestProposal.description } } } // Добавление в репозитарий, ответ сохраняется в контексте operation { startIf { status == MpBeContextStatus.RUNNING } execute { try { proposalRepo.create(this) status = MpBeContextStatus.FINISHING } catch (t: Throwable) { status = MpBeContextStatus.FAILING errors.add( MpError( code = "proposal-repo-create-error", message = t.message?:"") ) } } } // Подготовка ответа execute(CompletePipeline) })
0
Kotlin
0
1
5f52fc91b3d71397cfabd02b5abb86a69d8567a1
2,507
202012-otuskotlin-marketplace
MIT License
src/main/kotlin/no/nav/familie/ba/sak/kjerne/beregning/TilkjentYtelseRepositoryUtil.kt
navikt
224,639,942
false
null
package no.nav.familie.ba.sak.kjerne.beregning import no.nav.familie.ba.sak.kjerne.beregning.domene.AndelTilkjentYtelse import no.nav.familie.ba.sak.kjerne.beregning.domene.TilkjentYtelse import no.nav.familie.ba.sak.kjerne.beregning.domene.TilkjentYtelseRepository import no.nav.familie.ba.sak.kjerne.eøs.differanseberegning.AndelTilkjentYtelsePraktiskLikhet.erIPraksisLik import no.nav.familie.ba.sak.kjerne.eøs.differanseberegning.AndelTilkjentYtelsePraktiskLikhet.inneholderIPraksis import no.nav.familie.ba.sak.kjerne.tidslinje.tidslinje /** * En litt risikabel funksjon, som benytter "funksjonell likhet" for å sjekke etter endringer på andel tilkjent ytelse */ fun TilkjentYtelseRepository.oppdaterTilkjentYtelse( tilkjentYtelse: TilkjentYtelse, oppdaterteAndeler: Collection<AndelTilkjentYtelse>, ): TilkjentYtelse { if (tilkjentYtelse.andelerTilkjentYtelse.erIPraksisLik(oppdaterteAndeler)) { return tilkjentYtelse } // Her er det viktig å beholde de originale andelene, som styres av JPA og har alt av innhold val skalBeholdes = tilkjentYtelse.andelerTilkjentYtelse .filter { oppdaterteAndeler.inneholderIPraksis(it) } val skalLeggesTil = oppdaterteAndeler .filter { !tilkjentYtelse.andelerTilkjentYtelse.inneholderIPraksis(it) } // Forsikring: Sjekk at det ikke oppstår eller forsvinner andeler når de sjekkes for likhet if (oppdaterteAndeler.size != (skalBeholdes.size + skalLeggesTil.size)) { throw IllegalStateException("Avvik mellom antall innsendte andeler og kalkulerte endringer") } tilkjentYtelse.andelerTilkjentYtelse.clear() tilkjentYtelse.andelerTilkjentYtelse.addAll(skalBeholdes + skalLeggesTil) // Ekstra forsikring: Bygger tidslinjene på nytt for å sjekke at det ikke er introdusert duplikater // Krasjer med Exception hvis det forekommer perioder per aktør og ytelsetype som overlapper // Bør fjernes hvis det ikke forekommer feil tilkjentYtelse.andelerTilkjentYtelse.sjekkForDuplikater() return this.saveAndFlush(tilkjentYtelse) } @Deprecated("Brukes som sikkerhetsnett for å sjekke at det ikke oppstår duplikater. Burde være unødvendig") private fun Iterable<AndelTilkjentYtelse>.sjekkForDuplikater() { try { // Det skal ikke være overlapp i andeler for en gitt ytelsestype og aktør this .groupBy { it.aktør.aktørId + it.type } .mapValues { (_, andeler) -> tidslinje { andeler.map { it.tilPeriode() } } } .values .forEach { it.perioder() } } catch (throwable: Throwable) { throw IllegalStateException( "Endring av andeler tilkjent ytelse i differanseberegning holder på å introdusere duplikater", throwable, ) } }
9
Kotlin
1
9
a66763dbde868b61b6f3deb004e4603ac7306854
2,794
familie-ba-sak
MIT License
src/main/kotlin/com/jetbrains/snakecharm/stringLanguage/lang/psi/SmkSLElement.kt
sraorao
318,587,733
true
{"Python": 1594814, "Kotlin": 546717, "Gherkin": 394724, "HTML": 35539, "Lex": 2408, "CSS": 2403, "Java": 1079, "Roff": 74, "Shell": 49}
package com.jetbrains.snakecharm.stringLanguage.lang.psi interface SmkSLElement
0
null
0
0
5bb077e39b55eb67eed39572fc198dd99c8eae53
81
snakecharm
MIT License