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
app/src/main/java/ru/luckycactus/steamroulette/presentation/utils/extensions/viewModel.kt
luckycactus
196,364,852
false
null
package ru.luckycactus.steamroulette.presentation.utils.extensions import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.AbstractSavedStateViewModelFactory import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel inline fun <reified T : ViewModel> Fragment.assistedViewModel( crossinline viewModelProducer: (SavedStateHandle) -> T ) = viewModels<T> { object : AbstractSavedStateViewModelFactory(this, arguments) { override fun <T : ViewModel> create(key: String, modelClass: Class<T>, handle: SavedStateHandle) = viewModelProducer(handle) as T } }
0
Kotlin
0
5
c6c2b00ca77f8224145ef3182b1910bd249d76ba
661
steam-roulette
Apache License 2.0
ViewModel/src/main/java/com/example/core/NavigationScreen.kt
NovikFeed
804,718,118
false
{"Kotlin": 59354}
package com.example.core enum class NavigationScreen { Loading,Login, Register, Chats }
0
Kotlin
0
0
c2a6a090b97015cb3bb4b087f04b950685cc4474
92
chat-application
MIT License
bezier/src/main/java/io/channel/bezier/icon/SplitLeftFilled.kt
channel-io
736,533,981
false
{"Kotlin": 2421787, "Python": 12500}
@file:Suppress("ObjectPropertyName", "UnusedReceiverParameter") // Auto-generated by script/generate_compose_bezier_icon.py package io.channel.bezier.icon import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import io.channel.bezier.BezierIcon import io.channel.bezier.BezierIcons val BezierIcons.SplitLeftFilled: BezierIcon get() = object : BezierIcon { override val imageVector: ImageVector get() = _splitLeftFilled ?: ImageVector.Builder( name = "SplitLeftFilled", defaultWidth = 24.dp, defaultHeight = 24.dp, viewportWidth = 24f, viewportHeight = 24f, ).apply { path( fill = SolidColor(Color(0xFF313234)), strokeLineWidth = 1f, ) { moveTo(5.5f, 7.0f) arcTo(0.5f, 0.5f, 270.0f, isMoreThanHalf = false, isPositiveArc = false, 5.0f, 7.5f) lineTo(5.0f, 16.5f) arcTo(0.5f, 0.5f, 180.0f, isMoreThanHalf = false, isPositiveArc = false, 5.5f, 17.0f) lineTo(12.5f, 17.0f) arcTo(0.5f, 0.5f, 90.0f, isMoreThanHalf = false, isPositiveArc = false, 13.0f, 16.5f) lineTo(13.0f, 7.5f) arcTo(0.5f, 0.5f, 0.0f, isMoreThanHalf = false, isPositiveArc = false, 12.5f, 7.0f) close() } path( fill = SolidColor(Color(0xFF313234)), strokeLineWidth = 1f, pathFillType = PathFillType.EvenOdd, ) { moveTo(2.0f, 7.0f) arcTo(3.0f, 3.0f, 180.0f, isMoreThanHalf = false, isPositiveArc = true, 5.0f, 4.0f) lineTo(19.0f, 4.0f) arcTo(3.0f, 3.0f, 270.0f, isMoreThanHalf = false, isPositiveArc = true, 22.0f, 7.0f) lineTo(22.0f, 17.0f) arcTo(3.0f, 3.0f, 0.0f, isMoreThanHalf = false, isPositiveArc = true, 19.0f, 20.0f) lineTo(5.0f, 20.0f) arcTo(3.0f, 3.0f, 90.0f, isMoreThanHalf = false, isPositiveArc = true, 2.0f, 17.0f) close() moveTo(5.0f, 6.0f) lineTo(19.0f, 6.0f) arcTo(1.0f, 1.0f, 270.0f, isMoreThanHalf = false, isPositiveArc = true, 20.0f, 7.0f) lineTo(20.0f, 17.0f) arcTo(1.0f, 1.0f, 0.0f, isMoreThanHalf = false, isPositiveArc = true, 19.0f, 18.0f) lineTo(5.0f, 18.0f) arcTo(1.0f, 1.0f, 90.0f, isMoreThanHalf = false, isPositiveArc = true, 4.0f, 17.0f) lineTo(4.0f, 7.0f) arcTo(1.0f, 1.0f, 180.0f, isMoreThanHalf = false, isPositiveArc = true, 5.0f, 6.0f) } }.build().also { _splitLeftFilled = it } } private var _splitLeftFilled: ImageVector? = null @Preview(showBackground = true) @Composable private fun SplitLeftFilledIconPreview() { Icon( modifier = Modifier.size(128.dp), imageVector = BezierIcons.SplitLeftFilled.imageVector, contentDescription = null, ) }
7
Kotlin
3
6
39cd58b0dd4a1543d54f0c1ce7c605f33ce135c6
3,769
bezier-compose
MIT License
app/src/main/java/by/offvanhooijdonk/dailyroutine/ui/main/MainViewModel.kt
offvanHooijdonk
774,881,554
false
{"Kotlin": 16998}
package by.offvanhooijdonk.dailyroutine.ui.main import androidx.lifecycle.ViewModel class MainViewModel : ViewModel() { }
0
Kotlin
0
0
1f47888f29e41874183e96e1aee145af8c6239d6
123
daily-routine
Apache License 2.0
src/main/kotlin/es/joseluisgs/kotlinspringbootrestservice/config/cors/CorsConfig.kt
joseluisgs
462,853,361
false
{"Kotlin": 127596}
package es.joseluisgs.kotlinspringbootrestservice.config.cors import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.CorsRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration class CorsConfig { // @Bean // Cors para permitir cualquier petición /* public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/ **"); } }; } */ /** * CORS: Configuración más ajustada. */ @Bean fun corsConfigurer(): WebMvcConfigurer { return object : WebMvcConfigurer { // Ajustamos una configuración específica para cada serie de métodos // Así por cada fuente podemos permitir lo que queremos // Por ejemplo ene esta configuración solo permitirmos el dominio producto // Permitimos solo un dominio // e indicamos los verbos que queremos usar // Debes probar con uncliente desde ese puerto override fun addCorsMappings(registry: CorsRegistry) { registry.addMapping("/rest/producto/**") .allowedOrigins("http://localhost:6969") .allowedMethods("GET", "POST", "PUT", "DELETE") .maxAge(3600) } } } }
0
Kotlin
3
2
8ba321403c0e672372ed9df79c0ae996ae5c0e91
1,484
Kotlin-SpringBoot-REST-Service
MIT License
Chapter11/Exercise11.06/app/src/main/java/com/android/testable/camera/ProviderFileManager.kt
PacktWorkshops
204,445,200
false
{"Kotlin": 556387}
package com.android.testable.camera import android.content.Context import android.os.Environment import java.io.File class ProviderFileManager( private val context: Context, private val fileHelper: FileHelper ) { fun generatePhotoUri(time: Long): FileInfo { val file = File( context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "img_$time.jpg" ) return FileInfo(fileHelper.getUriFromFile(file), file) } fun generateVideoUri(time: Long): FileInfo { val file = File( context.getExternalFilesDir(Environment.DIRECTORY_MOVIES), "video_$time.mp4" ) return FileInfo(fileHelper.getUriFromFile(file), file) } }
0
Kotlin
18
9
ab42898f6debe3bc83d0f08bbb1c0b7dea959d4b
734
The-Android-Workshop
MIT License
pickerkt-ui/src/main/java/io/rektplorer64/pickerkt/ui/component/collection/CountBadge.kt
rektplorer64
453,108,501
false
{"Kotlin": 367937}
package io.rektplorer64.pickerkt.ui.component.collection import androidx.compose.animation.* import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.CheckCircleOutline import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import io.rektplorer64.pickerkt.ui.common.compose.animation.slideContentTransitionSpec @Composable @OptIn(ExperimentalAnimationApi::class) fun CountBadge( count: Int?, modifier: Modifier = Modifier, visible: Boolean = count != null && count > 0, icon: (@Composable () -> Unit)? = { Icon( Icons.Default.CheckCircleOutline, contentDescription = null, modifier = Modifier.fillMaxSize() ) }, contentDescription: String? ) { AnimatedVisibility( modifier = modifier.animateContentSize(), visible = visible, enter = fadeIn() + scaleIn(), exit = fadeOut() + scaleOut() ) { Badge( modifier = Modifier.semantics(mergeDescendants = true) { if (contentDescription != null) { this.contentDescription = contentDescription } } ) { if (icon != null) { Box( modifier = Modifier.padding(4.dp).size(12.dp), content = { icon() } ) } AnimatedContent( targetState = count ?: 0, transitionSpec = slideContentTransitionSpec() ) { Text( text = it.toString(), modifier = Modifier.padding(start = if (icon != null) 0.dp else 4.dp ,end = 4.dp), color = LocalContentColor.current, style = MaterialTheme.typography.labelMedium ) } } } }
2
Kotlin
2
24
2751247e76c50437930aca9b0904591eaecd7fac
2,258
picker-kt
Apache License 2.0
core/src/nativeMain/kotlin/pw.binom/ByteDataBuffer.kt
dragossusi
277,504,821
true
{"C": 13518997, "Kotlin": 569853, "C++": 546364, "Shell": 86}
package pw.binom import kotlinx.cinterop.* import platform.posix.free import platform.posix.malloc import platform.posix.memcpy import pw.binom.io.Closeable actual class ByteDataBuffer private constructor(actual val size: Int) : Closeable, Iterable<Byte> { actual companion object { actual fun alloc(size: Int): ByteDataBuffer { if (size <= 0) throw IllegalArgumentException("Argument size must be greater that 0") return ByteDataBuffer(size) } } private var _buffer: CPointer<ByteVar>? = malloc((size).convert())!!.reinterpret() val buffer: CPointer<ByteVar> get() { val bufferVar = _buffer check(bufferVar != null) { "DataBuffer already closed" } return bufferVar } fun refTo(index: Int): CPointer<ByteVar> { return (buffer + index)!! } override fun close() { check(_buffer != null) { "DataBuffer already closed" } free(_buffer) _buffer = null } actual operator fun set(index: Int, value: Byte) { if (index < 0 || index >= size) throw IndexOutOfBoundsException("Index: $index, Size=$size") buffer[index] = value } actual operator fun get(index: Int): Byte { if (index < 0 || index >= size) throw IndexOutOfBoundsException("Index: $index, Size=$size") return buffer[index] } actual override fun iterator(): ByteDataBufferIterator = ByteDataBufferIterator(this) actual fun write(position: Int, data: ByteArray, offset: Int, length: Int): Int { checkBounds(position, offset, length, data.size) memcpy(buffer + position, data.refTo(offset), length.convert()) return length } actual fun read(position: Int, data: ByteArray, offset: Int, length: Int): Int { checkBounds(position, offset, length, data.size) memcpy(data.refTo(offset), buffer + position, length.convert()) return length } actual fun write(position: Int, data: ByteDataBuffer, offset: Int, length: Int): Int { checkBounds(position, offset, length, data.size) memcpy(buffer + position, data.refTo(offset), length.convert()) return length } actual fun read(position: Int, data: ByteDataBuffer, offset: Int, length: Int): Int { checkBounds(position, offset, length, data.size) memcpy(data.refTo(offset), buffer + position, length.convert()) return length } }
0
null
0
0
d16040b0f0d340104194014fc174858244684813
2,502
pw.binom.io
Apache License 2.0
app/src/main/java/com/androiddevs/firebasenotifications/Constants.kt
abhinay100
700,343,283
false
{"Kotlin": 8253}
package com.androiddevs.firebasenotifications /** * Created by Abhinay on 04/10/23. */ class Constants { companion object { const val BASE_URL = "https://fcm.googleapis.com" const val SERVER_KEY = "<KEY><KEY>" const val CONTENT_TYPE = "application/json" } }
0
Kotlin
0
0
21bd874527248afca764e07e7bf75609bd374cc2
292
FirebasePushNotification
MIT License
aws-ses-request-handler/src/main/kotlin/com/johnturkson/aws/ses/requesthandler/SESConfiguration.kt
JohnTurkson
293,227,996
false
null
package com.johnturkson.aws.ses.requesthandler import com.johnturkson.aws.requesthandler.AWSServiceConfiguration data class SESConfiguration( override val region: String, override val path: String, override val service: String = "ses", override val endpoint: String = "https://email.$region.amazonaws.com", override val url: String = "$endpoint/$path", override val method: String = "POST", ) : AWSServiceConfiguration(region, path, service, endpoint, url, method)
0
Kotlin
0
0
f89c32631f230660fcdea6a0974d5f297a5cb76e
491
aws-tools
Apache License 2.0
src/main/java/cn/starrah/thu_course_backend/utils/CookiedFuel.kt
Starrah
258,477,700
false
null
package cn.starrah.thu_course_backend.utils import com.github.kittinunf.fuel.core.FuelManager import com.github.kittinunf.fuel.core.Headers import com.github.kittinunf.fuel.core.Request import com.github.kittinunf.fuel.core.Response import java.util.regex.Pattern import com.github.kittinunf.fuel.core.interceptors.redirectResponseInterceptor val CookiedFuel = FuelManager().apply { addRequestInterceptor { next -> {req -> next(req.enableCookie(DEFAULT_COOKIEJAR)) } } removeAllResponseInterceptors() addResponseInterceptor { next -> {req, resp -> next(req, resp.saveCookie(DEFAULT_COOKIEJAR)) } } addResponseInterceptor(redirectResponseInterceptor(this)) } private val SAVECOOKIE_KV_PATTERN = Pattern.compile("^(.+)=(.*)$") private val SAVECOOKIE_PATH_PATTERN = Pattern.compile("^Path=(.*)$", Pattern.CASE_INSENSITIVE) fun Response.saveCookie(cookieJar: CookieJar): Response { val domain = this.url.host val SCs = this[Headers.SET_COOKIE] for (SC in SCs) { val items = SC.split("; ") val main = items[0] val remainItems = items.drop(1) val mainMatcher = SAVECOOKIE_KV_PATTERN.matcher(main) if (!mainMatcher.matches()) continue val name = mainMatcher.group(1)!! val cookieValue = mainMatcher.group(2)!! var path: String? = null for (ss in remainItems) { val subMatcher = SAVECOOKIE_PATH_PATTERN.matcher(ss) if (subMatcher.matches()) path = subMatcher.group(1) } if (domain !in cookieJar.cookieMap) cookieJar.cookieMap[domain] = mutableMapOf() cookieJar.cookieMap[domain]!![name] = Pair(cookieValue, path) } return this } fun Triple<*, Response, *>.saveCookie(cookieJar: CookieJar): Triple<*, Response, *> { second.saveCookie(cookieJar) return this } fun Request.enableCookie(cookieJar: CookieJar): Request { val domain = this.url.host val cookies = cookieJar.cookieMap[domain] val cookieString = cookies?.filter { it.value.second?.let { request.url.path?.ifEmpty { "/" }?.startsWith(it) } != false } ?.map { "${it.key}=${it.value.first}" } ?.joinToString("; ") if (cookieString != null) { request[Headers.COOKIE] = cookieString } return this } class CookieJar { /** * cookie的储存位置。 * 结构是{ 域名: [{ cookie key: [ cookie value, path ] }] } * (path可能为空) */ val cookieMap: MutableMap<String, MutableMap<String, Pair<String, String?>>> = mutableMapOf() } val DEFAULT_COOKIEJAR = CookieJar()
0
Kotlin
1
4
587852c5e09a1ec4805aa30a0b090191de5a2690
2,556
THUCourseHelperBackend
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/BugSlash.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline 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.Outline.BugSlash: ImageVector get() { if (_bugSlash != null) { return _bugSlash!! } _bugSlash = Builder(name = "BugSlash", 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(14.98f, 19.2f) lineToRelative(1.46f, 1.46f) curveToRelative(-1.3f, 0.86f, -2.83f, 1.35f, -4.43f, 1.35f) curveToRelative(-2.95f, 0.0f, -5.53f, -1.61f, -6.92f, -4.0f) lineTo(3.0f, 18.01f) verticalLineToRelative(4.0f) lineTo(1.0f, 22.01f) verticalLineToRelative(-4.0f) curveToRelative(0.0f, -1.1f, 0.9f, -2.0f, 2.0f, -2.0f) horizontalLineToRelative(1.26f) curveToRelative(-0.17f, -0.64f, -0.26f, -1.31f, -0.26f, -2.0f) curveToRelative(0.0f, -0.29f, 0.04f, -0.63f, 0.1f, -1.0f) lineTo(1.0f, 13.01f) verticalLineToRelative(-2.0f) horizontalLineToRelative(3.58f) curveToRelative(0.16f, -0.55f, 0.34f, -1.12f, 0.53f, -1.68f) lineToRelative(1.59f, 1.59f) curveToRelative(-0.44f, 1.41f, -0.69f, 2.51f, -0.69f, 3.09f) curveToRelative(0.0f, 3.31f, 2.69f, 6.0f, 6.0f, 6.0f) curveToRelative(1.06f, 0.0f, 2.08f, -0.29f, 2.98f, -0.8f) close() moveTo(23.96f, 22.55f) lineToRelative(-1.41f, 1.41f) lineTo(0.04f, 1.46f) lineTo(1.46f, 0.04f) lineTo(6.68f, 5.26f) curveToRelative(1.02f, -1.99f, 3.07f, -3.26f, 5.32f, -3.26f) curveToRelative(2.39f, 0.0f, 4.54f, 1.41f, 5.5f, 3.6f) curveToRelative(0.0f, 0.0f, 0.07f, 0.16f, 0.16f, 0.4f) horizontalLineToRelative(3.34f) lineTo(21.0f, 2.0f) horizontalLineToRelative(2.0f) lineTo(23.0f, 6.0f) curveToRelative(0.0f, 1.1f, -0.9f, 2.0f, -2.0f, 2.0f) horizontalLineToRelative(-2.57f) curveToRelative(0.33f, 0.91f, 0.7f, 1.98f, 0.99f, 3.0f) horizontalLineToRelative(3.58f) verticalLineToRelative(2.0f) horizontalLineToRelative(-3.1f) curveToRelative(0.06f, 0.37f, 0.1f, 0.71f, 0.1f, 1.0f) curveToRelative(0.0f, 0.68f, -0.11f, 1.35f, -0.27f, 2.0f) horizontalLineToRelative(1.27f) curveToRelative(1.1f, 0.0f, 2.0f, 0.9f, 2.0f, 2.0f) verticalLineToRelative(3.59f) lineToRelative(0.96f, 0.96f) close() moveTo(21.0f, 18.01f) horizontalLineToRelative(-1.59f) lineToRelative(1.59f, 1.59f) verticalLineToRelative(-1.59f) close() moveTo(8.18f, 6.77f) lineToRelative(9.4f, 9.4f) curveToRelative(0.27f, -0.69f, 0.42f, -1.41f, 0.42f, -2.17f) curveToRelative(0.0f, -1.67f, -1.92f, -6.66f, -2.33f, -7.6f) curveToRelative(-0.64f, -1.46f, -2.08f, -2.4f, -3.67f, -2.4f) reflectiveCurveToRelative(-3.03f, 0.94f, -3.67f, 2.4f) curveToRelative(-0.03f, 0.07f, -0.08f, 0.19f, -0.15f, 0.37f) close() } } .build() return _bugSlash!! } private var _bugSlash: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,360
icons
MIT License
src/main/kotlin/com/vepanimas/intellij/prisma/lang/types/PrismaReferencedType.kt
vepanimas
527,378,342
false
{"Kotlin": 303241, "HTML": 7321, "Lex": 2375, "JavaScript": 1076}
package com.vepanimas.intellij.prisma.lang.types import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.vepanimas.intellij.prisma.lang.psi.PrismaFieldType class PrismaReferencedType(val name: String, element: PsiElement) : PrismaTypeBase(element), PrismaResolvableType { override fun resolveDeclaration(): PsiNamedElement? { if (!element.isValid) { return null } if (element is PrismaFieldType) { return element.typeReference.resolve() as? PsiNamedElement } return null } }
0
Kotlin
0
0
f98b18d5f9f451d70994ebe672ab9a584f184b73
587
intellij-prisma
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Auto.kt
AlejandroE25
563,062,386
false
{"Java": 50715, "Kotlin": 18110}
package org.firstinspires.ftc.teamcode import com.acmerobotics.dashboard.FtcDashboard import com.acmerobotics.dashboard.telemetry.MultipleTelemetry import com.qualcomm.robotcore.eventloop.opmode.Autonomous import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode import org.firstinspires.ftc.teamcode.DriveConstants.tileLength import org.firstinspires.ftc.teamcode.DriveConstants.turnTime import org.firstinspires.ftc.teamcode.QOL.Companion.inchesToMeters import kotlin.math.abs import org.firstinspires.ftc.teamcode.QOL.Companion.inchesToTicks import kotlin.math.exp @Autonomous(name = "Auto") class Auto: LinearOpMode() { fun forward(tiles: Int){ val target = RC!!.FR.currentPosition + (tiles * inchesToTicks(tileLength)) while (RC!!.FR.currentPosition < target) { //start at 0.75 power, and decrease power curve-ly as the robot gets closer to the target var power = abs(RC!!.FR.currentPosition - target) / target //square the power power *= power RC!!.drive(power, 0.0, 0.0) telemetry.addData("Position", RC!!.FR.currentPosition) telemetry.addData("Target", target) telemetry.addData("Distance Remaining", abs(RC!!.FR.currentPosition - target)) telemetry.addData("Power", power) telemetry.update() } RC!!.stop() } fun backward(tiles: Int){ val target = RC!!.FR.currentPosition - (tiles * inchesToTicks(tileLength)) while (RC!!.FR.currentPosition > target) { var power = abs(RC!!.FR.currentPosition - target) / target power *= power RC!!.drive(-power, 0.0, 0.0) telemetry.addData("Position", RC!!.FR.currentPosition) telemetry.addData("Target", target) telemetry.addData("Distance Remaining", abs(RC!!.FR.currentPosition - target)) telemetry.addData("Power", power) telemetry.update() } RC!!.stop() } fun left(tiles: Int){ val target = RC!!.FR.currentPosition + (tiles * inchesToTicks(tileLength)) while (RC!!.FR.currentPosition < target) { var power = abs(RC!!.FR.currentPosition - target) / target power *= power RC!!.drive(0.0, power, 0.0) telemetry.addData("Position", RC!!.FR.currentPosition) telemetry.addData("Target", target) telemetry.addData("Distance Remaining", abs(RC!!.FR.currentPosition - target)) telemetry.addData("Power", power) telemetry.update() } RC!!.stop() } fun right(tiles: Int){ val target = RC!!.FR.currentPosition - (tiles * inchesToTicks(tileLength)) while (RC!!.FR.currentPosition > target) { var power = abs(RC!!.FR.currentPosition - target) / target power *= power RC!!.drive(0.0, -power, 0.0) telemetry.addData("Position", RC!!.FR.currentPosition) telemetry.addData("Target", target) telemetry.addData("Distance Remaining", abs(RC!!.FR.currentPosition - target)) telemetry.addData("Power", power) telemetry.update() } RC!!.stop() } fun turnRight(){ RC!!.drive(0.0, 0.0, 0.3) sleep(turnTime.toLong()) RC!!.stop() } fun turnLeft(){ RC!!.drive(0.0, 0.0, -0.3) sleep(turnTime.toLong()) RC!!.stop() } var RC: RobotConfig? = null override fun runOpMode() { RC = RobotConfig(hardwareMap) telemetry = MultipleTelemetry(telemetry, FtcDashboard.getInstance().telemetry) waitForStart() forward(2) } }
1
null
1
1
a32db6958b2587b882e582094e1623d6229ab674
3,721
FTC_POWER_PLAY
BSD 3-Clause Clear License
marathons/oxfordCompSoc/y2024ht_robotMazeSolvingCompetition/robotMazeSolvingCompetition.kt
mikhail-dvorkin
93,438,157
false
{"XML": 3, "Text": 1, "Ignore List": 1, "Markdown": 5, "Java": 988, "Shell": 20, "Python": 66, "Kotlin": 512, "INI": 1, "Batchfile": 2, "Diff": 1, "Haskell": 140}
package marathons.oxfordCompSoc.y2024ht_robotMazeSolvingCompetition //TESTING import java.io.* private val TO_EVAL = -3 until 100 private val EVALUATOR: (() -> Unit) = { marathons.utils.evaluate(::robotMazeSolvingCompetitionEval, TO_EVAL) } //TESTING // ?= null //SUBMISSION @Suppress("SENSELESS_COMPARISON") private val SUBMIT = EVALUATOR == null private val VERBOSE = !SUBMIT private var log: PrintWriter? = null private val TIME_LIMIT = 5_000 - 150 private var timeStart = 0L private fun timePassed() = (System.currentTimeMillis() - timeStart) * 1.0 / TIME_LIMIT private fun checkTimeLimit(threshold: Double = 1.0) { if (timePassed() >= threshold) throw TimeOutException() } private fun solve(maze: List<String>, maskString: String): String { if (VERBOSE) log = PrintWriter(File("current~.log").writer(), true) timeStart = System.currentTimeMillis() val squareSize = 7 info { maskString.take(30) } val mask = BooleanArray(maskString.length) { maskString[it] == '?' } val n = maze.size fun encode(y: Int, x: Int) = y * n + x fun decode(cell: Int) = cell / n to cell % n val isWall = BooleanArray(n * n) { cell -> val (yCell, xCell) = decode(cell) maze[yCell][xCell] == '#' } val nei = List(n * n) { cell -> val (yCell, xCell) = decode(cell) if (isWall[cell]) return@List intArrayOf() IntArray(4) { d -> val y = yCell + DY[d] val x = xCell + DX[d] encode(y, x).let { if (isWall[it]) -1 else it } } } fun afterMove(cell: Int, d: Int) = nei[cell][d].let { if (it == -1) cell else it } fun encodePair(cell1: Int, cell2: Int): Int = if (cell1 <= cell2) cell1 * n * n + cell2 else encodePair(cell2, cell1) fun decodePair(code: Int) = code / (n * n) to code % (n * n) val joiningMove = IntArray(n * n * n * n) fun joiningBfs(): IntArray { fun pairMoved(cell1: Int, cell2: Int, d: Int): Int { val cell3 = afterMove(cell1, d) val cell4 = afterMove(cell2, d) val pairTo = encodePair(cell3, cell4) return pairTo } fun moveTowards(pairFrom: Int, pairTo: Int): Int { val (cell1, cell2) = decodePair(pairFrom) return (0 until 4).first { d -> pairMoved(cell1, cell2, d) == pairTo } } val neiBack = List(n * n * n * n) { mutableListOf<Int>() } for (cell1 in 0 until n * n) { if (isWall[cell1]) continue for (cell2 in 0 until cell1) { if (isWall[cell2]) continue val pairFrom = encodePair(cell1, cell2) for (d in 0 until 4) { val pairTo = pairMoved(cell1, cell2, d) neiBack[pairTo].add(pairFrom) } } } val dist = IntArray(n * n * n * n) { -1 } val queue = IntArray(n * n * n * n) var low = 0; var high = 0 for (cell in 0 until n * n) { if (isWall[cell]) continue val init = encodePair(cell, cell) dist[init] = 0 queue[high++] = init } while (low < high) { val pair1 = queue[low++] for (pair2 in neiBack[pair1]) { if (dist[pair2] != -1) continue dist[pair2] = dist[pair1] + 1 queue[high++] = pair2 joiningMove[pair2] = moveTowards(pair2, pair1) } } return dist } val joiningDist = joiningBfs() fun joinablePair(cells: List<Int>): Int { var joinablePair = -1 var joinablePairScore = Int.MAX_VALUE for (i in cells.indices) for (j in 0 until i) { val pair = encodePair(cells[i], cells[j]) val score = joiningDist[pair] require(score != -1) if (score < joinablePairScore) { joinablePair = pair joinablePairScore = score } } return joinablePair } val dirToFinish = IntArray(n * n) fun bfs(init: Int): Pair<IntArray, IntArray> { if (isWall[init]) return intArrayOf() to intArrayOf() val dist = IntArray(n * n) { -1 } val queue = IntArray(n * n) dist[init] = 0 queue[0] = init var low = 0; var high = 1 while (low < high) { val cell = queue[low++] for (d in 0 until 4) { val cell2 = nei[cell][d] if (cell2 == -1 || dist[cell2] != -1) continue dist[cell2] = dist[cell] + 1 queue[high++] = cell2 dirToFinish[cell2] = d xor 2 } } return dist to queue } val bfsResults = List(n * n) { bfs(it) } val dist = bfsResults.map { it.first } // val bfsQueues = bfsResults.map { it.second } val start = encode(1, 1) val finish = encode(n - 2, n - 2) val distFinish = dist[finish] var listTooLarge: List<Int>? = null fun Cells(list: List<Int>): Cells { listTooLarge = list if (list.isEmpty()) return -2 val yMin = list.minOf { decode(it).first } val xMin = list.minOf { decode(it).second } var result = (yMin.toLong() shl 59) or (xMin.toLong() shl 54) for (cell in list) { val (yCell, xCell) = decode(cell) val y = yCell - yMin if (y !in 0 until squareSize) return -1 val x = xCell - xMin if (x !in 0 until squareSize) return -1 result = result.setBit(y * squareSize + x) } listTooLarge = null return result } fun Cells.size() = this.shl(10).countOneBits() fun Cells.yxMin(): Pair<Int, Int> { val yMin = (this ushr 59).toInt() val xMin = ((this shl 5) ushr 59).toInt() return yMin to xMin } fun Cells.cellMin(): Int { val (yMin, xMin) = yxMin() return encode(yMin, xMin) } fun Cells.forEach(action: (Int, Int) -> Unit) { val (yMin, xMin) = yxMin() val bits = ((this shl 10) ushr 10).countSignificantBits() for (index in 0 until bits) { if (!this.hasBit(index)) continue action(yMin + index / squareSize, xMin + index % squareSize) } } fun Cells.toList(): List<Int> { if (this == -2L) return listOf() val cellsList = mutableListOf<Int>() forEach { y, x -> cellsList.add(encode(y, x)) } return cellsList } val memoMoved = mutableMapOf<Cells, Cells>() fun Cells.moved(d: Int): Cells { val code = this or (d.toLong() shl 52) val remembered = memoMoved[code] if (remembered != null) return remembered // TODO rewrite without lists val new = mutableListOf<Int>() this.forEach { y, x -> val cell = encode(y, x) val newCell = afterMove(cell, d) if (newCell != finish) new.add(newCell) } val result = Cells(new) if (result != -1L) memoMoved[code] = result return result } fun List<Int>.moved(d: Int): Cells { val new = mutableListOf<Int>() for (cell in this) { val newCell = afterMove(cell, d) if (newCell != finish) new.add(newCell) } return Cells(new) } val memoAfterQuestionMark = mutableMapOf<Cells, Cells>() fun Cells.afterQuestionMark(): Cells { val remembered = memoAfterQuestionMark[this] if (remembered != null) return remembered // TODO rewrite without lists val new = mutableListOf<Int>() this.forEach { y, x -> val cell = encode(y, x) for (d in 0 until 4) { val newCell = afterMove(cell, d) if (newCell != finish) new.add(newCell) } } val result = Cells(new) if (result != -1L) memoAfterQuestionMark[this] = result return result } fun List<Int>.afterQuestionMark(): Cells { val new = mutableListOf<Int>() for (cell in this) { for (d in 0 until 4) { val newCell = afterMove(cell, d) if (newCell != finish) new.add(newCell) } } return Cells(new) } val init = Cells(listOf(start)) val answer = StringBuilder() fun answerChar(c: Char) { answer.append(c) log { "MOVE: $c" } } fun answer(d: Int) = answerChar(DIR[d]) fun answerQuestion() = answerChar('?') fun magicScore(cellsNew: List<Int>, cellsOldSize: Int): Double { if (cellsNew.isEmpty()) return -1e100 var count = 0 var sum = 0 var max = 0 var maxDistToFinish = 0 for (i in cellsNew.indices) { maxDistToFinish = maxOf(maxDistToFinish, distFinish[cellsNew[i]]) for (j in 0 until i) { val x = dist[cellsNew[i]][cellsNew[j]] count++ sum += x max = maxOf(max, x) } } val magicScore = max * 1e6 + cellsNew.size * 1e4 + maxDistToFinish * 1e2 + sum / (count + 0.1) return magicScore } fun searchOneMoveForGroup(cells: List<Int>, depth: Int) = (0 until (1 shl (2 * depth))).minBy { path -> var p = path var c = cells var improvementScore = 0 repeat(depth) { val cellsNewOptimistic = c.moved(p % 4) p /= 4 c = if (cellsNewOptimistic != -1L) cellsNewOptimistic.toList() else listTooLarge!!.toSet().toList() if (it == 0) improvementScore = c.size.compareTo(cells.size) + 1 } magicScore(c, cells.size) + improvementScore * 1e9 }.let { it % 4 } fun bestMoveForGroup(cellsIn: List<Int>): Int { val cells = cellsIn.toSet().sorted() log { "det cells $cells" } val jPair = joinablePair(cells) val jDist = joiningDist[jPair] val jMove = joiningMove[jPair] val fClosest = cells.minBy { distFinish[it] } val fDist = distFinish[fClosest] val fMove = dirToFinish[fClosest] log { "need j$jDist / f$fDist" } if (jDist > 1) return if (jDist < fDist) jMove else fMove val magicDepth = if (cells.size > squareSize * squareSize) 1 else 2 return searchOneMoveForGroup(cells, magicDepth) } val memoBestMove = mutableMapOf<Cells, Int>() tailrec fun solve(cells: Cells, zStart: Int) { val zNextQuestion = (zStart until mask.size).firstOrNull { mask[it] } ?: mask.size val withoutQuestions = zNextQuestion - zStart require(withoutQuestions >= 0) log { "=== z=$zStart === , have ${withoutQuestions}" } log { "$cells (size ${cells.size()})" } log { listTooLarge } if (cells == -2L) return if (cells == -1L) { val cellsList = listTooLarge!!.toSet().toList() if (withoutQuestions == 0) { answerQuestion() return solve(cellsList.afterQuestionMark(), zStart + 1) } val move = bestMoveForGroup(cellsList) answer(move) return solve(cellsList.moved(move), zStart + 1) } val cellsSize = cells.size() if (withoutQuestions == 0) { answerQuestion() return solve(cells.afterQuestionMark(), zStart + 1) } if (cellsSize == 1) { val cell = cells.cellMin() if (withoutQuestions >= distFinish[cell]) { val move = dirToFinish[cell] answer(move) return solve(cells.moved(move), zStart + 1) } val move = dirToFinish[cell] answer(move) return solve(cells.moved(move), zStart + 1) } else { val move = memoBestMove.getOrPut(cells) { bestMoveForGroup(cells.toList()) } answer(move) return solve(cells.moved(move), zStart + 1) } } solve(init, 0) try { checkTimeLimit() } catch (_: TimeOutException) { } log?.close() return answer.toString() } typealias Cells = Long private fun Long.bit(index: Int) = ushr(index).toInt() and 1 private fun Long.hasBit(index: Int) = bit(index) != 0 private fun Long.setBit(index: Int) = or(1L shl index) private fun Long.countSignificantBits() = Long.SIZE_BITS - java.lang.Long.numberOfLeadingZeros(this) val DY = intArrayOf(0, 1, 0, -1) val DX = intArrayOf(1, 0, -1, 0) const val DIR = "RDLU" private class TimeOutException : RuntimeException() fun BufferedReader.readln() = readLine()!! fun BufferedReader.readStrings() = readln().split(" ") fun BufferedReader.readInt() = readln().toInt() fun solveIO(`in`: BufferedReader, out: PrintWriter): List<Any> { // val toVisualize = if (SUBMIT) null else mutableListOf<Any>() val n = `in`.readInt() val maze = List(n) { `in`.readLine() } `in`.readInt() val mask = `in`.readln() val answer = solve(maze, mask) out.println(answer) out.close() return listOf(answer) } private inline fun log(msg: () -> Any?) { log?.println(msg()) } private inline fun info(msg: () -> Any?) { if (VERBOSE) msg().also { print("$it\t"); log { it } } } fun main() { @Suppress("USELESS_ELVIS", "UNNECESSARY_SAFE_CALL") EVALUATOR?.invoke() ?: solveIO(System.`in`.bufferedReader(), PrintWriter(System.out)) }
0
Java
1
9
bf2846347011309aace0c4a04ac5355296dfbd90
11,412
competitions
The Unlicense
src/com/hxz/mpxjs/web/symbols/VueDocumentedItemSymbol.kt
wuxianqiang
508,329,768
false
{"Kotlin": 1447881, "Vue": 237479, "TypeScript": 106023, "JavaScript": 93869, "HTML": 17163, "Assembly": 12226, "Lex": 11227, "Java": 2846, "Shell": 1917, "Pug": 338}
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.hxz.mpxjs.web.symbols import com.intellij.webSymbols.PsiSourcedWebSymbol import com.intellij.model.Symbol import com.intellij.model.presentation.SymbolPresentation //import com.intellij.navigation.TargetPresentation import com.intellij.psi.PsiElement import com.hxz.mpxjs.VueBundle import com.hxz.mpxjs.codeInsight.documentation.VueDocumentedItem import com.hxz.mpxjs.codeInsight.documentation.VueItemDocumentation import java.util.* abstract class VueDocumentedItemSymbol<T : VueDocumentedItem>( override val name: String, protected val item: T) : VueWebSymbolBase(), PsiSourcedWebSymbol { override val source: PsiElement? get() = item.source val rawSource: PsiElement? get() = item.rawSource override val description: String? get() = item.description // override val presentation: TargetPresentation // get() = TargetPresentation.builder(VueBundle.message("vue.symbol.presentation", VueItemDocumentation.typeOf(item), name)) // .icon(icon) // .presentation() override fun equals(other: Any?): Boolean = other === this || (other is VueDocumentedItemSymbol<*> && other.javaClass == this.javaClass && name == other.name && item == other.item) override fun hashCode(): Int = Objects.hash(name, item) override fun isEquivalentTo(symbol: Symbol): Boolean = if (symbol is VueDocumentedItemSymbol<*>) symbol === this || (symbol.javaClass == this.javaClass && symbol.name == name) //&& VueDelegatedContainer.unwrap(item) == VueDelegatedContainer.unwrap(symbol.item)) else super.isEquivalentTo(symbol) }
2
Kotlin
0
4
e069e8b340ab04780ac13eab375d900f21bc7613
1,755
intellij-plugin-mpx
Apache License 2.0
plugins/publish-plugin/src/main/kotlin/AndroidAppyxPublishPlugin.kt
bumble-tech
493,334,393
false
{"Kotlin": 829246, "Python": 2324, "HTML": 347, "Shell": 327, "CSS": 134}
import com.android.build.gradle.LibraryExtension import org.gradle.api.Project import org.gradle.api.publish.PublicationContainer import org.gradle.api.publish.maven.MavenPublication import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.get internal class AndroidAppyxPublishPlugin : ProjectPlugin() { override fun configureDocAndSources(project: Project) { project.configure<LibraryExtension> { publishing { singleVariant(getComponentName()) { withSourcesJar() /** * Currently not working with Multiplatform plugin and AGP 8+ * https://github.com/bumble-tech/appyx/issues/582 */ // withJavadocJar() } } } } override fun apply(project: Project) { project.extensions.create("publishingPlugin", ProjectPluginExtension::class.java) super.apply(project) } override fun PublicationContainer.createPublications(project: Project) { create<MavenPublication>("androidRelease") { val artifactId = project.extensions.getByType(ProjectPluginExtension::class.java).artifactId if (artifactId.isNotEmpty()) { this.artifactId = artifactId } from(project.components[getComponentName()]) configurePublication(project) } } override fun getComponentName(): String = "release" }
85
Kotlin
54
997
f5cc89fbdf9a168a70f8e9f11313e6524914179a
1,543
appyx
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/twotone/Keysquare.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.twotone 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.Round import androidx.compose.ui.graphics.StrokeJoin 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 moe.tlaster.icons.vuesax.vuesaxicons.TwotoneGroup public val TwotoneGroup.Keysquare: ImageVector get() { if (_keysquare != null) { return _keysquare!! } _keysquare = Builder(name = "Keysquare", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 22.0f) horizontalLineTo(15.0f) curveTo(20.0f, 22.0f, 22.0f, 20.0f, 22.0f, 15.0f) verticalLineTo(9.0f) curveTo(22.0f, 4.0f, 20.0f, 2.0f, 15.0f, 2.0f) horizontalLineTo(9.0f) curveTo(4.0f, 2.0f, 2.0f, 4.0f, 2.0f, 9.0f) verticalLineTo(15.0f) curveTo(2.0f, 20.0f, 4.0f, 22.0f, 9.0f, 22.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.2792f, 13.6096f) curveTo(15.1492f, 14.7396f, 13.5292f, 15.0896f, 12.0992f, 14.6396f) lineTo(9.5092f, 17.2196f) curveTo(9.3292f, 17.4096f, 8.9592f, 17.5296f, 8.6892f, 17.4896f) lineTo(7.4892f, 17.3296f) curveTo(7.0892f, 17.2796f, 6.7292f, 16.8996f, 6.6692f, 16.5096f) lineTo(6.5092f, 15.3096f) curveTo(6.4692f, 15.0496f, 6.5992f, 14.6796f, 6.7792f, 14.4896f) lineTo(9.3592f, 11.9096f) curveTo(8.9192f, 10.4796f, 9.2592f, 8.8596f, 10.3892f, 7.7297f) curveTo(12.0092f, 6.1097f, 14.6492f, 6.1097f, 16.2792f, 7.7297f) curveTo(17.8992f, 9.3397f, 17.8992f, 11.9796f, 16.2792f, 13.6096f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.4496f, 16.2799f) lineTo(9.5996f, 15.4199f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.3949f, 10.7002f) horizontalLineTo(13.4039f) } } .build() return _keysquare!! } private var _keysquare: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
3,864
VuesaxIcons
MIT License
src/main/kotlin/com/github/l1an/yubattlemusic/YuBattleMusic.kt
L1-An
777,987,419
false
{"Kotlin": 11342}
package com.github.l1an.yubattlemusic import taboolib.common.platform.Platform import taboolib.common.platform.Plugin import taboolib.common.platform.function.console import taboolib.common.platform.function.pluginVersion import taboolib.module.chat.colored import taboolib.module.metrics.Metrics object YuBattleMusic : Plugin() { val messagePrefix = "&f[ &3YuBattleMusic &f]" override fun onEnable() { Metrics(21427, pluginVersion, Platform.BUKKIT) console().sendMessage("$messagePrefix &aYuBattleMusic has been loaded! - $pluginVersion".colored()) console().sendMessage("$messagePrefix &bAuthor by L1An".colored()) } }
0
Kotlin
0
0
587aba762b885a9c1ec73e85fdf05809a0d43718
660
YuBattleMusic
Creative Commons Zero v1.0 Universal
data/releases/src/main/java/tech/dalapenko/data/releases/datasource/remote/RemoteDataSource.kt
dalapenko
739,864,810
false
{"Kotlin": 136155, "Dockerfile": 1314}
package tech.dalapenko.data.releases.datasource.remote import tech.dalapenko.data.releases.model.Release import tech.dalapenko.core.network.adapter.NetworkResponse interface RemoteDataSource { suspend fun getReleaseList(month: String, year: Int): NetworkResponse<List<Release>> }
0
Kotlin
0
0
c1c5e965deb7216fbccf050175a66f9a07993079
286
kinosearch
Apache License 2.0
app/src/main/java/ru/mrfrozzen/cookbook/data/CategoryWithRecipes.kt
MrFrozzen
222,162,272
false
null
package ru.mrfrozzen.cookbook.data import androidx.room.Embedded import androidx.room.Relation import ru.mrfrozzen.cookbook.data.db.entity.Category import ru.mrfrozzen.cookbook.data.db.entity.Recipe class CategoryWithRecipes { @Embedded var category: Category? = null @Relation(parentColumn = "category_id", entityColumn = "category_category_id", entity = Recipe::class) var recipes: List<Recipe>? = null }
0
Kotlin
0
0
0d417a0beb30d3b9628372f67395ae7afbb0e715
427
Cookbook
Apache License 2.0
data/repository/city/cityrepo-impl/src/test/kotlin/com/francescsoftware/weathersample/data/repository/city/impl/CityRepositoryImplTest.kt
fvilarino
355,724,548
false
{"Kotlin": 593148, "Shell": 60}
package com.francescsoftware.weathersample.data.repository.city.impl import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isInstanceOf import assertk.assertions.isNotNull import com.francescsoftware.weathersample.core.type.either.Either import com.francescsoftware.weathersample.core.type.either.throwableOrNull import com.francescsoftware.weathersample.data.repository.city.api.CitiesException import com.francescsoftware.weathersample.data.repository.city.api.model.City import com.francescsoftware.weathersample.data.repository.city.api.model.Coordinates import com.francescsoftware.weathersample.testing.fake.dispatcher.TestDispatcherProvider import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import retrofit2.Retrofit private val ExpectedCities = listOf( City( id = 3323992, city = "Milwich", name = "Milwich", region = "Staffordshire", regionCode = "STS", country = "United Kingdom", countryCode = "GB", coordinates = Coordinates( latitude = 52.8879, longitude = -2.04314, ), ), City( id = 3415353, city = "Milwino", name = "Milwino", region = "Pomeranian Voivodeship", regionCode = "22", country = "Poland", countryCode = "PL", coordinates = Coordinates( latitude = 54.51944, longitude = 18.13167, ), ), City( id = 3371102, city = "Milwaukee", name = "Milwaukee", region = "North Carolina", regionCode = "NC", country = "United States of America", countryCode = "US", coordinates = Coordinates( latitude = 36.4056, longitude = -77.2322, ), ), ) internal class CityRepositoryImplTest { private val json = Json { ignoreUnknownKeys = true } private val mediaType = "application/json".toMediaType() private val mockWebServer = MockWebServer() private val service = Retrofit.Builder() .baseUrl(mockWebServer.url("/")) .addConverterFactory(json.asConverterFactory(mediaType)) .client(OkHttpClient.Builder().build()) .build() .create(CityService::class.java) @AfterEach fun cleanUp() { mockWebServer.shutdown() } @Test fun `success network response returns cities`() = runTest { val networkResponse = MockResponse() .addHeader("Content-Type", "application/json; charset=utf-8") .setResponseCode(200) .setBody(CitiesResponse) mockWebServer.enqueue(networkResponse) val repository = CityRepositoryImpl( cityService = service, dispatcherProvider = TestDispatcherProvider(), ) val response = repository.getCities(prefix = "", limit = 10) assertThat(response).isInstanceOf(Either.Success::class.java) val cityList = (response as Either.Success).value.cities assertThat(cityList.size).isEqualTo(ExpectedCities.size) cityList.forEachIndexed { index, city -> assertThat(city).isEqualTo(ExpectedCities[index]) } } @Test fun `invalid data returns error`() = runTest { val networkResponse = MockResponse() .addHeader("Content-Type", "application/json; charset=utf-8") .setResponseCode(200) .setBody(InvalidCitiesResponse) mockWebServer.enqueue(networkResponse) val repository = CityRepositoryImpl( cityService = service, dispatcherProvider = TestDispatcherProvider(), ) val response = repository.getCities(prefix = "", limit = 10) assertThat(response).isInstanceOf(Either.Failure::class.java) } @Test fun `400 network error returns error`() = runTest { val networkResponse = MockResponse() .addHeader("Content-Type", "application/json; charset=utf-8") .setResponseCode(404) .setBody("{}") mockWebServer.enqueue(networkResponse) val repository = CityRepositoryImpl( cityService = service, dispatcherProvider = TestDispatcherProvider(), ) val response = repository.getCities(prefix = "", limit = 10) assertThat(response).isInstanceOf<Either.Failure>() assertThat(response.throwableOrNull()).isNotNull().isInstanceOf<CitiesException>() } @Test fun `500 network error returns error`() = runTest { val networkResponse = MockResponse() .addHeader("Content-Type", "application/json; charset=utf-8") .setResponseCode(500) .setBody("{}") mockWebServer.enqueue(networkResponse) val repository = CityRepositoryImpl( cityService = service, dispatcherProvider = TestDispatcherProvider(), ) val response = repository.getCities(prefix = "", limit = 10) assertThat(response).isInstanceOf<Either.Failure>() assertThat(response.throwableOrNull()).isNotNull().isInstanceOf<CitiesException>() } }
2
Kotlin
1
39
ad29136cf04ae479db6b50109d3410e54e881f61
5,483
Weather-Sample
Apache License 2.0
src/main/kotlin/me/camdenorrb/purrbot/cmd/impl/LeaderBoardCmd.kt
camdenorrb
169,963,697
false
null
package me.camdenorrb.purrbot.cmd.impl import me.camdenorrb.purrbot.cmd.struct.MemberCmd import me.camdenorrb.purrbot.cmd.struct.context.MemberCmdContext import me.camdenorrb.purrbot.data.ChannelData import me.camdenorrb.purrbot.store.ScramblerStore import me.camdenorrb.purrbot.utils.createEmbed import net.dv8tion.jda.core.entities.Guild import net.dv8tion.jda.core.entities.Member import net.dv8tion.jda.core.entities.MessageChannel import java.awt.Color class LeaderBoardCmd(val scramblerStore: ScramblerStore) : MemberCmd("leaderboard") { override val name = "Leader Board Command" override val desc = "A leaderboard of the best scramble players" override fun MemberCmdContext.execute() { val embed = createEmbed { setColor(Color.GREEN) val winners = scramblerStore.data().values.sortedDescending() var count = 1 addField("Unscrambler Leaders", winners.take(10).joinToString("\n") { "**${count++}**. ${it.displayName} | ${it.wins}" }, false) } reply(embed) } override fun canExecute(guild: Guild, channel: MessageChannel, member: Member): Boolean { return channel.idLong == ChannelData.BOT_CMDS_ID } }
0
Kotlin
0
0
96aca918cd2b59caa9678080101f37f6410d7db5
1,253
PurrBot
MIT License
features/quiz/src/main/java/com/zigis/paleontologas/features/quiz/stories/finalresult/QuizFinalResultIntent.kt
edgar-zigis
240,962,785
false
{"Kotlin": 217487}
package com.zigis.paleontologas.features.quiz.stories.finalresult import com.zigis.paleontologas.core.architecture.interfaces.IIntent sealed class QuizFinalResultIntent : IIntent { data class Initialize(val mark: Int) : QuizFinalResultIntent() data object InvokeBack : QuizFinalResultIntent() }
0
Kotlin
16
123
5dbf133cc334c949d10a6caf37a8a698ecd873ca
304
Paleontologas
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/filled/ArrowUpSquare.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.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 com.woowla.compose.icon.collections.tabler.tabler.FilledGroup public val FilledGroup.ArrowUpSquare: ImageVector get() { if (_arrowUpSquare != null) { return _arrowUpSquare!! } _arrowUpSquare = Builder(name = "ArrowUpSquare", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.852f, 2.011f) lineToRelative(0.058f, -0.007f) lineToRelative(0.09f, -0.004f) lineToRelative(0.075f, 0.003f) lineToRelative(0.126f, 0.017f) lineToRelative(0.111f, 0.03f) lineToRelative(0.111f, 0.044f) lineToRelative(0.098f, 0.052f) lineToRelative(0.104f, 0.074f) lineToRelative(0.082f, 0.073f) lineToRelative(3.0f, 3.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, -1.414f, 1.414f) lineToRelative(-1.293f, -1.292f) verticalLineToRelative(10.585f) horizontalLineToRelative(1.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f) verticalLineToRelative(4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f) horizontalLineToRelative(-4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f) verticalLineToRelative(-4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f) horizontalLineToRelative(1.0f) verticalLineToRelative(-10.585f) lineToRelative(-1.293f, 1.292f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.32f, 0.083f) lineToRelative(-0.094f, -0.083f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -1.414f) lineToRelative(3.0f, -3.0f) quadToRelative(0.053f, -0.054f, 0.112f, -0.097f) lineToRelative(0.11f, -0.071f) lineToRelative(0.114f, -0.054f) lineToRelative(0.105f, -0.035f) close() } } .build() return _arrowUpSquare!! } private var _arrowUpSquare: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,082
compose-icon-collections
MIT License
src/main/java/net/ccbluex/liquidbounce/features/module/modules/world/Fisher.kt
Rmejia39
733,988,804
false
{"Kotlin": 2304965, "Java": 1271227, "GLSL": 13515, "JavaScript": 8926}
/* * FDPClient Hacked Client * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge by LiquidBounce. * https://github.com/SkidderMC/FDPClient/ */ package net.ccbluex.liquidbounce.features.module.modules.world import net.ccbluex.liquidbounce.event.EventTarget import net.ccbluex.liquidbounce.event.PacketEvent import net.ccbluex.liquidbounce.event.UpdateEvent import net.ccbluex.liquidbounce.features.module.Module import net.ccbluex.liquidbounce.features.module.ModuleCategory import net.ccbluex.liquidbounce.features.module.ModuleInfo import net.ccbluex.liquidbounce.utils.MathUtils.inRange import net.ccbluex.liquidbounce.utils.timer.MSTimer import net.ccbluex.liquidbounce.features.value.BoolValue import net.ccbluex.liquidbounce.features.value.IntegerValue import net.ccbluex.liquidbounce.features.value.ListValue import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement import net.minecraft.network.play.server.S12PacketEntityVelocity import net.minecraft.network.play.server.S29PacketSoundEffect @ModuleInfo(name = "Fisher", category = ModuleCategory.WORLD) object Fisher : Module() { private val detectionValue = ListValue("Detection", arrayOf("Motion", "Sound"), "Sound") private val recastValue = BoolValue("Recast", true) private val recastDelayValue = IntegerValue("RecastDelay", 1, 0, 1000).displayable { recastValue.get() } private var stage = Stage.NOTHING private val recastTimer = MSTimer() override fun onDisable() { stage = Stage.NOTHING } @EventTarget fun onUpdate(event: UpdateEvent) { if (stage == Stage.RECOVERING) { mc.netHandler.addToSendQueue(C08PacketPlayerBlockPlacement(mc.thePlayer.heldItem)) stage = if (recastValue.get()) { recastTimer.reset() Stage.RECASTING } else { Stage.NOTHING } return } else if (stage == Stage.RECASTING) { if (recastTimer.hasTimePassed(recastDelayValue.get().toLong())) { mc.netHandler.addToSendQueue(C08PacketPlayerBlockPlacement(mc.thePlayer.heldItem)) stage = Stage.NOTHING } } } @EventTarget fun onPacket(event: PacketEvent) { val packet = event.packet if (detectionValue.get() == "Sound" && packet is S29PacketSoundEffect && mc.thePlayer?.fishEntity != null && packet.soundName == "random.splash" && packet.x.inRange(mc.thePlayer.fishEntity.posX, 1.5) && packet.z.inRange(mc.thePlayer.fishEntity.posZ, 1.5)) { recoverFishRod() } else if (detectionValue.get() == "Motion" && packet is S12PacketEntityVelocity && mc.thePlayer?.fishEntity != null && packet.entityID == mc.thePlayer.fishEntity.entityId && packet.motionX == 0 && packet.motionY != 0 && packet.motionZ == 0) { recoverFishRod() } } private fun recoverFishRod() { if (stage != Stage.NOTHING) { return } stage = Stage.RECOVERING } private enum class Stage { NOTHING, RECOVERING, RECASTING } }
3
Kotlin
0
0
b48c4e83c888568111a6665037db7fd3f7813ed3
3,183
FDPClient
MIT License
app/src/main/java/com/samuelokello/kazihub/data/repository/AuthRepositoryImp.kt
OkelloSam21
749,782,789
false
{"Kotlin": 278163}
package com.samuelokello.kazihub.data.repository import android.util.Log import com.samuelokello.kazihub.data.model.profile.ProfileResponse import com.samuelokello.kazihub.data.model.sign_in.SignInRequest import com.samuelokello.kazihub.data.model.sign_in.SignInResponse import com.samuelokello.kazihub.data.remote.KaziHubApi import com.samuelokello.kazihub.di.TokenManager import com.samuelokello.kazihub.domain.model.shared.auth.sign_up.SignUpRequest import com.samuelokello.kazihub.domain.model.shared.auth.sign_up.SignUpResponse import com.samuelokello.kazihub.domain.repositpry.AuthRepository import com.samuelokello.kazihub.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject class AuthRepositoryImpl @Inject constructor( private val api: KaziHubApi, private val tokenManager: TokenManager ) : AuthRepository { override suspend fun signUp(signUpRequest: SignUpRequest): Resource<SignUpResponse> = withContext(Dispatchers.IO) { try { val response = api.signUp(signUpRequest) Log.d(TAG, "signUp: $response") Resource.Success(response) } catch (e: Exception) { Log.e(TAG, "signUp error: ${e.message}", e) Resource.Error(e.message ?: "An unexpected error occurred") } } override suspend fun signIn(signInRequest: SignInRequest): Resource<SignInResponse> = withContext(Dispatchers.IO) { try { val response = api.signIn(signInRequest) response.data?.accessToken?.let { tokenManager.setToken(it) } Log.d(TAG, "signIn: ${response.data?.accessToken}") Resource.Success(response) } catch (e: Exception) { Log.e(TAG, "signIn error: ${e.message}", e) Resource.Error(e.message ?: "An unexpected error occurred") } } override suspend fun getCurrentUser(): Resource<ProfileResponse> = withContext(Dispatchers.IO) { try { val response = api.getCurrentUser() Log.d(TAG, "getCurrentUser: $response") Resource.Success(response) } catch (e: Exception) { Log.e(TAG, "getCurrentUser error: ${e.message}", e) Resource.Error(e.message ?: "An unexpected error occurred") } } override suspend fun refreshToken(): Resource<SignInResponse> = withContext(Dispatchers.IO) { try { val response = api.refreshToken(tokenManager.getToken()) response.data?.accessToken?.let { tokenManager.setToken(it) } Log.d(TAG, "refreshToken: ${response.data?.accessToken}") Resource.Success(response) } catch (e: Exception) { Log.e(TAG, "refreshToken error: ${e.message}", e) Resource.Error(e.message ?: "An unexpected error occurred") } } companion object { private const val TAG = "AuthRepositoryImpl" } }
0
Kotlin
0
0
510745d20b259d7930fa58481181080fd70a4a9f
3,139
KaziHub
MIT License
src/main/kotlin/io/ysakhno/adventofcode2015/util/AlgorithmsEx.kt
YSakhno
816,649,625
false
{"Kotlin": 93259}
@file:Suppress("unused") package io.ysakhno.adventofcode2015.util /** * Searches this list or its sub-range for an element for which the given [comparison] function returns zero using the * binary search algorithm. Unlike the [binarySearch] function from Kotlin Standard Library, this function (and * consequently, the `comparison` lambda) is inlineable. * * The list is expected to be sorted so that the signs of the [comparison] function's return values ascend on the list * elements, i.e. negative values come before zero and zeroes come before positive values. Otherwise, the result is * undefined. * * If the list contains multiple elements for which [comparison] returns zero, there is no guarantee, which one will be * found. * * @param comparison function that returns zero when called on the list element being searched. On the elements coming * before the target element, the function must return negative values; on the elements coming after the target element, * the function must return positive values. * @return the index of the found element, if it is contained in the list within the specified range; otherwise, the * inverted insertion point `(-insertion point - 1)`. The _insertion point_ is defined as the index at which the element * should be inserted, so that the list (or the specified subrange of list) still remains sorted. */ inline fun <E> List<E>.inlinableBinarySearch(fromIndex: Int = 0, toIndex: Int = size, comparison: (E) -> Int): Int { checkBoundsStartEnd(fromIndex, toIndex, size) var low = fromIndex var high = toIndex - 1 while (low <= high) { val mid = (low + high).ushr(1) // safe from overflows val midVal = get(mid) val cmp = comparison(midVal) if (cmp < 0) low = mid + 1 else if (cmp > 0) high = mid - 1 else return mid // key found } return -(low + 1) // key not found } /** * Searches this list or its sub-range for an element having the key returned by the specified [selector] function equal * to the provided [key] value using the binary search algorithm. Unlike the [binarySearchBy] function from Kotlin * Standard Library, this function (and consequently, the `selector` lambda) is inlineable. * * The list is expected to be sorted into ascending order according to the Comparable natural ordering of keys of its * elements (the values returned by [selector]). Otherwise, the result is undefined. * * If the list contains multiple elements with the specified [key], there is no guarantee, which one will be found. * * @return the index of the element with the specified [key], if it is contained in the list within the specified range; * otherwise, the inverted insertion point `(-insertion point - 1)`. The insertion point is defined as the index at * which the element should be inserted, so that the list (or the specified subrange of list) still remains sorted. */ inline fun <E, K : Comparable<K>> List<E>.inlinableBinarySearchBy( key: K, fromIndex: Int = 0, toIndex: Int = size, selector: (E) -> K, ): Int = inlinableBinarySearch(fromIndex, toIndex) { selector(it).compareTo(key) } /** Returns a value _x_ such that _[f] (x)_ is `true`. Based on the values of [f] at [lo] and [hi]. */ inline fun bisect(lo: Double = 0.0, hi: Double? = null, eps: Double = 1e-9, f: (Double) -> Boolean): Double { val boolOfLo = f(lo) var high = hi ?: run { var offset = 1.0 while (f(lo + offset) == boolOfLo) { offset += offset * 0.5 } lo + offset } require(f(high) != boolOfLo) { "f(lo) must not be equal to f(hi) (hi = $high)" } var low = lo while (high - low > eps) { val mid = (high + low) / 2 if (f(mid) == boolOfLo) { low = mid } else { high = mid } } return if (boolOfLo) low else high } /** * Checks [start] and [end] indices against `0` and [size] bounds. * * @throws [IndexOutOfBoundsException] if [start] is negative, or [end] is greater than [size]. * @throws [IllegalArgumentException] if [start] is greater than [end]. */ fun checkBoundsStartEnd(start: Int, end: Int, size: Int): Unit = when { start > end -> throw IllegalArgumentException("Start index ($start) must not be greater than end index ($end).") start < 0 -> throw IndexOutOfBoundsException("Start index ($start) must be greater than or equal to zero.") end > size -> throw IndexOutOfBoundsException("End index ($end) must not be greater than size ($size).") else -> Unit }
0
Kotlin
0
0
200685847c7abf2e66f6af95cb3982a8b42713b4
4,575
advent-of-code-2015-in-kotlin
MIT License
sample/src/main/java/com/synesthesia/pushmanager/sample/view/PushTokenActivity.kt
synesthesia-it
316,270,228
false
null
// // Created by <NAME> on 25/11/2020. // Copyright © 2020 Synesthesia. All rights reserved. // package com.synesthesia.pushmanager.sample.view import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.activity.viewModels import androidx.fragment.app.FragmentActivity import com.android.app.R import com.synesthesia.pushmanager.sample.viewmodel.PushTokenViewModel class PushTokenActivity : FragmentActivity() { private val pushTokenViewModel by viewModels<PushTokenViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_push_token) pushTokenViewModel.token.observe(this@PushTokenActivity, { findViewById<TextView>(R.id.tv_push_service)?.text = "Push Service: ${it.tokenType.name}" findViewById<TextView>(R.id.tv_token)?.text = "Push Token: ${it.token}" }) findViewById<Button>(R.id.btn_get_token)?.setOnClickListener { pushTokenViewModel.getTokenWithCoroutine() } } }
0
Kotlin
0
4
d7937a91b184f9f36839b45712b9b7fe70e844c6
1,101
PushManager
MIT License
blockstack-sdk/src/main/java/org/blockstack/android/sdk/Scopes.kt
fiatexodus
146,040,832
true
{"JavaScript": 5132748, "Kotlin": 102301, "HTML": 4872, "CSS": 1691}
package org.blockstack.android.sdk /** * An enum of scopes supported in Blockstack Authentication. * * @property scope identifies the permission, same as in blockstack.js */ enum class Scope(val scope: String) { /** * Read and write data to the user's Gaia hub in an app-specific storage bucket. * * This is the default scope. */ StoreWrite("store_write"), /** * Publish data so that other users of the app can discover and interact with the user */ PublishData("publish_data"), /** * Requests the user's email if available */ Email("email"); /** * returns the scope as string */ override fun toString(): String { return scope } companion object { /** * converts an array of scopes into a string usable by blockstack.js */ @JvmStatic fun scopesArrayToJSONString(scopes: Array<Scope>): String { return scopes.joinToString(prefix = "[", transform = {"\"${it.scope}\""}, postfix = "]") } } }
0
JavaScript
0
0
6a34b6abf0b3c2c9e19c59bdb9364d219ff157a6
1,061
blockstack-android
MIT License
kProperties-core/src/commonMain/kotlin/de/kotlinBerlin/kProperties/binding/CombinedBindingsFactory.kt
KotlinBerlin
276,181,033
false
null
@file:Suppress("unused") package de.kotlinBerlin.kProperties.binding import de.kotlinBerlin.kProperties.constants.toObservableConst import de.kotlinBerlin.kProperties.value.KObservableValue /** * Creates a new [KBinding] which observes [this] as well as all of [anObservablesList] and combines their values * using [aMapper] function. */ fun <T> KObservableValue<T>.combineObservables( vararg anObservablesList: KObservableValue<T>, aMapper: T.(T) -> T ): KBinding<T> = ComplexKBinding(this, *anObservablesList, func = { tempObservables -> tempObservables.map { it.value }.reduce(aMapper) }) /** Creates a new [KBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, R> KObservableValue<T>.combineValue(aValue: T1, aMapper: T.(T1) -> R): KBinding<R> = this.combine(aValue.toObservableConst(), aMapper) /** Creates a new [KBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, R> KObservableValue<T>.combine(anObservable: KObservableValue<T1>, aMapper: T.(T1) -> R): KBinding<R> = ComplexBinaryKBinding(this, anObservable) { o1, o2 -> aMapper.invoke(o1.value, o2.value) } /** Creates a new [KBooleanBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, B : Boolean?> KObservableValue<T>.combineValueToBoolean( aValue: T1, aMapper: T.(T1) -> B ): KBooleanBinding<B> = this.combineToBoolean(aValue.toObservableConst(), aMapper) /** Creates a new [KBooleanBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, B : Boolean?> KObservableValue<T>.combineToBoolean( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> B ): KBooleanBinding<B> = object : ComplexBinaryKBinding<T, T1, B>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KBooleanBinding<B> {} /** Creates a new [KStringBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, S : String?> KObservableValue<T>.combineValueToString(aValue: T1, aMapper: T.(T1) -> S): KStringBinding<S> = this.combineToString(aValue.toObservableConst(), aMapper) /** Creates a new [KStringBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, S : String?> KObservableValue<T>.combineToString( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> S ): KStringBinding<S> = object : ComplexBinaryKBinding<T, T1, S>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KStringBinding<S> {} /** Creates a new [KNumberBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, N : Number?> KObservableValue<T>.combineValueToNumber(aValue: T1, aMapper: T.(T1) -> N): KNumberBinding<N> = this.combineToNumber(aValue.toObservableConst(), aMapper) /** Creates a new [KNumberBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, N : Number?> KObservableValue<T>.combineToNumber( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> N ): KNumberBinding<N> = object : ComplexBinaryKBinding<T, T1, N>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KNumberBinding<N> {} /** Creates a new [KDoubleBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, D : Double?> KObservableValue<T>.combineValueToDouble(aValue: T1, aMapper: T.(T1) -> D): KDoubleBinding<D> = this.combineToDouble(aValue.toObservableConst(), aMapper) /** Creates a new [KBooleanBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, D : Double?> KObservableValue<T>.combineToDouble( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> D ): KDoubleBinding<D> = object : ComplexBinaryKBinding<T, T1, D>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KDoubleBinding<D> {} /** Creates a new [KFloatBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, F : Float?> KObservableValue<T>.combineValueToFloat(aValue: T1, aMapper: T.(T1) -> F): KFloatBinding<F> = this.combineToFloat(aValue.toObservableConst(), aMapper) /** Creates a new [KFloatBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, F : Float?> KObservableValue<T>.combineToFloat( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> F ): KFloatBinding<F> = object : ComplexBinaryKBinding<T, T1, F>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KFloatBinding<F> {} /** Creates a new [KLongBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, L : Long?> KObservableValue<T>.combineValueToLong(aValue: T1, aMapper: T.(T1) -> L): KLongBinding<L> = this.combineToLong(aValue.toObservableConst(), aMapper) /** Creates a new [KLongBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, L : Long?> KObservableValue<T>.combineToLong( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> L ): KLongBinding<L> = object : ComplexBinaryKBinding<T, T1, L>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KLongBinding<L> {} /** Creates a new [KIntBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, I : Int?> KObservableValue<T>.combineValueToInt(aValue: T1, aMapper: T.(T1) -> I): KIntBinding<I> = this.combineToInt(aValue.toObservableConst(), aMapper) /** Creates a new [KIntBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, I : Int?> KObservableValue<T>.combineToInt( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> I ): KIntBinding<I> = object : ComplexBinaryKBinding<T, T1, I>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KIntBinding<I> {} /** Creates a new [KShortBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, S : Short?> KObservableValue<T>.combineValueToShort(aValue: T1, aMapper: T.(T1) -> S): KShortBinding<S> = this.combineToShort(aValue.toObservableConst(), aMapper) /** Creates a new [KShortBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, S : Short?> KObservableValue<T>.combineToShort( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> S ): KShortBinding<S> = object : ComplexBinaryKBinding<T, T1, S>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KShortBinding<S> {} /** Creates a new [KByteBinding] which observes [this] and combines its value with [aValue] using [aMapper] function. */ fun <T, T1, B : Byte?> KObservableValue<T>.combineValuesToByte(aValue: T1, aMapper: T.(T1) -> B): KByteBinding<B> = this.combineToByte(aValue.toObservableConst(), aMapper) /** Creates a new [KByteBinding] which observes [this] and [anObservable] and combines their values using [aMapper] function. */ fun <T, T1, B : Byte?> KObservableValue<T>.combineToByte( anObservable: KObservableValue<T1>, aMapper: T.(T1) -> B ): KByteBinding<B> = object : ComplexBinaryKBinding<T, T1, B>(this, anObservable, func = { o1, o2 -> aMapper.invoke(o1.value, o2.value) }), KByteBinding<B> {}
0
Kotlin
0
1
e4f37018e15bb291c68b677d9b1d8b559d80f6d5
8,000
kProperties
Apache License 2.0
domain/src/main/kotlin/dev/notypie/domain/command/dto/SlackEventResponse.kt
TrulyNotMalware
810,739,918
false
{"Kotlin": 2097}
package dev.notypie.domain.command.dto open class SlackEventResponse( val ok: Boolean, val warning: String, val error: String, val needed: String, val provided: String ) { }
0
Kotlin
0
0
1957383269756118941225e4ce84bc0ba245e3ca
194
CodeCompanion
MIT License
app/src/main/java/io/agora/education/config/ConfigService.kt
AgoraIO-Community
330,886,965
false
null
package io.agora.education.config import io.agora.agoraeducore.core.internal.education.impl.network.HttpBaseRes import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path interface ConfigService { @GET("edu/v3/rooms/{roomUuid}/roles/{role}/users/{userUuid}/token") fun getConfigV3( @Path("roomUuid") roomUuid: String, @Path("role") role: Int, @Path("userUuid") userUuid: String ): Call<HttpBaseRes<ConfigData>> /** * token007 + check token * * 获取token007(sso登陆) */ @GET("edu/v4/rooms/{roomUuid}/roles/{role}/users/{userUuid}/token") fun getConfigV4( @Path("roomUuid") roomUuid: String, @Path("role") role: Int, @Path("userUuid") userUuid: String ): Call<HttpBaseRes<ConfigData>> }
4
Kotlin
19
16
1d58c5a056cf6d126d9796999f72a6c3a17b911e
797
CloudClass-Android
MIT License
src/main/kotlin/br/com/jiratorio/service/chart/HistogramService.kt
andrelugomes
230,294,644
true
{"Kotlin": 541514, "PLSQL": 366, "Dockerfile": 315, "TSQL": 269}
package br.com.jiratorio.service.chart import br.com.jiratorio.domain.entity.Issue import br.com.jiratorio.domain.entity.embedded.Histogram interface HistogramService { fun issueHistogram(issues: List<Issue>): Histogram }
0
null
0
1
168de10e5e53f31734937816811ac9dae6940202
230
jirareport
MIT License
src/main/kotlin/me/blast/command/slash/SlashCommand.kt
vyfor
681,682,310
false
{"Kotlin": 179726}
package me.blast.command.slash import me.blast.command.Arguments import me.blast.command.BaseCommand import me.blast.command.text.TextCommand import me.blast.command.argument.builder.ArgumentBuilder import org.javacord.api.entity.permission.PermissionType import kotlin.time.Duration abstract class SlashCommand( name: String, override val description: String = "No description provided", val type: String? = null, val permissions: List<PermissionType>? = null, val selfPermissions: List<PermissionType>? = null, val subcommands: List<TextCommand>? = null, val userCooldown: Duration = Duration.ZERO, val channelCooldown: Duration = Duration.ZERO, val serverCooldown: Duration = Duration.ZERO, val isNsfw: Boolean = false, val guildId: Long? = null, ) : ArgumentBuilder(guildId != null), BaseCommand { override val name = name.lowercase() init { if ( userCooldown.isNegative() || channelCooldown.isNegative() || serverCooldown.isNegative() ) throw IllegalArgumentException("Cooldown cannot be negative.") } abstract suspend fun Arguments.execute(ctx: SlashContext) }
0
Kotlin
0
5
1db06a6405010f53db2913fd7b071810b4007260
1,130
Cordex
MIT License
library/src/main/java/eu/darken/mvpbakery/injection/broadcastreceiver/BroadcastReceiverComponent.kt
d4rken
123,724,699
false
null
package eu.darken.mvpbakery.injection.broadcastreceiver import android.content.BroadcastReceiver import dagger.android.AndroidInjector interface BroadcastReceiverComponent<ReceiverT : BroadcastReceiver> : AndroidInjector<ReceiverT> { abstract class Builder<ReceiverT : BroadcastReceiver, ComponentT : BroadcastReceiverComponent<ReceiverT>> : AndroidInjector.Builder<ReceiverT>() { abstract override fun build(): ComponentT } }
0
Kotlin
14
39
ddf2249eda5ac707f116f1db01e11c2f3df58077
446
mvp-bakery
MIT License
test/org/jetbrains/r/mock/MockInterpreterStateProvider.kt
JetBrains
214,212,060
false
{"Kotlin": 2850624, "Java": 814635, "R": 36890, "CSS": 23692, "Lex": 14307, "HTML": 10063, "Rez": 245, "Rebol": 64}
/* * 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.mock import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.r.common.ExpiringList import org.jetbrains.r.common.emptyExpiringList import org.jetbrains.r.interpreter.RInterpreterState import org.jetbrains.r.packages.RInstalledPackage import org.jetbrains.r.rinterop.RInterop interface MockInterpreterStateProvider { val rInterop: RInterop val isUpdating: Boolean? val userLibraryPath: String val libraryPaths: List<RInterpreterState.LibraryPath> val installedPackages: ExpiringList<RInstalledPackage> val skeletonFiles: Set<VirtualFile> companion object { val DUMMY = object : MockInterpreterStateProvider { override val rInterop: RInterop get() = throw NotImplementedError() override val isUpdating: Boolean? get() = null // Note: exception is not thrown intentionally (see `MockInterpreterState.isUpdating`) override val userLibraryPath: String get() = throw NotImplementedError() override val libraryPaths: List<RInterpreterState.LibraryPath> get() = throw NotImplementedError() override val installedPackages: ExpiringList<RInstalledPackage> get() = emptyExpiringList(false) // Note: exception is not thrown intentionally override val skeletonFiles: Set<VirtualFile> get() = emptySet() } } }
2
Kotlin
12
62
801234f9bee37a12063d11dff6515b9517555e31
1,496
Rplugin
Apache License 2.0
src/test/kotlin/MimeTypesVideoTest.kt
markwhitaker
456,146,247
false
null
package uk.co.mainwave.mimetypeskotlin import org.junit.Assert import org.junit.Test class MimeTypesVideoTest { @Test fun testVideoH264() = Assert.assertEquals("video/h264", MimeTypes.Video.H264) @Test fun testVideoMp4() = Assert.assertEquals("video/mp4", MimeTypes.Video.MP4) @Test fun testVideoMpeg() = Assert.assertEquals("video/mpeg", MimeTypes.Video.MPEG) @Test fun testVideoOgg() = Assert.assertEquals("video/ogg", MimeTypes.Video.OGG) @Test fun testVideoQuicktime() = Assert.assertEquals("video/quicktime", MimeTypes.Video.QUICKTIME) @Test fun testVideoThreegppDeprecatedVersion() = Assert.assertEquals("video/3gpp", MimeTypes.Video.THREE_GPP) @Test fun testVideoThreegpp() = Assert.assertEquals("video/3gpp", MimeTypes.Video.THREEGPP) @Test fun testVideoThreegpp2() = Assert.assertEquals("video/3gpp2", MimeTypes.Video.THREEGPP2) @Test fun testVideoWebm() = Assert.assertEquals("video/webm", MimeTypes.Video.WEBM) @Test fun testVideoXMsvideo() = Assert.assertEquals("video/x-msvideo", MimeTypes.Video.X_MSVIDEO) }
0
Kotlin
0
2
6ec340c32ae297719c57191d15da457fe8805453
1,112
MimeTypes.kt
Apache License 2.0
app/src/main/java/com/example/newsapp/viewModel/NewsViewModelProviderFactory.kt
rybakova-auca-2021
638,567,705
false
null
package com.example.newsapp.viewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.newsapp.repository.NewsRepository class NewsViewModelProviderFactory(val NewsRepository: NewsRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return NewsViewModel(NewsRepository) as T } }
0
Kotlin
0
0
24511f4de83fed30879be537d7801706b4f77a93
398
Neobis_Android_News_App
MIT License
app/src/main/java/com/xluo/nops/adapter/PenModeAdapter.kt
VocientLuo
794,170,414
false
{"Kotlin": 469730, "Java": 118636}
package com.xluo.nops.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import com.xluo.lib_base.adapter.BaseSingleRVAdapter import com.xluo.nops.R import com.xluo.nops.databinding.PopPenModeItemBinding import com.xluo.pen.core.PenMixMode class PenModeAdapter(context: Context, data: List<PenMixMode>) : BaseSingleRVAdapter<PenMixMode, PopPenModeItemBinding>(context, data) { var onClick: ((PenMixMode) -> Unit)? = null var index = 0 override fun getViewBinding( viewType: Int, from: LayoutInflater, parent: ViewGroup? ): PopPenModeItemBinding { return PopPenModeItemBinding.inflate(from, parent, false) } override fun bindView( binding: PopPenModeItemBinding, entity: PenMixMode, position: Int ) { binding.ivMode.setImageResource(entity.icon) binding.tvMode.text = entity.name if (index == position) { binding.ivSelect.setImageResource(R.drawable.icon_xuanzhong) } else { binding.ivSelect.setImageResource(0) } binding.layoutPaint.setOnClickListener { onClick?.invoke(entity) index = position notifyDataSetChanged() } } }
0
Kotlin
0
0
2ffabe9101cf772ee51a76a48b4287e18e64a5ed
1,294
NoPS
Apache License 2.0
src/commonMain/kotlin/codes/spectrum/konveyor/IHandlerContainerBuilder.kt
svok
216,475,985
false
null
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 codes.spectrum.konveyor interface IHandlerContainerBuilder<T: Any> { fun add(handler: IKonveyorHandler<T>) fun add(handler: IBaseBuilder<T>) = add(handler.build()) fun add(handler: KonveyorExecutorType<T>) = add(HandlerBuilder<T>().apply { execEnv(handler) }) fun add(handler: KonveyorExecutorShortType<T>) = add(HandlerBuilder<T>().apply { exec(handler) }) fun add(handler: IKonveyorExecutor<T>) = add(HandlerBuilder<T>().apply { execEnv { env -> handler.exec(this, env) } }) // fun add(handler: KCallable<T>) = add(HandlerBuilder<T>().apply { // execEnv { env -> // handler.call(this, env) // } // }) operator fun IKonveyorHandler<T>.unaryPlus() = [email protected](this) operator fun IBaseBuilder<T>.unaryPlus() = [email protected](this) operator fun IKonveyorExecutor<T>.unaryPlus() = [email protected](this) fun exec(block: KonveyorExecutorShortType<T>) { add(block) } fun execEnv(block: KonveyorExecutorType<T>) { add(block) } fun handler(block: HandlerBuilder<T>.() -> Unit) { val builder = HandlerBuilder<T>() builder.block() val handler = builder.build() add(handler) } fun konveyor(block: KonveyorBuilder<T>.() -> Unit) { val builder = KonveyorBuilder<T>() builder.block() val handler = builder.build() add(handler) } fun <S: Any> subKonveyor(block: SubKonveyorBuilder<T, S>.() -> Unit) { val builder = SubKonveyorBuilder<T, S>() builder.block() val handler = builder.build() add(handler) } }
0
Kotlin
1
1
4d201c9ac18fc5c21dde18a979f519788d230cdc
2,540
konveyor
Apache License 2.0
app-tv/src/main/kotlin/app/ss/tv/presentation/home/HomeUiScreen.kt
Adventech
65,243,816
false
{"Kotlin": 1485130, "Java": 23539, "CSS": 9010, "JavaScript": 7718, "HTML": 2229, "Shell": 544}
/* * Copyright (c) 2023. Adventech <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.tv.presentation.home import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.tv.material3.Icon import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text import app.ss.tv.R import app.ss.tv.presentation.home.HomeScreen.Event import app.ss.tv.presentation.home.HomeScreen.State import app.ss.tv.presentation.home.ui.HomeUiContent import app.ss.tv.presentation.theme.ParentPadding import app.ss.tv.presentation.theme.SSTvTheme import app.ss.translations.R as L10nR @Composable fun HomeUiScreen(state: State, modifier: Modifier = Modifier) { // Move Focus logic to Dashboard screen when available val focusManager = LocalFocusManager.current var currentItemFocusedIndex by remember { mutableIntStateOf(0) } fun handleBackPress() { if (currentItemFocusedIndex == 0) { state.eventSink(Event.OnBack) } else { focusManager.moveFocus(FocusDirection.Up) } } Box( modifier = modifier .fillMaxSize() .onPreviewKeyEvent { event -> if (event.key == Key.Back && event.type == KeyEventType.KeyUp) { handleBackPress() return@onPreviewKeyEvent true } false }, ) { HomeUiContent( state = state, focusItemEvent = { index -> currentItemFocusedIndex = index } ) TopAppBar( modifier = Modifier .align(Alignment.TopStart) .padding( horizontal = ParentPadding.calculateStartPadding( LocalLayoutDirection.current ) - 8.dp ) .padding( top = ParentPadding.calculateTopPadding(), bottom = ParentPadding.calculateBottomPadding() ) ) } } @Composable private fun TopAppBar(modifier: Modifier = Modifier) { Row( modifier = modifier, horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically ) { Icon( painter = painterResource(R.drawable.logo_blue), contentDescription = stringResource(id = L10nR.string.ss_app_name), modifier = Modifier.size(IconSize), tint = Color.White ) Text( text = stringResource(L10nR.string.ss_app_name), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Medium, ) } } val IconSize = 48.dp @Preview( name = "Home", device = Devices.TV_1080p ) @Composable fun HomePreview() { SSTvTheme { HomeUiScreen(state = State.Loading{}) } }
6
Kotlin
42
151
f929fe8123382ce7b313f41b9cf467487ce5916b
5,197
sabbath-school-android
MIT License
app/src/main/java/com/bawp/jetweatherapp/screens/screens/main/MainScreen.kt
pdichone
428,785,582
false
{"Kotlin": 75337}
package com.bawp.jetweatherapp.screens.screens.main import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import coil.annotation.ExperimentalCoilApi import com.bawp.jetweatherapp.components.WeatherAppBar import com.bawp.jetweatherapp.data.DataOrException import com.bawp.jetweatherapp.model.WeatherItem import com.bawp.jetweatherapp.model.WeatherObject import com.bawp.jetweatherapp.navigation.WeatherScreens import com.bawp.jetweatherapp.screens.screens.search.SearchViewModel import com.bawp.jetweatherapp.screens.screens.settings.SettingsViewModel import com.bawp.jetweatherapp.utils.formatDate import com.bawp.jetweatherapp.utils.formatDecimals import com.bawp.jetweatherapp.widgets.HumidityWindPressureRow import com.bawp.jetweatherapp.widgets.SunsetSunRiseRow import com.bawp.jetweatherapp.widgets.WeatherDetailRow import com.bawp.jetweatherapp.widgets.WeatherStateImage @ExperimentalCoilApi @ExperimentalAnimationApi @Composable fun MainScreen( viewModel: SearchViewModel = hiltViewModel(), settingsViewModel: SettingsViewModel = hiltViewModel(), navController: NavHostController, city: String) { val curCity: String = if (city.isBlank()) "Spokane" else city val unitFromDB = settingsViewModel.unitList.collectAsState().value var unit by remember { mutableStateOf("imperial") //default value } var isImperial by remember { mutableStateOf(false) } if (!unitFromDB.isNullOrEmpty()) { // Log.d("TAGF", "MainScreen: ${unitFromDB[0].unit.split(" ")[0].lowercase()}") unit = unitFromDB[0].unit.split(" ")[0].lowercase() isImperial = unit == "imperial" val weatherData = produceState<DataOrException<WeatherObject, Boolean, Exception>>( initialValue = DataOrException(loading = true)) { value = viewModel.getWeatherData(city = curCity, units = unit) }.value if (weatherData.loading == true) { CircularProgressIndicator( color = Color.DarkGray ) } else if (weatherData.data != null) { MainScaffold(weatherObject = weatherData.data!!, navController = navController, isImperial = isImperial) } } } @ExperimentalCoilApi @ExperimentalAnimationApi @Composable fun MainScaffold( weatherObject: WeatherObject, navController: NavHostController, isImperial: Boolean, ) { Scaffold(topBar = { WeatherAppBar( title = weatherObject.city.name + ", ${weatherObject.city.country}", navController = navController, onAddActionClicked = { navController.navigate(WeatherScreens.SearchScreen.name) }, elevation = 5.dp) }, bottomBar = {}, backgroundColor = Color.LightGray.copy(alpha = 0.08f) ) { MainContent(data = weatherObject, isImperial = isImperial) } } @ExperimentalCoilApi @ExperimentalAnimationApi @Composable private fun MainContent(data: WeatherObject?, isImperial: Boolean) { val imageUrl = "https://openweathermap.org/img/wn/${data!!.list[0].weather[0].icon}.png" var unitToggleState by remember { mutableStateOf(false) } Column( Modifier .padding(4.dp) .fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) { Text( text = formatDate(data.list[0].dt), //"Today Nov 29", style = MaterialTheme.typography.caption, color = MaterialTheme.colors.onSecondary, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(6.dp) ) // IconToggleButton( // checked = !unitToggleState, // onCheckedChange = { // unitToggleState = !it // Log.d("TAG", "MainContent: $unitToggleState") // }, ) { // Text(text = if (unitToggleState) "F" else "C") // } } Surface( modifier = Modifier .padding(4.dp) .size(200.dp), shape = CircleShape ) { Box( modifier = Modifier .background(Color(0xFFFFC400)) .padding(horizontal = 16.dp, vertical = 3.dp), contentAlignment = Alignment.Center ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { WeatherStateImage(imagerUrl = imageUrl) Text( text = formatDecimals(data.list[0].temp.day) + "º",//Press and hold the ALT key and type 0176 with NumLock on style = MaterialTheme.typography.h4, fontWeight = FontWeight.ExtraBold ) Text( text = data.list[0].weather[0].main, fontStyle = FontStyle.Italic ) } } } HumidityWindPressureRow(weather = data.list[0], isImperial = isImperial) Divider() Spacer(modifier = Modifier.height(15.dp)) SunsetSunRiseRow(weather = data.list[0]) Spacer(modifier = Modifier.height(15.dp)) Text( "This Week", style = MaterialTheme.typography.subtitle1, fontWeight = FontWeight.Bold ) Surface( modifier = Modifier .fillMaxWidth() .fillMaxHeight(), color = Color(0xFFEEF1EF), shape = RoundedCornerShape(size = 14.dp) ) { LazyColumn( modifier = Modifier.padding(2.dp), contentPadding = PaddingValues(1.dp) ) { items(items = data.list) { item: WeatherItem -> WeatherDetailRow(weather = item) } } } } }
0
Kotlin
0
2
3ddc8b97a5cdeae15c81b394718e594e51ef2044
6,956
jetWeatherApp-Test
Apache License 2.0
apps/processing/common/src/main/kotlin/io/enkrypt/common/config/ChainId.kt
briandevilish
169,686,634
true
{"Kotlin": 312805, "TypeScript": 204497, "Vue": 187785, "HCL": 64972, "Shell": 59077, "Dockerfile": 11314, "JavaScript": 7539, "CSS": 803, "HTML": 783}
package io.enkrypt.common.config enum class ChainId(val number: Int) { MainNet(1), Morden(2), Ropsten(3), Rinkleby(4), UbiqMainNet(8), UbiqTestNest(9), RootStockMainNet(30), RootStockTestNet(31), Kovan(42), EthClassicMainNet(61), EthClassicTestNet(62), EWasmTestNet(66), GethPrivateChains(1337), Görli(6284), Stureby(314158) }
0
Kotlin
0
0
c748068d143c42aded70441e82534dadb1cd0488
359
ethvm
MIT License
2GDAW/TFC/Activiza (front end)/app/src/main/java/com/activiza/activiza/data/RutinaPostData.kt
Barraguesh
702,637,366
false
{"Kotlin": 180174, "Python": 33897, "Dockerfile": 787, "Shell": 240}
package com.activiza.activiza.data import com.google.gson.annotations.SerializedName data class RutinaPostData ( @SerializedName("id") var id:Int, @SerializedName("nombre") var nombre:String, @SerializedName("descripcion") var descripcion:String, @SerializedName("ejercicios") var ejercicios:List<Int>, @SerializedName("genero") var genero:String, @SerializedName("objetivo") var objetivo:String, @SerializedName("lugar_entrenamiento") var lugar_entrenamiento:String, @SerializedName("media") var media:String, @SerializedName("duracion") var duracion:Int )
0
Kotlin
0
0
2361b0a4bb31a378c4bf2f2df735ca342565b74c
595
GDAM
MIT License
src/main/kotlin/io/github/gciatto/kt/node/SetRegistryTask.kt
gciatto
276,425,519
false
null
package io.github.gciatto.kt.node open class SetRegistryTask : AbstractNodeExecTask() { override fun setupArguments(): Array<String> { return arrayOf( npm.get().absolutePath, "set", "registry", "https://${registry.get()}/" ) } }
5
Kotlin
2
17
2db056208571d9b547dcdd223ceec812f81504c3
302
kt-npm-publish
Apache License 2.0
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/carousel/Carousel.kt
androidx
256,589,781
false
{"Kotlin": 95878258, "Java": 67276414, "C++": 9121933, "AIDL": 629410, "Python": 308602, "Shell": 191832, "TypeScript": 40586, "HTML": 26377, "Svelte": 20307, "ANTLR": 19860, "C": 16935, "CMake": 14401, "Groovy": 13532, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3.carousel import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ShapeDefaults import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.layout import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import kotlin.math.roundToInt /** * A enumeration of ways items can be aligned along a carousel's main axis */ internal enum class CarouselAlignment { /** Start aligned carousels place focal items at the start/top of the container */ Start, /** Center aligned carousels place focal items in the middle of the container */ Center, /** End aligned carousels place focal items at the end/bottom of the container */ End } /** * A modifier that handles clipping and translating an item as it moves along the scrolling axis * of a Carousel. * * @param index the index of the item in the carousel * @param viewportSize the size of the carousel container * @param orientation the orientation of the carousel * @param itemsCount the total number of items in the carousel * @param scrollOffset the amount the carousel has been scrolled in pixels * @param strategy the strategy used to mask and translate items in the carousel */ internal fun Modifier.carouselItem( index: Int, itemsCount: Int, viewportSize: IntSize, orientation: Orientation, scrollOffset: Float, strategy: Strategy ): Modifier { val isVertical = orientation == Orientation.Vertical val mainAxisCarouselSize = if (isVertical) viewportSize.height else viewportSize.width if (mainAxisCarouselSize == 0) { return this } val maxScrollOffset = itemsCount * strategy.itemMainAxisSize - mainAxisCarouselSize val keylines = strategy.getKeylineListForScrollOffset(scrollOffset, maxScrollOffset) // Find center of the item at this index val unadjustedCenter = (index * strategy.itemMainAxisSize) + (strategy.itemMainAxisSize / 2f) - scrollOffset // Find the keyline before and after this item's center and create an interpolated // keyline that the item should use for its clip shape and offset val keylineBefore = keylines.getKeylineBefore(unadjustedCenter) val keylineAfter = keylines.getKeylineAfter(unadjustedCenter) val progress = getProgress(keylineBefore, keylineAfter, unadjustedCenter) val interpolatedKeyline = lerp(keylineBefore, keylineAfter, progress) val isOutOfKeylineBounds = keylineBefore == keylineAfter return this then layout { measurable, constraints -> // Force the item to use the strategy's itemMainAxisSize along its main axis val mainAxisSize = strategy.itemMainAxisSize val itemConstraints = if (isVertical) { constraints.copy( minWidth = constraints.minWidth, maxWidth = constraints.maxWidth, minHeight = mainAxisSize.roundToInt(), maxHeight = mainAxisSize.roundToInt() ) } else { constraints.copy( minWidth = mainAxisSize.roundToInt(), maxWidth = mainAxisSize.roundToInt(), minHeight = constraints.minHeight, maxHeight = constraints.maxHeight ) } val placeable = measurable.measure(itemConstraints) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } then graphicsLayer { // Clip the item clip = true shape = object : Shape { // TODO: Find a way to use the shape of the item set by the client for each item val roundedCornerShape = RoundedCornerShape(ShapeDefaults.ExtraLarge.topStart) override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { val centerX = if (isVertical) size.height / 2f else strategy.itemMainAxisSize / 2f val centerY = if (isVertical) strategy.itemMainAxisSize / 2f else size.height / 2f val halfMaskWidth = if (isVertical) size.width / 2f else interpolatedKeyline.size / 2f val halfMaskHeight = if (isVertical) interpolatedKeyline.size / 2f else size.height / 2f val rect = Rect( left = centerX - halfMaskWidth, top = centerY - halfMaskHeight, right = centerX + halfMaskWidth, bottom = centerY + halfMaskHeight ) val cornerSize = roundedCornerShape.topStart.toPx( Size(rect.width, rect.height), density ) val cornerRadius = CornerRadius(cornerSize) return Outline.Rounded( RoundRect( rect = rect, topLeft = cornerRadius, topRight = cornerRadius, bottomRight = cornerRadius, bottomLeft = cornerRadius ) ) } } // After clipping, the items will have white space between them. Translate the items to // pin their edges together var translation = interpolatedKeyline.offset - unadjustedCenter if (isOutOfKeylineBounds) { // If this item is beyond the first or last keyline, continue to offset the item // by cutting its unadjustedOffset according to its masked size. val outOfBoundsOffset = (unadjustedCenter - interpolatedKeyline.unadjustedOffset) / interpolatedKeyline.size translation += outOfBoundsOffset } if (isVertical) { translationY = translation } else { translationX = translation } } } /** * Returns a float between 0 and 1 that represents how far [unadjustedOffset] is between * [before] and [after]. * * @param before the first keyline whose unadjustedOffset is less than [unadjustedOffset] * @param after the first keyline whose unadjustedOffset is greater than [unadjustedOffset] * @param unadjustedOffset the unadjustedOffset between [before] and [after]'s unadjustedOffset that * a progress value will be returned for */ private fun getProgress(before: Keyline, after: Keyline, unadjustedOffset: Float): Float { if (before == after) { return 1f } val total = after.unadjustedOffset - before.unadjustedOffset return (unadjustedOffset - before.unadjustedOffset) / total }
27
Kotlin
901
4,898
e7c7c42655aba3f04cb7672f2eb02744bd24ce7f
7,815
androidx
Apache License 2.0
src/main/kotlin/no/nav/tilleggsstonader/sak/migrering/routing/SøknadRoutingService.kt
navikt
685,490,225
false
{"Kotlin": 2149188, "Gherkin": 54372, "HTML": 39535, "Shell": 924, "Dockerfile": 164}
package no.nav.tilleggsstonader.sak.migrering.routing import no.nav.tilleggsstonader.kontrakter.arena.ArenaStatusDto import no.nav.tilleggsstonader.kontrakter.felles.IdentStønadstype import no.nav.tilleggsstonader.kontrakter.felles.ObjectMapperProvider.objectMapper import no.nav.tilleggsstonader.kontrakter.felles.Stønadstype import no.nav.tilleggsstonader.libs.unleash.UnleashService import no.nav.tilleggsstonader.sak.behandling.BehandlingService import no.nav.tilleggsstonader.sak.fagsak.FagsakService import no.nav.tilleggsstonader.sak.infrastruktur.database.JsonWrapper import no.nav.tilleggsstonader.sak.infrastruktur.unleash.Toggle import no.nav.tilleggsstonader.sak.infrastruktur.unleash.UnleashUtil.getVariantWithNameOrDefault import no.nav.tilleggsstonader.sak.opplysninger.arena.ArenaService import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service class SøknadRoutingService( private val søknadRoutingRepository: SøknadRoutingRepository, private val fagsakService: FagsakService, private val behandlingService: BehandlingService, private val arenaService: ArenaService, private val unleashService: UnleashService, ) { private val logger = LoggerFactory.getLogger(javaClass) fun sjekkRoutingForPerson(request: IdentStønadstype): SøknadRoutingResponse { val skalBehandlesINyLøsning = skalBehandlesINyLøsning(request) logger.info("routing - skalBehandlesINyLøsning=$skalBehandlesINyLøsning") return SøknadRoutingResponse(skalBehandlesINyLøsning = skalBehandlesINyLøsning) } fun harLagretRouting(request: IdentStønadstype): Boolean { val søknadRouting = søknadRoutingRepository.findByIdentAndType(request.ident, request.stønadstype) return søknadRouting != null } private fun skalBehandlesINyLøsning(request: IdentStønadstype): Boolean { if (harLagretRouting(request)) { logger.info("routing - harLagretRouting=true") return true } if (harBehandling(request)) { lagreRouting(request, mapOf("harBehandling" to true)) return true } if (skalStoppesPgaFeatureToggle(request.stønadstype)) { return false } val arenaStatus = arenaService.hentStatus(request.ident, request.stønadstype) if (harGyldigStateIArena(request.stønadstype, arenaStatus)) { lagreRouting(request, arenaStatus) return true } return false } private fun skalStoppesPgaFeatureToggle(stønadstype: Stønadstype): Boolean { return when (stønadstype) { Stønadstype.BARNETILSYN -> false // tilsyn barn skal ikke stoppes med feature toggle Stønadstype.LÆREMIDLER -> maksAntallErNådd(stønadstype) else -> error("Støtter ennå ikke stønadstype=$stønadstype") } } private fun maksAntallErNådd(stønadstype: Stønadstype): Boolean { val maksAntall = maksAntall(stønadstype) val antall = søknadRoutingRepository.countByType(stønadstype) logger.info("routing - antallIDatabase=$antall toggleMaksAntall=$maksAntall") return antall >= maksAntall } private fun maksAntall(stønadstype: Stønadstype) = unleashService.getVariantWithNameOrDefault(stønadstype.maksAntallToggle(), "antall", 0) private fun Stønadstype.maksAntallToggle() = when (this) { Stønadstype.LÆREMIDLER -> Toggle.SØKNAD_ROUTING_LÆREMIDLER else -> error("Har ikke maksAntalLToggle for stønadstype=$this") } private fun harGyldigStateIArena(stønadstype: Stønadstype, arenaStatus: ArenaStatusDto): Boolean { val harAktivtVedtak = arenaStatus.vedtak.harAktivtVedtak val harVedtakUtenUtfall = arenaStatus.vedtak.harVedtakUtenUtfall val harVedtak = arenaStatus.vedtak.harVedtak val harAktivSakUtenVedtak = arenaStatus.sak.harAktivSakUtenVedtak val harGyldigStatus = when (stønadstype) { Stønadstype.BARNETILSYN -> !harAktivtVedtak Stønadstype.LÆREMIDLER -> !harVedtak } logger.info("routing - harGyldigStatusArena=$harGyldigStatus - harAktivSakUtenVedtak=$harAktivSakUtenVedtak harVedtak=$harVedtak harAktivtVedtak=$harAktivtVedtak harVedtakUtenUtfall=$harVedtakUtenUtfall") return harGyldigStatus } private fun lagreRouting(request: IdentStønadstype, detaljer: Any) { søknadRoutingRepository.insert( SøknadRouting( ident = request.ident, type = request.stønadstype, detaljer = JsonWrapper(objectMapper.writeValueAsString(detaljer)), ), ) } private fun harBehandling( request: IdentStønadstype, ): Boolean { val harBehandling = ( fagsakService.finnFagsak(setOf(request.ident), request.stønadstype) ?.let { behandlingService.hentBehandlinger(it.id).isNotEmpty() } ?: false ) logger.info("routing - harBehandling=$harBehandling") return harBehandling } }
3
Kotlin
1
0
7520818c5a146efeb6ad3c690bc6155bf08a09ae
5,093
tilleggsstonader-sak
MIT License
app/src/main/java/com/devcommop/myapplication/ui/components/authscreen/SignInState.kt
pareekdevansh
648,905,400
false
null
package com.devcommop.myapplication.ui.components.authscreen data class SignInState( val isSignInSuccessful : Boolean = false , val signInError : String? = null )
0
Kotlin
0
0
d0fda60a15fe2c7bd93596cf6582fccdbccb788a
171
Social-Jaw
MIT License
app/src/main/java/net/yslibrary/monotweety/activity/ActionBarProvider.kt
konvergent
72,869,271
true
{"Kotlin": 177053, "Java": 2401}
package net.yslibrary.monotweety.activity import android.support.v7.app.ActionBar /** * Created by yshrsmz on 2016/09/25. */ interface ActionBarProvider { fun getSupportActionBar(): ActionBar? }
0
Kotlin
0
0
d662f9de6e7cbef180ee81964b6340a9a0aee3c0
200
monotweety
Apache License 2.0
library_widget/src/main/java/com/knight/kotlin/library_widget/CompatToolBar.kt
KnightAndroid
438,567,015
false
{"Kotlin": 1817006, "Java": 294277, "HTML": 46741, "C": 31605, "C++": 14920, "CMake": 5510}
package com.knight.kotlin.library_widget import android.content.Context import android.content.res.Resources import android.os.Build import android.util.AttributeSet import android.widget.Toolbar /** * Author:Knight * Time:2021/12/24 16:08 * Description:CompatToolBar */ class CompatToolBar : Toolbar { @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defAttrStyle: Int = 0) : super(context, attributeSet, defAttrStyle) { setUp() } private fun setUp() { var compatPaddingTop = 0 // android 4.4以上将Toolbar添加状态栏高度的上边距,沉浸到状态栏下方 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { compatPaddingTop = getStatusBarHeight() } this.setPadding( getPaddingLeft(), dp2px(10f) + compatPaddingTop, getPaddingRight(), getPaddingBottom() + compatPaddingTop / 2 ); } private fun getStatusBarHeight(): Int { var result = 0 try { val resourceId: Int = Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android") if (resourceId > 0) { result = Resources.getSystem().getDimensionPixelSize(resourceId) } } catch (e: Resources.NotFoundException) { e.printStackTrace() } return result } private fun dp2px(dpValue: Float): Int { val scale = Resources.getSystem().displayMetrics.density return (dpValue * scale + 0.5f).toInt() } }
0
Kotlin
3
6
d423c9cf863afe8e290c183b250950bf155d1f84
1,570
wanandroidByKotlin
Apache License 2.0
app/src/main/java/xyz/tberghuis/floatingtimer/common/OverlayState.kt
tberghuis
500,632,576
false
null
package xyz.tberghuis.floatingtimer.common import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.unit.IntOffset class OverlayState { var timerOffset by mutableStateOf(IntOffset.Zero) var showTrash by mutableStateOf(false) var isTimerHoverTrash = false // i could probably move these top level // this is a hack var screenWidthPx = Int.MAX_VALUE var screenHeightPx = Int.MAX_VALUE fun reset(){ timerOffset = IntOffset.Zero showTrash = false isTimerHoverTrash = false } }
6
Kotlin
0
19
91af4efb1abce0292b70150f18f64ea331d72c09
605
FloatingCountdownTimer
MIT License
app/src/main/java/uk/nhs/nhsx/covid19/android/app/exposure/sharekeys/ShareKeysInformationViewModel.kt
coderus-ltd
369,240,870
true
{"Kotlin": 3133494, "Shell": 1098, "Ruby": 847, "Batchfile": 197}
package uk.nhs.nhsx.covid19.android.app.exposure.sharekeys import android.app.Activity import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import uk.nhs.nhsx.covid19.android.app.exposure.sharekeys.ShareKeysNavigateTo.Finish import uk.nhs.nhsx.covid19.android.app.exposure.sharekeys.ShareKeysNavigateTo.ShareKeysResultActivity import uk.nhs.nhsx.covid19.android.app.exposure.sharekeys.ShareKeysNavigateTo.StatusActivity import uk.nhs.nhsx.covid19.android.app.exposure.sharekeys.ShareKeysNavigateTo.SubmitKeysProgressActivity import uk.nhs.nhsx.covid19.android.app.remote.data.NHSTemporaryExposureKey import uk.nhs.nhsx.covid19.android.app.util.SingleLiveEvent import java.time.Clock import javax.inject.Inject class ShareKeysInformationViewModel @Inject constructor( private val submitEpidemiologyDataForTestResult: SubmitEpidemiologyDataForTestResult, fetchKeysFlowFactory: FetchKeysFlow.Factory, private val keySharingInfoProvider: KeySharingInfoProvider, private val clock: Clock ) : ViewModel() { private val navigationLiveData = SingleLiveEvent<ShareKeysNavigationTarget>() fun navigation(): LiveData<ShareKeysNavigationTarget> = navigationLiveData private val permissionRequestLiveData = SingleLiveEvent<(Activity) -> Unit>() fun permissionRequest(): LiveData<(Activity) -> Unit> = permissionRequestLiveData private lateinit var keySharingInfo: KeySharingInfo private val fetchKeysFlow by lazy { fetchKeysFlowFactory.create( object : FetchKeysFlow.Callback { override fun onFetchKeysSuccess( temporaryExposureKeys: List<NHSTemporaryExposureKey>, diagnosisKeySubmissionToken: String ) { navigationLiveData.postValue( SubmitKeysProgressActivity(temporaryExposureKeys, diagnosisKeySubmissionToken) ) } override fun onFetchKeysPermissionDenied() { val keysSharingInfo = keySharingInfoProvider.keySharingInfo if (keysSharingInfo != null && keysSharingInfo.wasAcknowledgedMoreThan24HoursAgo(clock)) { keySharingInfoProvider.reset() } else { keySharingInfoProvider.setHasDeclinedSharingKeys() } navigationLiveData.postValue(StatusActivity) } override fun onFetchKeysUnexpectedError() { navigationLiveData.postValue(Finish) } override fun onPermissionRequired(permissionRequest: (Activity) -> Unit) { permissionRequestLiveData.postValue(permissionRequest) } }, viewModelScope, keySharingInfo ) } fun onCreate() { keySharingInfoProvider.keySharingInfo?.let { keySharingInfo = it } ?: navigationLiveData.postValue(Finish) } fun onShareKeysButtonClicked() { fetchKeysFlow() } fun onActivityResult(requestCode: Int, resultCode: Int) { fetchKeysFlow.onActivityResult(requestCode, resultCode) if (resultCode == Activity.RESULT_OK && requestCode == ShareKeysInformationActivity.REQUEST_CODE_SUBMIT_KEYS) { onSuccessfulKeySubmission() } } private fun onSuccessfulKeySubmission() { viewModelScope.launch { keySharingInfoProvider.reset() submitEpidemiologyDataForTestResult(keySharingInfo) navigationLiveData.postValue(ShareKeysResultActivity) } } sealed class ShareKeysInformationNavigateTo : ShareKeysNavigationTarget { object StatusActivity : ShareKeysInformationNavigateTo() } }
0
null
0
0
b74358684b9dbc0174890db896b93b0f7c6660a4
3,893
covid-19-app-android-ag-public
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/fms/_BuildableLastArgumentExtensions.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.fms import kotlin.Unit import software.amazon.awscdk.services.fms.CfnPolicy /** * Details about the security service that is being used to protect the resources. */ public inline fun CfnPolicy.setSecurityServicePolicyData(block: CfnPolicySecurityServicePolicyDataPropertyDsl.() -> Unit = {}) { val builder = CfnPolicySecurityServicePolicyDataPropertyDsl() builder.apply(block) return setSecurityServicePolicyData(builder.build()) } /** * Specifies the AWS account IDs and AWS Organizations organizational units (OUs) to exclude from * the policy. */ public inline fun CfnPolicy.setExcludeMap(block: CfnPolicyIEMapPropertyDsl.() -> Unit = {}) { val builder = CfnPolicyIEMapPropertyDsl() builder.apply(block) return setExcludeMap(builder.build()) } /** * Specifies the AWS account IDs and AWS Organizations organizational units (OUs) to include in the * policy. */ public inline fun CfnPolicy.setIncludeMap(block: CfnPolicyIEMapPropertyDsl.() -> Unit = {}) { val builder = CfnPolicyIEMapPropertyDsl() builder.apply(block) return setIncludeMap(builder.build()) }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
1,314
awscdk-dsl-kotlin
Apache License 2.0
src/main/kotlin/string/StringCompression.kt
ghonix
88,671,637
false
null
package string /** * https://leetcode.com/problems/string-compression/ */ class StringCompression { fun compress(chars: CharArray): Int { var index = 0 var compressedIndex = 0 while (index < chars.size) { var current = chars[index] var endOfRepeated = index + 1 chars[compressedIndex++] = current while (endOfRepeated < chars.size && current == chars[endOfRepeated]) { endOfRepeated++ } val nRepetition = endOfRepeated - index if (nRepetition > 1) { val repetitionString = nRepetition.toString() for (digit in repetitionString) { chars[compressedIndex] = digit compressedIndex++ } } index += nRepetition } return compressedIndex } } fun main() { println( StringCompression().compress( "aabbcc".toCharArray() ) ) println( StringCompression().compress( "abbbbbbbbbbbb".toCharArray() ) ) }
0
Kotlin
0
2
25d4ba029e4223ad88a2c353a56c966316dd577e
1,126
Problems
Apache License 2.0
app/src/main/java/com/particle/sample/utils/Ext.kt
Particle-Network
672,722,314
false
null
package com.particle.sample.utils import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.afollestad.materialdialogs.MaterialDialog import com.particle.base.ParticleNetwork import com.particle.base.isTron import com.particle.base.utils.toTronBase58 import java.math.BigDecimal import java.math.BigInteger import java.util.regex.Pattern import kotlin.math.pow /** * Created by chaichuanfa on 2023/6/9 */ fun Fragment.toast(message: String) { Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show() } fun AppCompatActivity.toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun Fragment.showMsg(title: String, message: String) { MaterialDialog(this.requireContext()).show { title(text = title) message(text = message) positiveButton(text = "ok") } } fun String.hex2Decimal(): BigInteger { return this.substring(2, this.length).toBigInteger(16) } fun BigInteger.toUIAmount(decimals: Int): BigDecimal { val mi = 10.0.pow(decimals.toDouble()) return this.toBigDecimal().divide(BigDecimal.valueOf(mi)) } fun String.hexAmount2UiAmount(): String { return this.hex2Decimal().toUIAmount(ParticleNetwork.chainInfo.nativeCurrency.decimals).toPlainString().dropLastWhile { it == '0' } .dropLastWhile { it == '.' } } fun String.uiAmount2HexAmount(): String { val result = this.toBigDecimal().multiply(BigDecimal.valueOf(10.0.pow(ParticleNetwork.chainInfo.nativeCurrency.decimals))) val hex = result.toBigInteger().toString(16) return "0x$hex" } fun String.uiAmount2Amount(): BigInteger { val result = this.toBigDecimal().multiply(BigDecimal.valueOf(10.0.pow(ParticleNetwork.chainInfo.nativeCurrency.decimals))) return result.toBigInteger() } fun String.formatDisplayAddress(formatCount: Int = 5): String { var currAddress = this if (currAddress.length < formatCount) return currAddress if (ParticleNetwork.chainInfo.isTron()) { try { currAddress = toTronBase58() } catch (_: Exception) { } } val startStr = currAddress.substring(0, formatCount) val endStr = currAddress.substring(currAddress.length - formatCount, currAddress.length) return "$startStr...$endStr" } private var pattern = "^[1-9A-HJ-NP-Za-km-z]{32,44}\$" internal fun String.isSolPublicKey(): Boolean { val isMatch = Pattern.matches(pattern, this); return isMatch }
0
Kotlin
0
0
82bf32ee839aaf29bdb6b79190195960db5fc3d9
2,503
particle-mpc-core-android
Apache License 2.0
app/src/main/java/com/yaman/multiplemoduleapp/MainActivity.kt
Yamanaswal
685,417,811
false
{"Kotlin": 74236}
package com.yaman.multiplemoduleapp import android.Manifest import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import com.yaman.pdf_viewer.ui.PdfViewerActivity import com.yaman.runtime_permissions.coroutine_permissions.PermissionManager import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<Button>(R.id.button).setOnClickListener { // demoPdfViewer() demoRuntimePermissions() } } private fun demoRuntimePermissions() { CoroutineScope(Dispatchers.IO).launch { PermissionManager.requestPermissions(this@MainActivity, 123, Manifest.permission.CAMERA, Manifest.permission.BLUETOOTH) } } private fun demoPdfViewer() { startActivity(Intent(this, PdfViewerActivity::class.java)) } }
0
Kotlin
0
0
51792700730e847231effd5ec79b006e1f7dd4e8
1,213
MultipleModuleApp
MIT License
app/src/main/java/com/namanh/lovedays/core/navigation/Navigator.kt
namanh11611
301,474,275
false
null
package com.namanh.lovedays.core.navigation import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import android.view.View import android.widget.ImageView import androidx.core.app.ActivityOptionsCompat import androidx.fragment.app.FragmentActivity import javax.inject.Inject import javax.inject.Singleton @Singleton class Navigator @Inject constructor() { // private fun showLogin(context: Context) = context.startActivity(LoginActivity.callingIntent(context)) // fun showMain(context: Context) { // when (authenticator.userLoggedIn()) { // true -> showMovies(context) // false -> showLogin(context) // } } // // private fun showMovies(context: Context) = context.startActivity(MoviesActivity.callingIntent(context)) // // fun showMovieDetails(activity: FragmentActivity, movie: MovieView, navigationExtras: Extras) { // val intent = MovieDetailsActivity.callingIntent(activity, movie) // val sharedView = navigationExtras.transitionSharedElement as ImageView // val activityOptions = ActivityOptionsCompat // .makeSceneTransitionAnimation(activity, sharedView, sharedView.transitionName) // activity.startActivity(intent, activityOptions.toBundle()) // } // // private val VIDEO_URL_HTTP = "http://www.youtube.com/watch?v=" // private val VIDEO_URL_HTTPS = "https://www.youtube.com/watch?v=" // // fun openVideo(context: Context, videoUrl: String) { // try { // context.startActivity(createYoutubeIntent(videoUrl)) // } catch (ex: ActivityNotFoundException) { // context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(videoUrl))) // } // } // // private fun createYoutubeIntent(videoUrl: String): Intent { // val videoId = when { // videoUrl.startsWith(VIDEO_URL_HTTP) -> videoUrl.replace(VIDEO_URL_HTTP, String.empty()) // videoUrl.startsWith(VIDEO_URL_HTTPS) -> videoUrl.replace(VIDEO_URL_HTTPS, String.empty()) // else -> videoUrl // } // // val intent = Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:$videoId")) // intent.putExtra("force_fullscreen", true) // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // // return intent // } // class Extras(val transitionSharedElement: View) }
0
Kotlin
0
0
cf3bacd74fb6823daaa23057be1f1159fc63f97a
2,415
LoveDays
MIT License
json-builder/kotlin/src/generated/kotlin/divkit/dsl/AlignmentVertical.kt
divkit
523,491,444
false
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
@file:Suppress( "unused", "UNUSED_PARAMETER", ) package divkit.dsl import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonValue import divkit.dsl.annotation.* import divkit.dsl.core.* import divkit.dsl.scope.* import kotlin.Any import kotlin.String import kotlin.Suppress import kotlin.collections.List import kotlin.collections.Map /** * Possible values: [top], [center], [bottom], [baseline]. */ @Generated sealed interface AlignmentVertical @Generated fun AlignmentVertical.asList() = listOf(this)
5
Kotlin
128
2,240
dd102394ed7b240ace9eaef9228567f98e54d9cf
609
divkit
Apache License 2.0
app/src/main/java/com/montfel/pokfinder/data/profile/dto/PokemonProfileDto.kt
Montfel
489,497,209
false
null
package com.montfel.pokfinder.data.profile.dto import com.google.gson.annotations.SerializedName import com.montfel.pokfinder.domain.profile.model.EV import com.montfel.pokfinder.domain.profile.model.PokemonProfile import com.montfel.pokfinder.data.DtoMapper import com.montfel.pokfinder.data.profile.dto.AbilitiesDto data class PokemonProfileDto( @SerializedName("id") val id: Int, @SerializedName("name") val name: String, @SerializedName("sprites") val sprite: SpriteDto, @SerializedName("types") val types: List<TypesDto>, @SerializedName("height") val height: Int, @SerializedName("weight") val weight: Int, @SerializedName("base_experience") val baseExp: Int, @SerializedName("abilities") val abilities: List<AbilitiesDto>, @SerializedName("stats") val stats: List<StatsDto> ) : DtoMapper<PokemonProfile> { override fun toDomain() = PokemonProfile( id = id, name = name.replaceFirstChar { it.uppercase() }, image = sprite.other.officialArtwork.frontDefault, types = types.map { it.toDomain() }, height = height.toFloat().div(10), weight = weight.toFloat().div(10), baseExp = baseExp, abilities = abilities.map { it.toDomain() }, stats = stats.map { it.toDomain() }, ev = stats .filter { it.effort > 0 } .map { EV( name = it.stat.toDomain().name, effort = it.effort ) } ) }
24
Kotlin
2
6
32102e924ec7e91a7f9bf387f9e89f0c004d5779
1,558
pokfinder
MIT License
composeApp/src/desktopMain/kotlin/presentation/extensions/AppPlatforms.desktop.kt
vrcm-team
746,586,818
false
{"Kotlin": 556756, "Swift": 567}
package io.github.vrcmteam.vrcm.presentation.extensions import io.github.vrcmteam.vrcm.AppPlatform import java.awt.Desktop import java.net.URI actual fun AppPlatform.openUrl(url: String) { Desktop.getDesktop().browse(URI(url)) } actual val AppPlatform.isSupportBlur: Boolean get() = true
0
Kotlin
3
23
cf723aee7c5653df01f8c1aa3e45f88cff3a45b6
298
VRCM
MIT License
generator/accessor-plugin/src/main/kotlin/me/kcra/takenaka/generator/accessor/plugin/tasks/ResolveMappingsTask.kt
zlataovce
596,960,001
false
{"Kotlin": 650033, "Java": 93227, "CSS": 12015, "JavaScript": 8203}
/* * This file is part of takenaka, licensed under the Apache License, Version 2.0 (the "License"). * * Copyright (c) 2023-2024 <NAME> * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.kcra.takenaka.generator.accessor.plugin.tasks import kotlinx.coroutines.runBlocking import me.kcra.takenaka.core.Version import me.kcra.takenaka.core.VersionManifest import me.kcra.takenaka.core.compositeWorkspace import me.kcra.takenaka.core.mapping.MappingContributor import me.kcra.takenaka.core.mapping.adapter.* import me.kcra.takenaka.core.mapping.analysis.impl.AnalysisOptions import me.kcra.takenaka.core.mapping.analysis.impl.MappingAnalyzerImpl import me.kcra.takenaka.core.mapping.resolve.impl.* import me.kcra.takenaka.core.util.md5Digest import me.kcra.takenaka.core.util.updateAndHex import me.kcra.takenaka.generator.accessor.plugin.PlatformTristate import me.kcra.takenaka.generator.common.provider.impl.BundledMappingProvider import me.kcra.takenaka.generator.common.provider.impl.ResolvingMappingProvider import me.kcra.takenaka.generator.common.provider.impl.buildMappingConfig import net.fabricmc.mappingio.tree.MappingTree import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.provider.MapProperty import org.gradle.api.provider.Property import org.gradle.api.provider.SetProperty import org.gradle.api.tasks.* import java.util.zip.ZipFile /** * A [me.kcra.takenaka.core.mapping.MutableMappingsMap], but as a Gradle [MapProperty]. */ typealias MutableMappingsMapProperty = MapProperty<Version, MappingTree> /** * A Gradle task that resolves and analyzes mappings. * * Mappings can be resolved from a mapping bundle, defined using the [mappingBundle] property, or * fetched and saved directly, defined using the [versions] property (only basic mappings for Mojang-based servers). * * **Mapping bundle content is not analyzed!** * * @author <NAME> */ abstract class ResolveMappingsTask : DefaultTask() { /** * The cache directory, defaults to `build/takenaka/cache`. * * @see me.kcra.takenaka.generator.accessor.plugin.AccessorGeneratorExtension.cacheDirectory */ @get:OutputDirectory abstract val cacheDir: DirectoryProperty /** * A mapping bundle, optional, defined via the `mappingBundle` dependency configuration by default. */ @get:Optional @get:InputFile abstract val mappingBundle: RegularFileProperty /** * Versions to be mapped. * * In case that a mapping bundle is selected ([mappingBundle] is present), * this property is used for selecting a version subset within the bundle * (every version from the bundle is mapped if no version is specified here). * * @see me.kcra.takenaka.generator.accessor.plugin.AccessorGeneratorExtension.versions * @see BundledMappingProvider.versions */ @get:Input abstract val versions: SetProperty<String> /** * Namespaces to be resolved, defaults to all supported namespaces ("mojang", "spigot", "yarn", "quilt", "searge", "intermediary" and "hashed"). * * *This is ignored if a [mappingBundle] is specified.* * * @see me.kcra.takenaka.generator.accessor.plugin.AccessorGeneratorExtension.namespaces * @see me.kcra.takenaka.generator.accessor.plugin.AccessorGeneratorExtension.historyNamespaces */ @get:Input abstract val namespaces: ListProperty<String> /** * Whether output cache verification constraints should be relaxed, defaults to true. * * @see me.kcra.takenaka.generator.accessor.plugin.AccessorGeneratorExtension.relaxedCache */ @get:Input abstract val relaxedCache: Property<Boolean> /** * The mapped platform(s), defaults to [PlatformTristate.SERVER]. * * @see me.kcra.takenaka.generator.accessor.plugin.AccessorGeneratorExtension.platform */ @get:Input abstract val platform: Property<PlatformTristate> /** * The version manifest. */ @get:Input abstract val manifest: Property<VersionManifest> /** * The resolved mappings. */ @get:Internal abstract val mappings: MutableMappingsMapProperty /** * The root cache workspace ([cacheDir]). */ @get:Internal val cacheWorkspace by lazy { compositeWorkspace { rootDirectory(cacheDir.asFile.get()) } } /** * The shared cache workspace, mainly for manifests and maven-metadata.xml files. */ @get:Internal val sharedCacheWorkspace by lazy { cacheWorkspace.createWorkspace { name = "shared" } } /** * The mapping cache workspace. */ @get:Internal val mappingCacheWorkspace by lazy { cacheWorkspace.createCompositeWorkspace { name = "mappings" } } init { namespaces.convention(listOf("mojang", "spigot", "yarn", "quilt", "searge", "intermediary", "hashed")) cacheDir.convention(project.layout.buildDirectory.dir("takenaka/cache")) relaxedCache.convention(true) platform.convention(PlatformTristate.SERVER) // manual up-to-date checking, it's an Internal property outputs.upToDateWhen { val mappings = mappings.orNull?.keys?.map(Version::id) ?: emptyList() val requiredVersions = versions.orNull ?: emptySet<String>() val versions = if (mappingBundle.isPresent) { ZipFile(mappingBundle.get().asFile).use { zf -> zf.entries() .asSequence() .mapNotNull { entry -> if (entry.isDirectory || !entry.name.endsWith(".tiny")) { return@mapNotNull null } entry.name.substringAfterLast('/').removeSuffix(".tiny") } .filterTo(mutableSetOf()) { version -> requiredVersions.isEmpty() || version in requiredVersions } } } else { requiredVersions } mappings.size == versions.size && versions.containsAll(mappings) } } /** * Runs the task. */ @TaskAction fun run() { val requiredPlatform = platform.get() val requiredVersions = versions.get().toList() val requiredNamespaces = namespaces.get().toSet() fun <T : MappingContributor> MutableCollection<T>.addIfSupported(contributor: T) { if (contributor.targetNamespace in requiredNamespaces) add(contributor) } val resolvedMappings = runBlocking { // resolve mappings on this system, if a bundle is not available if (mappingBundle.isPresent) { BundledMappingProvider(mappingBundle.get().asFile.toPath(), requiredVersions, manifest.get()).get() } else { val yarnProvider = YarnMetadataProvider(sharedCacheWorkspace, relaxedCache.get()) val quiltProvider = QuiltMetadataProvider(sharedCacheWorkspace, relaxedCache.get()) val mappingConfig = buildMappingConfig { version(requiredVersions) workspace(mappingCacheWorkspace) // remove Searge's ID namespace, it's not necessary intercept { v -> NamespaceFilter(v, "searge_id") } // remove static initializers, not needed in the documentation intercept(::StaticInitializerFilter) // remove overrides of java/lang/Object, they are implicit intercept(::ObjectOverrideFilter) // remove obfuscated method parameter names, they are a filler from Searge intercept(::MethodArgSourceFilter) // intern names to save memory intercept(::StringPoolingAdapter) contributors { versionWorkspace -> val mojangProvider = MojangManifestAttributeProvider(versionWorkspace, relaxedCache.get()) val spigotProvider = SpigotManifestProvider(versionWorkspace, relaxedCache.get()) buildList { if (requiredPlatform.wantsServer) { add( VanillaServerMappingContributor( versionWorkspace, mojangProvider, relaxedCache.get() ) ) addIfSupported(MojangServerMappingResolver(versionWorkspace, mojangProvider)) } if (requiredPlatform.wantsClient) { add( VanillaClientMappingContributor( versionWorkspace, mojangProvider, relaxedCache.get() ) ) addIfSupported(MojangClientMappingResolver(versionWorkspace, mojangProvider)) } addIfSupported(IntermediaryMappingResolver(versionWorkspace, sharedCacheWorkspace)) addIfSupported(HashedMappingResolver(versionWorkspace)) addIfSupported(YarnMappingResolver(versionWorkspace, yarnProvider, relaxedCache.get())) addIfSupported(QuiltMappingResolver(versionWorkspace, quiltProvider, relaxedCache.get())) addIfSupported( SeargeMappingResolver( versionWorkspace, sharedCacheWorkspace, relaxedCache = relaxedCache.get() ) ) // Spigot resolvers have to be last if (requiredPlatform.wantsServer) { val link = LegacySpigotMappingPrepender.Link() addIfSupported( // 1.16.5 mappings have been republished with proper packages, even though the reobfuscated JAR does not have those // See: https://hub.spigotmc.org/stash/projects/SPIGOT/repos/builddata/commits/80d35549ec67b87a0cdf0d897abbe826ba34ac27 link.createPrependingContributor( SpigotClassMappingResolver( versionWorkspace, spigotProvider, relaxedCache.get() ), prependEverything = versionWorkspace.version.id == "1.16.5" ) ) addIfSupported( link.createPrependingContributor( SpigotMemberMappingResolver( versionWorkspace, spigotProvider, relaxedCache.get() ) ) ) } } } joinedOutputPath { workspace -> val hash = md5Digest.updateAndHex(requiredNamespaces.sorted().joinToString(",")) workspace["$hash.$requiredPlatform.tiny"] } } val analyzer = MappingAnalyzerImpl( // if the namespaces are missing, nothing happens anyway - no need to configure based on resolvedNamespaces AnalysisOptions( innerClassNameCompletionCandidates = setOf("spigot"), inheritanceAdditionalNamespaces = setOf("searge") // mojang could be here too for maximal parity, but that's in exchange for a little bit of performance ) ) ResolvingMappingProvider(mappingConfig, manifest.get()).get(analyzer) .apply { analyzer.acceptResolutions() } } } mappings.set(resolvedMappings) } }
3
Kotlin
3
53
55839a77073b4ee588d5d2184b51964c31f930c9
13,477
takenaka
Apache License 2.0
src/main/kotlin/com/rutilicus/uisetlist/model/SongKey.kt
rutilicus
231,705,129
false
null
package com.rutilicus.uisetlist.model import com.rutilicus.uisetlist.Constants import java.io.Serializable class SongKey : Serializable { var movieId = "" set(value) { if (value.length == Constants.ID_LEN) { field = value } } var time = 0 }
4
Kotlin
1
1
d3a8e7ea33baaed77003448b1a10090f597e0a80
308
uisetlist
Apache License 2.0
src/main/kotlin/com/kreait/bots/agile/domain/common/data/StandupRepository.kt
kreait
316,613,408
false
null
package com.kreait.bots.agile.domain.common.data import com.kreait.bots.agile.domain.common.actuator.ArrayCount import com.kreait.bots.agile.domain.slack.standup.statistics.DailyActiveUsers import com.mongodb.client.result.UpdateResult import org.springframework.beans.factory.annotation.Autowired import org.springframework.cache.annotation.Cacheable import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.data.mongodb.core.aggregation.Aggregation.count import org.springframework.data.mongodb.core.aggregation.Aggregation.group import org.springframework.data.mongodb.core.aggregation.Aggregation.match import org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation import org.springframework.data.mongodb.core.aggregation.Aggregation.project import org.springframework.data.mongodb.core.find import org.springframework.data.mongodb.core.query.BasicQuery import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Criteria.where import org.springframework.data.mongodb.core.query.Query import org.springframework.data.mongodb.core.query.Update import org.springframework.data.mongodb.repository.MongoRepository import java.time.Instant import java.time.LocalDate import java.time.LocalTime import java.time.format.DateTimeFormatter interface StandupRepository : MongoRepository<Standup, String>, StandupRepositoryCustom { } interface StandupRepositoryCustom { fun getDailyActiveUsers(dateRange: List<LocalDate>): List<DailyActiveUsers> fun findAnsweredAndOpen(userId: String? = null): List<Standup> fun exists(withUserIds: Set<String>? = null, withStatus: Set<Standup.Status>? = null, withStandupDefinitionId: String? = null, isOnDate: LocalDate? = null, hasAnswer: Standup.Answer? = null): Boolean /** * Finds Standup objects by different criterias */ fun find(withIds: Set<String>? = null, withStandupDefinitionId: String? = null, withStatus: Set<Standup.Status>? = null, withoutStatus: Set<Standup.Status>? = null, isOnDate: LocalDate? = null, isBeforeDate: LocalDate? = null, isAfterDate: LocalDate? = null, isOnTime: LocalTime? = null, isBeforeOrOnTime: LocalTime? = null, withUserIds: Set<String>? = null, withBroadcastChannelId: String? = null, hasNumberOfAskedQuestions: Int? = null, timestampIsBefore: Instant? = null, timestampIsAfter: Instant? = null, hasAnswer: Standup.Answer? = null, offset: Long? = null, limit: Int? = null): List<Standup> /** * Finds Standup objects by different criterias */ fun update(withIds: Set<String>? = null, withStandupDefinitionId: String? = null, withStatus: Set<Standup.Status>? = null, withoutStatus: Set<Standup.Status>? = null, isOnDate: LocalDate? = null, isBeforeDate: LocalDate? = null, isAfterDate: LocalDate? = null, isOnTime: LocalTime? = null, isBeforeOrOnTime: LocalTime? = null, withUserIds: Set<String>? = null, withBroadcastChannelId: String? = null, hasNumberOfAskedQuestions: Int? = null, timestampIsBefore: Instant? = null, timestampIsAfter: Instant? = null, hasAnswer: Standup.Answer? = null, update: Update) fun findStandups(query: Query): List<Standup> /** * updates a [Standup] */ fun updateStandup(query: Query, update: Update): Standup? /** * updates a list of [Standup]s */ fun updateStandups(query: Query, update: Update): UpdateResult /** * checks if a received answer already exists * @return true if answer exists, otherwise false */ fun existsByCriteria(criteria: Criteria): Boolean fun getAnsweredStandups(): String } open class StandupRepositoryImpl constructor(@Autowired private val template: MongoTemplate) : StandupRepositoryCustom { override fun getDailyActiveUsers(dateRange: List<LocalDate>): List<DailyActiveUsers> { val dates = dateRange.map { it.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) } val agg = newAggregation( match(criteriaOf(withStatus = setOf(Standup.Status.CLOSED), isInDates = dates)), group(Standup.USER_ID), count().`as`("amount") ) return template.aggregate(agg, Standup.COLLECTION_NAME, DailyActiveUsers::class.java).mappedResults } /** * Finds all Answered standups that are open (this is determined by questions amount and answer amount equality) */ override fun findAnsweredAndOpen(userId: String?): List<Standup> { val query = BasicQuery("{ \$expr: { \$eq: [ { \$size: \"\$${Standup.QUESTIONS}\" }, { \$size: \"\$${Standup.ANSWERS}\" } ] } }") query.addCriteria(where(Standup.STATUS).`is`(Standup.Status.OPEN)) userId?.let { query.addCriteria(where(Standup.USER_ID).`is`(userId)) } return template.find(query, Standup::class.java) } override fun exists(withUserIds: Set<String>?, withStatus: Set<Standup.Status>?, withStandupDefinitionId: String?, isOnDate: LocalDate?, hasAnswer: Standup.Answer?): Boolean { val criteria = criteriaOf(withStandupDefinitionId = withStandupDefinitionId, withStatus = withStatus, isOnDate = isOnDate, withUserIds = withUserIds, hasAnswer = hasAnswer) val query = Query.query(criteria) return template.exists(query, Standup::class.java) } override fun find(withIds: Set<String>?, withStandupDefinitionId: String?, withStatus: Set<Standup.Status>?, withoutStatus: Set<Standup.Status>?, isOnDate: LocalDate?, isBeforeDate: LocalDate?, isAfterDate: LocalDate?, isOnTime: LocalTime?, isBeforeOrOnTime: LocalTime?, withUserIds: Set<String>?, withBroadcastChannelId: String?, hasNumberOfAskedQuestions: Int?, timestampIsBefore: Instant?, timestampIsAfter: Instant?, hasAnswer: Standup.Answer?, offset: Long?, limit: Int?): List<Standup> { val criteria = criteriaOf(withIds, withStandupDefinitionId, withStatus, withoutStatus, isOnDate, isBeforeDate, isOnTime, isBeforeOrOnTime, withUserIds, withBroadcastChannelId, hasNumberOfAskedQuestions, timestampIsBefore, timestampIsAfter, hasAnswer, isAfterDate) val query = Query.query(criteria) offset?.let { query.skip(it) } limit?.let { query.limit(it) } return template.find(query, Standup::class.java) } override fun update(withIds: Set<String>?, withStandupDefinitionId: String?, withStatus: Set<Standup.Status>?, withoutStatus: Set<Standup.Status>?, isOnDate: LocalDate?, isBeforeDate: LocalDate?, isAfterDate: LocalDate?, isOnTime: LocalTime?, isBeforeOrOnTime: LocalTime?, withUserIds: Set<String>?, withBroadcastChannelId: String?, hasNumberOfAskedQuestions: Int?, timestampIsBefore: Instant?, timestampIsAfter: Instant?, hasAnswer: Standup.Answer?, update: Update) { val criteria = criteriaOf(withIds, withStandupDefinitionId, withStatus, withoutStatus, isOnDate, isBeforeDate, isOnTime, isBeforeOrOnTime, withUserIds, withBroadcastChannelId, hasNumberOfAskedQuestions, timestampIsBefore, timestampIsAfter, hasAnswer, isAfterDate) template.updateMulti(Query.query(criteria), update, Standup::class.java) } /** * Creates [Criteria] object of given values */ private fun criteriaOf(withIds: Set<String>? = null, withStandupDefinitionId: String? = null, withStatus: Set<Standup.Status>? = null, withoutStatus: Set<Standup.Status>? = null, isOnDate: LocalDate? = null, isBeforeDate: LocalDate? = null, isOnTime: LocalTime? = null, isBeforeOrOnTime: LocalTime? = null, withUserIds: Set<String>? = null, withBroadcastChannelId: String? = null, hasNumberOfAskedQuestions: Int? = null, timestampIsBefore: Instant? = null, timestampIsAfter: Instant? = null, hasAnswer: Standup.Answer? = null, isAfterDate: LocalDate? = null, isInDates: List<String>? = null ): Criteria { val criteriaList = mutableListOf<Criteria>() withIds?.let { criteriaList.add(where("_id").`in`(it)) } withStandupDefinitionId?.let { criteriaList.add(where(Standup.STANDUP_DEFINITION_ID).`is`(it)) } withStatus?.let { criteriaList.add(where(Standup.STATUS).`in`(it)) } withoutStatus?.let { criteriaList.add(where(Standup.STATUS).nin(it)) } isOnDate?.let { criteriaList.add(where(Standup.DATE).`is`(it)) } isBeforeDate?.let { criteriaList.add(where(Standup.DATE).lt(it)) } isAfterDate?.let { criteriaList.add(where(Standup.DATE).gt(it)) } isOnTime?.let { criteriaList.add(where(Standup.TIME).`is`(it)) } isBeforeOrOnTime?.let { criteriaList.add(where(Standup.TIME).lte(it)) } withUserIds?.let { criteriaList.add(where(Standup.USER_ID).`in`(it)) } withBroadcastChannelId?.let { criteriaList.add(where(Standup.BROADCAST_CHANNEL_ID).`is`(it)) } timestampIsBefore?.let { criteriaList.add(where(Standup.TIMESTAMP).lt(it)) } timestampIsAfter?.let { criteriaList.add(where(Standup.TIMESTAMP).gt(it)) } hasNumberOfAskedQuestions?.let { criteriaList.add(where(Standup.QUESTIONS_ASKED).`is`(it)) } hasAnswer?.let { criteriaList.add(where(Standup.ANSWERS).`in`(it)) } isInDates?.let { criteriaList.add(where(Standup.DATE).`in`(it)) } return if (criteriaList.isEmpty()) Criteria() else Criteria().andOperator(*criteriaList.toTypedArray()) } @Cacheable(cacheNames = [Standup.ANSWERED_COLLECTION], sync = true) override fun getAnsweredStandups(): String { val criteria = Criteria() criteria.and(Standup.QUESTIONS_ASKED).ne(0) criteria.and(Standup.STATUS).`is`(Standup.Status.CLOSED) val agg = newAggregation(Standup::class.java, match(criteria), project() .and("answers") .size() .`as`("count")) val results = template.aggregate( agg, ArrayCount::class.java ) return results.mappedResults.map { it.count }.sum().toString() } override fun existsByCriteria(criteria: Criteria): Boolean { return this.template.exists(Query.query(criteria), Standup::class.java) } override fun findStandups(query: Query): List<Standup> { return this.template.find(query = query) } override fun updateStandup(query: Query, update: Update): Standup? { return this.template.findAndModify(query, update, Standup::class.java) } override fun updateStandups(query: Query, update: Update): UpdateResult { return this.template.updateMulti(query, update, Standup::class.java) } }
3
Kotlin
2
8
0b56e5b82eda60ed76f31dbdf8f57719b2d30acd
12,286
olaph-slack-app
MIT License
domain/src/main/java/com/clcmo/domain/entities/SpotlightType.kt
clcmo
572,208,998
false
{"Kotlin": 37997}
package com.clcmo.domain.entities enum class SpotlightType { COMICS, EVENTS, SERIES, STORIES }
6
Kotlin
0
1
a2e1c1f10b11949bae17f879943f777581cdce03
111
marvel-challenge
MIT License
app/src/main/java/com/madtoast/flyingboat/ui/fragments/creators/CreatorProfileFragment.kt
MadToast
511,992,274
false
{"Kotlin": 224718}
package com.madtoast.flyingboat.ui.fragments.creators import android.content.res.Configuration import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.madtoast.flyingboat.R import com.madtoast.flyingboat.api.floatplane.model.enums.SortType import com.madtoast.flyingboat.databinding.FragmentCreatorProfileBinding import com.madtoast.flyingboat.ui.components.adapters.BaseViewAdapter import com.madtoast.flyingboat.ui.components.adapters.ViewPagerCustomViewsAdapter import com.madtoast.flyingboat.ui.components.views.PostView import com.madtoast.flyingboat.ui.components.views.TextItemView import com.madtoast.flyingboat.ui.fragments.creators.viewmodels.CreatorProfileViewModel import com.madtoast.flyingboat.ui.fragments.creators.viewmodels.CreatorProfileViewModelFactory import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class CreatorProfileFragment() : Fragment() { companion object { const val LIMIT: Int = 20 } private lateinit var _creatorProfileViewModel: CreatorProfileViewModel private lateinit var _binding: FragmentCreatorProfileBinding val args: CreatorProfileFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentCreatorProfileBinding.inflate(inflater, container, false) _creatorProfileViewModel = ViewModelProvider( this, CreatorProfileViewModelFactory(requireContext().cacheDir, requireContext()) )[CreatorProfileViewModel::class.java] //Apply insets to list _binding.root.setOnApplyWindowInsetsListener { v, insets -> val tv = TypedValue() if (requireActivity().theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) { val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics) //Calculate top padding to take status bar into account val windowInsets = ViewCompat.getRootWindowInsets(requireActivity().window.decorView) val systemBarsInsets = windowInsets?.getInsets(WindowInsetsCompat.Type.systemBars()) systemBarsInsets?.top?.let { _binding.root.updatePadding(top = actionBarHeight + it) } systemBarsInsets?.bottom?.let { _binding.root.updatePadding(bottom = it) } } v.onApplyWindowInsets(insets) } //Initialize the view model _creatorProfileViewModel.init() //Set up recycler view setupViewPager() return _binding.root } private fun loadCreatorContent( forceRefresh: Boolean = false, search: String? = null, tags: Array<String>? = null, hasVideo: Boolean? = null, hasAudio: Boolean? = null, hasPicture: Boolean? = null, hasText: Boolean? = null, sort: SortType? = null, fromDuration: Int? = null, toDuration: Int? = null, fromDate: String? = null, toDate: String? = null ) { //Fetch the required data CoroutineScope(Dispatchers.IO).launch { _creatorProfileViewModel.listCreatorContent( args.creatorId, forceRefresh, LIMIT, _creatorProfileViewModel.postResults.value?.success?.size, //Always fetch after current size search, tags, hasVideo, hasAudio, hasPicture, hasText, sort, fromDuration, toDuration, fromDate, toDate ) } } private fun setupViewPager() { val listContentHandler = object : ViewPagerCustomViewsAdapter.ViewItemHandler { override fun getViewType(): Int { return 0 } override fun initializeView(parent: ViewGroup): RecyclerView.ViewHolder { val recyclerView = RecyclerView(parent.context) setupRecyclerView(recyclerView) return ViewPagerCustomViewsAdapter.ViewPagerContent(recyclerView) } override fun applyContent(viewHolder: RecyclerView.ViewHolder) { if (viewHolder.itemView is RecyclerView && _creatorProfileViewModel.postResults.value?.success != null) { val sourceData = _creatorProfileViewModel.postResults.value!!.success!! val recyclerView = viewHolder.itemView as RecyclerView val adapter = recyclerView.adapter as BaseViewAdapter val adapterDataSet = adapter.getItemSet() var startingIndex = 0 //Move forward in adapter at the same time we move forward with received content if (adapterDataSet.size - 1 > sourceData.size) { val itemsRemoved = adapterDataSet.size adapterDataSet.clear() //Clear the adapter data set adapter.notifyItemRangeRemoved( 0, itemsRemoved ) //Notify adapter that items were removed } for (item in sourceData) { var itemWasUpdated = false for (i in startingIndex..adapterDataSet.size) { val currentItem = adapterDataSet[i] if (currentItem is PostView.Companion.PostItem) { startingIndex = i itemWasUpdated = true break } } if (!itemWasUpdated) { adapter.addItem(PostView.Companion.PostItem(item)) startingIndex++ //Move this forward to avoid entering loop above } } } } } } private fun setupRecyclerView(recyclerView: RecyclerView) { val useGridLayout = resources.getBoolean(R.bool.isBigScreen) || resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE val gridColumns = resources.getInteger(R.integer.grid_columns) recyclerView.adapter = BaseViewAdapter(ArrayList()) recyclerView.layoutManager = if (useGridLayout) { val layoutManager = GridLayoutManager(requireContext(), gridColumns) layoutManager.spanSizeLookup = (object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { val item = (recyclerView.adapter as BaseViewAdapter).getItemAt(position) return if (item is TextItemView.Companion.TextItem) { gridColumns } else { 1 } } }) layoutManager } else { LinearLayoutManager(requireContext()) } } }
0
Kotlin
0
0
d2f52e5f22cfb580287d3baa7e0c7fe327d8cb86
7,883
refloated-android
MIT License
projects/core/src/main/kotlin/site/siredvin/peripheralworks/common/recipes/AnchorCleanRecipe.kt
SirEdvin
489,471,520
false
{"Kotlin": 624227, "Java": 4072}
package site.siredvin.peripheralworks.common.recipes import net.minecraft.core.RegistryAccess import net.minecraft.resources.ResourceLocation import net.minecraft.world.inventory.CraftingContainer import net.minecraft.world.item.ItemStack import net.minecraft.world.item.crafting.CraftingBookCategory import net.minecraft.world.item.crafting.CustomRecipe import net.minecraft.world.item.crafting.RecipeSerializer import net.minecraft.world.level.Level import site.siredvin.peripheralium.common.blocks.BaseNBTBlock import site.siredvin.peripheralworks.common.setup.Blocks import site.siredvin.peripheralworks.common.setup.RecipeSerializers class AnchorCleanRecipe(id: ResourceLocation, category: CraftingBookCategory) : CustomRecipe(id, category) { companion object { private fun isSuitableAnchor(stack: ItemStack): Boolean { return stack.`is`(Blocks.FLEXIBLE_REALITY_ANCHOR.get().asItem()) && stack.getTagElement(BaseNBTBlock.INTERNAL_DATA_TAG) != null } } private val resultItem by lazy { Blocks.FLEXIBLE_REALITY_ANCHOR.get().asItem().defaultInstance } override fun matches(p0: CraftingContainer, p1: Level): Boolean { return p0.items.count { !it.isEmpty } == 1 && p0.items.any { isSuitableAnchor(it) } } override fun getResultItem(registry: RegistryAccess): ItemStack { return resultItem } override fun assemble(p0: CraftingContainer, p1: RegistryAccess): ItemStack { val firstCandidate = p0.items.find(Companion::isSuitableAnchor) ?: ItemStack.EMPTY return resultItem.copyWithCount(firstCandidate.count) } override fun canCraftInDimensions(p0: Int, p1: Int): Boolean { return true } override fun getSerializer(): RecipeSerializer<*> { return RecipeSerializers.ANCHOR_CLEAN.get() } }
16
Kotlin
3
9
a59b8b79e5df1de388bba9fb0d8effe5763e569b
1,835
UnlimitedPeripheralWorks
MIT License
common/src/main/kotlin/com/zerra/common/api/mod/ModLoader.kt
bvanseg
309,162,032
false
{"Kotlin": 105931, "GLSL": 1222}
package com.zerra.common.api.mod import bvanseg.kotlincommons.any.getLogger import bvanseg.kotlincommons.evenir.bus.EventBus import bvanseg.kotlincommons.javaclass.createNewInstance import com.zerra.common.util.ModLoadException import com.zerra.common.util.resource.MasterResourceManager import com.zerra.common.util.storage.FileManager import io.github.classgraph.ClassGraph import java.net.URL import java.net.URLClassLoader import java.nio.file.Files import kotlin.reflect.jvm.jvmName /** * @author Boston Vanseghi * @since 0.0.1 */ object ModLoader { val logger = getLogger() val EVENT_BUS = EventBus() val mods = mutableMapOf<String, Any>() private var hasLoaded = false internal fun loadAllMods() { injectMods() findAndLoadMods() } private fun findAndLoadMods() { if (hasLoaded) { throw IllegalStateException("Attempted to load mods when mods have already been loaded!") } MasterResourceManager.resources.apply { logger.debug("Loading mod instances...") val start = System.currentTimeMillis() getClassesWithAnnotation(Mod::class.jvmName).loadClasses().forEach { modClass -> loadMod(modClass) } logger.debug("Finished loading ${mods.size} mods in ${System.currentTimeMillis() - start}ms") } hasLoaded = true } private fun loadMod(modClass: Class<*>) = try { logger.trace("Attempting to load mod class ${modClass.name}") val mod = try { modClass.kotlin.objectInstance ?: createNewInstance(modClass) } catch(e: NoSuchMethodException) { throw ModLoadException("Failed to construct mod class instance for $modClass. Make sure you have a no-arg constructor!", e) } catch(e: UninitializedPropertyAccessException) { throw ModLoadException("Failed to construct mod class instance for $modClass. Make sure you have a no-arg constructor!", e) } ?: throw ModLoadException("Failed to load mod for class $modClass") val metadata = modClass.getAnnotation(Mod::class.java) val domain = metadata.domain if (mods[domain.toLowerCase()] != null && domain.equals("zerra", true)) { throw ModLoadException("The domain name '$domain' is the same as the game's domain") } if (mods.containsKey(domain)) { throw ModLoadException("The domain name '$domain' is already being used by another mod") } mods[domain] = mod } catch (e: Exception) { logger.error("Error trying to load mod class ${modClass.name}", e) } /** * Loads all mods onto the classpath from their respective JARs. */ private fun injectMods() { logger.info("Beginning mod injection") val start = System.currentTimeMillis() val mods = FileManager.getModJARs() val classGraph = ClassGraph().enableAllInfo() val urls = mutableListOf<URL>() mods.filter(Files::isRegularFile).forEach { val file = it.toFile() if (file.extension.toLowerCase() == "jar") { logger.info("Found potential mod JAR $it") urls.add(file.toURI().toURL()) } } classGraph.addClassLoader(URLClassLoader(urls.toTypedArray(), this::class.java.classLoader)) // Scan the resources after performing the injection. MasterResourceManager.scanResources(true, classGraph) logger.info("Finished mod injection in ${System.currentTimeMillis() - start}ms") } }
0
Kotlin
0
0
8e3d6c86c573afb9e8942b9018ece3b1a6eeb95f
3,609
Zerra
MIT License
src/jsMain/kotlin/org/olafneumann/regex/generator/ui/utils/Xhtml.kt
noxone
239,624,807
false
{"Kotlin": 247250, "HTML": 22083, "CSS": 5034, "C": 2817, "Dockerfile": 1749, "JavaScript": 210}
package org.olafneumann.regex.generator.ui.utils import kotlinx.html.BUTTON import kotlinx.html.ButtonType import kotlinx.html.DIV import kotlinx.html.button import kotlinx.html.js.onClickFunction import kotlinx.html.title import org.w3c.dom.events.Event fun DIV.gButton( classes: String, title: String, onClickFunction: (Event) -> Unit, block: BUTTON.() -> Unit ) { button(classes = "btn btn-light btn-sm $classes", type = ButtonType.button) { block() this.title = title this.onClickFunction = onClickFunction } }
15
Kotlin
66
397
1e684746a51d7e4398e89f89986059b0edf5ef07
565
regex-generator
MIT License
tagged-union-implementation/src/main/kotlin/models.kt
Cerber-Ursi
587,276,242
false
null
import org.jboss.forge.roaster.Roaster data class SourceClass(val name: String) fun parseClass(code: String): SourceClass { val source = Roaster.parse(code) return SourceClass( name = source.getName() ) }
0
Kotlin
0
0
55c55eb1366ab5480df5b11d43617141c6237296
216
tagged-union-gradle-codegen-plugin
MIT License
Subscription-core/app/src/main/java/com/cashfree/subscription/demo/helper/Helper.kt
cashfree
644,277,821
false
{"Kotlin": 48510, "Java": 2357}
package com.cashfree.subscription.demo.helper import android.view.View fun View.visibility(show: Boolean) { if (show) this.visibility = View.VISIBLE else this.visibility = View.GONE }
0
Kotlin
0
2
05f9f7c3b474b79647d044a69b97c240888dcf6f
193
android-subscription-sdk
Apache License 2.0
app/src/main/java/com/laurenyew/githubbrowser/ui/GithubBrowserActivity.kt
laurenyew
252,290,716
false
null
package com.laurenyew.githubbrowser.ui import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.laurenyew.githubbrowser.R import com.laurenyew.githubbrowser.ui.browser.GithubBrowserFragment /** * Wrapper activity for Github Browser feature */ class GithubBrowserActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.github_browser_activity) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.container, GithubBrowserFragment.newInstance()) .commitNow() } } }
0
Kotlin
0
0
2694154be1bc21b745b2e8bc02393145a3b13108
703
GithubBrowser
MIT License
core/src/no/sandramoen/blipblop/actors/MiddleWhiteLine.kt
Slideshow776
384,910,444
false
null
package no.sandramoen.blipblop.actors import com.badlogic.gdx.scenes.scene2d.Stage import no.sandramoen.blipblop.utils.BaseActor class MiddleWhiteLine(x: Float, y: Float, s: Stage) : BaseActor(x, y, s) { init { loadImage("whitePixel") setSize(100f, .1f) setPosition(0f, 50f - height / 2) } }
0
Kotlin
0
1
6c5d94dd72262811cb5bd2b3c311cf580a166c13
326
Blip-Blop
Freetype Project License
news-cast-explorer-cdc/src/main/kotlin/org/jesperancinha/newscast/cdc/domain/Message.kt
jesperancinha
573,498,638
false
{"Kotlin": 83277, "Java": 40711, "TypeScript": 29056, "Shell": 7420, "Makefile": 6627, "HTML": 6537, "JavaScript": 5146, "Dockerfile": 3530, "CSS": 3421, "Python": 2092, "Sass": 80}
package org.jesperancinha.newscast.cdc.domain import org.hibernate.Hibernate import jakarta.persistence.Entity import jakarta.persistence.Id import jakarta.persistence.Table /** * Created by jofisaes on 08/10/2021 */ @Entity @Table(name = "message", schema = "eventuate") data class Message( @Id val id: String? = null, val destination: String? = null, val headers: String? = null, val payload: String? = null, val creation_time: Long? = null, val published: Int? = null ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false other as Message return id != null && id == other.id } override fun hashCode(): Int = javaClass.hashCode() @Override override fun toString(): String { return this::class.simpleName + "(id = $id , destination = $destination , headers = $headers , payload = $payload , creation_time = $creation_time , published = $published )" } }
0
Kotlin
0
4
0c68da885a7ef05623e1492a864fde0ea8fcf982
1,068
news-cast-explorer
Apache License 2.0
app/src/main/java/org/simple/clinic/search/results/PatientSearchResultsController.kt
TrendingTechnology
149,613,985
true
{"Kotlin": 869727, "C": 680052, "Makefile": 635}
package org.simple.clinic.search.results import io.reactivex.Observable import io.reactivex.ObservableSource import io.reactivex.ObservableTransformer import io.reactivex.rxkotlin.ofType import io.reactivex.rxkotlin.withLatestFrom import org.simple.clinic.ReportAnalyticsEvents import org.simple.clinic.patient.OngoingPatientEntry import org.simple.clinic.patient.OngoingPatientEntry.PersonalDetails import org.simple.clinic.patient.PatientRepository import org.simple.clinic.widgets.UiEvent import javax.inject.Inject typealias Ui = PatientSearchResultsScreen typealias UiChange = (Ui) -> Unit class PatientSearchResultsController @Inject constructor( val repository: PatientRepository ) : ObservableTransformer<UiEvent, UiChange> { override fun apply(events: Observable<UiEvent>): ObservableSource<UiChange> { val replayedEvents = events.compose(ReportAnalyticsEvents()).replay().refCount() return Observable.mergeArray( populateSearchResults(replayedEvents), openPatientSummary(replayedEvents), createNewPatient(replayedEvents)) } private fun populateSearchResults(events: Observable<UiEvent>): Observable<UiChange> { return events.ofType<PatientSearchResultsScreenCreated>() .map { it.key } .flatMap { // TODO: when age isn't present, calculate age from DOB. repository.search(name = it.fullName, assumedAge = it.age.trim().toInt()) } .map { { ui: Ui -> ui.updateSearchResults(it) } } } private fun openPatientSummary(events: Observable<UiEvent>): Observable<UiChange> { return events.ofType<PatientSearchResultClicked>() .map { it.searchResult.uuid } .map { { ui: Ui -> ui.openPatientSummaryScreen(patientUuid = it) } } } private fun createNewPatient(events: Observable<UiEvent>): Observable<UiChange> { val screenKey = events .ofType<PatientSearchResultsScreenCreated>() .map { it.key } return events.ofType<CreateNewPatientClicked>() .withLatestFrom(screenKey) .map { (_, key) -> OngoingPatientEntry(PersonalDetails( fullName = key.fullName, dateOfBirth = key.dateOfBirth, age = key.age, gender = null)) } .flatMap { repository .saveOngoingEntry(it) .andThen(Observable.just({ ui: Ui -> ui.openPatientEntryScreen() })) } } }
0
Kotlin
0
0
9ecc19d178b7aa04787f36474c542b806d94d1ba
2,437
simple-android
MIT License
app/src/main/java/com/androidapp/cakelistapp/app/view/adapter/CakeListAdapter.kt
serifenuruysal
435,931,288
false
{"Kotlin": 24162}
package com.androidapp.cakelistapp.app.view.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.androidapp.cakelistapp.R import com.androidapp.cakelistapp.data.model.CakeModel import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.view_row_item.view.* import javax.inject.Inject import javax.inject.Singleton /** * Created by Nur Uysal on 06/12/2021. */ @Singleton class CakeListAdapters @Inject constructor() : RecyclerView.Adapter<CakeListAdapters.CakeViewHolder>() { inner class CakeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) private val diffCallback = object : DiffUtil.ItemCallback<CakeModel>() { override fun areItemsTheSame(oldItem: CakeModel, newItem: CakeModel): Boolean { return (oldItem.title == newItem.title && oldItem.description == newItem.description && oldItem.imageUrl == newItem.imageUrl) } override fun areContentsTheSame(oldItem: CakeModel, newItem: CakeModel): Boolean { return oldItem.hashCode() == newItem.hashCode() } } private val differ = AsyncListDiffer(this, diffCallback) fun submitList(list: MutableList<CakeModel>) = differ.submitList(list) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CakeViewHolder { return CakeViewHolder( LayoutInflater.from( parent.context ).inflate( R.layout.view_row_item, parent, false ) ) } override fun getItemCount(): Int { return differ.currentList.size } override fun onBindViewHolder(holder: CakeViewHolder, position: Int) { val item = differ.currentList[position] holder.itemView.apply { tv_row_item_title.text = "${item.title}" Glide.with(this).load(item.imageUrl).error(R.drawable.no_image).into(iv_row_item_image) this.setOnClickListener { //TODO make more user friendly alert dialog or etc. it cause problem for continous clicks Toast.makeText(context, item.description, Toast.LENGTH_SHORT).show() } } } }
0
Kotlin
0
3
19292a0f77c3fb07c6cee833a089b9c5b17f5668
2,411
CakeListAndroidApp
Apache License 2.0
app/src/main/kotlin/com/hexanovate/familytree/ui/user/tree/TreeListActivityUser.kt
shivpanks19
229,116,616
false
null
/* * Copyright 2018 Farbod Salamat-Zadeh * * 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.hexanovate.familytree.ui.user.tree import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import com.hexanovate.familytree.R import com.hexanovate.familytree.model.Person import com.hexanovate.familytree.model.tree.TreeListItem import com.hexanovate.familytree.ui.subadmin.NavigationDrawerActivity import com.hexanovate.familytree.ui.user.person.CreatePersonActivityUser import com.hexanovate.familytree.ui.user.person.ViewPersonActivityUser import com.hexanovate.familytree.util.standardNavigationParams import com.hexanovate.familytree.util.withNavigation /** * Activity for displaying the tree as an indented list (a "vertical tree"). * * @see TreeActivity */ class TreeListActivityUser : NavigationDrawerActivity() { companion object { /** * Request code for starting [CreatePersonActivity] for result, to add a new person to the * database. */ private const val REQUEST_PERSON_CREATE = 8 /** * Request code for starting [ViewPersonActivity] for result, to view the details of a * [Person]. */ private const val REQUEST_VIEW_PERSON = 9 } private lateinit var treeAdapter: FamilyTreeAdapterUser private lateinit var items: ArrayList<TreeListItem<Person>> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(withNavigation(R.layout.activity_list)) setupFab() populateList() } private fun setupFab() { val addPersonButton = findViewById<FloatingActionButton>(R.id.fab) addPersonButton.setOnClickListener { addPerson() } } private fun addPerson() { val intent = Intent(this, CreatePersonActivityUser::class.java) startActivityForResult(intent, REQUEST_PERSON_CREATE) } private fun populateList() { val root = TreeHandlerUser.getDisplayedTree(this, null) items = root?.asTreeList() as ArrayList<TreeListItem<Person>> treeAdapter = FamilyTreeAdapterUser(this, items) treeAdapter.onItemClick { _, item -> viewPerson(item.data) } findViewById<RecyclerView>(R.id.recyclerView).apply { layoutManager = LinearLayoutManager(context) setHasFixedSize(true) adapter = treeAdapter } } private fun viewPerson(person: Person) { val intent = Intent(this, ViewPersonActivityUser::class.java) .putExtra(ViewPersonActivityUser.EXTRA_PERSON, person) startActivityForResult(intent, REQUEST_VIEW_PERSON) } /** * Refreshes the list by fetching the data (list) from the database and displaying it in the UI */ private fun refreshList() { items.clear() val newRoot = TreeHandlerUser.getDisplayedTree(this, null) items.addAll(newRoot?.asTreeList() as ArrayList<TreeListItem<Person>>) treeAdapter.notifyDataSetChanged() } override fun getSelfNavigationParams() = standardNavigationParams(NAVDRAWER_ITEM_TREE_LIST, findViewById(R.id.toolbar)) override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_PERSON_CREATE || requestCode == REQUEST_VIEW_PERSON) { if (resultCode == Activity.RESULT_OK) { // Refresh list refreshList() } } } }
0
Kotlin
0
0
7cbf7cd83510954113ec0109c0a1ac77fca3f275
4,270
FamilyTreeApp-master
Apache License 2.0
cams-module-mine/src/main/java/com/linwei/cams/module/mine/http/ApiService.kt
WeiShuaiDev
390,640,743
false
null
package com.linwei.cams.module.mine.http interface ApiService { }
0
Kotlin
0
3
37ffb7142ce1141c7b09ef69664c535150d25aaa
68
CamsModular
Apache License 2.0
asset-collection-example/src/main/kotlin/furhatos/app/assetcollectionexample/flow/behaviorlibrary/behaviorLibExample.kt
FurhatRobotics
418,899,332
false
{"Kotlin": 120881, "Python": 13628, "JavaScript": 5293, "HTML": 4541, "CSS": 2334}
package furhatos.app.assetcollectionexample.flow.behaviorlibrary import furhat.libraries.standard.BehaviorLib import furhat.libraries.standard.BehaviorLib.behaviorLib import furhatos.app.assetcollectionexample.flow.MenuParent import furhatos.flow.kotlin.State import furhatos.flow.kotlin.furhat import furhatos.flow.kotlin.state val behaviorLibExample: State = state(MenuParent) { /** randomHeadMovements is a partial state with OnTime triggers for making random head movements at specified intervals. * Triggers of a partial state can be included in a state with "include()" */ include(BehaviorLib.AutomaticMovements.randomHeadMovements(repetitionPeriod = 3000..5000)) onEntry { furhat.say("In this state my head will move randomly to give me a more natural stance.") furhat.say("You can also try switching characters.") } onButton("Without head movements") { /** Set value to avoid AutomaticHeadMovements to interfere with other head movements defined in a gesture. * We assume gestures are not longer than 3000 ms. * This function should be used if gestures are played in parallel. */ BehaviorLib.AutomaticMovements.autoHeadMovementDelay(10000) furhat.say("My head should stay still for a while.") } onButton("Switch to another character") { val newChar = furhat.characters.random() furhat.say("Switching to $newChar") behaviorLib.switchToCharacter(newChar) } }
1
Kotlin
12
4
70aa5af3ca6f1d4a1e81f01db9d86444aa838043
1,502
tutorials
MIT License
src/main/kotlin/unq/deportes/repository/TeamRepository.kt
Coronel-B
217,918,188
false
null
package unq.deportes.repository import org.springframework.data.repository.CrudRepository import unq.deportes.model.Team interface TeamRepository : CrudRepository<Team, Long> { }
0
Kotlin
1
0
c25915cebb358c48bae14e18aa82e707216f4707
181
deportesunq-backend
Apache License 2.0
src/main/kotlin/com/appifyhub/monolith/features/auth/domain/AuthMapper.kt
appifyhub
323,403,014
false
{"Kotlin": 874718, "Python": 840576, "HTML": 10613, "Shell": 4596, "Dockerfile": 930}
package com.appifyhub.monolith.features.auth.domain import com.appifyhub.monolith.features.common.domain.stubUser import com.appifyhub.monolith.features.user.domain.toData import com.appifyhub.monolith.features.user.domain.model.User import com.appifyhub.monolith.features.user.domain.model.UserId import com.appifyhub.monolith.features.auth.domain.model.TokenDetails import com.appifyhub.monolith.features.auth.domain.security.JwtClaims import com.appifyhub.monolith.features.auth.domain.security.JwtHelper import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.AUTHORITIES import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.AUTHORITY_DELIMITER import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.CREATED_AT import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.EXPIRES_AT import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.GEO import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.IP_ADDRESS import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.IS_STATIC import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.ORIGIN import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.UNIVERSAL_ID import com.appifyhub.monolith.features.auth.domain.security.JwtHelper.Claims.VALUE import com.appifyhub.monolith.features.auth.storage.model.TokenDetailsDbm import com.appifyhub.monolith.features.creator.domain.model.Project import org.springframework.security.core.GrantedAuthority import java.util.Date import java.util.concurrent.TimeUnit fun TokenDetailsDbm.toDomain( jwtHelper: JwtHelper, ): TokenDetails = jwtHelper .extractPropertiesFromJwt(tokenValue) .toTokenDetails(isBlocked = blocked) fun TokenDetails.toData( owner: User? = null, project: Project? = null, ): TokenDetailsDbm = TokenDetailsDbm( tokenValue = tokenValue, blocked = isBlocked, owner = owner?.toData(project) ?: stubUser().copy(id = ownerId).toData(project), ) fun JwtClaims.toTokenDetails( isBlocked: Boolean = false, ): TokenDetails = TokenDetails( tokenValue = get(VALUE).toString(), isBlocked = isBlocked, createdAt = getJwtDate(CREATED_AT), expiresAt = getJwtDate(EXPIRES_AT), ownerId = UserId.fromUniversalFormat(get(UNIVERSAL_ID).toString()), authority = get(AUTHORITIES).toString() .split(AUTHORITY_DELIMITER) .map { authorityValue -> GrantedAuthority { authorityValue } } .let { User.Authority.find(it, User.Authority.DEFAULT) }, origin = get(ORIGIN)?.toString(), ipAddress = get(IP_ADDRESS)?.toString(), geo = get(GEO)?.toString(), isStatic = get(IS_STATIC).toString().toBoolean(), ) private fun JwtClaims.getJwtDate(key: String): Date = Date( TimeUnit.SECONDS.toMillis((get(key) as Int).toLong()) )
20
Kotlin
0
0
6b7cdacf736505de038d19b5a5de34b9613f8eb1
2,842
monolith
MIT License
app/src/main/java/com/densitech/scrollsmooth/ui/video/model/MediaOwner.kt
thanhduy26091995
832,247,908
false
{"Kotlin": 223972}
package com.densitech.scrollsmooth.ui.video.model import kotlinx.serialization.Serializable @Serializable data class MediaOwner( val name: String, val email: String )
0
Kotlin
0
2
f607ca891885a71bd60ad909794df25ba9aff0eb
177
SmoothScroll
MIT License
application/src/main/kotlin/com/ziemsky/uploader/stats/StatsCalculator.kt
ziemsky
137,949,351
false
{"Kotlin": 222979}
package com.ziemsky.uploader.stats import com.ziemsky.uploader.securing.model.SecuredFileSummary import com.ziemsky.uploader.securing.model.SecuredFilesBatchStats import com.ziemsky.uploader.securing.model.local.LocalFile import java.time.Instant class StatsCalculator { fun calculateStatsFor(securedFileSummaries: Set<SecuredFileSummary>): SecuredFilesBatchStats = // exception on empty set? SecuredFilesBatchStats( securedFileSummaries.size, minStartTime(securedFileSummaries), maxStartTime(securedFileSummaries), totalFilesSizeInBytes(securedFileSummaries) ) private fun minStartTime(securedFileSummaries: Set<SecuredFileSummary>): Instant = securedFileSummaries.minOfOrNull { it.uploadStart } ?: Instant.MIN // todo null value? exception? private fun maxStartTime(securedFileSummaries: Set<SecuredFileSummary>): Instant = securedFileSummaries.maxOfOrNull { it.uploadEnd } ?: Instant.MIN // todo null value? exception? private fun totalFilesSizeInBytes(securedFileSummaries: Set<SecuredFileSummary>): Long = securedFileSummaries .map(SecuredFileSummary::securedFile) .fold(0, { totalFilesSizeInBytes: Long, securedFile: LocalFile -> totalFilesSizeInBytes + securedFile.sizeInBytes }) }
15
Kotlin
0
0
bcaab60a52abc473e259da32ad5c73839ffc5c59
1,382
gdrive-uploader
MIT License
project/src/tests/CaterPillarTests.kt
informramiz
173,284,942
false
null
package tests import org.junit.Test import problems.CaterPillarMethod import kotlin.test.assertEquals class CaterPillarTests { @Test fun testAbsDistinct() { assertEquals(7, CaterPillarMethod.absDistinct(intArrayOf(-10, -9, -3, -3, -3, -1, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 32))) assertEquals(5, CaterPillarMethod.absDistinct(intArrayOf(-5, -3, -1, 0, 3, 6))) //all negative assertEquals(3, CaterPillarMethod.absDistinct(intArrayOf(-3, -3, -2, -1))) //all positive assertEquals(4, CaterPillarMethod.absDistinct(intArrayOf(0, 1, 2, 2, 3, 3, 3))) //all same assertEquals(1, CaterPillarMethod.absDistinct(intArrayOf(3, 3, 3, 3, 3, 3, 3))) //just 1 element assertEquals(1, CaterPillarMethod.absDistinct(intArrayOf(0))) //arithmetic overflow assertEquals(3, CaterPillarMethod.absDistinct(intArrayOf(-2147483648, 0, 2147483647))) } @Test fun testMinAbsSumOfTwo() { val test = {A: IntArray, expectedSum: Int -> assertEquals(expectedSum, CaterPillarMethod.minAbsSumOfTwo(A)) } test(intArrayOf(1, -3, 4), 1) //extreme ends test(intArrayOf(-1_000_000_000, 1_000_000_000), 0) //mix of positive and negative test(intArrayOf(-5, -4, 1, 2, 3, 7), 1) //all negatives test(intArrayOf(-5, -4, -3, -2, -1), 2) //all positives test(intArrayOf(2, 3, 4, 5, 7), 4) } }
0
Kotlin
0
0
a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4
1,471
codility-challenges-practice
Apache License 2.0
app/src/main/java/com/example/tests/fundamentos/recycle_view/InternalStorageAdapter.kt
Fenias-Manhenge
611,944,189
false
null
package com.example.tests.fundamentos.recycle_view import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import com.example.tests.R import com.example.tests.storage.InternalStoragePhoto class InternalStorageAdapter(var dataGallery: List<InternalStoragePhoto>): RecyclerView.Adapter<InternalStorageAdapter.GalleryViewHolder>() { inner class GalleryViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GalleryViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.gallery_item, parent, false) return GalleryViewHolder(view) } override fun onBindViewHolder(holder: GalleryViewHolder, position: Int) { holder.itemView.apply { val photo = dataGallery[position].bitmap val imageView= findViewById<ImageView>(R.id.ivPhotoTest) imageView.setImageBitmap(photo) } // holder.itemView.apply { // val ivPhoto = findViewById<ImageView>(R.id.ivPhoto) // val image = dataGallery[position].fileName // Glide.with(this.context).load(image).into(ivPhoto) // } } override fun getItemCount(): Int { return dataGallery.size } }
0
Kotlin
0
0
52d961c367bddd0bf059614a86be8075e083dbd7
1,378
Tests-in-Android-Studio
MIT License
backend-kt/src/main/kotlin/net/daimatz/gql/study/KtorGraphQLServer.kt
daimatz
408,349,887
false
null
package net.daimatz.gql.study import com.expediagroup.graphql.server.execution.GraphQLRequestHandler import com.expediagroup.graphql.server.execution.GraphQLServer import io.ktor.request.ApplicationRequest class KtorGraphQLServer( requestParser: KtorGraphQLRequestParser, contextFactory: KtorGraphQLContextFactory, requestHandler: GraphQLRequestHandler ) : GraphQLServer<ApplicationRequest>(requestParser, contextFactory, requestHandler)
0
Kotlin
0
0
f105ae6193fad2c7c13bbad2100c736400cd2732
453
gql-study
MIT License
CompleteAppCodelab/app/src/main/java/com/google/relay/example/reflect/ui/HomeScreen.kt
googlecodelabs
619,951,716
false
{"Kotlin": 102766}
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.relay.example.reflect.ui import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.google.relay.example.reflect.model.* import com.google.relay.example.reflect.ui.components.* @Composable fun HomeScreen( modifier: Modifier = Modifier, onEditTracker: (Tracker) -> Unit = {}, onNewTracker: () -> Unit = {} ) { val data = ReflectRepo.model var day by remember { mutableStateOf(data.today()) } val deleteTracker: (Tracker) -> Unit = { tracker -> data.removeTracker(tracker) } Box(modifier.fillMaxSize()) { Column(modifier) { DayNavigationControl( modifier = Modifier.padding(vertical = 20.dp), onPrevTapped = { day = data.getOrCreateDay(offsetDate(day.date, -1)) }, onNextTapped = { day = data.getOrCreateDay(offsetDate(day.date, +1)) }, ) day.trackerData.forEach { TrackerControl( trackerData = it, onEditTracker = onEditTracker, onDeleteTracker = deleteTracker, modifier = modifier.height(64.dp).padding(horizontal = 10.dp, vertical = 5.dp), ) } } LargeFloatingActionButton( modifier = Modifier .align(Alignment.BottomEnd) .offset((-16).dp, (-16).dp), onClick = onNewTracker ) { Icon( Icons.Filled.Add, "Add Tracker", modifier = Modifier.size(36.dp) ) } } }
0
Kotlin
7
8
89948606cf9c22deb8d2bf31b46fc46be345eee3
2,538
relay-codelabs
Apache License 2.0
app/src/main/java/com/bluerayfsm/features/location/model/ShopDurationResponse.kt
DebashisINT
772,059,684
false
{"Kotlin": 14146263, "Java": 1002625}
package com.bluerayfsm.features.location.model import com.bluerayfsm.base.BaseResponse /** * Created by Pratishruti on 28-11-2017. */ class ShopDurationResponse:BaseResponse()
0
Kotlin
0
0
875bc5a3927897d1daa465a4f122c35df513a7ec
179
BluerayFSM
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/rekognition/KinesisVideoStreamPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.rekognition import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.rekognition.CfnStreamProcessor @Generated public fun buildKinesisVideoStreamProperty(initializer: @AwsCdkDsl CfnStreamProcessor.KinesisVideoStreamProperty.Builder.() -> Unit): CfnStreamProcessor.KinesisVideoStreamProperty = CfnStreamProcessor.KinesisVideoStreamProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
451a1e42282de74a9a119a5716bd95b913662e7c
513
aws-cdk-kt
Apache License 2.0
profiledomain/src/main/java/com/nikitamaslov/profiledomain/model/Profile.kt
nikitamasloff
182,624,620
false
null
package com.nikitamaslov.profiledomain.model data class Profile( val id: Id, val initials: Initials, val description: Description, val followersAmount: Int, val subscriptionsAmount: Int, val isMe: Boolean, val relation: Relation? ) { data class Id(val src: String) data class Initials( val firstName: String, val lastName: String ) data class Description(val src: String) data class Relation( val isFollower: Boolean, val isSubscription: Boolean ) data class Header( val id: Id, val initials: Initials, val isMe: Boolean ) }
0
null
0
0
cbdd62b9eab3ae3362c6fec4f8c0d498133174c0
646
in-touch
Apache License 2.0
step5/function8.kt
shilpasayura
400,781,913
false
null
// Triple represents a triad of values fun timeConversionTriple(seconds: Int): Triple<Int,Int,Int> { val hour = seconds/3600 val minutes = (seconds % 3600) / 60 val sec = seconds % 60 return Triple(hour,minutes, sec) } fun display(myTriple: Triple<Int,Int,Int>) { println("${myTriple.first} Hour(s) ${myTriple.second} Minute(s) ${myTriple.third} Second(s)") } fun main(args: Array<String>) { val myTriple = timeConversionTriple(10512) display(myTriple) }
0
Kotlin
0
0
d0898fef7231adc9c6661ab6f75f9020696d0600
487
kotlin
MIT License
src/main/kotlin/com/github/lld4n/rocketiconsjetbrains/settings/PluginSettings.kt
lld4n
844,119,636
false
{"Kotlin": 9795, "TypeScript": 2919}
package com.github.lld4n.rocketiconsjetbrains.settings import com.intellij.ide.GeneralSettings import com.intellij.ide.IdeBundle import com.intellij.ide.projectView.ProjectView import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.Messages import javax.swing.JComponent class PluginSettings : Configurable { private val component = PluginSettingsComponent(PluginSettingsState.instance.variant, PluginSettingsState.instance.subtype) override fun createComponent(): JComponent { return component.view } private fun packChanged(): Boolean { val state = PluginSettingsState.instance return component.variantView.variant != state.variant || component.subtypeView.variant != state.subtype } override fun isModified(): Boolean { return packChanged() } override fun apply() { val state = PluginSettingsState.instance if (packChanged()) { state.variant = component.variantView.variant state.subtype = component.subtypeView.variant restart() } val projects = ProjectManager.getInstance().openProjects for (project in projects) { val projectView = ProjectView.getInstance(project) projectView?.refresh() projectView?.currentProjectViewPane?.updateFromRoot(true) } } override fun getDisplayName(): String { return "Rocket Icons" } private fun restart() { val result = if (GeneralSettings.getInstance().isConfirmExit) { Messages.showYesNoDialog( "The IDE needs to be restarted for the changes to take effect. Restart now?", IdeBundle.message("dialog.title.restart.ide"), IdeBundle.message("dialog.action.restart.yes"), IdeBundle.message("dialog.action.restart.cancel"), Messages.getWarningIcon() ) == Messages.YES } else { true } if (result) { val app = ApplicationManager.getApplication() as ApplicationEx app.restart(true) } } }
3
Kotlin
0
0
673b43d7565b07f9163e56ece8d4e34d229325a8
2,339
rocket-icons-jetbrains
MIT License
src/main/kotlin/com/atlassian/performance/tools/virtualusers/api/browsers/Browser.kt
atlassian
172,478,035
false
{"Gradle Kotlin DSL": 2, "CODEOWNERS": 1, "Markdown": 4, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Text": 1, "XML": 1, "Dockerfile": 1, "Kotlin": 80, "Java": 1, "YAML": 1}
package com.atlassian.performance.tools.virtualusers.api.browsers @Deprecated("Include your browser/WebDriver logic in your LoadProcess") interface Browser { fun start(): CloseableRemoteWebDriver }
1
null
1
1
c1e8d65595c1482bd9b51a5fb980a30d5a4b3f60
203
virtual-users
Apache License 2.0
packages/expo-modules-core/android/src/androidTest/java/expo/modules/kotlin/jni/SharedObjectTest.kt
expo
65,750,241
false
{"Gemfile.lock": 1, "YAML": 79, "Git Config": 1, "JSON with Comments": 175, "Ignore List": 236, "JSON": 713, "Markdown": 291, "JavaScript": 1979, "Text": 62, "Git Attributes": 7, "Shell": 66, "Ruby": 99, "TSX": 976, "Gradle": 106, "Java Properties": 5, "Batchfile": 4, "INI": 8, "Proguard": 10, "XML": 273, "Kotlin": 1210, "Dotenv": 7, "OpenStep Property List": 30, "Objective-C": 586, "Objective-C++": 49, "Jest Snapshot": 52, "CODEOWNERS": 1, "SVG": 57, "Java": 282, "Swift": 733, "CMake": 5, "C++": 109, "C": 7, "Gradle Kotlin DSL": 3, "JSON5": 1, "HTML": 5, "MATLAB": 1, "Checksums": 6, "Diff": 46, "MDX": 748, "robots.txt": 1, "CSS": 4, "Cloud Firestore Security Rules": 1, "GraphQL": 17, "TOML": 1}
@file:OptIn(ExperimentalCoroutinesApi::class) package expo.modules.kotlin.jni import com.google.common.truth.Truth import expo.modules.kotlin.sharedobjects.SharedObject import expo.modules.kotlin.sharedobjects.SharedObjectId import expo.modules.kotlin.sharedobjects.sharedObjectIdPropertyName import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Test class SharedObjectTest { @Test fun shared_object_class_should_exists() = withJSIInterop { val sharedObjectClass = evaluateScript("expo.SharedObject") Truth.assertThat(sharedObjectClass.isFunction()).isTrue() } @Test fun has_release_function_in_prototype() = withJSIInterop { val releaseFunction = evaluateScript("expo.SharedObject.prototype.release") Truth.assertThat(releaseFunction.isFunction()).isTrue() } @Test fun can_be_created() = withJSIInterop { val sharedObjectInstance = evaluateScript("new expo.SharedObject()") Truth.assertThat(sharedObjectInstance.isObject()).isTrue() } @Test fun inherits_from_EventEmitter() = withJSIInterop { val inheritsFromEventEmitter = evaluateScript("new expo.SharedObject() instanceof expo.EventEmitter") Truth.assertThat(inheritsFromEventEmitter.getBool()).isTrue() } @Test fun has_base_class_prototype() = withExampleSharedClass { val hasBaseClassPrototype = evaluateScript( "$moduleRef.SharedObjectExampleClass.prototype instanceof expo.SharedObject" ).getBool() Truth.assertThat(hasBaseClassPrototype).isTrue() } @Test fun can_creates_new_instance() = withExampleSharedClass { val sharedObject = callClass("SharedObjectExampleClass") Truth.assertThat(sharedObject.isObject()).isTrue() } @Test fun should_register() = withExampleSharedClass { val sharedObject = callClass("SharedObjectExampleClass") val sharedObjectId = sharedObject.getObject().getProperty(sharedObjectIdPropertyName).getInt() val containSharedObject = jsiInterop .appContextHolder .get() ?.sharedObjectRegistry ?.pairs ?.contains(SharedObjectId(sharedObjectId)) Truth.assertThat(containSharedObject).isTrue() } @Test fun is_instance_of() = withExampleSharedClass { val isInstanceOf = evaluateScript( "sharedObject = new $moduleRef.SharedObjectExampleClass()", "sharedObject instanceof expo.SharedObject" ).getBool() Truth.assertThat(isInstanceOf).isTrue() } @Test fun has_functions_from_base_class() = withExampleSharedClass { val releaseFunction = evaluateScript( "sharedObject = new $moduleRef.SharedObjectExampleClass()", "sharedObject.release" ) Truth.assertThat(releaseFunction.isFunction()).isTrue() } @Test fun sends_events() = withExampleSharedClass { val jsObject = evaluateScript( "sharedObject = new $moduleRef.SharedObjectExampleClass()" ).getObject() // Add a listener that adds three arguments evaluateScript( "total = 0", "sharedObject.addListener('test event', (a, b, c) => { total = a + b + c })" ) // Get the native instance val nativeObject = jsiInterop .appContextHolder .get() ?.sharedObjectRegistry ?.toNativeObject(jsObject) // Send an event from the native object to JS nativeObject?.sendEvent("test event", 1, 2, 3) // Check the value that is set by the listener val total = evaluateScript("total") Truth.assertThat(total.isNumber()).isTrue() Truth.assertThat(total.getInt()).isEqualTo(6) } private class SharedObjectExampleClass : SharedObject() private fun withExampleSharedClass( block: SingleTestContext.() -> Unit ) = withSingleModule({ Class(SharedObjectExampleClass::class) { Constructor { SharedObjectExampleClass() } } }, block) }
668
TypeScript
5226
32,824
e62f80228dece98d5afaa4f5c5e4fb195f3daa15
3,810
expo
Apache License 2.0
oura-library/src/main/kotlin/org/radarbase/oura/route/OuraSessionRoute.kt
RADAR-base
142,870,498
false
{"Gradle Kotlin DSL": 6, "YAML": 7, "Dotenv": 1, "Ignore List": 3, "INI": 2, "Shell": 3, "Text": 2, "Batchfile": 1, "EditorConfig": 1, "Markdown": 2, "Java": 85, "XML": 1, "Dockerfile": 2, "Kotlin": 60, "Gradle": 1, "Python": 1}
package org.radarbase.oura.route import org.radarbase.oura.converter.OuraSessionConverter import org.radarbase.oura.converter.OuraSessionHeartRateConverter import org.radarbase.oura.converter.OuraSessionHrvConverter import org.radarbase.oura.converter.OuraSessionMotionCountConverter import org.radarbase.oura.user.UserRepository class OuraSessionRoute( private val userRepository: UserRepository, ) : OuraRoute(userRepository) { override fun subPath(): String = "session" override fun toString(): String = "oura_session" override var converters = listOf( OuraSessionConverter(), OuraSessionMotionCountConverter(), OuraSessionHrvConverter(), OuraSessionHeartRateConverter(), ) }
17
Java
4
4
361ae2bf1d2d71eb74d4c96e6ff71de1ee56ea67
736
RADAR-REST-Connector
Apache License 2.0
app/src/main/java/com/devicewifitracker/android/ui/notifications/NotificationsFragment.kt
wanghoa
542,192,628
false
{"Java": 434396, "Kotlin": 221472}
package com.devicewifitracker.android.ui.notifications import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.blankj.utilcode.util.BarUtils import com.blankj.utilcode.util.ConvertUtils import com.blankj.utilcode.util.LogUtils import com.devicewifitracker.android.databinding.FragmentNotificationsBinding import com.devicewifitracker.android.ui.guide.guide.GuideSafetyLiveActivity import com.devicewifitracker.android.ui.guide.guide.GuideSafetyPlaceActivity import com.devicewifitracker.android.ui.guide.guide.GuideStrategyOutActivity class NotificationsFragment : Fragment() { private var _binding: FragmentNotificationsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val notificationsViewModel = ViewModelProvider(this).get(NotificationsViewModel::class.java) _binding = FragmentNotificationsBinding.inflate(inflater, container, false) val root: View = binding.root val barHeight = BarUtils.getStatusBarHeight()//获取状态栏高度 // binding?.parentView?.setPadding(0, ConvertUtils.dp2px(55.toFloat()) - barHeight, 0, 0) // val textView: TextView = binding.textNotifications // notificationsViewModel.text.observe(viewLifecycleOwner) { // textView.text = it // } initListener() return root } fun initListener() { binding.safetyFirstParent.setOnClickListener{ GuideSafetyLiveActivity.actionOpenAct(context) } binding.safetySenondParent.setOnClickListener{ GuideSafetyPlaceActivity.actionOpenAct(context) } binding.safetyThirdarent.setOnClickListener{ GuideStrategyOutActivity.actionOpenAct(context) } } override fun getUserVisibleHint(): Boolean { return super.getUserVisibleHint() } override fun onResume() { super.onResume() } override fun onStop() { super.onStop() } override fun onAttach(context: Context) { super.onAttach(context) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
1
null
1
1
028916627beb4ea1827fa497433741749268ef25
2,563
DeviceScanner
Apache License 2.0
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/CatalogsFeedValidationWarningsTest.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.openapitools.client.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import org.openapitools.client.models.CatalogsFeedValidationWarnings class CatalogsFeedValidationWarningsTest : ShouldSpec() { init { // uncomment below to create an instance of CatalogsFeedValidationWarnings //val modelInstance = CatalogsFeedValidationWarnings() // to test the property `AD_LINK_FORMAT_WARNING` - Some items have ad links that are formatted incorrectly. should("test AD_LINK_FORMAT_WARNING") { // uncomment below to test the property //modelInstance.AD_LINK_FORMAT_WARNING shouldBe ("TODO") } // to test the property `AD_LINK_SAME_AS_LINK` - Some items have ad link URLs that are duplicates of the link URLs for those items. should("test AD_LINK_SAME_AS_LINK") { // uncomment below to test the property //modelInstance.AD_LINK_SAME_AS_LINK shouldBe ("TODO") } // to test the property `TITLE_LENGTH_TOO_LONG` - The title for some items were truncated because they contain too many characters. should("test TITLE_LENGTH_TOO_LONG") { // uncomment below to test the property //modelInstance.TITLE_LENGTH_TOO_LONG shouldBe ("TODO") } // to test the property `DESCRIPTION_LENGTH_TOO_LONG` - The description for some items were truncated because they contain too many characters. should("test DESCRIPTION_LENGTH_TOO_LONG") { // uncomment below to test the property //modelInstance.DESCRIPTION_LENGTH_TOO_LONG shouldBe ("TODO") } // to test the property `GENDER_INVALID` - Some items have gender values that are formatted incorrectly, which may limit visibility in recommendations, search results and shopping experiences. should("test GENDER_INVALID") { // uncomment below to test the property //modelInstance.GENDER_INVALID shouldBe ("TODO") } // to test the property `AGE_GROUP_INVALID` - Some items have age group values that are formatted incorrectly, which may limit visibility in recommendations, search results and shopping experiences. should("test AGE_GROUP_INVALID") { // uncomment below to test the property //modelInstance.AGE_GROUP_INVALID shouldBe ("TODO") } // to test the property `SIZE_TYPE_INVALID` - Some items have size type values that are formatted incorrectly, which may limit visibility in recommendations, search results and shopping experiences. should("test SIZE_TYPE_INVALID") { // uncomment below to test the property //modelInstance.SIZE_TYPE_INVALID shouldBe ("TODO") } // to test the property `SIZE_SYSTEM_INVALID` - Some items have size system values which are not one of the supported size systems. should("test SIZE_SYSTEM_INVALID") { // uncomment below to test the property //modelInstance.SIZE_SYSTEM_INVALID shouldBe ("TODO") } // to test the property `LINK_FORMAT_WARNING` - Some items have an invalid product link which contains invalid UTM tracking paramaters. should("test LINK_FORMAT_WARNING") { // uncomment below to test the property //modelInstance.LINK_FORMAT_WARNING shouldBe ("TODO") } // to test the property `SALES_PRICE_INVALID` - Some items have sale price values that are higher than the original price of the item. should("test SALES_PRICE_INVALID") { // uncomment below to test the property //modelInstance.SALES_PRICE_INVALID shouldBe ("TODO") } // to test the property `PRODUCT_CATEGORY_DEPTH_WARNING` - Some items only have 1 or 2 levels of google_product_category values, which may limit visibility in recommendations, search results and shopping experiences. should("test PRODUCT_CATEGORY_DEPTH_WARNING") { // uncomment below to test the property //modelInstance.PRODUCT_CATEGORY_DEPTH_WARNING shouldBe ("TODO") } // to test the property `ADWORDS_FORMAT_WARNING` - Some items have adwords_redirect links that are formatted incorrectly. should("test ADWORDS_FORMAT_WARNING") { // uncomment below to test the property //modelInstance.ADWORDS_FORMAT_WARNING shouldBe ("TODO") } // to test the property `ADWORDS_SAME_AS_LINK` - Some items have adwords_redirect URLs that are duplicates of the link URLs for those items. should("test ADWORDS_SAME_AS_LINK") { // uncomment below to test the property //modelInstance.ADWORDS_SAME_AS_LINK shouldBe ("TODO") } // to test the property `DUPLICATE_HEADERS` - Your feed contains duplicate headers. should("test DUPLICATE_HEADERS") { // uncomment below to test the property //modelInstance.DUPLICATE_HEADERS shouldBe ("TODO") } // to test the property `FETCH_SAME_SIGNATURE` - Ingestion completed early because there are no changes to your feed since the last successful update. should("test FETCH_SAME_SIGNATURE") { // uncomment below to test the property //modelInstance.FETCH_SAME_SIGNATURE shouldBe ("TODO") } // to test the property `ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG` - Some items have additional_image_link URLs that contain too many characters, so those items will not be published. should("test ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG") { // uncomment below to test the property //modelInstance.ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG shouldBe ("TODO") } // to test the property `ADDITIONAL_IMAGE_LINK_WARNING` - Some items have additional_image_link URLs that are formatted incorrectly and will not be published with your items. should("test ADDITIONAL_IMAGE_LINK_WARNING") { // uncomment below to test the property //modelInstance.ADDITIONAL_IMAGE_LINK_WARNING shouldBe ("TODO") } // to test the property `IMAGE_LINK_WARNING` - Some items have image_link URLs that are formatted incorrectly and will not be published with those items. should("test IMAGE_LINK_WARNING") { // uncomment below to test the property //modelInstance.IMAGE_LINK_WARNING shouldBe ("TODO") } // to test the property `SHIPPING_INVALID` - Some items have shipping values that are formatted incorrectly. should("test SHIPPING_INVALID") { // uncomment below to test the property //modelInstance.SHIPPING_INVALID shouldBe ("TODO") } // to test the property `TAX_INVALID` - Some items have tax values that are formatted incorrectly. should("test TAX_INVALID") { // uncomment below to test the property //modelInstance.TAX_INVALID shouldBe ("TODO") } // to test the property `SHIPPING_WEIGHT_INVALID` - Some items have invalid shipping_weight values. should("test SHIPPING_WEIGHT_INVALID") { // uncomment below to test the property //modelInstance.SHIPPING_WEIGHT_INVALID shouldBe ("TODO") } // to test the property `EXPIRATION_DATE_INVALID` - Some items have expiration_date values that are formatted incorrectly, those items will be published without an expiration date. should("test EXPIRATION_DATE_INVALID") { // uncomment below to test the property //modelInstance.EXPIRATION_DATE_INVALID shouldBe ("TODO") } // to test the property `AVAILABILITY_DATE_INVALID` - Some items have availability_date values that are formatted incorrectly, those items will be published without an availability date. should("test AVAILABILITY_DATE_INVALID") { // uncomment below to test the property //modelInstance.AVAILABILITY_DATE_INVALID shouldBe ("TODO") } // to test the property `SALE_DATE_INVALID` - Some items have sale_price_effective_date values that are formatted incorrectly, those items will be published without a sale date. should("test SALE_DATE_INVALID") { // uncomment below to test the property //modelInstance.SALE_DATE_INVALID shouldBe ("TODO") } // to test the property `WEIGHT_UNIT_INVALID` - Some items have weight_unit values that are formatted incorrectly, those items will be published without a weight unit. should("test WEIGHT_UNIT_INVALID") { // uncomment below to test the property //modelInstance.WEIGHT_UNIT_INVALID shouldBe ("TODO") } // to test the property `IS_BUNDLE_INVALID` - Some items have is_bundle values that are formatted incorrectly, those items will be published without being bundled with other products. should("test IS_BUNDLE_INVALID") { // uncomment below to test the property //modelInstance.IS_BUNDLE_INVALID shouldBe ("TODO") } // to test the property `UPDATED_TIME_INVALID` - Some items have updated_time values thate are formatted incorrectly, those items will be published without an updated time. should("test UPDATED_TIME_INVALID") { // uncomment below to test the property //modelInstance.UPDATED_TIME_INVALID shouldBe ("TODO") } // to test the property `CUSTOM_LABEL_LENGTH_TOO_LONG` - Some items have custom_label values that are too long, those items will be published without that custom label. should("test CUSTOM_LABEL_LENGTH_TOO_LONG") { // uncomment below to test the property //modelInstance.CUSTOM_LABEL_LENGTH_TOO_LONG shouldBe ("TODO") } // to test the property `PRODUCT_TYPE_LENGTH_TOO_LONG` - Some items have product_type values that are too long, those items will be published without that product type. should("test PRODUCT_TYPE_LENGTH_TOO_LONG") { // uncomment below to test the property //modelInstance.PRODUCT_TYPE_LENGTH_TOO_LONG shouldBe ("TODO") } // to test the property `TOO_MANY_ADDITIONAL_IMAGE_LINKS` - Some items have additional_image_link values that exceed the limit for additional images, those items will be published without some of your images. should("test TOO_MANY_ADDITIONAL_IMAGE_LINKS") { // uncomment below to test the property //modelInstance.TOO_MANY_ADDITIONAL_IMAGE_LINKS shouldBe ("TODO") } // to test the property `MULTIPACK_INVALID` - Some items have invalid multipack values. should("test MULTIPACK_INVALID") { // uncomment below to test the property //modelInstance.MULTIPACK_INVALID shouldBe ("TODO") } // to test the property `INDEXED_PRODUCT_COUNT_LARGE_DELTA` - The product count has increased or decreased significantly compared to the last successful ingestion. should("test INDEXED_PRODUCT_COUNT_LARGE_DELTA") { // uncomment below to test the property //modelInstance.INDEXED_PRODUCT_COUNT_LARGE_DELTA shouldBe ("TODO") } // to test the property `ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE` - Some items include additional_image_links that can't be found. should("test ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE") { // uncomment below to test the property //modelInstance.ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE shouldBe ("TODO") } // to test the property `OPTIONAL_PRODUCT_CATEGORY_MISSING` - Some items are missing a google_product_category. should("test OPTIONAL_PRODUCT_CATEGORY_MISSING") { // uncomment below to test the property //modelInstance.OPTIONAL_PRODUCT_CATEGORY_MISSING shouldBe ("TODO") } // to test the property `OPTIONAL_PRODUCT_CATEGORY_INVALID` - Some items include google_product_category values that are not formatted correctly according to the GPC taxonomy. should("test OPTIONAL_PRODUCT_CATEGORY_INVALID") { // uncomment below to test the property //modelInstance.OPTIONAL_PRODUCT_CATEGORY_INVALID shouldBe ("TODO") } // to test the property `OPTIONAL_CONDITION_MISSING` - Some items are missing a condition value, which may limit visibility in recommendations, search results and shopping experiences. should("test OPTIONAL_CONDITION_MISSING") { // uncomment below to test the property //modelInstance.OPTIONAL_CONDITION_MISSING shouldBe ("TODO") } // to test the property `OPTIONAL_CONDITION_INVALID` - Some items include condition values that are formatted incorrectly, which may limit visibility in recommendations, search results and shopping experiences. should("test OPTIONAL_CONDITION_INVALID") { // uncomment below to test the property //modelInstance.OPTIONAL_CONDITION_INVALID shouldBe ("TODO") } // to test the property `IOS_DEEP_LINK_INVALID` - Some items include invalid ios_deep_link values. should("test IOS_DEEP_LINK_INVALID") { // uncomment below to test the property //modelInstance.IOS_DEEP_LINK_INVALID shouldBe ("TODO") } // to test the property `ANDROID_DEEP_LINK_INVALID` - Some items include invalid android_deep_link. should("test ANDROID_DEEP_LINK_INVALID") { // uncomment below to test the property //modelInstance.ANDROID_DEEP_LINK_INVALID shouldBe ("TODO") } // to test the property `UTM_SOURCE_AUTO_CORRECTED` - Some items include utm_source values that are formatted incorrectly and have been automatically corrected. should("test UTM_SOURCE_AUTO_CORRECTED") { // uncomment below to test the property //modelInstance.UTM_SOURCE_AUTO_CORRECTED shouldBe ("TODO") } // to test the property `COUNTRY_DOES_NOT_MAP_TO_CURRENCY` - Some items include a currency that doesn't match the usual currency for the location where that product is sold or shipped. should("test COUNTRY_DOES_NOT_MAP_TO_CURRENCY") { // uncomment below to test the property //modelInstance.COUNTRY_DOES_NOT_MAP_TO_CURRENCY shouldBe ("TODO") } // to test the property `MIN_AD_PRICE_INVALID` - Some items include min_ad_price values that are formatted incorrectly. should("test MIN_AD_PRICE_INVALID") { // uncomment below to test the property //modelInstance.MIN_AD_PRICE_INVALID shouldBe ("TODO") } // to test the property `GTIN_INVALID` - Some items include incorrectly formatted GTINs. should("test GTIN_INVALID") { // uncomment below to test the property //modelInstance.GTIN_INVALID shouldBe ("TODO") } // to test the property `INCONSISTENT_CURRENCY_VALUES` - Some items include inconsistent currencies in price fields. should("test INCONSISTENT_CURRENCY_VALUES") { // uncomment below to test the property //modelInstance.INCONSISTENT_CURRENCY_VALUES shouldBe ("TODO") } // to test the property `SALES_PRICE_TOO_LOW` - Some items include sales price that is much lower than the list price. should("test SALES_PRICE_TOO_LOW") { // uncomment below to test the property //modelInstance.SALES_PRICE_TOO_LOW shouldBe ("TODO") } // to test the property `SHIPPING_WIDTH_INVALID` - Some items include incorrectly formatted shipping_width. should("test SHIPPING_WIDTH_INVALID") { // uncomment below to test the property //modelInstance.SHIPPING_WIDTH_INVALID shouldBe ("TODO") } // to test the property `SHIPPING_HEIGHT_INVALID` - Some items include incorrectly formatted shipping_height. should("test SHIPPING_HEIGHT_INVALID") { // uncomment below to test the property //modelInstance.SHIPPING_HEIGHT_INVALID shouldBe ("TODO") } // to test the property `SALES_PRICE_TOO_HIGH` - Some items include a sales price that is higher than the list price. The sales price has been defaulted to the list price. should("test SALES_PRICE_TOO_HIGH") { // uncomment below to test the property //modelInstance.SALES_PRICE_TOO_HIGH shouldBe ("TODO") } // to test the property `MPN_INVALID` - Some items include incorrectly formatted MPNs. should("test MPN_INVALID") { // uncomment below to test the property //modelInstance.MPN_INVALID shouldBe ("TODO") } } }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
17,145
pinterest-sdk
MIT License
Application-Challenge/【Dooze】CircleLive/app/src/main/java/com/dong/circlelive/live/createchannel/CreateLiveChannelFragment.kt
tningjs
372,697,757
false
{"Ignore List": 48, "Markdown": 43, "Gradle": 35, "Java Properties": 14, "Shell": 11, "Batchfile": 6, "Proguard": 21, "Java": 360, "XML": 530, "INI": 15, "C": 78, "C++": 849, "CMake": 4, "HTML": 284, "PHP": 3, "CSS": 23, "JavaScript": 541, "JSON": 187, "Text": 32, "JSON with Comments": 2, "Git Attributes": 1, "YAML": 8, "Vue": 2, "SVG": 66, "SCSS": 60, "Python": 381, "Fluent": 3, "Kotlin": 565, "Dart": 31, "Ruby": 1, "OpenStep Property List": 6, "Objective-C": 29, "Swift": 1, "Gradle Kotlin DSL": 5, "Unity3D Asset": 38, "GLSL": 2, "Groovy": 1, "C#": 92, "ShaderLab": 3, "HLSL": 1, "TOML": 2, "Rust": 5, "EditorConfig": 2, "robots.txt": 2, "Handlebars": 24, "Procfile": 1, "Gettext Catalog": 1, "CoffeeScript": 12, "Cython": 9, "Objective-C++": 6, "Microsoft Visual Studio Solution": 1}
package com.dong.circlelive.live.createchannel import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.appcompat.widget.Toolbar import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import com.dong.circlelive.R import com.dong.circlelive.base.BaseFragment import com.dong.circlelive.base.viewBinding import com.dong.circlelive.databinding.FragmentCreateLiveChannelBinding import com.dong.circlelive.hideIme import com.dong.circlelive.live.LivingFragment import com.dong.circlelive.live.model.LivesViewModel import com.dong.circlelive.showOtherFragment import com.dong.circlelive.toast import com.dong.circlelive.utils.roundCorner /** * Create by dooze on 2021/5/27 6:08 下午 * Email: [email protected] * Description: */ class CreateLiveChannelFragment : BaseFragment(R.layout.fragment_create_live_channel), Toolbar.OnMenuItemClickListener { private val binding by viewBinding(FragmentCreateLiveChannelBinding::bind) private val viewModel by viewModels<CreateLiveChannelViewModel>() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.ivChannelCover.roundCorner(isCircle = true) binding.toolbar.setNavigationOnClickListener { parentFragmentManager.popBackStack() } binding.toolbar.inflateMenu(R.menu.menu_create_live_channel) binding.toolbar.setOnMenuItemClickListener(this) viewModel.publishError.observe(viewLifecycleOwner) { errorInfo -> binding.toolbar.menu.findItem(R.id.menu_tool_bar_create_live_channel).isEnabled = true toast(errorInfo ?: return@observe) } viewModel.publishedChannelId.observe(viewLifecycleOwner) { if (it.isNotEmpty()) { val vm: LivesViewModel by activityViewModels() vm.fetchLiveChannels() hideIme() parentFragmentManager.popBackStack() if (binding.cbAutoLive.isChecked) { showOtherFragment(LivingFragment.newInstance(it), R.id.top_fragment_container) } } } } override fun onMenuItemClick(item: MenuItem?): Boolean { when (item?.itemId) { R.id.menu_tool_bar_create_live_channel -> { item.isEnabled = false viewModel.publish(binding.tvChannelName.text.toString(), binding.tvChannelDesc.text.toString()) } } return true } }
1
null
1
1
2778ae967db70c492a2addb9e754e56fbd45703b
2,577
RTE-2021-Innovation-Challenge
MIT License
app/src/main/java/com/fox2code/mmm/utils/RuntimeUtils.kt
DeeShawna84
644,886,164
true
{"Java Properties": 1, "Gradle Kotlin DSL": 3, "Shell": 8, "Markdown": 7, "Batchfile": 1, "Ignore List": 2, "YAML": 6, "INI": 1, "Text": 45, "Proguard": 1, "XML": 145, "Java": 53, "Kotlin": 9}
package com.fox2code.mmm.utils import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Handler import android.os.Looper import android.provider.Settings import android.view.View import android.widget.CheckBox import android.widget.CompoundButton import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.preference.PreferenceManager import com.fox2code.foxcompat.app.FoxActivity import com.fox2code.mmm.BuildConfig import com.fox2code.mmm.MainActivity import com.fox2code.mmm.MainApplication import com.fox2code.mmm.R import com.fox2code.mmm.SetupActivity import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import timber.log.Timber @Suppress("UNUSED_PARAMETER") class RuntimeUtils { @SuppressLint("RestrictedApi") private fun ensurePermissions(context: Context, activity: MainActivity) { if (BuildConfig.DEBUG) Timber.i("Ensure Permissions") // First, check if user has said don't ask again by checking if pref_dont_ask_again_notification_permission is true if (!PreferenceManager.getDefaultSharedPreferences(context) .getBoolean("pref_dont_ask_again_notification_permission", false) ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ContextCompat.checkSelfPermission( context, Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { if (BuildConfig.DEBUG) Timber.i("Request Notification Permission") if (FoxActivity.getFoxActivity(context) .shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) ) { // Show a dialog explaining why we need context permission, which is to show // notifications for updates activity.runOnUiThread { if (BuildConfig.DEBUG) Timber.i("Show Notification Permission Dialog") val builder = MaterialAlertDialogBuilder(context) builder.setTitle(R.string.permission_notification_title) builder.setMessage(R.string.permission_notification_message) // Don't ask again checkbox val view: View = activity.layoutInflater.inflate(R.layout.dialog_checkbox, null) val checkBox = view.findViewById<CheckBox>(R.id.checkbox) checkBox.setText(R.string.dont_ask_again) checkBox.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean -> PreferenceManager.getDefaultSharedPreferences( context ).edit().putBoolean( "pref_dont_ask_again_notification_permission", isChecked ).apply() } builder.setView(view) builder.setPositiveButton(R.string.permission_notification_grant) { _, _ -> // Request the permission activity.requestPermissions( arrayOf(Manifest.permission.POST_NOTIFICATIONS), 0 ) MainActivity.doSetupNowRunning = false } builder.setNegativeButton(R.string.cancel) { dialog, _ -> // Set pref_background_update_check to false and dismiss dialog val prefs = PreferenceManager.getDefaultSharedPreferences(context) prefs.edit().putBoolean("pref_background_update_check", false).apply() dialog.dismiss() MainActivity.doSetupNowRunning = false } builder.show() if (BuildConfig.DEBUG) Timber.i("Show Notification Permission Dialog Done") } } else { // Request the permission if (BuildConfig.DEBUG) Timber.i("Request Notification Permission") activity.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 0) if (BuildConfig.DEBUG) { // Log if granted via onRequestPermissionsResult val granted = ContextCompat.checkSelfPermission( context, Manifest.permission.POST_NOTIFICATIONS ) == PackageManager.PERMISSION_GRANTED Timber.i("Request Notification Permission Done. Result: %s", granted) } MainActivity.doSetupNowRunning = false } // Next branch is for < android 13 and user has blocked notifications } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU && !NotificationManagerCompat.from( context ).areNotificationsEnabled() ) { activity.runOnUiThread { val builder = MaterialAlertDialogBuilder(context) builder.setTitle(R.string.permission_notification_title) builder.setMessage(R.string.permission_notification_message) // Don't ask again checkbox val view: View = activity.layoutInflater.inflate(R.layout.dialog_checkbox, null) val checkBox = view.findViewById<CheckBox>(R.id.checkbox) checkBox.setText(R.string.dont_ask_again) checkBox.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean -> PreferenceManager.getDefaultSharedPreferences( context ).edit() .putBoolean("pref_dont_ask_again_notification_permission", isChecked) .apply() } builder.setView(view) builder.setPositiveButton(R.string.permission_notification_grant) { _, _ -> // Open notification settings val intent = Intent() intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS val uri = Uri.fromParts("package", activity.packageName, null) intent.data = uri activity.startActivity(intent) MainActivity.doSetupNowRunning = false } builder.setNegativeButton(R.string.cancel) { dialog, _ -> // Set pref_background_update_check to false and dismiss dialog val prefs = MainApplication.getSharedPreferences("mmm") prefs.edit().putBoolean("pref_background_update_check", false).apply() dialog.dismiss() MainActivity.doSetupNowRunning = false } builder.show() } } else { MainActivity.doSetupNowRunning = false } } else { if (BuildConfig.DEBUG) Timber.i("Notification Permission Already Granted or Don't Ask Again") MainActivity.doSetupNowRunning = false } } /** * Shows setup activity if it's the first launch */ // Method to show a setup box on first launch @SuppressLint("InflateParams", "RestrictedApi", "UnspecifiedImmutableFlag", "ApplySharedPref") fun checkShowInitialSetup(context: Context, activity: MainActivity) { if (BuildConfig.DEBUG) Timber.i("Checking if we need to run setup") // Check if context is the first launch using prefs and if doSetupRestarting was passed in the intent val prefs = MainApplication.getSharedPreferences("mmm") var firstLaunch = prefs.getString("last_shown_setup", null) != "v2" // First launch // context is intentionally separate from the above if statement, because it needs to be checked even if the first launch check is true due to some weird edge cases if (activity.intent.getBooleanExtra("doSetupRestarting", false)) { // Restarting setup firstLaunch = false } if (BuildConfig.DEBUG) { Timber.i( "First launch: %s, pref value: %s", firstLaunch, prefs.getString("last_shown_setup", null) ) } if (firstLaunch) { MainActivity.doSetupNowRunning = true // Launch setup wizard if (BuildConfig.DEBUG) Timber.i("Launching setup wizard") // Show setup activity val intent = Intent(context, SetupActivity::class.java) activity.finish() activity.startActivity(intent) } else { ensurePermissions(context, activity) } } /** * @return true if the load workflow must be stopped. */ fun waitInitialSetupFinished(context: Context, activity: MainActivity): Boolean { if (BuildConfig.DEBUG) Timber.i("waitInitialSetupFinished") if (MainActivity.doSetupNowRunning) activity.updateScreenInsets() // Fix an edge case try { // Wait for doSetupNow to finish while (MainActivity.doSetupNowRunning) { Thread.sleep(50) } } catch (e: InterruptedException) { Thread.currentThread().interrupt() return true } return MainActivity.doSetupRestarting } /** * Shows a snackbar offering to take users to Weblate if their language is not available. * * @param language The language code. * @param languageName The language name. */ @SuppressLint("RestrictedApi") fun showWeblateSnackbar( context: Context, activity: MainActivity, language: String, languageName: String ) { MainActivity.isShowingWeblateSb = true // if we haven't shown context snackbar for context version yet val prefs = MainApplication.getSharedPreferences("mmm") if (prefs.getInt("weblate_snackbar_shown", 0) == BuildConfig.VERSION_CODE) return val snackbar: Snackbar = Snackbar.make( activity.findViewById(R.id.root_container), activity.getString(R.string.language_not_available, languageName), 4000 ) snackbar.setAction(R.string.ok) { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse("https://translate.nift4.org/engage/foxmmm/?language=$language") activity.startActivity(intent) } snackbar.show() // after four seconds, set isShowingWeblateSb to false Handler(Looper.getMainLooper()).postDelayed({ MainActivity.isShowingWeblateSb = false }, 4000) prefs.edit().putInt("weblate_snackbar_shown", BuildConfig.VERSION_CODE).apply() } /** * Shows a snackbar to upgrade androidacy membership. * Sure it'll be wildly popular but it's only shown for 7 seconds every 7 days. * We could y'know stick ads in the app but we're gonna play nice. * @param context * @param activity */ @SuppressLint("RestrictedApi") fun showUpgradeSnackbar(context: Context, activity: MainActivity) { Timber.i("showUpgradeSnackbar start") // if sb is already showing, wait 4 seconds and try again if (MainActivity.isShowingWeblateSb) { Handler(Looper.getMainLooper()).postDelayed({ showUpgradeSnackbar(context, activity) }, 4500) return } val prefs = MainApplication.getSharedPreferences("mmm") // if last shown < 7 days ago if (prefs.getLong("ugsns4", 0) > System.currentTimeMillis() - 604800000) return val snackbar: Snackbar = Snackbar.make( context, activity.findViewById(R.id.blur_frame), activity.getString(R.string.upgrade_snackbar), 7000 ) snackbar.setAction(R.string.upgrade_now) { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse("https://androidacy.com/membership-join/#utm_source=foxmmm&utm_medium=app&utm_campaign=upgrade_snackbar") activity.startActivity(intent) } snackbar.setAnchorView(R.id.bottom_navigation) snackbar.show() // do not show for another 7 days prefs.edit().putLong("ugsns4", System.currentTimeMillis()).apply() Timber.i("showUpgradeSnackbar done") } }
0
Java
0
0
2324d0dc4f77f8ca3d1c80d2586bfe9a81dd0aeb
13,110
MagiskModuleManager
The Unlicense
domain/src/commonMain/kotlin/domain/stats/RateMovie.kt
4face-studi0
280,630,732
false
null
package domain.stats import entities.model.UserRating import entities.movies.Movie import entities.stats.StatRepository class RateMovie( private val stats: StatRepository ) { suspend operator fun invoke(movie: Movie, rating: UserRating): Unit = stats.rate(movie, rating) }
24
Kotlin
1
3
572514b24063815fba93809a9169a470f89fd445
293
CineScout
Apache License 2.0