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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
composeApp/src/commonMain/kotlin/images/DrinkImage.kt
|
thaapasa
| 702,418,399
| false
|
{"Kotlin": 208600, "Swift": 661, "Shell": 262}
|
package fi.tuska.beerclock.images
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp
import fi.tuska.beerclock.localization.strings
import fi.tuska.beerclock.logging.getLogger
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
private val logger = getLogger("DrinkImage")
enum class DrinkImage(val path: String) {
GENERIC_DRINK("drawable/drinks/generic_drink.webp"),
BEER_GLASS_1("drawable/drinks/beer_glass_1.webp"),
BEER_BOTTLE_1("drawable/drinks/beer_bottle_1.webp"),
BEER_CAN_1("drawable/drinks/beer_can_1.webp"),
BEER_CAN_2("drawable/drinks/beer_can_2.webp"),
BEER_CAN_3("drawable/drinks/beer_can_3.webp"),
BEER_CAN_4("drawable/drinks/beer_can_4.webp"),
RED_WINE_GLASS_1("drawable/drinks/red_wine_glass_1.webp"),
WHITE_WINE_GLASS_1("drawable/drinks/white_wine_glass_1.webp"),
WHITE_WINE_GLASS_2("drawable/drinks/white_wine_glass_2.webp"),
WHITE_WINE_BOTTLE_2("drawable/drinks/white_wine_bottle_1.webp"),
COGNAC_1("drawable/drinks/cognac_1.webp"),
CAIPIROSCA_1("drawable/drinks/caipirosca_1.webp"),
CAIPIROSCA_2("drawable/drinks/caipirosca_2.webp"),
MARTINI_1("drawable/drinks/martini_1.webp");
@OptIn(ExperimentalResourceApi::class)
@Composable
fun painter(): Painter = painterResource(this.path)
@Composable
fun smallImage(modifier: Modifier = Modifier) {
Image(
painter = painter(),
contentDescription = strings.drink.image,
modifier = modifier.size(64.dp).clip(RoundedCornerShape(12.dp)),
)
}
@Composable
fun largeImage(modifier: Modifier = Modifier) {
Image(
painter = painter(),
contentDescription = strings.drink.image,
modifier = modifier.size(128.dp).clip(RoundedCornerShape(12.dp)),
)
}
companion object {
fun forName(name: String): DrinkImage = try {
DrinkImage.valueOf(name)
} catch (e: IllegalArgumentException) {
logger.error("No drink icon found with name $name. Using a generic icon")
GENERIC_DRINK
}
}
}
| 0
|
Kotlin
|
0
| 1
|
9b0bdd97376341896215bb8d0074bfa6f0da8647
| 2,467
|
beerclock
|
Apache License 2.0
|
src/cn/leetcode/codes/simple3/Simple3_3.kt
|
shishoufengwise1234
| 258,793,407
| false
|
{"Java": 771296, "Kotlin": 68641}
|
package cn.leetcode.codes.simple3
import cn.leetcode.codes.out
import kotlin.math.max
fun lengthOfLongestSubstring(s: String): Int {
if (s.isEmpty()) {
return 0
}
val map = hashMapOf<Char, Int>()
var maxLen = 0
var start = 0
val chars = s.toCharArray()
for (i in chars.indices) {
out("map : $map")
val c = chars[i]
//ๅทฒ็ปๅซๆๅญ็ฌฆ ้่ฆ้ๆฐ่ฎก็ฎๅผๅงไฝ็ฝฎ
if (map.containsKey(c)) {
start = max(map.get(c) ?: 0, start)
}
//่ฎก็ฎๆๅคง้ฟๅบฆ
maxLen = max(maxLen,i - start + 1)
map.put(c,i+1)
}
return maxLen
}
| 1
| null |
1
| 1
|
f917a262bcfae8cd973be83c427944deb5352575
| 599
|
LeetCodeSimple
|
Apache License 2.0
|
test/src/me/anno/tests/mesh/Cylinder.kt
|
AntonioNoack
| 456,513,348
| false
|
{"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698}
|
package me.anno.tests.mesh
import me.anno.ecs.components.mesh.Material
import me.anno.ecs.components.mesh.Mesh
import me.anno.ecs.components.mesh.shapes.CylinderModel
import me.anno.engine.ui.render.SceneView.Companion.testSceneWithUI
import me.anno.ui.UIColors.axisXColor
import me.anno.ui.UIColors.axisZColor
import me.anno.utils.Color.white
fun main() {
val mesh = CylinderModel.createMesh(
16, 3, true, true,
listOf(
Material.diffuse(white).ref,
Material.diffuse(axisXColor).ref,
Material.diffuse(axisZColor).ref
),
3f, Mesh()
)
testSceneWithUI("Cylinder", mesh)
}
| 0
|
Kotlin
|
3
| 24
|
013af4d92e0f89a83958008fbe1d1fdd9a10e992
| 650
|
RemsEngine
|
Apache License 2.0
|
main/src/commonMain/kotlin/org/ooverkommelig/graph/ArgumentBoundDefinitionAndObject.kt
|
squins
| 74,140,237
| false
|
{"Kotlin": 78752}
|
package org.ooverkommelig.graph
import org.ooverkommelig.definition.ObjectCreatingDefinition
internal class ArgumentBoundDefinitionAndObject<TObject>(definition: ObjectCreatingDefinition<TObject>, argument: Any?, private val obj: TObject) :
DefinitionAndArgument<TObject>(definition, argument) {
fun wire() {
definition.wire(obj)
}
fun init() {
definition.init(obj)
}
fun dispose() {
definition.dispose(obj)
}
}
| 1
|
Kotlin
|
0
| 1
|
c611124e175e45370274e8d7a939c231015f9906
| 472
|
ooverkommelig
|
MIT License
|
idea/idea-completion/testData/handlers/smart/lambdaSignature/Simple.kt
|
JakeWharton
| 99,388,807
| true
| null |
fun foo(p: (x: Char, String) -> Unit){}
fun bar() {
foo { <caret> }
}
// ELEMENT: "x, s ->"
| 0
|
Kotlin
|
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 98
|
kotlin
|
Apache License 2.0
|
idea/idea-completion/testData/handlers/smart/lambdaSignature/Simple.kt
|
JakeWharton
| 99,388,807
| true
| null |
fun foo(p: (x: Char, String) -> Unit){}
fun bar() {
foo { <caret> }
}
// ELEMENT: "x, s ->"
| 0
|
Kotlin
|
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 98
|
kotlin
|
Apache License 2.0
|
application/src/main/kotlin/com/lukinhasssss/catalogo/application/video/delete/DeleteVideoUseCase.kt
|
Lukinhasssss
| 643,341,523
| false
|
{"Kotlin": 333012, "Shell": 669}
|
package com.lukinhasssss.catalogo.application.video.delete
import com.lukinhasssss.catalogo.application.UnitUseCase
import com.lukinhasssss.catalogo.domain.video.VideoGateway
class DeleteVideoUseCase(
private val videoGateway: VideoGateway
) : UnitUseCase<DeleteVideoUseCase.Input>() {
override fun execute(input: Input) = with(input) {
if (this.videoId.isNullOrBlank()) return
videoGateway.deleteById(this.videoId)
}
data class Input(
val videoId: String?
)
}
| 1
|
Kotlin
|
0
| 0
|
b5d65a4a39f3ebe30a0f25fa7c797ed36e8325ba
| 509
|
catalogo-de-videos
|
MIT License
|
app/src/main/java/cz/prague/cvut/fit/steuejan/amtelapp/data/dao/DAO.kt
|
hawklike
| 234,594,207
| false
|
{"Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 162, "XML": 116, "Java": 2}
|
package cz.prague.cvut.fit.steuejan.amtelapp.data.dao
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.QuerySnapshot
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import cz.prague.cvut.fit.steuejan.amtelapp.data.entities.Entity
import kotlinx.coroutines.tasks.await
interface DAO
{
val collection: String
suspend fun <T> insert(entity: T)
suspend fun findById(id: String): DocumentSnapshot
suspend fun <T> find(field: String, value: T?): QuerySnapshot
suspend fun update(documentId: String, mapOfFieldsAndValues: Map<String, Any?>)
suspend fun delete(documentId: String)
suspend fun <T> insert(collectionName: String, entity: Entity<T>, merge: Boolean = true)
{
val collection = Firebase.firestore.collection(collectionName)
val document = entity.id?.let { collection.document(it) } ?: collection.document()
entity.id = document.id
if(merge) document.set(entity, SetOptions.merge()).await()
else document.set(entity).await()
}
suspend fun findById(collectionName: String, id: String): DocumentSnapshot
{
return Firebase.firestore
.collection(collectionName)
.document(id)
.get()
.await()
}
suspend fun <T> find(collectionName: String, field: String, value: T?): QuerySnapshot
{
return Firebase.firestore
.collection(collectionName)
.whereEqualTo(field, value)
.get()
.await()
}
suspend fun update(collectionName: String, documentId: String, mapOfFieldsAndValues: Map<String, Any?>)
{
Firebase.firestore
.collection(collectionName)
.document(documentId)
.update(mapOfFieldsAndValues)
.await()
}
suspend fun delete(collectionName: String, documentId: String)
{
Firebase.firestore
.collection(collectionName)
.document(documentId)
.delete()
.await()
}
fun retrieveAllAndGetQuery(collectionName: String): Query
{
return Firebase.firestore
.collection(collectionName)
}
suspend fun retrieveAll(collectionName: String): QuerySnapshot
{
return Firebase.firestore
.collection(collectionName)
.get()
.await()
}
fun retrieveByPrefix(collectionName: String, textToSearch: String, searchField: String): Query
{
return Firebase.firestore
.collection(collection)
.whereGreaterThanOrEqualTo(searchField, textToSearch)
.whereLessThanOrEqualTo(searchField, textToSearch + '\uf8ff')
}
}
| 1
| null |
1
| 1
|
1f88ddbcbd8e547158a4677c934b4dbf18ec82e1
| 2,850
|
Amtel-App
|
MIT License
|
simplified-cardcreator/src/main/java/org/nypl/simplified/cardcreator/model/PersonalInformation.kt
|
NYPL-Simplified
| 30,199,881
| false
| null |
package org.nypl.simplified.cardcreator.model
data class PersonalInformation(
val firstName: String,
val middleName: String,
val lastName: String,
val birthDate: String,
val email: String
)
| 109
| null |
21
| 32
|
781e4e2122f1528253a6cf17931083944f91ceba
| 201
|
Simplified-Android-Core
|
Apache License 2.0
|
sdk/src/main/java/com/eyeson/sdk/model/sepp/base/UnknownCommandDto.kt
|
eyeson-team
| 488,502,949
| false
|
{"Kotlin": 428150}
|
package com.eyeson.sdk.model.datachannel.base
import com.eyeson.sdk.model.local.base.UnknownCommand
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal class UnknownCommandDto(
override val type: String = "Unknown command"
) : DataChannelCommandDto {
override fun toLocal(): UnknownCommand {
return UnknownCommand()
}
}
| 0
|
Kotlin
|
0
| 3
|
0b4395612ad2f321820c2a9f76072b6bbc2fb9f1
| 370
|
android-sdk
|
MIT License
|
shared/src/commonMain/kotlin/com/seiko/greenqrscanner/util/AppDateFormatter.kt
|
qdsfdhvh
| 650,389,325
| false
|
{"Kotlin": 266749, "Ruby": 1100, "Swift": 628, "Shell": 228}
|
/*
* Taken from https://github.com/chrisbanes/tivi/blob/main/common/ui/resources/strings/src/commonMain/kotlin/app/tivi/util/TiviDateFormatter.kt
*/
package com.seiko.greenqrscanner.util
import kotlinx.datetime.Clock
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.Instant
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalTime
expect class AppDateFormatter {
fun formatShortDate(instant: Instant): String
fun formatShortDate(date: LocalDate): String
fun formatMediumDate(instant: Instant): String
fun formatMediumDateTime(instant: Instant): String
fun formatShortTime(localTime: LocalTime): String
fun formatShortRelativeTime(date: Instant, reference: Instant = Clock.System.now()): String
fun formatDayOfWeek(dayOfWeek: DayOfWeek): String
}
| 12
|
Kotlin
|
0
| 3
|
d670b93173a89306f511000bab1a195fc1ff090d
| 798
|
green-qrscanner
|
Apache License 2.0
|
trustagent/src/com/google/android/libraries/car/trustagent/blemessagestream/GattHandle.kt
|
google
| 415,118,653
| false
| null |
// Copyright 2021 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.android.libraries.car.trustagent.blemessagestream
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattService
import android.content.Context
import java.util.UUID
/** Provides Bluetooth GATT functionality with a remote peripheral. */
interface GattHandle {
/** The remote [BluetoothDevice] that this GATT communicates with. */
val device: BluetoothDevice
/** The callback that will be notified of various GATT events. */
var callback: GattHandleCallback?
/** Attempts to connect to the remote [device]. */
fun connect(context: Context)
/**
* Attempts to disconnect the current connection with the remote [device].
*
* The [callback] set on this handle will be notified of the status of this call.
*/
fun disconnect()
/**
* Closes this handle and disposes of this handle.
*
* This method does not necessarily disconnect from the remote device. Ensure that [disconnect] is
* called first.
*/
fun close()
/** Clears the internal cache and forces a refresh of the services of the remote device. */
fun refresh()
/**
* Discover the services that are currently being offered by the remote [device] and returns
* `true` if this call initiates successfully.
*
* Discovered services are passed to the [callback] that is set on this class.
*/
fun discoverServices(): Boolean
/** Retrieves the service on the remote [device] that is identified by the given [serviceUuid]. */
fun getService(serviceUuid: UUID): BluetoothGattService?
/**
* Attempts to write the given [characteristic] and its value to the remote [device].
*
* This method returns `true` if the write was initiated successfully, but this does not mean that
* the operation itself succeeded. The [callback] set on this handle will be notified of the
* resulting status.
*/
fun writeCharacteristic(characteristic: BluetoothGattCharacteristic): Boolean
/**
* Issues a request to read the given [characteristic] on the remote [device] and returns `true`
* if the request was initiated successfully.
*
* The [callback] set on this handle will be notified of the result of the read.
*/
fun readCharacteristic(characteristic: BluetoothGattCharacteristic): Boolean
/**
* Sets if notifications for the given [characteristic] are enabled and returns `true` if the
* request was sent successfully.
*
* If notifications are enabled, then the [callback] set on this handle will be notified whenever
* the value in the characteristic has changed.
*/
fun setCharacteristicNotification(
characteristic: BluetoothGattCharacteristic,
isEnabled: Boolean
): Boolean
/**
* Issues a request to set the MTU of the GATT connection to be the given [mtuSize] and returns
* `true` if the operation was initiated successfully.
*
* The [callback] set on this handle will be notified of the resulting MTU size and if the request
* succeeded.
*/
fun requestMtu(mtuSize: Int): Boolean
/**
* Issues a request to set the connection `priority` and returns 'true' if the operation was
* initiated successfully.
*/
fun requestConnectionPriority(priority: Int): Boolean
/**
* Writes the value of [descriptor] to the remote [device].
*
* Returns `true` if the operation was initiated successfully; the [callback] set on this handle
* will be notified of the result of the write.
*/
fun writeDescriptor(descriptor: BluetoothGattDescriptor): Boolean
}
| 0
| null |
5
| 18
|
a48dc3318cfefd06643c12aff44660f311c987db
| 4,217
|
android-auto-companion-android
|
Apache License 2.0
|
xprl-efactura-jaxb-publishing/src/test/kotlin/uk/co/xprl/efactura/jaxb/ClaveAcceso_Modulo11Test.kt
|
xprl-gjf
| 534,729,919
| false
|
{"Kotlin": 364234}
|
package uk.co.xprl.efactura.jaxb
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.MethodSource
import kotlin.test.assertEquals
class ClaveAcceso_Modulo11Test {
@ParameterizedTest(name = "modulo11 calculates checksum for {0}")
@MethodSource("getValues")
fun modulo11CheckSumValue(claveAcceso48: String, expected: Int) {
assertEquals(expected, modulo11(claveAcceso48))
}
@ParameterizedTest(name = "modulo11 throws exception for {0}")
@MethodSource("getInvalidValues")
fun modulo11IllegalArgumentException(invalid: String) {
assertThrows<IllegalArgumentException> {
modulo11(invalid)
}
}
companion object {
@JvmStatic
fun getValues(): List<Arguments> = sequence {
yield(arguments("250520220117927582700012002004000006794012877011", 9))
yield(arguments("021220140117917369580011001100000000237000000861", 0))
yield(arguments("111220140117917369580011001100000000286000001271", 1))
yield(arguments("161220140117917369580011001001000000030000001671", 9))
yield(arguments("031220140117917369580011001100000000245000000941", 0))
}.toList()
@JvmStatic
fun getInvalidValues(): List<Arguments> = arrayOf(
"2505202201179275827000120020040000067940128770119", // too long
"25052022011792758270001200200400000679401287701", // too short
"25052022011792758270001200200400000679401287701A", // non-numeric
"-25052022011792758270001200200400000679401287701", // -ve
"", // empty
" ", // blank
).map {
arguments(it)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
58d75bd3bfb96e05ef919aebcec3336c3397c2fb
| 1,982
|
xprl-efactura
|
Apache License 2.0
|
MapboxSearch/offline/src/androidTest/java/com/mapbox/search/offline/tests_support/BlockingEngineReadyCallback.kt
|
mapbox
| 438,355,708
| false
|
{"Kotlin": 2244061, "Java": 41736, "Python": 18980, "Shell": 17499}
|
package com.mapbox.search.offline.tests_support
import com.mapbox.search.common.tests.BaseBlockingCallback
import com.mapbox.search.offline.OfflineSearchEngine
internal class BlockingEngineReadyCallback : BaseBlockingCallback<Unit>(), OfflineSearchEngine.EngineReadyCallback {
override fun onEngineReady() {
publishResult(Unit)
}
}
| 17
|
Kotlin
|
7
| 33
|
369bc63bb10a7da7f2b3e57839ba47b762c87b99
| 350
|
mapbox-search-android
|
Apache License 2.0
|
data_wallet/src/main/java/io/igrant/data_wallet/adapter/ReceiptItemListAdapter.kt
|
decentralised-dataexchange
| 344,557,240
| false
|
{"Kotlin": 987858, "Java": 85361}
|
package io.igrant.data_wallet.adapter
import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import io.igrant.data_wallet.R
class ReceiptItemListAdapter(
var itemList: ArrayList<Map<String, String>>
) : RecyclerView.Adapter<ReceiptItemListAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvAttributeName: TextView =
itemView.findViewById<View>(R.id.tvAttributeName) as TextView
var tvAttributeQuantity: TextView =
itemView.findViewById<View>(R.id.tvAttributeQuantity) as TextView
var tvAttributePrice: TextView =
itemView.findViewById<View>(R.id.tvAttributePrice) as TextView
var vDivider: View = itemView.findViewById<View>(R.id.vDivider) as View
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_receipt_attribute, parent, false)
)
}
override fun getItemCount(): Int {
return itemList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val attributes = itemList[position]
holder.tvAttributeName.text = attributes["name"]
holder.tvAttributeQuantity.text = attributes["quantity"]
holder.tvAttributePrice.text = attributes["value"]
holder.vDivider.visibility = if (position == itemList.size - 1) View.GONE else View.VISIBLE
holder.tvAttributeName.setTextColor(
ContextCompat.getColor(
holder.tvAttributeName.context,
R.color.black
)
)
holder.tvAttributeQuantity.setTextColor(
ContextCompat.getColor(
holder.tvAttributeName.context,
R.color.black
)
)
if (position == 0) {
holder.tvAttributePrice.setTextColor(
ContextCompat.getColor(
holder.tvAttributeName.context,
R.color.black
)
)
} else {
holder.tvAttributePrice.setTextColor(
ContextCompat.getColor(
holder.tvAttributeName.context,
R.color.textColorLight
)
)
}
if (position == 0 || position == itemList.size - 1) {
holder.tvAttributeName.setTypeface(holder.tvAttributeName.typeface, Typeface.BOLD);
holder.tvAttributeQuantity.setTypeface(
holder.tvAttributeQuantity.typeface,
Typeface.BOLD
);
holder.tvAttributePrice.setTypeface(holder.tvAttributePrice.typeface, Typeface.BOLD);
} else {
holder.tvAttributeName.setTypeface(holder.tvAttributeName.typeface, Typeface.NORMAL);
holder.tvAttributeQuantity.setTypeface(
holder.tvAttributeQuantity.typeface,
Typeface.NORMAL
);
holder.tvAttributePrice.setTypeface(holder.tvAttributePrice.typeface, Typeface.NORMAL);
}
}
}
| 3
|
Kotlin
|
0
| 1
|
79d311e2780df3b3a7b39262152dcc4d34d8dbb5
| 3,341
|
ama-android-sdk
|
Apache License 2.0
|
src/main/kotlin/com/michigang1/backendcourse/repository/record/RecordRepositoryImpl.kt
|
michigang1
| 717,830,098
| false
|
{"Kotlin": 29228, "Dockerfile": 440}
|
package com.michigang1.backendcourse.repository.record
import com.michigang1.backendcourse.exception.NoOneOfTwoParamsProvidedException
import com.michigang1.backendcourse.exception.ResourceByParamNotFound
import com.michigang1.backendcourse.models.Record
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Repository
@Repository
class RecordRepositoryImpl : RecordRepository {
private val recordStub = mutableListOf<Record>()
override suspend fun getRecordById(id: Int): Record? {
return recordStub.find { it.id == id }
}
override suspend fun getAllRecords(): List<Record> {
return recordStub
}
override suspend fun addRecord(record: Record): Record {
record.id = recordStub.count()
recordStub.add(record)
return recordStub.last()
}
override suspend fun deleteRecordById(id: Int): Boolean {
val record = recordStub.find { it.id == id }
if (record == null) throw ResourceByParamNotFound()
else {
recordStub.removeAt(recordStub.indexOf(record))
val isDeleted = recordStub.none { it.id == id }
return isDeleted
}
}
}
| 0
|
Kotlin
|
1
| 1
|
f4df22e30d6f06427b0584cad779d2ff491152eb
| 1,274
|
back-end-course
|
MIT License
|
app/src/main/java/com/vv/nasapod/di/ApplicationContext.kt
|
vishalvn
| 275,745,892
| false
|
{"Java": 97928, "Kotlin": 38097}
|
package com.vv.nasapod.di
import javax.inject.Qualifier
@Qualifier
annotation class ApplicationContext
| 1
| null |
1
| 1
|
3d9034b8f811151ca20411eb790b58a2b14d870e
| 105
|
Nasa-pic-of-the-day
|
Apache License 2.0
|
sample/src/main/java/com/parsuomash/affogato/app/screens/ScreenPdf.kt
|
ghasemdev
| 510,960,043
| false
|
{"Kotlin": 951619, "Shell": 3263}
|
package com.parsuomash.affogato.app.screens
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.parsuomash.affogato.pdfviewer.VerticalPDFView
@Composable
fun ScreenPdf() {
var pdfUri: Uri by rememberSaveable { mutableStateOf(Uri.EMPTY) }
val pickPDFLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.GetContent()
) { uri ->
if (uri != null) {
pdfUri = uri
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
onClick = { pickPDFLauncher.launch("application/pdf") }
) {
Text(text = "Select file")
}
Spacer(modifier = Modifier.height(8.dp))
AnimatedVisibility(
modifier = Modifier.fillMaxSize(),
visible = pdfUri != Uri.EMPTY,
enter = fadeIn(),
exit = fadeOut()
) {
VerticalPDFView(
modifier = Modifier.fillMaxSize(),
uri = pdfUri
)
}
}
}
| 1
|
Kotlin
|
1
| 12
|
d65733fb3a53ea4b61f98a10d59eb3b30fc65908
| 2,025
|
affogato
|
MIT License
|
user_impl/src/main/java/com/felix/android/user/destination/SetUserInfoDestinationImpl.kt
|
savelove123
| 670,151,809
| false
| null |
package com.felix.android.user.destination
import android.content.Intent
import android.os.Parcelable
import com.felix.android.navigation.Navigable
import com.felix.android.navigation.demo.user.SetUserInfoDestination
import com.felix.android.navigation.destination.Screen
import com.felix.android.user.ui.SetUserInfoActivity
import javax.inject.Inject
class SetUserInfoDestinationImpl @Inject constructor() :SetUserInfoDestination{
override fun toScreen(params: Parcelable?, navigable: Navigable): Screen {
return Intent( navigable.toContext(), SetUserInfoActivity::class.java)
}
}
| 0
|
Kotlin
|
0
| 4
|
1021a26afbcc2de93b891596ae008b7d126f62e1
| 601
|
AwesomeNavigation
|
Apache License 2.0
|
edu-format/src/com/jetbrains/edu/learning/yaml/format/student/StudentTaskFileUtil.kt
|
JetBrains
| 43,696,115
| false
|
{"Kotlin": 4860366, "HTML": 3417303, "Python": 18245, "Java": 13512, "CSS": 12216, "JavaScript": 302, "Shell": 71}
|
package com.jetbrains.edu.learning.yaml.format.student
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder
import com.jetbrains.edu.learning.courseFormat.BinaryContents
import com.jetbrains.edu.learning.courseFormat.EduFileErrorHighlightLevel
import com.jetbrains.edu.learning.courseFormat.InMemoryTextualContents
import com.jetbrains.edu.learning.courseFormat.TaskFile
import com.jetbrains.edu.learning.json.encrypt.Encrypt
import com.jetbrains.edu.learning.yaml.format.TaskFileBuilder
import com.jetbrains.edu.learning.yaml.format.TaskFileYamlMixin
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.EDITABLE
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.ENCRYPTED_TEXT
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.HIGHLIGHT_LEVEL
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.IS_BINARY
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.LEARNER_CREATED
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.NAME
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.PLACEHOLDERS
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.TEXT
import com.jetbrains.edu.learning.yaml.format.YamlMixinNames.VISIBLE
@Suppress("unused") // used for yaml serialization
@JsonDeserialize(builder = StudentTaskFileBuilder::class)
@JsonPropertyOrder(NAME, VISIBLE, PLACEHOLDERS, EDITABLE, HIGHLIGHT_LEVEL, TEXT, IS_BINARY, LEARNER_CREATED)
abstract class StudentTaskFileYamlMixin : TaskFileYamlMixin() {
private val isBinary: Boolean?
@JsonProperty(IS_BINARY)
@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = IsBinaryFilter::class)
get() = null
@JsonProperty(TEXT)
open fun getTextToSerialize(): String {
throw NotImplementedError()
}
@JsonProperty(LEARNER_CREATED)
private var isLearnerCreated = false
}
/**
* We write only is_binary: true, and omit is_binary: false for textual files.
*/
@Suppress("EqualsOrHashCode")
class IsBinaryFilter {
override fun equals(other: Any?) = other == false || other == null
}
class StudentTaskFileBuilder(
@JsonProperty(TEXT) val textFromConfig: String?,
@Encrypt @JsonProperty(ENCRYPTED_TEXT) val encryptedTextFromConfig: String?,
@JsonProperty(LEARNER_CREATED) val learnerCreated: Boolean = false,
@JsonProperty(IS_BINARY) val isBinary: Boolean? = false,
name: String?,
placeholders: List<AnswerPlaceholder> = mutableListOf(),
visible: Boolean = true,
editable: Boolean = true,
@JsonProperty(HIGHLIGHT_LEVEL) errorHighlightLevel: EduFileErrorHighlightLevel = EduFileErrorHighlightLevel.ALL_PROBLEMS
) : TaskFileBuilder(name, placeholders, visible, editable, errorHighlightLevel) {
override fun createTaskFile(): TaskFile {
val newTaskFile = super.createTaskFile()
newTaskFile.contents = if (isBinary == true) {
// binary contents are never stored in yaml
BinaryContents.EMPTY
}
else {
val text = encryptedTextFromConfig ?: textFromConfig ?: ""
InMemoryTextualContents(text)
}
newTaskFile.isLearnerCreated = learnerCreated
return newTaskFile
}
}
| 6
|
Kotlin
|
44
| 134
|
1ad7e26bfd3dc03939bf553f2b99ac14409d96d8
| 3,328
|
educational-plugin
|
Apache License 2.0
|
integration-test-jdbc/src/test/kotlin/integration/jdbc/JdbcSelectWindowFunctionTest.kt
|
komapper
| 349,909,214
| false
| null |
package integration.jdbc
import integration.core.Dbms
import integration.core.Run
import integration.core.department
import integration.core.employee
import integration.core.employeeSalary
import org.junit.jupiter.api.extension.ExtendWith
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.operator.alias
import org.komapper.core.dsl.operator.avg
import org.komapper.core.dsl.operator.cumeDist
import org.komapper.core.dsl.operator.denseRank
import org.komapper.core.dsl.operator.firstValue
import org.komapper.core.dsl.operator.lag
import org.komapper.core.dsl.operator.lastValue
import org.komapper.core.dsl.operator.lead
import org.komapper.core.dsl.operator.literal
import org.komapper.core.dsl.operator.min
import org.komapper.core.dsl.operator.nthValue
import org.komapper.core.dsl.operator.ntile
import org.komapper.core.dsl.operator.over
import org.komapper.core.dsl.operator.percentRank
import org.komapper.core.dsl.operator.rank
import org.komapper.core.dsl.operator.rowNumber
import org.komapper.jdbc.JdbcDatabase
import java.time.LocalDate
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
@ExtendWith(JdbcEnv::class)
@Run(unless = [Dbms.MYSQL_5])
class JdbcSelectWindowFunctionTest(private val db: JdbcDatabase) {
@Test
fun testPartitionBy() {
val e = Meta.employee
val subquery = QueryDsl.from(e).select(
e.departmentId,
e.employeeName,
e.salary,
avg(e.salary).over { partitionBy(e.departmentId) },
)
val t = Meta.employeeSalary
val query = QueryDsl.from(t, subquery)
.where {
t.salary greater t.averageSalary
}
.orderBy(t.departmentId, t.employeeName)
val list = db.runQuery { query }
println(list)
assertEquals(6, list.size)
list[0].let {
assertEquals(1, it.departmentId)
assertEquals("KING", it.employeeName)
}
list[5].let {
assertEquals(3, it.departmentId)
assertEquals("BLAKE", it.employeeName)
}
for (each in list) {
assertTrue(each.salary.toDouble() > each.averageSalary.toDouble())
}
}
@Test
fun testRowsBetween() {
val e = Meta.employee
val currentDate = e.hiredate alias "currentDate"
val latestDate = min(e.hiredate).over {
orderBy(e.hiredate)
rows(preceding(1), preceding(1))
} alias "latestDate"
val pairs = db.runQuery {
QueryDsl.from(e).select(currentDate, latestDate)
}
assertEquals(14, pairs.size)
pairs[0].let {
assertEquals(LocalDate.of(1980, 12, 17), it.first)
assertNull(it.second)
}
pairs[1].let {
assertEquals(LocalDate.of(1981, 2, 20), it.first)
assertEquals(LocalDate.of(1980, 12, 17), it.second)
}
}
@Test
fun testRowNumber() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, rowNumber().over { orderBy(e.departmentId) })
}
val expected = listOf(
(1 to 1L),
(1 to 2L),
(1 to 3L),
(2 to 4L),
(2 to 5L),
(2 to 6L),
(2 to 7L),
(2 to 8L),
(3 to 9L),
(3 to 10L),
(3 to 11L),
(3 to 12L),
(3 to 13L),
(3 to 14L),
)
assertEquals(expected, list)
}
@Test
fun testRank() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, rank().over { orderBy(e.departmentId) })
}
val expected = listOf(
(1 to 1L),
(1 to 1L),
(1 to 1L),
(2 to 4L),
(2 to 4L),
(2 to 4L),
(2 to 4L),
(2 to 4L),
(3 to 9L),
(3 to 9L),
(3 to 9L),
(3 to 9L),
(3 to 9L),
(3 to 9L),
)
assertEquals(expected, list)
}
@Test
fun testDenseRank() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, denseRank().over { orderBy(e.departmentId) })
}
val expected = listOf(
(1 to 1L),
(1 to 1L),
(1 to 1L),
(2 to 2L),
(2 to 2L),
(2 to 2L),
(2 to 2L),
(2 to 2L),
(3 to 3L),
(3 to 3L),
(3 to 3L),
(3 to 3L),
(3 to 3L),
(3 to 3L),
)
assertEquals(expected, list)
}
@Test
fun testPercentRank() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, percentRank().over { orderBy(e.departmentId) })
}
println(list)
}
@Test
fun testCumeDist() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, cumeDist().over { orderBy(e.departmentId) })
}
println(list)
}
@Test
fun testNtile() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, ntile(5).over { orderBy(e.departmentId) })
}
val expected = listOf(
(1 to 1),
(1 to 1),
(1 to 1),
(2 to 2),
(2 to 2),
(2 to 2),
(2 to 3),
(2 to 3),
(3 to 3),
(3 to 4),
(3 to 4),
(3 to 4),
(3 to 5),
(3 to 5),
)
assertEquals(expected, list)
}
@Run(unless = [Dbms.MARIADB])
@Test
fun testLead() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lead(d.departmentId).over { orderBy(d.departmentId) }
val c3 = lead(d.departmentId, 2).over { orderBy(d.departmentId) }
val c4 = lead(d.departmentId, 2, literal(-1)).over { orderBy(d.departmentId) }
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3, c4)
}
println(list)
assertEquals(4, list.size)
list[0].let {
assertEquals(1, it[c1])
assertEquals(2, it[c2])
assertEquals(3, it[c3])
assertEquals(3, it[c4])
}
list[1].let {
assertEquals(2, it[c1])
assertEquals(3, it[c2])
assertEquals(4, it[c3])
assertEquals(4, it[c4])
}
list[2].let {
assertEquals(3, it[c1])
assertEquals(4, it[c2])
assertEquals(null, it[c3])
assertEquals(-1, it[c4])
}
list[3].let {
assertEquals(4, it[c1])
assertEquals(null, it[c2])
assertEquals(null, it[c3])
assertEquals(-1, it[c4])
}
}
@Run(onlyIf = [Dbms.MARIADB])
@Test
fun testLeadWithoutDefaultValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lead(d.departmentId).over { orderBy(d.departmentId) }
val c3 = lead(d.departmentId, 2).over { orderBy(d.departmentId) }
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.selectAsRecord(c1, c2, c3)
}
println(list)
assertEquals(4, list.size)
list[0].let {
assertEquals(1, it[c1])
assertEquals(2, it[c2])
assertEquals(3, it[c3])
}
list[1].let {
assertEquals(2, it[c1])
assertEquals(3, it[c2])
assertEquals(4, it[c3])
}
list[2].let {
assertEquals(3, it[c1])
assertEquals(4, it[c2])
assertEquals(null, it[c3])
}
list[3].let {
assertEquals(4, it[c1])
assertEquals(null, it[c2])
assertEquals(null, it[c3])
}
}
@Run(unless = [Dbms.MARIADB])
@Test
fun testLag() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lag(d.departmentId).over { orderBy(d.departmentId) }
val c3 = lag(d.departmentId, 2).over { orderBy(d.departmentId) }
val c4 = lag(d.departmentId, 2, literal(-1)).over { orderBy(d.departmentId) }
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3, c4)
}
println(list)
assertEquals(4, list.size)
list[0].let {
assertEquals(1, it[c1])
assertEquals(null, it[c2])
assertEquals(null, it[c3])
assertEquals(-1, it[c4])
}
list[1].let {
assertEquals(2, it[c1])
assertEquals(1, it[c2])
assertEquals(null, it[c3])
assertEquals(-1, it[c4])
}
list[2].let {
assertEquals(3, it[c1])
assertEquals(2, it[c2])
assertEquals(1, it[c3])
assertEquals(1, it[c4])
}
list[3].let {
assertEquals(4, it[c1])
assertEquals(3, it[c2])
assertEquals(2, it[c3])
assertEquals(2, it[c4])
}
}
@Run(onlyIf = [Dbms.MARIADB])
@Test
fun testLagWithoutDefaultValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lag(d.departmentId).over { orderBy(d.departmentId) }
val c3 = lag(d.departmentId, 2).over { orderBy(d.departmentId) }
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.selectAsRecord(c1, c2, c3)
}
println(list)
assertEquals(4, list.size)
list[0].let {
assertEquals(1, it[c1])
assertEquals(null, it[c2])
assertEquals(null, it[c3])
}
list[1].let {
assertEquals(2, it[c1])
assertEquals(1, it[c2])
assertEquals(null, it[c3])
}
list[2].let {
assertEquals(3, it[c1])
assertEquals(2, it[c2])
assertEquals(1, it[c3])
}
list[3].let {
assertEquals(4, it[c1])
assertEquals(3, it[c2])
assertEquals(2, it[c3])
}
}
@Test
fun testFirstValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = firstValue(d.departmentId).over { orderBy(d.departmentId) }
val c3 = firstValue(d.departmentId).over {
orderBy(d.departmentId)
rows(preceding(1))
}
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3)
}
println(list)
val expected = listOf(
Triple(1, 1, 1),
Triple(2, 1, 1),
Triple(3, 1, 2),
Triple(4, 1, 3),
)
assertEquals(expected, list)
}
@Test
fun testLastValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lastValue(d.departmentId).over {
orderBy(d.departmentId)
rows(unboundedPreceding, unboundedFollowing)
}
val c3 = lastValue(d.departmentId).over {
orderBy(d.departmentId)
rows(currentRow, following(1))
}
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3)
}
println(list)
val expected = listOf(
Triple(1, 4, 2),
Triple(2, 4, 3),
Triple(3, 4, 4),
Triple(4, 4, 4),
)
assertEquals(expected, list)
}
@Run(unless = [Dbms.SQLSERVER])
@Test
fun testNthValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = nthValue(d.departmentId, 2).over {
orderBy(d.departmentId)
}
val c3 = nthValue(d.departmentId, 2).over {
orderBy(d.departmentId)
rows(preceding(2))
}
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3)
}
println(list)
val expected = listOf(
Triple(1, null, null),
Triple(2, 2, 2),
Triple(3, 2, 2),
Triple(4, 2, 3),
)
assertEquals(expected, list)
}
}
| 8
| null |
14
| 301
|
9fbc0b5652ee732583e977180cdc493e116e1022
| 13,271
|
komapper
|
Apache License 2.0
|
integration-test-jdbc/src/test/kotlin/integration/jdbc/JdbcSelectWindowFunctionTest.kt
|
komapper
| 349,909,214
| false
| null |
package integration.jdbc
import integration.core.Dbms
import integration.core.Run
import integration.core.department
import integration.core.employee
import integration.core.employeeSalary
import org.junit.jupiter.api.extension.ExtendWith
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.operator.alias
import org.komapper.core.dsl.operator.avg
import org.komapper.core.dsl.operator.cumeDist
import org.komapper.core.dsl.operator.denseRank
import org.komapper.core.dsl.operator.firstValue
import org.komapper.core.dsl.operator.lag
import org.komapper.core.dsl.operator.lastValue
import org.komapper.core.dsl.operator.lead
import org.komapper.core.dsl.operator.literal
import org.komapper.core.dsl.operator.min
import org.komapper.core.dsl.operator.nthValue
import org.komapper.core.dsl.operator.ntile
import org.komapper.core.dsl.operator.over
import org.komapper.core.dsl.operator.percentRank
import org.komapper.core.dsl.operator.rank
import org.komapper.core.dsl.operator.rowNumber
import org.komapper.jdbc.JdbcDatabase
import java.time.LocalDate
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
@ExtendWith(JdbcEnv::class)
@Run(unless = [Dbms.MYSQL_5])
class JdbcSelectWindowFunctionTest(private val db: JdbcDatabase) {
@Test
fun testPartitionBy() {
val e = Meta.employee
val subquery = QueryDsl.from(e).select(
e.departmentId,
e.employeeName,
e.salary,
avg(e.salary).over { partitionBy(e.departmentId) },
)
val t = Meta.employeeSalary
val query = QueryDsl.from(t, subquery)
.where {
t.salary greater t.averageSalary
}
.orderBy(t.departmentId, t.employeeName)
val list = db.runQuery { query }
println(list)
assertEquals(6, list.size)
list[0].let {
assertEquals(1, it.departmentId)
assertEquals("KING", it.employeeName)
}
list[5].let {
assertEquals(3, it.departmentId)
assertEquals("BLAKE", it.employeeName)
}
for (each in list) {
assertTrue(each.salary.toDouble() > each.averageSalary.toDouble())
}
}
@Test
fun testRowsBetween() {
val e = Meta.employee
val currentDate = e.hiredate alias "currentDate"
val latestDate = min(e.hiredate).over {
orderBy(e.hiredate)
rows(preceding(1), preceding(1))
} alias "latestDate"
val pairs = db.runQuery {
QueryDsl.from(e).select(currentDate, latestDate)
}
assertEquals(14, pairs.size)
pairs[0].let {
assertEquals(LocalDate.of(1980, 12, 17), it.first)
assertNull(it.second)
}
pairs[1].let {
assertEquals(LocalDate.of(1981, 2, 20), it.first)
assertEquals(LocalDate.of(1980, 12, 17), it.second)
}
}
@Test
fun testRowNumber() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, rowNumber().over { orderBy(e.departmentId) })
}
val expected = listOf(
(1 to 1L),
(1 to 2L),
(1 to 3L),
(2 to 4L),
(2 to 5L),
(2 to 6L),
(2 to 7L),
(2 to 8L),
(3 to 9L),
(3 to 10L),
(3 to 11L),
(3 to 12L),
(3 to 13L),
(3 to 14L),
)
assertEquals(expected, list)
}
@Test
fun testRank() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, rank().over { orderBy(e.departmentId) })
}
val expected = listOf(
(1 to 1L),
(1 to 1L),
(1 to 1L),
(2 to 4L),
(2 to 4L),
(2 to 4L),
(2 to 4L),
(2 to 4L),
(3 to 9L),
(3 to 9L),
(3 to 9L),
(3 to 9L),
(3 to 9L),
(3 to 9L),
)
assertEquals(expected, list)
}
@Test
fun testDenseRank() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, denseRank().over { orderBy(e.departmentId) })
}
val expected = listOf(
(1 to 1L),
(1 to 1L),
(1 to 1L),
(2 to 2L),
(2 to 2L),
(2 to 2L),
(2 to 2L),
(2 to 2L),
(3 to 3L),
(3 to 3L),
(3 to 3L),
(3 to 3L),
(3 to 3L),
(3 to 3L),
)
assertEquals(expected, list)
}
@Test
fun testPercentRank() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, percentRank().over { orderBy(e.departmentId) })
}
println(list)
}
@Test
fun testCumeDist() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, cumeDist().over { orderBy(e.departmentId) })
}
println(list)
}
@Test
fun testNtile() {
val e = Meta.employee
val list = db.runQuery {
QueryDsl.from(e)
.orderBy(e.departmentId)
.selectNotNull(e.departmentId, ntile(5).over { orderBy(e.departmentId) })
}
val expected = listOf(
(1 to 1),
(1 to 1),
(1 to 1),
(2 to 2),
(2 to 2),
(2 to 2),
(2 to 3),
(2 to 3),
(3 to 3),
(3 to 4),
(3 to 4),
(3 to 4),
(3 to 5),
(3 to 5),
)
assertEquals(expected, list)
}
@Run(unless = [Dbms.MARIADB])
@Test
fun testLead() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lead(d.departmentId).over { orderBy(d.departmentId) }
val c3 = lead(d.departmentId, 2).over { orderBy(d.departmentId) }
val c4 = lead(d.departmentId, 2, literal(-1)).over { orderBy(d.departmentId) }
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3, c4)
}
println(list)
assertEquals(4, list.size)
list[0].let {
assertEquals(1, it[c1])
assertEquals(2, it[c2])
assertEquals(3, it[c3])
assertEquals(3, it[c4])
}
list[1].let {
assertEquals(2, it[c1])
assertEquals(3, it[c2])
assertEquals(4, it[c3])
assertEquals(4, it[c4])
}
list[2].let {
assertEquals(3, it[c1])
assertEquals(4, it[c2])
assertEquals(null, it[c3])
assertEquals(-1, it[c4])
}
list[3].let {
assertEquals(4, it[c1])
assertEquals(null, it[c2])
assertEquals(null, it[c3])
assertEquals(-1, it[c4])
}
}
@Run(onlyIf = [Dbms.MARIADB])
@Test
fun testLeadWithoutDefaultValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lead(d.departmentId).over { orderBy(d.departmentId) }
val c3 = lead(d.departmentId, 2).over { orderBy(d.departmentId) }
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.selectAsRecord(c1, c2, c3)
}
println(list)
assertEquals(4, list.size)
list[0].let {
assertEquals(1, it[c1])
assertEquals(2, it[c2])
assertEquals(3, it[c3])
}
list[1].let {
assertEquals(2, it[c1])
assertEquals(3, it[c2])
assertEquals(4, it[c3])
}
list[2].let {
assertEquals(3, it[c1])
assertEquals(4, it[c2])
assertEquals(null, it[c3])
}
list[3].let {
assertEquals(4, it[c1])
assertEquals(null, it[c2])
assertEquals(null, it[c3])
}
}
@Run(unless = [Dbms.MARIADB])
@Test
fun testLag() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lag(d.departmentId).over { orderBy(d.departmentId) }
val c3 = lag(d.departmentId, 2).over { orderBy(d.departmentId) }
val c4 = lag(d.departmentId, 2, literal(-1)).over { orderBy(d.departmentId) }
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3, c4)
}
println(list)
assertEquals(4, list.size)
list[0].let {
assertEquals(1, it[c1])
assertEquals(null, it[c2])
assertEquals(null, it[c3])
assertEquals(-1, it[c4])
}
list[1].let {
assertEquals(2, it[c1])
assertEquals(1, it[c2])
assertEquals(null, it[c3])
assertEquals(-1, it[c4])
}
list[2].let {
assertEquals(3, it[c1])
assertEquals(2, it[c2])
assertEquals(1, it[c3])
assertEquals(1, it[c4])
}
list[3].let {
assertEquals(4, it[c1])
assertEquals(3, it[c2])
assertEquals(2, it[c3])
assertEquals(2, it[c4])
}
}
@Run(onlyIf = [Dbms.MARIADB])
@Test
fun testLagWithoutDefaultValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lag(d.departmentId).over { orderBy(d.departmentId) }
val c3 = lag(d.departmentId, 2).over { orderBy(d.departmentId) }
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.selectAsRecord(c1, c2, c3)
}
println(list)
assertEquals(4, list.size)
list[0].let {
assertEquals(1, it[c1])
assertEquals(null, it[c2])
assertEquals(null, it[c3])
}
list[1].let {
assertEquals(2, it[c1])
assertEquals(1, it[c2])
assertEquals(null, it[c3])
}
list[2].let {
assertEquals(3, it[c1])
assertEquals(2, it[c2])
assertEquals(1, it[c3])
}
list[3].let {
assertEquals(4, it[c1])
assertEquals(3, it[c2])
assertEquals(2, it[c3])
}
}
@Test
fun testFirstValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = firstValue(d.departmentId).over { orderBy(d.departmentId) }
val c3 = firstValue(d.departmentId).over {
orderBy(d.departmentId)
rows(preceding(1))
}
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3)
}
println(list)
val expected = listOf(
Triple(1, 1, 1),
Triple(2, 1, 1),
Triple(3, 1, 2),
Triple(4, 1, 3),
)
assertEquals(expected, list)
}
@Test
fun testLastValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = lastValue(d.departmentId).over {
orderBy(d.departmentId)
rows(unboundedPreceding, unboundedFollowing)
}
val c3 = lastValue(d.departmentId).over {
orderBy(d.departmentId)
rows(currentRow, following(1))
}
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3)
}
println(list)
val expected = listOf(
Triple(1, 4, 2),
Triple(2, 4, 3),
Triple(3, 4, 4),
Triple(4, 4, 4),
)
assertEquals(expected, list)
}
@Run(unless = [Dbms.SQLSERVER])
@Test
fun testNthValue() {
val d = Meta.department
val c1 = d.departmentId
val c2 = nthValue(d.departmentId, 2).over {
orderBy(d.departmentId)
}
val c3 = nthValue(d.departmentId, 2).over {
orderBy(d.departmentId)
rows(preceding(2))
}
val list = db.runQuery {
QueryDsl.from(d)
.orderBy(d.departmentId)
.select(c1, c2, c3)
}
println(list)
val expected = listOf(
Triple(1, null, null),
Triple(2, 2, 2),
Triple(3, 2, 2),
Triple(4, 2, 3),
)
assertEquals(expected, list)
}
}
| 8
| null |
14
| 301
|
9fbc0b5652ee732583e977180cdc493e116e1022
| 13,271
|
komapper
|
Apache License 2.0
|
core/src/com/battleship/controller/firebase/FirebaseController.kt
|
sirimykland
| 241,909,234
| false
| null |
package com.battleship.controller.firebase
import com.battleship.model.Game
import com.battleship.model.PendingGame
/**
* Interface for firebase functionality
*/
interface FirebaseController {
/**
* Creates a new game document in firebase
* @param userId the id of the user setting up the game
* @param userName the name of the user setting up the game
* @param callback function invoked once the process has completed.
*/
fun createGame(userId: String, userName: String, callback: (game: Game?) -> Unit)
/**
* Method for joining an existing game.
* @param gameId the id of the game document
* @param userId the id of the player that should be added
* @param userName the name of the player that should be added
* @param callback function invoked once the process has completed.
*/
fun joinGame(gameId: String, userId: String, userName: String, callback: (game: Game?) -> Unit)
/**
* Method for leaving an existing game.
* @param gameId the id of the game document.
* @param playerId the id of the player that leaves.
* @param callback function invoked once the process has completed.
*/
fun leaveGame(gameId: String, playerId: String, callback: () -> Unit)
/**
* Method for registering a player's treasures
* @param gameId the id of the game document
* @param userId the id of the player
* @param treasures list containing the treasures that should be added
*/
fun registerTreasures(gameId: String, userId: String, treasures: List<Map<String, Any>>)
/**
* Method for registering a move in the game
* @param gameId the id of the game document
* @param x x coordinate of move
* @param y y coordinate of move
* @param playerId the id of the player making the move
* @param equipment The name of the equipment used by the player
*/
fun registerMove(gameId: String, x: Int, y: Int, playerId: String, equipment: String)
/**
* Method for setting the winner of the game
* @param gameId the id of the game document
* @param userId the id of the player that won
*/
fun setWinner(userId: String, gameId: String)
/**
* Method adding listener to all games where player2 is empty.
* @param callback function invoked once the process has completed.
*/
fun addPendingGamesListener(callback: (pendingGames: ArrayList<PendingGame>) -> Unit)
/**
* Function adding listener to a specific game. Listening to when players joins and register treasures.
* @param gameId the id of the game document
* @param playerId the id of the player
*/
fun addGameListener(gameId: String, playerId: String)
/**
* Function adding listener to a specific game. Listening to when players make moves.
* @param gameId the id of the game document
*/
fun addPlayListener(gameId: String)
}
| 0
|
Kotlin
|
2
| 5
|
a0087ef0500ea426967bec81c84ae071f8734128
| 2,939
|
Battleship-Project
|
MIT License
|
core/src/iosMain/kotlin/net/smarttuner/kaffeeverde/core/AtomicInteger.kt
|
smarttuner
| 521,540,434
| false
| null |
package net.smarttuner.kaffeeverde.core
import kotlin.concurrent.AtomicInt
actual class AtomicInteger actual constructor(value_: Int) {
private val _value = AtomicInt(value_)
actual val andIncrement: Int
get() = _value.addAndGet(1)
actual val andDecrement: Int
get() = _value.addAndGet(-1)
actual fun get(): Int {
return _value.value
}
actual fun set(newValue: Int) {
_value.value = newValue
}
actual fun getAndSet(newValue: Int): Int {
val oldValue = _value.value
_value.value = newValue
return oldValue
}
actual fun compareAndSet(expect: Int, update: Int): Boolean {
return _value.compareAndSet(expect, update)
}
actual fun getAndAdd(delta: Int): Int {
val oldValue = _value.value
_value.value += delta
return oldValue
}
actual fun incrementAndGet(): Int {
return addAndGet(1)
}
actual fun decrementAndGet(): Int {
return addAndGet(-1)
}
actual fun toByte(): Byte {
return _value.value.toByte()
}
actual fun toChar(): Char {
return _value.value.toChar()
}
actual fun toDouble(): Double {
return _value.value.toDouble()
}
actual fun toFloat(): Float {
return _value.value.toFloat()
}
actual fun toInt(): Int {
return _value.value.toInt()
}
actual fun toLong(): Long {
return _value.value.toLong()
}
actual fun toShort(): Short {
return _value.value.toShort()
}
actual var value: Int
get() = _value.value
set(value) {
_value.value = value
}
actual fun addAndGet(delta: Int): Int {
return _value.addAndGet(delta)
}
}
| 2
|
Kotlin
|
0
| 1
|
e293288eefc2bec4980d4f51b09103e81be82055
| 1,786
|
kaffeeverde
|
Apache License 2.0
|
kandy-echarts/src/main/kotlin/org/jetbrains/kotlinx/kandy/echarts/features/Grid.kt
|
Kotlin
| 502,039,936
| false
| null |
/*
* Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.ggdsl.echarts.features
import org.jetbrains.kotlinx.ggdsl.dsl.internal.PlotDslMarker
import org.jetbrains.kotlinx.ggdsl.echarts.settings.SizeUnit
import org.jetbrains.kotlinx.ggdsl.echarts.translator.option.EchartsGrid
import org.jetbrains.kotlinx.ggdsl.echarts.translator.option.toEchartsColor
import org.jetbrains.kotlinx.ggdsl.util.color.Color
import org.jetbrains.kotlinx.ggdsl.util.context.SelfInvocationContext
/**
* Grid settings.
*
* @property left distance between a grid component and the left side of the container. `10%` by default.
* @property top distance between a grid component and the top side of the container. `60` by default.
* @property right distance between a grid component and the right side of the container. `10%` by default.
* @property bottom distance between a grid component and the bottom side of the container. `60` by default.
* @property width width of a grid component. Adaptive by default.
* @property height height of a grid component. Adaptive by default.
* @property backgroundColor background [color][Color] of the grid.
* @property borderColor border [color][Color] of the grid.
* @property borderWidth border width of the grid. `0` by default.
* @property shadowBlur the size of shadow blur.
* @property shadowColor shadow [color][Color].
* @property tooltip [tooltip][Tooltip] settings in the coordinate system component.
*
* @see SizeUnit
* @see Color
* @see Tooltip
*/
@PlotDslMarker
public class Grid(
public var left: SizeUnit? = null,
public var top: SizeUnit? = null,
public var right: SizeUnit? = null,
public var bottom: SizeUnit? = null,
public var width: SizeUnit? = null,
public var height: SizeUnit? = null,
public var backgroundColor: Color? = null,
public var borderColor: Color? = null,
public var borderWidth: Int? = null,
public var shadowBlur: Int? = null,
public var shadowColor: Color? = null,
public var tooltip: Tooltip? = null,
) : SelfInvocationContext {
internal fun isEmpty(): Boolean =
left == null && top == null && right == null && bottom == null && width == null && height == null
&& backgroundColor == null && borderColor == null && borderWidth == null && shadowBlur == null
&& shadowColor == null && tooltip == null
internal fun isNotEmpty(): Boolean = !isEmpty()
internal fun toEchartsGrid(): EchartsGrid? =
if (this.isNotEmpty())
EchartsGrid(
left = left,
top = top,
right = right,
bottom = bottom,
width = width,
height = height,
backgroundColor = backgroundColor?.toEchartsColor(),
borderColor = borderColor?.toEchartsColor(),
borderWidth = borderWidth,
shadowBlur = shadowBlur,
shadowColor = shadowColor?.toEchartsColor(),
tooltip = tooltip?.toEchartsTooltip(),
)
else
null
}
| 78
| null |
2
| 98
|
0e54a419c188b5e6dbee8a95af5213c7ac978bb6
| 3,156
|
kandy
|
Apache License 2.0
|
butler/src/main/java/com/pyamsoft/fridge/butler/runner/WorkResult.kt
|
pyamsoft
| 371,196,339
| false
| null |
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.splattrak.alarm
sealed class WorkResult(open val id: String) {
data class Success internal constructor(override val id: String) : WorkResult(id)
data class Cancel internal constructor(override val id: String) : WorkResult(id)
data class Failure internal constructor(override val id: String) : WorkResult(id)
}
| 5
|
Kotlin
|
2
| 6
|
c5309984f17de290ce2fb82120b4699cc8227b65
| 929
|
tickertape
|
Apache License 2.0
|
app/src/test/java/com/raywenderlich/ingredisearch/SearchResultsTests.kt
|
amadeu01
| 129,528,231
| false
| null |
package com.raywenderlich.ingredisearch
import com.nhaarman.mockito_kotlin.*
import com.raywenderlich.ingredisearch.data.RecipeRepository
import com.raywenderlich.ingredisearch.data.RepositoryCallback
import com.raywenderlich.ingredisearch.searchresults.SearchResultsPresenter
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class SearchResultsTests {
private lateinit var repository: RecipeRepository
private lateinit var presenter: SearchResultsPresenter
private lateinit var view: SearchResultsPresenter.View
@Before
fun setup() {
repository = mock()
view = mock()
presenter = SearchResultsPresenter(repository)
presenter.attachView(view)
}
@Test
fun search_callsShowLoading() {
presenter.search("eggs")
verify(view).showLoading()
}
@Test
fun search_callsGetRecipes() {
presenter.search("eggs")
verify(repository).getRecipes(eq("eggs"), any())
}
@Test
fun search_withRepositoryHavingRecipes_callsShowRecipes() {
val recipe = Recipe("id", "title", "imageUrl", "sourceUrl", false)
val recipes = listOf<Recipe>(recipe)
doAnswer {
val callback: RepositoryCallback<List<Recipe>> = it.getArgument(1)
callback.onSuccess(recipes)
}.whenever(repository).getRecipes(eq("eggs"), any())
presenter.search("eggs")
verify(view).showRecipes(eq(recipes))
}
@Test
fun addFavorite_shouldUpdateRecipeStatus() {
val recipe = Recipe("id", "title", "imageUrl", "sourceUrl", false)
presenter.addFavorite(recipe)
Assert.assertTrue(recipe.isFavorited)
}
}
| 0
|
Kotlin
|
0
| 1
|
d2b4a96382df092c54e117135dccaccdcb68e1dc
| 1,701
|
ingredisearch
|
MIT License
|
app/src/main/java/com/ojhdtapp/parabox/domain/model/Tag.kt
|
Parabox-App
| 482,740,446
| false
| null |
package com.ojhdtapp.parabox.domain.model
import com.ojhdtapp.parabox.data.local.entity.TagEntity
data class Tag(
val value: String,
val id: Long,
) {
fun toTagEntity(): TagEntity = TagEntity(value, id)
}
| 0
|
Kotlin
|
4
| 83
|
a0d9ecd2c4c9c4895f8392723a5577adbf3685b5
| 219
|
Parabox
|
MIT License
|
src/test/kotlin/com/jillesvangurp/eskotlinwrapper/AbstractElasticSearchTest.kt
|
jillesvangurp
| 140,093,768
| false
| null |
package com.jillesvangurp.eskotlinwrapper
import com.fasterxml.jackson.databind.ObjectMapper
import org.elasticsearch.client.RestHighLevelClient
import org.elasticsearch.client.asyncIndexRepository
import org.elasticsearch.client.create
import org.elasticsearch.client.indexRepository
import org.elasticsearch.xcontent.XContentType
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import java.util.UUID
import kotlin.reflect.KClass
class TestIndex<T : Any>(
val clazz: KClass<T>,
val esClient: RestHighLevelClient,
val repo: IndexRepository<T>,
val asyncRepo: AsyncIndexRepository<T>
)
inline fun <reified T : Any, O> withTestIndex(
index: String? = null,
createIndex: Boolean = true,
deleteIndexAfterTest: Boolean = createIndex,
refreshAllowed: Boolean = true,
mappingsAndSettingsResource: String = "/testmodel-settings.json",
block: TestIndex<T>.() -> O
): O {
val esClient = create(port = 9999)
val repo = esClient.indexRepository(
index = if(index != null) "$index-${UUID.randomUUID()}" else "test-${UUID.randomUUID()}",
refreshAllowed = refreshAllowed,
modelReaderAndWriter = JacksonModelReaderAndWriter(
T::class,
ObjectMapper().findAndRegisterModules()
)
)
val asyncRepo = esClient.asyncIndexRepository(
index = index ?: "test-${UUID.randomUUID()}",
refreshAllowed = refreshAllowed,
modelReaderAndWriter = JacksonModelReaderAndWriter(
T::class,
ObjectMapper().findAndRegisterModules()
)
)
if (createIndex) {
val mappingsAndSettings = TestIndex::class.java.getResource(mappingsAndSettingsResource).readText()
repo.createIndex {
source(mappingsAndSettings, XContentType.JSON)
}
}
val result = block.invoke(TestIndex(T::class, esClient, repo, asyncRepo))
if (deleteIndexAfterTest) {
repo.deleteIndex()
}
return result
}
open class AbstractElasticSearchTest(
val indexPrefix: String = "test",
val createIndex: Boolean = true,
val deleteIndexAfterTest: Boolean = true
) {
lateinit var repository: IndexRepository<TestModel>
lateinit var asyncRepository: AsyncIndexRepository<TestModel>
lateinit var esClient: RestHighLevelClient
lateinit var indexName: String
@BeforeEach
fun before() {
// sane defaults
esClient = create(port = 9999)
// each test gets a fresh index
indexName = "$indexPrefix-" + randomId()
repository = esClient.indexRepository(
index = indexName,
refreshAllowed = true,
modelReaderAndWriter = JacksonModelReaderAndWriter(
TestModel::class,
ObjectMapper().findAndRegisterModules()
)
)
asyncRepository = esClient.asyncIndexRepository(
index = indexName,
refreshAllowed = true,
modelReaderAndWriter = JacksonModelReaderAndWriter(
TestModel::class,
ObjectMapper().findAndRegisterModules()
)
)
if (createIndex) {
val settings = this.javaClass.getResource("/testmodel-settings.json").readText()
repository.createIndex {
source(settings, XContentType.JSON)
}
}
}
@AfterEach
fun after() {
// delete the index after the test
if (deleteIndexAfterTest) {
repository.deleteIndex()
}
}
}
| 6
| null |
18
| 96
|
c3dc1a1738d2382b775662ba0db4510966b7d717
| 3,555
|
es-kotlin-wrapper-client
|
MIT License
|
app/src/main/java/com/nilsinojiya/cowin20/viewModels/MyViewModelFactory.kt
|
nilsinojiya1
| 403,682,420
| false
|
{"Kotlin": 64236}
|
package com.nilsinojiya.cowin20.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.nilsinojiya.cowin20.repositorys.MainRepository
class MyViewModelFactory(private val repository: MainRepository): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
MainViewModel(this.repository) as T
} else {
throw IllegalArgumentException("Not Found")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7f91fd33528f7e3134c7685c25f60ad93b201595
| 561
|
CoWin2.0
|
MIT License
|
app/src/main/java/com/softartdev/poder/injection/module/AppModule.kt
|
softartdev
| 117,355,191
| false
| null |
package com.softartdev.poder.injection.module
import android.app.Application
import android.content.Context
import com.softartdev.poder.injection.ApplicationContext
import dagger.Module
import dagger.Provides
@Module(includes = [ApiModule::class, MediaModule::class])
class AppModule(private val application: Application) {
@Provides
internal fun provideApplication(): Application {
return application
}
@Provides
@ApplicationContext
internal fun provideContext(): Context {
return application
}
}
| 0
|
Kotlin
|
0
| 0
|
c9be64e287910bb157e61e2c39ea324ab6a95c17
| 545
|
Poder
|
The Unlicense
|
lib/src/test/kotlin/seleniumtestinglib/locators/ByTitleTest.kt
|
lsoares
| 551,381,828
| false
|
{"Kotlin": 134591, "JavaScript": 354}
|
package seleniumtestinglib.locators
import org.junit.jupiter.api.extension.ExtendWith
import org.openqa.selenium.remote.RemoteWebDriver
import seleniumtestinglib.DriverLifeCycle
import seleniumtestinglib.queries.JsType.Companion.asJsExpression
import seleniumtestinglib.render
import kotlin.test.Test
import kotlin.test.assertEquals
@ExtendWith(DriverLifeCycle::class)
class ByTitleTest(private val driver: RemoteWebDriver) {
@Test
fun `by title`() {
driver.render("<div title='foobar'>Hello World!</div>")
val result = driver.findElement(ByTitle("foobar"))
assertEquals("Hello World!", result.text)
}
@Test
fun `by title on svg`() {
driver.render(
"""<svg>
<title>foobar</title>
<g><path /></g>
</svg>"""
)
val result = driver.findElement(ByTitle("foobar"))
assertEquals("foobar", result.text)
}
@Test
fun `not exact`() {
driver.render("<div title='foobar'>Hello World!</div>")
val result = driver.findElement(ByTitle("FOO", exact = false))
assertEquals("Hello World!", result.text)
}
@Test
fun `not exact 2`() {
driver.render("<div title='foobar'>Hello World!</div>")
val result = driver.findElement(ByTitle("FOO").inexact())
assertEquals("Hello World!", result.text)
}
@Test
fun regex() {
driver.render("<div title='foobar'>Hello World!</div>")
val result = driver.findElement(ByTitle("/FOO/i".asJsExpression()))
assertEquals("Hello World!", result.text)
}
}
| 1
|
Kotlin
|
0
| 8
|
861a4ea4fb8ca035144b2df999a37fda0c5aa45d
| 1,618
|
selenium-testing-library
|
MIT License
|
src/commonMain/kotlin/baaahs/gl/glsl/GlslCode.kt
|
baaahs
| 174,897,412
| false
| null |
package baaahs.gl.glsl
import baaahs.englishize
import baaahs.getValue
import baaahs.gl.patch.ContentType
import baaahs.gl.shader.dialect.findContentType
import baaahs.plugin.PluginRef
import baaahs.plugin.Plugins
import baaahs.unknown
import baaahs.util.Logger
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
class GlslCode(
val src: String,
val statements: List<GlslStatement>
) {
val globalVarNames = hashSetOf<String>()
val functionNames = hashSetOf<String>()
val structsByName = mutableMapOf<String, GlslStruct>()
init {
statements.forEach {
when (it) {
is GlslStruct -> {
structsByName[it.name] = it
it.varName?.let { varName -> globalVarNames += varName }
}
is GlslVar -> globalVarNames.add(it.name)
is GlslFunction -> functionNames.add(it.name)
is GlslOther -> {}
else -> {
if (it.fullText.isNotBlank()) {
logger.warn { "unrecognized GLSL: ${it.fullText} at ${it.lineNumber}" }
}
}
}
}
}
val symbolNames = globalVarNames + functionNames + structsByName.keys
val globalVars: Collection<GlslVar> get() =
statements.filterIsInstance<GlslVar>() +
structs.filter { it.varName != null }
.map { it.getSyntheticVar() }
val globalInputVars: Collection<GlslVar> get() = globalVars.filter { it.isUniform || it.isVarying }
val uniforms: Collection<GlslVar> get() = globalVars.filter { it.isUniform }
val functions: Collection<GlslFunction> get() = statements.filterIsInstance<GlslFunction>()
val structs: Collection<GlslStruct> get() = statements.filterIsInstance<GlslStruct>()
fun findFunctionOrNull(name: String) =
functions.find { it.name == name}
fun findFunction(name: String) =
findFunctionOrNull(name)
?: error(unknown("function", name, functions.map { it.name }))
// TODO: We ought to ignore e.g. local variables, or strings that only appear in comments.
fun refersToGlobal(name: String): Boolean {
return src.contains(name)
}
companion object {
private val logger = Logger<GlslCode>()
fun replaceCodeWords(originalText: String, replaceFn: (String) -> String): String {
val buf = StringBuilder()
var inComment = false
var inDotTraversal = false
Regex(
"(.*?)" +
"(" +
"[a-zA-Z_][a-zA-Z0-9_]*" + // Any valid symbol.
"|[0-9]+[.][0-9]*" + // Floats like 1. or 1.1.
"|[.][0-9]+" + // Floats like .1.
"|[.\n]" + // '.' or newline.
"|$" + // EOL.
")", RegexOption.MULTILINE)
.findAll(originalText)
.forEach { matchResult ->
val (before, str) = matchResult.destructured
buf.append(before)
when (str) {
"//" -> {
inComment = true; buf.append(str)
}
"." -> {
if (!inComment) inDotTraversal = true; buf.append(str)
}
"\n" -> {
inComment = false; buf.append(str)
}
else -> {
buf.append(
if (inComment || inDotTraversal) str
else replaceFn(str)
)
inDotTraversal = false
}
}
}
return buf.toString()
}
}
fun interface Substitutions {
fun substitute(word: String): String
}
interface GlslStatement {
val name: String
val fullText: String
val lineNumber: Int?
val comments: List<String>
fun toGlsl(fileNumber: Int?, substitutions: Substitutions): String {
return substituteGlsl(fullText, substitutions, fileNumber)
}
fun substituteGlsl(text: String, substitutions: Substitutions, fileNumber: Int?): String {
return lineNumber?.let { "\n#line $lineNumber${fileNumber?.let { " $it" } ?: ""}\n" } +
replaceCodeWords(text) { substitutions.substitute(it) }
}
}
data class GlslOther(
override val name: String,
override val fullText: String,
override val lineNumber: Int?,
override val comments: List<String> = emptyList()
) : GlslStatement {
}
data class GlslStruct(
override val name: String,
val fields: Map<String, GlslType>,
val varName: String?,
val isUniform: Boolean = false,
override val fullText: String,
override val lineNumber: Int? = null,
override val comments: List<String> = emptyList()
) : GlslStatement {
val glslType: GlslType.Struct =
GlslType.Struct(name, fields.map { (name, type) -> GlslType.Field(name, type) })
fun getSyntheticVar(): GlslVar {
val structType = GlslType.Struct(this)
val fullText = "${if (isUniform) "uniform " else ""}$name $varName;"
return GlslVar(varName!!, structType, fullText, lineNumber = lineNumber, comments = comments)
}
}
interface GlslArgSite {
val name: String
val title: String
val type: GlslType
val isVarying: Boolean
val isGlobalInput: Boolean
val isAbstractFunction: Boolean
val hint: Hint?
val lineNumber: Int?
fun findInjectedData(plugins: Plugins): Map<String, ContentType> = emptyMap()
}
data class GlslVar(
override val name: String,
override val type: GlslType,
override val fullText: String = "",
val isConst: Boolean = false,
val isUniform: Boolean = false,
override val isVarying: Boolean = false,
val initExpr: String? = null,
override val lineNumber: Int? = null,
override val comments: List<String> = emptyList()
) : GlslStatement, GlslArgSite {
override val title get() = name.englishize()
override val isGlobalInput: Boolean get() = isUniform || isVarying
override val isAbstractFunction: Boolean get() = false
override val hint: Hint? by lazy { Hint.parse(comments.joinToString(" ") { it.trim() }, lineNumber) }
val deferInitialization: Boolean = !isConst && initExpr != null
fun declarationToGlsl(fileNumber: Int?, substitutions: Substitutions): String {
val declaration = if (deferInitialization) {
fullText.substring(0, fullText.indexOf(initExpr!!)) + ";"
} else fullText
return substituteGlsl(declaration, substitutions, fileNumber)
}
fun assignmentToGlsl(fileNumber: Int?, substitutions: Substitutions): String {
val assignment = " $name$initExpr;"
return substituteGlsl(assignment, substitutions, fileNumber)
}
}
class Hint(
val pluginRef: PluginRef?,
val config: JsonObject?,
private val tags: List<Pair<String, String>>,
val lineNumber: Int? = null
) {
fun tag(name: String) =
tags.find { it.first == name }?.second
fun tags(tagName: String): List<String> =
tags.filter { it.first == tagName }.map { it.second }
fun contentType(plugins: Plugins) = contentType("type", plugins)
fun contentType(tagName: String, plugins: Plugins) =
tag(tagName)?.let { plugins.resolveContentType(it) }
companion object {
fun from(comments: List<String>, lineNumber: Int? = null): Hint? =
parse(comments.joinToString(" ") { it.trim() }, lineNumber)
fun parse(commentString: String, lineNumber: Int? = null): Hint? {
var pluginRef: PluginRef? = null
var config: JsonObject? = null
val tags = arrayListOf<Pair<String, String>>()
Regex("@(@?[^@]+)").findAll(commentString).forEach { match ->
val tag = match.groupValues[1].trim()
if (tag.startsWith("@")) {
val string = commentString.trimStart('@').trim()
val parts = string.split(" ")
val type = parts.first()
pluginRef = PluginRef.from(type)
config = buildJsonObject {
parts.subList(1, parts.size).forEach { s ->
val kv = s.split("=")
put(kv.first(), kv.subList(1, kv.size).joinToString("="))
}
}
} else {
val parts = tag.split(Regex("\\s"), limit = 2)
when (parts.size) {
0 -> {} // No-op.
1 -> tags.add(parts[0] to parts[0])
2 -> tags.add(parts[0] to parts[1].trim())
}
}
}
return if (pluginRef != null || config != null || tags.isNotEmpty()) {
Hint(pluginRef, config, tags, lineNumber)
} else null
}
}
}
data class GlslFunction(
override val name: String,
val returnType: GlslType,
val params: List<GlslParam>,
override val fullText: String,
override val lineNumber: Int? = null,
override val comments: List<String> = emptyList(),
val isAbstract: Boolean = false
) : GlslStatement, GlslArgSite {
override val title: String get() = name.englishize()
override val type: GlslType get() = returnType
override val isVarying: Boolean get() = true
override val isGlobalInput: Boolean get() = false
override val isAbstractFunction: Boolean get() = isAbstract
override val hint: Hint? by lazy { Hint.from(comments, lineNumber) }
override fun findInjectedData(plugins: Plugins): Map<String, ContentType> {
return params.associate { it.name to (it.findContentType(plugins, this) ?: ContentType.Unknown) }
}
override fun toGlsl(fileNumber: Int?, substitutions: Substitutions): String {
// Chomp trailing ';' if it's an abstract method.
return super.toGlsl(fileNumber, substitutions)
.let { if (isAbstract) it.trimEnd(';') else it }
}
fun invoker(namespace: Namespace, portMap: Map<String, GlslExpr>): Invoker {
return object : Invoker {
override fun toGlsl(resultVar: String): String {
val assignment = if (returnType != GlslType.Void) {
"$resultVar = "
} else ""
val args = params.joinToString(", ") { glslParam ->
if (glslParam.isOut)
resultVar
else
portMap[glslParam.name]?.s
?: "/* huh? ${glslParam.name} */"
}
return assignment + namespace.qualify(name) + "($args)"
}
}
}
}
data class GlslParam(
override val name: String,
override val type: GlslType,
val isIn: Boolean = false,
val isOut: Boolean = false,
override val lineNumber: Int? = null,
val comments: List<String> = emptyList()
) : GlslArgSite {
override val title: String get() = name.englishize()
override val isVarying: Boolean get() = true
override val isGlobalInput: Boolean get() = false
override val hint: Hint? by lazy { Hint.from(comments, lineNumber) }
override val isAbstractFunction: Boolean get() = false
}
class Namespace(private val prefix: String) {
fun qualify(name: String) = build(prefix, name)
fun internalQualify(name: String) = build(prefix + "i", name)
// Because double underscores are reserved in GLSL.
private fun build(prefix: String, name: String): String {
return if (name.startsWith('_')) {
"${prefix}x$name"
} else {
"${prefix}_$name"
}
}
}
interface Invoker {
fun toGlsl(resultVar: String): String
}
}
| 88
| null |
6
| 40
|
2aca7de985798cd222b8427841052742cf0fe453
| 13,005
|
sparklemotion
|
MIT License
|
MeowFramework/src/main/kotlin/meow/widget/MeowCircleImageView.kt
|
oneHamidreza
| 239,642,692
| false
| null |
/*
* Copyright (C) 2020 <NAME> & <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 meow.widget
import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.etebarian.meowframework.R
import meow.ktx.avoidException
import kotlin.math.min
/**
* Meow Circle Image View class.
*
* @author <NAME>
* @version 1.0.0
* @since 2020-04-18
*/
@Suppress("LeakingThis", "MemberVisibilityCanBePrivate")
open class MeowCircleImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttrs: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttrs) {
var strokeColor = 0
set(value) {
field = value
if (isAttachedToWindow)
invalidate()
}
var strokeWidth = 0f
set(value) {
field = value
if (isAttachedToWindow)
invalidate()
}
init {
setAttributesFromXml(attrs, R.styleable.MeowCircleImageView) {
strokeColor =
it.getColor(R.styleable.MeowCircleImageView_meow_strokeColor, strokeColor)
strokeWidth =
it.getDimension(R.styleable.MeowCircleImageView_meow_strokeWidth, strokeWidth)
}
strokeColor = strokeColor
strokeWidth = strokeWidth
}
override fun onDraw(canvas: Canvas) {
avoidException {
val drawable = drawable ?: return
if (width == 0 || height == 0)
return
val b: Bitmap = (drawable as BitmapDrawable).bitmap
val bitmap: Bitmap = b.copy(Bitmap.Config.ARGB_8888, true)
val w = width
val roundBitmap: Bitmap = getCroppedBitmap(bitmap, w)
canvas.drawBitmap(roundBitmap, 0f, 0f, null)
}
}
private fun getCroppedBitmap(bmp: Bitmap, radius: Int): Bitmap {
val bitmap: Bitmap
bitmap = if (bmp.width != radius || bmp.height != radius) {
val smallest: Float = min(bmp.width.toFloat(), bmp.height.toFloat())
val factor = smallest / radius
Bitmap.createScaledBitmap(
bmp,
(bmp.width / factor).toInt(),
(bmp.height / factor).toInt(),
false
)
} else {
bmp
}
val output: Bitmap = Bitmap.createBitmap(
radius, radius,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(output)
val paint = Paint()
val rect = Rect(0, 0, radius, radius)
paint.isAntiAlias = true
paint.isFilterBitmap = true
paint.isDither = true
canvas.drawARGB(0, 0, 0, 0)
canvas.drawCircle(
radius / 2 + 0.7f,
radius / 2 + 0.7f, radius / 2 + 0.1f, paint
)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
canvas.drawBitmap(bitmap, rect, rect, paint)
paint.style = Paint.Style.STROKE
paint.strokeWidth = strokeWidth
paint.color = strokeColor
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f, radius / 2 + 0.1f, paint)
return output
}
}
| 0
|
Kotlin
|
18
| 124
|
deb3efbe8079d784d5850870b7b54ffc9721ffb4
| 3,824
|
Meow-Framework-MVVM
|
Apache License 2.0
|
app/src/main/java/cz/movapp/app/ui/children/ChildrenFairyTalePlayerAdapter.kt
|
cesko-digital
| 478,685,113
| false
|
{"Kotlin": 198789, "Ruby": 3026, "Java": 78}
|
package cz.movapp.app.ui.children
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import cz.movapp.app.R
import cz.movapp.app.data.FairyTale
import cz.movapp.app.data.LanguagePair
import cz.movapp.app.databinding.FairyTaleColumnBinding
enum class EmphasizerEvaluation {
LOWER,
EQUAL,
GREATER
}
class ChildrenFairyTalePlayerAdapter (
private val dataset: FairyTale,
private val isReversed: Boolean,
var onItemClicked: (String) -> Unit = {},
): RecyclerView.Adapter<ChildrenFairyTalePlayerAdapter.ItemViewHolder>() {
var langPair = LanguagePair.getDefault()
private var emphesizer : ((Int) -> EmphasizerEvaluation)? = null
private var columnCallback : ((Int) -> Unit)? = null
class ItemViewHolder(val binding: FairyTaleColumnBinding) : RecyclerView.ViewHolder(binding.root) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
return ItemViewHolder(FairyTaleColumnBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
override fun getItemCount(): Int {
return dataset.sections!!.size
}
fun setEmphasizer(emp: (Int)-> EmphasizerEvaluation) {
emphesizer = emp
}
fun setColumnCallback(c: (Int)-> Unit) {
columnCallback = c
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = dataset.sections!![position]
val context = holder.binding.root.context
holder.binding.apply {
fairyTaleColumnText.text = item.getValue(
if (isReversed) { langPair.to.langCode } else { langPair.from.langCode }
)?.text ?: ""
fairyTaleColumnText.setTextColor(
ContextCompat.getColor(
context, R.color.playerUnRead
)
)
fairyTaleColumnText.setOnClickListener {
if (columnCallback != null) {
columnCallback!!(position)
}
}
if (emphesizer != null) {
val textColor = when (emphesizer!!(position)) {
EmphasizerEvaluation.LOWER -> R.color.playerRead
EmphasizerEvaluation.EQUAL -> R.color.playerReading
EmphasizerEvaluation.GREATER -> R.color.playerUnRead
}
fairyTaleColumnText.setTextColor(
ContextCompat.getColor(
context, textColor
)
)
}
}
}
}
| 14
|
Kotlin
|
4
| 7
|
6271a2bcda417a8eebae1d3dcf1c10664735d927
| 2,665
|
movapp-android
|
MIT License
|
src/controller/java/generated/java/matter/devicecontroller/cluster/clusters/ElectricalMeasurementCluster.kt
|
nrfconnect
| 319,609,059
| false
|
{"C++": 23522189, "Java": 4933921, "Python": 3707868, "C": 2258497, "Kotlin": 1567297, "Objective-C": 1368441, "ZAP": 814351, "Objective-C++": 756316, "Shell": 291692, "CMake": 176244, "Jinja": 103624, "Dockerfile": 70720, "Swift": 30181, "JavaScript": 2379, "Emacs Lisp": 1042, "Tcl": 311}
|
/*
*
* Copyright (c) 2023 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package matter.devicecontroller.cluster.clusters
import java.util.ArrayList
class ElectricalMeasurementCluster(private val endpointId: UShort) {
companion object {
const val CLUSTER_ID: UInt = 2820u
}
fun getProfileInfoCommand(callback: DefaultClusterCallback) {
// Implementation needs to be added here
}
fun getProfileInfoCommand(callback: DefaultClusterCallback, timedInvokeTimeoutMs: Int) {
// Implementation needs to be added here
}
fun getMeasurementProfileCommand(
callback: DefaultClusterCallback,
attributeId: Integer,
startTime: Long,
numberOfIntervals: Integer
) {
// Implementation needs to be added here
}
fun getMeasurementProfileCommand(
callback: DefaultClusterCallback,
attributeId: Integer,
startTime: Long,
numberOfIntervals: Integer,
timedInvokeTimeoutMs: Int
) {
// Implementation needs to be added here
}
interface GeneratedCommandListAttributeCallback {
fun onSuccess(value: ArrayList<Long>)
fun onError(ex: Exception)
fun onSubscriptionEstablished(subscriptionId: Long)
}
interface AcceptedCommandListAttributeCallback {
fun onSuccess(value: ArrayList<Long>)
fun onError(ex: Exception)
fun onSubscriptionEstablished(subscriptionId: Long)
}
interface EventListAttributeCallback {
fun onSuccess(value: ArrayList<Long>)
fun onError(ex: Exception)
fun onSubscriptionEstablished(subscriptionId: Long)
}
interface AttributeListAttributeCallback {
fun onSuccess(value: ArrayList<Long>)
fun onError(ex: Exception)
fun onSubscriptionEstablished(subscriptionId: Long)
}
fun readMeasurementTypeAttribute(callback: LongAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasurementTypeAttribute(
callback: LongAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcVoltageAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcVoltageAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcVoltageMinAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcVoltageMinAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcVoltageMaxAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcVoltageMaxAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcCurrentMinAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcCurrentMinAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcCurrentMaxAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcCurrentMaxAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcPowerAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcPowerAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcPowerMinAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcPowerMinAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcPowerMaxAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcPowerMaxAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcVoltageMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcVoltageMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcVoltageDivisorAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcVoltageDivisorAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcCurrentMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcCurrentMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcCurrentDivisorAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcCurrentDivisorAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcPowerMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcPowerMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readDcPowerDivisorAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeDcPowerDivisorAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcFrequencyAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcFrequencyAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcFrequencyMinAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcFrequencyMinAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcFrequencyMaxAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcFrequencyMaxAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readNeutralCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeNeutralCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readTotalActivePowerAttribute(callback: LongAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeTotalActivePowerAttribute(
callback: LongAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readTotalReactivePowerAttribute(callback: LongAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeTotalReactivePowerAttribute(
callback: LongAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readTotalApparentPowerAttribute(callback: LongAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeTotalApparentPowerAttribute(
callback: LongAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasured1stHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasured1stHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasured3rdHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasured3rdHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasured5thHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasured5thHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasured7thHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasured7thHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasured9thHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasured9thHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasured11thHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasured11thHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasuredPhase1stHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasuredPhase1stHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasuredPhase3rdHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasuredPhase3rdHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasuredPhase5thHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasuredPhase5thHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasuredPhase7thHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasuredPhase7thHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasuredPhase9thHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasuredPhase9thHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readMeasuredPhase11thHarmonicCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeMeasuredPhase11thHarmonicCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcFrequencyMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcFrequencyMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcFrequencyDivisorAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcFrequencyDivisorAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readPowerMultiplierAttribute(callback: LongAttributeCallback) {
// Implementation needs to be added here
}
fun subscribePowerMultiplierAttribute(
callback: LongAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readPowerDivisorAttribute(callback: LongAttributeCallback) {
// Implementation needs to be added here
}
fun subscribePowerDivisorAttribute(
callback: LongAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readHarmonicCurrentMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeHarmonicCurrentMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readPhaseHarmonicCurrentMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribePhaseHarmonicCurrentMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readInstantaneousVoltageAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeInstantaneousVoltageAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readInstantaneousLineCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeInstantaneousLineCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readInstantaneousActiveCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeInstantaneousActiveCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readInstantaneousReactiveCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeInstantaneousReactiveCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readInstantaneousPowerAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeInstantaneousPowerAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageMinAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageMinAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageMaxAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageMaxAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentMinAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentMinAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentMaxAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentMaxAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerMinAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerMinAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerMaxAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerMaxAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readReactivePowerAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeReactivePowerAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readApparentPowerAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeApparentPowerAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readPowerFactorAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribePowerFactorAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsVoltageMeasurementPeriodAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun writeAverageRmsVoltageMeasurementPeriodAttribute(
callback: DefaultClusterCallback,
value: Integer
) {
// Implementation needs to be added here
}
fun writeAverageRmsVoltageMeasurementPeriodAttribute(
callback: DefaultClusterCallback,
value: Integer,
timedWriteTimeoutMs: Int
) {
// Implementation needs to be added here
}
fun subscribeAverageRmsVoltageMeasurementPeriodAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsUnderVoltageCounterAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun writeAverageRmsUnderVoltageCounterAttribute(
callback: DefaultClusterCallback,
value: Integer
) {
// Implementation needs to be added here
}
fun writeAverageRmsUnderVoltageCounterAttribute(
callback: DefaultClusterCallback,
value: Integer,
timedWriteTimeoutMs: Int
) {
// Implementation needs to be added here
}
fun subscribeAverageRmsUnderVoltageCounterAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsExtremeOverVoltagePeriodAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun writeRmsExtremeOverVoltagePeriodAttribute(callback: DefaultClusterCallback, value: Integer) {
// Implementation needs to be added here
}
fun writeRmsExtremeOverVoltagePeriodAttribute(
callback: DefaultClusterCallback,
value: Integer,
timedWriteTimeoutMs: Int
) {
// Implementation needs to be added here
}
fun subscribeRmsExtremeOverVoltagePeriodAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsExtremeUnderVoltagePeriodAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun writeRmsExtremeUnderVoltagePeriodAttribute(callback: DefaultClusterCallback, value: Integer) {
// Implementation needs to be added here
}
fun writeRmsExtremeUnderVoltagePeriodAttribute(
callback: DefaultClusterCallback,
value: Integer,
timedWriteTimeoutMs: Int
) {
// Implementation needs to be added here
}
fun subscribeRmsExtremeUnderVoltagePeriodAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageSagPeriodAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun writeRmsVoltageSagPeriodAttribute(callback: DefaultClusterCallback, value: Integer) {
// Implementation needs to be added here
}
fun writeRmsVoltageSagPeriodAttribute(
callback: DefaultClusterCallback,
value: Integer,
timedWriteTimeoutMs: Int
) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageSagPeriodAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageSwellPeriodAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun writeRmsVoltageSwellPeriodAttribute(callback: DefaultClusterCallback, value: Integer) {
// Implementation needs to be added here
}
fun writeRmsVoltageSwellPeriodAttribute(
callback: DefaultClusterCallback,
value: Integer,
timedWriteTimeoutMs: Int
) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageSwellPeriodAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcVoltageMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcVoltageMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcVoltageDivisorAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcVoltageDivisorAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcCurrentMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcCurrentMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcCurrentDivisorAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcCurrentDivisorAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcPowerMultiplierAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcPowerMultiplierAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcPowerDivisorAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcPowerDivisorAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readOverloadAlarmsMaskAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun writeOverloadAlarmsMaskAttribute(callback: DefaultClusterCallback, value: Integer) {
// Implementation needs to be added here
}
fun writeOverloadAlarmsMaskAttribute(
callback: DefaultClusterCallback,
value: Integer,
timedWriteTimeoutMs: Int
) {
// Implementation needs to be added here
}
fun subscribeOverloadAlarmsMaskAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readVoltageOverloadAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeVoltageOverloadAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readCurrentOverloadAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeCurrentOverloadAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcOverloadAlarmsMaskAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun writeAcOverloadAlarmsMaskAttribute(callback: DefaultClusterCallback, value: Integer) {
// Implementation needs to be added here
}
fun writeAcOverloadAlarmsMaskAttribute(
callback: DefaultClusterCallback,
value: Integer,
timedWriteTimeoutMs: Int
) {
// Implementation needs to be added here
}
fun subscribeAcOverloadAlarmsMaskAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcVoltageOverloadAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcVoltageOverloadAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcCurrentOverloadAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcCurrentOverloadAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcActivePowerOverloadAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcActivePowerOverloadAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcReactivePowerOverloadAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcReactivePowerOverloadAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsOverVoltageAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAverageRmsOverVoltageAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsUnderVoltageAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAverageRmsUnderVoltageAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsExtremeOverVoltageAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsExtremeOverVoltageAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsExtremeUnderVoltageAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsExtremeUnderVoltageAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageSagAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageSagAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageSwellAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageSwellAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readLineCurrentPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeLineCurrentPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActiveCurrentPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActiveCurrentPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readReactiveCurrentPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeReactiveCurrentPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltagePhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltagePhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageMinPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageMinPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageMaxPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageMaxPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentMinPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentMinPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentMaxPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentMaxPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerMinPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerMinPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerMaxPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerMaxPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readReactivePowerPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeReactivePowerPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readApparentPowerPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeApparentPowerPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readPowerFactorPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribePowerFactorPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsVoltageMeasurementPeriodPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAverageRmsVoltageMeasurementPeriodPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsOverVoltageCounterPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAverageRmsOverVoltageCounterPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsUnderVoltageCounterPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAverageRmsUnderVoltageCounterPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsExtremeOverVoltagePeriodPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsExtremeOverVoltagePeriodPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsExtremeUnderVoltagePeriodPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsExtremeUnderVoltagePeriodPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageSagPeriodPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageSagPeriodPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageSwellPeriodPhaseBAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageSwellPeriodPhaseBAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readLineCurrentPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeLineCurrentPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActiveCurrentPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActiveCurrentPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readReactiveCurrentPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeReactiveCurrentPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltagePhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltagePhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageMinPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageMinPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageMaxPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageMaxPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentMinPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentMinPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsCurrentMaxPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsCurrentMaxPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerMinPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerMinPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readActivePowerMaxPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeActivePowerMaxPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readReactivePowerPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeReactivePowerPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readApparentPowerPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeApparentPowerPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readPowerFactorPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribePowerFactorPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsVoltageMeasurementPeriodPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAverageRmsVoltageMeasurementPeriodPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsOverVoltageCounterPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAverageRmsOverVoltageCounterPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAverageRmsUnderVoltageCounterPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAverageRmsUnderVoltageCounterPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsExtremeOverVoltagePeriodPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsExtremeOverVoltagePeriodPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsExtremeUnderVoltagePeriodPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsExtremeUnderVoltagePeriodPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageSagPeriodPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageSagPeriodPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readRmsVoltageSwellPeriodPhaseCAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeRmsVoltageSwellPeriodPhaseCAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readGeneratedCommandListAttribute(callback: GeneratedCommandListAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeGeneratedCommandListAttribute(
callback: GeneratedCommandListAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAcceptedCommandListAttribute(callback: AcceptedCommandListAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAcceptedCommandListAttribute(
callback: AcceptedCommandListAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readEventListAttribute(callback: EventListAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeEventListAttribute(
callback: EventListAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readAttributeListAttribute(callback: AttributeListAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeAttributeListAttribute(
callback: AttributeListAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readFeatureMapAttribute(callback: LongAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeFeatureMapAttribute(
callback: LongAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
fun readClusterRevisionAttribute(callback: IntegerAttributeCallback) {
// Implementation needs to be added here
}
fun subscribeClusterRevisionAttribute(
callback: IntegerAttributeCallback,
minInterval: Int,
maxInterval: Int
) {
// Implementation needs to be added here
}
}
| 7
|
C++
|
53
| 44
|
e734b7924bf2b6bdc78e20d8416267f42ba95675
| 46,932
|
sdk-connectedhomeip
|
Apache License 2.0
|
character_detail/src/main/java/com/ezike/tobenna/starwarssearch/character_detail/ui/views/specie/SpecieViewState.kt
|
Ezike
| 294,171,829
| false
| null |
package com.ezike.tobenna.starwarssearch.character_detail.ui.views.specie
import com.ezike.tobenna.starwarssearch.character_search.model.SpecieModel
import com.ezike.tobenna.starwarssearch.presentation.base.ViewState
data class SpecieViewState(
val species: List<SpecieModel> = emptyList(),
val errorMessage: String? = null,
val isLoading: Boolean = false,
val showEmpty: Boolean = false,
val showError: Boolean = false,
val showTitle: Boolean = false,
val showSpecies: Boolean = false
) : ViewState
| 0
|
Kotlin
|
28
| 172
|
792caabf5a29b8bb4698c36c3257916a1cf6611d
| 530
|
StarWarsSearch-MVI
|
Apache License 2.0
|
app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/SourceItem.kt
|
arkon
| 127,645,159
| false
| null |
package eu.kanade.tachiyomi.ui.browse.source
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractSectionableItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.CatalogueSource
/**
* Item that contains source information.
*
* @param source Instance of [CatalogueSource] containing source information.
* @param header The header for this item.
*/
data class SourceItem(
val source: CatalogueSource,
val header: LangItem? = null,
val isPinned: Boolean = false
) :
AbstractSectionableItem<SourceHolder, LangItem>(header) {
override fun getLayoutRes(): Int {
return R.layout.source_main_controller_item
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): SourceHolder {
return SourceHolder(view, adapter as SourceAdapter)
}
override fun bindViewHolder(
adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>,
holder: SourceHolder,
position: Int,
payloads: MutableList<Any>
) {
holder.bind(this)
}
override fun equals(other: Any?): Boolean {
if (other is SourceItem) {
return source.id == other.source.id &&
getHeader()?.code == other.getHeader()?.code &&
isPinned == other.isPinned
}
return false
}
override fun hashCode(): Int {
var result = source.id.hashCode()
result = 31 * result + (header?.hashCode() ?: 0)
result = 31 * result + isPinned.hashCode()
return result
}
}
| 92
| null |
58
| 9
|
2f07f226b8182699884262ac67139454d5b7070d
| 1,744
|
tachiyomi
|
Apache License 2.0
|
app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/SourceItem.kt
|
arkon
| 127,645,159
| false
| null |
package eu.kanade.tachiyomi.ui.browse.source
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractSectionableItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.CatalogueSource
/**
* Item that contains source information.
*
* @param source Instance of [CatalogueSource] containing source information.
* @param header The header for this item.
*/
data class SourceItem(
val source: CatalogueSource,
val header: LangItem? = null,
val isPinned: Boolean = false
) :
AbstractSectionableItem<SourceHolder, LangItem>(header) {
override fun getLayoutRes(): Int {
return R.layout.source_main_controller_item
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): SourceHolder {
return SourceHolder(view, adapter as SourceAdapter)
}
override fun bindViewHolder(
adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>,
holder: SourceHolder,
position: Int,
payloads: MutableList<Any>
) {
holder.bind(this)
}
override fun equals(other: Any?): Boolean {
if (other is SourceItem) {
return source.id == other.source.id &&
getHeader()?.code == other.getHeader()?.code &&
isPinned == other.isPinned
}
return false
}
override fun hashCode(): Int {
var result = source.id.hashCode()
result = 31 * result + (header?.hashCode() ?: 0)
result = 31 * result + isPinned.hashCode()
return result
}
}
| 92
| null |
58
| 9
|
2f07f226b8182699884262ac67139454d5b7070d
| 1,744
|
tachiyomi
|
Apache License 2.0
|
increase-kotlin-core/src/main/kotlin/com/increase/api/services/blocking/WireDrawdownRequestService.kt
|
Increase
| 614,596,742
| false
| null |
// File generated from our OpenAPI spec by Stainless.
@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102
package com.increase.api.services.blocking
import com.increase.api.core.RequestOptions
import com.increase.api.models.WireDrawdownRequest
import com.increase.api.models.WireDrawdownRequestCreateParams
import com.increase.api.models.WireDrawdownRequestListPage
import com.increase.api.models.WireDrawdownRequestListParams
import com.increase.api.models.WireDrawdownRequestRetrieveParams
interface WireDrawdownRequestService {
/** Create a Wire Drawdown Request */
@JvmOverloads
fun create(
params: WireDrawdownRequestCreateParams,
requestOptions: RequestOptions = RequestOptions.none()
): WireDrawdownRequest
/** Retrieve a Wire Drawdown Request */
@JvmOverloads
fun retrieve(
params: WireDrawdownRequestRetrieveParams,
requestOptions: RequestOptions = RequestOptions.none()
): WireDrawdownRequest
/** List Wire Drawdown Requests */
@JvmOverloads
fun list(
params: WireDrawdownRequestListParams,
requestOptions: RequestOptions = RequestOptions.none()
): WireDrawdownRequestListPage
}
| 1
| null |
0
| 5
|
dc1361d08cb41ff45817c2e7638f53356f15cf8e
| 1,231
|
increase-kotlin
|
Apache License 2.0
|
src/test/kotlin/com/fasterxml/jackson/module/kotlin/test/github/Github464.kt
|
FasterXML
| 23,404,083
| false
| null |
package com.fasterxml.jackson.module.kotlin.test.github
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.ObjectWriter
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.jacksonMapperBuilder
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.testPrettyWriter
import org.junit.Ignore
import org.junit.Test
import kotlin.test.assertEquals
class Github464 {
class UnboxTest {
object NullValueClassKeySerializer : StdSerializer<ValueClass>(ValueClass::class.java) {
override fun serialize(value: ValueClass?, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeFieldName("null-key")
}
}
interface IValue
@JvmInline
value class ValueClass(val value: Int?) : IValue
data class WrapperClass(val inlineField: ValueClass)
abstract class AbstractGetter<T> {
abstract val qux: T
fun <T> getPlugh() = qux
}
interface IGetter<T> {
val quux: T
fun <T> getXyzzy() = quux
}
class Poko(
val foo: ValueClass,
val bar: ValueClass?,
val baz: IValue,
override val qux: ValueClass,
override val quux: ValueClass,
val corge: Collection<ValueClass?>,
val grault: Array<ValueClass?>,
val garply: WrapperClass,
val waldo: WrapperClass?,
val fred: Map<ValueClass, ValueClass?>
) : AbstractGetter<ValueClass>(), IGetter<ValueClass>
private val zeroValue = ValueClass(0)
private val oneValue = ValueClass(1)
private val nullValue = ValueClass(null)
private val target = Poko(
foo = zeroValue,
bar = null,
baz = zeroValue,
qux = zeroValue,
quux = zeroValue,
corge = listOf(zeroValue, null),
grault = arrayOf(zeroValue, null),
garply = WrapperClass(zeroValue),
waldo = null,
fred = mapOf(zeroValue to zeroValue, oneValue to null, nullValue to nullValue)
)
@Test
fun test() {
@Suppress("UNCHECKED_CAST")
val writer: ObjectWriter = jacksonObjectMapper()
.apply { serializerProvider.setNullKeySerializer(NullValueClassKeySerializer as JsonSerializer<Any?>) }
.testPrettyWriter()
assertEquals(
"""
{
"foo" : 0,
"bar" : null,
"baz" : 0,
"qux" : 0,
"quux" : 0,
"corge" : [ 0, null ],
"grault" : [ 0, null ],
"garply" : {
"inlineField" : 0
},
"waldo" : null,
"fred" : {
"0" : 0,
"1" : null,
"null-key" : null
},
"xyzzy" : 0,
"plugh" : 0
}
""".trimIndent(),
writer.writeValueAsString(target)
)
}
object NullValueSerializer : StdSerializer<Any>(Any::class.java) {
override fun serialize(value: Any?, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeString("null-value")
}
}
@Test
fun nullValueSerializerTest() {
@Suppress("UNCHECKED_CAST")
val writer = jacksonObjectMapper()
.apply {
serializerProvider.setNullKeySerializer(NullValueClassKeySerializer as JsonSerializer<Any?>)
serializerProvider.setNullValueSerializer(NullValueSerializer)
}.testPrettyWriter()
assertEquals(
"""
{
"foo" : 0,
"bar" : "null-value",
"baz" : 0,
"qux" : 0,
"quux" : 0,
"corge" : [ 0, "null-value" ],
"grault" : [ 0, "null-value" ],
"garply" : {
"inlineField" : 0
},
"waldo" : "null-value",
"fred" : {
"0" : 0,
"1" : "null-value",
"null-key" : "null-value"
},
"xyzzy" : 0,
"plugh" : 0
}
""".trimIndent(),
writer.writeValueAsString(target)
)
}
}
class SerializerPriorityTest {
@JvmInline
value class ValueBySerializer(val value: Int)
object Serializer : StdSerializer<ValueBySerializer>(ValueBySerializer::class.java) {
override fun serialize(value: ValueBySerializer, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeString(value.value.toString())
}
}
object KeySerializer : StdSerializer<ValueBySerializer>(ValueBySerializer::class.java) {
override fun serialize(value: ValueBySerializer, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeFieldName(value.value.toString())
}
}
private val target = mapOf(ValueBySerializer(1) to ValueBySerializer(2))
private val sm = SimpleModule()
.addSerializer(Serializer)
.addKeySerializer(ValueBySerializer::class.java, KeySerializer)
@Test
fun simpleTest() {
val om: ObjectMapper = jacksonMapperBuilder().addModule(sm).build()
assertEquals("""{"1":"2"}""", om.writeValueAsString(target))
}
// Currently, there is a situation where the serialization results are different depending on the registration order of the modules.
// This problem is not addressed because the serializer registered by the user has priority over Extensions.kt,
// since KotlinModule is basically registered first.
@Ignore
@Test
fun priorityTest() {
val km = KotlinModule.Builder().build()
val om1: ObjectMapper = JsonMapper.builder().addModules(km, sm).build()
val om2: ObjectMapper = JsonMapper.builder().addModules(sm, km).build()
// om1(collect) -> """{"1":"2"}"""
// om2(broken) -> """{"1":2}"""
assertEquals(om1.writeValueAsString(target), om2.writeValueAsString(target))
}
}
}
| 8
| null |
3
| 932
|
fa8ee76a8a00443aa6e8cc401c4e0868219d2d5b
| 7,186
|
jackson-module-kotlin
|
Apache License 2.0
|
sdk-media/src/main/kotlin/com/pexip/sdk/media/MediaConnectionSignaling.kt
|
pexip
| 493,156,648
| false
| null |
/*
* Copyright 2022 Pexip AS
*
* 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.pexip.sdk.media
/**
* Represents a signaling component of [MediaConnection].
*/
public interface MediaConnectionSignaling {
/**
* A list of available [IceServer]s.
*/
public val iceServers: List<IceServer>
/**
* Invoked when an offer is available.
*
* @param callType a call type (currently only "WEBRTC" is supported)
* @param description an offer, usually represented by an SDP
* @param presentationInMain whether presentation should be embedded in main video feed
* @param fecc whether far end camera control should be enabled
* @return an answer
*/
public fun onOffer(
callType: String,
description: String,
presentationInMain: Boolean,
fecc: Boolean,
): String
/**
* Invoked when a new ICE candidate is available.
*
* @param candidate an ICE candidate
* @param mid a media ID associated with this candidate
*/
public fun onCandidate(candidate: String, mid: String)
/**
* Invoked when a sequence of DTMF digits must be sent.
*
* @param digits a sequence of DTMF digits
*/
public fun onDtmf(digits: String)
/**
* Invoked when audio is muted.
*/
public fun onAudioMuted()
/**
* Invoked when audio is unmuted.
*/
public fun onAudioUnmuted()
/**
* Invoked when video is muted.
*/
public fun onVideoMuted()
/**
* Invoked when video is unmuted.
*/
public fun onVideoUnmuted()
/**
* Invoked when local presentation feed is added.
*/
public fun onTakeFloor()
/**
* Invoked when local presentation feed is removed.
*/
public fun onReleaseFloor()
}
| 13
|
Kotlin
|
3
| 5
|
e5647b314302500c1f3bf0611c68f7b884dbc532
| 2,331
|
pexip-android-sdk
|
Apache License 2.0
|
android/app/src/main/java/me/gentielezaj/wagwoord/managers/autofill/AppAutofillService.kt
|
gentielezaj
| 211,967,241
| false
| null |
package me.gentielezaj.wagwoord.managers.autofill
import android.app.assist.AssistStructure
import android.os.CancellationSignal
import android.service.autofill.*
import android.view.autofill.AutofillValue
import android.widget.RemoteViews
import com.google.common.net.InternetDomainName
import me.gentielezaj.wagwoord.R
enum class AutofillFieldTypes {
USERNAME,
PASSWORD,
FIRSTNAME,
LASTNAME
}
class AppAutofillService : AutofillService() {
override fun onFillRequest(
request: FillRequest,
cancellationSignal: CancellationSignal,
callback: FillCallback
) {
// val contexts = request.fillContexts
// val contex = contexts[contexts.size - 1]
// val structure = contex.structure
// val windowNode = structure.getWindowNodeAt(0)
// val viewNode = windowNode.rootViewNode // pretend this is an EditText
// val domain = getCanonicalDomain(contex.structure.activityComponent.packageName)
val viewNode = loopContext(request.fillContexts).firstOrNull()
if(viewNode == null) {
callback.onFailure("fuck this shit");
return
}
val suggestionText = "<EMAIL>"
val suggestion = RemoteViews(packageName, R.layout.autofill_suggestion)
suggestion.setTextViewText(R.id.autofill_suggestion_text, suggestionText)
val suggestionDataset = Dataset.Builder()
.setValue(viewNode.autofillId!!, AutofillValue.forText("<EMAIL>"), suggestion)
.build()
val response = FillResponse.Builder()
.addDataset(suggestionDataset)
.build()
callback.onSuccess(response)
}
fun loopContext(contexts: List<FillContext>): List<AssistStructure.ViewNode>{
val emailFields = mutableListOf<AssistStructure.ViewNode>()
for (context in contexts.filter { it.structure.windowNodeCount > 0 }) {
for (windowIndex in 0 until context.structure.windowNodeCount) {
emailFields.addAll(identifyEmailFields(context.structure.getWindowNodeAt(windowIndex).rootViewNode))
}
}
return emailFields
}
fun identifyEmailFields(node: AssistStructure.ViewNode): List<AssistStructure.ViewNode> {
val emailFields = mutableListOf<AssistStructure.ViewNode>()
if (node.className?.contains("EditText", true) == true) {
val viewId = node.idEntry
if (viewId != null && (viewId.contains("email") || viewId.contains("username"))) {
emailFields.add(node)
}
} else if(node.childCount > 0) {
for (index in 0 until node.childCount){
emailFields.addAll(identifyEmailFields(node.getChildAt(index)))
}
}
return emailFields
}
private fun getCanonicalDomain(domain: String): String? {
var idn = InternetDomainName.from(domain);
while (idn != null && !idn.isTopPrivateDomain()) {
idn = idn.parent();
}
return idn?.toString()
}
override fun onSaveRequest(request: SaveRequest, callback: SaveCallback) {
TODO("Not yet implemented")
}
}
| 36
|
Kotlin
|
0
| 0
|
3adf571dc6d4ce8a4e9410df18191c835ef101ce
| 3,184
|
wagwoord
|
MIT License
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/IgnoreDiacritics.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: IgnoreDiacritics
*
* Full name: System`IgnoreDiacritics
*
* Usage: IgnoreDiacritics is an option for string, grammar, and related functions that specifies whether diacritics should be ignored in strings.
*
* Options: None
*
* Attributes: Protected
*
* local: paclet:ref/IgnoreDiacritics
* Documentation: web: http://reference.wolfram.com/language/ref/IgnoreDiacritics.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun ignoreDiacritics(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("IgnoreDiacritics", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,055
|
mathemagika
|
Apache License 2.0
|
src/main/java/it/smartphonecombo/uecapabilityparser/bean/Feature.kt
|
HandyMenny
| 539,436,833
| false
| null |
package it.smartphonecombo.uecapabilityparser.bean
data class Feature(
val isNR: Boolean,
val downlink: Int,
val uplink: Int
) {
override fun toString(): String {
return "DL: " + downlink + " UL: " + uplink + if (isNR) " NR" else " EUTRA"
}
}
| 3
|
Kotlin
|
6
| 4
|
21a6bf8610bad0d5d250dea7f88e3b54c6de7798
| 271
|
uecapabilityparser
|
MIT License
|
app/src/main/java/dzmitryk/app/template/ui/hello/Greetings.kt
|
dzmitryk-dev
| 818,587,554
| false
|
{"Kotlin": 8729}
|
package dzmitryk.app.template.ui.hello
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import dzmitryk.app.template.ui.theme.AppTemplateTheme
import kotlinx.coroutines.delay
val rainbowColors = listOf(
Color(0xFFE74C3C), // Red
Color(0xFFF39C12), // Orange
Color(0xFFF1C40F), // Yellow
Color(0xFF2ECC71), // Green
Color(0xFF3498DB), // Blue
Color(0xFF8E44AD), // Indigo
Color(0xFF9B59B6) // Violet
)
@Composable
fun Greeting(text: String, modifier: Modifier = Modifier) {
Text(
text = text,
modifier = modifier,
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
}
@Composable
fun RainbowColorChangeText(text: String, modifier: Modifier = Modifier) {
var currentColorIndex by remember { mutableStateOf(0) }
LaunchedEffect(Unit) {
while (true) {
delay(500)
currentColorIndex = (currentColorIndex + 1) % rainbowColors.size
}
}
Text(
modifier = modifier,
text = text,
color = rainbowColors[currentColorIndex],
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
}
@Composable
fun RainbowColorText(modifier: Modifier = Modifier, text: String) {
Row(modifier = modifier) {
text.forEachIndexed { index, char ->
Text(
text = char.toString(),
color = rainbowColors[index % rainbowColors.size],
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
}
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
AppTemplateTheme {
Greeting(text = "Hello World")
}
}
@Preview(showBackground = true)
@Composable
fun RainbowTextPreview() {
AppTemplateTheme {
RainbowColorChangeText(text = "Hello World")
}
}
@Preview(showBackground = true)
@Composable
fun RainbowColorTextPreview() {
AppTemplateTheme {
RainbowColorText(text = "Hello World")
}
}
| 0
|
Kotlin
|
0
| 0
|
09d583320a34dd5aae09ecccbb14f64df935a78d
| 2,653
|
android-app-template
|
MIT License
|
skiko/src/wasmJsMain/kotlin/org/jetbrains/skiko/Convertors.wasm.kt
|
JetBrains
| 282,864,178
| false
|
{"Kotlin": 1802033, "C++": 1730435, "Objective-C++": 38471, "JavaScript": 6932, "Dockerfile": 4676, "Shell": 4522, "C": 1440, "Java": 1235, "Objective-C": 471}
|
package org.jetbrains.skiko
import org.w3c.dom.events.KeyboardEvent
import org.w3c.dom.events.MouseEvent
import org.w3c.dom.events.WheelEvent
internal fun toSkikoEvent(
event: MouseEvent,
kind: SkikoPointerEventKind
): SkikoPointerEvent {
return SkikoPointerEvent(
x = event.offsetX,
y = event.offsetY,
pressedButtons = toSkikoPressedMouseButtons(event, kind),
button = toSkikoMouseButton(event),
modifiers = toSkikoModifiers(event),
kind = kind,
timestamp = getEventTimestamp(event),
platform = event
)
}
internal fun toSkikoDragEvent(
event: MouseEvent
): SkikoPointerEvent {
return SkikoPointerEvent(
x = event.offsetX,
y = event.offsetY,
pressedButtons = SkikoMouseButtons(buttonsFlags),
button = toSkikoMouseButton(event),
modifiers = toSkikoModifiers(event),
kind = SkikoPointerEventKind.DRAG,
timestamp = getEventTimestamp(event),
platform = event
)
}
internal fun toSkikoTypeEvent(
character: String,
event: KeyboardEvent?,
): SkikoInputEvent? {
return if (SPECIAL_KEYS.contains(character)) {
null
} else {
val input = when (character) {
"Enter" -> "\n"
"Tab" -> "\t"
else -> character
}
val key = if (event != null) SkikoKey.valueOf(event.keyCode) else SkikoKey.KEY_UNKNOWN
val modifiers = if (event != null) toSkikoModifiers(event) else SkikoInputModifiers.EMPTY
SkikoInputEvent(
input,
key,
modifiers,
SkikoKeyboardEventKind.TYPE,
event
)
}
}
internal fun toSkikoEvent(
event: KeyboardEvent,
kind: SkikoKeyboardEventKind
): SkikoKeyboardEvent {
return SkikoKeyboardEvent(
SkikoKey.valueOf(toSkikoKey(event)),
toSkikoModifiers(event),
kind,
getEventTimestamp(event),
event
)
}
internal fun toSkikoScrollEvent(
event: WheelEvent,
): SkikoPointerEvent {
return SkikoPointerEvent(
x = event.offsetX,
y = event.offsetY,
deltaX = event.deltaX,
deltaY = event.deltaY,
pressedButtons = SkikoMouseButtons(buttonsFlags),
button = SkikoMouseButtons.NONE,
modifiers = toSkikoModifiers(event),
kind = SkikoPointerEventKind.SCROLL,
timestamp = getEventTimestamp(event),
platform = event
)
}
private var buttonsFlags = 0
private fun toSkikoPressedMouseButtons(
event: MouseEvent,
kind: SkikoPointerEventKind
): SkikoMouseButtons {
// https://www.w3schools.com/jsref/event_button.asp
val button = event.button.toInt()
if (kind == SkikoPointerEventKind.DOWN) {
buttonsFlags = buttonsFlags.or(getSkikoButtonValue(button))
return SkikoMouseButtons(buttonsFlags)
}
buttonsFlags = buttonsFlags.xor(getSkikoButtonValue(button))
return SkikoMouseButtons(buttonsFlags)
}
private fun toSkikoMouseButton(event: MouseEvent): SkikoMouseButtons {
return SkikoMouseButtons(getSkikoButtonValue(event.button.toInt()))
}
private fun getSkikoButtonValue(button: Int): Int {
return when (button) {
0 -> SkikoMouseButtons.LEFT.value
1 -> SkikoMouseButtons.MIDDLE.value
2 -> SkikoMouseButtons.RIGHT.value
3 -> SkikoMouseButtons.BUTTON_4.value
4 -> SkikoMouseButtons.BUTTON_5.value
else -> 0
}
}
private fun toSkikoModifiers(event: MouseEvent): SkikoInputModifiers {
var result = 0
if (event.altKey) {
result = result.or(SkikoInputModifiers.ALT.value)
}
if (event.shiftKey) {
result = result.or(SkikoInputModifiers.SHIFT.value)
}
if (event.ctrlKey) {
result = result.or(SkikoInputModifiers.CONTROL.value)
}
if (event.metaKey) {
result = result.or(SkikoInputModifiers.META.value)
}
return SkikoInputModifiers(result)
}
private fun toSkikoModifiers(event: KeyboardEvent): SkikoInputModifiers {
var result = 0
if (event.altKey) {
result = result.or(SkikoInputModifiers.ALT.value)
}
if (event.shiftKey) {
result = result.or(SkikoInputModifiers.SHIFT.value)
}
if (event.ctrlKey) {
result = result.or(SkikoInputModifiers.CONTROL.value)
}
if (event.metaKey) {
result = result.or(SkikoInputModifiers.META.value)
}
return SkikoInputModifiers(result)
}
private fun toSkikoKey(event: KeyboardEvent): Int {
var key = event.keyCode
val side = event.location
if (side == KeyboardEvent.DOM_KEY_LOCATION_RIGHT) {
if (
key == SkikoKey.KEY_LEFT_CONTROL.platformKeyCode ||
key == SkikoKey.KEY_LEFT_SHIFT.platformKeyCode ||
key == SkikoKey.KEY_LEFT_META.platformKeyCode
)
key = key.or(0x80000000.toInt())
}
return key
}
| 118
|
Kotlin
|
94
| 1,629
|
fd9a62d559cb59d0fad5c3e0484b2b6db938a041
| 4,898
|
skiko
|
Apache License 2.0
|
sample/src/main/java/re/notifica/sample/ui/beacons/BeaconsListAdapter.kt
|
Notificare
| 279,260,636
| false
|
{"Kotlin": 760683}
|
package re.notifica.sample.ui.beacons
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import re.notifica.geo.models.NotificareBeacon
import re.notifica.sample.R
import re.notifica.sample.databinding.BeaconRowBinding
class BeaconsListAdapter : ListAdapter<NotificareBeacon, RecyclerView.ViewHolder>(BeaconsDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return ItemViewHolder(
BeaconRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = getItem(position)
(holder as ItemViewHolder).bind(item)
}
private inner class ItemViewHolder(
private val binding: BeaconRowBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: NotificareBeacon) {
binding.name.text = item.name
binding.details.text = "${item.major}:${item.minor}"
when (item.proximity) {
NotificareBeacon.Proximity.IMMEDIATE -> binding.proximity.setImageResource(R.drawable.ic_signal_wifi_4_bar)
NotificareBeacon.Proximity.NEAR -> binding.proximity.setImageResource(R.drawable.ic_signal_wifi_3_bar)
NotificareBeacon.Proximity.FAR -> binding.proximity.setImageResource(R.drawable.ic_signal_wifi_1_bar)
NotificareBeacon.Proximity.UNKNOWN -> binding.proximity.setImageDrawable(null)
}
}
}
}
private class BeaconsDiffCallback : DiffUtil.ItemCallback<NotificareBeacon>() {
override fun areItemsTheSame(oldItem: NotificareBeacon, newItem: NotificareBeacon): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: NotificareBeacon, newItem: NotificareBeacon): Boolean {
return oldItem == newItem
}
}
| 2
|
Kotlin
|
0
| 2
|
f756ff63b5930360bbb43dafcb29dde61b37cb11
| 2,071
|
notificare-sdk-android
|
MIT License
|
trixnity-clientserverapi/trixnity-clientserverapi-model/src/commonMain/kotlin/net/folivo/trixnity/clientserverapi/model/rooms/GetEventContext.kt
|
benkuly
| 330,904,570
| false
| null |
package net.folivo.trixnity.clientserverapi.model.rooms
import io.ktor.resources.*
import kotlinx.serialization.Contextual
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import net.folivo.trixnity.core.HttpMethod
import net.folivo.trixnity.core.HttpMethodType.GET
import net.folivo.trixnity.core.MatrixEndpoint
import net.folivo.trixnity.core.model.EventId
import net.folivo.trixnity.core.model.RoomId
import net.folivo.trixnity.core.model.UserId
import net.folivo.trixnity.core.model.events.Event
/**
* @see <a href="https://spec.matrix.org/v1.7/client-server-api/#get_matrixclientv3roomsroomidcontexteventid">matrix spec</a>
*/
@Serializable
@Resource("/_matrix/client/v3/rooms/{roomId}/context/{eventId}")
@HttpMethod(GET)
data class GetEventContext(
@SerialName("roomId") val roomId: RoomId,
@SerialName("eventId") val eventId: EventId,
@SerialName("filter") val filter: String? = null,
@SerialName("limit") val limit: Long? = null,
@SerialName("user_id") val asUserId: UserId? = null
) : MatrixEndpoint<Unit, GetEventContext.Response> {
@Serializable
data class Response(
@SerialName("start") val start: String? = null,
@SerialName("end") val end: String? = null,
@SerialName("event") val event: @Contextual Event.RoomEvent<*>,
@SerialName("events_before") val eventsBefore: List<@Contextual Event.RoomEvent<*>>? = null,
@SerialName("events_after") val eventsAfter: List<@Contextual Event.RoomEvent<*>>? = null,
@SerialName("state") val state: List<@Contextual Event.StateEvent<*>>? = null
)
}
| 0
| null |
3
| 30
|
6dfadb2efa1843a33030fba9eb6be0bfecdfb94d
| 1,617
|
trixnity
|
Apache License 2.0
|
presentation/src/main/java/com/anytypeio/anytype/presentation/main/MainViewModel.kt
|
anyproto
| 647,371,233
| false
|
{"Kotlin": 10699233, "Java": 69306, "Shell": 11187, "Makefile": 1334}
|
package com.anytypeio.anytype.presentation.main
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anytypeio.anytype.analytics.base.Analytics
import com.anytypeio.anytype.analytics.base.updateUserProperties
import com.anytypeio.anytype.analytics.props.UserProperty
import com.anytypeio.anytype.core_models.AccountStatus
import com.anytypeio.anytype.core_models.Id
import com.anytypeio.anytype.core_models.Wallpaper
import com.anytypeio.anytype.core_models.exceptions.NeedToUpdateApplicationException
import com.anytypeio.anytype.domain.account.InterceptAccountStatus
import com.anytypeio.anytype.domain.auth.interactor.CheckAuthorizationStatus
import com.anytypeio.anytype.domain.auth.interactor.Logout
import com.anytypeio.anytype.domain.auth.interactor.ResumeAccount
import com.anytypeio.anytype.domain.auth.model.AuthStatus
import com.anytypeio.anytype.domain.base.BaseUseCase
import com.anytypeio.anytype.domain.base.Interactor
import com.anytypeio.anytype.domain.config.ConfigStorage
import com.anytypeio.anytype.domain.misc.LocaleProvider
import com.anytypeio.anytype.domain.search.ObjectTypesSubscriptionManager
import com.anytypeio.anytype.domain.search.RelationsSubscriptionManager
import com.anytypeio.anytype.domain.spaces.SpaceDeletedStatusWatcher
import com.anytypeio.anytype.domain.wallpaper.ObserveWallpaper
import com.anytypeio.anytype.domain.wallpaper.RestoreWallpaper
import com.anytypeio.anytype.presentation.splash.SplashViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import timber.log.Timber
class MainViewModel(
private val resumeAccount: ResumeAccount,
private val observeWallpaper: ObserveWallpaper,
private val restoreWallpaper: RestoreWallpaper,
private val analytics: Analytics,
private val interceptAccountStatus: InterceptAccountStatus,
private val logout: Logout,
private val relationsSubscriptionManager: RelationsSubscriptionManager,
private val objectTypesSubscriptionManager: ObjectTypesSubscriptionManager,
private val checkAuthorizationStatus: CheckAuthorizationStatus,
private val configStorage: ConfigStorage,
private val spaceDeletedStatusWatcher: SpaceDeletedStatusWatcher,
private val localeProvider: LocaleProvider
) : ViewModel() {
val wallpaper = MutableStateFlow<Wallpaper>(Wallpaper.Default)
val commands = MutableSharedFlow<Command>(replay = 0)
val toasts = MutableSharedFlow<String>(replay = 0)
init {
viewModelScope.launch {
restoreWallpaper.flow().collect {
// Do nothing, just run pipeline.
}
}
viewModelScope.launch {
observeWallpaper.build(BaseUseCase.None).collect {
wallpaper.value = it
}
}
viewModelScope.launch {
interceptAccountStatus.build().collect { status ->
when (status) {
is AccountStatus.PendingDeletion -> {
commands.emit(
Command.ShowDeletedAccountScreen(
deadline = status.deadline
)
)
}
is AccountStatus.Deleted -> {
proceedWithLogoutDueToAccountDeletion()
}
else -> {
// Do nothing
}
}
}
}
}
private fun proceedWithLogoutDueToAccountDeletion() {
viewModelScope.launch {
logout(Logout.Params(clearLocalRepositoryData = false)).collect { status ->
when (status) {
is Interactor.Status.Error -> {
toasts.emit("Error while logging out due to account deletion")
}
is Interactor.Status.Started -> {
toasts.emit("Your account is deleted. Logging out...")
}
is Interactor.Status.Success -> {
unsubscribeFromGlobalSubscriptions()
commands.emit(Command.LogoutDueToAccountDeletion)
}
}
}
}
}
private fun unsubscribeFromGlobalSubscriptions() {
relationsSubscriptionManager.onStop()
objectTypesSubscriptionManager.onStop()
spaceDeletedStatusWatcher.onStop()
}
fun onRestore() {
/***
* Before fragment backstack and screen states are restored by the OS,
* We need to resume account session in a blocking manner.
* Otherwise, we might run into illegal states, where account is not ready when we try:
* 1) to open an object, profile or dashboard
* 2) to execute queries and searches
* etc.
*/
runBlocking {
resumeAccount.run(params = BaseUseCase.None).process(
success = {
relationsSubscriptionManager.onStart()
objectTypesSubscriptionManager.onStart()
spaceDeletedStatusWatcher.onStart()
val analyticsID = configStorage.getOrNull()?.analytics
if (analyticsID != null) {
updateUserProperties(
analytics = analytics,
userProperty = UserProperty.AccountId(analyticsID)
)
localeProvider.language()?.let { lang ->
updateUserProperties(
analytics,
userProperty = UserProperty.InterfaceLanguage(lang)
)
}
}
Timber.d("Restored account after activity recreation")
},
failure = { error ->
when (error) {
is NeedToUpdateApplicationException -> {
commands.emit(Command.Error(SplashViewModel.ERROR_NEED_UPDATE))
}
else -> {
commands.emit(Command.Error(SplashViewModel.ERROR_MESSAGE))
}
}
Timber.e(error, "Error while launching account after activity recreation")
}
)
}
}
fun onIntentCreateObject(type: Id) {
viewModelScope.launch {
checkAuthorizationStatus(Unit).process(
failure = { e -> Timber.e(e, "Error while checking auth status") },
success = { status ->
if (status == AuthStatus.AUTHORIZED) {
commands.emit(Command.OpenCreateNewType(type))
}
}
)
}
}
fun onIntentTextShare(data: String) {
viewModelScope.launch {
checkAuthorizationStatus(Unit).process(
failure = { e -> Timber.e(e, "Error while checking auth status") },
success = { status ->
if (status == AuthStatus.AUTHORIZED) {
commands.emit(Command.Sharing.Text(data))
}
}
)
}
}
fun onIntentMultipleFilesShare(uris: List<String>) {
Timber.d("onIntentFileShare: $uris")
viewModelScope.launch {
checkAuthorizationStatus(Unit).process(
failure = { e -> Timber.e(e, "Error while checking auth status") },
success = { status ->
if (status == AuthStatus.AUTHORIZED) {
if (uris.size == 1) {
commands.emit(Command.Sharing.File(uris.first()))
} else {
commands.emit(Command.Sharing.Files(uris))
}
}
}
)
}
}
fun onIntentMultipleImageShare(uris: List<String>) {
Timber.d("onIntentImageShare: $uris")
viewModelScope.launch {
checkAuthorizationStatus(Unit).process(
failure = { e -> Timber.e(e, "Error while checking auth status") },
success = { status ->
if (status == AuthStatus.AUTHORIZED) {
if (uris.size == 1) {
commands.emit(Command.Sharing.Image(uris.first()))
} else {
commands.emit(Command.Sharing.Images(uris))
}
}
}
)
}
}
sealed class Command {
data class ShowDeletedAccountScreen(val deadline: Long) : Command()
object LogoutDueToAccountDeletion : Command()
class OpenCreateNewType(val type: Id) : Command()
data class Error(val msg: String) : Command()
sealed class Sharing : Command() {
data class Text(val data: String) : Sharing()
data class Image(val uri: String): Sharing()
data class Images(val uris: List<String>): Sharing()
data class File(val uri: String): Sharing()
data class Files(val uris: List<String>): Sharing()
}
}
}
| 37
|
Kotlin
|
33
| 383
|
d8c7605538b80738bea331ab74340a3e0ee3194d
| 9,489
|
anytype-kotlin
|
RSA Message-Digest License
|
examples/src/main/kotlin/examples/sprites/Mask.kt
|
hiperbou
| 77,711,558
| false
|
{"Kotlin": 456816, "HTML": 335}
|
package examples.sprites
import Phaser.*
class Mask: State() {
//var game = Phaser.Game(800, 600, Phaser.AUTO, "phaser-example", object{ var preload= preload; var create= create })
override fun preload() {
game.load.image("chaos", "assets/pics/hotshot-chaos_in_tokyo.png")
}
lateinit var sprite:Sprite
lateinit var mask:Graphics
override fun create() {
// Here we add a Sprite to the display list
sprite = game.add.sprite(0, 0, "chaos")
sprite.scale.set(2)
// A mask is a Graphics object
mask = game.add.graphics(0, 0)
// Shapes drawn to the Graphics object must be filled.
mask.beginFill(0xffffff)
// Here we"ll draw a circle
mask.drawCircle(100, 100, 100)
// And apply it to the Sprite
sprite.mask = mask
// As you move the mouse / touch, the circle will track the sprite
game.input.addMoveCallback(this::move, this)
}
fun move(pointer:Pointer, x:Double, y:Double) {
mask.x = x - 100
mask.y = y - 100
}
}
| 2
|
Kotlin
|
11
| 55
|
18d247ecf44c32f5aca0560dce7727c10dfe196a
| 1,025
|
kotlin-phaser
|
MIT License
|
gitnote-jetbrains/src/main/kotlin/io/cjlee/gitnote/core/ConnectorLoader.kt
|
cjlee38
| 780,015,519
| false
|
{"Rust": 64187, "Kotlin": 43629, "JavaScript": 12576, "Shell": 1028, "HTML": 896}
|
package io.cjlee.gitnote.core
import org.apache.commons.io.FileUtils
import java.io.File
import java.nio.file.Files
object ConnectorLoader {
private const val RESOURCE_LOCATION = "core/"
val platform = Platform.determine()
fun loadFile(filepath: String): File {
val classLoader = this::class.java.classLoader
return Files.createTempFile("git-note", ".tmp")
.toFile()
.apply {
this.deleteOnExit()
val resource = classLoader.getResource(RESOURCE_LOCATION + filepath)
FileUtils.copyURLToFile(resource, this)
}
}
}
| 1
|
Rust
|
0
| 2
|
17ba456cdc0aca536c87a27887729f0dd9bd0cd8
| 630
|
gitnote
|
Apache License 2.0
|
backend/src/main/kotlin/io/github/katarem/domain/response/ApiResponse.kt
|
katarem
| 857,288,553
| false
|
{"Kotlin": 45790, "Swift": 621, "HTML": 73}
|
package io.github.katarem.domain.response
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
data class ApiResponse<T>(
val errorMessage: String? = null,
val body: T? = null,
val cardAvailableAt: LocalDateTime? = null,
val responseDate: LocalDateTime = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
)
| 0
|
Kotlin
|
0
| 0
|
bbe068561694292ac1ee8da518e79dfa0f188961
| 430
|
anime-card-trader
|
MIT License
|
app/src/main/java/com/iserbin/diykstra/utils/Extensions.kt
|
iserbin
| 494,812,258
| false
|
{"Kotlin": 7121}
|
package com.iserbin.diykstra.utils
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
fun <T> MutableLiveData<T>.asLiveData() = this as LiveData<T>
fun <T, LD : LiveData<T>> Fragment.observe(liveData: LD, onChanged: (T) -> Unit) {
liveData.observe(
viewLifecycleOwner,
{
onChanged(it)
}
)
}
| 0
|
Kotlin
|
0
| 0
|
7a52d168f1d9b9f1fecd5cd95685991c5c9243ad
| 401
|
diykstra_project
|
Apache License 2.0
|
app/src/main/java/ke/co/tulivuapps/hobbyhorsetours/features/screen/travelstyles/navigation/TravelStyleNavigation.kt
|
brendenozie
| 685,892,586
| false
|
{"Kotlin": 631866}
|
@file:OptIn(ExperimentalAnimationApi::class)
package ke.co.tulivuapps.hobbyhorsetours.features.screen.travelstyles.navigation
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.NavOptions
import com.google.accompanist.navigation.animation.composable
import ke.co.tulivuapps.hobbyhorsetours.features.screen.travelstyles.TravelStylesScreen
/**
* Created by brendenozie on 23.01.2023
*/
const val travelStyleNavigationRoute = "travel_style_route"
fun NavController.navigateToTravelStyle(
navOptions: NavOptions? = null
) {
this.navigate(travelStyleNavigationRoute, navOptions)
}
fun NavGraphBuilder.travelStylesScreen(navController: NavHostController) {
composable(travelStyleNavigationRoute) {
TravelStylesScreen(viewModel = hiltViewModel(), navigateToDetail = {})
}
}
| 0
|
Kotlin
|
0
| 0
|
3f8f6a18adde1bb2c60b22585137dfa67568fff1
| 1,017
|
HobbyHorseToursAndroidApp
|
Apache License 2.0
|
src/main/kotlin/dev/jarand/oauthserver/config/Config.kt
|
JarandDev
| 754,770,861
| false
|
{"Kotlin": 51324, "Shell": 676, "Dockerfile": 366}
|
package dev.jarand.oauthserver.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.time.Instant
import java.util.*
@Configuration
class Config {
@Bean
fun uuidSupplier(): () -> UUID {
return { UUID.randomUUID() }
}
@Bean
fun instantSupplier(): () -> Instant {
return { Instant.now() }
}
}
| 0
|
Kotlin
|
0
| 0
|
d91fd472ef0d07fd4acdad20635678dad59283f8
| 411
|
oauth-server
|
The Unlicense
|
app/src/main/java/me/rosuh/easywatermark/ui/widget/DetectedPerformanceSeekBarListener.kt
|
rosuH
| 281,094,148
| false
| null |
package me.rosuh.easywatermark.utils
import android.widget.SeekBar
import me.rosuh.easywatermark.MyApp
import me.rosuh.easywatermark.model.WaterMarkConfig
import me.rosuh.easywatermark.utils.DetectedPerformanceSeekBarListener.Companion.HIGH_PERFORMANCE_MEMORY
/**
* An subClass of [SeekBar.OnSeekBarChangeListener] which using [isHighPerformancePredicate] to decide
* should invoke [postAction] in [onProgressChanged] or in [onStopTrackingTouch].
* In some low performance devices, invoke [postAction] in [onProgressChanged] would frozen or oom.
* Because we're doing hard work about the image in the thread, which using much memory.
* So here we would sacrifice a little real-time reaction, but can avoid OOM problems.
*
* ---
*
* ็บ็ฒไธไบ SeekBar ็ๅฎๆถๆงๆฅ้ฟๅ
OOM ้ฎ้ขใๅฆๆๅคๆญๅพๅฏ็จๅ
ๅญๅฐไบ[HIGH_PERFORMANCE_MEMORY]๏ผๅๆ [postAction]
* ๆพๅฐ [onStopTrackingTouch] ๆนๆณ้่ฐ็จใ
*/
open class DetectedPerformanceSeekBarListener(
private val config: WaterMarkConfig?
) : SeekBar.OnSeekBarChangeListener {
var inTimeAction: (SeekBar?, Int, Boolean) -> Unit = { _, _, _ -> }
var postAction: (SeekBar?, Int, Boolean) -> Unit = { _, _, _ -> }
private var isHighPerformancePredicate: () -> Boolean = {
config?.markMode == WaterMarkConfig.MarkMode.Text
|| !getAvailableMemory(MyApp.instance).lowMemory
}
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
if (isHighPerformancePredicate()) {
seekBar?.progress?.let { postAction.invoke(seekBar, it, fromUser) }
}
inTimeAction.invoke(seekBar, progress, fromUser)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
if (!isHighPerformancePredicate()) {
seekBar?.progress?.let { postAction.invoke(seekBar, it, true) }
}
}
companion object {
const val HIGH_PERFORMANCE_MEMORY = 20
}
}
| 12
| null |
91
| 885
|
b9c0b54eb98c1568b7a793630c98e5d0f0d055a1
| 1,954
|
EasyWatermark
|
MIT License
|
code/inclusive-range-operator.kt
|
linux-china
| 257,670,455
| true
|
{"HTML": 37482, "Cirru": 12092, "Kotlin": 10166, "TypeScript": 9957, "CSS": 2476, "CoffeeScript": 591}
|
for (index in 1..5) {
println("${index} times 5 is ${index * 5}")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
| 1
|
HTML
|
3
| 8
|
9521b96e50253a090c47ba00c0ddaa67e0ac173c
| 165
|
kotlin-is-like-typescript
|
MIT License
|
app/src/main/java/com/arturlasok/composeArturApp/MainActivity.kt
|
ArturLasok
| 382,950,235
| false
| null |
package com.arturlasok.composeArturApp
import android.content.Context
import android.os.Bundle
import android.provider.AlarmClock
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import androidx.hilt.navigation.HiltViewModelFactory
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navArgument
import androidx.navigation.compose.rememberNavController
import com.arturlasok.composeArturApp.datastore.UstawieniaDataStore
import com.arturlasok.composeArturApp.presentation.components.ListaWiadomosci
import com.arturlasok.composeArturApp.presentation.components.ListaWiadomosciViewModel
import com.arturlasok.composeArturApp.presentation.components.SzczegolyWiadomosci
import com.arturlasok.composeArturApp.presentation.components.SzczegolyWiadomosciViewModel
import com.arturlasok.composeArturApp.presentation.components.settings.SettingsView
import com.arturlasok.composeArturApp.presentation.components.settings.SettingsViewModel
import com.arturlasok.composeArturApp.presentation.components.user.UserAdmin
import com.arturlasok.composeArturApp.presentation.components.user.UserAdminViewModel
import com.arturlasok.composeArturApp.presentation.components.user.UserView
import com.arturlasok.composeArturApp.presentation.components.user.UserViewViewModel
import com.arturlasok.composeArturApp.presentation.navigation.Screen
import com.arturlasok.composeArturApp.presentation.util.TAG
import com.arturlasok.composeArturApp.presentation.util.isOnline
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.google.firebase.auth.FirebaseAuth
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.activity_foto.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import ruchradzionkow.ruchappartur.R
import java.util.concurrent.Executor
import javax.inject.Inject
// Datastore init
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "ustawienia")
@AndroidEntryPoint
//@ExperimentalComposeUiApi
class MainActivity : ComponentActivity() {
@Inject
lateinit var isOnline: isOnline
@Inject
lateinit var ustawieniaDataStore: UstawieniaDataStore
val isConMonVis = mutableStateOf(false)
override fun onStart() {
isOnline.runit()
super.onStart()
}
override fun onPause() {
super.onPause()
isConMonVis.value = false
}
override fun onResume() {
super.onResume()
CoroutineScope(Dispatchers.IO).launch() {
delay(4000)
isConMonVis.value = true
}
}
override fun onDestroy() {
super.onDestroy()
isConMonVis.value = false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Dane z intent
val message = intent.getStringExtra("EXTRA_MSG").orEmpty()
Log.i(TAG, "Extra message $message")
setContent {
Log.d(TAG, "Is network in main activity: ${isOnline.isNetworkAvailable.value}")
Log.d(TAG, "Is network info visible: ${isConMonVis.value }")
val systemUiController = rememberSystemUiController()
ustawieniaDataStore.observeDataStrore(dataStore,systemUiController)
FirebaseAuth.getInstance().setLanguageCode("pl-PL")
val navController = rememberNavController()
NavHost(navController = navController, startDestination = Screen.ListaWiadomosci.route) {
// NAWIGUJ DO LISTY WIADOMOSCI
composable(Screen.ListaWiadomosci.route)
{ navBackStackEntry ->
val factory = HiltViewModelFactory(LocalContext.current, navBackStackEntry)
val viewModel: ListaWiadomosciViewModel =
viewModel(key = "ListaWiadomosciViewModel",factory = factory)
ListaWiadomosci(
navController = navController,
listaWiadomosciviewModel = viewModel,
isNetworkAvailable = isOnline.isNetworkAvailable.value,
isConMonVis = isConMonVis.value,
isDarkTheme = ustawieniaDataStore.isDark.value,
)
}
// NAWIGUJ DO SZCZEGOLY WIADOMOSCI
composable(Screen.SzczegolyWiadomosci.route+ "/{wiadomoscId}",
arguments = listOf(navArgument("wiadomoscId") {
type = NavType.IntType })
)
{ navBackStackEntry ->
val factory = HiltViewModelFactory(LocalContext.current, navBackStackEntry)
val viewModel: SzczegolyWiadomosciViewModel =
viewModel(key="SzczegolyWiadomosciViewModel",factory = factory)
navBackStackEntry.arguments?.let {
SzczegolyWiadomosci(
navController = navController,
szczegolyWiadomosciViewModel = viewModel,
isNetworkAvailable = isOnline.isNetworkAvailable.value,
isConMonVis = isConMonVis.value,
wiadomoscId = it.getInt("wiadomoscId"),
isDarkTheme = ustawieniaDataStore.isDark.value
)
}
}
// NAWIGUJ DO SETTINGS
composable(Screen.SettingsView.route)
{ navBackStackEntry ->
val factory = HiltViewModelFactory(LocalContext.current, navBackStackEntry)
val viewModel: SettingsViewModel =
viewModel(key="SettingsViewModel",factory = factory)
navBackStackEntry.arguments?.let {
SettingsView(
isDarkTheme = ustawieniaDataStore.isDark.value,
isNetworkAvailable = isOnline.isNetworkAvailable.value,
isConMonVis = isConMonVis.value,
navController = navController
) {ustawieniaDataStore.UstawDark(dataStore,systemUiController)}
}
}
//Nawgiuj do UserView
composable(Screen.UserView.route+ "/{operacja}",
arguments = listOf(navArgument("operacja") {
type = NavType.IntType }) )
{ navBackStackEntry ->
val factory = HiltViewModelFactory(LocalContext.current, navBackStackEntry)
val viewModel: UserViewViewModel =
viewModel(key="UserViewViewModel", factory = factory)
navBackStackEntry.arguments?.let {
viewModel.passRecButtonEnable.value = true
viewModel.loginButtonEnable.value=true
viewModel.registerButtonEnable.value=true
UserView(
isDarkTheme = ustawieniaDataStore.isDark.value,
isNetworkAvailable = isOnline.isNetworkAvailable.value,
isConMonVis = isConMonVis.value,
navController = navController,
userViewViewModel = viewModel,
operacja = it.getInt("operacja"),
)
}
}
//Nawiguj do UserAdmin
composable(Screen.UserAdmin.route+ "/{operacja}",
arguments = listOf(navArgument("operacja") {
type = NavType.IntType }) )
{ navBackStackEntry ->
val factory = HiltViewModelFactory(LocalContext.current, navBackStackEntry)
val viewModel: UserAdminViewModel =
viewModel(key="UserAdminViewModel", factory=factory)
navBackStackEntry.arguments?.let {
UserAdmin(
isDarkTheme = ustawieniaDataStore.isDark.value,
isNetworkAvailable = isOnline.isNetworkAvailable.value,
isConMonVis = isConMonVis.value,
navController = navController,
userAdminViewModel = viewModel,
operacja = it.getInt("operacja"),
)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
dd1aa3bdbf002eb5f4ba4fff126d0518fa77ea2c
| 9,852
|
ComposeApp
|
The Unlicense
|
app/src/main/java/com/ghstudios/android/ClickListeners/ItemClickListener.kt
|
gatheringhallstudios
| 60,881,315
| false
|
{"Gradle": 6, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Text": 3, "Markdown": 1, "INI": 1, "XML": 173, "Java": 142, "Kotlin": 166}
|
package com.ghstudios.android.ClickListeners
import android.content.Context
import android.view.View
import com.ghstudios.android.data.classes.Item
import com.ghstudios.android.data.classes.ItemType
/**
* A proxy listener that internally uses an actual listener for general item pages.
* Created by Carlos on 1/22/2017.
*/
class ItemClickListener(context: Context, type: ItemType, id: Long?) : View.OnClickListener {
internal var innerListener: View.OnClickListener
init {
innerListener = constructTrueListener(context, type, id)
}
constructor(context: Context, item: Item) : this(context, item.type, item.id) {}
private fun constructTrueListener(c: Context, type: ItemType, id: Long?): View.OnClickListener {
return when (type) {
ItemType.WEAPON -> WeaponClickListener(c, id)
ItemType.ARMOR -> ArmorClickListener(c, id, false)
ItemType.DECORATION -> DecorationClickListener(c, id)
ItemType.MATERIAL -> MaterialClickListener(c, id)
ItemType.PALICO_WEAPON -> PalicoWeaponClickListener(c, id)
// todo: add a page for palico armor
ItemType.PALICO_ARMOR -> BasicItemClickListener(c, id)
ItemType.ITEM -> BasicItemClickListener(c, id)
}
}
override fun onClick(v: View) {
innerListener.onClick(v)
}
}
| 12
|
Kotlin
|
37
| 90
|
572ede48d78b9f61a91c7ef1fc64f87c9743b162
| 1,367
|
MHGenDatabase
|
MIT License
|
app/models/src/main/java/tv/orange/models/retrofit/bttv/BttvChannelData.kt
|
NyanArchive
| 503,292,084
| false
| null |
package tv.orange.models.retrofit.bttv
data class BttvChannelData(
val channelEmotes: List<BttvEmote>,
val sharedEmotes: List<BttvEmote>
)
| 0
|
Kotlin
|
0
| 2
|
69f8dcc9df76fe4a48b2fcad8290f8d1cfcc5ff6
| 148
|
OrangeTV
|
Apache License 2.0
|
app/src/main/java/com/blackdroids/movies/mvp/data/api/ServerGateway.kt
|
ristargomel
| 218,975,113
| false
|
{"Kotlin": 28320}
|
package com.blackdroids.movies.mvp.data.api
import io.reactivex.schedulers.Schedulers
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit
object ServerGateway {
const val BASE_URL = "https://api.themoviedb.org/3/"
const val BASE_IMAGE_URL = "https://image.tmdb.org/t/p/"
const val API_KEY = "INSERT_YOUR_KEY"
private val okHttpClient = OkHttpClient.Builder()
.addInterceptor(run {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.apply {
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
}
})
.retryOnConnectionFailure(true)
.connectionPool(ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
.build()
val api : API by lazy {
val retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
// Create Retrofit client
return@lazy retrofit.create(API::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
ea64fbadfe84986d069e45dff4ff5e14d270897d
| 1,518
|
android-movies-mvp
|
Do What The F*ck You Want To Public License
|
server/src/main/kotlin/com/xapphire13/database/GroupStore.kt
|
Xapphire13
| 448,160,864
| false
|
{"TypeScript": 113135, "Kotlin": 61331, "JavaScript": 4777, "Starlark": 3656, "Shell": 1070, "Batchfile": 757, "Dockerfile": 239}
|
package com.xapphire13.database
import com.xapphire13.models.Group
interface GroupStore {
suspend fun listGroups(): List<Group>
suspend fun getGroup(id: String): Group?
suspend fun addUserToGroup(groupId: String, userId: String)
}
| 5
|
TypeScript
|
0
| 1
|
614140aa16d7f711a277d79052d8bf9c84dbc71a
| 245
|
PhotoChallenge
|
MIT License
|
src/test/kotlin/mkuhn/aoc/Day18Test.kt
|
mtkuhn
| 572,236,871
| false
| null |
package mkuhn.aoc
import mkuhn.aoc.util.readInput
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import mkuhn.aoc.util.readTestInput
internal class Day18Test {
@Test
fun testPart1() {
val testInput = readTestInput("Day18_test")
assertEquals(64, day18part1(testInput))
}
@Test
fun testPart1r() {
val testInput = readInput("Day18")
assertEquals(3470, day18part1(testInput))
}
@Test
fun testPart2() {
val testInput = readTestInput("Day18_test")
assertEquals(58, day18part2(testInput))
}
@Test
fun testPart2r() {
val testInput = readInput("Day18")
assertEquals(1986, day18part2(testInput))
}
}
| 0
|
Kotlin
|
0
| 1
|
89138e33bb269f8e0ef99a4be2c029065b69bc5c
| 747
|
advent-of-code-2022
|
Apache License 2.0
|
presentation/src/main/java/com/sms/presentation/main/ui/detail/project/ProjectRelatedLinksComponent.kt
|
GSM-MSG
| 625,706,722
| false
|
{"Kotlin": 733672}
|
package com.sms.presentation.main.ui.detail.project
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.msg.sms.domain.model.common.LinkModel
@Composable
fun ProjectRelatedLinksComponent(modifier: Modifier = Modifier, links: List<LinkModel>) {
val itemHeight = remember {
mutableStateOf(0.dp)
}
LazyColumn(
modifier = modifier.heightIn(max = 200.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(links.size) {
ProjectLinkComponent(
linksData = links[it],
getHeight = { height -> itemHeight.value = height })
}
}
}
@Preview
@Composable
fun RelatedLinksComponentPre() {
ProjectRelatedLinksComponent(
links = listOf(
LinkModel("Youtube", "https://dolmc.com"),
LinkModel("GitHub", "https://youyu.com"),
LinkModel(
"X",
"https://asdgasasdfljkasjhdlfalsdhfklhalksdhfklhaskldjfhlkasdhfklahsdfkjgw.com"
)
)
)
}
| 11
|
Kotlin
|
1
| 16
|
d279f3f1266caac16ce2e5c2230e13d7e078a37f
| 1,395
|
SMS-Android
|
MIT License
|
PennMobile/src/main/java/com/pennapps/labs/pennmobile/GsrFragment.kt
|
mgarciaferreiro
| 214,044,788
| false
| null |
package com.pennapps.labs.pennmobile
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.answers.Answers
import com.crashlytics.android.answers.ContentViewEvent
import com.pennapps.labs.pennmobile.api.Labs
import com.pennapps.labs.pennmobile.classes.GSRContainer
import com.pennapps.labs.pennmobile.classes.GSRRoom
import com.pennapps.labs.pennmobile.classes.GSRSlot
import io.fabric.sdk.android.Fabric
import kotlinx.android.synthetic.main.fragment_gsr.*
import kotlinx.android.synthetic.main.fragment_gsr.view.*
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import java.util.*
import kotlin.collections.ArrayList
class GsrFragment : Fragment() {
// ui components
lateinit var selectDateButton: Button
lateinit var selectTimeButton: Button
lateinit var gsrLocationDropDown: Spinner
lateinit var durationDropDown: Spinner
lateinit var loadingPanel: LinearLayout
lateinit var noResultsPanel: LinearLayout
// api manager
private lateinit var mLabs: Labs
//list that holds all GSR rooms
private val gsrHashMap = HashMap<String, Int>()
// all the gsrs
private var mGSRS = ArrayList<GSRContainer>()
private lateinit var selectedDateTime : DateTime
private val spinnerDateFormatter = DateTimeFormat.forPattern("M/d/yyyy")
private val timeFormatter = DateTimeFormat.forPattern("h:mm a")
private val adjustedDateFormat = DateTimeFormat.forPattern("yyyy-MM-dd")
private val gsrSlotFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ")
private lateinit var durationAdapter: ArrayAdapter<String>
private lateinit var huntsmanDurationAdapter: ArrayAdapter<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mLabs = MainActivity.getLabsInstance()
(activity as MainActivity).closeKeyboard()
// set default GSR selection date + time to the current date and time
selectedDateTime = DateTime.now()
activity?.setTitle(R.string.gsr)
// fabric report handling
Fabric.with(context, Crashlytics())
Answers.getInstance().logContentView(ContentViewEvent()
.putContentName("GSR")
.putContentType("App Feature")
.putContentId("0"))
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// link UI elements
val v = inflater.inflate(R.layout.fragment_gsr, container, false)
selectDateButton = v.gsr_select_date
selectTimeButton = v.gsr_select_time
gsrLocationDropDown = v.gsr_building_selection
durationDropDown = v.gsr_duration
loadingPanel = v.gsr_loading
noResultsPanel = v.gsr_no_results
durationAdapter = ArrayAdapter(activity, R.layout.gsr_spinner_item, arrayOf("30m", "60m", "90m", "120m"))
huntsmanDurationAdapter = ArrayAdapter(activity, R.layout.gsr_spinner_item, arrayOf("30m", "60m", "90m"))
// populate the list of gsrs
populateDropDownGSR()
// Set default start date for GSR booking
selectDateButton.text = selectedDateTime.toString(spinnerDateFormatter)
// Set default start time for GSR booking
selectTimeButton.text = selectedDateTime.toString(timeFormatter)
// Set up recycler view for list of GSR rooms
val gsrRoomListLayoutManager = LinearLayoutManager(context)
gsrRoomListLayoutManager.orientation = LinearLayoutManager.VERTICAL
v.gsr_rooms_list?.layoutManager = (gsrRoomListLayoutManager)
/**
* On Click functions for buttons
*/
//set start time button
selectTimeButton.setOnClickListener {
// Get Current Time
val c = Calendar.getInstance()
val mHour = c.get(Calendar.HOUR_OF_DAY)
val mMinute = c.get(Calendar.MINUTE)
// Launch Time Picker Dialog
val timePickerDialog = TimePickerDialog(activity,
TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
// Update hour + minute
selectedDateTime = DateTime(selectedDateTime.year, selectedDateTime.monthOfYear, selectedDateTime.dayOfMonth, hourOfDay, minute)
// Display the selected time; use Joda to do the formatting work
selectTimeButton.text = selectedDateTime.toString(timeFormatter)
searchForGSR(false)
}, mHour, mMinute, false)
timePickerDialog.show()
}
//day for gsr
selectDateButton.setOnClickListener {
// Get Current Date
val c = Calendar.getInstance()
val mYear = c.get(Calendar.YEAR)
val mMonth = c.get(Calendar.MONTH)
val mDay = c.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(activity,
DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
//account for index starting at 0
val entryMonth = monthOfYear + 1
// Update year + month + day
selectedDateTime = DateTime(year, entryMonth, dayOfMonth, selectedDateTime.hourOfDay, selectedDateTime.minuteOfHour)
// Display the selected date; use Joda to do the formatting work
selectDateButton.text = selectedDateTime.toString(spinnerDateFormatter)
searchForGSR(false)
}, mYear, mMonth, mDay)
//set min and max choices for dates. Want to limit to week.
val today = Date()
c.time = today
val minDate = c.time.time
c.time = today
c.add(Calendar.DAY_OF_MONTH, +6)
val maxDate = c.time.time
datePickerDialog.datePicker.maxDate = maxDate
datePickerDialog.datePicker.minDate = minDate
datePickerDialog.show()
}
// handle swipe to refresh
v.gsr_refresh_layout?.setColorSchemeResources(R.color.color_accent, R.color.color_primary)
v.gsr_refresh_layout?.setOnRefreshListener {
searchForGSR(true)
}
return v
}
override fun onResume() {
super.onResume()
activity?.setTitle(R.string.gsr)
(activity as MainActivity).setNav(R.id.nav_gsr)
populateDropDownGSR()
}
// Performs GSR search
// Called when page loads and whenever user changes start/end time, date, or building
fun searchForGSR(calledByRefreshLayout: Boolean) {
val location = mapGSR(gsrLocationDropDown.selectedItem.toString())
if (location == -1) {
showNoResults()
Toast.makeText(activity, "Error: could not load buildings", Toast.LENGTH_LONG).show()
} else {
// display loading screen if user did not use swipe refresh
if (!calledByRefreshLayout) {
loadingPanel.visibility = View.VISIBLE
gsr_rooms_list?.visibility = View.GONE
}
noResultsPanel.visibility = View.GONE
//get the hours
getTimes(location)
}
}
// Performs GET request and fetches the rooms and availability
private fun getTimes(location: Int) {
val adjustedDateString = selectedDateTime.toString(adjustedDateFormat)
selectDateButton.isClickable = false
selectTimeButton.isClickable = false
gsrLocationDropDown.isEnabled = false
durationDropDown.isEnabled = false
mLabs.gsrRoom(location, adjustedDateString)
?.subscribe({ gsr ->
activity?.let {activity ->
activity.runOnUiThread {
val gsrRooms = gsr.rooms
var timeSlotLengthZero = true
if (gsrRooms == null) {
// a certification error causes "room" field to remain null
showNoResults()
Toast.makeText(activity, "Error: Could not load GSRs", Toast.LENGTH_LONG).show()
} else {
for (i in gsrRooms.indices) {
val gsrRoom = gsrRooms[i]
val gsrTimeSlots = gsrRoom.slots
//checks if the time slots are ever nonzero
val size = gsrTimeSlots?.size ?: 0
if (size > 0) {
timeSlotLengthZero = false
}
if (gsrTimeSlots != null) {
filterInsertTimeSlots(gsrRoom, gsrTimeSlots)
}
}
}
// remove loading icon
loadingPanel.visibility = View.GONE
noResultsPanel.visibility = View.GONE
// stop refreshing
gsr_rooms_list?.visibility = View.VISIBLE
gsr_refresh_layout?.isRefreshing = false
if (timeSlotLengthZero) {
Toast.makeText(context, "No GSRs available", Toast.LENGTH_LONG).show()
}
gsr_rooms_list?.adapter = (context?.let {
GsrBuildingAdapter(it, mGSRS, Integer.toString(location), (durationDropDown.selectedItemPosition + 1) * 30)
})
mGSRS = ArrayList()
selectDateButton.isClickable = true
selectTimeButton.isClickable = true
gsrLocationDropDown.isEnabled = true
durationDropDown.isEnabled = true
}
}
}, { activity?.let {
activity ->
activity.runOnUiThread {
showNoResults()
Toast.makeText(activity, "Error: could not load GSRs", Toast.LENGTH_LONG).show()
selectDateButton.isClickable = true
selectTimeButton.isClickable = true
gsrLocationDropDown.isEnabled = true
durationDropDown.isEnabled = true
} }
}
)
}
private fun filterInsertTimeSlots(gsrRoom: GSRRoom, timeSlots: Array<GSRSlot>) {
val availableSlotsAfterSelectedTime = ArrayList<GSRSlot>()
// Filter time slots so only available slots occurring after selected time are used
for (pos in timeSlots.indices) {
val currSlot = timeSlots[pos]
if (currSlot.isAvailable) {
val startString = currSlot.startTime
val endString = currSlot.endTime
if (startString != null && endString != null) {
val endTime = gsrSlotFormatter.parseDateTime(endString)
if (endTime.isAfter(selectedDateTime)) {
availableSlotsAfterSelectedTime.add(currSlot)
}
}
}
}
val duration = (durationDropDown.selectedItemPosition + 1) * 30
// Insert GSR slots that meet the specified duration
for (pos in 0 until availableSlotsAfterSelectedTime.size - durationDropDown.selectedItemPosition) {
// starting time and slot
val startingSlot = availableSlotsAfterSelectedTime[pos]
val startTime = gsrSlotFormatter.parseDateTime(startingSlot.startTime)
// ending time and slot
val endingSlot = availableSlotsAfterSelectedTime[pos + durationDropDown.selectedItemPosition]
val endTime = gsrSlotFormatter.parseDateTime(endingSlot.endTime)
// if start time + duration = end time then these slots meet the duration requirement
if (startTime.plusMinutes(duration).isEqual(endTime)) {
val stringStartTime = startTime.toString(timeFormatter)
val stringEndTime = endTime.toString(timeFormatter)
val gsrName = gsrRoom.name ?: ""
val gsrRoomId = gsrRoom.room_id ?: 0
insertGSRSlot(gsrName, "$stringStartTime-$stringEndTime",
startTime, Integer.toString(gsrRoomId))
}
}
}
private fun populateDropDownGSR() {
mLabs.location()
?.subscribe({ locations ->
activity?.let {activity ->
activity.runOnUiThread {
//reset the drop down
val emptyArray = arrayOfNulls<String>(0)
val emptyAdapter = ArrayAdapter<String>(activity,
android.R.layout.simple_spinner_dropdown_item, emptyArray)
gsrLocationDropDown.adapter = emptyAdapter
val numLocations = locations.size
var i = 0
// go through all the rooms
while (i < numLocations) {
val locationName = locations[i]?.name ?: ""
when (locations[i].id) {
1086 -> gsrHashMap["Van Pelt"] = 1086
2587 -> gsrHashMap["Lippincott"] = 2587
2495 -> gsrHashMap["Edu Commons"] = 2495
2683 -> gsrHashMap["Biomedical"] = 2683
2637 -> gsrHashMap["Fisher"] = 2637
1090 -> gsrHashMap["Levin Building"] = 1090
2634 -> gsrHashMap["Museum Library"] = 2634
2636 -> gsrHashMap["VP Seminar"] = 2636
2611 -> gsrHashMap["VP Special Use"] = 2611
1 -> gsrHashMap["Huntsman Hall"] = 1
4370 -> gsrHashMap["PCPSE Building"] = 4370
else -> gsrHashMap[locationName] = locations[i].id
}
i++
}
val gsrs = gsrHashMap.keys.toList().toTypedArray()
val adapter = ArrayAdapter(activity, R.layout.gsr_spinner_item, gsrs)
gsrLocationDropDown.adapter = adapter
durationDropDown.adapter = if (gsrLocationDropDown.selectedItem.toString() == "Huntsman Hall")
huntsmanDurationAdapter else durationAdapter
searchForGSR(false)
}
}
}, {
activity?.let {activity ->
activity.runOnUiThread {
//hard coded in case runs into error
gsrHashMap["<NAME>"] = 1086
gsrHashMap["Lippincott"] = 2587
gsrHashMap["Edu Commons"] = 2495
gsrHashMap["Biomedical"] = 2683
gsrHashMap["Fisher"] = 2637
gsrHashMap["Levin Building"] = 1090
gsrHashMap["Museum Library"] = 2634
gsrHashMap["VP Seminar"] = 2636
gsrHashMap["VP Special Use"] = 2611
gsrHashMap["Huntsman Hall"] = 1
val gsrs = gsrHashMap.keys.toList().toTypedArray()
val adapter = ArrayAdapter(activity, R.layout.gsr_spinner_item, gsrs)
gsrLocationDropDown.adapter = adapter
durationDropDown.adapter = if (gsrLocationDropDown.selectedItem.toString() == "Huntsman Hall")
huntsmanDurationAdapter else durationAdapter
searchForGSR(false)
}
}
}
)
gsrLocationDropDown.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View?, i: Int, l: Long) {
// change possible durations depending on the location
durationDropDown.adapter = if (gsrLocationDropDown.selectedItem.toString() == "Huntsman Hall")
huntsmanDurationAdapter else durationAdapter
searchForGSR(false)
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
durationDropDown.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, pos: Int, p3: Long) {
searchForGSR(false)
}
override fun onNothingSelected(p0: AdapterView<*>?) {
// User did not change the duration
}
}
}
private fun showNoResults() {
// get rid of loading screen and display no results
noResultsPanel.visibility = View.VISIBLE
loadingPanel.visibility = View.GONE
gsr_rooms_list?.visibility = View.GONE
gsr_refresh_layout?.isRefreshing = false
}
//takes the name of the gsr and returns an int for the corresponding code
fun mapGSR(name: String): Int = gsrHashMap[name] ?: 0
//function that takes all available GSR sessions and populates mGSRs
fun insertGSRSlot(gsrName: String, GSRTimeRange: String, GSRStartTime: DateTime, GSRElementId: String) {
var encountered = false
for (i in mGSRS.indices) {
val currentGSR = mGSRS[i]
//if there is GSR, add the available session to the GSR Object
if (currentGSR.gsrName == gsrName) {
currentGSR.addGSRSlot(GSRTimeRange, GSRStartTime, GSRElementId)
encountered = true
}
}
//can't find existing GSR. Create new object
if (!encountered) {
val newGSRObject = GSRContainer(gsrName, GSRTimeRange, GSRStartTime, GSRElementId)
mGSRS.add(newGSRObject)
}
}
}
| 1
| null |
1
| 1
|
5725f6464799fb21173032d4bdd0d7ee8790e753
| 19,095
|
penn-mobile-android
|
MIT License
|
feature/mobile/provider/src/main/kotlin/com/flixclusive/feature/mobile/provider/ProvidersScreen.kt
|
rhenwinch
| 659,237,375
| false
|
{"Kotlin": 1425616, "Java": 18011}
|
package com.flixclusive.feature.mobile.provider
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.flixclusive.core.ui.common.TopBarWithBackButton
import com.flixclusive.core.ui.common.navigation.GoBackAction
import com.flixclusive.core.ui.mobile.util.getFeedbackOnLongPress
import com.flixclusive.core.ui.mobile.util.isAtTop
import com.flixclusive.core.ui.mobile.util.isScrollingUp
import com.flixclusive.feature.mobile.provider.util.DragAndDropUtils.dragGestureHandler
import com.flixclusive.feature.mobile.provider.util.rememberDragDropListState
import com.ramcosta.composedestinations.annotation.Destination
import kotlinx.coroutines.Job
import com.flixclusive.core.util.R as UtilR
@Destination
@Composable
fun ProvidersScreen(
navigator: GoBackAction
) {
val viewModel = hiltViewModel<ProvidersScreenViewModel>()
val coroutineScope = rememberCoroutineScope()
val overscrollJob = remember { mutableStateOf<Job?>(null) }
val dragDropListState = rememberDragDropListState(onMove = viewModel::onMove)
val listState = dragDropListState.getLazyListState()
val shouldShowTopBar by listState.isScrollingUp()
val listIsAtTop by listState.isAtTop()
Scaffold(
modifier = Modifier
.fillMaxSize(),
topBar = {
AnimatedVisibility(
visible = shouldShowTopBar,
enter = slideInVertically(initialOffsetY = { -it }) + fadeIn(),
exit = slideOutVertically(targetOffsetY = { -it }) + fadeOut()
) {
TopBarWithBackButton(
headerTitle = stringResource(id = UtilR.string.providers),
onNavigationIconClick = navigator::goBack
)
}
}
) { innerPadding ->
val topPadding by animateDpAsState(
targetValue = if (listIsAtTop) innerPadding.calculateTopPadding() else 0.dp,
label = ""
)
LazyColumn(
state = listState,
modifier = Modifier
.padding(top = topPadding)
.dragGestureHandler(
scope = coroutineScope,
itemListDragAndDropState = dragDropListState,
overscrollJob = overscrollJob,
feedbackLongPress = getFeedbackOnLongPress()
),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
itemsIndexed(viewModel.providers) { index, provider ->
val displacementOffset =
if (index == dragDropListState.getCurrentIndexOfDraggedListItem()) {
dragDropListState.elementDisplacement.takeIf { it != 0f }
} else null
ProviderCard(
provider = provider,
displacementOffset = displacementOffset,
onToggleProvider = {
viewModel.toggleProvider(index)
}
)
}
}
}
}
| 18
|
Kotlin
|
13
| 178
|
59652f790dd1c51186fc6e657b009b1508479d05
| 3,985
|
Flixclusive
|
MIT License
|
src/main/kotlin/it/valeriovaudi/vauthenticator/keypair/KeyRepository.kt
|
bassista
| 262,500,046
| true
|
{"Kotlin": 89774, "JavaScript": 9725, "HTML": 1854, "Dockerfile": 178}
|
package it.valeriovaudi.vauthenticator.keypair
import java.security.KeyPair
interface KeyRepository {
fun getKeyPair(): KeyPair
}
| 0
| null |
0
| 0
|
ed4ec3f1bc0773a99f165f2c6d6489067684e662
| 135
|
vauthenticator
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/juagri/shared/domain/usecase/LoginInfoUseCase.kt
|
juagrideveloper
| 699,804,299
| false
|
{"Kotlin": 1302992, "Swift": 6001, "Shell": 615}
|
package com.juagri.shared.domain.usecase
import com.juagri.shared.domain.model.employee.JUEmployee
import com.juagri.shared.domain.repo.user.LoginInfoRepository
class LoginInfoUseCase(
private val repository: LoginInfoRepository
) {
suspend fun getLoginInfoDetails(employee: JUEmployee) = repository.getLoginInfoDetails(employee)
}
| 0
|
Kotlin
|
0
| 0
|
dfb433421930bbf970fae303f5e496698f9d9e09
| 342
|
juagriapp
|
Apache License 2.0
|
app/src/main/kotlin/wskim/aos/appMonitoring/MonitoringForegroundService.kt
|
tmvlke
| 737,728,614
| false
|
{"Kotlin": 15859}
|
package wskim.aos.appMonitoring
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationChannelGroup
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
class MonitoringForegroundService : Service() {
private var isRunningYn = false
private val binder: IBinder = LocalBinder()
var data: MutableStateFlow<String?> = MutableStateFlow(null)
private val coroutineScope = CoroutineScope(Dispatchers.Default)
inner class LocalBinder : Binder() {
val service: MonitoringForegroundService
get() = this@MonitoringForegroundService
}
private fun setData(newData: String) {
data.value = newData
}
override fun onBind(intent: Intent?): IBinder {
return binder
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (!isRunningYn) {
// stopForeground(startId)
// stopSelf()
// } else {
isRunningYn = true
generateForegroundNotification()
coroutineScope.launch {
while (true) {
val packageName = AppFinder.getPackageName(this@MonitoringForegroundService)
Log.d("getPackageName", packageName)
setData(packageName)
delay(1000L)
}
}
}
return START_STICKY
}
//Notififcation for ON-going
private var iconNotification: Bitmap? = null
private var notification: Notification? = null
private var mNotificationManager: NotificationManager? = null
private val mNotificationId = 123
private fun generateForegroundNotification() {
val intentMainLanding = Intent(this, MainActivity::class.java)
val pendingIntent =
PendingIntent.getActivity(this, 0, intentMainLanding, PendingIntent.FLAG_IMMUTABLE)
iconNotification = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
if (mNotificationManager == null) {
mNotificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
assert(mNotificationManager != null)
mNotificationManager?.createNotificationChannelGroup(
NotificationChannelGroup("chats_group", "Chats")
)
val notificationChannel =
NotificationChannel("service_channel", "Service Notifications",
NotificationManager.IMPORTANCE_MIN)
notificationChannel.enableLights(false)
notificationChannel.lockscreenVisibility = Notification.VISIBILITY_SECRET
mNotificationManager?.createNotificationChannel(notificationChannel)
val builder = NotificationCompat.Builder(this, "service_channel")
builder.setContentTitle(StringBuilder(resources.getString(R.string.app_name)).append(" service is running").toString())
.setTicker(StringBuilder(resources.getString(R.string.app_name)).append("service is running").toString())
.setContentText("Touch to open") // , swipe down for more options.
.setSmallIcon(R.drawable.ic_alaram)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setWhen(0)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
.setOngoing(true)
if (iconNotification != null) {
builder.setLargeIcon(Bitmap.createScaledBitmap(iconNotification!!, 128, 128, false))
}
builder.color = resources.getColor(R.color.purple_200)
notification = builder.build()
startForeground(mNotificationId, notification)
}
}
| 0
|
Kotlin
|
0
| 0
|
9f7598aaec99a90f1df719eb701cc81b7eb81a82
| 4,168
|
AppMonitoring
|
Apache License 2.0
|
build-logic/convention/src/main/kotlin/AndroidLibraryConventionPlugin.kt
|
Japskiddin
| 766,410,608
| false
|
{"Kotlin": 35170}
|
import io.github.japskiddin.android.core.buildlogic.androidConfig
import io.github.japskiddin.android.core.buildlogic.configureJUnit
import io.github.japskiddin.android.core.buildlogic.configureJUnitAndroid
import io.github.japskiddin.android.core.buildlogic.configureKotlinAndroid
import io.github.japskiddin.android.core.buildlogic.configureKotlinJvm
import io.github.japskiddin.android.core.buildlogic.libs
import io.github.japskiddin.android.core.buildlogic.plugins
import org.gradle.api.Plugin
import org.gradle.api.Project
class AndroidLibraryConventionPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
plugins {
apply(libs.plugins.android.library.get().pluginId)
apply(libs.plugins.jetbrains.kotlin.android.get().pluginId)
}
androidConfig {
configureKotlinJvm()
configureKotlinAndroid(this)
configureJUnitAndroid()
configureJUnit()
buildFeatures {
buildConfig = true
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
94b70e0b7cbf8373e11ce824ef81596f1bdf5535
| 1,137
|
SudokuGame
|
Apache License 2.0
|
src/main/kotlin/com/fantasy/ladbe/common/web/CommonErrorResponse.kt
|
fantasy-fans-ko
| 420,898,576
| false
|
{"HTML": 1023453, "Kotlin": 74755}
|
package com.fantasy.ladbe.common.web
import com.fantasy.ladbe.handler.exception.Exceptions
import java.time.Instant
import javax.servlet.http.HttpServletRequest
/**
* @param errorCode ์๋ฌ ์ฝ๋
* @param httpStatus ์๋ฌ ์ํ์ ๋ํ ์ ๋ณด
* @param httpMethod ์ฌ์ฉ๋ method
* @param message ์๋ฌ์ ๋ํ ๋ด์ฉ
* @param path ์๋ฌ๊ฐ ๋ฐ์
* @param timestamp ์๋ฌ๊ฐ ๋ฐ์๋ ์๊ฐ
*/
data class CommonErrorResponse(
val errorCode: String = "",
val httpStatus: String = "",
val httpMethod: String = "",
val message: String = "",
val path: String = "",
val timestamp: Long = 0L,
) {
companion object {
fun error(
exceptions: Exceptions,
request: HttpServletRequest,
): CommonErrorResponse =
CommonErrorResponse(
errorCode = exceptions.code,
httpStatus = exceptions.status.toString(),
httpMethod = request.method,
message = exceptions.message,
path = request.requestURI,
timestamp = Instant.now().epochSecond
)
}
}
| 6
|
HTML
|
0
| 4
|
575112118816e80da943bbbf8237fa6fcb65411b
| 1,064
|
lad-be
|
MIT License
|
src/main/java/space/impact/impact_compat/common/tiles/base/BaseTileRotationEntityModel.kt
|
GT-IMPACT
| 658,419,880
| false
| null |
package space.impact.impact_compat.common.tiles.base
import software.bernie.geckolib3.core.PlayState
import software.bernie.geckolib3.core.builder.AnimationBuilder
import software.bernie.geckolib3.core.builder.ILoopType
import software.bernie.geckolib3.core.controller.AnimationController
import software.bernie.geckolib3.core.manager.AnimationData
@Suppress("unused")
open class BaseTileRotationEntityModel : BaseTileEntityModel {
companion object {
private const val WORK_R = "work.right"
private const val STOP_R = "stop.right"
private const val IDLE_R = "idle.right"
private const val WORK_L = "work.left"
private const val STOP_L = "stop.left"
private const val IDLE_L = "idle.left"
}
constructor(name: String) : super(name)
constructor() : super()
override fun animation(data: AnimationData) {
data.addAnimationController(AnimationController(this, CONTROLLER, TICK) {
if (isActive()) {
it.controller.setAnimation(AnimationBuilder().addAnimation(WORK_L, ILoopType.EDefaultLoopTypes.LOOP))
PlayState.CONTINUE
} else {
val builder = AnimationBuilder()
it.controller.setAnimation(builder.addAnimation(IDLE_L, ILoopType.EDefaultLoopTypes.LOOP))
PlayState.CONTINUE
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
18ab2a6b7a88a76eb90a4edef9a8ce9db207f3c7
| 1,384
|
Impact-compat
|
MIT License
|
app/src/main/java/org/simple/clinic/patient/filter/WeightedLevenshteinSearch.kt
|
eco4ndly
| 244,967,563
| false
| null |
package org.simple.clinic.patient.filter
import info.debatty.java.stringsimilarity.CharacterInsDelInterface
import info.debatty.java.stringsimilarity.CharacterSubstitutionInterface
import info.debatty.java.stringsimilarity.WeightedLevenshtein
import io.reactivex.Single
import org.simple.clinic.patient.PatientSearchResult
import java.util.UUID
class WeightedLevenshteinSearch(
private val minimumSearchTermLength: Int,
private val maximumAllowedEditDistance: Float,
private val resultsComparator: Comparator<PatientSearchContext>,
characterSubstitutionCost: Float,
characterInsertionCost: Float,
characterDeletionCost: Float
) : SearchPatientByName {
init {
if (minimumSearchTermLength < 1) {
throw AssertionError("Minimum search term length cannot be less than 1")
}
}
private val whiteSpaceRegex = Regex("[\\s]")
private val levenshtein = WeightedLevenshtein(
CharacterSubstitutionInterface { _, _ -> characterSubstitutionCost.toDouble() },
object : CharacterInsDelInterface {
override fun deletionCost(c: Char) = characterDeletionCost.toDouble()
override fun insertionCost(c: Char) = characterInsertionCost.toDouble()
}
)
override fun search(searchTerm: String, names: List<PatientSearchResult.PatientNameAndId>): Single<List<UUID>> {
val searchTermParts = stringToSearchableParts(searchTerm)
.filter { it.length >= minimumSearchTermLength }
return if (searchTermParts.isEmpty()) {
Single.just(emptyList())
} else {
val searchContext = names
.filter { it.fullName.isNotBlank() }
.map {
PatientSearchContext(
patient = it,
nameParts = stringToSearchableParts(it.fullName),
searchParts = searchTermParts)
}
.filter { it.nameParts.isNotEmpty() }
.map {
val distances = searchTermParts.zip(it.nameParts) { searchPart, namePart ->
PatientSearchContext.EditDistance(
namePart = namePart,
searchPart = searchPart,
editDistance = levenshtein.distance(searchPart, namePart))
}
it.copy(editDistances = distances)
}
.filter(this::discardLowQualityResults)
.sortedWith(resultsComparator)
Single.just(searchContext.map { it.patient.uuid })
}
}
private fun discardLowQualityResults(patientSearchContext: PatientSearchContext): Boolean {
return patientSearchContext.totalEditDistance <= maximumAllowedEditDistance
}
private fun stringToSearchableParts(string: String) = string.split(whiteSpaceRegex)
.filter { it.length >= minimumSearchTermLength }
.map { namePart -> namePart.filter { it.isLetter() } }
.filter { it.isNotBlank() }
.map { it.toLowerCase() }
}
| 1
| null |
1
| 1
|
c0bb3139dada4f34206928ec81f1e5f6f056134b
| 2,867
|
simple-android
|
MIT License
|
app/src/main/java/br/com/francielilima/marvelcharacters/presentation/character_detail/CharacterDetailViewModel.kt
|
francieli-lima
| 751,010,734
| false
|
{"Kotlin": 54422}
|
package br.com.francielilima.marvelcharacters.presentation.character_detail
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import br.com.francielilima.marvelcharacters.common.Resource
import br.com.francielilima.marvelcharacters.domain.use_case.get_character.GetCharacterByIdUseCase
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class CharacterDetailViewModel(
private val getCharacterByIdUseCase: GetCharacterByIdUseCase,
) : ViewModel() {
private val _state = mutableStateOf(CharacterDetailState())
val state: State<CharacterDetailState> = _state
fun onEvent(event: CharacterDetailEvent) {
when(event){
is CharacterDetailEvent.Reload -> {
getCharacter(event.id)
}
}
}
private fun getCharacter(id: Int) {
getCharacterByIdUseCase(id).onEach { result ->
when (result) {
is Resource.Success -> {
result.data?.let { character ->
_state.value = CharacterDetailState(character = character)
}
}
is Resource.Error -> {
_state.value = CharacterDetailState(
error = result.message ?: "An unexpected error occured"
)
}
is Resource.Loading -> {
_state.value = CharacterDetailState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
}
| 0
|
Kotlin
|
0
| 0
|
5e6ec2d626db85925e7bfa58bdb1ea2e4390ec3b
| 1,645
|
MarvelCharacters
|
Apache License 2.0
|
rxbilling/src/main/java/com/gen/rxbilling/flow/delegate/support/FragmentFlowDelegate.kt
|
LloydBlv
| 152,423,790
| true
|
{"Kotlin": 32882}
|
package com.gen.rxbilling.flow.delegate.support
import android.app.PendingIntent
import android.content.Intent
import android.support.v4.app.Fragment
import com.gen.rxbilling.flow.delegate.FlowDelegate
class FragmentFlowDelegate(private val fragment: Fragment) : FlowDelegate {
override fun startFlow(pendingIntent: PendingIntent, requestCode: Int) {
fragment.startIntentSenderForResult(
pendingIntent.intentSender, requestCode, Intent(), 0, 0, 0, null)
}
}
| 0
|
Kotlin
|
0
| 0
|
75b01a18e2e4559f05aaf987e1b2005584f13aee
| 492
|
RxBilling
|
MIT License
|
user-profile/src/main/kotlin/com/skufbet/userprofile/controller/UserProfileController.kt
|
otto15
| 781,677,300
| false
|
{"Kotlin": 91789, "Shell": 59}
|
package com.skufbet.userprofile.controller
import com.skufbet.common.userprofile.domain.UserProfile
import com.skufbet.userprofile.dto.CreateUserProfileRequestTo
import com.skufbet.userprofile.dto.ProfileIdTo
import com.skufbet.userprofile.service.UserProfileBalanceService
import com.skufbet.userprofile.service.UserProfileCreationService
import com.skufbet.userprofile.service.command.UserProfileCreateCommand
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
class UserProfileController(
private val userProfileCreationService: UserProfileCreationService,
private val userProfileBalanceService: UserProfileBalanceService,
) {
@PostMapping("/user-profiles")
fun create(
@RequestBody createUserProfileRequestTo: CreateUserProfileRequestTo
): ProfileIdTo {
return userProfileCreationService
.create(createUserProfileRequestTo.toCommand())
.toDto()
}
@PostMapping("/user-profiles/{id}/balance:withdraw")
fun withdrawFromBalance(@PathVariable id: Int, @RequestBody balanceOperationRequestTo: BalanceOperationRequestTo) {
userProfileBalanceService.withdraw(id, balanceOperationRequestTo.amount)
}
@PostMapping("/user-profiles/{id}/balance:deposit")
fun depositToBalance(@PathVariable id: Int, @RequestBody balanceOperationRequestTo: BalanceOperationRequestTo) {
userProfileBalanceService.deposit(id, balanceOperationRequestTo.amount)
}
@GetMapping("/user-profiles/{id}")
fun get(@PathVariable id: Int): ResponseEntity<Any> {
val userProfile = userProfileCreationService.get(id)
return userProfile?.let { ResponseEntity(userProfile, HttpStatus.OK) }
?: ResponseEntity(HttpStatus.NOT_FOUND)
}
@GetMapping("/user-profiles/keycloak/{id}")
fun getKeycloakId(@PathVariable id: String): ResponseEntity<Any> {
val userProfile = userProfileCreationService.getByKeycloakId(id)
return userProfile?.let { ResponseEntity(userProfile, HttpStatus.OK) }
?: ResponseEntity(HttpStatus.NOT_FOUND)
}
data class BalanceOperationRequestTo(val amount: Int)
fun CreateUserProfileRequestTo.toCommand() = UserProfileCreateCommand(
this.keycloakId,
this.mail,
this.phoneNumber,
this.password,
this.firstName,
this.lastName,
this.passport,
this.dateOfBirth,
this.taxPayerId,
)
fun UserProfile.toDto() = ProfileIdTo(this.id)
}
| 0
|
Kotlin
|
0
| 0
|
e540f16ada621f260bbf911630e4dbd1121cc903
| 2,582
|
skufbet
|
MIT License
|
src/test/kotlin/com/davioooh/lptools/BookFunctionsTest.kt
|
davioooh
| 265,240,152
| false
| null |
package com.davioooh.lptools
import com.davioooh.lptools.commons.LINE_SEPARATOR
import com.davioooh.lptools.commons.TestBookFolder
import com.davioooh.lptools.commons.fakeMdFileNamesList
import com.davioooh.lptools.commons.fakeTxtFileNamesList
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class BookFunctionsTest {
private lateinit var testBook: TestBookFolder
private val expected3TxtFiles = fakeTxtFileNamesList
private val expected3MdFiles = fakeMdFileNamesList
private val expectedBookTxt = expected3TxtFiles.joinToString(LINE_SEPARATOR, postfix = LINE_SEPARATOR)
@BeforeAll
fun setup(@TempDir testRootFolder: Path) {
testBook = TestBookFolder(testRootFolder)
}
@AfterEach
fun clearManuscriptFolder() {
testBook.deleteManuscriptFolder()
}
/* List chapter files */
@Test
fun `should find 3 TXT chapter files in manuscript folder`() {
testBook.createManuscriptFolder()
.withFakeChapters(3)
.withFakeBookTxt()
.withFile("ch04_test.pdf")
val txtChapters = listChapterFilesWithExtension(testBook.bookRootFolder, TXT_EXT)
assertThat(txtChapters).hasSize(3)
assertThat(txtChapters.map { it.name }).isEqualTo(expected3TxtFiles)
}
@Test
fun `should find 3 MD chapter files in manuscript folder`() {
testBook.createManuscriptFolder()
.withFakeChapters(3, MD_EXT)
.withFakeBookTxt()
.withFile("ch04_test.pdf")
val mdChapters = listChapterFilesWithExtension(testBook.bookRootFolder, MD_EXT)
assertThat(mdChapters).hasSize(3)
assertThat(mdChapters.map { it.name }).isEqualTo(expected3MdFiles)
}
/* Generate Book.txt */
@Test
fun `should generate Book_txt with 3 chapter files`() {
testBook.createManuscriptFolder()
val bookTxt = generateBookTxtFromFileNames(testBook.bookRootFolder, expected3TxtFiles)
assertThat(bookTxt.name).isEqualTo("Book.txt")
assertThat(bookTxt.readText()).isEqualTo(expectedBookTxt)
}
/* Create new chapter */
@Test
fun `should create new chapter file given the chapter number`() {
testBook.createManuscriptFolder()
val newChapter = createNewChapterFile(testBook.bookRootFolder, 3)
assertThat(newChapter.name).isEqualTo("ch3.txt")
assertThat(newChapter.readText()).isEqualTo("{#ch-3}$LINE_SEPARATOR# New Chapter$LINE_SEPARATOR")
}
@Test
fun `should create new chapter file given the chapter number and title`() {
testBook.createManuscriptFolder()
val newChapter = createNewChapterFile(testBook.bookRootFolder, 5, 1, "Chapter name")
assertThat(newChapter.name).isEqualTo("ch05_chapter-name.txt")
assertThat(newChapter.readText()).isEqualTo("{#ch-chapter-name}$LINE_SEPARATOR# Chapter name$LINE_SEPARATOR")
}
@Test
fun `should throw exception when file already exists`() {
testBook.createManuscriptFolder()
.withFakeChapters(3)
assertThatThrownBy {
createNewChapterFile(testBook.bookRootFolder, 2, 1)
}.isInstanceOf(IllegalStateException::class.java)
}
/* Chapter numbers */
@Test
fun `should return an array with the chapter numbers used in the manuscript`() {
testBook.createManuscriptFolder()
.withFakeChapters(3)
assertThat(fetchChapterNumbers(testBook.bookRootFolder)).isEqualTo(intArrayOf(1, 2, 3))
}
}
| 6
|
Kotlin
|
0
| 2
|
4fd4159bd67d0661b124831b39ba5368ddafa132
| 3,890
|
leanpub-manuscript-tools
|
Apache License 2.0
|
app/src/main/java/traps/celestnaveasy/View.kt
|
Bolbe
| 701,213,106
| false
|
{"Kotlin": 98403}
|
package traps.celestnaveasy
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import java.time.format.DateTimeFormatter
import kotlin.math.abs
fun isInRange(str: String, min: Double, max: Double): Boolean {
if (str.isEmpty()) return true
try {
val d = str.toDouble()
if (d>=min && d<max) return true
return true
} catch (e: Exception) {}
return false
}
fun isInRange(str: String, min: Int, max: Int): Boolean {
if (str.isEmpty()) return true
try {
val i = str.toInt()
if (i in min..max) return true
} catch (e: Exception) {}
return false
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainPanel() {
val focusManager = LocalFocusManager.current
Column (
modifier = Modifier.verticalScroll(rememberScrollState())
){
Text(
"FEUILLE DE CALCUL\nDROITE DE HAUTEUR",
fontSize = 30.sp,
lineHeight = 35.sp,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSecondaryContainer,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.secondaryContainer)
)
Text(
"Cette feuille de calcul permet de tracer une droite de hauteur (line of position) aprรจs une mesure au sextant de la hauteur du soleil. "+
"Elle intรจgre un algorithme de calcul des positions du soleil (https://midcdmz.nrel.gov/spa) pour une date+heure donnรฉe, ce qui permet de sauter (ou vรฉrifier) l'รฉtape de consultation des รฉphรฉmรฉrides papier. "+
"Elle dรฉroule ensuite les calculs pas ร pas. Elle donne au final la longueur et la direction de l'intercept qui vous permettra de tracer sur la carte votre droite de hauteur.",
modifier = Modifier.fillMaxSize()
)
Spacer(modifier = Modifier.height(20.dp))
Text("Date du jour", fontSize = 25.sp)
Spacer(modifier = Modifier
.height(3.dp)
.background(color = MaterialTheme.colorScheme.primary)
.fillMaxWidth())
Row(
modifier = Modifier.fillMaxWidth(),
) {
TextField(
value = mainController.dayStr.value,
label = { Text("Jour") },
modifier = Modifier.weight(1f),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Right) }),
onValueChange = { newText ->
if (isInRange(newText, 1, 31)) {
mainController.dayStr.value = newText
mainController.dataReady.value = false
}
}
)
TextField(
value = mainController.monthStr.value,
label = { Text("Mois") },
modifier = Modifier.weight(1f),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Right) }),
onValueChange = { newText ->
if (isInRange(newText, 1, 12)) {
mainController.monthStr.value = newText
mainController.dataReady.value = false
}
}
)
TextField(
value = mainController.yearStr.value,
label = { Text("Annรฉe") },
modifier = Modifier.weight(1f),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
onValueChange = { newText ->
if (isInRange(newText, 0, 3000)) {
mainController.yearStr.value = newText
mainController.dataReady.value = false
}
}
)
}
Spacer(modifier = Modifier.height(20.dp))
Text("Point de calcul G", fontSize = 25.sp)
Text("Le point de calcul est un point d'observation arbitraire, proche de votre position rรฉelle. On prend gรฉnรฉralement la position estimรฉe depuis le dernier point sextant. C'est par rapport ร ce point que l'on se positionnera sur la carte.")
Text("Latitude (LatG)", fontSize = 20.sp)
Spacer(modifier = Modifier
.height(3.dp)
.background(color = MaterialTheme.colorScheme.primary)
.fillMaxWidth())
DMSComponent(mainController.latitudeDMS, "N", "S")
Text("Longitude (LonG)", fontSize = 20.sp)
Spacer(modifier = Modifier
.height(3.dp)
.background(color = MaterialTheme.colorScheme.primary)
.fillMaxWidth())
DMSComponent(mainController.longitudeDMS, "E", "W")
Spacer(modifier = Modifier.height(20.dp))
Text("Correction instrument", fontSize = 25.sp)
Text("Il s'agit de l'erreur intrasรจque de votre sextant. On l'obtient en alignant l'horizon direct avec l'horizon reflรฉtรฉ. Si l'alignement est obtenue en remontant le reflet, la correction est positive, sinon elle est negative.")
Spacer(modifier = Modifier
.height(3.dp)
.background(color = MaterialTheme.colorScheme.primary)
.fillMaxWidth())
TextField(
value = mainController.correctionIndexStr.value,
label = { Text("Minutes") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
onValueChange = { newText ->
if (isInRange(newText, -100.0, 100.0)) {
mainController.correctionIndexStr.value = newText
mainController.dataReady.value = false
}
}
)
Spacer(modifier = Modifier.height(20.dp))
Text("Hauteur oeil", fontSize = 25.sp)
Text("Hauteur ร laquelle se trouve votre oeil au dessus de l'eau.")
Spacer(modifier = Modifier
.height(3.dp)
.background(color = MaterialTheme.colorScheme.primary)
.fillMaxWidth())
TextField(
value = mainController.eyeHeightStr.value,
label = { Text("Mรจtres") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
onValueChange = { newText ->
if (isInRange(newText,0.0, 60.0)) {
mainController.eyeHeightStr.value = newText
mainController.dataReady.value = false
}
}
)
Spacer(modifier = Modifier.height(25.dp))
Row (
modifier = Modifier.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround
){
RadioButtonText("1 mesure", !mainController.fiveMeasures.value) {
mainController.fiveMeasures.value = false
mainController.dataReady.value = false
}
RadioButtonText("5 mesures", mainController.fiveMeasures.value) {
mainController.fiveMeasures.value = true
mainController.dataReady.value = false
}
}
if (mainController.fiveMeasures.value)
Text("Quand on dรฉbute dans la manipulation du sextant, on peut amรฉliorer la prรฉcision en faisant 5 mesures successives ร moins d'une minute d'intervalle. Cette feuille de calcul choisira la meilleure mesure parmi les 5 en procรฉdant ร des rรฉgressions linรฉaires. La mesure choisie sera la plus proche de la droite passant au plus proche des 3 points les plus alignรฉs.")
val measureCount = if (mainController.fiveMeasures.value) 5 else 1
for (i in 0 until measureCount)
PointEditor(mainController.measureList[i])
Spacer(modifier = Modifier.height(25.dp))
Row(
modifier = Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.Center
) {
Button(onClick = {
mainController.compute()
}
) {
Text(text = "Montrer les calculs")
}
}
if (mainController.error.value.isNotEmpty()) {
Text(
text = mainController.error.value,
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.error)
.padding(16.dp),
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onError
)
}
if (mainController.dataReady.value && mainController.selectedMeasure!=null) {
val rawMeasure = mainController.selectedMeasure!!
Spacer(modifier = Modifier.height(20.dp))
//if (mainController.fiveMeasures.value) Text(mainController.explain)
ResultRow("Heure Mesure retenue", "${rawMeasure.timeValue.format(DateTimeFormatter.ofPattern("HH:mm:ss"))}", MaterialTheme.colorScheme.primaryContainer)
Text("Le ${mainController.day}-${mainController.month}-${mainController.year} ร ${rawMeasure.timeValue.format(DateTimeFormatter.ofPattern("HH:mm:ss"))}, " +
"les รฉphรฉmรฉrides papiers ou les algorithmes calculant la position du soleil nous donnent les valeurs suivantes:")
ResultRow("Sun declination (DEC)\n(Latitude du soleil)\nPositif au nord", "${"%.${5}fยฐ".format(mainController.sunDeclination)}")
ResultRow("Greenwich Hour Angle (GHA)\n(Longitude du soleil)\nPositif ร l'est", "${"%.${5}fยฐ".format(mainController.sunHourAngle)}")
Text("L'angle entre la longitude du point de calcul LatG et du soleil GHA est donc:")
ResultRow("Local Hour Angle LHA", "${"%.${5}fยฐ".format(mainController.localHourAngle)}")
Text("Le principe est maintenant de calculer la hauteur et l'azimuth du soleil si on l'observait depuis le point de calcul.")
Text("Hauteur calculรฉe Hc:")
Image(
painterResource(id = R.mipmap.hc),
contentDescription = null,
modifier = Modifier.fillMaxSize().height(50.dp).horizontalScroll(rememberScrollState()),
contentScale = ContentScale.FillHeight
)
Text("Avec les valeurs suivantes:")
ResultRow("DEC", "${"%.${5}fยฐ".format(mainController.sunDeclination)}")
ResultRow("LatG", "${"%.${5}fยฐ".format(mainController.latG)}")
ResultRow("LHA", "${"%.${5}fยฐ".format(mainController.localHourAngle)}")
Text("On obtient:")
ResultRow("Hc (dรฉcimale)", "${"%.${5}fยฐ".format(mainController.elevation)}", MaterialTheme.colorScheme.primaryContainer)
ResultRow("c'est ร dire", "${Calc.decimalToSexaStr(mainController.elevation)}", MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.onPrimary)
Text("Azimuth:")
Image(
painterResource(id = R.mipmap.azimuth),
contentDescription = null,
modifier = Modifier.fillMaxSize().height(100.dp).horizontalScroll(rememberScrollState()),
contentScale = ContentScale.FillHeight
)
Text("\nAzimuth = z si matin\nAzimuth = 360-z si aprรจs-midi\n", Modifier.background(MaterialTheme.colorScheme.secondaryContainer).fillMaxSize())
Text("Avec les valeurs suivantes:")
ResultRow("DEC", "${"%.${5}fยฐ".format(mainController.sunDeclination)}")
ResultRow("LatG", "${"%.${5}fยฐ".format(mainController.latG)}")
ResultRow("Hc", "${"%.${5}fยฐ".format(mainController.elevation)}")
Text("On obtient:")
ResultRow("Azimuth", "${mainController.azimuth}ยฐ", MaterialTheme.colorScheme.primaryContainer)
Text("\nRevenons ร notre mesure retenue:")
ResultRow("Mesure decimale retenue", "${"%.${3}fยฐ".format(mainController.rawMeasure)}", MaterialTheme.colorScheme.primaryContainer)
Text("On applique les corrections (minutes):")
ResultRow("Instrument", "${mainController.correctionIndexStr.value}'")
ResultRow("Hauteur oeil", "${"%.${5}f".format(mainController.correctionDip)}'")
ResultRow("Demi diametre soleil", "${mainController.correctionDiameter}'")
ResultRow("Refraction", "${"%.${5}f".format(mainController.correctionRefraction)}'")
ResultRow("Mesure corrigรฉe", "${"%.${3}fยฐ".format(mainController.correctedMeasure)}", MaterialTheme.colorScheme.secondaryContainer)
ResultRow("c'est ร dire", "${Calc.decimalToSexaStr(mainController.correctedMeasure)}", MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.onPrimary)
Text("Depuis le point de calcul, la hauteur du soleil serait")
ResultRow("", "${Calc.decimalToSexaStr(mainController.elevation)}")
Text("Or depuis notre position rรฉelle, on l'a mesurรฉe ร ")
ResultRow("", "${Calc.decimalToSexaStr(mainController.correctedMeasure)}")
Text("L'intercept mesure donc")
ResultRow("Intercept", "${"%.${1}f".format(mainController.intercept)} NM", MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.onPrimary)
if (mainController.towards_sun) {
Text("La hauteur mesurรฉe est supรฉrieure ร la hauteur vue depuis le point de calcul, donc l'intercept part du point de calcul et VA VERS le soleil.")
ResultRow("Direction intercept", "${mainController.azimuth}ยฐ", MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.onPrimary)
}
else {
Text("La hauteur mesurรฉe est infรฉrieure ร la hauteur vue depuis le point de calcul, donc l'intercept part du point de calcul et S'ELOIGNE du soleil.")
ResultRow("Direction intercept", "${mainController.azimuth180}ยฐ", MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.onPrimary)
}
}
Spacer(modifier = Modifier.height(50.dp))
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DMSComponent(dms: DMS, positiveText: String, negativeText:String) {
val focusManager = LocalFocusManager.current
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
TextField (
value = dms.degStr.value,
singleLine = true,
label = { Text("Degrรฉs") },
modifier = Modifier.weight(1f),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Right) }),
onValueChange = { newText ->
if (isInRange(newText, 0, 90)) {
mainController.dataReady.value = false
dms.degStr.value = newText
}
}
)
TextField (
value = dms.minStr.value,
singleLine = true,
label = { Text("Minutes") },
modifier = Modifier.weight(1f),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
onValueChange = { newText ->
if (isInRange(newText, 0.0, 60.0)) {
mainController.dataReady.value = false
dms.minStr.value = newText
}
}
)
val buttonText = if (dms.positive.value) positiveText else negativeText
Button(onClick = {
dms.positive.value = !dms.positive.value
mainController.dataReady.value = false
}
) {
Text(text = " ${buttonText} ")
}
}
}
@Composable
fun RadioButtonText(text: String, selected: Boolean, onClick: () -> Unit) {
Row (
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.selectable(
selected = selected,
onClick = onClick
)
){
RadioButton(
selected = selected,
onClick = onClick
)
Text(
text = text,
fontSize = 20.sp
)
}
}
@Composable
fun ResultRow(
title: String,
value: String,
bgColor: Color = MaterialTheme.colorScheme.background,
textColor: Color = MaterialTheme.colorScheme.onBackground)
{
Row(
modifier = Modifier
.fillMaxSize()
.background(bgColor)
.padding(10.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(title, fontSize = 16.sp, color = textColor)
Text(value, fontSize = 20.sp, color = textColor)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PointEditor(measure: Measure) {
val focusManager = LocalFocusManager.current
Column {
Spacer(modifier = Modifier.height(25.dp))
Row(
modifier = Modifier.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(measure.title, fontSize = 25.sp)
Button(onClick = {
measure.clear()
}
) {
Text(text = "Effacer")
}
}
Spacer(modifier = Modifier
.height(3.dp)
.background(color = MaterialTheme.colorScheme.primary)
.fillMaxWidth())
Row(Modifier.fillMaxWidth()) {
TextField(
value = measure.timeHour.value,
modifier = Modifier.weight(1f),
label = { Text("Heure") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Right) }),
onValueChange = { newText ->
if (isInRange(newText, 0, 24)) {
measure.timeHour.value = newText
mainController.dataReady.value = false
}
}
)
TextField(
value = measure.timeMinute.value,
modifier = Modifier.weight(1f),
label = { Text("Minute") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Right) }),
onValueChange = { newText ->
if (isInRange(newText, 0, 60)) {
measure.timeMinute.value = newText
mainController.dataReady.value = false
}
}
)
TextField(
value = measure.timeSecond.value,
modifier = Modifier.weight(1f),
label = { Text("Second") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) }),
onValueChange = { newText ->
if (isInRange(newText, 0, 60)) {
measure.timeSecond.value = newText
mainController.dataReady.value = false
}
}
)
}
Row(Modifier.fillMaxWidth()) {
TextField (
value = measure.deg.value,
label = { Text("Degrรฉs") },
modifier = Modifier.weight(1f),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Right) }),
onValueChange = { newText ->
if (isInRange(newText, 0, 90)) {
mainController.dataReady.value = false
measure.deg.value = newText
}
}
)
TextField (
value = measure.min.value,
label = { Text("Minutes") },
modifier = Modifier.weight(1f),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
onValueChange = { newText ->
if (isInRange(newText, 0.0, 60.0)) {
mainController.dataReady.value = false
measure.min.value = newText
}
}
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b60b5bd6d1cfc7cace58df0552c5e3d54240f7eb
| 23,416
|
sightreduction
|
Apache License 2.0
|
src/me/anno/ecs/components/shaders/Texture3DBTMaterial.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.ecs.components.shaders
import me.anno.ecs.components.mesh.Material
import me.anno.ecs.prefab.PrefabSaveable
import me.anno.gpu.shader.Shader
import me.anno.gpu.texture.Texture3D
import me.anno.gpu.texture.TextureLib.whiteTex3d
import me.anno.io.serialization.NotSerializedProperty
import me.anno.maths.Maths.max
import me.anno.utils.pooling.JomlPools
import org.joml.Vector3f
import org.joml.Vector3i
/**
* [Texture3D] - block traced material.
* This [Material] lerps between two colors.
* You can modify the materials to be more complex by writing your own [Texture3DBTShader]-like [Shader].
* */
@Suppress("unused")
open class Texture3DBTMaterial : Material() {
val size = Vector3i(1)
@NotSerializedProperty
var blocks: Texture3D? = null
set(value) {
field = value
if (value != null) {
size.set(value.width, value.height, value.depth)
}
}
var color0 = Vector3f()
var color1 = Vector3f()
init {
shader = Texture3DBTShader
}
fun limitColors(count: Int) {
val div = max(1, count - 1)
val f0 = 1f + 1f / div
val f1 = 1f - 255f / div
val tmp = JomlPools.vec3f.borrow().set(color0)
color0.lerp(color1, 1f - f0)
color1.lerp(tmp, f1)
}
override fun bind(shader: Shader) {
super.bind(shader)
val ti = shader.getTextureIndex("blocksTexture")
val blocks = blocks
if (ti >= 0) (blocks ?: whiteTex3d).bindTrulyNearest(ti)
shader.v3i("bounds", size)
// max amount of blocks that can be traversed
val maxSteps = max(1, size.x + size.y + size.z)
shader.v1i("maxSteps", maxSteps)
shader.v3f("color0", color0)
shader.v3f("color1", color1)
}
override fun copyInto(dst: PrefabSaveable) {
super.copyInto(dst)
dst as Texture3DBTMaterial
dst.color0.set(color0)
dst.color1.set(color1)
dst.size.set(size)
// texture cannot be simply copied
}
override val className: String get() = "Texture3DBTMaterial"
}
| 0
| null |
3
| 9
|
b2532f7d40527eb2c9e24e3659dd904aa725a1aa
| 2,120
|
RemsEngine
|
Apache License 2.0
|
crystal-map-connector/src/main/kotlin/ch/ergon/dope/extension/type/stringfunction/Substring1.kt
|
ergon
| 745,483,606
| false
|
{"Kotlin": 1886765}
|
package ch.ergon.dope.extension.type.stringfunction
import ch.ergon.dope.resolvable.expression.TypeExpression
import ch.ergon.dope.resolvable.expression.unaliased.type.function.stringfunction.substring1
import ch.ergon.dope.resolvable.expression.unaliased.type.toDopeType
import ch.ergon.dope.toDopeType
import ch.ergon.dope.validtype.NumberType
import ch.ergon.dope.validtype.StringType
import com.schwarz.crystalapi.schema.CMJsonField
fun substring1(
inStr: CMJsonField<String>,
startPos: TypeExpression<NumberType>,
length: TypeExpression<NumberType>? = null,
) = substring1(inStr.toDopeType(), startPos, length)
fun substring1(
inStr: TypeExpression<StringType>,
startPos: CMJsonField<Number>,
length: TypeExpression<NumberType>? = null,
) = substring1(inStr, startPos.toDopeType(), length)
fun substring1(
inStr: TypeExpression<StringType>,
startPos: TypeExpression<NumberType>,
length: CMJsonField<Number>,
) = substring1(inStr, startPos, length.toDopeType())
fun substring1(
inStr: CMJsonField<String>,
startPos: CMJsonField<Number>,
length: TypeExpression<NumberType>? = null,
) = substring1(inStr.toDopeType(), startPos.toDopeType(), length)
fun substring1(inStr: CMJsonField<String>, startPos: TypeExpression<NumberType>, length: CMJsonField<Number>) =
substring1(inStr.toDopeType(), startPos, length.toDopeType())
fun substring1(inStr: TypeExpression<StringType>, startPos: CMJsonField<Number>, length: CMJsonField<Number>) =
substring1(inStr, startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: CMJsonField<String>, startPos: CMJsonField<Number>, length: CMJsonField<Number>) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: CMJsonField<String>, startPos: TypeExpression<NumberType>, length: Int) =
substring1(inStr.toDopeType(), startPos, length.toDopeType())
fun substring1(inStr: TypeExpression<StringType>, startPos: CMJsonField<Number>, length: Int) =
substring1(inStr, startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: CMJsonField<String>, startPos: CMJsonField<Number>, length: Int) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: TypeExpression<StringType>, startPos: Int, length: CMJsonField<Number>) =
substring1(inStr, startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: CMJsonField<String>, startPos: Int, length: TypeExpression<NumberType>? = null) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length)
fun substring1(inStr: CMJsonField<String>, startPos: Int, length: CMJsonField<Number>) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: String, startPos: CMJsonField<Number>, length: TypeExpression<NumberType>? = null) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length)
fun substring1(inStr: String, startPos: TypeExpression<NumberType>, length: CMJsonField<Number>) =
substring1(inStr.toDopeType(), startPos, length.toDopeType())
fun substring1(inStr: String, startPos: CMJsonField<Number>, length: CMJsonField<Number>) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: CMJsonField<String>, startPos: Int, length: Int) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: String, startPos: CMJsonField<Number>, length: Int) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length.toDopeType())
fun substring1(inStr: String, startPos: Int, length: CMJsonField<Number>) =
substring1(inStr.toDopeType(), startPos.toDopeType(), length.toDopeType())
| 2
|
Kotlin
|
0
| 6
|
40b18241d25c360080768902fc108ea70bb2f211
| 3,722
|
dope-query-builder
|
MIT License
|
packages/graalvm/src/main/kotlin/elide/runtime/gvm/internals/intrinsics/js/base64/Base64Intrinsic.kt
|
elide-dev
| 506,113,888
| false
| null |
/*
* Copyright (c) 2023 Elide Ventures, LLC.
*
* Licensed under the MIT license (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://opensource.org/license/mit/
*
* 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 elide.runtime.gvm.internals.intrinsics.js.base64
import org.graalvm.polyglot.proxy.ProxyExecutable
import elide.core.encoding.base64.DefaultBase64
import elide.runtime.gvm.internals.intrinsics.Intrinsic
import elide.runtime.gvm.internals.intrinsics.js.AbstractJsIntrinsic
import elide.runtime.gvm.internals.intrinsics.js.JsSymbol.JsSymbols.asJsSymbol
import elide.runtime.intrinsics.GuestIntrinsic
import elide.runtime.intrinsics.js.JavaScriptBase64
import elide.vm.annotations.Polyglot
/** Implements [JavaScriptBase64] via [elide.core.encoding.DefaultBase64], by way of [NativeBase64Intrinsic]. */
@Intrinsic(global = Base64Intrinsic.GLOBAL_BASE64)
internal class Base64Intrinsic : JavaScriptBase64, AbstractJsIntrinsic() {
internal companion object {
/** Injected name of the Base64 global. */
const val GLOBAL_BASE64 = "Base64"
/** Injected name of the `btoa` intrinsic. */
private const val GLOBAL_BTOA = "btoa"
/** Injected name of the `atob` intrinsic. */
private const val GLOBAL_ATOB = "atob"
/** Base64 symbol. */
private val BASE64_SYMBOL = GLOBAL_BASE64.asJsSymbol()
}
/** @inheritDoc */
@Polyglot override fun encode(input: String, websafe: Boolean): String =
if (websafe) DefaultBase64.encodeWebSafe(input) else DefaultBase64.encodeToString(input)
/** @inheritDoc */
@Polyglot @Intrinsic(global = GLOBAL_BTOA) override fun encode(input: String): String =
encode(input, false)
/** @inheritDoc */
@Polyglot @Intrinsic(global = GLOBAL_ATOB) override fun decode(input: String): String =
DefaultBase64.decodeToString(input)
/** @inheritDoc */
override fun install(bindings: GuestIntrinsic.MutableIntrinsicBindings) {
// mount `Base64`
bindings[BASE64_SYMBOL] = this
// mount `atob`
bindings[GLOBAL_ATOB.asJsSymbol()] = ProxyExecutable {
return@ProxyExecutable decode(it.firstOrNull()?.asString() ?: error("Cannot decode $it as string"))
}
// mount `btoa`
bindings[GLOBAL_BTOA.asJsSymbol()] = ProxyExecutable {
return@ProxyExecutable encode(it.firstOrNull()?.asString() ?: error("Cannot decode $it as string"))
}
}
}
| 75
| null |
15
| 88
|
5cd3312b5ee32726db34f5673f0d4f557ec91cca
| 2,728
|
elide
|
MIT License
|
app/src/main/java/com/example/blank/ui/myfoodsearch/MyFoodSearchViewModel.kt
|
olahdome
| 264,719,519
| false
| null |
package com.example.blank.ui.myfoodsearch
import co.zsmb.rainbowcake.base.JobViewModel
import javax.inject.Inject
class MyFoodSearchViewModel @Inject constructor(
private val myFoodSearchPresenter: MyFoodSearchPresenter
) : JobViewModel<MyFoodSearchViewState>(Loading) {
fun load() = execute {
viewState = MyFoodSearchReady(myFoodSearchPresenter.getData())
}
}
| 1
|
Kotlin
|
0
| 0
|
cd6f5f95f8aa10a7b38acddc8ad47f381e94fb3e
| 385
|
SmartScaleRainbowCakeKotlin
|
Apache License 2.0
|
app-inspection/inspectors/database/testSrc/com/android/tools/idea/sqlite/controllers/ExportToFileControllerTest.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.sqlite.controllers
import com.android.testutils.MockitoKt.any
import com.android.testutils.MockitoKt.mock
import com.android.testutils.MockitoKt.whenever
import com.android.tools.idea.concurrency.AndroidCoroutineScope
import com.android.tools.idea.concurrency.FutureCallbackExecutor
import com.android.tools.idea.sqlite.DatabaseInspectorAnalyticsTracker
import com.android.tools.idea.sqlite.OfflineModeManager.DownloadProgress
import com.android.tools.idea.sqlite.OfflineModeManager.DownloadState.COMPLETED
import com.android.tools.idea.sqlite.OfflineModeManager.DownloadState.IN_PROGRESS
import com.android.tools.idea.sqlite.cli.SqliteCliArg
import com.android.tools.idea.sqlite.cli.SqliteCliArgs
import com.android.tools.idea.sqlite.cli.SqliteCliClientImpl
import com.android.tools.idea.sqlite.cli.SqliteCliProviderImpl
import com.android.tools.idea.sqlite.cli.SqliteCliResponse
import com.android.tools.idea.sqlite.controllers.DumpCommand.DumpDatabase
import com.android.tools.idea.sqlite.controllers.DumpCommand.DumpTable
import com.android.tools.idea.sqlite.controllers.ExportProcessedListener.Scenario.ERROR
import com.android.tools.idea.sqlite.controllers.ExportProcessedListener.Scenario.NOT_CALLED
import com.android.tools.idea.sqlite.controllers.ExportProcessedListener.Scenario.SUCCESS
import com.android.tools.idea.sqlite.databaseConnection.DatabaseConnection
import com.android.tools.idea.sqlite.databaseConnection.SqliteResultSet
import com.android.tools.idea.sqlite.mocks.CliDatabaseConnection
import com.android.tools.idea.sqlite.mocks.FakeExportToFileDialogView
import com.android.tools.idea.sqlite.mocks.OpenDatabaseRepository
import com.android.tools.idea.sqlite.model.DatabaseFileData
import com.android.tools.idea.sqlite.model.Delimiter.COMMA
import com.android.tools.idea.sqlite.model.Delimiter.SEMICOLON
import com.android.tools.idea.sqlite.model.Delimiter.TAB
import com.android.tools.idea.sqlite.model.Delimiter.VERTICAL_BAR
import com.android.tools.idea.sqlite.model.ExportFormat.CSV
import com.android.tools.idea.sqlite.model.ExportFormat.DB
import com.android.tools.idea.sqlite.model.ExportFormat.SQL
import com.android.tools.idea.sqlite.model.ExportRequest
import com.android.tools.idea.sqlite.model.ExportRequest.ExportDatabaseRequest
import com.android.tools.idea.sqlite.model.ExportRequest.ExportQueryResultsRequest
import com.android.tools.idea.sqlite.model.ExportRequest.ExportTableRequest
import com.android.tools.idea.sqlite.model.SqliteDatabaseId
import com.android.tools.idea.sqlite.model.SqliteDatabaseId.FileSqliteDatabaseId
import com.android.tools.idea.sqlite.model.SqliteDatabaseId.LiveSqliteDatabaseId
import com.android.tools.idea.sqlite.model.SqliteRow
import com.android.tools.idea.sqlite.model.SqliteStatement
import com.android.tools.idea.sqlite.model.createSqliteStatement
import com.android.tools.idea.sqlite.model.isInMemoryDatabase
import com.android.tools.idea.sqlite.ui.exportToFile.ExportInProgressViewImpl.UserCancellationException
import com.android.tools.idea.sqlite.utils.getJdbcDatabaseConnection
import com.android.tools.idea.sqlite.utils.initAdbFileProvider
import com.android.tools.idea.sqlite.utils.toLines
import com.android.tools.idea.sqlite.utils.unzipTo
import com.android.tools.idea.testing.ProjectServiceRule
import com.android.tools.idea.testing.runDispatching
import com.google.common.base.Stopwatch
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import com.google.wireless.android.sdk.stats.AppInspectionEvent.DatabaseInspectorEvent.ConnectivityState
import com.google.wireless.android.sdk.stats.AppInspectionEvent.DatabaseInspectorEvent.ExportOperationCompletedEvent.Destination
import com.google.wireless.android.sdk.stats.AppInspectionEvent.DatabaseInspectorEvent.ExportOperationCompletedEvent.Outcome
import com.google.wireless.android.sdk.stats.AppInspectionEvent.DatabaseInspectorEvent.ExportOperationCompletedEvent.Source
import com.google.wireless.android.sdk.stats.AppInspectionEvent.DatabaseInspectorEvent.ExportOperationCompletedEvent.SourceFormat
import com.intellij.mock.MockVirtualFile
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.EdtRule
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.RuleChain
import com.intellij.testFramework.RunsInEdt
import com.intellij.testFramework.fixtures.IdeaTestFixture
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
import com.intellij.testFramework.fixtures.TempDirTestFixture
import com.intellij.util.concurrency.EdtExecutorService
import com.intellij.util.io.createDirectories
import com.intellij.util.io.createParentDirectories
import com.intellij.util.io.delete
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption.REPLACE_EXISTING
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.MILLISECONDS
import java.util.concurrent.TimeUnit.SECONDS
import java.util.concurrent.atomic.AtomicInteger
import junit.framework.TestCase.fail
import kotlin.io.path.createFile
import kotlin.io.path.exists
import kotlin.io.path.fileSize
import kotlin.io.path.isDirectory
import kotlin.io.path.isRegularFile
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.guava.asListenableFuture
import kotlinx.coroutines.guava.await
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.jetbrains.ide.PooledThreadExecutor
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.mockito.ArgumentCaptor
import org.mockito.Mockito.verify
private const val nonAsciiSuffix = " ฤ
ฤ"
// Tests running from IntelliJ have a JNU encoding that doesn't support paths with non-ascii chars.
private val fileSuffix =
when (System.getProperty("sun.jnu.encoding")) {
"UTF-8" -> nonAsciiSuffix
else -> ""
}
private val table1 = "t1$fileSuffix"
private val table2 = "t2$fileSuffix"
private val table3 = "t3$fileSuffix"
private const val view1 = "v1$nonAsciiSuffix"
private const val view2 = "v2$nonAsciiSuffix"
private const val column1 = "c1$nonAsciiSuffix"
private const val column2 = "c2$nonAsciiSuffix"
private val databaseDir = "db-dir-$fileSuffix"
private val databaseFileName = "db$fileSuffix.db"
private val outputFileName = "output$fileSuffix.out"
private val downloadFolderName = "downloaded$fileSuffix"
// TODO(161081452): add in-memory database test coverage
@RunsInEdt
@RunWith(Parameterized::class)
class ExportToFileControllerTest(private val testConfig: TestConfig) {
companion object {
@Suppress("unused") // Used by JUnit via reflection
@JvmStatic
@get:Parameterized.Parameters(name = "{0}")
val testConfigurations =
listOf(
TestConfig(DatabaseType.File, targetFileAlreadyExists = true),
TestConfig(DatabaseType.File, targetFileAlreadyExists = false),
TestConfig(DatabaseType.Live, targetFileAlreadyExists = true),
TestConfig(DatabaseType.Live, targetFileAlreadyExists = false),
)
}
private val projectRule = ProjectRule()
private val disposableRule = DisposableRule()
private val analyticsTracker = mock<DatabaseInspectorAnalyticsTracker>()
@get:Rule
val rule =
RuleChain(
projectRule,
disposableRule,
ProjectServiceRule(
projectRule,
DatabaseInspectorAnalyticsTracker::class.java,
analyticsTracker,
),
EdtRule(),
)
/** Keeps connection ids unique */
private val nextConnectionId: () -> Int = run {
var next = 1;
{ next++ }
}
// TODO(aalbert): Maybe replace with `TemporaryFolder` rule. This would require making some
// changes regarding use of VirtualFile in production code.
private val tempDirTestFixture =
IdeaTestFixtureFactory.getFixtureFactory().createTempDirTestFixture()
private val exportInProgressListener: (Job) -> Unit = mock()
private val exportProcessedListener = ExportProcessedListener()
private val databaseDownloadTestFixture by lazy {
DatabaseDownloadTestFixture(tempDirTestFixture.toNioPath())
}
private val edtExecutor = EdtExecutorService.getInstance()
private val taskExecutor = PooledThreadExecutor.INSTANCE
private val databaseRepository by lazy { OpenDatabaseRepository(project, taskExecutor) }
private val databaseLockingTestFixture by lazy { DatabaseLockingTestFixture(databaseRepository) }
private val sqliteCliClient by lazy {
SqliteCliClientImpl(
SqliteCliProviderImpl(project).getSqliteCli()!!,
taskExecutor.asCoroutineDispatcher(),
)
}
private val view = FakeExportToFileDialogView()
private val controller by lazy {
ExportToFileController(
project,
AndroidCoroutineScope(project, edtExecutor.asCoroutineDispatcher()),
view,
databaseRepository,
databaseDownloadTestFixture::downloadDatabase,
{ databaseDownloadTestFixture.deleteDatabase(it) },
{ databaseLockingTestFixture.acquireDatabaseLock(it) },
{ databaseLockingTestFixture.releaseDatabaseLock(it) },
taskExecutor,
edtExecutor,
exportInProgressListener,
exportProcessedListener::onExportComplete,
exportProcessedListener::onExportError,
)
}
private val project
get() = projectRule.project
private val disposable
get() = disposableRule.disposable
@Before
fun setUp() {
initAdbFileProvider(project)
databaseDownloadTestFixture.setUp()
databaseLockingTestFixture.setUp()
tempDirTestFixture.setUp()
controller.setUp()
// 16 bytes - simulates scenarios where a query returns more rows than we allow in a batch
controller.responseSizeByteLimitHint = 16
Disposer.register(disposable, controller)
}
@After
fun tearDown() {
databaseDownloadTestFixture.tearDown()
runDispatching { databaseRepository.clear() }
tempDirTestFixture.tearDown()
databaseLockingTestFixture.tearDown()
}
@Test
fun testExportQueryToCsv() {
val database = createEmptyDatabase(testConfig.databaseType)
val values = populateDatabase(database, listOf(table1), listOf(view1)).single().content
val statement =
createSqliteStatement(
"select * from '$table1' where cast(\"$column1\" as text) > cast(5 as text)"
)
val dstPath = tempDirTestFixture.toNioPath().resolve(outputFileName)
val exportRequest = ExportQueryResultsRequest(database, statement, CSV(VERTICAL_BAR), dstPath)
values
.filter { (c1, _) -> c1 > "5" }
.let { expectedValues ->
assertThat(expectedValues).isNotEmpty()
testExport(exportRequest, expectedValues.toCsvOutputLines(exportRequest.delimiter))
}
}
@Test
fun testExportTableToCsv() {
val database = createEmptyDatabase(testConfig.databaseType)
val values = populateDatabase(database, listOf(table1), listOf(view1)).single().content
val dstPath = tempDirTestFixture.toNioPath().resolve(outputFileName)
val exportRequest = ExportTableRequest(database, table1, CSV(TAB), dstPath)
testExport(exportRequest, expectedValues = values.toCsvOutputLines(exportRequest.delimiter))
}
@Test
fun testExportTableToSql() {
val targetTable = table1
testExportToSql(
databaseType = testConfig.databaseType,
databaseTables = listOf(table1, table2, table3),
exportRequestCreator = { database, dstPath ->
ExportTableRequest(database, targetTable, SQL, dstPath)
},
expectedTableNames = listOf(targetTable),
expectedOutputDumpCommand = DumpTable(targetTable),
)
}
@Test
fun testExportDatabaseToSql() {
val databaseTables = listOf(table1, table2, table3)
testExportToSql(
databaseType = testConfig.databaseType,
databaseTables = databaseTables,
exportRequestCreator = { database, dstPath -> ExportDatabaseRequest(database, SQL, dstPath) },
expectedTableNames = databaseTables,
expectedOutputDumpCommand = DumpDatabase,
)
}
private fun testExportToSql(
databaseType: DatabaseType,
databaseTables: List<String>,
exportRequestCreator: (SqliteDatabaseId, dstPath: Path) -> ExportRequest,
expectedTableNames: List<String>,
expectedOutputDumpCommand: DumpCommand,
) {
val database = createEmptyDatabase(databaseType)
populateDatabase(database, databaseTables, listOf(view1, view2)).map { it.name }
val dstPath = tempDirTestFixture.toNioPath().resolve("$outputFileName.sql")
val exportRequest = exportRequestCreator(database, dstPath)
val expectedOutput =
runSqlite3Command(
SqliteCliArgs.builder()
.database(database.backingFile)
.apply { expectedOutputDumpCommand.setOnBuilder(this) }
.build()
)
.checkSuccess()
.stdOutput
.split(System.lineSeparator())
.also { lines ->
assertThat(lines).isNotEmpty()
expectedTableNames.forEach { tableName ->
assertThat(
lines.filter { it.contains("create table ".toRegex(RegexOption.IGNORE_CASE)) }
)
.hasSize(expectedTableNames.size)
assertThat(
lines.filter {
it.contains("create table .*$tableName".toRegex(RegexOption.IGNORE_CASE))
}
)
.isNotEmpty()
assertThat(
lines.filter {
it.contains("insert into .*$tableName".toRegex(RegexOption.IGNORE_CASE))
}
)
.isNotEmpty()
}
}
testExport(exportRequest, expectedOutput)
}
/** Overload suitable for single file output (e.g. exporting a query or a single table). */
private fun testExport(exportRequest: ExportRequest, expectedValues: List<String>) =
testExport(
exportRequest,
decompress = { file -> listOf(file) },
expectedOutput = listOf(ExpectedOutputFile(exportRequest.dstPath, expectedValues)), // no-op
)
/**
* Overload suitable for a general case (provide a [decompress] function if required to get the
* underlying output files).
*/
private fun testExport(
exportRequest: ExportRequest,
decompress: (Path) -> List<Path>,
expectedOutput: List<ExpectedOutputFile>,
verifyExportCallbacks: (durationMs: Long) -> Unit = { durationMs ->
assertThat(exportProcessedListener.scenario).isEqualTo(SUCCESS)
assertThat(exportProcessedListener.capturedRequest).isEqualTo(exportRequest)
assertAnalyticsTrackerCall(
analyticsTracker,
exportRequest,
durationMs,
Outcome.SUCCESS_OUTCOME,
)
},
) {
// then: compare output file(s) with expected output
val stopwatch = Stopwatch.createStarted()
requireEmptyFileAtDestination(exportRequest.dstPath, testConfig.targetFileAlreadyExists)
submitExportRequest(exportRequest)
verify(exportInProgressListener).invoke(controller.lastExportJob!!)
awaitExportComplete(15_000L)
stopwatch.stop()
verifyExportCallbacks(stopwatch.elapsed(MILLISECONDS))
exportRequest.srcDatabase.let { db ->
assertThat(databaseLockingTestFixture.wasLocked(db)).isEqualTo(db is LiveSqliteDatabaseId)
}
val actualFiles = decompress(exportRequest.dstPath).sorted()
assertThat(actualFiles).isEqualTo(expectedOutput.map { it.path }.sorted())
actualFiles.zip(expectedOutput.sortedBy { it.path }) {
actualPath,
(expectedPath, expectedValues) ->
assertThat(actualPath.toFile().canonicalPath).isEqualTo(expectedPath.toFile().canonicalPath)
assertThat(actualPath.toLines()).isEqualTo(expectedValues)
}
}
/** Checks what was reported to analytics tracker after a <b>successful</b> export operation. */
private fun assertAnalyticsTrackerCall(
analyticsTracker: DatabaseInspectorAnalyticsTracker,
exportRequest: ExportRequest,
maxDurationMs: Long,
expectedOutcome: Outcome,
) {
// Using captors below to go the opposite way than the prod code: from analytics values to
// export-request values.
// Otherwise, we'd end up with a copy of production code in the tests (which would be of
// questionable value).
val sourceCaptor = ArgumentCaptor.forClass(Source::class.java)
val sourceFormatCaptor = ArgumentCaptor.forClass(SourceFormat::class.java)
val destinationCaptor = ArgumentCaptor.forClass(Destination::class.java)
val durationMsCaptor = ArgumentCaptor.forClass(Int::class.java)
val connectivityStateCaptor = ArgumentCaptor.forClass(ConnectivityState::class.java)
val outcomeCaptor = ArgumentCaptor.forClass(Outcome::class.java)
// `trackExportCompleted` does not accept null values and ArgumentCaptor for classes cannot work
// around that.
// Using fallback values () below to work around it. These don't affect verifications.
verify(analyticsTracker)
.trackExportCompleted(
sourceCaptor.capture() ?: Source.UNKNOWN_SOURCE,
sourceFormatCaptor.capture() ?: SourceFormat.UNKNOWN_SOURCE_FORMAT,
destinationCaptor.capture() ?: Destination.UNKNOWN_DESTINATION,
durationMsCaptor.capture(),
outcomeCaptor.capture() ?: Outcome.UNKNOWN_OUTCOME,
connectivityStateCaptor.capture() ?: ConnectivityState.UNKNOWN_CONNECTIVITY_STATE,
)
when (sourceCaptor.allValues.single()) {
Source.DATABASE_SOURCE ->
assertThat(exportRequest).isInstanceOf(ExportDatabaseRequest::class.java)
Source.TABLE_SOURCE -> assertThat(exportRequest).isInstanceOf(ExportTableRequest::class.java)
Source.QUERY_SOURCE ->
assertThat(exportRequest).isInstanceOf(ExportQueryResultsRequest::class.java)
else -> fail()
}
when (sourceFormatCaptor.allValues.single()) {
SourceFormat.FILE_FORMAT ->
assertThat(exportRequest.srcDatabase.isInMemoryDatabase()).isFalse()
SourceFormat.IN_MEMORY_FORMAT ->
assertThat(exportRequest.srcDatabase.isInMemoryDatabase()).isTrue()
else -> fail()
}
val format =
when (exportRequest) {
is ExportDatabaseRequest -> exportRequest.format
is ExportTableRequest -> exportRequest.format
is ExportQueryResultsRequest -> exportRequest.format
else -> null
}
when (destinationCaptor.allValues.single()) {
Destination.DB_DESTINATION -> {
assertThat(format).isEqualTo(DB)
assertThat(exportRequest::class.java).isEqualTo(ExportDatabaseRequest::class.java)
}
Destination.SQL_DESTINATION -> {
assertThat(format).isEqualTo(SQL)
assertThat(exportRequest::class.java)
.isAnyOf(ExportDatabaseRequest::class.java, ExportTableRequest::class.java)
}
Destination.CSV_DESTINATION -> {
assertThat(format).isInstanceOf(CSV::class.java)
assertThat(exportRequest::class.java)
.isAnyOf(
ExportDatabaseRequest::class.java,
ExportTableRequest::class.java,
ExportQueryResultsRequest::class.java,
)
}
else -> fail()
}
durationMsCaptor.allValues.single().let { durationMs ->
assertThat(durationMs).isGreaterThan(0)
assertThat(durationMs).isAtMost(maxDurationMs.toInt())
}
when (connectivityStateCaptor.allValues.single()) {
ConnectivityState.CONNECTIVITY_ONLINE ->
assertThat(exportRequest.srcDatabase).isInstanceOf(LiveSqliteDatabaseId::class.java)
ConnectivityState.CONNECTIVITY_OFFLINE ->
assertThat(exportRequest.srcDatabase).isInstanceOf(FileSqliteDatabaseId::class.java)
else -> fail()
}
assertThat(outcomeCaptor.allValues.single()).isEqualTo(expectedOutcome)
}
@Suppress("BlockingMethodInNonBlockingContext") // [CountDownLatch#await]
@Test
fun testExportCancelledByTheUser() {
// set up a database
val connection: DatabaseConnection = mock()
// set up a database: prepare a 'freeze' on issuing a database query - making the export
// operation go indefinitely
val queryIssuedLatch = CountDownLatch(1)
whenever(connection.query(any())).thenAnswer {
queryIssuedLatch.countDown()
CoroutineScope(taskExecutor.asCoroutineDispatcher())
.async<List<SqliteRow>> {
CompletableDeferred<SqliteResultSet>()
.await() // never going to complete, giving us time to cancel the job
fail() // we never expect to get past the above line
mock()
}
.asListenableFuture()
}
val databaseId = SqliteDatabaseId.fromFileDatabase(DatabaseFileData(MockVirtualFile("srcDb")))
runDispatching { databaseRepository.addDatabaseConnection(databaseId, connection) }
// submit export request
val exportRequest =
ExportTableRequest(
databaseId,
"ignored",
CSV(SEMICOLON),
tempDirTestFixture.toNioPath().resolve(outputFileName),
)
val stopwatch = Stopwatch.createStarted()
requireEmptyFileAtDestination(exportRequest.dstPath, testConfig.targetFileAlreadyExists)
submitExportRequest(exportRequest)
// verify that in-progress-listener (responsible for the progress bar) got called
runDispatching { assertThat(queryIssuedLatch.await(5, SECONDS)).isTrue() }
val job = controller.lastExportJob!!
verify(exportInProgressListener).invoke(job)
assertThat(job.isActive).isTrue()
// cancel the job simulating the cancel button invoked by the user
job.cancel(UserCancellationException())
// verify the job gets cancelled and notifyError gets the confirmation
awaitExportComplete(5000L)
stopwatch.stop()
assertThat(exportProcessedListener.scenario).isEqualTo(ERROR)
assertThat(exportProcessedListener.capturedRequest).isEqualTo(exportRequest)
assertThat(exportProcessedListener.capturedError)
.isInstanceOf(CancellationException::class.java)
assertAnalyticsTrackerCall(
analyticsTracker,
exportRequest,
stopwatch.elapsed(MILLISECONDS),
Outcome.CANCELLED_BY_USER_OUTCOME,
)
}
@Test
fun testExportDatabaseToCsv() {
// given: a database with a number of tables
val database = createEmptyDatabase(testConfig.databaseType)
val tableValuePairs =
populateDatabase(database, listOf(table1, table2, table3), listOf(view1, view2))
val dstPath = tempDirTestFixture.toNioPath().resolve("$outputFileName.zip")
val exportRequest = ExportDatabaseRequest(database, CSV(COMMA), dstPath)
val tmpDir = tempDirTestFixture.findOrCreateDir("unzipped")
val decompress: (Path) -> List<Path> = { it.unzipTo(tmpDir.toNioPath()) }
val expectedOutput =
tableValuePairs.map { (table, values) ->
ExpectedOutputFile(
tmpDir.toNioPath().resolve("$table.csv"),
values.toCsvOutputLines(exportRequest.delimiter),
)
}
testExport(exportRequest, decompress, expectedOutput)
}
@Test
fun testExportDatabaseToDb() {
// given: a database
val database = createEmptyDatabase(testConfig.databaseType)
val expectedTables = listOf(table1, table2, table3)
val expectedViews = listOf(view1, view2)
populateDatabase(database, expectedTables, expectedViews)
// given: an export request
val exportRequest = let {
val dstPath =
tempDirTestFixture
.findOrCreateDir("destination-dir")
.toNioPath()
.resolve("$outputFileName.db")
ExportDatabaseRequest(database, DB, dstPath)
}
// given: a set of expected outputs
val (actualTablesPath, actualViewsPath, actualSchemaPath) =
tempDirTestFixture.findOrCreateDir("db-as-txt").toNioPath().let { dir ->
listOf("actual-tables.txt", "actual-views.txt", "actual-schema.txt").map { dir.resolve(it) }
}
val databaseToTextFiles: (Path) -> List<Path> = { path ->
runSqlite3Command(
SqliteCliArgs.builder().database(path).output(actualTablesPath).queryTableList().build()
)
.checkSuccess()
runSqlite3Command(
SqliteCliArgs.builder().database(path).output(actualViewsPath).queryViewList().build()
)
.checkSuccess()
runSqlite3Command(
SqliteCliArgs.builder().database(path).output(actualSchemaPath).dump().build()
)
.checkSuccess()
listOf(actualSchemaPath, actualTablesPath, actualViewsPath)
}
val expectedSchema =
runSqlite3Command(SqliteCliArgs.builder().database(database.backingFile).dump().build())
.checkSuccess()
.stdOutput
.split(System.lineSeparator())
val expected: List<ExpectedOutputFile> =
listOf(
ExpectedOutputFile(actualTablesPath, expectedTables),
ExpectedOutputFile(actualViewsPath, expectedViews),
ExpectedOutputFile(actualSchemaPath, expectedSchema),
)
// when/then:
testExport(exportRequest, databaseToTextFiles, expected)
}
private val SqliteDatabaseId.backingFile: Path
get() =
when (this) {
is FileSqliteDatabaseId -> databaseFileData.mainFile.toNioPath()
is LiveSqliteDatabaseId ->
Paths.get(
path
) // we use the fact that in the test setup, live db is backed by a local file
}
@Test
fun testInvalidRequest() {
// given: an invalid request
val exportRequest =
ExportTableRequest(
createEmptyDatabase(testConfig.databaseType),
"non-existing-table", // this will cause an exception (we are a database without any tables)
CSV(TAB),
tempDirTestFixture.createFile("ignored-output-file").toNioPath(),
)
// when/then
val stopwatch = Stopwatch.createStarted()
testExport(
exportRequest = exportRequest,
decompress = {
// assertThat(exportRequest.dstPath.exists()).isFalse() // TODO(161081452): don't leave
// empty files around on error
emptyList() // no output expected
},
expectedOutput = emptyList(), // no output expected
verifyExportCallbacks = {
assertThat(exportProcessedListener.scenario).isEqualTo(ERROR)
assertThat(exportProcessedListener.capturedRequest).isEqualTo(exportRequest)
val sqlException =
generateSequence(exportProcessedListener.capturedError) { it.cause }
.firstOrNull {
it.message?.contains("no such table.*${exportRequest.srcTable}".toRegex()) ?: false
}
assertWithMessage("Expecting a SQLite exception caused by an invalid query.")
.that(sqlException)
.isNotNull()
stopwatch.stop()
assertAnalyticsTrackerCall(
analyticsTracker,
exportRequest,
stopwatch.elapsed(MILLISECONDS),
Outcome.ERROR_OUTCOME,
)
},
)
}
@Test
fun testNextConnectionId() {
assertThat((1..5).map { nextConnectionId() }).isEqualTo((1..5).toList())
assertThat((1..5).map { nextConnectionId() }).isEqualTo((6..10).toList())
}
private fun submitExportRequest(exportRequest: ExportRequest) = runDispatching {
view.listeners.forEach { it.exportRequestSubmitted(exportRequest) }
}
/**
* By enforcing an empty file at destination (if [shouldExist]) we prevent files from previous
* test runs from causing a false positive test outcome.
*/
private fun requireEmptyFileAtDestination(path: Path, shouldExist: Boolean) {
// Directory case is unusual, and better to fail than accidentally delete too much data.
assertWithMessage(
"Export target ($path) is an existing directory. Expecting a file or a new path."
)
.that(path.isDirectory())
.isFalse()
when {
path.exists() ->
when {
!shouldExist -> path.delete()
shouldExist && path.fileSize() > 0 -> {
path.delete()
path.createParentDirectories().createFile()
}
}
shouldExist -> path.createParentDirectories().createFile()
}
assertThat(path.exists()).isEqualTo(shouldExist)
if (shouldExist) {
assertThat(path.isRegularFile()).isTrue()
assertThat(path.fileSize()).isEqualTo(0)
}
}
@Suppress("SameParameterValue")
private fun awaitExportComplete(timeoutMs: Long) = runDispatching {
withTimeout(timeoutMs) { controller.lastExportJob!!.join() }
}
private fun createEmptyDatabase(type: DatabaseType): SqliteDatabaseId {
val databaseFile = let {
val databaseDir = tempDirTestFixture.findOrCreateDir(databaseDir)
databaseDir.createChildFile(databaseFileName)
}
val connection =
when (type) {
DatabaseType.File -> createFileDatabaseConnection(databaseFile)
DatabaseType.Live ->
CliDatabaseConnection(databaseFile.toNioPath(), sqliteCliClient, '|', taskExecutor)
}
val databaseId =
when (type) {
DatabaseType.File -> SqliteDatabaseId.fromFileDatabase(DatabaseFileData(databaseFile))
DatabaseType.Live ->
SqliteDatabaseId.fromLiveDatabase(databaseFile.toNioPath().toString(), nextConnectionId())
}
runDispatching { databaseRepository.addDatabaseConnection(databaseId, connection) }
return databaseId
}
private fun populateDatabase(
database: SqliteDatabaseId,
tableNames: List<String>,
viewNames: List<String>,
): List<Table> {
fun createTable(database: SqliteDatabaseId, table: Table) {
database.execute("create table '${table.name}' ('$column1' int, '$column2' text)")
table.content.forEach { (v1, v2) ->
database.execute("insert into '${table.name}' values ('$v1', '$v2')")
}
}
val tableValuePairs =
tableNames.mapIndexed { ix, tableName ->
val first = ix + 1
val last = first * 11
Table(tableName, (first..last).toTwoColumnTable())
}
tableValuePairs.forEach { createTable(database, it) }
viewNames.forEach { viewName ->
database.execute(
"create view '$viewName' as select * from '${tableNames.first()}'"
) // to verify if views also get exported
}
return tableValuePairs
}
private fun SqliteDatabaseId.execute(statementText: String) = let { db ->
val statement = createSqliteStatement(statementText)
runDispatching { databaseRepository.executeStatement(db, statement).await() }
}
private fun createSqliteStatement(statement: String): SqliteStatement = runDispatching {
withContext(edtExecutor.asCoroutineDispatcher()) { createSqliteStatement(project, statement) }
}
private fun createFileDatabaseConnection(databaseFile: VirtualFile): DatabaseConnection =
runDispatching {
getJdbcDatabaseConnection(disposable, databaseFile, FutureCallbackExecutor.wrap(taskExecutor))
.await()
}
private fun runSqlite3Command(args: List<SqliteCliArg>): SqliteCliResponse = runDispatching {
withContext(taskExecutor.asCoroutineDispatcher()) { sqliteCliClient.runSqliteCliCommand(args) }
}
enum class DatabaseType {
Live,
File,
}
data class TestConfig(val databaseType: DatabaseType, val targetFileAlreadyExists: Boolean)
}
private fun SqliteCliResponse.checkSuccess(): SqliteCliResponse = apply {
assertThat(this.exitCode).isEqualTo(0)
}
private fun TempDirTestFixture.toNioPath() = File(tempDirPath).toPath()
private val ExportRequest.delimiter
get(): Char = (format as CSV).delimiter.delimiter
private sealed class DumpCommand(open val setOnBuilder: (SqliteCliArgs.Builder) -> Unit) {
object DumpDatabase : DumpCommand({ it.dump() })
data class DumpTable(val name: String) : DumpCommand({ it.dumpTable(name) })
}
private data class ExpectedOutputFile(val path: Path, val values: List<String>)
private typealias TwoColumnTable = List<Pair<String, String>>
private data class Table(val name: String, val content: TwoColumnTable)
private fun TwoColumnTable.toCsvOutputLines(delimiter: Char): List<String> =
listOf("$column1$delimiter$column2") + this.map { (v1, v2) -> "$v1$delimiter$v2" }
/** Two columns with increasing numbers (and a non-ascii suffix) */
private fun IntRange.toTwoColumnTable(): TwoColumnTable =
this.map { "$it$nonAsciiSuffix" }.zipWithNext()
private fun VirtualFile.createChildFile(name: String): VirtualFile {
if (!isDirectory) throw IllegalStateException("Parent needs to be a directory. Got: $this.")
if (findChild(name) != null) throw IllegalStateException("Child already exists.")
return runWriteAction { createChildData(null, name) }
}
/** Simulates downloading a [LiveSqliteDatabaseId] */
private class DatabaseDownloadTestFixture(private val tmpDir: Path) : IdeaTestFixture {
private lateinit var downloadFolder: Path
private lateinit var downloaded: MutableList<DatabaseFileData>
private lateinit var deleted: MutableList<DatabaseFileData>
override fun setUp() {
downloadFolder = tmpDir.resolve(downloadFolderName).createDirectories()
downloaded = mutableListOf()
deleted = mutableListOf()
}
override fun tearDown() {
val sortKey = { fileData: DatabaseFileData -> fileData.mainFile.path }
assertThat(deleted.sortedBy(sortKey)).isEqualTo(downloaded.sortedBy(sortKey))
}
fun downloadDatabase(
db: LiveSqliteDatabaseId,
handleError: (String, Throwable?) -> Unit,
): Flow<DownloadProgress> = flow {
try {
val downloadedDatabase = createDatabaseCopy(db)
downloaded.add(downloadedDatabase)
emit(DownloadProgress(IN_PROGRESS, listOf(downloadedDatabase), 1))
emit(DownloadProgress(IN_PROGRESS, listOf(downloadedDatabase), 1))
emit(DownloadProgress(COMPLETED, listOf(downloadedDatabase), 1))
} catch (t: Throwable) {
handleError("Error while downloading a database: ${db.name}", t)
}
}
fun deleteDatabase(file: DatabaseFileData) {
deleted.add(file)
}
private fun createDatabaseCopy(db: LiveSqliteDatabaseId): DatabaseFileData {
val src =
Paths.get(
db.path
) // in test set up the database will already be on disk (i.e. not on a device)
val dbFileName = src.fileName.toString()
val mainFile = createFile(dbFileName)
val wal1 = createFile("$dbFileName.wal1") // empty WAL
val wal2 = createFile("$dbFileName.wal2") // empty WAL
Files.copy(src, mainFile, REPLACE_EXISTING)
return DatabaseFileData(mainFile.toVirtualFile(), listOf(wal1, wal2).map { it.toVirtualFile() })
}
private fun createFile(dbFileName: String): Path =
downloadFolder.resolve(dbFileName).also { it.createParentDirectories().createFile() }
private fun Path.toVirtualFile(): VirtualFile = VfsUtil.findFile(this, true)!!
}
/**
* Simulates database locking.
*
* Additionally, ensures that:
* - locks are only requested for [LiveSqliteDatabaseId]s,
* - [releaseDatabaseLock] only accepts locks issued by [acquireDatabaseLock],
* - a lock can only be released once,
* - all locks are released by the time [tearDown] is called.
*/
private class DatabaseLockingTestFixture(private val databaseRepository: OpenDatabaseRepository) :
IdeaTestFixture {
private lateinit var nextLockId: AtomicInteger
private lateinit var lockIdToDatabase: ConcurrentHashMap<Int, SqliteDatabaseId>
private lateinit var lockHistory:
ConcurrentHashMap<SqliteDatabaseId, Unit> // using the map as a set
override fun setUp() {
nextLockId = AtomicInteger(1)
lockIdToDatabase = ConcurrentHashMap()
lockHistory = ConcurrentHashMap()
}
override fun tearDown() {
assertThat(lockIdToDatabase).isEmpty()
}
fun acquireDatabaseLock(databaseId: Int): Int {
val db =
databaseRepository.openDatabases.filterIsInstance<LiveSqliteDatabaseId>().single {
it.connectionId == databaseId
}
val lock = nextLockId.getAndIncrement()
lockIdToDatabase.put(lock, db) ?: return lock
throw IllegalStateException()
}
fun releaseDatabaseLock(lockId: Int) {
val db = lockIdToDatabase.remove(lockId) ?: throw IllegalStateException()
lockHistory[db] =
Unit // presence of the key in the map is sufficient to indicate that the db was locked
}
fun wasLocked(db: SqliteDatabaseId): Boolean = lockHistory.containsKey(db)
}
/** Allows to track the outcome of an [ExportRequest] submitted to an [ExportToFileController]. */
private class ExportProcessedListener {
var capturedRequest: ExportRequest? = null
var capturedError: Throwable? = null
var scenario: Scenario = NOT_CALLED
fun onExportComplete(request: ExportRequest) {
checkOnlyCall()
capturedRequest = request
scenario = SUCCESS
}
fun onExportError(request: ExportRequest, error: Throwable?) {
checkOnlyCall()
capturedRequest = request
capturedError = error
scenario = ERROR
}
private fun checkOnlyCall() {
if (scenario != NOT_CALLED)
throw IllegalStateException(
"Expected: a single call to a callback method. Actual: more than one call."
)
}
enum class Scenario {
NOT_CALLED,
SUCCESS,
ERROR,
}
}
| 5
| null |
230
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 38,247
|
android
|
Apache License 2.0
|
src/main/kotlin/org/kstore/demo/stars/gameplay/view/console/component/tech/actions.kt
|
minorbyte
| 194,674,817
| false
| null |
package org.kstore.demo.stars.gameplay.view.console.component.tech
import react.kstore.selection.*
class SelectNextTech: SelectNextListItemAction
class SelectPrevTech: SelectPreviousListItemAction
class ResearchSelectedAction
| 0
|
Kotlin
|
0
| 0
|
b91a6a00d4e60a84dc8bceba5dd02c3aa352ca88
| 230
|
kotlin-reactive-store
|
MIT License
|
demo/src/main/java/br/com/suamusica/rxmediaplayer/QueueActivity.kt
|
SuaMusica
| 110,037,546
| false
| null |
package br.com.suamusica.rxmediaplayer
import android.os.Bundle
import br.com.suamusica.rxmediaplayer.android.RxMediaServiceActivity
class QueueActivity : RxMediaServiceActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_queue)
}
}
| 0
|
Kotlin
|
0
| 0
|
6a8a2099f6026d158531ff06d6d517a7927f7d5b
| 328
|
RxMediaPlayer
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/ui/theme/Color.kt
|
nezih94
| 347,229,883
| false
| null |
/*
* Copyright 2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.theme
import androidx.compose.ui.graphics.Color
val primary_lightTheme = Color(0xFFFFF1F1)
val primaryVariant_lightTheme = Color(0xFF3F2C2C)
val secondary_lightTheme = Color(0xFF3F2C2C)
val background_lightTheme = Color(0xFFFFFFFF)
val surface_lightTheme = Color(0xD9FFFFFF)
val onprimary_lightTheme = Color(0xFF232323)
val onsecondary_lightTheme = Color(0xFFFFFFFF)
val onbackground_lightTheme = Color(0xFF232323)
val onsurface_lightTheme = Color(0xFF232323)
val primary_darkTheme = Color(0xFF2D3B2D)
val primaryVariant_darkTheme = Color(0xFFFFFFFF)
val secondary_darkTheme = Color(0xFFB8C9B8)
val background_darkTheme = Color(0xFF232323)
val surface_darkTheme = Color(0x26FFFFFF)
val onprimary_darkTheme = Color(0xFFFFFFFF)
val onsecondary_darkTheme = Color(0xFF232323)
val onbackground_darkTheme = Color(0xFFFFFFFF)
val onsurface_darkTheme = Color(0xD9FFFFFF)
| 0
|
Kotlin
|
0
| 0
|
871f6e16bc650536b65fcaf807c58668bb42cc7b
| 1,525
|
arriba
|
Apache License 2.0
|
app/src/main/java/org/listenbrainz/android/repository/brainzplayer/BPArtistRepositoryImpl.kt
|
metabrainz
| 550,726,972
| false
| null |
package org.listenbrainz.android.repository.brainzplayer
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import org.listenbrainz.android.model.Album
import org.listenbrainz.android.model.Artist
import org.listenbrainz.android.model.Song
import org.listenbrainz.android.model.dao.ArtistDao
import org.listenbrainz.android.util.AlbumsData
import org.listenbrainz.android.util.SongsData
import org.listenbrainz.android.util.Transformer.toAlbumEntity
import org.listenbrainz.android.util.Transformer.toArtist
import org.listenbrainz.android.util.Transformer.toArtistEntity
import org.listenbrainz.android.util.Transformer.toSongEntity
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ArtistRepositoryImpl @Inject constructor(
private val artistDao: ArtistDao
) : ArtistRepository {
override fun getArtist(artistID: String): Flow<Artist> {
val artist = artistDao.getArtistEntity(artistID)
return artist.map {
it.toArtist()
}
}
override fun getArtists(): Flow<List<Artist>> =
artistDao.getArtistEntities()
.map { it ->
it.map {
it.toArtist()
}
}
override suspend fun addArtists(userRequestedRefresh: Boolean): Boolean {
val artists = AlbumsData.fetchAlbums(userRequestedRefresh)
.map {
it.toArtistEntity()
}
.distinct()
// Deleting all artists
artistDao.deleteAllArtists()
lateinit var songsJob : Deferred<Unit>
lateinit var albumsJob : Deferred<Unit>
withContext(Dispatchers.IO){
// Both jobs are being executed simultaneously.
songsJob = async {
for (artist in artists) {
// Here, if userRequestedRefresh is true, it will refresh songs cache which is what we expect from refreshing
artist.songs.addAll(addAllSongsOfArtist(artist.toArtist(), userRequestedRefresh).map {
it.toSongEntity()
})
}
}
albumsJob = async {
for (artist in artists) {
// We do not need to refresh cache (songsListCache) here as it already got refreshed above when we created list of albums.
artist.albums.addAll(addAllAlbumsOfArtist(artist.toArtist()).map {
it.toAlbumEntity()
})
}
}
}
songsJob.await()
albumsJob.await()
artistDao.addArtists(artists)
return artists.isNotEmpty()
}
override suspend fun addAllSongsOfArtist(artist: Artist, userRequestedRefresh: Boolean): List<Song> {
return SongsData.fetchSongs(userRequestedRefresh).filter {
it.artist == artist.name
}
.map {
it
}
}
override suspend fun addAllAlbumsOfArtist(artist: Artist): List<Album> {
return AlbumsData.fetchAlbums().filter {
it.artist == artist.name
}
.map {
it
}
}
}
| 4
| null |
31
| 99
|
573ab0ec6c5b87ea963f013174159ddfcd123976
| 3,393
|
listenbrainz-android
|
Apache License 2.0
|
src/ii_collections/_19_Sum_.kt
|
blissd
| 96,249,939
| true
|
{"Kotlin": 78558, "Java": 4952}
|
package ii_collections
fun example6() {
val sum = listOf(1, 5, 3).sum()
}
fun Customer.getTotalOrderPrice(): Double {
return this.orders.flatMap { it.products }.map { it.price }.sum()
}
| 0
|
Kotlin
|
0
| 0
|
af992c41c5c1c17701c361859ef3f68e2d4d8c4c
| 196
|
kotlin-koans
|
MIT License
|
Task-Tracker-Usecases-SQLite-Impl/src/jvmTest/kotlin/app/tasktrackersystems/tasktracker/usecases/sqlite/InMemoryDriverFactory.kt
|
Task-Tracker-Systems
| 644,555,079
| false
|
{"Kotlin": 22178}
|
package app.tasktrackersystems.tasktracker.usecases.sqlite
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
import app.tasktrackersystems.tasktracker.usecases.tasks.DBDriverFactory
class InMemoryDriverFactory : DBDriverFactory {
override fun createDriver(): SqlDriver =
JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY)
.apply {
Database.Schema.create(this)
}
}
| 13
|
Kotlin
|
0
| 0
|
073ec11c01c44e433a571e5049e1843f915dcf0b
| 465
|
Task-Tracker-App
|
MIT License
|
src/main/kotlin/it/scoppelletti/spaceship/gradle/model/NoticeModel.kt
|
dscoppelletti
| 263,325,699
| false
| null |
/*
* Copyright (C) 2022 Dario Scoppelletti, <http://www.scoppelletti.it/>.
*
* 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 it.scoppelletti.spaceship.gradle.model
/**
* Notice file model.
*
* @since 1.0.0
*
* @property projectTitle Title of the project.
* @property developerName Name of the developer.
* @property developerUrl URL of the developer website.
* @property inceptionYear Inception year.
*/
public data class NoticeModel(
public val projectTitle: String?,
public val developerName: String? = null,
public val developerUrl: String? = null,
public val inceptionYear: String? = null
)
| 0
|
Kotlin
|
0
| 0
|
4d4c6baacbea94b58bd0edc2dc67ad1c0ddd709f
| 1,145
|
spaceship-gradle
|
Apache License 2.0
|
site/src/jsMain/kotlin/zakadabar.site.frontend/Routing.kt
|
kondorj
| 355,137,640
| true
|
{"Kotlin": 577495, "HTML": 828, "JavaScript": 820, "Shell": 253}
|
/*
* Copyright ยฉ 2020, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.site.frontend
import zakadabar.site.frontend.pages.misc.Home
import zakadabar.stack.frontend.application.ZkAppRouting
object Routing : ZkAppRouting(DefaultLayout, Home) {
init {
+ Home
}
}
| 0
| null |
0
| 0
|
2379c0fb031f04a230e753a9afad6bd260f6a0b2
| 356
|
zakadabar-stack
|
Apache License 2.0
|
src/main/java/kr/co/byrobot/petroneapi/Enum/PetroneLightMode.kt
|
roylanceMichael
| 109,197,642
| true
|
{"Kotlin": 171938}
|
package kr.co.byrobot.petroneapi.Enum
/**
* Created by byrobot on 2017. 9. 26..
*/
enum class PetroneLightMode(val mode: Byte) {
NONE(0),
WaitingForConnect(0x01), ///< Waiting for connect
Connected(0x02),
EyeNone(0x10),
EyeHold(0x11), ///< Eye light hold
EyeMix(0x12), ///< Eye light color change
EyeFlicker(0x13), ///< Eye light flickering
EyeFlickerDouble(0x14), ///< Eye light flickering 2times
EyeDimming(0x15), ///< Eye light dimming
ArmNone(0x40),
ArmHold(0x41), ///< ์ง์ ํ ์์์ ๊ณ์ ์ผฌ
ArmMix(0x42), ///< ์์ฐจ์ ์ผ๋ก LED ์ ๋ณ๊ฒฝ
ArmFlicker(0x43), ///< ๊น๋นก์
ArmFlickerDouble(0x44), ///< ๊น๋นก์(๋ ๋ฒ ๊น๋นก์ด๊ณ ๊น๋นก์ธ ์๊ฐ๋งํผ ๊บผ์ง)
ArmDimming(0x45), ///< ๋ฐ๊ธฐ ์ ์ดํ์ฌ ์ฒ์ฒํ ๊น๋นก์
ArmFlow(0x46), ///< ์์์ ๋ค๋ก ํ๋ฆ
ArmFlowReverse(0x47), ///< ๋ค์์ ์์ผ๋ก ํ๋ฆ
EndOfType(0x48);
}
| 0
|
Kotlin
|
0
| 0
|
6fadf2cddc754431f15b9e0090e26bf2da7d71a1
| 872
|
PetroneAPI_kotlin
|
MIT License
|
app/src/main/java/com/geekymusketeers/uncrack/presentation/auth/AuthViewModel.kt
|
uncrack-vault
| 569,328,395
| false
|
{"Kotlin": 306752, "Java": 23299}
|
package com.aritradas.uncrack.presentation.auth
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.aritradas.uncrack.domain.model.User
import com.aritradas.uncrack.util.runIO
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.ktx.Firebase
import timber.log.Timber
class AuthViewModel : ViewModel() {
private val auth = Firebase.auth
val resetPassword = MutableLiveData<Boolean>()
val errorLiveData = MutableLiveData<String>()
val registerStatus = MutableLiveData<Boolean>()
val loginSuccess = MutableLiveData<Boolean>()
fun resetPassword(email: String) = runIO {
FirebaseAuth.getInstance().sendPasswordResetEmail(email)
.addOnSuccessListener {
resetPassword.postValue(true)
}.addOnFailureListener {
errorLiveData.postValue(it.message.toString())
}
}
fun logIn(email: String, password: String) = runIO {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
loginSuccess.postValue(true)
} else {
errorLiveData.postValue("Invalid email or password")
loginSuccess.postValue(false)
}
}
}
fun signUp(
name: String,
email: String,
password: String,
onSignedUp: (FirebaseUser) -> Unit,
) = runIO {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val user = auth.currentUser
val userProfile = User(name, email, password)
val userDB = FirebaseFirestore.getInstance()
user?.let {
userDB.collection("Users")
.document(it.uid)
.set(userProfile)
.addOnSuccessListener {
Timber.tag("AuthViewModel")
.d("User profile is successfully created for user %s", user)
onSignedUp(user)
registerStatus.postValue(true)
}
.addOnFailureListener { exception ->
Timber.tag("AuthViewModel")
.e("Failed to create user profile: %s", exception.message)
errorLiveData.postValue("Failed to create user profile: ${exception.message}")
}
} ?: run {
errorLiveData.postValue("User is null after creation")
}
} else {
Timber.tag("AuthViewModel").e("Sign up failed: %s", task.exception?.message)
errorLiveData.postValue("Sign up failed: ${task.exception?.message}")
}
}
}
}
| 13
|
Kotlin
|
3
| 28
|
e44b61c21e67ccce684882a54be87e0977f207c8
| 3,240
|
android
|
MIT License
|
cinescout/tvshows/domain/src/commonMain/kotlin/cinescout/tvshows/domain/model/TvShowWithDetails.kt
|
4face-studi0
| 280,630,732
| false
| null |
package cinescout.tvshows.domain.model
import cinescout.common.model.Genre
data class TvShowWithDetails(
val tvShow: TvShow,
val genres: List<Genre>
)
| 19
|
Kotlin
|
2
| 3
|
d64398507d60a20a445db1451bdd8be23d65c9aa
| 161
|
CineScout
|
Apache License 2.0
|
app/src/main/java/com/jskako/githubrepobrowser/domain/splash/KeepSplashAlive.kt
|
jskako
| 546,837,084
| false
| null |
package com.jskako.githubrepobrowser.domain.splash
import androidx.core.splashscreen.SplashScreen
import com.jskako.githubrepobrowser.domain.util.delay
class KeepSplashAlive(private val splashScreen: SplashScreen) {
private var splashScreenAlive = true
fun init(splashScreenDuration: Long = 2000L) {
// Keep SplashScreen alive until keep equals true
splashScreen.setKeepOnScreenCondition { splashScreenAlive }
delay(splashScreenDuration) {
splashScreenAlive = false
}
}
}
| 0
|
Kotlin
|
0
| 0
|
966de10bd68ef3b8b51b49fc9143bd27199c5d9a
| 533
|
GithubRepoBrowser
|
Apache License 2.0
|
core/src/main/kotlin/no/nav/poao_tilgang/core/policy/impl/NavAnsattTilgangTilSkjermetPersonPolicyImpl.kt
|
navikt
| 491,417,288
| false
| null |
package no.nav.poao_tilgang.core.policy.impl
import no.nav.poao_tilgang.core.domain.Decision
import no.nav.poao_tilgang.core.policy.NavAnsattBehandleSkjermedePersonerPolicy
import no.nav.poao_tilgang.core.policy.NavAnsattTilgangTilSkjermetPersonPolicy
import no.nav.poao_tilgang.core.provider.SkjermetPersonProvider
class NavAnsattTilgangTilSkjermetPersonPolicyImpl(
private val skjermetPersonProvider: SkjermetPersonProvider,
private val navAnsattBehandleSkjermedePersonerPolicy: NavAnsattBehandleSkjermedePersonerPolicy
) : NavAnsattTilgangTilSkjermetPersonPolicy {
override val name = "NavAnsattTilgangTilSkjermetPerson"
override fun evaluate(input: NavAnsattTilgangTilSkjermetPersonPolicy.Input): Decision {
val erSkjermet = skjermetPersonProvider.erSkjermetPerson(input.norskIdent)
if (erSkjermet) {
return navAnsattBehandleSkjermedePersonerPolicy.evaluate(
NavAnsattBehandleSkjermedePersonerPolicy.Input(input.navAnsattAzureId)
)
}
return Decision.Permit
}
}
| 2
|
Kotlin
|
2
| 1
|
71f15ca9c2c489aca0f22dbdbd352dd74d6fbc89
| 995
|
poao-tilgang
|
MIT License
|
kotlin/src/katas/kotlin/graph/Traversal4.kt
|
dkandalov
| 2,517,870
| false
|
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
|
package katas.kotlin.graph
import katas.kotlin.graph.Graph.Node
import nonstdlib.join
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.collections.LinkedHashSet
class Traversal4 {
@Test fun `depth-first traversal`() {
"[a]".toGraph().let {
it.dft("a") shouldEqual "a"
it.dft("x") shouldEqual ""
}
"[a-b]".toGraph().let {
it.dft("a") shouldEqual "a-b"
it.dft("b") shouldEqual "b-a"
it.dft("x") shouldEqual ""
}
"[a-b, b-c]".toGraph().let {
it.dft("a") shouldEqual "a-b-c"
it.dft("b") shouldEqual "b-a-c"
it.dft("c") shouldEqual "c-b-a"
it.dft("x") shouldEqual ""
}
// aโโb1โโc
// โโโb2โโโ
"[a-b1, a-b2, b1-c, b2-c]".toGraph().let {
it.dft("a") shouldEqual "a-b1-c-b2"
it.dft("b1") shouldEqual "b1-a-b2-c"
it.dft("b2") shouldEqual "b2-a-b1-c"
it.dft("c") shouldEqual "c-b1-a-b2"
}
}
@Test fun `breadth-first traversal`() {
"[a]".toGraph().let {
it.bft("a") shouldEqual "a"
it.bft("x") shouldEqual ""
}
"[a-b]".toGraph().let {
it.bft("a") shouldEqual "a-b"
it.bft("b") shouldEqual "b-a"
it.bft("x") shouldEqual ""
}
"[a-b, b-c]".toGraph().let {
it.bft("a") shouldEqual "a-b-c"
it.bft("b") shouldEqual "b-a-c"
it.bft("c") shouldEqual "c-b-a"
it.bft("x") shouldEqual ""
}
// aโโb1โโc
// โโโb2โโโ
"[a-b1, a-b2, b1-c, b2-c]".toGraph().let {
it.bft("a") shouldEqual "a-b1-b2-c"
it.bft("b1") shouldEqual "b1-a-c-b2"
it.bft("b2") shouldEqual "b2-a-c-b1"
it.bft("c") shouldEqual "c-b1-b2-a"
}
}
private data class Result<T>(val path: LinkedHashSet<T>) {
operator fun plus(value: T) = Result(LinkedHashSet(path + value))
fun contains(value: T) = path.contains(value)
companion object {
fun <T> empty(): Result<T> = Result(LinkedHashSet())
}
}
private interface Container<T> {
fun add(value: T)
fun add(values: Collection<T>)
fun remove(): T
fun isNotEmpty(): Boolean
companion object {
fun <T> queue() = object: Container<T> {
val list = LinkedList<T>()
override fun add(value: T) = list.addFirst(value)
override fun add(values: Collection<T>) { list.addAll(values) }
override fun remove() = list.removeFirst()
override fun isNotEmpty() = list.isNotEmpty()
}
fun <T> stack() = object: Container<T> {
val list = LinkedList<T>()
override fun add(value: T) = list.addLast(value)
override fun add(values: Collection<T>) { list.addAll(values.reversed()) }
override fun remove() = list.removeLast()
override fun isNotEmpty() = list.isNotEmpty()
}
}
}
private fun <Value, Label> Graph<Value, Label>.bft(value: Value, separator: String = "-"): String {
val node = nodes[value] ?: return ""
return node.traverse(Container.queue()).path.join(separator)
}
private fun <Value, Label> Graph<Value, Label>.dft(value: Value, separator: String = "-"): String {
val node = nodes[value] ?: return ""
return node.traverse(Container.stack()).path.join(separator)
}
private fun <Value, Label> Node<Value, Label>.traverse(container: Container<Node<Value, Label>>): Result<Value> {
var result = Result.empty<Value>()
container.add(this)
while (container.isNotEmpty()) {
val node = container.remove()
if (!result.contains(node.value)) {
result += node.value
container.add(node.neighbors())
}
}
return result
}
}
| 7
|
Roff
|
3
| 5
|
0f169804fae2984b1a78fc25da2d7157a8c7a7be
| 4,087
|
katas
|
The Unlicense
|
inference/inference-core/src/commonMain/kotlin/io/kinference.core/operators/layer/recurrent/gru/GRUData.kt
|
JetBrains-Research
| 244,400,016
| false
| null |
package io.kinference.core.operators.layer.recurrent.gru
import io.kinference.graph.asCoroutineContext
import io.kinference.model.ExecutionContext
import io.kinference.ndarray.arrays.*
import io.kinference.ndarray.extensions.allocateNDArray
import io.kinference.primitives.types.DataType
class GRUDefaultGate(private val weights: NumberNDArray, private val recurrentWeights: NumberNDArray, private val bias: NumberNDArray?, batchSize: Int, hiddenSize: Int, dataType: DataType) {
private val gateData = allocateNDArray(dataType, intArrayOf(batchSize, hiddenSize)) as MutableNumberNDArray
fun compute(
input: NumberNDArray,
hiddenState: GRUHiddenState,
activationFunction: PrimitiveToPrimitiveFunction,
numDirection: Int,
batchNum: Int,
executionContext: ExecutionContext? = null
) {
val gateLocal = gateData.viewMutable(batchNum)
gateLocal.clean()
input.dot(weights, gateLocal, executionContext.asCoroutineContext())
hiddenState.getVector(numDirection, batchNum).dot(recurrentWeights, gateLocal, executionContext.asCoroutineContext())
if (bias != null) gateLocal.plusAssign(bias)
gateLocal.mapMutable(activationFunction)
}
fun getVector(batchNum: Int) = gateData.view(batchNum)
}
class GRUHiddenGate(private val weights: NumberNDArray, private val recurrentWeights: NumberNDArray, wBias: NumberNDArray?, rBias: NumberNDArray?, batchSize: Int, hiddenSize: Int, dataType: DataType, private val linearBeforeReset: Boolean) {
private val bias: NumberNDArray?
private val weightsBias: NumberNDArray?
private val recurrentBias: NumberNDArray?
init {
if (linearBeforeReset) {
bias = null
weightsBias = wBias
recurrentBias = rBias
} else {
bias = when {
wBias != null && rBias != null -> wBias.plus(rBias)
wBias != null -> wBias
rBias != null -> rBias
else -> null
}
weightsBias = null
recurrentBias = null
}
}
private val gateData = allocateNDArray(dataType, intArrayOf(batchSize, hiddenSize)) as MutableNumberNDArray
private val tempData = allocateNDArray(dataType, intArrayOf(batchSize, hiddenSize)) as MutableNumberNDArray
fun compute(
input: NumberNDArray,
hiddenState: GRUHiddenState,
gates: GRUGates,
activationFunction: PrimitiveToPrimitiveFunction,
numDirection: Int,
batchNum: Int,
executionContext: ExecutionContext? = null
) =
if (linearBeforeReset)
computeWithReset(input, hiddenState, gates, activationFunction, numDirection, batchNum, executionContext)
else
computeDefault(input, hiddenState, gates, activationFunction, numDirection, batchNum, executionContext)
private fun computeDefault(
input: NumberNDArray,
hiddenState: GRUHiddenState,
gates: GRUGates,
activationFunction: PrimitiveToPrimitiveFunction,
numDirection: Int,
batchNum: Int,
executionContext: ExecutionContext? = null
) {
val gateLocal = gateData.viewMutable(batchNum)
val tempLocal = tempData.viewMutable(batchNum)
gateLocal.clean()
input.dot(weights, gateLocal, executionContext.asCoroutineContext())
gates.reset.getVector(batchNum).times(hiddenState.getVector(numDirection, batchNum), tempLocal)
tempLocal.dot(recurrentWeights, gateLocal, executionContext.asCoroutineContext())
if (bias != null) gateLocal.plusAssign(bias)
gateLocal.mapMutable(activationFunction)
}
private fun computeWithReset(
input: NumberNDArray,
hiddenState: GRUHiddenState,
gates: GRUGates,
activationFunction: PrimitiveToPrimitiveFunction,
numDirection: Int,
batchNum: Int,
executionContext: ExecutionContext? = null
) {
val gateLocal = gateData.viewMutable(batchNum)
gateLocal.clean()
hiddenState.getVector(numDirection, batchNum).dot(recurrentWeights, gateLocal, executionContext.asCoroutineContext())
if (recurrentBias != null) gateLocal.plusAssign(recurrentBias)
gateLocal.timesAssign(gates.reset.getVector(batchNum))
input.dot(weights, gateLocal, executionContext.asCoroutineContext())
if (weightsBias != null) gateLocal.plusAssign(weightsBias)
gateLocal.mapMutable(activationFunction)
}
fun getVector(batchNum: Int) = gateData.view(batchNum)
}
data class GRUGates(val update: GRUDefaultGate, val reset: GRUDefaultGate, val hidden: GRUHiddenGate) {
companion object {
fun create(weights: NumberNDArray, recurrentWeights: NumberNDArray, bias: NumberNDArray?, batchSize: Int, hiddenSize: Int, dataType: DataType, linearBeforeReset: Boolean): GRUGates {
val updateGate = GRUDefaultGate(
weights.view(0),
recurrentWeights.view(0),
bias?.view(0)?.plus(bias.view(3)),
batchSize, hiddenSize, dataType
)
val resetGate = GRUDefaultGate(
weights.view(1),
recurrentWeights.view(1),
bias?.view(1)?.plus(bias.view(4)),
batchSize, hiddenSize, dataType
)
val hiddenGate = GRUHiddenGate(
weights.view(2),
recurrentWeights.view(2),
bias?.view(2),
bias?.view(5),
batchSize, hiddenSize, dataType, linearBeforeReset
)
return GRUGates(updateGate, resetGate, hiddenGate)
}
}
}
class GRUHiddenState(initHiddenState: NumberNDArray?, private val dataType: DataType, numDirection: Int, batchSize: Int, hiddenSize: Int) {
private val stateData = initHiddenState?.toMutable() ?: allocateNDArray(dataType, intArrayOf(numDirection, batchSize, hiddenSize)) as MutableNumberNDArray
private val tempData = allocateNDArray(dataType, intArrayOf(numDirection, batchSize, hiddenSize)) as MutableNumberNDArray
val data: NumberNDArray
get() = stateData
fun compute(gates: GRUGates, numDirection: Int, batchNum: Int) {
val stateLocal = stateData.viewMutable(numDirection, batchNum)
val tempLocal = tempData.viewMutable(numDirection, batchNum)
stateLocal.timesAssign(gates.update.getVector(batchNum))
when (dataType) {
DataType.DOUBLE -> gates.update.getVector(batchNum).map(DoubleResetMap, tempLocal)
DataType.FLOAT -> gates.update.getVector(batchNum).map(FloatResetMap, tempLocal)
else -> error("Unsupported type: $dataType")
}
tempLocal.timesAssign(gates.hidden.getVector(batchNum))
stateLocal.plusAssign(tempLocal)
}
companion object {
private object FloatResetMap : FloatMap {
override fun apply(value: Float): Float {
return 1f - value
}
}
private object DoubleResetMap : DoubleMap {
override fun apply(value: Double): Double {
return 1.0 - value
}
}
}
fun getVector(numDirection: Int, batchNum: Int) = stateData.view(numDirection, batchNum)
}
| 2
|
Kotlin
|
5
| 74
|
5cd3ac9c79f3f1ebb9ec5c83adb706dc8325a852
| 7,342
|
kinference
|
Apache License 2.0
|
ui/src/main/java/com/pyamsoft/tetherfi/ui/LinkText.kt
|
pyamsoft
| 475,225,784
| false
| null |
/*
* Copyright 2023 pyamsoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.tetherfi.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
private inline fun AnnotatedString.Builder.withStringAnnotation(
tag: String,
annotation: String,
content: () -> Unit
) {
pushStringAnnotation(
tag = tag,
annotation = annotation,
)
content()
pop()
}
fun AnnotatedString.Builder.appendLink(
tag: String,
linkColor: Color,
text: String,
url: String,
) {
withStringAnnotation(
tag = tag,
annotation = url,
) {
withStyle(
style =
SpanStyle(
textDecoration = TextDecoration.Underline,
color = linkColor,
),
) {
append(text)
}
}
}
| 6
| null |
7
| 271
|
6219fc584e0e5700bd49241b65ee75023a1eb137
| 1,479
|
tetherfi
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.