path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/gggames/hourglass/features/video/VideoModule.kt | giladgotman | 252,945,764 | false | null | package com.gggames.hourglass.features.video
import android.content.Context
import com.gggames.hourglass.core.di.AppContext
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.SimpleExoPlayer
import dagger.Module
import dagger.Provides
@Module
class VideoModule {
@Provides
fun provideVideoPlayer(player: ExoVideoPlayer): VideoPlayer = player
@Provides
fun provideExoSimplePlayer(@AppContext context: Context): SimpleExoPlayer = ExoPlayerFactory.newSimpleInstance(context)
}
| 25 | Kotlin | 0 | 0 | 0f0fa11fbe1131387148e4d6d1b7d85c23d6e5f0 | 534 | celebs | MIT License |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/route53/ZoneDelegationOptions.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.route53
import io.cloudshiftdev.awscdk.Duration
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.String
import kotlin.Unit
/**
* Options available when creating a delegation relationship from one PublicHostedZone to another.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.*;
* import io.cloudshiftdev.awscdk.services.route53.*;
* ZoneDelegationOptions zoneDelegationOptions = ZoneDelegationOptions.builder()
* .comment("comment")
* .ttl(Duration.minutes(30))
* .build();
* ```
*/
public interface ZoneDelegationOptions {
/**
* A comment to add on the DNS record created to incorporate the delegation.
*
* Default: none
*/
public fun comment(): String? = unwrap(this).getComment()
/**
* The TTL (Time To Live) of the DNS delegation record in DNS caches.
*
* Default: 172800
*/
public fun ttl(): Duration? = unwrap(this).getTtl()?.let(Duration::wrap)
/**
* A builder for [ZoneDelegationOptions]
*/
@CdkDslMarker
public interface Builder {
/**
* @param comment A comment to add on the DNS record created to incorporate the delegation.
*/
public fun comment(comment: String)
/**
* @param ttl The TTL (Time To Live) of the DNS delegation record in DNS caches.
*/
public fun ttl(ttl: Duration)
}
private class BuilderImpl : Builder {
private val cdkBuilder: software.amazon.awscdk.services.route53.ZoneDelegationOptions.Builder =
software.amazon.awscdk.services.route53.ZoneDelegationOptions.builder()
/**
* @param comment A comment to add on the DNS record created to incorporate the delegation.
*/
override fun comment(comment: String) {
cdkBuilder.comment(comment)
}
/**
* @param ttl The TTL (Time To Live) of the DNS delegation record in DNS caches.
*/
override fun ttl(ttl: Duration) {
cdkBuilder.ttl(ttl.let(Duration.Companion::unwrap))
}
public fun build(): software.amazon.awscdk.services.route53.ZoneDelegationOptions =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.route53.ZoneDelegationOptions,
) : CdkObject(cdkObject),
ZoneDelegationOptions {
/**
* A comment to add on the DNS record created to incorporate the delegation.
*
* Default: none
*/
override fun comment(): String? = unwrap(this).getComment()
/**
* The TTL (Time To Live) of the DNS delegation record in DNS caches.
*
* Default: 172800
*/
override fun ttl(): Duration? = unwrap(this).getTtl()?.let(Duration::wrap)
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): ZoneDelegationOptions {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.route53.ZoneDelegationOptions):
ZoneDelegationOptions = CdkObjectWrappers.wrap(cdkObject) as? ZoneDelegationOptions ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: ZoneDelegationOptions):
software.amazon.awscdk.services.route53.ZoneDelegationOptions = (wrapped as
CdkObject).cdkObject as software.amazon.awscdk.services.route53.ZoneDelegationOptions
}
}
| 1 | Kotlin | 0 | 4 | 7a060aa8b6779ab04dc9881993d9598e11d278b1 | 3,734 | kotlin-cdk-wrapper | Apache License 2.0 |
common/sdk/settings/impl/src/androidMain/kotlin/io/chefbook/sdk/settings/impl/data/platform/IconSwitcherImpl.kt | mephistolie | 379,951,682 | false | {"Kotlin": 1334117, "Ruby": 16819, "Swift": 352} | package io.chefbook.sdk.settings.impl.data.platform
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import io.chefbook.sdk.settings.api.external.domain.entities.AppIcon
internal class IconSwitcherImpl(
private val context: Context,
) : IconSwitcher {
private val packageManager = context.packageManager
override fun switchIconVisibility(icon: AppIcon, isEnabled: Boolean) =
setComponent(classname = "$APP_ID.$icon", isEnabled = isEnabled)
private fun setComponent(
classname: String,
isEnabled: Boolean,
) {
packageManager.setComponentEnabledSetting(
ComponentName(context, classname),
if (isEnabled) {
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
} else {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
},
PackageManager.DONT_KILL_APP
)
}
companion object {
private const val APP_ID = "io.chefbook"
}
} | 0 | Kotlin | 0 | 12 | ddaf82ee3142f30aee8920d226a8f07873cdcffe | 959 | chefbook-mobile | Apache License 2.0 |
kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/component/Components.kt | bkbnio | 356,919,425 | false | null | package io.bkbn.kompendium.oas.component
import io.bkbn.kompendium.oas.security.SecuritySchema
import kotlinx.serialization.Serializable
@Serializable
data class Components(
val securitySchemes: MutableMap<String, SecuritySchema> = mutableMapOf()
)
| 8 | Kotlin | 7 | 33 | ae2a1b578a66d7c805a2fcd37878c482faa11f55 | 253 | kompendium | MIT License |
app/src/main/java/com/byteteam/bluesense/core/presentation/views/store/water_supplier/WaterSupplierScreen.kt | BlueSense-by-ByteTeam | 738,355,445 | false | {"Kotlin": 412626} | package com.byteteam.bluesense.core.presentation.views.store.water_supplier
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.byteteam.bluesense.core.data.common.Resource
import com.byteteam.bluesense.core.domain.model.WaterSupplierEntity
import com.byteteam.bluesense.core.presentation.widgets.ErrorHandler
import com.byteteam.bluesense.ui.theme.BlueSenseTheme
import kotlinx.coroutines.flow.StateFlow
@Composable
fun WaterSupplierScreen(
waterSuppliersState: StateFlow<Resource<List<WaterSupplierEntity>>>,
getWaterSupplier: () -> Unit,
) {
var fetchingWaterSupplier by remember { mutableStateOf(false) }
fun fetchOnceWaterSupplier() {
if (fetchingWaterSupplier) {
fetchingWaterSupplier = false
getWaterSupplier()
}
}
waterSuppliersState.collectAsState().value.let {
when (it) {
is Resource.Success -> {
fetchingWaterSupplier = false
LazyColumn(
modifier = androidx.compose.ui.Modifier
.padding(horizontal = 24.dp)
) {
if(it.data != null && it.data.isEmpty()){
item {
Text(text = "Belum ada data supplier air")
}
}
items(it.data ?: listOf()) { item ->
SupplierItem(item)
}
}
}
is Resource.Loading -> {
fetchingWaterSupplier = true
fetchOnceWaterSupplier()
Row {
Text(text = "Memuat data supplier air...")
CircularProgressIndicator()
}
}
is Resource.Error -> {
fetchingWaterSupplier = false
ErrorHandler(
onPressRetry = { fetchOnceWaterSupplier() },
errorText = it.message ?: "Error mengambil data supplier air"
)
}
}
}
}
@Preview
@Composable
private fun WaterSupplierScreenPreview() {
BlueSenseTheme {
Surface {
// WaterSupplierScreen()
}
}
} | 0 | Kotlin | 0 | 1 | 6efb7dfb300f9acaa07bb77f973907de57d490b7 | 2,860 | bluesense-android | Apache License 2.0 |
app/src/main/java/io/github/wulkanowy/data/mappers/MobileDeviceMapper.kt | wezuwiusz | 827,505,734 | false | {"Kotlin": 1759089, "HTML": 1949, "Shell": 257} | package io.github.wulkanowy.data.mappers
import io.github.wulkanowy.data.db.entities.MobileDevice
import io.github.wulkanowy.data.db.entities.Student
import io.github.wulkanowy.data.pojos.MobileDeviceToken
import io.github.wulkanowy.sdk.pojo.Device as SdkDevice
import io.github.wulkanowy.sdk.pojo.Token as SdkToken
fun List<SdkDevice>.mapToEntities(student: Student) = map {
MobileDevice(
userLoginId = student.userLoginId,
date = it.createDateZoned.toInstant(),
deviceId = it.id,
name = it.name
)
}
fun SdkToken.mapToMobileDeviceToken() = MobileDeviceToken(
token = token,
symbol = symbol,
pin = pin,
qr = qrCodeImage
)
| 98 | Kotlin | 6 | 28 | 82b4ea930e64d0d6e653fb9024201b372cdb5df2 | 681 | neowulkanowy | Apache License 2.0 |
app/src/main/java/com/dagan/lior/crypto_currency_market_price/login/presenter/LoginPresenter.kt | liorliord | 204,151,353 | false | null | package com.dagan.lior.crypto_currency_market_price.login.presenter
import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.annotation.NonNull
import com.google.firebase.auth.FirebaseUser
import com.dagan.lior.crypto_currency_market_price.bitcoinpricemainscreen.view.CryptoPriceActivity
import com.dagan.lior.crypto_currency_market_price.login.model.FirebaseInteractor
import com.dagan.lior.crypto_currency_market_price.login.view.LoginView
class LoginPresenter(
private var loginView: LoginView?,
private val context: Context,
private val firebaseInteractor: FirebaseInteractor
) : FirebaseInteractor.OnFinishListener {
fun signInButtonClicked(email: String, password: String) {
if (email.isEmpty() || password.isEmpty()) {
loginView?.showToast("Please fill in both e-mail & password", Toast.LENGTH_SHORT)
} else {
loginView?.clearPassword()
loginView?.showLoginProgress()
firebaseInteractor.processEmailAndPasswordInput(this, email, password)
}
}
override fun onSignInSuccess(currentUser: FirebaseUser?) {
loginView?.hideLoginProgress()
val intent = Intent(context, CryptoPriceActivity::class.java)
intent.putExtra("currentUser", currentUser?.uid.toString())
context.startActivity(intent)
loginView?.endActivity()
}
override fun onSignInFailed(error: String) {
loginView?.hideLoginProgress()
loginView?.showToast(error, Toast.LENGTH_SHORT)
}
fun onDestroy() {
loginView = null
}
}
| 0 | Kotlin | 0 | 0 | f8552525bc0cad3f8da9cf49613a9f49723dfb83 | 1,620 | crypto-currency-price | MIT License |
libkunits/src/test/kotlin/com/github/dlind1974/kunits/json/jackson/SpeedSerializerTest.kt | dlind1974 | 596,461,467 | false | {"Kotlin": 55827} | package com.github.dlind1974.kunits.json.jackson
import com.github.dlind1974.kunits.Speed
import com.github.dlind1974.kunits.meterPerSecond
import com.fasterxml.jackson.core.Version
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import kotlin.test.Test
import kotlin.test.assertEquals
class SpeedSerializerTest {
@Test
fun serialize_WhenSpeedIsMeterPerSecond_ProducedJsonIsInMeterPerSecond() {
val speedSerializer = SpeedSerializer(Speed::class.java)
val objectMapper = ObjectMapper()
val module = SimpleModule("SpeedSerializer", Version(1, 0, 0, null, null, null))
module.addSerializer(Speed::class.java, speedSerializer)
objectMapper.registerModule(module)
val speed = 12.7.meterPerSecond
val speedJson: String = objectMapper.writeValueAsString(speed)
val expectedSpeedJson = "{\"amount\":12.7,\"unit\":\"m/s\"}"
assertEquals(speedJson, expectedSpeedJson)
}
} | 0 | Kotlin | 0 | 0 | f55daeae01a11824b5841b8d070eaa195bcff003 | 1,012 | kunits | MIT License |
qr-code-app/src/main/kotlin/io/github/simonscholz/observables/JSpinnerIntObservable.kt | SimonScholz | 698,277,784 | false | {"Kotlin": 255097, "Java": 27034, "Shell": 1098} | package io.github.simonscholz.observables
import org.eclipse.core.databinding.observable.Diffs
import org.eclipse.core.databinding.observable.value.AbstractObservableValue
import javax.swing.JSpinner
class JSpinnerIntObservable(
private val jSpinner: JSpinner,
) : AbstractObservableValue<Int>() {
private var value: Int = jSpinner.value as Int
init {
jSpinner.addChangeListener {
val oldValue = value
value = doGetValue()
fireValueChange(Diffs.createValueDiff(oldValue, value))
}
}
override fun doGetValue(): Int = jSpinner.value as Int
override fun getValueType(): Any = Int::class.java
override fun doSetValue(value: Int?) {
jSpinner.value = value
}
}
| 3 | Kotlin | 1 | 9 | 9df3e851e1395d6678243260d0e850845f2c65f0 | 753 | qr-code-with-logo | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-api/src/main/kotlin/org/jetbrains/kotlin/gradle/dsl/KotlinJvmOptions.kt | JetBrains | 3,432,266 | false | null | // DO NOT EDIT MANUALLY!
// Generated by org/jetbrains/kotlin/generators/arguments/GenerateGradleOptions.kt
package org.jetbrains.kotlin.gradle.dsl
interface KotlinJvmOptions : org.jetbrains.kotlin.gradle.dsl.KotlinCommonOptions {
/**
* Include Kotlin runtime into the resulting JAR
* Default value: false
*/
var includeRuntime: kotlin.Boolean
/**
* Generate metadata for Java 1.8 reflection on method parameters
* Default value: false
*/
var javaParameters: kotlin.Boolean
/**
* Include a custom JDK from the specified location into the classpath instead of the default JAVA_HOME
* Default value: null
*/
var jdkHome: kotlin.String?
/**
* Target version of the generated JVM bytecode (1.6, 1.8, 9, 10, 11, 12 or 13), default is 1.6
* Possible values: "1.6", "1.8", "9", "10", "11", "12", "13"
* Default value: "1.6"
*/
var jvmTarget: kotlin.String
/**
* Don't automatically include the Java runtime into the classpath
* Default value: false
*/
var noJdk: kotlin.Boolean
/**
* Don't automatically include Kotlin reflection into the classpath
* Default value: true
*/
var noReflect: kotlin.Boolean
/**
* Don't automatically include the Kotlin/JVM stdlib and Kotlin reflection into the classpath
* Default value: true
*/
var noStdlib: kotlin.Boolean
/**
* Use the IR backend
* Default value: false
*/
var useIR: kotlin.Boolean
}
| 135 | null | 4980 | 40,442 | 817f9f13b71d4957d8eaa734de2ac8369ad64770 | 1,534 | kotlin | Apache License 2.0 |
src/main/kotlin/no/nav/hm/grunndata/register/event/EventItemRepository.kt | navikt | 572,421,718 | false | {"Kotlin": 244973, "Dockerfile": 136, "Shell": 111} | package no.nav.hm.grunndata.register.event
import io.micronaut.data.jdbc.annotation.JdbcRepository
import io.micronaut.data.model.query.builder.sql.Dialect
import io.micronaut.data.repository.kotlin.CoroutineCrudRepository
import java.time.LocalDateTime
import java.util.*
@JdbcRepository(dialect = Dialect.POSTGRES)
interface EventItemRepository:CoroutineCrudRepository<EventItem, UUID> {
suspend fun findByStatus(status: EventItemStatus): List<EventItem>
suspend fun deleteByStatusAndUpdatedBefore(status: EventItemStatus, updated: LocalDateTime): Int
} | 1 | Kotlin | 0 | 3 | 233592b5877bdd5fb8a6a8684451f28b3cd74118 | 570 | hm-grunndata-register | MIT License |
physics/src/test/kotlin/balls/physics/scene/TestScene.kt | knokko | 865,591,691 | false | {"Kotlin": 294965, "GLSL": 302} | package balls.physics.scene
import balls.geometry.Rectangle
import balls.physics.entity.EntitySpawnRequest
import balls.physics.tile.TilePlaceRequest
import fixie.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import kotlin.time.Duration.Companion.seconds
class TestScene {
private fun assertEquals(expected: Displacement, actual: Displacement, maxError: Displacement) {
if (abs(expected - actual) > maxError) assertEquals(expected, actual)
}
private fun assertEquals(expected: Speed, actual: Speed, maxError: Speed) {
if (abs(expected - actual) > maxError) assertEquals(expected, actual)
}
@Test
fun testGravityAcceleration() {
val scene = Scene()
scene.spawnEntity(EntitySpawnRequest(10.m, 0.m, 123.m, radius = 1.m))
scene.update(1.seconds)
val query = SceneQuery()
scene.read(query, 9.m, -10.m, 120.m, 11.m, 0.m, 125.m)
assertEquals(1, query.entities.size)
val subject = query.entities[0]
assertEquals(10.m, subject.position.x)
assertEquals(-4.9.m, subject.position.y, 100.mm)
assertEquals(123.m, subject.position.z)
assertEquals(0.mps, subject.velocity.x)
assertEquals(-9.8.mps, subject.velocity.y, 0.1.mps)
assertEquals(0.mps, subject.velocity.z)
}
@Test
fun testFallOnFlatFloor() {
val scene = Scene()
scene.spawnEntity(EntitySpawnRequest(x = 1.m, y = 2.m, z = 3.m, radius = 100.mm))
scene.addTile(TilePlaceRequest(collider = Rectangle(
startX = 500.mm, startY = 1.m, startZ = 2.m,
lengthX1 = 1.m, lengthY1 = 0.m, lengthZ1 = 0.m,
lengthX2 = 0.m, lengthY2 = 0.m, lengthZ2 = 1.5.m
)))
scene.update(10.seconds)
val query = SceneQuery()
scene.read(query, 0.m, 0.m, 0.m, 5.m, 5.m, 5.m)
assertEquals(1, query.entities.size)
val entity = query.entities[0]
assertEquals(1.m, entity.position.x, 1.mm)
assertEquals(1.1.m, entity.position.y, 5.mm)
assertEquals(1.m, entity.position.z, 3.m)
assertEquals(0.mps, entity.velocity.x, 0.01.mps)
assertEquals(0.mps, entity.velocity.y, 0.1.mps)
assertEquals(0.mps, entity.velocity.z, 0.01.mps)
}
@Test
fun testRollToLowestPoint() {
val scene = Scene()
scene.addTile(TilePlaceRequest(collider = Rectangle(
startX = -10.m, startY = -10.m, startZ = 0.m,
lengthX1 = 20.m, lengthY1 = 0.m, lengthZ1 = 0.m,
lengthX2 = 0.m, lengthY2 = 1.m, lengthZ2 = 10.m
)))
scene.addTile(TilePlaceRequest(collider = Rectangle(
startX = -10.m, startY = -10.m, startZ = 0.m,
lengthX1 = 20.m, lengthY1 = 0.m, lengthZ1 = 0.m,
lengthX2 = 0.m, lengthY2 = 1.m, lengthZ2 = -10.m
)))
scene.addTile(TilePlaceRequest(collider = Rectangle(
startX = 0.m, startY = -10.m, startZ = -10.m,
lengthX1 = 0.m, lengthY1 = 0.m, lengthZ1 = 20.m,
lengthX2 = 10.m, lengthY2 = 1.m, lengthZ2 = 0.m
)))
scene.addTile(TilePlaceRequest(collider = Rectangle(
startX = 0.m, startY = -10.m, startZ = -10.m,
lengthX1 = 0.m, lengthY1 = 0.m, lengthZ1 = 20.m,
lengthX2 = -10.m, lengthY2 = 1.m, lengthZ2 = 0.m
)))
scene.spawnEntity(EntitySpawnRequest(
x = -5.m, y = -5.m, z = -5.m, radius = 200.mm
))
scene.update(60.seconds)
val query = SceneQuery()
scene.read(query, -10.m, -100.m, -10.m, 10.m, 100.m, 10.m)
assertEquals(1, query.entities.size)
val entity = query.entities[0]
assertEquals(0.m, entity.position.x, 10.mm)
assertEquals(-9.8.m, entity.position.y, 10.mm)
assertEquals(0.m, entity.position.z, 10.mm)
assertEquals(0.mps, entity.velocity.x, 0.1.mps)
assertEquals(0.mps, entity.velocity.y, 0.2.mps)
assertEquals(0.mps, entity.velocity.z, 0.1.mps)
}
}
| 0 | Kotlin | 0 | 0 | 16c28af4aacc0485a4b70d93e2b5eae485c55af7 | 3,566 | balls-of-steel | MIT License |
content-types/content-types-ports-input/src/main/kotlin/org/orkg/contenttypes/input/compat.kt | TIBHannover | 197,416,205 | false | {"Kotlin": 5694631, "Cypher": 219418, "Python": 4881, "Shell": 2767, "Groovy": 1936, "HTML": 240, "Batchfile": 82} | package org.orkg.contenttypes.input
interface PaperUseCases : RetrievePaperUseCase, CreatePaperUseCase, CreateContributionUseCase, UpdatePaperUseCase, PublishPaperUseCase
interface ContributionUseCases : RetrieveContributionUseCase
interface ComparisonUseCases : RetrieveComparisonUseCase, CreateComparisonUseCase, UpdateComparisonUseCase, PublishComparisonUseCase
interface VisualizationUseCases : RetrieveVisualizationUseCase, CreateVisualizationUseCase
interface TemplateUseCases : RetrieveTemplateUseCase, CreateTemplateUseCase, CreateTemplatePropertyUseCase,
UpdateTemplateUseCase, UpdateTemplatePropertyUseCase
interface TemplateInstanceUseCases : RetrieveTemplateInstanceUseCase, UpdateTemplateInstanceUseCase
interface RosettaStoneTemplateUseCases : RetrieveRosettaStoneTemplateUseCase, CreateRosettaStoneTemplateUseCase,
UpdateRosettaStoneTemplateUseCase, DeleteRosettaStoneTemplateUseCase
interface RosettaStoneStatementUseCases : RetrieveRosettaStoneStatementUseCase, CreateRosettaStoneStatementUseCase,
UpdateRosettaStoneStatementUseCase, DeleteRosettaStoneStatementUseCase
interface LegacyPaperUseCases : LegacyRetrievePaperUseCase, LegacyCreatePaperUseCase
interface ResearchFieldHierarchyUseCases : RetrieveResearchFieldHierarchyUseCase
interface LiteratureListUseCases : RetrieveLiteratureListUseCase, CreateLiteratureListUseCase,
CreateLiteratureListSectionUseCase, UpdateLiteratureListUseCase, UpdateLiteratureListSectionUseCase,
DeleteLiteratureListSectionUseCase, PublishLiteratureListUseCase
interface SmartReviewUseCases : RetrieveSmartReviewUseCase, CreateSmartReviewUseCase, CreateSmartReviewSectionUseCase,
UpdateSmartReviewUseCase, UpdateSmartReviewSectionUseCase, DeleteSmartReviewSectionUseCase
interface ContentTypeUseCases : RetrieveContentTypeUseCase
| 0 | Kotlin | 0 | 4 | f820349e34bc98d9f7d500d34412c2c621584e1d | 1,819 | orkg-backend | MIT License |
profilers-ui/src/com/android/tools/profilers/cpu/capturedetails/CpuTraceTreeSorter.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2018 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.profilers.cpu.capturedetails
import com.android.tools.adtui.common.ColumnTreeBuilder.TreeSorter
import javax.swing.JTree
import javax.swing.SortOrder
class CpuTraceTreeSorter<T: Aggregate<T>>(private val tree: JTree,
private val model: CpuTreeModel<T>,
private var comparator: Comparator<CpuTreeNode<T>>) : TreeSorter<CpuTreeNode<*>> {
init {
sort(comparator as Comparator<CpuTreeNode<*>>, SortOrder.UNSORTED) //SortOrder Parameter is not used.
tree.invalidate()
}
override fun sort(comparator: Comparator<CpuTreeNode<*>>, order: SortOrder) {
this.comparator = compareBy { node: CpuTreeNode<*> -> node.base.isUnmatched }.then(comparator) as Comparator<CpuTreeNode<T>>
sort()
}
fun sort() {
val selectionPath = tree.selectionPath
model.sort(comparator)
tree.selectionPath = selectionPath
tree.scrollPathToVisible(selectionPath)
}
} | 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,608 | android | Apache License 2.0 |
src/main/kotlin/usecases/organization/UpdateOrganization.kt | ktapi | 562,243,352 | false | null | package usecases.organization
import entities.organization.Organization
import entities.organization.Organizations
import org.ktapi.entities.populateFrom
object UpdateOrganization {
data class UpdateOrganizationData(val name: String? = null)
fun update(orgId: Long, data: Map<String, Any>): Organization {
val org = Organizations.findById(orgId)!!
org.populateFrom(data, UpdateOrganizationData::class).validate().flushChanges()
return org
}
} | 0 | Kotlin | 0 | 0 | 1f2acc29779ed75c24c813f834548cc2ea84c980 | 481 | ktapi-base | The Unlicense |
core/logger/src/main/kotlin/com/onseok/marvelpedia/log/DebugTree.kt | onseok | 733,347,236 | false | {"Kotlin": 111071} | /*
* Copyright 2023 onseok
*
* 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.onseok.marvelpedia.log
import timber.log.Timber
class DebugTree : Logger.Tree {
private val delegate = Timber.DebugTree()
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
delegate.log(priority, tag, message, t)
}
}
| 4 | Kotlin | 17 | 2 | e2148252f5892a543f8661c1725b0f88539f0a79 | 872 | Marvelpedia | Apache License 2.0 |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/BorderCornerIos.kt | walter-juan | 868,046,028 | false | null | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.BorderCornerIos: ImageVector
get() {
if (_borderCornerIos != null) {
return _borderCornerIos!!
}
_borderCornerIos = Builder(name = "BorderCornerIos", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 20.0f)
curveToRelative(0.0f, -6.559f, 0.0f, -9.838f, 1.628f, -12.162f)
arcToRelative(9.0f, 9.0f, 0.0f, false, true, 2.21f, -2.21f)
curveToRelative(2.324f, -1.628f, 5.602f, -1.628f, 12.162f, -1.628f)
}
}
.build()
return _borderCornerIos!!
}
private var _borderCornerIos: ImageVector? = null
| 0 | null | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 1,623 | compose-icon-collections | MIT License |
packages/nativescript-masonkit/src-native/mason-android/masonkit/src/main/java/org/nativescript/mason/masonkit/Utils.kt | triniwiz | 571,762,944 | false | {"C++": 3133140, "HTML": 450165, "C": 393329, "TypeScript": 383656, "Rust": 346139, "Swift": 235919, "Objective-C": 214959, "Kotlin": 186138, "JavaScript": 104928, "Objective-C++": 42138, "Shell": 8247, "CMake": 7070, "Ruby": 3131, "SCSS": 2605, "Java": 1313, "Python": 1140} | package org.nativescript.mason.masonkit
import android.util.Log
val LengthPercentageZeroSize =
Size<LengthPercentage>(LengthPercentage.Zero, LengthPercentage.Zero)
val LengthPercentageAutoZeroSize =
Size<LengthPercentageAuto>(LengthPercentageAuto.Zero, LengthPercentageAuto.Zero)
val zeroSize = Size(0F, 0F)
val nanSize = Size(Float.NaN, Float.NaN)
val autoSize: Size<Dimension> = Size(Dimension.Auto, Dimension.Auto)
fun logArgs(vararg args: Any){
val builder = StringBuilder()
args.forEach {
builder.append("$it\n")
}
Log.d("Mason: Log", builder.toString())
}
val LengthPercentageZeroRect =
Rect<LengthPercentage>(
LengthPercentage.Zero,
LengthPercentage.Zero,
LengthPercentage.Zero,
LengthPercentage.Zero
)
val LengthPercentageAutoZeroRect =
Rect<LengthPercentageAuto>(
LengthPercentageAuto.Zero,
LengthPercentageAuto.Zero,
LengthPercentageAuto.Zero,
LengthPercentageAuto.Zero
)
| 2 | C++ | 3 | 10 | a522fd2e63adc37b86bf66e2908e75dc0371e18a | 948 | nativescript-mason | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/incentives/IncentivesDomainEventListener.kt | ministryofjustice | 445,140,246 | false | {"Kotlin": 1229627, "Mustache": 1803, "Dockerfile": 1118} | package uk.gov.justice.digital.hmpps.prisonertonomisupdate.incentives
import com.fasterxml.jackson.databind.ObjectMapper
import com.microsoft.applicationinsights.TelemetryClient
import io.awspring.cloud.sqs.annotation.SqsListener
import io.opentelemetry.api.trace.SpanKind
import io.opentelemetry.instrumentation.annotations.WithSpan
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.listeners.EventFeatureSwitch
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.DomainEventListener
import java.util.concurrent.CompletableFuture
@Service
class IncentivesDomainEventListener(
private val incentivesService: IncentivesService,
private val incentivesReferenceService: IncentivesReferenceService,
objectMapper: ObjectMapper,
eventFeatureSwitch: EventFeatureSwitch,
telemetryClient: TelemetryClient,
) : DomainEventListener(
service = incentivesService,
objectMapper = objectMapper,
eventFeatureSwitch = eventFeatureSwitch,
telemetryClient = telemetryClient,
) {
private companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
}
@SqsListener("incentive", factory = "hmppsQueueContainerFactoryProxy")
@WithSpan(value = "syscon-devs-hmpps_prisoner_to_nomis_incentive_queue", kind = SpanKind.SERVER)
fun onMessage(rawMessage: String): CompletableFuture<Void> = onDomainEvent(rawMessage) { eventType, message ->
when (eventType) {
"incentives.iep-review.inserted" -> incentivesService.createIncentive(message.fromJson())
"incentives.level.changed" -> incentivesReferenceService.globalIncentiveLevelChange(message.fromJson())
"incentives.levels.reordered" -> incentivesReferenceService.globalIncentiveLevelsReorder()
"incentives.prison-level.changed" -> incentivesReferenceService.prisonIncentiveLevelChange(message.fromJson()) // TODO
else -> log.info("Received a message I wasn't expecting: {}", eventType)
}
}
}
| 1 | Kotlin | 0 | 2 | cb523828b23bbf57983c5c99c67fee2821ef8a51 | 2,030 | hmpps-prisoner-to-nomis-update | MIT License |
app/src/main/java/com/bluetoothversion1/android/MainActivity.kt | feilongzaitian008 | 405,806,749 | false | null | package com.bluetoothversion1.android
import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ArrayAdapter
import android.widget.Toast
import com.bluetooth.bluetoothtest.Blueshow
import com.bluetooth.bluetoothtest.BlueshowAdapter
import kotlinx.android.synthetic.main.activity_main.*
import java.io.OutputStream
import com.tbruyelle.rxpermissions2.RxPermissions
class MainActivity : AppCompatActivity() {
lateinit var mReceiver: BluetoothReceiver
private var list: MutableList<Blueshow> = mutableListOf()
private var mBluetoothAdapter: BluetoothAdapter? = null
private var outStream: OutputStream? = null
private var btSocket: BluetoothSocket? = null
var bluetoothaddress:String?=null
var bluetoothSta: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
permissionsRequest()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.toolbar, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.blue -> Bluetooth_test()
R.id.button1 -> connectbluetooth()
}
return true
}
private fun Bluetooth_test() {
mBluetoothAdapter!!.startDiscovery()
}
private fun connectbluetooth(){
val intent = Intent(this, Main2Activity::class.java)
if(bluetoothaddress!=null)
{
intent.putExtra("extra_data1", bluetoothaddress)
}
startActivity(intent)
}
private fun permissionsRequest() {
val rxPermissions = RxPermissions(this)
rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe {
if (it) {
var intentFilter = IntentFilter()
intentFilter.addAction(BluetoothDevice.ACTION_FOUND)
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED) //绑定状态变化
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) //开始扫描
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) //扫描结束
mReceiver = BluetoothReceiver()
registerReceiver(mReceiver, intentFilter)
} else {
Toast.makeText(this, " 权限未开启", Toast.LENGTH_SHORT).show()
}
}
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
if (mBluetoothAdapter == null) {
Toast.makeText(this, " Device does not support Bluetooth", Toast.LENGTH_SHORT).show()
} else {
if (!mBluetoothAdapter!!.isEnabled) {
var intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(intent, 1)
}
}
}
inner class BluetoothReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND == action) {
// Get the BluetoothDevice object from the Intent
val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
if (device!!.name != null) { //过滤掉设备名称为null的设备
if (list.indexOf(Blueshow(device, device.name)) == -1) { //防止重复添加
list!!.add(Blueshow(device, device.name))
if(device.name=="HULICHUANG"){
bluetoothaddress=device.address
}
}
}
var adapter = BlueshowAdapter(this@MainActivity, R.layout.bluetooth_item, list)
listView1.adapter=adapter
listView1.setOnItemClickListener{_, _, position, _->
//手动配对,完成配对后重新扫描即可
val method = BluetoothDevice::class.java.getMethod("createBond")
val list1 = list[position]
method.invoke(list1.bluetoothId)
bluetoothaddress = list[position].bluetoothId.toString()
Toast.makeText(context, bluetoothaddress.toString(), Toast.LENGTH_SHORT).show()
bluetoothSta=2
}
}
}
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(mReceiver)
}
}
| 0 | Kotlin | 0 | 0 | 593d1a42a9e51b49a29e593e8fdc811a4d4dfd42 | 5,030 | bluetoothversion1 | Apache License 2.0 |
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/declarations/impl/IrVariableImpl.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* 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 org.jetbrains.kotlin.ir.declarations.impl
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.ir.declarations.IrDeclarationParent
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.declarations.MetadataSource
import org.jetbrains.kotlin.ir.expressions.IrConstructorCall
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.symbols.IrVariableSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrVariableSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.visitors.IrElementTransformer
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.SmartList
class IrVariableImpl(
override val startOffset: Int,
override val endOffset: Int,
override var origin: IrDeclarationOrigin,
override val symbol: IrVariableSymbol,
override val name: Name = symbol.descriptor.name,
override val type: IrType,
override val isVar: Boolean = symbol.descriptor.isVar,
override val isConst: Boolean = symbol.descriptor.isConst,
override val isLateinit: Boolean = symbol.descriptor.isLateInit
) : IrVariable {
private var _parent: IrDeclarationParent? = null
override var parent: IrDeclarationParent
get() = _parent
?: throw UninitializedPropertyAccessException("Parent not initialized: $this")
set(v) {
_parent = v
}
override var annotations: List<IrConstructorCall> = emptyList()
override val metadata: MetadataSource? get() = null
constructor(
startOffset: Int,
endOffset: Int,
origin: IrDeclarationOrigin,
symbol: IrVariableSymbol,
type: IrType
) : this(
startOffset, endOffset, origin, symbol,
symbol.descriptor.name, type,
isVar = symbol.descriptor.isVar,
isConst = symbol.descriptor.isConst,
isLateinit = symbol.descriptor.isLateInit
)
constructor(
startOffset: Int,
endOffset: Int,
origin: IrDeclarationOrigin,
descriptor: VariableDescriptor,
type: IrType
) : this(startOffset, endOffset, origin, IrVariableSymbolImpl(descriptor), type)
constructor(
startOffset: Int,
endOffset: Int,
origin: IrDeclarationOrigin,
descriptor: VariableDescriptor,
type: IrType,
initializer: IrExpression?
) : this(startOffset, endOffset, origin, descriptor, type) {
this.initializer = initializer
}
init {
symbol.bind(this)
}
override val descriptor: VariableDescriptor get() = symbol.descriptor
override var initializer: IrExpression? = null
override fun <R, D> accept(visitor: IrElementVisitor<R, D>, data: D): R =
visitor.visitVariable(this, data)
override fun <D> acceptChildren(visitor: IrElementVisitor<Unit, D>, data: D) {
initializer?.accept(visitor, data)
}
override fun <D> transformChildren(transformer: IrElementTransformer<D>, data: D) {
initializer = initializer?.transform(transformer, data)
}
} | 166 | null | 5771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 3,848 | kotlin | Apache License 2.0 |
finish/src/main/java/org/tensorflow/lite/examples/classification/MyDatabaseHelper.kt | aauu1234 | 648,887,662 | false | null | package org.tensorflow.lite.examples.classification
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast
class MyDatabaseHelper(var context:Context,name:String,version:Int):SQLiteOpenHelper(context,name,null,version) {
public var createPlant="create table Plant ("+
"id integer primary key autoincrement,"+
"plantname text,"+
"status text,"+
"info text,"+
"drugEffect text,"+
"curing text,"+
"image blob)"
override fun onCreate(db: SQLiteDatabase?) {
db?.execSQL(createPlant)
Toast.makeText(context,"Create Success",Toast.LENGTH_LONG).show()
}
override fun onUpgrade(db: SQLiteDatabase?, p1: Int, p2: Int) {
db?.execSQL("drop table if exists Plant")
onCreate(db)
}
} | 0 | Kotlin | 0 | 0 | 2ef08802e3c34285ed44b6c09e65214afcef7962 | 910 | mobile_cw2 | Apache License 2.0 |
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForUsersAction.kt | matrix-org | 287,466,066 | false | null | /*
* Copyright 2020 The Matrix.org Foundation C.I.C.
*
* 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 org.matrix.android.sdk.internal.crypto.actions
import org.matrix.android.sdk.internal.crypto.MXOlmDevice
import org.matrix.android.sdk.internal.crypto.model.MXOlmSessionResult
import org.matrix.android.sdk.internal.crypto.model.MXUsersDevicesMap
import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
import timber.log.Timber
import javax.inject.Inject
internal class EnsureOlmSessionsForUsersAction @Inject constructor(private val olmDevice: MXOlmDevice,
private val cryptoStore: IMXCryptoStore,
private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction) {
/**
* Try to make sure we have established olm sessions for the given users.
* @param users a list of user ids.
*/
suspend fun handle(users: List<String>): MXUsersDevicesMap<MXOlmSessionResult> {
Timber.v("## ensureOlmSessionsForUsers() : ensureOlmSessionsForUsers $users")
val devicesByUser = users.associateWith { userId ->
val devices = cryptoStore.getUserDevices(userId)?.values.orEmpty()
devices.filter {
// Don't bother setting up session to ourself
it.identityKey() != olmDevice.deviceCurve25519Key
// Don't bother setting up sessions with blocked users
&& !(it.trustLevel?.isVerified() ?: false)
}
}
return ensureOlmSessionsForDevicesAction.handle(devicesByUser)
}
}
| 91 | null | 418 | 97 | 55cc7362de34a840c67b4bbb3a14267bc8fd3b9c | 2,209 | matrix-android-sdk2 | Apache License 2.0 |
Kotlin/P39_a.kt | deveshp007 | 535,653,594 | false | {"Kotlin": 84827} | package com.example.three
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
class FragmentOne : Fragment() {
lateinit var view1: View
lateinit var lstView: ListView
private lateinit var txtfrag: FragmentTwo
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
view1 = inflater.inflate(R.layout.fragment_one, container, false)
val arr = arrayOf(
"Burger 🍔",
"Pizza 🍕",
"Chocolate 🍫",
"Coffee ☕",
"Shahi Paneer 😋",
"Cold Drink 🍷",
"Gulab Jamun 🍨",
"Paneer Tikka 🥘",
"Rice Bowl 🍚",
"Dahi Bhalle \uD83D\uDE0B",
"Malai Kofta \uD83D\uDE0B",
"Paneer Dosa 🍕",
"Ice Cream 🍦"
)
lstView = view1.findViewById(R.id.lstView)
val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, arr)
lstView.adapter = adapter
lstView.setOnItemClickListener { adapterView, view, i, l ->
txtfrag = parentFragmentManager.findFragmentById(R.id.fragment_2) as FragmentTwo
txtfrag.changeTxt(arr[i])
lstView.setSelector(R.color.purple_200)
}
return view1
}
} | 0 | Kotlin | 6 | 24 | a5d62d97081826a35308defd9641bb9552f5e789 | 1,542 | Android-App-Development | MIT License |
doflib/src/main/java/no/danielzeller/doflib/opengl/VertexArray.kt | danielzeller | 178,028,601 | false | null | package no.danielzeller.blurbehindlib.opengl
import android.opengl.GLES20.*
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
private const val BYTES_PER_FLOAT = 4
class VertexArray(vertexData: FloatArray) {
private val floatBuffer: FloatBuffer = ByteBuffer
.allocateDirect(vertexData.size * BYTES_PER_FLOAT)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.put(vertexData)
fun setVertexAttribPointer(dataOffset: Int, attributeLocation: Int, componentCount: Int, stride: Int) {
floatBuffer.position(dataOffset)
glVertexAttribPointer(attributeLocation, componentCount, GL_FLOAT,
false, stride, floatBuffer)
glEnableVertexAttribArray(attributeLocation)
floatBuffer.position(0)
}
}
| 0 | null | 1 | 6 | b5963d27670c82a18038fa90f5d19fbc83752135 | 827 | DepthOfFIeldAndroid | MIT License |
app/src/main/java/exirium/pe/authflowapp/presentation/authentication/signup/SignUpState.kt | gianpaul | 811,396,647 | false | {"Kotlin": 66641} | package exirium.pe.authflowapp.presentation.authentication.signup
data class SignUpState(
val email: String = "",
val password: String = "",
val name: String = "",
val isLoading: Boolean = false,
val navigateToColors: Boolean = false,
val toastMessage: String? = null,
)
| 0 | Kotlin | 0 | 1 | c225f7a8d17a19e2b90a1170eccf3c4244a73ff0 | 296 | TechnicalChallengeAuthentication | MIT License |
app/src/main/java/com/example/mycommish/feature/prize/data/local/repository/PrizeLocalRepository.kt | moaliyou | 786,551,198 | false | {"Kotlin": 142862} | package com.example.mycommish.feature.prize.data.local.repository
import com.example.mycommish.feature.prize.data.local.datasource.PrizeObject
import com.example.mycommish.feature.prize.domain.repository.PrizeRepository
import io.realm.kotlin.Realm
import io.realm.kotlin.ext.query
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import org.mongodb.kbson.ObjectId
class PrizeLocalRepository(
private val realm: Realm
) : PrizeRepository {
override fun getAllPrizes(): Flow<List<PrizeObject>> =
realm.query<PrizeObject>().asFlow().map { it.list }
override suspend fun insertPrize(prizeObject: PrizeObject) {
realm.write { copyToRealm(prizeObject) }
}
override suspend fun updatePrize(prizeObject: PrizeObject) {
realm.write {
val queriedPrize = query<PrizeObject>("_id = $0", prizeObject._id).find().first()
queriedPrize.name = prizeObject.name
queriedPrize.value = prizeObject.value
queriedPrize.description = prizeObject.description
}
}
override suspend fun deletePrize(id: ObjectId) {
realm.write {
}
}
} | 0 | Kotlin | 1 | 1 | 86630b2214859c50528c64166857357cdcaf36cc | 1,164 | My-Commish | MIT License |
test/server/ServerTest.kt | rtc11 | 874,209,959 | false | {"Kotlin": 53397, "Makefile": 2306} | package server
import client.*
import json.*
import kotlinx.coroutines.*
import test.*
import serde.*
import util.*
import java.net.*
class ServerTest {
private data class Name(val name: String) : Into<Json> {
override fun into(): Json = mapOf(Name::name.name to name)
companion object {
fun from(json: Json): Name {
val name: String by json
return Name(name)
}
}
}
private val server = Server(8080).apply {
router("/") {
get("text") {
respond(StatusCode.OK, "hello")
}
get("json") {
respond(StatusCode.OK, Name("robin"))
}
}
}
@Test
fun `response is idempotent`() {
val client = Client()
server.start(0)
fun fetchText(): HttpResponse = runBlocking {
client.get(URI("http://localhost:8080/text")) {
setHeader("Content-Type", ContentType.Text.withCharsetUtf8())
setHeader("Accept", ContentType.Text.value)
}
}
fun fetchJson(): HttpResponse = runBlocking {
client.get(URI("http://localhost:8080/json")) {
setHeader("Content-Type", ContentType.Json.withCharsetUtf8())
setHeader("Accept", ContentType.Json.value)
}
}
val firstText = StringSerde.deserialize(fetchText().body).expect("hello")
val secondText = StringSerde.deserialize(fetchText().body).expect("hello")
val firstJson = Name.from(JsonSerde.deserialize(fetchJson().body).expect("Json with name:robin"))
val secondJson = Name.from(JsonSerde.deserialize(fetchJson().body).expect("Json with name:robin"))
assertEq("hello", firstText)
assertEq("hello", secondText)
assertEq("{\"name\" : \"robin\"}", firstJson)
assertEq("{\"name\" : \"robin\"}", secondJson)
client.close()
server.stop(0)
}
}
object StringSerde : Serde<String> {
override fun serialize(from: String): Result<String, SerdeException> {
return Result.Ok(from)
}
override fun serialize(from: Collection<String>): Result<String, SerdeException> {
return Result.Ok(from.joinToString())
}
override fun deserialize(from: String): Result<String, SerdeException> {
return Result.Ok(from)
}
}
| 0 | Kotlin | 0 | 0 | efe2f192b6fbb582ac0b4fc1e0371df86c36f32f | 2,408 | klib | MIT License |
tools/sisyphus-protobuf-gradle-plugin/src/main/kotlin/com/bybutter/sisyphus/protobuf/gradle/ProtobufApiCompileTask.kt | z2058550226 | 299,014,281 | true | {"Kotlin": 1014038, "ANTLR": 10895} | package com.bybutter.sisyphus.protobuf.gradle
import com.bybutter.sisyphus.api.Service
import com.bybutter.sisyphus.jackson.toYaml
import com.google.api.tools.framework.tools.configgen.ServiceConfigGeneratorTool
import java.io.File
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.SourceTask
import org.gradle.api.tasks.TaskAction
open class ProtobufApiCompileTask : SourceTask() {
@get:InputDirectory
lateinit var protobufPath: File
@get:OutputDirectory
lateinit var resourceOutput: File
@get:Internal
var service: Service? = null
@TaskAction
fun compileApi() {
val service = service ?: return
val serviceConfig = protobufPath.resolve("service.yml")
serviceConfig.writeText(serviceToYamlConfig(service))
val descFile = protobufPath.resolve("protodesc.pb")
val apiConfig = resourceOutput.resolve("api.json")
ServiceConfigGeneratorTool.main(
arrayOf(
"--configs",
serviceConfig.toString(),
"--descriptor",
descFile.toString(),
"--json_out",
apiConfig.toString()
)
)
}
private val yamlHeaderRegex = """^---\n""".toRegex()
private fun serviceToYamlConfig(service: Service): String {
return service.toYaml().replace(yamlHeaderRegex, "---\ntype: google.api.Service\n")
}
}
| 0 | null | 0 | 0 | a4a2e608f20aa977278daa2382833184b30d6124 | 1,510 | sisyphus | MIT License |
app/src/main/java/dev/marcosfarias/pokedex/App.kt | zsmb13 | 232,301,179 | true | null | package dev.marcosfarias.pokedex
import android.app.Application
import android.content.Context
import androidx.room.Room
import dev.marcosfarias.pokedex.database.AppDatabase
class App : Application() {
companion object {
var context: Context? = null
var database: AppDatabase? = null
}
override fun onCreate() {
super.onCreate()
context = this
database = Room.databaseBuilder(
this,
AppDatabase::class.java,
getString(R.string.app_name)
)
.fallbackToDestructiveMigration()
.build()
}
} | 0 | Kotlin | 8 | 48 | a2ab162c1de76700e16ba521b1193c503b6b3f84 | 626 | Kotlin-Pokedex | MIT License |
app/src/main/java/com/droidconsf/architectureagnosticuidevelopment/ui/common/statemachine/StateMachineFactory.kt | vinaygaba | 221,616,306 | false | null | package com.droidconsf.architectureagnosticuidevelopment.ui.common.statemachine
import com.droidconsf.architectureagnosticuidevelopment.ui.ComicbooksViewModel
import com.tinder.StateMachine
import javax.inject.Inject
internal class StateMachineFactory @Inject constructor() {
internal fun create(
initialState: ViewState
): StateMachine<ViewState, Event, SideEffect> {
return StateMachine.create {
initialState(initialState)
state<ViewState.Empty> {
on<Event.View.LoadComics> {
transitionTo(
state = ViewState.Loading,
sideEffect = SideEffect.LoadComics
)
}
}
state<ViewState.Loading> {
on<Event.System.OnLoadSuccess> { event ->
transitionTo(
state = ViewState.ShowingComicBookList(
ComicbooksViewModel.ComicsContext(
comics = event.comics
)
)
)
}
}
state<ViewState.ShowingComicBook> {
on<Event.View.ComicbookDescriptionExtraLines> { event ->
transitionTo(
ViewState.ShowingComicBook(
comicbookContext = comicbookContext.copy(
shouldNavigate = false,
shouldDisplayShowMoreButton = event.extraLines > 0
)
)
)
}
on<Event.View.ShowMoreDescription> { event ->
transitionTo(
ViewState.ShowingComicBook(
comicbookContext = comicbookContext.copy(
descriptionExpanded = true
)
)
)
}
on<Event.View.GoBack> { event ->
transitionTo(
ViewState.ShowingComicBookList(
comicbookContext.copy(
shouldNavigate = true,
currentDisplayedComic = null,
descriptionExpanded = false,
shouldDisplayShowMoreButton = false
)
)
)
}
}
state<ViewState.ShowingComicBookList> {
on<Event.View.ShowComicbook> { event ->
transitionTo(
state = ViewState.ShowingComicBook(
comicbookContext.copy(
currentDisplayedComic = comicbookContext
.comics.find { it.id.toString() == event.comicbookId }
)
)
)
}
on<Event.View.GoBack> { event ->
transitionTo(
state = ViewState.CloseScreen
)
}
}
}
}
} | 0 | Kotlin | 2 | 6 | 0df6025e8b227d464a7d3c4f3ef16761187f0c56 | 3,327 | Droidcon-SF-2019-Architecture-Agnostic-UI-Development | Apache License 2.0 |
Project/app/src/main/java/org/ionproject/android/offline/models/CatalogAcademicYears.kt | i-on-project | 245,234,364 | false | null | package org.ionproject.android.offline.models
import com.fasterxml.jackson.annotation.JsonProperty
data class CatalogAcademicYears(
@JsonProperty("tree")
val years: List<CatalogAcademicYear>
) | 8 | Kotlin | 0 | 4 | c18e940a10b9bcc4e3511ca7fa2c647be5db9ff2 | 202 | android | Apache License 2.0 |
SovrinAgentApp/app/src/main/java/com/luxoft/supplychain/sovrinagentapp/ui/model/OrdersAdapter.kt | AntDroid82 | 202,780,935 | true | {"Kotlin": 220246, "JavaScript": 64411, "CSS": 25167, "Dockerfile": 1015, "HTML": 354, "Shell": 159} | /*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.luxoft.supplychain.sovrinagentapp.ui.model
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.support.v4.content.ContextCompat.startActivity
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.luxoft.supplychain.sovrinagentapp.R
import com.luxoft.supplychain.sovrinagentapp.data.PackageState
import com.luxoft.supplychain.sovrinagentapp.data.Product
import com.luxoft.supplychain.sovrinagentapp.ui.SimpleScannerActivity
import com.luxoft.supplychain.sovrinagentapp.ui.TrackPackageActivity
import io.realm.Realm
import io.realm.RealmChangeListener
import io.realm.RealmResults
import io.realm.Sort
import kotlinx.android.synthetic.main.order_list_item.view.*
import kotlinx.android.synthetic.main.qr_list_item.view.*
class OrdersAdapter(realm: Realm) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var realmChangeListener = RealmChangeListener<Realm> {
Log.i("TAG", "Change occurred!")
this.notifyDataSetChanged()
}
init {
realm.addChangeListener(realmChangeListener)
}
//Dirty hack to hide first hardcoded value if there are pending orders
private val orders = object {
private val orders: RealmResults<Product> = realm.where(Product::class.java).sort("requestedAt", Sort.DESCENDING).isNull("collectedAt").findAll()
val size: Int
get() {
var size = orders.size
if (size > 1)
size -= 1
return size
}
operator fun get(index: Int): Product? {
var position: Int = index
if (orders.size > 1) {
position += 1
}
return orders[position]
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val order = orders[position]
if (order == null) {
Log.i("TAG", "Item not found for index $position")
} else when (holder) {
is OrderViewHolder -> bindNormalItem(order, holder)
is QROrderViewHolder -> bindQRItem(order, holder)
}
}
private fun bindQRItem(order: Product, holder: QROrderViewHolder) {
holder.title.text = order.medicineName
holder.sn.text = "SN: " + order.serial
holder.message.text = order.currentStateMessage(PackageState.valueOf(order.state!!).ordinal)
holder.title.setOnClickListener {
startActivity(holder.title.context, Intent().setClass(holder.title.context, TrackPackageActivity::class.java).putExtra("serial", order.serial), null)
}
holder.qrButton.setOnClickListener {
ContextCompat.startActivity(holder.qrButton.context,
Intent().setClass(holder.qrButton.context, SimpleScannerActivity::class.java)
.putExtra("serial", order.serial)
.putExtra("state", order.state), null
)
}
}
private fun bindNormalItem(order: Product, holder: OrderViewHolder) {
holder.title.text = order.medicineName
holder.sn.text = "SN: " + order.serial
holder.message.text = order.currentStateMessage(PackageState.valueOf(order.state!!).ordinal)
holder.title.setOnClickListener {
startActivity(holder.title.context, Intent().setClass(holder.title.context, TrackPackageActivity::class.java).putExtra("serial", order.serial), null)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == QR) {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.qr_list_item, viewGroup, false)
QROrderViewHolder(view)
} else {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.order_list_item, viewGroup, false)
OrderViewHolder(view)
}
}
override fun getItemCount(): Int {
return orders.size
}
override fun getItemViewType(position: Int): Int {
val order = orders[position]
return if (order?.state == PackageState.NEW.name || order?.state == PackageState.DELIVERED.name) QR else plain
}
open inner class OrderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var title: TextView = itemView.listitem_medicine_name as TextView
var message: TextView = itemView.listitem_message as TextView
var sn: TextView = itemView.listitem_sn as TextView
}
open inner class QROrderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var title: TextView = itemView.qr_listitem_medicine_name as TextView
var message: TextView = itemView.qr_listitem_message as TextView
var qrButton: View = itemView.btn_scan_qr
var sn: TextView = itemView.qr_listitem_sn as TextView
}
companion object {
const val QR = 0
const val plain = 1
}
}
| 0 | Kotlin | 0 | 0 | 3df076ddf6a78fde40e88538e2939d600aad52d4 | 5,731 | cordentity-poc-supply-chain | Apache License 2.0 |
modules/module-content/src/main/java/com/bbgo/module_content/webclient/WebClientFactory.kt | bbggo | 371,705,786 | false | null | package com.cxz.wanandroid.webclient
import android.webkit.WebViewClient
/**
* @author guoyikai
* @date 2023/11/24
* @desc WebClientFactory
*/
object WebClientFactory {
val JIAN_SHU = "https://www.jianshu.com"
fun create(url: String): WebViewClient {
return when {
url.startsWith(JIAN_SHU) -> JianShuWebClient()
else -> BaseWebClient()
}
}
} | 3 | null | 3 | 8 | 9c983af26f5bd9cd5e08b7a6080190305738b435 | 402 | WanAndroid | Apache License 2.0 |
src/main/kotlin/com/magicreg/resql/format.kt | regadou | 835,444,933 | false | {"Kotlin": 141673, "Shell": 472} | package com.magicreg.resql
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import org.apache.commons.csv.CSVFormat
import java.io.*
import java.lang.reflect.Member
import java.net.URLDecoder
import java.net.URLEncoder
import java.nio.charset.Charset
import java.text.SimpleDateFormat
import java.util.*
import kotlin.reflect.KCallable
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
fun getSupportedFormats(): List<Format> {
return MIMETYPES.values.filter{it.supported}.toSortedSet(::compareFormats).toList()
}
fun getFormat(txt: String): Format? {
val lower = txt.lowercase()
return MIMETYPES[lower] ?: EXTENSIONS[lower]
}
fun getExtensionMimetype(txt: String): String? {
return EXTENSIONS[txt.lowercase()]?.mimetype
}
fun getMimetypeExtensions(txt: String): List<String> {
val format = MIMETYPES[txt.lowercase()]
return format?.extensions ?: listOf()
}
fun detectFileType(path: String?): String? {
if (path == null)
return null
var parts = path.trim().split("/")
val filename = parts[parts.size-1]
if (filename == "" || filename.indexOf(".") < 0)
return null
if (filename[0] == '.')
return "text/plain"
parts = filename.split(".")
return getExtensionMimetype(parts[parts.size-1])
}
fun loadAllMimetypes(): Map<String,List<String>> {
val map = mutableMapOf<String,MutableList<String>>()
val reader = BufferedReader(InputStreamReader(GenericFormat::class.java.getResource("/mime.types").openStream()))
reader.lines().forEach { line ->
val escape = line.indexOf('#')
val txt = if (escape >= 0) line.substring(0, escape) else line
var mimetype: String? = null
val extensions = mutableListOf<String>()
val e = StringTokenizer(txt.lowercase())
while (e.hasMoreElements()) {
val token = e.nextElement().toString()
if (mimetype == null)
mimetype = token
else
extensions.add(token)
}
if (mimetype != null)
map[mimetype] = extensions
}
reader.close()
return map
}
class GenericFormat(
override val mimetype: String,
override val extensions: List<String>,
private val decoder: (InputStream, String) -> Any?,
private val encoder: (Any?, OutputStream, String) -> Unit,
override val supported: Boolean
): Format {
override fun decode(input: InputStream, charset: String): Any? {
return decoder(input, charset)
}
override fun encode(value: Any?, output: OutputStream, charset: String) {
encoder(value, output, charset)
}
override fun toString(): String {
return "Format($mimetype)"
}
}
private const val CSV_MINIMUM_CONSECUTIVE_FIELDS_SIZE = 5
private const val CSV_BUFFER_SIZE = 1024
private const val JSON_EXPRESSION_START = "{[\""
private val CSV_SEPARATORS = ",;|:\t".toCharArray()
private val JSON_SERIALIZER_CLASSES = listOf(KClass::class, KCallable::class, Class::class, Member::class, KProperty::class, Exception::class,
InputStream::class, OutputStream::class, Reader::class, Writer::class, ByteArray::class, CharArray::class,
Property::class, Namespace::class, Format::class)
private val CSV_FORMAT = configureCsvFormat()
private val JSON_MAPPER = configureJsonMapper(ObjectMapper())
private val YAML_MAPPER = configureJsonMapper(ObjectMapper(YAMLFactory()))
private val EXTENSIONS = mutableMapOf<String,Format>()
private val MIMETYPES = loadMimeTypesFile()
private fun configureJsonMapper(mapper: ObjectMapper): ObjectMapper {
mapper.configure(SerializationFeature.INDENT_OUTPUT, true)
.configure(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, false)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false)
.configure(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, false)
.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, true)
.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, false)
.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true)
.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true)
.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, false)
.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true)
.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false)
.setDateFormat(SimpleDateFormat("yyyy-MM-dd hh:mm:ss"))
val module = SimpleModule()
for (klass in JSON_SERIALIZER_CLASSES)
addSerializer(module, klass.java)
return mapper.registerModule(module).registerModule(JavaTimeModule())
}
private fun loadMimeTypesFile(): MutableMap<String,Format> {
val mimetypes = initManagedMimetypes()
for (entry in loadAllMimetypes().entries) {
val mimetype = entry.key
val extensions = entry.value
if (mimetypes[mimetype] != null)
;
else if (mimetype.split("/")[0] == "text")
addMimetype(mimetypes, ::decodeString, ::encodeString, mimetype, extensions, false)
else
addMimetype(mimetypes, ::decodeBytes, ::encodeBytes, mimetype, extensions, false)
}
return mimetypes
}
private fun addMimetype(mimetypes: MutableMap<String,Format>,
decoder: (InputStream, String) -> Any?,
encoder: (Any?, OutputStream, String) -> Unit,
mimetype: String,
extensions: List<String>,
supported: Boolean = true) {
val format = GenericFormat(mimetype, extensions, decoder, encoder, supported)
mimetypes[mimetype] = format
addExtensions(format)
}
private fun addExtensions(format: Format) {
for (extension in format.extensions) {
if (!EXTENSIONS.containsKey(extension))
EXTENSIONS[extension] = format
}
}
private fun initManagedMimetypes(): MutableMap<String,Format> {
val formats = mutableMapOf<String,Format>()
addMimetype(formats, ::decodeBytes, ::encodeBytes, "application/octet-stream", listOf("bin"))
addMimetype(formats, ::decodeString, ::encodeString, "text/plain", listOf("txt"))
addMimetype(formats, ::decodeHtml, ::encodeHtml, "text/html", listOf("html", "htm", "xhtml"))
addMimetype(formats, ::decodeProperties, ::encodeProperties, "text/x-java-properties", listOf("properties"))
addMimetype(formats, ::decodeCsv, ::encodeCsv, "text/csv", listOf("csv"))
addMimetype(formats, ::decodeKotlin, ::encodeKotlin, "text/x-kotlin", listOf("kts", "kt"))
addMimetype(formats, ::decodeJson, ::encodeJson, "application/json", listOf("json"))
addMimetype(formats, ::decodeYaml, ::encodeYaml, "application/yaml", listOf("yaml"))
addMimetype(formats, ::decodeForm, ::encodeForm, "application/x-www-form-urlencoded", listOf("form", "urlencoded"))
return formats
}
private fun decodeString(input: InputStream, charset: String): Any? {
return input.readAllBytes().toString(Charset.forName(charset))
}
private fun encodeString(value: Any?, output: OutputStream, charset: String) {
if (value != null)
output.write(toString(value).toByteArray(Charset.forName(charset)))
}
private fun decodeBytes(input: InputStream, charset: String): Any? {
return input.readAllBytes()
}
private fun encodeBytes(value: Any?, output: OutputStream, charset: String) {
if (value is ByteArray)
output.write(value)
else if (value != null)
output.write(toString(value).toByteArray(Charset.forName(charset)))
}
private fun decodeJson(input: InputStream, charset: String): Any? {
return JSON_MAPPER.readValue(InputStreamReader(input, charset), Any::class.java)
}
private fun encodeJson(value: Any?, output: OutputStream, charset: String) {
encodeString(JSON_MAPPER.writeValueAsString(value)+"\n", output, charset)
}
private fun decodeYaml(input: InputStream, charset: String): Any? {
return YAML_MAPPER.readValue(InputStreamReader(input, charset), Any::class.java)
}
private fun encodeYaml(value: Any?, output: OutputStream, charset: String) {
encodeString(YAML_MAPPER.writeValueAsString(value)+"\n", output, charset)
}
private fun decodeProperties(input: InputStream, charset: String?): Any? {
val props = Properties()
props.load(InputStreamReader(input, charset))
return props
}
private fun encodeProperties(value: Any?, output: OutputStream, charset: String?) {
var properties: Properties?
if (value is Properties)
properties = value
else if (value == null)
properties = Properties()
else {
val map = toMap(value)
properties = Properties()
for (key in map.keys)
properties.setProperty(toString(key), toString(map[key]))
}
properties.store(OutputStreamWriter(output, charset), "")
}
private fun decodeKotlin(input: InputStream, charset: String): Any? {
return getKotlinParser().execute(input.readAllBytes().toString(Charset.forName(charset)))
}
private fun encodeKotlin(value: Any?, output: OutputStream, charset: String) {
output.write((value.toString()+"\n").toByteArray(Charset.forName(charset)))
}
private fun decodeCsv(input: InputStream, charset: String): Any {
val dst = mutableListOf<Map<String,Any>>()
val bufferedInput = BufferedInputStream(input, CSV_BUFFER_SIZE)
val records = CSV_FORMAT.builder().setDelimiter(detectSeparator(bufferedInput)).build().parse(InputStreamReader(bufferedInput, charset))
val fields = mutableListOf<String>()
for (record in records) {
if (fields.isEmpty()) {
val it = record.iterator()
while (it.hasNext())
fields.add(it.next())
}
else {
val map = mutableMapOf<String,Any>()
val n = Math.min(fields.size, record.size())
for (f in 0 until n)
map[fields[f]] = record.get(f)
dst.add(map)
}
}
return dst
}
private fun encodeCsv(value: Any?, output: OutputStream, charset: String) {
val printer = CSV_FORMAT.print(OutputStreamWriter(output, charset))
val records = toList(value)
val fields = mutableListOf<String>()
var lastSize = 0
var consecutives = 0
for (record in records) {
val map = toMap(record)
for (key in map.keys) {
if (fields.indexOf(key) < 0)
fields.add(key.toString())
}
if (lastSize == fields.size)
consecutives++
else {
consecutives = 0
lastSize = fields.size
}
if (consecutives >= CSV_MINIMUM_CONSECUTIVE_FIELDS_SIZE)
break;
}
printer.printRecord(fields)
for (record in records) {
val map = toMap(record)
for (field in fields) {
val cell = map[field];
printer.print(toString(cell))
}
printer.println();
}
printer.flush()
}
private fun decodeForm(input: InputStream, charset: String): Any? {
val map = mutableMapOf<String,Any?>()
var entries = InputStreamReader(input, charset).readText().split("&")
for (entry in entries) {
val eq = entry.indexOf('=')
if (eq < 0)
setValue(map, entry, true)
else
setValue(map, entry.substring(0,eq), entry.substring(eq+1))
}
return map
}
private fun encodeForm(value: Any?, output: OutputStream, charset: String) {
val entries = mutableListOf<String>()
val map = toMap(value)
for (key in map.keys) {
entries.add(urlencode(key?.toString() ?: "null")+"="+
urlencode(map[key]?.toString() ?: "null"))
}
encodeString(entries.joinToString("&"), output, charset)
}
private fun decodeHtml(input: InputStream, charset: String): Any? {
return input.readAllBytes().toString(Charset.forName(charset))
}
private fun encodeHtml(value: Any?, output: OutputStream, charset: String) {
if (value != null)
output.write(toString(value).toByteArray(Charset.forName(charset)))
}
private fun configureCsvFormat(): CSVFormat {
return CSVFormat.DEFAULT.builder().setDelimiter(CSV_SEPARATORS[0]).build()
}
private fun <T> addSerializer(module: SimpleModule, klass: Class<T>) {
val serializer = object : JsonSerializer<T>() {
override fun serialize(value:T, jgen: JsonGenerator, provider: SerializerProvider) {
jgen.writeString(value.toText())
}
}
module.addSerializer(klass, serializer)
}
private fun parseValue(src: Any?): Any? {
if (src is CharSequence) {
return when (val value = URLDecoder.decode(src.toString(), defaultCharset()).trim()) {
"null" -> null
"true" -> true
"false" -> false
else -> value.toLongOrNull() ?: value.toDoubleOrNull() ?: getExpression(value.trim())
}
}
return src
}
private fun getExpression(value: String): Any? {
if (value.isEmpty())
return ""
if (JSON_EXPRESSION_START.indexOf(value[0]) < 0)
return value
val first = value[0]
val last = value[value.length-1]
if ((first == '[' && last == ']') || (first == '{' && last == '}') || (first == '"' && last == '"')) {
try { return JSON_MAPPER.readValue(ByteArrayInputStream(value.toByteArray()), Any::class.java) }
catch(e: Exception) {}
}
return value
}
private fun setValue(map: MutableMap<String,Any?>, name: String, value: Any?) {
val key = URLDecoder.decode(name, defaultCharset())
val old = map[key]
if (old == null)
map[key] = parseValue(value)
else if (old is MutableCollection<*>)
(old as MutableCollection<Any?>).add(parseValue(value))
else
map[key] = mutableListOf<Any?>(old, parseValue(value))
}
private fun urlencode(txt: String): String {
return URLEncoder.encode(txt, defaultCharset()).replace("+", "%20")
}
private fun detectSeparator(input: InputStream): Char {
val buffer = ByteArray(CSV_BUFFER_SIZE)
input.mark(CSV_BUFFER_SIZE)
input.read(buffer)
input.reset()
val txt = buffer.toString(Charset.forName(defaultCharset()))
for (c in txt) {
if (CSV_SEPARATORS.contains(c))
return c
if (c == '\n' || c == '\r')
break
}
return CSV_SEPARATORS[0]
}
private fun compareFormats(f1: Format, f2: Format): Int {
return f1.mimetype.compareTo(f2.mimetype)
}
| 0 | Kotlin | 0 | 0 | 8df69c02ff1b588c76a573cb713c3b464c3ce10d | 15,180 | resql | MIT License |
common/src/main/java/io/homeassistant/companion/android/common/data/authentication/impl/entities/LoginFlowAuthentication.kt | nesror | 328,856,313 | true | null | package io.homeassistant.companion.android.common.data.authentication.impl.entities
import com.fasterxml.jackson.annotation.JsonProperty
data class LoginFlowAuthentication(
@JsonProperty("client_id")
val clientId: String,
@JsonProperty("username")
val userName: String,
@JsonProperty("password")
val password: String
)
| 0 | Kotlin | 15 | 61 | b36bb0f67fd884b0f8c938c048b51134063784f2 | 345 | Home-Assistant-Companion-for-Android | Apache License 2.0 |
app/src/main/java/moe/feng/danmaqua/ui/main/DanmakuContextMenuDialogFragment.kt | xiangyutian | 241,036,188 | true | {"Kotlin": 236437} | package moe.feng.danmaqua.ui.main
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import kotlinx.android.synthetic.main.main_danmaku_context_menu_dialog_layout.*
import moe.feng.common.eventshelper.of
import moe.feng.danmaqua.Danmaqua.EXTRA_DATA
import moe.feng.danmaqua.R
import moe.feng.danmaqua.event.MainDanmakuContextMenuListener
import moe.feng.danmaqua.model.BiliChatDanmaku
import moe.feng.danmaqua.ui.dialog.BaseBottomSheetDialogFragment
import moe.feng.danmaqua.util.ext.eventsHelper
class DanmakuContextMenuDialogFragment : BaseBottomSheetDialogFragment() {
companion object {
fun newInstance(data: BiliChatDanmaku): DanmakuContextMenuDialogFragment {
return DanmakuContextMenuDialogFragment().apply {
arguments = bundleOf(EXTRA_DATA to data)
}
}
}
private lateinit var danmaku: BiliChatDanmaku
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
danmaku = arguments!!.getParcelable(EXTRA_DATA)!!
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.main_danmaku_context_menu_dialog_layout, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
usernameView.text = danmaku.senderName
contentTextView.text = danmaku.text
val listener = view.context.eventsHelper.of<MainDanmakuContextMenuListener>()
blockTextButton.setOnClickListener {
listener.onConfirmBlockText(danmaku)
dismiss()
}
blockUserButton.setOnClickListener {
listener.onConfirmBlockUser(danmaku)
dismiss()
}
hideButton.setOnClickListener {
listener.onHideDanmaku(danmaku)
dismiss()
}
}
} | 0 | null | 0 | 0 | 14775dad36f8a704674e1e6ca501c949b71ec6df | 2,030 | danmaqua-android | Apache License 2.0 |
app/src/main/java/com/developerkurt/gamedatabase/ui/FavoriteGamesFragment.kt | DeveloperKurt | 319,710,837 | false | null | package com.developerkurt.gamedatabase.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import com.developerkurt.gamedatabase.adapters.GameListAdapter
import com.developerkurt.gamedatabase.data.model.GameData
import com.developerkurt.gamedatabase.data.source.Result
import com.developerkurt.gamedatabase.databinding.FavoriteGamesFragmentBinding
import com.developerkurt.gamedatabase.viewmodels.FavoriteGamesViewModel
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
@AndroidEntryPoint
class FavoriteGamesFragment : BaseDataFragment(), GameListAdapter.GameClickListener
{
private val viewModel: FavoriteGamesViewModel by viewModels()
// This property is only valid between onCreateView and onDestroyView.
private var _binding: FavoriteGamesFragmentBinding? = null
private val binding get() = _binding!!
private lateinit var gameListAdapter: GameListAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View?
{
_binding = FavoriteGamesFragmentBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?)
{
super.onViewCreated(view, savedInstanceState)
if (requireActivity() is MainActivity)
{
(requireActivity() as MainActivity).displayBottomNavBar()
}
gameListAdapter = GameListAdapter(this)
binding.recyclerViewFavoriteGames.adapter = gameListAdapter
}
override fun onResume()
{
super.onResume()
setupUI(gameListAdapter)
}
private fun setupUI(gameListAdapter: GameListAdapter)
{
lifecycleScope.launchWhenStarted {
viewModel.getFavoriteGameListResultLiveData().observe(viewLifecycleOwner, { result ->
if (activity != null)
{
requireActivity().runOnUiThread {
if (result is Result.Success)
{
gameListAdapter.updateList(result.data)
}
else
{
Timber.w("FragmentActivity was null, couldn't update the views' data")
}
handleDataStateChange(result)
}
}
})
}
}
override fun changeLayoutStateToLoading()
{
binding.progressBar.visibility = View.VISIBLE
}
override fun changeLayoutStateToReady()
{
binding.progressBar.visibility = View.GONE
binding.recyclerViewFavoriteGames.visibility = View.VISIBLE
binding.incErrorLayout.errorLayout.visibility = View.GONE
}
override fun changeLayoutStateToError()
{
binding.progressBar.visibility = View.GONE
binding.recyclerViewFavoriteGames.visibility = View.INVISIBLE
binding.incErrorLayout.errorLayout.visibility = View.VISIBLE
}
override fun changeLayoutFailedUpdate()
{
binding.progressBar.visibility = View.GONE
}
override fun onDestroyView()
{
super.onDestroyView()
_binding = null
}
override fun onGameClick(gameData: GameData)
{
navigateToGameDetails(gameData)
}
private fun navigateToGameDetails(gameData: GameData)
{
val direction = FavoriteGamesFragmentDirections.actionFavoriteGamesFragmentToGameDetailsFragment(gameData.id, gameData.isInFavorites)
binding.root.findNavController().navigate(direction)
}
} | 0 | Kotlin | 0 | 1 | 236ff45629bb193d58930e0d11f47952133d6027 | 3,867 | GameDatabase | Apache License 2.0 |
app/src/main/kotlin/com/cyb3rko/pazzword/fragments/analyzefragment/BottomLayoutTextView.kt | cyb3rko | 399,963,494 | false | {"Kotlin": 45935, "HTML": 6940} | /*
* Copyright (c) 2023 Cyb3rKo
*
* 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.cyb3rko.pazzword.fragments.analyzefragment
import android.annotation.SuppressLint
import android.content.Context
import android.util.TypedValue
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import com.cyb3rko.pazzword.R
@SuppressLint("AppCompatCustomView", "ViewConstructor")
class BottomLayoutTextView(
context: Context,
contentEntry: Boolean,
useMargins: Boolean,
message: String
) : TextView(context) {
init {
val newLayoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
text = message
if (contentEntry) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.customEntry))
if (useMargins) newLayoutParams.setMargins(0, 4, 0, 0)
} else {
setTextColor(ResourcesCompat.getColor(resources, R.color.textColorSecondary, context.theme))
setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.customTitle))
if (useMargins) newLayoutParams.setMargins(0, 20, 0, 0)
}
layoutParams = newLayoutParams
}
}
| 3 | Kotlin | 2 | 61 | ca456b8f6965ac70a48079db7642d38245716c80 | 1,838 | pazzword | Apache License 2.0 |
app/src/main/java/com/dkaera/mash/ui/onboarding/widgets/Password.kt | loreBart | 507,408,678 | false | null | package com.crazy.musicdrops.ui.util
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import com.crazy.musicdrops.R
@Composable
fun PasswordTextField(
label: String,
passwordState: TextFieldState,
modifier: Modifier = Modifier,
imeAction: ImeAction = ImeAction.Done,
onImeAction: () -> Unit = {}
) {
val showPassword = remember { mutableStateOf(false) }
OutlinedTextField(
value = passwordState.text,
onValueChange = {
passwordState.text = it
passwordState.enableShowErrors()
},
modifier = modifier
.fillMaxWidth()
.onFocusChanged { focusState ->
passwordState.onFocusChange(focusState.isFocused)
if (!focusState.isFocused) {
passwordState.enableShowErrors()
}
},
textStyle = MaterialTheme.typography.body2,
label = {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = label,
style = MaterialTheme.typography.body2
)
}
},
trailingIcon = {
if (showPassword.value) {
IconButton(onClick = { showPassword.value = false }) {
Icon(
imageVector = Icons.Filled.Visibility,
contentDescription = stringResource(id = R.string.label_password_hide)
)
}
} else {
IconButton(onClick = { showPassword.value = true }) {
Icon(
imageVector = Icons.Filled.VisibilityOff,
contentDescription = stringResource(id = R.string.label_password_show)
)
}
}
},
visualTransformation = if (showPassword.value) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
},
isError = passwordState.showErrors(),
keyboardOptions = KeyboardOptions.Default.copy(imeAction = imeAction),
keyboardActions = KeyboardActions(
onDone = {
onImeAction()
}
)
)
passwordState.getError()?.let { error -> TextFieldError(textError = error) }
}
| 0 | Kotlin | 0 | 0 | dad5c5e02c4dce888cf564ef2b4241c26784acac | 3,178 | music-drops | MIT License |
src/main/kotlin/cn/tursom/room/LiveUser.kt | tursom | 255,871,213 | false | null | package cn.tursom.room
data class LiveUser(
val code: Int,
val `data`: LiveUserData,
val message: String,
val msg: String
) | 0 | Kotlin | 0 | 0 | e1fc79083536f8e4ec149d859d8e576bd9a71132 | 132 | BiliWS | MIT License |
module/module-ui-receptacle/src/main/kotlin/taboolib/module/ui/receptacle/NMSImpl.kt | TabooLib | 120,413,612 | false | null | package taboolib.module.ui.receptacle
import net.minecraft.server.v1_16_R3.*
import org.bukkit.Material
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemStack
import org.bukkit.craftbukkit.v1_16_R3.util.CraftChatMessage
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import taboolib.common.reflect.Reflex.Companion.setProperty
import taboolib.common.reflect.Reflex.Companion.unsafeInstance
import taboolib.module.nms.MinecraftVersion
import taboolib.module.nms.sendPacket
import taboolib.platform.util.isAir
/**
* @author Arasple
* @date 2020/12/4 21:25
*/
class NMSImpl : NMS() {
private val emptyItemStack = CraftItemStack.asNMSCopy((ItemStack(Material.AIR)))
override fun sendInventoryPacket(player: Player, vararg packets: PacketInventory) {
packets.forEach {
when (it) {
// Close Window Packet
is PacketWindowClose -> {
player.sendPacket(PacketPlayOutCloseWindow(it.windowId))
}
// Update Window Slot
is PacketWindowSetSlot -> {
when {
MinecraftVersion.majorLegacy >= 11701 -> {
sendPacket(
player,
PacketPlayOutSetSlot::class.java.unsafeInstance(),
"containerId" to it.windowId,
"stateId" to -1,
"slot" to it.slot,
"itemStack" to toNMSCopy(it.itemStack)
)
}
else -> {
player.sendPacket(PacketPlayOutSetSlot(it.windowId, it.slot, toNMSCopy(it.itemStack)))
}
}
}
// Update Window Items
is PacketWindowItems -> {
when {
MinecraftVersion.majorLegacy >= 11701 -> {
sendPacket(
player,
PacketPlayOutWindowItems::class.java.unsafeInstance(),
"containerId" to it.windowId,
"stateId" to 1,
"items" to it.items.map { i -> toNMSCopy(i) }.toList(),
"carriedItem" to emptyItemStack
)
}
MinecraftVersion.majorLegacy >= 11700 -> {
sendPacket(
player,
PacketPlayOutWindowItems::class.java.unsafeInstance(),
"containerId" to it.windowId,
"items" to it.items.map { i -> toNMSCopy(i) }.toList()
)
}
else -> {
sendPacket(
player,
PacketPlayOutWindowItems::class.java.unsafeInstance(),
"a" to it.windowId,
"b" to it.items.map { i -> toNMSCopy(i) }.toList()
)
}
}
}
// Open Window Packet
is PacketWindowOpen -> {
when {
MinecraftVersion.isUniversal -> {
sendPacket(
player,
PacketPlayOutOpenWindow::class.java.unsafeInstance(),
"containerId" to it.windowId,
"type" to it.type.vanillaId,
"title" to CraftChatMessage.fromStringOrNull(it.title)
)
}
MinecraftVersion.majorLegacy >= 11400 -> {
sendPacket(
player,
PacketPlayOutOpenWindow(),
"a" to it.windowId,
"b" to it.type.vanillaId,
"c" to CraftChatMessage.fromStringOrNull(it.title)
)
}
else -> {
sendPacket(
player,
PacketPlayOutOpenWindow(),
"a" to it.windowId,
"b" to it.type.id,
"c" to ChatComponentText(it.title),
"d" to it.type.containerSize
)
}
}
}
}
}
}
fun toNMSCopy(itemStack: ItemStack?): net.minecraft.server.v1_16_R3.ItemStack {
return if (itemStack.isAir()) emptyItemStack else CraftItemStack.asNMSCopy(itemStack)
}
fun sendPacket(player: Player, packet: Any, vararg fields: Pair<String, Any>) {
fields.forEach { packet.setProperty(it.first, it.second) }
player.sendPacket(packet)
}
} | 6 | null | 47 | 133 | 3e9fa18bbb6150e09644453080674a55b7d48e7d | 5,353 | TabooLib | MIT License |
feature/tasks/src/main/kotlin/com/ngapps/phototime/feature/tasks/SingleShootViewModel.kt | ngapp-dev | 752,386,763 | false | {"Kotlin": 1840445, "Shell": 10136} | /*
* Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved.
*
* 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.ngapps.phototime.feature.tasks
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ngapps.phototime.core.data.repository.contacts.ContactResourceEntityQuery
import com.ngapps.phototime.core.data.repository.contacts.ContactsRepository
import com.ngapps.phototime.core.data.repository.locations.LocationResourceEntityQuery
import com.ngapps.phototime.core.data.repository.locations.LocationsRepository
import com.ngapps.phototime.core.data.repository.moodboards.MoodboardResourceEntityQuery
import com.ngapps.phototime.core.data.repository.moodboards.MoodboardsRepository
import com.ngapps.phototime.core.data.repository.shoots.ShootResourceEntityQuery
import com.ngapps.phototime.core.data.repository.shoots.ShootsRepository
import com.ngapps.phototime.core.data.repository.tasks.TaskResourceEntityQuery
import com.ngapps.phototime.core.data.repository.tasks.TasksRepository
import com.ngapps.phototime.core.decoder.StringDecoder
import com.ngapps.phototime.core.domain.GetDownloadUseCase
import com.ngapps.phototime.core.model.data.contact.ContactResource
import com.ngapps.phototime.core.model.data.location.LocationResource
import com.ngapps.phototime.core.model.data.moodboard.MoodboardResource
import com.ngapps.phototime.core.model.data.shoot.ShootResource
import com.ngapps.phototime.core.model.data.shoot.ShootResourceWithData
import com.ngapps.phototime.core.model.data.task.TaskResource
import com.ngapps.phototime.core.result.asResult
import com.ngapps.phototime.feature.tasks.navigation.ShootArgs
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
import com.ngapps.phototime.core.result.Result
@HiltViewModel
class SingleShootViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
stringDecoder: StringDecoder,
shootsRepository: ShootsRepository,
moodboardsRepository: MoodboardsRepository,
contactsRepository: ContactsRepository,
locationsRepository: LocationsRepository,
tasksRepository: TasksRepository,
private val getImageDownload: GetDownloadUseCase,
) : ViewModel() {
private val shootArgs: ShootArgs = ShootArgs(savedStateHandle, stringDecoder)
val shootId = shootArgs.shootId
val singleShootUiState: StateFlow<SingleShootUiState> = shootUiState(
shootId = shootId,
shootsRepository = shootsRepository,
moodboardsRepository = moodboardsRepository,
contactsRepository = contactsRepository,
locationsRepository = locationsRepository,
tasksRepository = tasksRepository,
)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = SingleShootUiState.Loading,
)
fun triggerAction(action: SingleShootAction) = when (action) {
is SingleShootAction.DeleteShoot -> doDeleteShoot(action.shootId)
is SingleShootAction.DownloadImage -> doDownloadImage(action.inputUrl)
}
private fun doDeleteShoot(shootId: String) {
viewModelScope.launch { }
}
private fun doDownloadImage(inputUrl: String) {
getImageDownload(inputUrl)
}
}
private fun shootUiState(
shootId: String,
shootsRepository: ShootsRepository,
moodboardsRepository: MoodboardsRepository,
contactsRepository: ContactsRepository,
locationsRepository: LocationsRepository,
tasksRepository: TasksRepository
): Flow<SingleShootUiState> {
val shootsStream: Flow<List<ShootResource>> =
shootsRepository.getShootResources(
ShootResourceEntityQuery(filterShootIds = setOf(element = shootId)),
)
return shootsStream.flatMapLatest { shoots ->
val shootResource = shoots.let { it[0] }
val moodboardsStream: Flow<List<MoodboardResource>> =
moodboardsRepository.getMoodboardResources(
MoodboardResourceEntityQuery(filterMoodboardIds = shootResource.moodboards.toSet()),
)
val contactsStream: Flow<List<ContactResource>> =
contactsRepository.getContactResources(
ContactResourceEntityQuery(filterContactIds = shootResource.contacts.toSet()),
)
val locationsStream: Flow<List<LocationResource>> =
locationsRepository.getLocationResources(
LocationResourceEntityQuery(filterLocationIds = shootResource.locations.toSet()),
)
val tasksStream: Flow<List<TaskResource>> =
tasksRepository.getTaskResources(
TaskResourceEntityQuery(filterTaskIds = shootResource.tasks.toSet()),
)
return@flatMapLatest combine(
shootsStream,
moodboardsStream,
contactsStream,
locationsStream,
tasksStream,
::ShootResourceWithData,
)
}.asResult()
.map { shootWithDataResult ->
when (shootWithDataResult) {
is Result.Success -> {
val (shoot, moodboards, contacts, locations, tasks) = shootWithDataResult.data
SingleShootUiState.Success(
shoot = shoot.let { it[0] },
moodboards = moodboards,
contacts = contacts,
locations = locations,
tasks = tasks,
)
}
is Result.Loading -> {
SingleShootUiState.Loading
}
is Result.Error -> {
SingleShootUiState.Error
}
}
}
}
sealed interface SingleShootUiState {
data class Success(
val shoot: ShootResource,
val moodboards: List<MoodboardResource>,
val contacts: List<ContactResource>,
val locations: List<LocationResource>,
val tasks: List<TaskResource>
) : SingleShootUiState
data object Error : SingleShootUiState
data object Loading : SingleShootUiState
}
sealed interface SingleShootAction {
data class DeleteShoot(val shootId: String) : SingleShootAction
data class DownloadImage(val inputUrl: String) : SingleShootAction
}
| 0 | Kotlin | 0 | 3 | dc6556f93cedf210597f0397ad3553de0fbb7a47 | 7,212 | phototime | Apache License 2.0 |
knee-compiler-plugin/src/main/kotlin/DownwardProperties.kt | deepmedia | 552,404,398 | false | {"Kotlin": 544280} | package io.deepmedia.tools.knee.plugin.compiler
import com.squareup.kotlinpoet.KModifier
import io.deepmedia.tools.knee.plugin.compiler.codegen.CodegenProperty
import io.deepmedia.tools.knee.plugin.compiler.codegen.KneeCodegen
import io.deepmedia.tools.knee.plugin.compiler.context.KneeContext
import io.deepmedia.tools.knee.plugin.compiler.features.KneeDownwardProperty
import io.deepmedia.tools.knee.plugin.compiler.import.concrete
import io.deepmedia.tools.knee.plugin.compiler.symbols.KneeSymbols
import io.deepmedia.tools.knee.plugin.compiler.utils.asModifier
import io.deepmedia.tools.knee.plugin.compiler.utils.asPropertySpec
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.types.IrSimpleType
fun processDownwardProperty(property: KneeDownwardProperty, context: KneeContext, codegen: KneeCodegen) {
property.makeCodegen(codegen, context.symbols)
}
// Create the codegen property. If we don't do this, this would be done anyway
// by codegen.container() when invoked by the setter/getter function. But let's do
// it so we can add appropriate modifiers.
private fun KneeDownwardProperty.makeCodegen(codegen: KneeCodegen, symbols: KneeSymbols) {
fun makeProperty(
typeMapper: (IrSimpleType) -> IrSimpleType = { it },
kdocSuffix: String = "",
isOverride: Boolean = false
) = source.asPropertySpec(typeMapper).run {
if (codegen.verbose) addKdoc("knee:properties${kdocSuffix}")
addModifiers(source.visibility.asModifier())
if (isOverride) addModifiers(KModifier.OVERRIDE)
if (source.modality == Modality.OPEN) addModifiers(KModifier.OPEN)
CodegenProperty(this).also {
codegenProducts.add(it)
}
}
// Where should the function implementation go?
when (kind) {
is KneeDownwardProperty.Kind.InterfaceMember -> {
// For the abstract child, use addChildIfNeeded. This is because when user imports
// a local type Flow<T> with more than implementation Flow<A>, Flow<B>, we make the codegen
// as the generic Flow<T> and as such A.property and B.property should not write twice there.
val abstract = makeProperty(kdocSuffix = ":abstract-interface-child")
kind.owner.codegenClone?.addChildIfNeeded(abstract)
val implementation = makeProperty(typeMapper = { it.concrete(kind.importInfo) })
implementation.spec.addModifiers(KModifier.OVERRIDE)
kind.owner.codegenImplementation.addChild(implementation)
codegenImplementation = implementation
}
is KneeDownwardProperty.Kind.ClassMember -> {
val isOverride = kind.owner.isOverrideInCodegen(symbols, this)
val property = makeProperty(isOverride = isOverride)
codegen.prepareContainer(source, kind.importInfo).addChild(property)
codegenImplementation = property
}
is KneeDownwardProperty.Kind.TopLevel -> {
val property = makeProperty()
codegen.prepareContainer(source, kind.importInfo).addChild(property)
codegenImplementation = property
}
}
}
| 6 | Kotlin | 2 | 76 | 033fe352320a38b882381929fecb7b1811e00ebb | 3,181 | Knee | Apache License 2.0 |
extensions/panache/hibernate-reactive-panache-kotlin/runtime/src/main/kotlin/io/quarkus/hibernate/reactive/panache/kotlin/runtime/KotlinJpaOperations.kt | patrox | 377,393,180 | false | null | package io.quarkus.hibernate.reactive.panache.kotlin.runtime
import io.quarkus.hibernate.reactive.panache.common.runtime.AbstractJpaOperations
import io.smallrye.mutiny.Uni
import org.hibernate.reactive.mutiny.Mutiny
class KotlinJpaOperations : AbstractJpaOperations<PanacheQueryImpl<*>>() {
override fun createPanacheQuery(
session: Uni<Mutiny.Session>,
query: String,
originalQuery: String?,
orderBy: String?,
paramsArrayOrMap: Any?
) = PanacheQueryImpl<Any>(session, query, originalQuery, orderBy, paramsArrayOrMap)
override fun list(query: PanacheQueryImpl<*>): Uni<MutableList<*>> =
query.list() as Uni<MutableList<*>>
companion object {
/**
* Provides the default implementations for quarkus to wire up. Should not be used by third
* party developers.
*/
@JvmField val INSTANCE = KotlinJpaOperations()
}
}
| 20 | null | 4 | 3 | 4b7e8c29de35541bb6a7b668391f31083abd1415 | 927 | quarkus | Apache License 2.0 |
card/src/main/java/com/adyen/checkout/card/internal/ui/view/CardListAdapter.kt | Adyen | 91,104,663 | false | null | /*
* Copyright (c) 2019 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by arman on 28/5/2019.
*/
package com.adyen.checkout.card.internal.ui.view
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.adyen.checkout.card.databinding.BrandLogoBinding
import com.adyen.checkout.card.internal.ui.model.CardListItem
import com.adyen.checkout.card.internal.ui.view.CardListAdapter.ImageViewHolder
import com.adyen.checkout.ui.core.internal.ui.loadLogo
internal class CardListAdapter : ListAdapter<CardListItem, ImageViewHolder>(CardDiffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
val binding = BrandLogoBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ImageViewHolder(binding)
}
override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
val card = currentList[position]
val alpha = if (card.isDetected) VIEW_ALPHA_DETECTED else VIEW_ALPHA_NON_DETECTED
holder.bind(card, alpha)
}
internal class ImageViewHolder(
private val binding: BrandLogoBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(card: CardListItem, alpha: Float) {
binding.imageViewBrandLogo.alpha = alpha
binding.imageViewBrandLogo.loadLogo(
environment = card.environment,
txVariant = card.cardBrand.txVariant,
)
}
}
companion object {
private const val VIEW_ALPHA_DETECTED = 1f
private const val VIEW_ALPHA_NON_DETECTED = 0.2f
}
object CardDiffCallback : DiffUtil.ItemCallback<CardListItem>() {
override fun areItemsTheSame(oldItem: CardListItem, newItem: CardListItem): Boolean =
oldItem.cardBrand.txVariant == newItem.cardBrand.txVariant
override fun areContentsTheSame(oldItem: CardListItem, newItem: CardListItem): Boolean =
oldItem == newItem
}
}
| 28 | Kotlin | 59 | 96 | 1f000e27e07467f3a30bb3a786a43de62be003b2 | 2,201 | adyen-android | MIT License |
nlp/front/storage-mongo/target/generated-sources/kapt/compile/ai/tock/nlp/front/shared/user/UserNamespace_.kt | theopenconversationkit | 84,538,053 | false | {"Kotlin": 6173880, "TypeScript": 1286450, "HTML": 532576, "Python": 376720, "SCSS": 79512, "CSS": 66318, "Shell": 12085, "JavaScript": 1849} | package ai.tock.nlp.front.shared.user
import kotlin.Boolean
import kotlin.String
import kotlin.Suppress
import kotlin.collections.Collection
import kotlin.collections.Map
import kotlin.reflect.KProperty1
import org.litote.kmongo.property.KCollectionPropertyPath
import org.litote.kmongo.property.KMapPropertyPath
import org.litote.kmongo.property.KPropertyPath
private val __Login: KProperty1<UserNamespace, String?>
get() = UserNamespace::login
private val __Namespace: KProperty1<UserNamespace, String?>
get() = UserNamespace::namespace
private val __Owner: KProperty1<UserNamespace, Boolean?>
get() = UserNamespace::owner
private val __Current: KProperty1<UserNamespace, Boolean?>
get() = UserNamespace::current
class UserNamespace_<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*, UserNamespace?>) :
KPropertyPath<T, UserNamespace?>(previous,property) {
val login: KPropertyPath<T, String?>
get() = KPropertyPath(this,__Login)
val namespace: KPropertyPath<T, String?>
get() = KPropertyPath(this,__Namespace)
val owner: KPropertyPath<T, Boolean?>
get() = KPropertyPath(this,__Owner)
val current: KPropertyPath<T, Boolean?>
get() = KPropertyPath(this,__Current)
companion object {
val Login: KProperty1<UserNamespace, String?>
get() = __Login
val Namespace: KProperty1<UserNamespace, String?>
get() = __Namespace
val Owner: KProperty1<UserNamespace, Boolean?>
get() = __Owner
val Current: KProperty1<UserNamespace, Boolean?>
get() = __Current}
}
class UserNamespace_Col<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*,
Collection<UserNamespace>?>) : KCollectionPropertyPath<T, UserNamespace?,
UserNamespace_<T>>(previous,property) {
val login: KPropertyPath<T, String?>
get() = KPropertyPath(this,__Login)
val namespace: KPropertyPath<T, String?>
get() = KPropertyPath(this,__Namespace)
val owner: KPropertyPath<T, Boolean?>
get() = KPropertyPath(this,__Owner)
val current: KPropertyPath<T, Boolean?>
get() = KPropertyPath(this,__Current)
@Suppress("UNCHECKED_CAST")
override fun memberWithAdditionalPath(additionalPath: String): UserNamespace_<T> =
UserNamespace_(this, customProperty(this, additionalPath))}
class UserNamespace_Map<T, K>(previous: KPropertyPath<T, *>?, property: KProperty1<*, Map<K,
UserNamespace>?>) : KMapPropertyPath<T, K, UserNamespace?,
UserNamespace_<T>>(previous,property) {
val login: KPropertyPath<T, String?>
get() = KPropertyPath(this,__Login)
val namespace: KPropertyPath<T, String?>
get() = KPropertyPath(this,__Namespace)
val owner: KPropertyPath<T, Boolean?>
get() = KPropertyPath(this,__Owner)
val current: KPropertyPath<T, Boolean?>
get() = KPropertyPath(this,__Current)
@Suppress("UNCHECKED_CAST")
override fun memberWithAdditionalPath(additionalPath: String): UserNamespace_<T> =
UserNamespace_(this, customProperty(this, additionalPath))}
| 163 | Kotlin | 127 | 475 | 890f69960997ae9146747d082d808d92ee407fcb | 3,141 | tock | Apache License 2.0 |
objects/src/commonMain/kotlin/ru/krindra/vkkt/objects/groups/GroupsAddressesInfo.kt | krindra | 780,080,411 | false | {"Kotlin": 1336107} | package ru.krindra.vkkt.objects.groups
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
*
* @param isEnabled Information whether addresses is enabled
* @param mainAddressId Main address id for group
* @param mainAddress Main address
* @param count Count of addresses
*/
@Serializable
data class GroupsAddressesInfo (
@SerialName("count") val count: Int? = null,
@SerialName("is_enabled") val isEnabled: Boolean,
@SerialName("main_address_id") val mainAddressId: Int? = null,
@SerialName("main_address") val mainAddress: GroupsAddress? = null,
)
| 0 | Kotlin | 0 | 1 | 58407ea02fc9d971f86702f3b822b33df65dd3be | 606 | VKKT | MIT License |
ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/application/Application.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.application
import kotlinx.coroutines.*
import org.slf4j.*
import kotlin.coroutines.*
/**
* Represents configured and running web application, capable of handling requests.
* It is also the application coroutine scope that is cancelled immediately at application stop so useful
* for launching background coroutines.
*
* @param environment Instance of [ApplicationEnvironment] describing environment this application runs in
*/
public class Application(
override val environment: ApplicationEnvironment
) : ApplicationCallPipeline(environment.developmentMode, environment), CoroutineScope {
private val applicationJob = SupervisorJob(environment.parentCoroutineContext[Job])
override val coroutineContext: CoroutineContext = environment.parentCoroutineContext + applicationJob
/**
* Called by [ApplicationEngine] when [Application] is terminated
*/
@Suppress("DEPRECATION")
public fun dispose() {
applicationJob.cancel()
uninstallAllPlugins()
}
}
/**
* Convenience property to access log from application
*/
public val Application.log: Logger get() = environment.log
| 302 | null | 976 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 1,286 | ktor | Apache License 2.0 |
aws-auth-cognito/src/test/java/com/amplifyframework/auth/cognito/actions/SetupTOTPCognitoActionsTest.kt | aws-amplify | 177,009,933 | false | {"Java": 5271326, "Kotlin": 3564857, "Shell": 28043, "Groovy": 11755, "Python": 3681, "Ruby": 1874} | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amplifyframework.auth.cognito.actions
import androidx.test.core.app.ApplicationProvider
import aws.sdk.kotlin.services.cognitoidentityprovider.CognitoIdentityProviderClient
import aws.sdk.kotlin.services.cognitoidentityprovider.model.AssociateSoftwareTokenRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.AssociateSoftwareTokenResponse
import aws.sdk.kotlin.services.cognitoidentityprovider.model.CodeMismatchException
import aws.sdk.kotlin.services.cognitoidentityprovider.model.SoftwareTokenMfaNotFoundException
import aws.sdk.kotlin.services.cognitoidentityprovider.model.VerifySoftwareTokenResponse
import aws.sdk.kotlin.services.cognitoidentityprovider.model.VerifySoftwareTokenResponseType
import aws.sdk.kotlin.services.cognitoidentityprovider.verifySoftwareToken
import com.amplifyframework.auth.cognito.AWSCognitoAuthService
import com.amplifyframework.auth.cognito.AuthConfiguration
import com.amplifyframework.auth.cognito.AuthEnvironment
import com.amplifyframework.auth.cognito.StoreClientBehavior
import com.amplifyframework.logging.Logger
import com.amplifyframework.statemachine.EventDispatcher
import com.amplifyframework.statemachine.StateMachineEvent
import com.amplifyframework.statemachine.codegen.data.SignInTOTPSetupData
import com.amplifyframework.statemachine.codegen.events.SetupTOTPEvent
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import kotlin.test.assertEquals
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class SetupTOTPCognitoActionsTest {
private val configuration = mockk<AuthConfiguration>()
private val cognitoAuthService = mockk<AWSCognitoAuthService>()
private val credentialStoreClient = mockk<StoreClientBehavior>()
private val logger = mockk<Logger>(relaxed = true)
private val cognitoIdentityProviderClientMock = mockk<CognitoIdentityProviderClient>()
private val dispatcher = mockk<EventDispatcher>()
private val capturedEvent = slot<StateMachineEvent>()
private lateinit var authEnvironment: AuthEnvironment
@Before
fun setup() {
every { dispatcher.send(capture(capturedEvent)) }.answers { }
every { cognitoAuthService.cognitoIdentityProviderClient }.answers { cognitoIdentityProviderClientMock }
authEnvironment = AuthEnvironment(
ApplicationProvider.getApplicationContext(),
configuration,
cognitoAuthService,
credentialStoreClient,
null,
null,
logger
)
}
@Test
fun `initiateTOTPSetup send waitForAnswer on success`() = runTest {
val secretCode = "SECRET_CODE"
val session = "SESSION"
val username = "USERNAME"
coEvery {
cognitoIdentityProviderClientMock.associateSoftwareToken(any())
}.answers {
AssociateSoftwareTokenResponse.invoke {
this.secretCode = secretCode
this.session = session
}
}
val initiateAction = SetupTOTPCognitoActions.initiateTOTPSetup(
SetupTOTPEvent.EventType.SetupTOTP(
SignInTOTPSetupData("", "SESSION", "USERNAME")
)
)
initiateAction.execute(dispatcher, authEnvironment)
val expectedEvent = SetupTOTPEvent(
SetupTOTPEvent.EventType.WaitForAnswer(SignInTOTPSetupData(secretCode, session, username))
)
assertEquals(
expectedEvent.type,
capturedEvent.captured.type
)
assertEquals(
secretCode,
(
(capturedEvent.captured as SetupTOTPEvent).eventType as SetupTOTPEvent.EventType.WaitForAnswer
).totpSetupDetails.secretCode
)
}
@Test
fun `initiateTOTPSetup send waitForAnswer on failure`() = runTest {
val session = "SESSION"
val serviceException = SoftwareTokenMfaNotFoundException {
message = "TOTP is not enabled"
}
coEvery {
cognitoIdentityProviderClientMock.associateSoftwareToken(
AssociateSoftwareTokenRequest.invoke {
this.session = session
}
)
}.answers {
throw serviceException
}
val initiateAction = SetupTOTPCognitoActions.initiateTOTPSetup(
SetupTOTPEvent.EventType.SetupTOTP(
SignInTOTPSetupData("", "SESSION", "USERNAME")
)
)
initiateAction.execute(dispatcher, authEnvironment)
val expectedEvent = SetupTOTPEvent(
SetupTOTPEvent.EventType.ThrowAuthError(serviceException, "USERNAME", "SESSION")
)
assertEquals(
expectedEvent.type,
capturedEvent.captured.type
)
assertEquals(
serviceException,
((capturedEvent.captured as SetupTOTPEvent).eventType as SetupTOTPEvent.EventType.ThrowAuthError).exception
)
}
@Test
fun `verifyChallengeAnswer send RespondToAuthChallenge on success`() = runTest {
val answer = "123456"
val session = "SESSION"
val username = "USERNAME"
val friendlyDeviceName = "TEST_DEVICE"
coEvery {
cognitoIdentityProviderClientMock.verifySoftwareToken {
this.userCode = answer
this.session = session
this.friendlyDeviceName = friendlyDeviceName
}
}.answers {
VerifySoftwareTokenResponse.invoke {
this.session = session
this.status = VerifySoftwareTokenResponseType.Success
}
}
val expectedEvent = SetupTOTPEvent(
SetupTOTPEvent.EventType.RespondToAuthChallenge(username, session)
)
val verifyChallengeAnswerAction = SetupTOTPCognitoActions.verifyChallengeAnswer(
SetupTOTPEvent.EventType.VerifyChallengeAnswer(
answer,
username,
session,
friendlyDeviceName
)
)
verifyChallengeAnswerAction.execute(dispatcher, authEnvironment)
assertEquals(
expectedEvent.type,
capturedEvent.captured.type
)
assertEquals(
session,
(
(capturedEvent.captured as SetupTOTPEvent).eventType as SetupTOTPEvent.EventType.RespondToAuthChallenge
).session
)
}
@Test
fun `verifyChallengeAnswer send RespondToAuthChallenge on Error`() = runTest {
val answer = "123456"
val session = "SESSION"
val username = "USERNAME"
val friendlyDeviceName = "TEST_DEVICE"
coEvery {
cognitoIdentityProviderClientMock.verifySoftwareToken {
this.userCode = answer
this.session = session
this.friendlyDeviceName = friendlyDeviceName
}
}.answers {
VerifySoftwareTokenResponse.invoke {
this.session = session
this.status = VerifySoftwareTokenResponseType.Error
}
}
val expectedEvent = SetupTOTPEvent(
SetupTOTPEvent.EventType.ThrowAuthError(
Exception("An unknown service error has occurred"),
"USERNAME",
"SESSION"
)
)
val verifyChallengeAnswerAction = SetupTOTPCognitoActions.verifyChallengeAnswer(
SetupTOTPEvent.EventType.VerifyChallengeAnswer(
answer,
username,
session,
friendlyDeviceName
)
)
verifyChallengeAnswerAction.execute(dispatcher, authEnvironment)
assertEquals(
expectedEvent.type,
capturedEvent.captured.type
)
assertEquals(
(expectedEvent.eventType as SetupTOTPEvent.EventType.ThrowAuthError).exception.message,
(
(capturedEvent.captured as SetupTOTPEvent).eventType as SetupTOTPEvent.EventType.ThrowAuthError
).exception.message
)
}
@Test
fun `verifyChallengeAnswer send RespondToAuthChallenge on exception`() = runTest {
val answer = "123456"
val session = "SESSION"
val username = "USERNAME"
val friendlyDeviceName = "TEST_DEVICE"
val serviceException = CodeMismatchException {
message = "Invalid Code"
}
coEvery {
cognitoIdentityProviderClientMock.verifySoftwareToken {
this.userCode = answer
this.session = session
this.friendlyDeviceName = friendlyDeviceName
}
}.answers {
throw serviceException
}
val expectedEvent = SetupTOTPEvent(
SetupTOTPEvent.EventType.ThrowAuthError(serviceException, "USERNAME", "SESSION")
)
val verifyChallengeAnswerAction = SetupTOTPCognitoActions.verifyChallengeAnswer(
SetupTOTPEvent.EventType.VerifyChallengeAnswer(
answer,
username,
session,
friendlyDeviceName
)
)
verifyChallengeAnswerAction.execute(dispatcher, authEnvironment)
assertEquals(
expectedEvent.type,
capturedEvent.captured.type
)
assertEquals(
(expectedEvent.eventType as SetupTOTPEvent.EventType.ThrowAuthError).exception.message,
(
(capturedEvent.captured as SetupTOTPEvent).eventType as SetupTOTPEvent.EventType.ThrowAuthError
).exception.message
)
}
}
| 99 | Java | 115 | 245 | 14c71f38f052a964b96d7abaff6e157bd21a64d8 | 10,467 | amplify-android | Apache License 2.0 |
Retos/Reto #0 - EL FAMOSO FIZZ BUZZ [Fácil]/kotlin/steepsalvadorman.kt | mouredev | 581,049,695 | false | {"Python": 4194087, "JavaScript": 1590517, "Java": 1408944, "C#": 782329, "Kotlin": 533858, "TypeScript": 479964, "Rust": 357628, "Go": 322940, "PHP": 288620, "Swift": 278290, "C": 223896, "Jupyter Notebook": 221090, "C++": 175187, "Dart": 159755, "Ruby": 71132, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 33508, "Haskell": 27994, "Shell": 27979, "R": 19771, "Lua": 16964, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12839, "F#": 12816, "Pascal": 12673, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Carbon": 2611, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1394, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "Haxe": 112, "HolyC": 110, "OpenEdge ABL": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "TeX": 72, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Mojo": 37, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | /*
* Escribe un programa que muestre por consola (con un print) los
* números de 1 a 100 (ambos incluidos y con un salto de línea entre
* cada impresión), sustituyendo los siguientes:
* - Múltiplos de 3 por la palabra "fizz".
* - Múltiplos de 5 por la palabra "buzz".
* - Múltiplos de 3 y de 5 a la vez por la palabra "fizzbuzz".
*/
fun main() {
for (i in 1..100) {
if ((i % 3 == 0) && (i % 5 == 0)) {
println("fizzbuzz")
} else if (i % 3 == 0) {
println("fizz")
} else if (i % 5 == 0) {
println("buzz")
} else {
println(i)
}
}
} | 1 | Python | 2974 | 5,192 | f8c44ac12756b14a32abf57cbf4e0cd06ad58088 | 633 | retos-programacion-2023 | Apache License 2.0 |
app/src/main/java/com/example/wordle_and/MainActivity.kt | ba-00001 | 766,139,279 | false | {"Kotlin": 6390} | package com.example.wordle_and
import android.content.Intent
import android.os.Bundle
import android.text.Spanned
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
class MainActivity : AppCompatActivity() {
// Word to be guessed
private val fourLetterWords = "Star"
// Variables to track game state
private lateinit var targetWord: String
private var remainingGuesses = 3
private var attemptCount = 1
// TextViews to display information
private lateinit var textViewTargetWord: TextView
private lateinit var textViewAttemptHistory: TextView
private lateinit var textViewGuessCheckHistory: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize TextViews
textViewTargetWord = findViewById(R.id.textViewTargetWord)
textViewAttemptHistory = findViewById(R.id.textViewAttemptHistory)
textViewGuessCheckHistory = findViewById(R.id.textViewGuessCheckHistory)
// Initialize the game
initializeGame()
}
// Function to initialize the game
private fun initializeGame() {
targetWord = getRandomFourLetterWord()
remainingGuesses = 3
attemptCount = 1
// Reset UI
findViewById<EditText>(R.id.editTextGuess).text.clear()
findViewById<Button>(R.id.buttonSubmit).isEnabled = true
findViewById<Button>(R.id.buttonReset).isEnabled = false
// Clear TextViews
textViewTargetWord.text = ""
textViewAttemptHistory.text = ""
textViewGuessCheckHistory.text = ""
}
// Function called when the user submits a guess
fun onGuessSubmit(view: View) {
val guessEditText = findViewById<EditText>(R.id.editTextGuess)
val guess = guessEditText.text.toString().uppercase()
// Check if the guess is valid
if (guess.length != 4 || !guess.isAllAlphabetic()) {
// Display error for invalid input
guessEditText.error = "Invalid guess! Must be a 4-letter word."
return
}
// Check the guess and get the result
val result = checkGuess(guess)
// Update TextViews
textViewAttemptHistory.append("Attempt #$attemptCount: $guess\n")
textViewGuessCheckHistory.append("Guess Check #$attemptCount: ")
textViewGuessCheckHistory.append(result)
textViewGuessCheckHistory.append("\n")
// Display a Toast for the current attempt
val toastMessage = "Attempt #$attemptCount: Guess: $guess"
showToast(toastMessage)
remainingGuesses--
attemptCount++
// Check if the game is over
if (remainingGuesses == 0 || (guess == targetWord)) {
// Disable submit button after 3 guesses
findViewById<Button>(R.id.buttonSubmit).isEnabled = false
findViewById<Button>(R.id.buttonReset).isEnabled = true
// Display the target word
textViewTargetWord.text = "Target Word: $targetWord"
}
}
// Function to display a Toast message
private fun showToast(message: String) {
val toast = Toast.makeText(this, message, Toast.LENGTH_SHORT)
toast.show()
}
// Function called when the user clicks the Reset button
fun onResetClick(view: View) {
// Initialize the game for a new round
initializeGame()
}
// Extension function to check if a string contains only alphabetic characters
fun String.isAllAlphabetic(): Boolean {
return all { it.isLetter() }
}
// Function to get a random 4-letter word from the predefined list
private fun getRandomFourLetterWord(): String {
val allWords = fourLetterWords.split(",")
val randomNumber = (0 until allWords.size).shuffled().first()
return allWords[randomNumber].uppercase()
}
// Function to check the user's guess and return a Spanned result
private fun checkGuess(guess: String): Spanned {
val coloredLetters = SpannableStringBuilder()
for (i in 0 until 4) {
val currentLetter = guess[i]
when {
currentLetter == targetWord[i] -> {
// Letter matches in position, set color to green
coloredLetters.append(currentLetter.toString(), ForegroundColorSpan(Color.GREEN), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
currentLetter in targetWord -> {
// Letter matches, but in the wrong position, set color to red
coloredLetters.append(currentLetter.toString(), ForegroundColorSpan(Color.RED), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
else -> {
// Letter doesn't match, set color to grey
coloredLetters.append(currentLetter.toString(), ForegroundColorSpan(Color.GRAY), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
return coloredLetters
}
}
| 0 | Kotlin | 0 | 0 | 21644063f7c60b2236a0a0eb20f4dda1279eae1a | 5,373 | WORDLE_AND | Apache License 2.0 |
server_undertow/src/test/kotlin/com/hexagonkt/server/undertow/HiWorld.kt | ozzpy | 126,635,042 | true | {"Kotlin": 316457, "FreeMarker": 16374, "CSS": 8405, "Groovy": 2183, "HTML": 1732, "JavaScript": 1280} | package com.hexagonkt.server.undertow
fun main(vararg args: String) {
serve {
get("/bye") { "Good Bye!" }
get { "Hi!" }
}
}
| 0 | Kotlin | 0 | 0 | 9c1a165e1ab2a4e83504bc251b013b2c5b08ab88 | 149 | hexagon | MIT License |
lib/src/main/java/com/smileidentity/viewmodel/document/OrchestratedDocumentViewModel.kt | smileidentity | 576,345,086 | false | null | package com.smileidentity.viewmodel.document
import android.os.Parcelable
import androidx.annotation.StringRes
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.smileidentity.R
import com.smileidentity.SmileID
import com.smileidentity.SmileIDCrashReporting
import com.smileidentity.compose.components.ProcessingState
import com.smileidentity.models.AuthenticationRequest
import com.smileidentity.models.DocumentCaptureFlow
import com.smileidentity.models.IdInfo
import com.smileidentity.models.JobType
import com.smileidentity.models.PartnerParams
import com.smileidentity.models.PrepUploadRequest
import com.smileidentity.models.UploadRequest
import com.smileidentity.networking.asDocumentBackImage
import com.smileidentity.networking.asDocumentFrontImage
import com.smileidentity.networking.asLivenessImage
import com.smileidentity.networking.asSelfieImage
import com.smileidentity.results.DocumentVerificationResult
import com.smileidentity.results.EnhancedDocumentVerificationResult
import com.smileidentity.results.SmartSelfieResult
import com.smileidentity.results.SmileIDCallback
import com.smileidentity.results.SmileIDResult
import com.smileidentity.util.FileType
import com.smileidentity.util.createAuthenticationRequestFile
import com.smileidentity.util.createPrepUploadFile
import com.smileidentity.util.createUploadRequestFile
import com.smileidentity.util.getExceptionHandler
import com.smileidentity.util.getFileByType
import com.smileidentity.util.getFilesByType
import com.smileidentity.util.handleOfflineJobFailure
import com.smileidentity.util.isNetworkFailure
import com.smileidentity.util.moveJobToSubmitted
import io.sentry.Breadcrumb
import io.sentry.SentryLevel
import java.io.File
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import timber.log.Timber
internal data class OrchestratedDocumentUiState(
val currentStep: DocumentCaptureFlow = DocumentCaptureFlow.FrontDocumentCapture,
@StringRes val errorMessage: Int? = null,
)
/**
* @param selfieFile The selfie image file to use for authentication. If null, selfie capture will
* be performed
*/
internal abstract class OrchestratedDocumentViewModel<T : Parcelable>(
private val jobType: JobType,
private val userId: String,
protected val jobId: String,
private val allowNewEnroll: Boolean,
private val countryCode: String,
private val documentType: String? = null,
private val captureBothSides: Boolean,
protected var selfieFile: File? = null,
private var extraPartnerParams: ImmutableMap<String, String> = persistentMapOf(),
) : ViewModel() {
private val _uiState = MutableStateFlow(OrchestratedDocumentUiState())
val uiState = _uiState.asStateFlow()
var result: SmileIDResult<T> = SmileIDResult.Error(
IllegalStateException("Document Capture incomplete"),
)
private var documentFrontFile: File? = null
private var documentBackFile: File? = null
private var livenessFiles: List<File>? = null
private var stepToRetry: DocumentCaptureFlow? = null
fun onDocumentFrontCaptureSuccess(documentImageFile: File) {
documentFrontFile = documentImageFile
if (captureBothSides) {
_uiState.update {
it.copy(currentStep = DocumentCaptureFlow.BackDocumentCapture, errorMessage = null)
}
} else if (selfieFile == null) {
_uiState.update {
it.copy(currentStep = DocumentCaptureFlow.SelfieCapture, errorMessage = null)
}
} else {
submitJob()
}
}
fun onDocumentBackSkip() {
if (selfieFile == null) {
_uiState.update {
it.copy(currentStep = DocumentCaptureFlow.SelfieCapture, errorMessage = null)
}
} else {
submitJob()
}
}
fun onDocumentBackCaptureSuccess(documentImageFile: File) {
documentBackFile = documentImageFile
if (selfieFile == null) {
_uiState.update {
it.copy(currentStep = DocumentCaptureFlow.SelfieCapture, errorMessage = null)
}
} else {
submitJob()
}
}
fun onSelfieCaptureSuccess(it: SmileIDResult.Success<SmartSelfieResult>) {
selfieFile = it.data.selfieFile
livenessFiles = it.data.livenessFiles
submitJob()
}
abstract fun saveResult(
selfieImage: File,
documentFrontFile: File,
documentBackFile: File?,
livenessFiles: List<File>?,
didSubmitJob: Boolean,
)
private fun submitJob() {
val documentFrontFile = documentFrontFile
?: throw IllegalStateException("documentFrontFile is null")
_uiState.update {
it.copy(currentStep = DocumentCaptureFlow.ProcessingScreen(ProcessingState.InProgress))
}
viewModelScope.launch(getExceptionHandler(::onError)) {
val authRequest = AuthenticationRequest(
jobType = jobType,
enrollment = false,
userId = userId,
jobId = jobId,
)
val frontImageInfo = documentFrontFile.asDocumentFrontImage()
val backImageInfo = documentBackFile?.asDocumentBackImage()
val selfieImageInfo = selfieFile?.asSelfieImage() ?: throw IllegalStateException(
"Selfie file is null",
)
// Liveness files will be null when the partner bypasses our Selfie capture with a file
val livenessImageInfo = livenessFiles.orEmpty().map { it.asLivenessImage() }
val uploadRequest = UploadRequest(
images = listOfNotNull(
frontImageInfo,
backImageInfo,
selfieImageInfo,
) + livenessImageInfo,
idInfo = IdInfo(countryCode, documentType),
)
if (SmileID.allowOfflineMode) {
createAuthenticationRequestFile(jobId, authRequest)
createPrepUploadFile(
jobId,
PrepUploadRequest(
partnerParams = PartnerParams(
jobType = jobType,
jobId = jobId,
userId = userId,
extras = extraPartnerParams,
),
allowNewEnroll = allowNewEnroll.toString(),
timestamp = "",
signature = "",
),
)
createUploadRequestFile(
jobId,
uploadRequest,
)
}
val authResponse = SmileID.api.authenticate(authRequest)
val prepUploadRequest = PrepUploadRequest(
partnerParams = authResponse.partnerParams.copy(extras = extraPartnerParams),
// TODO : Michael will change this to boolean
allowNewEnroll = allowNewEnroll.toString(),
signature = authResponse.signature,
timestamp = authResponse.timestamp,
)
val prepUploadResponse = SmileID.api.prepUpload(prepUploadRequest)
SmileID.api.upload(prepUploadResponse.uploadUrl, uploadRequest)
Timber.d("Upload finished")
sendResult(documentFrontFile, documentBackFile, livenessFiles)
}
}
private fun sendResult(
documentFrontFile: File,
documentBackFile: File? = null,
livenessFiles: List<File>? = null,
) {
var selfieFileResult: File = selfieFile ?: run {
Timber.w("Selfie file not found for job ID: $jobId")
throw Exception("Selfie file not found for job ID: $jobId")
}
var livenessFilesResult = livenessFiles
var documentFrontFileResult = documentFrontFile
var documentBackFileResult = documentBackFile
val copySuccess = moveJobToSubmitted(jobId)
if (copySuccess) {
selfieFileResult = getFileByType(jobId, FileType.SELFIE) ?: run {
Timber.w("Selfie file not found for job ID: $jobId")
throw IllegalStateException("Selfie file not found for job ID: $jobId")
}
livenessFilesResult = getFilesByType(jobId, FileType.LIVENESS)
documentFrontFileResult = getFileByType(jobId, FileType.DOCUMENT_FRONT) ?: run {
Timber.w("Document front file not found for job ID: $jobId")
throw IllegalStateException("Document front found for job ID: $jobId")
}
documentBackFileResult = getFileByType(jobId, FileType.DOCUMENT_BACK)
} else {
Timber.w("Failed to move job $jobId to complete")
SmileIDCrashReporting.hub.addBreadcrumb(
Breadcrumb().apply {
category = "Offline Mode"
message = "Failed to move job $jobId to complete"
level = SentryLevel.INFO
},
)
}
saveResult(
selfieImage = selfieFileResult,
documentFrontFile = documentFrontFileResult,
documentBackFile = documentBackFileResult,
livenessFilesResult,
didSubmitJob = true,
)
_uiState.update {
it.copy(currentStep = DocumentCaptureFlow.ProcessingScreen(ProcessingState.Success))
}
}
/**
* Trigger the display of the Error dialog
*/
fun onError(throwable: Throwable) {
handleOfflineJobFailure(jobId, throwable)
stepToRetry = uiState.value.currentStep
_uiState.update {
it.copy(
currentStep = DocumentCaptureFlow.ProcessingScreen(ProcessingState.Error),
errorMessage = R.string.si_processing_error_subtitle,
)
}
if (SmileID.allowOfflineMode && isNetworkFailure(throwable)) {
_uiState.update {
it.copy(
currentStep = DocumentCaptureFlow.ProcessingScreen(ProcessingState.Success),
errorMessage = R.string.si_offline_message,
)
}
saveResult(
selfieImage = selfieFile ?: throw IllegalStateException("Selfie file is null"),
documentFrontFile = documentFrontFile ?: throw IllegalStateException(
"Document front file is null",
),
documentBackFile = documentBackFile,
livenessFiles,
didSubmitJob = false,
)
} else {
result = SmileIDResult.Error(throwable)
_uiState.update {
it.copy(
currentStep = DocumentCaptureFlow.ProcessingScreen(ProcessingState.Error),
errorMessage = R.string.si_processing_error_subtitle,
)
}
}
}
/**
* If [stepToRetry] is ProcessingScreen, we're retrying a network issue, so we need to kick off
* the resubmission manually. Otherwise, we're retrying a capture error, so we just need to
* reset the UI state
*/
fun onRetry() {
// The step to retry is the one that failed, which should have been saved in onError.
// onError sets the current step to ProcessingScreen Error.
val step = stepToRetry
stepToRetry = null
step?.let { stepToRetry ->
_uiState.update { it.copy(currentStep = stepToRetry, errorMessage = null) }
if (stepToRetry is DocumentCaptureFlow.ProcessingScreen) {
submitJob()
}
}
}
fun onFinished(callback: SmileIDCallback<T>) = callback(result)
}
internal class DocumentVerificationViewModel(
jobType: JobType = JobType.DocumentVerification,
userId: String,
jobId: String,
allowNewEnroll: Boolean,
countryCode: String,
documentType: String? = null,
captureBothSides: Boolean,
selfieFile: File? = null,
extraPartnerParams: ImmutableMap<String, String> = persistentMapOf(),
) : OrchestratedDocumentViewModel<DocumentVerificationResult>(
jobType = jobType,
userId = userId,
jobId = jobId,
allowNewEnroll = allowNewEnroll,
countryCode = countryCode,
documentType = documentType,
captureBothSides = captureBothSides,
selfieFile = selfieFile,
extraPartnerParams = extraPartnerParams,
) {
override fun saveResult(
selfieImage: File,
documentFrontFile: File,
documentBackFile: File?,
livenessFiles: List<File>?,
didSubmitJob: Boolean,
) {
result = SmileIDResult.Success(
DocumentVerificationResult(
selfieFile = selfieImage,
documentFrontFile = documentFrontFile,
documentBackFile = documentBackFile,
didSubmitDocumentVerificationJob = didSubmitJob,
),
)
}
}
internal class EnhancedDocumentVerificationViewModel(
jobType: JobType = JobType.EnhancedDocumentVerification,
userId: String,
jobId: String,
allowNewEnroll: Boolean,
countryCode: String,
documentType: String? = null,
captureBothSides: Boolean,
selfieFile: File? = null,
extraPartnerParams: ImmutableMap<String, String> = persistentMapOf(),
) : OrchestratedDocumentViewModel<EnhancedDocumentVerificationResult>(
jobType = jobType,
userId = userId,
jobId = jobId,
allowNewEnroll = allowNewEnroll,
countryCode = countryCode,
documentType = documentType,
captureBothSides = captureBothSides,
selfieFile = selfieFile,
extraPartnerParams = extraPartnerParams,
) {
override fun saveResult(
selfieImage: File,
documentFrontFile: File,
documentBackFile: File?,
livenessFiles: List<File>?,
didSubmitJob: Boolean,
) {
result = SmileIDResult.Success(
EnhancedDocumentVerificationResult(
selfieImage,
documentFrontFile,
livenessFiles,
documentBackFile,
didSubmitEnhancedDocVJob = didSubmitJob,
),
)
}
}
| 6 | null | 5 | 16 | 78cba4e47eeff1df5079936cce8193321e2891b2 | 14,505 | android | MIT License |
plugin/src/main/java/io/github/timortel/kotlin_multiplatform_grpc_plugin/generate_mulitplatform_sources/generators/proto3_ios_file_writer.kt | TimOrtel | 503,391,702 | false | null | package io.github.timortel.kotlin_multiplatform_grpc_plugin.generate_mulitplatform_sources.generators
import io.github.timortel.kotlin_multiplatform_grpc_plugin.generate_mulitplatform_sources.content.ProtoFile
import io.github.timortel.kotlin_multiplatform_grpc_plugin.generate_mulitplatform_sources.generators.dsl.IosJvmDslBuilder
import io.github.timortel.kotlin_multiplatform_grpc_plugin.generate_mulitplatform_sources.generators.proto_file.IOSProtoFileWriter
import java.io.File
fun writeIOSFiles(protoFile: ProtoFile, iosOutputDir: File) {
IOSProtoFileWriter(protoFile).writeFile(iosOutputDir)
//JVM helper
// FileSpec
// .builder(protoFile.pkg, protoFile.fileNameWithoutExtension + "_jvm_helper")
// .apply {
// JvmCommonFunctionGenerator(this).generateCommonGetter(protoFile.messages)
// }
// .build()
// .writeTo(jvmOutputDir)
writeDSLBuilder(protoFile, IosJvmDslBuilder, iosOutputDir)
} | 6 | null | 14 | 62 | c2ab8b52c36cade78ba8cc5be1123ff006f715a2 | 960 | GRPC-Kotlin-Multiplatform | Apache License 2.0 |
presentation/base/src/main/java/com/ihorvitruk/telegramclient/presentation/base/BaseActivity.kt | ihorvitruk | 116,034,141 | false | null | package com.ihorvitruk.telegramclient.presentation.base
import android.support.v7.app.AppCompatActivity
import java.util.*
abstract class BaseActivity : AppCompatActivity() {
private val viewModelStack: Stack<BaseViewModel<*>> = Stack()
protected fun <VM : BaseViewModel<*>> replaceView(view: BaseView<*, VM>, viewModel: VM) {
while (viewModelStack.isNotEmpty()) {
viewModelStack.pop().onDestroy()
}
setContentView(view)
viewModelStack.push(viewModel).onCreate()
}
protected fun <VM : BaseViewModel<*>> addView(view: BaseView<*, VM>, viewModel: VM) {
//TODO implement using FrameLayout#addView
viewModelStack.push(viewModel).onCreate()
}
} | 0 | Java | 10 | 26 | 0e80cc5706ef6921b2594d5de25f9ea8a04f406b | 724 | Telegram-Client | Apache License 2.0 |
tests/src/commonMain/kotlin/app/thelema/test/gl/UniformBufferBaseTest.kt | zeganstyl | 275,550,896 | false | null | package app.thelema.test.gl
import app.thelema.app.APP
import app.thelema.data.DATA
import app.thelema.gl.*
import app.thelema.math.Mat4
import app.thelema.math.Vec2
import app.thelema.test.Test
class UniformBufferBaseTest: Test {
override fun testMain() {
val vertexBufferBytes = DATA.bytes(3 * 2 * 4).apply {
putFloats(
0f, 0f,
0f, 1f,
1f, 0f
)
rewind()
}
val vertexBuffer = GL.glGenBuffer()
GL.glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)
GL.glBufferData(GL_ARRAY_BUFFER, vertexBufferBytes.limit, vertexBufferBytes, GL_STATIC_DRAW)
val indexBufferBytes = DATA.bytes(3 * 2).apply {
putShorts(0, 1, 2)
rewind()
}
val indexBuffer = GL.glGenBuffer()
GL.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer)
GL.glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferBytes.limit, indexBufferBytes, GL_STATIC_DRAW)
val uniformBufferBytes = DATA.bytes(8 * 4).apply {
// put offset
val vec = Vec2(-0.5f, -0.5f)
putVec2(vec.x, vec.y)
position += 8 // vec2 must be aligned as vec4 for std140
// put color
putVec4(0f, 1f, 0.5f, 1f)
rewind()
}
val uniformBuffer = GL.glGenBuffer()
GL.glBindBuffer(GL_UNIFORM_BUFFER, uniformBuffer)
GL.glBufferData(GL_UNIFORM_BUFFER, uniformBufferBytes.limit, uniformBufferBytes, GL_STATIC_DRAW)
val vao = GL.glGenVertexArrays()
val glslVer = if (GL.isGLES) "300 es" else "330"
val positionLocation = 0
val vertexShaderCode = """
#version $glslVer
layout (location = $positionLocation) in vec2 POSITION;
out vec2 uv;
layout (std140) uniform Uniforms {
vec2 offset;
vec4 color;
};
void main() {
uv = POSITION;
gl_Position = vec4(POSITION + offset, 0.0, 1.0);
}
"""
val fragmentShaderCode = """
#version $glslVer
in vec2 uv;
out vec4 FragColor;
layout (std140) uniform Uniforms {
vec2 offset;
vec4 color;
};
void main() {
FragColor = color;
}
"""
val vertexShader = GL.glCreateShader(GL_VERTEX_SHADER)
GL.glShaderSource(vertexShader, vertexShaderCode)
GL.glCompileShader(vertexShader)
println(GL.glGetShaderInfoLog(vertexShader).ifEmpty { "Vertex shader OK" })
val fragmentShader = GL.glCreateShader(GL_FRAGMENT_SHADER)
GL.glShaderSource(fragmentShader, fragmentShaderCode)
GL.glCompileShader(fragmentShader)
println(GL.glGetShaderInfoLog(fragmentShader).ifEmpty { "Fragment shader OK" })
val shaderProgram = GL.glCreateProgram()
GL.glAttachShader(shaderProgram, vertexShader)
GL.glAttachShader(shaderProgram, fragmentShader)
GL.glLinkProgram(shaderProgram)
println(GL.glGetProgramInfoLog(shaderProgram).ifEmpty { "Shader program OK" })
val ubIndex = GL.glGetUniformBlockIndex(shaderProgram, "Uniforms")
val uboBindPoint = 0
GL.glUniformBlockBinding(shaderProgram, ubIndex, uboBindPoint)
GL.glBindBufferBase(GL_UNIFORM_BUFFER, uboBindPoint, uniformBuffer)
GL.glBindVertexArray(vao)
GL.glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)
GL.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer)
GL.glEnableVertexAttribArray(positionLocation)
GL.glVertexAttribPointer(positionLocation, 2, GL_FLOAT, false, 2 * 4, 0)
GL.glBindVertexArray(0)
APP.onRender = {
GL.glUseProgram(shaderProgram)
GL.glBindVertexArray(vao)
GL.glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, 0)
GL.glBindVertexArray(0)
}
}
} | 3 | Kotlin | 5 | 61 | 8e2943b6d2de3376ce338025b58ff31c14097caf | 3,758 | thelema-engine | Apache License 2.0 |
Android/app/src/main/java/ipn/mx/androidkleene/MainActivity.kt | Roberto-coder | 860,537,698 | false | {"Kotlin": 13031, "Java": 11792, "HTML": 2993} | package ipn.mx.androidkleene
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import ipn.mx.androidkleene.ui.theme.AndroidKleeneTheme
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
/**
* MainActivity es la actividad principal de la aplicación que contiene
* la interfaz de usuario y la lógica para abrir una página web en el navegador y cerrar la aplicación.
*/
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
AndroidKleeneTheme {
Surface(modifier = Modifier.fillMaxSize()) {
RequestScreen(
onOpenServer = { openServerPage() }, // Pasamos la función para abrir el navegador
onCloseApp = { finish() } // Pasamos la función para cerrar la app
)
}
}
}
}
/**
* Abre la página del servidor en el navegador web predeterminado.
*/
private fun openServerPage() {
val url = "http://127.0.0.1:8080" // Cambiar URL si es necesario
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
}
/**
* RequestScreen es una función composable que representa la pantalla principal de la aplicación.
* Incluye campos para ingresar un número, seleccionar una operación y mostrar el resultado.
*
* @param onOpenServer Función a ejecutar cuando se presiona el botón para abrir el servidor.
* @param onCloseApp Función a ejecutar cuando se presiona el botón para cerrar la aplicación.
*/
@Composable
fun RequestScreen(onOpenServer: () -> Unit, onCloseApp: () -> Unit) {
var inputValue by remember { mutableStateOf(TextFieldValue("")) }
var resultText by remember { mutableStateOf("Resultado aparecerá aquí") }
var selectedOption by remember { mutableStateOf("cerradura") } // Opción seleccionada: cerradura o estrella
val scrollState = rememberScrollState()
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center
) {
// Botones para abrir el servidor o cerrar la aplicación
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
// Botón para abrir navegador
Button(
onClick = onOpenServer,
modifier = Modifier.weight(1f),
colors = ButtonDefaults.buttonColors(
containerColor = Color.DarkGray,
contentColor = Color.White
)
) {
Text("Abrir Navegador")
}
Spacer(modifier = Modifier.width(16.dp)) // Espacio entre los botones
// Botón para cerrar la aplicación
Button(
onClick = { onCloseApp() },
modifier = Modifier.weight(1f),
colors = ButtonDefaults.buttonColors(
containerColor = Color.Red,
contentColor = Color.Black
)
) {
Text("Cerrar App")
}
}
// Texto y opciones para seleccionar la operación
Text(
text = "Seleccionar operación",
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(8.dp)
)
// Componente RadioButton para seleccionar la operación
RadioButtonGroup { option ->
selectedOption = option
}
// Campo de entrada para ingresar un número
OutlinedTextField(
value = inputValue,
onValueChange = { inputValue = it },
label = { Text("Ingrese un número") },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
// Botón para enviar la solicitud
Button(
onClick = {
val number = inputValue.text.toIntOrNull()
if (number != null) {
sendRequest(number, selectedOption) { result ->
resultText = result
}
} else {
resultText = "Por favor, ingrese un número válido."
}
},
modifier = Modifier.fillMaxWidth()
) {
Text("Enviar")
}
Spacer(modifier = Modifier.height(16.dp))
// Área para mostrar el resultado de la solicitud
Box(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.verticalScroll(scrollState)
.padding(8.dp)
) {
Text(
text = resultText,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(8.dp)
)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
/**
* Envía una solicitud HTTP GET al servidor con la opción seleccionada y un número ingresado.
*
* @param number El número ingresado por el usuario.
* @param option La operación seleccionada ("cerradura" o "estrella").
* @param onResult Función para manejar la respuesta de la solicitud.
*/
fun sendRequest(number: Int, option: String, onResult: (String) -> Unit) {
//val url = "http://192.168.x.x:8080/api/operaciones/$option/$number" // URL con la opción seleccionada
val url = "http://127.0.0.1:8080/api/operaciones/$option/$number"
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
onResult("Error en la solicitud: ${e.message}")
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
val responseData = response.body?.string()
if (responseData != null) {
try {
val jsonObject = JSONObject(responseData)
val resultBuilder = StringBuilder()
// Iterar sobre las claves del JSON y obtener los valores
jsonObject.keys().forEach { key ->
val value = jsonObject.get(key)
resultBuilder.append("$key: $value\n")
}
// Devolver el resultado formateado
onResult(resultBuilder.toString())
} catch (e: Exception) {
onResult("Error al parsear JSON: ${e.message}")
}
} else {
onResult("Error: respuesta vacía")
}
} else {
onResult("Error: ${response.code}")
}
}
})
}
/**
* RadioButtonGroup es un componente que permite seleccionar entre las opciones
* "cerradura" y "estrella".
*
* @param onSelectionChanged Función que se ejecuta cuando cambia la selección.
*/
@Composable
fun RadioButtonGroup(onSelectionChanged: (String) -> Unit) {
var selectedOption by remember { mutableStateOf("cerradura") }
Column {
Row(Modifier.padding(8.dp)) {
RadioButton(
selected = selectedOption == "cerradura",
onClick = {
selectedOption = "cerradura"
onSelectionChanged("cerradura")
}
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = "Cerradura")
}
Row(Modifier.padding(8.dp)) {
RadioButton(
selected = selectedOption == "estrella",
onClick = {
selectedOption = "estrella"
onSelectionChanged("estrella")
}
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = "Estrella")
}
}
}
/**
* Vista previa para mostrar cómo se verá la aplicación en el editor de Android Studio.
*/
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
AndroidKleeneTheme {
RequestScreen({}, {})
}
}
| 0 | Kotlin | 0 | 0 | b30156a037bb890d12177bfc12adbefb72284f61 | 9,001 | P1_Android_cerraduraWeb | MIT License |
sykepengeperioder/src/main/kotlin/no/nav/helse/sparkel/sykepengeperioder/InfotrygdService.kt | navikt | 341,650,641 | false | null | package no.nav.helse.sparkel.sykepengeperioder
import net.logstash.logback.argument.StructuredArguments.keyValue
import no.nav.helse.sparkel.sykepengeperioder.dbting.*
import no.nav.helse.sparkel.sykepengeperioder.dbting.PeriodeDAO.PeriodeDTO.Companion.ekstraFerieperioder
import org.slf4j.LoggerFactory
import java.time.LocalDate
internal class InfotrygdService(
private val periodeDAO: PeriodeDAO,
private val utbetalingDAO: UtbetalingDAO,
private val inntektDAO: InntektDAO,
private val statslønnDAO: StatslønnDAO,
private val feriepengeDAO: FeriepengeDAO
) {
private companion object {
private val sikkerlogg = LoggerFactory.getLogger("tjenestekall")
}
fun løsningForSykepengehistorikkbehov(
behovId: String,
fødselsnummer: Fnr,
fom: LocalDate,
tom: LocalDate
): List<Utbetalingshistorikk>? {
try {
val perioder = periodeDAO.perioder(
fødselsnummer,
fom,
tom
)
val historikk: List<Utbetalingshistorikk> = perioder
.sortedByDescending { it.sykemeldtFom }
.mapIndexed { index, periode ->
periode.tilUtbetalingshistorikk(
UtbetalingDAO.UtbetalingDTO.tilHistorikkutbetaling(
utbetalingDAO.utbetalinger(
fødselsnummer,
periode.seq
)
),
InntektDAO.InntektDTO.tilInntektsopplysninger(
inntektDAO.inntekter(
fødselsnummer,
periode.seq
)
),
index == 0 && statslønnDAO.harStatslønn(fødselsnummer, periode.seq)
)
}
sikkerlogg.info(
"løser behov: {}",
keyValue("id", behovId)
)
return historikk
} catch (err: Exception) {
sikkerlogg.warn(
"feil ved henting av infotrygd-data: ${err.message} for {}",
keyValue("id", behovId),
err
)
return null
}
}
fun løsningForSykepengehistorikkMk2behov(
behovId: String,
fødselsnummer: Fnr,
fom: LocalDate,
tom: LocalDate
): Sykepengehistorikk? {
try {
val perioder = periodeDAO.perioder(fødselsnummer, fom, tom).sortedByDescending { it.sykemeldtFom }
val sekvensIdeer = perioder.map { it.seq }.toIntArray()
val feriepengehistorikk =
FeriepengeDAO.FeriepengeDTO.tilFeriepenger(feriepengeDAO.feriepenger(fødselsnummer, fom, tom))
val feriepengerSkalBeregnesManuelt = feriepengeDAO.feriepengerSkalBeregnesManuelt(fødselsnummer, fom, tom)
val utbetalingDAOer = utbetalingDAO.utbetalinger(
fødselsnummer,
*sekvensIdeer
)
val utbetalinger =
UtbetalingDAO.UtbetalingDTO.tilHistorikkutbetaling(utbetalingDAOer) + perioder.ekstraFerieperioder()
val inntektshistorikk =
InntektDAO.InntektDTO.tilInntektsopplysninger(inntektDAO.inntekter(fødselsnummer, *sekvensIdeer))
val harStatslønn = perioder.firstOrNull()?.let { statslønnDAO.harStatslønn(fødselsnummer, it.seq) } ?: false
val arbeidskategorikoder = perioder
.mapNotNull { periode ->
val fom = utbetalingDAOer
.filter { it.sekvensId == periode.seq }
.filterNot { it.periodeType == "7" }
.mapNotNull { it.fom }
.minOrNull()
val tom = utbetalingDAOer
.filter { it.sekvensId == periode.seq }
.filterNot { it.periodeType == "7" }
.mapNotNull { it.tom }
.maxOrNull()
if (fom != null && tom != null) {
Sykepengehistorikk.Arbeidskategori(
kode = periode.arbeidsKategori,
fom = fom,
tom = tom
)
} else null
}
.sortedBy { it.fom }
sikkerlogg.info(
"løser behov: {}",
keyValue("id", behovId)
)
return Sykepengehistorikk(
utbetalinger = utbetalinger,
inntektshistorikk = inntektshistorikk,
feriepengehistorikk = feriepengehistorikk,
harStatslønn = harStatslønn,
arbeidskategorikoder = arbeidskategorikoder,
feriepengerSkalBeregnesManuelt = feriepengerSkalBeregnesManuelt
)
} catch (err: Exception) {
sikkerlogg.warn(
"feil ved henting av infotrygd-data: ${err.message} for {}",
keyValue("id", behovId),
err
)
return null
}
}
fun løsningForHentInfotrygdutbetalingerbehov(
behovId: String,
fødselsnummer: Fnr,
fom: LocalDate,
tom: LocalDate
): List<Utbetalingsperiode>? {
try {
val perioder = periodeDAO.perioder(
fødselsnummer,
fom,
tom
)
val historikk: List<Utbetalingsperiode> = perioder.flatMap { periode ->
periode.tilUtbetalingsperiode(
utbetalingDAO.utbetalinger(fødselsnummer, periode.seq)
)
}
sikkerlogg.info(
"løser behov: {}",
keyValue("id", behovId)
)
return historikk
} catch (err: Exception) {
sikkerlogg.warn(
"feil ved henting av infotrygd-data: ${err.message} for {}",
keyValue("id", behovId),
err
)
return null
}
}
}
| 1 | null | 1 | 2 | a963d0d5db6c4fcf81993a551efa2b38ed088b29 | 6,245 | helse-sparkelapper | MIT License |
sync/sync-impl/src/main/java/com/duckduckgo/sync/impl/ui/setup/SyncDeviceConnectedViewModel.kt | duckduckgo | 78,869,127 | false | null | /*
* Copyright (c) 2023 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.sync.impl.ui.setup
import androidx.annotation.DrawableRes
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.duckduckgo.anvil.annotations.ContributesViewModel
import com.duckduckgo.app.global.DispatcherProvider
import com.duckduckgo.di.scopes.ActivityScope
import com.duckduckgo.sync.impl.SyncAccountRepository
import com.duckduckgo.sync.impl.asDrawableRes
import com.duckduckgo.sync.impl.ui.setup.SyncDeviceConnectedViewModel.Command.FinishSetupFlow
import javax.inject.*
import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
@ContributesViewModel(ActivityScope::class)
class SyncDeviceConnectedViewModel @Inject constructor(
private val syncAccountRepository: SyncAccountRepository,
private val dispatchers: DispatcherProvider,
) : ViewModel() {
private val command = Channel<Command>(1, DROP_OLDEST)
private val viewState = MutableStateFlow<ViewState?>(null)
fun viewState(): Flow<ViewState> = viewState.filterNotNull().onStart {
val result = syncAccountRepository.getThisConnectedDevice() ?: throw IllegalStateException("This connected device not found")
emit(ViewState(result.deviceType.type().asDrawableRes(), result.deviceName))
}
fun commands(): Flow<Command> = command.receiveAsFlow()
data class ViewState(
@DrawableRes val deviceType: Int,
val deviceName: String,
)
sealed class Command {
object FinishSetupFlow : Command()
}
fun onNextClicked() {
viewModelScope.launch {
command.send(FinishSetupFlow)
}
}
}
| 49 | null | 847 | 3,198 | be3bcd0ff64a25d9732b72a618c27accce467a5a | 2,501 | Android | Apache License 2.0 |
src/main/kotlin/org/rust/ide/refactoring/move/common/RsMoveConflictsDetector.kt | intellij-rust | 42,619,487 | false | null | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.move.common
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.rust.ide.refactoring.move.common.RsMoveUtil.addInner
import org.rust.ide.refactoring.move.common.RsMoveUtil.isInsideMovedElements
import org.rust.ide.refactoring.move.common.RsMoveUtil.isSimplePath
import org.rust.ide.refactoring.move.common.RsMoveUtil.isTargetOfEachSubpathAccessible
import org.rust.ide.refactoring.move.common.RsMoveUtil.startsWithSelf
import org.rust.ide.utils.getTopmostParentInside
import org.rust.lang.core.macros.setContext
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.knownItems
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyAdt
import org.rust.lang.core.types.ty.TyReference
import org.rust.lang.core.types.type
class RsMoveConflictsDetector(
private val conflicts: MultiMap<PsiElement, String>,
private val elementsToMove: List<ElementToMove>,
private val sourceMod: RsMod,
private val targetMod: RsMod
) {
val itemsToMakePublic: MutableSet<RsElement> = hashSetOf()
fun detectInsideReferencesVisibilityProblems(insideReferences: List<RsMoveReferenceInfo>) {
updateItemsToMakePublic(insideReferences)
detectReferencesVisibilityProblems(insideReferences)
detectPrivateFieldOrMethodInsideReferences()
}
private fun updateItemsToMakePublic(insideReferences: List<RsMoveReferenceInfo>) {
for (reference in insideReferences) {
val pathOld = reference.pathOldOriginal
val target = reference.target
val usageMod = pathOld.containingMod
val isSelfReference = pathOld.isInsideMovedElements(elementsToMove)
if (!isSelfReference && !usageMod.superMods.contains(targetMod)) {
val itemToMakePublic = (target as? RsFile)?.declaration ?: target
itemsToMakePublic.add(itemToMakePublic)
}
}
}
fun detectOutsideReferencesVisibilityProblems(outsideReferences: List<RsMoveReferenceInfo>) {
detectReferencesVisibilityProblems(outsideReferences)
detectPrivateFieldOrMethodOutsideReferences()
}
private fun detectReferencesVisibilityProblems(references: List<RsMoveReferenceInfo>) {
for (reference in references) {
val pathNew = reference.pathNewAccessible
if (pathNew == null || !pathNew.isTargetOfEachSubpathAccessible()) {
addVisibilityConflict(conflicts, reference.pathOldOriginal, reference.target)
}
}
}
/**
* For now we check only references from [sourceMod],
* because to check all references we should find them,
* and it would be very slow when moving e.g. many files.
*/
private fun detectPrivateFieldOrMethodInsideReferences() {
val movedElementsShallowDescendants = movedElementsShallowDescendantsOfType<RsElement>(elementsToMove)
val sourceFile = sourceMod.containingFile
val elementsToCheck = sourceFile.descendantsOfType<RsElement>() - movedElementsShallowDescendants
detectPrivateFieldOrMethodReferences(elementsToCheck.asSequence(), ::checkVisibilityForInsideReference)
}
/** We create temp child mod of [targetMod] and copy [target] to this temp mod */
private fun checkVisibilityForInsideReference(referenceElement: RsElement, target: RsVisible) {
if (target.visibility == RsVisibility.Public) return
/**
* Can't use `target.containingMod` directly,
* because if [target] is expanded by macros,
* then `containingMod` will return element from other file,
* and [getTopmostParentInside] will throw exception.
* We expect [target] to be one of [elementsToMove], so [target] should not be expanded by macros.
*/
val targetContainingMod = target.ancestorStrict<RsMod>() ?: return
if (targetContainingMod != sourceMod) return // all moved items belong to `sourceMod`
val item = target.getTopmostParentInside(targetContainingMod)
// It is enough to check only references to descendants of moved items (not mods),
// because if something in inner mod is private, then it was not accessible before move.
if (elementsToMove.none { (it as? ItemToMove)?.item == item }) return
val tempMod = RsPsiFactory(sourceMod.project).createModItem(TMP_MOD_NAME, "")
tempMod.setContext(targetMod)
target.putCopyableUserData(RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY, target)
val itemInTempMod = tempMod.addInner(item)
val targetInTempMod = itemInTempMod.descendantsOfType<RsVisible>()
.singleOrNull { it.getCopyableUserData(RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY) == target }
?: return
if (!targetInTempMod.isVisibleFrom(referenceElement.containingMod)) {
addVisibilityConflict(conflicts, referenceElement, target)
}
target.putCopyableUserData(RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY, null)
}
private fun detectPrivateFieldOrMethodOutsideReferences() {
fun checkVisibility(referenceElement: RsElement, target: RsVisible) {
if (!target.isInsideMovedElements(elementsToMove) && !target.isVisibleFrom(targetMod)) {
addVisibilityConflict(conflicts, referenceElement, target)
}
}
// TODO: Consider using [PsiRecursiveElementVisitor]
val elementsToCheck = movedElementsDeepDescendantsOfType<RsElement>(elementsToMove)
detectPrivateFieldOrMethodReferences(elementsToCheck, ::checkVisibility)
}
private fun detectPrivateFieldOrMethodReferences(
elementsToCheck: Sequence<RsElement>,
checkVisibility: (RsElement, RsVisible) -> Unit
) {
fun checkVisibility(reference: RsReferenceElement) {
val target = reference.reference?.resolve() as? RsVisible ?: return
checkVisibility(reference, target)
}
loop@ for (element in elementsToCheck) {
when (element) {
is RsDotExpr -> {
val fieldReference = element.fieldLookup ?: element.methodCall ?: continue@loop
checkVisibility(fieldReference)
}
is RsStructLiteralField -> {
val field = element.resolveToDeclaration() ?: continue@loop
checkVisibility(element, field)
}
is RsPatField -> {
val patBinding = element.patBinding ?: continue@loop
checkVisibility(patBinding)
}
is RsPatTupleStruct -> {
// It is ok to use `resolve` and not `deepResolve` here
// because type aliases can't be used in destructuring tuple struct:
val struct = element.path.reference?.resolve() as? RsStructItem ?: continue@loop
val fields = struct.tupleFields?.tupleFieldDeclList ?: continue@loop
for (field in fields) {
checkVisibility(element, field)
}
}
is RsPath -> {
// Conflicts for simple paths are handled using `pathNewAccessible`/`pathNewFallback` machinery
val isInsideSimplePath = element.ancestors
.takeWhile { it is RsPath }
.any { isSimplePath(it as RsPath) }
if (!isInsideSimplePath && !element.startsWithSelf()) {
// Here we handle e.g. UFCS paths: `Struct1::method1`
checkVisibility(element)
}
}
}
}
}
/**
* Rules for inherent impls:
* - An implementing type must be defined within the same crate as the original type definition
* - https://doc.rust-lang.org/reference/items/implementations.html#inherent-implementations
* - https://doc.rust-lang.org/error-index.html#E0116
* We should check:
* - When moving inherent impl: check that implementing type is also moved
* - When moving struct/enum: check that all inherent impls are also moved
* TODO: Check impls for trait objects: `impl dyn Trait { ... }`
*
* Rules for trait impls:
* - Orphan rules: https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
* - https://doc.rust-lang.org/error-index.html#E0117
* We should check (denote impls as `impl<P1..=Pn> Trait<T1..=Tn> for T0`):
* - When moving trait impl:
* - either implemented trait is in target crate
* - or at least one of the types `T0..=Tn` is a local type
* - When moving trait: for each impl of this trait which remains in source crate:
* - at least one of the types `T0..=Tn` is a local type
* - Uncovering is not checking, because it is complicated
*/
fun checkImpls() {
if (sourceMod.crateRoot == targetMod.crateRoot) return
val structsToMove = movedElementsDeepDescendantsOfType<RsStructOrEnumItemElement>(elementsToMove).toSet()
val implsToMove = movedElementsDeepDescendantsOfType<RsImplItem>(elementsToMove)
val (inherentImplsToMove, traitImplsToMove) = implsToMove
.partition { it.traitRef == null }
.run { first.toSet() to second.toSet() }
checkStructIsMovedTogetherWithInherentImpl(structsToMove, inherentImplsToMove)
checkInherentImplIsMovedTogetherWithStruct(structsToMove, inherentImplsToMove)
traitImplsToMove.forEach(::checkTraitImplIsCoherentAfterMove)
}
// https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence
private fun checkTraitImplIsCoherentAfterMove(impl: RsImplItem) {
fun RsElement.isLocalAfterMove(): Boolean =
crateRoot == targetMod.crateRoot || isInsideMovedElements(elementsToMove)
val traitRef = impl.traitRef!!
val (trait, subst, _) = traitRef.resolveToBoundTrait() ?: return
if (trait.isLocalAfterMove()) return
val typeParameters = subst.typeSubst.values + (impl.typeReference?.type ?: return)
val anyTypeParameterIsLocal = typeParameters.any {
val ty = it.unwrapFundamentalTypes()
if (ty is TyAdt) ty.item.isLocalAfterMove() else false
}
if (!anyTypeParameterIsLocal) {
conflicts.putValue(impl, "Orphan rules check failed for trait implementation after move")
}
}
private fun checkStructIsMovedTogetherWithInherentImpl(
structsToMove: Set<RsStructOrEnumItemElement>,
inherentImplsToMove: Set<RsImplItem>
) {
for (impl in inherentImplsToMove) {
val struct = impl.implementingType?.item ?: continue
if (struct !in structsToMove) {
val structDescription = RefactoringUIUtil.getDescription(struct, true)
val message = "Inherent implementation should be moved together with $structDescription"
conflicts.putValue(impl, message)
}
}
}
private fun checkInherentImplIsMovedTogetherWithStruct(
structsToMove: Set<RsStructOrEnumItemElement>,
inherentImplsToMove: Set<RsImplItem>
) {
for ((file, structsToMoveInFile) in structsToMove.groupBy { it.containingFile }) {
// not working if there is inherent impl in other file
// but usually struct and its inherent impls belong to same file
val structInherentImpls = file.descendantsOfType<RsImplItem>()
.filter { it.traitRef == null }
.groupBy { it.implementingType?.item }
for (struct in structsToMoveInFile) {
val impls = structInherentImpls[struct] ?: continue
for (impl in impls.filter { it !in inherentImplsToMove }) {
val structDescription = RefactoringUIUtil.getDescription(struct, true)
val message = "Inherent implementation should be moved together with $structDescription"
conflicts.putValue(impl, message)
}
}
}
}
companion object {
val RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY: Key<RsElement> =
Key("RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY")
}
}
fun addVisibilityConflict(conflicts: MultiMap<PsiElement, String>, reference: RsElement, target: RsElement) {
val referenceDescription = RefactoringUIUtil.getDescription(reference.containingMod, true)
val targetDescription = RefactoringUIUtil.getDescription(target, true)
val message = "$referenceDescription uses $targetDescription which will be inaccessible after move"
conflicts.putValue(reference, StringUtil.capitalize(message))
}
private val RsImplItem.implementingType: TyAdt? get() = typeReference?.type as? TyAdt
// https://doc.rust-lang.org/reference/glossary.html#fundamental-type-constructors
private fun Ty.unwrapFundamentalTypes(): Ty {
when (this) {
// &T -> T
// &mut T -> T
is TyReference -> return referenced
// Box<T> -> T
// Pin<T> -> T
is TyAdt -> {
if (item == item.knownItems.Box || item == item.knownItems.Pin) {
return typeArguments.singleOrNull() ?: this
}
}
}
return this
}
| 1,841 | null | 380 | 4,528 | c6657c02bb62075bf7b7ceb84d000f93dda34dc1 | 13,804 | intellij-rust | MIT License |
app/src/main/java/com/akinci/doggoappcompose/data/mapper/DoggoDataSourceMapper.kt | AttilaAKINCI | 441,558,552 | false | null | package com.akinci.doggoappcompose.data.mapper
import com.akinci.doggoappcompose.data.local.entity.BreedEntity
import com.akinci.doggoappcompose.data.local.entity.ContentEntity
import com.akinci.doggoappcompose.data.local.entity.SubBreedEntity
import com.akinci.doggoappcompose.data.remote.output.BreedListResponse
import com.akinci.doggoappcompose.data.remote.output.BreedResponse
import com.akinci.doggoappcompose.data.remote.output.SubBreedListResponse
import com.akinci.doggoappcompose.ui.feaute.dashboard.data.Breed
fun List<Breed>.convertToBreedListEntity(): List<BreedEntity> {
return map { BreedEntity(name = it.name, selected = it.selected) }
}
fun List<Breed>.convertToSubBreedListEntity(ownerBreed:String): List<SubBreedEntity> {
return map { SubBreedEntity(breed = ownerBreed, name = it.name, selected = it.selected) }
}
fun List<String>.convertToDoggoContentListEntity(breed: String, subBreed: String): List<ContentEntity> {
return map { item -> ContentEntity(breed = breed, subBreed = subBreed, contentURL = item) }
}
fun List<BreedEntity>.convertToBreedListResponse(): BreedListResponse{
val map = mutableMapOf<String, List<Any>>()
map { map.put(it.name, listOf()) }
return BreedListResponse(message = map, status = "success")
}
fun List<SubBreedEntity>.convertToSubBreedListResponse(): SubBreedListResponse {
return SubBreedListResponse(message = map { item -> item.name }, status = "success")
}
fun List<ContentEntity>.convertToBreedResponse(): BreedResponse {
return BreedResponse(message = map { item -> item.contentURL }, status = "success")
} | 0 | Kotlin | 0 | 1 | d654070553b9366dc4e46c07818f6e61303342f2 | 1,602 | DoggoApp-Compose | Apache License 2.0 |
http4k-core/src/main/kotlin/org/http4k/routing/routing.kt | jmfayard | 151,679,616 | false | null | package org.http4k.routing
import org.http4k.core.Body
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.UriTemplate
import org.http4k.websocket.WsConsumer
fun routes(vararg list: Pair<Method, HttpHandler>): RoutingHttpHandler = routes(*list.map { "" bind it.first to it.second }.toTypedArray())
fun routes(vararg list: RoutingHttpHandler): RoutingHttpHandler = RouterBasedHttpHandler(OrRouter.from(list.toList()))
infix fun String.bind(method: Method): PathMethod = PathMethod(this, method)
infix fun String.bind(httpHandler: RoutingHttpHandler): RoutingHttpHandler = httpHandler.withBasePath(this)
infix fun String.bind(action: HttpHandler): RoutingHttpHandler = RouterBasedHttpHandler(TemplateRouter(UriTemplate.from(this), action))
infix fun String.bind(consumer: WsConsumer): RoutingWsHandler = TemplateRoutingWsHandler(UriTemplate.from(this), consumer)
infix fun String.bind(wsHandler: RoutingWsHandler): RoutingWsHandler = wsHandler.withBasePath(this)
infix fun Router.bind(handler: HttpHandler): RoutingHttpHandler = RouterBasedHttpHandler(and(PassthroughRouter(handler)))
infix fun Router.bind(handler: RoutingHttpHandler): RoutingHttpHandler = RouterBasedHttpHandler(and(handler))
infix fun Router.and(that: Router): Router = AndRouter.from(listOf(this, that))
/**
* Matches the Host header to a matching Handler.
*/
fun hostDemux(vararg hosts: Pair<String, HttpHandler>) = routes(*hosts.map { header("host", it.first) bind it.second }.toTypedArray())
/**
* Apply routing predicate to a query
*/
fun query(name: String, predicate: (String) -> Boolean) = { req: Request -> req.queries(name).filterNotNull().any(predicate) }.asRouter()
/**
* Apply routing predicate to a query
*/
fun query(name: String, value: String) = query(name) { it == value }
/**
* Ensure all queries are present
*/
fun queries(vararg names: String) = { req: Request -> names.all { req.query(it) != null } }.asRouter()
/**
* Apply routing predicate to a header
*/
fun header(name: String, predicate: (String) -> Boolean) = { req: Request -> req.headerValues(name).filterNotNull().any(predicate) }.asRouter()
/**
* Apply routing predicate to a header
*/
fun header(name: String, value: String) = header(name) { it == value }
/**
* Ensure all headers are present
*/
fun headers(vararg names: String) = { req: Request -> names.all { req.header(it) != null } }.asRouter()
/**
* Ensure body matches predicate
*/
fun body(predicate: (Body) -> Boolean) = { req: Request -> predicate(req.body) }.asRouter()
/**
* Ensure body string matches predicate
*/
@JvmName("bodyMatches")
fun body(predicate: (String) -> Boolean) = { req: Request -> predicate(req.bodyString()) }.asRouter()
| 1 | null | 1 | 1 | f2ec6a89ddfae9c54690f0a756dd1834a4d2a8e6 | 2,752 | http4k | Apache License 2.0 |
Project 21 - OurGithubContributions/app/src/main/java/com/example/ourgithubcontributions/ui/adapter/UserListAdapter.kt | heojungeun | 242,650,326 | false | null | package com.example.ourgithubcontributions.ui.adapter
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.barryzhang.tcontributionsview.TContributionsView
import com.example.ourgithubcontributions.R
import com.example.ourgithubcontributions.data.model.User
import com.example.ourgithubcontributions.retrofit.RetrofitPresenter
class UserListAdapter(private val cbList: List<User>) : RecyclerView.Adapter<UserListAdapter.ViewHolder>(){
//private var cbList: List<User> = listOf()
override fun getItemCount(): Int = cbList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cb, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(cbList[position])
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
var item_name = itemView.findViewById<TextView>(R.id.eachName)
var item_cbview = itemView.findViewById<TContributionsView>(R.id.eachCbView)
fun bind(user: User){
item_name.text = user.userName
RetrofitPresenter().getContributions(user.userName, item_cbview)
}
}
} | 0 | Kotlin | 0 | 9 | f325ed3a0a60dcaf45307ea0ce29509410a93fba | 1,431 | 30DaysofAndroid | Apache License 2.0 |
core/src/skikoMain/kotlin/dev/tclement/fonticons/VariableIconFont.skiko.kt | tclement0922 | 707,598,978 | false | null | /*
* Copyright 2024 T. Clément (@tclement0922)
*
* 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 dev.tclement.fonticons
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontVariation
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.platform.Typeface
import androidx.compose.ui.unit.Density
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.FontResource
import org.jetbrains.compose.resources.getFontResourceBytes
import org.jetbrains.skia.Data
import org.jetbrains.skia.FontMgr
import org.jetbrains.skia.FontVariation as SkFontVariation
import org.jetbrains.skia.Typeface as SkTypeface
/**
* Skiko (Kotlin's Skia wrapper) implementation of [VariableIconFont].
*/
internal class VariableIconFontSkikoImpl(
private val alias: String,
private val typefaceConstructor: (variationSettings: FontVariation.Settings) -> SkTypeface,
private val weights: Array<out FontWeight>,
override val variationSettings: Array<out FontVariation.Setting>,
override val featureSettings: String?
) : VariableIconFont() {
private val fontFamilies: MutableMap<Pair<Float, FontWeight>, FontFamily> = mutableMapOf()
override val opticalSizePreset: Boolean = variationSettings.any { it.axisName == "opsz" }
override fun textStyleWeightFor(weight: FontWeight): FontWeight {
return FontWeight.W400
}
override fun getFontFamily(
size: Float,
weight: FontWeight
): FontFamily {
return fontFamilies.getOrPut((if (opticalSizePreset) -1f else size) to weight) {
val variationSettings = if (opticalSizePreset) {
FontVariation.Settings(
weight = weights.nearestOf(weight),
style = FontStyle.Normal,
*variationSettings
)
} else {
FontVariation.Settings(
weight = weights.nearestOf(weight),
style = FontStyle.Normal,
FontVariation.Setting("opsz", size),
*variationSettings
)
}
FontFamily(
Typeface(
typeface = typefaceConstructor(variationSettings).apply {
this.isBold
},
// Generate a different alias for each requested variation,
// or else it would always return the first requested one
alias = "${variationSettings.hashCode()}-$alias"
)
)
}
}
}
/**
* Creates a variable [IconFont] using a Skia Typeface.
* @param alias the internal name to differentiate the typeface
* @param baseTypeface the base Skia [SkTypeface] that will be cloned for each required variation settings
* @param weights the supported weights for the font
* @param fontVariationSettings the font variation settings, should not include the optical size ('opsz')
* and must not include the weight ('wght')
* @param fontFeatureSettings the font feature settings, written in a CSS syntax
* @param density the density of the screen, used to convert the icon size to pixels
*/
@Composable
public fun rememberVariableIconFont(
alias: String,
baseTypeface: SkTypeface,
weights: Array<FontWeight>,
fontVariationSettings: Array<FontVariation.Setting> = emptyArray(),
fontFeatureSettings: String? = null,
density: Density = LocalDensity.current
): VariableIconFont =
remember(alias, baseTypeface, weights, fontVariationSettings, fontFeatureSettings, density) {
VariableIconFontSkikoImpl(
alias = alias,
typefaceConstructor = { settings ->
baseTypeface.makeClone(
settings.settings.map { setting ->
SkFontVariation(setting.axisName, setting.toVariationValue(density))
}.toTypedArray()
)
},
weights = weights,
featureSettings = fontFeatureSettings,
variationSettings = fontVariationSettings
)
}
/**
* Creates a variable [IconFont] using a byte array with loaded font data.
* @param alias the internal name to differentiate the typeface
* @param data a byte array with loaded font data
* @param weights the supported weights for the font
* @param fontVariationSettings the font variation settings, should not include the optical size ('opsz')
* and must not include the weight ('wght')
* @param fontFeatureSettings the font feature settings, written in a CSS syntax
* @param density the density of the screen, used to convert the icon size to pixels
*/
@Composable
public fun rememberVariableIconFont(
alias: String,
data: ByteArray,
weights: Array<FontWeight>,
fontVariationSettings: Array<FontVariation.Setting> = emptyArray(),
fontFeatureSettings: String? = null,
density: Density = LocalDensity.current
): VariableIconFont = rememberVariableIconFont(
alias = alias,
baseTypeface = FontMgr.default.makeFromData(Data.makeFromBytes(data))!!,
weights = weights,
fontVariationSettings = fontVariationSettings,
fontFeatureSettings = fontFeatureSettings,
density = density
)
@OptIn(ExperimentalResourceApi::class)
@Composable
public actual fun rememberVariableIconFont(
fontResource: FontResource,
weights: Array<FontWeight>,
fontVariationSettings: Array<FontVariation.Setting>,
fontFeatureSettings: String?
): VariableIconFont {
val environment = LocalIconResourceEnvironment.current
val typeface by produceState(SkTypeface.makeEmpty(), environment, fontResource) {
val bytes = getFontResourceBytes(environment, fontResource)
value = FontMgr.default.makeFromData(Data.makeFromBytes(bytes))!!
}
return rememberVariableIconFont(
alias = typeface.uniqueId.toString(),
baseTypeface = typeface,
weights = weights,
fontVariationSettings = fontVariationSettings,
fontFeatureSettings = fontFeatureSettings,
density = LocalDensity.current
)
}
/**
* Creates a variable [IconFont] using a Skia Typeface.
*
* This function is not composable, use [rememberVariableIconFont] when in a composition
* @param alias the internal name to differentiate the typeface
* @param baseTypeface the base Skia [SkTypeface] that will be cloned for each required variation settings
* @param weights the supported weights for the font
* @param fontVariationSettings the font variation settings, should not include the optical size ('opsz')
* and must not include the weight ('wght')
* @param fontFeatureSettings the font feature settings, written in a CSS syntax
* @param density the density of the screen, used to convert the icon size to pixels
*/
public fun createVariableIconFont(
alias: String,
baseTypeface: SkTypeface,
weights: Array<FontWeight>,
fontVariationSettings: Array<FontVariation.Setting> = emptyArray(),
fontFeatureSettings: String? = null,
density: Density
): VariableIconFont =
VariableIconFontSkikoImpl(
alias = alias,
typefaceConstructor = { settings ->
baseTypeface.makeClone(
settings.settings.map { setting ->
SkFontVariation(setting.axisName, setting.toVariationValue(density))
}.toTypedArray()
)
},
weights = weights,
featureSettings = fontFeatureSettings,
variationSettings = fontVariationSettings
) | 1 | null | 1 | 7 | d5ef8d9a34af16a3b1dfe55c66ae57f279cd7f58 | 8,388 | compose-font-icons | Apache License 2.0 |
app/src/main/java/io/agora/education/setting/FcrMainActivity.kt | AgoraIO-Community | 330,886,965 | false | null | package io.agora.education.setting
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.SystemClock
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.cardview.widget.CardView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.agora.edu.component.loading.AgoraLoadingDialog
import com.agora.edu.component.teachaids.networkdisk.FCRCloudDiskWidget
import com.agora.edu.component.teachaids.networkdisk.Statics
import io.agora.agoraeducore.BuildConfig
import io.agora.agoraeducore.BuildConfig.APAAS_VERSION
import io.agora.agoraeducore.core.context.EduContextVideoEncoderConfig
import io.agora.agoraeducore.core.internal.base.PreferenceManager
import io.agora.agoraeducore.core.internal.base.ToastManager
import io.agora.agoraeducore.core.internal.base.http.AppHostUtil
import io.agora.agoraeducore.core.internal.base.http.AppRetrofitManager
import io.agora.agoraeducore.core.internal.base.http.TokenUtils
import io.agora.agoraeducore.core.internal.education.impl.Constants
import io.agora.agoraeducore.core.internal.education.impl.network.HttpBaseRes
import io.agora.agoraeducore.core.internal.education.impl.network.HttpCallback
import io.agora.agoraeducore.core.internal.framework.data.EduCallback
import io.agora.agoraeducore.core.internal.framework.data.EduError
import io.agora.agoraeducore.core.internal.launch.*
import io.agora.agoraeducore.core.internal.launch.courseware.AgoraEduCourseware
import io.agora.agoraeducore.core.internal.launch.courseware.CoursewareUtil
import io.agora.agoraeducore.core.utils.SkinUtils
import io.agora.agoraeducore.extensions.widgets.bean.AgoraWidgetConfig
import io.agora.agoraeducore.extensions.widgets.bean.AgoraWidgetDefaultId
import io.agora.agoraeduuikit.config.template.FcrSceneTypeObject
import io.agora.agoraeduuikit.impl.whiteboard.AgoraWhiteBoardWidget
import io.agora.agoraeduuikit.util.PopupAnimationUtil
import io.agora.classroom.helper.FcrStreamParameters
import io.agora.classroom.sdk.AgoraClassSdkConfig
import io.agora.classroom.sdk.AgoraClassroomSDK
import io.agora.education.R
import io.agora.education.base.BaseActivity
import io.agora.education.dialog.ForbiddenDialog
import io.agora.education.dialog.ForbiddenDialogBuilder
import io.agora.education.config.ConfigData
import io.agora.education.config.ConfigUtil
import io.agora.education.data.DefaultPublicCoursewareJson
import io.agora.education.home.FcrLoginActivity
import io.agora.education.home.FcrPrivacyTermsDialog
import io.agora.education.home.LOGIN_URL_KEY
import io.agora.education.request.bean.FcrRedirectUrlReq
import io.agora.education.request.AppService
import io.agora.education.utils.AppUtil
import io.agora.education.utils.HashUtil
import java.util.*
import java.util.regex.Pattern
/**
* 免登录,进入教室入口
*/
class FcrMainActivity : BaseActivity(), View.OnClickListener {
private val TAG = "MainActivity"
private val REQUEST_CODE_RTC = 101
private lateinit var rootLayout: ConstraintLayout
private lateinit var icAbout: AppCompatImageView
private lateinit var edRoomName: AppCompatEditText
private lateinit var blRoomName: View
private lateinit var tipsRoomName: AppCompatTextView
private lateinit var edUserName: AppCompatEditText
private lateinit var blUserName: View
private lateinit var tipsUserName: AppCompatTextView
private lateinit var roomTypeLayout: RelativeLayout
private lateinit var roleTypeLayout: RelativeLayout
private lateinit var icDownUp: AppCompatImageView
private lateinit var tvRoomType: AppCompatTextView
private lateinit var tvRoleType: AppCompatTextView
private lateinit var cardRoomType: CardView
private lateinit var cardRoleType: CardView
private lateinit var tvOne2One: AppCompatTextView
private lateinit var tvSmallClass: AppCompatTextView
private lateinit var llClassNormal: LinearLayout
private lateinit var llClassArt: LinearLayout
private lateinit var tvSmallClassArt: AppCompatTextView
private lateinit var tvLargeClassArt: AppCompatTextView
private lateinit var tvLargeClass: AppCompatTextView
private lateinit var tvLargeClassVocational: AppCompatTextView
private lateinit var tvRoleStudent: AppCompatTextView
private lateinit var tvRoleTeacher: AppCompatTextView
private lateinit var tvRoleAudience: AppCompatTextView
private lateinit var icRoleDownUp: AppCompatImageView
private lateinit var videoStreamModeLayout: RelativeLayout
private lateinit var videoStreamKeyLayout: RelativeLayout
private lateinit var edVideoStreamKey: AppCompatEditText
private lateinit var edVideoStreamMode: AppCompatTextView
private lateinit var cardEncryptMode: CardView
private lateinit var btnJoin: AppCompatButton
private lateinit var tvFlexibleVersion: AppCompatTextView
private lateinit var logoView: View
private lateinit var serviceTypeLayout: RelativeLayout
private lateinit var cardServiceType: CardView
private lateinit var icServiceDownUp: AppCompatImageView
private lateinit var tvServiceType: AppCompatTextView
private lateinit var tvServiceLivePremium: AppCompatTextView
private lateinit var tvServiceLiveStandard: AppCompatTextView
private lateinit var tvServiceCdn: AppCompatTextView
private lateinit var tvServiceFusion: AppCompatTextView
private lateinit var tvServiceScreenShare: AppCompatTextView
private lateinit var tvServiceHostingScene: AppCompatTextView
private val pattern = Pattern.compile("[^a-zA-Z0-9]")
private val patternUserName = Pattern.compile("[^a-zA-Z0-9\\s\u4e00-\u9fa5]")
private var roomNameValid = false
private var userNameNameValid = false
private var roomTypeValid = false
private var roleTypeValid = false
private var serviceTypeValid = false
// private lateinit var rtmToken: String
private var mDialog: ForbiddenDialog? = null
private var regionStr: String = ""
private var encryptMode: Int = 0
private var debugMode: Boolean = false
private var tapCount: TapCount? = null
private var popupAnimationUtil = PopupAnimationUtil()
private lateinit var agoraLoading: AgoraLoadingDialog
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
regionStr = PreferenceManager.get(io.agora.education.config.AppConstants.KEY_SP_REGION, AgoraEduRegion.cn)
if (AppUtil.isTabletDevice(this)) {
AppUtil.hideStatusBar(window, true)
setContentView(R.layout.activity_main_tablet)
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
} else {
AppUtil.hideStatusBar(window, false)
setContentView(R.layout.activity_main_phone)
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
rootLayout = findViewById(R.id.root_Layout)
icAbout = findViewById(R.id.ic_about)
icAbout.setOnClickListener(this)
val statusBarHeight = AppUtil.getStatusBarHeight(this)
(icAbout.layoutParams as ViewGroup.MarginLayoutParams).topMargin += statusBarHeight
edRoomName = findViewById(R.id.ed_roomName)
edRoomName.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
val roomName = edRoomName.text.toString()
roomNameValid = pattern.matcher(roomName).replaceAll("").trim() == roomName
roomNameValid = roomNameValid && roomName.length > 5
tipsRoomName.visibility = if (roomNameValid) GONE else VISIBLE
blRoomName.isEnabled = roomNameValid
notifyBtnJoinEnable(true)
}
})
blRoomName = findViewById(R.id.bl_roomName)
tipsRoomName = findViewById(R.id.tips_roomName)
blUserName = findViewById(R.id.bl_userName)
edUserName = findViewById(R.id.ed_userName)
edUserName.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
val userName = edUserName.text.toString()
userNameNameValid = patternUserName.matcher(userName).replaceAll("").trim() == userName.trim()
userNameNameValid = userNameNameValid && userName.length > 5
tipsUserName.visibility = if (userNameNameValid) GONE else VISIBLE
blUserName.isEnabled = userNameNameValid
notifyBtnJoinEnable(true)
}
})
tipsUserName = findViewById(R.id.tips_userName)
roomTypeLayout = findViewById(R.id.roomType_Layout)
roomTypeLayout.setOnClickListener(this)
icDownUp = findViewById(R.id.ic_down0)
roleTypeLayout = findViewById(R.id.roleType_Layout)
roleTypeLayout.setOnClickListener(this)
tvRoomType = findViewById(R.id.tv_roomType)
tvRoleType = findViewById(R.id.tv_roleType)
cardRoomType = findViewById(R.id.card_room_type)
cardRoleType = findViewById(R.id.card_role_type)
tvOne2One = findViewById(R.id.tv_one2one)
tvOne2One.setOnClickListener(this)
tvSmallClass = findViewById(R.id.tv_small_class)
tvSmallClass.setOnClickListener(this)
llClassNormal = findViewById(R.id.class_type_normal)
llClassNormal.setOnClickListener(this)
llClassArt = findViewById(R.id.class_type_art)
llClassArt.setOnClickListener(this)
tvSmallClassArt = findViewById(R.id.tv_small_class_art)
tvSmallClassArt.setOnClickListener(this)
tvLargeClassArt = findViewById(R.id.tv_large_class_art)
tvLargeClassArt.setOnClickListener(this)
tvLargeClass = findViewById(R.id.tv_large_class)
tvLargeClass.setOnClickListener(this)
tvLargeClassVocational = findViewById(R.id.tv_large_class_vocational)
tvLargeClassVocational.setOnClickListener(this)
tvRoleStudent = findViewById(R.id.tv_role_student)
tvRoleStudent.setOnClickListener(this)
tvRoleTeacher = findViewById(R.id.tv_role_teacher)
tvRoleTeacher.setOnClickListener(this)
tvRoleAudience = findViewById(R.id.tv_role_audience)
tvRoleAudience.setOnClickListener(this)
icRoleDownUp = findViewById(R.id.ic_down9)
logoView = findViewById(R.id.logo)
btnJoin = findViewById(R.id.btn_join)
btnJoin.setOnClickListener(this)
tvFlexibleVersion = findViewById(R.id.tv_flexibleVersion)
tvFlexibleVersion.setOnClickListener(this)
tvFlexibleVersion.text = String.format(getString(R.string.flexible_version1), APAAS_VERSION)
edVideoStreamKey = findViewById(R.id.ed_videoStream_key)
edVideoStreamMode = findViewById(R.id.ed_videoStream_mode)
cardEncryptMode = findViewById(R.id.card_encrypt_mode)
videoStreamModeLayout = findViewById(R.id.videoStream_mode_Layout)
videoStreamModeLayout.setOnClickListener(this)
videoStreamModeLayout.visibility = GONE
videoStreamKeyLayout = findViewById(R.id.videoStream_key_Layout)
videoStreamKeyLayout.visibility = GONE
(findViewById<AppCompatTextView>(R.id.none)).setOnClickListener(this)
(findViewById<AppCompatTextView>(R.id.sm4_128_ecb)).setOnClickListener(this)
(findViewById<AppCompatTextView>(R.id.aes_128_gcm)).setOnClickListener(this)
(findViewById<AppCompatTextView>(R.id.aes_256_gcm)).setOnClickListener(this)
serviceTypeLayout = findViewById(R.id.serviceType_Layout)
serviceTypeLayout.setOnClickListener(this)
tvServiceType = findViewById(R.id.tv_serviceType)
icServiceDownUp = findViewById(R.id.ic_serivce_down)
cardServiceType = findViewById(R.id.card_service_type)
tvServiceLivePremium = findViewById(R.id.tv_service_live_premium)
tvServiceLivePremium.setOnClickListener(this)
tvServiceLiveStandard = findViewById(R.id.tv_service_live_standard)
tvServiceLiveStandard.setOnClickListener(this)
tvServiceCdn = findViewById(R.id.tv_service_cdn)
tvServiceCdn.setOnClickListener(this)
tvServiceFusion = findViewById(R.id.tv_service_fusion)
tvServiceFusion.setOnClickListener(this)
tvServiceScreenShare = findViewById(R.id.tv_service_screen_share)
tvServiceScreenShare.setOnClickListener(this)
tvServiceHostingScene = findViewById(R.id.tv_service_hosting_scene)
tvServiceHostingScene.setOnClickListener(this)
agoraLoading = AgoraLoadingDialog(this)
//showPrivacyTerms()
debugLayoutDetect()
setQATestPage()
// if (BuildConfig.DEBUG) {
// edRoomName.setText("apaas230309")
// edUserName.setText("student123")
// }
}
fun setQATestPage() {
logoView.setOnClickListener(object : View.OnClickListener {
val COUNTS = 5 //点击次数
val DURATION = (3 * 1000).toLong() //规定有效时间
var mHits = LongArray(COUNTS)
override fun onClick(v: View) {
/**
* 实现双击方法
* src 拷贝的源数组
* srcPos 从源数组的那个位置开始拷贝.
* dst 目标数组
* dstPos 从目标数组的那个位子开始写数据
* length 拷贝的元素的个数
*/
System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
//实现左移,然后最后一个位置更新距离开机的时间,如果最后一个时间和最开始时间小于DURATION,即连续5次点击
mHits[mHits.size - 1] = SystemClock.uptimeMillis()
if (mHits[0] >= SystemClock.uptimeMillis() - DURATION) {
startActivity(Intent(this@FcrMainActivity, FcrSettingTestActivity::class.java))
}
}
})
}
private fun debugLayoutDetect() {
tapCount = TapCount(this, 10, 2000) {
debugMode = !debugMode
debugLayout(debugMode)
}
findViewById<View>(R.id.entry_param_state)?.setOnClickListener {
tapCount?.step()
}
}
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
if (ev?.action == MotionEvent.ACTION_DOWN) {
val v = currentFocus
if (isShouldHideKeyboard(v, ev)) {
hideKeyboard(v?.windowToken)
}
}
return super.dispatchTouchEvent(ev)
}
private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
if (v != null && v is EditText) {
val l = intArrayOf(0, 0)
v.getLocationInWindow(l)
val left = l[0]
val top = l[1]
val bottom = top + v.getHeight()
val right = left + v.getWidth()
return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
}
return false
}
private fun hideKeyboard(token: IBinder?) {
if (token != null) {
val im: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
private fun debugLayout(isDebugMode: Boolean) {
val visibility = if (isDebugMode) VISIBLE else GONE
videoStreamModeLayout.visibility = visibility
videoStreamKeyLayout.visibility = visibility
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
for (result in grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.no_enough_permissions, Toast.LENGTH_SHORT).show()
return
}
}
when (requestCode) {
REQUEST_CODE_RTC -> start()
else -> {
}
}
}
override fun onClick(v: View?) {
v?.let {
when (it.id) {
R.id.ic_about -> {
// if (AppUtil.isTabletDevice(this)) {
// if (aboutDialog == null) {
// aboutDialog = AboutDialog(this)
// }
// aboutDialog?.show()
// } else {
// startActivity(Intent(this, SettingPageActivity::class.java))
// }
startActivity(Intent(this, FcrSettingActivity::class.java))
}
R.id.roomType_Layout -> {
if (cardRoomType.visibility == GONE) {
cardRoomType.visibility = VISIBLE
popupAnimationUtil.runShowAnimation(cardRoomType, (cardRoomType.width / 2).toFloat(), 0f)
cardRoleType.visibility = GONE
cardEncryptMode.visibility = GONE
cardServiceType.visibility = GONE
icDownUp.isActivated = true
if (!BuildConfig.isArtScene.toBoolean()) {
llClassNormal.visibility = VISIBLE
val sceneTypeArr = FcrSceneTypeObject.getSceneType()
sceneTypeArr.forEach { type ->
if (type == FcrSceneTypeObject.FcrSceneType.OneToOne) {
tvOne2One.visibility = VISIBLE
}
if (type == FcrSceneTypeObject.FcrSceneType.Small) {
tvSmallClass.visibility = VISIBLE
}
if (type == FcrSceneTypeObject.FcrSceneType.Lecture) {
tvLargeClass.visibility = VISIBLE
}
if (type == FcrSceneTypeObject.FcrSceneType.Vocational) {
tvLargeClassVocational.visibility = VISIBLE
}
}
llClassArt.visibility = GONE
} else {
llClassNormal.visibility = GONE
llClassArt.visibility = VISIBLE
}
refreshRoomTypeListColor()
} else {
popupAnimationUtil.runDismissAnimation(cardRoomType, (cardRoomType.width / 2).toFloat(), 0f) {
cardRoomType.visibility = GONE
icDownUp.isActivated = false
}
}
}
R.id.tv_one2one -> {
handleK12RoomTypeClick(R.string.one2one_class)
}
R.id.tv_small_class -> {
handleK12RoomTypeClick(R.string.small_class)
}
R.id.tv_large_class -> {
handleK12RoomTypeClick(R.string.large_class)
}
R.id.tv_small_class_art -> {
handleArtRoomTypeClick(R.string.small_class_art)
}
R.id.tv_large_class_art -> {
handleArtRoomTypeClick(R.string.large_class_art)
}
R.id.tv_large_class_vocational -> {
handleVocationalRoomTypeClick(R.string.large_class_vocational)
}
R.id.roleType_Layout -> {
if (cardRoleType.visibility == GONE) {
// if (tvRoomType.text.equals(this.getString(R.string.small_class_art))) {
cardRoleType.visibility = VISIBLE
popupAnimationUtil.runShowAnimation(cardRoleType, (cardRoleType.width / 2).toFloat(), 0f)
cardRoomType.visibility = GONE
cardEncryptMode.visibility = GONE
cardServiceType.visibility = GONE
// } else {
//// tvRoleType.setText(R.string.role_student)
//// roleTypeValid = true
// }
refreshRoleTypeListColor()
} else {
popupAnimationUtil.runDismissAnimation(cardRoleType, (cardRoleType.width / 2).toFloat(), 0f) {
cardRoleType.visibility = GONE
}
// cardRoleType.visibility = GONE
}
}
R.id.tv_role_student -> {
tvRoleType.setText(R.string.role_student)
cardRoleType.visibility = GONE
roleTypeValid = true
notifyBtnJoinEnable(true)
}
R.id.tv_role_teacher -> {
tvRoleType.setText(R.string.role_teacher)
cardRoleType.visibility = GONE
roleTypeValid = true
notifyBtnJoinEnable(true)
}
R.id.tv_role_audience -> {
tvRoleType.setText(R.string.role_audience)
cardRoleType.visibility = GONE
roleTypeValid = true
notifyBtnJoinEnable(true)
}
R.id.videoStream_mode_Layout -> {
if (cardEncryptMode.visibility == GONE) {
cardEncryptMode.visibility = VISIBLE
cardRoomType.visibility = GONE
cardRoleType.visibility = GONE
cardServiceType.visibility = GONE
} else {
cardEncryptMode.visibility = GONE
}
}
R.id.none -> {
encryptMode = AgoraEduEncryptMode.NONE.value
edVideoStreamMode.text = getString(R.string.none)
cardEncryptMode.visibility = GONE
}
R.id.sm4_128_ecb -> {
encryptMode = AgoraEduEncryptMode.SM4_128_ECB.value
edVideoStreamMode.text = getString(R.string.sm4_128_ecb)
cardEncryptMode.visibility = GONE
}
R.id.aes_128_gcm -> {
encryptMode = AgoraEduEncryptMode.AES_128_GCM.value
edVideoStreamMode.text = getString(R.string.aes_128_gcm)
cardEncryptMode.visibility = GONE
}
R.id.aes_256_gcm -> {
encryptMode = AgoraEduEncryptMode.AES_256_GCM.value
edVideoStreamMode.text = getString(R.string.aes_256_gcm)
cardEncryptMode.visibility = GONE
}
R.id.serviceType_Layout -> {
if (cardServiceType.visibility == GONE) {
cardServiceType.visibility = VISIBLE
popupAnimationUtil.runShowAnimation(cardServiceType, (cardServiceType.width / 2).toFloat(), 0f)
icServiceDownUp.isActivated = true
cardRoomType.visibility = GONE
cardRoleType.visibility = GONE
cardEncryptMode.visibility = GONE
refreshServiceTypeListColor()
} else {
popupAnimationUtil.runDismissAnimation(
cardServiceType,
(cardServiceType.width / 2).toFloat(),
0f
) {
cardServiceType.visibility = GONE
icServiceDownUp.isActivated = false
}
}
}
R.id.tv_service_live_premium -> {
handleServiceTypeClick(R.string.service_live_premium)
}
R.id.tv_service_live_standard -> {
handleServiceTypeClick(R.string.service_live_standard)
}
R.id.tv_service_cdn -> {
handleServiceTypeClick(R.string.service_cdn)
}
R.id.tv_service_fusion -> {
handleServiceTypeClick(R.string.service_fusion)
}
R.id.tv_service_screen_share -> {
handleServiceTypeClick(R.string.service_screen_share)
}
R.id.tv_service_hosting_scene -> {
handleServiceTypeClick(R.string.service_hosting_scene)
}
R.id.btn_join -> {
// if (tvRoomType.text.equals(resources.getString(R.string.large_class)) &&
// tvRoleType.text.equals(resources.getString(R.string.role_teacher))
// ) {
// AgoraUIToast.warn(
// applicationContext,
// tvRoomType,
// text = resources.getString(R.string.join_large_for_teacher_fail)
// )
// return
// }
if (AppUtil.isFastClick()) {
return
}
if (AppUtil.checkAndRequestAppPermission(
this, arrayOf(
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA
), REQUEST_CODE_RTC
)
) {
start()
} else {
}
}
else -> {
}
}
}
}
private fun start() {
regionStr = PreferenceManager.get(io.agora.education.config.AppConstants.KEY_SP_REGION, AgoraEduRegion.cn)
// if (!TokenUtils.isExistLoginToken()) {
// loadLoginPage()
// return
// }
notifyBtnJoinEnable(false)
val roomName: String = edRoomName.text.toString()
if (TextUtils.isEmpty(roomName)) {
Toast.makeText(this, R.string.room_name_should_not_be_empty, Toast.LENGTH_SHORT).show()
notifyBtnJoinEnable(true)
return
}
val userName: String = edUserName.text.toString()
if (TextUtils.isEmpty(userName)) {
Toast.makeText(this, R.string.your_name_should_not_be_empty, Toast.LENGTH_SHORT).show()
notifyBtnJoinEnable(true)
return
}
val type: String = tvRoomType.text.toString()
val roleTypeStr: String = tvRoleType.text.toString()
if (TextUtils.isEmpty(type)) {
Toast.makeText(this, R.string.room_type_should_not_be_empty, Toast.LENGTH_SHORT).show()
notifyBtnJoinEnable(true)
return
}
agoraLoading.show()
val roomType = getRoomType(type)
val roleType = getRoleType(roleTypeStr)
// val roomUuid = roomName.plus(roomType)
val roomUuid = HashUtil.md5(roomName).plus(roomType).lowercase()
// val userUuid = userName.plus(roleType)
val userUuid = HashUtil.md5(userName).plus(roleType).lowercase()
val roomRegion = getRoomRegion(regionStr)
val videoStreamKey: String = edVideoStreamKey.text.toString()
ConfigUtil.getV3Config(
AppHostUtil.getAppHostUrl(roomRegion),
roomUuid,
roleType,
userUuid,
object : EduCallback<ConfigData> {
override fun onSuccess(info: ConfigData?) {
// Use authentication info from server instead
info?.let {
// Room default duration is 30 minutes
val duration = 1800L
val userProperties = mutableMapOf<String, String>()
userProperties["avatar"] =
"https://download-sdk.oss-cn-beijing.aliyuncs.com/downloads/IMDemo/avatar/Image9.png"
val config = AgoraEduLaunchConfig(
userName,
userUuid,
roomName,
roomUuid,
roleType,
roomType,
it.token,
null,
duration
)
// 可选参数:加密方式
if (!TextUtils.isEmpty(videoStreamKey) && encryptMode != AgoraEduEncryptMode.NONE.value) {
config.mediaOptions =
AgoraEduMediaOptions(AgoraEduMediaEncryptionConfigs(videoStreamKey, encryptMode))
}
config.appId = it.appId
// 可选参数:区域
config.region = roomRegion
// 可选参数:用户参数
config.userProperties = userProperties
config.videoEncoderConfig = EduContextVideoEncoderConfig(
FcrStreamParameters.HeightStream.width,
FcrStreamParameters.HeightStream.height,
FcrStreamParameters.HeightStream.frameRate,
FcrStreamParameters.HeightStream.bitRate
)
// 互动直播比极速直播更快,延迟少
config.latencyLevel = AgoraEduLatencyLevel.AgoraEduLatencyLevelUltraLow
testData(config) // 测试,忽略
setConfigPublicCourseware(config) // 测试数据
configVocational(config) // 测试数据
// 测试:暗黑模式
val isNightMode = PreferenceManager.get(Constants.KEY_SP_NIGHT, false)
config.uiMode = if (isNightMode) AgoraEduUIMode.DARK else AgoraEduUIMode.LIGHT
// 暗黑模式,建议这个写在Application中,避免页面重启
if (isNightMode) {
SkinUtils.setNightMode(true)
} else {
SkinUtils.setNightMode(false)
}
AgoraClassroomSDK.setConfig(AgoraClassSdkConfig(it.appId))
launch(config)
Log.e(TAG, "appId = ${config.appId}")
}
}
override fun onFailure(error: EduError) {
agoraLoading.dismiss()
ToastManager.showShort("Get Token error: ${error.msg} ( ${error.type})")
notifyBtnJoinEnable(true)
}
})
}
fun launch(config: AgoraEduLaunchConfig) {
AgoraClassroomSDK.launch(this, config, AgoraEduLaunchCallback { event ->
Log.e(TAG, ":launch-课堂状态:" + event.name)
runOnUiThread {
agoraLoading.dismiss()
notifyBtnJoinEnable(true)
}
if (event == AgoraEduEvent.AgoraEduEventForbidden) {
runOnUiThread {
mDialog = ForbiddenDialogBuilder(this)
.title(resources.getString(R.string.join_forbidden_title))
.message(resources.getString(R.string.join_forbidden_message))
.positiveText(resources.getString(R.string.join_forbidden_button_confirm))
.positiveClick(View.OnClickListener {
if (mDialog != null && mDialog!!.isShowing) {
mDialog!!.dismiss()
mDialog = null
}
})
.build()
mDialog?.show()
}
}
})
}
fun testData(config: AgoraEduLaunchConfig) {
val isFastRoom = PreferenceManager.get(Constants.KEY_SP_FAST, false)
if (isFastRoom) {
config.latencyLevel = AgoraEduLatencyLevel.AgoraEduLatencyLevelLow
}
}
/**
* 职教数据
*/
private fun configVocational(launchConfig: AgoraEduLaunchConfig) {
if (tvRoomType.text == getString(R.string.large_class_vocational)) {
when (tvServiceType.text) {
getString(R.string.service_live_premium) -> {
launchConfig.latencyLevel = AgoraEduLatencyLevel.AgoraEduLatencyLevelUltraLow
//launchConfig.serviceType = AgoraServiceType.LivePremium
}
getString(R.string.service_live_standard) -> {
launchConfig.latencyLevel = AgoraEduLatencyLevel.AgoraEduLatencyLevelLow
//launchConfig.serviceType = AgoraServiceType.LiveStandard
}
getString(R.string.service_cdn) -> {
launchConfig.latencyLevel = AgoraEduLatencyLevel.AgoraEduLatencyLevelLow
launchConfig.serviceType = AgoraServiceType.CDN
}
getString(R.string.service_fusion) -> {
launchConfig.latencyLevel = AgoraEduLatencyLevel.AgoraEduLatencyLevelLow
launchConfig.serviceType = AgoraServiceType.Fusion
}
getString(R.string.service_screen_share) -> {
launchConfig.latencyLevel = AgoraEduLatencyLevel.AgoraEduLatencyLevelLow
launchConfig.serviceType = AgoraServiceType.MixStreamCDN
}
getString(R.string.service_hosting_scene) -> {
launchConfig.latencyLevel = AgoraEduLatencyLevel.AgoraEduLatencyLevelLow
launchConfig.serviceType = AgoraServiceType.HostingScene
}
}
}
}
/**
* 带入课件
*/
fun setConfigPublicCourseware(launchConfig: AgoraEduLaunchConfig) {
val courseware0 = CoursewareUtil.transfer(DefaultPublicCoursewareJson.data0)
val courseware1 = CoursewareUtil.transfer(DefaultPublicCoursewareJson.data1)
val publicCoursewares = ArrayList<AgoraEduCourseware>(2)
publicCoursewares.add(courseware0)
publicCoursewares.add(courseware1)
val cloudDiskExtra = mutableMapOf<String, Any>()
cloudDiskExtra[Statics.publicResourceKey] = publicCoursewares
cloudDiskExtra[Statics.configKey] = Pair(launchConfig.appId, launchConfig.userUuid)
val widgetConfigs = mutableListOf<AgoraWidgetConfig>()
widgetConfigs.add(AgoraWidgetConfig(FCRCloudDiskWidget::class.java, AgoraWidgetDefaultId.AgoraCloudDisk.id, extraInfo = cloudDiskExtra))
// 进入1v1教室,打开课件
//val coursewares = mutableMapOf<String, Any>()
//coursewares[Statics.publicResourceKey] = publicCoursewares
//widgetConfigs.add(AgoraWidgetConfig(widgetClass = AgoraWhiteBoardWidget::class.java, widgetId = AgoraWidgetDefaultId.WhiteBoard.id, extraInfo = coursewares))
launchConfig.widgetConfigs = widgetConfigs
}
private fun notifyBtnJoinEnable(enable: Boolean) {
runOnUiThread {
if (tvRoomType.text == getString(R.string.large_class_vocational)) {
btnJoin.isEnabled = enable && roomNameValid && userNameNameValid && roomTypeValid && roleTypeValid && serviceTypeValid
} else {
btnJoin.isEnabled = enable && roomTypeValid && roleTypeValid
}
}
}
private fun handleK12RoomTypeClick(strId: Int) {
tvRoomType.setText(strId)
popupAnimationUtil.runDismissAnimation(cardRoomType, (cardRoomType.width / 2).toFloat(), 0f) {
cardRoomType.visibility = GONE
icDownUp.isActivated = false
}
roomTypeValid = true
// tvRoleType.setText(R.string.role_student)
// roleTypeValid = true
serviceTypeLayout.visibility = GONE
forceRoleType(false)
notifyBtnJoinEnable(true)
}
private fun handleArtRoomTypeClick(strId: Int) {
tvRoomType.setText(strId)
popupAnimationUtil.runDismissAnimation(cardRoomType, (cardRoomType.width / 2).toFloat(), 0f) {
cardRoomType.visibility = GONE
icDownUp.isActivated = false
}
forceRoleType(false)
roomTypeValid = true
serviceTypeLayout.visibility = GONE
notifyBtnJoinEnable(true)
}
private fun handleVocationalRoomTypeClick(strId: Int) {
tvRoomType.setText(strId)
popupAnimationUtil.runDismissAnimation(cardRoomType, (cardRoomType.width / 2).toFloat(), 0f) {
cardRoomType.visibility = GONE
icDownUp.isActivated = false
}
roomTypeValid = true
notifyBtnJoinEnable(true)
forceRoleType(true)
serviceTypeLayout.visibility = VISIBLE
icServiceDownUp.isActivated = false
refreshServiceTypeListColor()
}
private fun handleServiceTypeClick(strId: Int) {
tvServiceType.setText(strId)
popupAnimationUtil.runDismissAnimation(cardServiceType, (cardServiceType.width / 2).toFloat(), 0f) {
cardServiceType.visibility = GONE
icServiceDownUp.isActivated = false
}
serviceTypeValid = true
notifyBtnJoinEnable(true)
}
private fun refreshRoomTypeListColor() {
tvOne2One.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvSmallClass.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvSmallClassArt.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvLargeClassArt.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvLargeClass.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvLargeClassVocational.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
when (tvRoomType.text) {
getString(R.string.one2one_class) -> {
tvOne2One.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.small_class) -> {
tvSmallClass.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.small_class_art) -> {
tvSmallClassArt.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.large_class_art) -> {
tvLargeClassArt.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.large_class) -> {
tvLargeClass.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.large_class_vocational) -> {
tvLargeClassVocational.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
else -> {
}
}
}
private fun refreshServiceTypeListColor() {
tvServiceLivePremium.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvServiceLiveStandard.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvServiceCdn.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvServiceFusion.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
when (tvServiceType.text) {
getString(R.string.service_live_premium) -> {
tvServiceLivePremium.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.service_live_standard) -> {
tvServiceLiveStandard.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.service_cdn) -> {
tvServiceCdn.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.large_class_art) -> {
tvServiceFusion.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
}
}
private fun refreshRoleTypeListColor() {
tvRoleStudent.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvRoleTeacher.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
tvRoleAudience.setTextColor(ContextCompat.getColor(this, R.color.fcr_black))
when (tvRoleType.text) {
getString(R.string.role_student) -> {
tvRoleStudent.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.role_teacher) -> {
tvRoleTeacher.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
getString(R.string.role_audience) -> {
tvRoleAudience.setTextColor(ContextCompat.getColor(this, R.color.text_selected))
}
else -> {
}
}
}
private fun getRoomType(typeName: String): Int {
return when (typeName) {
getString(R.string.one2one_class) -> {
AgoraEduRoomType.AgoraEduRoomType1V1.value
}
getString(R.string.small_class) -> {
AgoraEduRoomType.AgoraEduRoomTypeSmall.value
}
getString(R.string.small_class_art) -> {
AgoraEduRoomType.AgoraEduRoomTypeSmall.value
}
getString(R.string.large_class_art) -> {
AgoraEduRoomType.AgoraEduRoomTypeLecture.value
}
getString(R.string.large_class_vocational) -> {
AgoraEduRoomType.AgoraEduRoomTypeLecture.value
}
else -> {
AgoraEduRoomType.AgoraEduRoomTypeLecture.value
}
}
}
private fun getRoleType(typeName: String): Int {
return when (typeName) {
getString(R.string.role_teacher) -> {
AgoraEduRoleType.AgoraEduRoleTypeTeacher.value
}
getString(R.string.role_audience) -> {
AgoraEduRoleType.AgoraEduRoleTypeObserver.value
}
else -> AgoraEduRoleType.AgoraEduRoleTypeStudent.value
}
}
private fun getRoomRegion(region: String): String {
return when (region) {
getString(R.string.cn0) -> {
AgoraEduRegion.cn
}
getString(R.string.na0) -> {
AgoraEduRegion.na
}
getString(R.string.eu0) -> {
AgoraEduRegion.eu
}
getString(R.string.ap0) -> {
AgoraEduRegion.ap
}
else -> {
return AgoraEduRegion.default
}
}
}
private fun forceRoleType(isVocational: Boolean) {
if (isVocational) {
roleTypeValid = true
roleTypeLayout.isEnabled = false
icRoleDownUp.visibility = GONE
// vocational room force support student
tvRoleType.setText(R.string.fcr_role_student)
} else {
roleTypeLayout.isEnabled = true
icRoleDownUp.visibility = VISIBLE
}
refreshRoleTypeListColor()
}
override fun onDestroy() {
super.onDestroy()
tapCount?.reset()
agoraLoading.dismiss()
}
}
class TapCount(
context: Context,
private val count: Int,
private val interval: Long,
private val onCountDownEnd: Runnable? = null
) {
private var step: Int = 0
private val handler = Handler(context.mainLooper)
private val resetRunnable = Runnable {
reset()
}
@Synchronized
fun reset() {
step = 0
handler.removeCallbacks(resetRunnable)
}
@Synchronized
fun step() {
step++
if (step == count) {
handler.post {
onCountDownEnd?.run()
reset()
}
} else {
handler.removeCallbacks(resetRunnable)
handler.postDelayed(resetRunnable, interval)
}
}
} | 5 | null | 19 | 16 | 650f5c9892763a61ed4e468003bf1757abd90238 | 45,531 | CloudClass-Android | MIT License |
plugins/kotlin/base/facet/tests/test/KotlinFacetBridgeTest.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
import com.intellij.facet.FacetManager
import com.intellij.facet.impl.ui.FacetEditorImpl
import com.intellij.facet.mock.MockFacetEditorContext
import com.intellij.facet.ui.FacetEditorContext
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.roots.ui.configuration.projectRoot.FacetConfigurable
import com.intellij.platform.backend.workspace.WorkspaceModel
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.workspaceModel.KotlinSettingsEntity
class KotlinFacetBridgeTest : KotlinFacetTestCase() {
fun testSimpleKotlinFacetCreate() {
getKotlinFacet()
checkStorageForEntityAndFacet()
}
fun testEditorTabConfigurationOnFacetCreation() {
val facet = getKotlinFacet()
val editorContext: FacetEditorContext = MockFacetEditorContext(getKotlinFacet())
FacetEditorImpl(editorContext, facet.configuration).let {
it.getComponent()
it.reset()
assertNotNull(it.component)
}
}
fun testFacetRenameAndRemove() {
val oldFacetName = "Kotlin"
val newFacetName = "NewFacetName"
val mainFacet = getKotlinFacet()
checkStorageForEntityAndFacet()
val facetManager = FacetManager.getInstance(myModule)
var modifiableModel = facetManager.createModifiableModel()
assertEquals(oldFacetName, modifiableModel.getFacetName(mainFacet))
modifiableModel.rename(mainFacet, newFacetName)
checkStorageForEntityAndFacet()
assertEquals(oldFacetName, modifiableModel.getFacetName(mainFacet))
assertEquals(newFacetName, modifiableModel.getNewName(mainFacet))
runWriteActionAndWait {
modifiableModel.commit()
}
assertEquals(newFacetName, mainFacet.name)
checkStorageForEntityAndFacet(facetName = newFacetName)
modifiableModel = facetManager.createModifiableModel()
modifiableModel.removeFacet(mainFacet)
runWriteActionAndWait {
modifiableModel.commit()
}
val entityStorage = WorkspaceModel.getInstance(myProject).currentSnapshot
assertEmpty(entityStorage.entities(KotlinSettingsEntity::class.java).toList())
assertEmpty(facetManager.allFacets)
}
fun testCreateFacetWithDisabledUseProjectSettingsFlag() {
val mainFacet = getKotlinFacet()
checkStorageForEntityAndFacet()
mainFacet.configuration.settings.useProjectSettings = false
fireFacetChangedAndValidateKotlinFacet(mainFacet)
}
fun testCreateFacetEnableHmpp() {
val mainFacet = getKotlinFacet()
checkStorageForEntityAndFacet()
mainFacet.configuration.settings.isHmppEnabled = true
fireFacetChangedAndValidateKotlinFacet(mainFacet)
}
private fun fireFacetChangedAndValidateKotlinFacet(mainFacet: KotlinFacet) {
val allFacets = FacetManager.getInstance(myModule).allFacets
assertSize(1, allFacets)
assertSame(mainFacet, allFacets[0])
allFacets.forEach { facet -> FacetManager.getInstance(myModule).facetConfigurationChanged(facet) }
checkStorageForEntityAndFacet()
}
private fun getKotlinFacet(): KotlinFacet {
val facetManager = FacetManager.getInstance(myModule)
assertSize(1, facetManager.allFacets)
return facetManager.allFacets[0] as KotlinFacet
}
private fun checkStorageForEntityAndFacet(facetName: String = "Kotlin") {
val entityStorage = WorkspaceModel.getInstance(myProject).currentSnapshot
val entities: List<KotlinSettingsEntity> = entityStorage.entities(KotlinSettingsEntity::class.java).toList()
assertSize(1, entities)
val entity = entities[0]
assertEquals(facetName, entity.name)
assertEquals(myModule.name, entity.module.name)
val facetManager = FacetManager.getInstance(myModule)
assertSize(1, facetManager.allFacets)
val facet = facetManager.allFacets[0] as KotlinFacet
assertEquals(facetName, facet.name)
assertTrue(
"Use project settings differs. Entity: ${entity.useProjectSettings}, facet: ${facet.configuration.settings.useProjectSettings}",
entity.useProjectSettings == facet.configuration.settings.useProjectSettings
)
assertTrue(
"isHmppEnabled differs. Entity: ${entity.isHmppEnabled}, facet: ${facet.configuration.settings.isHmppEnabled}",
entity.isHmppEnabled == facet.configuration.settings.isHmppEnabled
) //// source roots
//val facetSourceRoots = facet.externalSource.also { println(it) }
//val entitySourceRoots = entity.sourceRoots.also { println(it) }
//val allModuleSourceRoots = entity.module.sourceRoots.map { it.url.url }.also { println(it) }
//val entitySourceRootsValid = facetSourceRoots == entitySourceRoots
//val allModuleSourceRootsValid = facetSourceRoots == allModuleSourceRoots && entitySourceRoots.isEmpty()
//val sourceRootsValid = entitySourceRootsValid || allModuleSourceRootsValid
//assertTrue("Invalid source roots", sourceRootsValid)
// web roots
//val facetWebRoots = facet.webRoots.map { WebRootData(it.directoryUrl, it.relativePath) }
//val entityWebRoots = entity.webRoots
//assertEquals(facetWebRoots, entityWebRoots)
// //config files
//val facetConfigFiles = facet.descriptorsContainer.configFiles.map { ConfigFileItem(it.info.metaData.id, it.url) }
//val entityConfigFiles = entity.configFileItems
//assertEquals(facetConfigFiles.size, entityConfigFiles.size)
}
} | 251 | null | 5079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 5,809 | intellij-community | Apache License 2.0 |
formula-test/src/test/java/com/instacart/formula/test/TestFormulaTest.kt | instacart | 171,923,573 | false | {"Kotlin": 565903, "Shell": 1203, "Ruby": 256} | package com.instacart.formula.test
import com.google.common.truth.Truth.assertThat
import junit.framework.Assert.fail
import org.junit.Test
class TestFormulaTest {
@Test fun `assert running count is zero when formula is not running`() {
val formula = TestSimpleFormula()
formula.implementation.assertRunningCount(0)
val observer = formula.test()
observer.input(SimpleFormula.Input())
formula.implementation.assertRunningCount(1)
observer.dispose()
formula.implementation.assertRunningCount(0)
}
@Test
fun `assert running count throws an exception when count does not match`() {
val formula = TestSimpleFormula()
val result = runCatching {
formula.implementation.assertRunningCount(5)
}
assertThat(result.exceptionOrNull()).hasMessageThat().contains(
"Expected 5 running formulas, but there were 0 instead"
)
}
@Test fun `emits initial output when subscribed`() {
val initialOutput = SimpleFormula.Output(100, "random")
val formula = TestSimpleFormula(initialOutput)
formula.test().input(SimpleFormula.Input()).output {
assertThat(this).isEqualTo(initialOutput)
}
}
@Test fun `output throws an exception when no test formula is running`() {
try {
val formula = TestSimpleFormula()
formula.implementation.output(SimpleFormula.Output(0, ""))
fail("Should not happen")
} catch (e: Exception) {
assertThat(e).hasMessageThat().startsWith("Formula is not running")
}
}
@Test fun `output emits new output to the parent`() {
val formula = TestSimpleFormula()
val observer = formula.test().input(SimpleFormula.Input())
val newOutput = SimpleFormula.Output(5, "random")
formula.implementation.output(newOutput)
observer.output { assertThat(this).isEqualTo(newOutput) }
}
@Test fun `output with key throws an exception when test formula matching key is not running`() {
try {
val newOutput = SimpleFormula.Output(5, "random")
val formula = TestSimpleFormula()
val observer = formula.test().input(SimpleFormula.Input())
formula.implementation.output("random-key", newOutput)
fail("Should not happen")
} catch (e: Exception) {
assertThat(e).hasMessageThat().startsWith("Formula for random-key is not running, there are [simple-formula-key] running")
}
}
@Test fun `output with key emits new output to the parent when key matches`() {
val newOutput = SimpleFormula.Output(5, "random")
val formula = TestSimpleFormula()
val observer = formula.test().input(SimpleFormula.Input())
formula.implementation.output("simple-formula-key", newOutput)
observer.output { assertThat(this).isEqualTo(newOutput) }
}
@Test fun `updateOutput uses previous output and emits new one to the parent`() {
val formula = TestSimpleFormula()
val observer = formula.test().input(SimpleFormula.Input())
formula.implementation.updateOutput { copy(outputId = outputId.inc()) }
observer.output { assertThat(this).isEqualTo(SimpleFormula.Output(1, "")) }
}
@Test fun `updateOutput with key emits a modified output when key matches a running formula`() {
val formula = TestSimpleFormula()
val observer = formula.test().input(SimpleFormula.Input())
formula.implementation.updateOutput("simple-formula-key") { copy(outputId = outputId.inc()) }
observer.output { assertThat(this).isEqualTo(SimpleFormula.Output(1, "")) }
}
@Test fun `updateOutput with key throws an error when there is no running formula matching the key`() {
try {
val formula = TestSimpleFormula()
val observer = formula.test().input(SimpleFormula.Input())
formula.implementation.updateOutput("random-key") { copy(outputId = outputId.inc()) }
observer.output { assertThat(this).isEqualTo(SimpleFormula.Output(1, "")) }
fail()
} catch (e: Exception) {
assertThat(e).hasMessageThat().startsWith("Formula for random-key is not running, there are [simple-formula-key] running")
}
}
@Test fun `input() throw an exception when no formulas are running`() {
try {
val formula = TestSimpleFormula()
formula.implementation.input { }
fail("Should not happen")
} catch (e: Exception) {
assertThat(e).hasMessageThat().startsWith("Formula is not running")
}
}
@Test fun `input() emits the last input provided by the parent`() {
val myInput = SimpleFormula.Input("my-input-id")
val formula = TestSimpleFormula()
val observer = formula.test()
// Initial input
observer.input(myInput)
formula.implementation.input { assertThat(this).isEqualTo(myInput) }
// Next input
val nextInput = SimpleFormula.Input("next-input-id")
observer.input(nextInput)
formula.implementation.input { assertThat(this).isEqualTo(nextInput) }
}
@Test fun `input() throws an error when NO formula that matches the key provided is running`() {
try {
val formula = TestSimpleFormula()
formula.test().input(SimpleFormula.Input())
formula.implementation.input(key = "random-key") {}
fail("Should not happen")
} catch (e: Exception) {
assertThat(e).hasMessageThat().startsWith("Formula for random-key is not running, there are [simple-formula-key] running")
}
}
@Test fun `input() works as expected when formula that matches the key provided is running`() {
val myInput = SimpleFormula.Input()
val formula = TestSimpleFormula()
formula.test().input(myInput)
formula.implementation.input(key = "simple-formula-key") {
assertThat(this).isEqualTo(myInput)
}
}
@Test fun `mostRecentInput returns last input passed by parent`() {
val inputA = SimpleFormula.Input("a")
val inputB = SimpleFormula.Input("b")
val formula = TestSimpleFormula()
formula.test().input(inputA).input(inputB)
val mostRecentInput = formula.implementation.mostRecentInput()
assertThat(mostRecentInput).isEqualTo(inputB)
}
@Test fun `mostRecentInputs returns all inputs parent passed`() {
val inputA = SimpleFormula.Input("a")
val inputB = SimpleFormula.Input("b")
val formula = TestSimpleFormula()
formula.test().input(inputA).input(inputB)
assertThat(formula.implementation.mostRecentInputs()).containsExactly(
inputA, inputB
).inOrder()
}
@Test fun `inputByKey returns last input passed by parent`() {
val inputA = SimpleFormula.Input("a")
val inputB = SimpleFormula.Input("b")
val formula = TestSimpleFormula()
formula.test().input(inputA).input(inputB)
val inputByKey = formula.implementation.inputByKey(SimpleFormula.CUSTOM_KEY)
assertThat(inputByKey).isEqualTo(inputB)
}
@Test fun `inputsByKey returns all inputs parent passed`() {
val inputA = SimpleFormula.Input("a")
val inputB = SimpleFormula.Input("b")
val formula = TestSimpleFormula()
formula.test().input(inputA).input(inputB)
assertThat(formula.implementation.inputsByKey(SimpleFormula.CUSTOM_KEY)).containsExactly(
inputA, inputB
).inOrder()
}
@Test fun `default key is null`() {
val formula = TestSimpleFormula(useCustomKey = false)
val key = formula.key(SimpleFormula.Input())
assertThat(key).isNull()
}
@Test fun `custom key is applied correctly`() {
val formula = TestSimpleFormula(useCustomKey = true)
val key = formula.key(SimpleFormula.Input())
assertThat(key).isEqualTo(SimpleFormula.CUSTOM_KEY)
}
}
| 7 | Kotlin | 14 | 151 | 26d544ea41b7a5ab2fa1a3b9ac6b668e69fe4dff | 8,138 | formula | BSD 3-Clause Clear License |
app-aqi/src/main/java/com/android/app_aqi/SharedViewModel.kt | blelalr | 245,851,898 | false | {"Gradle": 8, "Java Properties": 3, "Shell": 2, "Text": 1, "Ignore List": 6, "Batchfile": 2, "Markdown": 1, "JSON": 2, "Proguard": 4, "XML": 83, "Java": 22, "Kotlin": 35} | package com.android.app_aqi
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.android.app_aqi.model.AqiModel
import com.android.app_aqi.model.SiteModel
import com.android.app_aqi.repository.AqiRepository
import com.android.app_aqi.repository.AqiRepositoryImpl
class SharedViewModel(private val repositoryImpl: AqiRepository = AqiRepositoryImpl()) : ViewModel() {
var currentPos = 0
lateinit var allSite :List<SiteModel>
lateinit var followedSite :List<AqiModel>
fun getFollowSiteList() : LiveData<List<SiteModel>> {
return repositoryImpl.getAllFollowedSite()
}
fun getAllSiteList() : LiveData<List<SiteModel>> {
return repositoryImpl.getAllSiteList()
}
fun followSite(siteId: String) {
repositoryImpl.followSite(siteId)
}
fun unFollowSite(siteId: String) {
repositoryImpl.unFollowSite(siteId)
}
fun getLast12HourAqiDataBySiteId(siteId: String) : LiveData<List<AqiModel>>{
return repositoryImpl.getLast12HourAqiDataBySiteId(siteId)
}
fun getLastAqiDataBySiteId(siteIdList: List<SiteModel>) : LiveData<List<AqiModel>> {
return repositoryImpl.getLastAqiDataBySiteIdList(siteIdList)
}
} | 1 | null | 1 | 1 | 73c3365801ea90c99f1c742b71f5a09a42391edc | 1,230 | appcore-android | Apache License 2.0 |
core/domain/src/main/java/ksnd/hiraganaconverter/core/domain/repository/ReviewInfoRepository.kt | kosenda | 565,470,862 | false | {"Kotlin": 300958, "Ruby": 230} | package ksnd.hiraganaconverter.core.domain.repository
import kotlinx.coroutines.flow.Flow
import ksnd.hiraganaconverter.core.model.ReviewInfo
interface ReviewInfoRepository {
val reviewInfo: Flow<ReviewInfo>
suspend fun countUpTotalConvertCount(): Int
suspend fun updateLastRequestReviewLocalDate()
suspend fun completedRequestReview()
}
| 9 | Kotlin | 1 | 29 | d9eb05268100fb8c232e4e97cae9511f41352589 | 356 | hiragana-converter | Apache License 2.0 |
plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/archetype/MavenCatalog.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.indices.archetype
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.util.io.systemIndependentPath
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.project.staticOrBundled
import org.jetbrains.idea.maven.utils.MavenWslUtil
import org.jetbrains.idea.maven.wizards.MavenWizardBundle
import java.io.File
import java.net.URL
import java.nio.file.Path
sealed interface MavenCatalog {
val name: @NlsSafe String
val location: @NlsSafe String
sealed interface System : MavenCatalog {
object Internal : System {
override val name: String = MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.internal.name")
override val location: String = ""
}
data class DefaultLocal(private val project: Project) : System {
val file: File
get() {
val generalSettings = MavenProjectsManager.getInstance(project).generalSettings
val mavenConfig = generalSettings.mavenConfig
val mavenHome = generalSettings.mavenHomeType.staticOrBundled()
val userSettings = MavenWslUtil.getUserSettings(project, "", mavenConfig).path
return MavenWslUtil.getLocalRepo(project, "", mavenHome, userSettings, mavenConfig)
}
override val name: String = MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.default.local.name")
override val location: String get() = file.systemIndependentPath
}
object MavenCentral : System {
val url = URL("https://repo.maven.apache.org/maven2")
override val name: String = MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.central.name")
override val location: String = url.toExternalForm()
}
}
data class Local(override val name: String, val path: Path) : MavenCatalog {
override val location: String = path.systemIndependentPath
}
data class Remote(override val name: String, val url: URL) : MavenCatalog {
override val location: String = url.toExternalForm()
}
} | 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 2,291 | intellij-community | Apache License 2.0 |
model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/proxy/ReferenceExploder.kt | kohesive | 81,814,921 | false | null | package uy.kohesive.iac.model.aws.proxy
import java.util.*
import kotlin.collections.ArrayList
fun explodeReference(str: String): List<ResourceNode> {
val stack = Stack<ResourceNode>()
fun isWithinUnresolvedReference()
= stack.filter { it.isReferenceNode() }.any { it.isUnresolved() }
var i = 0
while (i < str.length) {
val currentNode: ResourceNode? = if (stack.empty()) null else stack.peek()
val nextRefStart = str.indexOf("{{kohesive:", i)
val nextRefEnd = str.indexOf("}}", i)
// Start new reference
if (nextRefStart == i) {
// We need to figure out the type of reference
val refTypeStart = nextRefStart + "{{kohesive:".length
val refTypeEnd = str.indexOf(":", refTypeStart)
val refType = ReferenceType.fromString(str.substring(
startIndex = refTypeStart,
endIndex = refTypeEnd
))
// Push the new reference node to the stack
val referenceNode = ResourceNode.forReferenceType(refType)
stack.push(referenceNode)
i = refTypeEnd + 1
} else if (nextRefEnd == i && isWithinUnresolvedReference()) {
// Pop the arguments (reference parts) and assign them as reference children
val referenceArguments = ArrayList<ResourceNode>()
while (true) {
val node = stack.peek()
if (node.isReferenceNode() && node.isUnresolved()) {
for (referenceNode in referenceArguments) {
node.insertChild(referenceNode)
}
break
} else {
referenceArguments.add(stack.pop())
}
}
i += 2
} else {
if (str[i] == ':' && isWithinUnresolvedReference()) {
if (i != nextRefStart - 1) {
stack.push(ResourceNode.StringLiteralNode())
}
i++; continue
}
// Must be a string literal
val stringNode = currentNode as? ResourceNode.StringLiteralNode ?:
ResourceNode.StringLiteralNode().apply {
stack.push(this)
}
stringNode.append(str[i++])
}
}
return stack
}
sealed class ResourceNode(
val arity: Int
) {
companion object {
fun forReferenceType(refType: ReferenceType) = when (refType) {
ReferenceType.Ref -> RefNode()
ReferenceType.RefProperty -> RefPropertyNode()
ReferenceType.Var -> VariableNode()
ReferenceType.Map -> MapNode()
ReferenceType.Implicit -> ImplicitNode()
}
}
class StringLiteralNode : ResourceNode(0) {
private val value: StringBuffer = StringBuffer()
fun append(c: Char) = value.append(c)
fun value() = value.toString()
override fun toString() = "\"$value\""
}
class ImplicitNode : ResourceNode(1)
class VariableNode : ResourceNode(1)
class RefNode : ResourceNode(2)
class RefPropertyNode : ResourceNode(3)
class MapNode : ResourceNode(3)
val children = ArrayList<ResourceNode>()
fun isReferenceNode() = arity > 0
fun isUnresolved() = children.size < arity
fun insertChild(childNode: ResourceNode, index: Int = 0) {
if (children.size + 1 > arity) {
throw IllegalStateException("Max children count reached for ${ this::class.simpleName }")
}
children.add(index, childNode)
}
override fun toString() = "${ this::class.simpleName }: (${children.joinToString(", ")})"
}
| 0 | Kotlin | 1 | 3 | c52427c99384396ea60f436750932ed12aad4e6d | 3,774 | kohesive-iac | MIT License |
sample/src/main/java/tech/dojo/pay/sdksample/CardPaymentActivity.kt | dojo-engineering | 478,120,913 | false | {"Kotlin": 1013793} | package tech.dojo.pay.sdksample
import tech.dojo.pay.sdk.DojoSdk
import tech.dojo.pay.sdk.card.entities.DojoCardPaymentPayLoad
import tech.dojo.pay.sdk.card.entities.DojoGPayPayload
import tech.dojo.pay.sdk.card.entities.DojoPaymentIntent
import tech.dojo.pay.sdk.card.entities.DojoSDKDebugConfig
class CardPaymentActivity : CardPaymentBaseActivity() {
private val cardPayment = DojoSdk.createCardPaymentHandler(this) { result ->
setProgressIndicatorVisible(false)
showResult(result)
}
private val savedCardPayment = DojoSdk.createSavedCardPaymentHandler(this) { result ->
setProgressIndicatorVisible(false)
showResult(result)
}
private val gPayment = DojoSdk.createGPayHandler(this) { result ->
showResult(result)
}
override fun onSandboxChecked(isChecked: Boolean) {
val dojoSDKDebugConfig = DojoSDKDebugConfig(
isSandboxWallet = isChecked,
isSandboxIntent = isChecked
)
DojoSdk.dojoSDKDebugConfig = dojoSDKDebugConfig
}
override fun onPayClicked(token: String, payload: DojoCardPaymentPayLoad.FullCardPaymentPayload) {
setProgressIndicatorVisible(true)
cardPayment.executeCardPayment(token, payload)
}
override fun onPaySavedCardClicked(
token: String,
payload: DojoCardPaymentPayLoad.SavedCardPaymentPayLoad
) {
setProgressIndicatorVisible(true)
savedCardPayment.executeSavedCardPayment(token, payload)
}
override fun onGPayClicked(
dojoGPayPayload: DojoGPayPayload,
dojoPaymentIntent: DojoPaymentIntent
) {
gPayment.executeGPay(dojoGPayPayload, dojoPaymentIntent)
}
}
| 2 | Kotlin | 2 | 3 | 5f2e422ed27a1440232dcc629ce4f4b9502b70f6 | 1,704 | android-dojo-pay-sdk | MIT License |
app/src/main/java/com/uragiristereo/mikansei/MikanseiModule.kt | uragiristereo | 583,834,091 | false | null | package com.uragiristereo.mikansei
import com.uragiristereo.mikansei.core.danbooru.DanbooruRepositoryImpl
import com.uragiristereo.mikansei.core.database.databaseModule
import com.uragiristereo.mikansei.core.domain.DomainModule
import com.uragiristereo.mikansei.core.domain.module.danbooru.DanbooruRepository
import com.uragiristereo.mikansei.core.network.NetworkModule
import com.uragiristereo.mikansei.core.preferences.PreferencesRepository
import com.uragiristereo.mikansei.core.preferences.PreferencesRepositoryImpl
import com.uragiristereo.mikansei.core.product.ProductModule
import com.uragiristereo.mikansei.feature.filters.FiltersViewModel
import com.uragiristereo.mikansei.feature.home.HomeModule
import com.uragiristereo.mikansei.feature.home.more.MoreViewModel
import com.uragiristereo.mikansei.feature.image.ImageModule
import com.uragiristereo.mikansei.feature.search.SearchViewModel
import com.uragiristereo.mikansei.feature.settings.SettingsViewModel
import com.uragiristereo.mikansei.feature.user.UserModule
import com.uragiristereo.mikansei.ui.MainViewModel
import kotlinx.coroutines.CompletableJob
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import org.koin.androidx.viewmodel.dsl.viewModelOf
import org.koin.core.module.Module
import org.koin.core.module.dsl.bind
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.module
object MikanseiModule {
operator fun invoke(): Module = module {
includes(
listOf(
databaseModule(),
DomainModule(),
NetworkModule(),
HomeModule(),
ImageModule(),
UserModule(),
ProductModule(),
)
)
single { SupervisorJob() }
factory { CoroutineScope(context = Dispatchers.Default + get<CompletableJob>()) }
singleOf(::DanbooruRepositoryImpl) { bind<DanbooruRepository>() }
singleOf(::PreferencesRepositoryImpl) { bind<PreferencesRepository>() }
viewModelOf(::MainViewModel)
viewModelOf(::SearchViewModel)
viewModelOf(::MoreViewModel)
viewModelOf(::FiltersViewModel)
viewModelOf(::SettingsViewModel)
}
}
| 3 | null | 2 | 62 | 4f136b0479ee7772f3d7ba48927cef9389d5c2be | 2,266 | Mikansei | Apache License 2.0 |
ui/src/sharedTest/kotlin/com/alexvanyo/composelife/ui/info/CellUniverseInfoItemTests.kt | alexvanyo | 375,146,193 | false | null | /*
* Copyright 2022 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.alexvanyo.composelife.ui.info
import androidx.compose.foundation.layout.Column
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertIsToggleable
import androidx.compose.ui.test.isToggleable
import androidx.compose.ui.test.junit4.StateRestorationTester
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
class CellUniverseInfoItemTests {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun editing_preview() {
composeTestRule.setContent {
CellUniverseInfoItemEditingPreview()
}
}
@Test
fun not_editing_preview() {
composeTestRule.setContent {
CellUniverseInfoItemNotEditingPreview()
}
}
@Test
fun can_check_while_editing() {
val cellUniverseInfoItemState = CellUniverseInfoItemState()
composeTestRule.setContent {
Column {
InfoItem(
cellUniverseInfoItemContent = CellUniverseInfoItemContent(cellUniverseInfoItemState) { "Test" },
isEditing = true,
)
}
}
composeTestRule.onNodeWithText("Test")
.assertIsToggleable()
.assertIsOn()
.performClick()
assertFalse(cellUniverseInfoItemState.isChecked)
composeTestRule.onNodeWithText("Test").assertIsOff()
}
@Test
fun can_uncheck_while_editing() {
val cellUniverseInfoItemState = CellUniverseInfoItemState(isChecked = false)
composeTestRule.setContent {
Column {
InfoItem(
cellUniverseInfoItemContent = CellUniverseInfoItemContent(cellUniverseInfoItemState) { "Test" },
isEditing = true,
)
}
}
composeTestRule.onNodeWithText("Test")
.assertIsToggleable()
.assertIsOff()
.performClick()
assertTrue(cellUniverseInfoItemState.isChecked)
composeTestRule.onNodeWithText("Test").assertIsOn()
}
@Test
fun unchecked_item_is_hidden_while_not_editing() {
val cellUniverseInfoItemState = CellUniverseInfoItemState(isChecked = false)
composeTestRule.setContent {
Column {
InfoItem(
cellUniverseInfoItemContent = CellUniverseInfoItemContent(cellUniverseInfoItemState) { "Test" },
isEditing = false,
)
}
}
composeTestRule.onNodeWithText("Test").assertDoesNotExist()
}
@Test
fun checkbox_is_hidden_for_checked_item_is_hidden_while_not_editing() {
val cellUniverseInfoItemState = CellUniverseInfoItemState(isChecked = true)
composeTestRule.setContent {
Column {
InfoItem(
cellUniverseInfoItemContent = CellUniverseInfoItemContent(cellUniverseInfoItemState) { "Test" },
isEditing = false,
)
}
}
composeTestRule.onNodeWithText("Test").assertIsDisplayed()
composeTestRule.onNode(isToggleable()).assertDoesNotExist()
}
@Test
fun is_checked_state_is_saved() {
val stateRestorationTester = StateRestorationTester(composeTestRule)
stateRestorationTester.setContent {
val cellUniverseInfoItemState = rememberCellUniverseInfoItemState()
Column {
InfoItem(
cellUniverseInfoItemContent = CellUniverseInfoItemContent(cellUniverseInfoItemState) { "Test" },
isEditing = true,
)
}
}
composeTestRule.onNodeWithText("Test")
.assertIsToggleable()
.assertIsOn()
.performClick()
composeTestRule.onNodeWithText("Test").assertIsOff()
stateRestorationTester.emulateSavedInstanceStateRestore()
composeTestRule.onNodeWithText("Test").assertIsOff()
}
}
| 5 | null | 6 | 7 | 15effbb45db9602bfd0f4256dd4f98a057ebf6cd | 5,032 | composelife | Apache License 2.0 |
mobile/src/main/java/com/aptopayments/mobile/repository/cardapplication/remote/entities/NewCardApplicationRequest.kt | ShiftFinancial | 130,093,227 | false | {"Markdown": 2, "Gradle": 5, "Text": 1, "Ignore List": 1, "Kotlin": 492, "JSON": 41, "XML": 2, "YAML": 1} | package com.aptopayments.mobile.repository.cardapplication.remote.entities
import com.google.gson.annotations.SerializedName
import java.io.Serializable
internal data class NewCardApplicationRequest(
@SerializedName("card_product_id")
val cardProductId: String
) : Serializable
| 0 | Kotlin | 0 | 5 | f79b3c532ae2dfec8e571b315401ef03d8e507f9 | 290 | shift-sdk-android | MIT License |
app/src/main/java/com/example/lunchtray/LunchTrayScreen.kt | ELIJAHMAITHYA | 699,069,208 | false | {"Kotlin": 47025} | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.lunchtray
import android.graphics.drawable.Icon
import android.icu.text.CaseMap.Title
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.lunchtray.datasource.DataSource
import com.example.lunchtray.model.OrderUiState
import com.example.lunchtray.ui.AccompanimentMenuScreen
import com.example.lunchtray.ui.CheckoutScreen
import com.example.lunchtray.ui.EntreeMenuScreen
import com.example.lunchtray.ui.OrderViewModel
import com.example.lunchtray.ui.SideDishMenuScreen
import com.example.lunchtray.ui.StartOrderScreen
// TODO: Screen enum
enum class LunchTrayScreen(@StringRes val title: Int) {
Start(title = R.string.app_name),
Entree_menu(title = R.string.choose_entree),
Sidedish_menu(title = R.string.choose_side_dish),
Accompaniment_menu(title = R.string.choose_accompaniment),
Checkout(title = R.string.order_checkout),
}
// TODO: AppBar
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LunchTrayScreenTopBar(
lunchTrayScreen: LunchTrayScreen,
canNavigateBack: Boolean,
navigateUp: () -> Unit = {},
modifier: Modifier = Modifier
) {
TopAppBar(
title = { Text(stringResource(lunchTrayScreen.title)) },
modifier = Modifier,
navigationIcon = {
if (canNavigateBack) {
IconButton(onClick = { navigateUp }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = stringResource(R.string.back_button)
)
}
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LunchTrayApp() {
// TODO: Create Controller and initialization
val navController = rememberNavController()
// Create ViewModel
val viewModel: OrderViewModel = viewModel()
val backStackEntry by navController.currentBackStackEntryAsState()
val currentScreen = LunchTrayScreen.valueOf(
backStackEntry?.destination?.route ?: LunchTrayScreen.Start.name
)
Scaffold(
topBar = {
LunchTrayScreenTopBar(
lunchTrayScreen = currentScreen,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = {
navController.navigateUp()
}
)
}
) { innerPadding ->
val uiState by viewModel.uiState.collectAsState()
// TODO: Navigation host
NavHost(
navController = navController,
startDestination = LunchTrayScreen.Start.name,
modifier = Modifier.padding(innerPadding)
) {
composable(route = LunchTrayScreen.Start.name) {
StartOrderScreen(
onStartOrderButtonClicked = {
navController.navigate(LunchTrayScreen.Entree_menu.name)
},
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
)
}
composable(route = LunchTrayScreen.Entree_menu.name) {
val context = LocalContext
EntreeMenuScreen(
options = DataSource.entreeMenuItems,
onCancelButtonClicked = {
CancelOrderAndNavigateToStart(
viewModel,
navController
)
},
onNextButtonClicked = { navController.navigate(LunchTrayScreen.Accompaniment_menu.name) },
onSelectionChanged = { item ->
viewModel.updateEntree(item)
},
modifier = Modifier
.fillMaxHeight()
.verticalScroll(rememberScrollState())
)
}
composable(route = LunchTrayScreen.Accompaniment_menu.name) {
val context = LocalContext.current
AccompanimentMenuScreen(
options = DataSource.accompanimentMenuItems,
onCancelButtonClicked = {
CancelOrderAndNavigateToStart(
viewModel,
navController
)
},
onNextButtonClicked = { navController.navigate(LunchTrayScreen.Sidedish_menu.name) },
onSelectionChanged = { item ->
viewModel.updateAccompaniment(item)
},
modifier = Modifier
.fillMaxHeight()
.verticalScroll(rememberScrollState())
)
}
composable(route = LunchTrayScreen.Sidedish_menu.name) {
val context = LocalContext.current
SideDishMenuScreen(
options = DataSource.sideDishMenuItems,
onCancelButtonClicked = {
CancelOrderAndNavigateToStart(
viewModel,
navController
)
},
onNextButtonClicked = { navController.navigate(LunchTrayScreen.Checkout.name) },
onSelectionChanged = { item ->
viewModel.updateSideDish(item)
},
modifier = Modifier
.fillMaxHeight()
.verticalScroll(rememberScrollState())
)
}
composable(route = LunchTrayScreen.Checkout.name) {
CheckoutScreen(
orderUiState = OrderUiState(),
onNextButtonClicked = { /*TODO*/ },
onCancelButtonClicked = {
CancelOrderAndNavigateToStart(
viewModel,
navController
)
},
modifier = Modifier
.fillMaxHeight()
.verticalScroll(rememberScrollState())
)
}
}
}
}
private fun CancelOrderAndNavigateToStart(
viewModel: OrderViewModel,
navController: NavHostController
) {
viewModel.resetOrder()
navController.popBackStack(LunchTrayScreen.Start.name, inclusive = false)
}
| 0 | Kotlin | 0 | 1 | 0c0babed477e77f70264748bdd7acc72f33ffc21 | 8,354 | Adding-Navigation-Lunch-Tray-App | Apache License 2.0 |
netk_app/src/main/java/com/mozhimen/netk/app/verify/NetKAppVerifyManager.kt | mozhimen | 737,202,327 | false | null | package com.mozhimen.netk.app.verify
import android.text.TextUtils
import android.util.Log
import com.mozhimen.basick.utilk.android.util.UtilKLogWrapper
import com.mozhimen.basick.lintk.optins.OApiInit_InApplication
import com.mozhimen.basick.utilk.commons.IUtilK
import com.mozhimen.basick.utilk.java.io.UtilKFileDir
import com.mozhimen.basick.utilk.java.io.file2strFilePath
import com.mozhimen.basick.utilk.java.io.file2strMd5
import com.mozhimen.netk.app.NetKApp
import com.mozhimen.netk.app.cons.CNetKAppErrorCode
import com.mozhimen.netk.app.cons.CNetKAppState
import com.mozhimen.netk.app.download.mos.intAppErrorCode2appDownloadException
import com.mozhimen.netk.app.task.db.AppTask
import com.mozhimen.netk.app.unzip.NetKAppUnzipManager
import java.io.File
/**
* @ClassName AppVerifyManager
* @Description TODO
* @Author Mozhimen
* @Date 2023/11/8 17:01
* @Version 1.0
*/
@OApiInit_InApplication
internal object NetKAppVerifyManager : IUtilK {
@JvmStatic
fun verify(appTask: AppTask) {
if (appTask.isTaskUnzip()) {
UtilKLogWrapper.d(TAG, "verify: the task already verify")
return
}
/**
* [CNetKAppState.STATE_VERIFYING]
*/
NetKApp.onVerifying(appTask)
UtilKLogWrapper.d(TAG, "verify: apkFileName ${appTask.apkFileName}")
if (appTask.apkFileName.endsWith(".apk") || appTask.apkFileName.endsWith(".npk")) {//如果文件以.npk结尾则先解压
verifyApp(appTask)
} else {
/**
* [CNetKAppState.STATE_VERIFY_FAIL]
*/
NetKApp.onVerifyFail(appTask, CNetKAppErrorCode.CODE_VERIFY_FORMAT_INVALID.intAppErrorCode2appDownloadException())
UtilKLogWrapper.d(TAG, "verifyAndUnzipNpk: getFilesDownloadsDir is null")
}
}
/**
* 安装.npk文件
*/
private fun verifyApp(appTask: AppTask) {
if (!isNeedVerify(appTask)) {//如果文件没有MD5值或者为空,则不校验 直接去安装
onVerifySuccess(appTask, File(UtilKFileDir.External.getFilesDownloads() ?: return, appTask.apkFileName))
return
}
if (NetKAppUnzipManager.isUnziping(appTask)) {
UtilKLogWrapper.d(TAG, "verifyAndUnzipNpk: isUnziping")
return//正在解压中,不进行操作
}
val externalFilesDir = UtilKFileDir.External.getFilesDownloads() ?: run {
/**
* [CNetKAppState.STATE_VERIFY_FAIL]
*/
NetKApp.onVerifyFail(appTask, CNetKAppErrorCode.CODE_VERIFY_DIR_NULL.intAppErrorCode2appDownloadException())
UtilKLogWrapper.e(TAG, "verifyAndUnzipNpk: getFilesDownloadsDir is null")
return
}
val fileApk = File(externalFilesDir, appTask.apkFileName)
if (!fileApk.exists()) {
/**
* [CNetKAppState.STATE_VERIFY_FAIL]
*/
NetKApp.onVerifyFail(appTask, CNetKAppErrorCode.CODE_VERIFY_FILE_NOT_EXIST.intAppErrorCode2appDownloadException())
UtilKLogWrapper.e(TAG, "verifyAndUnzipNpk: download file fail")
return
}
if (isNeedVerify(appTask)) {
val apkFileMd5Locale = fileApk.file2strMd5()//取文件的MD5值
if (!TextUtils.equals(appTask.apkFileMd5, apkFileMd5Locale)) {
/**
* [CNetKAppState.STATE_VERIFY_FAIL]
*/
NetKApp.onVerifyFail(appTask, CNetKAppErrorCode.CODE_VERIFY_MD5_FAIL.intAppErrorCode2appDownloadException())
UtilKLogWrapper.e(TAG, "verifyAndUnzipNpk: download file fail")
NetKApp.taskRetry(appTask.apply {
apkPathName = fileApk.file2strFilePath()
})
return
}
}
onVerifySuccess(appTask, fileApk)
}
private fun onVerifySuccess(appTask: AppTask, fileApk: File) {
/**
* [CNetKAppState.STATE_VERIFY_SUCCESS]
*/
NetKApp.onVerifySuccess(appTask)//检测通过,去安装
NetKAppUnzipManager.unzip(appTask.apply {
apkPathName = fileApk.file2strFilePath()
})
}
//////////////////////////////////////////////////////////////////
/**
* 判断是否需要校验MD5值
* 1、NPK不需要校验MD5值
* 2、如果是使用站内地址下载,不用校验MD5值
* 3、如果使用站外地址,且没有站内地址,且第一次校验失败,则第二次时不用校验
*/
@JvmStatic
private fun isNeedVerify(appTask: AppTask): Boolean {
// if (appTask.apkName.endsWith(".npk"))
// return false
// if (appTask.downloadUrlCurrent == appTask.downloadUrl) {//如果是使用站内地址下载,不用校验MD5值
// return false
// }
return appTask.apkVerifyNeed && appTask.apkFileMd5.isNotEmpty()
}
} | 0 | null | 7 | 3 | 9b8da89c633ac6ebe69d4416cd4dd035f21bb1f2 | 4,643 | ANetKit_App | Apache License 2.0 |
library/src/androidTest/java/OperationExpirationTests.kt | wultra | 259,247,352 | false | null | /*
* Copyright (c) 2021, Wultra s.r.o. (www.wultra.com).
*
* All rights reserved. This source code can be used only for purposes specified
* by the given license contract signed by the rightful deputy of Wultra s.r.o.
* This source code can be used only by the owner of the license.
*
* Any disputes arising in respect of this agreement (license) shall be brought
* before the Municipal Court of Prague.
*/
package com.wultra.android.mtokensdk.test
import com.wultra.android.mtokensdk.operation.expiration.ExpirableOperation
import com.wultra.android.mtokensdk.operation.expiration.OperationExpirationWatcher
import com.wultra.android.mtokensdk.operation.expiration.OperationExpirationWatcherListener
import org.junit.After
import org.junit.Assert
import org.junit.Test
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.zone.TzdbZoneRulesProvider
import org.threeten.bp.zone.ZoneRulesProvider
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
class OperationExpirationTests {
private val watcher = OperationExpirationWatcher()
init {
initThreeTen()
}
@After
fun clear() {
watcher.listener = null
watcher.removeAll()
}
@Test
fun testAddOperation() {
val op = Operation()
watcher.add(op)
val ops = watcher.getWatchedOperations()
Assert.assertTrue(ops.count() == 1 && ops.first().equals(op))
}
@Test
fun testAddSameOperationTwice() {
val op = Operation()
watcher.add(op)
val ops = watcher.add(op)
Assert.assertTrue(ops.count() == 1 && ops.first().equals(op))
}
@Test
fun testAddOperations() {
val ops = watcher.add(listOf(Operation(), Operation()))
Assert.assertTrue(ops.count() == 2)
}
@Test
fun testRemoveOperation() {
val op = Operation()
val ops = watcher.add(op)
Assert.assertTrue(ops.count() == 1 && ops.first().equals(op))
val opsAfterRemoved = watcher.remove(op)
Assert.assertTrue(opsAfterRemoved.isEmpty())
}
@Test
fun testRemoveNonAddedOperation() {
val op = Operation()
val ops = watcher.add(op)
Assert.assertTrue(ops.count() == 1 && ops.first().equals(op))
val opsAfterRemoved = watcher.remove(Operation())
Assert.assertTrue(opsAfterRemoved.count() == 1)
}
@Test
fun testRemoveOperations() {
val op = Operation()
val op2 = Operation()
watcher.add(op)
val ops = watcher.add(op2)
Assert.assertTrue(ops.count() == 2)
val opsAfterRemoved = watcher.remove(listOf(op, op2))
Assert.assertTrue(opsAfterRemoved.isEmpty())
}
@Test
fun testRemoveAllOperations() {
watcher.add(Operation())
val ops = watcher.add(listOf(Operation(), Operation()))
Assert.assertTrue(ops.count() == 3)
val opsAfterRemoved = watcher.removeAll()
Assert.assertTrue(opsAfterRemoved.isEmpty())
}
@Test
fun testExpiring() {
val future = CompletableFuture<Any?>()
val op = Operation()
watcher.listener = WatcherListener { ops ->
if (ops.count() != 1 || !ops.first().equals(op)) {
future.completeExceptionally(Throwable())
return@WatcherListener
}
val curOps = watcher.getWatchedOperations()
if (curOps.isNotEmpty()) {
future.completeExceptionally(Throwable())
return@WatcherListener
}
future.complete(null)
}
watcher.add(op)
// we need to wait longer, because minimum report time is 5 seconds
Assert.assertNull(future.get(10, TimeUnit.SECONDS))
}
@Test
fun testExpiring2() {
val future = CompletableFuture<Any?>()
watcher.listener = WatcherListener { ops ->
if (ops.count() != 1) {
future.completeExceptionally(Throwable())
return@WatcherListener
}
val curOps = watcher.getWatchedOperations()
if (curOps.count() != 1) {
future.completeExceptionally(Throwable())
return@WatcherListener
}
future.complete(null)
}
watcher.add(listOf(Operation(), Operation(ZonedDateTime.now().plusSeconds(20))))
// we need to wait longer, because minimum report time is 5 seconds
Assert.assertNull(future.get(10, TimeUnit.SECONDS))
}
}
private class WatcherListener(
private val callback: (List<ExpirableOperation>) -> Unit): OperationExpirationWatcherListener {
override fun operationsExpired(expiredOperations: List<ExpirableOperation>) {
callback(expiredOperations)
}
}
private class Operation(
override val expires: ZonedDateTime = ZonedDateTime.now()
): ExpirableOperation
fun Any.initThreeTen() {
if (ZoneRulesProvider.getAvailableZoneIds().isEmpty()) {
val stream = this.javaClass.classLoader!!.getResourceAsStream("TZDB.dat")
stream.use(::TzdbZoneRulesProvider).apply {
ZoneRulesProvider.registerProvider(this)
}
}
} | 3 | Kotlin | 0 | 0 | 5daf6c2c234bcc2b74e241abd7bbd2c5b73b6320 | 5,249 | mtoken-sdk-android | Apache License 2.0 |
common/src/main/java/net/sistr/flexibleguns/FlexibleGunsMod.kt | SistrScarlet | 437,250,021 | false | {"Kotlin": 239434, "Java": 36089} | package net.sistr.flexibleguns
import me.shedaniel.architectury.registry.entity.EntityAttributes
import net.sistr.flexibleguns.entity.FGBotEntity
import net.sistr.flexibleguns.setup.Registration
import org.apache.logging.log4j.LogManager
object FlexibleGunsMod {
const val MODID = "flexibleguns"
val LOGGER = LogManager.getLogger()!!
fun init() {
Registration.init()
EntityAttributes.register({ Registration.BOT_ENTITY.get() }, { FGBotEntity.createBotAttributes() })
}
} | 0 | Kotlin | 0 | 2 | c00fbbfbd98a253f971cb9f5c87a4cf3eef9b6a2 | 506 | FlexibleGuns | MIT License |
common/src/main/java/net/sistr/flexibleguns/FlexibleGunsMod.kt | SistrScarlet | 437,250,021 | false | {"Kotlin": 239434, "Java": 36089} | package net.sistr.flexibleguns
import me.shedaniel.architectury.registry.entity.EntityAttributes
import net.sistr.flexibleguns.entity.FGBotEntity
import net.sistr.flexibleguns.setup.Registration
import org.apache.logging.log4j.LogManager
object FlexibleGunsMod {
const val MODID = "flexibleguns"
val LOGGER = LogManager.getLogger()!!
fun init() {
Registration.init()
EntityAttributes.register({ Registration.BOT_ENTITY.get() }, { FGBotEntity.createBotAttributes() })
}
} | 0 | Kotlin | 0 | 2 | c00fbbfbd98a253f971cb9f5c87a4cf3eef9b6a2 | 506 | FlexibleGuns | MIT License |
rximagepicker_support/src/main/java/com/qingmei2/rximagepicker_extension/ui/AlbumPreviewActivity.kt | qingmei2 | 116,668,295 | false | null | /*
* Copyright 2017 Zhihu Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qingmei2.rximagepicker_extension.ui
import android.database.Cursor
import android.os.Bundle
import com.qingmei2.rximagepicker_extension.entity.Album
import com.qingmei2.rximagepicker_extension.entity.Item
import com.qingmei2.rximagepicker_extension.model.AlbumMediaCollection
import com.qingmei2.rximagepicker_extension.ui.adapter.PreviewPagerAdapter
import java.util.ArrayList
open class AlbumPreviewActivity : BasePreviewActivity(), AlbumMediaCollection.AlbumMediaCallbacks {
private val mCollection = AlbumMediaCollection()
private var mIsAlreadySetPosition: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initData()
}
open fun initData() {
mCollection.onCreate(this, this)
val album = intent.getParcelableExtra<Album>(EXTRA_ALBUM)
mCollection.load(album)
val item = intent.getParcelableExtra<Item>(EXTRA_ITEM)
if (mSpec.countable) {
mCheckView.setCheckedNum(mSelectedCollection.checkedNumOf(item))
} else {
mCheckView.setChecked(mSelectedCollection.isSelected(item))
}
updateSize(item)
}
override fun onDestroy() {
super.onDestroy()
mCollection.onDestroy()
}
override fun onAlbumMediaLoad(cursor: Cursor) {
val items = ArrayList<Item>()
while (cursor.moveToNext()) {
items.add(Item.valueOf(cursor))
}
val adapter = mPager.adapter as PreviewPagerAdapter
adapter.addAll(items)
adapter.notifyDataSetChanged()
if (!mIsAlreadySetPosition) {
//onAlbumMediaLoad is called many times..
mIsAlreadySetPosition = true
val selected = intent.getParcelableExtra<Item>(EXTRA_ITEM)
val selectedIndex = items.indexOf(selected)
mPager.setCurrentItem(selectedIndex, false)
mPreviousPos = selectedIndex
}
}
override fun onAlbumMediaReset() {
}
companion object {
const val EXTRA_ALBUM = "extra_album"
const val EXTRA_ITEM = "extra_item"
}
}
| 20 | null | 156 | 1,196 | 08aee5c815017845a0fd818cc6bfa5df872e3fae | 2,748 | RxImagePicker | MIT License |
src/main/kotlin/utils/OutputUtils.kt | y9tr3ble | 609,940,671 | false | {"Kotlin": 3295} | package utils
fun displayResult(language: String, title: String, snippet: String, articleText: String) {
println("URL: https://$language.wikipedia.org/wiki/$title")
println("Heading: $title")
println("Snippet: $snippet")
println("Text of the article: $articleText")
}
fun removeXmlTags(str: String): String = buildString {
var insideTag = false
for (char in str) {
when (char) {
'<' -> insideTag = true
'>' -> insideTag = false
else -> if (!insideTag) append(char)
}
}
} | 0 | Kotlin | 0 | 1 | 11dce15dcf739febb7929d8b591f9b4b2855e733 | 552 | WikiSearch | MIT License |
app/src/main/java/com/makaota/mammamskitchenmanager/utils/Constants.kt | makaota | 687,067,408 | false | {"Kotlin": 174867} | package com.makaota.mammamskitchenmanager.utils
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.webkit.MimeTypeMap
object Constants {
const val USER_MANAGER_ID = "user_manager_id"
const val BASE_URL = "https://fcm.googleapis.com"
const val SERVER_KEY = "AAAA6WuBVzg:APA91bG42BqsBYwZ9UHeROrVNaWFE6A1Bl2b8eMDFpWsE3MI4MaLY1PLbGd7R9YIj6ysR4FoIwMmO8fSXALcKAB78RU4eRVBGGz4zjcr6c8Xm9IVE0wZ0O21KgFE_yk_XALjg5JfQ6db"
const val CONTENT_TYPE = "application/json"
// Firebase Constants
// This is used for the collection in the firestore.
const val USER_MANAGER: String = "userManager"
const val USER: String = "user"
const val PRODUCTS: String = "products"
const val ORDERS: String = "orders"
const val SOLD_PRODUCTS: String = "sold_products"
const val NOTIFICATIONS: String = "notifications"
const val OPEN_CLOSE_STORE: String = "openCloseStore"
const val ORDER_STATUS: String = "orderStatus"
const val CART_ITEMS: String = "cart_items"
//menu categories
const val ADDITIONAL_MEALS: String = "ADDITIONAL MEALS"
const val SCAMBANE: String = "SCAMBANE"
const val CHIPS: String = "CHIPS"
const val RUSSIAN: String= "RUSSIAN"
const val DRINKS: String = "DRINKS"
// Product Constants
const val PRODUCT_TITLE = "title"
const val PRODUCT_PRICE = "price"
const val PRODUCT_DESCRIPTION = "description"
const val STOCK_QUANTITY: String = "stock_quantity"
const val USER_MANAGER_PREFERENCES: String = "userManagerPrefs"
const val LOGGED_IN_USERNAME: String = "logged_in_username"
const val EXTRA_USER_DETAILS: String = "extra_user_details"
const val READ_STORAGE_PERMISSION_CODE: Int = 2
const val PICK_IMAGE_REQUEST_CODE = 1
const val PICK_PRODUCT_IMAGE_REQUEST_CODE = 1
// Constant variables for Gender
const val MALE: String = "male"
const val FEMALE: String = "female"
// Firebase database field names
const val MOBILE: String = "mobile"
const val GENDER: String = "gender"
const val IMAGE: String = "image"
const val COMPLETE_PROFILE: String = "profileCompleted"
const val FIRST_NAME: String = "firstName"
const val LAST_NAME: String = "lastName"
const val USER_ID: String = "user_id"
const val PRODUCT_ID: String = "product_id"
//
const val USER_RESTAURANT_MANAGER_PROFILE_IMAGE: String = "User_Restaurant_Manager_Profile_Image"
const val PRODUCT_IMAGE: String = "Product_Image"
// Intent extra constants.
const val EXTRA_PRODUCT_ID: String = "extra_product_id"
const val EXTRA_PRODUCT_OWNER_ID: String = "extra_product_owner_id"
const val EXTRA_PRODUCT_DETAILS = "extra_product_details"
const val EXTRA_PIZZA_PRODUCT_DETAILS: String = "extra_pizza_product_details"
const val EXTRA_CHICKEN_PRODUCT_DETAILS: String = "extra_chicken_product_details"
const val EXTRA_BEEF_PRODUCT_DETAILS: String = "extra_beef_product_details"
const val EXTRA_ADDRESS_DETAILS: String = "AddressDetails"
const val EXTRA_SELECT_ADDRESS: String = "extra_select_address"
const val EXTRA_SELECTED_ADDRESS: String = "extra_selected_address"
const val EXTRA_MY_ORDER_DETAILS: String = "extra_my_order_details"
const val EXTRA_SOLD_PRODUCT_DETAILS: String = "extra_sold_product_details"
const val CART_QUANTITY: String = "cart_quantity"
const val HOME: String = "Home"
const val OFFICE: String = "Office"
const val OTHER: String = "Other"
// START
/**
* A function for user profile image selection from phone storage.
*/
fun showImageChooser(activity: Activity) {
// An intent for launching the image selection of phone storage.
val galleryIntent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
// Launches the image selection of phone storage using the constant code.
activity.startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST_CODE)
}
// END
// Create a function to get the extension of the selected image file.
// START
/**
* A function to get the image file extension of the selected image.
*
* @param activity Activity reference.
* @param uri Image file uri.
*/
fun getFileExtension(activity: Activity, uri: Uri?): String? {
/*
* MimeTypeMap: Two-way map that maps MIME-types to file extensions and vice versa.
*
* getSingleton(): Get the singleton instance of MimeTypeMap.
*
* getExtensionFromMimeType: Return the registered extension for the given MIME type.
*
* contentResolver.getType: Return the MIME type of the given content URL.
*/
return MimeTypeMap.getSingleton()
.getExtensionFromMimeType(activity.contentResolver.getType(uri!!))
}
// END
} | 0 | Kotlin | 0 | 1 | 9cf67dd82affc819dbbb95ec29327ed027960f06 | 4,949 | Mamma_Ms_Kitchen_Manager | MIT License |
react-table-kotlin/src/main/kotlin/tanstack/table/core/FiltersColumn.kt | turansky | 393,199,102 | false | null | // Automatically generated - do not modify!
package tanstack.table.core
import kotlinx.js.JsPair
import kotlinx.js.Record
external interface FiltersColumn<TData : RowData> {
var getAutoFilterFn: () -> FilterFn<TData>
var getFilterFn: () -> FilterFn<TData>
var setFilterValue: (updater: Updater<*>) -> Unit
var getCanFilter: () -> Boolean
var getCanGlobalFilter: () -> Boolean
var getFacetedRowModel: () -> RowModel<TData>
var getIsFiltered: () -> Boolean
var getFilterValue: () -> Any
var getFilterIndex: () -> Int
var getFacetedUniqueValues: () -> Record<Any, Int> /* JS Map */
var getFacetedMinMaxValues: () -> JsPair<Int, Int>?
}
| 0 | Kotlin | 5 | 13 | 0f67fb7955dc2c00a7fd18d369ea546d93fa7a92 | 680 | react-types-kotlin | Apache License 2.0 |
react-table-kotlin/src/main/kotlin/tanstack/table/core/FiltersColumn.kt | turansky | 393,199,102 | false | null | // Automatically generated - do not modify!
package tanstack.table.core
import kotlinx.js.JsPair
import kotlinx.js.Record
external interface FiltersColumn<TData : RowData> {
var getAutoFilterFn: () -> FilterFn<TData>
var getFilterFn: () -> FilterFn<TData>
var setFilterValue: (updater: Updater<*>) -> Unit
var getCanFilter: () -> Boolean
var getCanGlobalFilter: () -> Boolean
var getFacetedRowModel: () -> RowModel<TData>
var getIsFiltered: () -> Boolean
var getFilterValue: () -> Any
var getFilterIndex: () -> Int
var getFacetedUniqueValues: () -> Record<Any, Int> /* JS Map */
var getFacetedMinMaxValues: () -> JsPair<Int, Int>?
}
| 0 | Kotlin | 5 | 13 | 0f67fb7955dc2c00a7fd18d369ea546d93fa7a92 | 680 | react-types-kotlin | Apache License 2.0 |
app/src/main/java/androidx/compose/material3/pullrefresh/PullRefreshIndicatorTransform.kt | vitorpamplona | 587,850,619 | false | null | /*
* Copyright 2022 The Android Open Source Project
* Copyright 2023 Bamboo Apps
*
* 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 eu.bambooapps.material3.pullrefresh
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.platform.inspectable
/**
* A modifier for translating the position and scaling the size of a pull-to-refresh indicator
* based on the given [PullRefreshState].
* Taken from compose-material library and adapted for Material 3
*
* @param state The [PullRefreshState] which determines the position of the indicator.
* @param scale A boolean controlling whether the indicator's size scales with pull progress or not.
*/
@ExperimentalMaterial3Api
fun Modifier.pullRefreshIndicatorTransform(state: PullRefreshState, scale: Boolean = false) =
inspectable(
inspectorInfo = debugInspectorInfo {
name = "pullRefreshIndicatorTransform"
properties["state"] = state
properties["scale"] = scale
}
) {
Modifier
// Essentially we only want to clip the at the top, so the indicator will not appear when
// the position is 0. It is preferable to clip the indicator as opposed to the layout that
// contains the indicator, as this would also end up clipping shadows drawn by items in a
// list for example - so we leave the clipping to the scrolling container. We use MAX_VALUE
// for the other dimensions to allow for more room for elevation / arbitrary indicators - we
// only ever really want to clip at the top edge.
.drawWithContent {
clipRect(
top = 0f,
left = -Float.MAX_VALUE,
right = Float.MAX_VALUE,
bottom = Float.MAX_VALUE
) {
[email protected]()
}
}
.graphicsLayer {
translationY = state.position - size.height
if (scale && !state.refreshing) {
val scaleFraction = LinearOutSlowInEasing
.transform(state.position / state.threshold)
.coerceIn(0f, 1f)
scaleX = scaleFraction
scaleY = scaleFraction
}
}
}
| 8 | null | 945 | 981 | 2de3d19a34b97c012e39b203070d9c1c0b1f0520 | 3,198 | amethyst | MIT License |
libraries/android/src/main/java/com/raxdenstudios/commons/ext/AppCompatActivityExtension.kt | raxden | 32,153,256 | false | null | package com.raxdenstudios.commons.android.ext
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
fun AppCompatActivity.setupToolbar(
toolbar: Toolbar,
titleEnabled: Boolean = false
): Toolbar = toolbar.also {
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(titleEnabled)
toolbar.setNavigationOnClickListener { onBackPressed() }
}
| 1 | Kotlin | 2 | 3 | f7680adafb6a6ca9d72856a53a18fe3a4da6549e | 416 | android-commons | Apache License 2.0 |
graph/graph-application/src/main/kotlin/eu/tib/orkg/prototype/contenttypes/services/actions/paper/PaperResourceCreator.kt | TIBHannover | 197,416,205 | false | {"Kotlin": 2517987, "Cypher": 215872, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240} | package eu.tib.orkg.prototype.contenttypes.services.actions
import eu.tib.orkg.prototype.contenttypes.api.CreatePaperUseCase
import eu.tib.orkg.prototype.statements.api.Classes
import eu.tib.orkg.prototype.statements.api.CreateResourceUseCase
import eu.tib.orkg.prototype.statements.api.ResourceUseCases
class PaperResourceCreator(
private val resourceService: ResourceUseCases
) : PaperAction {
override operator fun invoke(command: CreatePaperCommand, state: PaperState): PaperState {
val paperId = resourceService.create(
CreateResourceUseCase.CreateCommand(
label = command.title,
classes = setOf(Classes.paper),
extractionMethod = command.extractionMethod,
contributorId = command.contributorId,
observatoryId = command.observatories.firstOrNull(),
organizationId = command.organizations.firstOrNull()
)
)
return state.copy(paperId = paperId)
}
}
| 0 | Kotlin | 2 | 5 | f96c2c41a6e2b1da63a9d93973602573b596ed0d | 1,010 | orkg-backend | MIT License |
shared/src/commonMain/kotlin/org/mixdrinks/ui/details/goods/GoodsView.kt | MixDrinks | 614,917,688 | false | {"Kotlin": 196307, "Swift": 10681, "Ruby": 277, "Shell": 228} | package org.mixdrinks.ui.details.goods
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.seiko.imageloader.rememberAsyncImagePainter
import org.mixdrinks.app.styles.MixDrinksColors
import org.mixdrinks.app.styles.MixDrinksTextStyles
import org.mixdrinks.dto.GoodId
import org.mixdrinks.ui.widgets.undomain.UiState
@Composable
internal fun GoodsView(
goodsSubComponent: GoodsSubComponent,
onGoodClick: (goodId: GoodId) -> Unit
) {
val state by goodsSubComponent.state.collectAsState()
if (state is UiState.Data) {
val safeState = (state as UiState.Data<GoodsSubComponent.GoodsUi>).data
Column {
Box(modifier = Modifier.fillMaxWidth()) {
Text(
modifier = Modifier
.padding(start = 12.dp, bottom = 12.dp)
.align(Alignment.CenterStart),
color = MixDrinksColors.Black,
text = "Інгрідієнти",
style = MixDrinksTextStyles.H1,
)
Box(
modifier = Modifier
.padding(horizontal = 12.dp)
.align(Alignment.CenterEnd)
) {
Counter(
count = safeState.count,
onPlus = goodsSubComponent::onPlusClick,
onMinus = goodsSubComponent::onMinusClick,
)
}
}
safeState.goods.forEach {
Good(it, onGoodClick)
}
}
}
}
@Composable
internal fun Good(good: GoodsSubComponent.GoodUi, onGoodClick: (goodId: GoodId) -> Unit) {
Card(
modifier = Modifier
.height(80.dp)
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 4.dp),
shape = RoundedCornerShape(8.dp),
) {
Row(modifier = Modifier.clickable { onGoodClick(good.goodId) }) {
Image(
painter = rememberAsyncImagePainter(good.url),
contentDescription = good.name,
contentScale = ContentScale.Inside,
modifier = Modifier.size(80.dp, 80.dp)
.padding(2.dp),
)
Text(
modifier = Modifier.align(Alignment.CenterVertically)
.padding(horizontal = 8.dp),
text = good.name,
style = MixDrinksTextStyles.H5,
)
Spacer(Modifier.weight(1f).fillMaxHeight())
Text(
modifier = Modifier.align(Alignment.CenterVertically)
.padding(horizontal = 8.dp),
text = good.amount,
style = MixDrinksTextStyles.H5,
)
}
}
}
| 14 | Kotlin | 1 | 9 | 182933ab91b766def2d6dfd67f63c7e4ef008ee8 | 3,712 | Mobile | Apache License 2.0 |
src/main/kotlin/io/github/config4k/readers/MapReader.kt | config4k | 72,716,336 | false | {"Kotlin": 68299, "Java": 319} | package io.github.config4k.readers
import com.typesafe.config.ConfigUtil
import io.github.config4k.ClassContainer
import io.github.config4k.MapEntry
import kotlin.reflect.full.isSubclassOf
internal class MapReader(
keyClass: ClassContainer,
valueClass: ClassContainer,
mutable: Boolean = false,
) : Reader<Map<*, *>?>({ config, path ->
val keyMapperClass = keyClass.mapperClass
when {
keyMapperClass == String::class -> {
val child = config.getConfig(path)
child.root().keys.associateWith { key ->
SelectReader.getReader(valueClass)(
child,
ConfigUtil.joinPath(key),
)
}
}
keyMapperClass.isSubclassOf(Enum::class) -> {
val child = config.getConfig(path)
child.root().keys.associate { key ->
val resultKey = EnumReader.stringToEnum(key, keyMapperClass)
val resultValue =
SelectReader.getReader(valueClass)(child, ConfigUtil.joinPath(key))
resultKey to resultValue
}
}
else -> {
val mapEntryClassContainer =
ClassContainer(MapEntry::class, mapOf("K" to keyClass, "V" to valueClass))
ListReader(mapEntryClassContainer).getValue(config, path)?.associate {
val mapEntry = it as MapEntry<*, *>
mapEntry.key to mapEntry.value
}
}
}.let { if (mutable) it?.toMutableMap() else it }
})
| 10 | Kotlin | 35 | 277 | 8ca9682d41baa27971f749ee4e5e04ed6d4493c3 | 1,668 | config4k | Apache License 2.0 |
plugins/hh-geminio/src/main/kotlin/ru/hh/plugins/geminio/config/GeminioPluginConfig.kt | hhru | 159,637,875 | false | null | package ru.hh.plugins.geminio.config
import ru.hh.plugins.extensions.EMPTY
data class GeminioPluginConfig(
var configFilePath: String = String.EMPTY,
var templatesRootDirPath: String = String.EMPTY,
var modulesTemplatesRootDirPath: String = String.EMPTY,
var groupsNames: GroupsNames = GroupsNames(),
) {
data class GroupsNames(
var forNewGroup: String = String.EMPTY,
var forNewModulesGroup: String = String.EMPTY
)
} | 24 | null | 18 | 97 | 2d6c02fc814eff3934c17de77ef7ade91d3116f5 | 463 | android-multimodule-plugin | MIT License |
acme-web/acme-web-api/src/main/kotlin/com/acme/web/api/scheduling/module.kt | mattupstate | 496,835,485 | false | {"Kotlin": 268073, "HCL": 28862, "HTML": 15841, "Smarty": 9320, "Shell": 2578, "Dockerfile": 460, "PLpgSQL": 179} | @file:OptIn(KtorExperimentalLocationsAPI::class)
package com.acme.web.api.scheduling
import com.acme.scheduling.data.SchedulingJooqUnitOfWork
import com.acme.web.api.KetoConfiguration
import com.acme.web.api.scheduling.data.JooqSchedulingWebViews
import com.acme.web.api.security.AccessControlService
import com.acme.web.api.security.KtorOryKetoAccessControlService
import com.acme.web.api.security.keto.KtorOryKetoClient
import com.acme.web.api.security.keto.defaultOryKetoClientConfiguration
import io.ktor.client.HttpClient
import io.ktor.server.auth.authenticate
import io.ktor.server.locations.KtorExperimentalLocationsAPI
import io.ktor.server.routing.Route
import org.jooq.Configuration
fun Route.scheduling(jooqConfig: Configuration, ketoConfig: KetoConfiguration, basePath: String = "") {
val accessControl = KtorOryKetoAccessControlService(
"scheduling",
KtorOryKetoClient(
HttpClient {
defaultOryKetoClientConfiguration(ketoConfig.readUrl)
},
HttpClient {
defaultOryKetoClientConfiguration(ketoConfig.writeUrl)
}
)
)
scheduling(jooqConfig, accessControl, basePath)
}
fun Route.scheduling(jooqConfig: Configuration, accessControl: AccessControlService, basePath: String = "") {
val schedulingUnitOfWork = SchedulingJooqUnitOfWork(jooqConfig)
val schedulingWebViews = JooqSchedulingWebViews(jooqConfig)
authenticate {
schedulingCommands(webApiSchedulingMessageBus, accessControl, schedulingUnitOfWork, basePath)
schedulingQueries(schedulingWebViews, accessControl, basePath)
}
}
| 0 | Kotlin | 0 | 6 | 4f514e9b32336fb73e13cb7fd2bced75b9cbfde6 | 1,567 | acme | MIT License |
core/reflection.jvm/src/kotlin/reflect/jvm/internal/KMemberPropertyImpl.kt | leomindez | 32,245,430 | true | {"Markdown": 33, "XML": 646, "Ant Build System": 32, "Ignore List": 8, "Kotlin": 16461, "Java": 4172, "Protocol Buffer": 3, "Text": 3438, "JavaScript": 66, "JAR Manifest": 2, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 114, "Groovy": 19, "Maven POM": 48, "Gradle": 68, "Java Properties": 9, "CSS": 10, "JFlex": 3, "Shell": 7, "Batchfile": 7} | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* 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 kotlin.reflect.jvm.internal
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import kotlin.reflect.IllegalPropertyAccessException
import kotlin.reflect.KMemberProperty
import kotlin.reflect.KMutableMemberProperty
open class KMemberPropertyImpl<T : Any, out R>(
override val container: KClassImpl<T>,
computeDescriptor: () -> PropertyDescriptor
) : DescriptorBasedProperty(computeDescriptor), KMemberProperty<T, R>, KPropertyImpl<R> {
override val name: String get() = descriptor.getName().asString()
override fun get(receiver: T): R {
try {
val getter = getter
[suppress("UNCHECKED_CAST")]
return if (getter != null) getter(receiver) as R else field!!.get(receiver) as R
}
catch (e: IllegalAccessException) {
throw IllegalPropertyAccessException(e)
}
}
override fun equals(other: Any?): Boolean =
other is KMemberPropertyImpl<*, *> && descriptor == other.descriptor
override fun hashCode(): Int =
descriptor.hashCode()
override fun toString(): String =
ReflectionObjectRenderer.renderProperty(descriptor)
}
class KMutableMemberPropertyImpl<T : Any, R>(
container: KClassImpl<T>,
computeDescriptor: () -> PropertyDescriptor
) : KMemberPropertyImpl<T, R>(container, computeDescriptor), KMutableMemberProperty<T, R>, KMutablePropertyImpl<R> {
override fun set(receiver: T, value: R) {
try {
val setter = setter
if (setter != null) setter(receiver, value) else field!!.set(receiver, value)
}
catch (e: IllegalAccessException) {
throw IllegalPropertyAccessException(e)
}
}
}
| 0 | Java | 1 | 0 | e0a394ec62f364a4a96c15b2d2adace32ce61e9e | 2,346 | kotlin | Apache License 2.0 |
ui/src/main/java/com/pyamsoft/pydroid/ui/defaults/ImageDefaults.kt | pyamsoft | 48,562,480 | false | null | package com.pyamsoft.pydroid.ui.defaults
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/** Default values for Icons */
public object ImageDefaults {
/** Default size unit */
public val LargeSize: Dp = 80.dp
/** Default size unit */
public val DefaultSize: Dp = 56.dp
/** Icon size unit */
public val IconSize: Dp = 24.dp
/** List item size unit */
public val ItemSize: Dp = 48.dp
}
| 4 | Kotlin | 5 | 9 | 23a5ae80f368e94eb5d6968895a2f5ed326720cf | 428 | pydroid | Apache License 2.0 |
app/src/main/java/com/xiang/ssg/main/MainViewModel.kt | kamoguai | 738,864,097 | false | {"Kotlin": 48035, "Ruby": 1278} | package com.xiang.ssg.main
import android.app.Application
import android.content.pm.PackageManager
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.xiang.ssg.getApplicationInfoCompat
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Time: 2023/6/7
* Author: Xing
* Descripton:
*
*
*/
@HiltViewModel
class MainViewModel @Inject constructor(
application: Application
): ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState = _uiState.asStateFlow()
init {
viewModelScope.launch {
val activityInfo = application.packageManager.getApplicationInfoCompat(application.packageName, PackageManager.GET_META_DATA)
val url = activityInfo.metaData.getString("templateweb.hostname") ?:""
var proxyHost = activityInfo.metaData.getString("templateweb.proxyHost") ?:""
var proxyPort = activityInfo.metaData.getInt("templateweb.proxyPort") ?: 0
var proxyUserName = activityInfo.metaData.getString("templateweb.proxyUserName") ?:""
var proxyPassword = activityInfo.metaData.getString("templateweb.proxyPassword") ?:""
val proxyList = activityInfo.metaData.getString("templateweb.proxyList") ?:""
if(proxyList.isNotEmpty()) {
val split = proxyList.split(";")
val ramdomArr = split.random()
val proxyStr = ramdomArr.split(",")
proxyHost = proxyStr[0]
proxyPort = proxyStr[1].toInt()
proxyUserName = proxyStr[2]
proxyPassword = proxyStr[3]
}
_uiState.update {
it.copy(url = url, proxyHost = proxyHost,proxyPort = proxyPort,proxyUserName = proxyUserName,proxyPassword = proxyPassword)
}
}
}
fun setSplashLoading(s: Boolean) {
viewModelScope.launch {
_uiState.update {
it.copy(splashState = s)
}
}
}
}
data class UiState(
val url: String = "",
val splashState: Boolean = true,
val proxyHost: String = "",
val proxyPort: Int = 0,
val proxyUserName: String = "",
val proxyPassword: String = ""
) | 0 | Kotlin | 0 | 0 | d62af0d0aa1bd904f6a73ab971cfe1bdbef80977 | 2,428 | sockpuppet | MIT License |
core/src/main/kotlin/org/hyrical/hcf/provider/scoreboard/adapter/impl/HCFScoreboardAdapter.kt | Hyrical | 597,847,737 | false | null | package org.hyrical.hcf.provider.scoreboard.adapter.impl
import org.bukkit.entity.Player
import org.hyrical.hcf.HCFPlugin
import org.hyrical.hcf.config.impl.ScoreboardFile
import org.hyrical.hcf.profile.ProfileService
import org.hyrical.hcf.provider.scoreboard.adapter.ScoreboardAdapter
import org.hyrical.hcf.server.ServerHandler
import org.hyrical.hcf.timer.type.PlayerTimer
import org.hyrical.hcf.timer.type.impl.playertimers.AppleTimer
import org.hyrical.hcf.timer.type.impl.playertimers.CombatTimer
import org.hyrical.hcf.timer.type.impl.playertimers.EnderpearlTimer
import org.hyrical.hcf.utils.time.TimeUtils
import org.hyrical.hcf.utils.translate
import java.util.LinkedList
class HCFScoreboardAdapter : ScoreboardAdapter {
override fun getTitle(player: Player): String {
return ScoreboardFile.getString("TITLE")!!
}
override fun getLines(player: Player): LinkedList<String> {
val lines: LinkedList<String> = LinkedList()
val combatTimer = CombatTimer.getRemainingTime(player)
val enderPearlTimer = EnderpearlTimer.getRemainingTime(player)
val appleTimer = AppleTimer.getRemainingTime(player)
val profile = HCFPlugin.instance.profileService.getProfile(player.uniqueId)!!
if (ServerHandler.isKitMap){
val kills = ScoreboardFile.getString("KITS.KILLS")!!
val deaths = ScoreboardFile.getString("KITS.DEATHS")!!
if (kills != ""){
lines.add(kills.replace("%kills%", profile.kills.toString()))
}
if (deaths != ""){
lines.add(deaths.replace("%deaths%", profile.deaths.toString()))
}
if (!lines.isEmpty()){
lines.add("")
}
}
if (combatTimer != null){
lines.add(ScoreboardFile.getString(CombatTimer.getConfigPath())!!.replace("%time%",
TimeUtils.formatIntoMMSS((combatTimer / 1000).toInt())))
}
if (enderPearlTimer != null){
lines.add(ScoreboardFile.getString(EnderpearlTimer.getConfigPath())!!.replace("%time%",
TimeUtils.formatFancy(enderPearlTimer / 1000L)))
}
if (appleTimer != null){
lines.add(ScoreboardFile.getString(AppleTimer.getConfigPath())!!.replace("" +
"%time%", TimeUtils.formatFancy(appleTimer / 1000L)))
}
if (!lines.isEmpty()){
lines.addFirst(ScoreboardFile.getString("LINES")!!)
lines.add(ScoreboardFile.getString("LINES")!!)
}
return lines.map { translate(it) }.toCollection(LinkedList())
}
} | 1 | Kotlin | 0 | 2 | 645b8746f3538acaa0e7b4aefdb1a5b640f48e2d | 2,634 | HCF | MIT License |
basick/src/main/java/com/mozhimen/basick/utilk/android/content/UtilKPackageManager.kt | mozhimen | 353,952,154 | false | null | package com.mozhimen.kotlin.utilk.android.content
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.content.pm.PackageManager.PackageInfoFlags
import android.content.pm.PermissionGroupInfo
import android.content.pm.PermissionInfo
import android.content.pm.ResolveInfo
import android.graphics.drawable.Drawable
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresPermission
import com.mozhimen.kotlin.elemk.android.content.cons.CPackageInfo
import com.mozhimen.kotlin.elemk.android.content.cons.CPackageManager
import com.mozhimen.kotlin.elemk.android.os.cons.CVersCode
import com.mozhimen.kotlin.lintk.annors.ADescription
import com.mozhimen.kotlin.lintk.optins.permission.OPermission_QUERY_ALL_PACKAGES
import com.mozhimen.kotlin.lintk.optins.permission.OPermission_REQUEST_INSTALL_PACKAGES
import com.mozhimen.kotlin.elemk.android.cons.CPermission
import com.mozhimen.kotlin.utilk.android.os.UtilKBuildVersion
import com.mozhimen.kotlin.utilk.android.util.UtilKLogWrapper
import com.mozhimen.kotlin.utilk.commons.IUtilK
import com.mozhimen.kotlin.utilk.android.content.UtilKContext
/**
* @ClassName UtilKPackageManager
* @Description TODO
* @Author Mozhimen & <NAME>
* @Date 2023/3/20 10:50
* @Version 1.0
*/
object UtilKPackageManager : IUtilK {
@JvmStatic
fun get(context: Context): PackageManager =
UtilKContext.getPackageManager(context)
@JvmStatic
fun getPackageInfo(context: Context, strPackageName: String, flags: Int): PackageInfo? =
try {
get(context).getPackageInfo(strPackageName, flags)
} catch (e: Exception) {
e.printStackTrace()
UtilKLogWrapper.e(TAG, "getPackageInfo: ", e)
null
}
@JvmStatic
fun getPackageArchiveInfo(context: Context, archiveFilePath: String, flags: Int): PackageInfo? =
get(context).getPackageArchiveInfo(archiveFilePath, flags)
@JvmStatic
@RequiresApi(CVersCode.V_21_5_L)
fun getPackageInstaller(context: Context): PackageInstaller =
get(context).packageInstaller
@JvmStatic
fun getApplicationInfo(context: Context, strPackageName: String): ApplicationInfo =
getApplicationInfo(context, strPackageName, CPackageInfo.INSTALL_LOCATION_AUTO)
@JvmStatic
fun getApplicationInfo(context: Context, strPackageName: String, flags: Int): ApplicationInfo =
get(context).getApplicationInfo(strPackageName, flags)
/**
* 得到应用名
*/
@JvmStatic
fun getApplicationLabel(context: Context, applicationInfo: ApplicationInfo): String =
get(context).getApplicationLabel(applicationInfo).toString()
@JvmStatic
fun getApplicationEnabledSetting(context: Context, strPackageName: String): Int =
get(context).getApplicationEnabledSetting(strPackageName)
/**
* 得到图标
*/
@JvmStatic
fun getApplicationIcon(context: Context, applicationInfo: ApplicationInfo): Drawable =
get(context).getApplicationIcon(applicationInfo)
/**
* 得到图标
*/
@JvmStatic
fun getApplicationIcon(context: Context, strPackageName: String): Drawable =
get(context).getApplicationIcon(strPackageName)
/**
* 查询所有的符合Intent的Activities
*/
@JvmStatic
@OPermission_QUERY_ALL_PACKAGES
@RequiresPermission(CPermission.QUERY_ALL_PACKAGES)
@SuppressLint("QueryPermissionsNeeded")
fun queryIntentActivities(context: Context, intent: Intent, flags: Int): List<ResolveInfo> =
get(context).queryIntentActivities(intent, flags)
@JvmStatic
@OPermission_QUERY_ALL_PACKAGES
@RequiresPermission(CPermission.QUERY_ALL_PACKAGES)
@SuppressLint("QueryPermissionsNeeded")
fun getInstalledPackages(context: Context, flags: Int): List<PackageInfo> =
get(context).getInstalledPackages(flags)
@JvmStatic
@RequiresApi(CVersCode.V_33_13_TIRAMISU)
@OPermission_QUERY_ALL_PACKAGES
@RequiresPermission(CPermission.QUERY_ALL_PACKAGES)
@SuppressLint("QueryPermissionsNeeded")
fun getInstalledPackages(context: Context, flags: PackageInfoFlags): List<PackageInfo> =
get(context).getInstalledPackages(flags)
@JvmStatic
@OPermission_QUERY_ALL_PACKAGES
@RequiresPermission(CPermission.QUERY_ALL_PACKAGES)
fun getInstalledPackages_ofGET_ACTIVITIES(context: Context): List<PackageInfo> =
getInstalledPackages(context, CPackageManager.GET_ACTIVITIES)
@JvmStatic
@OPermission_QUERY_ALL_PACKAGES
@RequiresPermission(CPermission.QUERY_ALL_PACKAGES)
fun getInstalledPackages(context: Context): List<PackageInfo> {
val flags = CPackageManager.GET_ACTIVITIES or CPackageManager.GET_SERVICES
val installedPackageInfos: List<PackageInfo> = if (UtilKBuildVersion.isAfterV_33_13_TIRAMISU()) {
getInstalledPackages(context, PackageInfoFlags.of(flags.toLong()))
} else {
getInstalledPackages(context, flags)
}
return installedPackageInfos
}
/////////////////////////////////////////////////////////////////
@JvmStatic
fun getPermissionInfo(context: Context, permName: String, flags: Int): PermissionInfo =
get(context).getPermissionInfo(permName, flags)
@JvmStatic
fun getAllPermissionGroups(context: Context, flags: Int): List<PermissionGroupInfo> =
get(context).getAllPermissionGroups(flags)
@JvmStatic
fun getActivityInfo(context: Context, component: ComponentName, flags: Int): ActivityInfo =
get(context).getActivityInfo(component, flags)
@JvmStatic
fun getActivityInfo(context: Context, packageClazzName: String, activityClazzName: String): ActivityInfo =
getActivityInfo(context, ComponentName(packageClazzName, activityClazzName), CPackageManager.GET_ACTIVITIES)
@JvmStatic
fun getLaunchIntentForPackage(context: Context, strPackageName: String): Intent? =
get(context).getLaunchIntentForPackage(strPackageName)
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 是否有配置
*/
@JvmStatic
fun hasSystemFeature(context: Context, featureName: String): Boolean =
get(context).hasSystemFeature(featureName)
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 是否有包安装权限
*/
@JvmStatic
@RequiresPermission(CPermission.REQUEST_INSTALL_PACKAGES)
@OPermission_REQUEST_INSTALL_PACKAGES
@ADescription(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
fun canRequestPackageInstalls(context: Context): Boolean =
if (UtilKBuildVersion.isAfterV_26_8_O())
get(context).canRequestPackageInstalls()
else true
} | 1 | null | 8 | 118 | e46732e4fc58f1ad66e3974a393e3af411de7b17 | 7,088 | SwiftKit | Apache License 2.0 |
app/src/main/java/com/ClassicaMusic/inventory/ui/item/ItemEntryViewModel.kt | rubenesteban | 604,469,365 | false | null | /*
* Copyright (C) 2022 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.example.inventory.ui.item
import android.util.Log
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ClassicaMusic.inventory.data.Item
import com.ClassicaMusic.inventory.data.ItemsRepository
import com.ClassicaMusic.inventory.data.OrderUiState
import com.example.inventory.ui.item.ItemEntryViewModel.king.piramide
import com.example.inventory.ui.item.ItemEntryViewModel.kingWork.sol
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.util.*
/**
* View Model to validate and insert items in the Room database.
*/
class ItemEntryViewModel(private val itemsRepository: ItemsRepository) : ViewModel() {
/**
* Holds current item ui state
*/
var itemUiState by mutableStateOf(OrderUiState())
private set
var taskUiState by mutableStateOf(HomeUiState())
private set
private val _artoUiState = MutableStateFlow(HulkUiState())
var artoUiState: StateFlow<HulkUiState> = _artoUiState.asStateFlow()
private val _mar = piramide.toMutableStateList()
val mar: List<Int>
get() = _mar
private var Palabras: MutableSet<String> = mutableSetOf()
private var Palabra: MutableSet<Int> = mutableSetOf()
private var Pala: MutableSet<String> = mutableSetOf()
private var World: MutableSet<String> = mutableSetOf()
private var Worlds: List<Item> = listOf()
private var Wolf: List<String> = listOf()
private var Wolfi: Flow<String> = flowOf()
private var Wolfy: Flow<Item?> = flowOf()
lateinit var pina: String
lateinit var hulk: String
lateinit var hilk: String
lateinit var bull: String
// ----------------------------------
val texto : String by lazy { reloj(agua) }
//val telo : String by lazy { i }
val exit : MutableSet<String> by lazy { nilo()}
val essit : MutableSet<Int> by lazy { amazo()}
val inpar : Flow<String> by lazy { primor()}
val primo : Flow<Item?> by lazy { remolacha(5) }
val agua : String by lazy { red() }
// ----------------------------------
private var k: Int = 0
private val TAG: String = "book"
/**
* Updates the [itemUiState] with the value provided in the argument. This method also triggers
* a validation for input values.
*/
fun chickMito(g: String, h: Int) {
viewModelScope.launch {
pina = g
if (e <= h) {
Palabras.add(pina)
var eli = itemUiState.alfin
//Log.d(TAG, " Este es shin en Book------>>> es: $eli!")
var pelo = Palabras.size
var tren = listade(Palabras)
//Log.d(TAG, " Este es shin en Last------>>> es: $tren!")
if (pelo == h) {
//Log.d(TAG, " Este es shin en Book de relatividad------>>> es: $Palabras!")
for (i in 0..h-1){
updateUiStateto(i, tren[i])
inserItem()
}
var elo = taskUiState.itemList
setNaipe(tren)
//Log.d(TAG, " Este es shin en Book------>>> es: $elo!")
updateUiSta(tren)
var hulk = elote()
updateUiState(tren)
uptaItem()
// Log.d(TAG, " Este es shin en Book---c--->>> es: $elit!")
}
e += 1
var eng = artoUiState.value.alfin
Log.d(TAG, " Este es shin en Book------>>> es: $eng!")
checko()
}
}
}
fun PalabrasUsa(guessdWord: String, mas: Int, l: Long, m: List<Item> ) {
pina = guessdWord
Worlds = m
var p = k
var h=k
var z = Worlds.size
World.add(pina)
var mit = World.size
for (i in 0..z-1){
if(Worlds[i].name == pina){
//chucki(i,pina)
Pala.add(pina)
nilo()
var mill = Pala.size.toString()
bull = mill
red()
reloj(mill)
updateUiSteto(mill)
setFlavor(texto)
Palabra.add(i)
amazo()
h+=1
if(mit == mas-1){
mir(h)
sir(h)
var nil = h.toString()
// ecuador()
ecua(nil)
Log.d(TAG, "Hello -----------en--------------medida 0: $h !")
}
}
}
if (mit >= mas-1) {
mir(8)
Log.d(TAG, "Hello -----------en--------------medida 0: $mit!")
libro()
val pi = 151000 - l
val time = pi.toString()
// bull = time
//reloj()
Log.d(TAG, "Hello -----------en----------jjjjjjjjjjjj----medida 0: $texto !")
Log.d(TAG, "Hello -----------en--------------medida 0: $pi !")
}
}
fun subir (){
chocko(10, texto)
// chocko(11, telo)
}
fun nilo(): MutableSet<String> {
return Pala
}
fun amazo(): MutableSet<Int> {
return Palabra
}
fun montain(): Flow<String> {
var uno = primo.toString()
var eco = listare(uno as List<Item>)
var elo = eco[1]
val flow = flow<String> { emit(elo) }
return flow
}
suspend fun par(): Flow<String> {
bull = _artoUiState.value.name
Log.d(TAG, "Hello -----------en--------mmmmmmmmmmmmm------medida 0: $bull !")
val flow = flow<String> { emit("5") }
return flow
}
fun inpar(): Flow<String> {
bull = _artoUiState.value.name
Log.d(TAG, "Hello -----------en--------mmmmmmmmmmmmm------medida 0: $bull !")
val flow = flow<String> { emit("5") }
return flow
}
suspend fun ecuador(): String {
var uno = primo.toString()
var eco = listare(uno as List<Item>)
Log.d(TAG, "Hello -----------en--------mmmmmmmmmmmmm------medida 0: $uno !")
var elo = eco[1]
return uno
}
val gole : Flow<Item?> = remolacha(5)
val gol : Flow<String> = inpar()
val go : Flow<String> = inpar()
fun ecua(h: String): String {
hulk = h
return hulk
}
fun primor(): Flow<String> {
bull = "chicko()"
Log.d(TAG, "Hello -----------en--------mmmmmmmmmmmmm------medida 0: $bull !")
val flow = flow<String> { emit(bull) }
return flow
}
fun libro(){
var mil = primo
}
suspend fun InsertarBD(i:Int, n:String){
updateUiStateto(i, n)
inserItem()
}
fun chocko(i:Int, n:String) {
viewModelScope.launch {
InsertarBD(i, n)
}
}
suspend fun BorrarBD(i:Int, n:String){
updateUiStateto(i, n)
borrarItem()
}
fun zanahoria(i:Int, n:String) {
viewModelScope.launch {
BorrarBD(i, n)
}
}
fun remolacha(i:Int): Flow<Item?> {
viewModelScope.launch {
val ruc :Flow<Item?> = getItems(5)
Wolfy = ruc
}
return Wolfy
}
fun listade(a: MutableSet<String>): List<String> {
val ls = a.asSequence().toList()
//chicko()
return ls
}
fun listadi(a: MutableSet<String>): List<String> {
val ls = a.asSequence().toList()
//chicko()
return ls
}
fun listare(a: List<Item>): List<String> {
val ls = a.asSequence().map { it -> it.name }.toList()
return ls
}
fun topdio(h: String): Flow<String> {
pina = h
val flow = flow<String> { emit(pina ) }
return flow
}
val bit : Flow<String> = topdio("hello")
object king{
var piramide = number()
fun number(): List<Int> {
val miel = listOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
return miel
}
}
var camello = sol.toMutableStateList()
fun mir(h:Int){
if (camello.contains(h)){
camello.remove(h)
}
prueba()
}
fun sir(h:Int) {
if (mar.contains(h)) {
_mar.remove(h)
}
prueba()
}
fun prueba() {
var g = k
val mir = mar.size
Log.d(TAG, " Este es shin en Book---1--->>> es: $mir!")
val miler = camello.size
Log.d(TAG, " Este es shin en Book----1-->>> es: $miler!")
}
var we = prueba()
object kingWork{
var sol = number()
fun number(): List<Int> {
val miel = listOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
return miel
}
}
fun trelo() {
pina = "hulk"
hulk = "ok"
hilk = "elo"
bull = "miel"
}
init {
trelo()
//checko()
k = 0
}
var e = k
var r = k
var hola = taskUiState.itemList
fun cark(){
hola
// Log.d(TAG, "Hello -----------en--------------shenshen: $hola !")
}
/**
* Inserts an [Item] in the Room database
*/
suspend fun saveItem() {
itemsRepository.insertItem(itemUiState.toItem())
}
fun checko(): Flow<String> {
viewModelScope.launch {
val eco:Flow<String> = par()
Wolfi = eco
}
return Wolfi
}
fun chicko(): String {
viewModelScope.launch {
bull = ecuador()
Log.d(TAG, "Hello -----------en----hhhhhhhhhhh----------shenshen: $bull !")
}
var efo = bull
return efo
}
fun setNaipe(item: List<String>) {
_artoUiState.update { currentState ->
currentState.copy(alfin = item)
}
//Elefe(item)
}
var minte = mast()
fun mast(){
val mas = itemUiState.alfin
Log.d(TAG, " Los elemantos son igual a-------------on------->>> es: $mas!")
}
var readAll = itemsRepository.getAllItemsStream()
suspend fun uptaItem() {
itemsRepository.updateItem(itemUiState.toItem())
}
suspend fun inserItem() {
itemsRepository.insertItem(itemUiState.toItem())
}
suspend fun borrarItem() {
itemsRepository.deleteItem(itemUiState.toItem())
}
suspend fun getItems(id: Int): Flow<Item?> {
var hulj = itemsRepository.getItemStream(id)
return hulj
}
fun setFlavor(item: String) {
_artoUiState.update { currentState ->
currentState.copy(name = item)
}
//Elefe(item)
}
fun updateUiSteto( score: String) {
itemUiState = OrderUiState(score = score)
}
fun updateUiStateto(id: Int, name: String) {
itemUiState = OrderUiState(id = id, name = name)
}
fun updateUiSta(alfin: List<String>) {
itemUiState = OrderUiState(alfin= alfin)
}
fun updateUiState(i: List<String>) {
taskUiState = HomeUiState(i)
}
fun reloj(j:String): String {
return j
}
fun red(): String {
hulk = bull
return hulk
}
fun elote(){
val tin = taskUiState.itemList
Log.d(TAG, "Hello -----------enter---------------homeviewmodel: $tin!")
// checko()
}
}
data class HomeUiState(val itemList: List<String> = listOf())
data class HulkUiState(val Id: Int = 0, val name: String = "", val alfin: List<String> = listOf())
/**
* Represents Ui State for an Item.
*/
/**
* Extension function to convert [ItemUiState] to [Item]. If the value of [ItemUiState.price] is
* not a valid [Double], then the price will be set to 0.0. Similarly if the value of
* [ItemUiState] is not a valid [Int], then the quantity will be set to 0
*/
fun OrderUiState.toItem(): Item = Item(
id = id,
name = name
)
/**
* Extension function to convert [Item] to [ItemUiState]
*/
/**
* Extension function to convert [Item] to [ItemDetails]
*/
| 0 | Kotlin | 0 | 0 | 8484c0e2733d85458f48083905fc898b9da23797 | 12,777 | Our-World | Apache License 2.0 |
collector/src/main/java/com/bitmovin/analytics/features/errordetails/ErrorDetailBackend.kt | bitmovin | 120,633,749 | false | {"Kotlin": 1090733, "Java": 24931, "Shell": 13078} | package com.bitmovin.analytics.features.errordetails
import android.content.Context
import com.bitmovin.analytics.CollectorConfig
import com.bitmovin.analytics.features.httprequesttracking.HttpRequest
import com.bitmovin.analytics.utils.DataSerializer
import com.bitmovin.analytics.utils.HttpClient
import com.bitmovin.analytics.utils.Util
import okhttp3.OkHttpClient
import java.util.LinkedList
class ErrorDetailBackend(collectorConfig: CollectorConfig, context: Context, private val httpClient: HttpClient = HttpClient(context, OkHttpClient())) {
private val backendUrl = Util.joinUrl(collectorConfig.backendUrl, "/analytics/error")
private val _queue = LinkedList<ErrorDetail>()
val queue: List<ErrorDetail> = _queue
var enabled: Boolean = false
fun limitHttpRequestsInQueue(max: Int) {
for ((index, detail) in _queue.withIndex()) {
_queue[index] = detail.copyTruncateHttpRequests(max)
}
}
fun send(errorDetail: ErrorDetail) {
val errorDetailCopy = errorDetail.copyTruncateStringsAndUrls(MAX_STRING_LENGTH, MAX_URL_LENGTH)
if (enabled) {
httpClient.post(backendUrl, DataSerializer.serialize(errorDetailCopy), null)
} else {
_queue.add(errorDetailCopy)
}
}
fun flush() {
// We create a copy of the list to avoid side-effects like ending up in an infinite loop if we always add and remove the same element.
// This shouldn't happen as Kotlin is call-by-value, so `send` would not modify the original queue.
_queue.toList().forEach {
send(it)
_queue.remove(it)
}
}
fun clear() {
_queue.clear()
}
companion object {
const val MAX_URL_LENGTH = 200
const val MAX_STRING_LENGTH = 400
fun ErrorDetail.copyTruncateStringsAndUrls(maxStringLength: Int, maxUrlLength: Int): ErrorDetail = this.copy(
message = message?.take(maxStringLength),
data = data.copyTruncateStrings(maxStringLength),
httpRequests = httpRequests?.mapNotNull {
it.copyTruncateUrls(maxUrlLength)
},
)
private fun HttpRequest?.copyTruncateUrls(maxLength: Int) = this?.copy(
url = url?.take(maxLength),
lastRedirectLocation = lastRedirectLocation?.take(maxLength),
)
private fun ErrorData.copyTruncateStrings(maxStringLength: Int) = this.copy(
exceptionMessage = exceptionMessage?.take(maxStringLength),
additionalData = additionalData?.take(maxStringLength),
)
fun ErrorDetail.copyTruncateHttpRequests(maxRequests: Int) = this.copy(httpRequests = httpRequests?.take(maxRequests))
}
}
| 0 | Kotlin | 6 | 8 | f79d5f251b7e63db420384ad9176baecc53f1e89 | 2,744 | bitmovin-analytics-collector-android | Amazon Digital Services License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.