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/com/dokja/mizumi/presentation/reader/components/FontLoader.kt | shrimpyvongue | 761,620,637 | false | {"Kotlin": 378034} | package com.dokja.mizumi.presentation.reader.components
import android.graphics.Typeface
import androidx.compose.ui.text.font.FontFamily
class FontsLoader {
companion object {
val availableFonts = listOf(
"casual",
"cursive",
"monospace",
"sans-serif",
"sans-serif-black",
"sans-serif-condensed",
"sans-serif-condensed-light",
"sans-serif-light",
"sans-serif-medium",
"sans-serif-smallcaps",
"sans-serif-thin",
"serif",
"serif-monospace"
)
}
private val typeFaceNORMALCache = mutableMapOf<String, Typeface>()
private val typeFaceBOLDCache = mutableMapOf<String, Typeface>()
private val fontFamilyCache = mutableMapOf<String, FontFamily>()
fun getTypeFaceNORMAL(name: String) = typeFaceNORMALCache.getOrPut(name) {
Typeface.create(name, Typeface.NORMAL)
}
fun getTypeFaceBOLD(name: String) = typeFaceBOLDCache.getOrPut(name) {
Typeface.create(name, Typeface.BOLD)
}
fun getFontFamily(name: String) = fontFamilyCache.getOrPut(name) {
FontFamily(getTypeFaceNORMAL(name))
}
} | 0 | Kotlin | 1 | 1 | eabf20688848d6896430de4e271bec46fe6a0b98 | 1,218 | Mizumi | MIT License |
core/src/me/wieku/circuits/input/event/KeyDownEvent.kt | Wieku | 113,257,102 | false | null | package me.wieku.circuits.input.event
import me.wieku.circuits.world.ClassicWorld
data class KeyDownEvent(val world: ClassicWorld, val keycode: Int) | 11 | Kotlin | 1 | 21 | c18c19c75296035371cba6e4f53c8dcd6856bfd3 | 150 | LogicDraw | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/modules/camera/StickProcessor.kt | WoEN239 | 850,255,356 | false | {"Kotlin": 92236, "Java": 48138} | package org.firstinspires.ftc.teamcode.modules.camera
import android.graphics.Bitmap
import android.graphics.Canvas
import org.firstinspires.ftc.robotcore.external.function.Consumer
import org.firstinspires.ftc.robotcore.external.function.Continuation
import org.firstinspires.ftc.robotcore.external.stream.CameraStreamSource
import org.firstinspires.ftc.robotcore.internal.camera.calibration.CameraCalibration
import org.firstinspires.ftc.teamcode.utils.configs.Configs
import org.firstinspires.ftc.vision.VisionProcessor
import org.opencv.android.Utils
import org.opencv.core.Core.inRange
import org.opencv.core.Core.normalize
import org.opencv.core.Mat
import org.opencv.core.MatOfPoint
import org.opencv.core.MatOfPoint2f
import org.opencv.core.Point
import org.opencv.core.RotatedRect
import org.opencv.core.Scalar
import org.opencv.core.Size
import org.opencv.imgproc.Imgproc.CHAIN_APPROX_SIMPLE
import org.opencv.imgproc.Imgproc.COLOR_RGB2HSV
import org.opencv.imgproc.Imgproc.MORPH_ERODE
import org.opencv.imgproc.Imgproc.RETR_TREE
import org.opencv.imgproc.Imgproc.blur
import org.opencv.imgproc.Imgproc.cvtColor
import org.opencv.imgproc.Imgproc.dilate
import org.opencv.imgproc.Imgproc.erode
import org.opencv.imgproc.Imgproc.findContours
import org.opencv.imgproc.Imgproc.getStructuringElement
import org.opencv.imgproc.Imgproc.line
import org.opencv.imgproc.Imgproc.minAreaRect
import org.opencv.imgproc.Imgproc.putText
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicReference
class StickProcessor : VisionProcessor, CameraStreamSource {
private var lastFrame: AtomicReference<Bitmap> =
AtomicReference(Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565))
private val _executorService: ExecutorService =
Executors.newWorkStealingPool(Configs.CameraConfig.DETECT_THREADS_COUNT)
override fun init(width: Int, height: Int, calibration: CameraCalibration?) {
}
private val _drawFrame = Mat()
private val _hsvFrame = Mat()
override fun processFrame(frame: Mat, captureTimeNanos: Long): Any {
frame.copyTo(_drawFrame)
frame.copyTo(_hsvFrame)
blur(_hsvFrame, _hsvFrame, Size(10.0, 10.0))
cvtColor(_hsvFrame, _hsvFrame, COLOR_RGB2HSV)
val blueRects = detect(Configs.CameraConfig.BLUE_STICK_DETECT, _hsvFrame.clone())
drawRotatedRects(_drawFrame, blueRects, Scalar(0.0, 0.0, 255.0), Scalar(0.0, 255.0, 0.0))
val redRects = detect(Configs.CameraConfig.RED_STICK_DETECT, _hsvFrame.clone())
drawRotatedRects(_drawFrame, redRects, Scalar(255.0, 0.0, 0.0), Scalar(0.0, 255.0, 0.0))
val b = Bitmap.createBitmap(
_drawFrame.width(),
_drawFrame.height(),
Bitmap.Config.RGB_565
)
Utils.matToBitmap(_drawFrame, b)
lastFrame.set(b)
return frame
}
private fun detect(
parameters: Configs.CameraConfig.StickDetectConfig,
hsvFrame: Mat
): Collection<RotatedRect> {
inRange(
hsvFrame,
Scalar(parameters.H_MIN, parameters.S_MIN, parameters.V_MIN),
Scalar(parameters.H_MAX, parameters.S_MAX, parameters.V_MAX),
hsvFrame
)
erodeDilate(hsvFrame, parameters.ERODE_DILATE)
erode(
hsvFrame,
hsvFrame,
getStructuringElement(
MORPH_ERODE,
Size(parameters.PRECOMPRESSION, parameters.PRECOMPRESSION)
)
)
dilateErode(hsvFrame, parameters.DILATE_ERODE)
dilate(
hsvFrame,
hsvFrame,
getStructuringElement(
MORPH_ERODE,
Size(parameters.PRECOMPRESSION, parameters.PRECOMPRESSION)
)
)
val contours = arrayListOf<MatOfPoint>()
findContours(hsvFrame, contours, Mat(), RETR_TREE, CHAIN_APPROX_SIMPLE)
val tasks = arrayListOf<Callable<RotatedRect?>>()
for (i in contours)
tasks.add { processContour(i) }
val result = _executorService.invokeAll(tasks)
return result.mapNotNull { it.get() }
}
fun drawRotatedRects(mat: Mat, rects: Collection<RotatedRect>, rectColor: Scalar, textColor: Scalar) {
for (i in rects) {
val points = Array<Point?>(4) { null }
i.points(points)
line(mat, points[0], points[1], rectColor, 5)
line(mat, points[1], points[2], rectColor, 5)
line(mat, points[2], points[3], rectColor, 5)
line(mat, points[3], points[0], rectColor, 5)
putText(
mat,
i.angle.toInt().toString(),
i.center,
5,
2.0,
textColor
)
}
}
private fun processContour(contour: MatOfPoint): RotatedRect? {
val points = MatOfPoint2f()
points.fromArray(*contour.toArray())
val rect = minAreaRect(points)
if (rect.size.height * rect.size.width > Configs.CameraConfig.MIN_STICK_AREA)
return rect
return null
}
override fun onDrawFrame(
canvas: Canvas?,
onscreenWidth: Int,
onscreenHeight: Int,
scaleBmpPxToCanvasPx: Float,
scaleCanvasDensity: Float,
userContext: Any?
) {
}
fun erodeDilate(mat: Mat, kSize: Double) {
erode(mat, mat, getStructuringElement(MORPH_ERODE, Size(kSize, kSize)))
dilate(mat, mat, getStructuringElement(MORPH_ERODE, Size(kSize, kSize)))
}
fun dilateErode(mat: Mat, kSize: Double) {
dilate(mat, mat, getStructuringElement(MORPH_ERODE, Size(kSize, kSize)))
erode(mat, mat, getStructuringElement(MORPH_ERODE, Size(kSize, kSize)))
}
override fun getFrameBitmap(continuation: Continuation<out Consumer<Bitmap>>?) {
continuation!!.dispatch { bitmapConsumer -> bitmapConsumer.accept(lastFrame.get()) }
}
} | 1 | Kotlin | 0 | 1 | ca7b06e73585bb3a1d65ccd4f604d1d7576f2b86 | 6,071 | IntoTheDeep18742 | BSD 3-Clause Clear License |
input/core/src/commonMain/kotlin/symphony/internal/FormImpl2.kt | aSoft-Ltd | 632,021,007 | false | {"Kotlin": 221021, "HTML": 296, "JavaScript": 200} | package symphony.internal
import cinematic.MutableLive
import cinematic.mutableLiveOf
import kase.Failure
import kase.Success
import kollections.listOf
import kollections.toList
import koncurrent.FailedLater
import koncurrent.Later
import koncurrent.later.finally
import neat.Invalid
import neat.Validator
import neat.custom
import symphony.CapturingPhase
import symphony.FailurePhase
import symphony.Fields
import symphony.Form
import symphony.FormAction
import symphony.FormActions
import symphony.FormState
import symphony.Label
import symphony.SubmittingPhase
import symphony.SuccessPhase
import symphony.ValidatingPhase
import symphony.Visibility
import symphony.properties.Clearable
import symphony.properties.Resetable
@PublishedApi
internal class FormImpl2<R, O : Any, F : Fields<O>>(
private val options: FormOptions<R, O, F>
) : AbstractHideable(), Form<R, O, F>, Resetable, Clearable {
override val heading = options.heading
override val details = options.details
override val fields = options.fields
override fun submit(): Later<R> {
logger.info("Validating")
state.value = state.value.copy(phase = ValidatingPhase(fields.output))
val validity = fields.validateToErrors()
if (validity is Invalid) {
state.value = state.value.copy(phase = FailurePhase(fields.output, validity.reasons.toList()))
return FailedLater(validity.exception())
}
logger.info("Submitting")
val output = fields.output
state.value = state.value.copy(phase = SubmittingPhase(output))
return submitAction.invoke(output).finally { res ->
val phase = when (res) {
is Success -> {
logger.info("Success")
try {
this.acts.onSuccess?.invoke(res.data)
} catch (err: Throwable) {
logger.error("Post Submit failed", err)
}
SuccessPhase(output, res.data)
}
is Failure -> {
logger.error("Failed", res.cause)
try {
this.acts.onFailure?.invoke(res.cause)
} catch (err: Throwable) {
logger.error("Post Submit failed", err)
}
FailurePhase(output, listOf(res.message))
}
}
state.value = state.value.copy(phase = phase)
}
}
private val label by lazy {
"${fields::class.simpleName}"
}
override val actions by lazy {
val cancel = acts.getOrSet("Cancel") { logger.warn("Cancel action was never setup") }
val sub = acts.submitAction
FormActions(
cancel = FormAction(label = Label(cancel.name, false), handler = { exit() }),
submit = FormAction(label = Label(sub.name, false), handler = { submit() })
)
}
private val acts = options.actions
private val logger = options.logger.get(label)
private val initial = FormState<O, R>(
visibility = options.visibility,
phase = CapturingPhase
)
override val state: MutableLive<FormState<O, R>> = mutableLiveOf(initial)
private val cancelAction = acts.getOrSet("Cancel") {
logger.warn("Cancel action was never setup")
}
private val submitAction = acts.submitAction
override fun exit() {
cancelAction.asInvoker?.invoke()
fields.finish()
state.stopAll()
state.history.clear()
}
override fun setVisibility(v: Visibility) {
state.value = state.value.copy(visibility = v)
}
override fun clear() {
fields.clear()
state.value = state.value.copy(phase = CapturingPhase)
}
override fun reset() {
fields.reset()
state.value = state.value.copy(phase = CapturingPhase)
}
} | 0 | Kotlin | 0 | 0 | c0dacd0844d942b9418934965b54c88fa6284dd7 | 3,938 | symphony | MIT License |
common/common-compose/src/commonMain/kotlin/ru/alexgladkov/common/compose/tabs/BottomConfiguration.kt | AlexGladkov | 409,687,153 | false | null | package ru.alexgladkov.common.compose.tabs
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import ru.alexgladkov.odyssey.compose.navigation.bottom_bar_navigation.BottomNavConfiguration
import ru.alexgladkov.odyssey.compose.navigation.bottom_bar_navigation.BottomNavModel
class BottomConfiguration : BottomNavModel() {
override val bottomNavConfiguration: BottomNavConfiguration
@Composable
get() {
return BottomNavConfiguration(
backgroundColor = Color.White,
selectedColor = Color.DarkGray,
unselectedColor = Color.LightGray
)
}
} | 3 | Kotlin | 2 | 58 | be24a83ed944510078417936f9846f2e521a896f | 671 | Odyssey | MIT License |
vtp-pensjon-application/src/main/kotlin/no/nav/pensjon/vtp/mocks/oppgave/rest/infrastruktur/validering/IsoDateValidator.kt | navikt | 254,055,233 | false | null | package no.nav.pensjon.vtp.mocks.oppgave.rest.infrastruktur.validering
import org.springframework.util.ObjectUtils.isEmpty
import java.time.LocalDate.parse
import java.time.format.DateTimeFormatter.ISO_LOCAL_DATE
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
class IsoDateValidator : ConstraintValidator<IsoDate?, String?> {
override fun initialize(isoDate: IsoDate?) {
// JSR303
}
override fun isValid(date: String?, constraintValidatorContext: ConstraintValidatorContext): Boolean {
return when {
isEmpty(date) -> true
else ->
try {
parse(date, ISO_LOCAL_DATE)
true
} catch (e: Exception) {
false
}
}
}
}
| 14 | Kotlin | 0 | 2 | cd270b5f698c78c1eee978cd24bd788163c06a0c | 831 | vtp-pensjon | MIT License |
busanalysis/src/main/kotlin/com/uu/application/LocalAnalysisApplication.kt | SONG7 | 116,321,314 | false | null | package com.uu.application
import com.jfinal.plugin.redis.Redis
import com.uu.common.DecisionTreeClassifier
import com.uu.common.TracingPointAnalyzer
import com.uu.common.constant.Consts
import com.uu.common.kit.AMapKit
import com.uu.common.kit.CurveFitKit
import com.uu.common.kit.ToolKit
import com.uu.common.proxy.DbBase
import com.uu.common.proxy.DbSubject
import com.uu.hadoop.bean.CarPoint
import com.uu.hadoop.bean.LineDirection
import com.uu.hadoop.bean.Point
import com.uu.hadoop.bean.Station
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
/**
* Created by song27 on 2017/11/22 0022.
*/
object LocalAnalysisApplication : DbSubject {
/**
* 本地运行版本
*/
override fun onStart() {
/**
* ****************************************************************
* ****************************************************************
* 装载数据 start
*
*/
val cache = Redis.use(Consts.JEDIS_UUAPP)!!
val keys = cache.keys("station:*")
val list: List<Station> = cache.mget(*keys.toTypedArray()) as MutableList<Station>
val carPoints: ArrayList<CarPoint> = ArrayList()
val file = File(Consts.LOCAL_SOURCE_INPUT_PATH)
var point: List<String>
val format = SimpleDateFormat("YYYY-MM-DD HH:mm:ss")
var prePoint: CarPoint? = null
file.forEachLine {
point = it.split(",")
var lat = point[1].toDouble()
var lon = point[2].toDouble()
if (prePoint?.lat != lat || prePoint?.lon != lon){
val carPoint = CarPoint()
carPoint.carPlate = point[3]
carPoint.lat = point[1].toDouble()
carPoint.lon = point[2].toDouble()
carPoint.time = format.parse(point[4]).time
if (!carPoints.contains(carPoint))
carPoints.add(carPoint)
prePoint = carPoint
}
}
/**
*
* 装载数据 end
* ****************************************************************
* ****************************************************************
*/
/**
* ****************************************************************
* ****************************************************************
* 所属线路分析
* 即:车辆A,输入车辆A走过的轨迹点经过了那些站点,分析出车辆A是20路
* start
*
*/
var result = DecisionTreeClassifier.determineRoute(carPoints!!, list)
/**
*
* 所属线路分析
* end
* ****************************************************************
* ****************************************************************
*/
/**
* ****************************************************************
* ****************************************************************
* 轨迹点分析
* 即:已知车辆A是20路,根据车辆A走过的定位数据分析出20路正向反向的路径轨迹
* start
*
*/
val shuttleBusAndLineID = TreeMap<Int, Int>()
val division = TracingPointAnalyzer.division(carPoints, result!!, shuttleBusAndLineID)
var line = result.lines[LineDirection.POSITIVE]
var shuttleBuses = shuttleBusAndLineID.filter { it.value == line?.id }
val pointArrays = ArrayList<ArrayList<CarPoint>>()
division.forEach { shuttleBus, arrayList ->
if (shuttleBuses.containsKey(shuttleBus)) {
pointArrays.add(arrayList)
}
}
var locateDataSet = TracingPointAnalyzer.getTracingPointsByLocateDataSet(pointArrays, line!!)
var lats = DoubleArray(locateDataSet.size)
var lons = DoubleArray(locateDataSet.size)
locateDataSet.forEachIndexed { index, carPoint ->
lats[index] = carPoint.lat
lons[index] = carPoint.lon
}
var curvePoints = CurveFitKit.getBSplineCurvePoints(lats, lons, lats.size - 1, 5)
var firstPoint: Point? = null
var lastPoint: Point? = null
line.stations.forEachIndexed { index, station ->
var point = Point(station.lat, station.lon)
if (index == 0) firstPoint = point
if (index == line!!.stations.size - 1) lastPoint = point
TracingPointAnalyzer.insertStation(curvePoints, point)
}
println("***************************************")
println("line.id:${result!!.lines[LineDirection.POSITIVE]?.id}")
println("[")
for (curvePoint in curvePoints.subList(curvePoints.indexOf(firstPoint), curvePoints.indexOf(lastPoint))) {
val wgs84ToGcj02 = AMapKit.wgs84ToGcj02(curvePoint.lat, curvePoint.lon)
var lat = wgs84ToGcj02["lat"]!!
var lon = wgs84ToGcj02["lon"]!!
print("{\"lon\":$lon,\"lat\":$lat},")
}
println("]")
println("***************************************")
line = result.lines[LineDirection.REVERSE]
shuttleBuses = shuttleBusAndLineID.filter { it.value == line?.id }
division.forEach { shuttleBus, arrayList ->
if (shuttleBuses.containsKey(shuttleBus)) {
pointArrays.add(arrayList)
}
}
locateDataSet = TracingPointAnalyzer.getTracingPointsByLocateDataSet(pointArrays, line!!)
lats = DoubleArray(locateDataSet.size)
lons = DoubleArray(locateDataSet.size)
locateDataSet.forEachIndexed { index, carPoint ->
lats[index] = carPoint.lat
lons[index] = carPoint.lon
}
curvePoints = CurveFitKit.getBSplineCurvePoints(lats, lons, lats.size - 1, 5)
line.stations.forEachIndexed { index, station ->
var point = Point(station.lat, station.lon)
if (index == 0) firstPoint = point
if (index == line!!.stations.size - 1) lastPoint = point
TracingPointAnalyzer.insertStation(curvePoints, point)
}
println("***************************************")
println("line.id:${result!!.lines[LineDirection.REVERSE]?.id}")
println("[")
for (curvePoint in curvePoints.subList(curvePoints.indexOf(firstPoint), curvePoints.indexOf(lastPoint))) {
val wgs84ToGcj02 = AMapKit.wgs84ToGcj02(curvePoint.lat, curvePoint.lon)
var lat = wgs84ToGcj02["lat"]!!
var lon = wgs84ToGcj02["lon"]!!
print("[$lon,$lat],")
}
println("]")
println("***************************************")
/**
*
* 轨迹点分析
* end
* ****************************************************************
* ****************************************************************
*/
}
}
fun main(args: Array<String>) {
val subject = DbBase(LocalAnalysisApplication).proxy as DbSubject
subject.onStart()
} | 0 | Kotlin | 1 | 4 | 2b2ef1b12e1c2372a694286cde045a76ffcf6c7f | 6,955 | bus-analysis | Apache License 2.0 |
stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/CallContentTest.kt | GetStream | 505,572,267 | false | {"Kotlin": 2549850, "MDX": 279508, "Python": 18285, "Shell": 4455, "JavaScript": 1112, "PureBasic": 107} | /*
* Copyright (c) 2014-2023 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-video-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getstream.video.android.compose
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import app.cash.paparazzi.DeviceConfig
import app.cash.paparazzi.Paparazzi
import io.getstream.video.android.compose.base.BaseComposeTest
import io.getstream.video.android.compose.ui.components.call.activecall.CallContent
import io.getstream.video.android.compose.ui.components.call.ringing.incomingcall.IncomingCallContent
import io.getstream.video.android.compose.ui.components.call.ringing.incomingcall.IncomingCallControls
import io.getstream.video.android.compose.ui.components.call.ringing.incomingcall.IncomingCallDetails
import io.getstream.video.android.compose.ui.components.call.ringing.outgoingcall.OutgoingCallContent
import io.getstream.video.android.compose.ui.components.call.ringing.outgoingcall.OutgoingCallControls
import io.getstream.video.android.compose.ui.components.call.ringing.outgoingcall.OutgoingCallDetails
import io.getstream.video.android.mock.previewCall
import io.getstream.video.android.mock.previewMemberListState
import org.junit.Rule
import org.junit.Test
internal class CallContentTest : BaseComposeTest() {
@get:Rule
val paparazzi = Paparazzi(deviceConfig = DeviceConfig.PIXEL_4A)
override fun basePaparazzi(): Paparazzi = paparazzi
@Test
fun `snapshot IncomingCallContentDetails Video composable`() {
snapshot {
IncomingCallDetails(participants = previewMemberListState)
}
}
@Test
fun `snapshot IncomingCallContentDetails Audio composable`() {
snapshot {
IncomingCallDetails(participants = previewMemberListState)
}
}
@Test
fun `snapshot IncomingCallOptions composable`() {
snapshotWithDarkMode {
IncomingCallControls(
isVideoCall = true,
isCameraEnabled = true,
onCallAction = { },
)
}
}
@Test
fun `snapshot IncomingCallContent with one participant composable`() {
snapshot {
IncomingCallContent(
call = previewCall,
participants = previewMemberListState.takeLast(1),
isCameraEnabled = false,
onBackPressed = {},
) {}
}
}
@Test
fun `snapshot IncomingCallContent Video type with multiple participants composable`() {
snapshot {
IncomingCallContent(
call = previewCall,
participants = previewMemberListState,
isCameraEnabled = false,
onBackPressed = {},
) {}
}
}
@Test
fun `snapshot OutgoingCallDetails Video composable`() {
snapshot {
OutgoingCallDetails(participants = previewMemberListState)
}
}
@Test
fun `snapshot OutgoingCallDetails Audio composable`() {
snapshot {
OutgoingCallDetails(participants = previewMemberListState)
}
}
@Test
fun `snapshot OutgoingCallOptions composable`() {
snapshotWithDarkMode {
Column {
OutgoingCallControls(
isMicrophoneEnabled = true,
isCameraEnabled = true,
onCallAction = { },
)
OutgoingCallControls(
isMicrophoneEnabled = false,
isCameraEnabled = false,
onCallAction = { },
)
}
}
}
@Test
fun `snapshot OutgoingCallContent with one participant composable`() {
snapshot {
OutgoingCallContent(
call = previewCall,
participants = previewMemberListState.take(1),
modifier = Modifier.fillMaxSize(),
onBackPressed = {},
onCallAction = {},
)
}
}
@Test
fun `snapshot OutgoingCallContent with multiple participants composable`() {
snapshot {
OutgoingCallContent(
call = previewCall,
participants = previewMemberListState,
onBackPressed = {},
) {}
}
}
@Test
fun `snapshot CallContent with multiple participants composable`() {
snapshot {
CallContent(call = previewCall)
}
}
}
| 3 | Kotlin | 30 | 308 | 1c67906e4c01e480ab180f30b39f341675bc147e | 5,078 | stream-video-android | FSF All Permissive License |
plugin-api/src/main/kotlin/com/santaev/gradle_metrics_plugin/api/Plugin.kt | santaevpavel | 240,732,704 | false | {"Kotlin": 57817, "Shell": 101} | package com.santaev.gradle_metrics_plugin.api
import org.gradle.api.flow.FlowProviders
import org.gradle.api.flow.FlowScope
import org.gradle.build.event.BuildEventsListenerRegistry
import javax.inject.Inject
@Suppress("UnstableApiUsage")
interface Plugin {
@Inject
fun getBuildEventsListenerRegistry(): BuildEventsListenerRegistry
@Inject
fun getFlowScope(): FlowScope
@Inject
fun getFlowProviders(): FlowProviders
} | 0 | Kotlin | 0 | 2 | b7e82f5c2de470396772da39424af8ff6a029330 | 446 | gradle-metrics-plugin | Apache License 2.0 |
opendc-simulator/opendc-simulator-resources/src/main/kotlin/org/opendc/simulator/resources/consumer/SimSpeedConsumerAdapter.kt | Koen1999 | 419,678,775 | true | {"Kotlin": 1112148, "Jupyter Notebook": 275743, "JavaScript": 264579, "Shell": 133323, "Python": 101126, "Sass": 7151, "HTML": 3690, "Dockerfile": 1742} | /*
* Copyright (c) 2021 AtLarge Research
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.opendc.simulator.resources.consumer
import org.opendc.simulator.resources.SimResourceCommand
import org.opendc.simulator.resources.SimResourceConsumer
import org.opendc.simulator.resources.SimResourceContext
import org.opendc.simulator.resources.SimResourceEvent
import kotlin.math.min
/**
* Helper class to expose an observable [speed] field describing the speed of the consumer.
*/
public class SimSpeedConsumerAdapter(
private val delegate: SimResourceConsumer,
private val callback: (Double) -> Unit = {}
) : SimResourceConsumer by delegate {
/**
* The resource processing speed at this instant.
*/
public var speed: Double = 0.0
private set(value) {
if (field != value) {
callback(value)
field = value
}
}
init {
callback(0.0)
}
override fun onNext(ctx: SimResourceContext): SimResourceCommand {
return delegate.onNext(ctx)
}
override fun onEvent(ctx: SimResourceContext, event: SimResourceEvent) {
val oldSpeed = speed
delegate.onEvent(ctx, event)
when (event) {
SimResourceEvent.Run -> speed = ctx.speed
SimResourceEvent.Capacity -> {
// Check if the consumer interrupted the consumer and updated the resource consumption. If not, we might
// need to update the current speed.
if (oldSpeed == speed) {
speed = min(ctx.capacity, speed)
}
}
SimResourceEvent.Exit -> speed = 0.0
else -> {}
}
}
override fun onFailure(ctx: SimResourceContext, cause: Throwable) {
speed = 0.0
delegate.onFailure(ctx, cause)
}
override fun toString(): String = "SimSpeedConsumerAdapter[delegate=$delegate]"
}
| 0 | Kotlin | 0 | 0 | f9b43518d2d50f33077734537a477539fca9f5b7 | 2,981 | opendc | MIT License |
AcornUiJsBackend/src/com/acornui/js/gl/WebGlTextureLoader.kt | konsoletyper | 105,533,124 | false | null | /*
* Copyright 2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.js.gl
import com.acornui.action.BasicAction
import com.acornui.core.UserInfo
import com.acornui.core.assets.AssetType
import com.acornui.core.assets.AssetTypes
import com.acornui.core.assets.AssetLoader
import com.acornui.core.graphics.Texture
import com.acornui.gl.core.Gl20
import com.acornui.gl.core.GlState
/**
* An asset loader for textures (images).
* @author nbilyk
*/
class WebGlTextureLoader(
private val gl: Gl20,
private val glState: GlState
) : BasicAction(), AssetLoader<Texture> {
override val type: AssetType<Texture> = AssetTypes.TEXTURE
private var _asset: WebGlTexture? = null
override var path: String = ""
override val result: Texture
get() = _asset!!
override var estimatedBytesTotal: Int = 0
override val secondsLoaded: Float
get() = if (hasCompleted()) secondsTotal else 0f
override val secondsTotal: Float
get() = estimatedBytesTotal * UserInfo.downBpsInv
override fun onInvocation() {
val jsTexture = WebGlTexture(gl, glState)
jsTexture.onLoad = {
success()
}
jsTexture.src(path)
_asset = jsTexture
}
override fun onAborted() {
_asset?.onLoad = null
_asset = null
}
override fun onReset() {
_asset?.onLoad = null
_asset = null
}
} | 0 | Kotlin | 3 | 0 | a84b559fe1d1cad01eb9223ad9af73b4d5fb5bc8 | 1,825 | Acorn | Apache License 2.0 |
src/androidInstrumentedTest/kotlin/software/momento/kotlin/sdk/BaseAndroidTestClass.kt | momentohq | 724,323,089 | false | {"Kotlin": 265819} | package software.momento.kotlin.sdk
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.runBlocking
import org.junit.AfterClass
import org.junit.BeforeClass
import software.momento.kotlin.sdk.auth.CredentialProvider
import software.momento.kotlin.sdk.config.Configurations
import java.util.UUID
import kotlin.time.Duration.Companion.seconds
open class BaseAndroidTestClass {
companion object {
@JvmStatic
protected lateinit var credentialProvider: CredentialProvider
lateinit var cacheClient: CacheClient
lateinit var cacheName: String
@JvmStatic
@BeforeClass
fun createCacheClient() {
// Instrumented Android tests cannot access environment variables directly, so we
// pass them in as arguments to the test runner. They are defined in build.gradle.kts.
val arguments = InstrumentationRegistry.getArguments()
val apiKey = arguments.getString("TestApiKey")!!
cacheName = arguments.getString("TestCacheName")!!
credentialProvider = CredentialProvider.fromString(apiKey)
cacheClient = CacheClient(
credentialProvider = credentialProvider,
configuration = Configurations.Mobile.latest,
itemDefaultTtl = 60.seconds
)
runBlocking { cacheClient.createCache(cacheName) }
}
@JvmStatic
@AfterClass
fun destroyCacheClient() {
runBlocking { cacheClient.deleteCache(cacheName) }
cacheClient.close()
}
}
}
| 2 | Kotlin | 1 | 0 | b722c7a0037b79aecdcd2183baa8f721be167aab | 1,614 | client-sdk-kotlin | Apache License 2.0 |
app/src/main/java/org/p2p/wallet/striga/user/interactor/StrigaUserInteractor.kt | p2p-org | 306,035,988 | false | null | package org.p2p.wallet.striga.user.interactor
import kotlinx.coroutines.flow.StateFlow
import org.p2p.wallet.kyc.model.StrigaKycStatusBanner
import org.p2p.wallet.striga.StrigaUserIdProvider
import org.p2p.wallet.striga.model.StrigaDataLayerResult
import org.p2p.wallet.striga.signup.repository.StrigaSignupDataLocalRepository
import org.p2p.wallet.striga.signup.repository.model.StrigaSignupData
import org.p2p.wallet.striga.user.model.StrigaUserDetails
import org.p2p.wallet.striga.user.model.StrigaUserInitialDetails
import org.p2p.wallet.striga.user.model.StrigaUserStatusDestination
import org.p2p.wallet.striga.user.repository.StrigaUserRepository
import org.p2p.wallet.striga.user.repository.StrigaUserStatusRepository
class StrigaUserInteractor(
private val userRepository: StrigaUserRepository,
private val strigaUserIdProvider: StrigaUserIdProvider,
private val userStatusRepository: StrigaUserStatusRepository,
private val strigaSignupDataRepository: StrigaSignupDataLocalRepository
) {
suspend fun createUser(data: List<StrigaSignupData>): StrigaDataLayerResult<StrigaUserInitialDetails> {
return userRepository.createUser(data)
}
suspend fun getUserDetails(): StrigaDataLayerResult<StrigaUserDetails> {
return userRepository.getUserDetails()
}
suspend fun resendSmsForVerifyPhoneNumber(): StrigaDataLayerResult<Unit> {
return userRepository.resendSmsForVerifyPhoneNumber()
}
fun isUserCreated(): Boolean = strigaUserIdProvider.getUserId() != null
suspend fun isUserDetailsLoaded(): Boolean {
return strigaSignupDataRepository.getUserSignupData().unwrap().isEmpty()
}
fun isUserVerificationStatusLoaded(): Boolean = userStatusRepository.getUserVerificationStatus() != null
suspend fun loadAndSaveUserStatusData(): StrigaDataLayerResult<Unit> {
return userStatusRepository.loadAndSaveUserKycStatus()
}
fun getUserStatusBannerFlow(): StateFlow<StrigaKycStatusBanner?> {
return userStatusRepository.getBannerFlow()
}
/**
* Returns user destination based on user status or NONE if unable to detect (no user status)
*/
fun getUserDestination(): StrigaUserStatusDestination {
return userStatusRepository.getUserDestination()
}
}
| 8 | Kotlin | 16 | 28 | 71b282491cdafd26be1ffc412a971daaa9c06c61 | 2,296 | key-app-android | MIT License |
core/kotlinx-coroutines-core/test/guide/test/ExceptionsGuideTest.kt | cybernetics | 151,160,077 | true | {"Kotlin": 1805502, "CSS": 8215, "JavaScript": 2505, "Ruby": 1927, "HTML": 1675, "Shell": 1308, "Java": 356} | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
package kotlinx.coroutines.experimental.guide.test
import org.junit.Test
class ExceptionsGuideTest {
@Test
fun testKotlinxCoroutinesExperimentalGuideExceptions01() {
test("KotlinxCoroutinesExperimentalGuideExceptions01") { kotlinx.coroutines.experimental.guide.exceptions01.main(emptyArray()) }.verifyExceptions(
"Throwing exception from launch",
"Exception in thread \"DefaultDispatcher-worker-2 @coroutine#2\" java.lang.IndexOutOfBoundsException",
"Joined failed job",
"Throwing exception from async",
"Caught ArithmeticException"
)
}
@Test
fun testKotlinxCoroutinesExperimentalGuideExceptions02() {
test("KotlinxCoroutinesExperimentalGuideExceptions02") { kotlinx.coroutines.experimental.guide.exceptions02.main(emptyArray()) }.verifyLines(
"Caught java.lang.AssertionError"
)
}
@Test
fun testKotlinxCoroutinesExperimentalGuideExceptions03() {
test("KotlinxCoroutinesExperimentalGuideExceptions03") { kotlinx.coroutines.experimental.guide.exceptions03.main(emptyArray()) }.verifyLines(
"Cancelling child",
"Child is cancelled",
"Parent is not cancelled"
)
}
@Test
fun testKotlinxCoroutinesExperimentalGuideExceptions04() {
test("KotlinxCoroutinesExperimentalGuideExceptions04") { kotlinx.coroutines.experimental.guide.exceptions04.main(emptyArray()) }.verifyLines(
"Second child throws an exception",
"Children are cancelled, but exception is not handled until all children terminate",
"The first child finished its non cancellable block",
"Caught java.lang.ArithmeticException"
)
}
@Test
fun testKotlinxCoroutinesExperimentalGuideExceptions05() {
test("KotlinxCoroutinesExperimentalGuideExceptions05") { kotlinx.coroutines.experimental.guide.exceptions05.main(emptyArray()) }.verifyLines(
"Caught java.io.IOException with suppressed [java.lang.ArithmeticException]"
)
}
@Test
fun testKotlinxCoroutinesExperimentalGuideExceptions06() {
test("KotlinxCoroutinesExperimentalGuideExceptions06") { kotlinx.coroutines.experimental.guide.exceptions06.main(emptyArray()) }.verifyLines(
"Rethrowing CancellationException with original cause",
"Caught original java.io.IOException"
)
}
@Test
fun testKotlinxCoroutinesExperimentalGuideSupervision01() {
test("KotlinxCoroutinesExperimentalGuideSupervision01") { kotlinx.coroutines.experimental.guide.supervision01.main(emptyArray()) }.verifyLines(
"First child is failing",
"First child is cancelled: true, but second one is still active",
"Cancelling supervisor",
"Second child is cancelled because supervisor is cancelled"
)
}
@Test
fun testKotlinxCoroutinesExperimentalGuideSupervision02() {
test("KotlinxCoroutinesExperimentalGuideSupervision02") { kotlinx.coroutines.experimental.guide.supervision02.main(emptyArray()) }.verifyLines(
"Child is sleeping",
"Throwing exception from scope",
"Child is cancelled",
"Caught assertion error"
)
}
@Test
fun testKotlinxCoroutinesExperimentalGuideSupervision03() {
test("KotlinxCoroutinesExperimentalGuideSupervision03") { kotlinx.coroutines.experimental.guide.supervision03.main(emptyArray()) }.verifyLines(
"Scope is completing",
"Child throws an exception",
"Caught java.lang.AssertionError",
"Scope is completed"
)
}
}
| 0 | Kotlin | 0 | 0 | 7764e43c6fe9640615747f7830e8aae1b9bc26d2 | 3,801 | kotlinx.coroutines | Apache License 2.0 |
presentation-core/src/commonMain/kotlin/com.chrynan.video.presentation.core/Mapper.kt | chRyNaN | 174,161,260 | false | null | package com.chrynan.video.presentation.core
interface Mapper<IN, OUT> {
suspend fun map(model: IN): OUT
} | 0 | Kotlin | 0 | 8 | 63456dcfdd57dbee9ff02b2155b7e1ec5761db81 | 111 | Video | Apache License 2.0 |
famintos_mobile/android/app/src/main/kotlin/br/com/famintos_mobile/MainActivity.kt | ErictonFelicidade86 | 336,825,445 | false | {"Dart": 65074, "Swift": 404, "Kotlin": 127, "Objective-C": 38} | package br.com.famintos_mobile
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | null | 0 | 0 | 8613efbbe5f81b03824952b72f10c1ab139bbae0 | 127 | Famintos-Mobile | MIT License |
app/src/main/java/com/wegdut/wegdut/data/PageWrapper.kt | laishere | 301,439,203 | false | null | package com.wegdut.wegdut.data
data class PageWrapper<T>(
val list: List<T>,
val isLast: Boolean,
val marker: String? = null
) {
fun <R> map(mapper: (T) -> R) = PageWrapper(
list.map(mapper), isLast, marker
)
} | 0 | Kotlin | 2 | 6 | b62720ce8fbe79817b9c05e6bb1eeff09f53e804 | 239 | wegdut-android | MIT License |
src/main/kotlin/com/github/dankinsoid/appcodeassets/services/ui/extensions/RenderSection.kt | dankinsoid | 505,212,247 | false | {"Kotlin": 87862} | package com.github.dankinsoid.appcodeassets.services.ui
import com.github.dankinsoid.appcodeassets.models.TemplateRenderingIntent
import com.intellij.openapi.ui.ComboBox
import java.awt.Dimension
import javax.swing.Box
import javax.swing.BoxLayout
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
fun JComponent.addRenderAsSection(update: () -> Unit): ComboBox<String>? {
var comboBox: ComboBox<String>? = null
addSection("Render As") {
Box(BoxLayout.LINE_AXIS).apply {
add(
ComboBox<String>().apply {
model = DefaultComboBoxModel((listOf(null) + TemplateRenderingIntent.values()).map { it?.title() ?: "Default" }.toTypedArray())
comboBox = this
addItemListener { update() }
}
)
add(Box.Filler(Dimension(0, 0), Dimension(0, 0), Dimension(Int.MAX_VALUE, 0)))
}
}
return comboBox
} | 0 | Kotlin | 0 | 0 | 69f835a9d670fd1c7aaf1647e742db6f33f1ec96 | 962 | AppCodeAssets | Microsoft Public License |
korio/src/commonTest/kotlin/com/soywiz/korio/i18n/LanguageTest.kt | korlibs | 77,343,418 | false | null | package com.soywiz.korio.i18n
import com.soywiz.korio.util.i18n.*
import kotlin.test.*
class LanguageTest {
@Test
fun testThatLanguageCurrentDoNotThrowExceptions() {
println("Language.CURRENT: " + Language.CURRENT)
}
} | 15 | Kotlin | 33 | 349 | e9e89804f5682db0a70e58b91f469b49698dd72b | 225 | korio | MIT License |
app/src/main/java/com/example/hobbyfi/models/data/UserGeoPoint.kt | GGLozanov | 310,078,278 | false | null | package com.example.hobbyfi.models.data
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.firebase.firestore.GeoPoint
@Keep
data class UserGeoPoint(
val username: String,
val chatroomIds: List<Long>,
val eventIds: List<Long>,
val geoPoint: GeoPoint
) : Parcelable { // custom parcelable in lieu of annotation because GeoPoint can't be serialized directly
override fun describeContents(): Int = 0
override fun writeToParcel(parcel: Parcel, i: Int) {
parcel.writeString(username)
parcel.writeArray(chatroomIds.toTypedArray())
parcel.writeArray(eventIds.toTypedArray())
parcel.writeDouble(geoPoint.latitude)
parcel.writeDouble(geoPoint.longitude)
}
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<UserGeoPoint> {
override fun createFromParcel(parcel: Parcel) = UserGeoPoint(parcel)
override fun newArray(size: Int) = arrayOfNulls<UserGeoPoint>(size)
}
}
private constructor(parcel: Parcel) : this(
username = parcel.readString()!!,
chatroomIds = parcel.readArray(Long::class.java.classLoader)!!.toList() as List<Long>,
eventIds = parcel.readArray(Long::class.java.classLoader)!!.toList() as List<Long>,
geoPoint = GeoPoint(parcel.readDouble(), parcel.readDouble())
)
} | 0 | Kotlin | 3 | 1 | afb30f72a4213c924fdf8e3cb5eefd76d6a0d320 | 1,411 | Hobbyfi | Apache License 2.0 |
app/src/main/java/com/banghuazhao/swiftcomp/Homogenization/Model/MaterialOrthotropic.kt | banghuazhao | 258,548,942 | false | {"Kotlin": 84538} | package com.banghuazhao.swiftcomp.Homogenization.Model
class MaterialOrthotropic(
var e1: Double?,
var e2: Double?,
var e3: Double?,
var g12: Double?,
var g13: Double?,
var g23: Double?,
var nu12: Double?,
var nu13: Double?,
var nu23: Double?
) {
fun isMaterialValide(): Boolean {
if ((e1 != null) &&
(e2 != null) &&
(e3 != null) &&
(g12 != null) &&
(g13 != null) &&
(g23 != null) &&
(nu12 != null) &&
(nu13 != null) &&
(nu23 != null)
) {
if ((nu12!! > -1) &&
(nu12!! < 0.5) &&
(nu13!! > -1) &&
(nu13!! < 0.5) &&
(nu23!! > -1) &&
(nu23!! < 0.5)
) {
return true
}
}
return false
}
} | 0 | Kotlin | 0 | 3 | 046ac05b2091d0346e32f9f3eace1532e5b783a8 | 889 | SwiftComp_Andriod_App | MIT License |
app/src/main/java/com/prasan/applegames/persistence/converters/EntryRightsTypeConverter.kt | Prasan-Apaya | 277,036,785 | false | null | package com.prasan.applegames.persistence.converters
import androidx.room.TypeConverter
import com.prasan.applegames.model.GameResponse
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
class EntryRightsTypeConverter {
private val moshi = Moshi.Builder().build()
@TypeConverter
fun fromString(value: String?): GameResponse.Rights? {
val adapter: JsonAdapter<GameResponse.Rights> = moshi.adapter(GameResponse.Rights::class.java)
return adapter.fromJson(value)
}
@TypeConverter
fun fromInfoType(type: GameResponse.Rights?): String? {
val adapter: JsonAdapter<GameResponse.Rights> = moshi.adapter(GameResponse.Rights::class.java)
return adapter.toJson(type)
}
} | 0 | Kotlin | 0 | 0 | 078ebe9d244c2968f4db0d167ed18d5ad23d7a32 | 742 | AppleGames | Apache License 2.0 |
service/src/test/java/be/hogent/faith/service/usecases/InitialiseUserUseCaseTest.kt | hydrolythe | 353,694,404 | false | null | package be.hogent.faith.service.usecases
import be.hogent.faith.domain.models.Backpack
import be.hogent.faith.domain.models.Cinema
import be.hogent.faith.domain.models.TreasureChest
import be.hogent.faith.domain.models.User
import be.hogent.faith.service.encryption.ContainerType
import be.hogent.faith.service.encryption.IDetailContainerEncryptionService
import be.hogent.faith.service.repositories.IAuthManager
import be.hogent.faith.service.repositories.IDetailContainerRepository
import be.hogent.faith.service.repositories.IUserRepository
import be.hogent.faith.service.usecases.user.InitialiseUserUseCase
import be.hogent.faith.util.factory.UserFactory
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class InitialiseUserUseCaseTest {
private lateinit var userUseCase: InitialiseUserUseCase
private lateinit var scheduler: Scheduler
private val userRepository: IUserRepository = mockk()
private val authManager: IAuthManager = mockk()
private val backpackRepository: IDetailContainerRepository<Backpack> = mockk()
private val cinemaRepository: IDetailContainerRepository<Cinema> = mockk()
private val treasureChestRepository: IDetailContainerRepository<TreasureChest> = mockk()
private val backpackEncryptionService: IDetailContainerEncryptionService<Backpack> = mockk()
private val cinemaEncryptionService: IDetailContainerEncryptionService<Cinema> = mockk()
private val treasureChestEncryptionService: IDetailContainerEncryptionService<TreasureChest> = mockk()
private val user: User = UserFactory.makeUser()
@Before
fun setUp() {
every { backpackRepository.saveEncryptedContainer(any()) } returns Completable.complete()
every { backpackEncryptionService.createContainer(ContainerType.BACKPACK) } returns Single.just(
mockk()
)
every { cinemaRepository.saveEncryptedContainer(any()) } returns Completable.complete()
every { cinemaEncryptionService.createContainer(ContainerType.CINEMA) } returns Single.just(
mockk()
)
every { treasureChestRepository.saveEncryptedContainer(any()) } returns Completable.complete()
every { treasureChestEncryptionService.createContainer(ContainerType.TREASURECHEST) } returns Single.just(
mockk()
)
scheduler = mockk()
userUseCase =
InitialiseUserUseCase(
userRepository,
backpackRepository,
cinemaRepository,
treasureChestRepository,
backpackEncryptionService,
cinemaEncryptionService,
treasureChestEncryptionService,
scheduler,
Schedulers.trampoline()
)
}
@After
fun tearDown() {
clearAllMocks()
}
@Test
fun registerUserUC_nonExistingUser_Succeeds() {
// Arrange
val userArg = slot<User>()
every { userRepository.initialiseUser(capture(userArg)) } returns Completable.complete()
val params = InitialiseUserUseCase.Params(user)
// Act
val result = userUseCase.buildUseCaseObservable(params)
// Assert
result.test()
.assertNoErrors()
.assertComplete()
Assert.assertEquals(params.user.username, userArg.captured.username)
Assert.assertEquals(params.user.avatarName, userArg.captured.avatarName)
Assert.assertEquals(params.user.username, userArg.captured.username)
}
@Test
fun createUserUC_normal_userIsPassedToRepo() {
// Arrange
val userArg = slot<User>()
every { userRepository.initialiseUser(capture(userArg)) } returns Completable.complete()
every { authManager.register(any(), any()) } returns Maybe.just("uuid")
val params = InitialiseUserUseCase.Params(user)
// Act
userUseCase.buildUseCaseObservable(params)
.test()
// Assert
Assert.assertEquals(params.user.username, userArg.captured.username)
Assert.assertEquals(params.user.avatarName, userArg.captured.avatarName)
}
} | 0 | Kotlin | 0 | 0 | 14c6aec4b3c0a42bc73a7f779964d166fffeea20 | 4,489 | FAITHAndroid | The Unlicense |
app/src/main/java/com/denobaba/dencar/carsmodel.kt | dnzcany | 655,841,848 | false | null | package com.denobaba.dencar
data class carsmodel(val carname : String,val caryear: Int,val carprice:String,val carimage: Int) | 0 | Kotlin | 0 | 0 | a635119223dd8bd576e0a07870c7de3e6a49d33d | 126 | RentA-Car-Kotlin | The Unlicense |
app/src/main/java/com/example/expensetracker/EditCategoryActivity.kt | JuzDaydream | 861,736,858 | false | {"Kotlin": 312267} | package com.example.expensetracker
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.GridView
import androidx.appcompat.app.AppCompatActivity
import com.example.expensetracker.databinding.ActivityEditCategoryBinding
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class EditCategoryActivity : AppCompatActivity() {
private lateinit var binding: ActivityEditCategoryBinding
private lateinit var categoryId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditCategoryBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.iconBack.setOnClickListener { finish() }
binding.btnRemove.setOnClickListener{
showPopup()
}
// Retrieve the category ID from the intent
categoryId = intent.getStringExtra("categoryID").toString()
if (categoryId.isEmpty()) {
Log.e("DEBUGTEST", "Category ID is missing")
finish() // End activity if no valid ID is provided
return
}
// Set up listeners
binding.editImage.setOnClickListener {
showIconSelectionDialog()
}
binding.btnUpdate.setOnClickListener {
updateCategory()
}
// Fetch and populate category details
fetchCategoryDetails()
}
private fun fetchCategoryDetails() {
val categoryRef = FirebaseDatabase.getInstance("https://expensetracker-a260c-default-rtdb.asia-southeast1.firebasedatabase.app")
.getReference("Category")
.child(categoryId)
categoryRef.get().addOnSuccessListener { snapshot ->
val name = snapshot.child("name").getValue(String::class.java)
val icon = snapshot.child("icon").getValue(String::class.java)
val type = snapshot.child("type").getValue(String::class.java)
if (name != null && icon != null && type !=null) {
binding.editName.setText(name)
binding.editImage.setText(icon)
val resourceId = resources.getIdentifier(icon, "drawable", packageName)
if (resourceId != 0) {
binding.iconImage.setImageResource(resourceId)
}
when (type) {
"Expense" -> binding.radioExpense.isChecked = true
"Income" -> binding.radioIncome.isChecked = true
else -> Log.e("DEBUGTEST", "Unknown category type")
}
} else {
Log.e("DEBUGTEST", "Category details not found")
}
}.addOnFailureListener { exception ->
Log.e("DEBUGTEST", "Error fetching category details: ${exception.message}")
}
}
private fun showIconSelectionDialog() {
// Inflate the dialog layout
val dialog = Dialog(this)
dialog.setContentView(R.layout.popup_select_icon)
dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
dialog.window?.setBackgroundDrawableResource(R.drawable.shadow_bg)
val btnClose = dialog.findViewById<View>(R.id.btn_close)
btnClose.setOnClickListener {
dialog.dismiss()
}
// Set up the GridView
val gridView = dialog.findViewById<GridView>(R.id.image_grid)
val iconResIds = getDrawableIdsByPrefix(this, "icon_")
val adapter = IconAdapter(this, iconResIds)
gridView.adapter = adapter
// Set item click listener to handle icon selection
gridView.setOnItemClickListener { _, _, position, _ ->
val selectedIconResId = iconResIds[position]
// Retrieve the name of the selected icon from the resource ID
val selectedIconName = resources.getResourceEntryName(selectedIconResId)
// Update the text of editImage with the selected icon name
binding.editImage.setText(selectedIconName)
val resourceId = resources.getIdentifier(selectedIconName, "drawable", packageName)
if (resourceId != 0) {
// Set the image resource if the resource ID is valid
binding.iconImage.setImageResource(resourceId)
} else {
// Handle case where the resource ID is not found
binding.iconImage.setImageResource(R.drawable.icon_money)
}
// Dismiss the dialog
dialog.dismiss()
}
// Show the dialog
dialog.show()
}
private fun updateCategory() {
Log.d("DEBUGTEST", "updateCategory method called with ID: $categoryId")
// Retrieve category details from input fields
val name = binding.editName.text.toString()
val icon = binding.editImage.text.toString()
val selectedRadioId = binding.radioGroup.checkedRadioButtonId
val type = when (selectedRadioId) {
R.id.radio_expense -> "Expense"
R.id.radio_income -> "Income"
else -> null // Handle the case where neither is selected
}
if (name.isNotEmpty() && icon.isNotEmpty() && type !=null) {
val categoryRef = FirebaseDatabase.getInstance("https://expensetracker-a260c-default-rtdb.asia-southeast1.firebasedatabase.app")
.getReference("Category")
// Create a map of updated category details
val updatedCategory = mapOf(
"name" to name,
"icon" to icon,
"type" to type
)
// Update the category in Firebase
categoryRef.child(categoryId).updateChildren(updatedCategory).addOnCompleteListener { task ->
if (task.isSuccessful) {
// Successfully updated the category
Log.d("DEBUGTEST", "Category updated successfully")
finish() // Close the activity after successful update
} else {
// Log the error
Log.e("DEBUGTEST", "Error updating category: ${task.exception?.message}")
}
}
} else {
// Handle missing fields
binding.tvErrorMsg.setText("Please fill all required fields")
}
}
private fun removeCategory(categoryId: String) {
val categoryRef = FirebaseDatabase.getInstance("https://expensetracker-a260c-default-rtdb.asia-southeast1.firebasedatabase.app")
.getReference("Category")
.child(categoryId)
categoryRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
var indexToRemove: String? = null
for (child in snapshot.children) {
val id = child.value as? String
if (id == categoryId) {
indexToRemove = child.key
break
}
}
if (indexToRemove != null) {
// Remove the index containing transactionID
categoryRef.child(indexToRemove).removeValue()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("DEBUGTEST", "Index for transaction ID $categoryId removed from transactionList.")
} else {
Log.e("DEBUGTEST", "Failed to remove index for transaction ID $categoryId from transactionList: ${task.exception?.message}")
}
}
} else {
Log.e("DEBUGTEST", "Transaction ID $categoryId not found in transactionList.")
}
categoryRef.removeValue()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("DEBUGTEST", "Transaction $categoryId removed successfully.")
} else {
Log.e("DEBUGTEST", "Failed to remove : ${task.exception?.message}")
}
}
}
override fun onCancelled(error: DatabaseError) {
Log.e("DEBUGTEST", "Database error: ${error.message}")
}
})
}
private fun showPopup() {
val dialog = Dialog(this)
dialog.setContentView(R.layout.popup_confirmation)
dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
dialog.window?.setBackgroundDrawableResource(R.drawable.shadow_bg)
val btnCancel = dialog.findViewById<View>(R.id.btn_cancel)
val btnRemove = dialog.findViewById<View>(R.id.btn_remove)
btnCancel.setOnClickListener {
dialog.dismiss()
}
btnRemove.setOnClickListener {
removeCategory(categoryId)
finish()
}
dialog.show()
}
private fun getDrawableIdsByPrefix(context: Context, prefix: String): List<Int> {
val drawableResIds = mutableListOf<Int>()
val drawableClass = R.drawable::class.java
val fields = drawableClass.fields
for (field in fields) {
if (field.name.startsWith(prefix)) {
try {
val resId = field.getInt(null)
drawableResIds.add(resId)
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
}
return drawableResIds
}
}
| 0 | Kotlin | 0 | 0 | c4d2a42b5f1644c77a0cfe48f8963b71d9309150 | 10,004 | ExpenseTracker-With-Advanced-Security | MIT License |
tv/tv-foundation/src/main/java/androidx/tv/foundation/text/TvImeOptions.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2023 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.tv.foundation.text
import androidx.compose.ui.text.input.PlatformImeOptions
import androidx.tv.foundation.ExperimentalTvFoundationApi
/**
* Additional IME configuration options supported for TV.
*
* It is not guaranteed if IME will comply with the options provided here.
*
* @param horizontalAlignment defines the horizontal alignment [TvKeyboardAlignment] option for
* keyboard.
*/
@ExperimentalTvFoundationApi
fun PlatformImeOptions(horizontalAlignment: TvKeyboardAlignment) =
PlatformImeOptions(horizontalAlignment.option)
/**
* Adds the keyboard alignment option to the private IME configuration options.
*
* It is not guaranteed if IME will comply with the options provided here.
*
* @param horizontalAlignment defines the horizontal alignment [TvKeyboardAlignment] option for
* keyboard.
*/
@ExperimentalTvFoundationApi
fun PlatformImeOptions.keyboardAlignment(
horizontalAlignment: TvKeyboardAlignment
): PlatformImeOptions {
val privateImeOptions =
if (!privateImeOptions.isNullOrBlank()) this.privateImeOptions + "," else ""
return PlatformImeOptions(privateImeOptions + horizontalAlignment.option)
}
/**
* Represents the TV keyboard alignment options available for TextField(s).
*
* It is not guaranteed if IME will comply with the options provided here.
*/
@ExperimentalTvFoundationApi
enum class TvKeyboardAlignment(val option: String? = null) {
Left("horizontalAlignment=left"),
Right("horizontalAlignment=right"),
Center("horizontalAlignment=center"),
Fullscreen("fullWidthKeyboard")
}
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 2,200 | androidx | Apache License 2.0 |
questPresentation/src/main/java/ru/nekit/android/qls/lockScreen/mediator/LockScreenContentMediator.kt | ru-nekit-android | 126,668,350 | false | null | package ru.nekit.android.qls.lockScreen.mediator
import android.animation.Animator
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Context.WINDOW_SERVICE
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
import android.graphics.PixelFormat.TRANSLUCENT
import android.graphics.Rect
import android.os.Build
import android.util.DisplayMetrics
import android.view.Gravity.*
import android.view.View
import android.view.View.*
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.WindowManager
import android.view.WindowManager.LayoutParams
import android.view.WindowManager.LayoutParams.*
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.ViewFlipper
import com.jakewharton.rxbinding2.view.layoutChangeEvents
import io.reactivex.disposables.CompositeDisposable
import ru.nekit.android.domain.event.IEvent
import ru.nekit.android.qls.R
import ru.nekit.android.qls.R.anim.*
import ru.nekit.android.qls.R.string.clock_formatter
import ru.nekit.android.qls.R.string.quest_timer_formatter
import ru.nekit.android.qls.R.styleable.*
import ru.nekit.android.qls.domain.model.Transition.*
import ru.nekit.android.qls.domain.useCases.TransitionChoreographEvent
import ru.nekit.android.qls.domain.useCases.TransitionChoreographUseCases
import ru.nekit.android.qls.lockScreen.LockScreen
import ru.nekit.android.qls.lockScreen.mediator.IViewState.*
import ru.nekit.android.qls.lockScreen.mediator.LockScreenContentMediatorAction.*
import ru.nekit.android.qls.lockScreen.mediator.LockScreenContentMediatorEvent.ON_CONTENT_SWITCH
import ru.nekit.android.qls.lockScreen.mediator.LockScreenViewViewState.SwitchContentViewState
import ru.nekit.android.qls.lockScreen.mediator.StatusBarViewState.*
import ru.nekit.android.qls.lockScreen.mediator.StatusBarViewState.VisibleViewState
import ru.nekit.android.qls.lockScreen.mediator.common.AbstractLockScreenContentMediator
import ru.nekit.android.qls.quest.QuestContext
import ru.nekit.android.qls.quest.QuestContextEvent.QUEST_PAUSE
import ru.nekit.android.qls.quest.QuestContextEvent.QUEST_RESUME
import ru.nekit.android.qls.quest.providers.IQuestContextSupport
import ru.nekit.android.qls.window.common.QuestWindowEvent.CLOSED
import ru.nekit.android.qls.window.common.QuestWindowEvent.OPEN
import ru.nekit.android.utils.AnimationUtils.fadeAnimation
import ru.nekit.android.utils.Delay.SHORT
import ru.nekit.android.utils.ScreenHost
import ru.nekit.android.utils.ViewHolder
import ru.nekit.android.utils.responsiveClicks
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap
class LockScreenContentMediator(override var questContext: QuestContext) : IQuestContextSupport {
override var disposableMap: MutableMap<String, CompositeDisposable> = HashMap()
private lateinit var viewHolder: LockScreenContentViewHolder
private var statusBarViewHolder: StatusBarViewHolder
private val windowManager: WindowManager = questContext.getSystemService(WINDOW_SERVICE) as WindowManager
private val contentMediatorStack: Array<AbstractLockScreenContentMediator?> = arrayOf(null, null)
private val animatorListenerOnClose = object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {
render(FadeOutViewState)
}
override fun onAnimationEnd(animation: Animator) {
animation.removeAllListeners()
LockScreen.getInstance().hide()
}
override fun onAnimationCancel(animation: Animator) {
animation.removeAllListeners()
}
override fun onAnimationRepeat(animation: Animator) {}
}
private val timeTickReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
render(TimeViewState(questContext.timeProvider.getCurrentTime()))
}
}
init {
viewHolder = LockScreenContentViewHolder(questContext, windowManager,
object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {
if (animation == viewHolder.outAnimation) {
contentMediatorStack[1]?.apply {
viewHolder.contentContainer?.setLayerType(LAYER_TYPE_NONE, null)
detachView()
}
} else if (animation == viewHolder.inAnimation) {
contentMediatorStack[0]?.apply {
viewHolder.contentContainer?.setLayerType(LAYER_TYPE_NONE, null)
}
sendEvent(ON_CONTENT_SWITCH)
}
}
override fun onAnimationRepeat(animation: Animation) {}
}).apply {
autoDispose {
contentContainer.responsiveClicks {
hideKeyboard()
}
}
}
statusBarViewHolder = StatusBarViewHolder(questContext, windowManager)
questContext.registerReceiver(timeTickReceiver, IntentFilter(Intent.ACTION_TIME_TICK))
listenForEvent(LockScreenContentMediatorAction::class.java) { action ->
when (action) {
CLOSE -> closeView()
HIDE -> render(IViewState.VisibleViewState(false))
SHOW -> render(IViewState.VisibleViewState(true))
}
}
listenForQuestEvent { event ->
when (event) {
QUEST_PAUSE ->
render(FadeOutViewState)
QUEST_RESUME ->
render(FadeInViewState)
else -> {
}
}
}
listenForWindowEvent { event ->
when (event) {
OPEN ->
render(FadeOutViewState)
CLOSED ->
render(FadeInViewState)
else -> {
}
}
}
listenForEvent(TransitionChoreographEvent::class.java) { event ->
if (event == TransitionChoreographEvent.TRANSITION_CHANGED) {
if (event.currentTransition == null) {
closeView()
} else {
val currentTransition = event.currentTransition
val previousTransition = event.previousTransition
val questTransition = currentTransition == QUEST
if (previousTransition == null || !questTransition ||
currentTransition != previousTransition) {
val useAnimation = previousTransition != null || questTransition
contentMediatorStack[1] = contentMediatorStack[0]
contentMediatorStack[1]?.apply {
deactivate()
viewHolder.contentContainer?.setLayerType(LAYER_TYPE_HARDWARE, null)
}
contentMediatorStack[0] = when (currentTransition) {
QUEST -> LockScreenQuestContentMediator(questContext)
INTRODUCTION -> IntroductionContentMediator(questContext)
ADVERT -> AdsContentMediator(questContext)
LEVEL_UP -> LevelUpContentMediator(questContext)
else -> TODO()
}
render(SwitchContentViewState(contentMediatorStack[0]!!,
useAnimation, previousTransition == null && questTransition))
}
if (questTransition) {
render(VisibleViewState(true))
}
render(if (questTransition) FadeInViewState else FadeOutViewState)
}
}
}
listenSessionTime { sessionTime, maxSessionTime ->
questStatisticsReport { report ->
var bestTime = report.bestAnswerTime
val worstTime = report.worseAnswerTime
val maxTimeDefault = Math.min(maxSessionTime, Math.max(1000 * 60, worstTime * 2))
val maxTime = if (sessionTime < maxTimeDefault) maxTimeDefault else maxSessionTime
if (bestTime == Long.MAX_VALUE) {
bestTime = 0
}
render(SessionTimeViewState(sessionTime, bestTime, worstTime, maxTime))
}
}
autoDispose {
viewHolder.view.layoutChangeEvents().subscribe {
val screenRect = ScreenHost.getScreenSize(questContext)
val isOpened = screenRect.y - it.bottom() > 200
sendEvent(SoftKeyboardVisibilityChangeEvent(isOpened))
render(LockScreenViewViewState.UpdateSizeViewState(Rect(it.left(), it.top(),
it.right(), it.bottom())))
}
}
TransitionChoreographUseCases.goStartTransition()
}
fun render(viewState: IViewState) {
when (viewState) {
DetachViewState, is IViewState.VisibleViewState, is IViewState.AttachViewState -> {
viewHolder.render(viewState)
statusBarViewHolder.render(viewState)
if (viewState == AttachViewState)
render(TimeViewState(questContext.timeProvider.getCurrentTime()))
}
is StatusBarViewState -> statusBarViewHolder.render(viewState)
is LockScreenViewViewState -> viewHolder.render(viewState)
}
}
fun attachView() {
render(AttachViewState)
}
fun deactivate() {
TransitionChoreographUseCases.destroyTransition()
render(DeactiveViewState)
contentMediatorStack[0]?.deactivate()
questContext.unregisterReceiver(timeTickReceiver)
dispose()
}
fun detachView() {
render(DetachViewState)
contentMediatorStack[0]?.detachView()
}
private fun startWindowAnimation(listener: Animator.AnimatorListener?) =
render(LockScreenViewViewState.FadeOutViewState(listener))
private fun closeView() = startWindowAnimation(animatorListenerOnClose)
private class LockScreenContentViewHolder
internal constructor(private val questContext: QuestContext,
private val windowManager: WindowManager,
private val animationListener: Animation.AnimationListener) :
ViewHolder(questContext, R.layout.layout_lock_screen) {
val container: View = view.findViewById(R.id.container)
val contentContainer: ViewFlipper = view.findViewById(R.id.container_content)
val titleContainer: ViewFlipper = view.findViewById(R.id.container_title)
var outAnimation: Animation = AnimationUtils.loadAnimation(questContext, slide_horizontal_out)
var inAnimation: Animation? = null
private lateinit var lockScreenLayoutParams: LayoutParams
private val styleParameters: StyleParameters = StyleParameters(questContext)
private var lastYPosition = 0
init {
titleContainer.outAnimation = outAnimation
contentContainer.outAnimation = outAnimation
outAnimation.setAnimationListener(animationListener)
}
internal fun AbstractLockScreenContentMediator.switchToContent(useAnimation: Boolean,
useFadeAnimation: Boolean) {
val contentContainerHasChild = contentContainer.childCount != 0
val titleContainerHasChild = titleContainer.childCount != 0
inAnimation?.apply {
cancel()
setAnimationListener(null)
}
inAnimation = AnimationUtils.loadAnimation(questContext,
if (useFadeAnimation) fade_in else slide_horizontal_in).apply {
setAnimationListener(animationListener)
titleContainer.inAnimation = this
contentContainer.inAnimation = this
}
val contentViewHolder = viewHolder
val titleContent = contentViewHolder.titleContentContainer
if (titleContent != null) {
titleContainer.visibility = VISIBLE
titleContainer.addView(contentViewHolder.titleContentContainer)
} else {
titleContainer.visibility = GONE
}
val content = contentViewHolder.contentContainer
if (content != null) {
contentContainer.visibility = VISIBLE
contentContainer.addView(contentViewHolder.contentContainer)
} else {
contentContainer.visibility = GONE
}
if (useAnimation) {
view.setLayerType(LAYER_TYPE_HARDWARE, null)
contentContainer.showNext()
if (contentContainerHasChild) {
contentContainer.removeViewAt(0)
}
titleContainer.showNext()
if (titleContainerHasChild) {
titleContainer.removeViewAt(0)
}
}
}
val isViewAttached: Boolean
get() = view.parent != null
inner class StyleParameters internal constructor(context: Context) {
internal var animationDuration: Int = 0
internal var dimAmount: Float = 0F
init {
context.obtainStyledAttributes(R.style.LockScreen_Window,
LockScreenWindowStyle).apply {
dimAmount = getFloat(LockScreenWindowStyle_dimAmount, 1f)
animationDuration = getInteger(LockScreenWindowStyle_animationDuration,
0)
recycle()
}
}
}
private fun createLockScreenLayoutParams(): LayoutParams {
val isLandscape = isLandscape(windowManager)
val screenSize = ScreenHost.getScreenSize(questContext)
val statusBaHeight = if (isLandscape) 0 else StatusBarViewHolder.statusBarHeight(questContext)
val x = Math.max(screenSize.x, screenSize.y)
val y = Math.min(screenSize.x, screenSize.y)
val height = y - if (isLandscape) statusBaHeight else 0
val width = if (isLandscape)
Math.min(x, (height * y.toFloat() / x * 1.3).toInt())
else
MATCH_PARENT
return LayoutParams(
width,
MATCH_PARENT,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
TYPE_APPLICATION_OVERLAY
else {
@Suppress("DEPRECATION")
TYPE_SYSTEM_ERROR
},
FLAG_SHOW_WHEN_LOCKED
or FLAG_FULLSCREEN
or FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
or FLAG_DIM_BEHIND
or FLAG_HARDWARE_ACCELERATED,
TRANSLUCENT).apply {
softInputMode = SOFT_INPUT_ADJUST_RESIZE
screenBrightness = 1f
gravity = if (isLandscape) CENTER_HORIZONTAL else LEFT
screenOrientation = if (isLandscape)
SCREEN_ORIENTATION_LANDSCAPE
else
SCREEN_ORIENTATION_PORTRAIT
dimAmount = styleParameters.dimAmount
this.y = 0
}
}
fun render(viewState: IViewState) {
when (viewState) {
is IViewState.AttachViewState -> {
if (!isViewAttached) {
lockScreenLayoutParams = createLockScreenLayoutParams()
windowManager.addView(view, lockScreenLayoutParams)
}
}
is LockScreenViewViewState.UpdateSizeViewState -> {
val containerLayout: FrameLayout.LayoutParams = container.layoutParams as FrameLayout.LayoutParams
val statusBarHeight = StatusBarViewHolder.statusBarHeight(questContext)
val position = IntArray(2)
view.getLocationOnScreen(position)
if (lastYPosition != position[1]) {
lastYPosition = position[1]
containerLayout.setMargins(0, if (position[1] < statusBarHeight) statusBarHeight else 0, 0, 0)
container.layoutParams = containerLayout
}
val screenRect = ScreenHost.getScreenSize(questContext)
val isOpened = screenRect.y - viewState.rect.bottom > 200
titleContainer.visibility = if (isOpened) GONE else VISIBLE
titleContainer.parent.requestLayout()
}
is LockScreenViewViewState.FadeOutViewState ->
container.animate().setListener(viewState.listener).withLayer().alpha(0f).start()
is LockScreenViewViewState.SwitchContentViewState ->
viewState.apply {
lockScreenContentMediator.apply {
attachView {
switchToContent(useAnimation, useFadeAnimation)
}
}
}
is IViewState.VisibleViewState -> {
if (viewState.visibility)
lockScreenLayoutParams.apply {
width = MATCH_PARENT
flags = flags and FLAG_NOT_TOUCHABLE.inv()
}
else
lockScreenLayoutParams.apply {
width = 0
flags = flags or FLAG_NOT_TOUCHABLE
}
windowManager.updateViewLayout(view, lockScreenLayoutParams)
}
DeactiveViewState -> {
outAnimation.setAnimationListener(null)
inAnimation!!.setAnimationListener(null)
}
DetachViewState -> {
if (isViewAttached) {
titleContainer.removeAllViews()
contentContainer.removeAllViews()
windowManager.removeView(view)
}
}
}
}
}
private class StatusBarViewHolder internal constructor(private val questContext: QuestContext,
private val windowManager: WindowManager) :
ViewHolder(questContext, R.layout.layout_status_bar) {
private var sessionTimeView: TextView = view.findViewById(R.id.tv_session_time)
private var timeView: TextView = view.findViewById(R.id.tv_clock)
private var progressSessionTimeView: View = view.findViewById(R.id.progress_session_time)
private var bestTimeView: View = view.findViewById(R.id.progress_best_time)
private var worstTimeView: View = view.findViewById(R.id.progress_worst_time)
private var timerContainer: View = view.findViewById(R.id.container_timer)
private lateinit var statusBarLayoutParams: LayoutParams
companion object {
fun statusBarHeight(context: Context): Int = context.resources.getDimensionPixelSize(R.dimen.status_bar_height)
}
fun render(viewState: IViewState) {
when (viewState) {
is IViewState.AttachViewState -> {
if (!isLandscape(windowManager)) {
LayoutParams().apply {
statusBarLayoutParams = this
type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
TYPE_APPLICATION_OVERLAY
else
@Suppress("DEPRECATION")
TYPE_SYSTEM_ERROR
gravity = TOP
flags = FLAG_NOT_FOCUSABLE or
FLAG_NOT_TOUCH_MODAL or
FLAG_LAYOUT_IN_SCREEN
format = TRANSLUCENT
width = MATCH_PARENT
height = statusBarHeight(questContext)
timerContainer.visibility = INVISIBLE
windowManager.addView(view, this)
}
}
}
is StatusBarViewState.VisibleViewState -> {
timerContainer.visibility = if (viewState.value) VISIBLE else INVISIBLE
bestTimeView.scaleX = 0F
worstTimeView.scaleX = 0F
progressSessionTimeView.scaleX = 0F
updateSessionTimeView(0)
}
is StatusBarViewState.TimeViewState ->
timeView.text = SimpleDateFormat(context.getString(clock_formatter), Locale.getDefault())
.format(viewState.time)
is StatusBarViewState.SessionTimeViewState -> viewState.apply {
bestTimeView.scaleX = bestTime.toFloat() / maxTime
worstTimeView.scaleX = worstTime.toFloat() / maxTime
progressSessionTimeView.scaleX = Math.min(1f, sessionTime.toFloat() / maxTime)
updateSessionTimeView(sessionTime)
}
DetachViewState -> if (view.parent != null)
windowManager.removeView(view)
FadeInViewState ->
fadeAnimation(timerContainer, false, SHORT.get(questContext))
FadeOutViewState ->
fadeAnimation(timerContainer, true, SHORT.get(questContext))
is IViewState.VisibleViewState -> statusBarLayoutParams.apply {
if (viewState.visibility) {
width = MATCH_PARENT
flags = flags and FLAG_NOT_TOUCHABLE.inv()
} else {
width = 0
flags = flags or FLAG_NOT_TOUCHABLE
}
windowManager.updateViewLayout(view, this)
}
}
}
private fun updateSessionTimeView(sessionTime: Long) {
SimpleDateFormat(questContext.getString(quest_timer_formatter), Locale.getDefault()).apply {
sessionTimeView.text = format(sessionTime)
}
}
}
companion object {
fun isLandscape(windowManager: WindowManager): Boolean = is10InchTabletDevice(windowManager)
private fun is10InchTabletDevice(windowManager: WindowManager): Boolean {
val diagonalInches = DisplayMetrics().let {
with(it) {
windowManager.defaultDisplay.getMetrics(it)
val widthPixels = widthPixels
val heightPixels = heightPixels
val widthDpi = xdpi
val heightDpi = ydpi
val widthInches = widthPixels / widthDpi
val heightInches = heightPixels / heightDpi
Math.sqrt((widthInches * widthInches + heightInches * heightInches).toDouble())
}
}
return diagonalInches >= 9
}
}
}
sealed class StatusBarViewState : IViewState {
data class SessionTimeViewState(val sessionTime: Long,
val bestTime: Long,
val worstTime: Long,
val maxTime: Long) : StatusBarViewState()
data class TimeViewState(val time: Long) : StatusBarViewState()
data class VisibleViewState(val value: Boolean) : StatusBarViewState()
object FadeOutViewState : StatusBarViewState()
object FadeInViewState : StatusBarViewState()
}
sealed class LockScreenViewViewState : IViewState {
data class SwitchContentViewState(val lockScreenContentMediator: AbstractLockScreenContentMediator,
val useAnimation: Boolean,
val useFadeAnimation: Boolean) : LockScreenViewViewState()
data class FadeOutViewState(val listener: Animator.AnimatorListener?) : LockScreenViewViewState()
data class UpdateSizeViewState(val rect: Rect) : LockScreenViewViewState()
}
interface IViewState {
object DetachViewState : IViewState
object DeactiveViewState : IViewState
data class VisibleViewState(val visibility: Boolean) : IViewState
object AttachViewState : IViewState
}
enum class LockScreenContentMediatorEvent : IEvent {
ON_CONTENT_SWITCH;
override val eventName = "${javaClass.name}::$name"
}
data class SoftKeyboardVisibilityChangeEvent(val visibility: Boolean) : IEvent {
override val eventName: String = javaClass.name
}
enum class LockScreenContentMediatorAction : IEvent {
CLOSE,
HIDE,
SHOW;
override val eventName = "${javaClass.name}::$name"
} | 0 | Kotlin | 0 | 1 | 37a2037be2ecdbe19607b5fbb9e5f7852320a5a0 | 25,873 | QuestLockScreen | Apache License 2.0 |
src/main/kotlin/net/model/AccessToken.kt | cris-null | 350,882,080 | false | null | package net.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
import java.time.ZoneOffset
/**
* Data class that represent the response send by Reddit when you successfully
* authorize and receive an authorization token.
*
* Note that depending on whether you requested a permanent authorization, there might
* or might not be a refresh token included in the response.
*
* Note that the JSON parsing library Moshi has support for Kotlin via code-gen which allows
* nullable types to be declared in a JSON model class. This means that an error will be thrown
* if a non-nullable property is in the class but not in the JSON. However, if a nullable property
* is in the class and not in the JSON, then the value will just be set to null.
*
* This means that this single can handle both kinds of authorization response, those that contain
* a refresh token, and those that don't.
*/
@Serializable
class AccessToken(
@SerialName("access_token")
val accessToken: String,
@SerialName("token_type")
val tokenType: String,
@SerialName("expires_in")
val duration: Int,
@SerialName("refresh_token")
val refreshToken: String? = null,
val scope: String
) {
@SerialName("retrieved_at")
val retrievedAt = getCurrentTimestamp()
/** Returns how many seconds remain till this token expires */
fun getSecondsTillExpiration(): Long = getExpirationTimestamp() - getCurrentTimestamp()
/** Returns the moment when this token will expire in seconds since the epoch. */
private fun getExpirationTimestamp(): Long = retrievedAt + duration
/** Returns the current number of seconds since the epoch. */
private fun getCurrentTimestamp(): Long {
val now = LocalDateTime.now(ZoneOffset.UTC)
return now.atZone(ZoneOffset.UTC).toEpochSecond()
}
override fun toString(): String {
return "AccessToken(accessToken=$accessToken, tokenType=$tokenType, " +
"duration=$duration, refreshToken=$refreshToken, " +
"scope=$scope, retrievedAt=$retrievedAt"
}
} | 5 | Kotlin | 0 | 0 | ef11ddc13100bb0abd14261a1c731dfdeabba2dc | 2,142 | marciano | MIT License |
app/src/main/java/us/ait/weatherappsimple/ui/citylist/CityListScreen.kt | saislam10 | 639,632,555 | false | null | package us.ait.weatherappsimple.ui.citylist
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Map
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import us.ait.weatherappsimple.R
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun CityListScreen(navController: NavController, userCity: MutableState<String>) {
val cityViewModel: CityViewModel = viewModel()
var showDialog by remember { mutableStateOf(false) }
var newCity by remember { mutableStateOf("") }
Scaffold(
content = { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding),
horizontalAlignment = Alignment.CenterHorizontally
) {
if (cityViewModel.cityList.isEmpty()) {
Text(
text = stringResource(R.string.no_city_added),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
style = MaterialTheme.typography.h5
)
} else {
LazyColumn {
items(cityViewModel.cityList) { cityName ->
CityListItem(
cityName = cityName,
onDeleteClick = { cityViewModel.removeCity(cityName) },
onClick = { navController.navigate("weatherDetails/$cityName") }
)
}
}
}
}
},
floatingActionButton = {
Row(
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.End,
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
FloatingActionButton(
onClick = { navController.navigate("weatherDetails/${userCity.value}") },
// backgroundColor = Color.Blue,
content = {
Icon(
Icons.Filled.Map,
contentDescription = stringResource(R.string.map),
// tint = Color.White
)
}
)
Spacer(modifier = Modifier.width(16.dp))
FloatingActionButton(
onClick = { cityViewModel.clearCities() },
backgroundColor = Color.Red,
content = {
Icon(
Icons.Filled.Delete,
contentDescription = stringResource(R.string.delete_all)
)
}
)
Spacer(modifier = Modifier.width(16.dp))
FloatingActionButton(
onClick = { showDialog = true },
content = {
Icon(
Icons.Filled.Add,
contentDescription = stringResource(R.string.add_city)
)
}
)
}
}
)
if (showDialog) {
AlertDialog(
onDismissRequest = { showDialog = false },
title = {
Text(
text = stringResource(R.string.add_city),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
)
},
text = {
Spacer(modifier = Modifier.height(24.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp)
) {
TextField(
value = newCity,
onValueChange = { newCity = it },
label = { Text(stringResource(R.string.enter_city_name)) },
modifier = Modifier.align(Alignment.Center)
)
}
Spacer(modifier = Modifier.height(16.dp))
},
buttons = {
Column {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround
) {
Button(
onClick = { showDialog = false },
colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary)
) {
Text(text = stringResource(R.string.cancel))
}
Button(
onClick = {
cityViewModel.addCity(newCity)
newCity = ""
showDialog = false
cityViewModel.saveCityData() // Save the city data
},
colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.primary)
) {
Text(text = stringResource(R.string.add))
}
}
}
}
)
}
}
| 0 | Kotlin | 0 | 0 | 2fdcbbb124b2067047dba1830a16726d4612b3b1 | 6,257 | WeatherMate | MIT License |
presentation/src/main/kotlin/team/mobileb/opgg/ui/multifab/MultiFabState.kt | OPGG-HACKTHON | 391,351,999 | false | null | package team.mobileb.opgg.ui.multifab
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
sealed class MultiFabState {
object Collapsed : MultiFabState()
object Expaned : MultiFabState()
fun toggle() = if (this == Expaned) {
Collapsed
} else {
Expaned
}
}
@Composable
fun rememberMultiFabState() = remember { mutableStateOf<MultiFabState>(MultiFabState.Collapsed) }
| 0 | Kotlin | 1 | 23 | 7d64f477ca73c25d197ea1b9806268b499f3d2d8 | 485 | mobile-b-android | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/opmode/the auto.kt | amarcolini | 557,562,421 | false | {"Kotlin": 94873, "Java": 41907} | package org.firstinspires.ftc.teamcode.opmode
import android.content.Context
import com.acmerobotics.dashboard.config.Config
import com.amarcolini.joos.command.*
import com.amarcolini.joos.dashboard.ConfigHandler
import com.amarcolini.joos.dashboard.JoosConfig
import com.amarcolini.joos.geometry.Pose2d
import com.amarcolini.joos.util.deg
import com.qualcomm.robotcore.eventloop.opmode.*
import org.firstinspires.ftc.robotcontroller.internal.FtcOpModeRegister
import org.firstinspires.ftc.robotcore.external.Telemetry
import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName
import org.firstinspires.ftc.robotcore.internal.opmode.OpModeMeta
import org.firstinspires.ftc.robotcore.internal.opmode.OpModeMetaAndClass
import org.firstinspires.ftc.teamcode.AprilTagPipeline
import org.firstinspires.ftc.teamcode.Bot
import org.openftc.easyopencv.OpenCvCamera
import org.openftc.easyopencv.OpenCvCameraFactory
import org.openftc.easyopencv.OpenCvCameraRotation
import org.openftc.easyopencv.OpenCvInternalCamera2
@JoosConfig
@Autonomous(name = "1+5 High (Right)")
open class TheAuto(private val transform: Pose2d.() -> Pose2d = { this }) : CommandOpMode() {
private lateinit var robot: Bot
private lateinit var camera: OpenCvCamera
private lateinit var pipeline: AprilTagPipeline
private var tagId: Int = 2
companion object {
var startPose = Pose2d(-63.0, -36.0, 0.deg)
var initialScorePose = Pose2d(-14.0, -32.0, 40.deg)
var stackPose = Pose2d(-12.0, -63.0, (90).deg)
var scorePose = Pose2d(-9.0, 33.0, 40.deg)
@JvmStatic
@OpModeRegistrar
fun get(opModeManager: OpModeManager) {
opModeManager.register(OpModeMeta.Builder().run {
name = "1+5 High (Left)"
flavor = OpModeMeta.Flavor.AUTONOMOUS
source = OpModeMeta.Source.ANDROID_STUDIO
build()
}, TheAuto { Pose2d(x - 4.0, -y, -heading) })
}
}
final override fun preInit() {
robot = registerRobot(Bot())
robot.drive.initializeIMU()
robot.drive.poseEstimate = Pose2d()
val cameraMonitorViewId = hardwareMap.appContext.resources.getIdentifier(
"cameraMonitorViewId",
"id",
hardwareMap.appContext.packageName
)
camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName::class.java, "webcam"), cameraMonitorViewId)
camera.setViewportRenderer(OpenCvCamera.ViewportRenderer.GPU_ACCELERATED)
pipeline = AprilTagPipeline()
camera.setPipeline(pipeline)
camera.openCameraDeviceAsync(object : OpenCvCamera.AsyncCameraOpenListener {
override fun onOpened() {
camera.startStreaming(640, 480)
dashboard?.startCameraStream(camera, 60.0)
}
override fun onError(errorCode: Int) {}
})
schedule(Command.of {
robot.arm.servo.position = 0.0
robot.intake.open()
} wait 1.0 then robot.intake::close)
schedule(true) {
if (requiring(robot.lift) == null) telem.addData("Ready!", "")
val id = pipeline.latestDetections.getOrNull(0)?.id
telem.addData("tag id", id)
if (id != null) tagId = id
}
initLoop = true
}
final override fun preStart() {
cancelAll()
robot.drive.poseEstimate = startPose.transform()
val initialScorePose = initialScorePose.transform()
val stackPose = stackPose.transform()
val scorePose = scorePose.transform()
val parkPose = Pose2d(0.0, when (tagId) {
0 -> 24.0
42 -> -24.0
else -> 0.0
}, 0.deg) + Pose2d(-12.0, -36.0, 0.deg).transform()
robot.lift.positionControlEnabled = false
schedule(
SequentialCommand(
true,
ParallelCommand(true, robot.arm.rest(), robot.drive.followTrajectory {
forward(24.0)
splineTo(initialScorePose.vec(), initialScorePose.heading)
build()
}, robot.lift.goToPosition(1165.0)),
robot.arm.outDown() and WaitCommand(1.0),
InstantCommand(robot.intake::open) and WaitCommand(0.3),
robot.arm.rest() wait 0.5,
robot.drive.followTrajectory(initialScorePose) {
lineToSplineHeading(parkPose)
build()
} and robot.lift.goToPosition(0.0),
//TODO: pick up stack cones and score
Command.of {
Bot.poseStorage = robot.drive.poseEstimate
requestOpModeStop()
}
)
)
}
} | 0 | Kotlin | 0 | 0 | 5b6595ba7098c6d924b8a0f05812d5f225f5e21c | 4,825 | 18421-PP | BSD 3-Clause Clear License |
app/src/main/java/com/items/bim/common/ui/SwipeProgress.kt | losebai | 800,799,665 | false | {"Kotlin": 644896, "Java": 11455} | package com.items.bim.common.ui
import androidx.compose.runtime.Immutable
const val NONE = 0
const val TOP = 1 //indicator在顶部
const val BOTTOM = 2 //indicator在底部
@Immutable
data class SwipeProgress(
val location: Int = NONE,//是在顶部还是在底部
val offset: Float = 0f,//可见indicator的高度
/*@FloatRange(from = 0.0, to = 1.0)*/
val fraction: Float = 0f //0到1,0: indicator不可见 1:可见indicator的最大高度
)
| 0 | Kotlin | 0 | 0 | 86f8cb939b3671158e568638b0c8e3b82df87fa1 | 406 | B-Im | Apache License 2.0 |
app/src/main/java/com/lanier/foxcomposepractice/api/OpenApi.kt | taxeric | 398,469,729 | false | null | package com.lanier.foxcomposepractice.api
import com.lanier.foxcomposepractice.entity.DataX
import com.lanier.foxcomposepractice.entity.PokemonBaseInfoEntity
import com.lanier.foxcomposepractice.entity.PokemonDetailInfoEntity
import com.lanier.foxcomposepractice.entity.PokemonListEntity
import com.lanier.libbase.net.HttpBaseBean
import retrofit2.http.*
/**
* Author: 芒硝
* Email : [email protected]
* Date : 2021/8/17 15:20
* Desc : 接口
*/
interface OpenApi {
@FormUrlEncoded
@POST("checkVersion")
suspend fun testFunction(
@Field("lvc") versionCode: Int,
@Field("pn") pn: String,
@Field("os") os: String
): HttpBaseBean<DataX>
@GET("pokemon")
suspend fun fetchPokemonList(
@Query("limit") limit: Int = 20,
@Query("offset") offset: Int = 0
): PokemonListEntity
/**
* 该接口可获得:
* 基础亲密度
* 基础颜色
* 名字
* 蛋组
* 性别比例
* 类别
* 捕获率
*/
@GET("pokemon-species/{path}/")
suspend fun searchPokemonDetailInfo(
@Path("path") baseName_or_id: String
): PokemonDetailInfoEntity
/**
* 该接口可获得:
* id
* 用于查询的名字
* 高度
* 重量
* 属性
*/
@GET("pokemon/{path}/")
suspend fun describeInfo(
@Path("path") baseName_or_id: String
): PokemonBaseInfoEntity
} | 0 | null | 3 | 9 | 31ad9d7e2440c43d0380143ec01818c60fe8781c | 1,323 | PokeCompose | Apache License 2.0 |
libnavui-maps/src/main/java/com/mapbox/navigation/ui/maps/guidance/signboard/view/MapboxSignboardView.kt | Capotasto | 366,568,071 | true | {"Kotlin": 3040317, "Java": 72446, "Python": 11557, "Makefile": 6255, "Shell": 1686} | package com.mapbox.navigation.ui.maps.guidance.signboard.view
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.mapbox.navigation.ui.base.model.Expected
import com.mapbox.navigation.ui.maps.guidance.signboard.model.SignboardError
import com.mapbox.navigation.ui.maps.guidance.signboard.model.SignboardValue
/**
* Default Signboard View that renders a signboard view.
*/
class MapboxSignboardView : AppCompatImageView {
/**
*
* @param context Context
* @constructor
*/
constructor(context: Context) : super(context)
/**
*
* @param context Context
* @param attrs AttributeSet?
* @constructor
*/
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
/**
*
* @param context Context
* @param attrs AttributeSet?
* @param defStyleAttr Int
* @constructor
*/
constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int
) : super(context, attrs, defStyleAttr)
/**
* Invoke to render the signboard based on data or clear the view on error conditions.
*
* @param result type [Expected] which holds either the signboard or error
*/
fun render(result: Expected<SignboardValue, SignboardError>) {
when (result) {
is Expected.Success -> {
setImageBitmap(result.value.bitmap)
}
is Expected.Failure -> {
setImageBitmap(null)
}
}
}
}
| 0 | null | 0 | 0 | 2d0c2165ca78a50931d17e3683e754e61da5e54e | 1,589 | mapbox-navigation-android | MIT License |
src/main/kotlin/com/arkivanov/compose3d/draw/Canvas3D.kt | arkivanov | 357,703,190 | false | null | package com.arkivanov.compose3d.draw
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.arkivanov.compose3d.Camera
@Composable
fun Canvas3D(camera: Camera, modifier: Modifier, onDraw: Draw3DScope.() -> Unit) {
Canvas(modifier) {
Draw3DScopeImpl(
camera = camera,
drawScope = this
).onDraw()
}
}
| 1 | Kotlin | 0 | 7 | bbfe8b117b078c65fdd1b7a7505b1b5ebbda4c7d | 426 | compose-3d | MIT License |
app/app/src/main/kotlin/tech/nagual/phoenix/tools/organizer/archive/ArchiveViewModel.kt | overphoenix | 621,371,055 | false | null | package tech.nagual.phoenix.tools.organizer.archive
import dagger.hilt.android.lifecycle.HiltViewModel
import tech.nagual.phoenix.tools.organizer.data.repo.NoteRepository
import tech.nagual.phoenix.tools.organizer.preferences.PreferenceRepository
import tech.nagual.phoenix.tools.organizer.common.AbstractNotesViewModel
import javax.inject.Inject
@HiltViewModel
class ArchiveViewModel @Inject constructor(
private val noteRepository: NoteRepository,
preferenceRepository: PreferenceRepository,
) : AbstractNotesViewModel(preferenceRepository) {
override val provideNotes = noteRepository::getArchived
}
| 0 | Kotlin | 0 | 0 | 64264f261c2138d5f1932789702661917bbfae28 | 618 | phoenix-android | Apache License 2.0 |
server/src/main/kotlin/org/reckful/archive/twitter/server/dto/tweet/ReplyTweetDTO.kt | ReckfulArchive | 632,190,129 | false | null | package org.reckful.archive.twitter.server.dto.tweet
import io.swagger.v3.oas.annotations.media.Schema
import org.reckful.archive.twitter.server.dto.*
@Schema(
name = "ReplyTweet",
description = "A tweet that is part of a conversation or a thread. " +
"Contains handles that are being replied to (i.e profiles that are part of the conversation)"
)
class ReplyTweetDTO(
id: String,
twitterUrl: String,
@Schema(description = "Some information about the tweet sender. Always present.")
val profileInfo: ShortProfileInfoDTO,
@Schema(description = "Date and time at which this tweet was sent, UTC. Always present.")
val dateSent: DateTimeDTO,
@Schema(description = "Location at which this tweet was sent.")
val location: LocationDTO? = null,
@Schema(
description = "Handles of twitter profiles that have been part of this thread. " +
"Handles are without the at ('@') symbol.",
example = "\"Byron\", \"reckful\""
)
val replyToHandles: List<String>,
@Schema(description = "Text of the tweet, if any.")
val text: TextDTO? = null,
@Schema(
description = "Any media attached to the tweet, such as photos/gif/video. " +
"In a single tweet there can be: 1-3 photos OR 1 gif OR 1 video."
)
val media: List<MediaDTO> = emptyList(),
@Schema(description = "Information about the tweet this tweet is quoting.")
val quote: QuoteDTO? = null,
@Schema(description = "Reaction counters, such as likes and retweets.")
val reactions: ReactionsDTO
) : TweetDTO(id, twitterUrl) {
override fun toString(): String {
return "ReplyTweetDTO(id=$id, handle=${profileInfo.handle}, text=${text?.plain})"
}
}
| 1 | Kotlin | 0 | 0 | 118e8785c1c82afe934c17ba4be45fa03edac51b | 1,758 | twitter-server | MIT License |
app/src/main/java/com/revolgenx/anilib/staff/presenter/StaffMediaCharacterSeriesPresenter.kt | AniLibApp | 244,410,204 | false | {"Kotlin": 1593083, "Shell": 52} | package com.revolgenx.anilib.staff.presenter
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import com.otaliastudios.elements.Element
import com.otaliastudios.elements.Page
import com.revolgenx.anilib.R
import com.revolgenx.anilib.common.event.OpenMediaInfoEvent
import com.revolgenx.anilib.common.event.OpenMediaListEditorEvent
import com.revolgenx.anilib.common.presenter.BasePresenter
import com.revolgenx.anilib.databinding.StaffMediaCharacterSeriesPresenterLayoutBinding
import com.revolgenx.anilib.media.data.meta.MediaInfoMeta
import com.revolgenx.anilib.media.data.model.MediaModel
import com.revolgenx.anilib.util.loginContinue
import com.revolgenx.anilib.util.naText
class StaffMediaCharacterSeriesPresenter(context: Context) : BasePresenter<StaffMediaCharacterSeriesPresenterLayoutBinding, MediaModel>(context) {
override val elementTypes: Collection<Int> = listOf(0)
private val mediaFormatList by lazy {
context.resources.getStringArray(R.array.media_format)
}
private val mediaStatus by lazy {
context.resources.getStringArray(R.array.media_status)
}
private val statusColors by lazy {
context.resources.getStringArray(R.array.status_color)
}
override fun bindView(inflater: LayoutInflater, parent: ViewGroup?, elementType: Int): StaffMediaCharacterSeriesPresenterLayoutBinding {
return StaffMediaCharacterSeriesPresenterLayoutBinding.inflate(inflater, parent, false)
}
override fun onBind(page: Page, holder: Holder, element: Element<MediaModel>) {
super.onBind(page, holder, element)
val binding = holder.getBinding() ?: return
val item = element.data ?: return
binding.apply {
characterMediaImageView.setImageURI(item.coverImage?.image())
characterMediaTitleTv.text = item.title?.title()
characterMediaFormatTv.text =
context.getString(R.string.media_format_year_s).format(item.format?.let {
mediaFormatList[it]
}.naText(), item.seasonYear?.toString().naText())
characterMediaFormatTv.status = item.mediaListEntry?.status
characterMediaStatusTv.text = item.status?.let {
characterMediaStatusTv.color = Color.parseColor(statusColors[it])
mediaStatus[it]
}.naText()
characterMediaRatingTv.text = item.averageScore
root.setOnClickListener {
OpenMediaInfoEvent(
MediaInfoMeta(
item.id,
item.type!!,
item.title!!.romaji!!,
item.coverImage!!.image(),
item.coverImage!!.largeImage,
item.bannerImage
)
).postEvent
}
root.setOnLongClickListener {
context.loginContinue {
OpenMediaListEditorEvent(item.id).postEvent
}
true
}
}
}
} | 36 | Kotlin | 3 | 76 | b3caec5c00779c878e4cf22fb7d2034aefbeee54 | 3,139 | AniLib | Apache License 2.0 |
app/src/main/java/com/nora/cinemoapp/CinemoApplication.kt | NoraHeithur | 650,469,979 | false | null | package com.nora.cinemoapp
import android.app.Application
import com.nora.cinemoapp.di.databaseModule
import com.nora.cinemoapp.di.networkModule
import com.nora.cinemoapp.di.repositoryModule
import com.nora.cinemoapp.di.useCaseModule
import com.nora.cinemoapp.di.viewModelModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import org.koin.core.logger.Level
class CinemoApplication : Application() {
override fun onCreate() {
super.onCreate()
initKoin()
}
private fun initKoin() {
startKoin {
androidContext(this@CinemoApplication)
androidLogger(Level.ERROR)
modules(listOf(databaseModule, networkModule, repositoryModule, useCaseModule, viewModelModule))
}
}
} | 0 | Kotlin | 0 | 0 | bafdba8d8fc02fef3a1b49f28d7eda6bffb7856b | 838 | Cinemo | MIT License |
feature-assets/src/main/java/io/novafoundation/nova/feature_assets/presentation/send/TransferDirectionModel.kt | novasamatech | 415,834,480 | false | {"Kotlin": 8137060, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.feature_assets.presentation.send
import io.novafoundation.nova.feature_account_api.view.ChainChipModel
class TransferDirectionModel(
val originChip: ChainChipModel,
val originChainLabel: String,
val destinationChip: ChainChipModel?
)
| 12 | Kotlin | 6 | 9 | 618357859a4b7af95391fc0991339b78aff1be82 | 279 | nova-wallet-android | Apache License 2.0 |
app/src/main/java/com/anayaenterprises/features/NewQuotation/interfaces/SalesmanOnClick.kt | DebashisINT | 533,183,856 | false | {"Kotlin": 11224841, "Java": 960771} | package com.anayaenterprises.features.NewQuotation.interfaces
import com.anayaenterprises.features.member.model.TeamListDataModel
interface SalesmanOnClick {
fun OnClick(obj: TeamListDataModel)
} | 0 | Kotlin | 0 | 0 | 1f59ca22da8458779f9b0bc337dc553f965ec082 | 201 | AnayaEnterprises | Apache License 2.0 |
elytra-api/src/main/kotlin/io/elytra/api/utils/Updatable.kt | Elytra-Server | 249,470,188 | false | null | package io.elytra.api.utils
/**
* Marks an actor [A] as updatable
*/
interface Updatable<A> {
fun update(record: A)
}
| 15 | Kotlin | 5 | 56 | d998c0ee26c948ae1352f00158ac978145875e8e | 125 | Elytra | MIT License |
buildSrc/src/main/java/com/buildsrc/kts/Dependencies.kt | Western-parotia | 617,381,942 | false | {"Kotlin": 104968, "Java": 5599} | package com.buildsrc.kts
import org.gradle.api.JavaVersion
object Dependencies {
const val kotlinVersion = "1.7.0"
const val agp = "7.4.2"
val javaVersion = JavaVersion.VERSION_1_8
val jvmTarget = "11"
object Kotlin {
const val kotlin_stdlib = "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
}
object Foundation {
const val loading = "com.foundation.widget:loadingview:1.1.9"
const val viewBindingHelper = "com.foundation.widget:view-binding-helper:1.0.6"
const val net = "com.foundation.service:net:1.0.5"
}
object AndroidX {
const val appcompat = "androidx.appcompat:appcompat:1.2.0"
const val constraintLayout = "androidx.constraintlayout:constraintlayout:2.0.4"
}
object Material {
const val material = "com.google.android.material:material:1.3.0"
}
object Coroutines {
const val coroutines_android = "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9"
}
object Retrofit {
const val retorifit = "com.squareup.retrofit2:retrofit:2.9.0"//依赖okhttp 3.14.9
const val converter_gson = "com.squareup.retrofit2:converter-gson:2.9.0"
const val url_manager = "me.jessyan:retrofit-url-manager:1.4.0"
const val gson = "com.google.code.gson:gson:2.8.5"
}
object UI {
const val BaseRecyclerViewAdapterHelper =
"com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4"
const val glde =
"com.github.bumptech.glide:glide:4.3.1"
}
/**
* ktx 库清单与版本:https://developer.android.google.cn/kotlin/ktx?hl=zh-cn
*/
object JetPack {
const val core_ktx = "androidx.core:core-ktx:1.3.2"
const val fragment_ktx = "androidx.fragment:fragment-ktx:1.3.3"
/*Lifecycle 拓展协程*/
const val lifecycle_runtime_ktx = "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
/*livedata 拓展协程*/
const val lifecycle_liveData_ktx = "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"
// "androidx.lifecycle:lifecycle-livedata-core:2.3.1"
/*viewModel 拓展协程*/
const val lifecycle_viewModel_ktx = "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
}
} | 0 | Kotlin | 2 | 5 | 70b6a39103a5c759f889ab3463e2c1283631e0c0 | 2,229 | AndroidBaseArchitecture | MIT License |
foundry-databind/src/main/kotlin/com/valaphee/foundry/databind/binding/Binding.kt | valaphee | 372,059,969 | false | null | /*
* MIT License
*
* Copyright (c) 2021, Valaphee.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.valaphee.foundry.databind.binding
import com.valaphee.foundry.databind.value.ObservableValue
import com.valaphee.foundry.util.Disposable
import com.valaphee.foundry.util.DisposedByException
/**
* @author Kevin Ludwig
*/
interface Binding<out T : Any> : ObservableValue<T>, Disposable
internal fun <T : Any> Binding<T>.runWithDisposeOnFailure(function: () -> Unit) {
try {
function()
} catch (ex: Exception) {
dispose(DisposedByException(ex))
}
}
| 0 | Kotlin | 0 | 1 | 69ecf91e6b34031162c43ac12aae88975a2e6f75 | 1,625 | foundry | MIT License |
app/src/main/java/com/nizamsetiawan/app/fasttrackedu/views/dashboard/PaymentVideoLessonActivity.kt | FastTrack-Edu | 837,266,942 | false | {"Kotlin": 88362} | package com.nizamsetiawan.app.fasttrackedu.views.dashboard
import android.os.Bundle
import android.view.LayoutInflater
import com.nizamsetiawan.app.fasttrackedu.core.CoreActivity
import com.nizamsetiawan.app.fasttrackedu.databinding.ActivityPaymentVideoLessonBinding
class PaymentVideoLessonActivity : CoreActivity<ActivityPaymentVideoLessonBinding>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun setupBinding(layoutInflater: LayoutInflater): ActivityPaymentVideoLessonBinding =
ActivityPaymentVideoLessonBinding.inflate(layoutInflater)
}
| 0 | Kotlin | 1 | 0 | 67773f286a8b7ac79026cf0aeabcb47ce7ecbc37 | 630 | Mobile-App | MIT License |
common/common-core/src/main/kotlin/com/blank/common/core/exception/GlobalException.kt | qq781846712 | 705,955,843 | false | {"Kotlin": 847346, "Vue": 376959, "TypeScript": 137544, "Java": 45954, "HTML": 29445, "SCSS": 19657, "JavaScript": 3399, "Batchfile": 2056, "Shell": 1786, "Dockerfile": 1306} | package com.blank.common.core.exception
import java.io.Serial
/**
* 全局异常
*/
class GlobalException(
/**
* 错误提示
*/
override var message: String?
) : RuntimeException(message) {
companion object {
@Serial
private const val serialVersionUID = 1L
}
/**
* 错误明细,内部调试错误
*/
var detailMessage: String? = null
}
| 1 | Kotlin | 0 | 0 | d14c56f4a4e6c777eadbb8b1b9d2743034c6a7f6 | 366 | Ruoyi-Vue-Plus-Kotlin | Apache License 2.0 |
src/main/java/com/github/kisaragieffective/opencommandblock/task/CheckUpdate.kt | KisaragiArchive | 174,288,842 | false | {"Kotlin": 119308} | package com.github.kisaragieffective.opencommandblock.task
import com.github.kisaragieffective.opencommandblock.OpenCommandBlock
import com.github.kisaragieffective.opencommandblock.api.common.Version
import org.bukkit.scheduler.BukkitRunnable
object CheckUpdate : BukkitRunnable() {
override fun run() {
val logger = OpenCommandBlock.instance.value!!.logger
logger.info("Checking updates...")
var newVersionAvailable = false
val newVersion: Version
logger.info(
if (newVersionAvailable) {
"New version is available! (v${OpenCommandBlock.getVersion()}"
} else {
"You are running the latest version."
}
)
}
} | 13 | Kotlin | 0 | 0 | 7f78beb8e628ac4c8ac0991d2648412cd989edc0 | 757 | OpenCommandBlock | MIT License |
app/src/main/java/com/brandonhxrr/gallery/PhotoView.kt | brandonhxrr | 548,636,887 | false | null | package com.brandonhxrr.gallery
import android.annotation.SuppressLint
import android.app.Activity
import android.content.*
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.InsetDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.TypedValue
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.MenuRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.menu.MenuBuilder
import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.Toolbar
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.FileProvider
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.ViewPager
import com.brandonhxrr.gallery.adapter.view_pager.ViewPagerAdapter
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.google.gson.Gson
import kotlinx.coroutines.launch
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
class PhotoView : AppCompatActivity() {
private var media: List<Photo>? = null
private lateinit var viewPager: CustomViewPager
private lateinit var viewPagerAdapter: ViewPagerAdapter
private lateinit var photoDate: TextView
private lateinit var photoTime: TextView
private lateinit var container: ConstraintLayout
private lateinit var bottomContainer: Toolbar
private lateinit var toolbar: Toolbar
private lateinit var btnDelete: ImageButton
private lateinit var btnShare: ImageButton
private lateinit var btnMenu: ImageButton
var position: Int = 0
private lateinit var windowInsetsController : WindowInsetsControllerCompat
private lateinit var operation: String
private lateinit var currentFile: File
private var deletedImageUri: Uri? = null
private lateinit var intentSenderLauncher: ActivityResultLauncher<IntentSenderRequest>
private val PERMISSION_PREFS_NAME = "permissions"
private val SD_CARD_PERMISSION_GRANTED_KEY = "sd_card_permission_granted"
private lateinit var destinationPath: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
windowInsetsController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
setContentView(R.layout.activity_photo_view)
photoDate = findViewById(R.id.photo_date)
photoTime = findViewById(R.id.photo_time)
container = findViewById(R.id.constraintContainer)
bottomContainer = findViewById(R.id.bottom_container)
btnDelete = findViewById(R.id.btn_delete)
btnShare = findViewById(R.id.btn_share)
btnMenu = findViewById(R.id.btn_menu)
toolbar = findViewById(R.id.toolbar)
val params = toolbar.layoutParams as ViewGroup.MarginLayoutParams
params.topMargin = getStatusBarHeight()
toolbar.layoutParams = params
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_back)
supportActionBar?.title = ""
val bundle = intent.extras
position = bundle?.getInt("position")!!
val gson = Gson()
val data = intent.getStringExtra("data")
media = gson.fromJson(data, Array<Photo>::class.java).toList()
viewPager = findViewById(R.id.viewPager)
currentFile = File(media!![position].path)
viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener(){
override fun onPageSelected(pos: Int) {
super.onPageSelected(pos)
setDateTime()
position = pos
currentFile = File(media!![position].path)
}
})
viewPagerAdapter = ViewPagerAdapter(this, media!!)
viewPager.adapter = viewPagerAdapter
setDateTime()
viewPager.currentItem = position
toolbar.visibility = View.GONE
bottomContainer.visibility = View.GONE
windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
container.setBackgroundColor(Color.BLACK)
btnDelete.setOnClickListener {
showMenu(it, R.menu.menu_delete)
}
btnShare.setOnClickListener {
val intent = Intent(Intent.ACTION_SEND)
intent.type = if (imageExtensions.contains(currentFile.extension)) "image/*" else "video/*"
val uri = FileProvider.getUriForFile(this, "${this.packageName}.provider", currentFile)
intent.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(Intent.createChooser(intent, getString(R.string.menu_share)))
}
btnMenu.setOnClickListener {
showSubmenu(it, R.menu.menu_submenu)
}
intentSenderLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
if(it.resultCode == RESULT_OK) {
if(Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
lifecycleScope.launch {
deletePhotoFromExternal(this@PhotoView, deletedImageUri ?: return@launch, intentSenderLauncher)
}
}
} else {
Toast.makeText(this, getString(R.string.file_not_deleted), Toast.LENGTH_SHORT).show()
}
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressedDispatcher.onBackPressed()
return true
}
@SuppressLint("RestrictedApi")
private fun showMenu(v: View, @MenuRes menuRes: Int) {
val popup = PopupMenu(this, v)
popup.menuInflater.inflate(menuRes, popup.menu)
if (popup.menu is MenuBuilder) {
val menuBuilder = popup.menu as MenuBuilder
menuBuilder.setOptionalIconsVisible(true)
for (item in menuBuilder.visibleItems) {
val iconMarginPx =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 5f, resources.displayMetrics
)
.toInt()
if (item.icon != null) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
item.icon = InsetDrawable(item.icon, iconMarginPx, 0, iconMarginPx, 0)
} else {
item.icon =
object : InsetDrawable(item.icon, iconMarginPx, 0, iconMarginPx, 0) {
override fun getIntrinsicWidth(): Int {
return intrinsicHeight + iconMarginPx + iconMarginPx
}
}
}
}
}
popup.setOnMenuItemClickListener { menuItem: MenuItem ->
when (menuItem.itemId) {
R.id.menu_delete -> {
if(currentFile.delete()){
removeImageFromAdapter()
Toast.makeText(this, getString(R.string.file_deleted), Toast.LENGTH_SHORT).show()
}else if(deletePhotoFromExternal(this, getContentUri(this, currentFile)!!, intentSenderLauncher)) {
removeImageFromAdapter()
Toast.makeText(this, getString(R.string.file_deleted), Toast.LENGTH_SHORT).show()
}else {
Toast.makeText(this, getString(R.string.file_not_deleted), Toast.LENGTH_SHORT).show()
}
}
}
true
}
popup.setOnDismissListener {
}
popup.show()
}
}
private fun removeImageFromAdapter(){
media = ArrayList(media!!).apply { removeAt(position) }
if((media as ArrayList<Photo>).isNotEmpty()){
viewPagerAdapter.updateData(media!!)
viewPager.adapter = viewPagerAdapter
viewPager.invalidate()
viewPager.currentItem = position
currentFile = File(media!![position].path)
setDateTime()
}else {
onBackPressedDispatcher.onBackPressed()
}
}
private fun showSubmenu(v: View, @MenuRes menuRes: Int) {
val popup = PopupMenu(this, v)
popup.menuInflater.inflate(menuRes, popup.menu)
popup.setOnMenuItemClickListener { menuItem: MenuItem ->
when (menuItem.itemId) {
R.id.menu_details-> {
//"dd/MM/yyyy HH:mm a"
val dateFormat = SimpleDateFormat(getString(R.string.time_format), Locale.getDefault())
val lastModified = currentFile.lastModified()
val fileSize = currentFile.length()
val fileSizeString: String = if (fileSize >= 1024 * 1024 * 1024) {
String.format(Locale.getDefault(), "%.2f GB", fileSize.toFloat() / (1024 * 1024 * 1024))
} else if (fileSize >= 1024 * 1024) {
String.format(Locale.getDefault(), "%.2f MB", fileSize.toFloat() / (1024 * 1024))
} else if (fileSize >= 1024) {
String.format(Locale.getDefault(), "%.2f KB", fileSize.toFloat() / 1024)
} else {
"$fileSize bytes"
}
MaterialAlertDialogBuilder(this)
//.setTitle((position + 1).toString() + "/" + media!!.size.toString())
.setMessage(getString(R.string.details_path) + ": " + currentFile.absolutePath
+ "\n" + getString(R.string.details_type) + ": " + currentFile.extension
+ "\n" + getString(R.string.details_size) + ": " + fileSizeString
+ "\n" + getString(R.string.details_resolution) + ": " + getResolution(currentFile.path)
+ "\n" + getString(R.string.details_date) + ": " + dateFormat.format(Date(lastModified)))
.setPositiveButton(getString(R.string.accept)) { dialog, _ ->
dialog.dismiss()
}
.show()
}
R.id.menu_move -> {
val selectionIntent = Intent(this, AlbumSelection::class.java)
resultLauncher.launch(selectionIntent)
operation = "MOVE"
}
R.id.menu_copy -> {
val mimeType: String = if (currentFile.extension in imageExtensions) "image/${currentFile.extension}" else "video/${currentFile.extension}"
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
.setType(mimeType)
.addCategory(Intent.CATEGORY_OPENABLE)
.setComponent(ComponentName(this, AlbumSelection::class.java))
resultLauncher.launch(intent)
operation = "COPY"
}
R.id.menu_rename -> {
val view = layoutInflater.inflate(R.layout.alert_edit_text, null)
val textInputLayout = view.findViewById<TextInputLayout>(R.id.text_input_layout)
val textInputEditText = view.findViewById<TextInputEditText>(R.id.text_input_edit_text)
textInputEditText.setText(currentFile.nameWithoutExtension)
MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.menu_rename))
.setView(textInputLayout)
.setPositiveButton(getString(R.string.menu_rename)) { _, _ ->
var newName = textInputEditText.text.toString()
newName += "." + currentFile.extension
val newFile = File(currentFile.parent!! + "/" + newName)
if (currentFile.renameTo(newFile)) {
currentFile = File(media!![position].path)
Toast.makeText(this, getString(R.string.file_renamed), Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, getString(R.string.file_not_renamed), Toast.LENGTH_SHORT).show()
}
}
.setNegativeButton(getString(R.string.cancel)) { dialog, _ ->
dialog.dismiss()
}
.show()
}
}
true
}
popup.setOnDismissListener {}
popup.show()
}
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
destinationPath = data?.getStringExtra("RUTA")!!
when(operation) {
"MOVE" -> {
copyFileToUri(this, currentFile, destinationPath, true, requestPermissionLauncher, intentSenderLauncher)
removeImageFromAdapter()
}
"COPY" -> {
copyFileToUri(this, currentFile, destinationPath, false, requestPermissionLauncher, intentSenderLauncher)
}
}
}
}
private fun getResolution(path: String): String {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeFile(path, options)
return options.outWidth.toString() + "x" + options.outHeight.toString()
}
private fun setDateTime() {
val date = Date(currentFile.lastModified())
val inputFormat = SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.getDefault())
val outputFormatDate = SimpleDateFormat(getString(R.string.time_format_date), Locale.getDefault())
val outputFormatTime = SimpleDateFormat("hh:mm a", Locale.getDefault())
val input = inputFormat.format(date)
val dateParse = inputFormat.parse(input)
photoDate.text = outputFormatDate.format(dateParse!!)
photoTime.text = outputFormatTime.format(dateParse)
}
@SuppressLint("InternalInsetResource")
private fun getStatusBarHeight(): Int {
val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
return if (resourceId != 0) {
resources.getDimensionPixelSize(resourceId)
} else 0
}
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val uri: Uri? = result.data?.data
if (uri != null) {
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
contentResolver.takePersistableUriPermission(uri, takeFlags)
val sharedPreferences = getSharedPreferences(PERMISSION_PREFS_NAME, Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putBoolean(SD_CARD_PERMISSION_GRANTED_KEY, true)
editor.apply()
copyToExternal(this, currentFile, destinationPath, operation == "MOVE", intentSenderLauncher)
}
}
}
} | 0 | null | 2 | 8 | 55acbeedd80ea139bb28172c07e62a05c0be5191 | 16,493 | Gallery | MIT License |
app/src/main/java/com/axel_stein/glucose_tracker/room/DatePeriodUtil.kt | AxelStein | 320,277,698 | false | null | package com.axel_stein.glucose_tracker.room
import com.axel_stein.glucose_tracker.core.DatePeriod
import com.axel_stein.glucose_tracker.core.DatePeriod.*
fun DatePeriod.toSqlString(): String {
return when (this) {
TODAY -> "" // todo test
TWO_WEEKS -> "-14 day"
MONTH -> "-1 month"
THREE_MONTHS -> "-3 month"
SIX_MONTHS -> "-6 month"
YEAR -> "-1 year"
}
} | 4 | Kotlin | 0 | 1 | d6f6877c33b960c8bcc1cfd2ff355071908891ec | 413 | GlucoseTracker | Apache License 2.0 |
src/main/kotlin/io/github/pleahmacaka/example/gui/RewardGui.kt | PleahMaCaka | 758,012,881 | false | {"Kotlin": 48599, "Python": 5517} | package io.github.pleahmacaka.example.gui
import io.github.pleahmacaka.example.Example
import net.kyori.adventure.text.Component
import org.bukkit.Bukkit
import org.bukkit.configuration.file.YamlConfiguration
import org.bukkit.inventory.Inventory
import java.io.File
object RewardGui {
private const val SIZEOF = 6 * 9
val inv: Inventory = Bukkit.createInventory(null, SIZEOF, Component.text("보상 목록"))
fun getRewardSize(): Int {
return inv.contents.filter { it != null && it.type != org.bukkit.Material.AIR }.size
}
fun saveReward() {
val file = File("./config/rewards.yaml")
file.createNewFile()
val config = YamlConfiguration.loadConfiguration(file)
for (i in 0 until SIZEOF) {
val item = inv.getItem(i)
if (item != null) {
config.set("rewards.$i", item)
}
}
config.save(file)
}
fun loadReward() {
val file = File("./config/rewards.yaml")
if (!file.exists()) {
Example.instance.logger.info("보상 데이터를 찾을 수 없습니다.")
return
}
val config = YamlConfiguration.loadConfiguration(file)
for (i in 0 until SIZEOF) {
val item = config.getItemStack("rewards.$i")
if (item != null) {
inv.setItem(i, item)
}
}
}
} | 0 | Kotlin | 0 | 0 | 05312f8c1d9d52ad89586dbea2c890a722fa49a9 | 1,370 | world-border-survival | MIT License |
src/commonMain/kotlin/StringUtils.kt | allegro | 439,312,455 | false | null | internal val String.intOrZero: Int
get() = doubleOrZero.toInt()
internal val String.longOrZero: Long
get() = doubleOrZero.toLong()
internal val String.doubleOrZero: Double
get() = toDoubleOrNull() ?: 0.0
| 4 | Kotlin | 1 | 10 | f1edfd217e151ba9cc5f8a52c001405578f81d91 | 219 | json-logic-kmp | Apache License 2.0 |
android/app/src/main/java/com/example/gamebaaz/ui/composables/DrawTitle.kt | sarnavakonar | 404,768,470 | false | {"Kotlin": 149152} | package com.example.gamebaaz.ui.composables
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun DrawTitle(
text: String,
modifier: Modifier? = null,
color: Color = MaterialTheme.colors.onPrimary,
alpha: Float = 1f,
fontSize: TextUnit = 16.sp,
style: TextStyle? = null
) {
Text(
text = text,
style = style?.copy(
color = color.copy(alpha = alpha),
fontSize = fontSize
)
?: MaterialTheme.typography.body2
.copy(
color = color.copy(alpha = alpha),
fontSize = fontSize
),
textAlign = TextAlign.Justify,
modifier = modifier ?: Modifier.padding(start = 16.dp, end = 16.dp)
)
}
@Composable
fun DrawSearchTitle(
text: String,
modifier: Modifier = Modifier,
showLoader: Boolean = false
) {
Row(modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp),
verticalAlignment = Alignment.CenterVertically
){
Text(
text = text,
style = MaterialTheme.typography.body2,
textAlign = TextAlign.Center,
modifier = modifier
)
Spacer(modifier = Modifier.width(width = 16.dp))
if (showLoader){
DrawLoader()
Spacer(modifier = Modifier.weight(1f))
}
}
} | 0 | Kotlin | 17 | 89 | ea0b04980ba82db5f85f9a64b64b10911a1f3f7a | 1,834 | Gamebaaz | MIT License |
airbyte-cdk/java/airbyte-cdk/db-sources/src/test/kotlin/io/airbyte/cdk/integrations/source/relationaldb/state/StateGeneratorUtilsTest.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.cdk.integrations.source.relationaldb.state
import io.airbyte.protocol.models.v0.StreamDescriptor
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
/** Test suite for the [StateGeneratorUtils] class. */
class StateGeneratorUtilsTest {
@Test
fun testValidStreamDescriptor() {
val streamDescriptor1: StreamDescriptor? = null
val streamDescriptor2 = StreamDescriptor()
val streamDescriptor3 = StreamDescriptor().withName("name")
val streamDescriptor4 = StreamDescriptor().withNamespace("namespace")
val streamDescriptor5 = StreamDescriptor().withName("name").withNamespace("namespace")
val streamDescriptor6 = StreamDescriptor().withName("name").withNamespace("")
val streamDescriptor7 = StreamDescriptor().withName("").withNamespace("namespace")
val streamDescriptor8 = StreamDescriptor().withName("").withNamespace("")
Assertions.assertFalse(StateGeneratorUtils.isValidStreamDescriptor(streamDescriptor1))
Assertions.assertFalse(StateGeneratorUtils.isValidStreamDescriptor(streamDescriptor2))
Assertions.assertTrue(StateGeneratorUtils.isValidStreamDescriptor(streamDescriptor3))
Assertions.assertFalse(StateGeneratorUtils.isValidStreamDescriptor(streamDescriptor4))
Assertions.assertTrue(StateGeneratorUtils.isValidStreamDescriptor(streamDescriptor5))
Assertions.assertTrue(StateGeneratorUtils.isValidStreamDescriptor(streamDescriptor6))
Assertions.assertTrue(StateGeneratorUtils.isValidStreamDescriptor(streamDescriptor7))
Assertions.assertTrue(StateGeneratorUtils.isValidStreamDescriptor(streamDescriptor8))
}
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 1,763 | airbyte | MIT License |
app/src/main/java/com/example/doodle/remote/setting/SettingItem.kt | BillyWei01 | 145,632,245 | false | {"Markdown": 5, "Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "XML": 62, "SVG": 1, "Kotlin": 73, "Java": 43} | package com.example.doodle.remote.setting
class SettingItem(var id: Int, var title: String, var subtitle: String) | 0 | Java | 15 | 90 | 9c2407209faac547744e197558f18470441a6d75 | 114 | Doodle | MIT License |
zircon.examples/src/main/kotlin/org/hexworks/zircon/examples/CP437CharsExample.kt | entelente | 148,384,225 | false | null | package org.hexworks.zircon.examples
import org.hexworks.zircon.api.*
import org.hexworks.zircon.api.graphics.BoxType
import org.hexworks.zircon.api.resource.BuiltInTrueTypeFontResource
import org.hexworks.zircon.api.tileset.lookup.CP437TileMetadataLoader
object CP437CharsExample {
private val theme = ColorThemes.entrappedInAPalette()
@JvmStatic
fun main(args: Array<String>) {
val tileGrid = SwingApplications.startTileGrid(AppConfigs.newConfig()
.defaultSize(Sizes.create(21, 21))
.defaultTileset(TrueTypeFontResources.amstrad(20))
.build())
val screen = Screens.createScreenFor(tileGrid)
val cp437panel = Components.panel()
.size(Sizes.create(19, 19))
.position(Positions.create(1, 1))
.wrapWithBox()
.wrapWithShadow()
.boxType(BoxType.SINGLE)
.build()
val loader = CP437TileMetadataLoader(16, 16)
screen.addComponent(cp437panel)
screen.applyColorTheme(theme)
loader.fetchMetadata().forEach { char, meta ->
cp437panel.draw(drawable = Tiles.defaultTile()
.withCharacter(char)
.withBackgroundColor(theme.primaryBackgroundColor())
.withForegroundColor(theme.primaryForegroundColor()),
position = Positions.create(meta.x, meta.y)
.plus(Positions.offset1x1()))
}
screen.display()
}
}
| 1 | null | 1 | 1 | a8320415e949d47f55b316092a29f20469450720 | 1,548 | zircon | MIT License |
app/src/main/java/br/com/luisfernandez/github/client/mvp/LoadContentView.kt | luisfernandezbr | 132,829,457 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Kotlin": 35, "XML": 18, "Java": 5} | package br.com.luisfernandez.github.client.mvp
/**
* Created by luisfernandez on 13/05/18.
*/
interface LoadContentView<CONTENT, ERROR_BODY>: ErrorHandlerView<ERROR_BODY> {
fun showLoading()
fun showEmpty()
fun showContent(content: CONTENT)
} | 21 | null | 2 | 1 | 3a306d601c6465095cdf6f70d0b5e023cfa3ffe6 | 257 | github-api-android-client | MIT License |
springcloud-business/springcloud-consumer-webflux-kotlin/src/main/kotlin/com/xangqun/springcloud/webflux/WebfluxApplication.kt | liuzeminm | 164,986,630 | false | {"Java": 5765197, "JavaScript": 1505881, "HTML": 645666, "Vue": 253431, "CSS": 214273, "FreeMarker": 68431, "Shell": 44208, "Dockerfile": 10580, "Kotlin": 6143, "Scala": 3647, "Batchfile": 3145, "Smarty": 2485, "PHP": 332} | package com.xangqun.springcloud.webflux
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
open class WebfluxApplication
fun main(args: Array<String>) {
runApplication<WebfluxApplication>(*args)
}
| 1 | null | 1 | 1 | 15dd6823087adb6117589d6f747b412c5ad5efd1 | 291 | springcloud | Apache License 2.0 |
CrossDeviceRockPaperScissorsKotlin/app/src/main/java/com/google/crossdevice/sample/rps/model/GameChoice.kt | android | 206,875,901 | false | null | /*
* Copyright 2022 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.crossdevice.sample.rps.model
/** Class to enumerate game choices and rules */
enum class GameChoice {
ROCK,
PAPER,
SCISSORS;
fun beats(other: GameChoice): Boolean {
return other == inferior()
}
fun superior(): GameChoice {
return when (this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
fun inferior(): GameChoice {
return when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
}
| 159 | null | 1308 | 1,611 | 777517eb2898cd48e139446246808a2106d343cc | 1,095 | connectivity-samples | Apache License 2.0 |
platform/workspaceModel-core/src/pstorage/Entities.kt | Blackdread | 253,757,648 | false | null | // Copyright 2000-2020 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 com.intellij.workspace.api.pstorage
import com.intellij.workspace.api.EntitySource
import com.intellij.workspace.api.ModifiableTypedEntity
import com.intellij.workspace.api.ReferableTypedEntity
import com.intellij.workspace.api.TypedEntity
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.*
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.jvm.isAccessible
abstract class PTypedEntity : ReferableTypedEntity, Any() {
override lateinit var entitySource: EntitySource
internal set
internal open lateinit var id: PId<TypedEntity>
internal open lateinit var snapshot: AbstractPEntityStorage
override fun hasEqualProperties(e: TypedEntity): Boolean {
if (this.javaClass != e.javaClass) return false
this::class.memberProperties.forEach {
if (it.name == PTypedEntity::id.name) return@forEach
if (it.getter.call(this) != it.getter.call(e)) return false
}
return true
}
override fun <R : TypedEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R> {
val connectionId = snapshot.refs.findConnectionId(this::class.java, entityClass) as ConnectionId<PTypedEntity, R>?
if (connectionId == null) return emptySequence()
return when (connectionId.connectionType) {
ConnectionId.ConnectionType.ONE_TO_MANY -> snapshot.extractOneToManyChildren(connectionId, id as PId<PTypedEntity>)
ConnectionId.ConnectionType.ONE_TO_ONE -> snapshot.extractOneToOneChild(connectionId, id as PId<PTypedEntity>)?.let { sequenceOf(it) } ?: emptySequence()
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> snapshot.extractOneToAbstractManyChildren(connectionId, id as PId<PTypedEntity>)
}
}
override fun toString(): String = "${javaClass.simpleName}-:-$id"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PTypedEntity
if (id != other.id) return false
return true
}
override fun hashCode(): Int = id.hashCode()
}
abstract class PModifiableTypedEntity<T : PTypedEntity> : PTypedEntity(), ModifiableTypedEntity<T> {
internal lateinit var original: PEntityData<T>
internal lateinit var diff: PEntityStorageBuilder
internal val modifiable = ThreadLocal.withInitial { false }
internal inline fun allowModifications(action: () -> Unit) {
modifiable.set(true)
try {
action()
}
finally {
modifiable.remove()
}
}
internal fun getEntityClass(): KClass<T> = ClassConversion.modifiableEntityToEntity(this::class)
}
internal data class PId<E : TypedEntity>(val arrayId: Int, val clazz: KClass<E>) {
init {
if (arrayId < 0) error("ArrayId cannot be negative: $arrayId")
}
override fun toString(): String = arrayId.toString()
}
abstract class PEntityData<E : TypedEntity> {
lateinit var entitySource: EntitySource
var id: Int = -1
internal fun createEntity(snapshot: AbstractPEntityStorage): E {
val returnClass = ClassConversion.entityDataToEntity(this::class)
val params = returnClass.primaryConstructor!!.parameters
.associateWith { param ->
val value = this::class.memberProperties.first { it.name == param.name }.getter.call(this)
if (param.type.isList()) ArrayList(value as List<*>) else value
}.toMutableMap()
val res = returnClass.primaryConstructor!!.callBy(params)
(res as PTypedEntity).entitySource = entitySource
(res as PTypedEntity).id = PId(this::class.memberProperties.first { it.name == "id" }.getter.call(this) as Int, returnClass as KClass<TypedEntity>)
(res as PTypedEntity).snapshot = snapshot
return res
}
internal fun wrapAsModifiable(diff: PEntityStorageBuilder): ModifiableTypedEntity<E> {
val returnClass = ClassConversion.entityDataToModifiableEntity(this::class)
val primaryConstructor = returnClass.primaryConstructor!!
primaryConstructor.isAccessible = true
val res = primaryConstructor.call() as ModifiableTypedEntity<E>
res as PModifiableTypedEntity
res.original = this
res.diff = diff
res.id = PId(this.id, res.getEntityClass() as KClass<TypedEntity>)
res.entitySource = this.entitySource
return res
}
fun clone(): PEntityData<E> {
val copied = this::class.primaryConstructor!!.call()
this::class.memberProperties.filterIsInstance<KMutableProperty<*>>().forEach {
if (it.returnType.isList()) {
it.setter.call(copied, ArrayList(it.getter.call(this) as List<*>))
}
else {
it.setter.call(copied, it.getter.call(this))
}
}
return copied
}
private fun KType.isList(): Boolean = this.classifier == List::class
}
internal class EntityDataDelegation<A : PModifiableTypedEntity<*>, B> : ReadWriteProperty<A, B> {
override fun getValue(thisRef: A, property: KProperty<*>): B {
return ((thisRef.original::class.memberProperties.first { it.name == property.name }) as KProperty1<Any, *>).get(thisRef.original) as B
}
override fun setValue(thisRef: A, property: KProperty<*>, value: B) {
if (!thisRef.modifiable.get()) {
throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!")
}
((thisRef.original::class.memberProperties.first { it.name == property.name }) as KMutableProperty<*>).setter.call(thisRef.original,
value)
}
}
| 5 | null | 1 | 1 | 713cd98e68644db6926bdf0a869b225d36145583 | 5,690 | intellij-community | Apache License 2.0 |
ide-diff-builder/src/main/java/org/jetbrains/ide/diff/builder/persistence/json/JsonSerializer.kt | JetBrains | 3,686,654 | false | null | /*
* Copyright 2000-2020 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.ide.diff.builder.persistence.json
import com.jetbrains.plugin.structure.intellij.version.IdeVersion
import kotlinx.serialization.Serializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
val jsonInstance: Json = Json {
isLenient = true
ignoreUnknownKeys = true
prettyPrint = true
prettyPrintIndent = " "
}
@Serializer(forClass = IdeVersion::class)
object IdeVersionSerializer {
override val descriptor
get() = PrimitiveSerialDescriptor("IdeVersionSerializer", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: IdeVersion) {
encoder.encodeString(value.asString())
}
override fun deserialize(decoder: Decoder) =
IdeVersion.createIdeVersion(decoder.decodeString())
} | 4 | null | 38 | 178 | 8be19a2c67854545d719fe56f3677122481b372f | 1,118 | intellij-plugin-verifier | Apache License 2.0 |
tmp/arrays/youTrackTests/4765.kt | DaniilStepanov | 228,623,440 | false | null | // Original bug: KT-29510
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ExperimentalContracts
class A {
fun foo() {
bar {}
}
inline fun bar(crossinline f: () -> Unit) {
baz {
f()
}
}
}
@ExperimentalContracts
inline fun baz(crossinline f: () -> Unit) {
contract {
callsInPlace(f, InvocationKind.EXACTLY_ONCE)
}
f()
}
| 1 | null | 8 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 465 | bbfgradle | Apache License 2.0 |
src/main/kotlin/classesiiiandiiiobjects/classesiiiandiiiinheritance/p03initiiiorderiiidemo/InitOrderDemo.kt | tomasbjerre | 145,370,738 | false | null | package com.hypo.driven.simpledb
class InitOrderDemo(name: String) {
val firstProperty = "First property: $name".also(::println)
init {
println("First initializer block that prints $name")
}
val secondProperty = "Second property: ${name.length}".also(::println)
init {
println("Second initializer block that prints ${name.length}")
}
}
| 3 | null | 3 | 14 | fc8213c50ee8e1137f3b55c48db7cfcca4af1ca2 | 377 | yet-another-kotlin-vs-java-comparison | Apache License 2.0 |
app/src/main/java/com/ryan/github/kndroid/practice/type/ListBaseOp.kt | Ryan-Shz | 294,726,589 | false | null | package com.ryan.github.kndroid.practice.type
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
fun arrayOp() {
val arr1 = shortArrayOf(1, 2, 3)
val arr2 = intArrayOf(1, 2, 3)
val arr3 = longArrayOf(1L, 2L, 3L)
val arr4 = floatArrayOf(1f, 2f, 3f)
val arr5 = doubleArrayOf(1.0, 2.0, 3.0)
val arr6 = charArrayOf('a', 'b', 'c')
val arr7 = byteArrayOf(1, 2, 3)
val arr8 = arrayOf(1, 2, 3)
val arr9 = arrayOf('a', 'b', 'c')
val arr10 = arrayOf(1.0, 2.0, 3.0)
val arr11 = arrayOf("1", "2", "3")
val arr12 = arrayOfNulls<DataClassPerson>(10)
}
fun rangeOp() {
val range1 = 1..10
val range2 = 1.0..10.0
}
fun listOp() {
// 创建一个不可变的List
val intList1 = listOf(1, 2, 3, 4)
// 创建一个可变的List
val intList2 = mutableListOf(1, 2, 3, 4)
// 创建一个ArrayList,ArrayList是可变的
val intList3 = ArrayList<Int>()
// 创建一个LinkedList,LinkedList是可变的
val intList4 = LinkedList<Int>()
intList1.forEach {
println(it)
}
for (element in intList1) {
println(element)
}
for (index in intList1.indices) {
println(intList1[index])
}
}
fun mapOp() {
// 创建一个不可变的Map
val map1 = mapOf("name" to "Ryan", "age" to "20")
// 创建一个可变的Map
val map2 = mutableMapOf("name" to "Ryan", "age" to "20")
// 创建一个HashMap
val map3 = HashMap<String, String>()
// 添加
map2 += "name" to "Tom"
map2.put("name", "Tom")
// 删除
map2.remove("name")
map2 -= "name"
2.to(3)
// 修改
map2["name"] = "Tom"
// 查询
println("name is: ${map2["name"]}")
// 遍历
// 1. 使用forEach遍历
map1.forEach {
println("key: ${it.key}, value: ${it.value}")
}
// 2. 使用for in遍历
for (key in map1.keys) {
println("key: $key, value: ${map1[key]}")
}
// 长度
println("map size: ${map1.size}")
// 包含
map1.containsKey("name")
map1.containsValue("Ryan")
} | 0 | Kotlin | 0 | 1 | 9ac72cfaef6e69dccae5a971217b2b08f8c66968 | 1,965 | Kndroid | MIT License |
app/src/main/java/com/bharathvishal/layoutchangingrecyclerview/CustomRecyclerView.kt | BharathVishal | 141,532,247 | false | {"Java": 1163, "Kotlin": 475} | package com.bharathvishal.layoutchangingrecyclerview
import androidx.recyclerview.widget.RecyclerView
class CustomRecyclerView:RecyclerView()
{
} | 1 | null | 1 | 1 | 05ceac7f580ca6565d0b08161959771cb4ccc95e | 148 | Layout-Changing-Recycler-View | Apache License 2.0 |
kotlin/Numeric Matrix Processor/Stage 2/Main.kt | YuraVolk | 699,763,308 | false | {"Java": 270149, "Kotlin": 160960, "JavaScript": 46154, "CSS": 25589, "HTML": 21447} | package processor
class MatrixProcessor {
private fun inputMatrix(): Matrix {
val (rows, cols) = readln().split(" ").map { it.toInt() }
val matrix = Array(rows) { IntArray(cols) }
for (i in 0 until rows) {
val row = readln().split(" ").map { it.toInt() }
for (j in 0 until cols) matrix[i][j] = row[j]
}
return Matrix(matrix, rows, cols)
}
fun addMatrices() {
val matrixA = inputMatrix(); val matrixB = inputMatrix()
if (matrixA.rows != matrixB.rows || matrixA.cols != matrixB.cols) {
println("ERROR")
} else println(Matrix(Array(matrixA.rows) { i -> IntArray(matrixA.cols) { j -> matrixA.matrix[i][j] + matrixB.matrix[i][j] } }))
}
fun multiplyMatrices() {
val matrix = inputMatrix(); val constant = readln().toInt()
println(Matrix(Array(matrix.rows) { i -> IntArray(matrix.cols) { j -> matrix.matrix[i][j] * constant } }))
}
}
fun main() = MatrixProcessor().multiplyMatrices()
| 1 | null | 1 | 1 | 8ceb6e2c20bb347a4a9b6cd5d121170d199c8667 | 1,023 | hyperskill-projects | The Unlicense |
lifecycleEvents/src/main/java/robertapikyan/com/events/implementation/lifecycle/PendingEvents.kt | RobertApikyan | 144,712,893 | false | {"Kotlin": 28073, "Java": 1128} | package robertapikyan.com.events.implementation.lifecycle
import java.util.*
class PendingEvents<T>(private val policy: PendingEventsRules,
private val events: LinkedList<T> = LinkedList()) :
Queue<T> by events {
override fun add(element: T): Boolean {
return when (policy) {
PendingEventsRules.IN_ORDER -> events.add(element)
PendingEventsRules.REVERSE_ORDER -> {
events.addFirst(element)
return true
}
PendingEventsRules.ONLY_FIRST -> {
if (events.isEmpty()) {
events.addFirst(element)
return true
}
return false
}
PendingEventsRules.ONLY_LAST -> {
events.clear()
events.addFirst(element)
return true
}
PendingEventsRules.IGNORE -> false
PendingEventsRules.IMMEDIATE -> false
}
}
} | 0 | Kotlin | 4 | 22 | 9cfe8e5060d09163628bfa6782a1f0dd6816581c | 1,023 | LifecycleEvents | Apache License 2.0 |
app/src/main/java/pt/dbmg/mobiletaiga/network/response/RelationshipsGroupActionLogs.kt | worm69 | 166,021,572 | false | null | package pt.dbmg.mobiletaiga.network.response
import com.google.gson.annotations.SerializedName
data class RelationshipsGroupActionLogs(
@SerializedName("group")
val group: Group,
@SerializedName("target")
val target: Target,
@SerializedName("user")
val user: User
) | 0 | null | 0 | 4 | 8ec09bed018d57225b85e042865608952633c622 | 291 | mobiletaiga | Apache License 2.0 |
app/src/main/java/com/geniusforapp/movies/shared/domain/datasources/SimilarMoviesDataSource.kt | geniusforapp | 91,422,278 | false | null | package com.geniusforapp.movies.shared.domain.datasources
import androidx.lifecycle.MutableLiveData
import androidx.paging.ItemKeyedDataSource
import com.geniusforapp.movies.shared.data.model.MoviesResponse
import com.geniusforapp.movies.shared.domain.usecases.GetSimilarMoviesByIdUseCase
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject
class SimilarMoviesDataSource @Inject constructor(private val compositeDisposable: CompositeDisposable,
private val getSimilarMoviesByIdUseCase: GetSimilarMoviesByIdUseCase) : ItemKeyedDataSource<Int, MoviesResponse.Result>() {
private var currentPage: Int = 1
var movieId: Int = 0
lateinit var loaderLiveData: MutableLiveData<Boolean>
lateinit var errorLiveData: MutableLiveData<Throwable>
lateinit var loadMoreLiveData: MutableLiveData<Boolean>
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<MoviesResponse.Result>) {
loaderLiveData.postValue(true)
compositeDisposable.add(getSimilarMoviesByIdUseCase
.getSimilarMovies(movieId, currentPage)
.subscribe({
loaderLiveData.postValue(false)
callback.onResult(it.results)
}, { errorLiveData.postValue(it) }))
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<MoviesResponse.Result>) {
loadMoreLiveData.postValue(true)
compositeDisposable.add(getSimilarMoviesByIdUseCase
.getSimilarMovies(movieId, params.key)
.subscribe({
currentPage += 1
loadMoreLiveData.postValue(false)
callback.onResult(it.results)
}, { errorLiveData.postValue(it) }))
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<MoviesResponse.Result>) {
}
override fun getKey(item: MoviesResponse.Result): Int = currentPage
} | 1 | Kotlin | 5 | 3 | e63a4d948d5a2253b5c3c47196476bb45053df2b | 2,026 | movies | Apache License 2.0 |
app/src/main/java/com/obaniu/inappfloatview/test/MyApplication.kt | gold-duo | 158,714,429 | false | {"Java": 31680, "Kotlin": 6639} | package com.obaniu.inappfloatview.test
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.util.Log
import com.obaniu.inappfloatview.InAppFloatView
import com.obaniu.inappfloatview.LayoutParams
/**
* Created by obaniu on 2018/12/19.
*/
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
val isMainProcess = getCurrentProcessName().equals(packageName);
InAppFloatView.init(this, isMainProcess)
InAppFloatView.setOnFloatViewCreated { view, tag ->
Log.i("InAppFloatView", "onCreated:$tag")
}
InAppFloatView.setOnFloatViewAttached { _, view, tag ->
Common.setViewBgWithGravity(tag,view)
Log.i("InAppFloatView", "onAttached:$tag")
}
InAppFloatView.setOnFloatViewDetached { _, tag -> Log.i("InAppFloatView", "onDetached:$tag") }
InAppFloatView.setOnFloatViewChanged{view,tag->
Common.setViewBgWithGravity(tag,view)
Log.i("InAppFloatView", "onChanged:$tag")
}
if(isMainProcess) {
val params = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Common.randPosition)
InAppFloatView.show(R.layout.float_view, Common.FLOAT_VIEW_FEED_BACK, params, true)
}
}
private fun getCurrentProcessName(): String? {
val pid = android.os.Process.myPid()
val mActivityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (appProcess in mActivityManager.runningAppProcesses) {
if (appProcess.pid == pid) return appProcess.processName
}
return null
}
}
| 1 | Java | 1 | 8 | 9cb8aea10ff8deda766e73fc1ddc043836d7c63e | 1,709 | InAppFloatView | Apache License 2.0 |
app/src/main/kotlin/kozyriatskyi/anton/sked/audiences/AudiencesModule.kt | antonKozyriatskyi | 123,421,471 | false | null | package kozyriatskyi.anton.sked.audiences
import dagger.Module
import dagger.Provides
import kozyriatskyi.anton.sked.analytics.AnalyticsManager
import kozyriatskyi.anton.sked.data.api.ClassroomsApi
import kozyriatskyi.anton.sked.data.repository.ResourceManager
import kozyriatskyi.anton.sked.di.Audiences
import kozyriatskyi.anton.sked.repository.AudiencesProvider
@Module
class AudiencesModule {
@Audiences
@Provides
fun providePresenter(interactor: AudiencesInteractor, mapper: AudiencesMapper): AudiencesPresenter =
AudiencesPresenter(interactor, mapper)
@Audiences
@Provides
fun provideInteractor(
provider: AudiencesProvider,
analyticsManager: AnalyticsManager
): AudiencesInteractor = AudiencesInteractor(provider, analyticsManager)
@Audiences
@Provides
fun provideMapper(resourceManager: ResourceManager): AudiencesMapper =
AudiencesMapper(resourceManager)
@Audiences
@Provides
fun provideAudiencesProvider(api: ClassroomsApi): AudiencesProvider =
ApiAudiencesProvider(api)
} | 1 | null | 1 | 3 | e2aa0d4474cf3067c2fa9165bed40a47a599b78e | 1,094 | sked | Apache License 2.0 |
ui/src/main/java/nick/ui/ToolbarSetter.kt | nihk | 165,444,955 | false | {"Gradle": 10, "Java Properties": 2, "Shell": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 1, "Text": 1, "Proguard": 8, "XML": 62, "Kotlin": 84, "Java": 1} | package nick.ui
import androidx.appcompat.widget.Toolbar
interface ToolbarSetter {
fun setToolbar(toolbar: Toolbar, withBackButton: Boolean)
} | 0 | Kotlin | 0 | 2 | 600fd5c8148ddc6225983296b0a0e7254cd1c8c7 | 149 | IAmJob | The Unlicense |
ontrack-extension-stash/src/main/java/net/nemerosa/ontrack/extension/stash/model/StashConfiguration.kt | nemerosa | 19,351,480 | false | {"Git Config": 1, "Gradle Kotlin DSL": 67, "Markdown": 46, "Ignore List": 22, "Java Properties": 3, "Shell": 9, "Text": 3, "Batchfile": 2, "Groovy": 145, "JSON": 31, "JavaScript": 792, "JSON with Comments": 4, "GraphQL": 79, "Kotlin": 3960, "Java": 649, "HTML": 269, "PlantUML": 25, "AsciiDoc": 288, "XML": 9, "YAML": 33, "INI": 4, "Dockerfile": 7, "Less": 31, "CSS": 13, "SQL": 43, "Dotenv": 1, "Maven POM": 1, "SVG": 4} | package net.nemerosa.ontrack.extension.stash.model
import com.fasterxml.jackson.annotation.JsonIgnore
import net.nemerosa.ontrack.model.annotations.APIDescription
import net.nemerosa.ontrack.model.annotations.APILabel
import net.nemerosa.ontrack.model.form.*
import net.nemerosa.ontrack.model.form.Form.Companion.defaultNameField
import net.nemerosa.ontrack.model.support.ConfigurationDescriptor
import net.nemerosa.ontrack.model.support.UserPasswordConfiguration
import org.apache.commons.lang3.StringUtils
import java.lang.String.format
/**
* @property name Name of this configuration
* @property url Bitbucket URL
* @property user User name
* @property password User password
* @property autoMergeToken Token used for approving pull requests for the auto merge operations
*/
// TODO #532 Workaround
open class StashConfiguration(
name: String,
val url: String,
user: String?,
password: String?,
@APILabel("Auto merge user")
@APIDescription("Slug of the user approving pull requests for the auto merge operations")
val autoMergeUser: String?,
@APILabel("Auto merge token")
@APIDescription("Token used for approving pull requests for the auto merge operations")
val autoMergeToken: String?,
) : UserPasswordConfiguration<StashConfiguration>(name, user, password) {
/**
* Checks if this configuration denotes any Bitbucket Cloud instance
*/
@Deprecated("Specific Bitbucket Cloud configuration must be used. Will be removed in V5.")
val isCloud: Boolean
@JsonIgnore
get() = StringUtils.contains(url, "bitbucket.org")
override val descriptor: ConfigurationDescriptor
get() = ConfigurationDescriptor(
name,
format("%s (%s)", name, url)
)
override fun obfuscate() = StashConfiguration(
name = name,
url = url,
user = user,
password = "",
autoMergeUser = autoMergeUser,
autoMergeToken = "",
)
override fun withPassword(password: String?): StashConfiguration {
return StashConfiguration(
name = name,
url = url,
user = user,
password = password,
autoMergeUser = autoMergeUser,
autoMergeToken = autoMergeToken,
)
}
fun asForm(): Form {
return form()
.with(defaultNameField().readOnly().value(name))
.fill("url", url)
.fill("user", user)
.fill("password", "")
.fill("autoMergeUser", autoMergeUser)
.fill("autoMergeToken", "")
}
companion object {
fun form(): Form {
return Form.create()
.with(defaultNameField())
.with(
Text.of("url")
.label("URL")
.help("URL to the Bitbucket instance (https://bitbucket.org for example)")
)
.with(
Text.of("user")
.label("User")
.length(16)
.optional()
)
.with(
Password.of("password")
.label("Password")
.length(40)
.optional()
)
.textField(StashConfiguration::autoMergeUser, null)
.passwordField(StashConfiguration::autoMergeToken)
}
}
}
| 48 | Kotlin | 25 | 96 | 759f17484c9b507204e5a89524e07df871697e74 | 3,476 | ontrack | MIT License |
utbot-framework/src/main/kotlin/org/utbot/framework/codegen/tree/CgAbstractSpringTestClassConstructor.kt | UnitTestBot | 480,810,501 | false | null | package org.utbot.framework.codegen.tree
import org.utbot.framework.codegen.domain.builtin.TestClassUtilMethodProvider
import org.utbot.framework.codegen.domain.context.CgContext
import org.utbot.framework.codegen.domain.models.AnnotationTarget.Method
import org.utbot.framework.codegen.domain.models.CgClassBody
import org.utbot.framework.codegen.domain.models.CgFieldDeclaration
import org.utbot.framework.codegen.domain.models.CgFrameworkUtilMethod
import org.utbot.framework.codegen.domain.models.CgMethod
import org.utbot.framework.codegen.domain.models.CgMethodTestSet
import org.utbot.framework.codegen.domain.models.CgMethodsCluster
import org.utbot.framework.codegen.domain.models.CgRegion
import org.utbot.framework.codegen.domain.models.CgStatement
import org.utbot.framework.codegen.domain.models.CgStaticsRegion
import org.utbot.framework.codegen.domain.models.SimpleTestClassModel
import org.utbot.framework.codegen.tree.fieldmanager.ClassFieldManagerFacade
import org.utbot.framework.plugin.api.UtExecution
import org.utbot.framework.plugin.api.util.id
abstract class CgAbstractSpringTestClassConstructor(context: CgContext) :
CgAbstractTestClassConstructor<SimpleTestClassModel>(context) {
protected val variableConstructor: CgSpringVariableConstructor =
CgComponents.getVariableConstructorBy(context) as CgSpringVariableConstructor
override fun constructTestClassBody(testClassModel: SimpleTestClassModel): CgClassBody {
return buildClassBody(currentTestClass) {
// TODO: support inner classes here
fields += constructClassFields(testClassModel)
clearUnwantedVariableModels()
constructAdditionalTestMethods()?.let { methodRegions += it }
for ((testSetIndex, testSet) in testClassModel.methodTestSets.withIndex()) {
updateExecutableUnderTest(testSet.executableUnderTest)
withTestSetIdScope(testSetIndex) {
val currentMethodUnderTestRegions = constructTestSet(testSet) ?: return@withTestSetIdScope
val executableUnderTestCluster = CgMethodsCluster(
"Test suites for executable $currentExecutableUnderTest",
currentMethodUnderTestRegions
)
methodRegions += executableUnderTestCluster
}
}
constructAdditionalUtilMethods()?.let { methodRegions += it }
if (currentTestClass == outerMostTestClass) {
val utilEntities = collectUtilEntities()
// If utilMethodProvider is TestClassUtilMethodProvider, then util entities should be declared
// in the test class. Otherwise, util entities will be located elsewhere (e.g. another class).
if (utilMethodProvider is TestClassUtilMethodProvider && utilEntities.isNotEmpty()) {
staticDeclarationRegions += CgStaticsRegion("Util methods", utilEntities)
}
}
}
}
override fun constructTestSet(testSet: CgMethodTestSet): List<CgRegion<CgMethod>>? {
val regions = mutableListOf<CgRegion<CgMethod>>()
if (testSet.executions.any()) {
runCatching {
createTest(testSet, regions)
}.onFailure { e -> processFailure(testSet, e) }
}
val errors = testSet.allErrors
if (errors.isNotEmpty()) {
regions += methodConstructor.errorMethod(testSet, errors)
testsGenerationReport.addMethodErrors(testSet, errors)
}
return if (regions.any()) regions else null
}
abstract fun constructClassFields(testClassModel: SimpleTestClassModel): List<CgFieldDeclaration>
/**
* Here "additional" means that these tests are not obtained from
* [UtExecution]s generated by engine or fuzzer, but have another origin.
*/
open fun constructAdditionalTestMethods(): CgMethodsCluster? = null
open fun constructAdditionalUtilMethods(): CgMethodsCluster? = null
/**
* Clears the results of variable instantiations that occurred
* when we create class variables with specific annotations.
* Actually, only mentioned variables should be stored in `valueByModelId`.
*
* This is a kind of HACK.
* It is better to distinguish creating variable by model with all
* related side effects and just creating a variable definition,
* but it will take very long time to do it now.
*/
private fun clearUnwantedVariableModels() {
val trustedListOfModels = ClassFieldManagerFacade(context).findTrustedModels()
valueByUtModelWrapper
.filterNot { it.key in trustedListOfModels }
.forEach { valueByUtModelWrapper.remove(it.key) }
}
protected fun constructBeforeMethod(statements: List<CgStatement>): CgFrameworkUtilMethod {
val beforeAnnotation = addAnnotation(context.testFramework.beforeMethodId, Method)
return CgFrameworkUtilMethod(
name = "setUp",
statements = statements,
exceptions = emptySet(),
annotations = listOf(beforeAnnotation),
)
}
protected fun constructAfterMethod(statements: List<CgStatement>): CgFrameworkUtilMethod {
val afterAnnotation = addAnnotation(context.testFramework.afterMethodId, Method)
return CgFrameworkUtilMethod(
name = "tearDown",
statements = statements,
exceptions = setOf(Exception::class.id),
annotations = listOf(afterAnnotation),
)
}
} | 398 | Kotlin | 32 | 91 | abb62682c70d7d2ecc4ad610851d304f7ad716e4 | 5,627 | UTBotJava | Apache License 2.0 |
publishing-sdk/src/test/java/com/ably/tracking/publisher/workerqueue/workers/DisconnectSuccessWorkerTest.kt | ably | 313,556,297 | false | null | package com.ably.tracking.publisher.workerqueue.workers
import com.ably.tracking.Accuracy
import com.ably.tracking.EnhancedLocationUpdate
import com.ably.tracking.LocationUpdate
import com.ably.tracking.LocationUpdateType
import com.ably.tracking.Resolution
import com.ably.tracking.TrackableState
import com.ably.tracking.common.Ably
import com.ably.tracking.common.ConnectionState
import com.ably.tracking.common.ConnectionStateChange
import com.ably.tracking.publisher.PublisherInteractor
import com.ably.tracking.publisher.PublisherProperties
import com.ably.tracking.publisher.Trackable
import com.ably.tracking.publisher.workerqueue.WorkerSpecification
import com.ably.tracking.test.common.anyLocation
import com.google.common.truth.Truth.assertThat
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runTest
import org.junit.Test
@ExperimentalCoroutinesApi
class DisconnectSuccessWorkerTest {
private val trackable = Trackable("testtrackable")
private val otherTrackable = Trackable("other-trackable")
private val recalculateResolutionCallbackFunction = mockk<() -> Unit>(relaxed = true)
private val publisherInteractor = mockk<PublisherInteractor> {
every { updateTrackables(any()) } just runs
every { updateTrackableStateFlows(any()) } just runs
every { notifyResolutionPolicyThatTrackableWasRemoved(any()) } just runs
every { removeAllSubscribers(any(), any()) } just runs
every { stopLocationUpdates(any()) } just runs
every { removeCurrentDestination(any()) } just runs
every { notifyResolutionPolicyThatActiveTrackableHasChanged(any()) } just runs
}
private val ably: Ably = mockk {
coEvery { stopConnection() } returns Result.success(Unit)
}
private val worker = DisconnectSuccessWorker(
trackable,
publisherInteractor,
recalculateResolutionCallbackFunction,
ably
)
private val asyncWorks = mutableListOf<suspend () -> Unit>()
private val postedWorks = mutableListOf<WorkerSpecification>()
@Test
fun `should remove the trackable from the tracked trackables`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.trackables).doesNotContain(trackable)
}
@Test
fun `should remove the trackable state flow`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.trackableStateFlows[trackable.id] = MutableStateFlow(TrackableState.Offline())
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.trackableStateFlows).isEmpty()
}
@Test
fun `should remove the trackable state`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.trackableStates[trackable.id] = TrackableState.Offline()
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.trackableStates).isEmpty()
}
@Test
fun `should remove the trackable resolution`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.resolutions[trackable.id] = Resolution(Accuracy.BALANCED, 1L, 1.0)
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.resolutions).isEmpty()
}
@Test
fun `should call the location engine resolution recalculation callback if this trackable had a resolution`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.resolutions[trackable.id] = Resolution(Accuracy.BALANCED, 1L, 1.0)
// when
worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 1) {
recalculateResolutionCallbackFunction.invoke()
}
}
@Test
fun `should not call the location engine resolution recalculation callback if this trackable didn't have a resolution`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.resolutions.clear()
// when
worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 0) {
recalculateResolutionCallbackFunction.invoke()
}
}
@Test
fun `should remove the trackable resolution requests`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.requests[trackable.id] = mutableMapOf()
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.requests).isEmpty()
}
@Test
fun `should remove the trackable last sent enhanced location`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.lastSentEnhancedLocations[trackable.id] = anyLocation()
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.lastSentEnhancedLocations).isEmpty()
}
@Test
fun `should remove the trackable last sent raw location`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.lastSentRawLocations[trackable.id] = anyLocation()
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.lastSentRawLocations).isEmpty()
}
@Test
fun `should remove the trackable last channel connection state change`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.lastChannelConnectionStateChanges[trackable.id] =
ConnectionStateChange(ConnectionState.OFFLINE, null)
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.lastChannelConnectionStateChanges).isEmpty()
}
@Test
fun `should update the trackables in the publisher`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 1) {
publisherInteractor.updateTrackables(updatedProperties)
}
}
@Test
fun `should update the trackable state flows in the publisher`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 1) {
publisherInteractor.updateTrackableStateFlows(updatedProperties)
}
}
@Test
fun `should notify the resolution policy that a trackable was removed`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
// when
worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 1) {
publisherInteractor.notifyResolutionPolicyThatTrackableWasRemoved(trackable)
}
}
@Test
fun `should remove all saved subscribers for the removed trackable`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 1) {
publisherInteractor.removeAllSubscribers(trackable, updatedProperties)
}
}
@Test
fun `should clear all skipped enhanced locations for the removed trackable`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.skippedEnhancedLocations.add(trackable.id, anyLocation())
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.skippedEnhancedLocations.toList(trackable.id)).isEmpty()
}
@Test
fun `should clear all skipped raw locations for the removed trackable`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.skippedRawLocations.add(trackable.id, anyLocation())
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.skippedRawLocations.toList(trackable.id)).isEmpty()
}
@Test
fun `should clear the enhanced locations publishing state for the removed trackable`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.enhancedLocationsPublishingState.markMessageAsPending(trackable.id)
val locationUpdateEvent =
EnhancedLocationUpdate(anyLocation(), emptyList(), emptyList(), LocationUpdateType.ACTUAL)
initialProperties.enhancedLocationsPublishingState.addToWaiting(trackable.id, locationUpdateEvent)
initialProperties.enhancedLocationsPublishingState.maxOutRetryCount(trackable.id)
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.enhancedLocationsPublishingState.hasPendingMessage(trackable.id)).isFalse()
assertThat(updatedProperties.enhancedLocationsPublishingState.getNextWaiting(trackable.id)).isNull()
assertThat(updatedProperties.enhancedLocationsPublishingState.shouldRetryPublishing(trackable.id)).isTrue()
}
@Test
fun `should clear the raw locations publishing state for the removed trackable`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.rawLocationsPublishingState.markMessageAsPending(trackable.id)
val locationUpdateEvent = LocationUpdate(anyLocation(), emptyList())
initialProperties.rawLocationsPublishingState.addToWaiting(trackable.id, locationUpdateEvent)
initialProperties.rawLocationsPublishingState.maxOutRetryCount(trackable.id)
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.rawLocationsPublishingState.hasPendingMessage(trackable.id)).isFalse()
assertThat(updatedProperties.rawLocationsPublishingState.getNextWaiting(trackable.id)).isNull()
assertThat(updatedProperties.rawLocationsPublishingState.shouldRetryPublishing(trackable.id)).isTrue()
}
fun `should post TrackableRemovalSuccess work on completion`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.trackableStateFlows[trackable.id] = MutableStateFlow(TrackableState.Offline())
// when
worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
val postedWork = postedWorks[0] as WorkerSpecification.TrackableRemovalSuccess
assertThat(postedWork.trackable).isEqualTo(trackable)
assertThat(postedWork.result.isSuccess).isTrue()
}
fun `should post TrackableRemovalSuccess work on error`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.trackableStateFlows[trackable.id] = MutableStateFlow(TrackableState.Offline())
// when
val exception = Exception("error")
worker.onUnexpectedError(
exception,
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
val postedWork = postedWorks[0] as WorkerSpecification.TrackableRemovalSuccess
assertThat(postedWork.trackable).isEqualTo(trackable)
assertThat(postedWork.result.isSuccess).isFalse()
assertThat(postedWork.result.exceptionOrNull()).isEqualTo(exception)
}
@Test
fun `should clear the active trackable if the removed trackable was the active one`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.active = trackable
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.active).isNull()
}
@Test
fun `should remove the current destination if the removed trackable was the active one`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.active = trackable
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 1) {
publisherInteractor.removeCurrentDestination(updatedProperties)
}
}
@Test
fun `should notify the Resolution Policy that there is no active trackable the removed trackable was the active one`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.active = trackable
// when
worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 1) {
publisherInteractor.notifyResolutionPolicyThatActiveTrackableHasChanged(null)
}
}
@Test
fun `should not clear the active trackable if the removed trackable was not the active one`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.active = otherTrackable
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
assertThat(updatedProperties.active).isEqualTo(otherTrackable)
}
@Test
fun `should not remove the current destination if the removed trackable was not the active one`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.active = otherTrackable
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 0) {
publisherInteractor.removeCurrentDestination(updatedProperties)
}
}
@Test
fun `should not notify the Resolution Policy that there is no active trackable if the removed trackable was not the active one`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.active = otherTrackable
// when
worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 0) {
publisherInteractor.notifyResolutionPolicyThatActiveTrackableHasChanged(null)
}
}
@Test
fun `should stop location updates if the removed trackable was the last one and the publisher is currently tracking`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.trackables.remove(otherTrackable)
initialProperties.isTracking = true
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(postedWorks).hasSize(1)
verify(exactly = 1) {
publisherInteractor.stopLocationUpdates(updatedProperties)
}
}
@Test
fun `should not stop location updates if the removed trackable was not the last one`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.isTracking = true
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(asyncWorks).isEmpty()
assertThat(postedWorks).hasSize(1)
verify(exactly = 0) {
publisherInteractor.stopLocationUpdates(updatedProperties)
}
}
@Test
fun `should not stop location updates if the publisher is not currently tracking`() {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.trackables.remove(otherTrackable)
initialProperties.isTracking = false
// when
val updatedProperties = worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
// then
assertThat(postedWorks).hasSize(1)
verify(exactly = 0) {
publisherInteractor.stopLocationUpdates(updatedProperties)
}
}
@Test
fun `should stop ably and post StoppingConnectionFinished work if the removed trackable was the last one`() =
runTest {
// given
val initialProperties = createPublisherPropertiesWithMultipleTrackables()
initialProperties.trackables.remove(otherTrackable)
// when
worker.doWork(
initialProperties,
asyncWorks.appendWork(),
postedWorks.appendSpecification()
)
asyncWorks.executeAll()
// then
assertThat(asyncWorks).hasSize(1)
assertThat(postedWorks).hasSize(2)
val postedWorker = postedWorks[1]
coVerify(exactly = 1) {
ably.stopConnection()
}
assertThat(postedWorker).isEqualTo(WorkerSpecification.StoppingConnectionFinished)
}
private fun createPublisherPropertiesWithMultipleTrackables(): PublisherProperties {
val properties = createPublisherProperties()
properties.trackables.add(trackable)
properties.trackables.add(otherTrackable)
return properties
}
}
| 93 | null | 6 | 9 | dca56bac165ebc1474cf2afb863728c2aad4aeb4 | 23,407 | ably-asset-tracking-android | Apache License 2.0 |
desktop/src/main/kotlin/nebulosa/desktop/logic/atlas/provider/ephemeris/AbstractEphemerisProvider.kt | tiagohm | 568,578,345 | false | null | package nebulosa.desktop.logic.atlas.provider.ephemeris
import nebulosa.desktop.view.atlas.DateTimeProvider
import nebulosa.horizons.HorizonsEphemeris
import nebulosa.horizons.HorizonsQuantity
import nebulosa.log.loggerFor
import nebulosa.nova.position.GeographicPosition
import nebulosa.time.UTC
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.OffsetDateTime
abstract class AbstractEphemerisProvider<T> : EphemerisProvider<T> {
private val ephemerisCache = hashMapOf<GeographicPosition, MutableMap<T, HorizonsEphemeris>>()
abstract val timeBucket: TimeBucket
abstract fun compute(
target: T,
position: GeographicPosition,
timeSpan: List<Pair<UTC, LocalDateTime>>,
vararg quantities: HorizonsQuantity,
): HorizonsEphemeris?
final override fun compute(
target: T,
position: GeographicPosition,
dateTimeProvider: DateTimeProvider,
force: Boolean,
vararg quantities: HorizonsQuantity,
): HorizonsEphemeris? {
val date = dateTimeProvider.date
val timeOffset = dateTimeProvider.timeOffset
val offsetInSeconds = timeOffset.totalSeconds.toLong()
val now = OffsetDateTime.of(date, LocalTime.now(timeOffset), timeOffset)
val isToday = LocalDate.now(timeOffset).compareTo(date) == 0
val startTime = if (!isToday || now.hour >= 12) LocalDateTime.of(date, NOON).minusSeconds(offsetInSeconds)
else LocalDateTime.of(date, NOON).minusDays(1L).minusSeconds(offsetInSeconds)
if (position !in ephemerisCache) ephemerisCache[position] = hashMapOf()
return if (timeBucket.compute(force, startTime)
|| target !in ephemerisCache[position]!!
|| startTime != ephemerisCache[position]!![target]!!.start
) {
val endTime = timeBucket.last().second
LOG.info("retrieving ephemeris from JPL Horizons. target={}, startTime={}, endTime={}, force={}", target, startTime, endTime, force)
compute(target, position, timeBucket, *quantities)
?.also { ephemerisCache[position]!![target] = it }
} else {
ephemerisCache[position]!![target]
}
}
companion object {
@JvmStatic private val LOG = loggerFor<AbstractEphemerisProvider<*>>()
@JvmStatic private val NOON = LocalTime.of(12, 0, 0, 0)
}
}
| 2 | Kotlin | 0 | 2 | 9ccdfa8049d8ff034d282c065e71aec1a6ea6ab8 | 2,429 | nebulosa | MIT License |
core/descriptors/src/org/jetbrains/kotlin/types/TypeParameterErasureOptions.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.types
class TypeParameterErasureOptions(
val leaveNonTypeParameterTypes: Boolean,
val intersectUpperBounds: Boolean,
)
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 367 | kotlin | Apache License 2.0 |
libs/docker-client/src/main/kotlin/batect/docker/build/buildkit/services/HealthService.kt | viniciussalmeida | 330,515,605 | true | {"Kotlin": 3777014, "Python": 32167, "Groovy": 27495, "Shell": 22487, "PowerShell": 6949, "Dockerfile": 5467, "Batchfile": 3234, "Java": 1421, "HTML": 745} | /*
Copyright 2017-2021 Charles Korn.
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 batect.docker.build.buildkit.services
import com.squareup.wire.MessageSink
import io.grpc.health.v1.HealthBlockingServer
import io.grpc.health.v1.HealthCheckRequest
import io.grpc.health.v1.HealthCheckResponse
class HealthService : HealthBlockingServer, ServiceWithEndpointMetadata {
override fun Check(request: HealthCheckRequest): HealthCheckResponse {
return HealthCheckResponse(HealthCheckResponse.ServingStatus.SERVING)
}
override fun Watch(request: HealthCheckRequest, response: MessageSink<HealthCheckResponse>) {
throw UnsupportedGrpcMethodException(HealthBlockingServer::Watch.path)
}
override fun getEndpoints(): Map<String, Endpoint<*, *>> {
return mapOf(
HealthBlockingServer::Check.path to Endpoint(::Check, HealthCheckRequest.ADAPTER, HealthCheckResponse.ADAPTER)
)
}
}
| 0 | null | 0 | 0 | 1013e57de23f9b493606fb246264a44d4a13b048 | 1,460 | batect | Apache License 2.0 |
main/src/main/kotlin/siliconsloth/miniruler/engine/TimelineRecorder.kt | SiliconSloth | 229,996,790 | false | {"Gradle Kotlin DSL": 4, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 1, "Java": 77, "INI": 1, "Kotlin": 65} | package siliconsloth.miniruler.engine
import com.beust.klaxon.JsonObject
import siliconsloth.miniruler.engine.bindings.AggregateBinding
import siliconsloth.miniruler.engine.bindings.Binding
import siliconsloth.miniruler.engine.bindings.InvertedBinding
import siliconsloth.miniruler.engine.bindings.SimpleBinding
import siliconsloth.miniruler.engine.matching.CompleteMatch
import java.io.File
class TimelineRecorder(outputPath: String) {
val writer = File(outputPath).bufferedWriter()
var timestep = 0
init {
Runtime.getRuntime().addShutdownHook(object : Thread() {
override fun run() {
writer.close()
}
})
}
fun tick() =
timestep++
fun recordMatchState(match: CompleteMatch) {
val fields = mutableMapOf<String, Any>(
"type" to "match",
"id" to match.id,
"state" to match.state,
"time" to timestep
)
if (match.state == CompleteMatch.State.MATCHED) {
fields["rule"] = match.rule.name
fields["bindings"] = match.rule.bindings.zip(match.bindValues) { b,v -> serializeBinding(b,v) }
}
writeObject(fields)
}
fun recordUpdate(update: RuleEngine.Update<*>) {
val fields = mutableMapOf<String, Any>(
"type" to "fact",
"class" to (update.fact::class.simpleName ?: "null"),
"fact" to update.fact.toString(),
"insert" to update.isInsert,
"maintain" to update.maintain,
"time" to timestep
)
update.producer?.let { fields["producer"] = it.id }
writeObject(fields)
}
fun serializeBinding(binding: Binding<*,*>, value: Any?): Any? =
when (binding) {
is SimpleBinding<*> -> value.toString()
is InvertedBinding<*> -> null
is AggregateBinding<*> -> (value as Iterable<*>).map { it.toString() }
else -> error("Unknown binding class: ${binding::class}")
}
fun writeObject(fields: Map<String, Any?>) {
writer.write(JsonObject(fields).toJsonString()+"\n")
}
} | 1 | null | 1 | 1 | 2c30a2a9d92385f2015b63f1fadb683e3edcddfc | 2,215 | MiniRuler | MIT License |
app/src/main/java/com/kssidll/arru/ui/screen/modify/product/ModifyProductViewModel.kt | KSSidll | 655,360,420 | false | null | package com.kssidll.arru.ui.screen.modify.product
import androidx.compose.runtime.*
import androidx.lifecycle.*
import com.kssidll.arru.data.data.*
import com.kssidll.arru.data.repository.*
import com.kssidll.arru.domain.data.*
import com.kssidll.arru.ui.screen.modify.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
/**
* Base [ViewModel] class for Product modification view models
* @property screenState A [ModifyProductScreenState] instance to use as screen state representation
*/
abstract class ModifyProductViewModel: ViewModel() {
protected abstract val productRepository: ProductRepositorySource
protected abstract val producerRepository: ProducerRepositorySource
protected abstract val categoryRepository: CategoryRepositorySource
internal val screenState: ModifyProductScreenState = ModifyProductScreenState()
private var mProducerListener: Job? = null
private var mCategoryListener: Job? = null
suspend fun setSelectedProducer(providedProducerId: Long?) {
if (providedProducerId != null) {
screenState.selectedProductProducer.apply { value = value.toLoading() }
onNewProducerSelected(producerRepository.get(providedProducerId))
}
}
suspend fun setSelectedCategory(providedCategoryId: Long?) {
if (providedCategoryId != null) {
screenState.selectedProductCategory.apply { value = value.toLoading() }
onNewCategorySelected(categoryRepository.get(providedCategoryId))
}
}
fun onNewProducerSelected(producer: ProductProducer?) {
screenState.selectedProductProducer.value = Field.Loaded(producer)
mProducerListener?.cancel()
if (producer != null) {
mProducerListener = viewModelScope.launch {
producerRepository.getFlow(producer.id)
.collectLatest {
screenState.selectedProductProducer.value = Field.Loaded(it)
}
}
}
}
fun onNewCategorySelected(category: ProductCategory?) {
screenState.selectedProductCategory.value = Field.Loaded(category)
mCategoryListener?.cancel()
if (category != null) {
mCategoryListener = viewModelScope.launch {
categoryRepository.getFlow(category.id)
.collectLatest {
screenState.selectedProductCategory.value = Field.Loaded(it)
}
}
}
}
/**
* @return List of all categories
*/
fun allCategories(): Flow<List<ProductCategoryWithAltNames>> {
return categoryRepository.allWithAltNamesFlow()
}
/**
* @return List of all producers
*/
fun allProducers(): Flow<List<ProductProducer>> {
return producerRepository.allFlow()
}
}
/**
* Data representing [ModifyProductScreenImpl] screen state
*/
data class ModifyProductScreenState(
val selectedProductCategory: MutableState<Field<ProductCategory>> = mutableStateOf(Field.Loaded()),
val selectedProductProducer: MutableState<Field<ProductProducer?>> = mutableStateOf(Field.Loaded()),
val name: MutableState<Field<String>> = mutableStateOf(Field.Loaded()),
val isCategorySearchDialogExpanded: MutableState<Boolean> = mutableStateOf(false),
val isProducerSearchDialogExpanded: MutableState<Boolean> = mutableStateOf(false),
): ModifyScreenState() | 0 | null | 0 | 4 | ff3f257a0604a6d9e5169dc47753094c9b0c9520 | 3,438 | Arru | BSD 3-Clause Clear License |
src/main/kotlin/org/sol4k/Convert.kt | sol4k | 595,734,363 | false | {"Kotlin": 98172} | package org.sol4k
import java.math.BigDecimal
import java.math.RoundingMode
object Convert {
@JvmStatic
fun lamportToSol(v: String): BigDecimal =
lamportToSol(BigDecimal(v))
@JvmStatic
fun lamportToSol(v: BigDecimal): BigDecimal =
v.divide(BigDecimal.TEN.pow(9)).setScale(9, RoundingMode.CEILING)
@JvmStatic
fun solToLamport(v: String): BigDecimal =
solToLamport(BigDecimal(v))
@JvmStatic
fun solToLamport(v: BigDecimal): BigDecimal =
v.multiply(BigDecimal.TEN.pow(9))
@JvmStatic
fun microToLamport(v: BigDecimal): BigDecimal =
v.divide(BigDecimal.TEN.pow(6))
@JvmStatic
fun lamportToMicro(v: BigDecimal): BigDecimal =
v.multiply(BigDecimal.TEN.pow(6))
}
| 6 | Kotlin | 16 | 53 | 6f56e80dbfe76d83a4d5d54daa3712e08a0c5ef1 | 758 | sol4k | Apache License 2.0 |
AtomicKotlin/Power Tools/Creating Generics/Examples/src/DefiningGenerics.kt | fatiq123 | 726,462,263 | false | {"Kotlin": 370528, "HTML": 6544, "JavaScript": 5252, "Java": 4416, "CSS": 3780, "Assembly": 94} | // CreatingGenerics/DefiningGenerics.kt
package creatinggenerics
fun <T> gFunction(arg: T): T = arg
class GClass<T>(val x: T) {
fun f(): T = x
}
class GMemberFunction {
fun <T> f(arg: T): T = arg
}
interface GInterface<T> {
val x: T
fun f(): T
}
class GImplementation<T>(
override val x: T
) : GInterface<T> {
override fun f(): T = x
}
class ConcreteImplementation
: GInterface<String> {
override val x: String
get() = "x"
override fun f() = "f()"
}
fun basicGenerics() {
gFunction("Yellow")
gFunction(1)
gFunction(Dog()).bark() // [1]
gFunction<Dog>(Dog()).bark()
GClass("Cyan").f()
GClass(11).f()
GClass(Dog()).f().bark() // [2]
GClass<Dog>(Dog()).f().bark()
GMemberFunction().f("Amber")
GMemberFunction().f(111)
GMemberFunction().f(Dog()).bark() // [3]
GMemberFunction().f<Dog>(Dog()).bark()
GImplementation("Cyan").f()
GImplementation(11).f()
GImplementation(Dog()).f().bark()
ConcreteImplementation().f()
ConcreteImplementation().x
} | 0 | Kotlin | 0 | 0 | 3d351652ebe1dd7ef5f93e054c8f2692c89a144e | 1,027 | AtomicKotlinCourse | MIT License |
src/main/kotlin/au/jamal/instabiobot/instagram/InstagramInterface.kt | Jamal135 | 783,196,993 | false | {"Kotlin": 15332, "Shell": 369} | package au.jamal.instabiobot.instagram
import au.jamal.instabiobot.utilities.Log
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait
class InstagramInterface(session: BrowserManager) {
private val wait: WebDriverWait = session.wait
fun getUsernameElement(): WebElement {
return getElement(By::cssSelector, "input[name='username']")
}
fun getPasswordElement(): WebElement {
return getElement(By::cssSelector, "input[name='password']")
}
fun getLoginElement(): WebElement {
return getElement(By::xpath, "//button[@type='submit']")
}
fun getBioElement(): WebElement {
return getElement(By::cssSelector, "textarea[id='pepBio']")
}
fun getUpdateElement(): WebElement {
return getElement(By::xpath, "//*[contains(text(), 'Submit')]")
}
fun getBioTextAttribute(): String {
val bioElement = getBioElement()
return getValue(bioElement)
}
fun getUpdateButtonStatus(): Boolean {
val updateElement = getUpdateElement() // If span means submit button non-interactable
return updateElement.tagName.equals("span", ignoreCase = true)
}
private fun getElement(selector: (String) -> By, expression: String): WebElement {
try {
val locator: By = selector(expression)
return wait.until(
ExpectedConditions.presenceOfElementLocated(locator)
)
} catch (e: Exception) {
Log.alert("Failed to access element: [$selector, $expression]")
throw IllegalStateException("Failed to get element...", e)
}
}
private fun getValue(element: WebElement): String {
try {
return element.getAttribute("value") ?: throw IllegalStateException("Null attribute")
} catch (e: Exception) {
Log.alert("Failed to access attribute [value]")
Log.dump(element)
throw IllegalStateException("Failed to get attribute...", e)
}
}
} | 0 | Kotlin | 0 | 0 | aea5462c32df32762fdaf31a4b9ff293a361f670 | 2,133 | InstaBioBot | MIT License |
src/main/kotlin/com/ecwid/apiclient/v3/dto/coupon/request/CouponCreateRequest.kt | alf-ecwid | 267,801,795 | true | {"Kotlin": 412279} | package com.ecwid.apiclient.v3.dto.coupon.request
import com.ecwid.apiclient.v3.dto.ApiRequest
import com.ecwid.apiclient.v3.httptransport.HttpBody
import com.ecwid.apiclient.v3.impl.RequestInfo
data class CouponCreateRequest(
var newCoupon: UpdatedCoupon = UpdatedCoupon()
) : ApiRequest {
override fun toRequestInfo() = RequestInfo.createPostRequest(
endpoint = "discount_coupons",
httpBody = HttpBody.JsonBody(
obj = newCoupon
)
)
}
| 0 | null | 0 | 0 | 1eb037cdc7504b10cc3a417e4799d0ad977214af | 456 | ecwid-java-api-client | Apache License 2.0 |
commons/src/main/java/com/anp/commons/helpers/HelperApp.kt | antocara | 113,018,839 | false | null | package com.anp.commons.helpers
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import com.anp.commons.Constants
import com.anp.commons.data.entities.AppInfo
object HelperApp {
fun getVersionInfo(context: Context): AppInfo {
var versionName = ""
var versionCode = -1
try {
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
versionName = packageInfo.versionName
versionCode = packageInfo.versionCode
} catch (e: PackageManager.NameNotFoundException) {
Log.d(Constants.APP_NAME, "Error retrieving app info")
}
return AppInfo(versionName, versionCode)
}
} | 1 | Kotlin | 24 | 31 | 58e6dc4bc9c55302f3beafa2cc187f47394f1184 | 690 | iptvManagement | The Unlicense |
android/modules/module_ops/src/main/java/github/tornaco/thanos/android/ops/ops/dashboard/OpsDashboardScreen.kt | Tornaco | 228,014,878 | false | null | package github.tornaco.thanos.android.ops.ops.dashboard
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.google.android.material.composethemeadapter3.Mdc3Theme
import github.tornaco.android.thanos.widget.pie.CenterText
import github.tornaco.android.thanos.widget.pie.ChartItem
import github.tornaco.android.thanos.widget.pie.Legend
import github.tornaco.android.thanos.widget.pie.PieChart
@Composable
fun OpsDashboardScreen() {
Mdc3Theme {
Surface {
OpsDashboardContent()
}
}
}
@Composable
private fun OpsDashboardContent() {
val viewModel = hiltViewModel<OpsDashboardViewModel>()
Column(modifier = Modifier.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = viewModel.toString())
Spacer(modifier = Modifier.size(64.dp))
val items = listOf(
ChartItem("",
color = Color(0xFFE57600),
value = 1,
label = "Contacts"),
ChartItem("",
color = Color(0xFF4485AA),
value = 2,
label = "Camera"),
ChartItem("", color = Color(0xFF94E287),
value = 3,
label = "External Photos"),
ChartItem("", color = Color(0xFF0093E5),
value = 6,
label = "Device Id"),
ChartItem("", color = Color(0xFFB446C8),
value = 4,
label = "Audio recorder"),
ChartItem("", color = Color(0xFF5A5AE6), value = 4, label = "Vib"),
)
PieChart(modifier = Modifier
.fillMaxWidth(0.6f)
.aspectRatio(1f),
strokeSize = 38.dp,
chartItems = items,
centerText = CenterText(
text = "Thanox",
color = Color.DarkGray,
size = 24.dp
))
Spacer(modifier = Modifier.size(32.dp))
Legend(
modifier = Modifier
.fillMaxWidth(0.6f)
.padding(32.dp),
chartItems = items,
columnCount = 1,
)
}
}
| 239 | Java | 26 | 509 | 2c3531b7c2f23a1cabc7d0de2131257c57ff920b | 2,469 | Thanox | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/CloudMeatball.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.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.rounded.Icons
public val Icons.Outline.CloudMeatball: ImageVector
get() {
if (_cloudMeatball != null) {
return _cloudMeatball!!
}
_cloudMeatball = Builder(name = "CloudMeatball", 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) {
moveToRelative(20.0f, 22.5f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
close()
moveTo(4.5f, 21.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(17.974f, 5.146f)
curveToRelative(-0.332f, -0.066f, -0.603f, -0.274f, -0.742f, -0.569f)
curveTo(15.681f, 1.306f, 12.089f, -0.519f, 8.497f, 0.137f)
curveTo(5.226f, 0.736f, 2.66f, 3.349f, 2.113f, 6.639f)
curveToRelative(-0.162f, 0.97f, -0.15f, 1.942f, 0.033f, 2.89f)
curveToRelative(0.06f, 0.308f, -0.072f, 0.653f, -0.345f, 0.901f)
curveToRelative(-1.145f, 1.041f, -1.801f, 2.524f, -1.801f, 4.07f)
curveToRelative(0.0f, 2.586f, 1.759f, 4.792f, 4.278f, 5.364f)
curveToRelative(0.075f, 0.017f, 0.149f, 0.025f, 0.223f, 0.025f)
curveToRelative(0.457f, 0.0f, 0.869f, -0.314f, 0.974f, -0.778f)
curveToRelative(0.123f, -0.539f, -0.215f, -1.075f, -0.753f, -1.197f)
curveToRelative(-1.577f, -0.358f, -2.722f, -1.794f, -2.722f, -3.414f)
curveToRelative(0.0f, -0.984f, 0.418f, -1.928f, 1.146f, -2.591f)
curveToRelative(0.786f, -0.714f, 1.155f, -1.772f, 0.963f, -2.761f)
curveToRelative(-0.138f, -0.712f, -0.146f, -1.446f, -0.024f, -2.181f)
curveToRelative(0.403f, -2.422f, 2.365f, -4.421f, 4.771f, -4.862f)
curveToRelative(2.745f, -0.504f, 5.385f, 0.835f, 6.567f, 3.329f)
curveToRelative(0.414f, 0.872f, 1.2f, 1.482f, 2.158f, 1.673f)
curveToRelative(2.56f, 0.511f, 4.417f, 2.779f, 4.417f, 5.394f)
curveToRelative(0.0f, 2.228f, -1.329f, 4.221f, -3.385f, 5.079f)
curveToRelative(-0.51f, 0.212f, -0.751f, 0.798f, -0.538f, 1.308f)
curveToRelative(0.212f, 0.51f, 0.799f, 0.753f, 1.308f, 0.538f)
curveToRelative(2.804f, -1.169f, 4.615f, -3.887f, 4.615f, -6.924f)
curveToRelative(0.0f, -3.565f, -2.534f, -6.658f, -6.026f, -7.354f)
close()
moveTo(14.927f, 18.07f)
curveToRelative(0.299f, -0.566f, 0.231f, -1.275f, -0.246f, -1.751f)
curveToRelative(-0.477f, -0.477f, -1.185f, -0.545f, -1.751f, -0.246f)
curveToRelative(-0.185f, -0.619f, -0.752f, -1.073f, -1.431f, -1.073f)
reflectiveCurveToRelative(-1.246f, 0.454f, -1.431f, 1.073f)
curveToRelative(-0.566f, -0.299f, -1.274f, -0.231f, -1.751f, 0.246f)
curveToRelative(-0.477f, 0.476f, -0.545f, 1.185f, -0.246f, 1.751f)
curveToRelative(-0.619f, 0.185f, -1.072f, 0.752f, -1.072f, 1.431f)
reflectiveCurveToRelative(0.454f, 1.246f, 1.072f, 1.431f)
curveToRelative(-0.299f, 0.566f, -0.231f, 1.275f, 0.246f, 1.751f)
curveToRelative(0.293f, 0.293f, 0.677f, 0.439f, 1.061f, 0.439f)
curveToRelative(0.241f, 0.0f, 0.472f, -0.078f, 0.69f, -0.194f)
curveToRelative(0.185f, 0.619f, 0.752f, 1.073f, 1.431f, 1.073f)
reflectiveCurveToRelative(1.246f, -0.454f, 1.431f, -1.073f)
curveToRelative(0.218f, 0.115f, 0.45f, 0.194f, 0.69f, 0.194f)
curveToRelative(0.384f, 0.0f, 0.768f, -0.146f, 1.061f, -0.439f)
curveToRelative(0.477f, -0.476f, 0.545f, -1.185f, 0.246f, -1.751f)
curveToRelative(0.619f, -0.185f, 1.072f, -0.752f, 1.072f, -1.431f)
reflectiveCurveToRelative(-0.454f, -1.246f, -1.072f, -1.431f)
close()
}
}
.build()
return _cloudMeatball!!
}
private var _cloudMeatball: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,386 | icons | MIT License |
appvox-appstore/src/main/kotlin/io/appvox/appstore/review/AppStoreReviewService.kt | fabiouu | 277,291,845 | false | null | //package io.appvox.appstore.review
//
//import io.appvox.appstore.review.domain.AppStoreReview
//import io.appvox.appstore.review.domain.AppStoreReviewRequestParameters
//import io.appvox.core.configuration.Constant.MAX_RETRY_ATTEMPTS
//import io.appvox.core.configuration.Constant.MIN_RETRY_DELAY
//import io.appvox.core.configuration.RequestConfiguration
//import io.appvox.core.review.ReviewRequest
//import io.appvox.core.review.ReviewService
//import io.appvox.core.util.retryRequest
//import kotlinx.coroutines.delay
//import kotlinx.coroutines.flow.Flow
//import kotlinx.coroutines.flow.flow
//
//internal class AppStoreReviewService(
// private val config: RequestConfiguration
//) : ReviewService<AppStoreReviewRequestParameters, AppStoreReviewResult.Entry, AppStoreReview> {
//
// private val appStoreReviewRepository = AppStoreReviewRepository(config)
//
// private val appStoreReviewConverter = AppStoreReviewConverter()
//
// override fun getReviewsByAppId(
// initialRequest: ReviewRequest<AppStoreReviewRequestParameters>
// ): Flow<AppStoreReview> = flow {
// var request = initialRequest
// do {
// val response = retryRequest(MAX_RETRY_ATTEMPTS, MIN_RETRY_DELAY) {
// appStoreReviewRepository.getReviewsByAppId(request)
// }
// request = request.copy(request.parameters, response.nextToken)
// response.results?.forEach { result ->
// val review = appStoreReviewConverter.toResponse(request.parameters, result)
// emit(review)
// }
// delay(timeMillis = config.delay.toLong())
// } while (request.nextToken != null && response.results != null)
// }
//}
| 0 | Kotlin | 1 | 5 | d99ea4dfed58eda2ff48cafd0d96bc0ad45e4ea2 | 1,730 | appvox | Apache License 2.0 |
core/base/src/commonMain/kotlin/app/tivi/util/Collections.kt | chrisbanes | 100,624,553 | false | null | /*
* 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 app.tivi.util
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.DEFAULT_CONCURRENCY
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flow
@OptIn(FlowPreview::class)
suspend fun <T> Collection<T>.parallelForEach(
concurrency: Int = DEFAULT_CONCURRENCY,
block: suspend (value: T) -> Unit,
) = asFlow()
.flatMapMerge(concurrency = concurrency) { item ->
flow {
block(item)
emit(Unit)
}
}
.collect()
| 20 | Kotlin | 792 | 5,749 | 5dc4d831fd801afab556165d547042c517f98875 | 1,183 | tivi | Apache License 2.0 |
app/src/main/java/com/github/qingmei2/opengl_demo/c_image_process/processor/C01ImageProcessor.kt | qingmei2 | 389,633,594 | false | {"Kotlin": 121582, "Java": 46901, "GLSL": 2366} | package com.github.qingmei2.opengl_demo.c_image_process.processor
import android.content.Context
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.opengl.GLES20
import android.opengl.GLUtils
import com.github.qingmei2.opengl_demo.R
import com.github.qingmei2.opengl_demo.c_image_process.ImageProcessor
import com.github.qingmei2.opengl_demo.loadShaderWithResource
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
class C01ImageProcessor(private val mContext: Context) : ImageProcessor {
//顶点坐标
private val vertexData = floatArrayOf(
-1.0f, -1.0f,
1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, 1.0f
)
// 纹理坐标需要和顶点坐标相反
// https://blog.csdn.net/zhangpengzp/article/details/89543108
private val textureData = floatArrayOf(
0.0f, 1.0f,
1.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f
)
// 不相反就会出错 ↓
// private val textureData = floatArrayOf(
// 0.0f, 0.0f,
// 1.0f, 0.0f,
// 0.0f, 1.0f,
// 1.0f, 1.0f
// )
private val mVertexBuffer: FloatBuffer
private val mTextureBuffer: FloatBuffer
private var mProgram: Int = 0
private var avPosition = 0
private var afPosition = 0
private var textureId = 0
init {
//初始化buffer
mVertexBuffer = ByteBuffer.allocateDirect(vertexData.size * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.put(vertexData)
mVertexBuffer.position(0)
mTextureBuffer = ByteBuffer.allocateDirect(textureData.size * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.put(textureData)
mTextureBuffer.position(0)
}
override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
mProgram = loadShaderWithResource(
mContext,
R.raw.viewport_vertex_shader,
R.raw.viewport_fragment_shader
)
avPosition = GLES20.glGetAttribLocation(mProgram, "av_Position")
afPosition = GLES20.glGetAttribLocation(mProgram, "af_Position")
//生成纹理
val textureIds = IntArray(1)
GLES20.glGenTextures(1, textureIds, 0)
if (textureIds[0] == 0) {
return
}
textureId = textureIds[0]
//绑定纹理
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId)
//环绕方式
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT)
//过滤方式
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
val bitmap = BitmapFactory.decodeResource(mContext.resources, R.drawable.women_h)
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0)
bitmap.recycle()
}
override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
//设置大小位置
GLES20.glViewport(0, 0, width, height)
}
override fun onDrawFrame(gl: GL10) {
//清屏,清理掉颜色的缓冲区
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
//设置清屏的颜色,这里是float颜色的取值范围的[0,1]
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f)
//使用program
GLES20.glUseProgram(mProgram)
//设置为可用的状态
GLES20.glEnableVertexAttribArray(avPosition)
//size 指定每个顶点属性的组件数量。必须为1、2、3或者4。初始值为4。(如position是由3个(x,y,z)组成,而颜色是4个(r,g,b,a))
//stride 指定连续顶点属性之间的偏移量。如果为0,那么顶点属性会被理解为:它们是紧密排列在一起的。初始值为0。
//size 2 代表(x,y),stride 8 代表跨度 (2个点为一组,2个float有8个字节)
GLES20.glVertexAttribPointer(avPosition, 2, GLES20.GL_FLOAT, false, 8, mVertexBuffer)
GLES20.glEnableVertexAttribArray(afPosition);
GLES20.glVertexAttribPointer(afPosition, 2, GLES20.GL_FLOAT, false, 8, mTextureBuffer)
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
}
}
| 0 | Kotlin | 15 | 32 | 3bf1474ab254fb81d30a2617884380a1aca8ff70 | 4,121 | OpenGL-demo | MIT License |
ocpp-2-0-core/src/main/kotlin/com/izivia/ocpp/core20/model/installcertificate/enumeration/InstallCertificateStatusEnumType.kt | IZIVIA | 501,708,979 | false | {"Kotlin": 1934096} | package com.izivia.ocpp.core20.model.installcertificate.enumeration
enum class InstallCertificateStatusEnumType(val value : String) {
Accepted("Accepted"),
Rejected("Rejected"),
Failed("Failed")
}
| 6 | Kotlin | 10 | 32 | bd8e7334ae05ea75d02d96a508269acbe076bcd8 | 210 | ocpp-toolkit | MIT License |
domain/images/src/main/java/com/alexnechet/domain/images/model/Image.kt | alex-nechet | 634,167,292 | false | null | package com.alexnechet.domain.images.model
data class Image(
val id: Long,
val tags: String,
val previewUrl: String,
val largeImageUrl: String,
val views: Int,
val comments: Int,
val downloads: Int,
val collections: Int,
val likes: Int,
val userName: String,
val userImageUrl: String
) | 0 | Kotlin | 0 | 0 | 6adf90e68f20d413a4a20a960339ae5c26840fb6 | 330 | PixabayApp | MIT License |
kotlin-telegram-api/src/main/kotlin/ru/loginov/telegram/api/request/GetUpdatesRequest.kt | EdmonDantes | 529,398,328 | false | null | /*
* Copyright (c) 2022. <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.loginov.telegram.api.request
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
/**
* This object represents request for method [ru.loginov.telegram.api.TelegramAPI.getUpdates]
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class GetUpdatesRequest {
/**
* Identifier of the first update to be returned.
* Must be greater by one than the highest among the identifiers of previously received updates.
* By default, updates starting with the earliest unconfirmed update are returned.
* An update is considered confirmed as soon as [ru.loginov.telegram.api.TelegramAPI.getUpdates]
* is called with an [offset] higher than its [ru.loginov.telegram.api.entity.Update.id].
* The negative [offset] can be specified to retrieve updates starting from *-offset* update from
* the end of the updates queue. All previous updates will forgotten.
*/
@JsonProperty(value = "offset", required = false)
var offset: Long? = null
/**
* Limits the number of updates to be retrieved.
* Values between 1-100 are accepted. Defaults to 100.
*/
@JsonProperty(value = "limit", required = false)
var limit: Long? = null
/**
* Timeout in seconds for long polling.
* Defaults to 0, i.e. usual short polling.
* Should be positive, short polling should be used for testing purposes only.
*/
@JsonProperty(value = "timeout", required = false)
var timeoutSec: Long? = null
/**
* A JSON-serialized list of the update types you want your bot to receive.
* For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types.
* See Update for a complete list of available update types.
* Specify an empty list to receive all update types except chat_member (default).
* If not specified, the previous setting will be used.
*
* Please note that this parameter doesn't affect updates created before the call to the getUpdates,
* so unwanted updates may be received for a short period of time.
*/
@JsonProperty(value = "allowed_updates", required = false)
var allowedUpdates: List<String>? = null
} | 0 | Kotlin | 0 | 1 | a08c3fe6331043a503aced9cde0c580255ca99d2 | 3,088 | salary-bot | Apache License 2.0 |
app/src/main/java/com/vkochenkov/waifupictures/presentation/view_model/ViewModelFactory.kt | Kochenkov | 398,776,143 | false | null | package com.vkochenkov.waifupictures.presentation.view_model
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.vkochenkov.waifupictures.data.Repository
import com.vkochenkov.waifupictures.presentation.utils.NetworkChecker
import javax.inject.Inject
class ViewModelFactory @Inject constructor(private val repository: Repository,
private val networkChecker: NetworkChecker
) :
ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return when {
modelClass.isAssignableFrom(PicturesViewModel::class.java) -> {
PicturesViewModel(repository, networkChecker) as T
}
modelClass.isAssignableFrom(FavouritesViewModel::class.java) -> {
FavouritesViewModel(repository) as T
}
modelClass.isAssignableFrom(PictureViewModel::class.java) -> {
PictureViewModel(repository) as T
}
else -> {
throw IllegalArgumentException("Unknown ViewModel class")
}
}
}
} | 0 | Kotlin | 1 | 1 | 9ef066141eda60d393f62e6fa18062275cd1c9ce | 1,152 | AndroidApp-WaifuPictures | MIT License |
domain/src/main/kotlin/com/lomeone/domain/authentication/exception/OAuth2ProviderNotSupportedException.kt | lomeone | 583,942,276 | false | {"Kotlin": 105805, "Smarty": 1861} | package com.lomeone.domain.authentication.exception
import com.lomeone.util.exception.CustomException
import com.lomeone.util.exception.ExceptionCategory
class OAuth2ProviderNotSupportedException(
detail: Map<String, Any>
) : CustomException(
errorCode = ERROR_CODE,
message = MESSAGE,
exceptionCategory = ExceptionCategory.BAD_REQUEST,
detail = detail
) {
companion object {
const val ERROR_CODE = "authentication/oauth-provider-not-supported"
const val MESSAGE = "Not yet supported oauth2 provider"
}
}
| 4 | Kotlin | 0 | 0 | 610fe8147968a6d18db69d50c4546c64c14a5148 | 551 | lomeone-server | MIT License |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/codebuild/EnvironmentType.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.codebuild
public enum class EnvironmentType(
private val cdkObject: software.amazon.awscdk.services.codebuild.EnvironmentType,
) {
ARM_CONTAINER(software.amazon.awscdk.services.codebuild.EnvironmentType.ARM_CONTAINER),
LINUX_CONTAINER(software.amazon.awscdk.services.codebuild.EnvironmentType.LINUX_CONTAINER),
LINUX_GPU_CONTAINER(software.amazon.awscdk.services.codebuild.EnvironmentType.LINUX_GPU_CONTAINER),
WINDOWS_SERVER_2019_CONTAINER(software.amazon.awscdk.services.codebuild.EnvironmentType.WINDOWS_SERVER_2019_CONTAINER),
WINDOWS_SERVER_2022_CONTAINER(software.amazon.awscdk.services.codebuild.EnvironmentType.WINDOWS_SERVER_2022_CONTAINER),
MAC_ARM(software.amazon.awscdk.services.codebuild.EnvironmentType.MAC_ARM),
;
public companion object {
internal fun wrap(cdkObject: software.amazon.awscdk.services.codebuild.EnvironmentType):
EnvironmentType = when (cdkObject) {
software.amazon.awscdk.services.codebuild.EnvironmentType.ARM_CONTAINER ->
EnvironmentType.ARM_CONTAINER
software.amazon.awscdk.services.codebuild.EnvironmentType.LINUX_CONTAINER ->
EnvironmentType.LINUX_CONTAINER
software.amazon.awscdk.services.codebuild.EnvironmentType.LINUX_GPU_CONTAINER ->
EnvironmentType.LINUX_GPU_CONTAINER
software.amazon.awscdk.services.codebuild.EnvironmentType.WINDOWS_SERVER_2019_CONTAINER ->
EnvironmentType.WINDOWS_SERVER_2019_CONTAINER
software.amazon.awscdk.services.codebuild.EnvironmentType.WINDOWS_SERVER_2022_CONTAINER ->
EnvironmentType.WINDOWS_SERVER_2022_CONTAINER
software.amazon.awscdk.services.codebuild.EnvironmentType.MAC_ARM -> EnvironmentType.MAC_ARM
}
internal fun unwrap(wrapped: EnvironmentType):
software.amazon.awscdk.services.codebuild.EnvironmentType = wrapped.cdkObject
}
}
| 0 | Kotlin | 0 | 4 | 652b030da47fc795f7a987eba0f8c82f64035d24 | 2,065 | kotlin-cdk-wrapper | Apache License 2.0 |
game/src/commonMain/kotlin/io/itch/mattemade/blackcat/physics/Block.kt | mattemade | 821,007,625 | false | {"Kotlin": 84204, "JavaScript": 1066, "HTML": 312} | package io.itch.mattemade.blackcat.physics
import com.lehaine.littlekt.math.Rect
import io.itch.mattemade.utils.disposing.HasContext
import org.jbox2d.collision.shapes.PolygonShape
import org.jbox2d.dynamics.Body
import org.jbox2d.dynamics.BodyDef
import org.jbox2d.dynamics.BodyType
import org.jbox2d.dynamics.Filter
import org.jbox2d.dynamics.FixtureDef
import org.jbox2d.dynamics.World
class Block(world: World, val rect: Rect, friction: Float = 0.4f, userData: String? = null, filter: Filter.() -> Unit = {
categoryBits = ContactBits.ALL_NORMAL_BITS
maskBits = ContactBits.ALL_NORMAL_BITS
}): HasContext<Body> {
private val hx = rect.width / 2f
private val hy = rect.height / 2f
private val body = world.createBody(BodyDef(
type = BodyType.STATIC,
).apply {
position.set(rect.x + hx, rect.y + hy)
}).apply {
createFixture(FixtureDef(
shape = PolygonShape().apply {
setAsBox(hx, hy)
},
friction = friction,
filter = Filter().apply(filter),
userData = userData
))
}
override val context: Map<Any, Body> = mapOf(Body::type to body)
} | 0 | Kotlin | 0 | 0 | b65ad4d330e73c28f301d03c6b7251740bde0834 | 1,183 | black-cat-jam-1 | MIT License |
app/src/main/java/com/king/easychat/bean/Group.kt | yetel | 218,673,212 | false | null | package com.king.easychat.bean
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.Index
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize
/**
* @author: Zed
* date: 2019/08/22.
* description:
*/
@Entity(indices = [Index(value = ["groupId"], unique = true)])
@Parcelize
class Group(val groupId: String,var groupName: String,var avatar: String?,var mainUserId: String?) : Parcelable {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@Ignore var memberNum: Int = 0
fun getMemberNumber(): String{
return memberNum.toString()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Group
if (groupId != other.groupId) return false
return true
}
override fun hashCode(): Int {
return groupId.hashCode()
}
override fun toString(): String {
return "Group(groupId='$groupId', groupName='$groupName', avatar=$avatar, mainUserId=$mainUserId, memberNum=$memberNum, id=$id)"
}
}
| 4 | null | 50 | 146 | 393e334c8bb3a14e9d554e5187fbc88a0afc3d43 | 1,149 | EasyChatAndroidClient | Apache License 2.0 |
app/src/main/java/com/tzapps/calculator/ConvertorActivity.kt | JohnX4321 | 448,324,079 | false | null | package com.tzapps.calculator
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.tzapps.calculator.databinding.ActivityConvertorBinding
import com.tzapps.calculator.utils.ConverterUtils
import com.tzapps.calculator.utils.Utils
import java.math.BigDecimal
class ConvertorActivity: AppCompatActivity(),ConverterAdapter.RecyclerItemClickListener {
companion object {
var type = 0
var fromIndex = 0
var toIndex = 0
}
private lateinit var binding: ActivityConvertorBinding
private val handler = Handler(Looper.myLooper()?: Looper.getMainLooper())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityConvertorBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.categoryRecyclerView.layoutManager = LinearLayoutManager(this)
binding.categoryRecyclerView.adapter = ConverterAdapter(this)
binding.categoryRecyclerView.setHasFixedSize(true)
binding.fromConvertSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
fromIndex=position
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
binding.toConvertSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
toIndex=position
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
/*try {
when(resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
Configuration.UI_MODE_NIGHT_YES-> binding.fromInput.setHintTextColor(Color.WHITE)
else -> binding.fromInput.setHintTextColor(Color.BLACK)
}
} catch (e: Exception) {
}*/
binding.convertButton.setOnClickListener {
try {
if (binding.fromInput.text.isNullOrEmpty())
return@setOnClickListener
val f: String
try {
f = binding.fromInput.text.toString()
} catch (ex: Exception) {
return@setOnClickListener
}
when (type) {
0 -> {
handler.post { convertLength(f.toBigDecimal()) }
}
1 -> {
handler.post { convertArea(f.toBigDecimal()) }
}
2 -> {
handler.post { convertTemperature(f.toBigDecimal()) }
}
3 -> {
handler.post { convertVolume(f.toBigDecimal()) }
}
4 -> {
handler.post { convertWeight(f.toBigDecimal()) }
}
}
} catch (e: Exception) {
Log.e("Calculator","Conversion Error: ${e.message.toString()}")
}
}
Handler(Looper.getMainLooper()).postDelayed({
try {
binding.categoryRecyclerView.findViewHolderForAdapterPosition(0)?.itemView?.findViewById<TextView>(android.R.id.text1)?.performClick()
} catch (e: Exception) {}
},300)
}
private fun convertArea(a: BigDecimal) {
when {
fromIndex == toIndex -> {
binding.toInput.text = a.toPlainString()
}
/*fromIndex == 5 -> {
binding.toInput.text = when(toIndex) {
0-> ConverterUtils.SqmToAcres(a)
1-> ConverterUtils.SqmToH(a)
2-> ConverterUtils.SqmToSqcm(a)
3-> ConverterUtils.SqmToSqft(a)
else-> ConverterUtils.SqmToSqi(a)
}.toPlainString()
}
toIndex == 5 -> {
binding.toInput.text = when(fromIndex) {
0-> ConverterUtils.AcresToSqm(a)
1-> ConverterUtils.HToSqm(a)
2-> ConverterUtils.SqcmToSqm(a)
3-> ConverterUtils.SqftToSqm(a)
else-> ConverterUtils.SqiToSqm(a)
}.toPlainString()
}*/
else -> {
val ta = when(fromIndex) {
0-> ConverterUtils.AcresToSqm(a)
1-> ConverterUtils.HToSqm(a)
2-> ConverterUtils.SqcmToSqm(a)
3-> ConverterUtils.SqftToSqm(a)
4-> ConverterUtils.SqiToSqm(a)
else-> a
}
val tb = when(toIndex) {
0-> ConverterUtils.SqmToAcres(ta)
1-> ConverterUtils.SqmToH(ta)
2-> ConverterUtils.SqmToSqcm(ta)
3-> ConverterUtils.SqmToSqft(ta)
4-> ConverterUtils.SqmToSqi(ta)
else-> ta
}
binding.toInput.text = ConverterUtils.format(tb)
}
}
}
private fun convertLength(a: BigDecimal) {
when {
fromIndex == toIndex -> {
binding.toInput.text = a.toPlainString()
}
else -> {
val ta = when(fromIndex) {
0-> a
1-> ConverterUtils.MMToM(a)
2-> ConverterUtils.CMToM(a)
3-> ConverterUtils.KMToM(a)
4-> ConverterUtils.InToM(a)
5-> ConverterUtils.FtToM(a)
6-> ConverterUtils.YdToM(a)
7-> ConverterUtils.MiToM(a)
else-> ConverterUtils.NMToM(a)
}
val tb = when(toIndex) {
0-> ta
1-> ConverterUtils.MToMM(ta)
2-> ConverterUtils.MToCM(ta)
3-> ConverterUtils.MToKM(ta)
4-> ConverterUtils.MToIn(ta)
5-> ConverterUtils.MToFt(ta)
6-> ConverterUtils.MToYd(ta)
7-> ConverterUtils.MToMi(ta)
else-> ConverterUtils.MToNM(ta)
}.toPlainString()
binding.toInput.text = tb
}
}
}
private fun convertTemperature(a: BigDecimal) {
when {
fromIndex == toIndex -> {
binding.toInput.text = a.toPlainString()
}
else -> {
val ta = when(fromIndex) {
0-> ConverterUtils.FtoC(a)
1-> a
else-> ConverterUtils.KToC(a)
}
val tb = when(toIndex) {
0-> ConverterUtils.CToF(ta)
1-> ta
else-> ConverterUtils.CToK(ta)
}.toPlainString()
binding.toInput.text = tb
}
}
}
private fun convertVolume(a: BigDecimal) {
when {
fromIndex == toIndex -> {
binding.toInput.text = a.toPlainString()
}
else -> {
val ta = when(fromIndex) {
0-> ConverterUtils.GUSToL(a)
1-> ConverterUtils.GUKToL(a)
2-> a
else-> ConverterUtils.MLToL(a)
}
val tb = when(toIndex) {
0-> ConverterUtils.LToGUS(ta)
1-> ConverterUtils.LToGUK(ta)
2-> ta
else-> ConverterUtils.LToMl(ta)
}.toPlainString()
binding.toInput.text = tb
}
}
}
private fun convertWeight(a: BigDecimal) {
when {
fromIndex == toIndex -> {
binding.toInput.text = a.toPlainString()
}
else -> {
val ta = when(fromIndex) {
0-> a
1-> ConverterUtils.GToKG(a)
2-> ConverterUtils.TToKG(a)
3-> ConverterUtils.PToKG(a)
else-> ConverterUtils.OZToKG(a)
}
val tb = when(toIndex) {
0-> ta
1-> ConverterUtils.KGToG(ta)
2-> ConverterUtils.KGToT(ta)
3-> ConverterUtils.KGToP(ta)
else-> ConverterUtils.KGToOZ(ta)
}.toPlainString()
binding.toInput.text = tb
}
}
}
override fun onRecyclerItemClick(pos: Int) {
//0 - Length, 1 - Area, 2 - Temp, 3 - Volume, 4 - Weight
type = pos
handler.post {
when (pos) {
0 -> {
binding.fromConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.LENGTH_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.fromConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
binding.toConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.LENGTH_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.toConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
}
1 -> {
binding.fromConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.AREA_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.fromConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
binding.toConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.AREA_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.toConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
}
2 -> {
binding.fromConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.TEMP_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.fromConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
binding.toConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.TEMP_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.toConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
}
3 -> {
binding.fromConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.VOLUME_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.fromConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
binding.toConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.VOLUME_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.toConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
}
4 -> {
binding.fromConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.WEIGHT_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.fromConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
binding.toConvertSpinner.adapter = ArrayAdapter(
this, android.R.layout.simple_spinner_dropdown_item, Utils.WEIGHT_CATEGORY
)//.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
(binding.toConvertSpinner.adapter as ArrayAdapter<String>).notifyDataSetChanged()
}
}
binding.fromConvertSpinner.setSelection(0)
binding.toConvertSpinner.setSelection(0)
}
}
override fun onDestroy() {
ConverterAdapter.lastSelectedIndex=-1
super.onDestroy()
}
} | 0 | Kotlin | 0 | 0 | a7e798dec410ec7dfce2fded64d6f713baf03100 | 13,645 | Calculator | Apache License 2.0 |
application/KSChat/app/src/main/java/vn/id/hvg/kschat/data/repositories/AuthRepository.kt | HVgiang86 | 718,081,850 | false | {"Kotlin": 59080, "JavaScript": 14839, "Shell": 5289, "Dockerfile": 356} | package vn.id.hvg.kschat.data.repositories
import androidx.lifecycle.MutableLiveData
import vn.id.hvg.kschat.contants.LoginState
import vn.id.hvg.kschat.contants.RegisterState
import vn.id.hvg.kschat.data.network.model.auth.RefreshTokenResponse
interface AuthRepository {
suspend fun login(email: String, password: String, loginState: MutableLiveData<LoginState>)
suspend fun register(
email: String,
password: String,
registerState: MutableLiveData<RegisterState>
)
fun refreshToken(): RefreshTokenResponse
} | 0 | Kotlin | 0 | 0 | 65c3351557fe847352cee4e70ff6c9a5d2991400 | 553 | ks-chat | MIT License |
libkunits/src/test/kotlin/com/github/dlind1974/kunits/json/jackson/DistanceSerializerTest.kt | dlind1974 | 596,461,467 | false | null | package com.github.dlind1974.kunits.json.jackson
import com.github.dlind1974.kunits.Distance
import com.github.dlind1974.kunits.meter
import com.fasterxml.jackson.core.Version
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import kotlin.test.Test
import kotlin.test.assertEquals
class DistanceSerializerTest {
@Test
fun serialize_WhenDistanceIsMeterPerSecond_ProducedJsonIsInMeters() {
val speedSerializer = DistanceSerializer(Distance::class.java)
val objectMapper = ObjectMapper()
val module = SimpleModule("DistanceSerializer", Version(1, 0, 0, null, null, null))
module.addSerializer(Distance::class.java, speedSerializer)
objectMapper.registerModule(module)
val distance = 12.7.meter
val distanceJson: String = objectMapper.writeValueAsString(distance)
val expectedDistanceJson = "{\"amount\":12.7,\"unit\":\"m\"}"
assertEquals(distanceJson, expectedDistanceJson)
}
} | 0 | Kotlin | 0 | 0 | f55daeae01a11824b5841b8d070eaa195bcff003 | 1,023 | kunits | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.