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
android/src/main/kotlin/tech/soit/quiet/service/MusicPlayerService.kt
boyan01
203,903,720
false
null
package tech.soit.quiet.service import android.content.Intent import android.os.Bundle import android.os.IBinder import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.session.MediaSessionCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.media.MediaBrowserServiceCompat import tech.soit.quiet.player.MusicPlayerSessionImpl import tech.soit.quiet.receiver.BecomingNoisyReceiverAdapter class MusicPlayerService : MediaBrowserServiceCompat(), LifecycleOwner { companion object { const val ACTION_MUSIC_PLAYER_SERVICE = "tech.soit.quiet.session.MusicSessionService" const val META_DATA_PLAYER_LAUNCH_ACTIVITY_ACTION = "tech.soit.quiet.session.LaunchActivityAction" } private val lifecycle = LifecycleRegistry(this) override fun getLifecycle(): Lifecycle = lifecycle private val playerSession by lazy { MusicPlayerSessionImpl(this) } private val mediaSession by lazy { return@lazy MediaSessionCompat(this, "MusicService").apply { isActive = true } } override fun onCreate() { super.onCreate() lifecycle.markState(Lifecycle.State.CREATED) sessionToken = mediaSession.sessionToken mediaSession.setCallback(MediaSessionCallbackAdapter(playerSession)) playerSession.addCallback(MusicSessionCallbackAdapter(mediaSession, this)) playerSession.addCallback(BecomingNoisyReceiverAdapter(this, playerSession)) val notificationAdapter = NotificationAdapter(this, playerSession, mediaSession) playerSession.addCallback(notificationAdapter) lifecycle.addObserver(notificationAdapter) } override fun onBind(intent: Intent?): IBinder? { if (intent?.action == ACTION_MUSIC_PLAYER_SERVICE) { return playerSession.asBinder() } return super.onBind(intent) } override fun onLoadChildren( parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>> ) { result.sendResult(mutableListOf()) } override fun onGetRoot( clientPackageName: String, clientUid: Int, rootHints: Bundle? ): BrowserRoot { return BrowserRoot("ROOT", null) } override fun onTaskRemoved(rootIntent: Intent?) { super.onTaskRemoved(rootIntent) if (playerSession.servicePlugin.config.pauseWhenTaskRemoved) { playerSession.stop() } } override fun onDestroy() { lifecycle.markState(Lifecycle.State.DESTROYED) mediaSession.isActive = false mediaSession.release() playerSession.destroy() super.onDestroy() } }
4
Kotlin
31
77
434e6fdc79a81d1a2a0877339ae29004c0f32734
2,768
flutter-music-player
MIT License
app/src/main/java/com/oxyethylene/easynote/ui/components/TextInputs.kt
PolyOxyethylene
738,671,054
false
{"Kotlin": 175216, "CSS": 229}
package com.oxyethylene.easynote.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextIndent import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.oxyethylene.easynote.ui.theme.SkyBlue /** * Created with IntelliJ IDEA. * @Project : EasyNoteDemo * @Package : com.oxyethylene.easynote.ui * @ClassName : CustomedComponents.java * @createTime : 2023/12/18 22:49 * @version : 1.0 * @author : Polyoxyethylene * @Description : */ /** * 自定义的文本输入框 * @param inputText 输入框的文本 * @param shape 输入框的形状 * @param hint 提示性信息 * @param modifier 设置输入框的长宽 */ @Composable fun InputText (modifier: Modifier, shape: Shape, containerColor: Color, inputText : MutableState<String>, hint : String) { BasicTextField( value = inputText.value, modifier = modifier, onValueChange = { inputText.value = it }, singleLine = true, textStyle = TextStyle(fontSize = 16.sp), decorationBox = { innerTextField -> Box { Surface( modifier = Modifier.fillMaxSize(), shape = shape ) { Row( modifier = Modifier.background(containerColor).padding(8.dp), verticalAlignment = Alignment.CenterVertically ) { Box(modifier = Modifier.padding(start = 16.dp, end = 4.dp)) { if (inputText.value.isEmpty()) Text(text = hint, color = Color(0x88000000), fontSize = 16.sp) innerTextField() } } } } } ) } /** * 文章内容编辑区域 * @param modifier 定制组件外观 * @param inputText 输入框的文本 * @param enable 是否支持输入,默认为 true * @param _onValueChange 输入框内容更新时执行的方法 */ @Composable fun TextArea (modifier: Modifier, inputText : MutableState<String>, enable : Boolean = true, _onValueChange : (String) -> Unit) { BasicTextField( value = inputText.value, modifier = modifier, onValueChange = _onValueChange, enabled = enable, textStyle = TextStyle( fontSize = 16.sp, color = Color.DarkGray, lineHeight = 28.sp, textAlign = TextAlign.Justify, textIndent = TextIndent(firstLine = 32.sp), ), cursorBrush = SolidColor(SkyBlue), decorationBox = { innerTextField-> Column ( modifier = Modifier.clip(RoundedCornerShape(16.dp)) ){ Surface( modifier = Modifier.fillMaxSize(), color = Color.White ) { Column ( modifier = Modifier.verticalScroll(rememberScrollState()) ) { Spacer(Modifier.size(10.dp)) Box(modifier = Modifier.fillMaxSize().padding(top = 6.dp, bottom = 6.dp, start = 14.dp, end = 14.dp)) { innerTextField() } } } } } ) }
0
Kotlin
0
0
1d5882c42b493fb2e88239641846de6674a7955f
4,321
EasyNote
Apache License 2.0
plot-api/src/commonMain/kotlin/org/jetbrains/letsPlot/geom/geom_histogram.kt
JetBrains
172,682,391
false
null
/* * Copyright (c) 2021. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.geom import org.jetbrains.letsPlot.Geom import org.jetbrains.letsPlot.Stat import org.jetbrains.letsPlot.intern.layer.LayerBase import org.jetbrains.letsPlot.intern.layer.PosOptions import org.jetbrains.letsPlot.intern.layer.SamplingOptions import org.jetbrains.letsPlot.intern.layer.StatOptions import org.jetbrains.letsPlot.intern.layer.geom.HistogramAesthetics import org.jetbrains.letsPlot.intern.layer.geom.HistogramMapping import org.jetbrains.letsPlot.intern.layer.stat.BinStatAesthetics import org.jetbrains.letsPlot.intern.layer.stat.BinStatParameters import org.jetbrains.letsPlot.pos.positionStack import org.jetbrains.letsPlot.tooltips.TooltipOptions @Suppress("ClassName") /** * Display a 1d distribution by dividing variable mapped to x axis into bins and counting the number of observations in each bin. * * ## Examples * * - [distributions.ipynb](https://nbviewer.jupyter.org/github/JetBrains/lets-plot-kotlin/blob/master/docs/examples/jupyter-notebooks/distributions.ipynb) * * @param data * The data to be displayed in this layer. If None, the default, the data * is inherited from the plot data as specified in the call to [letsPlot][org.jetbrains.letsPlot.letsPlot]. * @param stat * The statistical transformation to use on the data for this layer. Supported transformations: * "identity" (leaves the data unchanged), "count" (counts number of points with same x-axis coordinate), * "bin" (counts number of points with x-axis coordinate in the same bin), "smooth" (performs smoothing - * linear default). * Statistic types: [letsPlot][org.jetbrains.letsPlot.Stat]. * @param position * Position adjustment: Pos.identity, Pos.stack, etc. - see [letsPlot][org.jetbrains.letsPlot.Pos]. * @param tooltips result of the call to the layerTooltips() function. * Specifies appearance, style and content. * @param orientation Specifies the axis that the layer' stat and geom should run along. * Possible values: 'x' (default), 'y'. * @param x x-axis value (this values will produce cases or bins for bars). * @param y y-axis value (this value will be used to multiply the bar heights), setting y to '..density..' produces * normalized (density) histogram. * @param alpha transparency level of a layer * Understands numbers between 0 and 1. * @param color (colour) color of a geometry lines. * Can be continuous or discrete. For continuous value this will be a color gradient between two colors. * @param fill color of geometry filling. * @param size line width. * Defines bar line width. * @param mapping set of aesthetic mappings. * Aesthetic mappings describe the way that variables in the data are * mapped to plot "aesthetics". */ class geomHistogram( data: Map<*, *>? = null, stat: StatOptions = Stat.bin(), position: PosOptions = positionStack(), showLegend: Boolean = true, sampling: SamplingOptions? = null, tooltips: TooltipOptions? = null, orientation: String? = null, override val x: Number? = null, override val y: Number? = null, override val alpha: Number? = null, override val color: Any? = null, override val fill: Any? = null, override val size: Number? = null, override val weight: Any? = null, override val bins: Int? = null, override val binWidth: Number? = null, override val center: Number? = null, override val boundary: Number? = null, mapping: HistogramMapping.() -> Unit = {} ) : HistogramAesthetics, BinStatAesthetics, BinStatParameters, LayerBase( mapping = HistogramMapping().apply(mapping).seal(), data = data, geom = Geom.histogram(), stat = stat, position = position, showLegend = showLegend, sampling = sampling, tooltips = tooltips, orientation = orientation ) { override fun seal() = super<HistogramAesthetics>.seal() + super<BinStatAesthetics>.seal() + super<BinStatParameters>.seal() }
15
null
31
309
c94d1c2e751c2bcfd337de3706add9733e365efa
4,206
lets-plot-kotlin
MIT License
app/src/main/java/ua/polodarb/gmsflags/ui/screens/settingsScreen/resetSaved/ResetSavedScreen.kt
polodarb
624,518,043
false
{"Kotlin": 369647, "AIDL": 1483}
package ua.polodarb.gmsflags.ui.screens.settingsScreen.resetSaved import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.outlined.Info import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import org.koin.androidx.compose.koinViewModel import ua.polodarb.gmsflags.R import ua.polodarb.gmsflags.ui.screens.settingsScreen.SettingsViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun ResetSavedScreen( onBackPressed: () -> Unit ) { val viewModel = koinViewModel<SettingsViewModel>() val context = LocalContext.current val haptic = LocalHapticFeedback.current var showDialog by rememberSaveable { mutableStateOf(false) } var resetFlagsType by rememberSaveable { mutableStateOf(SettingsResetSavedType.NONE) } Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text(text = "Reset saved") }, navigationIcon = { IconButton(onClick = onBackPressed) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = "Localized description" ) } }, ) } ) { Column( modifier = Modifier .padding(top = it.calculateTopPadding()) .fillMaxSize(), verticalArrangement = Arrangement.SpaceBetween ) { SettingsResetFlagsHeader() Spacer(modifier = Modifier.height(16.dp)) SettingsResetFlagsButtons( onPackagesClick = { haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) resetFlagsType = SettingsResetSavedType.PACKAGES showDialog = true }, onFlagsClick = { haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) resetFlagsType = SettingsResetSavedType.FLAGS showDialog = true }, onResetAllClick = { haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) resetFlagsType = SettingsResetSavedType.ALL showDialog = true } ) } ConfirmResetFlagsDialog(showDialog = showDialog, onDismiss = { showDialog = false }) { showDialog = false haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) when (resetFlagsType) { SettingsResetSavedType.PACKAGES -> viewModel.deleteAllSavedPackages() SettingsResetSavedType.FLAGS -> viewModel.deleteAllSavedFlags() SettingsResetSavedType.ALL -> viewModel.deleteAllSavedFlagsAndPackages() SettingsResetSavedType.NONE -> {} } Toast.makeText(context, "Done!", Toast.LENGTH_SHORT).show() } } } @Composable fun SettingsResetFlagsHeader() { Column { Box( modifier = Modifier .fillMaxWidth() .padding(24.dp) .clip(RoundedCornerShape(24.dp)) .background(MaterialTheme.colorScheme.surfaceContainer), contentAlignment = Alignment.Center ) { Icon( painter = painterResource(id = R.drawable.ic_reset_saved), contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier .padding(36.dp) .size(112.dp) ) } Image( imageVector = Icons.Outlined.Info, contentDescription = null, colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onSurfaceVariant), modifier = Modifier.padding(start = 24.dp, bottom = 12.dp) ) Text( text = "In this section you can reset all packages and flags on the \"Saved\" screen that you have saved before.", style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, modifier = Modifier.padding(horizontal = 24.dp), color = MaterialTheme.colorScheme.onSurfaceVariant ) } } @Composable fun SettingsResetFlagsButtons( onPackagesClick: () -> Unit, onFlagsClick: () -> Unit, onResetAllClick: () -> Unit ) { Column( modifier = Modifier.padding(horizontal = 24.dp) ) { OutlinedButton( onClick = onPackagesClick, modifier = Modifier.fillMaxWidth() ) { Text(text = "Reset saved packages") } OutlinedButton( onClick = onFlagsClick, modifier = Modifier .fillMaxWidth() .padding(vertical = 12.dp) ) { Text(text = "Reset saved flags") } Button( onClick = onResetAllClick, modifier = Modifier .fillMaxWidth() .padding(bottom = 24.dp) ) { Text(text = "Reset all saved flags and packages") } } } @Composable fun ConfirmResetFlagsDialog( showDialog: Boolean, onDismiss: () -> Unit, onConfirmClick: () -> Unit ) { if (showDialog) { AlertDialog( onDismissRequest = onDismiss, icon = { Image( painter = painterResource(id = R.drawable.ic_force_stop), contentDescription = null, modifier = Modifier.size(36.dp), colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onSurface) ) }, title = { Text(text = "Confirm action") }, text = { Text( text = "All flags that you saved will be reset!", textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() ) }, confirmButton = { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { OutlinedButton( onClick = onDismiss ) { Text("Close") } Button( onClick = onConfirmClick ) { Text("Confirm") } } }, ) } } enum class SettingsResetSavedType { NONE, FLAGS, PACKAGES, ALL }
1
Kotlin
2
61
8353895480a0e368297cd9aeba0d46efe9d685ed
8,673
GMS-Flags
MIT License
kotlin/services/s3/src/test/kotlin/com/kotlin/s3/PresignTests.kt
awsdocs
66,023,605
false
null
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.kotlin.s3 import aws.sdk.kotlin.services.s3.S3Client import aws.sdk.kotlin.services.s3.model.GetObjectRequest import aws.smithy.kotlin.runtime.client.LogMode import aws.smithy.kotlin.runtime.content.decodeToString import aws.smithy.kotlin.runtime.time.Instant import aws.smithy.kotlin.runtime.time.toJvmInstant import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.MethodOrderer.OrderAnnotation import org.junit.jupiter.api.Order import org.junit.jupiter.api.TestMethodOrder import org.slf4j.LoggerFactory import java.time.temporal.ChronoUnit import java.util.UUID import kotlin.test.Test import kotlin.time.Duration.Companion.hours @TestMethodOrder(OrderAnnotation::class) class PresignTests { val logger = LoggerFactory.getLogger("com.kotlin.s3.PresignTests") private val s3 = S3Client { region = "us-east-1" logMode = LogMode.LogRequestWithBody + LogMode.LogResponseWithBody } private val bucketName = UUID.randomUUID().toString() private val keyName = "bar" @BeforeEach fun setUp() = runBlocking { setUp(s3, bucketName) } @AfterEach fun cleanUp() = runBlocking { cleanup(s3, bucketName) } @Test @Order(1) fun getObjectPresignTest() = runBlocking { val contents = "body" logger.info("start getObjectPresignTest") // Put an object into the bucket. putObject(s3, bucketName, keyName, contents) val returnedContent = getObjectPresigned(s3, bucketName, keyName) deleteObject(s3, bucketName, keyName) Assertions.assertEquals(contents, returnedContent) logger.info("getObjectPresigned returned the same content") } @Test @Order(2) fun putObjectPresignTest() = runBlocking { val contents = "Hello World" logger.info("start putObjectPresignTest") putObjectPresigned(s3, bucketName, keyName, contents) val returnedContent = s3.getObject( GetObjectRequest { bucket = bucketName key = keyName } ) { resp -> val respString = resp.body?.decodeToString() respString } deleteObject(s3, bucketName, keyName) Assertions.assertEquals(contents, returnedContent) logger.info("putObjectPresigned returned the same content") } @Test @Order(3) fun getObjectPresignMoreOptionsTest() = runBlocking { // The example under test sets a future signing date of 12 hours from now. // The signing date ends up as the 'X-Amz-Date' query parameter on the URL. val presignedRequest = getObjectPresignedMoreOptions(s3, bucketName, keyName) val myMap = presignedRequest.url.parameters.encodedParameters val stringDate = myMap["X-Amz-Date"]?.firstOrNull() println(stringDate) if (!stringDate.isNullOrEmpty()) { val signingDate = Instant.fromIso8601(stringDate.toString()) val aroundNow = signingDate.minus(12.hours) val aroundNowJvmInstant: java.time.Instant = aroundNow.toJvmInstant() val nowJvmInstant: java.time.Instant = Instant.now().toJvmInstant() val difference: Long = aroundNowJvmInstant.until(nowJvmInstant, ChronoUnit.MILLIS) logger.info(difference.toString()) // The difference between the signing date minus 12 hours and now should be very small. // Asserting here that the difference is less than 5 seconds. Assertions.assertTrue(difference < 5000) } } }
250
null
5614
9,502
3d8f94799b9c661cd7092e03d6673efc10720e52
3,809
aws-doc-sdk-examples
Apache License 2.0
server/src/main/kotlin/Application.kt
Domo3000
509,616,464
false
null
import data.CSS import data.index import data.styles import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.html.* import io.ktor.server.http.content.* import io.ktor.server.netty.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.websocket.* import kotlinx.coroutines.coroutineScope import kotlinx.css.* import kotlinx.html.* import utils.logError import kotlin.time.Duration.Companion.seconds import kotlin.time.toJavaDuration suspend fun main(): Unit = coroutineScope { /* with(Connect4) { launch(Dispatchers.IO) { while (true) { cleanUp() delay(10.minutes) } } */ embeddedServer(Netty, port = 8080) { with(environment) { install(StatusPages) { exception<Throwable> { call, cause -> logError(cause) call.respondText(text = "500: $cause.", status = HttpStatusCode.InternalServerError) } status(HttpStatusCode.NotFound) { call, code -> call.respondText(text = "Page Not Found", status = code) } } install(WebSockets) { pingPeriod = 15.seconds.toJavaDuration() timeout = 15.seconds.toJavaDuration() maxFrameSize = Long.MAX_VALUE masking = false } routing { //createConnect4Websocket() get("/health") { call.respondText("Healthy!") } get("/robots.txt") { call.respondText( """User-agent: * |Allow: /""".trimMargin() ) } get("/static/styles.css") { call.respondCss(CssBuilder::styles) } get("/{...}") { call.respondHtml(HttpStatusCode.OK, HTML::index) } static("/static") { resources("assets") } } } }.start(wait = true) } private suspend fun ApplicationCall.respondText(text: String) = respondText(text = text, status = HttpStatusCode.OK) /** * https://ktor.io/docs/css-dsl.html#serve_css */ private suspend inline fun ApplicationCall.respondCss(css: CSS) { this.respondText(CssBuilder().apply(css).toString(), ContentType.Text.CSS) }
0
Kotlin
0
0
c3ba4be6049cfd9ee2a3d07bd2ba6ee90ceb3360
2,603
Portfolio
MIT License
src/org/jetbrains/r/RBundle.kt
JetBrains
214,212,060
false
{"Kotlin": 2657533, "Java": 558927, "R": 37082, "Lex": 14307, "HTML": 10063, "Rez": 70, "Rebol": 47}
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.r import com.intellij.DynamicBundle import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey @NonNls private const val BUNDLE = "messages.RPluginBundle" object RBundle : DynamicBundle(BUNDLE) { @Nls fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params) }
2
Kotlin
13
62
9225567ed712f54d019ce5ab712016acdb6fc98e
562
Rplugin
Apache License 2.0
app/src/main/java/com/opsc/timesync/ui/addtimesheetentry/AddTimesheetEntryViewModel.kt
johanngeustyn
648,824,203
false
null
package com.opsc.timesync.ui.addtimesheetentry import Category import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.firestore.FirebaseFirestore class AddTimesheetEntryViewModel : ViewModel() { private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance() private var user: FirebaseUser = FirebaseAuth.getInstance().currentUser!! private val _categories = MutableLiveData<List<Category>>() val categories: LiveData<List<Category>> = _categories fun fetchCategories() { firestore.collection("categories") .whereEqualTo("user_id", user.uid) .get() .addOnSuccessListener { querySnapshot -> val categoriesList = mutableListOf<Category>() for (document in querySnapshot) { val categoryId = document.id val categoryName = document.getString("name") val category = Category(categoryId, categoryName!!) categoriesList.add(category) } _categories.value = categoriesList } .addOnFailureListener { // Handle the failure } } }
0
Kotlin
0
0
546f5783e318ac654319577f0d4f169a4e0ec078
1,373
TimeSync
MIT License
basic-kotlin/app/src/main/java/nl/gjalsem/basickotlinexample/viewmodel/MainViewModelFactory.kt
gjalsem
139,480,922
false
null
package nl.gjalsem.basickotlinexample.viewmodel import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.content.Context import com.android.volley.toolbox.ImageLoader import com.android.volley.toolbox.Volley import nl.gjalsem.basickotlinexample.model.BitmapCache import nl.gjalsem.basickotlinexample.model.RpcClient /** * Creates an instance of MainViewModel and all classes it depends on. */ class MainViewModelFactory(private val context: Context) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { val requestQueue = Volley.newRequestQueue(context) val rpcClient = RpcClient(requestQueue) val imageLoader = ImageLoader(requestQueue, BitmapCache()) return MainViewModel(rpcClient, imageLoader) as T } }
1
null
1
1
cca33f331d52a385bdd47426ef820f82d4d3ed0f
870
android-examples
Apache License 2.0
telnyx_rtc/src/main/java/com/telnyx/webrtc/sdk/model/SocketError.kt
team-telnyx
343,455,010
false
null
/* * Copyright © 2021 Telnyx LLC. All rights reserved. */ package com.telnyx.webrtc.sdk.model /** * Enum class to detail the error responses that the socket connection can receive * with the given [errorCode] * * @param errorCode is the Telnyx error code representation of the method, eg. Token_Error -> -32000 * * @property TOKEN_ERROR there was an issue with a token - either invalid or expired * @property CREDENTIAL_ERROR there was an issue with the credentials used - likely invalid. */ enum class SocketError(var errorCode: Int) { TOKEN_ERROR(-32000), CREDENTIAL_ERROR(-32001) }
8
null
1
9
a4646e5ccff9b82b4871be48bcdf189534880c49
605
telnyx-webrtc-android
MIT License
strava-api/src/test/kotlin/models/TokenResponseTest.kt
PtrTeixeira
80,689,783
false
null
package models import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule import com.github.ptrteixeira.strava.api.models.TokenResponse import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class TokenResponseTest { private val objectMapper = ObjectMapper().registerKotlinModule() @Test fun `it can deserialize token responses with state without athlete`() { val accessToken = "987654321234567898765432123456789" val state = "STRAVA" val json = """ { "token_type": "Bearer", "access_token": "$accessToken", "refresh_token": "1234567898765432112345678987654321", "expires_at": 1531378346, "state": "$state" } """.trimIndent() val tokenResponse = objectMapper.readValue(json, TokenResponse::class.java) assertThat(tokenResponse.athlete) .isNull() assertThat(tokenResponse.accessToken) .isEqualTo(accessToken) assertThat(tokenResponse.state) .isEqualTo(state) } @Test fun `it can deserialize token responses without state or athlete`() { val accessToken = "987654321234567898765432123456789" val json = """ { "token_type": "Bearer", "access_token": "$accessToken", "refresh_token": "1234567898765432112345678987654321", "expires_at": 1531378346 } """.trimIndent() val tokenResponse = objectMapper.readValue(json, TokenResponse::class.java) assertThat(tokenResponse.athlete) .isNull() assertThat(tokenResponse.accessToken) .isEqualTo(accessToken) } }
6
Kotlin
0
0
18b425b93c1eef5b824c695c7050e4ac69ae75ee
1,691
cookbook
MIT License
app/src/main/java/com/rakib/commitviewapp/repository/model/CommitModelItem.kt
rakibcse99
666,992,655
false
null
package com.rakib.commitviewapp.repository.model data class CommitModelItem( val author: Author, val comments_url: String, val commit: Commit, val committer: CommitterX, val html_url: String, val node_id: String, val parents: List<Parent>, val sha: String, val url: String )
0
Kotlin
0
0
8dd4edfe2bbe3524c5345602e9e4d1ff81d878d2
311
CommitViewApps
The Unlicense
app/src/main/java/com/rakib/commitviewapp/repository/model/CommitModelItem.kt
rakibcse99
666,992,655
false
null
package com.rakib.commitviewapp.repository.model data class CommitModelItem( val author: Author, val comments_url: String, val commit: Commit, val committer: CommitterX, val html_url: String, val node_id: String, val parents: List<Parent>, val sha: String, val url: String )
0
Kotlin
0
0
8dd4edfe2bbe3524c5345602e9e4d1ff81d878d2
311
CommitViewApps
The Unlicense
src/androidTest/java/com/astoev/cave/survey/test/service/data/OpensTopoExportTest.kt
lz1asl
13,239,867
false
null
package com.astoev.cave.survey.test.service.data import com.astoev.cave.survey.model.Option.UNIT_FEET import com.astoev.cave.survey.model.Option.UNIT_GRADS import com.astoev.cave.survey.test.helper.Common.goBack import com.astoev.cave.survey.test.helper.Data.dataScreen import com.astoev.cave.survey.test.helper.Data.opensTopo import com.astoev.cave.survey.test.helper.OpensTopo.exportCSV import com.astoev.cave.survey.test.helper.Survey.addCoordinate import com.astoev.cave.survey.test.helper.Survey.addLeg import com.astoev.cave.survey.test.helper.Survey.addLegMiddle import com.astoev.cave.survey.test.helper.Survey.addVector import com.astoev.cave.survey.test.helper.Survey.createAndOpenSurvey import com.astoev.cave.survey.test.helper.Survey.nextGallery import com.astoev.cave.survey.test.helper.Survey.openLegWithText import com.astoev.cave.survey.test.helper.Survey.saveLeg import com.astoev.cave.survey.test.helper.Survey.selectFirstSurveyLeg import com.astoev.cave.survey.test.helper.Survey.setLegData import org.junit.Test class OpensTopoExportTest : AbstractExportTest() { @Test fun opensTopoExportTest() { // create survey val surveyName = createAndOpenSurvey() // first test legs selectFirstSurveyLeg() setLegData(1f, 2f, null) openLegWithText("A1") addCoordinate(42.811522f, 23.378906f, 123, 5) addLeg(1.2f, 2.2f, 1.3f) addLeg(2.3f, 3.4f, 4.5f, 1.1f, 1.2f, 1.3f, 1.4f) // compare exportAndCompare(surveyName, "initial") // rest of the test data addLeg(5.5f, 4.4f, 5.5f, 2.1f, 2.2f, 2.3f, 2.4f) addLegMiddle(3.1f, 3.1f, 3.2f, 3.3f, 3.4f) addLeg(3.4f, 3.5f, 3.6f, 6.1f, 6.2f, 6.3f, 6.4f) openLegWithText("A5") addVector(1.1f, 1.2f, 1.3f) addVector(1.4f, 1.5f, 1.6f) addVector(1.7f, 1.8f, 1.9f) saveLeg() nextGallery() setLegData(4.4f, 4.5f, 4.6f, 0.1f, 0.2f, 0.3f, 0.4f) // compare exportAndCompare(surveyName, "full") } @Test fun opensTopoExportNonStandardUnitsTest() { // create survey with non default units val surveyName = createAndOpenSurvey(null, UNIT_FEET, UNIT_GRADS, UNIT_GRADS) // first test legs - data is the same selectFirstSurveyLeg() setLegData(1f, 2f, null) openLegWithText("A1") addCoordinate(42.811522f, 23.378906f, 123, 5) addLeg(1.2f, 2.2f, 1.3f) addLeg(2.3f, 3.4f, 4.5f, 1.1f, 1.2f, 1.3f, 1.4f) // compare exportAndCompare(surveyName, "initial_feet") } @Test fun opensTopoIntegration() { // create survey val surveyName = createAndOpenSurvey() // first test legs selectFirstSurveyLeg() setLegData(1f, 2f, null) addLeg(1.2f, 2.2f, 1.3f) addLeg(2.3f, 3.4f, 4.5f, 1.1f, 1.2f, 1.3f, 1.4f) // open OpensTopo UI dataScreen() opensTopo() // export from within OpensTopo exportCSV() // compare output compare(surveyName, "opensTopoExport", "csv") } private fun exportAndCompare(surveyName: String, expected: String) { dataScreen() opensTopo() compare(surveyName, expected) goBack() goBack() } private fun compare(projectName: String, expected: String) { compare(projectName, expected, "json") } private fun compare(projectName: String, expected: String, extension: String) { val expectedStream = findAsset("export/openstopo/$expected.$extension") val params = mapOf(PARAM_PROJECT_NAME to projectName) compareContents(expectedStream, params, projectName, ".$extension") } }
56
null
9
44
d8493663a76531c2833ac118e36751092eb48c48
3,742
CaveSurvey
MIT License
src/generated/kotlin/net/highteq/cylab/awssdk/dynamodb/kotlin/dsl/model/BackupSummaryDSL.kt
cylab
258,882,001
false
null
/* This file was generated from https://github.com/aws/aws-sdk-java-v2 by https://github.com/cylab/aws-kotlin-dsl-builder Like the original code, this file and project is licensed under Apache License Version 2.0 See LICENSE.txt for more info */ @file:Suppress("DEPRECATION", "NOTHING_TO_INLINE") package net.highteq.cylab.awssdk.dynamodb.kotlin.dsl.model import kotlin.DeprecationLevel.HIDDEN import kotlin.DeprecationLevel.WARNING import java.time.Instant import net.highteq.cylab.awssdk.dynamodb.kotlin.dsl.DynamodbDSL import net.highteq.cylab.awssdk.dynamodb.kotlin.dsl.DynamodbDSLMarker import software.amazon.awssdk.services.dynamodb.model.BackupStatus import software.amazon.awssdk.services.dynamodb.model.BackupSummary import software.amazon.awssdk.services.dynamodb.model.BackupType /** * Builds instances of type BackupSummary: * Contains details for the backup. */ @DynamodbDSLMarker inline class BackupSummaryDSL( @Deprecated("Usage of the builder field is not recommended. It might vanish in any new release!", level = WARNING) val builder: BackupSummary.Builder ){ @PublishedApi internal fun build(): BackupSummary = builder.build() /** * */ inline var backupArn: String? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.backupArn(value) } /** * */ inline var backupCreationDateTime: Instant? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.backupCreationDateTime(value) } /** * */ inline var backupExpiryDateTime: Instant? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.backupExpiryDateTime(value) } /** * */ inline var backupName: String? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.backupName(value) } /** * */ inline var backupSizeBytes: Long? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.backupSizeBytes(value) } /** * */ inline var backupStatus: BackupStatus? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.backupStatus(value) } /** * */ inline var backupType: BackupType? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.backupType(value) } /** * */ inline var tableArn: String? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.tableArn(value) } /** * */ inline var tableId: String? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.tableId(value) } /** * */ inline var tableName: String? @Deprecated("", level = HIDDEN) // Hide from Kotlin callers get() = throw UnsupportedOperationException() set(value) { builder.tableName(value) } /** * */ inline fun backupStatus(value: String?) { builder.backupStatus(value) } /** * */ inline fun backupType(value: String?) { builder.backupType(value) } } /** * Builds instances of type BackupSummary: * Contains details for the backup. */ inline fun backupSummary(dslBlock: BackupSummaryDSL.() -> Unit) = BackupSummaryDSL(BackupSummary.builder()).apply(dslBlock).build() /** * Builds instances of type BackupSummary: * Contains details for the backup. */ inline fun DynamodbDSL.Companion.backupSummary(dslBlock: BackupSummaryDSL.() -> Unit) = BackupSummaryDSL(BackupSummary.builder()).apply(dslBlock).build()
0
Kotlin
0
4
b3f40e013e78f363794f7671a43de88983280bb9
4,127
awssdk-dynamodb-kotlin-dsl
Apache License 2.0
src/main/kotlin/com/oocode/Almanac.kt
ivanmoore
725,978,325
false
{"Kotlin": 42155}
package com.oocode fun almanacFrom(input: String): Almanac { val lines = input.split("\n") val seedNumbers = lines[0].split(" ").drop(1).map { it.toLong() } val seeds = seedNumbers.chunked(2).map { val startNumber = it[0] val rangeSize = it[1] InputRange(startNumber, (startNumber + rangeSize) - 1) } val converters = mutableListOf<Converter>() var currentMappings = mutableListOf<Mapping>() lines.drop(1).forEach { line -> if (line.isEmpty()) { if (currentMappings.isNotEmpty()) converters.add(Converter(currentMappings)) currentMappings = mutableListOf() } else { val numbers = numbersFrom(line) if (numbers.isNotEmpty()) { currentMappings.add(Mapping(numbers[0], numbers[1], numbers[2])) } } } if (currentMappings.isNotEmpty()) converters.add(Converter(currentMappings)) return Almanac(seeds, ConverterChain(converters)) } data class InputRange(val startNumber: Long, val endNumber: Long) private fun numbersFrom(line: String) = Regex("(\\d+)") .findAll(line) .map { it.value.toLong() } .toList() class Almanac(private val seeds: List<InputRange>, private val converterChain: ConverterChain) { fun lowestLocationNumber() = seeds.flatMap { converterChain.convert(it) }.map { it.startNumber }.min() } data class Mapping( private val destinationRangeStart: Long, private val sourceRangeStart: Long, private val rangeLength: Long, ) { val sourceRange = LongRange(sourceRangeStart, sourceRangeStart + rangeLength - 1) fun find(sourceNumber: Long) = if (sourceRange.contains(sourceNumber)) destinationRangeStart + (sourceNumber - sourceRangeStart) else null } class Converter(private val mappings: List<Mapping>) { fun convert(sourceNumber: Long) = mappings.firstNotNullOfOrNull { it.find(sourceNumber) } ?: sourceNumber fun convert(inputRanges: Set<InputRange>): Set<InputRange> = inputRanges.flatMap { convert(it) }.toSet() fun convert(inputRange: InputRange): Set<InputRange> { val mappingsInOrder = overlappingMappings(inputRange) if (mappingsInOrder.isEmpty()) { return setOf(inputRange) } val firstMappingSourceRange = mappingsInOrder[0].sourceRange val firstMappingStart = firstMappingSourceRange.start if (inputRange.startNumber < firstMappingStart) { return setOf(inputRange.copy(endNumber = firstMappingStart - 1)) + convert(inputRange.copy(startNumber = firstMappingStart)) } if (inputRange.endNumber <= firstMappingSourceRange.endInclusive) { return mapped(inputRange) } return mapped(inputRange.copy(endNumber = firstMappingSourceRange.endInclusive)) + convert(inputRange.copy(startNumber = firstMappingSourceRange.endInclusive + 1)) } private fun mapped(inputRange: InputRange): Set<InputRange> = setOf(InputRange(convert(inputRange.startNumber), convert(inputRange.endNumber))) private fun overlappingMappings(inputRange: InputRange) = mappings .sortedBy { it.sourceRange.first } .filter { it.sourceRange.overlapsWith(inputRange) } } private fun LongRange.overlapsWith(inputRange: InputRange) = !(inputRange.endNumber < start || inputRange.startNumber > endInclusive) class ConverterChain(private val converters: List<Converter>) { fun convert(sourceNumber: InputRange) = converters.fold(setOf(sourceNumber), { accumulator, converter -> converter.convert(accumulator) }) }
0
Kotlin
0
0
36ab66daf1241a607682e7f7a736411d7faa6277
3,672
advent-of-code-2023
MIT License
exoplayer-codelab-00/src/main/java/com/example/exoplayer/App.kt
alifTC12
427,908,780
false
{"Kotlin": 52456}
package com.example.exoplayer import androidx.multidex.MultiDexApplication class App : MultiDexApplication() { override fun onCreate() { super.onCreate() } }
0
Kotlin
0
2
27c6b1b7d847305cea55723cdb77f9d946e4e3ff
177
ExoMotion
Apache License 2.0
sykepenger-model/src/main/kotlin/no/nav/helse/sykdomstidslinje/Sykdomshistorikk.kt
navikt
193,907,367
false
{"Kotlin": 7859394, "PLpgSQL": 2738, "Dockerfile": 168}
package no.nav.helse.sykdomstidslinje import java.time.LocalDateTime import java.util.UUID import no.nav.helse.hendelser.Periode import no.nav.helse.dto.SykdomshistorikkElementDto import no.nav.helse.dto.SykdomshistorikkDto import no.nav.helse.person.SykdomshistorikkVisitor import no.nav.helse.sykdomstidslinje.Sykdomshistorikk.Element.Companion.uhåndtertSykdomstidslinje import no.nav.helse.tournament.Dagturnering class Sykdomshistorikk private constructor( private val elementer: MutableList<Element> ) { internal constructor() : this(mutableListOf()) internal val size get() = elementer.size internal fun isEmpty() = elementer.isEmpty() internal fun harSykdom() = !isEmpty() && !elementer.first().isEmpty() internal fun sykdomstidslinje() = Element.sykdomstidslinje(elementer) internal fun håndter(hendelse: SykdomshistorikkHendelse): Sykdomstidslinje { val nyttElement = hendelse.element() val uhåndtertSykdomstidslinje = elementer.uhåndtertSykdomstidslinje(hendelse) ?: return sykdomstidslinje() elementer.add(0, nyttElement.merge(this, uhåndtertSykdomstidslinje)) return sykdomstidslinje() } internal fun fjernDager(perioder: List<Periode>) { if (perioder.isEmpty()) return if (isEmpty()) return val periode = sykdomstidslinje().periode() ?: return if (perioder.none { periode.overlapperMed(it) }) return elementer.add(0, Element.opprettReset(this, perioder)) } internal fun accept(visitor: SykdomshistorikkVisitor) { visitor.preVisitSykdomshistorikk(this) elementer.forEach { it.accept(visitor) } visitor.postVisitSykdomshistorikk(this) } class Element private constructor( private val id: UUID = UUID.randomUUID(), private val hendelseId: UUID? = null, private val tidsstempel: LocalDateTime = LocalDateTime.now(), private val hendelseSykdomstidslinje: Sykdomstidslinje = Sykdomstidslinje(), private val beregnetSykdomstidslinje: Sykdomstidslinje = Sykdomstidslinje(), ) : Comparable<Element> { internal fun merge(historikk: Sykdomshistorikk, uhåndtertSykdomstidslinje: Sykdomstidslinje): Element { val beregnetSykdomstidslinje = mergeTidslinje(historikk.elementer.firstOrNull(), uhåndtertSykdomstidslinje) return Element( id = this.id, hendelseId = this.hendelseId, tidsstempel = this.tidsstempel, hendelseSykdomstidslinje = uhåndtertSykdomstidslinje, beregnetSykdomstidslinje = beregnetSykdomstidslinje ) } private fun mergeTidslinje(forrige: Element?, uhåndtertSykdomstidslinje: Sykdomstidslinje) = forrige?.beregnetSykdomstidslinje?.merge(uhåndtertSykdomstidslinje, Dagturnering.TURNERING::beste) ?: uhåndtertSykdomstidslinje internal fun accept(visitor: SykdomshistorikkVisitor) { visitor.preVisitSykdomshistorikkElement(this, id, hendelseId, tidsstempel) visitor.preVisitHendelseSykdomstidslinje(hendelseSykdomstidslinje, hendelseId, tidsstempel) hendelseSykdomstidslinje.accept(visitor) visitor.postVisitHendelseSykdomstidslinje(hendelseSykdomstidslinje) visitor.preVisitBeregnetSykdomstidslinje(beregnetSykdomstidslinje) beregnetSykdomstidslinje.accept(visitor) visitor.postVisitBeregnetSykdomstidslinje(beregnetSykdomstidslinje) visitor.postVisitSykdomshistorikkElement(this, id, hendelseId, tidsstempel) } override fun compareTo(other: Element) = this.tidsstempel.compareTo(other.tidsstempel) override fun toString() = beregnetSykdomstidslinje.toString() internal fun harHåndtert(hendelse: SykdomshistorikkHendelse) = hendelseId == hendelse.element().hendelseId internal fun isEmpty(): Boolean = !beregnetSykdomstidslinje.iterator().hasNext() companion object { internal fun List<Element>.uhåndtertSykdomstidslinje(hendelse: SykdomshistorikkHendelse) : Sykdomstidslinje? { if (hendelse.element().hendelseSykdomstidslinje.periode() == null) return null // tom sykdomstidslinje val tidligere = filter { it.harHåndtert(hendelse) }.takeUnless { it.isEmpty() } ?: return hendelse.element().hendelseSykdomstidslinje // Første gang vi ser hendelsen val alleredeHåndtertSykdomstidslinje = tidligere.fold(Sykdomstidslinje()) { tidligereHåndtert, element -> tidligereHåndtert + element.hendelseSykdomstidslinje } val uhåndtertSykdomstidslinje = hendelse.element().hendelseSykdomstidslinje - alleredeHåndtertSykdomstidslinje if (uhåndtertSykdomstidslinje.periode() == null) return null // Tom sykdomstidslinje, ikke noe nytt return uhåndtertSykdomstidslinje.also { hendelse.info("Legger til bit nummer ${tidligere.size +1 } for ${it.periode()} i sykdomshistorikken") } } internal fun sykdomstidslinje(elementer: List<Element>) = elementer.first().beregnetSykdomstidslinje internal fun opprett( meldingsreferanseId: UUID, hendelseSykdomstidslinje: Sykdomstidslinje ): Element { return Element( hendelseId = meldingsreferanseId, hendelseSykdomstidslinje = hendelseSykdomstidslinje, ) } internal fun opprettReset( historikk: Sykdomshistorikk, perioder: List<Periode> ): Element { return Element(beregnetSykdomstidslinje = historikk.sykdomstidslinje().trim(perioder)) } internal fun gjenopprett(dto: SykdomshistorikkElementDto): Element { return Element( id = dto.id, hendelseId = dto.hendelseId, tidsstempel = dto.tidsstempel, hendelseSykdomstidslinje = Sykdomstidslinje.gjenopprett(dto.hendelseSykdomstidslinje), beregnetSykdomstidslinje = Sykdomstidslinje.gjenopprett(dto.beregnetSykdomstidslinje) ) } } internal fun dto() = SykdomshistorikkElementDto( id = id, hendelseId = hendelseId, tidsstempel = tidsstempel, hendelseSykdomstidslinje = hendelseSykdomstidslinje.dto(), beregnetSykdomstidslinje = beregnetSykdomstidslinje.dto(), ) } internal fun dto() = SykdomshistorikkDto( elementer = elementer.map { it.dto() } ) internal companion object { internal fun gjenopprett(dto: SykdomshistorikkDto): Sykdomshistorikk { return Sykdomshistorikk( elementer = dto.elementer.map { Element.gjenopprett(it) }.toMutableList() ) } } }
2
Kotlin
7
3
fb626aafa84da2fbb12ebdb9cc04c8c237fa4916
7,007
helse-spleis
MIT License
dagger-basic/src/main/java/com/jintin/dagger/HoneyLemonadeComponent.kt
Jintin
314,076,200
false
null
package com.jintin.dagger import dagger.Component @Component interface HoneyLemonadeComponent { // Don't need this anymore // fun getHoneyLemonade(): HoneyLemonade fun inject(mainActivity: MainActivity) }
0
Kotlin
0
0
88756ae3772640017772db3e90687ce65829fb3e
219
DaggerSample
MIT License
src/org/jetbrains/r/skeleton/psi/RSkeletonAssignmentStatement.kt
JetBrains
214,212,060
false
null
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.r.skeleton.psi import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.stubs.StubElement import com.intellij.util.IncorrectOperationException import org.jetbrains.r.RBundle import org.jetbrains.r.classes.s4.methods.RS4MethodsUtil.associatedS4MethodInfo import org.jetbrains.r.classes.s4.methods.RS4RawMethodInfo import org.jetbrains.r.console.RConsoleManager import org.jetbrains.r.console.RConsoleView import org.jetbrains.r.interpreter.RInterpreterManager import org.jetbrains.r.packages.LibrarySummary.RLibrarySymbol.Type import org.jetbrains.r.packages.RSkeletonUtil import org.jetbrains.r.psi.RElementFactory import org.jetbrains.r.psi.RPomTarget import org.jetbrains.r.psi.api.RAssignmentStatement import org.jetbrains.r.psi.api.RExpression import org.jetbrains.r.psi.api.RFunctionExpression import org.jetbrains.r.psi.references.RReferenceBase import org.jetbrains.r.refactoring.RNamesValidator import org.jetbrains.r.rinterop.RInteropTerminated import org.jetbrains.r.rinterop.RReference import org.jetbrains.r.rinterop.RValueError import org.jetbrains.r.rinterop.RVar class RSkeletonAssignmentStatement(private val myStub: RSkeletonAssignmentStub) : RSkeletonBase(), RAssignmentStatement { override fun getMirror() = null override fun getParent(): PsiElement = myStub.getParentStub().getPsi() override fun setName(name: String): PsiElement { throw IncorrectOperationException("Operation not supported in: $javaClass") } override fun getStub(): RSkeletonAssignmentStub = myStub override fun getElementType(): IStubElementType<out StubElement<*>, *> = stub.stubType override fun isLeft(): Boolean = true override fun isRight(): Boolean = !isLeft override fun isEqual(): Boolean = false override fun isClosureAssignment(): Boolean = false override fun getAssignedValue(): RExpression? = null override fun getAssignee(): RExpression? = null override fun getName(): String = myStub.name override fun getNameIdentifier(): PsiNamedElement? = null override fun isFunctionDeclaration(): Boolean = myStub.isFunctionDeclaration override fun isPrimitiveFunctionDeclaration(): Boolean = myStub.isPrimitiveFunctionDeclaration override fun getFunctionParameters(): String = if (this.isFunctionDeclaration()) "(" + myStub.parameters + ")" else "" private val parameterNameListValue: List<String> by lazy l@{ if (!isFunctionDeclaration()) return@l emptyList<String>() return@l (RElementFactory.createRPsiElementFromText(project, "function $functionParameters") as? RFunctionExpression) ?.parameterList?.parameterList?.map{ it.name } ?: emptyList<String>() } override fun getParameterNameList(): List<String> { return parameterNameListValue } override fun canNavigate(): Boolean { return super<RSkeletonBase>.canNavigate() && RInterpreterManager.getInstance(project).hasInterpreter() } override fun getText(): String { return name + functionParameters } override fun getReference(): RReferenceBase<*>? { return null } override fun navigate(requestFocus: Boolean) { RConsoleManager.getInstance(project).runAsync { console -> val createPsiElementByRValue = RPomTarget.createPsiElementByRValue(createRVar(console)) createPsiElementByRValue.navigate(requestFocus) } } internal fun createRVar(consoleView: RConsoleView): RVar { val (packageName, _) = RSkeletonUtil.skeletonFileToRPackage(containingFile) ?: throw IllegalStateException("bad filename") val accessOperator = if (stub.exported) "::" else ":::" val name = RNamesValidator.quoteIfNeeded(name) val expressionRef = RReference.expressionRef( if (stub.type == Type.S4METHOD) { val types = (associatedS4MethodInfo as RS4RawMethodInfo).parameters.joinToString(", ") { "'${it.type}'" } "methods::selectMethod('$name', signature = c($types))" } else { "$packageName$accessOperator$name" }, consoleView.rInterop ) val rValue = try { expressionRef.getValueInfo() } catch (e: RInteropTerminated) { RValueError(RBundle.message("rinterop.terminated")) } return RVar(name, expressionRef, rValue) } }
2
null
13
62
8b4f3aac10693cbfb5841f0afff46338bffbc50e
4,436
Rplugin
Apache License 2.0
velocity/src/main/kotlin/kingmc/platform/velocity/impl/extension/VelocityExtensionDispatcherImpl.kt
Kingsthere
599,960,106
false
null
package kingmc.platform.bukkit.impl.extension import kingmc.common.OpenAPI import kingmc.common.application.* import kingmc.common.context.process.afterProcess import kingmc.common.context.process.processBeans import kingmc.common.logging.error import kingmc.common.logging.slf4j.Slf4jLoggerManager import kingmc.common.logging.slf4j.Slf4jLoggerWrapper import kingmc.common.logging.warn import kingmc.common.structure.classloader.ExtensionClassLoader import kingmc.platform.ExperimentalPlatformApi import kingmc.platform.bukkit.impl.driver.BukkitPlatformDriverImpl import kingmc.platform.extension.* import kingmc.platform.logging.infoColored import kingmc.util.Lifecycle import kotlinx.coroutines.* import net.kyori.adventure.text.logger.slf4j.ComponentLogger import java.io.File import java.util.function.Consumer /** * Bukkit [ExtensionDispatcher] implementation * * @since 0.0.8 * @author kingsthere */ class BukkitExtensionDispatcherImpl(val driver: BukkitPlatformDriverImpl) : AbstractExtensionDispatcher(), ExtensionDispatcher { lateinit var extensionSourceDirectory: File lateinit var extractedExtensions: List<ExtensionClassSource> override lateinit var dispatchedExtensions: MutableList<ExtensionData> /** * Validate an extension file is valid for this `ExtensionDispatcher` to load */ fun validateExtension(extension: File): Boolean { // Check if the extension file is a valid // extension that available to install return extension.extension == "jar" } /** * Try to extract extensions from a file * * @param extensionFile file to extract extensions from * @return the class loader to load classes for extension extracted from the file */ fun recognizeExtensionFromJarFile(extensionFile: File): ExtensionClassSource? { infoColored("<grey>Recognizing extension(s) from $extensionFile...</grey>") return try { val classSource = ExtensionClassSource( file = extensionFile, extensionClassLoader = ExtensionClassLoader(extensionFile, OpenAPI.classLoader()!!).apply { addToClassloaders() }, parentFormatContext = driver.formatContext, properties = application.properties ) classSource } catch (e: ClassNotFoundException) { error(msg = "Unable to load extension (Is it up to date or missing dependencies?)", throwable = e) null } catch (e: Exception) { error(msg = "Unable to load extension", throwable = e) null } } /** * Load maven dependencies for [extractedExtensions] */ suspend fun loadExtensionMavenDependencies() = withContext(Dispatchers.IO) { extractedExtensions.forEach { extensionSource -> launch { extensionSource.loadMavenDependencies(driver.dependencyDispatcher, setOf(driver.mavenRepository)) } } } fun loadExtension(source: ExtensionClassSource, lifecycle: Lifecycle<Runnable>): List<ExtensionData> { try { val extensionLoggers = Slf4jLoggerManager(Slf4jLoggerWrapper(ComponentLogger.logger(source.extensions.first().displayName))) val extensionEnvironment = ExtensionEnvironment(source.classLoader) val extensionDefinition = source.extensions.first() val extensionContext = ExtensionContextImpl(properties = driver.properties, name = extensionDefinition.id, extension = extensionDefinition) val extensionContextInitializer = ExtensionContextInitializer(extensionContext).apply { addSource(source) addParent(driver.application.context) } (0..5).forEach { index -> lifecycle.insertPlan(index) { try { extensionContext.processBeans(index) } catch (e: Exception) { e.printStackTrace() } } } (0..5).forEach { index -> lifecycle.insertPlan(index) { try { extensionContext.afterProcess(index) } catch (e: Exception) { e.printStackTrace() } } } val application = ExtensionApplicationImpl(driver.platform, extensionContext, extensionEnvironment, source, extensionLoggers) extensionContext.application = application val returns = mutableListOf<ExtensionData>() source.extensions.forEach { // Create data directory for extension File("$extensionSourceDirectory/${it.id}").mkdir() val extensionData = ExtensionData(it, extensionContext, extensionContextInitializer, application, source) returns.add(extensionData) } // Load extension lifecycle for (index in 0..4) { lifecycle.insertPlan(index) { extensionContext.lifecycle().next() } } source.extensions.forEach { withApplication(application) { infoColored(StringBuilder().apply { append("<gradient:aqua:light_purple>Extension ${it.displayName}(${it.id}) v. ${it.tag}") if (it.description.contributors.isNotEmpty()) { append(" by ${it.description.contributors.joinToString(", ")}") } append(" has been loaded successfully</gradient>") }.toString()) if (it.description.website != "https://www.example.com/") { infoColored("<dark_grey>Check the website of this extension <blue>${it.description.website}</blue> for more information") } } } return returns } catch (e: Exception) { error(msg = "Unable to load recognized extensions from $source", throwable = e) return emptyList() } } fun solveExtensionDependencies(extensions: List<ExtensionData>): ExtensionLoadingRoutes { return buildList { val firsts = mutableListOf<ExtensionLoadingRoute>() val callbacks = mutableMapOf<ExtensionData, Consumer<ExtensionLoadingRoute>>() fun findExtensionLoadingRoute(extension: ExtensionData, parent: ExtensionLoadingRoute): ExtensionLoadingRoute? { if (parent.extension == extension) { return parent } for (nextRoute in parent.next) { findExtensionLoadingRoute(extension, nextRoute)?.let { return it } } return null } fun findExtensionLoadingRoute(extension: ExtensionData): ExtensionLoadingRoute? { firsts.forEach { findExtensionLoadingRoute(extension, it)?.let { found -> return found } } return null } fun findOrCallbackExtensionLoadingRoute(extension: ExtensionData, callback: (ExtensionLoadingRoute) -> Unit) { findExtensionLoadingRoute(extension)?.let { callback.invoke(it) return } callbacks.put(extension, callback) } extensions.forEach { extension -> // Get extension by the dependency name val dependencies = extension.definition.dependencies if (dependencies.isNotEmpty()) { for (dependency in extension.definition.dependencies) { val dependencyExtension = extensions.find { it.definition.id == dependency.id } if (!dependency.optional) { dependencyExtension ?: warn("Disable extension ${extension.definition.id} because the required dependencies of this plugin is missing (${dependency.id})") } dependencyExtension?.let { findOrCallbackExtensionLoadingRoute(it) { parentRoute -> val newedRoute = ExtensionLoadingRoute(extension, mutableListOf()) parentRoute.next.add(newedRoute) callbacks.remove(extension)?.accept(newedRoute) extension.contextInitializer.addParent(it.context) } } } } else { val new = ExtensionLoadingRoute(extension, mutableListOf()) firsts.add(new) callbacks.remove(extension)?.accept(new) } } addAll(firsts) } } @WithApplication suspend fun loadExtensionsFromDirectory(directory: File, lifecycle: Lifecycle<Runnable>) = coroutineScope { val application = currentApplication() extensionSourceDirectory = directory val loadingExtensions = mutableListOf<ExtensionData>() fun finishLoadExtensionRecurves(extensionLoadingRoute: ExtensionLoadingRoute) { extensionLoadingRoute.extension.contextInitializer() extensionLoadingRoute.next.forEach { finishLoadExtensionRecurves(it) } } fun finishLoadExtensionsRecurves(extensionLoadingRoutes: ExtensionLoadingRoutes) { extensionLoadingRoutes.forEach { finishLoadExtensionRecurves(it) } } // Load extension classes val scope = CoroutineScope(Dispatchers.IO) extractedExtensions = (directory.listFiles()?.map { file -> scope.async { return@async withApplicationSuspend(application) { if (validateExtension(file)) { try { recognizeExtensionFromJarFile(file)?.let { source -> source.loadExtensionDefinitions() source.loadProperties() source.loadFormatContext() return@withApplicationSuspend source } } catch (e: Exception) { error(msg = "Unable to recognize extension for file $file", throwable = e) } } null } } } ?: emptyList()).mapNotNull { it.await() } loadExtensionMavenDependencies() // Traverse the extensions in the extension // directory and load if the file is a valid extension // Make dirs if the direction is not exists extractedExtensions.map { launch { withApplicationSuspend(application) { try { val extension = loadExtension(it, lifecycle) extension.forEach { ex -> infoColored("<grey>Successfully load extension ${ex.definition.displayName} from ${ex.source}") } loadingExtensions.addAll(extension) } catch (e: Exception) { error(msg = "Unable to load extension from $it", throwable = e) } } } }.joinAll() finishLoadExtensionsRecurves(solveExtensionDependencies(loadingExtensions)) dispatchedExtensions = loadingExtensions } @WithApplication override fun disableExtension(extension: ExtensionData) { infoColored("<grey>Disabling extension ${extension.definition.id}(${extension.definition.displayName})...") extension.context.lifecycle().next() extension.contextInitializer.dispose() extension.application.shutdown() val classLoader = extension.source.extensionClassLoader classLoader.close() super.disableExtension(extension) } @WithApplication fun disableExtensions() { val disablingExtensions = this.dispatchedExtensions.toList() disablingExtensions.forEach { disableExtension(it) } } @WithApplication @ExperimentalPlatformApi override fun reload() { disableExtensions() val reloadLifecycle = Lifecycle.create<Runnable>() runBlocking { loadExtensionsFromDirectory(extensionSourceDirectory, reloadLifecycle) reloadLifecycle.jump(4) } } @WithApplication @ExperimentalPlatformApi override fun reload(extension: ExtensionData) { disableExtension(extension) val reloadLifecycle = Lifecycle.create<Runnable>() loadExtension(extension.source, reloadLifecycle) reloadLifecycle.jump(4) } }
0
Kotlin
0
1
6c325cbe550bcebc70f3071564e63459c2592f6b
13,226
kingmc-platform
MIT License
app/src/main/java/com/example/booklibrary/splashscreen/onboarding/screen/SecondScreen.kt
NoBody313
573,783,064
false
{"Kotlin": 37355}
package com.example.booklibrary.splashscreen.onboarding.screen import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.Fragment import androidx.viewpager2.widget.ViewPager2 import com.example.booklibrary.R class SecondScreen : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_second_screen, container, false) val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager) // Next button val nextButton: Button = view.findViewById(R.id.btn_next) nextButton.setOnClickListener { viewPager?.currentItem = 2 } return view } }
0
Kotlin
0
2
113e96b6045aaac927bc0b7e1917603409c04550
915
Book_Library
MIT License
clef-workflow-api/clef-workflow-api-factory/clef-workflow-api-factory-element/src/main/java/io/arkitik/clef/workflow/api/usecase/factory/element/request/ExecuteActionRequest.kt
arkitik
443,436,455
false
{"Kotlin": 433170, "Shell": 268, "Dockerfile": 244}
package io.arkitik.clef.workflow.api.usecase.factory.element.request import io.arkitik.radix.develop.usecase.model.UseCaseRequest /** * Created By [**<NAME> **](https://www.linkedin.com/in/iloom/)<br></br> * Created At **19**, **Thu Mar, 2020** * Project **clef-workflow** [arkitik.IO](https://arkitik.io/)<br></br> */ data class ExecuteActionRequest( val element: ElementByKeyRequest, val action: ElementByKeyRequest, ) : UseCaseRequest
0
Kotlin
0
0
785e1b4ee583b6a6e3ea01e656eecd8365f171ef
452
clef-workflow
Apache License 2.0
web/src/main/kotlin/world/phantasmal/web/viewer/stores/ViewerStore.kt
DaanVandenBosch
189,066,992
false
null
package world.phantasmal.web.viewer.stores import kotlinx.coroutines.launch import mu.KotlinLogging import world.phantasmal.core.enumValueOfOrNull import world.phantasmal.psolib.fileFormats.AreaGeometry import world.phantasmal.psolib.fileFormats.CollisionGeometry import world.phantasmal.psolib.fileFormats.ninja.NinjaObject import world.phantasmal.psolib.fileFormats.ninja.NjMotion import world.phantasmal.psolib.fileFormats.ninja.NjObject import world.phantasmal.psolib.fileFormats.ninja.XvrTexture import world.phantasmal.observable.cell.Cell import world.phantasmal.observable.cell.and import world.phantasmal.observable.cell.list.ListCell import world.phantasmal.observable.cell.list.mutableListCell import world.phantasmal.observable.cell.map import world.phantasmal.observable.cell.mutableCell import world.phantasmal.observable.change import world.phantasmal.web.core.PwToolType import world.phantasmal.web.core.rendering.conversion.PSO_FRAME_RATE import world.phantasmal.web.core.stores.UiStore import world.phantasmal.web.shared.dto.SectionId import world.phantasmal.web.viewer.ViewerUrls import world.phantasmal.web.viewer.loading.AnimationAssetLoader import world.phantasmal.web.viewer.loading.CharacterClassAssetLoader import world.phantasmal.web.viewer.models.AnimationModel import world.phantasmal.web.viewer.models.CharacterClass import world.phantasmal.webui.stores.Store private val logger = KotlinLogging.logger {} sealed class NinjaGeometry { class Object(val obj: NinjaObject<*, *>) : NinjaGeometry() class Render(val geometry: AreaGeometry) : NinjaGeometry() class Collision(val geometry: CollisionGeometry) : NinjaGeometry() } class ViewerStore( private val characterClassAssetLoader: CharacterClassAssetLoader, private val animationAssetLoader: AnimationAssetLoader, uiStore: UiStore, ) : Store() { // Ninja concepts. private val _currentNinjaGeometry = mutableCell<NinjaGeometry?>(null) private val _currentTextures = mutableListCell<XvrTexture?>() private val _currentNinjaMotion = mutableCell<NjMotion?>(null) // High-level concepts. private val _currentCharacterClass = mutableCell<CharacterClass?>(CharacterClass.VALUES.random()) private val _currentSectionId = mutableCell(SectionId.VALUES.random()) private val _currentBody = mutableCell((1.._currentCharacterClass.value!!.bodyStyleCount).random()) private val _currentAnimation = mutableCell<AnimationModel?>(null) // Settings. private val _applyTextures = mutableCell(true) private val _showSkeleton = mutableCell(false) private val _animationPlaying = mutableCell(true) private val _frameRate = mutableCell(PSO_FRAME_RATE) private val _frame = mutableCell(0) // Ninja concepts. val currentNinjaGeometry: Cell<NinjaGeometry?> = _currentNinjaGeometry val currentTextures: ListCell<XvrTexture?> = _currentTextures val currentNinjaMotion: Cell<NjMotion?> = _currentNinjaMotion // High-level concepts. val currentCharacterClass: Cell<CharacterClass?> = _currentCharacterClass val currentSectionId: Cell<SectionId> = _currentSectionId val currentBody: Cell<Int> = _currentBody val animations: List<AnimationModel> = (0 until 572).map { AnimationModel( "Animation ${it + 1}", "/player/animation/animation_${it.toString().padStart(3, '0')}.njm", ) } val currentAnimation: Cell<AnimationModel?> = _currentAnimation // Settings. val applyTexturesEnabled: Cell<Boolean> = _currentNinjaGeometry.map { it == null || it !is NinjaGeometry.Collision } val applyTextures: Cell<Boolean> = applyTexturesEnabled and _applyTextures val showSkeletonEnabled: Cell<Boolean> = _currentNinjaGeometry.map { it is NinjaGeometry.Object && it.obj is NjObject } val showSkeleton: Cell<Boolean> = showSkeletonEnabled and _showSkeleton val animationPlaying: Cell<Boolean> = _animationPlaying val frameRate: Cell<Int> = _frameRate val frame: Cell<Int> = _frame init { for (path in listOf(ViewerUrls.mesh, ViewerUrls.texture)) { addDisposables( uiStore.registerParameter( PwToolType.Viewer, path, MODEL_PARAM, setInitialValue = { initialValue -> if (uiStore.path.value.startsWith(path)) { CharacterClass.VALUES.find { it.slug == initialValue }?.let { _currentCharacterClass.value = it } } }, value = currentCharacterClass.map { it?.slug }, onChange = { newValue -> scope.launch { setCurrentCharacterClass( CharacterClass.VALUES.find { it.slug == newValue }, ) } }, ), uiStore.registerParameter( PwToolType.Viewer, path, SECTION_ID_PARAM, setInitialValue = { initialValue -> if (uiStore.path.value.startsWith(path)) { initialValue?.let { enumValueOfOrNull<SectionId>(it) }?.let { _currentSectionId.value = it } } }, value = currentSectionId.map { it.name }, onChange = { newValue -> scope.launch { setCurrentSectionId( newValue?.let { enumValueOfOrNull<SectionId>(it) } ?: SectionId.VALUES.random() ) } }, ), uiStore.registerParameter( PwToolType.Viewer, path, BODY_PARAM, setInitialValue = { initialValue -> if (uiStore.path.value.startsWith(path)) { val maxBody = _currentCharacterClass.value?.bodyStyleCount ?: 1 initialValue?.toIntOrNull()?.takeIf { it <= maxBody }?.let { _currentBody.value = it - 1 } } }, value = currentBody.map { (it + 1).toString() }, onChange = { newValue -> scope.launch { setCurrentBody((newValue?.toIntOrNull() ?: 1) - 1) } }, ), ) } scope.launch { loadCharacterClassNinjaObject(clearAnimation = true) } } fun setCurrentNinjaGeometry(geometry: NinjaGeometry?) { change { if (_currentCharacterClass.value != null) { _currentCharacterClass.value = null _currentTextures.clear() } _currentAnimation.value = null _currentNinjaMotion.value = null _currentNinjaGeometry.value = geometry } } fun setCurrentTextures(textures: List<XvrTexture>) { _currentTextures.replaceAll(textures) } suspend fun setCurrentCharacterClass(char: CharacterClass?) { val clearAnimation = _currentCharacterClass.value == null _currentCharacterClass.value = char if (char != null && _currentBody.value >= char.bodyStyleCount) { _currentBody.value = char.bodyStyleCount - 1 } loadCharacterClassNinjaObject(clearAnimation) } suspend fun setCurrentSectionId(sectionId: SectionId) { _currentSectionId.value = sectionId loadCharacterClassNinjaObject(clearAnimation = false) } suspend fun setCurrentBody(body: Int) { _currentBody.value = body loadCharacterClassNinjaObject(clearAnimation = false) } fun setCurrentNinjaMotion(njm: NjMotion) { change { _currentNinjaMotion.value = njm _animationPlaying.value = true } } suspend fun setCurrentAnimation(animation: AnimationModel?) { _currentAnimation.value = animation if (animation == null) { _currentNinjaMotion.value = null } else { loadAnimation(animation) } } fun setApplyTextures(apply: Boolean) { _applyTextures.value = apply } fun setShowSkeleton(show: Boolean) { _showSkeleton.value = show } fun setAnimationPlaying(playing: Boolean) { _animationPlaying.value = playing } fun setFrameRate(frameRate: Int) { _frameRate.value = frameRate } fun setFrame(frame: Int) { val maxFrame = currentNinjaMotion.value?.frameCount ?: Int.MAX_VALUE _frame.value = when { frame > maxFrame -> 1 frame < 1 -> maxFrame else -> frame } } private suspend fun loadCharacterClassNinjaObject(clearAnimation: Boolean) { val char = currentCharacterClass.value ?: return try { val sectionId = currentSectionId.value val body = currentBody.value val ninjaObject = characterClassAssetLoader.loadNinjaObject(char) val textures = characterClassAssetLoader.loadXvrTextures(char, sectionId, body) change { if (clearAnimation) { _currentAnimation.value = null _currentNinjaMotion.value = null } _currentNinjaGeometry.value = NinjaGeometry.Object(ninjaObject) _currentTextures.replaceAll(textures) } } catch (e: Exception) { logger.error(e) { "Couldn't load Ninja model for $char." } change { _currentAnimation.value = null _currentNinjaMotion.value = null _currentNinjaGeometry.value = null _currentTextures.clear() } } } private suspend fun loadAnimation(animation: AnimationModel) { try { val ninjaMotion = animationAssetLoader.loadAnimation(animation.filePath) change { _currentNinjaMotion.value = ninjaMotion _animationPlaying.value = true } } catch (e: Exception) { logger.error(e) { "Couldn't load Ninja motion for ${animation.name} (path: ${animation.filePath})." } _currentNinjaMotion.value = null } } companion object { private const val MODEL_PARAM = "model" private const val BODY_PARAM = "body" private const val SECTION_ID_PARAM = "section_id" } }
1
Kotlin
5
20
423c3e252b2be6de63a03108915861fced90aaa6
11,075
phantasmal-world
MIT License
android/src/main/java/com/detectfrida/constant/GeneralConst.kt
imanshul
788,112,116
false
null
package com.detectfrida.constant object GeneralConst { const val CH_TYPE_UNKNOWN = 0 const val CH_TYPE_TEST_KEYS = 10 const val CH_TYPE_DEV_KEYS = 20 const val CH_TYPE_NON_RELEASE_KEYS = 30 const val CH_TYPE_DANGEROUS_PROPS = 40 const val CH_TYPE_PERMISSIVE_SELINUX = 50 const val CH_TYPE_SU_EXISTS = 60 const val CH_TYPE_SUPER_USER_APK = 70 const val CH_TYPE_SU_BINARY = 80 const val CH_TYPE_BUSYBOX_BINARY = 90 const val CH_TYPE_XPOSED = 100 const val CH_TYPE_RESETPROP = 110 const val CH_TYPE_WRONG_PATH_PERMITION = 120 const val CH_TYPE_HOOKS = 130 const val CH_STATE_UNCHECKED = 0 const val CH_STATE_STILL_GOING = 10 const val CH_STATE_CHECKED_ROOT_DETECTED = 20 const val CH_STATE_CHECKED_ROOT_NOT_DETECTED = 30 const val CH_STATE_CHECKED_ERROR = 40 const val ITEM_CHECK_RESULT = 10 }
1
null
23
9
2e3407f8284de3ce857622348b225593cbb90cdc
875
react-native-detect-frida
MIT License
client/configservice/ad/src/commonTest/kotlin/com/oztechan/ccc/client/configservice/ad/mapper/AdConfigMapperTest.kt
Oztechan
102,633,334
false
null
package com.oztechan.ccc.client.configservice.ad.mapper import kotlin.test.Test import kotlin.test.assertEquals import com.oztechan.ccc.client.configservice.ad.AdConfig as AdConfigRCModel class AdConfigMapperTest { @Test fun toAdConfigModel() { val rcModel = AdConfigRCModel() val model = rcModel.toAdConfigModel() assertEquals(rcModel.bannerAdSessionCount, model.bannerAdSessionCount) assertEquals(rcModel.interstitialAdSessionCount, model.interstitialAdSessionCount) assertEquals(rcModel.interstitialAdInitialDelay, model.interstitialAdInitialDelay) assertEquals(rcModel.interstitialAdPeriod, model.interstitialAdPeriod) } }
26
null
30
331
6e693e802e78b411051be9c4398df2bd60023c46
691
CCC
Apache License 2.0
src/test/resources/examples/enumPolymorphicDiscriminator/models/DiscriminatedChild2.kt
cjbooms
229,844,927
false
{"Kotlin": 874094, "Handlebars": 4874}
package examples.enumPolymorphicDiscriminator.models import com.fasterxml.jackson.`annotation`.JsonProperty import javax.validation.Valid import javax.validation.constraints.NotNull import kotlin.String import kotlin.collections.List public data class DiscriminatedChild2( @get:JsonProperty("some_enum") @get:NotNull override val someEnum: ChildDiscriminator, @param:JsonProperty("inline_obj") @get:JsonProperty("inline_obj") @get:Valid override val inlineObj: ChildDefinitionInlineObj? = null, @param:JsonProperty("inline_array") @get:JsonProperty("inline_array") @get:Valid override val inlineArray: List<ChildDefinitionInlineArray>? = null, @param:JsonProperty("inline_enum") @get:JsonProperty("inline_enum") override val inlineEnum: ChildDefinitionInlineEnum? = null, @param:JsonProperty("some_prop") @get:JsonProperty("some_prop") public val someProp: String? = null, ) : ChildDefinition(inlineObj, inlineArray, inlineEnum)
33
Kotlin
41
154
b95cb5bd8bb81e59eca71e467118cd61a1848b3f
965
fabrikt
Apache License 2.0
app/src/main/java/com/wangyz/wanandroid/kotlin/view/ArchitectureFragment.kt
milovetingting
277,392,959
false
null
package com.wangyz.wanandroid.kotlin.view import android.annotation.SuppressLint import android.view.View import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.OrientationHelper import androidx.recyclerview.widget.RecyclerView import com.wangyz.wanandroid.kotlin.R import com.wangyz.wanandroid.kotlin.adapter.ArchitectureAdapter import com.wangyz.wanandroid.kotlin.bean.ArchitectureResponse import com.wangyz.wanandroid.kotlin.databinding.FragmentArchitectureBinding import com.wangyz.wanandroid.kotlin.view.base.BaseFragment import com.wangyz.wanandroid.kotlin.view.custom.SpaceItemDecoration import com.wangyz.wanandroid.kotlin.viewmodel.ArchitectureViewModel import com.wangyz.wanandroid.kotlin.viewmodel.BottomViewModel import com.wangyz.wanandroid.kotlin.viewmodel.ShareViewModel import com.wangyz.wanandroid.kotlin.viewmodel.ViewModelBus /** * 体系Fragment */ class ArchitectureFragment : BaseFragment<FragmentArchitectureBinding, ArchitectureViewModel>() { override val classT: Class<ArchitectureViewModel> get() = ArchitectureViewModel::class.java override fun getLayoutId(): Int = R.layout.fragment_architecture @SuppressLint("WrongConstant") override fun initView() { val viewModel = ViewModelBus.INSTANCE.get(ArchitectureViewModel::class.java) val layoutManager = LinearLayoutManager(context) layoutManager.orientation = OrientationHelper.VERTICAL viewModel?.binding?.architectureRv?.layoutManager = layoutManager viewModel?.binding?.architectureRv?.addItemDecoration( SpaceItemDecoration( resources.getDimensionPixelSize( R.dimen.item_margin ) ) ) viewModel?.binding?.architectureRv?.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dy > 0) { ViewModelBus.INSTANCE.get(BottomViewModel::class.java) ?.binding?.root?.visibility = View.GONE } else { ViewModelBus.INSTANCE.get(BottomViewModel::class.java) ?.binding?.root?.visibility = View.VISIBLE } } }) viewModel?.data?.observe(viewLifecycleOwner, Observer<List<ArchitectureResponse>> { viewModel?.adapter = ArchitectureAdapter(context) viewModel?.binding!!.architectureRv.adapter = viewModel?.adapter }) viewModel?.loadArchitecture() ViewModelBus.INSTANCE.get(ShareViewModel::class.java)!!.head.postValue(getString(R.string.tab_architecture)) } override fun reInit() { ViewModelBus.INSTANCE.get(ShareViewModel::class.java)!!.head.postValue(getString(R.string.tab_architecture)) ViewModelBus.INSTANCE.get(BottomViewModel::class.java)?.binding?.root?.visibility = View.VISIBLE } }
0
Kotlin
0
0
4f3808a7b18e0d31ddf426f1de7749209c4a7efc
3,092
WanAndroid-Kotlin
Apache License 2.0
app/src/main/java/org/avmedia/gShockPhoneSync/ui/main/WatchName.kt
izivkov
480,047,057
false
null
/* * Created by Ivo Zivkov (izivkov@gmail.com) on 2022-03-30, 12:06 a.m. * Copyright (c) 2022 . All rights reserved. * Last modified 2022-03-29, 5:57 p.m. */ package org.avmedia.gShockPhoneSync.ui.main import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import org.avmedia.gShockPhoneSync.R import org.avmedia.gShockPhoneSync.utils.LocalDataStorage import org.avmedia.gshockapi.EventAction import org.avmedia.gshockapi.ProgressEvents import org.avmedia.gshockapi.WatchInfo class WatchName @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : androidx.appcompat.widget.AppCompatTextView(context, attrs, defStyleAttr) { init { createSubscription() val deviceName = LocalDataStorage.get("LastDeviceName", "") text = if (deviceName.isNullOrBlank()) { resources.getString(R.string.no_watch) } else { deviceName.removePrefix("CASIO").trim() } } @SuppressLint("SetTextI18n") private fun createSubscription() { val eventActions = arrayOf( EventAction("DeviceName") { val deviceName = ProgressEvents.getPayload("DeviceName") if ((deviceName as String).isBlank()) { text = resources.getString(R.string.no_watch) } if (deviceName.contains("CASIO")) { text = deviceName.removePrefix("CASIO").trim() } }, ) ProgressEvents.runEventActions(this.javaClass.name, eventActions) } }
6
null
9
99
8a04e7985ce260090cbe206800aff04684bd0dc4
1,629
CasioGShockSmartSync
Apache License 2.0
compose-ide-plugin/compiler-hosted-src/androidx/compose/compiler/plugins/kotlin/WeakBindingTrace.kt
JetBrains
60,701,247
false
null
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin import com.intellij.util.keyFMap.KeyFMap import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.codegen.state.GenerationState import org.jetbrains.kotlin.ir.declarations.IrAttributeContainer import org.jetbrains.kotlin.psi2ir.generators.GeneratorContext import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice import org.jetbrains.kotlin.util.slicedMap.WritableSlice import java.util.WeakHashMap /** * This class is meant to have the shape of a BindingTrace object that could exist and flow * through the Psi2Ir -> Ir phase, but doesn't currently exist. Ideally, this gets replaced in * the future by a trace that handles this use case in upstream. For now, we are okay with this * because the combination of IrAttributeContainer and WeakHashMap makes this relatively safe. */ class WeakBindingTrace { private val map = WeakHashMap<Any, KeyFMap>() fun <K : IrAttributeContainer, V> record(slice: WritableSlice<K, V>, key: K, value: V) { var holder = map[key.attributeOwnerId] ?: KeyFMap.EMPTY_MAP val prev = holder.get(slice.key) if (prev != null) { holder = holder.minus(slice.key) } holder = holder.plus(slice.key, value!!) map[key.attributeOwnerId] = holder } operator fun <K : IrAttributeContainer, V> get(slice: ReadOnlySlice<K, V>, key: K): V? { return map[key.attributeOwnerId]?.get(slice.key) } } private val ComposeTemporaryGlobalBindingTrace = WeakBindingTrace() @Suppress("unused") val GeneratorContext.irTrace: WeakBindingTrace get() = ComposeTemporaryGlobalBindingTrace @Suppress("unused") val GenerationState.irTrace: WeakBindingTrace get() = ComposeTemporaryGlobalBindingTrace @Suppress("unused") val IrPluginContext.irTrace: WeakBindingTrace get() = ComposeTemporaryGlobalBindingTrace
3
null
945
925
71cc8d80cd2fa6899d69c7f908539c5a4ad08265
2,510
android
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Headset.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.Headset: ImageVector get() { if (_headset != null) { return _headset!! } _headset = Builder(name = "Headset", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.0f, 12.418f) verticalLineTo(11.0f) arcTo(9.0f, 9.0f, 0.0f, false, false, 3.0f, 11.0f) verticalLineToRelative(1.418f) arcTo(5.0f, 5.0f, 0.0f, false, false, 5.0f, 22.0f) horizontalLineTo(7.0f) verticalLineTo(12.0f) horizontalLineTo(5.0f) verticalLineTo(11.0f) arcToRelative(7.0f, 7.0f, 0.0f, false, true, 14.0f, 0.0f) verticalLineToRelative(1.0f) horizontalLineTo(17.0f) verticalLineToRelative(8.0f) horizontalLineTo(13.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(6.0f) arcToRelative(5.0f, 5.0f, 0.0f, false, false, 2.0f, -9.582f) close() } } .build() return _headset!! } private var _headset: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,052
icons
MIT License
shared/src/commonMain/kotlin/net.wwwhackcom/experience/userInfo/UserInfoScreen.kt
wwwhackcom
656,480,862
false
null
package net.wwwhackcom.experience.userInfo import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import net.wwwhackcom.experience.base.ErrorScreen import net.wwwhackcom.experience.base.LoadingScreen import net.wwwhackcom.experience.base.TopBar import net.wwwhackcom.ext.getScreenModel internal class UserInfoRoute(private val id: String) : Screen { @Composable override fun Content() { val viewModel = getScreenModel<UserInfoViewModel>() val state by viewModel.state.collectAsState() val navigator = LocalNavigator.currentOrThrow LaunchedEffect(Unit) { viewModel.userInfo(id) } when (state) { is UserInfoUiState.Loading -> LoadingScreen() is UserInfoUiState.Success -> UserInfoScreen((state as UserInfoUiState.Success).user.toString()) { navigator.pop() } is UserInfoUiState.Error -> ErrorScreen((state as UserInfoUiState.Error).error) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun UserInfoScreen( userInfo: String, onBackPressed: () -> Unit ) { Scaffold( topBar = { TopBar(title = "User Info", onBackPressed = onBackPressed) }) { Column( modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp), verticalArrangement = Arrangement.Center ) { Text( modifier = Modifier .fillMaxWidth() .padding(10.dp), textAlign = TextAlign.Center, text = userInfo ) } } }
0
Kotlin
0
0
ebc912fc189f1aaa7a67894440511964c0e97bd3
2,434
compose-multiplatform-exercise
Apache License 2.0
demo-transactions/src/test/kotlin/io/holixon/cqrshexagonaldemo/demoparent/transactions/integrationtest/GlobalIT.kt
holixon
747,608,283
false
{"Kotlin": 69299, "Shell": 72}
package io.holixon.cqrshexagonaldemo.demoparent.transactions.integrationtest import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.port.inbound.account.CreateAccountInPort import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.port.inbound.account.DepositAccountInPort import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.port.inbound.customer.CreateCustomerInPort import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.port.outbound.account.AccountService import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.domain.model.account.Amount import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.domain.model.common.Name import io.holixon.cqrshexagonaldemo.demoparent.transactions.query.application.port.inbound.accountbalance.AccountBalanceInPort import org.assertj.core.api.Assertions import org.hamcrest.CoreMatchers.containsString import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import java.math.BigDecimal class GlobalIT : IntegrationTextBase() { @Autowired private lateinit var createCustomerInPort: CreateCustomerInPort @Autowired private lateinit var createAccountInPort: CreateAccountInPort @Autowired private lateinit var depositAccountInPort: DepositAccountInPort @Autowired private lateinit var accountBalanceInPort: AccountBalanceInPort @Autowired private lateinit var accountService: AccountService @Test fun `should create customer`() { // given val payload = """ { "name": "Dagobert Duck" } """.trimIndent() // when val response = this.mockMvc.perform( post("/api/v1/customer/create") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(payload) ) // then response.andExpect(status().isOk) .andExpect(content().string(containsString("\"name\":\"Dagobert Duck\""))) .andExpect(content().string(containsString("\"customerNumber\":"))) } @Test fun `should create account for existing customer`() { // given val customer = createCustomerInPort.createCustomer(Name("Richie Rich")) val payload = """ { "customerNumber": "${customer.customerNumber.value}" } """.trimIndent() // when val response = this.mockMvc.perform( post("/api/v1/account/create") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(payload) ) // then response.andExpect(status().isOk) .andExpect(content().string(containsString("\"customerNumber\":\"${customer.customerNumber.value}\""))) .andExpect(content().string(containsString("\"iban\":"))) } @Test fun `should deposit money on existing account`() { // given val customer = createCustomerInPort.createCustomer(Name("Charles Montgomery Burns")) val account = createAccountInPort.createAccount(customer.customerNumber) depositAccountInPort.deposit(account.iban, Amount(BigDecimal.valueOf(123.45))) val payload = """ { "iban": "${account.iban}", "amount": 111.11 } """.trimIndent() // when val response = this.mockMvc.perform( post("/api/v1/account/deposit") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(payload) ) // then response.andExpect(status().isNoContent) val currentAccount = accountService.findAccount(account.iban) Assertions.assertThat(currentAccount.balance.amount).isEqualTo(Amount(BigDecimal.valueOf(234.56))) } @Test fun `should fetch account balance for existing account`() { //given val customer = createCustomerInPort.createCustomer(Name("Charles Montgomery Burns")) val account = createAccountInPort.createAccount(customer.customerNumber) depositAccountInPort.deposit(account.iban, Amount(BigDecimal.valueOf(123.45))) //when val response = this.mockMvc.perform( get("/api/v1/account/balance") .queryParam("accountNumber", account.iban.value) .accept(MediaType.ALL) .contentType(MediaType.APPLICATION_JSON) ) // then response.andExpect(status().isOk) val currentAccount = accountBalanceInPort.getAccountBalance(account.iban.value) Assertions.assertThat(currentAccount.iban).isEqualTo(account.iban) Assertions.assertThat(currentAccount.balance.amount.value).isEqualTo(BigDecimal.valueOf(123.45)) } }
3
Kotlin
0
0
e634c14ca89f3de72f53ae6680c8ca12c539d6a7
5,359
cqrs-meets-hexagonal
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress1020001.kt
qwewqa
390,928,568
false
null
package xyz.qwewqa.relive.simulator.core.presets.dress.generated import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType import xyz.qwewqa.relive.simulator.stage.character.Character import xyz.qwewqa.relive.simulator.stage.character.DamageType import xyz.qwewqa.relive.simulator.stage.character.Position /* import xyz.qwewqa.relive.simulator.core.presets.condition.* import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress1020001 import xyz.qwewqa.relive.simulator.core.stage.Act import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff import xyz.qwewqa.relive.simulator.core.stage.dress.DressCategory import xyz.qwewqa.relive.simulator.core.stage.autoskill.new import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint import xyz.qwewqa.relive.simulator.core.stage.buff.* import xyz.qwewqa.relive.simulator.core.stage.passive.* import xyz.qwewqa.relive.simulator.core.stage.stageeffect.* val dress = dress1020001( name = "聖翔音楽学園", acts = listOf( ActType.Act1.blueprint("斬撃") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [88, 92, 96, 101, 105] times1: 1 */ } }, ActType.Act2.blueprint("キラめきの斬撃") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [93, 98, 102, 107, 112] times1: 1 キラめき回復(%value%) target: 自身 hit_rate2: 100 values2: [20, 20, 20, 20, 20] times2: [0, 0, 0, 0, 0] */ } }, ActType.Act3.blueprint("倦怠の独奏") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [132, 138, 145, 151, 158] times1: 2 クリティカル率ダウン(%value%) target: 前から1番目の敵役 hit_rate2: 100 values2: [12, 13, 14, 16, 17] times2: [3, 3, 3, 3, 3] */ } }, ActType.ClimaxAct.blueprint("Blossom Bright") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [286, 300, 314, 328, 343] times1: 3 ACTパワーダウン(%value%) target: 前から1番目の敵役 hit_rate2: 100 values2: [16, 18, 19, 21, 23] times2: [3, 3, 3, 3, 3] */ } } ), autoSkills = listOf( listOf( /* auto skill 1: 与ダメージアップ(%value%) target: 自身 values: [2, 3, 3, 3, 4] */ ), listOf( /* auto skill 2: ランサー特攻(%value%) target: 自身 values: [50, 75, 75, 75, 100] */ ), listOf( /* auto skill 3: 被ダメージダウン(%value%) target: 自身 values: [5, 6, 6, 7, 8] */ ), ), unitSkill = null /* None */, multipleCA = false, categories = setOf(), ) */ val dress1020001 = PartialDressBlueprint( id = 1020001, name = "聖翔音楽学園", baseRarity = 2, cost = 6, character = Character.Hikari, attribute = Attribute.Flower, damageType = DamageType.Normal, position = Position.Front, positionValue = 14050, stats = StatData( hp = 794, actPower = 109, normalDefense = 53, specialDefense = 51, agility = 120, dexterity = 5, critical = 50, accuracy = 0, evasion = 0, ), growthStats = StatData( hp = 26170, actPower = 1810, normalDefense = 880, specialDefense = 860, agility = 1990, ), actParameters = mapOf( ActType.Act1 to ActBlueprint( name = "斬撃", type = ActType.Act1, apCost = 1, icon = 1, parameters = listOf( actParameters0, actParameters1, actParameters1, actParameters1, actParameters1, ), ), ActType.Act2 to ActBlueprint( name = "キラめきの斬撃", type = ActType.Act2, apCost = 2, icon = 89, parameters = listOf( actParameters2, actParameters3, actParameters1, actParameters1, actParameters1, ), ), ActType.Act3 to ActBlueprint( name = "倦怠の独奏", type = ActType.Act3, apCost = 3, icon = 21, parameters = listOf( actParameters71, actParameters72, actParameters1, actParameters1, actParameters1, ), ), ActType.ClimaxAct to ActBlueprint( name = "<NAME>", type = ActType.ClimaxAct, apCost = 2, icon = 9, parameters = listOf( actParameters73, actParameters74, actParameters1, actParameters1, actParameters1, ), ), ), autoSkillRanks = listOf(1, 4, 9, null), autoSkillPanels = listOf(0, 0, 5, 0), rankPanels = growthBoard0, friendshipPanels = friendshipPattern0, remakeParameters = listOf( ), )
0
Kotlin
11
7
70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74
5,888
relight
MIT License
data/network/src/main/java/com/ebdz/network/utils/HttpUrlApolloAdapter.kt
lupsyn
438,954,334
false
{"Kotlin": 104294}
package com.ebdz.network.utils import com.apollographql.apollo3.api.Adapter import com.apollographql.apollo3.api.CustomScalarAdapters import com.apollographql.apollo3.api.json.JsonReader import com.apollographql.apollo3.api.json.JsonReader.Token.STRING import com.apollographql.apollo3.api.json.JsonWriter import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl /** * An Apollo adapter for converting between URI types to HttpUrl. */ object HttpUrlApolloAdapter : Adapter<HttpUrl> { override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): HttpUrl { return when (reader.peek()) { STRING -> reader.nextString()!!.toHttpUrl() else -> throw IllegalArgumentException("Value wasn't a string!") } } override fun toJson( writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: HttpUrl ) { writer.value(value.toString()) } }
12
Kotlin
0
0
f4d78fffde4ea59f1894c5cb558e3a095ba0676a
969
ny-challenge
Apache License 2.0
app/src/main/java/phocidae/mirounga/leonina/fragment/add/UnSocAddGralFragment.kt
poximan
711,693,982
false
{"Kotlin": 382538}
package phocidae.mirounga.leonina.fragment.add import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import phocidae.mirounga.leonina.R import phocidae.mirounga.leonina.databinding.FragmentUnsocGralBinding import phocidae.mirounga.leonina.model.LatLong import phocidae.mirounga.leonina.viewModel.UnSocShareViewModel class UnSocAddGralFragment : AddGralAbstract() { private var _binding: FragmentUnsocGralBinding? = null val binding get() = _binding!! private val sharedViewModel: UnSocShareViewModel by activityViewModels() private var latLon = LatLong() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentUnsocGralBinding.inflate(inflater, container, false) val view = binding.root // punto de observacion val ptObsUnSoc = resources.getStringArray(R.array.op_punto_obs_unsoc) val ptObsUnSocArrayAdapter = ArrayAdapter(view.context, R.layout.dropdown_item, ptObsUnSoc) binding.spinnerAddPtoObs.adapter = ptObsUnSocArrayAdapter binding.helpPtoObsUnSoc.setOnClickListener { ptoObsUnidadSocialInfo() } // contexto social val ctxSocial = resources.getStringArray(R.array.op_contexto_social) val ctxSocialArrayAdapter = ArrayAdapter(view.context, R.layout.dropdown_item, ctxSocial) binding.spinnerAddCtxSocial.adapter = ctxSocialArrayAdapter binding.helpCtxSocial.setOnClickListener { ctxSocialInfo() } // tipo de sustrato en playa val tpoSustrato = resources.getStringArray(R.array.op_tipo_sustrato) val tpoSustratoArrayAdapter = ArrayAdapter(view.context, R.layout.dropdown_item, tpoSustrato) binding.spinnerAddTpoSustrato.adapter = tpoSustratoArrayAdapter binding.helpTpoSustrato.setOnClickListener { tpoSustratoInfo() } binding.getPosicion.setOnClickListener { getPosicionActual(binding.latitud) } binding.spinnerAddPtoObs.onItemSelectedListener = onItemSelectedListener binding.spinnerAddCtxSocial.onItemSelectedListener = onItemSelectedListener binding.spinnerAddTpoSustrato.onItemSelectedListener = onItemSelectedListener binding.unSocComentario.addTextChangedListener(textWatcher) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) indicatorLight = view.findViewById(R.id.gpsLightUnSoc) } override fun onResume() { super.onResume() try { latLon.lat = arguments?.getDouble("lat")!! latLon.lon = arguments?.getDouble("lon")!! } catch (e: NullPointerException) { } cargarMap() mostrarEnPantalla() } override fun onPause() { super.onPause() val bundle = Bundle().apply { latLon.lat.let { putDouble("lat", it) } latLon.lon.let { putDouble("lon", it) } } arguments = bundle cargarMap() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun cargarMap() { map["pto_observacion"] = binding.spinnerAddPtoObs.selectedItem.toString() map["ctx_social"] = binding.spinnerAddCtxSocial.selectedItem.toString() map["tpo_sustrato"] = binding.spinnerAddTpoSustrato.selectedItem.toString() map["latitud"] = latLon.lat map["longitud"] = latLon.lon map["comentario"] = binding.unSocComentario.text.toString() colectar(0, map) } private val onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { when (parent?.id) { R.id.spinnerAddCtxSocial -> { val selectedValue = binding.spinnerAddCtxSocial.getItemAtPosition(position).toString() sharedViewModel.setLastSelectedValue(selectedValue) } } cargarMap() } override fun onNothingSelected(parent: AdapterView<*>?) {} } private val textWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { cargarMap() } } override fun updateLocationViews(latitud: Double, longitud: Double) { latLon.lat = latitud latLon.lon = longitud mostrarEnPantalla() cargarMap() } private fun mostrarEnPantalla() { val lat = String.format("%.6f", latLon.lat) val lon = String.format("%.6f", latLon.lon) binding.latitud.text = lat binding.longitud.text = lon } private fun ptoObsUnidadSocialInfo() { findNavController().navigate(R.id.ptoObsUnSoc_activity) } private fun ctxSocialInfo() { findNavController().navigate(R.id.ctxSocial_activity) } private fun tpoSustratoInfo() { findNavController().navigate(R.id.tpoSustrato_activity) } }
0
Kotlin
0
0
7de60f2aef0271c21ebe2e81e874f10bb8d7ad5c
5,606
harenkaren
MIT License
app/src/main/kotlin/com/czbix/v2ex/network/V2exService.kt
CzBiX
36,221,300
false
null
package com.czbix.v2ex.network import com.czbix.v2ex.db.Comment import com.czbix.v2ex.model.* import com.czbix.v2ex.parser.Parser import com.czbix.v2ex.parser.TopicParser import com.czbix.v2ex.util.TrackerUtils import com.google.common.base.Stopwatch import okhttp3.FormBody import okhttp3.internal.EMPTY_REQUEST import timber.log.Timber import java.util.concurrent.TimeUnit import javax.inject.Inject class V2exService @Inject constructor( private val helper: RequestHelper ) { suspend fun getTopic(topic: Topic, page: Int): TopicResponse { require(page > 0) { "Page must greater than zero" } Timber.d("Request topic with comments, topic: %s, page: %d", topic, page) val request = helper.newRequest(useMobile = true) .url(topic.url + "?p=" + page) .build() val html = helper.sendRequestSuspend(request) { response -> check(!response.isRedirect) { "Topic page shouldn't redirect" } response.body!!.string() } val doc = Parser.toDoc(html) helper.processUserState(doc, Parser.PageType.Topic) val stopwatch = Stopwatch.createStarted() val result = TopicParser.parseDoc(doc, topic, page) TrackerUtils.onParseTopic(stopwatch.elapsed(TimeUnit.MILLISECONDS), result.comments.size.toString()) return result } suspend fun postComment(topic: Topic, content: String, onceToken: String) { Timber.d("Post comment to topic: %s", topic) // @Suppress("NAME_SHADOWING") // val onceToken = onceToken ?: helper.getOnceToken().await() val requestBody = FormBody.Builder() .add("once", onceToken) .add("content", content.replace("\n", "\r\n")) .build() val request = RequestHelper.newRequest(useMobile = true) .url(topic.url) .post(requestBody).build() helper.sendRequestSuspend(request, false) { response -> // v2ex will redirect if reply success check(response.isRedirect) } } suspend fun favor(favable: Favable, bool: Boolean, csrfToken: String) { Timber.d("Favorite %s, bool: %s", favable, bool) val url = if (bool) favable.getFavUrl(csrfToken) else favable.getUnFavUrl(csrfToken) val request = RequestHelper.newRequest().url(url) .build() helper.sendRequestSuspend(request, false) { response -> check(response.isRedirect) } } suspend fun thank(obj: Thankable, onceToken: String) { Timber.d("Thank %s", obj) val request = RequestHelper.newRequest().apply { url(obj.thankUrl + "?once=" + onceToken) post(EMPTY_REQUEST) }.build() helper.sendRequestSuspend(request) } suspend fun ignore(obj: Ignorable, onceToken: String) { Timber.d("Ignore %s", obj) val builder = RequestHelper.newRequest().url(obj.ignoreUrl + "?once=" + onceToken) val isComment = obj is Comment if (isComment) { builder.post(EMPTY_REQUEST) } val request = builder.build() helper.sendRequestSuspend(request, isComment) {} } }
2
Kotlin
25
138
f6a79a91b84ae8030930231d965845798c4ce0a8
3,303
v2ex-android
Apache License 2.0
app/src/main/java/com/adammcneilly/toa/core/ui/components/navigation/NavigationTab.kt
AdamMc331
402,227,056
false
{"Kotlin": 255872, "Shell": 691, "Ruby": 666}
package com.adammcneilly.toa.core.ui.components.navigation import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Settings import androidx.compose.ui.graphics.vector.ImageVector import com.adammcneilly.toa.R import com.adammcneilly.toa.destinations.SettingsScreenDestination import com.adammcneilly.toa.destinations.TaskListScreenDestination /** * Represents a tab that can appear on some navigation component. */ sealed class NavigationTab( val labelTextRes: Int, val icon: ImageVector, val screenRoute: String, ) { object Home : NavigationTab( labelTextRes = R.string.home, icon = Icons.Default.Home, screenRoute = TaskListScreenDestination.route, ) object Settings : NavigationTab( labelTextRes = R.string.settings, icon = Icons.Default.Settings, screenRoute = SettingsScreenDestination.route, ) }
36
Kotlin
19
146
ff6d0b0e0645a3bacea703108fd35fc54f0c4b1b
969
TOA
MIT License
src/main/kotlin/spp/protocol/instrument/variable/LiveVariableScope.kt
sourceplusplus
418,984,808
false
{"Kotlin": 294528, "HTML": 3449, "Java": 813}
/* * Source++, the continuous feedback platform for developers. * Copyright (C) 2022-2023 CodeBrig, 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 spp.protocol.instrument.variable /** * Represents the scope of a variable encountered in a live probe. * * @since 0.3.0 * @author [<NAME>](mailto:<EMAIL>) */ enum class LiveVariableScope { LOCAL_VARIABLE, GLOBAL_VARIABLE, INSTANCE_FIELD, STATIC_FIELD, GENERATED_METHOD }
3
Kotlin
3
0
bffdf87557ee36dc70ae5c8199eff524918459ff
974
protocol
Apache License 2.0
frontend/android/app/src/main/java/elte/moneyshare/view/viewholder/GroupViewHolder.kt
elte-sztgy
171,624,276
false
{"C#": 197589, "Kotlin": 195505, "TypeScript": 65554, "HTML": 32369, "TSQL": 24784, "CSS": 4476, "Shell": 3755, "JavaScript": 1737, "Batchfile": 1189, "Dockerfile": 621, "Ruby": 619}
package elte.moneyshare.view.viewholder import android.support.constraint.ConstraintLayout import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import elte.moneyshare.R class GroupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var groupRootLayout: ConstraintLayout = itemView.findViewById(R.id.rootConstraintLayout) var groupNameTextView: TextView = itemView.findViewById(R.id.groupNameTextView) var groupMemberCountTextView: TextView = itemView.findViewById(R.id.groupMemberCountTextView) var groupOwnerTextView: TextView = itemView.findViewById(R.id.groupOwnerTextView) var groupBalanceTextView: TextView = itemView.findViewById(R.id.groupBalanceTextView) }
10
C#
2
0
0d7b07dd6b10279ddbaeb0390a9336c1ade63fa6
749
mshare
MIT License
client/src/main/kotlin/dev/throwouterror/game/client/engine/input/KeyboardInputHelper.kt
throw-out-error
277,902,461
false
null
package dev.throwouterror.game.client.engine.input import org.lwjgl.glfw.GLFW object KeyboardInputHelper { private const val KEYBOARD_SIZE = GLFW.GLFW_KEY_LAST + 1 private val lwjglToKeyboard: IntArray fun get(key: Int): Int { return lwjglToKeyboard[key] } private fun create() { // Map to none for (i in 0 until KEYBOARD_SIZE) { lwjglToKeyboard[i] = Keyboard.NONE.ordinal } lwjglToKeyboard[GLFW.GLFW_KEY_ESCAPE] = Keyboard.ESCAPE.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F1] = Keyboard.F1.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F2] = Keyboard.F2.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F3] = Keyboard.F3.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F4] = Keyboard.F4.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F5] = Keyboard.F5.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F6] = Keyboard.F6.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F7] = Keyboard.F7.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F8] = Keyboard.F8.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F9] = Keyboard.F9.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F10] = Keyboard.F10.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F11] = Keyboard.F11.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F12] = Keyboard.F12.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_PRINT_SCREEN] = Keyboard.PRINT_SCREEN.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_SCROLL_LOCK] = Keyboard.SCROLL_LOCK.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_PAUSE] = Keyboard.PAUSE.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_GRAVE_ACCENT] = Keyboard.GRAVE_ACCENT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_1] = Keyboard.NUM1.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_2] = Keyboard.NUM2.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_3] = Keyboard.NUM3.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_4] = Keyboard.NUM4.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_5] = Keyboard.NUM5.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_6] = Keyboard.NUM6.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_7] = Keyboard.NUM7.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_8] = Keyboard.NUM8.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_9] = Keyboard.NUM9.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_0] = Keyboard.NUM0.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_MINUS] = Keyboard.DASH.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_EQUAL] = Keyboard.EQUALS.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_BACKSPACE] = Keyboard.BACKSPACE.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_A] = Keyboard.A.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_B] = Keyboard.B.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_C] = Keyboard.C.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_D] = Keyboard.D.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_E] = Keyboard.E.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_F] = Keyboard.F.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_G] = Keyboard.G.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_H] = Keyboard.H.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_I] = Keyboard.I.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_J] = Keyboard.J.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_K] = Keyboard.K.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_L] = Keyboard.L.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_M] = Keyboard.M.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_N] = Keyboard.N.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_O] = Keyboard.O.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_P] = Keyboard.P.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_Q] = Keyboard.Q.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_R] = Keyboard.R.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_S] = Keyboard.S.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_T] = Keyboard.T.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_U] = Keyboard.U.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_V] = Keyboard.V.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_W] = Keyboard.W.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_X] = Keyboard.X.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_Y] = Keyboard.Y.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_Z] = Keyboard.Z.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_TAB] = Keyboard.TAB.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_LEFT_BRACKET] = Keyboard.LEFT_BRACKET.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_RIGHT_BRACKET] = Keyboard.RIGHT_BRACKET.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_BACKSLASH] = Keyboard.BACKSLASH.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_CAPS_LOCK] = Keyboard.CAPS_LOCK.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_SEMICOLON] = Keyboard.SEMICOLON.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_APOSTROPHE] = Keyboard.APOSTROPHE.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_ENTER] = Keyboard.ENTER.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_RIGHT_SHIFT] = Keyboard.RIGHT_SHIFT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_COMMA] = Keyboard.COMMA.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_PERIOD] = Keyboard.PERIOD.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_SLASH] = Keyboard.SLASH.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_LEFT_SHIFT] = Keyboard.LEFT_SHIFT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_LEFT_CONTROL] = Keyboard.LEFT_CONTROL.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_LEFT_SUPER] = Keyboard.LEFT_SUPER.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_LEFT_ALT] = Keyboard.LEFT_ALT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_SPACE] = Keyboard.SPACE.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_RIGHT_ALT] = Keyboard.RIGHT_ALT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_RIGHT_SUPER] = Keyboard.RIGHT_SUPER.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_RIGHT_CONTROL] = Keyboard.RIGHT_CONTROL.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_INSERT] = Keyboard.INSERT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_HOME] = Keyboard.HOME.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_PAGE_UP] = Keyboard.PAGE_UP.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_DELETE] = Keyboard.DELETE.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_END] = Keyboard.END.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_PAGE_DOWN] = Keyboard.PAGE_DOWN.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_DOWN] = Keyboard.DOWN.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_LEFT] = Keyboard.LEFT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_RIGHT] = Keyboard.RIGHT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_UP] = Keyboard.UP.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_NUM_LOCK] = Keyboard.NUM_LOCK.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_DIVIDE] = Keyboard.KP_DIVIDE.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_MULTIPLY] = Keyboard.KP_MULTIPLY.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_SUBTRACT] = Keyboard.KP_SUBTRACT.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_ADD] = Keyboard.KP_ADD.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_0] = Keyboard.KP_0.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_1] = Keyboard.KP_1.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_2] = Keyboard.KP_2.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_3] = Keyboard.KP_3.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_4] = Keyboard.KP_4.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_5] = Keyboard.KP_5.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_6] = Keyboard.KP_6.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_7] = Keyboard.KP_7.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_8] = Keyboard.KP_8.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_9] = Keyboard.KP_9.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_DECIMAL] = Keyboard.KP_DECIMAL.ordinal lwjglToKeyboard[GLFW.GLFW_KEY_KP_ENTER] = Keyboard.KP_ENTER.ordinal } init { lwjglToKeyboard = IntArray(KEYBOARD_SIZE) create() } }
4
Kotlin
0
0
7850ff32883352d3ad913e03b45e898bf84a0c30
7,649
java-game
MIT License
app/src/main/java/com/guru/composecookbook/ui/demoapps/cryptoappmvvm/ui/home/CryptoHomeViewModel.kt
zedlabs
349,067,191
true
{"Kotlin": 583941}
package com.guru.composecookbook.ui.demoapps.cryptoappmvvm.ui.home import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.cachedIn import com.guru.composecookbook.ui.demoapps.cryptoappmvvm.data.db.entities.Crypto import com.guru.composecookbook.ui.demoapps.cryptoappmvvm.data.repository.CryptoRepository import com.guru.composecookbook.ui.demoapps.cryptoappmvvm.di.DemoDIGraph import com.guru.composecookbook.ui.utils.PageNumSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class CryptoHomeViewModel( val cryptoRepository: CryptoRepository = DemoDIGraph.cryptoRepository ) : ViewModel() { //live data to read room database val favCryptoLiveData = liveData(Dispatchers.IO) { emitSource(cryptoRepository.getFavourite()) } fun getAllCryptos(pageSize: Int = 20) = Pager(config = PagingConfig(pageSize = pageSize, initialLoadSize = pageSize)) { PageNumSource { pageNo, pageSize -> cryptoRepository.getPageCryptos(pageNo, pageSize) } }.flow.cachedIn(viewModelScope) fun addToFav(crypto: Crypto) { viewModelScope.launch(Dispatchers.IO) { cryptoRepository.addFavorite(crypto = crypto) } } fun removeFav(crypto: Crypto) { viewModelScope.launch(Dispatchers.IO) { cryptoRepository.removeFavorite(crypto = crypto) } } }
0
null
0
1
f22a1101e73439dcc6feb078265722d159748530
1,544
ComposeCookBook
MIT License
buildSrc/src/test/kotlin/net/evendanan/versiongenerator/VersionGeneratorFactoryTest.kt
mirfatif
282,874,014
false
null
package net.evendanan.versiongenerator import com.nhaarman.mockito_kotlin.* import org.junit.Assert import org.junit.Test class VersionGeneratorFactoryTest { open class FakeVersionGenerator(name: String, private val enabled: Boolean, private val fakeVersionCode: Int) : VersionGenerator(name) { override fun isValidForEnvironment(): Boolean { return enabled } override fun getVersionCode(generationData: GenerationData): Int { return fakeVersionCode } } private val generators = listOf( spy(FakeVersionGenerator("first", false, 33)), spy(FakeVersionGenerator("second", true, 11)), spy(FakeVersionGenerator("third", true, 100)) ) @Test fun testHappyPath() { val factory = VersionGeneratorFactory() val generateVersion = factory.generateVersion(1, 2, 3, generators) Assert.assertEquals(11, generateVersion.versionCode) verify(generators[0]).isValidForEnvironment() verify(generators[1]).isValidForEnvironment() verify(generators[2], never()).isValidForEnvironment() verify(generators[0], never()).generate(any()) verify(generators[2], never()).generate(any()) val captor = argumentCaptor<GenerationData>() verify(generators[1]).generate(captor.capture()) Assert.assertEquals(1, captor.firstValue.major) Assert.assertEquals(2, captor.firstValue.minor) Assert.assertEquals(3, captor.firstValue.patchOffset) } @Test(expected = IllegalStateException::class) fun tesNoGenerator() { val factory = VersionGeneratorFactory() factory.generateVersion(1, 2, 3, listOf(FakeVersionGenerator("first", false, 33))) } }
890
null
823
7
7dbd4e8f2df077610373cb3fda05587ac6fc86e1
1,767
AnySoftKeyboard
Apache License 2.0
feature-account-impl/src/main/java/jp/co/soramitsu/feature_account_impl/presentation/about/di/AboutModule.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.feature_account_impl.presentation.about.di import android.content.Context import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import dagger.Module import dagger.Provides import dagger.multibindings.IntoMap import jp.co.soramitsu.common.data.network.AppLinksProvider import jp.co.soramitsu.common.di.viewmodel.ViewModelKey import jp.co.soramitsu.common.di.viewmodel.ViewModelModule import jp.co.soramitsu.common.resources.ResourceManager import jp.co.soramitsu.feature_account_impl.presentation.AccountRouter import jp.co.soramitsu.feature_account_impl.presentation.about.AboutViewModel @Module(includes = [ViewModelModule::class]) class AboutModule { @Provides @IntoMap @ViewModelKey(AboutViewModel::class) fun provideViewModel( router: AccountRouter, context: Context, appLinksProvider: AppLinksProvider, resourceManager: ResourceManager ): ViewModel { return AboutViewModel(router, context, appLinksProvider, resourceManager) } @Provides fun provideViewModelCreator(fragment: Fragment, viewModelFactory: ViewModelProvider.Factory): AboutViewModel { return ViewModelProvider(fragment, viewModelFactory).get(AboutViewModel::class.java) } }
2
Kotlin
15
55
756c1fea772274ad421de1b215a12bf4e2798d12
1,317
fearless-Android
Apache License 2.0
play-services-core/src/main/kotlin/org/microg/gms/accountsettings/ui/MainActivity.kt
kazimmt
645,813,057
false
null
/* * SPDX-FileCopyrightText: 2023 microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.accountsettings.ui import android.accounts.Account import android.accounts.AccountManager import android.os.Bundle import android.util.Log import android.view.View import android.webkit.WebView import android.widget.FrameLayout import android.widget.ProgressBar import android.widget.RelativeLayout import android.widget.RelativeLayout.LayoutParams.MATCH_PARENT import android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT import androidx.core.view.updateLayoutParams import org.microg.gms.auth.AuthConstants import org.microg.gms.common.Constants import org.microg.tools.ui.BaseActivity private const val TAG = "AccountSettings" // TODO: There likely is some API to figure those out... private val SCREEN_ID_TO_URL = hashMapOf( 1 to "https://myaccount.google.com", 200 to "https://myaccount.google.com/privacycheckup", 203 to "https://myaccount.google.com/email", 204 to "https://myaccount.google.com/phone", 205 to "https://myaccount.google.com/birthday", 206 to "https://myaccount.google.com/gender", 210 to "https://myaccount.google.com/locationsharing", 214 to "https://myaccount.google.com/dashboard", 215 to "https://takeout.google.com", 216 to "https://myaccount.google.com/inactive", 219 to "https://myactivity.google.com/myactivity", 220 to "https://www.google.com/maps/timeline", 224 to "https://myactivity.google.com/activitycontrols?settings=search", 227 to "https://myactivity.google.com/activitycontrols?settings=location", 231 to "https://myactivity.google.com/activitycontrols?settings=youtube", 235 to "https://myactivity.google.com/activitycontrols/youtube", 238 to "https://www.google.com/setting/search/privateresults/", 241 to "https://myaccount.google.com/communication-preferences", 300 to "https://myaccount.google.com/language", 301 to "https://drive.google.com/settings/storage", 302 to "https://myaccount.google.com/deleteservices", 303 to "https://myaccount.google.com/deleteaccount", 307 to "https://payments.google.com/payments/home", 308 to "https://myaccount.google.com/subscriptions", 309 to "https://myaccount.google.com/purchases", 310 to "https://myaccount.google.com/reservations", 312 to "https://myaccount.google.com/accessibility", 313 to "https://myaccount.google.com/inputtools", 400 to "https://myaccount.google.com/security-checkup/", 401 to "https://myaccount.google.com/signinoptions/password", 403 to "https://myaccount.google.com/signinoptions/two-step-verification", 406 to "https://myaccount.google.com/signinoptions/rescuephone", 407 to "https://myaccount.google.com/recovery/email", 409 to "https://myaccount.google.com/notifications", 410 to "https://myaccount.google.com/device-activity", 417 to "https://myaccount.google.com/find-your-phone", 425 to "https://myaccount.google.com/account-enhanced-safe-browsing", 426 to "https://myaccount.google.com/two-step-verification/authenticator", 427 to "https://myaccount.google.com/two-step-verification/backup-codes", 429 to "https://myaccount.google.com/two-step-verification/security-keys", 430 to "https://myaccount.google.com/two-step-verification/prompt", 431 to "https://myaccount.google.com/connections", 432 to "https://myaccount.google.com/two-step-verification/phone-numbers", 433 to "https://myaccount.google.com/signinoptions/passkeys", 437 to "https://myaccount.google.com/signinoptions/passwordoptional", 500 to "https://policies.google.com/privacy", 503 to "https://policies.google.com/terms", 519 to "https://myaccount.google.com/yourdata/maps", 520 to "https://myaccount.google.com/yourdata/search", 530 to "https://fit.google.com/privacy/settings", 547 to "https://myactivity.google.com/product/search", 562 to "https://myaccount.google.com/yourdata/youtube", 10003 to "https://myaccount.google.com/personal-info", 10004 to "https://myaccount.google.com/data-and-privacy", 10005 to "https://myaccount.google.com/people-and-sharing", 10006 to "https://myaccount.google.com/security", 10007 to "https://myaccount.google.com/payments-and-subscriptions", 10015 to "https://support.google.com/accounts", 10050 to "https://myaccount.google.com/profile", 10090 to "https://myaccount.google.com/profile/name", 10704 to "https://www.google.com/account/about", 10706 to "https://myaccount.google.com/profile/profiles-summary", 10728 to "https://myaccount.google.com/data-and-privacy/how-data-improves-experience", 10729 to "https://myaccount.google.com/data-and-privacy/data-visibility", 10759 to "https://myaccount.google.com/address/home", 10760 to "https://myaccount.google.com/address/work", ) private val ALLOWED_WEB_PREFIXES = setOf( "https://accounts.google.com/", "https://myaccount.google.com/", "https://one.google.com/", "https://myactivity.google.com/", "https://timeline.google.com/", "https://takeout.google.com/", "https://www.google.com/maps/timeline", "https://www.google.com/setting/", "https://drive.google.com/settings/", "https://drive.google.com/accounts/", "https://drive.google.com/u/1/settings/", "https://payments.google.com/", "https://policies.google.com/", "https://fit.google.com/privacy/settings", "https://maps.google.com/maps/timeline", ) private val ACTION_TO_SCREEN_ID = hashMapOf( ACTION_MY_ACCOUNT to 1, ACTION_ACCOUNT_PREFERENCES_SETTINGS to 1, ACTION_SECURITY_SETTINGS to 10006, ACTION_PRIVACY_SETTINGS to 10004, ) class MainActivity : BaseActivity() { private lateinit var webView: WebView private fun getSelectedAccountName(): String? = null override fun onCreate(savedInstanceState: Bundle?) { val extras = intent?.extras?.also { it.keySet() } Log.d(TAG, "Invoked with ${intent.action} and extras $extras") super.onCreate(savedInstanceState) val screenId = intent?.getIntExtra(EXTRA_SCREEN_ID, -1).takeIf { it != -1 } ?: ACTION_TO_SCREEN_ID[intent.action] ?: 1 val screenOptions = intent.extras?.keySet().orEmpty() .filter { it.startsWith(EXTRA_SCREEN_OPTIONS_PREFIX) } .map { it.substring(EXTRA_SCREEN_OPTIONS_PREFIX.length) to intent.getStringExtra(it) } .toMap() val callingPackage = intent?.getStringExtra(EXTRA_CALLING_PACKAGE_NAME) ?: callingActivity?.packageName ?: Constants.GMS_PACKAGE_NAME val ignoreAccount = intent?.getBooleanExtra(EXTRA_IGNORE_ACCOUNT, false) ?: false val accountName = if (ignoreAccount) null else { val accounts = AccountManager.get(this).getAccountsByType(AuthConstants.DEFAULT_ACCOUNT_TYPE) val accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME) ?: intent.getParcelableExtra<Account>("account")?.name ?: getSelectedAccountName() accounts.find { it.name.equals(accountName) }?.name } if (accountName == null) { Log.w(TAG, "No account, going without!") } if (screenId in SCREEN_ID_TO_URL) { val layout = RelativeLayout(this) layout.addView(ProgressBar(this).apply { layoutParams = RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { addRule(RelativeLayout.CENTER_HORIZONTAL) addRule(RelativeLayout.CENTER_VERTICAL) } isIndeterminate = true }) webView = WebView(this).apply { layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT) visibility = View.INVISIBLE } layout.addView(webView) setContentView(layout) WebViewHelper(this, webView, ALLOWED_WEB_PREFIXES).openWebView(SCREEN_ID_TO_URL[screenId], accountName) setResult(RESULT_OK) } else { Log.w(TAG, "Unknown screen id, can't open corresponding web page") setResult(RESULT_CANCELED) finish() } } override fun onDestroy() { super.onDestroy() } override fun onBackPressed() { if (this::webView.isInitialized && webView.canGoBack()) { webView.goBack() } else { super.onBackPressed() } } }
990
null
77
96
30e774b23b845d20eb82f8a611345cf32fdc991e
8,479
mMicroG
Apache License 2.0
paymentsheet/src/androidTest/java/com/stripe/android/paymentsheet/ui/GooglePayButtonTest.kt
stripe
6,926,049
false
null
package com.stripe.android.paymentsheet.ui import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick import com.google.common.truth.Truth.assertThat import com.stripe.android.GooglePayJsonFactory import com.stripe.android.paymentsheet.MainActivity import org.junit.Ignore import org.junit.Rule import org.junit.Test class GooglePayButtonTest { @get:Rule val composeTestRule = createAndroidComposeRule<MainActivity>() @Ignore("Re-enable once we have refactored the Google Pay button handling") @Test fun handlesPressWhenEnabled() { val testTag = GooglePayButton.TEST_TAG var didCallOnPressed = false composeTestRule.setContent { GooglePayButton( state = null, isEnabled = true, allowCreditCards = true, billingAddressParameters = GooglePayJsonFactory.BillingAddressParameters(), onPressed = { didCallOnPressed = true }, modifier = Modifier.testTag(testTag), ) } composeTestRule .onNodeWithTag(testTag) .performClick() composeTestRule.waitForIdle() assertThat(didCallOnPressed).isTrue() } @Ignore("Re-enable once we have refactored the Google Pay button handling") @Test fun ignoresPressWhenDisabled() { val testTag = GooglePayButton.TEST_TAG var didCallOnPressed = false composeTestRule.setContent { GooglePayButton( state = null, isEnabled = false, allowCreditCards = true, billingAddressParameters = GooglePayJsonFactory.BillingAddressParameters(), onPressed = { didCallOnPressed = true }, modifier = Modifier.testTag(testTag), ) } composeTestRule .onNodeWithTag(testTag) .performClick() composeTestRule.waitForIdle() assertThat(didCallOnPressed).isFalse() } }
88
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
2,192
stripe-android
MIT License
app/src/main/java/com/adammcneilly/toa/addtask/ui/AddTaskViewModel.kt
AdamMc331
402,227,056
false
null
package com.adammcneilly.toa.addtask.ui import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.adammcneilly.toa.R import com.adammcneilly.toa.addtask.domain.model.AddTaskResult import com.adammcneilly.toa.addtask.domain.model.TaskInput import com.adammcneilly.toa.addtask.domain.usecases.AddTaskUseCase import com.adammcneilly.toa.core.models.Task import com.adammcneilly.toa.core.ui.UIText import com.adammcneilly.toa.destinations.AddTaskScreenDestination import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import java.time.LocalDate import java.time.ZoneId import java.util.UUID import javax.inject.Inject @HiltViewModel class AddTaskViewModel @Inject constructor( private val addTaskUseCase: AddTaskUseCase, savedStateHandle: SavedStateHandle, ) : ViewModel() { /** * Even though this screen can be navigated to using either AddTaskDialogDestination, or * AddTaskScreenDestination, because they both have the same typesafe nav arguments delegate of * [AddTaskNavArguments], it doesn't matter what we use here to call `argsFrom(savedStateHandle) * because both will have the same functionality. */ private val args: AddTaskNavArguments = AddTaskScreenDestination.argsFrom(savedStateHandle) private val _viewState: MutableStateFlow<AddTaskViewState> = MutableStateFlow( AddTaskViewState.Initial( initialDate = args.initialDate, ) ) val viewState = _viewState.asStateFlow() fun onTaskDescriptionChanged(newDescription: String) { val currentInput = _viewState.value.taskInput val newInput = currentInput.copy( description = newDescription, ) _viewState.value = AddTaskViewState.Active( taskInput = newInput, descriptionInputErrorMessage = null, ) } fun onTaskScheduledDateChanged(newDate: LocalDate) { val currentInput = _viewState.value.taskInput val newInput = currentInput.copy( scheduledDate = newDate, ) _viewState.value = AddTaskViewState.Active( taskInput = newInput, descriptionInputErrorMessage = (_viewState.value as? AddTaskViewState.Active) ?.descriptionInputErrorMessage, ) } fun onSubmitButtonClicked() { val taskToCreate = Task( id = UUID.randomUUID().toString(), description = _viewState.value.taskInput.description, scheduledDateMillis = _viewState.value.taskInput.scheduledDate .atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli(), completed = false, ) viewModelScope.launch { val canRetry = (_viewState.value as? AddTaskViewState.SubmissionError)?.allowRetry val result = addTaskUseCase.invoke( task = taskToCreate, ignoreTaskLimits = canRetry == true, ) _viewState.value = when (result) { is AddTaskResult.Success -> { AddTaskViewState.Completed } is AddTaskResult.Failure.InvalidInput -> { result.toViewState( taskInput = _viewState.value.taskInput, ) } is AddTaskResult.Failure.MaxTasksPerDayExceeded -> { AddTaskViewState.SubmissionError( taskInput = _viewState.value.taskInput, errorMessage = UIText.ResourceText(R.string.err_add_task_limit_reached), overrideButtonText = UIText.ResourceText(R.string.that_is_okay), allowRetry = true, ) } is AddTaskResult.Failure.Unknown -> { AddTaskViewState.SubmissionError( taskInput = _viewState.value.taskInput, errorMessage = UIText.StringText("Unable to add task."), ) } } } } } private fun AddTaskResult.Failure.InvalidInput.toViewState( taskInput: TaskInput, ): AddTaskViewState { return AddTaskViewState.Active( taskInput = taskInput, descriptionInputErrorMessage = UIText.ResourceText(R.string.err_empty_task_description).takeIf { this.emptyDescription }, ) }
32
Kotlin
15
129
b0e7a57e700c1b000bc525f9938966c5f33bbba0
4,659
TOA
MIT License
ui/src/main/java/com/redvelvet/ui/composable/PasswordTextField.kt
RedVelvet-Team
670,763,637
false
null
package com.redvelvet.ui.composable import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Lock import androidx.compose.material3.Icon import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import com.redvelvet.ui.R @Composable fun PasswordTextField( modifier: Modifier = Modifier, value: String, isError: Boolean, text: String, onClick: (String) -> Unit, ) { OutlinedTextField( modifier = modifier.fillMaxWidth(), value = value, onValueChange = { onClick(it) }, label = { Text(text) }, singleLine = true, visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), leadingIcon = { Icon(Icons.Default.Lock, contentDescription = stringResource(R.string.show_and_hide_password_icon)) }, shape = RoundedCornerShape(16.dp), isError = isError, colors = OutlinedTextFieldDefaults.colors( focusedTextColor = Color.White, unfocusedTextColor = Color.White, disabledTextColor = Color.White, focusedContainerColor = Color(0xFF20233C), unfocusedContainerColor = Color(0xFF20233C), disabledContainerColor = Color(0xFF20233C), focusedBorderColor = Color.Transparent, unfocusedBorderColor = Color.Transparent, disabledBorderColor = Color.Transparent, cursorColor = Color.White ) ) }
0
Kotlin
0
0
0d6a1934ee4bbe993a03230b01237d99bc21bc30
2,104
IMovie
Apache License 2.0
core/src/main/java/com/supercaliman/core/di/RepositoryModule.kt
SuperCaliMan
280,449,917
false
null
package com.supercaliman.core.di import android.content.Context import androidx.datastore.preferences.createDataStore import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import com.supercaliman.core.data.CoreRepository import com.supercaliman.core.data.FireStoreAPI import com.supercaliman.core.data.LocalDataSource import com.supercaliman.core.data.ModelMapperDataSource import com.supercaliman.core.domain.LocalRepository import com.supercaliman.core.domain.NotesApi import com.supercaliman.core.domain.Repository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Singleton @InstallIn(ApplicationComponent::class) @Module object RepositoryModule { @Provides @Singleton fun getFireStoreApi(@ApplicationContext context: Context): NotesApi { return FireStoreAPI(context, ModelMapperDataSource()) } @Provides @Singleton fun getRepository(api: NotesApi, localRepository: LocalRepository): Repository { return CoreRepository(api, localRepository) } @Provides @Singleton fun getLocalDataSource(@ApplicationContext context: Context): LocalRepository { return LocalDataSource( context.createDataStore("user_setting"), Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() ) } }
0
Kotlin
0
1
8961f03823afd25db4624017eea1d5a49ad06d13
1,522
Notes
Apache License 2.0
hollowkit/src/main/java/com/funnywolf/hollowkit/States.kt
liaobude
305,176,692
true
{"Kotlin": 191766}
package com.funnywolf.hollowkit import android.os.Handler import android.os.Looper import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import java.lang.Exception import java.util.concurrent.ConcurrentHashMap import kotlin.collections.ArrayList /** * 「状态」的集合,支持读写和观察 * * @author https://github.com/funnywolfdadada * @since 2020/6/18 */ class States { private val states = ConcurrentHashMap<String, State>() private val listeners = ConcurrentHashMap<StateListener, Any>() fun get(type: String?): State? = type?.let { states[it] } fun set(state: State?): States { state ?: return this states[state.type] = state listeners.keys.forEach { it.notify(state) } return this } fun addListener(listener: StateListener): States { listeners[listener] = this return this } fun removeListener(listener: StateListener): States { listeners.remove(listener) return this } } interface StateListener { /** * 状态改变的回调 */ fun onStateChanged(state: State) /** * [onStateChanged] 发生异常时的回调 */ fun onStateChangedError(error: Throwable?) = Unit } fun StateListener.notify(state: State) = try { onStateChanged(state) } catch (e: Exception) { onStateChangedError(e) } private val mainHandler = Handler(Looper.getMainLooper()) data class LifecycleStateListener( val listener: StateListener ): StateListener, LifecycleEventObserver { private var lifecycle: Lifecycle? = null private var minLifecycleState: Lifecycle.State = Lifecycle.State.CREATED private var states: States? = null private val stateList = ArrayList<State>() fun addTo(states: States, lifecycle: Lifecycle? = null, minLifecycleState: Lifecycle.State = Lifecycle.State.CREATED) { clear() this.minLifecycleState = minLifecycleState this.lifecycle = lifecycle lifecycle?.addObserver(this) this.states = states states.addListener(this) } fun clear() { states?.removeListener(this) states = null lifecycle?.removeObserver(this) lifecycle = null stateList.clear() } override fun onStateChanged(state: State) { if (Thread.currentThread() != Looper.getMainLooper().thread) { mainHandler.post { onStateChanged(state) } return } stateList.add(state) dispatchAll() } override fun onStateChangedError(error: Throwable?) { super.onStateChangedError(error) listener.onStateChangedError(error) } override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { dispatchAll() } private fun dispatchAll() { val current = lifecycle?.currentState when { current == Lifecycle.State.DESTROYED -> clear() current == null || current >= minLifecycleState -> { stateList.forEach { listener.notify(it) } stateList.clear() } } } } /** * 所有数据(文本、列表、等)和行为(刷新、点击、删除等)都抽象为「状态」 * 「状态」用 [type] 区分类型,[data] 承载元数据,可能处于就绪 [READY]、加载中 [LOADING] 或出错 [ERROR] * 出错时可以携带错误信息 [error] */ data class State ( val type: String, var data: Any? = null, var status: Int = READY, var error: Throwable? = null ) { companion object { const val READY = 0 const val LOADING = 1 const val ERROR = 2 @JvmStatic fun ready(type: String, data: Any? = null): State { return State(type, data, READY) } @JvmStatic fun loading(type: String, data: Any? = null): State { return State(type, data, LOADING) } @JvmStatic fun error(type: String, throwable: Throwable? = null, data: Any? = null): State { return State(type, data, ERROR, throwable) } } }
0
null
0
0
2989f92d34fc961c6442b58371a7240f943e1252
3,993
HollowKit
Apache License 2.0
nlp/front/storage-mongo/target/generated-sources/kapt/compile/ai/tock/nlp/front/shared/config/ClassifiedEntity_Serializer.kt
theopenconversationkit
84,538,053
false
null
package fr.vsct.tock.nlp.front.shared.config import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.databind.ser.std.StdSerializer import org.litote.jackson.JacksonModuleServiceLoader internal class ClassifiedEntity_Serializer : StdSerializer<ClassifiedEntity>(ClassifiedEntity::class.java), JacksonModuleServiceLoader { override fun module() = SimpleModule().addSerializer(ClassifiedEntity::class.java, this) override fun serialize( value: ClassifiedEntity, gen: JsonGenerator, serializers: SerializerProvider ) { gen.writeStartObject() gen.writeFieldName("type") val _type_ = value.type gen.writeString(_type_) gen.writeFieldName("role") val _role_ = value.role gen.writeString(_role_) gen.writeFieldName("start") val _start_ = value.start gen.writeNumber(_start_) gen.writeFieldName("end") val _end_ = value.end gen.writeNumber(_end_) gen.writeFieldName("subEntities") val _subEntities_ = value.subEntities serializers.findTypedValueSerializer( serializers.config.typeFactory.constructCollectionType( kotlin.collections.List::class.java, serializers.config.typeFactory.constructType(fr.vsct.tock.nlp.front.shared.config.ClassifiedEntity::class.java) ), true, null ) .serialize(_subEntities_, gen, serializers) gen.writeEndObject() } }
163
null
127
475
890f69960997ae9146747d082d808d92ee407fcb
1,690
tock
Apache License 2.0
core/src/main/kotlin/gateway/handler/UserEventHandler.kt
kordlib
202,856,399
false
null
package dev.kord.core.gateway.handler import dev.kord.cache.api.DataCache import dev.kord.cache.api.put import dev.kord.cache.api.query import dev.kord.core.Kord import dev.kord.core.cache.data.UserData import dev.kord.core.cache.idEq import dev.kord.core.entity.User import dev.kord.core.event.user.UserUpdateEvent import dev.kord.gateway.Event import dev.kord.gateway.UserUpdate import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.singleOrNull import dev.kord.core.event.Event as CoreEvent @Suppress("EXPERIMENTAL_API_USAGE") internal class UserEventHandler( cache: DataCache ) : BaseGatewayEventHandler(cache) { override suspend fun handle(event: Event, shard: Int, kord: Kord, coroutineScope: CoroutineScope): CoreEvent? = when (event) { is UserUpdate -> handle(event, shard, kord, coroutineScope) else -> null } private suspend fun handle(event: UserUpdate, shard: Int, kord: Kord, coroutineScope: CoroutineScope): UserUpdateEvent { val data = UserData.from(event.user) val old = cache.query<UserData> { idEq(UserData::id, data.id) } .asFlow().map { User(it, kord) }.singleOrNull() cache.put(data) val new = User(data, kord) return UserUpdateEvent(old, new, shard, coroutineScope) } }
35
null
58
559
06e90d2db5b49ac8c4235184ef0dbb7de82ab2f7
1,340
kord
MIT License
game-plugins/src/main/kotlin/org/alter/plugins/content/items/spade/spade.plugin.kts
AlterRSPS
421,831,790
false
null
package gg.rsmod.plugins.content.items.spade on_item_option(item = Items.SPADE, "dig") { player.animate(830) if (player.tile.x == 3229 && player.tile.z == 3209 && player.inventory.contains(Items.TREASURE_SCROLL)) { player.queue { player.inventory.remove(23067, 1) player.inventory.add(23068, 1) player.setVarp(2111, 2) itemMessageBox("You dig up a Treasure Scroll.", item = 23068) } } else if (player.tile.x == 3202 && player.tile.z == 3211 && player.inventory.contains(Items.TREASURE_SCROLL_23068)) { player.queue { player.inventory.remove(23068, 1) player.inventory.add(23069, 1) player.setVarp(2111, 3) itemMessageBox("You dig up a Mysterious Orb.", item = 23069) } } else if (player.tile.x == 3108 && player.tile.z == 3264 && player.inventory.contains(Items.MYSTERIOUS_ORB_23069)) { player.queue { player.inventory.remove(23069, 1) player.inventory.add(23070, 1) player.setVarp(2111, 4) itemMessageBox("You dig up a Treasure Scroll.", item = 23070) } } else if (player.tile.x == 3077 && player.tile.z == 3260 && player.inventory.contains(Items.TREASURE_SCROLL_23070)) { player.queue { player.inventory.remove(23070, 1) player.inventory.add(23071, 1) player.setVarp(2111, 5) itemMessageBox( "You dig up an Ancient Casket. As you do, you hear a<br>faint whispering. You can't make out what it says<br>though...", item = 23071 ) chatPlayer("Hmmmm... Must have been the wind.") chatPlayer("Anyway, this must be the treasure that Veos is after. I<br>should take it to him. If I remember right, he's docked<br>at the northernmost pier in Port Sarim.") } } else player.message("Nothing interesting happens.") }
8
null
33
23
8d3b3cb38ab6a0e4bed7976cb2dbfcf75bfac9b3
1,956
Alter
Apache License 2.0
demo/plot/src/jvmBatikMain/kotlin/demo/plot/batik/plotConfig/ImageWithScaleLimitsBatik.kt
JetBrains
176,771,727
false
{"Kotlin": 7616680, "Python": 1299756, "Shell": 3453, "C": 3039, "JavaScript": 931, "Dockerfile": 94}
/* * Copyright (c) 2020. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package demo.plot.batik.plotConfig import demo.plot.common.model.plotConfig.ImageWithScaleLimits import demo.common.batik.demoUtils.PlotSpecsDemoWindowBatik fun main() { with(ImageWithScaleLimits()) { PlotSpecsDemoWindowBatik( "image_geom", plotSpecList() ).open() } }
150
Kotlin
51
1,561
c8db300544974ddd35a82a90072772b788600ac6
464
lets-plot
MIT License
src/test/kotlin/com/appifyhub/monolith/validation/impl/CleanersTest.kt
appifyhub
323,403,014
false
null
package com.appifyhub.monolith.validation.impl import assertk.assertThat import assertk.assertions.isEmpty import assertk.assertions.isEqualTo import assertk.assertions.isFalse import assertk.assertions.isNull import assertk.assertions.isTrue import assertk.assertions.isZero import com.appifyhub.monolith.domain.user.Organization import com.appifyhub.monolith.domain.user.UserId import com.appifyhub.monolith.util.Stubs import java.util.Date import java.util.Locale import org.junit.jupiter.api.Test import org.mockito.kotlin.mock class CleanersTest { // region Generic cleaners @Test fun `trim with null is empty`() { assertThat(Cleaners.Trim.clean(null)) .isEmpty() } @Test fun `trim with non-null works`() { assertThat(Cleaners.Trim.clean(" \na\t ")) .isEqualTo("a") } @Test fun `nullable trim with null is null`() { assertThat(Cleaners.TrimNullable.clean(null)) .isNull() } @Test fun `nullable trim with non-null works`() { assertThat(Cleaners.TrimNullable.clean(" \na\t ")) .isEqualTo("a") } @Test fun `nullified trim with null is null`() { assertThat(Cleaners.TrimNullified.clean(null)) .isNull() } @Test fun `nullified trim with blank is null`() { assertThat(Cleaners.TrimNullified.clean(" \n\t ")) .isNull() } @Test fun `nullified trim with non-null works`() { assertThat(Cleaners.TrimNullified.clean(" \na\t ")) .isEqualTo("a") } @Test fun `removing spaces with null is empty`() { assertThat(Cleaners.RemoveSpaces.clean(null)) .isEmpty() } @Test fun `removing spaces with non-null `() { assertThat(Cleaners.RemoveSpaces.clean(" \na\t ")) .isEqualTo("a") } @Test fun `nullable removing spaces with null is empty`() { assertThat(Cleaners.RemoveSpacesNullable.clean(null)) .isNull() } @Test fun `nullable removing spaces with non-null `() { assertThat(Cleaners.RemoveSpacesNullable.clean(" \na b\t ")) .isEqualTo("ab") } @Test fun `long to cardinal with null is zero`() { assertThat(Cleaners.LongToCardinal.clean(null)) .isZero() } @Test fun `long to cardinal with negative is zero`() { assertThat(Cleaners.LongToCardinal.clean(-5)) .isZero() } @Test fun `long to cardinal with positive works`() { assertThat(Cleaners.LongToCardinal.clean(5)) .isEqualTo(5) } @Test fun `flag defaulting to false with null is false`() { assertThat(Cleaners.FlagDefFalse.clean(null)) .isFalse() } @Test fun `flag defaulting to false with false is false`() { assertThat(Cleaners.FlagDefFalse.clean(false)) .isFalse() } @Test fun `flag defaulting to false with true is true`() { assertThat(Cleaners.FlagDefFalse.clean(true)) .isTrue() } @Test fun `flag defaulting to true with null is true`() { assertThat(Cleaners.FlagDefTrue.clean(null)) .isTrue() } @Test fun `flag defaulting to true with false is false`() { assertThat(Cleaners.FlagDefTrue.clean(false)) .isFalse() } @Test fun `flag defaulting to true with true is true`() { assertThat(Cleaners.FlagDefTrue.clean(true)) .isTrue() } // endregion // region Top level cleaners @Test fun `project ID is long-to-cardinal`() { assertThat(Cleaners.ProjectId) .isEqualTo(Cleaners.LongToCardinal) } @Test fun `account ID is long-to-cardinal`() { assertThat(Cleaners.AccountId) .isEqualTo(Cleaners.LongToCardinal) } // endregion // region ID domain cleaners @Test fun `custom user ID is removing spaces`() { assertThat(Cleaners.CustomUserId) .isEqualTo(Cleaners.RemoveSpaces) } @Test fun `username is removing spaces`() { assertThat(Cleaners.Username) .isEqualTo(Cleaners.RemoveSpaces) } @Test fun `raw signature is trimming`() { assertThat(Cleaners.RawSignature) .isEqualTo(Cleaners.Trim) } @Test fun `nullable raw signature is trimming nullable`() { assertThat(Cleaners.RawSignatureNullified) .isEqualTo(Cleaners.TrimNullified) } @Test fun `user ID with space and negative is empty and zero`() { assertThat(Cleaners.UserId.clean(UserId("\t\n ", -1))) .isEqualTo(UserId("", 0)) } @Test fun `user ID is removing spaces from identifier and making project ID cardinal`() { assertThat(Cleaners.UserId.clean(UserId(" \na b\t ", 5))) .isEqualTo(UserId("ab", 5)) } // endregion // region Contact cleaners @Test fun `name is trimming nullable`() { assertThat(Cleaners.Name) .isEqualTo(Cleaners.TrimNullable) } @Test fun `custom contact is trimming nullable`() { assertThat(Cleaners.CustomContact) .isEqualTo(Cleaners.TrimNullable) } @Test fun `email is removing spaces`() { assertThat(Cleaners.Email) .isEqualTo(Cleaners.RemoveSpaces) } @Test fun `phone with null is empty`() { assertThat(Cleaners.Phone.clean(null)) .isEmpty() } @Test fun `phone with no chars is empty`() { assertThat(Cleaners.Phone.clean("")) .isEmpty() } @Test fun `phone with alpha chars only is empty`() { assertThat(Cleaners.Phone.clean("invalid")) .isEqualTo("") } @Test fun `phone with alpha chars keeps only digits`() { assertThat(Cleaners.Phone.clean("abc123")) .isEqualTo("+123") } @Test fun `phone with local format becomes international`() { assertThat(Cleaners.Phone.clean("0123")) .isEqualTo("+123") } @Test fun `phone with international 00-format becomes international`() { assertThat(Cleaners.Phone.clean("00123")) .isEqualTo("+123") } @Test fun `phone with international format works`() { assertThat(Cleaners.Phone.clean("+123")) .isEqualTo("+123") } // endregion // region Organization cleaners @Test fun `orga name is trimming nullable`() { assertThat(Cleaners.OrganizationName) .isEqualTo(Cleaners.TrimNullable) } @Test fun `orga street is trimming nullable`() { assertThat(Cleaners.OrganizationStreet) .isEqualTo(Cleaners.TrimNullable) } @Test fun `orga postcode is trimming nullable`() { assertThat(Cleaners.OrganizationPostcode) .isEqualTo(Cleaners.TrimNullable) } @Test fun `orga city is trimming nullable`() { assertThat(Cleaners.OrganizationCity) .isEqualTo(Cleaners.TrimNullable) } @Test fun `orga country code with null is null`() { assertThat(Cleaners.OrganizationCountryCode.clean(null)) .isNull() } @Test fun `orga country code with blank is empty`() { assertThat(Cleaners.OrganizationCountryCode.clean(" \t\n ")) .isNull() } @Test fun `orga country code with one char is one char`() { assertThat(Cleaners.OrganizationCountryCode.clean("D")) .isEqualTo("D") } @Test fun `orga country code with more chars keeps only 2`() { assertThat(Cleaners.OrganizationCountryCode.clean("DEX")) .isEqualTo("DE") } @Test fun `orga country code with lowercase will uppercase`() { assertThat(Cleaners.OrganizationCountryCode.clean("de")) .isEqualTo("DE") } @Test fun `orga country code with valid code works`() { assertThat(Cleaners.OrganizationCountryCode.clean("DE")) .isEqualTo("DE") } @Test fun `orga with nulls is null`() { assertThat(Cleaners.Organization.clean(Organization.EMPTY)) .isNull() } @Test fun `orga with blanks is null`() { assertThat( Cleaners.Organization.clean( Organization( name = " \t\n ", street = " \t\n ", postcode = " \t\n ", city = " \t\n ", countryCode = " \t\n ", ) ) ).isNull() } @Test fun `orga with one non-blank property works`() { assertThat( Cleaners.Organization.clean( Organization( name = " \t\n ", street = " \tstreet\n ", postcode = " \t\n ", city = null, countryCode = null, ) ) ).isEqualTo( Organization( name = "", street = "street", postcode = "", city = null, countryCode = null, ) ) } @Test fun `orga with all non-blank properties works`() { assertThat(Cleaners.Organization.clean(Stubs.company)) .isEqualTo(Stubs.company) } // endregion // region Project property cleaners @Test fun `project name is trimming`() { assertThat(Cleaners.ProjectName) .isEqualTo(Cleaners.Trim) } @Test fun `url is trimming`() { assertThat(Cleaners.Url) .isEqualTo(Cleaners.Trim) } @Test fun `nullified url is trimming nullified`() { assertThat(Cleaners.UrlNullified) .isEqualTo(Cleaners.TrimNullified) } @Test fun `long to cardinal (as string) with null is zero`() { assertThat(Cleaners.LongToCardinalAsString.clean(null)) .isEqualTo("0") } @Test fun `long to cardinal (as string) with negative is zero`() { assertThat(Cleaners.LongToCardinalAsString.clean("-5")) .isEqualTo("0") } @Test fun `long to cardinal (as string) with positive works`() { assertThat(Cleaners.LongToCardinalAsString.clean("5")) .isEqualTo("5") } @Test fun `flag defaulting to false (as string) with null is false`() { assertThat(Cleaners.FlagDefFalseAsString.clean(null)) .isEqualTo("false") } @Test fun `flag defaulting to false (as string) with false is false`() { assertThat(Cleaners.FlagDefFalseAsString.clean("false")) .isEqualTo("false") } @Test fun `flag defaulting to false (as string) with true is true`() { assertThat(Cleaners.FlagDefFalseAsString.clean("true")) .isEqualTo("true") } @Test fun `flag defaulting to true (as string) with null is false`() { assertThat(Cleaners.FlagDefTrueAsString.clean(null)) .isEqualTo("true") } @Test fun `flag defaulting to true (as string) with false is false`() { assertThat(Cleaners.FlagDefTrueAsString.clean("false")) .isEqualTo("false") } @Test fun `flag defaulting to true (as string) with true is true`() { assertThat(Cleaners.FlagDefTrueAsString.clean("true")) .isEqualTo("true") } // endregion // region Other cleaners @Test fun `origin is trimming nullable`() { assertThat(Cleaners.Origin) .isEqualTo(Cleaners.TrimNullable) } @Test fun `IP address is removing spaces nullable`() { assertThat(Cleaners.IpAddress) .isEqualTo(Cleaners.RemoveSpacesNullable) } @Test fun `birthday is doing nothing`() { val birthday: BDay = Date() to mock() assertThat(Cleaners.BDay.clean(birthday)) .isEqualTo(birthday) } @Test fun `language tag defaulting to null with null`() { assertThat(Cleaners.LanguageTag.clean(null)) .isNull() } @Test fun `language tag defaulting to null with empty`() { assertThat(Cleaners.LanguageTag.clean("")) .isNull() } @Test fun `language tag defaulting to null with invalid code`() { assertThat(Cleaners.LanguageTag.clean("asdasdasdasd")) .isNull() } @Test fun `language tag cleans trimmed valid code`() { val tag = Locale.US.toLanguageTag() assertThat(Cleaners.LanguageTag.clean(" \n$tag\t ")) .isEqualTo(tag) } // endregion }
1
Kotlin
0
0
6c35d77cfe6e8d6ed29257935372aa5c35c63785
11,228
monolith
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Tubes.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt 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 me.localx.icons.straight.Icons public val Icons.Bold.Tubes: ImageVector get() { if (_tubes != null) { return _tubes!! } _tubes = Builder(name = "Tubes", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(24.0f, 0.0f) horizontalLineToRelative(-11.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(1.0f) verticalLineToRelative(16.5f) curveToRelative(0.0f, 2.481f, 2.019f, 4.5f, 4.5f, 4.5f) reflectiveCurveToRelative(4.5f, -2.019f, 4.5f, -4.5f) lineTo(23.0f, 3.0f) horizontalLineToRelative(1.0f) lineTo(24.0f, 0.0f) close() moveTo(18.5f, 21.0f) curveToRelative(-0.827f, 0.0f, -1.5f, -0.673f, -1.5f, -1.5f) verticalLineToRelative(-8.5f) horizontalLineToRelative(3.0f) verticalLineToRelative(8.5f) curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f) close() moveTo(20.0f, 8.0f) horizontalLineToRelative(-3.0f) lineTo(17.0f, 3.0f) horizontalLineToRelative(3.0f) verticalLineToRelative(5.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(11.0f, 0.0f) lineTo(0.0f, 0.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(1.0f) verticalLineToRelative(16.5f) curveToRelative(0.0f, 2.481f, 2.019f, 4.5f, 4.5f, 4.5f) reflectiveCurveToRelative(4.5f, -2.019f, 4.5f, -4.5f) lineTo(10.0f, 3.0f) horizontalLineToRelative(1.0f) lineTo(11.0f, 0.0f) close() moveTo(5.5f, 21.0f) curveToRelative(-0.827f, 0.0f, -1.5f, -0.673f, -1.5f, -1.5f) verticalLineToRelative(-8.5f) horizontalLineToRelative(3.0f) verticalLineToRelative(8.5f) curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f) close() moveTo(7.0f, 8.0f) horizontalLineToRelative(-3.0f) lineTo(4.0f, 3.0f) horizontalLineToRelative(3.0f) verticalLineToRelative(5.0f) close() } } .build() return _tubes!! } private var _tubes: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,758
icons
MIT License
shared/src/commonMain/kotlin/com/darrenthiores/ecoswap/presentation/other_profile/OtherProfileViewModel.kt
darrenthiores
688,372,873
false
{"Kotlin": 770054, "Swift": 362583}
package com.darrenthiores.ecoswap.presentation.other_profile import com.darrenthiores.ecoswap.domain.item.use_cases.GetUserItems import com.darrenthiores.ecoswap.domain.reviews.use_cases.AddUserReview import com.darrenthiores.ecoswap.domain.reviews.use_cases.GetUserReviews import com.darrenthiores.ecoswap.domain.user.use_cases.GetUserById import com.darrenthiores.ecoswap.domain.utils.Resource import com.darrenthiores.ecoswap.domain.utils.UiEvent import com.darrenthiores.ecoswap.presentation.utils.DefaultPaginator import com.darrenthiores.ecoswap.utils.flow.toCommonFlow import com.darrenthiores.ecoswap.utils.flow.toCommonStateFlow import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class OtherProfileViewModel( private val getUserById: GetUserById, private val getUserItems: GetUserItems, private val getUserReviews: GetUserReviews, private val addUserReview: AddUserReview, coroutineScope: CoroutineScope? = null ) { private val viewModelScope = coroutineScope ?: CoroutineScope(Dispatchers.Main) private val _state = MutableStateFlow(OtherProfileState()) val state = _state.toCommonStateFlow() private val _uiEvent = Channel<UiEvent>() val uiEvent = _uiEvent .receiveAsFlow() .toCommonFlow() private val itemPaginator = DefaultPaginator( initialKey = state.value.items.page, onLoadUpdated = { isLoading -> _state.update { it.copy( items = it.items.copy( isLoading = isLoading ) ) } }, onRequest = { nextPage -> state.value.user?.id?.let { id -> getUserItems( page = nextPage, id = id ) } ?: Resource.Error("Unknown Error Just Occurred") }, getNextKey = { state.value.items.page + 1 }, onError = { error -> _state.update { it.copy( items = it.items.copy( error = error, endReached = true ) ) } }, onSuccess = { items, key -> _state.update { it.copy( items = it.items.copy( items = items, page = key, endReached = items.isEmpty() ) ) } } ) private val reviewPaginator = DefaultPaginator( initialKey = state.value.reviews.page, onLoadUpdated = { isLoading -> _state.update { it.copy( reviews = it.reviews.copy( isLoading = isLoading ) ) } }, onRequest = { nextPage -> state.value.user?.id?.let { id -> getUserReviews( page = nextPage, id = id ) } ?: Resource.Error("Unknown Error Just Occurred") }, getNextKey = { state.value.reviews.page + 1 }, onError = { error -> _state.update { it.copy( reviews = it.reviews.copy( error = error, endReached = true ) ) } }, onSuccess = { items, key -> _state.update { it.copy( reviews = it.reviews.copy( items = items, page = key, endReached = items.isEmpty() ) ) } } ) fun initialFetch(id: String) { fetchUser( id = id ) } fun onEvent(event: OtherProfileEvent) { when (event) { OtherProfileEvent.LoadItemNextPage -> { viewModelScope.launch { itemPaginator.loadNextItems() } } OtherProfileEvent.LoadReviewNextPage -> { viewModelScope.launch { reviewPaginator.loadNextItems() } } OtherProfileEvent.AddReview -> { addReview() } is OtherProfileEvent.OnMessageChange -> { _state.update { it.copy( message = event.message ) } } is OtherProfileEvent.OnPickRating -> { _state.update { it.copy( rating = event.rating ) } } OtherProfileEvent.Reset -> { _state.update { it.copy( isSuccess = false ) } } OtherProfileEvent.HideError -> { _state.update { it.copy( showError = false ) } } } } private fun fetchUser( id: String ) { viewModelScope.launch { _state.update { it.copy( isUserLoading = true ) } val result = getUserById( id = id ) when (result) { is Resource.Error -> { _state.update { it.copy( isUserLoading = false, userError = result.message ) } } is Resource.Loading -> Unit is Resource.Success -> { _state.update { it.copy( isUserLoading = false, user = result.data ) } viewModelScope.launch { itemPaginator.loadNextItems() } viewModelScope.launch { reviewPaginator.loadNextItems() } } } } } private fun addReview() { viewModelScope.launch { if (state.value.rating == 0) { return@launch } if (state.value.message.isEmpty()) { return@launch } _state.update { it.copy( isLoading = true ) } val result = addUserReview( rating = state.value.rating, message = state.value.message, userId = state.value.user?.id ?: return@launch ) when (result) { is Resource.Error -> { _state.update { it.copy( isLoading = false, error = result.message, showError = true ) } } is Resource.Loading -> Unit is Resource.Success -> { _state.update { it.copy( isLoading = false, isSuccess = true ) } viewModelScope.launch { _uiEvent.send( UiEvent.Success ) } _state.update { it.copy( rating = 0, message = "" ) } } } } } }
0
Kotlin
0
0
792b3293b4e378b7482f948ce4de622cb88f3cf1
8,358
EcoSwap
MIT License
core/src/com/ascending/games/id1/edit/board/action/content/BattleAction.kt
AscendingGames
147,917,936
false
null
package com.ascending.games.id1.edit.board.action.content import com.ascending.games.id1.edit.mechanics.BattleDomain import com.ascending.games.id1.model.mechanics.Battle import com.ascending.games.engine.edit.action.ITimedAction class BattleAction(private val battle : Battle) : com.ascending.games.engine.edit.action.ITimedAction { private val battleDomain = BattleDomain(battle) override val canExecute : Boolean get() = battle.monster.roomElement.clearables.contains(battle.monster) override fun execute(delta: Float): Boolean { if (battle.winner == null) { battleDomain.update(delta) } val winner = battle.winner if (winner == battle.hero) { battle.monster.roomElement.clearables.remove(battle.monster) } return winner != null } }
11
null
1
1
7fb0ee90967c49ab1056620c68a2029f663e4e40
837
DungeonCreator
MIT License
src/main/kotlin/automaton/constructor/view/module/executor/tree/ExecutionTreeView.kt
spbu-se
460,362,528
false
{"Kotlin": 450397, "CSS": 78}
package automaton.constructor.view.module.executor.tree import automaton.constructor.controller.module.executor.tree.ExecutionTreeController import automaton.constructor.model.module.executor.ExecutionState import automaton.constructor.model.module.executor.Executor import automaton.constructor.utils.customizedZoomScrollPane import automaton.constructor.view.GRAPH_PANE_CENTER import automaton.constructor.view.GRAPH_PANE_INIT_SIZE import javafx.collections.SetChangeListener import javafx.scene.layout.Pane import tornadofx.* class ExecutionTreeView(executor: Executor) : Pane() { val controller = ExecutionTreeController(executor) init { visibleWhen(executor.startedBinding) executor.startedBinding.onChange { clear() customizedZoomScrollPane { minWidth = GRAPH_PANE_INIT_SIZE.x minHeight = GRAPH_PANE_INIT_SIZE.y pane { translateX = GRAPH_PANE_CENTER.x translateY = GRAPH_PANE_CENTER.y val treeParent = this val decorNode = pane() hbox(ExecutionNodeView.HORIZONTAL_SPACING) { translateXProperty().bind(layoutBoundsProperty().doubleBinding { -it!!.width / 2 }) val executionStateToNodeViewMap = mutableMapOf<ExecutionState, ExecutionNodeView>() fun addRoot(root: ExecutionState) { executionStateToNodeViewMap[root] = executionNodeView(controller, root, treeParent, decorNode) } executor.roots.forEach { addRoot(it) } executor.roots.addListener(SetChangeListener { if (it.wasAdded()) addRoot(it.elementAdded) if (it.wasRemoved()) executionStateToNodeViewMap.remove(it.elementRemoved)?.remove() }) } } } } } }
4
Kotlin
0
8
008858326d8b70316a95bded8c927d5a635b1f3b
2,055
KotlinAutomataConstructor
Apache License 2.0
serenity-ensure/src/main/kotlin/net/serenitybdd/screenplay/ensure/PerformableExpectations.kt
serenity-bdd
26,201,720
false
{"HTML": 106295454, "JavaScript": 11374128, "Java": 6664877, "Groovy": 1260866, "CSS": 1192001, "FreeMarker": 458192, "Kotlin": 389324, "Gherkin": 170891, "SCSS": 70764, "Shell": 2452, "XSLT": 980, "TypeScript": 780}
package net.serenitybdd.screenplay.ensure import net.serenitybdd.annotations.Step import net.serenitybdd.core.Serenity import net.serenitybdd.screenplay.Actor import net.serenitybdd.screenplay.Performable import net.thucydides.core.steps.StepEventBus import net.thucydides.model.steps.ExecutedStepDescription import net.thucydides.model.steps.StepFailure private fun handleException(errorMsg: String) { takeScreenshot() if (BlackBox.isUsingSoftAssertions()) { BlackBox.softlyAssert(errorMsg.trim()) StepEventBus.getParallelEventBus().baseStepListener.updateCurrentStepFailureCause(AssertionError(errorMsg.trim())); } else { throw AssertionError(errorMsg.trim()) } } open class PerformableExpectation<A, E>( private val actual: A?, private val expectation: Expectation<A?, E>, private val expected: E?, private val isNegated: Boolean = false, private val expectedDescription: String = "a value", private val reportedError: String = "" ) : Performable { private val description = expectation.describe(expected, isNegated, expectedDescription); /** * Override the default description reported when the assertion fails. */ fun withReportedError(reportedError: String): PerformableExpectation<A, E> { return PerformableExpectation(actual, expectation, expected, isNegated, expectedDescription, reportedError) } @Step("{0} should see #description") override fun <T : Actor?> performAs(actor: T) { BlackBox.reset() val result = expectation.apply(actual, expected!!, actor) if (isAFailure(result, isNegated)) { val exceptionMessage = expectation.compareActualWithExpected( actual, expected, isNegated, expectedDescription ) val exceptionMessageWithDescription = if (reportedError.isEmpty()) exceptionMessage else "$reportedError: $exceptionMessage"; handleException(exceptionMessageWithDescription) } } /** * Internal use only - DO NOT USE */ protected constructor() : this(null, Expectation<A?, E>( "placeholder", "placeholder", fun(_: Actor?, _: A?, _: E): Boolean = true ), null) { } } open class BiPerformableExpectation<A, E>( private val actual: A?, private val expectation: DoubleValueExpectation<A?, E>, private val startRange: E?, private val endRange: E?, private val isNegated: Boolean = false, private val expectedDescription: String ) : Performable { private val description = expectation.describeRange(startRange,endRange,isNegated,expectedDescription) @Step("{0} should see #description") override fun <T : Actor?> performAs(actor: T) { BlackBox.reset() val result = expectation.apply(actual, startRange, endRange, actor) if (isAFailure(result, isNegated)) { val exceptionMessage = expectation.compareActualWithExpected( actual, startRange, endRange, isNegated, expectedDescription ); handleException(exceptionMessage) } } /** * Internal use only - DO NOT USE */ protected constructor() : this(null, DoubleValueExpectation<A?, E>( "placeholder", fun(_: Actor?, _: A?, _: E, _: E): Boolean = true ), null, null, false, "") { } } fun takeScreenshot() { if (StepEventBus.getEventBus().isBaseStepListenerRegistered) { StepEventBus.getEventBus().takeScreenshot() } } open class PerformablePredicate<A>( private val actual: A?, private val expectation: PredicateExpectation<A?>, private val isNegated: Boolean = false, private val expectedDescription: String, private val exception: Throwable? = null ) : Performable { private val description = expectation.describe(isNegated, expectedDescription); @Step("{0} should see #description") override fun <T : Actor?> performAs(actor: T) { BlackBox.reset() val result = expectation.apply(actual, actor) if (isAFailure(result, isNegated)) { if (exception != null) { throw exception } else { val exceptionMessage = expectation.compareActualWithExpected(actual, isNegated, expectedDescription) handleException(exceptionMessage) } } } fun orElseThrow(exception: Throwable): PerformablePredicate<A> { return PerformablePredicate(actual, expectation, isNegated, expectedDescription, exception) } /** * Internal use only - DO NOT USE */ protected constructor() : this(null, PredicateExpectation<A?>( "placeholder", "placeholder", fun(_: Actor?, _: A?): Boolean = true ), false, "placeholder") { } } private fun isAFailure(result: Boolean, isNegated: Boolean) = (!isNegated && !result || isNegated && result)
384
HTML
518
720
9370955ce66b3ee0cb0d400c5705fc0dcb47eddd
5,164
serenity-core
Apache License 2.0
app/src/main/java/com/example/customproject/ui/viewbrand/ViewBrandFragment.kt
Aeth01
542,880,018
false
{"Kotlin": 46369}
@file:Suppress("NAME_SHADOWING") package com.example.customproject.ui.viewbrand import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.lifecycle.LiveData import androidx.lifecycle.asLiveData import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.NavHostFragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.example.customproject.DatabaseApplication import com.example.customproject.database.BrandItem import com.example.customproject.databinding.FragmentViewBrandBinding import com.example.customproject.ui.deleteConfirmDialog.DeleteDialogFragment import kotlinx.coroutines.launch class ViewBrandFragment : Fragment() { private lateinit var binding: FragmentViewBrandBinding private lateinit var linearLayoutManager : LinearLayoutManager private lateinit var adapter : ViewBrandAdapter private lateinit var data : MutableList<BrandItem> private val viewModel : ViewBrandViewModel by activityViewModels { ViewBrandViewModelFactory( (activity?.application as DatabaseApplication).database.brandDao() ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding = FragmentViewBrandBinding.inflate(inflater, container, false) // populate recycler view with brand items val itemListView = binding.viewBrandList linearLayoutManager = LinearLayoutManager(context) itemListView.layoutManager = linearLayoutManager data = initData() adapter = ViewBrandAdapter( brandOpenListener = { openBrand(it) }, brandDeleteListener = { deleteBrand(it) } ) itemListView.adapter = adapter viewModel.getRows().asLiveData().observe(viewLifecycleOwner) { adapter.updateData(it) } // go to add brand on click binding.fabAddBrand.setOnClickListener{ val action = ViewBrandFragmentDirections.actionNavSelectBrandToAddBrandFragment() NavHostFragment.findNavController(this).navigate(action) } return binding.root } // return data to show private fun initData() : MutableList<BrandItem> { val ret = mutableListOf<BrandItem>() val rows : LiveData<List<BrandItem>> = viewModel.getRows().asLiveData() rows.observe(viewLifecycleOwner) { rows -> rows?.let { for (row in it) { data.add(BrandItem(row.brandName)) } } } return ret } // go to view items page for brand private fun openBrand(item : BrandItem) { val action = ViewBrandFragmentDirections.actionNavSelectBrandToNavSelectItem2() action.brandItem = item NavHostFragment.findNavController(this).navigate(action) } // open delete confirmation dialog private fun deleteBrand(item : BrandItem) { val action = ViewBrandFragmentDirections.actionNavSelectBrandToDeleteDialogFragment() action.brand = item findNavController().navigate(action) } }
0
Kotlin
0
1
46b80a8aa205c2df5a291ae50b0a8a9172b7270e
3,491
COS30017-Custom-Project
MIT License
src/main/java/com/adityaamolbavadekar/hiphe/SharedActivity.kt
AdityaBavadekar
421,028,992
false
null
/******************************************************************************* * Copyright (c) 2021. <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package com.adityaamolbavadekar.hiphe import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.ContactsContract import android.provider.OpenableColumns import android.util.Log import android.webkit.MimeTypeMap import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.adityaamolbavadekar.hiphe.interaction.showToast import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import kotlinx.android.synthetic.main.activity_shared.* class SharedActivity : AppCompatActivity() { private val TAG = "SharedActivity" private lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_shared) textView = findViewById(R.id.resultTetxView) val data: Uri? = intent?.data when { intent?.type?.startsWith("image/jpeg") == true -> { this.showToast("Image.jpeg") } intent?.type?.startsWith("image/jpg") == true -> { this.showToast("Image.jpg") } intent?.type?.startsWith("image/gif") == true -> { this.showToast("Image.gif") } intent?.type?.startsWith("image/png") == true -> { this.showToast("Image.png") } intent?.type?.startsWith("image/webp") == true -> { this.showToast("Image.webp") } intent?.type?.startsWith("image/svgz") == true -> { this.showToast("Image.svgz") } intent?.type?.startsWith("image/wbmp") == true -> { this.showToast("Image.wbmp") } intent?.type?.startsWith("text/*") == true -> { this.showToast("Text") if (data != null) { this.showToast("${contentResolver.getType(data)}") val text = intent.getStringExtra(Intent.EXTRA_TEXT) if (intent.getStringExtra(Intent.EXTRA_TITLE) != null) { textView.text = text + intent.getStringExtra(Intent.EXTRA_TITLE).toString() }else{ textView.text = text } } } intent?.type?.startsWith("video/wav") == true -> { this.showToast("Video.wav") } intent?.type?.startsWith("video/mp4") == true -> { this.showToast("Video.mp4") } else -> { val type = contentResolver.getType(data!!).toString() this.showToast("Unknown type: $type , ${data.scheme}") } } result_ok_shared_activity.setOnClickListener { setResult(Activity.RESULT_OK) finish() } } }
0
Kotlin
0
1
eb8608b7aa63ed3fca9ffd3b2e999824c1e072de
3,795
Hiphe
Apache License 2.0
app/src/main/java/org/simple/clinic/search/results/PatientSearchResultsInit.kt
KelvnPere
310,601,209
true
{"Kotlin": 4452962, "Shell": 3616, "Python": 3162}
package org.simple.clinic.search.results import com.spotify.mobius.First import com.spotify.mobius.Init import org.simple.clinic.mobius.first class PatientSearchResultsInit : Init<PatientSearchResultsModel, PatientSearchResultsEffect> { override fun init(model: PatientSearchResultsModel): First<PatientSearchResultsModel, PatientSearchResultsEffect> { return first(model) } }
0
null
0
0
79b5055be07a4e9b46b84b0a157bb07f6cc254ad
388
simple-android
MIT License
app/src/main/java/com/zlagi/blogfy/view/blog/search/result/SearchResultFragment.kt
Zlagi
475,379,557
false
{"Kotlin": 496613}
package com.zlagi.blogfy.view.blog.search.result import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import androidx.activity.addCallback import androidx.core.view.isVisible import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import coil.ImageLoader import com.google.android.material.snackbar.Snackbar import com.zlagi.blogfy.R import com.zlagi.blogfy.databinding.FragmentSearchBlogBinding import com.zlagi.blogfy.view.utils.* import com.zlagi.presentation.viewmodel.blog.search.historyview.QUERY import com.zlagi.presentation.viewmodel.blog.search.resultview.SearchResultContract import com.zlagi.presentation.viewmodel.blog.search.resultview.SearchResultContract.SearchResultEvent import com.zlagi.presentation.viewmodel.blog.search.resultview.SearchResultViewModel import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class SearchResultFragment : Fragment() { private val viewModel by viewModels<SearchResultViewModel>() private val binding get() = _binding!! private var _binding: FragmentSearchBlogBinding? = null private var searchResultAdapter: SearchResultAdapter? = null @Inject lateinit var imageLoader: ImageLoader private val args: SearchResultFragmentArgs by navArgs() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) viewModel.setEvent( SearchResultEvent.ExecuteSearch( initSearch = true, query = args.query ) ) savedInstanceState?.putBoolean("init", false) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSearchBlogBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { searchResultAdapter = createSearchBlogAdapter() binding.searchInputText.setText(args.query) setupSearchBlogRecyclerView() setupViews() observeViewState() observeViewEffect() } private fun createSearchBlogAdapter(): SearchResultAdapter { val ai: ApplicationInfo = requireContext().packageManager .getApplicationInfo(requireContext().packageName, PackageManager.GET_META_DATA) val firestoreImageBucketUrl = ai.metaData["firestoreImageBucketUrlKey"].toString() return SearchResultAdapter(firestoreImageBucketUrl) } private fun setupNavigateUp(state: Int) { binding.apply { searchBackButton.setImageResource(state) searchBackButton.setOnClickListener { viewModel.setEvent(SearchResultEvent.NavigateUp(icon = state)) } } requireActivity().onBackPressedDispatcher.addCallback(this) { viewModel.setEvent(SearchResultEvent.NavigateUp(icon = null)) } } private fun setupViews() { binding.apply { searchInputText.setOnFocusChangeListener { view, _ -> if (view.hasFocus()) { viewModel.setEvent( SearchResultEvent.UpdateIcon ) } } searchInputText.addTextChangedListener { viewModel.setEvent(SearchResultEvent.UpdateQuery(query = it.toString())) } searchInputText.setOnEditorActionListener { view, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED || actionId == EditorInfo.IME_ACTION_SEARCH) { val query = view.text.toString() viewModel.setEvent( SearchResultEvent.ExecuteSearch( initSearch = false, query = query ) ) } true } } } private fun setupSearchBlogRecyclerView() { binding.searchResult.blogsRecyclerView.apply { addItemDecoration(BottomSpacingItemDecoration(resources.getDimensionPixelSize(R.dimen.dimen_16))) layoutManager = LinearLayoutManager(requireContext()) itemAnimator = SpringAddItemAnimator() adapter = searchResultAdapter addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) val layoutManager = recyclerView.layoutManager as LinearLayoutManager val lastPosition = layoutManager.findLastVisibleItemPosition() if ( lastPosition == searchResultAdapter?.itemCount?.minus(1) && !viewModel.isLoadingNextPage && !viewModel.isLastPage ) { viewModel.setEvent(SearchResultEvent.NextPage) } } }) } } private fun observeViewState() { viewLifecycleOwner.collectWhenStarted(viewModel.viewState) { state -> render(state) } } private fun render(state: SearchResultContract.SearchResultViewState) { binding.apply { searchHistory.apply { initialSearchMessage.visibility = View.GONE historyRecyclerView.visibility = View.GONE clearSearchHistory.visibility = View.GONE } searchResult.apply { progressBar.isVisible = state.loading errorMessageTextView.isVisible = state.showEmptyBlogs blogsRecyclerView.visibility = View.VISIBLE } appbar.setExpanded(false) setupNavigateUp(state.icon) searchResultAdapter?.submitList(state.blogs) } } private fun observeViewEffect() { viewLifecycleOwner.collectWhenStarted(viewModel.viewEffect) { reactTo(it) } } private fun reactTo( effect: SearchResultContract.SearchResultViewEffect ) { binding.apply { when (effect) { is SearchResultContract.SearchResultViewEffect.ShowSnackBarError -> { progressBar.visibility = View.GONE showSnackBar(effect.message, Snackbar.LENGTH_LONG) } is SearchResultContract.SearchResultViewEffect.NavigateUp -> { findNavController().previousBackStackEntry?.savedStateHandle?.set( QUERY, effect.query ) findNavController().navigateUp() } SearchResultContract.SearchResultViewEffect.ClearFocus -> searchInputText.clearFocus() SearchResultContract.SearchResultViewEffect.HideKeyboard -> requireActivity().hideKeyboard() } } } override fun onDestroyView() { super.onDestroyView() searchResultAdapter = null _binding = null } }
0
Kotlin
12
63
dffd07e8533c285bb5ca9de4e9676985aa0e87cc
7,736
Blogfy
Apache License 2.0
test-common/src/main/kotlin/KontrollsamtaleTestData.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.test import no.nav.su.se.bakover.common.Tidspunkt import no.nav.su.se.bakover.domain.kontrollsamtale.Kontrollsamtale import no.nav.su.se.bakover.domain.kontrollsamtale.Kontrollsamtalestatus import java.time.LocalDate import java.util.UUID fun kontrollsamtale( id: UUID = UUID.randomUUID(), opprettet: Tidspunkt = fixedTidspunkt, sakId: UUID = UUID.randomUUID(), innkallingsdato: LocalDate = fixedLocalDate.plusMonths(4), status: Kontrollsamtalestatus = Kontrollsamtalestatus.PLANLAGT_INNKALLING, frist: LocalDate = fixedLocalDate.plusMonths(5), dokumentId: UUID? = null ): Kontrollsamtale = Kontrollsamtale( id = id, opprettet = opprettet, sakId = sakId, innkallingsdato = innkallingsdato, status = status, frist = frist, dokumentId = dokumentId )
1
Kotlin
0
0
2a69312721cc29dc5f8794bdfa1b96ac29a3f4ce
835
su-se-bakover
MIT License
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/framework/impl/FrameworkRecordsTable.kt
JetBrains
43,696,115
false
null
package com.jetbrains.edu.learning.framework.impl import com.intellij.util.io.StorageLockContext import com.intellij.util.io.storage.AbstractRecordsTable import java.nio.file.Path @Suppress("UnstableApiUsage") class FrameworkRecordsTable(storageFilePath: Path, context: StorageLockContext) : AbstractRecordsTable(storageFilePath, context) { override fun getImplVersion(): Int = 1 override fun getZeros(): ByteArray = ZEROS override fun getRecordSize(): Int = RECORD_SIZE companion object { private const val RECORD_SIZE = DEFAULT_RECORD_SIZE private val ZEROS = ByteArray(RECORD_SIZE) } }
7
null
49
150
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
613
educational-plugin
Apache License 2.0
app/src/main/java/eu/kanade/domain/chapter/interactor/DeleteChapters.kt
scb261
381,944,147
true
{"Kotlin": 4047397}
package eu.kanade.domain.chapter.interactor import eu.kanade.domain.chapter.repository.ChapterRepository class DeleteChapters( private val chapterRepository: ChapterRepository, ) { suspend fun await(chapters: List<Long>) { chapterRepository.removeChaptersWithIds(chapters) } }
0
Kotlin
0
7
5a3a2084cbfff68c4187ea55ad6b8fd7be2796b7
300
TachiyomiSY
Apache License 2.0
IndoorNavAndroid/nav-core/src/main/java/com/izhxx/navcore/domain/model/location/MapCoordinates.kt
ZhevlakovII
507,916,442
false
null
package com.izhxx.navcore.domain.model.location /** * Дата-класс для координа локации. Применяется на карту и зависит от её размеров * @param startAxisX - Стартовая координата по оХ/оY * @param endAxisX - Конечная координата по оХ/oY * @param centerAxisX - Точка в центре локации. * Координаты задаются как по оси Х, так и по оси Y. */ data class MapCoordinates( val startAxisX: Double, val centerAxisX: Double, val endAxisX: Double, val startAxisY: Double, val centerAxisY: Double, val endAxisY: Double, var currentAxisX: Double? = null, var currentAxisY: Double? = null ) { fun matchAxisX(x: Double): Boolean = x in startAxisX..endAxisX fun matchAxisY(y: Double): Boolean = y in startAxisY..endAxisY }
2
Kotlin
0
1
c59bbb793ee28057f49392eab36206a05909265b
752
IndoorNavigation
MIT License
src/test/kotlin/de/flapdoodle/photosync/filehash/HashStrategyTest.kt
flapdoodle-oss
231,620,257
false
null
package de.flapdoodle.photosync.filehash import de.flapdoodle.io.tree.Tree import de.flapdoodle.photosync.Blob import de.flapdoodle.photosync.LastModified import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.nio.file.Path class HashStrategyTest { @Test fun `single group if hashStrategy provides no hasher`() { val blobs = listOf( Blob(Path.of("foo","bar"),0,now()), Blob(Path.of("foo","baz"),1,now()) ) val result = HashStrategy.groupBlobs(HashStrategy { emptyList() }, blobs) assertThat(result).size().isEqualTo(1) .returnToMap() .containsValues(blobs) } @Test fun `group blobs by hash`() { val blobBarA = Blob(Path.of("foo", "bar"), 0, now()) val blobBarB = Blob(Path.of("blob", "bar"), 1, now()) val blobBaz = Blob(Path.of("foo", "baz"), 1, now()) val blobs = listOf( blobBarA, blobBarB, blobBaz ) val result = HashStrategy.groupBlobs(HashStrategy { listOf(HashFilename(), HashSize()) }, blobs) assertThat(result) .containsKey(FilenameHash("baz")) .containsKey(FilenameHash("bar").append(SizeHash(0))) .containsKey(FilenameHash("bar").append(SizeHash(1))) .size().isEqualTo(3) .returnToMap() .containsEntry(FilenameHash("baz"), listOf(blobBaz)) .containsEntry(FilenameHash("bar").append(SizeHash(0)), listOf(blobBarA)) .containsEntry(FilenameHash("bar").append(SizeHash(1)), listOf(blobBarB)) } @Test fun `group files by hash`() { val fileBarA = Tree.File(Path.of("foo", "bar"), 0, now()) val fileBarB = Tree.File(Path.of("blob", "bar"), 1, now()) val fileBaz = Tree.File(Path.of("foo", "baz"), 1, now()) val files = listOf( fileBarA, fileBarB, fileBaz ) val result = HashStrategy.groupBy(listOf(HashFilename(), HashSize()), files) assertThat(result) .containsKey(FilenameHash("baz")) .containsKey(FilenameHash("bar").append(SizeHash(0))) .containsKey(FilenameHash("bar").append(SizeHash(1))) .size().isEqualTo(3) .returnToMap() .containsEntry(FilenameHash("baz"), listOf(fileBaz)) .containsEntry(FilenameHash("bar").append(SizeHash(0)), listOf(fileBarA)) .containsEntry(FilenameHash("bar").append(SizeHash(1)), listOf(fileBarB)) } data class FilenameHash(val key: String) : Hash<FilenameHash> data class SizeHash(val key: Long) : Hash<SizeHash> class HashFilename : Hasher<FilenameHash> { override fun hash(path: Path, size: Long): FilenameHash { return FilenameHash(path.fileName.toString()) } } class HashSize : Hasher<SizeHash> { override fun hash(path: Path, size: Long): SizeHash { return SizeHash(size) } } private fun now(): LastModified { return LastModified.now() } }
1
null
1
1
2c39e73edb0d1eefd277c1e31d2ed7042cf62029
2,931
photosync
Apache License 2.0
libraries/stdlib/test/time/TimeMarkTest.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:OptIn(ExperimentalTime::class) package test.time import kotlin.test.* import kotlin.time.* import kotlin.time.Duration.Companion.microseconds import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.nanoseconds class TimeMarkTest { @Test fun adjustment() { val timeSource = TestTimeSource() fun TimeMark.assertHasPassed(hasPassed: Boolean) { assertEquals(!hasPassed, this.hasNotPassedNow(), "Expected mark in the future") assertEquals(hasPassed, this.hasPassedNow(), "Expected mark in the past") assertEquals( !hasPassed, this.elapsedNow() < Duration.ZERO, "Mark elapsed: ${this.elapsedNow()}, expected hasPassed: $hasPassed" ) } val mark = timeSource.markNow() val markFuture1 = (mark + 1.milliseconds).apply { assertHasPassed(false) } val markFuture2 = (mark - (-1).milliseconds).apply { assertHasPassed(false) } val markPast1 = (mark - 1.milliseconds).apply { assertHasPassed(true) } val markPast2 = (markFuture1 + (-2).milliseconds).apply { assertHasPassed(true) } timeSource += 500_000.nanoseconds val elapsed = mark.elapsedNow() val elapsedFromFuture = elapsed - 1.milliseconds val elapsedFromPast = elapsed + 1.milliseconds assertEquals(0.5.milliseconds, elapsed) assertEquals(elapsedFromFuture, markFuture1.elapsedNow()) assertEquals(elapsedFromFuture, markFuture2.elapsedNow()) assertEquals(elapsedFromPast, markPast1.elapsedNow()) assertEquals(elapsedFromPast, markPast2.elapsedNow()) markFuture1.assertHasPassed(false) markPast1.assertHasPassed(true) timeSource += 1.milliseconds markFuture1.assertHasPassed(true) markPast1.assertHasPassed(true) } fun testAdjustmentInfinite(timeSource: TimeSource) { val baseMark = timeSource.markNow() val infiniteFutureMark = baseMark + Duration.INFINITE val infinitePastMark = baseMark - Duration.INFINITE assertEquals(-Duration.INFINITE, infiniteFutureMark.elapsedNow()) assertTrue(infiniteFutureMark.hasNotPassedNow()) assertEquals(Duration.INFINITE, infinitePastMark.elapsedNow()) assertTrue(infinitePastMark.hasPassedNow()) assertFailsWith<IllegalArgumentException> { infiniteFutureMark - Duration.INFINITE } assertFailsWith<IllegalArgumentException> { infinitePastMark + Duration.INFINITE } val longDuration = Long.MAX_VALUE.nanoseconds val long2Duration = longDuration * 2 val pastMark = baseMark - longDuration val futureMark = pastMark + long2Duration val sameMark = futureMark - longDuration val elapsedDiff = sameMark.elapsedNow() - baseMark.elapsedNow() assertTrue(elapsedDiff < 1.milliseconds, "$elapsedDiff") } @Test fun adjustmentInfinite() { testAdjustmentInfinite(TestTimeSource()) } fun testLongDisplacement(timeSource: TimeSource, wait: (Duration) -> Unit) { val baseMark = timeSource.markNow() val longDuration = Long.MAX_VALUE.nanoseconds val waitDuration = 10.milliseconds val pastMark = baseMark - longDuration wait(waitDuration) val elapsed = pastMark.elapsedNow() assertTrue(elapsed > longDuration) assertTrue(elapsed >= longDuration + waitDuration) } @Test fun longDisplacement() { val timeSource = TestTimeSource() testLongDisplacement(timeSource, { waitDuration -> timeSource += waitDuration }) } @Test fun defaultTimeMarkAdjustment() { val baseMark = TimeSource.Monotonic.markNow() var markBefore = baseMark markBefore -= 100.microseconds markBefore -= 100.microseconds val markAfter = baseMark + 100.microseconds MeasureTimeTest.longRunningCalc() val elapsedAfter = markAfter.elapsedNow() val elapsedBase = baseMark.elapsedNow() val elapsedBefore = markBefore.elapsedNow() assertTrue(elapsedBefore >= elapsedBase + 200.microseconds) assertTrue(elapsedAfter <= elapsedBase - 100.microseconds) } @Test fun defaultTimeMarkAdjustmentInfinite() { testAdjustmentInfinite(TimeSource.Monotonic) // do the same with specialized methods val baseMark = TimeSource.Monotonic.markNow() val infiniteFutureMark = baseMark + Duration.INFINITE val infinitePastMark = baseMark - Duration.INFINITE assertEquals(-Duration.INFINITE, infiniteFutureMark.elapsedNow()) assertTrue(infiniteFutureMark.hasNotPassedNow()) assertEquals(Duration.INFINITE, infinitePastMark.elapsedNow()) assertTrue(infinitePastMark.hasPassedNow()) assertFailsWith<IllegalArgumentException> { infiniteFutureMark - Duration.INFINITE } assertFailsWith<IllegalArgumentException> { infinitePastMark + Duration.INFINITE } val longDuration = Long.MAX_VALUE.nanoseconds val long2Duration = longDuration * 2 val pastMark = baseMark - longDuration val futureMark = pastMark + long2Duration val sameMark = futureMark - longDuration val elapsedDiff = sameMark.elapsedNow() - baseMark.elapsedNow() assertTrue(elapsedDiff < 1.milliseconds, "$elapsedDiff") } }
157
Kotlin
5209
42,102
65f712ab2d54e34c5b02ffa3ca8c659740277133
5,657
kotlin
Apache License 2.0
restx-samplest-kotlin/src/main/java/samplest/hello/HeaderResource.kt
restx
9,836,833
false
{"Java": 1648842, "Less": 149456, "JavaScript": 109081, "HTML": 71380, "CSS": 19545, "Mustache": 12835, "Kotlin": 6385, "Shell": 1276}
package samplest.hello import restx.RestxRequest import restx.annotations.GET import restx.annotations.Param import restx.annotations.RestxResource import restx.factory.Component /** * Created by xhanin on 13/01/2018. */ @Component @RestxResource class HeaderResource { @GET("/headers") fun headers(@Param(kind = Param.Kind.CONTEXT) request: RestxRequest): Map<String, String> = request.headers }
43
Java
81
444
f7fefe8ae398a638d226d57878b698f18e92989d
408
restx
Apache License 2.0
watchlist/src/main/java/com/pyamsoft/tickertape/watchlist/add/WatchlistAddViewModel.kt
pyamsoft
371,196,339
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.tickertape.watchlist.add import com.pyamsoft.pydroid.arch.UiSavedState import com.pyamsoft.pydroid.arch.UiSavedStateViewModelProvider import com.pyamsoft.tickertape.main.add.SymbolAddInteractor import com.pyamsoft.tickertape.main.add.SymbolAddViewModel import com.pyamsoft.tickertape.quote.TickerInteractor import com.pyamsoft.tickertape.stocks.api.EquityType import com.pyamsoft.tickertape.stocks.api.StockQuote import com.pyamsoft.tickertape.stocks.api.TradeSide import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import timber.log.Timber class WatchlistAddViewModel @AssistedInject internal constructor( @Assisted savedState: UiSavedState, private val interactor: WatchlistAddInteractor, addInteractor: SymbolAddInteractor, tickerInteractor: TickerInteractor, equityType: EquityType, tradeSide: TradeSide, ) : SymbolAddViewModel( savedState, addInteractor, tickerInteractor, equityType, tradeSide, ) { override suspend fun onCommitSymbol(stock: StockQuote) { val symbol = stock.symbol() Timber.d("Commit symbol to DB: $symbol") interactor.commitSymbol(symbol).onSuccess { Timber.d("Committed symbols: $symbol") }.onFailure { Timber.e(it, "Error committing symbols: $symbol") } } @AssistedFactory interface Factory : UiSavedStateViewModelProvider<WatchlistAddViewModel> { override fun create(savedState: UiSavedState): WatchlistAddViewModel } }
5
Kotlin
0
1
54ea8e2b452da10d87a79c37fa72a0a7f70d8c5c
2,129
tickertape
Apache License 2.0
app/src/main/kotlin/com/flxrs/dankchat/data/api/helix/dto/CommercialRequestDto.kt
flex3r
186,238,019
false
{"Kotlin": 977613}
package com.flxrs.dankchat.data.api.helix.dto import androidx.annotation.Keep import com.flxrs.dankchat.data.UserId import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Keep @Serializable data class CommercialRequestDto(@SerialName("broadcaster_id") val broadcastUserId: UserId, val length: Int)
73
Kotlin
37
266
49d86a05f3bba655881e6e93360f216316cee7c9
328
DankChat
MIT License
confluence-plugin/src/main/java/com/networkedassets/git4c/core/GetPredefinedRepositoryUseCase.kt
rpaasche
321,741,515
true
{"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716}
package com.networkedassets.git4c.core import com.networkedassets.git4c.application.BussinesPluginComponents import com.networkedassets.git4c.boundary.GetPredefinedRepositoryCommand import com.networkedassets.git4c.boundary.GetPredefinedRepositoryResultRequest import com.networkedassets.git4c.boundary.outbound.PredefinedRepository import com.networkedassets.git4c.boundary.outbound.VerificationStatus import com.networkedassets.git4c.boundary.outbound.exceptions.NotFoundException import com.networkedassets.git4c.core.bussiness.ComputationCache import com.networkedassets.git4c.core.bussiness.SourcePlugin import com.networkedassets.git4c.core.datastore.repositories.PredefinedRepositoryDatabase import com.networkedassets.git4c.core.datastore.repositories.RepositoryDatabase import com.networkedassets.git4c.core.usecase.async.ComputationResultUseCase import com.networkedassets.git4c.core.usecase.async.MultiThreadAsyncUseCase import com.networkedassets.git4c.data.Repository import com.networkedassets.git4c.data.RepositoryWithNoAuthorization import com.networkedassets.git4c.data.RepositoryWithSshKey import com.networkedassets.git4c.data.RepositoryWithUsernameAndPassword class GetPredefinedRepositoryUseCase( components: BussinesPluginComponents, val predefinedRepositoryDatabase: PredefinedRepositoryDatabase = components.database.predefinedRepositoryDatabase, val repositoryDatabase: RepositoryDatabase = components.providers.repositoryProvider, val importer: SourcePlugin = components.macro.importer, computations: ComputationCache<PredefinedRepository> = components.async.getPredefinedRepositoryUseCaseCache ) : MultiThreadAsyncUseCase<GetPredefinedRepositoryCommand, PredefinedRepository> (components, computations, 2) { override fun executedAsync(requestId: String, request: GetPredefinedRepositoryCommand) { val predefinedRepository = predefinedRepositoryDatabase.get(request.repositoryId) ?: return error(requestId, NotFoundException(request.transactionInfo, VerificationStatus.REMOVED)) val repository = repositoryDatabase.get(predefinedRepository.repositoryUuid) ?: return error(requestId, NotFoundException(request.transactionInfo, VerificationStatus.REMOVED)) importer.verify(repository).apply { if (isOk()) { return success(requestId, PredefinedRepository(predefinedRepository.uuid, repository.repositoryPath, authType(repository), predefinedRepository.name, repository.isEditable)) } else { return error(requestId, IllegalArgumentException(status.name)) } } return error(requestId, NotFoundException(request.transactionInfo, VerificationStatus.REMOVED)) } private fun authType(repository: Repository) = when (repository) { is RepositoryWithNoAuthorization -> "NOAUTH" is RepositoryWithUsernameAndPassword -> "USERNAMEANDPASSWORD" is RepositoryWithSshKey -> "SSHKEY" else -> throw RuntimeException("Unknown auth type: ${repository.javaClass}") } } class GetPredefinedRepositoryResultUseCase( components: BussinesPluginComponents, computations: ComputationCache<PredefinedRepository> = components.async.getPredefinedRepositoryUseCaseCache ) : ComputationResultUseCase<GetPredefinedRepositoryResultRequest, PredefinedRepository>(components, computations)
0
Kotlin
0
0
e55391b33cb70d66bbf5f36ba570fb8822f10953
3,425
git4c
Apache License 2.0
data/src/main/java/com/wasin/data/model/company/SaveCompanyByOpenAPIRequest.kt
wa-sin-sang-dam
828,217,645
false
{"Kotlin": 342772}
package com.wasin.data.model.company import kotlinx.serialization.Serializable @Serializable data class SaveCompanyByOpenAPIRequest ( val serviceKey: String = "", val companyFssId: String = "", val location: String = "", val companyName: String = "" )
0
Kotlin
0
0
3931b34962fe857b8accd5f922b0f5df1add2595
270
wasin-android
MIT License
mbcarkit/src/main/java/com/daimler/mbcarkit/business/model/vehicle/SpeedUnitType.kt
Daimler
199,815,262
false
null
package com.daimler.mbcarkit.business.model.vehicle enum class SpeedUnitType { KM, MILES, UNKNOWN }
1
null
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
113
MBSDK-Mobile-Android
MIT License
app/src/main/java/com/example/events/domain/di/DomainModule.kt
diegoleonds
369,679,332
false
null
package com.example.events.domain.di import com.example.events.domain.transform.EventPersonTransform import com.example.events.domain.usecase.JoinEventUseCase import org.koin.dsl.module val domainModule = module { factory { EventPersonTransform() } factory { JoinEventUseCase(get(), get()) } }
0
Kotlin
0
0
d3b906fd44d1fab03bbc9449c218a668258c732d
303
Events-App
MIT License
src/main/kotlin/br/com/ot6/BcbClient.kt
Josh-Andrade
397,634,098
true
{"Kotlin": 55018}
package br.com.ot6 import br.com.ot6.bcb.CreatePixKeyRequest import br.com.ot6.bcb.DeletePixKey import br.com.ot6.bcb.PixKeyDetailsResponse import io.micronaut.http.HttpResponse import io.micronaut.http.MediaType import io.micronaut.http.annotation.* import io.micronaut.http.client.annotation.Client @Client("\${http.services.bcb.url}") interface BcbClient { @Post("/api/v1/pix/keys") @Produces(MediaType.APPLICATION_XML) @Consumes(MediaType.APPLICATION_XML) fun registerPixKey(@Body createPixKeyRequest: CreatePixKeyRequest?): HttpResponse<PixKeyDetailsResponse> @Delete("/api/v1/pix/keys/{key}") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) fun deletePixKey(@QueryValue key: String, @Body deletePixKey: DeletePixKey): HttpResponse<DeletePixKey> @Get("/api/v1/pix/keys/{key}") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) fun findPixKey(@QueryValue key: String): HttpResponse<PixKeyDetailsResponse> }
0
Kotlin
0
0
85fc0319a8198ab15cb4c0bd0a49a24b76c4769d
1,014
orange-talents-06-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/com/example/tracking_app/database/dao/RoadMapDao.kt
yassine-zouhri
373,333,286
false
null
package com.example.tracking_app.database.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.tracking_app.database.models.RoadMapEntity @Dao interface RoadMapDao { @Query("SELECT * FROM roadMap_table ") fun getRoadMaps1() : List<RoadMapEntity> @Query("SELECT * FROM roadMap_table ") fun getRoadMaps() : LiveData<List<RoadMapEntity>> @Query("SELECT * FROM roadMap_table WHERE idAgentRoadMap=(:id)") fun getRoapMapByIdAgentRoadMap(id : Long) : RoadMapEntity @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun addRoadMap(roadMap : RoadMapEntity) @Query("DELETE FROM roadMap_table WHERE idAgentRoadMap=(:id) ") suspend fun deleteRoadMap(id : Long) @Query("DELETE FROM roadMap_table") suspend fun deleteAllRoadMap() }
0
Kotlin
0
0
88d1c899814e9e3b6df86833dab19b5853963d8f
908
AppMobilePFE
MIT License
framework/src/main/java/com/gw/mvvm/framework/core/ActivityManger.kt
play0451
347,845,609
false
null
package com.gw.mvvm.framework.core import android.app.Activity import java.util.* /** * Activity管理单例类 */ object ActivityManger { private val activityList = LinkedList<Activity>() private val currentActivity: Activity? get() = if (activityList.isEmpty()) null else activityList.last /** * activity入栈 */ fun pushActivity(activity: Activity) { if (activityList.contains(activity)) { if (activityList.last != activity) { activityList.remove(activity) activityList.add(activity) } } else { activityList.add(activity) } } /** * activity出栈 */ fun popActivity(activity: Activity) { activityList.remove(activity) } /** * 关闭当前activity */ fun finishCurrentActivity() { currentActivity?.finish() } /** * 关闭传入的activity */ fun finishActivity(activity: Activity) { activityList.remove(activity) activity.finish() } /** * 关闭传入的activity类名 */ fun finishActivity(clazz: Class<*>) { for (activity in activityList) if (activity.javaClass == clazz) activity.finish() } /** * 关闭所有的activity */ fun finishAllActivity() { for (activity in activityList) activity.finish() } }
0
Kotlin
0
0
bbf15ccf5eddb470f3841a97d79c76a867c213fd
1,410
wan-android-jetpack-mvvm-practice
MIT License
lint/src/main/java/org/simple/clinic/lint/TextViewTextSizeDetector.kt
simpledotorg
132,515,649
false
{"Kotlin": 6129044, "Shell": 1660, "HTML": 545}
package org.simple.clinic.lint import com.android.SdkConstants.ANDROID_URI import com.android.SdkConstants.ATTR_TEXT_SIZE import com.android.SdkConstants.TEXT_VIEW import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.ResourceXmlDetector import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.XmlContext import org.w3c.dom.Element class TextViewTextSizeDetector : ResourceXmlDetector() { companion object { private const val TextViewTextSizeExplanation = "Please use `android:textAppearance` for setting the text style instead of setting the text size" val TextViewTextSizeIssue = Issue.create( id = "TextViewTextSize", briefDescription = "Use `android:textAppearance` for applying the text style", explanation = TextViewTextSizeExplanation, category = Category.CORRECTNESS, severity = Severity.ERROR, implementation = Implementation( TextViewTextSizeDetector::class.java, Scope.RESOURCE_FILE_SCOPE ), androidSpecific = true ) } override fun getApplicableElements() = listOf(TEXT_VIEW) override fun visitElement(context: XmlContext, element: Element) { if (element.hasAttributeNS(ANDROID_URI, ATTR_TEXT_SIZE)) { reportSrcIssue(context, element) } } private fun reportSrcIssue(context: XmlContext, element: Element) { context.report( TextViewTextSizeIssue, element, context.getLocation(element.getAttributeNodeNS(ANDROID_URI, ATTR_TEXT_SIZE)), TextViewTextSizeExplanation ) } }
6
Kotlin
73
236
ff699800fbe1bea2ed0492df484777e583c53714
1,789
simple-android
MIT License
src/main/kotlin/io/framed/framework/model/ModelElement.kt
Eden-06
138,000,306
false
{"Kotlin": 675525, "SCSS": 21894, "HTML": 768}
package io.framed.framework.model import kotlinx.serialization.Serializable /** * Base class for all model elements. * * @author lars */ @Serializable abstract class ModelElement { val id: Long = lastId++ abstract fun copy(): ModelElement open fun maxId(): Long = id companion object { var lastId: Long = 0 } } inline fun <reified T: ModelElement> T.copyGeneric():T { val element = copy() if (element is T) return element throw IllegalStateException() }
5
Kotlin
1
2
27f4a4c44d90f20f748ab779c3c184cb012a59fe
506
FRaMED-io
MIT License
src/main/kotlin/com/github/goldsubmarine/restfulhelper/utils/CommonUtils.kt
GoldSubmarine
394,201,620
false
null
package com.viartemev.requestmapper.utils fun String.unquote(): String = if (length >= 2 && first() == '"' && last() == '"') substring(1, this.length - 1) else this fun String.inCurlyBrackets(): Boolean = length >= 2 && first() == '{' && last() == '}' fun String.unquoteCurlyBrackets(): String = if (this.inCurlyBrackets()) this.drop(1).dropLast(1) else this fun String.addCurlyBrackets(): String = "{$this}" fun List<String>.dropFirstEmptyStringIfExists(): List<String> = if (this.isNotEmpty() && this.first().isEmpty()) this.drop(1) else this fun String.isNumeric(): Boolean = this.toBigDecimalOrNull() != null
16
null
4
9
9d187542a38548a353625ea06201075d001ef8b9
619
RestfulHelper
MIT License
src/main/kotlin/com/github/goldsubmarine/restfulhelper/utils/CommonUtils.kt
GoldSubmarine
394,201,620
false
null
package com.viartemev.requestmapper.utils fun String.unquote(): String = if (length >= 2 && first() == '"' && last() == '"') substring(1, this.length - 1) else this fun String.inCurlyBrackets(): Boolean = length >= 2 && first() == '{' && last() == '}' fun String.unquoteCurlyBrackets(): String = if (this.inCurlyBrackets()) this.drop(1).dropLast(1) else this fun String.addCurlyBrackets(): String = "{$this}" fun List<String>.dropFirstEmptyStringIfExists(): List<String> = if (this.isNotEmpty() && this.first().isEmpty()) this.drop(1) else this fun String.isNumeric(): Boolean = this.toBigDecimalOrNull() != null
16
null
4
9
9d187542a38548a353625ea06201075d001ef8b9
619
RestfulHelper
MIT License
app-tracking-protection/vpn-impl/src/main/java/com/duckduckgo/mobile/android/vpn/ui/notification/VpnEnabledNotificationBuilder.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2020 DuckDuckGo * * 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.duckduckgo.mobile.android.vpn.ui.notification import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager.IMPORTANCE_LOW import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.duckduckgo.mobile.android.vpn.R import com.duckduckgo.mobile.android.vpn.service.VpnActionReceiver import com.duckduckgo.mobile.android.vpn.service.VpnEnabledNotificationContentPlugin import com.duckduckgo.mobile.android.vpn.service.VpnEnabledNotificationContentPlugin.NotificationActions import com.duckduckgo.mobile.android.vpn.service.VpnEnabledNotificationContentPlugin.NotificationActions.VPNActions import com.duckduckgo.mobile.android.vpn.service.VpnEnabledNotificationContentPlugin.NotificationActions.VPNFeatureActions class VpnEnabledNotificationBuilder { companion object { private const val VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_ID = "com.duckduckgo.mobile.android.vpn.notification.ongoing.v2" private const val VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_NAME = "App Tracking Protection Status" private const val VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_DESCRIPTION = "Ongoing state of App Tracking Protection" private fun registerOngoingNotificationChannel(context: Context) { val channel = NotificationChannel( VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_ID, VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_NAME, IMPORTANCE_LOW, ) channel.setShowBadge(false) channel.description = VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_DESCRIPTION val notificationManager = NotificationManagerCompat.from(context) notificationManager.createNotificationChannel(channel) /** * We needed to create a new channel to fix: https://app.asana.com/0/488551667048375/1206484244032061/f */ notificationManager.deleteNotificationChannel("com.duckduckgo.mobile.android.vpn.notification.ongoing") } fun buildVpnEnabledNotification( context: Context, vpnEnabledNotificationContent: VpnEnabledNotificationContentPlugin.VpnEnabledNotificationContent, ): Notification { registerOngoingNotificationChannel(context) return NotificationCompat.Builder(context, VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_ID) .setSmallIcon(com.duckduckgo.mobile.android.R.drawable.notification_logo) .setContentTitle(context.getString(R.string.atp_name)) .setStyle(NotificationCompat.BigTextStyle().bigText(vpnEnabledNotificationContent.title)) .setContentIntent(vpnEnabledNotificationContent.onNotificationPressIntent) .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_LOW) .setChannelId(VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_ID) .setCategory(NotificationCompat.CATEGORY_SERVICE) .build() } fun buildVpnEnabledUpdateNotification( context: Context, vpnNotification: VpnEnabledNotificationContentPlugin.VpnEnabledNotificationContent, ): Notification { registerOngoingNotificationChannel(context) return NotificationCompat.Builder(context, VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_ID) .setSmallIcon(com.duckduckgo.mobile.android.R.drawable.notification_logo) .setStyle(NotificationCompat.BigTextStyle().bigText(vpnNotification.text)) .setContentTitle(vpnNotification.title) .setContentIntent(vpnNotification.onNotificationPressIntent) .setPriority(NotificationCompat.PRIORITY_LOW) .setSilent(true) .setOngoing(true) .addNotificationActions(context, vpnNotification.notificationActions) .setChannelId(VPN_FOREGROUND_SERVICE_NOTIFICATION_CHANNEL_ID) .setCategory(NotificationCompat.CATEGORY_SERVICE) .setDeleteIntentIfValid(vpnNotification.deleteIntent) .build() } private fun NotificationCompat.Builder.setDeleteIntentIfValid(deleteIntent: PendingIntent?): NotificationCompat.Builder { if (deleteIntent != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { this.setDeleteIntent(deleteIntent) } return this } private fun NotificationCompat.Builder.addNotificationActions( context: Context, notificationActions: NotificationActions, ): NotificationCompat.Builder { when (notificationActions) { is VPNActions -> getVpnActions(context) is VPNFeatureActions -> notificationActions.actions.take(2) }.onEach { action -> addAction(action) } return this } private fun getVpnActions( context: Context, ): List<NotificationCompat.Action> { return listOf( NotificationCompat.Action( R.drawable.ic_baseline_feedback_24, context.getString(R.string.vpn_NotificationCTASnoozeVpn), PendingIntent.getBroadcast( context, 0, Intent(context, VpnActionReceiver::class.java).apply { action = VpnActionReceiver.ACTION_VPN_SNOOZE }, PendingIntent.FLAG_IMMUTABLE, ), ), NotificationCompat.Action( R.drawable.ic_baseline_feedback_24, context.getString(R.string.vpn_NotificationCTADisableVpn), PendingIntent.getBroadcast( context, 1, Intent(context, VpnActionReceiver::class.java).apply { action = VpnActionReceiver.ACTION_VPN_DISABLE }, PendingIntent.FLAG_IMMUTABLE, ), ), ) } } }
67
null
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
7,101
Android
Apache License 2.0
home/src/main/java/com/pabloangeles/hackernewsapp/home/data/di/HomeModule.kt
PabloJair
551,790,924
false
{"Kotlin": 68936}
package com.pabloangeles.hackernewsapp.home.data.di import com.pabloangeles.hackernewsapp.core.local.HackerNewsDatabase import com.pabloangeles.hackernewsapp.core.local.dao.NewsHitsDao import com.pabloangeles.hackernewsapp.home.data.services.NewHitsService import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import javax.inject.Named import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class HomeModule { @Singleton @Provides fun provideCurrencyService(@Named("retrofit") retrofit: Retrofit): NewHitsService = retrofit.create(NewHitsService::class.java) @Singleton @Provides fun provideNewsHitsDao(@Named("hacker_news_db") db: HackerNewsDatabase): NewsHitsDao = db.newsHitsEntityDao() }
0
Kotlin
0
0
a88fc09a8d5c8cbea13e598c2c75513a95533678
835
hacks_news-demo
MIT License
buildSrc/src/dependencies.kt
wanghoa
204,402,514
true
{"Java": 93265, "Kotlin": 13390}
import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.plugin.use.PluginDependenciesSpec fun DependencyHandler.android() = "com.android.tools.build:gradle:3.5.0-beta03" fun PluginDependenciesSpec.android(submodule: String) = id("com.android.$submodule") fun DependencyHandler.androidx( repository: String, module: String = repository, version: String = VERSION_ANDROIDX ) = "androidx.$repository:$module:$version" fun DependencyHandler.material( version: String = VERSION_ANDROIDX ) = "com.google.android.material:material:$version" fun DependencyHandler.hendraanggrian( repository: String, module: String = repository, version: String ) = "com.hendraanggrian.$repository:$module:$version" fun DependencyHandler.jakeWharton( module: String, version: String ) = "com.jakewharton:$module:$version" fun DependencyHandler.truth() = "com.google.truth:truth:0.44" fun DependencyHandler.bintray() = "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4" inline val PluginDependenciesSpec.bintray get() = id("com.jfrog.bintray") fun DependencyHandler.bintrayRelease() = "com.novoda:bintray-release:0.9.1" inline val PluginDependenciesSpec.`bintray-release` get() = id("com.novoda.bintray-release")
0
Java
0
0
55951219406a75f9d36baf50a5f85dc05cbd11d4
1,251
collapsingtoolbarlayout-subtitle
Apache License 2.0
app/app/src/main/java/xyz/mirage/app/presentation/ui/shared/GenericDialog.kt
sentrionic
378,704,735
false
null
package xyz.mirage.app.presentation.ui.shared import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.AlertDialog import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import xyz.mirage.app.business.domain.core.NegativeAction import xyz.mirage.app.business.domain.core.PositiveAction @Composable fun GenericDialog( modifier: Modifier = Modifier, onDismiss: (() -> Unit)?, title: String, description: String? = null, positiveAction: PositiveAction?, negativeAction: NegativeAction?, onRemoveHeadFromQueue: () -> Unit, isDarkTheme: Boolean, ) { AlertDialog( modifier = modifier, onDismissRequest = { onDismiss?.invoke() onRemoveHeadFromQueue() }, title = { Text( text = title, fontSize = 20.sp, fontWeight = FontWeight.Bold ) }, text = { if (description != null) { Text( text = description, fontSize = 16.sp, ) } }, buttons = { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.End, ) { if (negativeAction != null) { TextButton( modifier = Modifier.padding(end = 8.dp), onClick = { negativeAction.onNegativeAction() onRemoveHeadFromQueue() }, ) { Text( text = negativeAction.negativeBtnTxt, color = if (isDarkTheme) Color.White else Color.Black, ) } } if (positiveAction != null) { Button( modifier = Modifier.padding(end = 8.dp), onClick = { positiveAction.onPositiveAction() onRemoveHeadFromQueue() }, ) { Text( text = positiveAction.positiveBtnTxt, color = Color.White, ) } } } } ) }
0
Kotlin
2
1
8f50fc8244f16b43b8e054e79bcd50e98765a0e1
2,979
Mirage
MIT License
app/src/main/java/org/phcbest/neteasymusic/base/IBaseCallBack.kt
phcbest
471,621,513
false
null
package org.phcbest.neteasymusic.base interface IBaseCallBack { /** * 失败调用 */ fun onError() /** * 加载调用 */ fun onLoading() /** * 请求成功但数据为null调用 */ fun onEmpty() }
0
Kotlin
1
2
d94a834216d24f81ee5e2e35b0c54ef6da8b50af
218
KotlinNetEasyMusic
MIT License
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/taskschedule/command/handler/CreateTaskScheduleCommandHandler.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: Robert Bosch Power Tools GmbH, 2018 - 2023 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.project.taskschedule.command.handler import com.bosch.pt.csm.cloud.common.command.snapshotstore.VersionedSnapshot.Companion.INITIAL_SNAPSHOT_VERSION import com.bosch.pt.csm.cloud.common.exceptions.PreconditionViolationException import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskScheduleEventEnumAvro import com.bosch.pt.iot.smartsite.common.i18n.Key.TASK_SCHEDULE_VALIDATION_ERROR_ALREADY_EXISTS import com.bosch.pt.iot.smartsite.project.eventstore.ProjectContextLocalEventBus import com.bosch.pt.iot.smartsite.project.taskschedule.command.api.CreateTaskScheduleCommand import com.bosch.pt.iot.smartsite.project.taskschedule.command.handler.helper.TaskScheduleCommandHandlerHelper import com.bosch.pt.iot.smartsite.project.taskschedule.command.snapshotstore.TaskScheduleSnapshot import com.bosch.pt.iot.smartsite.project.taskschedule.domain.TaskScheduleId import com.bosch.pt.iot.smartsite.project.taskschedule.facade.rest.resource.request.TaskScheduleSlotDto import datadog.trace.api.Trace import org.springframework.security.access.prepost.PreAuthorize import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional @Component open class CreateTaskScheduleCommandHandler( private val eventBus: ProjectContextLocalEventBus, private val taskScheduleCommandHandlerHelper: TaskScheduleCommandHandlerHelper ) { @Trace @Transactional @PreAuthorize("@taskAuthorizationComponent.hasEditPermissionOnTask(#command.taskIdentifier)") open fun handle(command: CreateTaskScheduleCommand): TaskScheduleId { val task = taskScheduleCommandHandlerHelper.findTaskOrFail(command) if (task.taskSchedule != null) { throw PreconditionViolationException(TASK_SCHEDULE_VALIDATION_ERROR_ALREADY_EXISTS) } val slots = command.slots?.map { TaskScheduleSlotDto(it.key, it.value) } ?: listOf() taskScheduleCommandHandlerHelper.validateTaskSchedule(command.start, command.end, slots) taskScheduleCommandHandlerHelper.updateSlotOrder(slots.toMutableList()) val project = taskScheduleCommandHandlerHelper.findProjectOrFail(task.project.identifier) return TaskScheduleSnapshot( identifier = command.identifier, version = INITIAL_SNAPSHOT_VERSION, projectIdentifier = project.identifier, start = command.start, end = command.end, taskIdentifier = task.identifier, slots = slots) .toCommandHandler() .emitEvent(TaskScheduleEventEnumAvro.CREATED) .to(eventBus) .andReturnSnapshot() .identifier } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
2,880
bosch-pt-refinemysite-backend
Apache License 2.0
src/test/kotlin/sqlproxy/jdbc/SQLProxyConnectionTest.kt
dustinliu
227,580,613
false
null
package sqlproxy.jdbc; import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import sqlproxy.client.SQLProxyDriver import sqlproxy.client.parseUrl class SQLProxyConnectionTest { @Test fun `test parseUrl`() { val url = SQLProxyDriver.prefix + "//localhost:8080" val pair = parseUrl(url) assertEquals("localhost", pair.first) assertEquals(8080, pair.second) } }
0
Kotlin
0
0
bf8ccc35c73e36c941ec6dcb3770b22aa65b0e59
441
sqlproxy
MIT License
app/src/main/java/com/coderbdk/tictactoe/ui/home/HomeScreen.kt
CoderBDK
828,847,363
false
{"Kotlin": 74767}
package com.coderbdk.tictactoe.ui.home import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement 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.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountBox import androidx.compose.material.icons.filled.LocationOn import androidx.compose.material.icons.filled.Person import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ElevatedButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.Dimension import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import com.coderbdk.tictactoe.R import com.coderbdk.tictactoe.Screen import com.coderbdk.tictactoe.navigate import com.coderbdk.tictactoe.ui.theme.TicTacToeTheme import java.util.Locale @Composable fun HomeScreen(navController: NavController) { val configuration = LocalConfiguration.current val isLandscape = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE ConstraintLayout( modifier = Modifier .fillMaxSize() .background( brush = Brush.linearGradient( listOf( colorScheme.primaryContainer, colorScheme.surfaceDim, colorScheme.primaryContainer ) ) ) ) { val (share, settings, sound, help, menu) = createRefs() ElevatedButton( modifier = Modifier .padding(8.dp) .constrainAs(share) { start.linkTo(parent.start) top.linkTo(parent.top) }, shape = RoundedCornerShape(8.dp), onClick = { /*TODO*/ }) { Text(text = "Share") } ElevatedButton( modifier = Modifier .padding(8.dp) .constrainAs(settings) { end.linkTo(parent.end) top.linkTo(parent.top) }, shape = RoundedCornerShape(8.dp), onClick = { /*TODO*/ }) { Text(text = "Settings") } Column( modifier = Modifier .constrainAs(menu) { start.linkTo(parent.start) top.linkTo(share.bottom) end.linkTo(parent.end) bottom.linkTo(sound.top) height = Dimension.fillToConstraints }, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( modifier = Modifier .padding(bottom = 40.dp), text = "Tic \nTac Toe", fontSize = 64.sp, lineHeight = 64.sp, textAlign = TextAlign.Center, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Serif, style = TextStyle( color = colorScheme.surface, shadow = Shadow( color = colorScheme.primary, blurRadius = 8f ) ) ) ElevatedButton( modifier = Modifier .height(64.dp) .padding(start = 16.dp, end = 16.dp, bottom = 8.dp), shape = RoundedCornerShape(8.dp), onClick = { navigate(navController, Screen.OfflineTwoPlayer) }) { Row( Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .size(40.dp), painter = painterResource(id = R.drawable.baseline_people_24), contentDescription = "play icon" ) Text( modifier = Modifier .padding(4.dp) .fillMaxWidth(), text = "Offline Two Player".uppercase(), fontSize = 24.sp, textAlign = TextAlign.Justify, fontWeight = FontWeight.Bold, ) } } ElevatedButton( modifier = Modifier .height(64.dp) .padding(start = 16.dp, end = 16.dp, bottom = 8.dp), shape = RoundedCornerShape(8.dp), onClick = { navigate(navController, Screen.OfflineVsComputer) }) { Row( Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .size(40.dp), imageVector = Icons.Default.Person, contentDescription = "play icon" ) Text( modifier = Modifier .fillMaxWidth() .padding(4.dp), text = "Player Vs Computer".uppercase(), fontSize = 24.sp, textAlign = TextAlign.Justify ) } } ElevatedButton( modifier = Modifier .height(64.dp) .padding(start = 16.dp, end = 16.dp, bottom = 8.dp), shape = RoundedCornerShape(8.dp), onClick = { navigate(navController, Screen.OfflineTwoPlayer) }) { Row( Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .size(40.dp), painter = painterResource(id = R.drawable.baseline_connect_without_contact_24), contentDescription = "play icon" ) Text( modifier = Modifier .fillMaxWidth() .padding(4.dp), text = "Online Two Player".uppercase(), fontSize = 24.sp, textAlign = TextAlign.Justify ) } } } ElevatedButton( modifier = Modifier .padding(8.dp) .constrainAs(sound) { start.linkTo(parent.start) bottom.linkTo(parent.bottom) }, shape = RoundedCornerShape(8.dp), onClick = { /*TODO*/ }) { Text(text = "Sound") } ElevatedButton( modifier = Modifier .padding(8.dp) .constrainAs(help) { end.linkTo(parent.end) bottom.linkTo(parent.bottom) }, shape = RoundedCornerShape(8.dp), onClick = { /*TODO*/ }) { Text(text = "Help") } } } @Preview(showBackground = true) @Composable fun HomePreview(modifier: Modifier = Modifier) { TicTacToeTheme( dynamicColor = false, darkTheme = false ) { HomeScreen(navController = rememberNavController()) } }
0
Kotlin
0
2
dfaeebc46c403cd2d28a64861fba06ce622592cf
9,083
TicTacToe
MIT License
src/backend/ci/core/common/common-api/src/main/kotlin/com/tencent/devops/common/api/pojo/agent/DockerInitFileInfo.kt
TencentBlueKing
189,153,491
false
{"Kotlin": 30176725, "Vue": 6739254, "JavaScript": 1256623, "Go": 616850, "Lua": 567159, "TypeScript": 461781, "SCSS": 365654, "Shell": 157561, "Java": 153049, "CSS": 106299, "HTML": 96201, "Python": 39238, "Less": 24714, "Makefile": 10630, "Smarty": 10297, "Dockerfile": 5097, "Batchfile": 4908, "PowerShell": 1626, "VBScript": 189}
package com.tencent.devops.common.api.pojo.agent import io.swagger.v3.oas.annotations.media.Schema @Schema(title = "docker init 文件升级信息") data class DockerInitFileInfo( @get:Schema(title = "文件md5值") val fileMd5: String, @get:Schema(title = "目前只支持linux机器,所以其他系统不需要检查") val needUpgrade: Boolean )
719
Kotlin
498
2,382
dd483c38bdbe5c17fa0e5e5bc3390cd1cd40757c
312
bk-ci
MIT License
app/src/main/java/imraan/imraan/thinkbright/AnimalQuizResults.kt
imraanishmail
364,049,813
false
{"Kotlin": 53584}
package imraan.imraan.thinkbright import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ListView import android.widget.TextView import androidx.fragment.app.Fragment import imraan.imraan.thinkbright.fragments.AboutFragment import imraan.imraan.thinkbright.fragments.HomeFragment import imraan.imraan.thinkbright.fragments.QuizFragment import com.google.android.material.bottomnavigation.BottomNavigationView class AnimalQuizResults : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_animal_quiz_results) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) val homeFragment = HomeFragment() val aboutFragment = AboutFragment() val quizFragment = QuizFragment() makeCurrentFragment(homeFragment) bottomNavigationView.setOnNavigationItemSelectedListener { when(it.itemId) { R.id.ic_home -> intent = Intent(this, Welcome2::class.java).apply { } R.id.ic_info -> intent = Intent(this, AboutUs1::class.java).apply { } R.id.ic_school -> intent = Intent(this, UserDetails::class.java).apply { } } startActivity(intent) true } val animal_answer = intent.getStringExtra(EXTRA_MESSAGE2) val user_score = findViewById<TextView>(R.id.txtAnimalScoreTotalCorrect).apply { text = animal_answer.toString() } val message = intent3.getStringExtra(EXTRA_MESSAGE3) val name = findViewById<TextView>(R.id.txtAnimalName).apply { text = message } val animalListView = findViewById<ListView>(R.id.listViewAnimalResultsBox) animalListView.adapter = AnimalListAdapter(this) // tells list what to render } fun makeCurrentFragment(fragment: Fragment) = supportFragmentManager.beginTransaction().apply { replace(R.id.fl_wrapper, fragment) commit() } fun onClearClick(view: View) { var listview = ListView(this) listview = findViewById(R.id.listViewAnimalResultsBox) listview.setAdapter(null) var txtName = TextView(this) txtName = findViewById(R.id.txtAnimalName) txtName.text = "" var txtScore = TextView(this) txtScore = findViewById(R.id.txtAnimalScoreTotalCorrect) txtScore.text = "" score2 = 0 } class AnimalListAdapter(context: Context): BaseAdapter() { private val mContext: Context val animal_q1_user = intentAnimal1.getStringExtra(EXTRA_MESSAGE8) val animal_q2_user = intentAnimal2.getStringExtra(EXTRA_MESSAGE9) val animal_q3_user = intentAnimal3.getStringExtra(EXTRA_MESSAGE10) val animal_q4_user = intentAnimal4.getStringExtra(EXTRA_MESSAGE11) val user_answer = arrayListOf<String>(" " + animal_q1_user.toString(), " " + animal_q2_user.toString(), " " + animal_q3_user.toString(), " " + animal_q4_user.toString()) val correct_answer = arrayListOf<String>(" Lion", " Cow", " Cat", " Dog") init { mContext = context } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val layoutInflator = LayoutInflater.from(mContext) val rowMain = layoutInflator.inflate(R.layout.row_main_animal, parent, false) val questionNum = rowMain.findViewById<TextView>(R.id.questionNumAnimal) questionNum.text = (position + 1).toString() val radSelected = rowMain.findViewById<TextView>(R.id.userAnswerAnimal) radSelected.text = user_answer.get(position) val correctAnswer = rowMain.findViewById<TextView>(R.id.correctAnswerAnimal) correctAnswer.text = correct_answer.get(position) return rowMain } override fun getItem(position: Int): Any { return "TEST STRING" } override fun getItemId(position: Int): Long { return position.toLong() } override fun getCount(): Int { return user_answer.size } } }
0
Kotlin
2
0
8a3d018be428f309beb46c7a34ce618b12195458
4,641
thinkBright-app-playstore
MIT License
app/src/main/java/com/alessandrofarandagancio/nycschools/school/model/SchoolSimple.kt
alexs60
608,871,839
false
null
package com.alessandrofarandagancio.nycschools.school.model data class SchoolSimple(val dbn: String, val school_name: String, val location: String)
0
Kotlin
0
0
842212bdff31702e8f8958fd965dab0fb94c7cc0
148
20230302-AlessandroFarandaGancio-NYCSchools
Apache License 2.0
src/test/kotlin/no/nav/tilleggsstonader/sak/infrastruktur/mocks/PdlClientConfig.kt
navikt
685,490,225
false
{"Kotlin": 1714587, "Gherkin": 41585, "HTML": 39172, "Shell": 924, "Dockerfile": 164}
package no.nav.tilleggsstonader.sak.infrastruktur.mocks import io.mockk.every import io.mockk.mockk import io.mockk.slot import no.nav.tilleggsstonader.kontrakter.pdl.GeografiskTilknytningDto import no.nav.tilleggsstonader.kontrakter.pdl.GeografiskTilknytningType import no.nav.tilleggsstonader.sak.opplysninger.pdl.PdlClient import no.nav.tilleggsstonader.sak.opplysninger.pdl.PdlNotFoundException import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Adressebeskyttelse import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.AdressebeskyttelseGradering import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Bostedsadresse import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Dødsfall import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Familierelasjonsrolle import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Folkeregisteridentifikator import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.FolkeregisteridentifikatorStatus import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Folkeregistermetadata import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Folkeregisterpersonstatus import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.ForelderBarnRelasjon import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Fullmakt import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.IdentifiserendeInformasjon import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.InnflyttingTilNorge import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Kontaktadresse import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.KontaktadresseType import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.MotpartsRolle import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Navn import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Opphold import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Oppholdstillatelse import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.PdlAnnenForelder import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.PdlBarn import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.PdlIdent import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.PdlIdenter import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.PdlPersonKort import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Statsborgerskap import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.UtflyttingFraNorge import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Vegadresse import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.VergeEllerFullmektig import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.VergemaalEllerFremtidsfullmakt import no.nav.tilleggsstonader.sak.util.PdlTestdataHelper.fødsel import no.nav.tilleggsstonader.sak.util.PdlTestdataHelper.lagNavn import no.nav.tilleggsstonader.sak.util.PdlTestdataHelper.metadataGjeldende import no.nav.tilleggsstonader.sak.util.PdlTestdataHelper.pdlBarn import no.nav.tilleggsstonader.sak.util.PdlTestdataHelper.pdlSøker import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary import org.springframework.context.annotation.Profile import java.time.LocalDate import java.time.LocalDateTime import java.time.Month @Configuration @Profile("mock-pdl") class PdlClientConfig { @Bean @Primary fun pdlClient(): PdlClient { val pdlClient: PdlClient = mockk() every { pdlClient.hentPersonKortBolk(any()) } answers { firstArg<List<String>>().associateWith { lagPersonKort(it) } } every { pdlClient.hentSøker(any()) } answers { opprettPdlSøker() } every { pdlClient.hentBarn(any()) } returns barn() every { pdlClient.hentAndreForeldre(any()) } returns mapOf(annenForelderFnr to annenForelder()) every { pdlClient.hentAktørIder(any()) } answers { val ident = firstArg<String>() if (ident == "19117313797") { throw PdlNotFoundException() } else { PdlIdenter(listOf(PdlIdent("00$ident", false))) } } val personIdent = slot<String>() every { pdlClient.hentPersonidenter(capture(personIdent)) } answers { if (personIdent.captured == "19117313797") { throw PdlNotFoundException() } else { PdlIdenter(listOf(PdlIdent(firstArg(), false), PdlIdent("98765432109", true))) } } every { pdlClient.hentIdenterBolk(listOf("123", "456")) } .returns( mapOf( "123" to PdlIdent("ny123", false), "456" to PdlIdent("ny456", false), ), ) every { pdlClient.hentIdenterBolk(listOf("456", "123")) } .returns( mapOf( "123" to PdlIdent("ny123", false), "456" to PdlIdent("ny456", false), ), ) every { pdlClient.hentIdenterBolk(listOf("111", "222")) } .returns( mapOf( "111" to PdlIdent("111", false), "222" to PdlIdent("222", false), ), ) every { pdlClient.hentGeografiskTilknytning(any()) } returns GeografiskTilknytningDto( gtBydel = "030103", gtKommune = "0301", gtType = GeografiskTilknytningType.BYDEL, gtLand = "NOR", ) return pdlClient } companion object { private val startdato = LocalDate.of(2020, 1, 1) private val sluttdato = LocalDate.of(2021, 1, 1) const val barnFnr = "01012067050" const val barn2Fnr = "14041385481" const val søkerFnr = "01010172272" const val annenForelderFnr = "17097926735" private const val fnrPåAdresseSøk = "01012067050" fun lagPersonKort(it: String) = PdlPersonKort( listOf( Adressebeskyttelse( gradering = AdressebeskyttelseGradering.UGRADERT, metadata = metadataGjeldende, ), ), listOf(lagNavn(fornavn = it)), emptyList(), ) val folkeregisteridentifikatorSøker = Folkeregisteridentifikator( søkerFnr, FolkeregisteridentifikatorStatus.I_BRUK, metadataGjeldende, ) fun opprettPdlSøker() = pdlSøker( adressebeskyttelse = listOf( Adressebeskyttelse( gradering = AdressebeskyttelseGradering.UGRADERT, metadata = metadataGjeldende, ), ), bostedsadresse = bostedsadresse(), dødsfall = listOf(), forelderBarnRelasjon = forelderBarnRelasjoner(), folkeregisteridentifikator = listOf(folkeregisteridentifikatorSøker), fødselsdato = listOf(fødsel()), folkeregisterpersonstatus = listOf( Folkeregisterpersonstatus( "bosatt", "bosattEtterFolkeregisterloven", metadataGjeldende, ), ), fullmakt = fullmakter(), kontaktadresse = kontaktadresse(), navn = listOf(lagNavn()), opphold = listOf(Opphold(Oppholdstillatelse.PERMANENT, startdato, null)), oppholdsadresse = listOf(), statsborgerskap = statsborgerskap(), innflyttingTilNorge = listOf(InnflyttingTilNorge("SWE", "Stockholm", folkeregistermetadata)), utflyttingFraNorge = listOf( UtflyttingFraNorge( tilflyttingsland = "SWE", tilflyttingsstedIUtlandet = "Stockholm", utflyttingsdato = LocalDate.of(2021, 1, 1), folkeregistermetadata = folkeregistermetadata, ), ), vergemaalEllerFremtidsfullmakt = vergemaalEllerFremtidsfullmakt(), ) private val folkeregistermetadata = Folkeregistermetadata( LocalDateTime.of(2010, Month.AUGUST, 30, 10, 10), LocalDateTime.of(2018, Month.JANUARY, 15, 12, 55), ) private fun barn(): Map<String, PdlBarn> = mapOf( barnFnr to pdlBarn( bostedsadresse = bostedsadresse(), forelderBarnRelasjon = familierelasjonerBarn(), fødselsdato = fødsel(), navn = lagNavn("Barn", null, "Barnesen"), ), barn2Fnr to pdlBarn( bostedsadresse = bostedsadresse(), forelderBarnRelasjon = familierelasjonerBarn(), fødselsdato = fødsel(), navn = lagNavn("Barn2", null, "Barnesen"), ), ) private fun annenForelder(): PdlAnnenForelder = PdlAnnenForelder( adressebeskyttelse = emptyList(), bostedsadresse = bostedsadresse(), dødsfall = listOf(Dødsfall(LocalDate.of(2021, 9, 22))), fødselsdato = listOf(fødsel(1994, 11, 1)), navn = listOf(Navn("Bob", "", "Burger", metadataGjeldende)), folkeregisteridentifikator = listOf( Folkeregisteridentifikator( annenForelderFnr, FolkeregisteridentifikatorStatus.I_BRUK, metadataGjeldende, ), ), ) private fun forelderBarnRelasjoner(): List<ForelderBarnRelasjon> = listOf( ForelderBarnRelasjon( relatertPersonsIdent = barnFnr, relatertPersonsRolle = Familierelasjonsrolle.BARN, minRolleForPerson = Familierelasjonsrolle.MOR, ), ForelderBarnRelasjon( relatertPersonsIdent = barn2Fnr, relatertPersonsRolle = Familierelasjonsrolle.BARN, minRolleForPerson = Familierelasjonsrolle.MOR, ), ) private fun familierelasjonerBarn(): List<ForelderBarnRelasjon> = listOf( ForelderBarnRelasjon( relatertPersonsIdent = søkerFnr, relatertPersonsRolle = Familierelasjonsrolle.MOR, minRolleForPerson = Familierelasjonsrolle.BARN, ), ForelderBarnRelasjon( relatertPersonsIdent = annenForelderFnr, relatertPersonsRolle = Familierelasjonsrolle.FAR, minRolleForPerson = Familierelasjonsrolle.BARN, ), ) private fun kontaktadresse(): List<Kontaktadresse> = listOf( Kontaktadresse( coAdressenavn = "co", gyldigFraOgMed = startdato, gyldigTilOgMed = sluttdato, postadresseIFrittFormat = null, postboksadresse = null, type = KontaktadresseType.INNLAND, utenlandskAdresse = null, utenlandskAdresseIFrittFormat = null, vegadresse = vegadresse(), ), ) private fun statsborgerskap(): List<Statsborgerskap> = listOf( Statsborgerskap( land = "NOR", gyldigFraOgMed = startdato, gyldigTilOgMed = null, ), Statsborgerskap( land = "SWE", gyldigFraOgMed = startdato.minusYears(3), gyldigTilOgMed = startdato, ), ) private fun fullmakter(): List<Fullmakt> = listOf( Fullmakt( gyldigTilOgMed = startdato, gyldigFraOgMed = sluttdato, motpartsPersonident = "11111133333", motpartsRolle = MotpartsRolle.FULLMEKTIG, omraader = listOf(), ), ) private fun bostedsadresse(): List<Bostedsadresse> = listOf( Bostedsadresse( angittFlyttedato = startdato.plusDays(1), gyldigFraOgMed = startdato, gyldigTilOgMed = LocalDate.of(2199, 1, 1), utenlandskAdresse = null, coAdressenavn = "CONAVN", vegadresse = vegadresse(), ukjentBosted = null, matrikkeladresse = null, metadata = metadataGjeldende, ), ) private fun vegadresse(): Vegadresse = Vegadresse( husnummer = "13", husbokstav = "b", adressenavn = "Charlies vei", kommunenummer = "0301", postnummer = "0575", bruksenhetsnummer = "", tilleggsnavn = null, matrikkelId = 0, ) private fun vergemaalEllerFremtidsfullmakt(): List<VergemaalEllerFremtidsfullmakt> { return listOf( VergemaalEllerFremtidsfullmakt( embete = null, folkeregistermetadata = null, type = "voksen", vergeEllerFullmektig = VergeEllerFullmektig( motpartsPersonident = annenForelderFnr, identifiserendeInformasjon = IdentifiserendeInformasjon(navn = null), omfang = "personligeOgOekonomiskeInteresser", omfangetErInnenPersonligOmraade = false, ), ), VergemaalEllerFremtidsfullmakt( embete = null, folkeregistermetadata = null, type = "stadfestetFremtidsfullmakt", vergeEllerFullmektig = VergeEllerFullmektig( motpartsPersonident = annenForelderFnr, identifiserendeInformasjon = IdentifiserendeInformasjon(navn = null), omfang = "personligeOgOekonomiskeInteresser", omfangetErInnenPersonligOmraade = false, ), ), ) } } }
3
Kotlin
1
0
f4191dcf48ee50d3010e5794c6d4462f1c19002f
14,754
tilleggsstonader-sak
MIT License
src/main/java/mutation/tool/parser/CSharpParser.kt
jcarlosadm
212,240,193
true
{"XML": 10, "Maven POM": 1, "Text": 1, "Ignore List": 1, "YAML": 1, "Markdown": 1, "JSON": 3, "Kotlin": 93, "Java": 5, "C#": 2, "Java Properties": 1}
package mutation.tool.parser import mutation.tool.context.InsertionPoint import mutation.tool.util.xml.getAllTagNodes import mutation.tool.util.xml.getTagNode import org.w3c.dom.Node import java.io.File import javax.xml.parsers.DocumentBuilderFactory private fun printNode(node:Node) { /*//println(node.nodeName) if (node.nodeName == "attribute") { val insertionPoint = findParent(node) println(node.textContent + " >>> " + insertionPoint) // find target (class, function, decl_stmt, parameter) }*/ /*if (node.nodeName == "class") { println(getTagValue(node, "name", true)) }*/ if (node.nodeName == "class") { println(getTagNode(node, "name", false)?.attributes?.getNamedItem("pos:column")?.textContent) } /*if (node.nodeName == "parameter") { val list = getAllTagNodes(node, "attribute", listOf("decl_stmt", "function", "class")) for (item in list) { println(item.textContent) } if(list.isNotEmpty()) println("-----------------") }*/ for (i in 0 until node.childNodes.length) { printNode(node.childNodes.item(i)) } } fun findParent(node: Node): InsertionPoint? { var parent = node.parentNode val map = mapOf("class" to InsertionPoint.CLASS, "function" to InsertionPoint.METHOD, "decl_stmt" to InsertionPoint.PROPERTY, "parameter" to InsertionPoint.PARAMETER) while (parent != null && !map.containsKey(parent.nodeName)) { parent = parent.parentNode } if (parent == null) return null return map.get(parent.nodeName) } class CSharpParser(private val file:File) { fun processAnnotations(insertionPoints: List<InsertionPoint>, processor:AnnotationProcessor?){ /*val destPath = file.absolutePath + ".xml" val process = Runtime.getRuntime().exec("srcml " + file.absolutePath + " -o " + destPath + " --position") process.waitFor() val xmlFile = File(destPath)*/ val process = Runtime.getRuntime().exec("srcml " + file.absolutePath + " --position") process.waitFor() val builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() val doc = builder.parse(process.inputStream) for (i in 0 until doc.childNodes.length) { printNode(doc.childNodes.item(i)) } /*val reader = BufferedReader(FileReader(xmlFile)) for (line in reader.lines()) { println(line) }*/ } } fun main() { val a = CSharpParser(File("src/main/resources/test.cs")) a.processAnnotations(listOf(InsertionPoint.CLASS), null) }
0
Kotlin
0
0
fce32936b61819b4791b04a7db7fefbe61e871c6
2,661
mutation-tool-for-annotations
MIT License
app/src/main/java/com/trackmyterm/data/remote/response/BaseResponse.kt
shah-vraj
842,748,055
false
{"Kotlin": 62828}
package com.trackmyterm.data.remote.response interface BaseResponse<T> { val resultType: String val data: T val message: String }
0
Kotlin
0
0
a8ead944acbda14d2eb1d5967334c8afd42b1a3a
142
TrackMyTerm
MIT License
common/src/main/kotlin/com/codeviking/kxg/util/TouchGestureEvaluator.kt
dwbullok
153,008,678
true
{"Kotlin": 925045}
package com.codeviking.kxg.util import com.codeviking.kxg.InputManager import com.codeviking.kxg.KxgContext import com.codeviking.kxg.math.MutableVec2f import com.codeviking.kxg.math.Vec2f /** * Evaluates standard touch gestures (pinch-to-zoom, two-finger drag) */ open class TouchGestureEvaluator { var currentGesture = Gesture() protected set private val activePointers = mutableListOf<InputManager.Pointer>() private val tmpVec1 = MutableVec2f() private val tmpVec2 = MutableVec2f() protected val startPositions = mutableMapOf<Int, Vec2f>() protected var screenDpi = 96f fun evaluate(ctx: KxgContext) { screenDpi = ctx.screenDpi ctx.inputMgr.getActivePointers(activePointers) if (activePointers.size > 1) { when (currentGesture.type) { INVALID -> onGestureInit(activePointers) INDETERMINATE -> onDetermineGesture(activePointers) PINCH -> handleGesture(activePointers) TWO_FINGER_DRAG -> handleGesture(activePointers) } } else { // not enough valid pointers for a multi-touch gesture currentGesture.type = INVALID startPositions.clear() } } protected open fun onGestureInit(pointers: MutableList<InputManager.Pointer>) { pointers.forEach { startPositions[it.id] = Vec2f(it.x, it.y) } currentGesture.type = INDETERMINATE } protected open fun onDetermineGesture(pointers: MutableList<InputManager.Pointer>) { // remove any missing pointer startPositions.keys.removeAll { ptrId -> pointers.find { it.id == ptrId } == null } // add any new pointer pointers.filter { !startPositions.containsKey(it.id) } .forEach { startPositions[it.id] = Vec2f(it.x, it.y) } // try to match gesture when { isPinch(pointers) -> currentGesture.type = PINCH isTwoFingerDrag(pointers) -> currentGesture.type = TWO_FINGER_DRAG } } protected open fun isPinch(pointers: MutableList<InputManager.Pointer>): Boolean { // two pointers moving in opposing direction if (pointers.size == 2) { tmpVec1.set(pointers[0].x, pointers[0].y).subtract(startPositions[pointers[0].id]!!) tmpVec2.set(pointers[1].x, pointers[1].y).subtract(startPositions[pointers[1].id]!!) tmpVec1.scale(96f / screenDpi) tmpVec2.scale(96f / screenDpi) if (tmpVec1.length() > 5f && tmpVec2.length() > 5f && tmpVec1 * tmpVec2 < 0) { tmpVec1.set(startPositions[pointers[0].id]!!) tmpVec2.set(startPositions[pointers[1].id]!!) currentGesture.init(PINCH, tmpVec1, tmpVec2, screenDpi) handleGesture(pointers) return true } } return false } protected open fun isTwoFingerDrag(pointers: MutableList<InputManager.Pointer>): Boolean { // two pointers moving in same direction if (pointers.size == 2) { tmpVec1.set(pointers[0].x, pointers[0].y).subtract(startPositions[pointers[0].id]!!) tmpVec2.set(pointers[1].x, pointers[1].y).subtract(startPositions[pointers[1].id]!!) tmpVec1.scale(96f / screenDpi) tmpVec2.scale(96f / screenDpi) if (tmpVec1.length() > 5f && tmpVec2.length() > 5f && tmpVec1 * tmpVec2 > 0) { tmpVec1.set(startPositions[pointers[0].id]!!) tmpVec2.set(startPositions[pointers[1].id]!!) currentGesture.init(TWO_FINGER_DRAG, tmpVec1, tmpVec2, screenDpi) handleGesture(pointers) return true } } return false } protected open fun handleGesture(pointers: MutableList<InputManager.Pointer>) { if (pointers.size == 2) { tmpVec1.set(pointers[0].x, pointers[0].y) tmpVec2.set(pointers[1].x, pointers[1].y) currentGesture.update(tmpVec1, tmpVec2, screenDpi) } else { currentGesture.type = INVALID } } companion object { const val INVALID = 0 const val INDETERMINATE = -1 const val PINCH = 1 const val TWO_FINGER_DRAG = 2 } open class Gesture { val centerStart = MutableVec2f() val centerCurrent = MutableVec2f() val centerShift = MutableVec2f() val dCenter = MutableVec2f() var pinchAmountStart = 0f var pinchAmountCurrent = 0f var dPinchAmount = 0f val pinchAmountRel: Float get() = (pinchAmountCurrent - pinchAmountStart) / pinchAmountStart + 1f var type = INVALID var numUpdates = 0 internal fun init(type: Int, ptr1: Vec2f, ptr2: Vec2f, dpi: Float) { this.type = type centerStart.set(ptr1).add(ptr2).scale(0.5f) centerCurrent.set(centerStart) centerShift.set(Vec2f.ZERO) dCenter.set(Vec2f.ZERO) pinchAmountStart = ptr1.distance(ptr2) * 96f / dpi pinchAmountCurrent = pinchAmountStart dPinchAmount = 0f numUpdates = 0 } internal fun update(ptr1: Vec2f, ptr2: Vec2f, dpi: Float) { dCenter.set(ptr1).add(ptr2).scale(0.5f).subtract(centerCurrent) centerCurrent.set(ptr1).add(ptr2).scale(0.5f) centerShift.set(centerCurrent).subtract(centerStart) val pinch = ptr1.distance(ptr2) * 96f / dpi dPinchAmount = pinch - pinchAmountCurrent pinchAmountCurrent = pinch numUpdates++ } } }
0
Kotlin
0
0
5121acb8d80480bf60624ae9ef87a39b97428e27
5,714
kool
Apache License 2.0
src/main/kotlin/Contacts.kt
nolequen
162,179,912
false
null
package su.nlq.icq.bot import com.fasterxml.jackson.annotation.JsonProperty import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.parameter import io.ktor.http.HttpMethod import su.nlq.icq.bot.request.HttpRequest class Contacts internal constructor(private val bot: Bot) { suspend fun all() = HttpRequest("getBuddyList").request<Response>(bot) .map { (json) -> json.data.groups ?.flatMap { it.buddies } ?.map { Buddy(it.aimId, it.friendly, bot) } ?: emptyList() } private data class Response( @JsonProperty("response") val response: Content ) private data class Content( val statusCode: Int, val statusText: String, val data: RawData ) private data class RawData( @JsonProperty("groups") val groups: List<RawGroup>? ) private data class RawGroup( val id: Int, val name: String, val buddies: List<RawBuddy> = emptyList() ) private data class RawBuddy( val aimId: String, val displayId: String, val friendly: String, val userType: String ) class Buddy internal constructor( id: String, val name: String, private val bot: Bot ) : PenPal(id) { suspend fun remove(group: String) = remove { parameter("group", group) } suspend fun remove() = remove { parameter("allGroups", 1) } private suspend fun remove(parameters: HttpRequestBuilder.() -> Unit) = HttpRequest("/buddylist/removeBuddy", HttpMethod.Post) { parameter("buddy", id) parameters() }.request<Unit>(bot) } }
0
Kotlin
1
0
9cedccc0ababdb8a5b4ff80c92f79255f8831781
1,601
icq-bot-core
MIT License