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/volvo/techtask/contracts/AppLogger.kt | msndvlpr | 458,329,184 | false | {"Kotlin": 61614} | /// Author(s): Mohsen Emami
/// Modified Date: 10/Feb/2022
package com.volvo.techtask.contracts
/**
* Common util for logging events.
* Can be used to store logs locally as well.
*/
interface AppLogger {
//May extend the functionality for accumulating log files into device memory as well
fun logD(tag: String, message: String)
fun logE(tag: String, message: String)
fun logV(tag: String, message: String)
fun logI(tag: String, message: String)
} | 0 | Kotlin | 0 | 0 | 80dc1ca4ac26a34152430ff822fdbd9330c47ff2 | 475 | volvo_tech_task | Apache License 2.0 |
android/src/main/java/com/stoneposdeeplink/executors/Printer.kt | cassiomariott | 731,980,424 | false | {"Kotlin": 11599, "TypeScript": 3789, "Ruby": 3728, "Objective-C": 2563, "JavaScript": 2254, "Objective-C++": 1228, "C": 103, "Swift": 68} | package com.stoneposdeeplink.executors
import android.app.Activity
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReadableMap
import android.net.Uri
import android.content.Intent
import java.lang.Exception
class Printer(reactApplicationContext: ReactApplicationContext ) {
val reactApplicationContext = reactApplicationContext
fun executeAction(
restOfPrinter: ReadableMap
) {
val requiredValues =
listOf(
"show_feedback_screen",
"return_scheme",
"json"
)
requiredValues.forEach {
if (!restOfPrinter.hasKey(it)) {
throw Exception(
String.format("%s is required", it)
)
}
}
val json = restOfPrinter.getString("json")
val return_scheme = restOfPrinter.getString("return_scheme")
val show_feedback_screen = restOfPrinter.getString("show_feedback_screen")
val uriBuilder = Uri.Builder()
uriBuilder.authority("print")
uriBuilder.scheme("printer-app")
uriBuilder.appendQueryParameter("SCHEME_RETURN", return_scheme)
uriBuilder.appendQueryParameter("PRINTABLE_CONTENT", json)
uriBuilder.appendQueryParameter("SHOW_FEEDBACK_SCREEN", show_feedback_screen)
val intent = Intent(Intent.ACTION_VIEW)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.data = uriBuilder.build()
reactApplicationContext.startActivity(intent)
}
}
| 0 | Kotlin | 0 | 0 | 24e820b52f5e49411180720e695de2e82d8a18af | 1,434 | react-native-stone-pos-deeplink | MIT License |
modules/core/arrow-typeclasses/src/main/kotlin/arrow/typeclasses/MonadContinuations.kt | Krishan14sharma | 183,217,828 | true | {"Kotlin": 2391225, "CSS": 152663, "JavaScript": 67900, "HTML": 23177, "Java": 4465, "Shell": 3043, "Ruby": 1598} | package arrow.typeclasses
import arrow.Kind
import arrow.core.Continuation
import java.util.concurrent.CountDownLatch
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED
import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn
interface BindingInContextContinuation<in T> : Continuation<T> {
fun await(): Throwable?
}
@RestrictsSuspension
open class MonadContinuation<F, A>(M: Monad<F>, override val context: CoroutineContext = EmptyCoroutineContext) :
Continuation<Kind<F, A>>, Monad<F> by M {
override fun resume(value: Kind<F, A>) {
returnedMonad = value
}
override fun resumeWithException(exception: Throwable) {
throw exception
}
protected fun bindingInContextContinuation(context: CoroutineContext): BindingInContextContinuation<Kind<F, A>> =
object : BindingInContextContinuation<Kind<F, A>> {
val latch: CountDownLatch = CountDownLatch(1)
var error: Throwable? = null
override fun await() = latch.await().let { error }
override val context: CoroutineContext = context
override fun resume(value: Kind<F, A>) {
returnedMonad = value
latch.countDown()
}
override fun resumeWithException(exception: Throwable) {
error = null
latch.countDown()
}
}
protected lateinit var returnedMonad: Kind<F, A>
open fun returnedMonad(): Kind<F, A> = returnedMonad
suspend fun <B> Kind<F, B>.bind(): B = bind { this }
suspend fun <B> (() -> B).bindIn(context: CoroutineContext): B =
bindIn(context, this)
open suspend fun <B> bind(m: () -> Kind<F, B>): B = suspendCoroutineUninterceptedOrReturn { c ->
val labelHere = c.stateStack // save the whole coroutine stack labels
returnedMonad = m().flatMap { x: B ->
c.stateStack = labelHere
c.resume(x)
returnedMonad
}
COROUTINE_SUSPENDED
}
open suspend fun <B> bindIn(context: CoroutineContext, m: () -> B): B = suspendCoroutineUninterceptedOrReturn { c ->
val labelHere = c.stateStack // save the whole coroutine stack labels
val monadCreation: suspend () -> Kind<F, A> = {
just(m()).flatMap { xx: B ->
c.stateStack = labelHere
c.resume(xx)
returnedMonad
}
}
val completion = bindingInContextContinuation(context)
returnedMonad = just(Unit).flatMap {
monadCreation.startCoroutine(completion)
val error = completion.await()
if (error != null) {
throw error
}
returnedMonad
}
COROUTINE_SUSPENDED
}
}
| 0 | Kotlin | 0 | 1 | 2b26976e1a8fbf29b7a3786074d56612440692a8 | 2,565 | arrow | Apache License 2.0 |
src/test/kotlin/br/com/zup/orangetalents/ConsultaChaveEndpointTest.kt | jmarcosfmg | 384,517,757 | true | {"Kotlin": 50535, "Smarty": 2032, "Dockerfile": 165} | package br.com.zup.orangetalents
import br.com.zup.orangetalents.commons.external.bcb.*
import br.com.zup.orangetalents.commons.external.itau.ClienteResponse
import br.com.zup.orangetalents.commons.external.itau.SistemaItau
import br.com.zup.orangetalents.commons.external.itau.SistemaItauInstituicao
import br.com.zup.orangetalents.model.ChavePix
import br.com.zup.orangetalents.model.TipoChave
import br.com.zup.orangetalents.model.TipoConta
import br.com.zup.orangetalents.repositories.ChavePixRepository
import io.grpc.ManagedChannel
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.annotation.GrpcChannel
import io.micronaut.grpc.server.GrpcServerChannel
import io.micronaut.http.HttpResponse
import io.micronaut.test.annotation.MockBean
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.*
import org.mockito.Mockito
import java.time.LocalDateTime
import java.util.*
import javax.inject.Inject
@Nested
@MicronautTest(transactional = false)
internal class ConsultaChaveEndpointTest(
@Inject val repository: ChavePixRepository,
@Inject val consultaChaveClient: ConsultaChavePixServiceGrpc.ConsultaChavePixServiceBlockingStub
) {
@Inject
lateinit var itauCliente: SistemaItau
@Inject
lateinit var bcbCliente: SistemaBCB
lateinit var pixId: UUID
val chaveDefault: ChavePix = ChavePix(
idCliente = "5260263c-a3c1-4727-ae32-3bdb2538841b",
tipoChave = TipoChave.EMAIL,
tipoConta = TipoConta.POUPANCA,
chave = "<EMAIL>"
)
val itauBuscaPorClienteResponse = ClienteResponse(
instituicao = SistemaItauInstituicao(nome = "ITAÚ UNIBANCO S.A.", ispb = "60701190"),
id = "5260263c-a3c1-4727-ae32-3bdb2538841b",
nome = "<NAME>",
cpf = "86135457004"
)
val clienteETipoContaResponse = ClienteETipoContaResponse(
tipo = "CONTA_POUPANCA",
instituicao = SistemaItauInstituicao(
nome = "ITAÚ UNIBANCO S.A.",
ispb = "60701190"
),
agencia = "0001",
numero = "291900",
titular = SistemaItauTitular(
id = "5260263c-a3c1-4727-ae32-3bdb2538841b",
nome = "<NAME>",
cpf = "86135457004"
)
)
@BeforeEach
fun setUp() {
pixId = repository.save(chaveDefault).id
}
@AfterEach
fun clean() {
repository.deleteAll()
}
@Test
fun `deve buscar pela chave Pix`() {
Mockito.`when`(
itauCliente.buscaContaCliente(
chaveDefault.idCliente, "CONTA_${chaveDefault.tipoConta.name}"
)
).thenReturn(
HttpResponse.ok(clienteETipoContaResponse)
)
val response: ConsultaChavePixResponse =
consultaChaveClient.consulta(ConsultaChavePixRequest.newBuilder().setChave(chaveDefault.chave).build())
Assertions.assertEquals(response.pixId, pixId.toString())
Assertions.assertEquals(response.clienteId, chaveDefault.idCliente)
Assertions.assertEquals(response.chave.chave, chaveDefault.chave)
Assertions.assertEquals(response.chave.conta.cpfDoTitular, itauBuscaPorClienteResponse.cpf)
Assertions.assertEquals(response.chave.conta.tipo.name, chaveDefault.tipoConta.name)
}
@Test
fun `deve buscar pelo keymanager`() {
Mockito.`when`(
itauCliente.buscaContaCliente(
chaveDefault.idCliente, "CONTA_${chaveDefault.tipoConta.name}"
)
).thenReturn(
HttpResponse.ok(clienteETipoContaResponse)
)
Mockito.`when`(
bcbCliente.buscaChave(pixId.toString())
).thenReturn(
HttpResponse.ok(
DetalhesChaveBCBResponse(
keyType = chaveDefault.tipoChave.name,
key = chaveDefault.chave,
bankAccount = BCBBankAccountResponse(
participant = clienteETipoContaResponse.instituicao.ispb,
branch = clienteETipoContaResponse.agencia,
accountNumber = clienteETipoContaResponse.numero,
accountType = BCBAccountType.fromTipoConta(chaveDefault.tipoConta).name
),
owner = BCBOwnerResponse(
type = "NATURAL_PERSON",
name = clienteETipoContaResponse.titular.nome,
taxIdNumber = clienteETipoContaResponse.titular.cpf
),
createdAt = LocalDateTime.now()
)
)
)
val response: ConsultaChavePixResponse =
consultaChaveClient.consulta(
ConsultaChavePixRequest.newBuilder()
.setPixId(
ConsultaChavePixRequest.FiltroPorPixId.newBuilder()
.setClienteId(chaveDefault.idCliente)
.setPixId(pixId.toString())
.build()
).build()
)
Assertions.assertEquals("", response.pixId)
Assertions.assertEquals("", response.clienteId)
Assertions.assertEquals(chaveDefault.chave, response.chave.chave)
Assertions.assertEquals(itauBuscaPorClienteResponse.cpf, response.chave.conta.cpfDoTitular)
Assertions.assertEquals(chaveDefault.tipoConta.name, response.chave.conta.tipo.name)
}
@Test
fun `deve dar erro se a chave nao existir`() {
val newPixId = UUID.randomUUID().toString()
Mockito.`when`(
bcbCliente.buscaChave(newPixId)
).thenReturn(
HttpResponse.notFound()
)
val thrownKey = assertThrows<StatusRuntimeException> {
consultaChaveClient.consulta(
ConsultaChavePixRequest
.newBuilder().setChave(newPixId).build()
)
}
val thrownChavePix = assertThrows<StatusRuntimeException> {
consultaChaveClient.consulta(
ConsultaChavePixRequest.newBuilder()
.setPixId(
ConsultaChavePixRequest.FiltroPorPixId.newBuilder()
.setClienteId(chaveDefault.idCliente)
.setPixId(newPixId)
.build()
).build()
)
}
Assertions.assertEquals(Status.NOT_FOUND.code, thrownChavePix.status.code)
Assertions.assertEquals(Status.NOT_FOUND.code, thrownKey.status.code)
}
@Test
fun `deve dar erro se a chave nao pertencer ao cliente`() {
val thrownChavePix = assertThrows<StatusRuntimeException> {
consultaChaveClient.consulta(
ConsultaChavePixRequest.newBuilder()
.setPixId(
ConsultaChavePixRequest.FiltroPorPixId.newBuilder()
.setClienteId("c56dfef4-7901-44fb-84e2-a2cefb157890")
.setPixId(pixId.toString())
.build()
).build()
)
}
Assertions.assertEquals(thrownChavePix.status.code, Status.PERMISSION_DENIED.code)
}
@Test
fun `deve buscar no bcb se a chave nao for encontrada no sistema`() {
val newPixId = UUID.randomUUID().toString()
Mockito.`when`(
bcbCliente.buscaChave(newPixId)
).thenReturn(
HttpResponse.ok(
DetalhesChaveBCBResponse(
keyType = chaveDefault.tipoChave.name,
key = chaveDefault.chave,
bankAccount = BCBBankAccountResponse(
participant = clienteETipoContaResponse.instituicao.ispb,
branch = clienteETipoContaResponse.agencia,
accountNumber = clienteETipoContaResponse.numero,
accountType = BCBAccountType.fromTipoConta(chaveDefault.tipoConta).name
),
owner = BCBOwnerResponse(
type = "NATURAL_PERSON",
name = clienteETipoContaResponse.titular.nome,
taxIdNumber = clienteETipoContaResponse.titular.cpf
),
createdAt = LocalDateTime.now()
)
)
)
}
@Test
fun `deve dar erro se a chave nao estiver no bcb`() {
Mockito.`when`(
bcbCliente.buscaChave(pixId.toString())
).thenReturn(HttpResponse.notFound())
val thrown = assertThrows<StatusRuntimeException> {
consultaChaveClient.consulta(
ConsultaChavePixRequest.newBuilder()
.setPixId(
ConsultaChavePixRequest.FiltroPorPixId.newBuilder()
.setClienteId(chaveDefault.idCliente)
.setPixId(pixId.toString())
.build()
).build()
)
}
Assertions.assertEquals(Status.PERMISSION_DENIED.code, thrown.status.code)
Assertions.assertEquals("PERMISSION_DENIED: Chave inválida - Aguardando aprovação!", thrown.message)
}
@MockBean(SistemaItau::class)
fun sistemaItau(): SistemaItau? {
return Mockito.mock(SistemaItau::class.java)
}
@MockBean(SistemaBCB::class)
fun sistemaBCB(): SistemaBCB? {
return Mockito.mock(SistemaBCB::class.java)
}
@Factory
class GrpcConsultaClient {
@Bean
fun blockingStub(@GrpcChannel(GrpcServerChannel.NAME) channel: ManagedChannel):
ConsultaChavePixServiceGrpc.ConsultaChavePixServiceBlockingStub {
return ConsultaChavePixServiceGrpc.newBlockingStub(channel)
}
}
} | 0 | Kotlin | 0 | 0 | 96e90398f75cbebbe51ccc45e653864da166ad27 | 10,004 | orange-talents-05-template-pix-keymanager-grpc | Apache License 2.0 |
vmtools/src/main/kotlin/com/vmloft/develop/library/tools/widget/dialog/VMDefaultDialog.kt | lzan13 | 78,939,095 | false | {"Kotlin": 759701, "Java": 45897, "HTML": 2434, "C": 2090, "Makefile": 967} | package com.vmloft.develop.library.tools.widget.dialog
import android.content.Context
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import com.vmloft.develop.library.tools.widget.dialog.VMBDialog
import com.vmloft.develop.library.tools.databinding.VmWidgetDefaultDialogBinding
/**
* Create by lzan13 on 2021/5/13 11:41
* 描述:自定义通用对话框
*/
open class VMDefaultDialog(context: Context) : VMBDialog<VmWidgetDefaultDialogBinding>(context) {
override fun initVB() = VmWidgetDefaultDialogBinding.inflate(LayoutInflater.from(context))
override fun getTitleTV(): TextView? = mBinding.vmDialogTitleTV
override fun getContentTV(): TextView? = mBinding.vmDialogContentTV
override fun getContainerLL(): LinearLayout? = mBinding.vmDialogContainerLL
override fun getNegativeTV(): TextView? = mBinding.vmDialogPositiveTV
override fun getPositiveTV(): TextView? = mBinding.vmDialogConfirmTV
} | 0 | Kotlin | 14 | 34 | c6eca3fb479d82ca14ca3bdcc3fb5f5494a4db0c | 965 | VMLibrary | MIT License |
utils/src/androidMain/kotlin/dev/icerock/moko/utils/callOnDispatcherWithoutFreeze.kt | icerockdev | 348,223,537 | false | null | /*
* Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.utils
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
actual fun <R> callOnDispatcherWithoutFreeze(
dispatcher: CoroutineDispatcher,
block: suspend () -> R
): suspend () -> R {
return {
withContext(dispatcher) {
block()
}
}
}
| 1 | Kotlin | 1 | 3 | 4c38882e4b1352eefa81e1d4fb43ae10a72956e5 | 439 | moko-utils | Apache License 2.0 |
src/main/kotlin/aoc2023/Day10.kt | j4velin | 572,870,735 | false | {"Kotlin": 212097, "Python": 1446} | package aoc2023
import readInput
object Day10 {
fun part1(input: List<String>): Int {
return 0
}
fun part2(input: List<String>): Int {
return 0
}
}
fun main() {
val testInput = readInput("Day10_test", 2023)
check(Day10.part1(testInput) == 0)
check(Day10.part2(testInput) == 0)
val input = readInput("Day10", 2023)
println(Day10.part1(input))
println(Day10.part2(input))
}
| 0 | Kotlin | 0 | 0 | a9f56bb01e27e501cad124bfcebb8e25763acb35 | 391 | adventOfCode | Apache License 2.0 |
app/src/main/java/com/bubelov/coins/model/User.kt | msgpo | 266,929,338 | true | {"Kotlin": 227542, "Dockerfile": 847} | package com.bubelov.coins.model
import org.joda.time.DateTime
data class User(
val id: String,
val email: String,
val emailConfirmed: Boolean,
val firstName: String,
val lastName: String,
val avatarUrl: String,
val createdAt: DateTime,
val updatedAt: DateTime
) | 0 | null | 0 | 0 | f3033534d1c104b04a98f9e734853f533a6c26dd | 295 | coin-map-android | MIT License |
graphql-kotlin-toolkit-codegen/src/test/kotlin/com/auritylab/graphql/kotlin/toolkit/codegen/CodegenSchemaParserTest.kt | AurityLab | 231,481,189 | false | null | package com.auritylab.graphql.kotlin.toolkit.codegen
import com.auritylab.graphql.kotlin.toolkit.codegen._test.TestObject
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import java.nio.file.Path
internal class CodegenSchemaParserTest {
@Test
fun `should parse single schema properly`() {
val schema = CodegenSchemaParser(TestObject.options).parseSchemas(setOf(testSchemaPath))
// Assert that the User type is available...
assertNotNull(schema.getObjectType("User"))
}
private val testSchemaPath = Path.of(
Thread.currentThread().contextClassLoader.getResource("testschema.graphqls")!!.toURI()
)
}
| 4 | Kotlin | 1 | 8 | 3dbb4e3b43cf713da34297bf827b63caaeb15ffa | 696 | graphql-kotlin-toolkit | Apache License 2.0 |
suspending/src/commonMain/kotlin/matt/collect/suspending/fake/fake.kt | mgroth0 | 532,378,323 | false | {"Kotlin": 203969} | package matt.collect.suspending.fake
import matt.collect.suspending.SuspendIterator
import matt.collect.suspending.SuspendMutableIterator
import matt.collect.suspending.list.SuspendListIterator
import matt.collect.suspending.list.SuspendMutableListIterator
import matt.lang.common.ILLEGAL
import matt.lang.common.err
fun <E> SuspendIterator<E>.toSuspendableFakeMutableIterator() = SuspendFakeMutableIterator(this)
open class SuspendFakeMutableIterator<E>(val itr: SuspendIterator<E>) :
SuspendIterator<E> by itr,
SuspendMutableIterator<E> {
final override suspend fun remove() {
err("tried remove in ${SuspendFakeMutableIterator::class.simpleName}")
}
}
class SuspendFakeMutableListIterator<E>(itr: SuspendListIterator<E>) :
SuspendListIterator<E> by itr,
SuspendMutableListIterator<E> {
override suspend fun add(element: E) = ILLEGAL
override suspend fun previous() = ILLEGAL
override suspend fun remove() = ILLEGAL
override suspend fun set(element: E) = ILLEGAL
}
| 0 | Kotlin | 0 | 0 | 178a627ede13e0f7b6c59a86a1d6c8c07627953a | 1,021 | collect | MIT License |
prefs/src/main/java/com/mathewsachin/fategrandautomata/prefs/BattleConfig.kt | MaxAkito | 297,404,165 | false | null | package com.mathewsachin.fategrandautomata.prefs
import androidx.core.content.edit
import com.mathewsachin.fategrandautomata.StorageDirs
import com.mathewsachin.fategrandautomata.prefs.core.PrefsCore
import com.mathewsachin.fategrandautomata.prefs.core.map
import com.mathewsachin.fategrandautomata.scripts.enums.MaterialEnum
import com.mathewsachin.fategrandautomata.scripts.prefs.IBattleConfig
const val defaultCardPriority = "WB, WA, WQ, B, A, Q, RB, RA, RQ"
internal class BattleConfig(
override val id: String,
prefsCore: PrefsCore,
val storageDirs: StorageDirs
) : IBattleConfig {
val prefs = prefsCore.forBattleConfig(id)
override var name by prefs.name
override var skillCommand by prefs.skillCommand
override var cardPriority by prefs.cardPriority
override val rearrangeCards get() = prefs.rearrangeCards
override val braveChains get() = prefs.braveChains
override val party by prefs.party
override val materials by prefs.materials.map {
it.mapNotNull { mat ->
try {
enumValueOf<MaterialEnum>(mat)
} catch (e: Exception) {
null
}
}
}
override val support = SupportPreferences(prefs.support, storageDirs)
override val npSpam by prefs.npSpam
override val skillSpam by prefs.skillSpam
override val autoChooseTarget by prefs.autoChooseTarget
override fun export(): Map<String, *> = prefs.sharedPrefs.all
override fun import(map: Map<String, *>) =
prefs.sharedPrefs.edit {
import(map)
}
override fun equals(other: Any?): Boolean {
if (other is IBattleConfig) {
return other.id == id
}
return super.equals(other)
}
override fun hashCode() = id.hashCode()
} | 0 | null | 1 | 1 | 5ea4e1478d4ac76c14ac9207d626103a6316e047 | 1,810 | FGA | MIT License |
components-core/src/main/java/com/adyen/checkout/components/base/GenericStoredPaymentComponentProvider.kt | tobias-square | 411,476,471 | true | {"Java Properties": 2, "Markdown": 6, "Gradle": 43, "Shell": 5, "EditorConfig": 1, "Batchfile": 1, "Text": 2, "Ignore List": 7, "INI": 22, "Proguard": 24, "Java": 241, "XML": 236, "Kotlin": 79, "JSON": 2, "CODEOWNERS": 1, "YAML": 4} | /*
* Copyright (c) 2020 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by caiof on 8/12/2020.
*/
package com.adyen.checkout.components.base
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import com.adyen.checkout.components.StoredPaymentComponentProvider
import com.adyen.checkout.components.base.lifecycle.viewModelFactory
import com.adyen.checkout.components.model.paymentmethods.PaymentMethod
import com.adyen.checkout.components.model.paymentmethods.StoredPaymentMethod
class GenericStoredPaymentComponentProvider<
BaseComponentT : BasePaymentComponent<*, *, *, *>,
ConfigurationT : Configuration
>(private val componentClass: Class<BaseComponentT>) : StoredPaymentComponentProvider<BaseComponentT, ConfigurationT> {
override fun get(
viewModelStoreOwner: ViewModelStoreOwner,
storedPaymentMethod: StoredPaymentMethod,
configuration: ConfigurationT
): BaseComponentT {
val genericStoredFactory: ViewModelProvider.Factory = viewModelFactory {
componentClass.getConstructor(
GenericStoredPaymentDelegate::class.java,
configuration.javaClass
).newInstance(GenericStoredPaymentDelegate(storedPaymentMethod), configuration)
}
return ViewModelProvider(viewModelStoreOwner, genericStoredFactory)[componentClass]
}
override fun get(
viewModelStoreOwner: ViewModelStoreOwner,
paymentMethod: PaymentMethod,
configuration: ConfigurationT
): BaseComponentT {
val genericFactory: ViewModelProvider.Factory = viewModelFactory {
componentClass.getConstructor(
GenericPaymentMethodDelegate::class.java,
configuration.javaClass
).newInstance(GenericPaymentMethodDelegate(paymentMethod), configuration)
}
return ViewModelProvider(viewModelStoreOwner, genericFactory)[componentClass]
}
}
| 0 | null | 0 | 0 | b6069aa9df2fa2ab0e04d265dc6fa934b2d91222 | 2,046 | adyen-android | MIT License |
app/src/main/java/com/dispositivosmoveis/watchfilmes/ui/more/MoreFragment.kt | thomas-soares | 321,982,495 | false | null | package com.dispositivosmoveis.watchfilmes.ui.more
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.dispositivosmoveis.watchfilmes.R
class MoreFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_more, container, false)
}
companion object {
@JvmStatic
fun newInstance(): MoreFragment {
return MoreFragment()
}
}
} | 0 | Kotlin | 0 | 0 | 0acd59e9a0d5291709b9fc3aa322e885422aeeed | 640 | WatchFilmes | MIT License |
superior-oracle-parser/src/test/java/io/github/melin/superior/parser/oracle/OracleSqlParserDdlTest.kt | melin | 140,644,913 | false | null | package io.github.melin.superior.parser.oracle
import io.github.melin.superior.common.StatementType
import io.github.melin.superior.common.relational.DefaultStatement
import io.github.melin.superior.common.relational.common.CommentData
import io.github.melin.superior.common.relational.create.CreateDatabase
import io.github.melin.superior.common.relational.create.CreateMaterializedView
import io.github.melin.superior.common.relational.create.CreateTable
import io.github.melin.superior.common.relational.create.CreateView
import org.junit.Assert
import org.junit.Test
class OracleSqlParserDdlTest {
@Test
fun createDatabaseTest() {
val sql = """
CREATE DATABASE bigdata1 USER SYSTEM IDENTIFIED BY 123213
drop DATABASE bigdata2
""".trimIndent()
val statements = OracleSqlHelper.parseMultiStatement(sql)
val createDatabse = statements.get(0)
val dropDatabase = statements.get(1)
if (createDatabse is CreateDatabase) {
Assert.assertEquals("bigdata1", createDatabse.databaseName)
} else {
Assert.fail()
}
if (dropDatabase is DefaultStatement) {
Assert.assertTrue(true)
} else {
Assert.fail()
}
}
@Test
fun createTableTest0() {
val sql = """
CREATE TABLE employees(
employee_id number(10) NOT NULL,
employee_name varchar2(50) NOT NULL,
city varchar2(50),
CONSTRAINT employees_pk PRIMARY KEY (employee_id)
);
""".trimIndent()
val statement = OracleSqlHelper.parseStatement(sql)
if (statement is CreateTable) {
Assert.assertEquals(StatementType.CREATE_TABLE, statement.statementType)
Assert.assertEquals("employees", statement.tableId.tableName)
Assert.assertEquals(3, statement.columnRels?.size)
Assert.assertTrue(statement.columnRels?.get(0)?.isPk!!)
Assert.assertFalse(statement.columnRels?.get(1)?.isPk!!)
} else {
Assert.fail()
}
}
@Test
fun createView0() {
val sql = """
CREATE OR REPLACE VIEW comedies AS
SELECT f.*,
country_code_to_name(f.country_code) AS country,
(SELECT avg(r.rating)
FROM user_ratings r
WHERE r.film_id = f.id) AS avg_rating
FROM films f
WHERE f.kind = 'Comedy'
""".trimIndent()
val statement = OracleSqlHelper.parseStatement(sql)
if (statement is CreateView) {
Assert.assertEquals(StatementType.CREATE_VIEW, statement.statementType)
Assert.assertEquals("comedies", statement.tableId.tableName)
Assert.assertEquals(2, statement.inputTables.size)
} else {
Assert.fail()
}
}
@Test
fun createMatView0() {
val sql = """
CREATE MATERIALIZED VIEW sales_summary AS
SELECT
seller_no,
invoice_date,
sum(invoice_amt) as sales_amt
FROM invoice
WHERE invoice_date < CURRENT_DATE
GROUP BY
seller_no,
invoice_date;
""".trimIndent()
val statement = OracleSqlHelper.parseStatement(sql)
if (statement is CreateMaterializedView) {
Assert.assertEquals(StatementType.CREATE_MATERIALIZED_VIEW, statement.statementType)
Assert.assertEquals("sales_summary", statement.tableId.tableName)
Assert.assertEquals(1, statement.inputTables.size)
} else {
Assert.fail()
}
}
@Test
fun commentTest0() {
val sql = """
COMMENT ON COLUMN employees.job_id IS 'abbreviated job title'
COMMENT ON COLUMN employees1.job_id IS 'abbreviated job title';
""".trimIndent()
val statement = OracleSqlHelper.parseMultiStatement(sql)
val st1 = statement.get(0)
val st2 = statement.get(1)
if (st1 is CommentData) {
Assert.assertEquals(StatementType.COMMENT, st1.statementType)
Assert.assertEquals("employees.job_id", st1.objValue)
Assert.assertEquals("abbreviated job title", st1.comment)
Assert.assertFalse(st1.isNull)
}
if (st2 is CommentData) {
Assert.assertEquals(StatementType.COMMENT, st2.statementType)
Assert.assertEquals("employees1.job_id", st2.objValue)
Assert.assertEquals("abbreviated job title", st2.comment)
Assert.assertFalse(st2.isNull)
}
}
} | 5 | ANTLR | 98 | 97 | dabf49097c380395b6ed0782d319da1b537453c4 | 4,785 | superior-sql-parser | Apache License 2.0 |
src/test/kotlin/com/hans/de/melo/restaurantsgeospatial/restaurantsgeospatial/ConstantsIntegrationTest.kt | hansmelo | 247,266,869 | false | null | package com.hans.de.melo.restaurantsgeospatial.restaurantsgeospatial
var polygonJson = "{\"coordinates\":" +
"[[" +
"[-73.94193078816193,40.70072523469547]," +
"[-73.9443878859649,40.70042452378256]," +
"[-73.94424286147482,40.69969927964773]," +
"[-73.94409591260093,40.69897295461309]," +
"[-73.94394947271304,40.69822127983908]," +
"[-73.94391750192877,40.69805620211356]," +
"[-73.94380383211836,40.697469265449826]," +
"[-73.94378455587042,40.6973697290538]," +
"[-73.94374306706803,40.69715549995503]," +
"[-73.9437245356891,40.697059812179496]," +
"[-73.94368427322361,40.696851909818065]," +
"[-73.9436842703752,40.69685189440415]," +
"[-73.94363806934868,40.69661331854307]," +
"[-73.94362121369004,40.696526279661654]," +
"[-73.9435563415296,40.69619128295102]," +
"[-73.94354024149403,40.6961081421151]," +
"[-73.94352527471477,40.69603085523812]," +
"[-73.94338802084431,40.69528899051899]," +
"[-73.943242490861,40.694557485733355]," +
"[-73.94312826743185,40.693967038330925]," +
"[-73.94311427813774,40.693894720557466]," +
"[-73.94310040895432,40.69382302905847]," +
"[-73.94295136131598,40.69309078423585]," +
"[-73.94280765181726,40.692357794128945]," +
"[-73.94266181801652,40.69162434435983]," +
"[-73.94251587928605,40.69089200097073]," +
"[-73.94236932748694,40.690159944665304]," +
"[-73.94222203471806,40.68942797886745]," +
"[-73.94207684924385,40.68869720298344]," +
"[-73.9419324508184,40.687962958755094]," +
"[-73.94178527584324,40.687228372121126]," +
"[-73.94163933150469,40.68649727009258]," +
"[-73.94149491757346,40.68576452882908]," +
"[-73.94134827184915,40.685031202512505]," +
"[-73.94120399291621,40.68429983923358]," +
"[-73.94105783787931,40.68356687284592]," +
"[-73.9409133427312,40.682833617234294]," +
"[-73.94076893329961,40.68210083903887]," +
"[-73.94062005382186,40.68137013010259]," +
"[-73.94047635005941,40.680635695422964]," +
"[-73.94032793962053,40.67988997506463]," +
"[-73.94120864299748,40.67993835375214]," +
"[-73.94326176928655,40.68005060712657]," +
"[-73.94397347805013,40.680088128426995]," +
"[-73.94627470970092,40.68021332692951]," +
"[-73.94674915979888,40.680239661363046]," +
"[-73.9477302355664,40.680291846282316]," +
"[-73.9495568871113,40.68039040292329]," +
"[-73.95115828512961,40.68047861480679]," +
"[-73.95155682676496,40.680498847575564]," +
"[-73.95337017508861,40.68064050844431]," +
"[-73.95351616791015,40.68138260047889]," +
"[-73.95366256227194,40.68211490361348]," +
"[-73.95380893530668,40.68284800827331]," +
"[-73.95395453033524,40.68358077882069]," +
"[-73.95410042574005,40.684313107633436]," +
"[-73.95424647696164,40.68504624826183]," +
"[-73.95439296867414,40.685779720013606]," +
"[-73.95453798607406,40.68651117540455]," +
"[-73.95468418850508,40.68724485443714]," +
"[-73.95684165193596,40.68699607883792]," +
"[-73.95956770121337,40.68668255592727]," +
"[-73.95971374756459,40.6874156340909]," +
"[-73.95985939425704,40.688147451217226]," +
"[-73.96000519802635,40.688881033718204]," +
"[-73.96009714565346,40.689345210097464]," +
"[-73.96012172912181,40.68946930706387]," +
"[-73.96017256138677,40.68972986156118]," +
"[-73.96018691858275,40.689803455988546]," +
"[-73.96022304539724,40.689988627383755]," +
"[-73.96023740336433,40.69006222280781]," +
"[-73.96029281668112,40.690346249915414]," +
"[-73.96013760800457,40.69036438035883]," +
"[-73.96008336800442,40.6903707157072]," +
"[-73.95957591847137,40.69042998753855]," +
"[-73.95942791320554,40.69044727471387]," +
"[-73.95934862389824,40.6904564609108]," +
"[-73.95928133730644,40.69046425696955]," +
"[-73.95899330491858,40.69049762936284]," +
"[-73.95886713625437,40.69051224801476]," +
"[-73.95857844775936,40.690545694857576]," +
"[-73.9581804874994,40.69059073040573]," +
"[-73.95808563435828,40.69060146372528]," +
"[-73.95727249112613,40.69069347835403]," +
"[-73.95635602958276,40.69079978191732]," +
"[-73.95541057949602,40.690908291885876]," +
"[-73.95582662769675,40.69299238288233]," +
"[-73.95614239268207,40.69457901857237]," +
"[-73.9570870194244,40.694470440162995]," +
"[-73.95799732979468,40.694365838684114]," +
"[-73.95931047927598,40.69421508783189]," +
"[-73.96015854658333,40.69411730915604]," +
"[-73.96062056531659,40.6963201401926]," +
"[-73.96092543804184,40.69773650701631]," +
"[-73.96105100700007,40.698326078819065]," +
"[-73.96019688857467,40.698462727438596]," +
"[-73.95885874627406,40.6986773264162]," +
"[-73.95795938220984,40.69882000321581]," +
"[-73.95701993123406,40.698973914349565]," +
"[-73.957167301054,40.69970786791901]," +
"[-73.95722517405626,40.69999935002626]," +
"[-73.95745736372834,40.70082260318457]," +
"[-73.95572361014881,40.70194576955721]," +
"[-73.9538119690652,40.70318097979544]," +
"[-73.95318085172319,40.70261690547745]," +
"[-73.95255052777945,40.7020516665144]," +
"[-73.951920189279,40.70148754916077]," +
"[-73.95128819434734,40.70092236548591]," +
"[-73.95027424109588,40.70157924195056]," +
"[-73.9493787354337,40.70215888982628]," +
"[-73.94753858146478,40.703350650664795]," +
"[-73.94705205297524,40.70366394934019]," +
"[-73.94625107780892,40.70320874745355]," +
"[-73.9458549904679,40.70298720677488]," +
"[-73.94544988192177,40.702760635974364]," +
"[-73.94463910154856,40.70231369467456]," +
"[-73.94431460096804,40.70213334535181]," +
"[-73.94400504048726,40.70196179219718]," +
"[-73.9438247374114,40.701862007878276]," +
"[-73.94322686012315,40.701520709145726]," +
"[-73.94306406845838,40.7014244350918]," +
"[-73.94220058705264,40.700890667467746]," +
"[-73.94193078816193,40.70072523469547]" +
"]]," +
"\"type\":\"Polygon\"}"
var location1 = "{\"coordinates\":[-73.9440286,40.7006576],\"type\":\"Point\"}"
var location2 = "{\"coordinates\":[-73.9434833,40.70067239999999],\"type\":\"Point\"}"
var location3 = "{\"coordinates\":[-73.94195599999999,40.823392],\"type\":\"Point\"}"
var habaneroCafeMexicanGrillJson =
"{\"id\":{\"timestamp\":1487244251,\"counter\":15966002,\"time\":1487244251000,\"machineIdentifier\":8755099,\"processIdentifier\":21525,\"timeSecond\":1487244251,\"date\":1487244251000}," +
"\"location\":{\"x\":-73.9440286,\"y\":40.7006576,\"type\":\"Point\",\"coordinates\":[-73.9440286,40.7006576]}," +
"\"name\":\"Habanero Cafe Mexican Grill\"}"
var peoplesChoiceKitchenJson =
"{\"id\":{\"timestamp\":1439408711,\"counter\":348171,\"machineIdentifier\":7098924,\"processIdentifier\":-20517,\"timeSecond\":1439408711,\"time\":1439408711000,\"date\":1439408711000}," +
"\"location\":{\"x\":-73.94195599999999,\"y\":40.823392,\"coordinates\":[-73.94195599999999,40.823392],\"type\":\"Point\"}," +
"\"name\":\"Peoples Choice Kitchen\"}"
var losAngelesBakeryJson =
"{\"id\":{\"timestamp\":1487244251,\"counter\":15966052,\"date\":1487244251000,\"machineIdentifier\":8755099,\"processIdentifier\":21525,\"timeSecond\":1487244251,\"time\":1487244251000}," +
"\"location\":{\"x\":-73.9434833,\"y\":40.70067239999999,\"type\":\"Point\",\"coordinates\":[-73.9434833,40.70067239999999]}," +
"\"name\":\"<NAME>\"}]\n"
var neighborhoodJson = "{\"id\":{\"timestamp\":1487244251,\"counter\":15965987,\"time\":1487244251000,\"machineIdentifier\":8755099,\"processIdentifier\":21525,\"timeSecond\":1487244251,\"date\":1487244251000},\"geometry\":{\"points\":[{\"x\":-73.94193078816193,\"y\":40.70072523469547,\"type\":\"Point\",\"coordinates\":[-73.94193078816193,40.70072523469547]},{\"x\":-73.9443878859649,\"y\":40.70042452378256,\"type\":\"Point\",\"coordinates\":[-73.9443878859649,40.70042452378256]},{\"x\":-73.94424286147482,\"y\":40.69969927964773,\"type\":\"Point\",\"coordinates\":[-73.94424286147482,40.69969927964773]},{\"x\":-73.94409591260093,\"y\":40.69897295461309,\"type\":\"Point\",\"coordinates\":[-73.94409591260093,40.69897295461309]},{\"x\":-73.94394947271304,\"y\":40.69822127983908,\"type\":\"Point\",\"coordinates\":[-73.94394947271304,40.69822127983908]},{\"x\":-73.94391750192877,\"y\":40.69805620211356,\"type\":\"Point\",\"coordinates\":[-73.94391750192877,40.69805620211356]},{\"x\":-73.94380383211836,\"y\":40.697469265449826,\"type\":\"Point\",\"coordinates\":[-73.94380383211836,40.697469265449826]},{\"x\":-73.94378455587042,\"y\":40.6973697290538,\"type\":\"Point\",\"coordinates\":[-73.94378455587042,40.6973697290538]},{\"x\":-73.94374306706803,\"y\":40.69715549995503,\"type\":\"Point\",\"coordinates\":[-73.94374306706803,40.69715549995503]},{\"x\":-73.9437245356891,\"y\":40.697059812179496,\"type\":\"Point\",\"coordinates\":[-73.9437245356891,40.697059812179496]},{\"x\":-73.94368427322361,\"y\":40.696851909818065,\"type\":\"Point\",\"coordinates\":[-73.94368427322361,40.696851909818065]},{\"x\":-73.9436842703752,\"y\":40.69685189440415,\"type\":\"Point\",\"coordinates\":[-73.9436842703752,40.69685189440415]},{\"x\":-73.94363806934868,\"y\":40.69661331854307,\"type\":\"Point\",\"coordinates\":[-73.94363806934868,40.69661331854307]},{\"x\":-73.94362121369004,\"y\":40.696526279661654,\"type\":\"Point\",\"coordinates\":[-73.94362121369004,40.696526279661654]},{\"x\":-73.9435563415296,\"y\":40.69619128295102,\"type\":\"Point\",\"coordinates\":[-73.9435563415296,40.69619128295102]},{\"x\":-73.94354024149403,\"y\":40.6961081421151,\"type\":\"Point\",\"coordinates\":[-73.94354024149403,40.6961081421151]},{\"x\":-73.94352527471477,\"y\":40.69603085523812,\"type\":\"Point\",\"coordinates\":[-73.94352527471477,40.69603085523812]},{\"x\":-73.94338802084431,\"y\":40.69528899051899,\"type\":\"Point\",\"coordinates\":[-73.94338802084431,40.69528899051899]},{\"x\":-73.943242490861,\"y\":40.694557485733355,\"type\":\"Point\",\"coordinates\":[-73.943242490861,40.694557485733355]},{\"x\":-73.94312826743185,\"y\":40.693967038330925,\"type\":\"Point\",\"coordinates\":[-73.94312826743185,40.693967038330925]},{\"x\":-73.94311427813774,\"y\":40.693894720557466,\"type\":\"Point\",\"coordinates\":[-73.94311427813774,40.693894720557466]},{\"x\":-73.94310040895432,\"y\":40.69382302905847,\"type\":\"Point\",\"coordinates\":[-73.94310040895432,40.69382302905847]},{\"x\":-73.94295136131598,\"y\":40.69309078423585,\"type\":\"Point\",\"coordinates\":[-73.94295136131598,40.69309078423585]},{\"x\":-73.94280765181726,\"y\":40.692357794128945,\"type\":\"Point\",\"coordinates\":[-73.94280765181726,40.692357794128945]},{\"x\":-73.94266181801652,\"y\":40.69162434435983,\"type\":\"Point\",\"coordinates\":[-73.94266181801652,40.69162434435983]},{\"x\":-73.94251587928605,\"y\":40.69089200097073,\"type\":\"Point\",\"coordinates\":[-73.94251587928605,40.69089200097073]},{\"x\":-73.94236932748694,\"y\":40.690159944665304,\"type\":\"Point\",\"coordinates\":[-73.94236932748694,40.690159944665304]},{\"x\":-73.94222203471806,\"y\":40.68942797886745,\"type\":\"Point\",\"coordinates\":[-73.94222203471806,40.68942797886745]},{\"x\":-73.94207684924385,\"y\":40.68869720298344,\"type\":\"Point\",\"coordinates\":[-73.94207684924385,40.68869720298344]},{\"x\":-73.9419324508184,\"y\":40.687962958755094,\"type\":\"Point\",\"coordinates\":[-73.9419324508184,40.687962958755094]},{\"x\":-73.94178527584324,\"y\":40.687228372121126,\"type\":\"Point\",\"coordinates\":[-73.94178527584324,40.687228372121126]},{\"x\":-73.94163933150469,\"y\":40.68649727009258,\"type\":\"Point\",\"coordinates\":[-73.94163933150469,40.68649727009258]},{\"x\":-73.94149491757346,\"y\":40.68576452882908,\"type\":\"Point\",\"coordinates\":[-73.94149491757346,40.68576452882908]},{\"x\":-73.94134827184915,\"y\":40.685031202512505,\"type\":\"Point\",\"coordinates\":[-73.94134827184915,40.685031202512505]},{\"x\":-73.94120399291621,\"y\":40.68429983923358,\"type\":\"Point\",\"coordinates\":[-73.94120399291621,40.68429983923358]},{\"x\":-73.94105783787931,\"y\":40.68356687284592,\"type\":\"Point\",\"coordinates\":[-73.94105783787931,40.68356687284592]},{\"x\":-73.9409133427312,\"y\":40.682833617234294,\"type\":\"Point\",\"coordinates\":[-73.9409133427312,40.682833617234294]},{\"x\":-73.94076893329961,\"y\":40.68210083903887,\"type\":\"Point\",\"coordinates\":[-73.94076893329961,40.68210083903887]},{\"x\":-73.94062005382186,\"y\":40.68137013010259,\"type\":\"Point\",\"coordinates\":[-73.94062005382186,40.68137013010259]},{\"x\":-73.94047635005941,\"y\":40.680635695422964,\"type\":\"Point\",\"coordinates\":[-73.94047635005941,40.680635695422964]},{\"x\":-73.94032793962053,\"y\":40.67988997506463,\"type\":\"Point\",\"coordinates\":[-73.94032793962053,40.67988997506463]},{\"x\":-73.94120864299748,\"y\":40.67993835375214,\"type\":\"Point\",\"coordinates\":[-73.94120864299748,40.67993835375214]},{\"x\":-73.94326176928655,\"y\":40.68005060712657,\"type\":\"Point\",\"coordinates\":[-73.94326176928655,40.68005060712657]},{\"x\":-73.94397347805013,\"y\":40.680088128426995,\"type\":\"Point\",\"coordinates\":[-73.94397347805013,40.680088128426995]},{\"x\":-73.94627470970092,\"y\":40.68021332692951,\"type\":\"Point\",\"coordinates\":[-73.94627470970092,40.68021332692951]},{\"x\":-73.94674915979888,\"y\":40.680239661363046,\"type\":\"Point\",\"coordinates\":[-73.94674915979888,40.680239661363046]},{\"x\":-73.9477302355664,\"y\":40.680291846282316,\"type\":\"Point\",\"coordinates\":[-73.9477302355664,40.680291846282316]},{\"x\":-73.9495568871113,\"y\":40.68039040292329,\"type\":\"Point\",\"coordinates\":[-73.9495568871113,40.68039040292329]},{\"x\":-73.95115828512961,\"y\":40.68047861480679,\"type\":\"Point\",\"coordinates\":[-73.95115828512961,40.68047861480679]},{\"x\":-73.95155682676496,\"y\":40.680498847575564,\"type\":\"Point\",\"coordinates\":[-73.95155682676496,40.680498847575564]},{\"x\":-73.95337017508861,\"y\":40.68064050844431,\"type\":\"Point\",\"coordinates\":[-73.95337017508861,40.68064050844431]},{\"x\":-73.95351616791015,\"y\":40.68138260047889,\"type\":\"Point\",\"coordinates\":[-73.95351616791015,40.68138260047889]},{\"x\":-73.95366256227194,\"y\":40.68211490361348,\"type\":\"Point\",\"coordinates\":[-73.95366256227194,40.68211490361348]},{\"x\":-73.95380893530668,\"y\":40.68284800827331,\"type\":\"Point\",\"coordinates\":[-73.95380893530668,40.68284800827331]},{\"x\":-73.95395453033524,\"y\":40.68358077882069,\"type\":\"Point\",\"coordinates\":[-73.95395453033524,40.68358077882069]},{\"x\":-73.95410042574005,\"y\":40.684313107633436,\"type\":\"Point\",\"coordinates\":[-73.95410042574005,40.684313107633436]},{\"x\":-73.95424647696164,\"y\":40.68504624826183,\"type\":\"Point\",\"coordinates\":[-73.95424647696164,40.68504624826183]},{\"x\":-73.95439296867414,\"y\":40.685779720013606,\"type\":\"Point\",\"coordinates\":[-73.95439296867414,40.685779720013606]},{\"x\":-73.95453798607406,\"y\":40.68651117540455,\"type\":\"Point\",\"coordinates\":[-73.95453798607406,40.68651117540455]},{\"x\":-73.95468418850508,\"y\":40.68724485443714,\"type\":\"Point\",\"coordinates\":[-73.95468418850508,40.68724485443714]},{\"x\":-73.95684165193596,\"y\":40.68699607883792,\"type\":\"Point\",\"coordinates\":[-73.95684165193596,40.68699607883792]},{\"x\":-73.95956770121337,\"y\":40.68668255592727,\"type\":\"Point\",\"coordinates\":[-73.95956770121337,40.68668255592727]},{\"x\":-73.95971374756459,\"y\":40.6874156340909,\"type\":\"Point\",\"coordinates\":[-73.95971374756459,40.6874156340909]},{\"x\":-73.95985939425704,\"y\":40.688147451217226,\"type\":\"Point\",\"coordinates\":[-73.95985939425704,40.688147451217226]},{\"x\":-73.96000519802635,\"y\":40.688881033718204,\"type\":\"Point\",\"coordinates\":[-73.96000519802635,40.688881033718204]},{\"x\":-73.96009714565346,\"y\":40.689345210097464,\"type\":\"Point\",\"coordinates\":[-73.96009714565346,40.689345210097464]},{\"x\":-73.96012172912181,\"y\":40.68946930706387,\"type\":\"Point\",\"coordinates\":[-73.96012172912181,40.68946930706387]},{\"x\":-73.96017256138677,\"y\":40.68972986156118,\"type\":\"Point\",\"coordinates\":[-73.96017256138677,40.68972986156118]},{\"x\":-73.96018691858275,\"y\":40.689803455988546,\"type\":\"Point\",\"coordinates\":[-73.96018691858275,40.689803455988546]},{\"x\":-73.96022304539724,\"y\":40.689988627383755,\"type\":\"Point\",\"coordinates\":[-73.96022304539724,40.689988627383755]},{\"x\":-73.96023740336433,\"y\":40.69006222280781,\"type\":\"Point\",\"coordinates\":[-73.96023740336433,40.69006222280781]},{\"x\":-73.96029281668112,\"y\":40.690346249915414,\"type\":\"Point\",\"coordinates\":[-73.96029281668112,40.690346249915414]},{\"x\":-73.96013760800457,\"y\":40.69036438035883,\"type\":\"Point\",\"coordinates\":[-73.96013760800457,40.69036438035883]},{\"x\":-73.96008336800442,\"y\":40.6903707157072,\"type\":\"Point\",\"coordinates\":[-73.96008336800442,40.6903707157072]},{\"x\":-73.95957591847137,\"y\":40.69042998753855,\"type\":\"Point\",\"coordinates\":[-73.95957591847137,40.69042998753855]},{\"x\":-73.95942791320554,\"y\":40.69044727471387,\"type\":\"Point\",\"coordinates\":[-73.95942791320554,40.69044727471387]},{\"x\":-73.95934862389824,\"y\":40.6904564609108,\"type\":\"Point\",\"coordinates\":[-73.95934862389824,40.6904564609108]},{\"x\":-73.95928133730644,\"y\":40.69046425696955,\"type\":\"Point\",\"coordinates\":[-73.95928133730644,40.69046425696955]},{\"x\":-73.95899330491858,\"y\":40.69049762936284,\"type\":\"Point\",\"coordinates\":[-73.95899330491858,40.69049762936284]},{\"x\":-73.95886713625437,\"y\":40.69051224801476,\"type\":\"Point\",\"coordinates\":[-73.95886713625437,40.69051224801476]},{\"x\":-73.95857844775936,\"y\":40.690545694857576,\"type\":\"Point\",\"coordinates\":[-73.95857844775936,40.690545694857576]},{\"x\":-73.9581804874994,\"y\":40.69059073040573,\"type\":\"Point\",\"coordinates\":[-73.9581804874994,40.69059073040573]},{\"x\":-73.95808563435828,\"y\":40.69060146372528,\"type\":\"Point\",\"coordinates\":[-73.95808563435828,40.69060146372528]},{\"x\":-73.95727249112613,\"y\":40.69069347835403,\"type\":\"Point\",\"coordinates\":[-73.95727249112613,40.69069347835403]},{\"x\":-73.95635602958276,\"y\":40.69079978191732,\"type\":\"Point\",\"coordinates\":[-73.95635602958276,40.69079978191732]},{\"x\":-73.95541057949602,\"y\":40.690908291885876,\"type\":\"Point\",\"coordinates\":[-73.95541057949602,40.690908291885876]},{\"x\":-73.95582662769675,\"y\":40.69299238288233,\"type\":\"Point\",\"coordinates\":[-73.95582662769675,40.69299238288233]},{\"x\":-73.95614239268207,\"y\":40.69457901857237,\"type\":\"Point\",\"coordinates\":[-73.95614239268207,40.69457901857237]},{\"x\":-73.9570870194244,\"y\":40.694470440162995,\"type\":\"Point\",\"coordinates\":[-73.9570870194244,40.694470440162995]},{\"x\":-73.95799732979468,\"y\":40.694365838684114,\"type\":\"Point\",\"coordinates\":[-73.95799732979468,40.694365838684114]},{\"x\":-73.95931047927598,\"y\":40.69421508783189,\"type\":\"Point\",\"coordinates\":[-73.95931047927598,40.69421508783189]},{\"x\":-73.96015854658333,\"y\":40.69411730915604,\"type\":\"Point\",\"coordinates\":[-73.96015854658333,40.69411730915604]},{\"x\":-73.96062056531659,\"y\":40.6963201401926,\"type\":\"Point\",\"coordinates\":[-73.96062056531659,40.6963201401926]},{\"x\":-73.96092543804184,\"y\":40.69773650701631,\"type\":\"Point\",\"coordinates\":[-73.96092543804184,40.69773650701631]},{\"x\":-73.96105100700007,\"y\":40.698326078819065,\"type\":\"Point\",\"coordinates\":[-73.96105100700007,40.698326078819065]},{\"x\":-73.96019688857467,\"y\":40.698462727438596,\"type\":\"Point\",\"coordinates\":[-73.96019688857467,40.698462727438596]},{\"x\":-73.95885874627406,\"y\":40.6986773264162,\"type\":\"Point\",\"coordinates\":[-73.95885874627406,40.6986773264162]},{\"x\":-73.95795938220984,\"y\":40.69882000321581,\"type\":\"Point\",\"coordinates\":[-73.95795938220984,40.69882000321581]},{\"x\":-73.95701993123406,\"y\":40.698973914349565,\"type\":\"Point\",\"coordinates\":[-73.95701993123406,40.698973914349565]},{\"x\":-73.957167301054,\"y\":40.69970786791901,\"type\":\"Point\",\"coordinates\":[-73.957167301054,40.69970786791901]},{\"x\":-73.95722517405626,\"y\":40.69999935002626,\"type\":\"Point\",\"coordinates\":[-73.95722517405626,40.69999935002626]},{\"x\":-73.95745736372834,\"y\":40.70082260318457,\"type\":\"Point\",\"coordinates\":[-73.95745736372834,40.70082260318457]},{\"x\":-73.95572361014881,\"y\":40.70194576955721,\"type\":\"Point\",\"coordinates\":[-73.95572361014881,40.70194576955721]},{\"x\":-73.9538119690652,\"y\":40.70318097979544,\"type\":\"Point\",\"coordinates\":[-73.9538119690652,40.70318097979544]},{\"x\":-73.95318085172319,\"y\":40.70261690547745,\"type\":\"Point\",\"coordinates\":[-73.95318085172319,40.70261690547745]},{\"x\":-73.95255052777945,\"y\":40.7020516665144,\"type\":\"Point\",\"coordinates\":[-73.95255052777945,40.7020516665144]},{\"x\":-73.951920189279,\"y\":40.70148754916077,\"type\":\"Point\",\"coordinates\":[-73.951920189279,40.70148754916077]},{\"x\":-73.95128819434734,\"y\":40.70092236548591,\"type\":\"Point\",\"coordinates\":[-73.95128819434734,40.70092236548591]},{\"x\":-73.95027424109588,\"y\":40.70157924195056,\"type\":\"Point\",\"coordinates\":[-73.95027424109588,40.70157924195056]},{\"x\":-73.9493787354337,\"y\":40.70215888982628,\"type\":\"Point\",\"coordinates\":[-73.9493787354337,40.70215888982628]},{\"x\":-73.94753858146478,\"y\":40.703350650664795,\"type\":\"Point\",\"coordinates\":[-73.94753858146478,40.703350650664795]},{\"x\":-73.94705205297524,\"y\":40.70366394934019,\"type\":\"Point\",\"coordinates\":[-73.94705205297524,40.70366394934019]},{\"x\":-73.94625107780892,\"y\":40.70320874745355,\"type\":\"Point\",\"coordinates\":[-73.94625107780892,40.70320874745355]},{\"x\":-73.9458549904679,\"y\":40.70298720677488,\"type\":\"Point\",\"coordinates\":[-73.9458549904679,40.70298720677488]},{\"x\":-73.94544988192177,\"y\":40.702760635974364,\"type\":\"Point\",\"coordinates\":[-73.94544988192177,40.702760635974364]},{\"x\":-73.94463910154856,\"y\":40.70231369467456,\"type\":\"Point\",\"coordinates\":[-73.94463910154856,40.70231369467456]},{\"x\":-73.94431460096804,\"y\":40.70213334535181,\"type\":\"Point\",\"coordinates\":[-73.94431460096804,40.70213334535181]},{\"x\":-73.94400504048726,\"y\":40.70196179219718,\"type\":\"Point\",\"coordinates\":[-73.94400504048726,40.70196179219718]},{\"x\":-73.9438247374114,\"y\":40.701862007878276,\"type\":\"Point\",\"coordinates\":[-73.9438247374114,40.701862007878276]},{\"x\":-73.94322686012315,\"y\":40.701520709145726,\"type\":\"Point\",\"coordinates\":[-73.94322686012315,40.701520709145726]},{\"x\":-73.94306406845838,\"y\":40.7014244350918,\"type\":\"Point\",\"coordinates\":[-73.94306406845838,40.7014244350918]},{\"x\":-73.94220058705264,\"y\":40.700890667467746,\"type\":\"Point\",\"coordinates\":[-73.94220058705264,40.700890667467746]},{\"x\":-73.94193078816193,\"y\":40.70072523469547,\"type\":\"Point\",\"coordinates\":[-73.94193078816193,40.70072523469547]}],\"coordinates\":[{\"type\":\"LineString\",\"coordinates\":[{\"x\":-73.94193078816193,\"y\":40.70072523469547,\"type\":\"Point\",\"coordinates\":[-73.94193078816193,40.70072523469547]},{\"x\":-73.9443878859649,\"y\":40.70042452378256,\"type\":\"Point\",\"coordinates\":[-73.9443878859649,40.70042452378256]},{\"x\":-73.94424286147482,\"y\":40.69969927964773,\"type\":\"Point\",\"coordinates\":[-73.94424286147482,40.69969927964773]},{\"x\":-73.94409591260093,\"y\":40.69897295461309,\"type\":\"Point\",\"coordinates\":[-73.94409591260093,40.69897295461309]},{\"x\":-73.94394947271304,\"y\":40.69822127983908,\"type\":\"Point\",\"coordinates\":[-73.94394947271304,40.69822127983908]},{\"x\":-73.94391750192877,\"y\":40.69805620211356,\"type\":\"Point\",\"coordinates\":[-73.94391750192877,40.69805620211356]},{\"x\":-73.94380383211836,\"y\":40.697469265449826,\"type\":\"Point\",\"coordinates\":[-73.94380383211836,40.697469265449826]},{\"x\":-73.94378455587042,\"y\":40.6973697290538,\"type\":\"Point\",\"coordinates\":[-73.94378455587042,40.6973697290538]},{\"x\":-73.94374306706803,\"y\":40.69715549995503,\"type\":\"Point\",\"coordinates\":[-73.94374306706803,40.69715549995503]},{\"x\":-73.9437245356891,\"y\":40.697059812179496,\"type\":\"Point\",\"coordinates\":[-73.9437245356891,40.697059812179496]},{\"x\":-73.94368427322361,\"y\":40.696851909818065,\"type\":\"Point\",\"coordinates\":[-73.94368427322361,40.696851909818065]},{\"x\":-73.9436842703752,\"y\":40.69685189440415,\"type\":\"Point\",\"coordinates\":[-73.9436842703752,40.69685189440415]},{\"x\":-73.94363806934868,\"y\":40.69661331854307,\"type\":\"Point\",\"coordinates\":[-73.94363806934868,40.69661331854307]},{\"x\":-73.94362121369004,\"y\":40.696526279661654,\"type\":\"Point\",\"coordinates\":[-73.94362121369004,40.696526279661654]},{\"x\":-73.9435563415296,\"y\":40.69619128295102,\"type\":\"Point\",\"coordinates\":[-73.9435563415296,40.69619128295102]},{\"x\":-73.94354024149403,\"y\":40.6961081421151,\"type\":\"Point\",\"coordinates\":[-73.94354024149403,40.6961081421151]},{\"x\":-73.94352527471477,\"y\":40.69603085523812,\"type\":\"Point\",\"coordinates\":[-73.94352527471477,40.69603085523812]},{\"x\":-73.94338802084431,\"y\":40.69528899051899,\"type\":\"Point\",\"coordinates\":[-73.94338802084431,40.69528899051899]},{\"x\":-73.943242490861,\"y\":40.694557485733355,\"type\":\"Point\",\"coordinates\":[-73.943242490861,40.694557485733355]},{\"x\":-73.94312826743185,\"y\":40.693967038330925,\"type\":\"Point\",\"coordinates\":[-73.94312826743185,40.693967038330925]},{\"x\":-73.94311427813774,\"y\":40.693894720557466,\"type\":\"Point\",\"coordinates\":[-73.94311427813774,40.693894720557466]},{\"x\":-73.94310040895432,\"y\":40.69382302905847,\"type\":\"Point\",\"coordinates\":[-73.94310040895432,40.69382302905847]},{\"x\":-73.94295136131598,\"y\":40.69309078423585,\"type\":\"Point\",\"coordinates\":[-73.94295136131598,40.69309078423585]},{\"x\":-73.94280765181726,\"y\":40.692357794128945,\"type\":\"Point\",\"coordinates\":[-73.94280765181726,40.692357794128945]},{\"x\":-73.94266181801652,\"y\":40.69162434435983,\"type\":\"Point\",\"coordinates\":[-73.94266181801652,40.69162434435983]},{\"x\":-73.94251587928605,\"y\":40.69089200097073,\"type\":\"Point\",\"coordinates\":[-73.94251587928605,40.69089200097073]},{\"x\":-73.94236932748694,\"y\":40.690159944665304,\"type\":\"Point\",\"coordinates\":[-73.94236932748694,40.690159944665304]},{\"x\":-73.94222203471806,\"y\":40.68942797886745,\"type\":\"Point\",\"coordinates\":[-73.94222203471806,40.68942797886745]},{\"x\":-73.94207684924385,\"y\":40.68869720298344,\"type\":\"Point\",\"coordinates\":[-73.94207684924385,40.68869720298344]},{\"x\":-73.9419324508184,\"y\":40.687962958755094,\"type\":\"Point\",\"coordinates\":[-73.9419324508184,40.687962958755094]},{\"x\":-73.94178527584324,\"y\":40.687228372121126,\"type\":\"Point\",\"coordinates\":[-73.94178527584324,40.687228372121126]},{\"x\":-73.94163933150469,\"y\":40.68649727009258,\"type\":\"Point\",\"coordinates\":[-73.94163933150469,40.68649727009258]},{\"x\":-73.94149491757346,\"y\":40.68576452882908,\"type\":\"Point\",\"coordinates\":[-73.94149491757346,40.68576452882908]},{\"x\":-73.94134827184915,\"y\":40.685031202512505,\"type\":\"Point\",\"coordinates\":[-73.94134827184915,40.685031202512505]},{\"x\":-73.94120399291621,\"y\":40.68429983923358,\"type\":\"Point\",\"coordinates\":[-73.94120399291621,40.68429983923358]},{\"x\":-73.94105783787931,\"y\":40.68356687284592,\"type\":\"Point\",\"coordinates\":[-73.94105783787931,40.68356687284592]},{\"x\":-73.9409133427312,\"y\":40.682833617234294,\"type\":\"Point\",\"coordinates\":[-73.9409133427312,40.682833617234294]},{\"x\":-73.94076893329961,\"y\":40.68210083903887,\"type\":\"Point\",\"coordinates\":[-73.94076893329961,40.68210083903887]},{\"x\":-73.94062005382186,\"y\":40.68137013010259,\"type\":\"Point\",\"coordinates\":[-73.94062005382186,40.68137013010259]},{\"x\":-73.94047635005941,\"y\":40.680635695422964,\"type\":\"Point\",\"coordinates\":[-73.94047635005941,40.680635695422964]},{\"x\":-73.94032793962053,\"y\":40.67988997506463,\"type\":\"Point\",\"coordinates\":[-73.94032793962053,40.67988997506463]},{\"x\":-73.94120864299748,\"y\":40.67993835375214,\"type\":\"Point\",\"coordinates\":[-73.94120864299748,40.67993835375214]},{\"x\":-73.94326176928655,\"y\":40.68005060712657,\"type\":\"Point\",\"coordinates\":[-73.94326176928655,40.68005060712657]},{\"x\":-73.94397347805013,\"y\":40.680088128426995,\"type\":\"Point\",\"coordinates\":[-73.94397347805013,40.680088128426995]},{\"x\":-73.94627470970092,\"y\":40.68021332692951,\"type\":\"Point\",\"coordinates\":[-73.94627470970092,40.68021332692951]},{\"x\":-73.94674915979888,\"y\":40.680239661363046,\"type\":\"Point\",\"coordinates\":[-73.94674915979888,40.680239661363046]},{\"x\":-73.9477302355664,\"y\":40.680291846282316,\"type\":\"Point\",\"coordinates\":[-73.9477302355664,40.680291846282316]},{\"x\":-73.9495568871113,\"y\":40.68039040292329,\"type\":\"Point\",\"coordinates\":[-73.9495568871113,40.68039040292329]},{\"x\":-73.95115828512961,\"y\":40.68047861480679,\"type\":\"Point\",\"coordinates\":[-73.95115828512961,40.68047861480679]},{\"x\":-73.95155682676496,\"y\":40.680498847575564,\"type\":\"Point\",\"coordinates\":[-73.95155682676496,40.680498847575564]},{\"x\":-73.95337017508861,\"y\":40.68064050844431,\"type\":\"Point\",\"coordinates\":[-73.95337017508861,40.68064050844431]},{\"x\":-73.95351616791015,\"y\":40.68138260047889,\"type\":\"Point\",\"coordinates\":[-73.95351616791015,40.68138260047889]},{\"x\":-73.95366256227194,\"y\":40.68211490361348,\"type\":\"Point\",\"coordinates\":[-73.95366256227194,40.68211490361348]},{\"x\":-73.95380893530668,\"y\":40.68284800827331,\"type\":\"Point\",\"coordinates\":[-73.95380893530668,40.68284800827331]},{\"x\":-73.95395453033524,\"y\":40.68358077882069,\"type\":\"Point\",\"coordinates\":[-73.95395453033524,40.68358077882069]},{\"x\":-73.95410042574005,\"y\":40.684313107633436,\"type\":\"Point\",\"coordinates\":[-73.95410042574005,40.684313107633436]},{\"x\":-73.95424647696164,\"y\":40.68504624826183,\"type\":\"Point\",\"coordinates\":[-73.95424647696164,40.68504624826183]},{\"x\":-73.95439296867414,\"y\":40.685779720013606,\"type\":\"Point\",\"coordinates\":[-73.95439296867414,40.685779720013606]},{\"x\":-73.95453798607406,\"y\":40.68651117540455,\"type\":\"Point\",\"coordinates\":[-73.95453798607406,40.68651117540455]},{\"x\":-73.95468418850508,\"y\":40.68724485443714,\"type\":\"Point\",\"coordinates\":[-73.95468418850508,40.68724485443714]},{\"x\":-73.95684165193596,\"y\":40.68699607883792,\"type\":\"Point\",\"coordinates\":[-73.95684165193596,40.68699607883792]},{\"x\":-73.95956770121337,\"y\":40.68668255592727,\"type\":\"Point\",\"coordinates\":[-73.95956770121337,40.68668255592727]},{\"x\":-73.95971374756459,\"y\":40.6874156340909,\"type\":\"Point\",\"coordinates\":[-73.95971374756459,40.6874156340909]},{\"x\":-73.95985939425704,\"y\":40.688147451217226,\"type\":\"Point\",\"coordinates\":[-73.95985939425704,40.688147451217226]},{\"x\":-73.96000519802635,\"y\":40.688881033718204,\"type\":\"Point\",\"coordinates\":[-73.96000519802635,40.688881033718204]},{\"x\":-73.96009714565346,\"y\":40.689345210097464,\"type\":\"Point\",\"coordinates\":[-73.96009714565346,40.689345210097464]},{\"x\":-73.96012172912181,\"y\":40.68946930706387,\"type\":\"Point\",\"coordinates\":[-73.96012172912181,40.68946930706387]},{\"x\":-73.96017256138677,\"y\":40.68972986156118,\"type\":\"Point\",\"coordinates\":[-73.96017256138677,40.68972986156118]},{\"x\":-73.96018691858275,\"y\":40.689803455988546,\"type\":\"Point\",\"coordinates\":[-73.96018691858275,40.689803455988546]},{\"x\":-73.96022304539724,\"y\":40.689988627383755,\"type\":\"Point\",\"coordinates\":[-73.96022304539724,40.689988627383755]},{\"x\":-73.96023740336433,\"y\":40.69006222280781,\"type\":\"Point\",\"coordinates\":[-73.96023740336433,40.69006222280781]},{\"x\":-73.96029281668112,\"y\":40.690346249915414,\"type\":\"Point\",\"coordinates\":[-73.96029281668112,40.690346249915414]},{\"x\":-73.96013760800457,\"y\":40.69036438035883,\"type\":\"Point\",\"coordinates\":[-73.96013760800457,40.69036438035883]},{\"x\":-73.96008336800442,\"y\":40.6903707157072,\"type\":\"Point\",\"coordinates\":[-73.96008336800442,40.6903707157072]},{\"x\":-73.95957591847137,\"y\":40.69042998753855,\"type\":\"Point\",\"coordinates\":[-73.95957591847137,40.69042998753855]},{\"x\":-73.95942791320554,\"y\":40.69044727471387,\"type\":\"Point\",\"coordinates\":[-73.95942791320554,40.69044727471387]},{\"x\":-73.95934862389824,\"y\":40.6904564609108,\"type\":\"Point\",\"coordinates\":[-73.95934862389824,40.6904564609108]},{\"x\":-73.95928133730644,\"y\":40.69046425696955,\"type\":\"Point\",\"coordinates\":[-73.95928133730644,40.69046425696955]},{\"x\":-73.95899330491858,\"y\":40.69049762936284,\"type\":\"Point\",\"coordinates\":[-73.95899330491858,40.69049762936284]},{\"x\":-73.95886713625437,\"y\":40.69051224801476,\"type\":\"Point\",\"coordinates\":[-73.95886713625437,40.69051224801476]},{\"x\":-73.95857844775936,\"y\":40.690545694857576,\"type\":\"Point\",\"coordinates\":[-73.95857844775936,40.690545694857576]},{\"x\":-73.9581804874994,\"y\":40.69059073040573,\"type\":\"Point\",\"coordinates\":[-73.9581804874994,40.69059073040573]},{\"x\":-73.95808563435828,\"y\":40.69060146372528,\"type\":\"Point\",\"coordinates\":[-73.95808563435828,40.69060146372528]},{\"x\":-73.95727249112613,\"y\":40.69069347835403,\"type\":\"Point\",\"coordinates\":[-73.95727249112613,40.69069347835403]},{\"x\":-73.95635602958276,\"y\":40.69079978191732,\"type\":\"Point\",\"coordinates\":[-73.95635602958276,40.69079978191732]},{\"x\":-73.95541057949602,\"y\":40.690908291885876,\"type\":\"Point\",\"coordinates\":[-73.95541057949602,40.690908291885876]},{\"x\":-73.95582662769675,\"y\":40.69299238288233,\"type\":\"Point\",\"coordinates\":[-73.95582662769675,40.69299238288233]},{\"x\":-73.95614239268207,\"y\":40.69457901857237,\"type\":\"Point\",\"coordinates\":[-73.95614239268207,40.69457901857237]},{\"x\":-73.9570870194244,\"y\":40.694470440162995,\"type\":\"Point\",\"coordinates\":[-73.9570870194244,40.694470440162995]},{\"x\":-73.95799732979468,\"y\":40.694365838684114,\"type\":\"Point\",\"coordinates\":[-73.95799732979468,40.694365838684114]},{\"x\":-73.95931047927598,\"y\":40.69421508783189,\"type\":\"Point\",\"coordinates\":[-73.95931047927598,40.69421508783189]},{\"x\":-73.96015854658333,\"y\":40.69411730915604,\"type\":\"Point\",\"coordinates\":[-73.96015854658333,40.69411730915604]},{\"x\":-73.96062056531659,\"y\":40.6963201401926,\"type\":\"Point\",\"coordinates\":[-73.96062056531659,40.6963201401926]},{\"x\":-73.96092543804184,\"y\":40.69773650701631,\"type\":\"Point\",\"coordinates\":[-73.96092543804184,40.69773650701631]},{\"x\":-73.96105100700007,\"y\":40.698326078819065,\"type\":\"Point\",\"coordinates\":[-73.96105100700007,40.698326078819065]},{\"x\":-73.96019688857467,\"y\":40.698462727438596,\"type\":\"Point\",\"coordinates\":[-73.96019688857467,40.698462727438596]},{\"x\":-73.95885874627406,\"y\":40.6986773264162,\"type\":\"Point\",\"coordinates\":[-73.95885874627406,40.6986773264162]},{\"x\":-73.95795938220984,\"y\":40.69882000321581,\"type\":\"Point\",\"coordinates\":[-73.95795938220984,40.69882000321581]},{\"x\":-73.95701993123406,\"y\":40.698973914349565,\"type\":\"Point\",\"coordinates\":[-73.95701993123406,40.698973914349565]},{\"x\":-73.957167301054,\"y\":40.69970786791901,\"type\":\"Point\",\"coordinates\":[-73.957167301054,40.69970786791901]},{\"x\":-73.95722517405626,\"y\":40.69999935002626,\"type\":\"Point\",\"coordinates\":[-73.95722517405626,40.69999935002626]},{\"x\":-73.95745736372834,\"y\":40.70082260318457,\"type\":\"Point\",\"coordinates\":[-73.95745736372834,40.70082260318457]},{\"x\":-73.95572361014881,\"y\":40.70194576955721,\"type\":\"Point\",\"coordinates\":[-73.95572361014881,40.70194576955721]},{\"x\":-73.9538119690652,\"y\":40.70318097979544,\"type\":\"Point\",\"coordinates\":[-73.9538119690652,40.70318097979544]},{\"x\":-73.95318085172319,\"y\":40.70261690547745,\"type\":\"Point\",\"coordinates\":[-73.95318085172319,40.70261690547745]},{\"x\":-73.95255052777945,\"y\":40.7020516665144,\"type\":\"Point\",\"coordinates\":[-73.95255052777945,40.7020516665144]},{\"x\":-73.951920189279,\"y\":40.70148754916077,\"type\":\"Point\",\"coordinates\":[-73.951920189279,40.70148754916077]},{\"x\":-73.95128819434734,\"y\":40.70092236548591,\"type\":\"Point\",\"coordinates\":[-73.95128819434734,40.70092236548591]},{\"x\":-73.95027424109588,\"y\":40.70157924195056,\"type\":\"Point\",\"coordinates\":[-73.95027424109588,40.70157924195056]},{\"x\":-73.9493787354337,\"y\":40.70215888982628,\"type\":\"Point\",\"coordinates\":[-73.9493787354337,40.70215888982628]},{\"x\":-73.94753858146478,\"y\":40.703350650664795,\"type\":\"Point\",\"coordinates\":[-73.94753858146478,40.703350650664795]},{\"x\":-73.94705205297524,\"y\":40.70366394934019,\"type\":\"Point\",\"coordinates\":[-73.94705205297524,40.70366394934019]},{\"x\":-73.94625107780892,\"y\":40.70320874745355,\"type\":\"Point\",\"coordinates\":[-73.94625107780892,40.70320874745355]},{\"x\":-73.9458549904679,\"y\":40.70298720677488,\"type\":\"Point\",\"coordinates\":[-73.9458549904679,40.70298720677488]},{\"x\":-73.94544988192177,\"y\":40.702760635974364,\"type\":\"Point\",\"coordinates\":[-73.94544988192177,40.702760635974364]},{\"x\":-73.94463910154856,\"y\":40.70231369467456,\"type\":\"Point\",\"coordinates\":[-73.94463910154856,40.70231369467456]},{\"x\":-73.94431460096804,\"y\":40.70213334535181,\"type\":\"Point\",\"coordinates\":[-73.94431460096804,40.70213334535181]},{\"x\":-73.94400504048726,\"y\":40.70196179219718,\"type\":\"Point\",\"coordinates\":[-73.94400504048726,40.70196179219718]},{\"x\":-73.9438247374114,\"y\":40.701862007878276,\"type\":\"Point\",\"coordinates\":[-73.9438247374114,40.701862007878276]},{\"x\":-73.94322686012315,\"y\":40.701520709145726,\"type\":\"Point\",\"coordinates\":[-73.94322686012315,40.701520709145726]},{\"x\":-73.94306406845838,\"y\":40.7014244350918,\"type\":\"Point\",\"coordinates\":[-73.94306406845838,40.7014244350918]},{\"x\":-73.94220058705264,\"y\":40.700890667467746,\"type\":\"Point\",\"coordinates\":[-73.94220058705264,40.700890667467746]},{\"x\":-73.94193078816193,\"y\":40.70072523469547,\"type\":\"Point\",\"coordinates\":[-73.94193078816193,40.70072523469547]}]}],\"type\":\"Polygon\"},\"name\":\"Bedford\"}\n"
| 0 | Kotlin | 0 | 1 | 7d2b5ed93dadaf35e477eaa83cffc58d90f93066 | 39,187 | restaurantsgeospatial | MIT License |
app/src/main/java/com/suqir/wasaischedule/ui/settings/TimeTableFragment.kt | suqir | 287,276,130 | true | {"Kotlin": 726821} | package com.suqir.wasaischedule.ui.settings
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.suqir.wasaischedule.R
import com.suqir.wasaischedule.ui.base_view.BaseFragment
import es.dmoral.toasty.Toasty
import splitties.snackbar.longSnack
class TimeTableFragment : BaseFragment() {
private val viewModel by activityViewModels<TimeSettingsViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val arguments = requireArguments()
viewModel.selectedId = arguments.getInt("selectedId")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.time_table_fragment, container, false)
val recyclerView = view.findViewById<RecyclerView>(R.id.rv_time_table)
initRecyclerView(recyclerView, view)
viewModel.getTimeTableList().observe(viewLifecycleOwner, Observer {
if (it == null) return@Observer
viewModel.timeTableList.clear()
viewModel.timeTableList.addAll(it)
recyclerView.adapter?.notifyDataSetChanged()
})
return view
}
private fun initRecyclerView(recyclerView: RecyclerView, fragmentView: View) {
val adapter = TimeTableAdapter(R.layout.item_time_table, viewModel.timeTableList, viewModel.selectedId)
recyclerView.adapter = adapter
adapter.addFooterView(initFooterView())
adapter.setOnItemClickListener { _, _, position ->
adapter.selectedId = viewModel.timeTableList[position].id
viewModel.selectedId = viewModel.timeTableList[position].id
adapter.notifyDataSetChanged()
}
adapter.addChildClickViewIds(R.id.ib_edit, R.id.ib_delete)
adapter.setOnItemChildClickListener { _, view, position ->
when (view.id) {
R.id.ib_edit -> {
viewModel.entryPosition = position
val bundle = Bundle()
bundle.putInt("position", position)
Navigation.findNavController(fragmentView).navigate(R.id.timeTableFragment_to_timeSettingsFragment, bundle)
}
R.id.ib_delete -> {
Toasty.info(requireActivity().applicationContext, "长按确认删除").show()
}
}
}
adapter.addChildLongClickViewIds(R.id.ib_delete)
adapter.setOnItemChildLongClickListener { _, view, position ->
when (view.id) {
R.id.ib_delete -> {
if (viewModel.timeTableList[position].id == viewModel.selectedId) {
view.longSnack("不能删除已选中的时间表")
} else {
launch {
try {
viewModel.deleteTimeTable(viewModel.timeTableList[position])
view.longSnack("删除成功")
} catch (e: Exception) {
view.longSnack("正在使用中的时间表无法删除")
}
}
}
return@setOnItemChildLongClickListener true
}
else -> {
true
}
}
}
recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity)
recyclerView.adapter = adapter
}
private fun initFooterView(): View {
val view = LayoutInflater.from(activity).inflate(R.layout.item_add_course_btn, null)
val tvBtn = view.findViewById<MaterialButton>(R.id.tv_add)
tvBtn.text = "新建时间表"
tvBtn.setOnClickListener {
val dialog = MaterialAlertDialogBuilder(requireContext())
.setTitle("时间表名字")
.setView(R.layout.dialog_edit_text)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.sure, null)
.create()
dialog.show()
val inputLayout = dialog.findViewById<TextInputLayout>(R.id.text_input_layout)
val editText = dialog.findViewById<TextInputEditText>(R.id.edit_text)
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val value = editText?.text
if (value.isNullOrBlank()) {
inputLayout?.error = "名称不能为空"
} else {
launch {
try {
viewModel.addNewTimeTable(editText.text.toString())
Toasty.success(requireActivity().applicationContext, "新建成功").show()
} catch (e: Exception) {
Toasty.error(requireActivity().applicationContext, "发生异常>_<${e.message}").show()
}
dialog.dismiss()
}
}
}
}
return view
}
}
| 0 | Kotlin | 0 | 0 | 533f1a36067dbb14dca8d694d4fa86cd021ac6ac | 5,635 | WaSaiSchedule | Apache License 2.0 |
src/main/kotlin/com/coxautodev/graphql/tools/SchemaParserBuilder.kt | jflorencio | 102,769,945 | true | {"Kotlin": 77982, "Groovy": 33746, "Java": 7896} | package com.coxautodev.graphql.tools
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
import com.google.common.collect.Maps
import graphql.parser.Parser
import graphql.schema.GraphQLScalarType
import org.antlr.v4.runtime.RecognitionException
import org.antlr.v4.runtime.misc.ParseCancellationException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionStage
import java.util.concurrent.Future
/**
* @author <NAME>
*/
class SchemaParserBuilder constructor(private val dictionary: SchemaParserDictionary = SchemaParserDictionary()) {
private val schemaString = StringBuilder()
private val resolvers = mutableListOf<GraphQLResolver<*>>()
private val scalars = mutableListOf<GraphQLScalarType>()
private var options = SchemaParserOptions.defaultOptions()
/**
* Add GraphQL schema files from the classpath.
*/
fun files(vararg files: String) = this.apply {
files.forEach { this.file(it) }
}
/**
* Add a GraphQL Schema file from the classpath.
*/
fun file(filename: String) = this.apply {
this.schemaString(java.io.BufferedReader(java.io.InputStreamReader(
object : Any() {}.javaClass.classLoader.getResourceAsStream(filename) ?: throw java.io.FileNotFoundException("classpath:$filename")
)).readText())
}
/**
* Add a GraphQL schema string directly.
*/
fun schemaString(string: String) = this.apply {
schemaString.append("\n").append(string)
}
/**
* Add GraphQLResolvers to the parser's dictionary.
*/
fun resolvers(vararg resolvers: GraphQLResolver<*>) = this.apply {
this.resolvers.addAll(resolvers)
}
/**
* Add GraphQLResolvers to the parser's dictionary.
*/
fun resolvers(resolvers: List<GraphQLResolver<*>>) = this.apply {
this.resolvers.addAll(resolvers)
}
/**
* Add scalars to the parser's dictionary.
*/
fun scalars(vararg scalars: GraphQLScalarType) = this.apply {
this.scalars.addAll(scalars)
}
/**
* Add arbitrary classes to the parser's dictionary, overriding the generated type name.
*/
fun dictionary(name: String, clazz: Class<*>) = this.apply {
this.dictionary.add(name, clazz)
}
/**
* Add arbitrary classes to the parser's dictionary, overriding the generated type name.
*/
fun dictionary(dictionary: Map<String, Class<*>>) = this.apply {
this.dictionary.add(dictionary)
}
/**
* Add arbitrary classes to the parser's dictionary.
*/
fun dictionary(clazz: Class<*>) = this.apply {
this.dictionary.add(clazz)
}
/**
* Add arbitrary classes to the parser's dictionary.
*/
fun dictionary(vararg dictionary: Class<*>) = this.apply {
this.dictionary.add(*dictionary)
}
/**
* Add arbitrary classes to the parser's dictionary.
*/
fun dictionary(dictionary: List<Class<*>>) = this.apply {
this.dictionary.add(dictionary)
}
fun options(options: SchemaParserOptions) = this.apply {
this.options = options
}
/**
* Build the parser with the supplied schema and dictionary.
*/
fun build(): SchemaParser {
val document = try {
Parser().parseDocument(this.schemaString.toString())
} catch (pce: ParseCancellationException) {
val cause = pce.cause
if(cause != null && cause is RecognitionException) {
throw InvalidSchemaError(pce, cause)
} else {
throw pce
}
}
val definitions = document.definitions
val customScalars = scalars.associateBy { it.name }
return SchemaClassScanner(dictionary.getDictionary(), definitions, resolvers, customScalars, options).scanForClasses()
}
}
class InvalidSchemaError(pce: ParseCancellationException, val recognitionException: RecognitionException): RuntimeException(pce) {
override val message: String?
get() = "Invalid schema provided (${recognitionException.javaClass.name}) at: ${recognitionException.offendingToken}"
}
class SchemaParserDictionary {
private val dictionary: BiMap<String, Class<*>> = HashBiMap.create()
fun getDictionary(): BiMap<String, Class<*>> = Maps.unmodifiableBiMap(dictionary)
/**
* Add arbitrary classes to the parser's dictionary, overriding the generated type name.
*/
fun add(name: String, clazz: Class<*>) = this.apply {
this.dictionary.put(name, clazz)
}
/**
* Add arbitrary classes to the parser's dictionary, overriding the generated type name.
*/
fun add(dictionary: Map<String, Class<*>>) = this.apply {
this.dictionary.putAll(dictionary)
}
/**
* Add arbitrary classes to the parser's dictionary.
*/
fun add(clazz: Class<*>) = this.apply {
this.add(clazz.simpleName, clazz)
}
/**
* Add arbitrary classes to the parser's dictionary.
*/
fun add(vararg dictionary: Class<*>) = this.apply {
dictionary.forEach { this.add(it) }
}
/**
* Add arbitrary classes to the parser's dictionary.
*/
fun add(dictionary: List<Class<*>>) = this.apply {
dictionary.forEach { this.add(it) }
}
}
data class SchemaParserOptions internal constructor(val genericWrappers: List<GenericWrapper>, val allowUnimplementedResolvers: Boolean, val objectMapperConfigurer: ObjectMapperConfigurer) {
companion object {
@JvmStatic fun newOptions() = Builder()
@JvmStatic fun defaultOptions() = Builder().build()
}
class Builder {
private val genericWrappers: MutableList<GenericWrapper> = mutableListOf()
private var useDefaultGenericWrappers = true
private var allowUnimplementedResolvers = false
private var objectMapperConfigurer: ObjectMapperConfigurer = ObjectMapperConfigurer { _, _ -> }
fun genericWrappers(genericWrappers: List<GenericWrapper>) = this.apply {
this.genericWrappers.addAll(genericWrappers)
}
fun genericWrappers(vararg genericWrappers: GenericWrapper) = this.apply {
this.genericWrappers.addAll(genericWrappers)
}
fun useDefaultGenericWrappers(useDefaultGenericWrappers: Boolean) = this.apply {
this.useDefaultGenericWrappers = useDefaultGenericWrappers
}
fun allowUnimplementedResolvers(allowUnimplementedResolvers: Boolean) = this.apply {
this.allowUnimplementedResolvers = allowUnimplementedResolvers
}
fun objectMapperConfigurer(objectMapperConfigurer: ObjectMapperConfigurer) = this.apply {
this.objectMapperConfigurer = objectMapperConfigurer
}
fun objectMapperConfigurer(objectMapperConfigurer: (ObjectMapper, ObjectMapperConfigurerContext) -> Unit) = this.apply {
this.objectMapperConfigurer(ObjectMapperConfigurer(objectMapperConfigurer))
}
fun build(): SchemaParserOptions {
val wrappers = if(useDefaultGenericWrappers) {
genericWrappers + listOf(
GenericWrapper(Future::class.java, 0),
GenericWrapper(CompletableFuture::class.java, 0),
GenericWrapper(CompletionStage::class.java, 0)
)
} else {
genericWrappers
}
return SchemaParserOptions(wrappers, allowUnimplementedResolvers, objectMapperConfigurer)
}
}
data class GenericWrapper(val type: Class<*>, val index: Int)
}
| 0 | Kotlin | 1 | 0 | 14101cbc3f6f67088736422fe95871ff7b2c6fdb | 7,713 | graphql-java-tools | MIT License |
mesh-exam/library/mesh/src/main/java/io/flaterlab/meshexam/librariy/mesh/client/ClientAdvertisingMeshManager.kt | chorobaev | 434,863,301 | false | {"Kotlin": 467494, "Java": 1951} | package io.flaterlab.meshexam.librariy.mesh.client
import android.content.Context
import com.google.android.gms.nearby.Nearby
import com.google.android.gms.nearby.connection.AdvertisingOptions
import com.google.android.gms.nearby.connection.ConnectionsClient
import com.google.android.gms.nearby.connection.Payload
import com.google.android.gms.nearby.connection.Strategy
import com.google.gson.GsonBuilder
import io.flaterlab.meshexam.librariy.mesh.common.ConnectionsLifecycleAdapterCallback2
import io.flaterlab.meshexam.librariy.mesh.common.LOW_ENERGY
import io.flaterlab.meshexam.librariy.mesh.common.dto.AdvertiserInfo
import io.flaterlab.meshexam.librariy.mesh.common.dto.ChildInfo
import io.flaterlab.meshexam.librariy.mesh.common.dto.ClientInfo
import io.flaterlab.meshexam.librariy.mesh.common.parser.AdvertiserInfoJsonParser
import io.flaterlab.meshexam.librariy.mesh.common.parser.ClientInfoJsonParser
import io.flaterlab.meshexam.librariy.mesh.common.parser.JsonParser
import kotlinx.coroutines.tasks.await
import timber.log.Timber
internal class ClientAdvertisingMeshManager(
private val serviceId: String,
private val nearby: ConnectionsClient,
private val connectionsCallback: ConnectionsLifecycleAdapterCallback2<ClientInfo>,
private val payloadCallback: BytesForwardingPayloadAdapter,
private val advertiserInfoJsonParser: JsonParser<AdvertiserInfo>,
) : ConnectionsLifecycleAdapterCallback2.AdapterCallback<ClientInfo> {
var onClientConnectedListener: (ClientInfo) -> Unit = {}
var onClientDisconnectedListener: (ClientInfo) -> Unit = {}
var onErrorListener: (Exception) -> Unit = {}
private var advertiserInfo: AdvertiserInfo? = null
private var child: ChildInfo? = null
init {
connectionsCallback.adapterCallback = this
}
fun advertise(info: AdvertiserInfo) {
advertiserInfo = info
startAdvertising()
}
private fun startAdvertising() {
val infoJson = advertiserInfoJsonParser
.toJson(advertiserInfo!!)
.toByteArray()
val options = AdvertisingOptions.Builder()
.setDisruptiveUpgrade(false)
.setStrategy(Strategy.P2P_CLUSTER)
.setLowPower(LOW_ENERGY)
.build()
nearby.startAdvertising(infoJson, serviceId, connectionsCallback, options)
.addOnFailureListener(::onError)
}
fun close() {
nearby.stopAdvertising()
child?.first?.let(nearby::disconnectFromEndpoint)
advertiserInfo = null
child = null
}
fun setOnBytesReceivedListener(listener: ((ByteArray) -> Unit)?) {
payloadCallback.onBytesReceivedListener = listener ?: {}
}
override fun onRequested(endpointId: String, info: ClientInfo) {
nearby.acceptConnection(endpointId, payloadCallback)
.addOnFailureListener(::onError)
}
override fun onConnected(endpointId: String, info: ClientInfo) {
if (child == null) {
child = endpointId to info
onClientConnectedListener(info)
nearby.stopAdvertising()
} else {
nearby.disconnectFromEndpoint(endpointId)
}
}
override fun onRejected(endpointId: String, info: ClientInfo) = Unit
override fun onError(endpointId: String, info: ClientInfo) = Unit
override fun onDisconnected(endpointId: String, info: ClientInfo) {
if (child?.first == endpointId) {
child = null
onClientDisconnectedListener(info)
startAdvertising()
}
}
override fun rejectConnection(endpointId: String) {
nearby.rejectConnection(endpointId)
}
private fun onError(e: Exception) {
close()
onErrorListener(e)
Timber.e(e)
}
suspend fun forwardPayload(payload: Payload) {
nearby.sendPayload(
child?.first ?: throw IllegalStateException("Has not child"),
payload
).await()
}
companion object {
fun getInstance(context: Context): ClientAdvertisingMeshManager =
GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create()
.let { gson ->
ClientAdvertisingMeshManager(
serviceId = context.packageName,
nearby = Nearby.getConnectionsClient(context),
connectionsCallback = ConnectionsLifecycleAdapterCallback2(
ClientInfoJsonParser(gson)
),
payloadCallback = BytesForwardingPayloadAdapter(),
advertiserInfoJsonParser = AdvertiserInfoJsonParser(gson)
)
}
}
} | 0 | Kotlin | 0 | 2 | 364c4fcb70a461fc02d2a5ef2590ad5f8975aab5 | 4,768 | mesh-exam | MIT License |
java/io/jackbradshaw/otter/engine/core/EngineCoreImpl.kt | jack-bradshaw | 468,854,318 | false | {"Kotlin": 139153, "Starlark": 60977, "Shell": 2958, "Java": 444} | package io.jackbradshaw.otter.engine.core
import com.jme3.app.LostFocusBehavior
import com.jme3.app.SimpleApplication
import com.jme3.app.VRAppState
import com.jme3.app.VRConstants
import com.jme3.app.VREnvironment
import com.jme3.bullet.BulletAppState
import com.jme3.system.AppSettings
import com.jme3.system.JmeContext
import io.jackbradshaw.otter.OtterScope
import io.jackbradshaw.otter.config.Config
import io.jackbradshaw.otter.openxr.manifest.installer.ManifestInstaller
import javax.inject.Inject
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
@OtterScope
class EngineCoreImpl
@Inject
internal constructor(private val config: Config, private val manifestInstaller: ManifestInstaller) :
EngineCore, SimpleApplication() {
private val started = MutableStateFlow(false)
private var totalRuntimeSec = 0.0
private val settings =
AppSettings(/* loadDefaults= */ true).apply {
if (config.engineConfig.xrEnabled) {
put(VRConstants.SETTING_VRAPI, VRConstants.SETTING_VRAPI_OPENVR_LWJGL_VALUE)
put(VRConstants.SETTING_ENABLE_MIRROR_WINDOW, true)
}
}
private val xr = if (config.engineConfig.xrEnabled) createVrAppState() else null
private val physics = BulletAppState()
private val coroutineScopeJob = Job()
private val coroutineScope = CoroutineScope(coroutineScopeJob)
private fun createVrAppState(): VRAppState {
val environment =
VREnvironment(settings).apply {
initialize()
if (!isInitialized())
throw IllegalStateException("VR environment did not successfully initialize")
}
return VRAppState(settings, environment).apply {
setMirrorWindowSize(DEFAULT_VR_MIRROR_WINDOW_WIDTH_PX, DEFAULT_VR_MIRROR_WINDOW_HEIGHT_PX)
}
}
init {
runBlocking {
setSettings(settings)
setShowSettings(false)
setLostFocusBehavior(LostFocusBehavior.Disabled)
setDisplayFps(config.engineConfig.debugEnabled)
if (config.engineConfig.headlessEnabled) start(JmeContext.Type.Headless) else start()
blockUntilStarted()
if (xr != null) {
stateManager.attach(xr)
manifestInstaller.deployActionManifestFiles()
}
stateManager.attach(physics)
cam.frustumFar = Float.MAX_VALUE
}
}
private suspend fun blockUntilStarted() = started.filter { it == true }.first()
override fun simpleInitApp() {
started.value = true
}
override fun simpleUpdate(tpf: Float) = runBlocking { totalRuntimeSec = totalRuntimeSec + tpf }
override fun destroy() {
coroutineScopeJob.cancel()
super.destroy()
}
override fun extractApplication() = this
override fun extractContext() = context
override fun extractAssetManager() = assetManager
override fun extractStateManager() = stateManager
override fun extractInputManager() = inputManager
override fun extractRenderManager() = renderManager
override fun extractVideoRenderer() = renderer
override fun extractAudioRenderer() = audioRenderer
override fun extractDefaultInGameCamera() = cam
override fun extractDefaultInGameMicrophone() = listener
override fun extractDefaultViewPort() = viewPort
override fun extractXr() = xr
override fun extractPhysics() = physics
override fun extractRootNode() = rootNode
override fun extractCoroutineScope() = coroutineScope
override fun extractTimer() = timer
override fun extractTotalEngineRuntime() = totalRuntimeSec
companion object {
private const val DEFAULT_VR_MIRROR_WINDOW_WIDTH_PX = 1024
private const val DEFAULT_VR_MIRROR_WINDOW_HEIGHT_PX = 800
}
}
| 4 | Kotlin | 0 | 7 | d51e20a4564504af6a0e95c294c3d9a4e3256232 | 3,698 | monorepo | MIT License |
src/main/kotlin/net/ndrei/bcoreprocessing/integrations/jei/OreProcessorCategory.kt | MinecraftModDevelopmentMods | 100,987,449 | false | null | package net.ndrei.bcoreprocessing.integrations.jei
import mezz.jei.api.IModRegistry
import mezz.jei.api.gui.IDrawable
import mezz.jei.api.gui.IRecipeLayout
import mezz.jei.api.ingredients.IIngredients
import mezz.jei.api.recipe.IRecipeCategoryRegistration
import mezz.jei.api.recipe.IRecipeWrapper
import net.minecraft.client.Minecraft
import net.minecraft.item.ItemStack
import net.minecraftforge.fluids.FluidStack
import net.ndrei.bcoreprocessing.api.recipes.IOreProcessorRecipe
import net.ndrei.bcoreprocessing.lib.gui.GuiTextures
import net.ndrei.bcoreprocessing.lib.recipes.OreProcessorRecipeManager
import net.ndrei.bcoreprocessing.machines.oreprocessor.OreProcessorBlock
object OreProcessorCategory
: BaseCategory<OreProcessorCategory.RecipeWrapper>(OreProcessorBlock) {
override fun drawExtras(minecraft: Minecraft?) { }
override fun getTooltipStrings(mouseX: Int, mouseY: Int) = mutableListOf<String>()
override fun getIcon() = null
private lateinit var fluidOverlay: IDrawable
override fun setRecipe(recipeLayout: IRecipeLayout, recipeWrapper: RecipeWrapper, ingredients: IIngredients) {
val stacks = recipeLayout.itemStacks
stacks.init(0, true, 6, 9)
stacks.set(0, ingredients.getInputs(ItemStack::class.java)[0])
val fluids = recipeLayout.fluidStacks
val outputs = recipeWrapper.recipe.getTotalOutput()
val capacity = arrayOf(outputs.first, outputs.second).filterNotNull().map { it.amount }.max()
if (outputs.first != null) {
fluids.init(0, true, 45, 5, 8, 27, capacity ?: outputs.first!!.amount, capacity != null, this.fluidOverlay)
fluids.set(0, outputs.first)
}
if (outputs.second != null) {
fluids.init(1, true, 57, 5, 8, 27, capacity ?: outputs.second!!.amount, capacity != null, this.fluidOverlay)
fluids.set(1, outputs.second)
}
}
class RecipeWrapper(val recipe: IOreProcessorRecipe)
: IRecipeWrapper {
override fun drawInfo(minecraft: Minecraft?, recipeWidth: Int, recipeHeight: Int, mouseX: Int, mouseY: Int) { }
override fun getTooltipStrings(mouseX: Int, mouseY: Int) = mutableListOf<String>()
override fun handleClick(minecraft: Minecraft?, mouseX: Int, mouseY: Int, mouseButton: Int) = false
override fun getIngredients(ingredients: IIngredients) {
ingredients.setInput(ItemStack::class.java, this.recipe.getPossibleInputs().first())
val pair = this.recipe.getTotalOutput()
ingredients.setOutputs(FluidStack::class.java, arrayOf(pair.first, pair.second).filterNotNull())
}
}
override fun register(registry: IRecipeCategoryRegistration) {
super.register(registry)
this.recipeBackground = this.guiHelper.createDrawable(GuiTextures.GUI_JEI.resourceLocation, 0, 0, 124, 37)
this.fluidOverlay = this.guiHelper.createDrawable(GuiTextures.GUI_JEI.resourceLocation, 45, 5, 8, 27)
}
override fun register(registry: IModRegistry) {
super.register(registry)
registry.handleRecipes(IOreProcessorRecipe::class.java, { RecipeWrapper(it) }, this.uid)
registry.addRecipes(OreProcessorRecipeManager.allRecipes, this.uid)
}
}
| 2 | Kotlin | 2 | 4 | 4bb1a16771f9643bf56c1242fb91cc83c2f7769e | 3,257 | BC-Ore-Processing | MIT License |
bbfgradle/tmp/results/BACKUP_JVM-Xuse-ir/BACKEND_wcafasm_FILE.kt | DaniilStepanov | 346,008,310 | false | null | // Bug happens on JVM -Xuse-ir
//File: tmp/tmp0.kt
fun box()
{
if (true) ({{}!!}) else 1
}
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 94 | kotlinWithFuzzer | Apache License 2.0 |
app/src/main/java/com/nkuppan/giphybrowser/presentation/searchlist/StickersSearchViewModel.kt | nkuppan | 419,636,097 | false | {"Kotlin": 100536} | package com.nkuppan.giphybrowser.presentation.searchlist
import androidx.paging.PagingSource
import com.nkuppan.giphybrowser.domain.model.GiphyImage
import com.nkuppan.giphybrowser.domain.usecase.StickerSearchUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class StickersSearchViewModel @Inject constructor(
private val stickerSearchUseCase: StickerSearchUseCase
) : GiphySearchViewModel<GiphyImage>() {
override fun getPagingSource(): PagingSource<Int, GiphyImage> {
return GiphyStickersPagingSource(
queryString,
stickerSearchUseCase
)
}
}
| 0 | Kotlin | 0 | 1 | e0e1eed4017eaae8c61685125a4f4b0b02146d3a | 650 | giphy-browser | Apache License 2.0 |
misc/ktx/src/main/kotlin/fan/akua/misc/ktx/AlertDialogExtensions.kt | AquaApps | 763,100,710 | false | {"Kotlin": 50201, "Java": 39623} | package fan.akua.misc.ktx
import android.annotation.TargetApi
import android.app.Dialog
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.content.DialogInterface
import android.widget.AdapterView
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
/**
* Build AlertDialog in Activity
*
* @param process The process of building AlertDialog
* @see android.app.AlertDialog
*/
fun AppCompatActivity.buildAlertDialog(process: MaterialAlertDialogBuilder.() -> Unit): AlertDialog {
val builder = MaterialAlertDialogBuilder(this)
builder.process()
return builder.create()
}
/**
* Build AlertDialog in Fragment
*
* @param process The process of building AlertDialog
* @see android.app.AlertDialog
*/
fun Fragment.buildAlertDialog(process: MaterialAlertDialogBuilder.() -> Unit) {
val appCompatActivity = requireActivity() as AppCompatActivity
appCompatActivity.buildAlertDialog(process)
}
var MaterialAlertDialogBuilder.title: String
get() {
throw NoSuchMethodException("Title getter is not supported")
}
set(value) {
this.setTitle(value)
}
var MaterialAlertDialogBuilder.titleRes: Int
get() {
throw NoSuchMethodException("Title res id getter is not supported")
}
set(value) {
this.setTitle(value)
}
var MaterialAlertDialogBuilder.message: String
get() {
throw NoSuchMethodException("Message getter is not supported")
}
set(value) {
this.setMessage(value)
}
var MaterialAlertDialogBuilder.messageRes: Int
get() {
throw NoSuchMethodException("Message res id getter is not supported")
}
set(value) {
this.setMessage(value)
}
var MaterialAlertDialogBuilder.isCancelable: Boolean
get() {
throw NoSuchMethodException("isCancelable getter is not supported")
}
set(value) {
this.setCancelable(value)
}
var MaterialAlertDialogBuilder.customTitle: View
get() {
throw NoSuchMethodException("Custom title getter is not supported")
}
set(value) {
this.setCustomTitle(value)
}
var MaterialAlertDialogBuilder.icon: Drawable
get() {
throw NoSuchMethodException("Icon getter is not supported")
}
set(value) {
this.setIcon(value)
}
var MaterialAlertDialogBuilder.iconRes: Int
get() {
throw NoSuchMethodException("Icon res id getter is not supported")
}
set(value) {
this.setIcon(value)
}
var MaterialAlertDialogBuilder.iconAttribute: Int
get() {
throw NoSuchMethodException("Icon attribute getter is not supported")
}
set(value) {
this.setIconAttribute(value)
}
var MaterialAlertDialogBuilder.onCancel: (DialogInterface) -> Unit
get() {
throw NoSuchMethodException("OnCancelListener getter is not supported")
}
set(value) {
this.setOnCancelListener(value)
}
var MaterialAlertDialogBuilder.onDismiss: (DialogInterface) -> Unit
get() {
throw NoSuchMethodException("OnDismissListener getter is not supported")
}
set(value) {
this.setOnDismissListener(value)
}
var MaterialAlertDialogBuilder.onKey: DialogInterface.OnKeyListener
get() {
throw NoSuchMethodException("OnKeyListener getter is not supported")
}
set(value) {
this.setOnKeyListener(value)
}
var MaterialAlertDialogBuilder.onItemSelected: AdapterView.OnItemSelectedListener
get() {
throw NoSuchMethodException("OnItemSelectedListener getter is not supported")
}
set(value) {
this.setOnItemSelectedListener(value)
}
var MaterialAlertDialogBuilder.view: View
get() {
throw NoSuchMethodException("View getter is not supported")
}
set(value) {
this.setView(value)
}
var MaterialAlertDialogBuilder.viewRes: Int
get() {
throw NoSuchMethodException("View res id getter is not supported")
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
set(value) {
this.setView(value)
}
/**
* Set ok button for AlertDialog
*
* @param onClick onClick callback
*/
fun MaterialAlertDialogBuilder.okButton(onClick: (DialogInterface, Int) -> Unit = { _, _ -> }) {
setPositiveButton(android.R.string.ok, onClick)
}
/**
* Set cancel button for AlertDialog
*
* @param onClick onClick callback
*/
fun MaterialAlertDialogBuilder.cancelButton(onClick: (DialogInterface, Int) -> Unit = { _, _ -> }) {
setNegativeButton(android.R.string.cancel, onClick)
}
/**
* Set positive button for AlertDialog
*
* @param textId Text resource id
* @param onClick onClick callback
*/
fun MaterialAlertDialogBuilder.positiveButton(textId: Int, onClick: (DialogInterface, Int) -> Unit) {
setPositiveButton(textId, onClick)
}
/**
* Set positive button for AlertDialog
*
* @param text Text string
* @param onClick onClick callback
*/
fun MaterialAlertDialogBuilder.positiveButton(text: String, onClick: (DialogInterface, Int) -> Unit) {
setPositiveButton(text, onClick)
}
/**
* Set negative button for AlertDialog
*
* @param textId Text resource id
* @param onClick onClick callback
*/
fun MaterialAlertDialogBuilder.negativeButton(textId: Int, onClick: (DialogInterface, Int) -> Unit) {
setNegativeButton(textId, onClick)
}
/**
* Set negative button for AlertDialog
*
* @param text Text string
* @param onClick onClick callback
*/
fun MaterialAlertDialogBuilder.negativeButton(text: String, onClick: (DialogInterface, Int) -> Unit) {
setNegativeButton(text, onClick)
}
/**
* Set neutral button for AlertDialog
*
* @param textId Text resource id
* @param onClick onClick callback
*/
fun MaterialAlertDialogBuilder.neutralButton(textId: Int, onClick: (DialogInterface, Int) -> Unit) {
setNeutralButton(textId, onClick)
}
/**
* Set neutral button for AlertDialog
*
* @param text Text string
* @param onClick onClick callback
*/
fun MaterialAlertDialogBuilder.neutralButton(text: String, onClick: (DialogInterface, Int) -> Unit) {
setNeutralButton(text, onClick)
}
fun <T : Dialog> T.afterViewCreated(block: (T) -> Unit): T {
this.setOnShowListener { block(this) }
return this
}
val AlertDialog.positiveButton: Button
get() = this.getButton(DialogInterface.BUTTON_POSITIVE)
val AlertDialog.negativeButton: Button
get() = this.getButton(DialogInterface.BUTTON_NEGATIVE)
val AlertDialog.neutralButton: Button
get() = this.getButton(DialogInterface.BUTTON_NEUTRAL) | 0 | Kotlin | 0 | 0 | ee185df61eae49c7d840b7f4933fb2b8b67c6d5b | 6,694 | AkuaX | MIT License |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/contactdiary/ui/edit/ContactDiaryEditLocationsFragment.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.contactdiary.ui.edit
import android.os.Bundle
import android.view.View
import android.view.accessibility.AccessibilityEvent
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import de.rki.coronawarnapp.R
import de.rki.coronawarnapp.contactdiary.ui.edit.ContactDiaryEditLocationsViewModel.NavigationEvent.ShowDeletionConfirmationDialog
import de.rki.coronawarnapp.contactdiary.ui.edit.ContactDiaryEditLocationsViewModel.NavigationEvent.ShowLocationDetailFragment
import de.rki.coronawarnapp.contactdiary.ui.edit.adapter.LocationEditAdapter
import de.rki.coronawarnapp.databinding.ContactDiaryEditLocationsFragmentBinding
import de.rki.coronawarnapp.util.DialogHelper
import de.rki.coronawarnapp.util.di.AutoInject
import de.rki.coronawarnapp.util.lists.diffutil.update
import de.rki.coronawarnapp.util.ui.doNavigate
import de.rki.coronawarnapp.util.ui.observe2
import de.rki.coronawarnapp.util.ui.popBackStack
import de.rki.coronawarnapp.util.ui.viewBindingLazy
import de.rki.coronawarnapp.util.viewmodel.CWAViewModelFactoryProvider
import de.rki.coronawarnapp.util.viewmodel.cwaViewModels
import javax.inject.Inject
class ContactDiaryEditLocationsFragment : Fragment(R.layout.contact_diary_edit_locations_fragment), AutoInject {
@Inject lateinit var viewModelFactory: CWAViewModelFactoryProvider.Factory
private val viewModel: ContactDiaryEditLocationsViewModel by cwaViewModels { viewModelFactory }
private val binding: ContactDiaryEditLocationsFragmentBinding by viewBindingLazy()
private lateinit var listAdapter: LocationEditAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
binding.toolbar.setNavigationOnClickListener {
popBackStack()
}
binding.deleteButton.setOnClickListener { viewModel.onDeleteAllLocationsClick() }
viewModel.isListVisible.observe2(this) {
binding.contactDiaryLocationListNoItemsGroup.isGone = it
}
viewModel.isButtonEnabled.observe2(this) {
binding.deleteButton.isEnabled = it
}
viewModel.locationsLiveData.observe2(this) {
listAdapter.update(it, true)
}
viewModel.navigationEvent.observe2(this) {
when (it) {
ShowDeletionConfirmationDialog -> DialogHelper.showDialog(deleteAllLocationsConfirmationDialog)
is ShowLocationDetailFragment -> {
doNavigate(
ContactDiaryEditLocationsFragmentDirections
.actionContactDiaryEditLocationsFragmentToContactDiaryAddLocationFragment(
it.location
)
)
}
}
}
}
override fun onResume() {
super.onResume()
binding.contentContainer.sendAccessibilityEvent(AccessibilityEvent.TYPE_ANNOUNCEMENT)
}
private fun setupRecyclerView() {
listAdapter = LocationEditAdapter(
clickLabelString = getString(R.string.accessibility_edit),
getContentDescriptionString = { getString(R.string.accessibility_location, it.locationName) },
onItemClicked = { viewModel.onEditLocationClick(it) }
)
binding.locationsRecyclerView.adapter = listAdapter
}
private val deleteAllLocationsConfirmationDialog by lazy {
DialogHelper.DialogInstance(
requireActivity(),
R.string.contact_diary_delete_locations_title,
R.string.contact_diary_delete_locations_message,
R.string.contact_diary_delete_button_positive,
R.string.contact_diary_delete_button_negative,
positiveButtonFunction = {
viewModel.onDeleteAllConfirmedClick()
}
)
}
}
| 6 | null | 8 | 2,495 | d3833a212bd4c84e38a1fad23b282836d70ab8d5 | 3,933 | cwa-app-android | Apache License 2.0 |
samples/showcase/src/main/java/com/facebook/fresco/samples/showcase/common/DimensionUtils.kt | element-hq | 429,050,697 | false | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.samples.showcase.common
import android.content.Context
import android.util.TypedValue
fun Float.dpToPx(context: Context): Float =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, context.resources.displayMetrics)
fun Int.dpToPx(context: Context): Int = toFloat().dpToPx(context).toInt()
| 171 | null | 4 | 4 | 509593ac7aeed5fd7a354eec1d4703e6d798ea32 | 523 | fresco | MIT License |
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/impl/email/incontext/EmailProtectionInContextSignupActivity.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.autofill.impl.email.incontext
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.webkit.WebSettings
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.duckduckgo.anvil.annotations.ContributeToActivityStarter
import com.duckduckgo.anvil.annotations.InjectWith
import com.duckduckgo.app.global.DispatcherProvider
import com.duckduckgo.app.global.DuckDuckGoActivity
import com.duckduckgo.app.statistics.pixels.Pixel
import com.duckduckgo.autofill.api.BrowserAutofill
import com.duckduckgo.autofill.api.EmailProtectionInContextSignUpHandleVerificationLink
import com.duckduckgo.autofill.api.EmailProtectionInContextSignUpScreenNoParams
import com.duckduckgo.autofill.api.EmailProtectionInContextSignUpScreenResult
import com.duckduckgo.autofill.api.EmailProtectionInContextSignupFlowListener
import com.duckduckgo.autofill.api.email.EmailManager
import com.duckduckgo.autofill.api.emailprotection.EmailInjector
import com.duckduckgo.autofill.impl.AutofillJavascriptInterface
import com.duckduckgo.autofill.impl.R
import com.duckduckgo.autofill.impl.databinding.ActivityEmailProtectionInContextSignupBinding
import com.duckduckgo.autofill.impl.email.incontext.EmailProtectionInContextSignupViewModel.ExitButtonAction
import com.duckduckgo.autofill.impl.email.incontext.EmailProtectionInContextSignupViewModel.ViewState
import com.duckduckgo.di.scopes.ActivityScope
import com.duckduckgo.mobile.android.ui.view.dialog.TextAlertDialogBuilder
import com.duckduckgo.mobile.android.ui.viewbinding.viewBinding
import com.duckduckgo.navigation.api.getActivityParams
import com.duckduckgo.user.agent.api.UserAgentProvider
import javax.inject.Inject
import kotlinx.coroutines.launch
@InjectWith(ActivityScope::class)
@ContributeToActivityStarter(EmailProtectionInContextSignUpScreenNoParams::class)
@ContributeToActivityStarter(EmailProtectionInContextSignUpHandleVerificationLink::class)
class EmailProtectionInContextSignupActivity :
DuckDuckGoActivity(),
EmailProtectionInContextSignUpWebChromeClient.ProgressListener,
EmailProtectionInContextSignUpWebViewClient.NewPageCallback {
val binding: ActivityEmailProtectionInContextSignupBinding by viewBinding()
private val viewModel: EmailProtectionInContextSignupViewModel by bindViewModel()
@Inject
lateinit var userAgentProvider: UserAgentProvider
@Inject
lateinit var dispatchers: DispatcherProvider
@Inject
lateinit var emailInjector: EmailInjector
@Inject
lateinit var configurator: BrowserAutofill.Configurator
@Inject
lateinit var autofillInterface: AutofillJavascriptInterface
@Inject
lateinit var emailManager: EmailManager
@Inject
lateinit var pixel: Pixel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
initialiseToolbar()
setTitle(R.string.autofillEmailProtectionInContextSignUpDialogFeatureName)
configureWebView()
configureBackButtonHandler()
observeViewState()
configureEmailManagerObserver()
loadFirstWebpage(intent)
}
private fun loadFirstWebpage(intent: Intent?) {
val url = intent?.getActivityParams(EmailProtectionInContextSignUpHandleVerificationLink::class.java)?.url ?: STARTING_URL
binding.webView.loadUrl(url)
if (url == STARTING_URL) {
viewModel.loadedStartingUrl()
}
}
private fun configureEmailManagerObserver() {
lifecycleScope.launch(dispatchers.main()) {
repeatOnLifecycle(Lifecycle.State.STARTED) {
emailManager.signedInFlow().collect() { signedIn ->
viewModel.signedInStateUpdated(signedIn, binding.webView.url)
}
}
}
}
private fun observeViewState() {
lifecycleScope.launch(dispatchers.main()) {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.viewState.collect { viewState ->
when (viewState) {
is ViewState.CancellingInContextSignUp -> cancelInContextSignUp()
is ViewState.ConfirmingCancellationOfInContextSignUp -> confirmCancellationOfInContextSignUp()
is ViewState.NavigatingBack -> navigateWebViewBack()
is ViewState.ShowingWebContent -> showWebContent(viewState)
is ViewState.ExitingAsSuccess -> closeActivityAsSuccessfulSignup()
}
}
}
}
}
private fun showWebContent(viewState: ViewState.ShowingWebContent) {
when (viewState.urlActions.exitButton) {
ExitButtonAction.Disabled -> getToolbar().navigationIcon = null
ExitButtonAction.ExitWithConfirmation -> {
getToolbar().run {
setNavigationIconAsCross()
setNavigationOnClickListener { confirmCancellationOfInContextSignUp() }
}
}
ExitButtonAction.ExitWithoutConfirmation -> {
getToolbar().run {
setNavigationIconAsCross()
setNavigationOnClickListener {
viewModel.userCancelledSignupWithoutConfirmation()
}
}
}
ExitButtonAction.ExitTreatAsSuccess -> {
getToolbar().run {
setNavigationIconAsCross()
setNavigationOnClickListener { closeActivityAsSuccessfulSignup() }
}
}
}
}
private fun cancelInContextSignUp() {
setResult(EmailProtectionInContextSignUpScreenResult.CANCELLED)
finish()
}
private fun closeActivityAsSuccessfulSignup() {
setResult(EmailProtectionInContextSignUpScreenResult.SUCCESS)
finish()
}
private fun navigateWebViewBack() {
val previousUrl = getPreviousWebPageUrl()
binding.webView.goBack()
viewModel.consumedBackNavigation(previousUrl)
}
private fun confirmCancellationOfInContextSignUp() {
TextAlertDialogBuilder(this)
.setTitle(R.string.autofillEmailProtectionInContextSignUpConfirmExitDialogTitle)
.setPositiveButton(R.string.autofillEmailProtectionInContextSignUpConfirmExitDialogPositiveButton)
.setNegativeButton(R.string.autofillEmailProtectionInContextSignUpConfirmExitDialogNegativeButton)
.addEventListener(
object : TextAlertDialogBuilder.EventListener() {
override fun onPositiveButtonClicked() {
viewModel.onUserDecidedNotToCancelInContextSignUp()
}
override fun onNegativeButtonClicked() {
viewModel.onUserConfirmedCancellationOfInContextSignUp()
}
},
)
.show()
}
private fun configureBackButtonHandler() {
onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
viewModel.onBackButtonPressed(url = binding.webView.url, canGoBack = binding.webView.canGoBack())
}
},
)
}
private fun initialiseToolbar() {
with(getToolbar()) {
title = getString(R.string.autofillEmailProtectionInContextSignUpDialogFeatureName)
setNavigationIconAsCross()
setNavigationOnClickListener { onBackPressed() }
}
}
private fun Toolbar.setNavigationIconAsCross() {
setNavigationIcon(com.duckduckgo.mobile.android.R.drawable.ic_close_24)
}
@SuppressLint("SetJavaScriptEnabled")
private fun configureWebView() {
binding.webView.let {
it.webViewClient = EmailProtectionInContextSignUpWebViewClient(this)
it.webChromeClient = EmailProtectionInContextSignUpWebChromeClient(this)
it.settings.apply {
userAgentString = userAgentProvider.userAgent()
javaScriptEnabled = true
domStorageEnabled = true
loadWithOverviewMode = true
useWideViewPort = true
builtInZoomControls = true
displayZoomControls = false
mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
setSupportMultipleWindows(true)
databaseEnabled = false
setSupportZoom(true)
}
it.addJavascriptInterface(autofillInterface, AutofillJavascriptInterface.INTERFACE_NAME)
autofillInterface.webView = it
autofillInterface.emailProtectionInContextSignupFlowCallback = object : EmailProtectionInContextSignupFlowListener {
override fun closeInContextSignup() {
closeActivityAsSuccessfulSignup()
}
}
emailInjector.addJsInterface(it, {}, {})
}
}
companion object {
private const val STARTING_URL = "https://duckduckgo.com/email/start-incontext"
fun intent(context: Context): Intent {
return Intent(context, EmailProtectionInContextSignupActivity::class.java)
}
}
override fun onPageStarted(url: String) {
configurator.configureAutofillForCurrentPage(binding.webView, url)
}
override fun onPageFinished(url: String) {
viewModel.onPageFinished(url)
}
private fun getPreviousWebPageUrl(): String? {
val webHistory = binding.webView.copyBackForwardList()
val currentIndex = webHistory.currentIndex
if (currentIndex < 0) return null
val previousIndex = currentIndex - 1
if (previousIndex < 0) return null
return webHistory.getItemAtIndex(previousIndex)?.url
}
private fun getToolbar() = binding.includeToolbar.toolbar as Toolbar
}
| 67 | null | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 10,899 | Android | Apache License 2.0 |
app/src/main/java/com/certified/covid19response/ui/result/ResultFragment.kt | certified84 | 465,168,574 | false | {"Kotlin": 151395} | package com.certified.covid19response.ui.result
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.certified.covid19response.adapter.DoctorAdapter
import com.certified.covid19response.data.model.Conversation
import com.certified.covid19response.data.model.User
import com.certified.covid19response.databinding.FragmentResultBinding
import com.certified.covid19response.util.Extensions.openBrowser
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ResultFragment : Fragment() {
private var _binding: FragmentResultBinding? = null
private val binding get() = _binding!!
private val args: ResultFragmentArgs by navArgs()
private val viewModel: ResultViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentResultBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewModel = viewModel
binding.lifecycleOwner = this
binding.uiState = viewModel.uiState
binding.apply {
result = args.result
btnBack.setOnClickListener { findNavController().navigate(ResultFragmentDirections.actionResultFragmentToStatusFragment()) }
btnCovidIsolationLink.setOnClickListener {
val url =
"https://www.who.int/emergencies/diseases/novel-coronavirus-2019/advice-for-public"
requireContext().openBrowser(
url,
findNavController(),
ResultFragmentDirections.actionResultFragmentToWebFragment(url)
)
}
val pieDataSet = PieDataSet(
listOf(
PieEntry(args.result.severePercent / 100),
PieEntry(args.result.lessPercent / 100),
PieEntry(args.result.mostPercent / 100)
), ""
)
pieDataSet.apply {
sliceSpace = 2f
valueTextSize = 0f
colors = listOf(Color.RED, Color.BLUE, Color.YELLOW)
}
val descrip = Description()
descrip.text = ""
pieChart.apply {
isRotationEnabled = false
holeRadius = 2f
description = descrip
setTransparentCircleAlpha(0)
data = PieData(pieDataSet)
invalidate()
}
val adapter = DoctorAdapter()
adapter.setOnItemClickedListener(object : DoctorAdapter.OnItemClickedListener {
override fun onItemClick(doctor: User) {
findNavController().navigate(
ResultFragmentDirections.actionResultFragmentToChatFragment(
conversation = Conversation(
sender = args.user,
receiver = doctor
), message = args.result.feeling
)
)
}
})
recyclerViewDoctors.adapter = adapter
recyclerViewDoctors.layoutManager =
LinearLayoutManager(requireContext())
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 0 | 5 | 1a464ff649f33e8ef2a77a1c2b2515c92ab42c2d | 4,119 | COVID-19Response | Apache License 2.0 |
libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ir/OperationBasedWithInterfacesModelGroupBuilder.kt | apollographql | 69,469,299 | false | null | package com.apollographql.apollo3.compiler.ir
import com.apollographql.apollo3.ast.GQLField
import com.apollographql.apollo3.ast.GQLFragmentDefinition
import com.apollographql.apollo3.ast.GQLFragmentSpread
import com.apollographql.apollo3.ast.GQLInlineFragment
import com.apollographql.apollo3.ast.GQLNamedType
import com.apollographql.apollo3.ast.GQLNonNullType
import com.apollographql.apollo3.ast.GQLSelection
import com.apollographql.apollo3.ast.Schema
import com.apollographql.apollo3.compiler.capitalizeFirstLetter
import com.apollographql.apollo3.compiler.lowerCamelCaseIgnoringNonLetters
import com.apollographql.apollo3.compiler.codegen.modelName
import com.apollographql.apollo3.compiler.decapitalizeFirstLetter
import com.apollographql.apollo3.compiler.internal.escapeKotlinReservedWord
/**
* Very similar to [OperationBasedModelGroupBuilder] except:
* - it doesn't support compat
* - it doesn't support `@include` and `@defer`
* - it generates interfaces for polymorphic selection sets
*
* For that last point, it starts just like [OperationBasedModelGroupBuilder] and once it has a tree of nodes,
* it converts nodes that contains fragments into a modelGroup that has multiple models
*/
internal class OperationBasedWithInterfacesModelGroupBuilder(
private val schema: Schema,
private val allFragmentDefinitions: Map<String, GQLFragmentDefinition>,
private val fieldMerger: FieldMerger,
) : ModelGroupBuilder {
override fun buildOperationData(
selections: List<GQLSelection>,
rawTypeName: String,
operationName: String,
): Pair<IrProperty, IrModelGroup> {
val info = IrFieldInfo(
responseName = "data",
description = null,
type = IrModelType(MODEL_UNKNOWN),
deprecationReason = null,
optInFeature = null,
gqlType = GQLNonNullType(type = GQLNamedType(name = rawTypeName))
)
val field = buildNode(
path = "${MODEL_OPERATION_DATA}.$operationName",
info = info,
parentTypes = listOf(rawTypeName),
selections = selections,
condition = BooleanExpression.True
)
return field.toProperty() to field.toModelGroup()!!
}
override fun buildFragmentInterface(fragmentName: String): IrModelGroup? {
return null
}
override fun buildFragmentData(fragmentName: String): Pair<IrProperty, IrModelGroup> {
val fragmentDefinition = allFragmentDefinitions[fragmentName]!!
/**
* XXX: because we want the model to be named after the fragment (and not data), we use
* fragmentName below. This means the id for the very first model is going to be
* FragmentName.FragmentName unlike operations where it's OperationName.Data
*/
val info = IrFieldInfo(
responseName = fragmentName,
description = null,
type = IrModelType(MODEL_UNKNOWN),
deprecationReason = null,
optInFeature = null,
gqlType = GQLNonNullType(type = fragmentDefinition.typeCondition),
)
val mergedSelections = fragmentDefinition.selections
val field = buildNode(
path = "${MODEL_FRAGMENT_DATA}.$fragmentName",
info = info,
selections = mergedSelections,
condition = BooleanExpression.True,
parentTypes = listOf(fragmentDefinition.typeCondition.name),
)
return field.toProperty() to field.toModelGroup()!!
}
/**
* Build a field, inline fragment or fragment definition.
*
* @param path the path up to but not including this selection
* @param parentTypes the list of the different typeConditions going from the field type through all inline fragments
* - for a field, this is the rawTypeName of the field
* - for an inline fragment, this is the typeCondition of the fragment and all previous inline fragment:
* ```
* {
* node {
* ... on Character {
* # building this inline fragment, parentTypes = listOf("Node", "Character", "Droid")
* ... on Droid {
* }
* }
* }
* }
* ```
* - for a fragment definition this is the typeCondition of this fragment definition
*
* @param info information about this selection
* @param selections the sub-selections of this selection. They are all on the same parentType
* @param condition the condition for this field. A mix of include directives, @defer labels and type conditions
*/
private fun buildNode(
path: String,
parentTypes: List<String>,
info: IrFieldInfo,
selections: List<GQLSelection>,
condition: BooleanExpression<BTerm>,
): OperationField2 {
if (selections.isEmpty()) {
return OperationField2(
info = info,
condition = condition,
fieldSet = null,
parentTypes = parentTypes
)
}
val selfPath = path + "." + info.responseName
val parentType = parentTypes.last()
/**
* Merge fragments with the same type condition
*
* We do not support `@include`/`@skip` directives here
*/
val inlineFragmentsFields = selections.filterIsInstance<GQLInlineFragment>()
.groupBy { it.typeCondition?.name ?: parentType }
.entries.map { entry ->
val name = "on${entry.key.capitalizeFirstLetter()}"
val typeCondition = entry.key
val childCondition: BooleanExpression<BTerm> = if (parentTypes.any { schema.isTypeASubTypeOf(it, typeCondition) }) {
/**
* If any of the parent types is a subtype of the type condition (e.g. Cat is a subtype of Animal) then we can skip checking the typename
*/
BooleanExpression.True
} else {
val possibleTypes = schema.possibleTypes(typeCondition)
BooleanExpression.Element(BPossibleTypes(possibleTypes))
}
var type: IrType = IrModelType(MODEL_UNKNOWN, nullable = true)
if (childCondition == BooleanExpression.True) {
type = type.nullable(false)
}
val childInfo = IrFieldInfo(
responseName = name,
description = "Synthetic field for inline fragment on $typeCondition",
deprecationReason = null,
optInFeature = null,
type = type,
gqlType = null,
)
val childSelections = entry.value.flatMap {
it.selections
}
buildNode(
path = selfPath,
info = childInfo,
selections = childSelections,
condition = childCondition,
parentTypes = parentTypes + typeCondition,
)
}
/**
* Merge fragment spreads, regardless of the type condition
*
* Since they all have the same shape, it's ok, contrary to inline fragments above
*/
val fragmentSpreadFields = selections.filterIsInstance<GQLFragmentSpread>()
.groupBy {
it.name
}.values.map { fragmentSpreadsWithSameName ->
val first = fragmentSpreadsWithSameName.first()
val fragmentDefinition = allFragmentDefinitions[first.name]!!
val typeCondition = fragmentDefinition.typeCondition.name
val childCondition: BooleanExpression<BTerm> = if (parentTypes.any { schema.isTypeASubTypeOf(it, typeCondition) }) {
/**
* If any of the parent types is a subtype (e.g. Cat is a subtype of Animal) then we can skip checking the typename
*/
BooleanExpression.True
} else {
val possibleTypes = schema.possibleTypes(typeCondition)
BooleanExpression.Element(BPossibleTypes(possibleTypes))
}
/**
* Beware the double first.name because:
* - first one is the fragment name
* - second one is the name of the field (there could be multiple root classes/interfaces for fragments)
*/
val fragmentModelPath = "${MODEL_FRAGMENT_DATA}.${first.name}.${first.name}"
var type: IrType = IrModelType(fragmentModelPath, nullable = true)
if (childCondition == BooleanExpression.True) {
type = type.nullable(false)
}
val childInfo = IrFieldInfo(
responseName = first.name.decapitalizeFirstLetter().escapeKotlinReservedWord(),
description = "Synthetic field for '${first.name}'",
deprecationReason = null,
optInFeature = null,
type = type,
gqlType = null,
)
buildNode(
path = selfPath,
info = childInfo,
selections = emptyList(), // Don't create a model for fragments spreads
condition = childCondition,
parentTypes = parentTypes + typeCondition
)
}
val modelName = modelName(info)
/**
* Merge fields with the same response name in the selectionSet
*/
val fieldsWithParent = selections.mapNotNull {
if (it is GQLField) {
FieldWithParent(it, parentType)
} else {
null
}
}
val fields = fieldMerger.merge(fieldsWithParent).map { mergedField ->
val childInfo = mergedField.info.maybeNullable(mergedField.condition != BooleanExpression.True)
buildNode(
path = selfPath,
info = childInfo,
selections = mergedField.selections,
condition = BooleanExpression.True,
parentTypes = listOf(mergedField.rawTypeName)
)
}
val fieldSet = OperationFieldSet2(
id = selfPath,
modelName = modelName,
fields = fields + inlineFragmentsFields + fragmentSpreadFields,
)
val patchedInfo = info.copy(
type = info.type.replacePlaceholder(fieldSet.id),
responseName = if (info.gqlType == null) {
lowerCamelCaseIgnoringNonLetters(setOf(modelName))
} else {
info.responseName
}
)
return OperationField2(
info = patchedInfo,
condition = condition,
parentTypes = parentTypes,
fieldSet = fieldSet,
)
}
private class OperationField2(
val info: IrFieldInfo,
val condition: BooleanExpression<BTerm>,
val parentTypes: List<String>,
val fieldSet: OperationFieldSet2?,
) {
val isSynthetic: Boolean
get() = info.gqlType == null
}
private data class OperationFieldSet2(
val id: String,
val modelName: String,
val fields: List<OperationField2>,
)
private fun OperationField2.toModelGroup(): IrModelGroup? {
if (fieldSet == null) {
// fast path: leaf field
return null
}
val syntheticFields = fieldSet.fields.filter { it.isSynthetic }
val selfTypeCondition = parentTypes.last()
// TODO: cache this computation
val incomingTypes = parentTypes.map { schema.possibleTypes(it) }.intersection().toList()
val typeSets = syntheticFields.map {
setOf(selfTypeCondition, it.parentTypes.last())
}
var buckets = buckets(schema, incomingTypes, typeSets)
if (buckets.none { it.typeSet.size == 1 }) {
/**
* Add the fallback type if required
*/
buckets = buckets + Bucket(setOf(selfTypeCondition), incomingTypes.toSet())
}
val models = if (buckets.size == 1) {
listOf(fieldSet.toClass())
} else {
listOf(fieldSet.toInterface()) + buckets.map { fieldSet.toSubClass(info, selfTypeCondition, it) }
}
return IrModelGroup(
models = models,
baseModelId = fieldSet.id
)
}
private fun OperationFieldSet2.toClass(): IrModel {
return IrModel(
modelName = modelName,
id = id,
properties = fields.map { it.toProperty() },
accessors = emptyList(),
implements = emptyList(),
isFallback = false,
isInterface = false,
modelGroups = fields.mapNotNull { it.toModelGroup() },
possibleTypes = emptyList(),
typeSet = emptySet(),
)
}
private fun OperationFieldSet2.toInterface(): IrModel {
return IrModel(
modelName = modelName,
id = id,
properties = fields.map { it.toProperty() },
accessors = emptyList(),
implements = emptyList(),
isFallback = false,
isInterface = true,
modelGroups = fields.mapNotNull { it.toModelGroup() },
possibleTypes = emptyList(),
typeSet = emptySet(),
)
}
private fun OperationFieldSet2.toSubClass(fieldInfo: IrFieldInfo, rawTypeName: String, bucket: Bucket): IrModel {
val isOther = bucket.typeSet.size == 1
val modelName = modelName(fieldInfo, bucket.typeSet, rawTypeName, isOther)
return IrModel(
modelName = modelName,
id = id.substringBeforeLast(".") + modelName,
properties = fields.map { it.toOverriddenProperty(bucket.possibleTypes) },
accessors = emptyList(),
implements = listOf(id),
isFallback = isOther,
isInterface = false,
modelGroups = emptyList(),
possibleTypes = bucket.possibleTypes.toList(),
typeSet = emptySet(),
)
}
private fun OperationField2.toProperty(): IrProperty {
return IrProperty(
info = info,
override = false,
condition = condition,
requiresBuffering = fieldSet?.fields?.any { it.isSynthetic } ?: false,
)
}
private fun OperationField2.toOverriddenProperty(possibleTypes: PossibleTypes): IrProperty {
val info: IrFieldInfo
val condition: BooleanExpression<BTerm>
if (isSynthetic) {
condition = this.condition.simplify(possibleTypes)
info = if (condition is BooleanExpression.True && this.info.type.nullable) {
this.info.copy(type = this.info.type.nullable(false))
} else {
this.info
}
} else {
info = this.info
condition = this.condition
}
return IrProperty(
info = info,
override = true,
condition = condition,
requiresBuffering = fieldSet?.fields?.any { it.isSynthetic } ?: false,
)
}
private fun BooleanExpression<BTerm>.simplify(possibleTypes: PossibleTypes): BooleanExpression<BTerm> {
if (this !is BooleanExpression.Element) {
return this
}
val value = this.value
if (value !is BPossibleTypes) {
return this
}
if(value.possibleTypes.containsAll(possibleTypes)) {
return BooleanExpression.True
}
return this
}
}
| 177 | null | 658 | 3,750 | 174cb227efe76672cf2beac1affc7054f6bb2892 | 14,457 | apollo-kotlin | MIT License |
idea/testData/inspections/canBeParameter/test.kt | JakeWharton | 99,388,807 | false | null | class NonUsed(val x: Int) // NO
// NO
data class UsedInData(val x: Int)
// YES
class UsedInProperty(val x: Int) {
val y = x
}
// YES
class UsedInInitializer(val x: Int) {
val y: Int
init {
y = x
}
}
// NO!
class UsedInConstructor(val x: Int) {
fun foo(arg: Int) = arg
constructor(): this(42) {
foo(x)
}
}
// NO
class UsedInFunction(val x: Int) {
fun get() = x
}
// NO
class UsedInGetter(val x: Int) {
val y: Int
get() = x
}
// NO
class UsedInSetter(val x: Int) {
var y: Int = 0
get() = field
set(arg) { field = x + arg }
}
// NO
class UsedInInnerClass(val x: Int) {
inner class Inner {
fun foo() = x
}
}
// NO
class UsedOutside(val x: Int)
fun use(): Int {
val used = UsedOutside(30)
return used.x
}
// YES
class PrivateUsedInProperty(private val x: Int) {
val y = x
}
// NO
open class Base(protected open val x: Int)
// NO
class UsedOverridden(override val x: Int) : Base(x) {
val y = x
}
// YES
class UsedInPropertyVar(var x: Int) {
var y = x
}
// NO
class UsedInPropertyAnnotated(@JvmField val x: Int) {
val y = x
}
// YES
class UsedWithoutThisInInitProperty(val x: Int) {
init {
val y = x
}
}
// NO
class UsedWithThisInInitProperty(val x: Int) {
init {
val y = this.x
}
}
// NO
class UsedWithLabeledThisInInitProperty(val x: Int) {
init {
run {
val y = [email protected]
}
}
}
// NO
class UsedInFunctionProperty(val x: Int) {
fun get(): Int {
val y = x
return y
}
}
// NO
class ModifiedInInit(var x: Int) {
init {
x += 2
}
}
// NO
open class UsedInOverride(open val x: Int)
class UserInOverride(override val x: Int) : UsedInOverride(x)
// NO
class UsedInLambda(val x: Int) {
init {
run {
val y = x
}
}
}
// NO
class UsedInDelegate(val x: Int) {
val y: Int by lazy {
x * x
}
}
// NO
class UsedInParent(val x: UsedInParent?) {
val y = x?.x
}
// NO
class UsedInObjectLiteral(val x: Int) {
val y = object: Any() {
fun bar() = x
}
}
// NO
class UsedInLocalFunction(val x: Int) {
init {
fun local() {
val y = x
}
local()
}
}
// YES
open class Base1(s: String)
class UsedInSuper(val bar123: String) : Base1(bar123)
// NO
class UsedInLocalSuper(val bar456: String) {
fun foo() {
class Local : Base1(bar456)
}
}
// NO
class UsedInObjectSuper(val bar456: String) {
fun foo() {
object : Base1(bar456) {}
}
}
| 0 | null | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 2,603 | kotlin | Apache License 2.0 |
idea/testData/inspections/canBeParameter/test.kt | JakeWharton | 99,388,807 | false | null | class NonUsed(val x: Int) // NO
// NO
data class UsedInData(val x: Int)
// YES
class UsedInProperty(val x: Int) {
val y = x
}
// YES
class UsedInInitializer(val x: Int) {
val y: Int
init {
y = x
}
}
// NO!
class UsedInConstructor(val x: Int) {
fun foo(arg: Int) = arg
constructor(): this(42) {
foo(x)
}
}
// NO
class UsedInFunction(val x: Int) {
fun get() = x
}
// NO
class UsedInGetter(val x: Int) {
val y: Int
get() = x
}
// NO
class UsedInSetter(val x: Int) {
var y: Int = 0
get() = field
set(arg) { field = x + arg }
}
// NO
class UsedInInnerClass(val x: Int) {
inner class Inner {
fun foo() = x
}
}
// NO
class UsedOutside(val x: Int)
fun use(): Int {
val used = UsedOutside(30)
return used.x
}
// YES
class PrivateUsedInProperty(private val x: Int) {
val y = x
}
// NO
open class Base(protected open val x: Int)
// NO
class UsedOverridden(override val x: Int) : Base(x) {
val y = x
}
// YES
class UsedInPropertyVar(var x: Int) {
var y = x
}
// NO
class UsedInPropertyAnnotated(@JvmField val x: Int) {
val y = x
}
// YES
class UsedWithoutThisInInitProperty(val x: Int) {
init {
val y = x
}
}
// NO
class UsedWithThisInInitProperty(val x: Int) {
init {
val y = this.x
}
}
// NO
class UsedWithLabeledThisInInitProperty(val x: Int) {
init {
run {
val y = [email protected]
}
}
}
// NO
class UsedInFunctionProperty(val x: Int) {
fun get(): Int {
val y = x
return y
}
}
// NO
class ModifiedInInit(var x: Int) {
init {
x += 2
}
}
// NO
open class UsedInOverride(open val x: Int)
class UserInOverride(override val x: Int) : UsedInOverride(x)
// NO
class UsedInLambda(val x: Int) {
init {
run {
val y = x
}
}
}
// NO
class UsedInDelegate(val x: Int) {
val y: Int by lazy {
x * x
}
}
// NO
class UsedInParent(val x: UsedInParent?) {
val y = x?.x
}
// NO
class UsedInObjectLiteral(val x: Int) {
val y = object: Any() {
fun bar() = x
}
}
// NO
class UsedInLocalFunction(val x: Int) {
init {
fun local() {
val y = x
}
local()
}
}
// YES
open class Base1(s: String)
class UsedInSuper(val bar123: String) : Base1(bar123)
// NO
class UsedInLocalSuper(val bar456: String) {
fun foo() {
class Local : Base1(bar456)
}
}
// NO
class UsedInObjectSuper(val bar456: String) {
fun foo() {
object : Base1(bar456) {}
}
}
| 0 | null | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 2,603 | kotlin | Apache License 2.0 |
plugin/src/main/kotlin/com/chimerapps/storageinspector/util/Logger.kt | ikbendewilliam | 445,913,624 | true | {"Kotlin": 220093, "Dart": 83872, "Shell": 1093} | package com.chimerapps.storageinspector.util
import com.intellij.openapi.diagnostic.Logger
/**
* @author <NAME>
*/
val Any.classLogger : Logger
get() = Logger.getInstance(this::class.java) | 0 | null | 0 | 0 | 6c34d22121f24374b71d0a65b7454fee4d1800fe | 196 | flutter_local_storage_inspector | MIT License |
plugin/src/main/kotlin/com/chimerapps/storageinspector/util/Logger.kt | ikbendewilliam | 445,913,624 | true | {"Kotlin": 220093, "Dart": 83872, "Shell": 1093} | package com.chimerapps.storageinspector.util
import com.intellij.openapi.diagnostic.Logger
/**
* @author <NAME>
*/
val Any.classLogger : Logger
get() = Logger.getInstance(this::class.java) | 0 | null | 0 | 0 | 6c34d22121f24374b71d0a65b7454fee4d1800fe | 196 | flutter_local_storage_inspector | MIT License |
snowplow-tracker/src/androidTest/java/com/snowplowanalytics/snowplow/tracker/ExecutorTest.kt | snowplow | 20,056,757 | false | {"Kotlin": 1227237, "Java": 38410, "Shell": 78} | /*
* Copyright (c) 2015-present Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.snowplowanalytics.core.emitter.Executor.shutdown
import com.snowplowanalytics.core.emitter.Executor.execute
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.lang.Exception
import java.lang.NullPointerException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.Throws
@RunWith(AndroidJUnit4::class)
class ExecutorTest {
@Before
@Throws(Exception::class)
fun setUp() {
val es = shutdown()
es?.awaitTermination(60, TimeUnit.SECONDS)
}
@Test
@Throws(InterruptedException::class)
fun testExecutorRaisingException() {
val expectation = Any() as Object
val exceptionRaised = AtomicBoolean(false)
execute({ throw NullPointerException() }) { t: Throwable? ->
exceptionRaised.set(t is NullPointerException)
synchronized(expectation) { expectation.notify() }
}
synchronized(expectation) { expectation.wait(10000) }
Assert.assertTrue(exceptionRaised.get())
}
}
| 16 | Kotlin | 62 | 102 | c6ad42b49faf979f3f8c13cc8b91304c423872bd | 1,906 | snowplow-android-tracker | Apache License 2.0 |
src/main/kotlin/wf/garnier/sessiondemo/user/User.kt | Kehrlann | 136,068,731 | false | {"Kotlin": 7228, "Shell": 1000, "Java": 668} | package wf.garnier.sessiondemo.user
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
import com.fasterxml.jackson.annotation.JsonIgnore
@Entity
class User(@Id @GeneratedValue val id: Long = 0L,
val username: String = "",
@JsonIgnore val encryptedPassword: String = "") {
constructor(username: String, clearTextPassword: String):
this(username = username, encryptedPassword = BCryptPasswordEncoder(11).encode(clearTextPassword))
}
| 0 | Kotlin | 0 | 0 | 020de350f0dd897c760ba1eef9d8c4e016e1b76f | 594 | spring-security-and-session | Apache License 2.0 |
src/test/integration/kotlin/no/fintlabs/operator/application/DeploymentDRTest.kt | FINTLabs | 540,843,912 | false | {"Kotlin": 92018, "Smarty": 1822, "Dockerfile": 157} | package no.fintlabs.operator.application
import com.sksamuel.hoplite.PropertySource
import io.fabric8.kubernetes.api.model.*
import io.fabric8.kubernetes.api.model.apps.Deployment
import io.fabric8.kubernetes.api.model.apps.DeploymentStrategy
import io.fabric8.kubernetes.api.model.apps.RollingUpdateDeployment
import io.fabric8.kubernetes.client.KubernetesClientException
import no.fintlabs.extensions.KubernetesOperatorContext
import no.fintlabs.extensions.KubernetesResources
import no.fintlabs.loadConfig
import no.fintlabs.operator.application.Utils.createAndGetResource
import no.fintlabs.operator.application.Utils.createKoinTestExtension
import no.fintlabs.operator.application.Utils.createKubernetesOperatorExtension
import no.fintlabs.operator.application.Utils.createTestFlaisApplication
import no.fintlabs.operator.application.api.*
import no.fintlabs.v1alpha1.kafkauserandaclspec.Acls
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.RegisterExtension
import org.koin.dsl.module
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
@KubernetesResources("deployment/kubernetes")
class DeploymentDRTest {
//region General
@Test
fun `should create deployment`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication()
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals("test", deployment.metadata.name)
assertEquals("test", deployment.metadata.labels["app"])
assertEquals("test.org", deployment.metadata.labels["fintlabs.no/org-id"])
assertEquals("test", deployment.metadata.labels["fintlabs.no/team"])
assertEquals("test", deployment.spec.template.metadata.annotations["kubectl.kubernetes.io/default-container"])
assert(deployment.spec.selector.matchLabels.containsKey("app"))
assertEquals("test", deployment.spec.selector.matchLabels["app"])
assertEquals(1, deployment.spec.replicas)
assertEquals(2, deployment.spec.template.spec.imagePullSecrets.size)
assertEquals("reg-key-1", deployment.spec.template.spec.imagePullSecrets[0].name)
assertEquals("reg-key-2", deployment.spec.template.spec.imagePullSecrets[1].name)
assertEquals(1, deployment.spec.template.spec.containers.size)
assertEquals("test-image", deployment.spec.template.spec.containers[0].image)
assertEquals("test", deployment.spec.template.spec.containers[0].name)
assertEquals("Always", deployment.spec.template.spec.containers[0].imagePullPolicy)
assertEquals(1, deployment.spec.template.spec.containers[0].ports.size)
assertEquals("http", deployment.spec.template.spec.containers[0].ports[0].name)
assertEquals(8080, deployment.spec.template.spec.containers[0].ports[0].containerPort)
assertEquals(2, deployment.spec.template.spec.containers[0].env.size)
}
//endregion
//region Deployment
@Test
fun `should create deployment with correct replicas`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(replicas = 3)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(3, deployment.spec.replicas)
}
@Test
fun `should throw error on invalid replicas`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(replicas = -1)
}
val exception = assertThrows<KubernetesClientException> {
context.createAndGetDeployment(flaisApplication)
}
assert("spec.replicas: Invalid value: -1" in exception.status.message)
}
@Test
fun `should create deployment with rolling update strategy`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(strategy = DeploymentStrategy().apply {
type = "RollingUpdate"
rollingUpdate = RollingUpdateDeployment().apply {
maxSurge = IntOrString("25%")
maxUnavailable = IntOrString("25%")
}
})
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals("RollingUpdate", deployment.spec.strategy.type)
assertEquals("25%", deployment.spec.strategy.rollingUpdate.maxSurge.strVal)
assertEquals("25%", deployment.spec.strategy.rollingUpdate.maxUnavailable.strVal)
}
@Test
fun `should create deployment with recreate strategy`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(strategy = DeploymentStrategy().apply {
type = "Recreate"
})
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals("Recreate", deployment.spec.strategy.type)
}
//endregion
//region Metadata
@Test
fun `should create deployment with correct labels`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
metadata = metadata.apply {
labels = labels.plus(
"test" to "test"
)
}
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals("test", deployment.metadata.labels["test"])
}
@Test
fun `should add managed by label`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication()
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals("flaiserator", deployment.metadata.labels["app.kubernetes.io/managed-by"])
}
@Test
fun `should add prometheus annotations`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
prometheus = Prometheus(
enabled = true,
port = "8081",
path = "/metrics"
)
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals("true", deployment.spec.template.metadata.annotations["prometheus.io/scrape"])
assertEquals("8081", deployment.spec.template.metadata.annotations["prometheus.io/port"])
assertEquals("/metrics", deployment.spec.template.metadata.annotations["prometheus.io/path"])
}
//endregion
//region Image
@Test
fun `should create deployment with correct container pull policy`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(image = "test-image:latest")
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals("Always", deployment.spec.template.spec.containers[0].imagePullPolicy)
}
@Test
fun `should create deployment with correct image pull secrets`(context: KubernetesOperatorContext) {
context.create(Secret().apply {
metadata = ObjectMeta().apply {
name = "test-secret"
type = "kubernetes.io/dockerconfigjson"
}
stringData = mapOf(
".dockerconfigjson" to "{}"
)
})
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
imagePullSecrets = listOf(
"test-secret"
)
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(3, deployment.spec.template.spec.imagePullSecrets.size)
assertEquals("test-secret", deployment.spec.template.spec.imagePullSecrets[0].name)
}
//endregion
//region Resources
@Test
fun `should have correct resource limits`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
resources = ResourceRequirementsBuilder()
.addToRequests("cpu", Quantity("500m"))
.addToRequests("memory", Quantity("512Mi"))
.addToLimits("cpu", Quantity("1"))
.addToLimits("memory", Quantity("1Gi"))
.build()
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(2, deployment.spec.template.spec.containers[0].resources.requests.size)
assertEquals("500m", deployment.spec.template.spec.containers[0].resources.requests["cpu"]?.toString())
assertEquals("512Mi", deployment.spec.template.spec.containers[0].resources.requests["memory"]?.toString())
assertEquals(2, deployment.spec.template.spec.containers[0].resources.limits.size)
assertEquals("1", deployment.spec.template.spec.containers[0].resources.limits["cpu"]?.toString())
assertEquals("1Gi", deployment.spec.template.spec.containers[0].resources.limits["memory"]?.toString())
}
//endregion
//region Secrets and Environment variables
@Test
fun `should have additional env variables`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(env = listOf(
EnvVar().apply {
name = "key1"
value = "value1"
},
EnvVar().apply {
name = "key2"
value = "value2"
}
))
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(4, deployment.spec.template.spec.containers[0].env.size)
assertEquals("key1", deployment.spec.template.spec.containers[0].env[0].name)
assertEquals("value1", deployment.spec.template.spec.containers[0].env[0].value)
assertEquals("key2", deployment.spec.template.spec.containers[0].env[1].name)
assertEquals("value2", deployment.spec.template.spec.containers[0].env[1].value)
assertEquals("fint.org-id", deployment.spec.template.spec.containers[0].env[2].name)
assertEquals("test.org", deployment.spec.template.spec.containers[0].env[2].value)
assertEquals("TZ", deployment.spec.template.spec.containers[0].env[3].name)
assertEquals("Europe/Oslo", deployment.spec.template.spec.containers[0].env[3].value)
}
@Test
fun `should not have overlapping env variables`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(env = listOf(
EnvVar().apply {
name = "fint.org-id"
value = "value1"
},
EnvVar().apply {
name = "key2"
value = "value2"
}
))
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(3, deployment.spec.template.spec.containers[0].env.size)
assertEquals("fint.org-id", deployment.spec.template.spec.containers[0].env[0].name)
assertEquals("value1", deployment.spec.template.spec.containers[0].env[0].value)
assertEquals("key2", deployment.spec.template.spec.containers[0].env[1].name)
assertEquals("value2", deployment.spec.template.spec.containers[0].env[1].value)
assertEquals("TZ", deployment.spec.template.spec.containers[0].env[2].name)
assertEquals("Europe/Oslo", deployment.spec.template.spec.containers[0].env[2].value)
}
@Test
fun `should have additional envFrom variable from 1Password`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
onePassword = OnePassword(
itemPath = "test"
)
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(1, deployment.spec.template.spec.containers[0].envFrom.size)
assertEquals(
"${flaisApplication.metadata.name}-op",
deployment.spec.template.spec.containers[0].envFrom[0].secretRef.name
)
}
@Test
fun `should have additional envFrom variable from database`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
database = Database("test-db")
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(1, deployment.spec.template.spec.containers[0].envFrom.size)
assertEquals(
"${flaisApplication.metadata.name}-db",
deployment.spec.template.spec.containers[0].envFrom[0].secretRef.name
)
}
@Test
fun `should have additional envFrom variable from Kafka`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
kafka = Kafka(
acls = listOf(
Acls().apply {
topic = "test-topic"
permission = "write"
}
)
)
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(1, deployment.spec.template.spec.containers[0].envFrom.size)
assertEquals(
"${flaisApplication.metadata.name}-kafka",
deployment.spec.template.spec.containers[0].envFrom[0].secretRef.name
)
}
@Test
fun `should have correct path env vars`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
url = Url(
basePath = "/test"
)
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(4, deployment.spec.template.spec.containers[0].env.size)
assertEquals("spring.webflux.base-path", deployment.spec.template.spec.containers[0].env[2].name)
assertEquals("/test", deployment.spec.template.spec.containers[0].env[2].value)
assertEquals("spring.mvc.servlet.path", deployment.spec.template.spec.containers[0].env[3].name)
assertEquals("/test", deployment.spec.template.spec.containers[0].env[3].value)
}
//endregion
//region Volumes and volume mounts
@Test
fun `should have volume for Kafka`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
kafka = Kafka(
acls = listOf(
Acls().apply {
topic = "test-topic"
permission = "write"
}
)
)
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(1, deployment.spec.template.spec.volumes.size)
assertEquals("credentials", deployment.spec.template.spec.volumes[0].name)
assertEquals("test-kafka-certificates", deployment.spec.template.spec.volumes[0].secret.secretName)
}
@Test
fun `should have volume mounts for Kafka`(context: KubernetesOperatorContext) {
val flaisApplication = createTestFlaisApplication().apply {
spec = spec.copy(
kafka = Kafka(
acls = listOf(
Acls().apply {
topic = "test-topic"
permission = "write"
}
)
)
)
}
val deployment = context.createAndGetDeployment(flaisApplication)
assertNotNull(deployment)
assertEquals(1, deployment.spec.template.spec.volumes.size)
assertEquals("credentials", deployment.spec.template.spec.volumes[0].name)
assertEquals(1, deployment.spec.template.spec.containers[0].volumeMounts.size)
assertEquals("credentials", deployment.spec.template.spec.containers[0].volumeMounts[0].name)
assertEquals("/credentials", deployment.spec.template.spec.containers[0].volumeMounts[0].mountPath)
assertEquals(true, deployment.spec.template.spec.containers[0].volumeMounts[0].readOnly)
}
//endregion
private fun KubernetesOperatorContext.createAndGetDeployment(app: FlaisApplicationCrd) =
createAndGetResource<Deployment>(app)
companion object {
@RegisterExtension
val koinTestExtension = createKoinTestExtension(module {
single {
loadConfig(PropertySource.resource("/deployment/application.yaml", optional = false))
}
})
@RegisterExtension
val kubernetesOperatorExtension = createKubernetesOperatorExtension()
}
} | 1 | Kotlin | 0 | 0 | db1265ed3f91ba78845b550e92f4a415a1c567b2 | 17,993 | flaiserator | MIT License |
app/src/main/java/net/redwarp/app/multitool/compass/CompassListener.kt | redwarp | 102,224,951 | false | {"Gradle": 4, "Java Properties": 3, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 8, "XML": 11, "Java": 2} | package net.redwarp.app.multitool.compass
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import java.util.concurrent.TimeUnit
class CompassListener(val context: Context) : SensorEventListener {
companion object {
private fun angleMod(value: Float): Float {
var workValue = value;
if (workValue < 0) {
workValue = value + 360f
}
return workValue
}
}
private val publisher: PublishSubject<Float> = PublishSubject.create()
private val sensorManager: SensorManager
get() = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
fun getAngle(): Observable<Float> = publisher
.debounce(16, TimeUnit.MILLISECONDS)
.lift(AverageAngleOperator(1))
.distinct()
.map {
angleMod((-it * 360f / (2f * Math.PI)).toFloat())
}
fun resume() {
val rotationVector = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
sensorManager.registerListener(this, rotationVector, SensorManager.SENSOR_DELAY_UI)
}
fun pause() {
sensorManager.unregisterListener(this)
}
val matrixFromVector = FloatArray(9)
val remapedMatrix = FloatArray(9)
val values = FloatArray(3)
override fun onSensorChanged(event: SensorEvent?) {
if (event?.sensor == null) {
return
}
if (event.sensor?.type == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(matrixFromVector, event.values)
SensorManager.remapCoordinateSystem(matrixFromVector, SensorManager.AXIS_Z, SensorManager.AXIS_Y, remapedMatrix)
SensorManager.getOrientation(remapedMatrix, values)
publisher.onNext(values[0])
}
}
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
}
}
| 0 | Kotlin | 0 | 1 | 8121a25780ce42fbcc585723532a198bfe28e22f | 2,094 | Multi-Tool | Apache License 2.0 |
formula/src/test/java/com/instacart/formula/FromObservableWithInputFormula.kt | lgleasain | 393,435,967 | true | {"Kotlin": 249040, "Shell": 275, "Ruby": 220} | package com.instacart.formula
import io.reactivex.Observable
class FromObservableWithInputFormula : StatelessFormula<FromObservableWithInputFormula.Input, Unit>() {
data class Input(
val itemId: String,
val onItem: (Item) -> Unit
)
data class Item(val itemId: String)
class Repo {
fun fetchItem(itemId: String): Observable<Item> {
return Observable.just(Item(itemId))
}
}
private val repo = Repo()
override fun evaluate(input: Input, context: FormulaContext<Unit>): Evaluation<Unit> {
return Evaluation(
renderModel = Unit,
updates = context.updates {
val fetchItem = RxStream.fromObservable(key = input.itemId) {
repo.fetchItem(input.itemId)
}
events(fetchItem) {
transition { input.onItem(it) }
}
}
)
}
}
| 0 | null | 0 | 0 | c7630a3fd657ef95b823a45b5ea5a3cba30d69b6 | 945 | formula | BSD 3-Clause Clear License |
example/src/commonMain/kotlin/com/jeantuffier/statemachine/ArticleActions.kt | jeantuffier | 448,109,955 | false | {"Kotlin": 110935} | package com.jeantuffier.statemachine
import com.jeantuffier.statemachine.orchestrate.Action
import com.jeantuffier.statemachine.orchestrate.Limit
import com.jeantuffier.statemachine.orchestrate.Offset
import com.jeantuffier.statemachine.orchestrate.PageLoader
@Action
interface LoadMovies : PageLoader {
override val offset: Offset
override val limit: Limit
}
@Action
interface SelectMovie {
val id: String
}
@Action
interface CloseMovieDetails
| 0 | Kotlin | 0 | 3 | 4082d1b0b503822e2348de33191622bd0677c956 | 461 | statemachine | MIT License |
features/playlist/src/main/java/com/m3u/features/playlist/PlaylistEvent.kt | realOxy | 592,741,804 | false | {"Kotlin": 734765} | package com.m3u.features.playlist
import android.content.Context
sealed interface PlaylistEvent {
data class Observe(val playlistUrl: String) : PlaylistEvent
data object Refresh : PlaylistEvent
data class Favourite(val id: Int, val target: Boolean) : PlaylistEvent
data class Ban(val id: Int, val target: Boolean) : PlaylistEvent
data class SavePicture(val id: Int) : PlaylistEvent
data object ScrollUp : PlaylistEvent
data class Query(val text: String) : PlaylistEvent
data class CreateShortcut(val context: Context, val id: Int) : PlaylistEvent
}
| 8 | Kotlin | 9 | 95 | 67e7185408a544094c7b4403f8309a52dad4aca0 | 583 | M3UAndroid | Apache License 2.0 |
cqrs-and-event-sourcing/src/main/kotlin/com/showmeyourcode/cqrseventsourcing/demo/repository/eventstore/EventStore.kt | maciek1839 | 657,872,861 | false | null | package com.showmeyourcode.cqrseventsourcing.demo.repository.eventstore
import com.showmeyourcode.cqrseventsourcing.demo.domain.ProductID
import com.showmeyourcode.cqrseventsourcing.demo.domain.event.Event
interface EventStore {
fun save(event: Event)
fun saveAll(events: List<Event>) {
events.forEach(this::save)
}
fun allFor(productNumber: ProductID): List<Event>
fun exists(productNumber: ProductID): Boolean
}
| 0 | Kotlin | 0 | 0 | d43ae3ccc55357a1f911a3ac74cd53732c4e7496 | 447 | cqrs-and-event-sourcing-in-kotlin | MIT License |
MyTracker/app/src/main/java/com/mrzabbah/mytracker/feature_book_tracker/presentation/specificBook/components/CircularProgressBar.kt | MrZabbah | 442,011,201 | false | {"Kotlin": 134826} | package com.mrzabbah.mytracker.feature_book_tracker.presentation.specificBook.components
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.mrzabbah.mytracker.ui.theme.CasualBlue
import com.mrzabbah.mytracker.ui.theme.LightGray
@Composable
fun CircularProgressBar(
percentage: Float,
fontSize: TextUnit = 20.sp,
radius: Dp = 32.dp,
color: Color = CasualBlue,
strokeWidth: Dp = 8.dp,
animDuration: Int = 2000,
animDelay: Int = 0
) {
val currPercentage = animateFloatAsState(
targetValue = percentage,
animationSpec = tween(
durationMillis = animDuration,
delayMillis = animDelay
)
)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(radius * 2f)
) {
Canvas(
modifier = Modifier.size(radius * 2f)
) {
drawArc(
color = color,
-90f,
360 * currPercentage.value,
useCenter = false,
style = Stroke(strokeWidth.toPx(), cap = StrokeCap.Round)
)
}
Text(
text = (currPercentage.value * 100).toInt().toString() + "%",
color = LightGray,
fontSize = fontSize,
fontWeight = FontWeight.Bold
)
}
} | 0 | Kotlin | 0 | 0 | 29abd9ef0fb77b41f1888537c9a13bdcabbb0912 | 1,997 | Timestamp-Tracker-Android | MIT License |
src/main/kotlin/pl/org/pablo/slack/money/graph/Model.kt | pablow91 | 110,442,981 | false | null | package pl.org.tosio.slack.money.graph
import org.neo4j.ogm.annotation.*
import java.math.BigDecimal
import java.time.LocalDateTime
import java.util.*
@NodeEntity
data class UserEntity(
var name: String,
@Relationship(type = "PAY", direction = Relationship.OUTGOING) var payed: MutableList<PayRelationship> = arrayListOf(),
@Relationship(type = "PAY", direction = Relationship.INCOMING) var received: MutableList<PayRelationship> = arrayListOf(),
@Relationship(type = "BALANCE", direction = Relationship.OUTGOING) var toPay: MutableList<BalanceRelationship> = arrayListOf(),
@Relationship(type = "BALANCE", direction = Relationship.INCOMING) var toReturn: MutableList<BalanceRelationship> = arrayListOf(),
var id: Long? = null
) {
protected constructor() : this("")
companion object {
val STUB = UserEntity()
}
}
abstract class MoneyRelationship(
@StartNode var payer: UserEntity,
@EndNode var receiver: UserEntity,
@Property var value: BigDecimal,
var id: Long? = null,
@Property var uuid: String = UUID.randomUUID().toString()
) {
protected constructor() : this(UserEntity.STUB, UserEntity.STUB, BigDecimal.ZERO)
}
@RelationshipEntity(type = "PAY")
class PayRelationship(payer: UserEntity,
receiver: UserEntity,
value: BigDecimal,
var description: String? = null,
var date: LocalDateTime = LocalDateTime.now(),
id: Long? = null
) : MoneyRelationship(payer, receiver, value, id) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PayRelationship
if (receiver != other.receiver) return false
if (payer != other.payer) return false
if (description != other.description) return false
if (value != other.value) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
var result = description?.hashCode() ?: 0
result = 31 * result + date.hashCode()
return result
}
}
@RelationshipEntity(type = "BALANCE")
class BalanceRelationship(payer: UserEntity,
receiver: UserEntity,
value: BigDecimal,
id: Long? = null
) : MoneyRelationship(payer, receiver, value, id) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BalanceRelationship
if (receiver != other.receiver) return false
if (payer != other.payer) return false
if (value != other.value) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return javaClass.hashCode()
}
} | 4 | null | 2 | 1 | efde0f75af9286cb65cb9b6f5d0e60632fab9e66 | 2,979 | money-dispatcher | Apache License 2.0 |
src/rider/main/kotlin/me/seclerp/rider/plugins/monogame/mgcb/previewer/properties/MgcbPropertyTable.kt | seclerp | 417,300,695 | false | {"Kotlin": 91656, "C#": 18042, "Lex": 3418, "HLSL": 843} | package me.seclerp.rider.plugins.monogame.mgcb.previewer.properties
import com.intellij.ui.table.TableView
class MgcbPropertyTable(model: MgcbPropertyTableModel) : TableView<MgcbProperty>(model) {
override fun createDefaultTableHeader() = JBTableHeader()
}
| 7 | Kotlin | 1 | 28 | 3221c0d39f857e4398851b0be4a84890036ed010 | 264 | rider-monogame | MIT License |
rest/src/commonMain/kotlin/builder/message/create/ForumMessageCreateBuilder.kt | kordlib | 202,856,399 | false | null | package dev.kord.rest.builder.message.create
import dev.kord.common.annotation.KordPreview
import dev.kord.common.entity.InteractionResponseType
import dev.kord.common.entity.optional.*
import dev.kord.rest.builder.RequestBuilder
import dev.kord.rest.builder.component.MessageComponentBuilder
import dev.kord.rest.builder.message.AllowedMentionsBuilder
import dev.kord.rest.builder.message.EmbedBuilder
import dev.kord.rest.json.request.InteractionApplicationCommandCallbackData
import dev.kord.rest.json.request.InteractionResponseCreateRequest
import dev.kord.rest.json.request.MultipartInteractionResponseCreateRequest
import java.io.InputStream
/**
* Message builder for publicly responding to an interaction.
*/
@KordPreview
class PublicInteractionResponseCreateBuilder
: PersistentMessageCreateBuilder,
RequestBuilder<MultipartInteractionResponseCreateRequest> {
override var content: String? = null
override var tts: Boolean? = null
override val embeds: MutableList<EmbedBuilder> = mutableListOf()
override var allowedMentions: AllowedMentionsBuilder? = null
@KordPreview
override val components: MutableList<MessageComponentBuilder> = mutableListOf()
override val files: MutableList<Pair<String, InputStream>> = mutableListOf()
override fun toRequest(): MultipartInteractionResponseCreateRequest {
return MultipartInteractionResponseCreateRequest(
InteractionResponseCreateRequest(
type = InteractionResponseType.ChannelMessageWithSource,
data = Optional(
InteractionApplicationCommandCallbackData(
content = Optional(content).coerceToMissing(),
tts = Optional(tts).coerceToMissing().toPrimitive(),
embeds = Optional(embeds).mapList { it.toRequest() },
allowedMentions = Optional(allowedMentions).coerceToMissing().map { it.build() },
components = Optional(components).coerceToMissing().mapList { it.build() },
)
)
),
Optional(files)
)
}
}
| 54 | null | 74 | 781 | 29a904b330c592799c29381e7cfa9fe99f8e9dc0 | 2,164 | kord | MIT License |
idea/tests/testData/inspectionsLocal/convertNaNEquality/inequality.kt | JetBrains | 278,369,660 | false | null | // WITH_RUNTIME
fun main() {
val result = 5.0 + 3.0 <caret>!= Double.NaN;
}
| 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 80 | intellij-kotlin | Apache License 2.0 |
app/src/test/java/com/rafaelfelipeac/improov/features/backup/domain/usecase/ExportDatabaseUseCaseTest.kt | rafaelfelipeac | 160,363,382 | false | null | package com.rafaelfelipeac.improov.features.backup.domain.usecase
import com.rafaelfelipeac.improov.base.DataProviderTest
import com.rafaelfelipeac.improov.base.DataProviderTest.createJson
import com.rafaelfelipeac.improov.base.equalTo
import com.rafaelfelipeac.improov.features.backup.domain.repository.DatabaseRepository
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.BDDMockito.given
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class ExportDatabaseUseCaseTest {
@Mock
internal lateinit var mockDatabaseRepository: DatabaseRepository
private lateinit var exportDatabaseUseCase: ExportDatabaseUseCase
@Before
fun setup() {
exportDatabaseUseCase = ExportDatabaseUseCase(mockDatabaseRepository)
}
@Test
fun `GIVEN information in Dao and Preferences WHEN exportDatabaseUseCase is called THEN return a json`() {
runBlocking {
// given
val goals = listOf(DataProviderTest.createGoalDataModel())
val historics = listOf(DataProviderTest.createHistoricDataModel())
val items = listOf(DataProviderTest.createItemDataModel())
val language = ""
val welcome = false
val name = ""
val firstTimeAdd = false
val firstTimeList = false
val json = createJson(
goals,
historics,
items,
language,
welcome,
name,
firstTimeAdd,
firstTimeList
)
given(mockDatabaseRepository.export())
.willReturn(json)
// when
val result = exportDatabaseUseCase()
// then
result equalTo json
}
}
}
| 1 | Kotlin | 3 | 22 | 6ff4d515f0968a0752817ef4d942f1b3f424611c | 1,913 | improov | Apache License 2.0 |
app/src/main/java/com/umaplasticsfsm/features/leaveapplynew/ClickonStatus.kt | DebashisINT | 740,356,583 | false | {"Kotlin": 13950763, "Java": 1000924} | package com.umaplasticsfsm.features.leaveapplynew
import com.umaplasticsfsm.features.addAttendence.model.Leave_list_Response
interface ClickonStatus {
fun OnApprovedclick(obj: Leave_list_Response)
fun OnRejectclick(obj: Leave_list_Response)
} | 0 | Kotlin | 0 | 0 | 2ccc871bdcf7df2d08825d0b9ded73b11495519e | 253 | UmaPlastics | Apache License 2.0 |
plugins/graphql-kotlin-gradle-plugin/src/main/kotlin/com/expediagroup/graphql/plugin/gradle/GraphQLPluginExtension.kt | ExpediaGroup | 148,706,161 | false | null | /*
* Copyright 2021 Expedia, 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
*
* 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.expediagroup.graphql.plugin.gradle
import com.expediagroup.graphql.plugin.gradle.config.GraphQLScalar
import com.expediagroup.graphql.plugin.gradle.config.GraphQLSerializer
import com.expediagroup.graphql.plugin.gradle.config.TimeoutConfiguration
import org.gradle.api.Action
import java.io.File
/**
* GraphQL Kotlin Gradle Plugin extension.
*/
@Suppress("UnstableApiUsage")
open class GraphQLPluginExtension {
private var clientExtensionConfigured: Boolean = false
internal val clientExtension: GraphQLPluginClientExtension by lazy {
clientExtensionConfigured = true
GraphQLPluginClientExtension()
}
private var schemaExtensionConfigured: Boolean = false
internal val schemaExtension: GraphQLPluginSchemaExtension by lazy {
schemaExtensionConfigured = true
GraphQLPluginSchemaExtension()
}
/** Plugin configuration for generating GraphQL client. */
fun client(action: Action<GraphQLPluginClientExtension>) {
action.execute(clientExtension)
}
internal fun isClientConfigurationAvailable(): Boolean = clientExtensionConfigured
internal fun isSchemaConfigurationAvailable(): Boolean = schemaExtensionConfigured
/** Plugin configuration for generating GraphQL schema artifact. */
fun schema(action: Action<GraphQLPluginSchemaExtension>) {
action.execute(schemaExtension)
}
}
open class GraphQLPluginClientExtension {
/** GraphQL server endpoint that will be used to for running introspection queries. Alternatively you can download schema directly from [sdlEndpoint] or specify local [schemaFile]. */
var endpoint: String? = null
/** GraphQL server SDL endpoint that will be used to download schema. Alternatively you can run introspection query against [endpoint] or specify local [schemaFile]. */
var sdlEndpoint: String? = null
/** GraphQL schema file. Can be used instead of [endpoint] or [sdlEndpoint]. */
var schemaFile: File? = null
/** Target package name to be used for generated classes. */
var packageName: String? = null
/** Optional HTTP headers to be specified on an introspection query or SDL request. */
var headers: Map<String, Any> = emptyMap()
/** Boolean flag indicating whether or not selection of deprecated fields is allowed. */
var allowDeprecatedFields: Boolean = false
/** List of custom GraphQL scalar to converter mapping containing information about corresponding Java type and converter that should be used to serialize/deserialize values. */
var customScalars: List<GraphQLScalar> = emptyList()
/** List of query files to be processed. */
var queryFiles: List<File> = emptyList()
/** Directory containing GraphQL query files. */
var queryFileDirectory: String? = null
/** JSON serializer that will be used to generate the data classes. */
var serializer: GraphQLSerializer = GraphQLSerializer.JACKSON
/** Opt-in flag to wrap nullable arguments in OptionalInput that supports both null and undefined. Only supported for JACKSON serializer. */
var useOptionalInputWrapper: Boolean = false
/** Connect and read timeout configuration for executing introspection query/download schema */
internal val timeoutConfig: TimeoutConfiguration = TimeoutConfiguration()
fun timeout(action: Action<TimeoutConfiguration>) {
action.execute(timeoutConfig)
}
}
open class GraphQLPluginSchemaExtension {
/** List of supported packages that can contain GraphQL schema type definitions. */
var packages: List<String> = emptyList()
}
| 68 | null | 345 | 1,739 | d3ad96077fc6d02471f996ef34c67066145acb15 | 4,187 | graphql-kotlin | Apache License 2.0 |
aaper/src/main/java/com/likethesalad/android/aaper/errors/AaperNotInitializedException.kt | LikeTheSalad | 289,293,129 | false | {"Kotlin": 130235, "Java": 1063, "Shell": 88} | package com.likethesalad.android.aaper.errors
import com.likethesalad.android.aaper.api.errors.AaperException
/**
* This exception is thrown when an attempt to access Aaper is made before initializing it.
*/
class AaperNotInitializedException
: AaperException(
"Aaper is not initialized. You must call Aaper.initialize before performing this operation",
null
) | 0 | Kotlin | 9 | 219 | 8f2c88bb4272b0cb276eb006100f8ec17b70bebf | 376 | aaper | MIT License |
base/src/main/java/com/surrus/galwaybus/di/ApplicationModule.kt | chanyaz | 125,964,728 | true | {"Kotlin": 114008, "Java": 73173, "GLSL": 9264, "Ruby": 3132} | package com.surrus.galwaybus.di
import android.app.Application
import android.arch.persistence.room.Room
import android.content.Context
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import com.surrus.galwaybus.cache.GalwayBusCacheImpl
import com.surrus.galwaybus.cache.PreferencesHelper
import com.surrus.galwaybus.cache.db.GalwayBusDatabase
import com.surrus.galwaybus.data.GalwayBusDataRepository
import com.surrus.galwaybus.data.repository.GalwayBusCache
import com.surrus.galwaybus.data.repository.GalwayBusRemote
import com.surrus.galwaybus.data.source.GalwayBusDataStoreFactory
import com.surrus.galwaybus.di.scopes.PerApplication
import com.surrus.galwaybus.domain.executor.ExecutorThread
import com.surrus.galwaybus.domain.executor.PostExecutionThread
import com.surrus.galwaybus.domain.repository.GalwayBusRepository
import com.surrus.galwaybus.remote.GalwayBusRemoteImpl
import com.surrus.galwaybus.remote.GalwayBusService
import com.surrus.galwaybus.ui.UiThread
import dagger.Module
import dagger.Provides
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.buffer.android.boilerplate.data.executor.JobExecutorThread
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit
@Module
open class ApplicationModule {
@Provides
@PerApplication
fun provideContext(application: Application): Context {
return application
}
@Provides
@PerApplication
internal fun providePreferencesHelper(context: Context): PreferencesHelper {
return PreferencesHelper(context)
}
@Provides
@PerApplication
fun provideOkHttpClient(application: Application): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val cacheDir = File(application.cacheDir, UUID.randomUUID().toString())
// 10MB cache
val cache = Cache(cacheDir, 10 * 1024 * 1024)
return OkHttpClient.Builder()
.cache(cache)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.addNetworkInterceptor( StethoInterceptor())
.build()
}
@Provides
@PerApplication
internal fun provideGalwayBusService(okHttpClient: OkHttpClient) : GalwayBusService {
val gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ")
.create()
val retrofit = Retrofit.Builder()
.baseUrl("http://galwaybus.herokuapp.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
return retrofit.create(GalwayBusService::class.java)
}
@Provides
@PerApplication
internal fun provideGalwayBusRepository(factory: GalwayBusDataStoreFactory): GalwayBusRepository {
return GalwayBusDataRepository(factory)
}
@Provides
@PerApplication
internal fun provideGalwayBusCache(database: GalwayBusDatabase, preferencesHelper: PreferencesHelper): GalwayBusCache {
return GalwayBusCacheImpl(database, preferencesHelper)
}
@Provides
@PerApplication
internal fun provideGalwayBusRemote(galwayBusService: GalwayBusService): GalwayBusRemote {
return GalwayBusRemoteImpl(galwayBusService)
}
@Provides
@PerApplication
internal fun provideThreadExecutor(jobExecutor: JobExecutorThread): ExecutorThread {
return jobExecutor
}
@Provides
@PerApplication
internal fun providePostExecutionThread(uiThread: UiThread): PostExecutionThread {
return uiThread
}
@Provides
@PerApplication
internal fun provideGalwayBusDatabase(application: Application): GalwayBusDatabase {
return Room.databaseBuilder(application.applicationContext,
GalwayBusDatabase::class.java, "galway_bus.db")
.fallbackToDestructiveMigration()
.build()
}
} | 0 | Kotlin | 0 | 0 | 18b0ddc9755886ca05a7437df29a8ddaa75ab927 | 4,526 | galway-bus-android | MIT License |
ynab-api/src/main/kotlin/com/youneedabudget/client/models/Account.kt | ryanmoelter | 270,082,440 | false | null | /**
* NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: YNAB API Endpoints
*
* More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen
*/
package com.youneedabudget.client.models
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.util.UUID
/**
* @property id
* @property name
* @property type The type of account. Note: payPal, merchantAccount, investmentAccount, and mortgage types have been deprecated and will be removed in the future.
* @property onBudget Whether this account is on budget or not
* @property closed Whether this account is closed or not
* @property note
* @property balance The current balance of the account in milliunits format
* @property clearedBalance The current cleared balance of the account in milliunits format
* @property unclearedBalance The current uncleared balance of the account in milliunits format
* @property transferPayeeId The payee id which should be used when transferring to this account
* @property deleted Whether or not the account has been deleted. Deleted accounts will only be included in delta requests.
*/
@JsonClass(generateAdapter = true)
data class Account(
@Json(name = "id") @field:Json(name = "id") var id: UUID,
@Json(name = "name") @field:Json(name = "name") var name: String,
@Json(name = "type") @field:Json(name = "type") var type: Account.TypeEnum,
@Json(name = "on_budget") @field:Json(name = "on_budget") var onBudget: Boolean,
@Json(name = "closed") @field:Json(name = "closed") var closed: Boolean,
@Json(name = "balance") @field:Json(name = "balance") var balance: Long,
@Json(name = "cleared_balance") @field:Json(name = "cleared_balance") var clearedBalance: Long,
@Json(name = "uncleared_balance") @field:Json(name = "uncleared_balance") var unclearedBalance: Long,
@Json(name = "transfer_payee_id") @field:Json(name = "transfer_payee_id") var transferPayeeId: UUID,
@Json(name = "deleted") @field:Json(name = "deleted") var deleted: Boolean,
@Json(name = "note") @field:Json(name = "note") var note: String? = null
) {
/**
* The type of account. Note: payPal, merchantAccount, investmentAccount, and mortgage types have been deprecated and will be removed in the future.
* Values: CHECKING, SAVINGS, CASH, CREDITCARD, LINEOFCREDIT, OTHERASSET, OTHERLIABILITY, PAYPAL, MERCHANTACCOUNT, INVESTMENTACCOUNT, MORTGAGE
*/
@JsonClass(generateAdapter = false)
enum class TypeEnum(val value: String) {
@Json(name = "checking") CHECKING("checking"),
@Json(name = "savings") SAVINGS("savings"),
@Json(name = "cash") CASH("cash"),
@Json(name = "creditCard") CREDITCARD("creditCard"),
@Json(name = "lineOfCredit") LINEOFCREDIT("lineOfCredit"),
@Json(name = "otherAsset") OTHERASSET("otherAsset"),
@Json(name = "otherLiability") OTHERLIABILITY("otherLiability"),
@Json(name = "payPal") PAYPAL("payPal"),
@Json(name = "merchantAccount") MERCHANTACCOUNT("merchantAccount"),
@Json(name = "investmentAccount") INVESTMENTACCOUNT("investmentAccount"),
@Json(name = "mortgage") MORTGAGE("mortgage")
}
}
| 2 | Kotlin | 0 | 2 | d2fdc47362272bdd57b0a3c2667c42ce749f9c5e | 3,235 | splity | Apache License 2.0 |
core/domain/common/src/main/java/com/goalpanzi/mission_mate/core/domain/common/DomainResult.kt | Nexters | 828,096,097 | false | {"Kotlin": 469213, "Ruby": 1219} | package com.goalpanzi.mission_mate.core.domain.common
sealed interface DomainResult<out T> {
data class Success<out T>(val data: T) :
DomainResult<T>
data class Error(val code: Int? = null, val message: String? = null) :
DomainResult<Nothing>
data class Exception(val error: Throwable) :
DomainResult<Nothing>
}
fun <T,R> DomainResult<T>.convert(
convert : (T) -> R
) : DomainResult<R> {
return when(this){
is DomainResult.Success -> {
DomainResult.Success(convert(this.data))
}
is DomainResult.Error -> {
DomainResult.Error(code = this.code, message = this.message)
}
is DomainResult.Exception -> {
DomainResult.Exception(error = this.error)
}
}
}
| 1 | Kotlin | 0 | 3 | 912bebd2706d1206f38c910e85c79fece73e4213 | 783 | goalpanzi-android | Apache License 2.0 |
client/src/main/kotlin/com/configset/client/converter/Converters.kt | raymank26 | 296,910,120 | false | null | package com.configset.client.converter
import java.util.Properties
object Converters {
val STRING = GenericConverter { it }
val LONG = GenericConverter { it.toLong() }
val INTEGER = GenericConverter { it.toInt() }
val BOOLEAN = GenericConverter { it.toBoolean() }
val CHAR = GenericConverter { str ->
require(str.length == 1)
str.first()
}
val BYTE = GenericConverter { str -> str.toByte() }
val DOUBLE = GenericConverter { it.toDouble() }
val SHORT = GenericConverter { it.toShort() }
val PROPERTIES: Converter<Properties> = PropertiesConverter()
val LIST_STRING: Converter<List<String>> = listConverter(STRING)
val LIST_LONG: Converter<List<Long>> = listConverter(LONG)
}
fun <T> listConverter(itemConverter: Converter<T>, delimiters: Array<String> = arrayOf(",")): Converter<List<T>> {
return CollectionConverter(itemConverter, { it.toList() }, delimiters)
}
fun <T, P> Converter<T>.map(mapper: (T) -> P): Converter<P> {
val that = this
return object : Converter<P> {
override fun convert(value: String): P {
return mapper.invoke(that.convert(value))
}
}
}
| 0 | null | 0 | 1 | bf54c361628a207a219afd6772ac2e4b6ffefbcb | 1,172 | configset | Apache License 2.0 |
compose/ui/ui-test/src/androidInstrumentedTest/kotlin/androidx/compose/ui/test/injectionscope/mouse/MoveTest.kt | androidx | 256,589,781 | false | {"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019} | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test.injectionscope.mouse
import androidx.compose.testutils.expectError
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventType.Companion.Enter
import androidx.compose.ui.input.pointer.PointerEventType.Companion.Exit
import androidx.compose.ui.input.pointer.PointerEventType.Companion.Move
import androidx.compose.ui.input.pointer.PointerEventType.Companion.Press
import androidx.compose.ui.test.InputDispatcher
import androidx.compose.ui.test.MouseButton
import androidx.compose.ui.test.MouseInjectionScope
import androidx.compose.ui.test.animateMoveAlong
import androidx.compose.ui.test.animateMoveBy
import androidx.compose.ui.test.animateMoveTo
import androidx.compose.ui.test.injectionscope.mouse.Common.PrimaryButton
import androidx.compose.ui.test.injectionscope.mouse.Common.runMouseInputInjectionTest
import androidx.compose.ui.test.injectionscope.mouse.Common.verifyMouseEvent
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
@Suppress("KotlinConstantConditions") // for "0 * T"
class MoveTest {
companion object {
private val T = InputDispatcher.eventPeriodMillis
private val positionIn = Offset(1f, 1f)
private val positionMove1 = Offset(2f, 2f)
private val positionMove2 = Offset(3f, 3f)
private val positionOut = Offset(101f, 101f)
// For testing the animated movement methods:
private val steps = 4
private val distancePerStep = Offset(5f, 5f)
private val distance = distancePerStep * steps.toFloat()
private val position1 = Offset.Zero + distance
private val position2 = Offset(1f, 1f)
private val curveFromHere = { t: Long -> Offset(t.toFloat(), t.toFloat()) }
private val curveFromElsewhere = { t: Long -> Offset(1f + t.toFloat(), 1f + t.toFloat()) }
}
@Test
fun moveTo() =
runMouseInputInjectionTest(
mouseInput = {
// enter the box
moveToAndCheck(positionIn, delayMillis = 0L)
// move around the box
moveToAndCheck(positionMove1)
// move around the box with long delay
moveToAndCheck(positionMove2, delayMillis = 2 * eventPeriodMillis)
// exit the box
moveToAndCheck(positionOut)
// move back in the box
moveToAndCheck(positionIn)
},
eventVerifiers =
arrayOf(
{ verifyMouseEvent(0 * T, Enter, false, positionIn) },
{ verifyMouseEvent(1 * T, Move, false, positionMove1) },
{ verifyMouseEvent(3 * T, Move, false, positionMove2) },
{ verifyMouseEvent(4 * T, Exit, false, positionOut) },
{ verifyMouseEvent(5 * T, Enter, false, positionIn) },
)
)
@Test
fun moveBy() =
runMouseInputInjectionTest(
mouseInput = {
// enter the box
moveByAndCheck(positionIn, delayMillis = 0L)
// move around the box
moveByAndCheck(positionMove1 - positionIn)
// move around the box with long delay
moveByAndCheck(positionMove2 - positionMove1, delayMillis = 2 * eventPeriodMillis)
// exit the box
moveByAndCheck(positionOut - positionMove2)
// move back in the box
moveByAndCheck(positionIn - positionOut)
},
eventVerifiers =
arrayOf(
{ verifyMouseEvent(0 * T, Enter, false, positionIn) },
{ verifyMouseEvent(1 * T, Move, false, positionMove1) },
{ verifyMouseEvent(3 * T, Move, false, positionMove2) },
{ verifyMouseEvent(4 * T, Exit, false, positionOut) },
{ verifyMouseEvent(5 * T, Enter, false, positionIn) },
)
)
@Test
fun updatePointerTo() =
runMouseInputInjectionTest(
mouseInput = {
// move around
updatePointerToAndCheck(positionIn)
updatePointerToAndCheck(positionMove1)
updatePointerToAndCheck(positionMove2)
// press primary button
press(MouseButton.Primary)
},
eventVerifiers =
arrayOf(
{ verifyMouseEvent(0, Enter, false, positionMove2) },
{ verifyMouseEvent(0, Press, true, positionMove2, PrimaryButton) },
)
)
@Test
fun updatePointerBy() =
runMouseInputInjectionTest(
mouseInput = {
// move around
updatePointerByAndCheck(positionIn)
updatePointerByAndCheck(positionMove1 - positionIn)
updatePointerByAndCheck(positionMove2 - positionMove1)
// press primary button
press(MouseButton.Primary)
},
eventVerifiers =
arrayOf(
{ verifyMouseEvent(0, Enter, false, positionMove2) },
{ verifyMouseEvent(0, Press, true, positionMove2, PrimaryButton) },
)
)
@Test
fun enter_exit() =
runMouseInputInjectionTest(
mouseInput = {
// enter the box
enter(positionIn)
// move around the box
moveTo(positionMove1)
// exit the box
exit(positionOut)
},
eventVerifiers =
arrayOf(
{ verifyMouseEvent(1 * T, Enter, false, positionIn) },
{ verifyMouseEvent(2 * T, Move, false, positionMove1) },
{ verifyMouseEvent(3 * T, Exit, false, positionOut) },
)
)
@Test
fun enter_alreadyEntered() =
runMouseInputInjectionTest(
mouseInput = {
// enter the box
enter(positionIn)
// enter again
expectError<IllegalStateException>(
expectedMessage =
"Cannot send mouse hover enter event, mouse is already hovering"
) {
enter(positionMove1)
}
},
eventVerifiers =
arrayOf(
{ verifyMouseEvent(1 * T, Enter, false, positionIn) },
)
)
@Test
fun exit_notEntered() =
runMouseInputInjectionTest(
mouseInput = {
// exit the box
expectError<IllegalStateException>(
expectedMessage = "Cannot send mouse hover exit event, mouse is not hovering"
) {
exit(positionOut)
}
}
)
@Test
fun animatePointerTo() =
runMouseInputInjectionTest(
mouseInput = { animateMoveTo(position1, durationMillis = steps * T) },
eventVerifiers =
arrayOf(
{ verifyMouseEvent(1 * T, Enter, false, distancePerStep * 1f) },
{ verifyMouseEvent(2 * T, Move, false, distancePerStep * 2f) },
{ verifyMouseEvent(3 * T, Move, false, distancePerStep * 3f) },
{ verifyMouseEvent(4 * T, Move, false, distancePerStep * 4f) },
)
)
@Test
fun animatePointerBy() =
runMouseInputInjectionTest(
mouseInput = {
moveTo(position2)
animateMoveBy(distance, durationMillis = steps * T)
},
eventVerifiers =
arrayOf(
{ verifyMouseEvent(1 * T, Enter, false, position2) },
{ verifyMouseEvent(2 * T, Move, false, position2 + (distancePerStep * 1f)) },
{ verifyMouseEvent(3 * T, Move, false, position2 + (distancePerStep * 2f)) },
{ verifyMouseEvent(4 * T, Move, false, position2 + (distancePerStep * 3f)) },
{ verifyMouseEvent(5 * T, Move, false, position2 + (distancePerStep * 4f)) },
)
)
@Test
fun animateAlong_fromCurrentPosition() =
runMouseInputInjectionTest(
mouseInput = { animateMoveAlong(curveFromHere, durationMillis = steps * T) },
eventVerifiers =
arrayOf(
// The curve starts at the current position (0, 0) so we expect no initial
// event.
{ verifyMouseEvent(1 * T, Enter, false, curveFromHere(1 * T)) },
{ verifyMouseEvent(2 * T, Move, false, curveFromHere(2 * T)) },
{ verifyMouseEvent(3 * T, Move, false, curveFromHere(3 * T)) },
{ verifyMouseEvent(4 * T, Move, false, curveFromHere(4 * T)) },
)
)
@Test
fun animateAlong_fromOtherPosition() =
runMouseInputInjectionTest(
mouseInput = { animateMoveAlong(curveFromElsewhere, durationMillis = steps * T) },
eventVerifiers =
arrayOf(
// The curve doesn't start at the current position (0, 0) so we expect an
// initial event
{ verifyMouseEvent(0 * T, Enter, false, curveFromElsewhere(0 * T)) },
{ verifyMouseEvent(1 * T, Move, false, curveFromElsewhere(1 * T)) },
{ verifyMouseEvent(2 * T, Move, false, curveFromElsewhere(2 * T)) },
{ verifyMouseEvent(3 * T, Move, false, curveFromElsewhere(3 * T)) },
{ verifyMouseEvent(4 * T, Move, false, curveFromElsewhere(4 * T)) },
)
)
private fun MouseInjectionScope.moveToAndCheck(
position: Offset,
delayMillis: Long = eventPeriodMillis
) {
moveTo(position, delayMillis)
assertThat(currentPosition).isEqualTo(position)
}
private fun MouseInjectionScope.moveByAndCheck(
delta: Offset,
delayMillis: Long = eventPeriodMillis
) {
val expectedPosition = currentPosition + delta
moveBy(delta, delayMillis)
assertThat(currentPosition).isEqualTo(expectedPosition)
}
private fun MouseInjectionScope.updatePointerToAndCheck(position: Offset) {
updatePointerTo(position)
assertThat(currentPosition).isEqualTo(position)
}
private fun MouseInjectionScope.updatePointerByAndCheck(delta: Offset) {
val expectedPosition = currentPosition + delta
updatePointerBy(delta)
assertThat(currentPosition).isEqualTo(expectedPosition)
}
}
| 30 | Kotlin | 950 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 11,619 | androidx | Apache License 2.0 |
app/src/main/kotlin/com/j380/alarm/battery/BatteryBroadcastReceiver.kt | Ilya-Gh | 57,147,267 | false | null | package com.j380.alarm.battery
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.j380.alarm.battery.BatteryService
class BatteryBroadcastReceiver : BroadcastReceiver () {
override fun onReceive(context: Context, intent: Intent?) {
val startServiceIntent = Intent(context, BatteryService::class.java)
context.startService(startServiceIntent)
}
} | 0 | Kotlin | 0 | 1 | 1c4993a840c746171e452a5e4d20186e979eeb18 | 434 | BatteryReminder | MIT License |
app/src/main/kotlin/com/j380/alarm/battery/BatteryBroadcastReceiver.kt | Ilya-Gh | 57,147,267 | false | null | package com.j380.alarm.battery
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.j380.alarm.battery.BatteryService
class BatteryBroadcastReceiver : BroadcastReceiver () {
override fun onReceive(context: Context, intent: Intent?) {
val startServiceIntent = Intent(context, BatteryService::class.java)
context.startService(startServiceIntent)
}
} | 0 | Kotlin | 0 | 1 | 1c4993a840c746171e452a5e4d20186e979eeb18 | 434 | BatteryReminder | MIT License |
service/src/main/kotlin/net/devslash/outputs/DebugOutput.kt | devslash-paul | 152,959,898 | false | null | package net.devslash.outputs
import net.devslash.HttpResponse
import net.devslash.OutputFormat
import net.devslash.RequestData
import net.devslash.mustGet
class DebugOutput : OutputFormat {
override fun accept(resp: HttpResponse, data: RequestData<*>): ByteArray {
return """
----------------
url: ${resp.uri}
status: ${resp.statusCode}
headers: [${resp.headers}]
data: ${data.mustGet<Any?>()}
body ->
${String(resp.body)}
----------------
""".trimIndent().toByteArray()
}
}
| 9 | null | 2 | 9 | 9346d497282869958f913bb84459921f53e3288e | 608 | fetchDSL | MIT License |
architecture/kmm-tagd-arch/kmm-tagd-arch-test/src/commonMain/kotlin/io/tagd/arch/test/FakeInjector.kt | pavan2you | 589,617,975 | false | null | /*
* Copyright (C) 2021 The TagD 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 io.tagd.arch.test
import io.tagd.arch.domain.crosscutting.CrossCutting
import io.tagd.arch.domain.crosscutting.async.*
import io.tagd.core.Releasable
import io.tagd.di.Global
import io.tagd.di.layer
class FakeInjector : Releasable {
fun inject() {
with(Global) {
injectCrossCuttings()
}
}
private fun Global.injectCrossCuttings() {
// global - cross cuttings
layer<CrossCutting> {
//platform
val testStrategy = FakeAsyncStrategy()
bind<PresentationStrategy>().toInstance(testStrategy)
bind<ComputationStrategy>().toInstance(testStrategy)
bind<ComputeIOStrategy>().toInstance(testStrategy)
bind<NetworkIOStrategy>().toInstance(testStrategy)
bind<DiskIOStrategy>().toInstance(testStrategy)
bind<DaoIOStrategy>().toInstance(testStrategy)
bind<CacheIOStrategy>().toInstance(testStrategy)
}
}
override fun release() {
Global.reset()
}
companion object {
private var active: FakeInjector? = null
fun inject(): FakeInjector {
release()
active = FakeInjector().apply { inject() }
return active!!
}
fun release() {
active?.release()
}
}
} | 3 | null | 3 | 2 | dd2aaf1e4f20850f31b7024f7f8e4bd33f467f3d | 1,957 | kmm-clean-architecture | Apache License 2.0 |
app/src/main/java/com/apisap/demopersistentservice/DemoServiceApplication.kt | AguilasBuildingCode | 822,727,817 | false | {"Kotlin": 64862} | package com.apisap.demopersistentservice
import com.apisap.persistentservice.PersistentServiceApplication
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class DemoServiceApplication : PersistentServiceApplication() {
override val notificationChannelId: String by lazy { resources.getString(R.string.notification_channel_id) }
override val notificationChannelName: String by lazy { resources.getString(R.string.notification_channel_name) }
override val notificationChannelDescription: String by lazy { resources.getString(R.string.notification_channel_description) }
} | 0 | Kotlin | 0 | 0 | 5931b3e6993eb9688efb2c9776146eb8c7986e3f | 594 | DemoPersistentService | MIT License |
database/src/commonMain/kotlin/uk/co/sentinelweb/cuer/db/mapper/PlaylistItemMapper.kt | sentinelweb | 220,796,368 | false | null | package uk.co.sentinelweb.cuer.db.mapper
import uk.co.sentinelweb.cuer.database.entity.Playlist_item
import uk.co.sentinelweb.cuer.domain.MediaDomain
import uk.co.sentinelweb.cuer.domain.PlaylistItemDomain
import uk.co.sentinelweb.cuer.domain.PlaylistItemDomain.Companion.FLAG_ARCHIVED
import uk.co.sentinelweb.cuer.domain.ext.hasFlag
class PlaylistItemMapper {
fun map(entity: Playlist_item, mediaDomain: MediaDomain) = PlaylistItemDomain(
id = entity.id,
media = mediaDomain,
dateAdded = entity.date_added,
order = entity.ordering,
archived = entity.flags.hasFlag(FLAG_ARCHIVED),
playlistId = entity.playlist_id
)
fun map(domain: PlaylistItemDomain) = Playlist_item(
id = domain.id ?: 0,
flags = mapFlags(domain),
media_id = domain.media.id ?: throw IllegalArgumentException("No media id"),
ordering = domain.order,
playlist_id = domain.playlistId ?: throw IllegalArgumentException("No playlist id"),
date_added = domain.dateAdded
)
private fun mapFlags(domain: PlaylistItemDomain): Long =
(if (domain.archived) FLAG_ARCHIVED else 0)
} | 82 | Kotlin | 0 | 2 | cd5b28c720c08c9b718f904421b0580e6b716ec0 | 1,165 | cuer | Apache License 2.0 |
app/src/main/kotlin/com/pusher/chatkitdemo/room/RoomFragment.kt | KingIdee | 135,069,008 | true | {"Kotlin": 43052} | package com.pusher.chatkitdemo.room
import android.arch.lifecycle.Lifecycle.State.STARTED
import android.arch.lifecycle.LifecycleOwner
import android.os.Bundle
import android.os.Looper
import android.support.annotation.UiThread
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.pusher.chatkit.*
import com.pusher.chatkitdemo.R
import com.pusher.chatkitdemo.app
import com.pusher.chatkitdemo.navigation.NavigationEvent
import com.pusher.chatkitdemo.navigation.failNavigation
import com.pusher.chatkitdemo.navigation.navigationEvent
import com.pusher.chatkitdemo.recyclerview.dataAdapterFor
import com.pusher.chatkitdemo.showOnly
import kotlinx.android.synthetic.main.fragment_room.*
import kotlinx.android.synthetic.main.fragment_room_loaded.*
import kotlinx.android.synthetic.main.include_error.*
import kotlinx.android.synthetic.main.item_message.*
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import com.pusher.chatkitdemo.room.RoomState.*
import kotlinx.coroutines.experimental.Job
import kotlin.properties.Delegates
typealias PusherError = elements.Error
class RoomFragment : Fragment() {
private val views by lazy { arrayOf(idleLayout, loadedLayout, errorLayout) }
private var state by Delegates.observable<RoomState>(RoomState.Initial) { _, _, new ->
new.render()
}
private val adapter = dataAdapterFor<Item> {
on<Item.Loaded>(R.layout.item_message) { (details) ->
userNameView.text = details.userName
messageView.text = details.message
}
on<Item.Pending>(R.layout.item_message_pending) { (details) ->
userNameView.text = details.userName
messageView.text = details.message
}
on<Item.Failed>(R.layout.item_message_pending) { (details, error) ->
userNameView.text = details.userName
messageView.text = details.message
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_room, container, false)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity?.apply {
val event = activity!!.intent.navigationEvent
when (event) {
is NavigationEvent.Room -> bind(event.roomId)
else -> activity!!.failNavigation(event)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(view) {
messageList.adapter = adapter
messageList.layoutManager = LinearLayoutManager(activity).apply {
reverseLayout = true
}
sendButton.setOnClickListener {
messageInput.text.takeIf { it.isNotBlank() }?.let { text ->
state.let { it as? Ready }?.let { it.room.id }?.let { roomId ->
senMessage(roomId, text)
}
}
}
}
}
private fun senMessage(roomId: Int, text: CharSequence) = launch {
app.currentUser().apply {
val item = Item.Pending(Item.Details(id, text))
addItem(item)
sendMessage(
roomId = roomId,
text = text.toString(),
attachment = null,
onCompleteListener = MessageSentListener {
removeItem(item)
addItem(item.details.let { (userName, message) ->
Item.Loaded(Item.Details(userName, message))
})
},
onErrorListener = ErrorListener { error ->
removeItem(item)
addItem(item.details.let { (userName, message) ->
Item.Failed(Item.Details(userName, message), error)
})
}
)
}
}
fun bind(roomId: Int) = launch {
if(Looper.myLooper() == null)Looper.prepare() // Old version of the SDK uses a handle and breaks
with(app.currentUser()) {
val room = getRoom(roomId)
when (room) {
null -> renderFailed(Error("Room not found"))
else -> subscribeToRoom(room, messageLimit = 20, listeners = object : RoomSubscriptionListeners {
override fun onError(error: PusherError) {
state = RoomState.Failed(error)
}
override fun onNewMessage(message: Message) {
addItem(Item.Loaded(Item.Details(message.user?.name ?: "???", message.text ?: "---")))
}
})
}
}
}
private fun addItem(item: Item) = launchOnUi {
adapter.data = adapter.data + item
}
private fun removeItem(item: Item) = launchOnUi {
adapter.data = adapter.data - item
}
private fun RoomState.render(): Job = when (this) {
is Initial -> renderIdle()
is Idle -> renderIdle()
is NoMembership -> renderNoMembership()
is RoomLoaded -> renderLoadedRoom(room)
is Ready -> renderLoadedCompletely(room, items)
is Failed -> renderFailed(Error("$error"))
}
@UiThread
private fun renderIdle() = launchOnUi {
views.showOnly(idleLayout)
adapter.data = emptyList()
}
private fun renderLoadedRoom(room: Room) = launchOnUi {
views.showOnly(loadedLayout)
activity?.title = room.coolName
}
private fun renderLoadedCompletely(room: Room, messages: List<RoomState.Item>) = launchOnUi {
views.showOnly(loadedLayout)
activity?.title = room.coolName
adapter.data = messages
}
private fun renderFailed(error: Error) = launchOnUi {
views.showOnly(errorLayout)
errorMessageView.text = error.message
retryButton.visibility = View.GONE // TODO: Retry button
}
private fun renderNoMembership() =
renderIdle()
}
private fun LifecycleOwner.launchOnUi(block: suspend CoroutineScope.() -> Unit) = when {
lifecycle.currentState > STARTED -> launch(context = UI, block = block)
else -> launch { Log.d("Boo", "Unexpected lifecycle state: ${lifecycle.currentState}") }
}
sealed class RoomState {
object Initial : RoomState()
data class Idle(val roomId: Int) : RoomState()
data class NoMembership(val room: Room) : RoomState()
data class RoomLoaded(val room: Room) : RoomState()
data class Ready(val room: Room, val items: List<Item>) : RoomState()
data class Failed (val error: PusherError) : RoomState()
sealed class Item {
abstract val details: Details
data class Loaded(override val details: Details) : Item()
data class Pending(override val details: Details) : Item()
data class Failed(override val details: Details, val error: PusherError) : Item()
data class Details(val userName: CharSequence, val message: CharSequence)
}
}
| 0 | Kotlin | 0 | 1 | d7f4bacca0db71275b691f56719296e8a225b8a2 | 7,428 | android-slack-clone | MIT License |
turms-client-kotlin/src/main/kotlin/im/turms/client/util/SystemUtil.kt | turms-im | 191,290,973 | false | null | /*
* Copyright (C) 2019 The Turms Project
* https://github.com/turms-im/turms
*
* 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 im.turms.client.util
import im.turms.client.model.proto.constant.DeviceType
/**
* @author James Chen
*/
object SystemUtil {
val isAndroid: Boolean =
try {
Class.forName("android.os.Build")
true
} catch (e: ClassNotFoundException) {
false
}
val deviceType: DeviceType = if (isAndroid) DeviceType.ANDROID else DeviceType.DESKTOP
}
| 535 | null | 267 | 947 | 9cc2b50c3f06a34dfde82e86a3c341e505f64e4e | 1,053 | turms | Apache License 2.0 |
app/src/main/java/com/xda/nachonotch/util/EnvironmentManager.kt | zacharee | 127,220,159 | false | {"Kotlin": 102537, "AIDL": 103} | package com.xda.nachonotch.util
import android.annotation.SuppressLint
import android.content.Context
import java.util.concurrent.ConcurrentHashMap
val Context.environmentManager: EnvironmentManager
get() = EnvironmentManager.getInstance(this)
class EnvironmentManager private constructor(private val context: Context) {
companion object {
@SuppressLint("StaticFieldLeak")
private var instance: EnvironmentManager? = null
fun getInstance(context: Context) : EnvironmentManager {
return instance ?: EnvironmentManager(context.applicationContext ?: context).apply {
instance = this
}
}
}
enum class EnvironmentStatus {
STATUS_IMMERSIVE,
NAV_IMMERSIVE,
LANDSCAPE
}
private val _environmentStatus: ConcurrentHashMap.KeySetView<EnvironmentStatus, Boolean> = ConcurrentHashMap.newKeySet()
fun hasAllStatuses(vararg status: EnvironmentStatus): Boolean {
return status.all { _environmentStatus.contains(it) }
}
fun hasAnyStatuses(vararg status: EnvironmentStatus): Boolean {
return status.any { _environmentStatus.contains(it) }
}
fun addStatus(vararg status: EnvironmentStatus) {
val oldSet = ConcurrentHashMap(_environmentStatus.map)
LoggingBugsnag.leaveBreadcrumb("Adding EnvironmentStatus ${status.contentToString()}")
_environmentStatus.addAll(status.toSet())
mainHandler.post {
if (oldSet.size != _environmentStatus.size) {
context.eventManager.sendEvent(Event.EnvironmentStatusUpdated)
}
}
}
fun removeStatus(vararg status: EnvironmentStatus) {
val oldSet = ConcurrentHashMap(_environmentStatus.map)
LoggingBugsnag.leaveBreadcrumb("Removing EnvironmentStatus ${status.contentToString()}")
_environmentStatus.removeAll(status.toSet())
mainHandler.post {
if (oldSet.size != _environmentStatus.size) {
context.eventManager.sendEvent(Event.EnvironmentStatusUpdated)
}
}
}
} | 4 | Kotlin | 17 | 78 | cbea9323fd43d5f84f39c7999bb2318ddcfedfe1 | 2,108 | NachoNotch | MIT License |
app/src/main/java/com/example/events/ui/di/UiModule.kt | diegoleonds | 369,679,332 | false | null | package com.example.events.ui.di
import com.example.events.ui.viewmodel.EntryViewModel
import com.example.events.ui.viewmodel.EventInfoViewModel
import com.example.events.ui.viewmodel.EventListViewModel
import org.koin.android.viewmodel.dsl.viewModel
import org.koin.dsl.module
val viewModelModule = module {
viewModel { EntryViewModel() }
viewModel { EventListViewModel(get()) }
viewModel { EventInfoViewModel(get()) }
} | 0 | Kotlin | 0 | 0 | d3b906fd44d1fab03bbc9449c218a668258c732d | 435 | Events-App | MIT License |
product-services/src/main/kotlin/com/academy/fourtk/product_services/application/web/controllers/builders/BuildsProducts.kt | Dev-JeanSantos | 812,719,923 | false | {"Kotlin": 68234, "Shell": 728} | package com.academy.fourtk.product_services.application.web.controllers.builders
import com.academy.fourtk.product_services.application.web.controllers.dto.requesties.ProductSavedRequestV1
import com.academy.fourtk.product_services.application.web.controllers.dto.responses.ProductSavedResponseV1
import com.academy.fourtk.product_services.domain.entities.ProductEntity
import java.time.LocalDateTime
object BuildsProducts {
fun buildProductEntity(product: ProductSavedRequestV1) =
ProductEntity(
name = product.name,
description = product.description,
origin = product.origin,
quantity = product.quantity,
createdAt = LocalDateTime.now()
)
fun buildResponse(
productId: String,
message: String,
) = ProductSavedResponseV1(
productId = productId,
message = message
)
} | 0 | Kotlin | 0 | 0 | 89e0407dfdfe28b126b7adb971cece124bef1b82 | 895 | desafio-back | MIT License |
app/src/main/java/cn/wthee/pcrtool/ui/tool/pvp/PvpViewModel.kt | wthee | 277,015,110 | false | null | package cn.wthee.pcrtool.ui.tool.pvp
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.wthee.pcrtool.R
import cn.wthee.pcrtool.data.db.entity.PvpFavoriteData
import cn.wthee.pcrtool.data.db.entity.PvpHistoryData
import cn.wthee.pcrtool.data.db.repository.PvpRepository
import cn.wthee.pcrtool.data.db.repository.UnitRepository
import cn.wthee.pcrtool.data.db.view.PvpCharacterData
import cn.wthee.pcrtool.data.db.view.getIdStr
import cn.wthee.pcrtool.data.model.PvpResultData
import cn.wthee.pcrtool.data.model.ResponseData
import cn.wthee.pcrtool.data.network.ApiRepository
import cn.wthee.pcrtool.ui.MainActivity
import cn.wthee.pcrtool.utils.LogReportUtil
import cn.wthee.pcrtool.utils.ToastUtil
import cn.wthee.pcrtool.utils.calcDate
import cn.wthee.pcrtool.utils.getString
import cn.wthee.pcrtool.utils.getToday
import cn.wthee.pcrtool.utils.second
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import java.util.UUID
import javax.inject.Inject
/**
* 页面状态:竞技场查询
*/
@Immutable
data class PvpUiState(
//所有角色
val allUnitList: List<PvpCharacterData> = emptyList(),
//查询结果
val pvpResult: ResponseData<List<PvpResultData>>? = null,
//收藏信息
val favoritesList: List<PvpFavoriteData> = emptyList(),
//所有收藏信息
val allFavoritesList: List<PvpFavoriteData> = emptyList(),
//历史记录
val historyList: List<PvpHistoryData> = emptyList(),
//最近使用的角色
val recentlyUsedUnitList: List<PvpCharacterData> = emptyList(),
val requesting: Boolean = false,
val idArray: JsonArray? = null
)
/**
* 竞技场 ViewModel
*
* fixme 角色查询时偶现排序错乱问题
* @param pvpRepository
* @param apiRepository
*/
@HiltViewModel
class PvpViewModel @Inject constructor(
private val pvpRepository: PvpRepository,
private val apiRepository: ApiRepository,
private val unitRepository: UnitRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(PvpUiState())
val uiState: StateFlow<PvpUiState> = _uiState.asStateFlow()
init {
getAllCharacter()
getAllFavorites()
getHistory()
}
/**
* 获取收藏信息
*/
private fun getAllFavorites() {
viewModelScope.launch {
val data = pvpRepository.getLiked(MainActivity.regionType.value)
_uiState.update {
it.copy(
allFavoritesList = data
)
}
}
}
/**
* 根据防守队伍 [defs] 获取收藏信息
*/
private fun getFavoritesList(defs: String) {
viewModelScope.launch {
val data = pvpRepository.getLikedList(defs, MainActivity.regionType.value)
_uiState.update {
it.copy(
favoritesList = data
)
}
}
}
/**
* 新增收藏信息
*/
fun insert(data: PvpFavoriteData) {
viewModelScope.launch {
pvpRepository.insert(data)
getAllFavorites()
getFavoritesList(data.defs)
}
}
/**
* 删除收藏信息
*/
fun delete(atks: String, defs: String) {
viewModelScope.launch {
pvpRepository.delete(atks, defs, MainActivity.regionType.value)
getAllFavorites()
getFavoritesList(defs)
}
}
/**
* 获取搜索历史信息
*/
private fun getHistory() {
viewModelScope.launch {
val data = pvpRepository.getHistory(MainActivity.regionType.value, 10)
_uiState.update {
it.copy(
historyList = data
)
}
}
}
/**
* 获取搜索历史信息
*/
private fun getRecentlyUsedUnitList(characterDataList: List<PvpCharacterData>) {
viewModelScope.launch {
try {
val today = getToday()
//获取前60天
val beforeDate = calcDate(today, 60, true)
//仅保存60天数据,删除超过60天的历史数据
pvpRepository.deleteOldHistory(MainActivity.regionType.value, beforeDate)
//删除旧数据后,查询全部数据
val data = pvpRepository.getHistory(MainActivity.regionType.value, Int.MAX_VALUE)
val unitList = arrayListOf<PvpCharacterData>()
val map = hashMapOf<Int, Int>()
//统计数量
data.forEach { pvpData ->
pvpData.getDefIds().forEach { unitId ->
var count = 1
if (map[unitId] != null) {
count = map[unitId]!! + 1
}
map[unitId] = count
}
}
map.forEach {
unitList.add(
PvpCharacterData(
unitId = it.key,
count = it.value
)
)
}
//角色数量限制
val limit = 50
var list = unitList.sortedByDescending { it.count }
if (list.size > limit) {
list = list.subList(0, limit)
}
//处理最近使用角色的站位信息
list.forEach {
it.position =
characterDataList.find { d -> d.unitId == it.unitId }!!.position
}
_uiState.update {
it.copy(
recentlyUsedUnitList = list
)
}
} catch (e: Exception) {
LogReportUtil.upload(
e,
"getRecentlyUsedUnitList#characterDataList:$characterDataList"
)
}
}
}
/**
* 新增搜索信息
*/
fun insert(data: PvpHistoryData) {
viewModelScope.launch {
val preData = pvpRepository.getHistory(MainActivity.regionType.value, 1)
//避免重复插入
if (preData.isNotEmpty()) {
//与上一记录不相同或间隔大于10分钟,插入新记录
if (data.date.second(preData[0].date) > 10 * 60 || data.defs != preData[0].defs) {
pvpRepository.insert(data)
}
} else {
pvpRepository.insert(data)
}
getHistory()
getRecentlyUsedUnitList(_uiState.value.allUnitList)
}
}
/**
* 查询
*/
private fun getPvpData(ids: JsonArray) {
viewModelScope.launch {
if (_uiState.value.pvpResult == null && !_uiState.value.requesting) {
_uiState.update {
it.copy(
requesting = true
)
}
val data = apiRepository.getPvpData(ids)
_uiState.update {
it.copy(
pvpResult = data,
requesting = false,
idArray = ids
)
}
}
}
}
/**
* 重新查询
*/
fun research() {
viewModelScope.launch {
resetResult()
_uiState.value.idArray?.let { getPvpData(it) }
}
}
/**
* 从收藏或历史搜索
*/
fun searchByDefs(defs: List<Int>) {
viewModelScope.launch {
resetResult()
val selectedData = unitRepository.getCharacterByIds(defs).filter { it.position > 0 }
val selectedIds = selectedData as ArrayList<PvpCharacterData>
MainActivity.navViewModel.selectedPvpData.postValue(selectedIds)
searchByCharacterList(selectedIds)
}
}
/**
* 处理数据后搜索
*/
fun searchByCharacterList(characterDataList: ArrayList<PvpCharacterData>? = null) {
viewModelScope.launch {
val list = characterDataList ?: MainActivity.navViewModel.selectedPvpData.value
if (list == null || list.contains(PvpCharacterData())) {
ToastUtil.short(getString(R.string.tip_select_5))
return@launch
}
resetResult()
//加载数据
val defIds = list.getIdStr()
var unSplitDefIds = ""
var isError = false
val idArray = buildJsonArray {
for (sel in list) {
if (sel.unitId == -1) {
isError = true
return@buildJsonArray
}
add(sel.unitId)
unSplitDefIds += "${sel.unitId}-"
}
}
if (!isError) {
MainActivity.navViewModel.showResult.postValue(true)
//搜索
getPvpData(idArray)
getFavoritesList(defIds)
//添加搜索记录
insert(
PvpHistoryData(
id = UUID.randomUUID().toString(),
defs = "${MainActivity.regionType.value}@$unSplitDefIds",
date = getToday(),
)
)
} else {
ToastUtil.short(getString(R.string.tip_select_5))
}
}
}
/**
* 竞技场角色信息
*/
private fun getAllCharacter() {
viewModelScope.launch {
val data = unitRepository.getCharacterByPosition(1, 999)
_uiState.update {
it.copy(
allUnitList = data
)
}
//加载常用角色
getRecentlyUsedUnitList(data)
}
}
/**
* 改变请求状态
*/
fun changeRequesting(requesting: Boolean) {
_uiState.update {
it.copy(
requesting = requesting
)
}
}
/**
* 改变请求状态
*/
private fun resetResult() {
_uiState.update {
it.copy(
pvpResult = null
)
}
}
}
| 1 | null | 3 | 79 | 87f6753d141e16f7ee0befbebf865edb4e93badd | 10,295 | pcr-tool | Apache License 2.0 |
app/src/main/java/com/comic_con/museum/ar/views/ViewUtil.kt | Comic-Con-Museum | 153,692,659 | false | {"Kotlin": 71992} | package com.comic_con.museum.ar.views
import android.content.res.Resources
import android.util.TypedValue
class ViewUtil {
companion object {
fun dpToPx(resources: Resources, value: Float): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
value,
resources.displayMetrics
).toInt()
}
}
} | 18 | Kotlin | 1 | 8 | 6e5396fde31d57f5bcde87f608d1357c468c90d2 | 405 | ccm-android | Apache License 2.0 |
src/test/kotlin/no/nav/eessi/pensjon/prefill/sed/PrefillP9000GLmedUtlandInnvTest.kt | navikt | 358,172,246 | false | null | package no.nav.eessi.pensjon.prefill.sed
import io.mockk.every
import io.mockk.mockk
import no.nav.eessi.pensjon.eux.model.SedType
import no.nav.eessi.pensjon.prefill.InnhentingService
import no.nav.eessi.pensjon.prefill.PersonPDLMock
import no.nav.eessi.pensjon.prefill.models.EessiInformasjon
import no.nav.eessi.pensjon.prefill.models.PensjonCollection
import no.nav.eessi.pensjon.prefill.models.PersonDataCollection
import no.nav.eessi.pensjon.prefill.models.PrefillDataModelMother
import no.nav.eessi.pensjon.prefill.person.PrefillPDLNav
import no.nav.eessi.pensjon.shared.api.PersonId
import no.nav.eessi.pensjon.shared.api.PrefillDataModel
import no.nav.eessi.pensjon.shared.person.Fodselsnummer
import no.nav.eessi.pensjon.shared.person.FodselsnummerGenerator
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class PrefillP9000GLmedUtlandInnvTest {
private val personFnr = FodselsnummerGenerator.generateFnrForTest(65)
private val avdodPersonFnr = FodselsnummerGenerator.generateFnrForTest(75)
private val pesysSaksnummer = "22875355"
lateinit var prefillData: PrefillDataModel
lateinit var prefillNav: PrefillPDLNav
lateinit var prefillSEDService: PrefillSEDService
private lateinit var personDataCollection: PersonDataCollection
private lateinit var pensjonCollection: PensjonCollection
@BeforeEach
fun setup() {
personDataCollection = PersonPDLMock.createAvdodFamilie(personFnr, avdodPersonFnr)
prefillNav = PrefillPDLNav(
prefillAdresse = mockk(){
every { hentLandkode(any()) } returns "NO"
every { createPersonAdresse(any()) } returns mockk(relaxed = true)
},
institutionid = "NO:noinst002",
institutionnavn = "NOINST002, NO INST002, NO")
prefillData = PrefillDataModelMother.initialPrefillDataModel(SedType.P9000, personFnr, penSaksnummer = pesysSaksnummer, avdod = PersonId(avdodPersonFnr, "112233445566"))
val pensjonInformasjonService = PrefillTestHelper.lesPensjonsdataFraFil("/pensjonsinformasjon/krav/KravAlderEllerUfore_AP_UTLAND.xml")
val innhentingService = InnhentingService(mockk(), pensjonsinformasjonService = pensjonInformasjonService)
pensjonCollection = innhentingService.hentPensjoninformasjonCollection(prefillData)
prefillSEDService = PrefillSEDService(EessiInformasjon(), prefillNav)
}
@Test
fun `forventet korrekt utfylt P9000 med mockdata fra testfiler`() {
val p9000 = prefillSEDService.prefill(prefillData, personDataCollection,pensjonCollection)
assertEquals("BAMSE LUR", p9000.nav?.bruker?.person?.fornavn)
assertEquals("MOMBALO", p9000.nav?.bruker?.person?.etternavn)
val navfnr1 = Fodselsnummer.fra(p9000.nav?.bruker?.person?.pin?.get(0)?.identifikator!!)
assertEquals(75, navfnr1?.getAge())
assertEquals("M", p9000.nav?.bruker?.person?.kjoenn)
assertNotNull(p9000.nav?.bruker?.person?.pin)
val pinlist = p9000.nav?.bruker?.person?.pin
val pinitem = pinlist?.get(0)
assertEquals(null, pinitem?.sektor)
assertEquals(avdodPersonFnr, pinitem?.identifikator)
assertEquals("01", p9000.nav?.annenperson?.person?.rolle)
assertEquals("BAMSE ULUR", p9000.nav?.annenperson?.person?.fornavn)
assertEquals("DOLLY", p9000.nav?.annenperson?.person?.etternavn)
val navfnr2 = Fodselsnummer.fra(p9000.nav?.annenperson?.person?.pin?.get(0)?.identifikator!!)
assertEquals(65, navfnr2?.getAge())
assertEquals("K", p9000.nav?.annenperson?.person?.kjoenn)
assertNotNull(p9000.pensjon)
assertNotNull(p9000.pensjon?.gjenlevende)
}
}
| 3 | Kotlin | 0 | 4 | b5d65bb8df9a82e0640e5ba0eaec85e338501802 | 3,867 | eessi-pensjon-prefill | MIT License |
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/kofunction/KoFunctionDeclarationForKoReceiverTypeProviderTest.kt | LemonAppDev | 621,181,534 | false | {"Kotlin": 2941189, "Python": 25669} | package com.lemonappdev.konsist.core.declaration.kofunction
import com.lemonappdev.konsist.TestSnippetProvider.getSnippetKoScope
import org.amshove.kluent.assertSoftly
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
class KoFunctionDeclarationForKoReceiverTypeProviderTest {
@Test
fun `function-without-receiver`() {
// given
val sut = getSnippetFile("function-without-receiver")
.functions()
.first()
// then
assertSoftly(sut) {
receiverType shouldBeEqualTo null
hasReceiverType() shouldBeEqualTo false
hasReceiverType { it.name == "Int" } shouldBeEqualTo false
hasReceiverTypeOf(Int::class) shouldBeEqualTo false
hasReceiverType("Int") shouldBeEqualTo false
}
}
@Test
fun `function-with-type-receiver`() {
// given
val sut = getSnippetFile("function-with-type-receiver")
.functions()
.first()
// then
assertSoftly(sut) {
receiverType?.name shouldBeEqualTo "Int"
hasReceiverType() shouldBeEqualTo true
hasReceiverType { it.name == "Int" } shouldBeEqualTo true
hasReceiverType { it.name == "String" } shouldBeEqualTo false
hasReceiverTypeOf(Int::class) shouldBeEqualTo true
hasReceiverTypeOf(String::class) shouldBeEqualTo false
hasReceiverType("Int") shouldBeEqualTo true
hasReceiverType("String") shouldBeEqualTo false
}
}
private fun getSnippetFile(fileName: String) =
getSnippetKoScope("core/declaration/kofunction/snippet/forkoreceivertypeprovider/", fileName)
}
| 16 | Kotlin | 19 | 768 | 22f45504ab1c88fca8314bd86f91af7dd8a3672b | 1,722 | konsist | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/LessEqualGreater.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: LessEqualGreater
*
* Full name: System`LessEqualGreater
*
* Usage: LessEqualGreater[x, y, …] displays as x ⋚ y ⋚ ….
*
* Options: None
*
* Attributes:
*
* local: paclet:ref/LessEqualGreater
* Documentation: web: http://reference.wolfram.com/language/ref/LessEqualGreater.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun lessEqualGreater(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("LessEqualGreater", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 951 | mathemagika | Apache License 2.0 |
orchestrator/src/main/kotlin/configuration/Configuration.kt | rdf-connect | 782,188,424 | false | {"Kotlin": 107756, "TypeScript": 35127, "Python": 21679, "Shell": 1021, "Dockerfile": 423} | package technology.idlab.configuration
import technology.idlab.parser.Parser
/**
* The Configuration class is an extension of the parser, and allows for much more powerful querying
* of the model, as well as provide important assertions of the model's consistency.
*/
abstract class Configuration(parser: Parser) {}
| 13 | Kotlin | 0 | 1 | be481269e4fec6bbdf1b782ad6cc796821d0249a | 321 | orchestrator | MIT License |
solar/src/main/java/com/chiksmedina/solar/boldduotone/videoaudiosound/Rewind15SecondsBack.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.bold.videoaudiosound
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.bold.VideoAudioSoundGroup
val VideoAudioSoundGroup.Rewind15SecondsBack: ImageVector
get() {
if (_rewind15SecondsBack != null) {
return _rewind15SecondsBack!!
}
_rewind15SecondsBack = Builder(
name = "Rewind15SecondsBack", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(10.3249f, 7.824f)
curveTo(10.5848f, 7.9489f, 10.75f, 8.2117f, 10.75f, 8.5f)
verticalLineTo(15.5f)
curveTo(10.75f, 15.9142f, 10.4142f, 16.25f, 10.0f, 16.25f)
curveTo(9.5858f, 16.25f, 9.25f, 15.9142f, 9.25f, 15.5f)
verticalLineTo(10.0605f)
lineTo(7.9686f, 11.0857f)
curveTo(7.6451f, 11.3444f, 7.1731f, 11.292f, 6.9144f, 10.9685f)
curveTo(6.6556f, 10.6451f, 6.7081f, 10.1731f, 7.0315f, 9.9144f)
lineTo(9.5315f, 7.9144f)
curveTo(9.7566f, 7.7343f, 10.0651f, 7.6991f, 10.3249f, 7.824f)
close()
moveTo(12.6746f, 8.6047f)
curveTo(12.8447f, 8.0943f, 13.3224f, 7.75f, 13.8604f, 7.75f)
horizontalLineTo(16.5f)
curveTo(16.9142f, 7.75f, 17.25f, 8.0858f, 17.25f, 8.5f)
curveTo(17.25f, 8.9142f, 16.9142f, 9.25f, 16.5f, 9.25f)
horizontalLineTo(14.0406f)
lineTo(13.5406f, 10.75f)
horizontalLineTo(14.5f)
curveTo(16.0188f, 10.75f, 17.25f, 11.9812f, 17.25f, 13.5f)
curveTo(17.25f, 15.0188f, 16.0188f, 16.25f, 14.5f, 16.25f)
horizontalLineTo(12.5f)
curveTo(12.0858f, 16.25f, 11.75f, 15.9142f, 11.75f, 15.5f)
curveTo(11.75f, 15.0858f, 12.0858f, 14.75f, 12.5f, 14.75f)
horizontalLineTo(14.5f)
curveTo(15.1904f, 14.75f, 15.75f, 14.1904f, 15.75f, 13.5f)
curveTo(15.75f, 12.8097f, 15.1904f, 12.25f, 14.5f, 12.25f)
horizontalLineTo(13.1937f)
curveTo(12.3405f, 12.25f, 11.7381f, 11.4141f, 12.0079f, 10.6047f)
lineTo(12.6746f, 8.6047f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(11.324f, 1.6751f)
curveTo(11.4489f, 1.4153f, 11.7117f, 1.25f, 12.0f, 1.25f)
curveTo(12.7353f, 1.25f, 13.4541f, 1.3239f, 14.1492f, 1.465f)
curveTo(19.0563f, 2.4611f, 22.75f, 6.7984f, 22.75f, 12.0f)
curveTo(22.75f, 17.9371f, 17.9371f, 22.75f, 12.0f, 22.75f)
curveTo(6.0629f, 22.75f, 1.25f, 17.9371f, 1.25f, 12.0f)
curveTo(1.25f, 7.5907f, 3.9046f, 3.803f, 7.6997f, 2.1448f)
curveTo(8.0793f, 1.979f, 8.5214f, 2.1522f, 8.6873f, 2.5318f)
curveTo(8.8531f, 2.9114f, 8.6798f, 3.3535f, 8.3003f, 3.5194f)
curveTo(5.0318f, 4.9474f, 2.75f, 8.2081f, 2.75f, 12.0f)
curveTo(2.75f, 17.1086f, 6.8914f, 21.25f, 12.0f, 21.25f)
curveTo(17.1086f, 21.25f, 21.25f, 17.1086f, 21.25f, 12.0f)
curveTo(21.25f, 7.8495f, 18.5158f, 4.3362f, 14.75f, 3.1654f)
verticalLineTo(4.5f)
curveTo(14.75f, 4.8185f, 14.5488f, 5.1023f, 14.2483f, 5.2077f)
curveTo(13.9477f, 5.3131f, 13.6133f, 5.2172f, 13.4143f, 4.9685f)
lineTo(11.4143f, 2.4685f)
curveTo(11.2342f, 2.2434f, 11.1991f, 1.935f, 11.324f, 1.6751f)
close()
}
}
.build()
return _rewind15SecondsBack!!
}
private var _rewind15SecondsBack: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 4,743 | SolarIconSetAndroid | MIT License |
app/src/main/java/com/no5ing/bbibbi/presentation/ui/common/button/IconedCTAButton.kt | depromeet | 738,807,741 | false | {"Kotlin": 649362} | package com.no5ing.bbibbi.presentation.ui.common.button
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp
import com.no5ing.bbibbi.presentation.ui.theme.bbibbiScheme
import com.no5ing.bbibbi.presentation.ui.theme.bbibbiTypo
@Composable
fun IconedCTAButton(
text: String,
painter: Painter,
modifier: Modifier = Modifier,
contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
onClick: () -> Unit = {},
isActive: Boolean = true,
) {
Button(
shape = RoundedCornerShape(100.dp),
onClick = { if (isActive) onClick() },
colors = ButtonDefaults.buttonColors(
containerColor = if (isActive) MaterialTheme.bbibbiScheme.mainGreen else MaterialTheme.bbibbiScheme.mainGreen.copy(
alpha = 0.2f
)
),
modifier = modifier,
contentPadding = contentPadding,
) {
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
Icon(
painter = painter,
contentDescription = null,
modifier = Modifier
.size(20.dp),
tint = MaterialTheme.bbibbiScheme.backgroundPrimary
)
Text(
text = text,
color = MaterialTheme.bbibbiScheme.backgroundPrimary,
style = MaterialTheme.bbibbiTypo.bodyOneBold,
)
}
}
} | 0 | Kotlin | 0 | 3 | 5d0d722bf8390b9e75c46bdeabd40485df207251 | 2,015 | 14th-team5-AOS | MIT License |
app/src/main/java/io/horizontalsystems/bankwallet/core/storage/migrations/Migration_48_49.kt | horizontalsystems | 142,825,178 | false | null | package io.deus.wallet.core.storage.migrations
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
object Migration_48_49 : Migration(48, 49) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS `NftAssetBriefMetadataRecord` (`nftUid` TEXT NOT NULL, `providerCollectionUid` TEXT NOT NULL, `name` TEXT, `imageUrl` TEXT, `previewImageUrl` TEXT, PRIMARY KEY(`nftUid`))") }
} | 153 | null | 346 | 805 | 399fd8dc84c249dd1094fee0a7a043ec5e4ffa90 | 475 | unstoppable-wallet-android | MIT License |
modules/dagger/arrow-dagger/src/main/kotlin/arrow/dagger/instances/function1.kt | mikezx6r | 160,887,969 | true | {"Kotlin": 2173554, "CSS": 142438, "JavaScript": 66836, "HTML": 14634, "Java": 4465, "Shell": 3043, "Ruby": 1606} | package arrow.dagger.instances
import arrow.data.Function1PartialOf
import arrow.instances.Function1ApplicativeInstance
import arrow.instances.Function1FunctorInstance
import arrow.instances.Function1MonadInstance
import arrow.typeclasses.Applicative
import arrow.typeclasses.Functor
import arrow.typeclasses.Monad
import dagger.Module
import dagger.Provides
import javax.inject.Inject
@Module
abstract class Function1Instances<F> {
@Provides
fun function1Functor(ev: DaggerFunction1FunctorInstance<F>): Functor<Function1PartialOf<F>> = ev
@Provides
fun function1Applicative(ev: DaggerFunction1ApplicativeInstance<F>): Applicative<Function1PartialOf<F>> = ev
@Provides
fun function1Monad(ev: DaggerFunction1MonadInstance<F>): Monad<Function1PartialOf<F>> = ev
}
class DaggerFunction1FunctorInstance<F> @Inject constructor(val FF: Functor<F>) : Function1FunctorInstance<F>
class DaggerFunction1ApplicativeInstance<F> @Inject constructor(val FF: Monad<F>) : Function1ApplicativeInstance<F>
class DaggerFunction1MonadInstance<F> @Inject constructor(val FF: Monad<F>) : Function1MonadInstance<F> | 0 | Kotlin | 0 | 0 | 6d973fe5296b7d5eac8a2823057be1a8289a8f12 | 1,124 | kategory | Apache License 2.0 |
shared/src/commonMain/kotlin/com/llamalabb/phillygarbageday/domain/usecase/_old/GetHeadlinesUseCase.kt | AndyGOBrien | 569,400,450 | false | {"Kotlin": 74636, "Swift": 31810, "Ruby": 1706} | package com.llamalabb.phillygarbageday.domain.usecase._old
//import com.llamalabb.phillygarbageday.data.remote.dto.asDomainModel
//import com.llamalabb.phillygarbageday.data.repository.IAddressRepository
//import kotlinx.coroutines.flow.flow
//
//class GetHeadlinesUseCase(
// private val repository: IAddressRepository
//) {
//
// operator fun invoke(page: Int, pageSize: Int = 20, country: String = "us") = flow {
//
// val response =
// repository.getAllHeadlines(page = page, pageSize = pageSize, country = country)
// .asDomainModel()
//
// emit(response)
//
// }
//} | 0 | Kotlin | 0 | 1 | 6d70e96281eefb89fb19e4138f0975538b9b84ed | 622 | PhillyGarbageDay | Apache License 2.0 |
compiler/daemon/daemon-tests/test/org/jetbrains/kotlin/daemon/experimental/unit/ClientSerializationTest.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.daemon.experimental.unit
import io.ktor.network.sockets.aSocket
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.jetbrains.kotlin.daemon.common.experimental.CompilerServicesFacadeBaseClientSideImpl
import org.jetbrains.kotlin.daemon.common.experimental.LoopbackNetworkInterfaceKtor.selectorMgr
import org.jetbrains.kotlin.daemon.common.experimental.socketInfrastructure.DefaultClient
import org.jetbrains.kotlin.daemon.common.experimental.socketInfrastructure.ServerBase
import org.jetbrains.kotlin.daemon.common.experimental.socketInfrastructure.openIO
import org.jetbrains.kotlin.daemon.common.experimental.socketInfrastructure.runWithTimeout
import org.jetbrains.kotlin.daemon.common.toRMI
import org.jetbrains.kotlin.integration.KotlinIntegrationTestBase
import org.jetbrains.kotlin.test.IgnoreAll
import org.junit.runner.RunWith
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.InetSocketAddress
import java.util.logging.Logger
class TestServer(val serverPort: Int = 6999) {
private val serverSocket = aSocket(selectorMgr).tcp().bind(InetSocketAddress(serverPort))
private val log = Logger.getLogger("TestServer")
fun awaitClient() = GlobalScope.async {
log.info("accepting clientSocket...")
val client = serverSocket.accept()
log.info("client accepted! (${client.remoteAddress})")
client.openIO(log)
true
}
}
val testServer = TestServer()
@RunWith(IgnoreAll::class)
@Suppress("UNCHECKED_CAST")
class ClientSerializationTest : KotlinIntegrationTestBase() {
val file = createTempFile()
val log = Logger.getLogger("ClientSerializationTest")
private inline fun <reified T> abstractSerializationTest(initClient: () -> T, vararg additionalTests: (T, T) -> Unit) {
val client = initClient()
log.info("created")
file.outputStream().use {
ObjectOutputStream(it).use {
it.writeObject(client)
}
}
log.info("printed")
var client2: T? = null
var connected = false
runBlocking {
val clientAwait = testServer.awaitClient()
client2 = file.inputStream().use {
ObjectInputStream(it).use {
it.readObject() as T
}
}
connected = runWithTimeout { clientAwait.await() } ?: false
}
assert(connected)
log.info("read")
assert(client2 != null)
additionalTests.forEach { it(client, client2!!) }
log.info("test passed")
}
fun ignore_testDefaultClient() = abstractSerializationTest(
{ DefaultClient<ServerBase>(testServer.serverPort) },
{ client, client2 -> assert(client.serverPort == client2.serverPort) },
{ _, client2 ->
client2.log.info("abacaba (2)")
log.info("test passed")
}
)
fun ignore_testCompilerServicesFacadeBaseClientSide() = abstractSerializationTest(
{ CompilerServicesFacadeBaseClientSideImpl(testServer.serverPort) },
{ client, client2 -> assert(client.serverPort == client2.serverPort) }
)
fun ignore_testRMIWrapper() = abstractSerializationTest({ CompilerServicesFacadeBaseClientSideImpl(testServer.serverPort).toRMI() })
}
| 157 | null | 5209 | 42,102 | 65f712ab2d54e34c5b02ffa3ca8c659740277133 | 3,547 | kotlin | Apache License 2.0 |
src/main/java/org/jonnyzzz/demo/lang-basic.kt | jonnyzzz | 108,171,151 | false | null | package org.jonnyzzz.demo.langbasic
fun main(args: Array<String>) {
runBasic {
10 PRINT "Hello, from Kotlin!"
30 PRINT "@jonnyzzz"
40 INPUT "@jonnyzzz" AS "twitter"
50 PRINT "Another text"
60 GOTO 10
}
}
fun runBasic(builder : BasicBuilder.() -> Unit) {
val host = ProgramBuilder()
BasicBuilder(host).builder()
host.execute()
}
class BasicBuilder(private val builder : ProgramBuilder) {
infix fun Int.PRINT(text : String) {
builder.nextLine(PrintStatement(this, text))
}
infix fun Int.INPUT(text: String) = INPUTStatement(this, text).apply {
builder.nextLine(this)
}
infix fun Int.GOTO(line : Int) {
builder.nextLine(GOTOStatement(this, line))
}
}
class ProgramBuilder {
private val lines = mutableListOf<BasicLine>()
fun nextLine(code: BasicLine) {
val line = lines.lastOrNull()?.line
if (line != null && line >= code.line) {
throw Exception("Invalid line number. In Basic lines must be monotonious. Current line: ${code.line}, prev line: $line")
}
lines += code
}
fun execute() {
var line = lines.firstOrNull()
fun nextLine() {
val targetNumber = line?.line
if (targetNumber != null) {
line = lines.firstOrNull { it.line > targetNumber}
}
}
while(line != null) {
val current = line
when(current) {
is PrintStatement -> {
println(current.text)
nextLine()
}
is GOTOStatement -> {
line = lines.firstOrNull { it.line == current.toLine }
}
is INPUTStatement -> {
println(current.text)
readLine()
nextLine()
}
}
}
}
}
sealed class BasicLine(val line : Int)
class PrintStatement(line: Int, val text: String) : BasicLine(line)
class GOTOStatement(line: Int, val toLine: Int) : BasicLine(line)
class INPUTStatement(line: Int, val text: String) : BasicLine(line) {
var targetVariableName : String? = null
infix fun AS(text : String) {
targetVariableName = text
}
} | 0 | Kotlin | 0 | 7 | 2ffbc3bef5d7c220eb0464ecc1eb3f7e7cefee23 | 2,044 | kotlin-dsl-demo | MIT License |
Kotlin基础-2/src/main/java/com/yey/kotlin2/53-lambda表达式.kt | rgdzh1 | 266,117,976 | false | null | package com.yey.kotlin2
import org.junit.Test
class `53-lambda表达式` {
/***
* (Int,Int)->Int: 这个类型是函数类型其中(Int,Int)为参数类型,->Int为该函数的返回值类型,
* 函数类型的参数需要接收该函数的地址值.
*/
fun cacl(a: Int, b: Int, tool: (Int, Int) -> Int): Int {
// return util(a, b)
return tool.invoke(a, b)//invoke()就是调用方法
}
/**
* 在Kotlin中匿名函数的别名就是lambda表达式
*/
@Test
fun lambda表达式() {
// {m,n->m+n} : 这个就是匿名函数,上面的cacl()方法中最后一个参数的类型是函数类型,匿名函数直接就能被cacl中最后一个参数tool接收.
println(cacl(10, 20, { m, n -> m + n }))
}
// 看看这个lambda表达式
fun myFun(f: () -> Unit) {
f()
}
@Test
fun lambda表达式优化写法() {
// 如果函数中最后一个参数是函数类型, 那么lambda表达式可以移动到括号以外的地方
cacl(10, 200) { m, n ->
// lambda表达式中最后一行就是返回值
m + n
}
// 如果函数中最后一个参数是函数类型,那么lambda表达式可以移动到括号以外的地方,如果括号中没有参数,那么这个括号可以去除.
// 第一种写法
myFun({
println("第一种写法")
})
// 第二种写法
myFun() {
println("第二种写法")
}
// 第三种写法
myFun {
println("第三种写法")
}
}
@Test
fun 嵌套匿名函数() {
// {
// println("执行匿名函数")
// }()
// invoke的好处就是可以用?. 安全调用符号
{
println("执行匿名函数方法2")
}?.invoke()
}
@Test
fun 嵌套匿名有参lambda表达式() {
// 第一种有参lambda表达式
// val result = { a: Int, b: Int ->
// a + b
// }(10, 20)
// println(result)
// 第二种
// invoke() 调用,好处是可以使用安全符号调用
val invoke = { a: Int, b: Int -> a + b }?.invoke(10, 20)
println(invoke)
}
@Test
fun 嵌套匿名lambda表达式如何保存() {
// 使用myFun变量保存lambda表达式
val myFun: (Int, Int) -> Int = { a: Int, b: Int -> a + b }
// 调用保存的lambda表达式
myFun(20, 30)
// invoke 就是可以加安全调用符号
myFun.invoke(10, 30)
}
@Test
fun lambda表达式一个参数省略it() {
println(tool(10) {
100 + 10
})
}
// 参数f是函数类型,f的参数只有一个,如果f是一个lambda表达式,那么第一个参数就可以忽略不写,然后用it代替
fun tool(a: Int, f: (Int) -> Int) {
f(a)
}
@Test
fun lambda表达式的返回值() {
val function = {
// 在lambda表达式中,大括号的最后一行代表的就是返回值,
println("返回值")
10
"10"
}()
}
class Food {
fun eat() {
println("吃饭")
}
}
fun tools(f: Food.() -> Unit) {
Food().f()
}
@Test
fun 好好体会下吧() {
tools {
eat()
}
}
@Test
fun 查看Kotlin中的lambda表达式() {
// 阅读下forEach lambda表达
// 1. CharSequence.forEach() 代表的是对字符串的扩展函数
// 2. action: (Char) -> Unit 表示forEach中接收的是一个函数类型的参数
// 3. for (element in this) this代表字符串本身,对字符串进行遍历
// 4. 美遍历到一个元素都会调用传入的lanmbda函数.
// public inline fun CharSequence.forEach(action: (Char) -> Unit): Unit {
// for (element in this) action(element)
// }
var str = "abcms"
// forEach中接收的函数参数,action: (Char) -> Unit,然后看看println整好符合这个类型,所以println()方法其实适合当作参数传入forEach中
str.forEach(::println)
}
@Test
fun 查看indexOffFirst() {
val arrayOf = arrayOf("林大瞎", "风大", "林大傻")
// 1. Array<out T>.indexOfFirst : indexOfFirst是Array的扩展函数
// 2. indexOfFirst(predicate: (T) -> Boolean) 接收的参数类型是方法类型,该lambda表达式接收一个泛型参数,
// 3. indices 为Array的长度
// 4. 遍历Array长度,取出不同的值,然后传入lambda表达式中
// 5. 如果lanmbda表达式返回的是true,则indexOfFirst返回当前索引,如果lambda表达式为false,就indexOfFirst返回-1
// public inline fun <T> Array<out T>.indexOfFirst(predicate: (T) -> Boolean): Int {
// for (index in indices) {
// if (predicate(this[index])) {
// return index
// }
// }
// return -1
// }
val indexOfFirst = arrayOf.indexOfFirst {
it.startsWith("林")
}
println(arrayOf[indexOfFirst])
}
} | 0 | Kotlin | 0 | 0 | 450905528aba3d39f2c98af172c0282ec9b268aa | 3,937 | Java-Kotlin-Learning | Apache License 2.0 |
backend/src/main/java/org/gdglille/devfest/backend/internals/helpers/drive/GoogleDriveDataSource.kt | GerardPaligot | 444,230,272 | false | {"Kotlin": 763877, "Swift": 115847, "Shell": 1148, "Dockerfile": 369} | package org.gdglille.devfest.backend.internals.helpers.drive
import com.google.api.services.drive.Drive
import com.google.api.services.drive.model.File
import com.google.api.services.drive.model.Permission
private const val PageSize = 10
class GoogleDriveDataSource(private val service: Drive) : DriveDataSource {
override fun findDriveByName(name: String): String? {
val drives = service.drives().list().apply {
pageSize = PageSize
fields = "nextPageToken, drives(id, name)"
}.execute()
return drives.drives.find { it.name == name }?.id
}
override fun findFolderByName(driveId: String, parentId: String?, name: String): String? {
return service.files().list().apply {
this.driveId = driveId
includeItemsFromAllDrives = true
supportsAllDrives = true
corpora = "drive"
pageSize = PageSize
fields = "nextPageToken, files(id)"
this.q = "name='$name'${parentId?.let { " and parents='$parentId'" } ?: run { "" }}"
}.execute().files.firstOrNull()?.id
}
override fun findFileByName(driveId: String, parentId: String?, name: String): String? {
return service.files().list().apply {
this.driveId = driveId
includeItemsFromAllDrives = true
supportsAllDrives = true
corpora = "drive"
pageSize = PageSize
fields = "nextPageToken, files(id)"
this.q = "name='$name'${parentId?.let { " and parents='$parentId'" } ?: run { "" }}"
}.execute().files.firstOrNull()?.id
}
override fun copyFile(driveId: String, fileId: String, name: String): String {
val file = File().apply {
this.name = name
this.mimeType = "application/vnd.google-apps.spreadsheet"
parents = listOf(driveId)
}
return service.files().copy(fileId, file).apply {
supportsAllDrives = true
fields = "id"
}.execute().id
}
override fun moveFile(driveId: String, fileId: String, folderId: String): List<String> {
val file = service.files()[fileId].apply {
supportsAllDrives = true
fields = "parents"
}.execute()
return service.files().update(fileId, null).apply {
supportsAllDrives = true
addParents = folderId
removeParents = file.parents.joinToString(",")
fields = "parents"
}.execute().parents
}
override fun grantPermission(fileId: String, email: String) {
val userPermission: Permission = Permission()
.setType("user")
.setRole("writer")
userPermission.setEmailAddress(email)
service.permissions().create(fileId, userPermission).setFields("id").execute()
}
}
| 7 | Kotlin | 5 | 136 | 51ac11d04f9b0561b250ca163266a853a1965f0a | 2,854 | conferences4hall | Apache License 2.0 |
app/src/main/java/dev/tcode/thinmp/repository/media/AlbumRepository.kt | tcode-dev | 392,735,283 | false | null | package dev.tcode.thinmp.repository.media
import android.content.Context
import android.provider.MediaStore
import dev.tcode.thinmp.model.media.AlbumModel
class AlbumRepository(context: Context) : MediaStoreRepository<AlbumModel>(
context, MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, arrayOf(
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Albums.ARTIST
)
) {
fun findAll(): List<AlbumModel> {
selection = null
selectionArgs = null
sortOrder = MediaStore.Audio.Albums.ALBUM + " ASC"
return getList();
}
fun findById(albumId: String): AlbumModel? {
selection = MediaStore.Audio.Albums._ID + " = ?"
selectionArgs = arrayOf(albumId)
sortOrder = null
return get()
}
fun findByArtistId(artistId: String): List<AlbumModel> {
selection = MediaStore.Audio.Media.ARTIST_ID + " = ?"
selectionArgs = arrayOf(artistId)
sortOrder = null
return getList()
}
private fun getId(): String {
return cursor?.getColumnIndex(MediaStore.Audio.Albums._ID)?.let { cursor?.getString(it) }
?: ""
}
private fun getArtistId(): String {
return cursor?.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)
?.let { cursor?.getString(it) }
?: ""
}
private fun getArtistName(): String {
return cursor?.getColumnIndex(MediaStore.Audio.Media.ARTIST)?.let { cursor?.getString(it) }
?: ""
}
private fun getAlbumName(): String {
return cursor?.getColumnIndex(MediaStore.Audio.Media.ALBUM)?.let { cursor?.getString(it) }
?: ""
}
private fun getAlbum(): AlbumModel {
return AlbumModel(
getId(),
getAlbumName(),
getArtistId(),
getArtistName(),
)
}
override fun fetch(): AlbumModel {
return getAlbum()
}
} | 0 | Kotlin | 0 | 0 | 88b10290f674830d9fdf90a359e06d565ea86a26 | 2,009 | ThinMP_Android_Kotlin | MIT License |
src/main/kotlin/team/mke/tg/ExposedUtils.kt | MKE-overseas | 750,836,175 | false | {"Kotlin": 36096} | package team.mke.tg
import org.jetbrains.exposed.sql.Table
import team.mke.utils.db.COLLATE_UTF8MB4_UNICODE_CI
fun Table.botComment(name: String = "comment") = text(name, COLLATE_UTF8MB4_UNICODE_CI) | 0 | Kotlin | 0 | 0 | 31b1d1acedd4713a216cce4e32f57230e4d58e24 | 200 | mke-tg | Apache License 2.0 |
camerax_lib/src/main/java/com/kiylx/camerax_lib/main/manager/CameraHolder.kt | Knightwood | 517,621,489 | false | null | package com.kiylx.camerax_lib.main.manager
import android.annotation.SuppressLint
import android.net.Uri
import android.util.Log
import androidx.camera.core.*
import androidx.camera.video.Recording
import androidx.camera.video.VideoRecordEvent
import androidx.camera.view.PreviewView
import com.kiylx.camerax_lib.main.manager.imagedetection.base.AnalyzeUtils
import com.kiylx.camerax_lib.main.manager.model.*
import com.kiylx.camerax_lib.main.manager.photo.ImageCaptureHelper
import com.kiylx.camerax_lib.main.manager.video.OnceRecorder
import com.kiylx.camerax_lib.main.manager.video.OnceRecorderHelper
import com.kiylx.camerax_lib.main.store.ImageCaptureConfig
import com.kiylx.camerax_lib.main.store.VideoRecordConfig
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.callback.ExplainReasonCallbackWithBeforeParam
import com.permissionx.guolindev.callback.ForwardToSettingsCallback
import com.permissionx.guolindev.request.ExplainScope
import com.permissionx.guolindev.request.ForwardScope
import java.util.concurrent.Executors
/**
* 实现拍照,录制等功能
*/
class CameraHolder(
cameraPreview: PreviewView,
cameraConfig: ManagerConfig,
cameraManagerListener: CameraManagerEventListener,
var captureResultListener: CaptureResultListener? = null,
) : CameraXManager(
cameraPreview, cameraConfig, cameraManagerListener
) {
private var analyzer: ImageAnalysis.Analyzer = AnalyzeUtils.emptyAnalyzer
fun changeAnalyzer(analyzer: ImageAnalysis.Analyzer) {
this.analyzer = analyzer
}
override fun selectAnalyzer(): ImageAnalysis.Analyzer = analyzer
/** 检查权限,通过后执行block块初始化相机 */
override fun checkPerm(block: () -> Unit) {
PermissionX.init(context).permissions(ManagerUtil.REQUIRED_PERMISSIONS.asList())
.explainReasonBeforeRequest()//在第一次请求权限之前就先弹出一个对话框向用户解释自己需要哪些权限,然后才会进行权限申请。
.onExplainRequestReason(object : ExplainReasonCallbackWithBeforeParam {
//onExplainRequestReason() 方法可以用于监听那些被用户拒绝,而又可以再次去申请的权限。
//从方法名上也可以看出来了,应该在这个方法中解释申请这些权限的原因。
override fun onExplainReason(
scope: ExplainScope,
deniedList: MutableList<String>,
beforeRequest: Boolean,
) {
scope.showRequestReasonDialog(
deniedList,
"即将重新申请的权限是程序必须依赖的权限",
"我已明白",
"取消"
)
}
})
.onForwardToSettings(object : ForwardToSettingsCallback {
//onForwardToSettings() 方法,专门用于监听那些被用户永久拒绝的权限。
//另外从方法名上就可以看出,我们可以在这里提醒用户手动去应用程序设置当中打开权限。
override fun onForwardToSettings(
scope: ForwardScope,
deniedList: MutableList<String>,
) {
scope.showForwardToSettingsDialog(
deniedList,
"您需要去应用程序设置当中手动开启权限",
"我已明白",
"取消"
)
}
})
.request { allGranted, grantedList, deniedList ->
if (allGranted) {
block()
} else {
throw Exception("缺失权限")
}
}
}
override fun reBindUseCase() {
stopRecord()
super.reBindUseCase()
}
/**
* 可以启用或停用手电筒(手电筒应用)
* 启用手电筒后,无论闪光灯模式设置如何,手电筒在拍照和拍视频时都会保持开启状态。
* 仅当手电筒被停用时,ImageCapture 中的 flashMode 才会起作用。
*/
fun useTorch(b: Boolean) {
camera?.run {
val flashCanUse = cameraInfo.hasFlashUnit()
if (flashCanUse) {
cameraControl.enableTorch(b)
}
}
}
/** 拍照处理方法(这里只是拍照,录制视频另外有方法) 图像分析和拍照都绑定了拍照用例,所以,拍照后不需要重新绑定图像分析或拍照 拍照前会检查用例绑定 */
fun takePhoto(imageCaptureConfig: ImageCaptureConfig? = null) {
if (imageCaptureConfig != null) {
cameraConfig.imageCaptureConfig = imageCaptureConfig
}
val captureConfig = cameraConfig.imageCaptureConfig
//当前,既不是拍照,也不是图像识别的话,要拍照,就得先去绑定拍照的实例
if (whichInstance != WhichInstanceBind.PICTURE && whichInstance != WhichInstanceBind.IMAGE_DETECTION) {
setCamera(CaptureMode.takePhoto)
}
// 设置拍照的元数据
val metadata = ImageCapture.Metadata().apply {
// 用前置摄像头的话要镜像画面
// Mirror image when using the front camera
isReversedHorizontal = when (captureConfig.horizontalMirrorMode) {
MirrorMode.MIRROR_MODE_ON_FRONT_ONLY -> {
lensFacing == CameraSelector.LENS_FACING_FRONT
}
MirrorMode.MIRROR_MODE_ON -> {
true
}
MirrorMode.MIRROR_MODE_OFF -> {
false
}
else -> {
throw IllegalArgumentException("未知参数")
}
}
isReversedVertical = when (captureConfig.verticalMirrorMode) {
MirrorMode.MIRROR_MODE_ON_FRONT_ONLY -> {
lensFacing == CameraSelector.LENS_FACING_FRONT
}
MirrorMode.MIRROR_MODE_ON -> {
true
}
MirrorMode.MIRROR_MODE_OFF -> {
false
}
else -> {
throw IllegalArgumentException("未知参数")
}
}
location = captureConfig.location
}
// 创建输出选项,包含有图片文件和其中的元数据
val pair = ImageCaptureHelper.getFileOutputOption(metadata, context)
val outputOptions = pair.first
val saveFileData = pair.second
currentStatus = TakeVideoState.takePhoto
// 设置拍照监听回调,当拍照动作被触发的时候
// Setup image capture listener which is triggered after photo has been taken
imageCapture.takePicture(
outputOptions, cameraExecutor, object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) {
Log.e(TAG, "Photo capture failed:-----------------\n\n ${exc.message}", exc)
handler.post {
captureResultListener?.onPhotoTaken(null)
}
currentStatus = TakeVideoState.none
}
override fun onImageSaved(output: ImageCapture.OutputFileResults) {
currentStatus = TakeVideoState.none
output.savedUri?.let {
saveFileData.uri = it
}
handler.post {
captureResultListener?.onPhotoTaken(saveFileData)
}
}
})
}
/**
* 为拍摄的图片提供内存缓冲区,自行处理,而不保存为文件
*/
fun takePhotoInMem(callback: ImageCapture.OnImageCapturedCallback) {
//当前,既不是拍照,也不是图像识别的话,要拍照,就得先去绑定拍照的实例
if (whichInstance != WhichInstanceBind.PICTURE && whichInstance != WhichInstanceBind.IMAGE_DETECTION) {
setCamera(CaptureMode.takePhoto)
}
currentStatus = TakeVideoState.takePhoto
imageCapture.takePicture(cameraExecutor, callback)
currentStatus = TakeVideoState.none
}
/**
* 如果绑定了图像识别,录视频后,可以调用它来恢复图像识别实例绑定,其他情况不需要这么做
*
* 绑定图像识别,是靠配置参数里的[ManagerConfig.captureMode]
*/
private fun imageAnalyze() {
if (cameraConfig.captureMode == CaptureMode.imageAnalysis) {
//几种情况:
// A:绑定图像识别,再进行拍照或录视频
// 1.使用了图像识别,此时,是绑定了图像识别和拍照的用例的。点击拍照,是不需要解绑再去绑定拍照用例的;拍照后,不需要恢复图像识别用例绑定
// 2.依旧使用了图像识别,但此时录制了视频,录制完后,就需要恢复图像识别用例绑定
// B:没绑定图像识别,进行拍照或录视频
// 3.仅绑定了拍照,此时,拍照后不需要恢复图像识别用例绑定
// 4.仅绑定了视频拍摄,此时,录制视频后不需要恢复图像识别用例绑定
handler.post {
setCamera(CaptureMode.imageAnalysis)
}
}
}
/** 翻转相机时,还需要翻转叠加层 */
override fun switchCamera() {
if (currentStatus == TakeVideoState.takeVideo && !cameraConfig.recordConfig.asPersistentRecording) {
//如果未开启持久录制,录制视频时得先停下来
stopRecord()
}
super.switchCamera()
}
/** 提供视频录制,暂停,恢复,停止等功能。每一次录制完成,都会置为null */
private var recording: Recording? = null
/**
* 开始录制
* @param videoRecordConfig 将覆盖原有配置
*/
@SuppressLint("UnsafeOptInUsageError")
fun startRecord(videoRecordConfig: VideoRecordConfig? = null) {
if (videoRecordConfig != null) {
this.cameraConfig.recordConfig = videoRecordConfig //覆盖原有配置
}
val recordConfig = cameraConfig.recordConfig
if (whichInstance != WhichInstanceBind.VIDEO)//如果当前绑定的不是视频捕获实例,绑定他
setCamera(ManagerUtil.TAKE_VIDEO_CASE)
currentStatus = TakeVideoState.takeVideo
val onceRecorder: OnceRecorder = OnceRecorderHelper.newOnceRecorder(context, recordConfig)
val videoFile = onceRecorder.saveFileData
val pendingRecording = onceRecorder.getVideoRecording(videoCapture)
if (recordConfig.asPersistentRecording) {
//持久性录制
pendingRecording.asPersistentRecording()
}
recording = pendingRecording.start(Executors.newSingleThreadExecutor(),
object : androidx.core.util.Consumer<VideoRecordEvent> {
override fun accept(t: VideoRecordEvent) {
if (t is VideoRecordEvent.Finalize) {
//t.outputResults.outputUri
currentStatus = TakeVideoState.none
imageAnalyze()
if (t.hasError()) {
handler.post {
captureResultListener?.onVideoRecorded(null)
}
Log.e(TAG, "accept: what the fuck", t.cause)
} else {
if (t.outputResults.outputUri != Uri.EMPTY) {
videoFile.uri = t.outputResults.outputUri
}
handler.post {
captureResultListener?.onVideoRecorded(videoFile)
}
}
}
}
})
}
/**
* 停止录制
*/
fun stopRecord() {
//这里是不是会自动的unbind VideoCapture
if (currentStatus == TakeVideoState.takeVideo) {
recording?.stop()
recording = null
}
}
/**
* 暂停录制
*/
fun pauseRecord() {
recording?.pause()
}
/**
* 恢复录制
*/
fun resumeRecord() {
recording?.resume()
}
/**
* 录制时静音
*/
fun recordMute(mute: Boolean) {
recording?.mute(mute)
}
} | 1 | null | 6 | 34 | 4db9a7dafd770415d7f85b3f5159bcb542e2925d | 10,934 | CameraX-Helper | Apache License 2.0 |
src/main/kotlin/no/nav/dagpenger/soknad/orkestrator/søknad/MeldingOmSøknadInnsendt.kt | navikt | 758,018,874 | false | {"Kotlin": 201231, "HTML": 701, "Dockerfile": 109} | package no.nav.dagpenger.soknad.orkestrator.søknad
import no.nav.helse.rapids_rivers.JsonMessage
import java.util.UUID
class MeldingOmSøknadInnsendt(private val søknadId: UUID, private val ident: String) {
fun asMessage(): JsonMessage =
JsonMessage.newMessage(
eventName = "søknad_innsendt",
map =
mapOf(
"søknad_id" to søknadId.toString(),
"ident" to ident,
),
)
}
| 1 | Kotlin | 0 | 0 | b8f6d4a0f20fdc6f536bfc078c4ad4c3b1b026fd | 484 | dp-soknad-orkestrator | MIT License |
core/network/src/main/java/kr/pe/ssun/template/core/network/di/NetworkModule.kt | SunChulBaek | 604,435,864 | false | {"Kotlin": 74238} | package kr.pe.ssun.template.core.network.di
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.serialization.json.Json
import kr.pe.ssun.template.core.network.SsunNetworkDataSource
import kr.pe.ssun.template.core.network.ktor.KtorSsunNetwork
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun providesNetworkJson(): Json = Json {
ignoreUnknownKeys = true
}
}
@Module
@InstallIn(SingletonComponent::class)
interface SsunNetworkModule {
@Binds
fun bindKtorSsunNetwork(
network: KtorSsunNetwork
): SsunNetworkDataSource
} | 0 | Kotlin | 0 | 0 | 7526786fdaaa5df42f30b0d74ae53afb47890acb | 746 | ComposeMultiTemplate | Apache License 2.0 |
vector/src/test/java/im/vector/app/features/notifications/NotificationFactoryTest.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright (c) 2021 New Vector Ltd
*
* 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 im.vector.app.features.notifications
import im.vector.app.features.notifications.ProcessedEvent.Type
import im.vector.app.test.fakes.FakeNotificationUtils
import im.vector.app.test.fakes.FakeRoomGroupMessageCreator
import im.vector.app.test.fakes.FakeSummaryGroupMessageCreator
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Test
private const val MY_USER_ID = "user-id"
private const val A_ROOM_ID = "room-id"
private const val AN_EVENT_ID = "event-id"
private val MY_AVATAR_URL: String? = null
private val AN_INVITATION_EVENT = anInviteNotifiableEvent(roomId = A_ROOM_ID)
private val A_SIMPLE_EVENT = aSimpleNotifiableEvent(eventId = AN_EVENT_ID)
private val A_MESSAGE_EVENT = aNotifiableMessageEvent(eventId = AN_EVENT_ID, roomId = A_ROOM_ID)
class NotificationFactoryTest {
private val notificationUtils = FakeNotificationUtils()
private val roomGroupMessageCreator = FakeRoomGroupMessageCreator()
private val summaryGroupMessageCreator = FakeSummaryGroupMessageCreator()
private val notificationFactory = NotificationFactory(
notificationUtils.instance,
roomGroupMessageCreator.instance,
summaryGroupMessageCreator.instance
)
@Test
fun `given a room invitation when mapping to notification then is Append`() = testWith(notificationFactory) {
val expectedNotification = notificationUtils.givenBuildRoomInvitationNotificationFor(AN_INVITATION_EVENT, MY_USER_ID)
val roomInvitation = listOf(ProcessedEvent(Type.KEEP, AN_INVITATION_EVENT))
val result = roomInvitation.toNotifications(MY_USER_ID)
result shouldBeEqualTo listOf(OneShotNotification.Append(
notification = expectedNotification,
meta = OneShotNotification.Append.Meta(
key = A_ROOM_ID,
summaryLine = AN_INVITATION_EVENT.description,
isNoisy = AN_INVITATION_EVENT.noisy,
timestamp = AN_INVITATION_EVENT.timestamp
))
)
}
@Test
fun `given a missing event in room invitation when mapping to notification then is Removed`() = testWith(notificationFactory) {
val missingEventRoomInvitation = listOf(ProcessedEvent(Type.REMOVE, AN_INVITATION_EVENT))
val result = missingEventRoomInvitation.toNotifications(MY_USER_ID)
result shouldBeEqualTo listOf(OneShotNotification.Removed(
key = A_ROOM_ID
))
}
@Test
fun `given a simple event when mapping to notification then is Append`() = testWith(notificationFactory) {
val expectedNotification = notificationUtils.givenBuildSimpleInvitationNotificationFor(A_SIMPLE_EVENT, MY_USER_ID)
val roomInvitation = listOf(ProcessedEvent(Type.KEEP, A_SIMPLE_EVENT))
val result = roomInvitation.toNotifications(MY_USER_ID)
result shouldBeEqualTo listOf(OneShotNotification.Append(
notification = expectedNotification,
meta = OneShotNotification.Append.Meta(
key = AN_EVENT_ID,
summaryLine = A_SIMPLE_EVENT.description,
isNoisy = A_SIMPLE_EVENT.noisy,
timestamp = AN_INVITATION_EVENT.timestamp
))
)
}
@Test
fun `given a missing simple event when mapping to notification then is Removed`() = testWith(notificationFactory) {
val missingEventRoomInvitation = listOf(ProcessedEvent(Type.REMOVE, A_SIMPLE_EVENT))
val result = missingEventRoomInvitation.toNotifications(MY_USER_ID)
result shouldBeEqualTo listOf(OneShotNotification.Removed(
key = AN_EVENT_ID
))
}
@Test
fun `given room with message when mapping to notification then delegates to room group message creator`() = testWith(notificationFactory) {
val events = listOf(A_MESSAGE_EVENT)
val expectedNotification = roomGroupMessageCreator.givenCreatesRoomMessageFor(events, A_ROOM_ID, MY_USER_ID, MY_AVATAR_URL)
val roomWithMessage = mapOf(A_ROOM_ID to listOf(ProcessedEvent(Type.KEEP, A_MESSAGE_EVENT)))
val result = roomWithMessage.toNotifications(MY_USER_ID, MY_AVATAR_URL)
result shouldBeEqualTo listOf(expectedNotification)
}
@Test
fun `given a room with no events to display when mapping to notification then is Empty`() = testWith(notificationFactory) {
val events = listOf(ProcessedEvent(Type.REMOVE, A_MESSAGE_EVENT))
val emptyRoom = mapOf(A_ROOM_ID to events)
val result = emptyRoom.toNotifications(MY_USER_ID, MY_AVATAR_URL)
result shouldBeEqualTo listOf(RoomNotification.Removed(
roomId = A_ROOM_ID
))
}
@Test
fun `given a room with only redacted events when mapping to notification then is Empty`() = testWith(notificationFactory) {
val redactedRoom = mapOf(A_ROOM_ID to listOf(ProcessedEvent(Type.KEEP, A_MESSAGE_EVENT.copy(isRedacted = true))))
val result = redactedRoom.toNotifications(MY_USER_ID, MY_AVATAR_URL)
result shouldBeEqualTo listOf(RoomNotification.Removed(
roomId = A_ROOM_ID
))
}
@Test
fun `given a room with redacted and non redacted message events when mapping to notification then redacted events are removed`() = testWith(notificationFactory) {
val roomWithRedactedMessage = mapOf(A_ROOM_ID to listOf(
ProcessedEvent(Type.KEEP, A_MESSAGE_EVENT.copy(isRedacted = true)),
ProcessedEvent(Type.KEEP, A_MESSAGE_EVENT.copy(eventId = "not-redacted"))
))
val withRedactedRemoved = listOf(A_MESSAGE_EVENT.copy(eventId = "not-redacted"))
val expectedNotification = roomGroupMessageCreator.givenCreatesRoomMessageFor(withRedactedRemoved, A_ROOM_ID, MY_USER_ID, MY_AVATAR_URL)
val result = roomWithRedactedMessage.toNotifications(MY_USER_ID, MY_AVATAR_URL)
result shouldBeEqualTo listOf(expectedNotification)
}
}
fun <T> testWith(receiver: T, block: T.() -> Unit) {
receiver.block()
}
| 86 | null | 418 | 9 | 8781b6bc4c7298ee137571bb574226ff75bd7519 | 6,742 | tchap-android | Apache License 2.0 |
plan/src/main/kotlin/com/r3/demos/ubin2a/plan/NewPlanFlow.kt | project-ubin | 110,582,332 | false | null | package com.r3.demos.ubin2a.plan
import co.paralleluniverse.fibers.Suspendable
import com.r3.demos.ubin2a.obligation.Obligation
import com.r3.demos.ubin2a.plan.generator.ObligationEdge
import com.r3.demos.ubin2a.plan.solver.ComponentCycleSolver
import com.r3.demos.ubin2a.plan.solver.ComponentNettingOptimiser
import com.r3.demos.ubin2a.plan.solver.NettingOptimiserImpl
import net.corda.core.contracts.Amount
import net.corda.core.flows.FlowLogic
import net.corda.core.flows.InitiatingFlow
import net.corda.core.flows.StartableByRPC
import net.corda.core.identity.AbstractParty
import java.util.*
data class NettingPayment(val from: AbstractParty, val to: AbstractParty, val amount: Amount<Currency>) {
override fun toString(): String {
return "NettingPayment(" +
"from=${from.nameOrNull()!!.organisation}, " +
"to=${to.nameOrNull()!!.organisation}, " +
"amount=$amount)"
}
}
@InitiatingFlow
@StartableByRPC
class NewPlanFlow(val obligations: Set<Obligation.State>,
val limits: Map<AbstractParty, Amount<Currency>>, // Would usually just take 'AnonymousParty'.
private val nettingMode: ComponentCycleSolver,
private val extendComponents: Boolean = false
) : FlowLogic<Pair<List<NettingPayment>, List<ObligationEdge>>>() {
@Suspendable
override fun call(): Pair<List<NettingPayment>, List<ObligationEdge>> {
val (_, obligationsMap, cycles) = obligationsGraphFrom(obligations.toList(), extendComponents)
val optimiser = NettingOptimiserImpl(cycles, obligationsMap, limits, logger, { c, o, l, lg ->
ComponentNettingOptimiser(c, o, l, lg, nettingMode)
})
return optimiser.optimise()
}
}
| 3 | Kotlin | 51 | 81 | 8eb2ab9a3decb92b2c258f2c6dd7a2b4e7ca95f8 | 1,750 | ubin-corda | Apache License 2.0 |
src/test/kotlin/no/nav/bidrag/person/hendelse/database/AktorTest.kt | navikt | 517,990,382 | false | {"Kotlin": 171422, "Dockerfile": 147} | package no.nav.bidrag.person.hendelse.database
import io.kotest.matchers.shouldBe
import io.mockk.junit5.MockKExtension
import org.assertj.core.api.SoftAssertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.time.LocalDateTime
@ExtendWith(MockKExtension::class)
class AktorTest {
@Test
fun `teste equals for Aktør`() {
// gitt
val aktør1 = Aktor("1234567891012")
val aktør2 = Aktor("2345678910123")
val aktør3 = Aktor("2345678910123", LocalDateTime.now().minusDays(5))
// hvis
val aktør1VsAktør2 = aktør1.equals(aktør2)
val aktør2VsAktør3 = aktør2.equals(aktør3)
val aktør3VsAktør1 = aktør3.equals(aktør1)
val aktør2VsNull = aktør2.equals(null)
// så
SoftAssertions.assertSoftly {
aktør1VsAktør2 shouldBe false
aktør2VsAktør3 shouldBe true
aktør3VsAktør1 shouldBe false
aktør2VsNull shouldBe false
}
}
}
| 0 | Kotlin | 0 | 0 | b00b38d83c84892ae066688d7112e936c2eb33dd | 1,015 | bidrag-person-hendelse | MIT License |
app/src/main/java/com/wreckingballsoftware/fiveoclocksomewhere/repos/CocktailsRepo.kt | leewaggoner | 691,900,392 | false | {"Kotlin": 68083} | package com.wreckingballsoftware.fiveoclocksomewhere.repos
import com.wreckingballsoftware.fiveoclocksomewhere.database.DBCocktails
import com.wreckingballsoftware.fiveoclocksomewhere.database.DBPlaces
import com.wreckingballsoftware.fiveoclocksomewhere.database.RegionalCocktailsDao
import com.wreckingballsoftware.fiveoclocksomewhere.network.CocktailDBService
import com.wreckingballsoftware.fiveoclocksomewhere.network.NetworkResponse
import com.wreckingballsoftware.fiveoclocksomewhere.network.models.ApiCocktails
import com.wreckingballsoftware.fiveoclocksomewhere.network.toNetworkErrorResponse
import com.wreckingballsoftware.fiveoclocksomewhere.repos.models.Response
import com.wreckingballsoftware.fiveoclocksomewhere.repos.models.UICocktail
import com.wreckingballsoftware.fiveoclocksomewhere.utils.getArticle
import com.wreckingballsoftware.fiveoclocksomewhere.utils.rand
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException
class CocktailsRepo(
private val cocktailDBService: CocktailDBService,
private val regionalCocktailsDao: RegionalCocktailsDao
) {
suspend fun getCocktailById(cocktailId: Long): Response<UICocktail> = withContext(Dispatchers.IO) {
val cocktails = callCocktailApi {
cocktailDBService.getCocktailById(cocktailId.toString())
}
cocktails.toResponse()
}
suspend fun getRandomCocktail(): Response<UICocktail> = withContext(Dispatchers.IO) {
val cocktails = callCocktailApi {
cocktailDBService.getRandomCocktail()
}
cocktails.toResponse()
}
private suspend fun callCocktailApi(
callForCocktail: (suspend () -> ApiCocktails)
): NetworkResponse<ApiCocktails> =
withContext(Dispatchers.IO) {
try {
NetworkResponse.Success(callForCocktail())
} catch (ex: HttpException) {
ex.toNetworkErrorResponse()
} catch (ex: Exception) {
NetworkResponse.Error.UnknownNetworkError(ex)
}
}
suspend fun getCocktailFromWhereIts5OClock(place: DBPlaces): Response<UICocktail> = withContext(Dispatchers.IO) {
val regionalCocktails = regionalCocktailsDao.getAllCocktailsInPlace(place.id)
val cocktail = chooseCocktail(regionalCocktails)
getCocktailInfo(cocktail)
}
private suspend fun getCocktailInfo(dbCocktail: DBCocktails): Response<UICocktail> {
val cocktail = callCocktailApiForDrink(dbCocktail.searchString)
return cocktail.toResponse()
}
private suspend fun callCocktailApiForDrink(cocktail: String): NetworkResponse<ApiCocktails> =
withContext(Dispatchers.IO) {
try {
NetworkResponse.Success(cocktailDBService.getCocktail(cocktail))
} catch (ex: HttpException) {
ex.toNetworkErrorResponse()
} catch (ex: Exception) {
NetworkResponse.Error.UnknownNetworkError(ex)
}
}
private fun chooseCocktail(
cocktails: List<DBCocktails>
): DBCocktails = cocktails[(0 .. cocktails.size).rand()]
}
private fun NetworkResponse<ApiCocktails>.toResponse(): Response<UICocktail> =
when (this) {
is NetworkResponse.Success -> {
if (!data.drinks.isNullOrEmpty()) {
val drink = data.drinks[0]
Response.Success(
UICocktail(
id = drink.id,
name = drink.name,
displayName = "${drink.name.getArticle()} ${drink.name}",
glass = drink.glass,
instructions = drink.instructions,
imageUrl = drink.imageUrl,
ingredients = drink.getIngredientList(),
measures = drink.getMeasuresList(),
attribution = drink.attribution,
)
)
} else {
Response.Error(errorMessage = "Unknown network error.")
}
}
is NetworkResponse.Error -> {
Response.Error(errorMessage = "Error code ${code}: ${exception.localizedMessage}")
}
}
| 0 | Kotlin | 0 | 0 | e08b78c427133dd05db999c08905054a001d0cc6 | 4,244 | fiveoclocksomewherre | Apache License 2.0 |
kcrud-core/src/main/kotlin/kcrud/core/scheduler/api/scheduler/audit/All.kt | perracodex | 682,128,013 | false | {"Kotlin": 664693, "JavaScript": 29018, "CSS": 12683, "HTML": 5862, "Dockerfile": 3127, "Java": 1017} | /*
* Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license.
*/
package ktask.core.scheduler.api.scheduler.audit
import io.ktor.http.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import ktask.core.scheduler.api.SchedulerRouteAPI
import ktask.core.scheduler.audit.AuditService
import ktask.core.scheduler.model.audit.AuditLog
/**
* Returns all existing audit logs for the scheduler.
*/
@SchedulerRouteAPI
internal fun Route.schedulerAllAuditRoute() {
/**
* Returns all existing audit logs for the scheduler.
* @OpenAPITag Scheduler - Maintenance
*/
get("scheduler/audit") {
val audit: List<AuditLog> = AuditService.findAll()
call.respond(status = HttpStatusCode.OK, message = audit)
}
}
| 0 | Kotlin | 0 | 2 | dccf9121b3686f31cf487938e5ade3d2411707d4 | 795 | kcrud | MIT License |
fireko-codegen/src/main/java/de/musichin/fireko/processor/genDocumentSnapshotDeserializer.kt | musichin | 272,263,347 | false | null | package de.musichin.fireko.processor
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.STRING
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview
@KotlinPoetMetadataPreview
internal fun genDocumentSnapshotDeserializer(context: Context, target: TargetClass) = FunSpec
.builder(toType(target.type))
.addKdoc("Converts %T to %T.", FIREBASE_DOCUMENT_SNAPSHOT, target.type)
.receiver(FIREBASE_DOCUMENT_SNAPSHOT)
.returns(target.type.asNullable())
.beginControlFlow("if (!exists())")
.addStatement("return null")
.endControlFlow()
.addCode(CodeBlock.builder().generateBody(context, target).build())
.build()
@KotlinPoetMetadataPreview
private fun CodeBlock.Builder.generateBody(
context: Context,
target: TargetClass
): CodeBlock.Builder = apply {
val params = target.params
genProperties(context, params)
genTargetClassInitializer(target)
}
@KotlinPoetMetadataPreview
private fun CodeBlock.Builder.genProperties(
context: Context,
params: List<TargetParameter>
) {
params.forEach { param ->
add("%L", generateLocalProperty(context, param))
}
}
@KotlinPoetMetadataPreview
private fun generateLocalProperty(context: Context, param: TargetParameter): PropertySpec =
PropertySpec
.builder(param.name, param.propertyType)
.initializer(generateInitializer(context, param))
.build()
@KotlinPoetMetadataPreview
private fun generateInitializer(context: Context, param: TargetParameter): CodeBlock {
val name = param.propertyName
val type = param.type
if (param.documentId) {
return CodeBlock.builder().add("getId()").convert(STRING, type).build()
}
if (param.embedded) {
type as ClassName
return CodeBlock.builder()
.add("this%L", invokeToType(type.asNotNullable()))
.convert(type.asNullable(), type.asNullable())
.assertNotNull(param)
.build()
}
val adapter = param.usingAdapter?.let { context.adapterElement(it) }
?: context.getAnnotatedAdapter(type)
if (adapter != null) {
return if (adapter.readFunSpec != null) {
val sourceType = adapter.readFunSpec.parameters.first().type
CodeBlock.builder()
.add(getBaseInitializer(context, name, sourceType))
.deserialize(context, sourceType.asNullable(), true)
.add("?.let(%L::%L)", adapter.className, adapter.readFunSpec.name)
.assertNotNull(param)
.build()
} else {
CodeBlock.of("Adapter should contain read method.")
}
}
return CodeBlock.builder()
.add(getBaseInitializer(context, name, type))
.deserialize(context, type.asNullable(), true)
.assertNotNull(param)
.build()
}
@KotlinPoetMetadataPreview
private fun CodeBlock.Builder.assertNotNull(param: TargetParameter) = apply {
if (!param.type.isNullable && !param.hasDefaultValue) {
add(
"?: throw NullPointerException(%S)",
"Property ${param.propertyName} is absent or null."
)
}
}
@KotlinPoetMetadataPreview
private fun getBaseInitializer(context: Context, name: String, type: TypeName) =
when (ValueType.valueOf(context, type)) {
null -> CodeBlock.of("get(%S)", name)
ValueType.BOOLEAN -> CodeBlock.of("getBoolean(%S)", name)
ValueType.INTEGER -> CodeBlock.of("getLong(%S)", name)
ValueType.DOUBLE -> CodeBlock.of("getDouble(%S)", name)
ValueType.STRING -> CodeBlock.of("getString(%S)", name)
ValueType.BYTES -> CodeBlock.of("getBlob(%S)", name)
ValueType.GEO_POINT -> CodeBlock.of("getGeoPoint(%S)", name)
ValueType.REFERENCE -> CodeBlock.of("getDocumentReference(%S)", name)
ValueType.TIMESTAMP -> CodeBlock.of("getTimestamp(%S)", name)
ValueType.MAP,
ValueType.ARRAY ->
CodeBlock.of("(get(%S) as %T)", name, ValueType.typeOf(context, type).asNullable())
}
@KotlinPoetMetadataPreview
private val TargetParameter.propertyType: TypeName
get() = type.copy(nullable = type.isNullable || hasDefaultValue)
@KotlinPoetMetadataPreview
private val TargetClass.resultName: String
get() = findFreeParamName("result")
| 5 | Kotlin | 0 | 2 | 8c36bf692ec037b63fffd3d0b3f3db986a965a7a | 4,474 | fireko | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/appsync/LambdaConflictHandlerConfigPropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.appsync
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.appsync.CfnResolver
@Generated
public fun buildLambdaConflictHandlerConfigProperty(initializer: @AwsCdkDsl
CfnResolver.LambdaConflictHandlerConfigProperty.Builder.() -> Unit):
CfnResolver.LambdaConflictHandlerConfigProperty =
CfnResolver.LambdaConflictHandlerConfigProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | a1cf8fbfdfef9550b3936de2f864543edb76348b | 513 | aws-cdk-kt | Apache License 2.0 |
hammer-core/src/main/kotlin/dev/vini2003/hammer/core/api/common/util/extension/PacketByteBufExtension.kt | Shnupbups | 497,613,399 | true | {"Kotlin": 647205, "Java": 143999, "GLSL": 925} | /*
* MIT License
*
* Copyright (c) 2020 - 2022 vini2003
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.vini2003.hammer.core.api.common.util.extension
import dev.vini2003.hammer.core.api.common.math.position.Position
import dev.vini2003.hammer.core.api.common.math.size.Size
import net.minecraft.client.util.math.Vector2f
import net.minecraft.client.util.math.Vector3d
import net.minecraft.network.PacketByteBuf
import net.minecraft.tag.TagKey
import net.minecraft.util.math.*
import net.minecraft.util.registry.RegistryKey
fun PacketByteBuf.writePosition(value: Position) {
writeFloat(value.x)
writeFloat(value.y)
writeFloat(value.z)
}
fun PacketByteBuf.readPosition(): Position {
return Position(readFloat(), readFloat(), readFloat())
}
fun PacketByteBuf.writeSize(value: Size) {
writeFloat(value.width)
writeFloat(value.height)
writeFloat(value.length)
}
fun PacketByteBuf.readSize(): Size {
return Size(readFloat(), readFloat(), readFloat())
}
fun <T> PacketByteBuf.writeRegistryKey(value: RegistryKey<T>) {
writeIdentifier(value.method_41185())
writeIdentifier(value.value)
}
fun <T> PacketByteBuf.readRegistryKey(): RegistryKey<T> {
val registryId = readIdentifier()
val id = readIdentifier()
return RegistryKey.of(RegistryKey.ofRegistry(registryId), id)
}
fun <T> PacketByteBuf.writeTagKey(value: TagKey<T>) {
writeIdentifier(value.registry.value)
writeIdentifier(value.id)
}
fun <T> PacketByteBuf.readTagKey(): TagKey<T> {
val registryId = readIdentifier()
val tagId = readIdentifier()
return TagKey.of(RegistryKey.ofRegistry(registryId), tagId)
}
fun PacketByteBuf.writeVec2f(value: Vec2f) {
writeFloat(value.x)
writeFloat(value.y)
}
fun PacketByteBuf.readVec2f(): Vec2f {
return Vec2f(readFloat(), readFloat())
}
fun PacketByteBuf.writeVec3d(value: Vec3d) {
writeDouble(value.x)
writeDouble(value.y)
writeDouble(value.z)
}
fun PacketByteBuf.readVec3d(): Vec3d {
return Vec3d(readDouble(), readDouble(), readDouble())
}
fun PacketByteBuf.writeVec3f(value: Vec3f) {
writeFloat(value.x)
writeFloat(value.y)
writeFloat(value.z)
}
fun PacketByteBuf.readVec3f(): Vec3f {
return Vec3f(readFloat(), readFloat(), readFloat())
}
fun PacketByteBuf.writeVec3i(value: Vec3i) {
writeInt(value.x)
writeInt(value.y)
writeInt(value.z)
}
fun PacketByteBuf.readVec3i(): Vec3i {
return Vec3i(readInt(), readInt(), readInt())
}
fun PacketByteBuf.writeVector2f(value: Vector2f) {
writeFloat(value.x)
writeFloat(value.y)
}
fun PacketByteBuf.readVector2f(): Vector2f {
return Vector2f(readFloat(), readFloat())
}
fun PacketByteBuf.writeVector3d(value: Vector3d) {
writeDouble(value.x)
writeDouble(value.y)
writeDouble(value.z)
}
fun PacketByteBuf.readVector3d(): Vector3d {
return Vector3d(readDouble(), readDouble(), readDouble())
}
fun PacketByteBuf.writeVector4f(value: Vector4f) {
writeFloat(value.x)
writeFloat(value.y)
writeFloat(value.z)
writeFloat(value.w)
}
fun PacketByteBuf.readVector4f(): Vector4f {
return Vector4f(readFloat(), readFloat(), readFloat(), readFloat())
}
fun PacketByteBuf.writeQuaternion(value: Quaternion) {
writeFloat(value.x)
writeFloat(value.y)
writeFloat(value.z)
writeFloat(value.w)
}
fun PacketByteBuf.readQuaternion(): Quaternion {
return Quaternion(readFloat(), readFloat(), readFloat(), readFloat())
} | 0 | null | 0 | 0 | b08882400350ae95672e24b2696be04c04e15140 | 4,351 | Hammer | MIT License |
src/main/kotlin/dev/kkorolyov/ponk/Launcher.kt | kkorolyov | 363,740,075 | false | null | package dev.kkorolyov.ponk
import dev.kkorolyov.pancake.audio.jfx.system.AudioSystem
import dev.kkorolyov.pancake.core.component.ActionQueue
import dev.kkorolyov.pancake.core.component.Bounds
import dev.kkorolyov.pancake.core.component.Transform
import dev.kkorolyov.pancake.core.component.movement.Damping
import dev.kkorolyov.pancake.core.component.movement.Force
import dev.kkorolyov.pancake.core.component.movement.Mass
import dev.kkorolyov.pancake.core.component.movement.Velocity
import dev.kkorolyov.pancake.core.component.movement.VelocityCap
import dev.kkorolyov.pancake.core.event.EntitiesIntersected
import dev.kkorolyov.pancake.core.system.AccelerationSystem
import dev.kkorolyov.pancake.core.system.ActionSystem
import dev.kkorolyov.pancake.core.system.CappingSystem
import dev.kkorolyov.pancake.core.system.CollisionSystem
import dev.kkorolyov.pancake.core.system.DampingSystem
import dev.kkorolyov.pancake.core.system.IntersectionSystem
import dev.kkorolyov.pancake.core.system.MovementSystem
import dev.kkorolyov.pancake.editor.openEditor
import dev.kkorolyov.pancake.editor.registerEditor
import dev.kkorolyov.pancake.graphics.jfx.component.Graphic
import dev.kkorolyov.pancake.graphics.jfx.component.Lens
import dev.kkorolyov.pancake.graphics.jfx.drawable.Oval
import dev.kkorolyov.pancake.graphics.jfx.drawable.Rectangle
import dev.kkorolyov.pancake.graphics.jfx.drawable.Text
import dev.kkorolyov.pancake.graphics.jfx.system.CameraSystem
import dev.kkorolyov.pancake.graphics.jfx.system.DrawSystem
import dev.kkorolyov.pancake.input.jfx.Compensated
import dev.kkorolyov.pancake.input.jfx.Reaction
import dev.kkorolyov.pancake.input.jfx.component.Input
import dev.kkorolyov.pancake.input.jfx.system.InputSystem
import dev.kkorolyov.pancake.platform.Config
import dev.kkorolyov.pancake.platform.GameEngine
import dev.kkorolyov.pancake.platform.GameLoop
import dev.kkorolyov.pancake.platform.Resources
import dev.kkorolyov.pancake.platform.action.Action
import dev.kkorolyov.pancake.platform.entity.EntityPool
import dev.kkorolyov.pancake.platform.event.EventLoop
import dev.kkorolyov.pancake.platform.math.Vector3
import dev.kkorolyov.pancake.platform.math.Vectors
import dev.kkorolyov.pancake.platform.plugin.DeferredConverterFactory
import dev.kkorolyov.pancake.platform.plugin.Plugins
import dev.kkorolyov.pancake.platform.registry.Registry
import dev.kkorolyov.pancake.platform.registry.ResourceReader
import dev.kkorolyov.ponk.component.Follow
import dev.kkorolyov.ponk.component.Score
import dev.kkorolyov.ponk.system.FollowSystem
import dev.kkorolyov.ponk.system.ScoreSystem
import javafx.application.Platform
import javafx.event.EventHandler
import javafx.scene.canvas.Canvas
import javafx.scene.image.Image
import javafx.scene.input.KeyCode
import javafx.scene.layout.TilePane
import javafx.scene.paint.Color
import javafx.stage.Stage
import tornadofx.App
import tornadofx.View
val pane = TilePane()
val actions = Resources.inStream("actions.yaml").use {
Registry<String, Action>().apply {
load(
ResourceReader(Plugins.deferredConverter(DeferredConverterFactory.ActionStrat::class.java)).fromYaml(
it
)
)
}
}
val paddleVelocityCap = VelocityCap(Vectors.create(0.0, 20.0, 20.0))
val paddleDamping = Damping(Vectors.create(0.0, 0.0, 0.0))
val paddleMass = Mass(1e-2)
val ballMass = Mass(1e-9)
val paddleSize: Vector3 = Vectors.create(1.0, 4.0, 0.0)
val ballSize: Vector3 = Vectors.create(1.0, 1.0, 0.0)
val goalSize: Vector3 = Vectors.create(2.0, 10.0, 0.0)
val netSize: Vector3 = Vectors.create(10.0, 2.0, 0.0)
val ballTransform = Transform(Vectors.create(0.0, 0.0, 0.0))
val paddleBounds = Bounds.box(paddleSize)
val ballBounds = Bounds.round(ballSize.x / 2)
val goalBounds = Bounds.box(goalSize)
val netBounds = Bounds.box(netSize)
val paddleGraphic: Graphic = Graphic(Rectangle(paddleSize, Color.BLACK))
val ballGraphic: Graphic = Graphic(Oval(ballSize, Color.GRAY))
val goalGraphic: Graphic = Graphic(Rectangle(goalSize, Color.BLUE))
val netGraphic: Graphic = Graphic(Rectangle(netSize, Color.RED))
val events: EventLoop.Broadcasting = EventLoop.Broadcasting()
val entities: EntityPool = EntityPool(events).apply {
val camera = create().apply {
put(
Transform(Vectors.create(0.0, 0.0, 0.0)),
Lens(
Canvas().apply {
pane.children += this
widthProperty().bind(pane.widthProperty())
heightProperty().bind(pane.heightProperty())
},
Vectors.create(64.0, 64.0)
)
)
}
val ball = create().apply {
put(
ballGraphic,
ballBounds,
ballTransform,
Velocity(Vectors.create(0.0, 0.0, 0.0)),
VelocityCap(Vectors.create(50.0, 50.0, 0.0)),
Force(Vectors.create(0.0, 0.0, 0.0)),
ballMass,
ActionQueue()
)
Resources.inStream("ballInput.yaml").use {
put(
Input(
Reaction.matchType(
Reaction.whenCode(
KeyCode.SPACE to Reaction.keyToggle(Compensated(actions["reset"], Action { }))
)
)
)
)
}
}
val player = create().apply {
put(
paddleGraphic,
paddleBounds,
Transform(Vectors.create(-4.0, 0.0, 0.0)),
Velocity(Vectors.create(0.0, 0.0, 0.0)),
paddleVelocityCap,
paddleDamping,
Force(Vectors.create(0.0, 0.0, 0.0)),
paddleMass,
ActionQueue()
)
Resources.inStream("input.yaml").use {
put(
Input(
Reaction.matchType(
Reaction.whenCode(
KeyCode.W to Reaction.keyToggle(Compensated(actions["forceUp"], actions["forceDown"])),
KeyCode.S to Reaction.keyToggle(Compensated(actions["forceDown"], actions["forceUp"])),
)
)
)
)
}
}
val opponent = create().apply {
put(
paddleGraphic,
paddleBounds,
Transform(Vectors.create(4.0, 0.0, 0.0)),
Velocity(Vectors.create(0.0, 0.0, 0.0)),
paddleVelocityCap,
paddleDamping,
Force(Vectors.create(0.0, 0.0, 0.0)),
paddleMass,
Follow(ballTransform.position, 0.2)
)
}
val goalPlayer = create().apply {
put(
goalBounds,
goalGraphic,
Transform(Vectors.create(-6.0, 0.0, 0.0)),
Score()
)
}
val goalOpponent = create().apply {
put(
goalBounds,
goalGraphic,
Transform(Vectors.create(6.0, 0.0, 0.0)),
Score()
)
}
val top = create().apply {
put(
netBounds,
netGraphic,
Transform(Vectors.create(0.0, 6.0, 0.0))
)
}
val bottom = create().apply {
put(
netBounds,
netGraphic,
Transform(Vectors.create(0.0, -6.0, 0.0))
)
}
val playerScoreText = create().apply {
put(
Transform(Vectors.create(-4.0, -4.0, 1.0)),
Graphic(makeScoreText(0))
)
}
val opponentScoreText = create().apply {
put(
Transform(Vectors.create(4.0, -4.0, 1.0)),
Graphic(makeScoreText(0))
)
}
val helpText = create().apply {
put(
Transform(Vectors.create(-0.5, -4.0, 1.0)),
Graphic(Text("Press SPACE to reset", 2.0, Color.BLACK))
)
}
events.register(EntitiesIntersected::class.java) {
for (id in listOf(it.a, it.b).map { it.id }) {
if (goalPlayer.id == id) {
opponentScoreText.put(Graphic(makeScoreText(goalPlayer.get(Score::class.java).value)))
} else if (goalOpponent.id == id) {
playerScoreText.put(Graphic(makeScoreText(goalOpponent.get(Score::class.java).value)))
}
}
}
}
val gameLoop = GameLoop(
GameEngine(
events,
entities,
listOf(
CollisionSystem(),
ActionSystem(),
InputSystem(listOf(pane)),
AccelerationSystem(),
CappingSystem(),
MovementSystem(),
DampingSystem(),
IntersectionSystem(),
AudioSystem(),
CameraSystem(),
DrawSystem(),
FollowSystem(),
ScoreSystem()
)
)
)
fun main() {
Platform.startup {
Launcher(gameLoop)
}
gameLoop.start()
}
private fun makeScoreText(score: Int): Text = Text(score.toString(), 1.0, Color.GREEN)
class Launcher(private val gameLoop: GameLoop) : App(MainView::class) {
init {
registerEditor(gameLoop)
start(Stage())
}
override fun start(stage: Stage) {
stage.icons += Image(Config.get().getProperty("icon"))
stage.width = Config.get().getProperty("width").toDouble()
stage.height = Config.get().getProperty("height").toDouble()
stage.onCloseRequest = EventHandler { gameLoop.stop() }
super.start(stage)
}
}
class MainView : View(Config.get().getProperty("title")) {
override val root = pane
override fun onDock() {
root.requestFocus()
currentStage?.let { curStage ->
curStage.scene?.onKeyPressed = EventHandler { e ->
when (e.code) {
KeyCode.F1 -> openEditor(curStage)
else -> {}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 73672bf6d7e4ea859d433ecf639e887b9538c7dc | 8,430 | ponk | MIT License |
app/src/main/java/com/base/searchapp/ui/base/viewmodel/BaseActivityViewModel.kt | uygemre | 335,039,935 | false | null | package com.base.searchapp.ui.base.viewmodel
abstract class BaseActivityViewModel : BaseViewControllerViewModel() | 0 | Kotlin | 0 | 0 | 24c32e066a2680aed91a0932eee48fae490597d8 | 114 | SearchApp | MIT License |
app/src/main/java/com/example/careerboast/view/navigation/Screen.kt | Ev4esem | 771,869,351 | false | {"Kotlin": 125189} | package com.example.careerboast.view.navigation
sealed class Screen(
val route : String
) {
object LOGIN_SCREEN : Screen("LoginScreen")
object INTERVIEWS_SCREEN : Screen("InterviewsScreen")
object INTERVIEW_SCREEN : Screen("InterviewScreen")
object MENTORS_SCREEN : Screen("MentorsScreen")
object INTERSHIPS_SCREEN : Screen("IntershipsScreen")
object SPECIALITY_SCREEN : Screen("SpecialityScreen")
object FEEDBACK_SCREEN : Screen("FeedbackScreen")
object DETAILS_MENTOR_SCREEN : Screen("DetailsMentorScreen")
object DETAILS_JOB_SCREEN : Screen("FeedbackScreen")
object FAVORITE_JOB_SCREEN : Screen("FavoriteScreen")
object JOBS_TO_FAVORITE_SCREEN : Screen("jobsToFavoriteScreen")
}
| 0 | Kotlin | 0 | 0 | 2bd9ed82e8195294480e361919d1a5cc26ec8f86 | 734 | CareerBoast | Apache License 2.0 |
app/src/main/java/pl/droidsonroids/toast/app/base/BaseActivity.kt | l-o-b-s-t-e-r | 126,404,496 | true | {"Kotlin": 377167, "Prolog": 102} | package pl.droidsonroids.toast.app.base
import android.arch.lifecycle.ViewModelProvider
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
abstract class BaseActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>
override fun supportFragmentInjector(): AndroidInjector<Fragment> = fragmentInjector
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
}
} | 0 | Kotlin | 0 | 0 | b33bb2419802e936cec67f771b067adda92f2117 | 886 | Toast-App | Apache License 2.0 |
collaboration-suite-phone-ui/src/main/java/com/kaleyra/collaboration_suite_phone_ui/call/dialogs/KaleyraSnapshotDialog.kt | Bandyer | 337,367,845 | false | null | /*
* Copyright 2022 Kaleyra @ https://www.kaleyra.com
*
* 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.kaleyra.collaboration_suite_phone_ui.call.dialogs
import android.content.DialogInterface
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.OvershootInterpolator
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.ContextThemeWrapper
import androidx.fragment.app.DialogFragment
import com.ablanco.zoomy.ZoomListener
import com.ablanco.zoomy.Zoomy
import com.kaleyra.collaboration_suite_phone_ui.R
import com.kaleyra.collaboration_suite_phone_ui.bottom_sheet.KaleyraBottomSheetDialog
import com.kaleyra.collaboration_suite_phone_ui.call.layout.KaleyraSnapshotDialogLayout
import com.kaleyra.collaboration_suite_phone_ui.dialogs.KaleyraDialog
import com.kaleyra.collaboration_suite_phone_ui.extensions.*
/**
*
* @author kristiyan
*/
class KaleyraSnapshotDialog : KaleyraDialog<KaleyraSnapshotDialog.SnapshotDialogFragment> {
override val id: String = "KaleyraSnapshotDialog"
override var dialog: SnapshotDialogFragment? = null
override fun show(activity: androidx.fragment.app.FragmentActivity) {
if (dialog == null) dialog = SnapshotDialogFragment()
dialog!!.show(activity.supportFragmentManager, id)
}
/**
* @suppress
*/
class SnapshotDialogFragment : KaleyraBottomSheetDialog() {
private var confirmDialog: AlertDialog? = null
private var saved = false
private var zoomy: Zoomy.Builder? = null
private var rootView: KaleyraSnapshotDialogLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.KaleyraCollaborationSuiteUI_BottomSheetDialog_Snapshot)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = KaleyraSnapshotDialogLayout(ContextThemeWrapper(context, R.style.KaleyraCollaborationSuiteUI_BottomSheetDialog_Snapshot_Layout))
return rootView
}
override fun onStart() {
super.onStart()
dialog ?: return
dialog!!.window!!.decorView.fitsSystemWindows = false
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
dismiss()
KaleyraSnapshotDialog().apply {
context?.scanForFragmentActivity()?.let {
this.show(it)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// see https://github.com/imablanco/Zoomy/issues/19
dialog?.window?.decorView?.setOnTouchListener { v, event ->
rootView?.binding?.kaleyraSnapshotPreview?.dispatchTouchEvent(event)
v.performClick()
}
zoomy = Zoomy.Builder(this.dialog).target(rootView?.binding?.kaleyraSnapshotPreview)
.enableImmersiveMode(false)
.interpolator(OvershootInterpolator())
.animateZooming(true)
.doubleTapListener {
rootView?.binding?.kaleyraSnapshotShareSaveButton?.visibility = View.VISIBLE
rootView?.binding?.kaleyraSnapshotShareCloseButton?.visibility = View.VISIBLE
rootView?.binding?.kaleyraSnapshotShareWhiteboardButton?.visibility = View.VISIBLE
}
.tapListener {
rootView?.binding?.kaleyraSnapshotShareSaveButton?.visibility = View.VISIBLE
rootView?.binding?.kaleyraSnapshotShareCloseButton?.visibility = View.VISIBLE
rootView?.binding?.kaleyraSnapshotShareWhiteboardButton?.visibility = View.VISIBLE
}
.zoomListener(object : ZoomListener {
override fun onViewEndedZooming(view: View?) {
rootView?.binding?.kaleyraSnapshotShareSaveButton?.visibility = View.VISIBLE
rootView?.binding?.kaleyraSnapshotShareCloseButton?.visibility = View.VISIBLE
rootView?.binding?.kaleyraSnapshotShareWhiteboardButton?.visibility = View.VISIBLE
}
override fun onViewStartedZooming(view: View?) {
rootView?.binding?.kaleyraSnapshotShareSaveButton?.visibility = View.INVISIBLE
rootView?.binding?.kaleyraSnapshotShareCloseButton?.visibility = View.INVISIBLE
rootView?.binding?.kaleyraSnapshotShareWhiteboardButton?.visibility = View.INVISIBLE
}
})
zoomy!!.register()
rootView?.binding?.kaleyraSnapshotShareSaveButton?.setOnClickListener {
saved = true
Toast.makeText(context, context?.resources?.getString(R.string.kaleyra_snapshot_saved_in_gallery), Toast.LENGTH_SHORT).show()
}
rootView?.binding?.kaleyraSnapshotShareCloseButton?.setOnClickListener {
if (saved) {
dismiss()
return@setOnClickListener
}
showDialog(context?.resources?.getString(R.string.kaleyra_alert_discard_snapshot_title) ?: "",
context?.resources?.getString(R.string.kaleyra_alert_discard_snapshot_message) ?: "", {
dismiss()
}, {
})
}
rootView?.binding?.kaleyraSnapshotShareWhiteboardButton?.setOnClickListener {
if (!saved)
showDialog(context?.resources?.getString(R.string.kaleyra_alert_save_snapshot_title) ?: "",
context?.resources?.getString(R.string.kaleyra_alert_save_snapshot_message) ?: "", {
}, {
})
}
}
override fun onExpanded() {}
override fun onCollapsed() {}
override fun onDialogWillShow() {
}
override fun onSlide(offset: Float) {}
override fun onStateChanged(newState: Int) {}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
confirmDialog?.dismiss()
Zoomy.unregister(rootView?.binding?.kaleyraSnapshotPreview)
}
private fun showDialog(title: String, body: String, positiveCallback: () -> Unit, negativeCallback: () -> Unit) {
confirmDialog = AlertDialog.Builder(requireContext(), R.style.KaleyraCollaborationSuiteUI_AlertDialogTheme)
.setTitle(title)
.setCancelable(true)
.setPositiveButton(context?.resources?.getString(R.string.kaleyra_confirm_message)) { dialog, which ->
positiveCallback.invoke()
}
.setNegativeButton(context?.resources?.getString(R.string.kaleyra_cancel_message)) { dialog, which ->
negativeCallback.invoke()
}
.setMessage(body)
.show()
}
}
} | 1 | null | 1 | 2 | 626da0b71293360bf7708835876b1a8b2db530b4 | 8,102 | Bandyer-Android-Design | Apache License 2.0 |
gradle-dsl-toml/src/com/android/tools/idea/gradle/dsl/toml/catalog/CatalogTomlDslWriter.kt | JetBrains | 60,701,247 | false | {"Kotlin": 49550960, "Java": 35837871, "HTML": 1217714, "Starlark": 909188, "C++": 357481, "Python": 106384, "C": 71782, "Lex": 66732, "NSIS": 58538, "AIDL": 35382, "Shell": 26938, "CMake": 26798, "JavaScript": 18437, "Smali": 7580, "Batchfile": 6951, "RenderScript": 4411, "Makefile": 2495, "IDL": 269, "QMake": 18} | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.dsl.toml.catalog
import com.android.tools.idea.gradle.dsl.model.BuildModelContext
import com.android.tools.idea.gradle.dsl.toml.TomlDslWriter
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslElement
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslExpressionList
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslExpressionMap
import com.android.tools.idea.gradle.dsl.parser.elements.GradleNameElement
import com.android.tools.idea.gradle.dsl.parser.files.GradleDslFile
import com.android.tools.idea.gradle.dsl.parser.findLastPsiElementIn
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.findParentOfType
import org.toml.lang.psi.TomlArray
import org.toml.lang.psi.TomlElementTypes
import org.toml.lang.psi.TomlFile
import org.toml.lang.psi.TomlInlineTable
import org.toml.lang.psi.TomlKeyValue
import org.toml.lang.psi.TomlLiteral
import org.toml.lang.psi.TomlPsiFactory
import org.toml.lang.psi.TomlTable
class CatalogTomlDslWriter(context: BuildModelContext): TomlDslWriter(context), CatalogTomlDslNameConverter {
val tables = listOf("versions", "libraries", "plugins", "bundles")
override fun createDslElement(element: GradleDslElement): PsiElement? {
element.psiElement?.let { return it }
val parentPsiElement = ensureParentPsi(element) ?: return null
val project = parentPsiElement.project
val factory = TomlPsiFactory(project)
val comma = factory.createInlineTable("a = \"b\", c = \"d\"").children[2]
val name = normalizeName(element.fullName)
val psi = when (element.parent) {
is GradleDslFile -> when (element) {
is GradleDslExpressionMap -> factory.createTable(name)
else -> factory.createKeyValue(name, "\"placeholder\"")
}
is GradleDslExpressionList -> when (element) {
is GradleDslExpressionList -> factory.createArray("")
is GradleDslExpressionMap -> factory.createInlineTable(" ")
else -> factory.createLiteral("\"placeholder\"")
}
else -> when (element) {
is GradleDslExpressionMap -> factory.createKeyValue(name, "{ }")
is GradleDslExpressionList -> factory.createKeyValue(name, "[]")
else -> factory.createKeyValue(name, "\"placeholder\"")
}
}
if (psi is TomlTable && name in tables) {
return insertTable(psi, parentPsiElement, element, factory)
}
val anchor = getAnchorPsi(parentPsiElement, element.anchor)
val addedElement = parentPsiElement.addAfter(psi, anchor)
if (anchor != null) {
when (parentPsiElement) {
is TomlTable, is TomlFile -> addedElement.addAfter(factory.createNewline(), null)
is TomlInlineTable -> when {
parentPsiElement.entries.size == 1 -> Unit
anchor is LeafPsiElement && anchor.elementType == TomlElementTypes.L_CURLY -> parentPsiElement.addAfter(comma, addedElement)
else -> parentPsiElement.addBefore(comma, addedElement)
}
is TomlArray -> when {
parentPsiElement.elements.size == 1 -> Unit
anchor is LeafPsiElement && anchor.elementType == TomlElementTypes.L_BRACKET -> parentPsiElement.addAfter(comma, addedElement)
else -> parentPsiElement.addBefore(comma, addedElement)
}
}
}
when (addedElement) {
is TomlKeyValue -> element.psiElement = addedElement.value
else -> element.psiElement = addedElement
}
return element.psiElement
}
override fun deleteDslElement(element: GradleDslElement) {
val psiElement = element.psiElement ?: return
val parent = element.parent ?: return
val parentPsi = ensureParentPsi(element)
when (parent) {
is GradleDslFile -> psiElement.findParentOfType<TomlKeyValue>()?.delete()
is GradleDslExpressionMap -> when (parentPsi) {
is TomlTable -> psiElement.findParentOfType<TomlKeyValue>()?.delete()
is TomlInlineTable -> deletePsiParentOfTypeFromDslParent<GradleDslExpressionMap, TomlKeyValue>(element, psiElement, parent)
}
is GradleDslExpressionList -> when (parentPsi) {
is TomlArray -> deletePsiParentOfTypeFromDslParent<GradleDslExpressionList, TomlLiteral>(element, psiElement, parent)
}
}
}
private fun insertTable(psiElement: TomlTable, file: PsiElement, element: GradleDslElement, factory: TomlPsiFactory): PsiElement? =
insertTable(psiElement, file, factory).also { element.psiElement = it }
private fun insertTable(psiElement: TomlTable, file: PsiElement, factory: TomlPsiFactory): PsiElement? {
val index = psiElement.orderIndex()
val existingTables = file.children.filterIsInstance<TomlTable>()
// first element is always 0
val constraints = existingTables.map { c -> c.orderIndex() }.runningFold(0, ::maxOf)
val position = constraints.withIndex().reversed().find { index >= it.value }
check(position != null)
return if (file.children.isEmpty() || position.index == 0) {
val addedElement = file.addAfter(psiElement, null)
if (existingTables.isNotEmpty()) file.addAfter(factory.createNewline(), addedElement)
addedElement
}
else {
val addedElement = file.addAfter(psiElement, existingTables[position.index-1])
file.addBefore(factory.createNewline(), addedElement)
addedElement
}
}
private fun TomlTable.orderIndex() = tables.indexOf(header.key?.text)
private fun getAnchorPsi(parent: PsiElement, anchorDsl: GradleDslElement?): PsiElement? {
var anchor = anchorDsl?.let{ findLastPsiElementIn(it) }
if (anchor == null && (parent is TomlInlineTable || parent is TomlArray)) return parent.firstChild
if (anchor == null && parent is TomlTable) return parent.header
while (anchor != null && anchor.parent != parent) {
anchor = anchor.parent
}
return anchor ?: parent
}
private fun normalizeName(name: String): String {
val unescaped = GradleNameElement.unescape(name)
return when {
unescaped == "version.ref" -> unescaped // TODO need to fix GradleDslVersionLiteral eventually - b/300075092
"[A-Za-z0-9_-]+".toRegex().matches(unescaped) -> unescaped
else -> "\"$unescaped\""
}
}
} | 3 | Kotlin | 219 | 921 | dbd9aeae0dc5b8c56ce2c7d51208ba26ea0f169b | 6,893 | android | Apache License 2.0 |
shared/domain/movie/src/main/java/com/kennethss/movie/domain/movie/preview/Preview.kt | KennethSS | 325,671,801 | false | null | package com.kennethss.movie.domain.movie.preview
data class Preview(
val key: String,
val name: String,
val site: Site,
val type: Type
) {
enum class Type {
TRAILER,
TEASER,
FEATURETTE
}
enum class Site {
YOUTUBE
}
} | 0 | Kotlin | 1 | 9 | e72bcf9a3c7b63862e41787bf45f4991cefc27dd | 282 | Movie | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.