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/alex/location/helper/OnExceptionListener.kt
equinox2333
750,623,509
false
{"Kotlin": 37794, "Java": 5752}
package com.alex.location.helper /** * 异常回调 */ interface OnExceptionListener { /** * Callback this method on exception * [errorCode] -> [LocationErrorCode] * [e] -> [Exception] */ fun onException(@LocationErrorCode errorCode: Int, e: Exception) }
0
Kotlin
0
0
f373edd852a72e1975c15a2316f6930e4b616629
278
MAS-Homework1-Location
MIT License
Framework/src/test/kotlin/net/milosvasic/factory/test/implementation/StubSSHCommand.kt
Server-Factory
326,063,014
true
{"Kotlin": 470923, "Shell": 188}
package net.milosvasic.factory.test.implementation import net.milosvasic.factory.execution.flow.implementation.ObtainableTerminalCommand import net.milosvasic.factory.remote.Remote import net.milosvasic.factory.remote.ssh.SSHCommand import net.milosvasic.factory.terminal.TerminalCommand class StubSSHCommand @Throws(IllegalStateException::class) constructor(remote: Remote, command: TerminalCommand) : @Throws(IllegalStateException::class) SSHCommand( remote, command, sshCommand = if (command is ObtainableTerminalCommand) { command.obtainable.obtain().command } else { command.command } )
0
Kotlin
0
1
7c9a48ac22541c01d56cb7ed404348f9dbcf6d6d
671
Core-Framework
Apache License 2.0
app/src/main/java/io/geeteshk/hyper/ui/adapter/LogsAdapter.kt
geeteshk
67,724,412
false
null
/* * Copyright 2016 <NAME> <<EMAIL>> * * 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.geeteshk.hyper.ui.adapter import android.graphics.Color import android.view.View import android.view.ViewGroup import android.webkit.ConsoleMessage import androidx.annotation.ColorInt import androidx.recyclerview.widget.RecyclerView import io.geeteshk.hyper.R import io.geeteshk.hyper.extensions.inflate import kotlinx.android.synthetic.main.item_log.view.* class LogsAdapter(private val localWithoutIndex: String, private val jsLogs: List<ConsoleMessage>, private val darkTheme: Boolean) : RecyclerView.Adapter<LogsAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val rootView = parent.inflate(R.layout.item_log) return ViewHolder(rootView) } override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(jsLogs[position]) override fun getItemCount(): Int = jsLogs.size inner class ViewHolder(private var v: View) : RecyclerView.ViewHolder(v) { fun bind(consoleMessage: ConsoleMessage) { with (v) { val newId = consoleMessage.sourceId().replace(localWithoutIndex, "") + ":" + consoleMessage.lineNumber() val msg = consoleMessage.message() val msgLevel = consoleMessage.messageLevel().name.substring(0, 1) logLevel.text = msgLevel logLevel.setTextColor(getLogColor(consoleMessage.messageLevel())) logMessage.text = msg logMessage.setTextColor(if (darkTheme) { Color.WHITE } else { Color.BLACK }) logDetails.text = newId } } @ColorInt private fun getLogColor(messageLevel: ConsoleMessage.MessageLevel): Int = when (messageLevel) { ConsoleMessage.MessageLevel.LOG -> if (darkTheme) { Color.WHITE } else { -0x79000000 } ConsoleMessage.MessageLevel.TIP -> -0x83b201 ConsoleMessage.MessageLevel.DEBUG -> -0xff198a ConsoleMessage.MessageLevel.ERROR -> -0xadae ConsoleMessage.MessageLevel.WARNING -> -0x3c00 } } }
0
Kotlin
9
21
fc492e0d9d1c112f851163d15dadf2977436123b
2,749
Hyper
Apache License 2.0
core/src/main/kotlin/io/github/kerelape/reikai/io/network/TcpChannel.kt
kerelape
515,105,814
false
{"Kotlin": 129891}
/* * The MIT License (MIT) * * Copyright (c) 2022 kerelape * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.kerelape.reikai.io.network import io.github.kerelape.reikai.Entity import io.github.kerelape.reikai.io.Channel import io.github.kerelape.reikai.io.Source import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.nio.ByteBuffer import java.nio.channels.AsynchronousSocketChannel import java.nio.channels.CompletionHandler import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine /** * TCP destination. * * @since 0.0.0 */ class TcpChannel(private val socket: AsynchronousSocketChannel, private val parent: Source) : Channel { /** * Read next chunk of data from the socket. * * @return The next chunk (1024 bytes). */ override suspend fun dataize(): ByteArray { return suspendCoroutine { continuation -> with(ByteBuffer.allocate(1024)) { [email protected]( this, this, object : CompletionHandler<Int, ByteBuffer> { override fun completed(result: Int, attachment: ByteBuffer) { continuation.resume(attachment.array()) } override fun failed(exc: Throwable, attachment: ByteBuffer) { continuation.resumeWithException(exc) } } ) } } } /** * Put arbitrary data to the socket channel. * * @return [data]. */ override suspend fun put(data: Entity): Entity { val bytes = data.dataize() return suspendCoroutine { continuation -> this.socket.write( ByteBuffer.wrap(bytes), null, object : CompletionHandler<Int, Unit?> { override fun completed(result: Int, attachment: Unit?) { continuation.resume(data) } override fun failed(exc: Throwable, attachment: Unit?) { continuation.resumeWithException(exc) } } ) } } /** * Close the underlying [AsynchronousSocketChannel]. * * @return The source that made this channel. */ override suspend fun close(): Source { withContext(Dispatchers.IO) { [email protected]() } return this.parent } }
10
Kotlin
0
3
5811ffb9e21d078cf748f64545ea70f2fe1e2e29
3,677
reikai
MIT License
app/src/main/java/com/example/nanoclientkotlin/AmcuipValuesActionIds.kt
melinaminaya
656,832,686
false
null
package com.example.nanoclientkotlin /** * Identificadores das ac�es. * * **S->I** significa envio no sentido Servico para Interface. * **I->S** significa envio no sentido Interface para Servico. * * @author rhobison.pereira */ object AmcuipValuesActionIds { /* * <b>S->I</b><br> * Uma nova mensagem foi recebida.<br> * <b>Param1:</b> C�digo da mensagem no banco de dados.<br> * <b>Param2:</b> Nao utilizado.<br> * <b>Param3:</b> Nao utilizado.<br> * <b>Param4:</b> Nao utilizado.<br> */ /** * * Esta acao foi substituida pela acao [AmcuipValuesActionIds.MESSAGE_STATUS] e * sera removida em vers�es futuras. */ @Deprecated("") val MESSAGE_RECEIVED = 0x00 /** * **I->S**<br></br> * Existe uma mensagem a ser enviada.<br></br> * **Param1:** C�digo da mensagem no banco de dados.<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val MESSAGE_TO_SEND = 0x01 /* * <b>S->I</b><br> * Uma mensagem foi enviada/transmitida.<br> * <b>Param1:</b> C�digo da mensagem no banco de dados.<br> * <b>Param2:</b> Nao utilizado.<br> * <b>Param3:</b> Nao utilizado.<br> * <b>Param4:</b> Nao utilizado.<br> */ /** * Esta acao foi substituida pela acao [AmcuipValuesActionIds.MESSAGE_STATUS] e * sera removida em vers�es futuras. */ @Deprecated("") val MESSAGE_SENT = 0x02 /** * **S->I**<br></br> * Um formulario foi recebido ou atualizado.<br></br> * **Param1:** C�digo do formulario no banco de dados.<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val FORM_RECEIVED = 0x03 /** * **S->I**<br></br> * Um formulario foi removido.<br></br> * **Param1:** C�digo do formulario no banco de dados.<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val FORM_DELETED = 0x04 /** * **S->I**<br></br> * A unidade se conectou ao servidor AMH. Ver protocolo Aap.<br></br> * **Param1:** Status do SignOn.<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val SIGN_ON_STATUS = 0x05 /** * **I->S**<br></br> * Ac�es relacionadas ao processo de batismo.<br></br> * **Param1:** Acao a ser executada. Ver [AmcuipValuesBaptismActionParam1]<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val BAPTISM_ACTION = 0x06 /** * **S->I**<br></br> * Indica o status do processo de batismo.<br></br> * **Param1:** Status do processo de batismo. Ver [AmcuipValuesBaptismStatusParam1]<br></br> * **Param2:** Depende de Param1.<br></br> * Se [AmcuipValuesBaptismStatusParam1.BAPTIZED], * [AmcuipValuesBaptismStatusParam1.WAITING_CONFIRMATION], * [AmcuipValuesBaptismStatusParam1.MCT_ADDR_RESPONSE] ou * [AmcuipValuesBaptismStatusParam1.MCT_NOT_AUTORIZED], Param2 sera o n�mero do Mct. * Se [AmcuipValuesBaptismStatusParam1.NOT_BAPTIZED], * [AmcuipValuesBaptismStatusParam1.IN_BAPTISM_PROCESS], * [AmcuipValuesBaptismStatusParam1.BAPTISM_TIMED_OUT], Param2 nao E utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val BAPTISM_STATUS = 0x07 /** * **S->I**<br></br> * Os arquivos de atualizacao foram baixados e estao prontos para iniciar * a atualizacao.<br></br> * **Param1:** Nao utilizado.<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Indica a versao de atualizacao disponivel contida no nome do versionList.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val READY_TO_UPDATE_SOFTWARE = 0x08 /** * **S->I**<br></br> * Status das conex�es de rede.<br></br> * **Param1:** Indica a rede. Ver [AmcuipValuesNetworkTypes]<br></br> * **Param2:** Indica o status da conexao. Ver [AmcuipValuesConnectionStates].<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val NETWORK_CONNECTION_STATUS = 0x09 /** * **S->I**<br></br> * Mudanca no modo de comunicacao.<br></br> * **Param1:** Modo atual de comunicacao. Ver [AmcuipValuesNetworkTypes]<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val COMMUNICATION_MODE_CHANGED = 0x0A /** * **S->I**<br></br> * Mudanca no sinal do satElite.<br></br> * **Param1:** Status do sinal<br></br> * 0 � Sem sinal.<br></br> * 1 � Com sinal.<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val SATELLITE_SIGNAL_CHANGED = 0x0B /** * **I->S**<br></br> * Indica que um parametro (propriedade) deve ser enviado ao servidor. * Este parametro deve ser do tipo [AmcuipValuesParameterType.EXTERNAL]<br></br> * **Param1:** N�mero do parametro a ser enviado.<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Pode conter o valor do parametro. Neste caso o valor do parametro sera atualizado * no banco de dados antes de ser enviado ao servidor. Se este parametro nao estiver presente, o * valor corrente do parametro no banco de dados sera enviado ao servidor.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val UPDATE_SERVER_PARAMETER = 0x0C /** * **S->I**<br></br> * Indica o status do processo de ativacao.<br></br> * **Param1:** Status do processo de ativacao. Ver [AmcuipValuesActivationStatusParam1]<br></br> * **Param2:** Depende de Param1.<br></br> * Se ACTIVATED ou IN_ACTIVATION_PROCESS, Param2 E o n�mero da Uc. * Se Param1 for qualquer outro valor, Param2 nao E utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val ACTIVATION_STATUS = 0x0D /** * **I->S**<br></br> * Solicita que os parametros do Mct (M0..M9) sejam atualizados no banco de dados.<br></br> * **Param1:** Indica o periodo, em segundos, em que a atualizacao deve acontecer. * Ex.: se igual a 10*60, indica que a atualizacao deve ocorrer por 10 minutos.<br></br> * **Param2:** Indica o intervalo, em segundos, entre cada atualizacao. Ex.: se * igual a 60, indica que a atualizacao deve ocorrer a cada minuto.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val UPDATE_MCT_M0_M9_PARAMS = 0x0E /** * **S->I**<br></br> * Informa que os parametros do Mct (M0..M9) foram atualizados no banco de dados e * traz o valor de dois parametros M.<br></br> * **Param1:** Valor do parametro M0.<br></br> * **Param2:** Valor do parametro M2.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val MCT_M0_M9_PARAMS_UPDATED = 0x0F /** * **I->S**<br></br> * Habilita ou desabilita o uso da rede WiFi pelo servico.<br></br> * **Param1:** Habilita/desabilita o uso do WiFi<br></br> * 0 - Habilita o uso do WiFi pelo servico.<br></br> * 1 - Desabilita o uso do WiFi pelo servico (aplicac�es externas podem utilizar o WiFi).<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val DISABLE_WIFI_COMMUNICATION = 0x10 /** * **I->S**<br></br> * Inicia ou cancela o processo de ativacao;<br></br> * **Param1:** Acao a ser executada: Ver [AmcuipValuesActivationActionParam1].<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val ACTIVATION_ACTION = 0x11 /** * **S->I**<br></br> * Notifica que a Data/Hora do servico foi alterada.<br></br> * **Param1:** Data/Hora atualizada, em segundos desde 01/01/1970 00:00:00 GMT.<br></br> * **Param2:** Diferenca para a Data/Hora do sistema, em segundos. Pode ser um n�mero * positivo ou negativo. O resultado de Param1 - Param2 E igual a Data/Hora do sistema.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val DATE_TIME_CHANGED = 0x12 /** * **I->S** <br></br> * Instrui o servico a recarregar o valor de um parametro do banco de dados.<br></br> * **Param1:** N�mero do parametro a ser recarregado. * **Param2:** Tipo do parametro a ser recarregado. Ver [AmcuipValuesRealoadParamFromDbParam2]. <br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val RELOAD_PARAMETER_FROM_DB = 0x13 /** * **I->S**<br></br> * Ac�es relacionadas a operac�es com arquivos.<br></br> * **Param1:** Tipo de operacao a ser realizada. Ver [AmcuipValuesFileOperationActionParam1]. <br></br> * **Param2:** Tipo de compressao utilizada. Ver [AmcuipValuesFileOperationActionParam2]. <br></br> * **Param3:** Nomes dos arquivos de origem, separados por "|". Podem ser utilizados caracteres curingas * (wildcards: "*", "?") para indicar varios arquivos que seguem um padrao. * Ex.: "/mnt/sdcard/Teste*.txt|/mnt/sdcard/Banco_num?.sqlite".<br></br> * **Param4:** Depende da operacao e tipo de compressao:<br></br> * * * **DestDirectory**: Quando a acao for [AmcuipValuesFileOperationActionParam1.COPY] * ou [AmcuipValuesFileOperationActionParam1.MOVE] e o tipo de compressao for * [AmcuipValuesFileOperationActionParam2.NO_COMPRESSION]. * * * **DestFilename**: Quando a acao for [AmcuipValuesFileOperationActionParam1.COPY] * ou [AmcuipValuesFileOperationActionParam1.MOVE] e o tipo de compressao for **diferente** de * [AmcuipValuesFileOperationActionParam2.NO_COMPRESSION], ou seja, quando algum tipo de compressao * for utilizado. * * * **Nao utilizado**: quando a acao for [AmcuipValuesFileOperationActionParam1.DELETE]. * * */ const val FILE_OPERATION_ACTION = 0x14 /** * **S->I**<br></br> * Indica o status de uma operacao com arquivos iniciada anteriormente. <br></br> * **Param1:** Status da operacao com arquivos. Ver [AmcuipValuesFileOperationStatusParam1]<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val FILE_OPERATION_STATUS = 0x15 /** * **S->I**<br></br> * Indica o status de uma mensagem no banco de dados. Esta acao pode ser utilizada quando uma nova mensagem * for recebida ou quando uma mensagem que foi postada para envio acabou de ser enviada, alEm de outros * status. Uma mensagem nao lida tera o status [AmcuipValuesMessageStatus.NOT_READ]. Uma mensagem * que foi enviada tera o status [AmcuipValuesMessageStatus.SENT]. <br></br> * **Param1:** C�digo da mensagem no banco de dados.<br></br> * **Param2:** Status da mensagem. Este campo deve ser utilizado para distinguir entre os diferentes status * de uma mensagem. Ver [AmcuipValuesMessageStatus]. Este campo deve ser tratado como um inteiro de * 32bits com sinal (signed int).<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val MESSAGE_STATUS = 0x16 /** * **S->I**<br></br> * Indica o status de requisicao de algum recurso do sistema. Esta acao pode ser utilizada para informar * status de requisic�es de recursos do sistema, mas geralmente E utilizada para informar quando algum recurso * do sistema que E necessario ao bom funcionamento da aplicacao nao pode ser obtido.<br></br> * **Param1:** Tipo do recurso requisitado. Ver [AmcuipValuesSysResourceReqParam1].<br></br> * **Param2:** Status da requisicao. Ver [AmcuipValuesSysResourceStatusParam2].<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val SYSTEM_RESOURCE_REQ_STATUS = 0x17 /** * **S->I**<br></br> * Indica o status da ignicao do dispositivo externo. <br></br> * **Param1:** Status da ignicao. Ver [AmcuipValuesIgnitionStatusParam1]<br></br> * **Param2:** Nao utilizado.<br></br> * **Param3:** Nao utilizado.<br></br> * **Param4:** Nao utilizado.<br></br> */ const val IGNITION_STATUS = 0x18 /** Valores possiveis para o parametro Param2 da acao [AmcuipValuesActionIds.RELOAD_PARAMETER_FROM_DB]. */ object AmcuipValuesRealoadParamFromDbParam2 { /** Parametro exclusivo do servico de comunicacao. */ const val SERVICE = 0 /** Parametro externo, armazenado no servidor. */ const val EXTERNAL = 1 /** Parametro compartilhado entre o servico e a interface de usuario. */ const val SERVICE_INTERFACE = 2 } /** * Operac�es possiveis de serem executadas na acao [AmcuipValuesActionIds.BAPTISM_ACTION]. */ object AmcuipValuesBaptismActionParam1 { /** Inicia o processo de batismo. */ const val DO_BAPTISM = 0 /** Consulta o n�mero do Mct. */ const val CONSULT_MCT_ADDR = 1 /** Desfaz o processo de batismo. */ const val UNDO_BAPTISM = 2 } /** Status possiveis retornados pelo Param1 de Acao [AmcuipValuesActionIds.BAPTISM_STATUS]. */ object AmcuipValuesBaptismStatusParam1 { /** A Uc ainda nao foi batizada. */ const val NOT_BAPTIZED = 0 /** A Uc ja esta batizada. */ const val BAPTIZED = 1 /** O processo de batismo esta em execucao. */ const val IN_BAPTISM_PROCESS = 2 /** Aguardando pela confirmacao do batismo pelo servidor. */ const val WAITING_CONFIRMATION = 3 /** Resposta da consulta do n�mero do Mct. */ const val MCT_ADDR_RESPONSE = 4 /** * O Mct conectado nao esta autorizado a se comunicar. * A Uc esta batizada com outro Mct. */ const val MCT_NOT_AUTORIZED = 5 /** Houve timeout no processo de batismo. */ const val BAPTISM_TIMED_OUT = 6 } /** Tipos de redes de comunicacao disponiveis. */ object AmcuipValuesNetworkTypes { /** Nenhuma/Sem conexao. */ const val NONE = 0 /** Celular. */ const val CELLULAR = 1 /** SatElite. */ const val SATELLITE = 2 } /** Tipos possiveis de conexao. */ object AmcuipValuesConnectionStates { /** Conexao fisica no estado desconectado. */ const val PHYSICAL_DISCONNECTED = 0 /** Conexao fisica estabelecida. */ const val PHYSICAL_CONNECTED = 1 /** Conexao l�gica no estado desconectado. */ const val LOGICAL_DISCONNECTED = 2 /** Conexao l�gica estabelecida (a troca de pacotes iniciada). */ const val LOGICAL_CONNECTED = 3 } /** * Operac�es possiveis de serem executadas na acao [AmcuipValuesActionIds.ACTIVATION_ACTION]. */ object AmcuipValuesActivationActionParam1 { /** Inicia o processo de ativacao. */ const val START_ACTIVATION = 0 /** Cancela o processo de ativacao. */ const val CANCEL_ACTIVATION = 1 } /** Status possiveis retornados pelo Param1 da acao [AmcuipValuesActionIds.ACTIVATION_STATUS]. */ object AmcuipValuesActivationStatusParam1 { /** A Uc ainda nao foi ativada. */ const val NOT_ACTIVATED = 0 /** A Uc ja esta ativada. */ const val ACTIVATED = 1 /** O processo de ativacao esta em execucao. */ const val IN_ACTIVATION_PROCESS = 2 /** A chave de ativacao fornecida nao E valida. */ const val INVALID_ACTIVATION_KEY = 3 /** Senha de ativacao, gerada a partir da chave de ativacao, invalida! */ const val INVALID_ACTIVATION_PASSOWRD = 4 } /** Status posiveis retornados pelo Param1 da acao [AmcuipValuesActionIds.FILE_OPERATION_STATUS]. */ object AmcuipValuesFileOperationStatusParam1 { /** O arquivo foi transferido com sucesso. */ const val SUCCESS = 0 /** Erro na transfer�ncia do arquivo. */ const val ERROR = 1 } /** Status posiveis retornados pelo Param1 da acao [AmcuipValuesActionIds.IGNITION_STATUS]. */ object AmcuipValuesIgnitionStatusParam1 { /** A ignicao esta desligada. */ const val OFF = 0 /** A ignicao esta ligada. */ const val ON = 1 } /** Status posiveis retornados pelo Param1 da acao [AmcuipValuesActionIds.FILE_OPERATION_ACTION]. */ object AmcuipValuesFileOperationActionParam1 { /** Indica que os arquivos deverao ser copiados. */ const val COPY = 0 /** Indica que os arquivos deverao ser movidos. */ const val MOVE = 1 /** Indica que os arquivos deverao ser apagados. */ const val DELETE = 2 } /** Status posiveis retornados pelo Param2 da acao [AmcuipValuesActionIds.FILE_OPERATION_ACTION]. */ object AmcuipValuesFileOperationActionParam2 { /** Indica que os arquivos deverao ser copiados. */ const val NO_COMPRESSION = 0 /** Indica que os arquivos deverao ser movidos. */ const val ZIP = 1 } /** Possiveis recursos do sistema cujos status da solicitacao podem ser informados. */ object AmcuipValuesSysResourceReqParam1 { // /** Alterar configurac�es de conexao/modem (ativar dados/dados em roaming, etc.). */ // public static final int MODEM_CONFIGURATION = 0; /** Configuracao de Nomes de Pontos de Acesso. */ const val APN_CONFIGURATION = 1 /** Configuracao do GPS (inclui ligar/desligar/configurar posicao precisa). */ const val GPS_CONFIGURATION = 2 // /** Configuracao de Hot Spot WiFi. */ // public static final int WIFI_HOTSPOT_CONFIGURATION = 3; } /** Possiveis status dos recursos solicitados ao sistema. */ object AmcuipValuesSysResourceStatusParam2 { /** Sucesso, nenhum erro. */ const val SUCCESS = 0 /** Erro desconhecido. */ const val UNKNOWN_ERROR = 1 /** Sem permissao para obter o recurso. */ const val PERMISSION_DENIED = 2 /** Recurso nao disponivel. */ const val NOT_AVAILABLE = 3 } }
0
Kotlin
0
0
ad22172f1b0e160292091d27e422ef0de3346f79
19,012
RestAPIKotlinApp
Freetype Project License
mb-autoconfigure/src/main/kotlin/com/nomkhonwaan/mb/autoconfigure/MongoConfiguration.kt
nomkhonwaan
164,768,574
false
null
package com.nomkhonwaan.mb.autoconfigure import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.convert.converter.Converter import org.springframework.data.mongodb.core.convert.MongoCustomConversions import java.time.ZoneId import java.time.ZonedDateTime import java.util.* /** * An auto-configure of the Spring Data MongoDB. */ @Configuration class MongoConfiguration { /** * Registers custom conversions for the MongoDB field type. * <p> * The first conversion is from [java.util.Date] to [java.time.ZonedDateTime] * which uses Asia/Bangkok as a default timezone. * <p> * The second conversion is from [java.time.ZonedDateTime] to [java.util.Date]. */ @Bean @ConditionalOnMissingBean fun mongoCustomConversions(): MongoCustomConversions { return MongoCustomConversions(listOf( Converter<Date, ZonedDateTime> { ZonedDateTime.ofInstant(it.toInstant(), ZoneId.of("Asia/Bangkok")) }, Converter<ZonedDateTime, Date> { Date.from(it.toInstant()) } )) } }
0
Kotlin
0
0
481c3b60568cac387be12cdaeb05f7c538494772
1,298
mb
MIT License
example/android/app/src/main/kotlin/com/example/easy_separator_example/MainActivity.kt
CodeFoxLk
427,701,930
false
{"Dart": 8361, "HTML": 3879, "Swift": 404, "Kotlin": 139, "Objective-C": 38}
package com.example.easy_separator_example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
2
03d160b71b3071e66eca7cbe2f4d426f4601aa42
139
easy_separator
MIT License
common/src/main/kotlin/com/helloclue/sse/SseParseLineEnd.kt
biowink
223,560,480
false
null
package io.sharptree.maximo.app.label.sse internal typealias Index = Long /** * Finds the next line terminator in some character stream/sequence, which can be either: * * - [`\r\n`][onCrLf]: _Carriage Return_ character followed by _Line Feed_ character. * - [`\n`][onLf]: _Line Feed_ character. * - [`\r`][onCr]: _Carriage Return_ character. * - [EOF][onEof]: _End Of File_ reached before finding any terminator. * * * ### From [Parsing an event stream](https://www.w3.org/TR/2015/REC-eventsource-20150203/#parsing-an-event-stream): * * > This event stream format's MIME type is `text/event-stream`. * * > The event stream format is as described by the `stream` production of the following [ABNF](https://www.w3.org/TR/2015/REC-eventsource-20150203/#refsABNF), the character set for which is Unicode. * * > > stream = [ bom ] *event * > event = *( comment / field ) end-of-line * > comment = colon *any-char end-of-line * > field = 1*name-char [ colon [ space ] *any-char ] end-of-line * > end-of-line = ( cr lf / cr / lf ) * > * > ; characters * > lf = %x000A ; U+000A LINE FEED (LF) * > cr = %x000D ; U+000D CARRIAGE RETURN (CR) * > space = %x0020 ; U+0020 SPACE * > colon = %x003A ; U+003A COLON (:) * > bom = %xFEFF ; U+FEFF BYTE ORDER MARK * > name-char = %x0000-0009 / %x000B-000C / %x000E-0039 / %x003B-10FFFF * > ; a Unicode character other than U+000A LINE FEED (LF), U+000D CARRIAGE RETURN (CR), or U+003A COLON (:) * > any-char = %x0000-0009 / %x000B-000C / %x000E-10FFFF * > ; a Unicode character other than U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) * * > Event streams in this format must always be encoded as UTF-8. ([RFC3629](https://www.w3.org/TR/2015/REC-eventsource-20150203/#refsRFC3629)) * * > Lines must be separated by either a [U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair][onCrLf], a [single U+000A LINE FEED (LF) character][onLf], or a [single U+000D CARRIAGE RETURN (CR) character][onCr]. * * @see [parseSseLine] */ @PublishedApi internal inline fun <T> parseSseLineEnd( indexOfCr: () -> Index, indexOfLf: () -> Index, onCrLf: (Index) -> T, onLf: (Index) -> T, onCr: (Index) -> T, onEof: () -> T ): T { val lfIndex = indexOfLf() if (lfIndex == 0L) return onLf(lfIndex) val crIndex = indexOfCr() val hasCr = crIndex >= 0 val hasLf = lfIndex >= 0 return when { hasCr && hasLf -> when { crIndex + 1 == lfIndex -> onCrLf(crIndex) lfIndex < crIndex -> onLf(lfIndex) else -> onCr(crIndex) } hasLf -> onLf(lfIndex) hasCr -> onCr(crIndex) else -> onEof() } }
2
null
2
41
4fbd373adfe2acfd57dc3f96a0ba95be1243427b
2,885
oksse
MIT License
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/ui/base/BasePresenter.kt
chromeos
419,334,870
false
null
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 dev.chromeos.videocompositionsample.presentation.ui.base import dev.chromeos.videocompositionsample.presentation.tools.exception.ErrorMessageFactory import io.reactivex.disposables.CompositeDisposable import java.lang.ref.WeakReference /** * Base class that implements the Presenter interface and provides a base implementation for * onAttach() and onDetach(). It also handles keeping a reference to the mvpView. */ abstract class BasePresenter<T : IBaseView>(protected val compositeDisposable: CompositeDisposable) { protected lateinit var weakView: WeakReference<T> fun onAttach(mvpView: T) { weakView = WeakReference(mvpView) } protected fun showProgress() { weakView.get()?.showProgress(compositeDisposable) } protected fun hideProgress() { weakView.get()?.hideProgress() } protected open fun onThrowable(e: Throwable) { hideProgress() weakView.get()?.showError(ErrorMessageFactory.create(e)) } fun onDetach() { compositeDisposable.clear() weakView.clear() } }
0
Kotlin
2
7
7a91156a14bd4a735a9bcaa42b8e09c1ad92e08f
1,684
video-composition-sample
Apache License 2.0
app/src/main/java/com/zlucas2k/mytask/presentation/common/model/TaskView.kt
zLuCaS2K
238,888,752
false
null
package com.zlucas2k.mytask.presentation.common.model import com.zlucas2k.mytask.common.utils.emptyString // TODO: Mudar o tipo do id para Long data class TaskView( val id: Int = 0, val title: String = emptyString(), val date: String = emptyString(), val time: String = emptyString(), val description: String = emptyString(), val priority: PriorityView = PriorityView.NONE, val status: StatusView = StatusView.TODO )
0
Kotlin
3
8
4bdcca1f17f45971bdf63253046df63cc805a76c
447
MyTask
MIT License
app/src/main/java/com/challenge/xkcd/di/DataModule.kt
AbdullahAimen
408,370,136
false
null
package com.challenge.xkcd.di import android.content.Context import androidx.room.Room import com.challenge.xkcd.dataLayer.local.ComicDAO import com.challenge.xkcd.dataLayer.local.ComicsRoomDatabase import com.challenge.xkcd.dataLayer.remote.RemoteService import com.challenge.xkcd.dataLayer.remote.ServiceGenerator import com.challenge.xkcd.domainLayer.base.UseCaseHandler import com.challenge.xkcd.domainLayer.base.UseCaseScheduler import com.challenge.xkcd.domainLayer.base.UseCaseThreadPoolScheduler import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DataModule { @Singleton @Provides fun provideRemoteService(): RemoteService { return ServiceGenerator().createService(RemoteService::class.java) } /** * binds handlers * */ @Singleton @Provides fun provideUseCaseHandler(useCaseScheduler: UseCaseScheduler): UseCaseHandler { return UseCaseHandler(useCaseScheduler) } @Singleton @Provides fun provideUseCaseScheduler(): UseCaseScheduler = UseCaseThreadPoolScheduler() @Singleton @Provides fun provideComicsRoomDatabase(@ApplicationContext appContext: Context): ComicDAO { return Room.databaseBuilder( appContext.applicationContext, ComicsRoomDatabase::class.java, "comics.db" ).build().comicDAODao() } }
0
null
0
0
759c2faffad8059309beb7d3affa3fd569ff0245
1,565
xkcd-shortcut.io
Apache License 2.0
idea/testData/addImport/ImportPackage.kt
staltz
38,581,975
true
{"Markdown": 34, "XML": 687, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18510, "Java": 4307, "Protocol Buffer": 4, "Text": 4085, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 71, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
// IMPORT: java.util package p fun foo(): util.ArrayList<String> {}
0
Java
0
1
80074c71fa925a1c7173e3fffeea4cdc5872460f
69
kotlin
Apache License 2.0
app/src/main/java/com/vonHousen/kappusta/ui/wallets/WalletsOverviewListAdapter.kt
vonHousen
255,431,497
false
null
package com.vonHousen.kappusta.ui.wallets import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.vonHousen.kappusta.walletSharing.WalletOverview class WalletsOverviewListAdapter( private val list: MutableList<WalletOverview>, private val whomNotify: WalletsOverviewViewModel, private val onClickListener: (View, WalletOverview) -> Unit ) : RecyclerView.Adapter<WalletsOverviewViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WalletsOverviewViewHolder { val inflater = LayoutInflater.from(parent.context) return WalletsOverviewViewHolder( inflater, parent ) } override fun onBindViewHolder(holderOverview: WalletsOverviewViewHolder, position: Int) { val walletOverview = list[position] holderOverview.bind(walletOverview) holderOverview.itemView.setOnClickListener { view -> onClickListener.invoke(view, walletOverview) } } override fun getItemCount(): Int = list.size fun removeAt(position: Int) { list.removeAt(position) // whomNotify.notifyReportRemoved(position) TODO implement removing notifyItemRemoved(position) } }
0
Kotlin
0
1
f6421f0323b7cd3aed3831f1c2ad9cbac138f609
1,318
kappusta
MIT License
dominion-app/src/commonMain/kotlin/io/ashdavies/playground/kingdom/KingdomScreen.kt
ashdavies
36,688,248
false
null
package io.ashdavies.playground.kingdom import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.unit.dp import io.ashdavies.playground.DominionCard import io.ashdavies.playground.DominionExpansion import io.ashdavies.playground.DominionRoot import io.ashdavies.playground.DominionViewState import io.ashdavies.playground.RemoteImage import io.ashdavies.playground.windowInsetsPadding @Composable @OptIn(ExperimentalMaterial3Api::class) internal fun KingdomScreen(child: DominionRoot.Child.Kingdom) { val scrollBehavior = remember { TopAppBarDefaults.enterAlwaysScrollBehavior() } val viewModel: KingdomViewModel = rememberKingdomViewModel() val _state: DominionViewState<DominionCard> by viewModel.state.collectAsState() LaunchedEffect(Unit) { viewModel.produceEvent(child.expansion) } Scaffold( topBar = { KingdomTopBar(child.expansion, scrollBehavior) { child.navigateToExpansion() } }, modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection) ) { contentPadding -> when (val state = _state) { is DominionViewState.Success -> KingdomScreen( onClick = { child.navigateToCard(it) }, contentPadding = contentPadding, kingdom = state.value, ) else -> LinearProgressIndicator( modifier = Modifier .fillMaxWidth() .padding(4.dp) ) } } } @Composable private fun KingdomTopBar( expansion: DominionExpansion, scrollBehavior: TopAppBarScrollBehavior, onBack: () -> Unit = { } ) { Surface(color = MaterialTheme.colorScheme.surface) { LargeTopAppBar( title = { Text(expansion.name) }, navigationIcon = { /*Image( contentDescription = expansion.name, modifier = Modifier.fillMaxWidth(), urlString = expansion.image, )*/ BackIconButton(onBack) }, scrollBehavior = scrollBehavior, modifier = Modifier .nestedScroll(scrollBehavior.nestedScrollConnection) .windowInsetsPadding() ) } } @Composable private fun BackIconButton(onClick: () -> Unit) { IconButton(onClick = onClick) { Image( painter = rememberVectorPainter(Icons.Filled.ArrowBack), contentDescription = null, ) } } @Composable @ExperimentalMaterial3Api private fun KingdomScreen( kingdom: List<DominionCard>, contentPadding: PaddingValues, onClick: (DominionCard) -> Unit = { }, modifier: Modifier = Modifier, ) { LazyVerticalGrid( columns = GridCells.Fixed(3), modifier = modifier.padding(4.dp), contentPadding = contentPadding, ) { items(kingdom) { KingdomCard(it) { onClick(it) } } } } @Composable @ExperimentalMaterial3Api private fun KingdomCard( value: DominionCard, modifier: Modifier = Modifier, onClick: () -> Unit = { }, ) { Box(Modifier.padding(4.dp)) { Card( modifier = modifier .clickable(onClick = onClick) .aspectRatio(1.0f) ) { when (val image = value.image) { null -> Text(value.name, color = Color.White) else -> RemoteImage( modifier = Modifier.aspectRatio(0.62F).height(300.dp), urlString = image ) } } } }
7
Kotlin
33
109
ae2d602f3eb2516117bacdbeab8f9eb4c4ca4799
5,161
playground
Apache License 2.0
app/src/main/java/vn/loitp/up/a/cv/wwlVideo/detail/WWLVideoMetaInfoFragment.kt
tplloi
126,578,283
false
null
package vn.loitp.up.a.cv.wwlVideo.detail import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import vn.loitp.databinding.FWwlVideoMetaInfoBinding import vn.loitp.up.a.cv.wwlVideo.utils.WWLVideoDataset class WWLVideoMetaInfoFragment : Fragment() { private lateinit var binding: FWwlVideoMetaInfoBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FWwlVideoMetaInfoBinding.inflate(inflater, container, false) return binding.root } fun updateItem(item: WWLVideoDataset.DatasetItem) { binding.liTitle.text = item.title binding.liSubtitle.text = item.subtitle } }
1
null
1
9
1bf1d6c0099ae80c5f223065a2bf606a7542c2b9
825
base
Apache License 2.0
app/src/main/java/no/usn/mob3000/ui/screens/user/ProfileAddFriendsScreen.kt
frigvid
851,070,715
false
{"Kotlin": 189213}
package no.usn.mob3000.ui.screens.user import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import no.usn.mob3000.R import no.usn.mob3000.Viewport import no.usn.mob3000.ui.theme.DefaultButton /** * Screen for allowing users to search for other users and sending them a friend request. * * @author frigvid * @created 2024-10-11 */ @Composable fun ProfileAddFriendsScreen() { var searchQuery by remember { mutableStateOf("") } /* TODO: Extract user fetcher to data layer. */ val dummyUsers = remember { listOf( User("00ba54a6-c585-4871-905e-7d53262f05c1", "ChessMaster42", R.drawable.profile_icon), User("b82bcc28-79b4-4a5f-8efd-080a9c00dc2f", "PawnStar", R.drawable.profile_icon), User("3a574a5d-9406-4245-aebb-6074fc56b9ec", "KnightRider", R.drawable.profile_icon), User("b39a02b1-9b72-4134-905c-fa538b2a9a53", "BishopBoss", R.drawable.profile_icon), User("6237de51-a463-42c8-8c0a-5f0c8930ccc3", "RookiePlayer", R.drawable.profile_icon) ) } val filteredUsers = dummyUsers.filter { it.username.contains(searchQuery, ignoreCase = true) || it.id.contains(searchQuery) } Viewport { innerPadding -> Column( modifier = Modifier .fillMaxSize() .padding(innerPadding) .padding(16.dp) ) { OutlinedTextField( value = searchQuery, onValueChange = { searchQuery = it }, label = { Text(stringResource(R.string.profile_add_friends_search_label)) }, modifier = Modifier .fillMaxWidth() .padding(bottom = 16.dp) ) LazyColumn( modifier = Modifier .fillMaxWidth() .weight(1f) ) { items(filteredUsers) { user -> UserListItem(user) } } } } } /** * Composable list item to display the user's profile picture, display name and UUID. * * @param user The (dummy) user data object. * @author frigvid * @created 2024-10-12 */ @Composable fun UserListItem( user: User ) { Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Image( painter = painterResource(user.profilePicture), contentDescription = "Profile picture", modifier = Modifier .size(48.dp) .clip(CircleShape) ) Column( modifier = Modifier .padding(start = 16.dp) .weight(1f) ) { Text( text = user.username, fontWeight = FontWeight.Bold ) Text( text = user.id, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f) ) } Button( onClick = { /* TODO: Implement send friend request logic */ }, colors = ButtonDefaults.buttonColors(DefaultButton), modifier = Modifier.padding(start = 8.dp) ) { Text(stringResource(R.string.profile_add_friends_add_button)) } } } /* TODO: Extract to data layer and fix dummy User data class. */ data class User( val id: String, val username: String, val profilePicture: Int )
1
Kotlin
0
1
313e41364902a650316431c19c25a337a5780621
4,076
mob3000-group11
MIT License
app/src/main/java/com/misit/faceidchecklogptabp/Api/ApiClient.kt
borisreyson
354,711,920
false
null
package com.misit.abpenergy.api import android.content.Context import com.franmontiel.persistentcookiejar.BuildConfig import com.franmontiel.persistentcookiejar.ClearableCookieJar import com.franmontiel.persistentcookiejar.PersistentCookieJar import com.franmontiel.persistentcookiejar.cache.SetCookieCache import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor import okhttp3.OkHttpClient import okhttp3.Protocol import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.* object ApiClient{ // private var BASE_URL= "http://10.10.3.13" private var BASE_URL= "https://abpjobsite.com:8443" private var retrofit : Retrofit? = null fun getClient(context: Context?):Retrofit?{ if (retrofit==null){ retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .client(getHeader(context)) .addConverterFactory(GsonConverterFactory.create()) .build() } return retrofit } private fun getHeader(context: Context?): OkHttpClient { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY val cookieJar: ClearableCookieJar = PersistentCookieJar(SetCookieCache(),SharedPrefsCookiePersistor(context)) var okhttpClient = OkHttpClient.Builder().addInterceptor(interceptor) return okhttpClient .cookieJar(cookieJar) .retryOnConnectionFailure(true) .build() } }
0
Kotlin
0
0
2a0b507559cfeddd3bff624f447ce088d334d85a
1,589
FaceIdChecklogPTABP
MIT License
clef-workflow-api/clef-workflow-api-contract/clef-workflow-api-contract-workflow/src/main/kotlin/io/quee/clef/workflow/api/contract/workflow/dto/CreateWorkflowRequestDto.kt
Quee-io
247,057,756
false
null
package io.quee.clef.workflow.api.contract.workflow.dto import com.fasterxml.jackson.annotation.JsonProperty import io.quee.clef.workflow.api.usecase.factory.workflow.request.workflow.CreateWorkflowRequest /** * Created By [**<NAME> **](https://www.linkedin.com/in/iloom/)<br></br> * Created At **17**, **Tue Mar, 2020** * Project **clef-workflow** [Quee.IO](https://quee.io/)<br></br> */ data class CreateWorkflowRequestDto( @JsonProperty("workflowKey") override val workflowKey: String, @JsonProperty("workflowName") override val workflowName: String, @JsonProperty("workflowDescription") override val workflowDescription: String ) : CreateWorkflowRequest
1
Kotlin
0
0
217da218289fbbc1c1460309883d806dc52dc401
688
clef-workflow
Apache License 2.0
app/src/main/kotlin/webauthnkit/example/BleAuthenticatorRegistrationActivity.kt
lyokato
166,183,654
false
null
package webauthnkit.example import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.ExperimentalCoroutinesApi import org.jetbrains.anko.* import org.jetbrains.anko.sdk27.coroutines.onClick import webauthnkit.core.authenticator.internal.InternalAuthenticator import webauthnkit.core.authenticator.internal.ui.UserConsentUI import webauthnkit.core.authenticator.internal.ui.UserConsentUIFactory import webauthnkit.core.ctap.ble.BleFidoService import webauthnkit.core.ctap.ble.BleFidoServiceListener import webauthnkit.core.util.WAKLogger @ExperimentalCoroutinesApi @ExperimentalUnsignedTypes class BleAuthenticatorRegistrationActivity : AppCompatActivity() { companion object { val TAG = BleAuthenticatorRegistrationActivity::class.simpleName } var consentUI: UserConsentUI? = null var bleFidoService: BleFidoService? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = "REGISTRATION BLE SERVICE" verticalLayout { padding = dip(10) button("START") { textSize = 24f onClick { onStartClicked() } } button("STOP") { textSize = 24f onClick { onStopClicked() } } } } private fun onStartClicked() { WAKLogger.d(TAG, "onStartClicked") createBleFidoService() if (bleFidoService!!.start()) { WAKLogger.d(TAG, "started successfully") } else { WAKLogger.d(TAG, "failed to start") } } private fun onStopClicked() { WAKLogger.d(TAG, "onStopClicked") bleFidoService?.stop() bleFidoService = null } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { WAKLogger.d(TAG, "onActivityResult") consentUI?.onActivityResult(requestCode, resultCode, data) /* if (consentUI != null && consentUI!!.onActivityResult(requestCode, resultCode, data)) { return } */ } val bleServiceListener = object: BleFidoServiceListener { override fun onConnected(address: String) { WAKLogger.d(TAG, "onConnected") } override fun onDisconnected(address: String) { WAKLogger.d(TAG, "onDisconnected") } override fun onClosed() { WAKLogger.d(TAG, "onClosed") } } private fun createBleFidoService() { consentUI = UserConsentUIFactory.create(this) bleFidoService = BleFidoService.create( activity = this, ui = consentUI!!, listener = bleServiceListener ) } }
1
Kotlin
5
22
7646b8b3f7eb6442832696e34fb7625288d41349
2,893
WebAuthnKit-Android
MIT License
app/src/main/java/ar/com/wolox/android/features/homepage/profile/ProfileView.kt
wolox-training
347,987,157
false
null
package ar.com.wolox.android.features.homepage.profile interface ProfileView
0
Kotlin
0
0
557068a90eab37f5b6932f01fca72d332a0aa979
77
ea-android
MIT License
src/main/kotlin/httpclient/HttpClient.kt
AweShowSome
489,786,566
false
{"Kotlin": 44093}
package httpclient import io.ktor.client.HttpClient import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.HttpTimeout import io.ktor.client.features.json.JsonFeature import io.ktor.client.features.json.serializer.KotlinxSerializer import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.headers import io.ktor.client.request.post import io.ktor.client.request.url import io.ktor.client.statement.HttpResponse import kotlinx.serialization.json.JsonElement class HttpClient(engine: HttpClientEngine) : AutoCloseable { val client = HttpClient(engine) { install(JsonFeature) { serializer = KotlinxSerializer() } install(HttpTimeout) { requestTimeoutMillis = 5000 connectTimeoutMillis = 5000 } expectSuccess = false } suspend fun get( url: String, bearerToken: String? = "" ): HttpResponse { return client.get { url(url) headers { header("Authorization", "Bearer $bearerToken") } } } suspend fun post( url: String, payload: JsonElement, bearerToken: String? = null ): HttpResponse { client.post<HttpResponse> { url(url) headers { header("Accept", "application/json") header("content-type", "application/json; charset=utf-8") header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.39") header("X-Robinhood-API-Version", "1.431.4") bearerToken?.let { header("Authorization", "Bearer $bearerToken") } } this.body = payload }.let { response -> return response } } override fun close() { client.close() } }
0
Kotlin
0
0
9ee5d68a8a7e8dc6564c462894982f2da9282262
1,963
RobinhoodTerminal
MIT License
14-webflux-demo-lab/src/main/kotlin/course/kotlin/webfluxdemo/model/Device.kt
iproduct
277,474,020
false
{"JavaScript": 3237497, "Kotlin": 545267, "Java": 110766, "HTML": 83688, "CSS": 44893, "SCSS": 32196, "Dockerfile": 58}
package course.kotlin.webfluxdemo.model class Device(val name: String, val reading: Double)
0
JavaScript
1
4
89884f8c29fffe6c6f0384a49ae8768c8e7ab509
93
course-kotlin
Apache License 2.0
app/src/main/java/net/catstack/nfcpay/domain/HistoryItemModel.kt
sharphurt
324,763,445
true
{"Kotlin": 68119}
package net.catstack.nfcpay.domain import java.io.Serializable data class HistoryItemModel( val title: String, val cost: Float, val datetime: String, val status: String, val historyDate: String, val paymentDateAndTime: String ) : Serializable
0
Kotlin
0
0
33cc8930229c1f5d3524cbfb652943fdc9bd1f61
268
NfcPayments-android
Apache License 2.0
app/src/main/java/pfc/safepass/app/MainMenuActivity.kt
Bau64
790,334,407
false
{"Kotlin": 66581}
@file:Suppress("DEPRECATION") package pfc.safepass.app import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.Menu import android.view.MenuItem import android.widget.SearchView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.recyclerview.widget.LinearLayoutManager import pfc.safepass.app.databinding.MainMenuBinding import pfc.safepass.app.preferences.Preferences import pfc.safepass.app.recycler.PassItem import pfc.safepass.app.recycler.PasswordAdapter import java.time.LocalDate import java.time.format.DateTimeFormatter class MainMenuActivity : AppCompatActivity() { private lateinit var binding: MainMenuBinding private lateinit var dataBaseHelper: DataBaseHelper private lateinit var passwordAdapter: PasswordAdapter private lateinit var searchView: SearchView private lateinit var sortedList: List<PassItem> private lateinit var prefs: Preferences private var doubleBackPressed = false private val utils = Utils() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = MainMenuBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) initUI() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main_menu, menu) val searchItem = menu?.findItem(R.id.menuItem_search) if (searchItem != null) { searchView = searchItem.actionView as SearchView searchView.isIconifiedByDefault = false searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { searchView.clearFocus() return true } override fun onQueryTextChange(newText: String?): Boolean { if (newText!!.isNotEmpty()) passwordAdapter.filterByName(newText) else sortItems(true) return true } }) searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem): Boolean { searchView.requestFocus() utils.showKeyboard(this@MainMenuActivity) return true } override fun onMenuItemActionCollapse(item: MenuItem): Boolean { utils.hideKeyboard(this@MainMenuActivity) sortItems(true) return true } }) } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menuItem_addNew -> { goToAddPassword() return true } R.id.menuItem_lock -> { Preferences(applicationContext).clearSession() goToLogin() Toast.makeText(this, getString(R.string.database_locked), Toast.LENGTH_SHORT).show() finish() return true } R.id.menuItem_settings -> { goToSettings() return true } R.id.menuItem_bin -> { gotoRecycleBin() return true } R.id.menuItem_sort -> { sortItems(false) return true } else -> super.onOptionsItemSelected(item) } } /** * Shows an AlertDialog with options for sorting the password list */ private fun sortItems(skipBuilder: Boolean) { sortedList = dataBaseHelper.getAllPassword(false) val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy") if (!skipBuilder) { val options = arrayOf(getString(R.string.sort_nickname_asc), getString(R.string.sort_nickname_desc), getString(R.string.sort_date_asc), getString(R.string.sort_date_desc)) val builder = AlertDialog.Builder(this) builder.setTitle(getString(R.string.menuItem_sort)) builder.setSingleChoiceItems(options, prefs.getTempSort()) { dialog, option -> prefs.setTempSort(option) when (prefs.getTempSort()) { 1 -> passwordAdapter.refreshData(sortedList.sortedByDescending { it.nickname }) 2 -> passwordAdapter.refreshData(sortedList.sortedByDescending { LocalDate.parse(it.date, formatter) }) 3 -> passwordAdapter.refreshData(sortedList.sortedBy { LocalDate.parse(it.date, formatter) }) else -> passwordAdapter.refreshData(sortedList.sortedBy { it.nickname }) } dialog.dismiss() } val dialog = builder.create() dialog.show() } else { when (prefs.getTempSort()) { 1 -> passwordAdapter.refreshData(sortedList.sortedByDescending { it.nickname }) 2 -> passwordAdapter.refreshData(sortedList.sortedByDescending { LocalDate.parse(it.date, formatter) }) 3 -> passwordAdapter.refreshData(sortedList.sortedBy { LocalDate.parse(it.date, formatter) }) else -> passwordAdapter.refreshData(sortedList.sortedBy { it.nickname }) } } } private fun goToLogin() { prefs.setTempSort(0) startActivity(Intent(this, LoginActivity::class.java)) overridePendingTransition(R.anim.zoom_in, R.anim.zoom_out) } private fun goToAddPassword(){ startActivity(Intent(this, NewPasswordActivity::class.java)) overridePendingTransition(R.anim.slide_bottom_2, R.anim.slide_top_2) } private fun goToSettings() { startActivity(Intent(this, SettingsActivity::class.java)) overridePendingTransition(R.anim.slide_left, R.anim.stay) } private fun gotoRecycleBin(){ startActivity(Intent(this, RecycledItemsActivity::class.java)) overridePendingTransition(R.anim.slide_right_2, R.anim.slide_right) } private fun initUI(){ prefs = Preferences(applicationContext) dataBaseHelper = DataBaseHelper(this) passwordAdapter = PasswordAdapter(dataBaseHelper.getAllPassword(false), this, false) sortItems(true) binding.recyclerview.layoutManager = LinearLayoutManager(this) binding.recyclerview.adapter = passwordAdapter firstpwdHelper() } // Cuando el usuario presione atras se le pedira que lo vuelva a hacer para salir de la aplicacion @Deprecated("Deprecated") override fun onBackPressed() { if (doubleBackPressed) { super.onBackPressed() return } doubleBackPressed = true Toast.makeText(this, getString(R.string.toast_created_press_exit), Toast.LENGTH_SHORT).show() // If the users presses BACK twice in 2 seconds, the user exits the app Handler(Looper.getMainLooper()).postDelayed({ doubleBackPressed = false }, 2000) } override fun onResume() { super.onResume() binding.toolbar.collapseActionView() sortItems(true) firstpwdHelper() } override fun onPause() { super.onPause() utils.hideKeyboard(this) } /** * Shows or hides the help message about how to create a password when the list is empty */ private fun firstpwdHelper() { if (passwordAdapter.itemCount == 0) binding.menuNoPasswordHint.isVisible = true else binding.menuNoPasswordHint.isGone = true } }
0
Kotlin
0
0
54c9917f205cd844d8ae1de3831f533b3c1868d6
7,945
SafePass
MIT License
mobile_app1/module364/src/main/java/module364packageKt0/Foo1688.kt
uber-common
294,831,672
false
null
package module364packageKt0; annotation class Foo1688Fancy @Foo1688Fancy class Foo1688 { fun foo0(){ module364packageKt0.Foo1687().foo6() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } fun foo5(){ foo4() } fun foo6(){ foo5() } }
6
Java
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
331
android-build-eval
Apache License 2.0
core/core-android/src/main/java/zakadabar/android/jdbc/zklite/ZkLiteDatabase.kt
spxbhuhb
290,390,793
false
{"Kotlin": 2390839, "HTML": 2835, "JavaScript": 1021, "Dockerfile": 269, "Shell": 253}
/* * Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.android.jdbc.zklite import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabaseLockedException import android.database.sqlite.SQLiteException import java.sql.SQLException /** A proxy class for the database that allows actions to be retried without forcing every method * through the reflection process. This was originally implemented as an interface and a Proxy. * While quite slick, it always used reflection which can be horribly slow. * * SQLiteDatabaseLockedException did not exist before API 11 so this resolves that problem by * using reflection to determine if the Exception is a SQLiteDatabaseLockedException which will, * presumably, only work on API 11 or later. * * This is still pretty ugly. Part of the problem is an architectural decision to handle errors within * the JDBC driver. * * ALL databases fail. Any code that used JDBC has to be able to handle those failures. * The locking errors in SQLite are analogous to network failures in other DBs Handling them within the * driver deprives the upper level code of the opportunity to handle these in an application specific * manner. The timouts in the first implementation were extreme. The loops would wait one second between attempts * to retry that, like, the middle of next week in computer terms. * * To provide a specific problem case for the timout code. We routinely read data on sub-second intervals. * Frequently on a 100ms timebase. The data collection and insert usually occur on the same thread. This * isn't a requirement, but it helps to have the code synchronized. If we attempt an insert, we want the * code to fail fast. That insert is cached and will be completed when the next insert is attempted. So 100ms * later there will be two inserts (or 3, 200ms later, etc.). * * This code now also makes the timeouts optional and attempts to minimize the performance penalties in this case. * * @param dbQname * @param timeout * @param retryInterval * @throws SQLException thrown if the attempt to connect to the database throws an exception * other than a locked exception or throws a locked exception after the timeout has expired. */ class ZkLiteDatabase( /** The name of the database. */ var dbQname: String, /** The timeout in milliseconds. Zero indicated that there should be no retries. * Any other value allows an action to be retried until success or the timeout has expired. */ protected var timeout: Long, /** The delay in milliseconds between retries when timeout is given. * The value is ignored if timeout is not given. */ protected var retryInterval: Long, flags: Int ) { enum class Transaction { setTransactionSuccessful, endTransaction, close, beginTransaction } /** Returns the android SQLiteDatabase that we are delegating for. * @return the sqliteDatabase */ /** The actual android database. */ var sqliteDatabase: SQLiteDatabase? = null private set /** Returns true if the exception is an instance of "SQLiteDatabaseLockedException". Since this exception does not exist * in APIs below 11 this code uses reflection to check the exception type. */ private fun isLockedException(maybeLocked: SQLiteException) = maybeLocked is SQLiteDatabaseLockedException /** Proxy for the "rawQuery" command. * @throws SQLException */ fun rawQuery(sql: String?, makeArgListQueryString: Array<String?>?): Cursor { ZkLiteLog.v("SQLiteDatabase rawQuery: " + Thread.currentThread().id + " \"" + Thread.currentThread().name + "\" " + sql) val queryStart = System.currentTimeMillis() var delta: Long do { delta = try { val cursor = sqliteDatabase !!.rawQuery(sql, makeArgListQueryString) ZkLiteLog.v("SQLiteDatabase rawQuery OK: " + Thread.currentThread().id + " \"" + Thread.currentThread().name + "\" " + sql) return cursor } catch (e: SQLiteException) { if (isLockedException(e)) { System.currentTimeMillis() - queryStart } else { throw ZkLiteConnection.chainException(e) } } } while (delta < timeout) throw SQLException("Timeout Expired") } /** Proxy for the "execSQL" command. * @throws SQLException */ fun execSQL(sql: String?, makeArgListQueryObject: Array<Any?>?) { ZkLiteLog.v("SQLiteDatabase execSQL: " + Thread.currentThread().id + " \"" + Thread.currentThread().name + "\" " + sql) val timeNow = System.currentTimeMillis() var delta: Long do { delta = try { sqliteDatabase !!.execSQL(sql, makeArgListQueryObject) ZkLiteLog.v("SQLiteDatabase execSQL OK: " + Thread.currentThread().id + " \"" + Thread.currentThread().name + "\" " + sql) return } catch (e: SQLiteException) { if (isLockedException(e)) { System.currentTimeMillis() - timeNow } else { throw ZkLiteConnection.chainException(e) } } } while (delta < timeout) throw SQLException("Timeout Expired") } /** Proxy for the "execSQL" command. * @throws SQLException */ fun execSQL(sql: String) { ZkLiteLog.v("SQLiteDatabase execSQL: " + Thread.currentThread().id + " \"" + Thread.currentThread().name + "\" " + sql) val timeNow = System.currentTimeMillis() var delta: Long do { delta = try { sqliteDatabase !!.execSQL(sql) ZkLiteLog.v("SQLiteDatabase execSQL OK: " + Thread.currentThread().id + " \"" + Thread.currentThread().name + "\" " + sql) return } catch (e: SQLiteException) { if (isLockedException(e)) { System.currentTimeMillis() - timeNow } else { throw ZkLiteConnection.chainException(e) } } } while (delta < timeout) throw SQLException("Timeout Expired") } /** Checks if the current thread has a transaction pending in the database. * @return true if the current thread has a transaction pending in the database */ fun inTransaction(): Boolean { return sqliteDatabase !!.inTransaction() } /** Executes one of the methods in the "transactions" enum. This just allows the * timeout code to be combined in one method. * @throws SQLException thrown if the timeout expires before the method successfully executes. */ fun execNoArgVoidMethod(transaction: Transaction?) { val timeNow = System.currentTimeMillis() var delta: Long = 0 do { try { when (transaction) { Transaction.setTransactionSuccessful -> { sqliteDatabase !!.setTransactionSuccessful() return } Transaction.beginTransaction -> { sqliteDatabase !!.beginTransaction() return } Transaction.endTransaction -> { sqliteDatabase !!.endTransaction() return } Transaction.close -> { sqliteDatabase !!.close() return } } } catch (e: SQLiteException) { delta = if (isLockedException(e)) { System.currentTimeMillis() - timeNow } else { throw ZkLiteConnection.chainException(e) } } } while (delta < timeout) throw SQLException("Timeout Expired") } /** Call the "setTransactionSuccessful" method on the database. * @throws SQLException */ fun setTransactionSuccessful() { execNoArgVoidMethod(Transaction.setTransactionSuccessful) } /** Call the "beginTransaction" method on the database. * @throws SQLException */ fun beginTransaction() { execNoArgVoidMethod(Transaction.beginTransaction) } /** Call the "endTransaction" method on the database. * @throws SQLException */ fun endTransaction() { execNoArgVoidMethod(Transaction.endTransaction) } /** Call the "close" method on the database. * @throws SQLException */ fun close() { execNoArgVoidMethod(Transaction.close) } init { val timeNow = System.currentTimeMillis() var delta: Long while (sqliteDatabase == null) { try { sqliteDatabase = SQLiteDatabase.openDatabase(dbQname, null, flags) } catch (e: SQLiteException) { if (isLockedException(e)) { try { Thread.sleep(retryInterval) } catch (e1: InterruptedException) { // ignore } delta = System.currentTimeMillis() - timeNow if (delta >= timeout) { throw ZkLiteConnection.chainException(e) } } else { throw ZkLiteConnection.chainException(e) } } } } }
3
Kotlin
3
24
00859b62570bf455addc9723015ba2c48b77028b
9,733
zakadabar-stack
Apache License 2.0
visionforge-solid/src/jsMain/kotlin/hep/dataforge/vision/solid/three/ThreeCanvasComponent.kt
cybernetics
324,970,553
true
{"Kotlin": 608275, "CSS": 687, "HTML": 436}
package hep.dataforge.vision.solid.three import hep.dataforge.context.Context import hep.dataforge.names.Name import hep.dataforge.vision.solid.Solid import hep.dataforge.vision.solid.specifications.Canvas3DOptions import org.w3c.dom.Element import org.w3c.dom.HTMLElement import react.RBuilder import react.RComponent import react.RProps import react.RState import react.dom.div import react.dom.findDOMNode interface ThreeCanvasProps : RProps { var context: Context var obj: Solid var options: Canvas3DOptions? var selected: Name? var clickCallback: (Name?) -> Unit var canvasCallback: ((ThreeCanvas?) -> Unit)? } interface ThreeCanvasState : RState { var element: Element? // var canvas: ThreeCanvas? } class ThreeCanvasComponent : RComponent<ThreeCanvasProps, ThreeCanvasState>() { private var canvas: ThreeCanvas? = null override fun componentDidMount() { if(canvas == null) { val element = state.element as? HTMLElement ?: error("Canvas element not found") val three: ThreePlugin = props.context.plugins.fetch(ThreePlugin) canvas = three.output(element, props.options ?: Canvas3DOptions.empty()).apply { onClick = props.clickCallback } props.canvasCallback?.invoke(canvas) } canvas?.render(props.obj) } override fun componentDidUpdate(prevProps: ThreeCanvasProps, prevState: ThreeCanvasState, snapshot: Any) { if (prevProps.obj != props.obj) { componentDidMount() } if (prevProps.selected != props.selected) { canvas?.select(props.selected) } } override fun RBuilder.render() { div { ref { state.element = findDOMNode(it) } } } } fun RBuilder.threeCanvas(object3D: Solid, options: Canvas3DOptions.() -> Unit = {}) { child(ThreeCanvasComponent::class) { attrs { this.obj = object3D this.options = Canvas3DOptions.invoke(options) } } }
0
null
0
0
62a6eafdeb1ce4b0d4f12a796ac6db22fc363f6e
2,067
visionforge
Apache License 2.0
src/main/kotlin/de/darkatra/vrising/discord/serverstatus/model/ServerStatusMonitorBuilder.kt
DarkAtra
500,198,988
false
null
package de.darkatra.vrising.discord.serverstatus.model class ServerStatusMonitorBuilder( var id: String, var discordServerId: String, var discordChannelId: String, var hostname: String, var queryPort: Int, var apiHostname: String? = null, var apiPort: Int? = null, var status: ServerStatusMonitorStatus, var displayServerDescription: Boolean, var displayPlayerGearLevel: Boolean, var currentEmbedMessageId: String? = null, var currentFailedAttempts: Int, var recentErrors: MutableList<Error> ) { fun build(): ServerStatusMonitor { return ServerStatusMonitor( id = id, discordServerId = discordServerId, discordChannelId = discordChannelId, hostname = hostname, queryPort = queryPort, apiHostname = apiHostname, apiPort = apiPort, status = status, displayServerDescription = displayServerDescription, displayPlayerGearLevel = displayPlayerGearLevel, currentEmbedMessageId = currentEmbedMessageId, currentFailedAttempts = currentFailedAttempts, recentErrors = recentErrors ) } }
4
Kotlin
2
8
051aaa99387c49f9fef6513d1f9f75c9de427ce7
1,215
v-rising-discord-bot
MIT License
src/main/kotlin/de/darkatra/vrising/discord/serverstatus/model/ServerStatusMonitorBuilder.kt
DarkAtra
500,198,988
false
null
package de.darkatra.vrising.discord.serverstatus.model class ServerStatusMonitorBuilder( var id: String, var discordServerId: String, var discordChannelId: String, var hostname: String, var queryPort: Int, var apiHostname: String? = null, var apiPort: Int? = null, var status: ServerStatusMonitorStatus, var displayServerDescription: Boolean, var displayPlayerGearLevel: Boolean, var currentEmbedMessageId: String? = null, var currentFailedAttempts: Int, var recentErrors: MutableList<Error> ) { fun build(): ServerStatusMonitor { return ServerStatusMonitor( id = id, discordServerId = discordServerId, discordChannelId = discordChannelId, hostname = hostname, queryPort = queryPort, apiHostname = apiHostname, apiPort = apiPort, status = status, displayServerDescription = displayServerDescription, displayPlayerGearLevel = displayPlayerGearLevel, currentEmbedMessageId = currentEmbedMessageId, currentFailedAttempts = currentFailedAttempts, recentErrors = recentErrors ) } }
4
Kotlin
2
8
051aaa99387c49f9fef6513d1f9f75c9de427ce7
1,215
v-rising-discord-bot
MIT License
libnavannotion/src/main/java/com/yjf/libnavannotion/FragmentDestination.kt
onemorechoice
302,218,017
false
null
package com.yjf.libnavannotion @Target(AnnotationTarget.CLASS) annotation class FragmentDestination(val pageUrl:String,val needLogin:Boolean=false,val asStart:Boolean=false)
0
Kotlin
0
0
da73f50296c5718717e0c0d33a27e625dac2b584
177
MyVideo
Apache License 2.0
buildSrc/src/main/java/io/wax911/emoji/buildSrc/plugin/components/AndroidDependencies.kt
AniTrend
98,423,653
false
null
package io.wax911.emoji.buildSrc.plugin.components import io.wax911.emoji.buildSrc.plugin.extensions.implementation import io.wax911.emoji.buildSrc.plugin.strategy.DependencyStrategy import org.gradle.api.Project internal fun Project.configureDependencies() { val dependencyStrategy = DependencyStrategy(project) dependencies.implementation( fileTree("libs") { include("*.jar") }, ) dependencyStrategy.applyDependenciesOn(dependencies) }
10
null
12
26
d91a63182b73b22c3a0163523c3073ee1108d57c
484
android-emojify
Apache License 2.0
app/src/main/java/com/hieuwu/groceriesstore/domain/usecases/impl/UserSettingsUseCaseImpl.kt
hieuwu
360,573,503
false
{"Kotlin": 307996}
package com.hieuwu.groceriesstore.domain.usecases.impl import com.hieuwu.groceriesstore.data.repository.UserRepository import com.hieuwu.groceriesstore.domain.usecases.UserSettingsUseCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject class UserSettingsUseCaseImpl @Inject constructor(private val userRepository: UserRepository) : UserSettingsUseCase { override suspend fun execute(input: UserSettingsUseCase.Input): UserSettingsUseCase.Output { withContext(Dispatchers.IO) { userRepository.updateUserSettings( input.id, input.isOrderCreatedEnabled, input.isDatabaseRefreshedEnabled, input.isPromotionEnabled ) } return UserSettingsUseCase.Output() } }
23
Kotlin
44
178
914b3948397f93d33a719109eaeb894e6e273828
835
android-groceries-store
MIT License
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/EduDocumentListenerBase.kt
JetBrains
43,696,115
false
{"Kotlin": 5014435, "Java": 42267, "Python": 19649, "HTML": 14893, "CSS": 10327, "JavaScript": 302, "Shell": 71}
package com.jetbrains.edu.learning import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.jetbrains.edu.learning.courseFormat.Course abstract class EduDocumentListenerBase(protected val holder: CourseInfoHolder<out Course?>) : DocumentListener { constructor(project: Project) : this(project.toCourseInfoHolder()) protected val fileDocumentManager: FileDocumentManager = FileDocumentManager.getInstance() protected fun DocumentEvent.isInProjectContent(): Boolean { val file = fileDocumentManager.getFile(document) ?: return false return VfsUtil.isAncestor(holder.courseDir, file, true) } }
7
Kotlin
49
150
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
822
educational-plugin
Apache License 2.0
partiql-lang/src/test/kotlin/org/partiql/lang/planner/transforms/PartiQLSchemaInferencerTests.kt
partiql
186,474,394
false
null
package org.partiql.lang.planner.transforms import com.amazon.ionelement.api.field import com.amazon.ionelement.api.ionString import com.amazon.ionelement.api.ionStructOf import com.amazon.ionelement.api.loadSingleElement import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.parallel.Execution import org.junit.jupiter.api.parallel.ExecutionMode import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource import org.junit.jupiter.params.provider.MethodSource import org.partiql.annotations.ExperimentalPartiQLSchemaInferencer import org.partiql.errors.Problem import org.partiql.errors.UNKNOWN_PROBLEM_LOCATION import org.partiql.lang.errors.ProblemCollector import org.partiql.lang.planner.SchemaLoader.toStaticType import org.partiql.lang.planner.transforms.PartiQLSchemaInferencerTests.ProblemHandler import org.partiql.lang.planner.transforms.PartiQLSchemaInferencerTests.TestCase.ErrorTestCase import org.partiql.lang.planner.transforms.PartiQLSchemaInferencerTests.TestCase.SuccessTestCase import org.partiql.lang.planner.transforms.PartiQLSchemaInferencerTests.TestCase.ThrowingExceptionTestCase import org.partiql.plan.debug.PlanPrinter import org.partiql.planner.PartiQLPlanner import org.partiql.planner.PlanningProblemDetails import org.partiql.planner.test.PartiQLTest import org.partiql.planner.test.PartiQLTestProvider import org.partiql.plugins.memory.MemoryCatalog import org.partiql.plugins.memory.MemoryPlugin import org.partiql.types.AnyOfType import org.partiql.types.AnyType import org.partiql.types.BagType import org.partiql.types.ListType import org.partiql.types.SexpType import org.partiql.types.StaticType import org.partiql.types.StaticType.Companion.ANY import org.partiql.types.StaticType.Companion.BAG import org.partiql.types.StaticType.Companion.BOOL import org.partiql.types.StaticType.Companion.DATE import org.partiql.types.StaticType.Companion.DECIMAL import org.partiql.types.StaticType.Companion.INT import org.partiql.types.StaticType.Companion.INT4 import org.partiql.types.StaticType.Companion.INT8 import org.partiql.types.StaticType.Companion.MISSING import org.partiql.types.StaticType.Companion.NULL import org.partiql.types.StaticType.Companion.STRING import org.partiql.types.StaticType.Companion.unionOf import org.partiql.types.StructType import org.partiql.types.TupleConstraint import java.time.Instant import java.util.stream.Stream import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class PartiQLSchemaInferencerTests { private val testProvider = PartiQLTestProvider() init { // load test inputs testProvider.load() } @ParameterizedTest @ArgumentsSource(TestProvider::class) fun test(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("collections") @Execution(ExecutionMode.CONCURRENT) fun testCollections(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("selectStar") @Execution(ExecutionMode.CONCURRENT) fun testSelectStar(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("sessionVariables") @Execution(ExecutionMode.CONCURRENT) fun testSessionVariables(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("bitwiseAnd") @Execution(ExecutionMode.CONCURRENT) fun testBitwiseAnd(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("unpivotCases") @Execution(ExecutionMode.CONCURRENT) fun testUnpivot(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("joinCases") @Execution(ExecutionMode.CONCURRENT) fun testJoins(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("excludeCases") @Execution(ExecutionMode.CONCURRENT) fun testExclude(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("orderByCases") @Execution(ExecutionMode.CONCURRENT) fun testOrderBy(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("tupleUnionCases") @Execution(ExecutionMode.CONCURRENT) fun testTupleUnion(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("aggregationCases") @Execution(ExecutionMode.CONCURRENT) fun testAggregations(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("scalarFunctions") @Execution(ExecutionMode.CONCURRENT) fun testScalarFunctions(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("pathExpressions") @Execution(ExecutionMode.CONCURRENT) fun testPathExpressions(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("caseWhens") @Execution(ExecutionMode.CONCURRENT) fun testCaseWhens(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("subqueryCases") @Execution(ExecutionMode.CONCURRENT) fun testSubqueries(tc: TestCase) = runTest(tc) @ParameterizedTest @MethodSource("dynamicCalls") @Execution(ExecutionMode.CONCURRENT) fun testDynamicCalls(tc: TestCase) = runTest(tc) companion object { val inputStream = this::class.java.getResourceAsStream("/resource_path.txt")!! val catalogProvider = MemoryCatalog.Provider().also { val map = mutableMapOf<String, MutableList<Pair<String, StaticType>>>() inputStream.reader().readLines().forEach { path -> if (path.startsWith("catalogs/default")) { val schema = this::class.java.getResourceAsStream("/$path")!! val ion = loadSingleElement(schema.reader().readText()) val staticType = ion.toStaticType() val steps = path.split('/').drop(2) // drop the catalogs/default val catalogName = steps.first() val subPath = steps .drop(1) .joinToString(".") { it.lowercase() } .let { it.substring(0, it.length - 4) } if (map.containsKey(catalogName)) { map[catalogName]!!.add(subPath to staticType) } else { map[catalogName] = mutableListOf(subPath to staticType) } } } map.forEach { (k: String, v: MutableList<Pair<String, StaticType>>) -> it[k] = MemoryCatalog.of(*v.toTypedArray()) } } private val PLUGINS = listOf(MemoryPlugin(catalogProvider)) private const val USER_ID = "TEST_USER" private val catalogConfig = mapOf( "aws" to ionStructOf( field("connector_name", ionString("memory")), ), "b" to ionStructOf( field("connector_name", ionString("memory")), ), "db" to ionStructOf( field("connector_name", ionString("memory")), ), "pql" to ionStructOf( field("connector_name", ionString("memory")), ), "subqueries" to ionStructOf( field("connector_name", ionString("memory")), ), ) const val CATALOG_AWS = "aws" const val CATALOG_B = "b" const val CATALOG_DB = "db" val DB_SCHEMA_MARKETS = listOf("markets") val TYPE_BOOL = StaticType.BOOL private val TYPE_AWS_DDB_PETS_ID = INT4 private val TYPE_AWS_DDB_PETS_BREED = STRING val TABLE_AWS_DDB_PETS = BagType( elementType = StructType( fields = mapOf( "id" to TYPE_AWS_DDB_PETS_ID, "breed" to TYPE_AWS_DDB_PETS_BREED ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) val TABLE_AWS_DDB_PETS_LIST = ListType( elementType = StructType( fields = mapOf( "id" to TYPE_AWS_DDB_PETS_ID, "breed" to TYPE_AWS_DDB_PETS_BREED ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) val TABLE_AWS_DDB_B = BagType( StructType( fields = mapOf("identifier" to STRING), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) val TABLE_AWS_B_B = BagType( StructType( fields = mapOf("identifier" to INT4), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) val TYPE_B_B_B_B_B = INT4 private val TYPE_B_B_B_B = StructType( mapOf("b" to TYPE_B_B_B_B_B), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered) ) val TYPE_B_B_B_C = INT4 val TYPE_B_B_C = INT4 val TYPE_B_B_B = StructType( fields = mapOf( "b" to TYPE_B_B_B_B, "c" to TYPE_B_B_B_C ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) private fun assertProblemExists(problem: () -> Problem) = ProblemHandler { problems, ignoreSourceLocation -> when (ignoreSourceLocation) { true -> assertTrue("Expected to find ${problem.invoke()} in $problems") { problems.any { it.details == problem.invoke().details } } false -> assertTrue("Expected to find ${problem.invoke()} in $problems") { problems.any { it == problem.invoke() } } } } // Tests private fun key(name: String) = PartiQLTest.Key("schema_inferencer", name) @JvmStatic fun collections() = listOf<TestCase>( SuccessTestCase( name = "Collection BAG<INT4>", key = key("collections-01"), expected = BagType(INT4), ), SuccessTestCase( name = "Collection LIST<INT4>", key = key("collections-02"), expected = ListType(INT4), ), SuccessTestCase( name = "Collection LIST<INT4>", key = key("collections-03"), expected = ListType(INT4), ), SuccessTestCase( name = "Collection SEXP<INT4>", key = key("collections-04"), expected = SexpType(INT4), ), SuccessTestCase( name = "SELECT from array", key = key("collections-05"), expected = BagType(INT4), ), SuccessTestCase( name = "SELECT from array", key = key("collections-06"), expected = BagType( StructType( fields = listOf(StructType.Field("x", INT4)), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ) @JvmStatic fun structs() = listOf<TestCase>() @JvmStatic fun selectStar() = listOf<TestCase>( SuccessTestCase( name = "Test #8", catalog = CATALOG_AWS, query = "SELECT * FROM ddb.pets", expected = TABLE_AWS_DDB_PETS ), SuccessTestCase( name = "Test #9", catalog = CATALOG_AWS, query = "SELECT * FROM b.b", expected = TABLE_AWS_B_B ), SuccessTestCase( name = "Select star with join", key = key("sanity-05"), catalog = "pql", expected = BagType( StructType( contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(false), TupleConstraint.Ordered ), fields = listOf( StructType.Field( "name", StructType( fields = listOf( StructType.Field("first", STRING), StructType.Field("last", STRING), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ), ) ), StructType.Field("ssn", STRING), StructType.Field("employer", STRING.asNullable()), StructType.Field("name", STRING), StructType.Field("tax_id", INT8), StructType.Field( "address", StructType( fields = listOf( StructType.Field("street", STRING), StructType.Field("zip", INT4), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ), ) ) ) ), SuccessTestCase( name = "Select star", key = key("sanity-06"), catalog = "pql", expected = BagType( StructType( fields = listOf( StructType.Field("first", STRING), StructType.Field("last", STRING), StructType.Field("full_name", STRING), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ) @JvmStatic fun sessionVariables() = listOf( SuccessTestCase( name = "Current User", query = "CURRENT_USER", expected = unionOf(STRING, StaticType.NULL) ), SuccessTestCase( name = "Current User Concat", query = "CURRENT_USER || 'hello'", expected = unionOf(STRING, StaticType.NULL) ), SuccessTestCase( name = "Current User in WHERE", query = "SELECT VALUE a FROM [ 0 ] AS a WHERE CURRENT_USER = 'hello'", expected = BagType(INT4) ), SuccessTestCase( name = "Current User in WHERE", query = "SELECT VALUE a FROM [ 0 ] AS a WHERE CURRENT_USER = 5", expected = BagType(INT4), ), SuccessTestCase( name = "Testing CURRENT_USER and CURRENT_DATE Binders", query = """ SELECT CURRENT_USER, CURRENT_DATE, CURRENT_USER AS "curr_user", CURRENT_DATE AS "curr_date", CURRENT_USER || ' is my name.' AS name_desc FROM << 0, 1 >>; """.trimIndent(), expected = BagType( StructType( fields = listOf( StructType.Field("CURRENT_USER", STRING.asNullable()), StructType.Field("CURRENT_DATE", DATE), StructType.Field("curr_user", STRING.asNullable()), StructType.Field("curr_date", DATE), StructType.Field("name_desc", STRING.asNullable()), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ErrorTestCase( name = "Current User (String) PLUS String", query = "CURRENT_USER + 'hello'", expected = StaticType.MISSING, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnknownFunction( "plus", listOf( unionOf(STRING, StaticType.NULL), STRING, ), ) ) } ), ) @JvmStatic fun bitwiseAnd() = listOf( SuccessTestCase( name = "BITWISE_AND_1", query = "1 & 2", expected = INT4 ), SuccessTestCase( name = "BITWISE_AND_2", query = "CAST(1 AS INT2) & CAST(2 AS INT2)", expected = StaticType.unionOf(StaticType.INT2, MISSING) ), SuccessTestCase( name = "BITWISE_AND_3", query = "1 & 2", expected = INT4 ), SuccessTestCase( name = "BITWISE_AND_4", query = "CAST(1 AS INT8) & CAST(2 AS INT8)", expected = StaticType.INT8 ), SuccessTestCase( name = "BITWISE_AND_5", query = "CAST(1 AS INT2) & 2", expected = StaticType.unionOf(StaticType.INT4, MISSING) ), SuccessTestCase( name = "BITWISE_AND_6", query = "CAST(1 AS INT2) & CAST(2 AS INT8)", expected = StaticType.unionOf(StaticType.INT8, MISSING) ), SuccessTestCase( name = "BITWISE_AND_7", query = "CAST(1 AS INT2) & 2", expected = StaticType.unionOf(INT4, MISSING) ), SuccessTestCase( name = "BITWISE_AND_8", query = "1 & CAST(2 AS INT8)", expected = StaticType.INT8 ), SuccessTestCase( name = "BITWISE_AND_9", query = "1 & 2", expected = StaticType.INT4 ), SuccessTestCase( name = "BITWISE_AND_10", query = "CAST(1 AS INT8) & 2", expected = INT8 ), SuccessTestCase( name = "BITWISE_AND_NULL_OPERAND", query = "1 & NULL", expected = StaticType.NULL, ), ErrorTestCase( name = "BITWISE_AND_MISSING_OPERAND", query = "1 & MISSING", expected = StaticType.MISSING, problemHandler = assertProblemExists { Problem( sourceLocation = UNKNOWN_PROBLEM_LOCATION, details = PlanningProblemDetails.UnknownFunction( "bitwise_and", listOf(INT4, MISSING) ) ) } ), ErrorTestCase( name = "BITWISE_AND_NON_INT_OPERAND", query = "1 & 'NOT AN INT'", expected = StaticType.MISSING, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnknownFunction("bitwise_and", listOf(INT4, STRING)) ) } ), ) @JvmStatic fun unpivotCases() = listOf( SuccessTestCase( name = "UNPIVOT", query = "SELECT VALUE v FROM UNPIVOT { 'a': 2 } AS v AT attr WHERE attr = 'a'", expected = BagType(INT4) ), ) @JvmStatic fun joinCases() = listOf( SuccessTestCase( name = "CROSS JOIN", query = "SELECT * FROM <<{ 'a': 1 }>> AS t1, <<{ 'b': 2.0 }>> AS t2", expected = BagType( StructType( fields = mapOf( "a" to INT4, "b" to StaticType.DECIMAL, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "LEFT JOIN", query = "SELECT * FROM <<{ 'a': 1 }>> AS t1 LEFT JOIN <<{ 'b': 2.0 }>> AS t2 ON TRUE", expected = BagType( StructType( fields = mapOf( "a" to INT4, "b" to unionOf(NULL, DECIMAL), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "LEFT JOIN", query = "SELECT b, a FROM <<{ 'a': 1 }>> AS t1 LEFT JOIN <<{ 'b': 2.0 }>> AS t2 ON TRUE", expected = BagType( StructType( fields = listOf( StructType.Field("b", unionOf(NULL, DECIMAL)), StructType.Field("a", INT4), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "LEFT JOIN", query = "SELECT t1.a, t2.a FROM <<{ 'a': 1 }>> AS t1 LEFT JOIN <<{ 'a': 2.0 }>> AS t2 ON t1.a = t2.a", expected = BagType( StructType( fields = listOf( StructType.Field("a", INT4), StructType.Field("a", unionOf(NULL, DECIMAL)), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(false), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "LEFT JOIN ALL", query = "SELECT * FROM <<{ 'a': 1 }>> AS t1 LEFT JOIN <<{ 'a': 2.0 }>> AS t2 ON t1.a = t2.a", expected = BagType( StructType( fields = listOf( StructType.Field("a", INT4), StructType.Field("a", unionOf(NULL, DECIMAL)), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(false), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "LEFT JOIN ALL", query = """ SELECT * FROM <<{ 'a': 1 }>> AS t1 LEFT JOIN <<{ 'a': 2.0 }>> AS t2 ON t1.a = t2.a LEFT JOIN <<{ 'a': 'hello, world' }>> AS t3 ON t3.a = 'hello' """, expected = BagType( StructType( fields = listOf( StructType.Field("a", INT4), StructType.Field("a", unionOf(DECIMAL, NULL)), StructType.Field("a", unionOf(STRING, NULL)), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(false), TupleConstraint.Ordered ) ) ) ), ErrorTestCase( name = "LEFT JOIN Ambiguous Reference in ON", query = "SELECT * FROM <<{ 'a': 1 }>> AS t1 LEFT JOIN <<{ 'a': 2.0 }>> AS t2 ON a = 3", expected = BagType( StructType( fields = listOf( StructType.Field("a", INT4), StructType.Field("a", unionOf(DECIMAL, NULL)), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(false), TupleConstraint.Ordered ) ) ), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("a", false) ) } ), ) @JvmStatic fun excludeCases() = listOf( SuccessTestCase( name = "EXCLUDE SELECT star", key = key("exclude-01"), expected = BagType( StructType( fields = mapOf( "name" to StaticType.STRING, "custId" to StaticType.INT4, "address" to StructType( fields = mapOf( "city" to StaticType.STRING, "zipcode" to StaticType.INT4, "street" to StaticType.STRING, ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE SELECT star multiple paths", key = key("exclude-02"), expected = BagType( StructType( fields = mapOf( "name" to StaticType.STRING, "custId" to StaticType.INT4, "address" to StructType( fields = mapOf( "city" to StaticType.STRING, "zipcode" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE SELECT star list index and list index field", key = key("exclude-03"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to ListType( elementType = StructType( fields = mapOf( "field" to AnyOfType( setOf( INT4, MISSING // c[1]'s `field` was excluded ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), "foo" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE SELECT star collection index as last step", key = key("exclude-04"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to ListType( elementType = StaticType.INT4 ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), "foo" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC) SuccessTestCase( name = "EXCLUDE SELECT star collection wildcard as last step", key = key("exclude-05"), expected = BagType( StructType( fields = mapOf( "a" to ListType( elementType = StaticType.INT4 // empty list but still preserve typing information ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE SELECT star list wildcard", key = key("exclude-06"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to ListType( elementType = StructType( fields = mapOf( "field_y" to StaticType.INT4 ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), "foo" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE SELECT star list tuple wildcard", key = key("exclude-07"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to ListType( elementType = StructType( fields = mapOf( // all fields gone ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), "foo" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE SELECT star order by", key = key("exclude-08"), expected = ListType( StructType( fields = mapOf( "foo" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE SELECT star with JOINs", key = key("exclude-09"), expected = BagType( StructType( fields = mapOf( "a" to StaticType.INT4, "b" to StaticType.INT4, "c" to StaticType.INT4 ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT t.b EXCLUDE ex 1", key = key("exclude-10"), expected = BagType( StructType( fields = mapOf( "b" to ListType( elementType = StructType( fields = mapOf( "b_2" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT * EXCLUDE ex 2", key = key("exclude-11"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "a_1" to StaticType.INT4, "a_2" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), "b" to ListType( elementType = StructType( fields = mapOf( "b_2" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ), "c" to StaticType.INT4, "d" to StaticType.INT4 ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT VALUE t.b EXCLUDE", key = key("exclude-12"), expected = BagType( ListType( elementType = StructType( fields = mapOf( "b_2" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ), ) ), SuccessTestCase( name = "SELECT * EXCLUDE collection wildcard and nested tuple attr", key = key("exclude-13"), expected = BagType( StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StructType( fields = mapOf( "d" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT * EXCLUDE collection index and nested tuple attr", key = key("exclude-14"), expected = BagType( StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to StaticType.INT4.asOptional(), "d" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT * EXCLUDE collection wildcard and nested tuple wildcard", key = key("exclude-15"), expected = BagType( StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StructType( fields = mapOf(), // empty map; all fields of b excluded contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT * EXCLUDE collection index and nested tuple wildcard", key = key("exclude-16"), expected = BagType( StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StructType( fields = mapOf( // all fields of b optional "c" to StaticType.INT4.asOptional(), "d" to StaticType.STRING.asOptional() ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT * EXCLUDE collection wildcard and nested collection wildcard", key = key("exclude-17"), expected = BagType( StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to StaticType.INT4, "d" to ListType( elementType = StructType( fields = mapOf( "f" to StaticType.BOOL ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT * EXCLUDE collection index and nested collection wildcard", key = key("exclude-18"), expected = BagType( StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to StaticType.INT4, "d" to ListType( elementType = StructType( fields = mapOf( "e" to StaticType.STRING.asOptional(), // last step is optional since only a[1]... is excluded "f" to StaticType.BOOL ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "SELECT * EXCLUDE collection index and nested collection index", key = key("exclude-19"), expected = BagType( StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to StaticType.INT4, "d" to ListType( elementType = StructType( fields = mapOf( // same as above "e" to StaticType.STRING.asOptional(), "f" to StaticType.BOOL ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE case sensitive lookup", key = key("exclude-20"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "B" to StructType( fields = mapOf( "d" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE case sensitive lookup with capitalized and uncapitalized attr", key = key("exclude-21"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "B" to StructType( fields = mapOf( "C" to StaticType.BOOL, // keep 'C' "d" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE case sensitive lookup with both capitalized and uncapitalized removed", key = key("exclude-22"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "B" to StructType( fields = mapOf( "d" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE with both duplicates", key = key("exclude-23"), expected = BagType( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "B" to StructType( fields = mapOf( // both "c" removed "d" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(false) ) // UniqueAttrs set to false ), ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC) SuccessTestCase( name = "EXCLUDE with removed attribute later referenced", key = key("exclude-24"), expected = BagType( StructType( fields = mapOf( "c" to StaticType.INT4 ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC) SuccessTestCase( name = "EXCLUDE with non-existent attribute reference", key = key("exclude-25"), expected = BagType( StructType( fields = mapOf( "a" to StaticType.INT4 ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC); could give error/warning SuccessTestCase( name = "exclude union of types", key = key("exclude-26"), expected = BagType( StructType( fields = mapOf( "t" to StaticType.unionOf( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "c" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), StructType( fields = mapOf( "a" to StaticType.NULL ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "exclude union of types exclude same type", key = key("exclude-27"), expected = BagType( StructType( fields = mapOf( "t" to StaticType.unionOf( StructType( fields = mapOf( "a" to StructType( fields = mapOf( "c" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), StructType( fields = mapOf( "a" to StructType( fields = mapOf( "c" to StaticType.NULL ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ), ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "exclude union of types exclude different type", key = key("exclude-28"), expected = BagType( StructType( fields = mapOf( "t" to StructType( // union gone fields = mapOf( "a" to StructType( fields = mapOf( "b" to StaticType.INT4 ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC); could give error/warning SuccessTestCase( name = "invalid exclude collection wildcard", key = key("exclude-29"), expected = BagType( elementType = StructType( fields = mapOf( "a" to StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to StaticType.INT4, "d" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC); could give error/warning SuccessTestCase( name = "invalid exclude collection index", key = key("exclude-30"), expected = BagType( elementType = StructType( fields = mapOf( "a" to StructType( fields = mapOf( "b" to StructType( fields = mapOf( "c" to StaticType.INT4, "d" to StaticType.STRING ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC); could give error/warning SuccessTestCase( name = "invalid exclude tuple attr", key = key("exclude-31"), expected = BagType( elementType = StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC); could give error/warning SuccessTestCase( name = "invalid exclude tuple wildcard", key = key("exclude-32"), expected = BagType( elementType = StructType( fields = mapOf( "a" to ListType( elementType = StructType( fields = mapOf( "b" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC); could give error/warning SuccessTestCase( name = "invalid exclude tuple attr step", key = key("exclude-33"), expected = BagType( elementType = StructType( fields = mapOf( "a" to BagType( elementType = StructType( fields = mapOf( "b" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), // EXCLUDE regression test (behavior subject to change pending RFC); could give error/warning ErrorTestCase( name = "invalid exclude root", key = key("exclude-34"), expected = BagType( elementType = StructType( fields = mapOf( "a" to BagType( elementType = StructType( fields = mapOf( "b" to StaticType.INT4 ), contentClosed = true, constraints = setOf(TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true)) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnresolvedExcludeExprRoot("nonsense") ) } ), // EXCLUDE regression test (behavior subject to change pending RFC); could give error/warning SuccessTestCase( name = "exclude with unions and last step collection index", key = key("exclude-35"), expected = BagType( elementType = StructType( fields = mapOf( "a" to ListType( elementType = StaticType.unionOf( StructType( fields = mapOf( "b" to StaticType.INT4, "c" to StaticType.INT4.asOptional() ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), StructType( fields = mapOf( "b" to StaticType.INT4, "c" to StaticType.NULL.asOptional() ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ), StructType( fields = mapOf( "b" to StaticType.INT4, "c" to StaticType.DECIMAL.asOptional() ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true) ) ) ) ) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "EXCLUDE using a catalog", catalog = CATALOG_B, key = key("exclude-36"), expected = BagType( elementType = StructType( fields = mapOf( "b" to StructType( fields = mapOf( "b" to StaticType.INT4 ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ) @JvmStatic fun orderByCases() = listOf( SuccessTestCase( name = "ORDER BY int", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM pets ORDER BY id", expected = TABLE_AWS_DDB_PETS_LIST ), SuccessTestCase( name = "ORDER BY str", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM pets ORDER BY breed", expected = TABLE_AWS_DDB_PETS_LIST ), ErrorTestCase( name = "ORDER BY str", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM pets ORDER BY unknown_col", expected = TABLE_AWS_DDB_PETS_LIST, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("unknown_col", false) ) } ), ) @JvmStatic fun tupleUnionCases() = listOf( SuccessTestCase( name = "Empty Tuple Union", query = "TUPLEUNION()", expected = StructType( fields = emptyMap(), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ), SuccessTestCase( name = "Tuple Union with Literal Struct", query = "TUPLEUNION({ 'a': 1, 'b': 'hello' })", expected = StructType( fields = mapOf( "a" to StaticType.INT4, "b" to StaticType.STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), ) ), ), SuccessTestCase( name = "Tuple Union with Literal Struct AND Duplicates", query = "TUPLEUNION({ 'a': 1, 'a': 'hello' })", expected = StructType( fields = listOf( StructType.Field("a", INT4), StructType.Field("a", STRING), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(false), ) ), ), SuccessTestCase( name = "Tuple Union with Nested Struct", query = """ SELECT VALUE TUPLEUNION( t.a ) FROM << { 'a': { 'b': 1 } } >> AS t """, expected = BagType( StructType( fields = listOf( StructType.Field("b", INT4), ), contentClosed = true, // TODO: This shouldn't be ordered. However, this doesn't come from the TUPLEUNION. It is // coming from the RexOpSelect. constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ), ), SuccessTestCase( name = "Tuple Union with Heterogeneous Data", query = """ SELECT VALUE TUPLEUNION( t.a ) FROM << { 'a': { 'b': 1 } }, { 'a': 1 } >> AS t """, expected = BagType( unionOf( MISSING, StructType( fields = listOf( StructType.Field("b", INT4), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), ) ) ) ), ), SuccessTestCase( name = "Tuple Union with Heterogeneous Data (2)", query = """ SELECT VALUE TUPLEUNION( t.a ) FROM << { 'a': { 'b': 1 } }, { 'a': { 'b': 'hello' } }, { 'a': NULL }, { 'a': 4.5 }, { } >> AS t """, expected = BagType( unionOf( NULL, MISSING, StructType( fields = listOf( StructType.Field("b", INT4), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), ) ), StructType( fields = listOf( StructType.Field("b", STRING), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), ) ) ) ), ), SuccessTestCase( name = "Tuple Union with Heterogeneous Data (3)", query = """ SELECT VALUE TUPLEUNION( p.name ) FROM aws.ddb.persons AS p """, expected = BagType( unionOf( MISSING, StructType( fields = listOf( StructType.Field("first", STRING), StructType.Field("last", STRING), ), contentClosed = false, constraints = setOf( TupleConstraint.Open(true), TupleConstraint.UniqueAttrs(false), ) ), StructType( fields = listOf( StructType.Field("full_name", STRING), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ), ) ), ), SuccessTestCase( name = "Complex Tuple Union with Heterogeneous Data", query = """ SELECT VALUE TUPLEUNION( p.name, p.name ) FROM aws.ddb.persons AS p """, expected = BagType( unionOf( MISSING, StructType( fields = listOf( StructType.Field("first", STRING), StructType.Field("last", STRING), StructType.Field("first", STRING), StructType.Field("last", STRING), ), contentClosed = false, constraints = setOf( TupleConstraint.Open(true), TupleConstraint.UniqueAttrs(false), ) ), StructType( fields = listOf( StructType.Field("first", STRING), StructType.Field("last", STRING), StructType.Field("full_name", STRING), ), contentClosed = false, constraints = setOf( TupleConstraint.Open(true), TupleConstraint.UniqueAttrs(false), ) ), StructType( fields = listOf( StructType.Field("full_name", STRING), StructType.Field("first", STRING), StructType.Field("last", STRING), ), contentClosed = false, constraints = setOf( TupleConstraint.Open(true), TupleConstraint.UniqueAttrs(false), ) ), StructType( fields = listOf( StructType.Field("full_name", STRING), StructType.Field("full_name", STRING), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(false), TupleConstraint.Ordered ) ), ) ), ), ) @JvmStatic fun caseWhens() = listOf( SuccessTestCase( name = "Easy case when", query = """ CASE WHEN FALSE THEN 0 WHEN TRUE THEN 1 ELSE 2 END; """, expected = INT4 ), SuccessTestCase( name = "Folded case when to grab the true", query = """ CASE WHEN FALSE THEN 0 WHEN TRUE THEN 'hello' END; """, expected = STRING ), SuccessTestCase( name = "Boolean case when", query = """ CASE 'Hello World' WHEN 'Hello World' THEN TRUE ELSE FALSE END; """, expected = BOOL ), SuccessTestCase( name = "Folded out false", query = """ CASE WHEN FALSE THEN 'IMPOSSIBLE TO GET' ELSE TRUE END; """, expected = BOOL ), SuccessTestCase( name = "Folded out false without default", query = """ CASE WHEN FALSE THEN 'IMPOSSIBLE TO GET' END; """, expected = NULL ), SuccessTestCase( name = "Not folded gives us a nullable without default", query = """ CASE 1 WHEN 1 THEN TRUE WHEN 2 THEN FALSE END; """, expected = BOOL.asNullable() ), SuccessTestCase( name = "Not folded gives us a nullable without default for query", query = """ SELECT CASE breed WHEN 'golden retriever' THEN 'fluffy dog' WHEN 'pitbull' THEN 'short-haired dog' END AS breed_descriptor FROM dogs """, catalog = "pql", catalogPath = listOf("main"), expected = BagType( StructType( fields = mapOf( "breed_descriptor" to STRING.asNullable(), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Query", query = """ SELECT CASE breed WHEN 'golden retriever' THEN 'fluffy dog' WHEN 'pitbull' THEN 'short-haired dog' ELSE 'something else' END AS breed_descriptor FROM dogs """, catalog = "pql", catalogPath = listOf("main"), expected = BagType( StructType( fields = mapOf( "breed_descriptor" to STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Query with heterogeneous data", query = """ SELECT CASE breed WHEN 'golden retriever' THEN 'fluffy dog' WHEN 'pitbull' THEN 2 ELSE 2.0 END AS breed_descriptor FROM dogs """, catalog = "pql", catalogPath = listOf("main"), expected = BagType( StructType( fields = mapOf( "breed_descriptor" to unionOf(STRING, INT4, DECIMAL), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ) @JvmStatic fun pathExpressions() = listOf( SuccessTestCase( name = "Index on literal list", query = """ [0, 1, 2, 3][0] """, expected = INT4 ), SuccessTestCase( name = "Index on global list", query = """ dogs[0].breed """, catalog = "pql", catalogPath = listOf("main"), expected = STRING ), SuccessTestCase( name = "Index on list attribute of global table", query = """ SELECT typical_allergies[0] AS main_allergy FROM dogs """, catalog = "pql", catalogPath = listOf("main"), expected = BagType( StructType( fields = mapOf( "main_allergy" to STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Pathing into resolved local variable without qualification", query = """ SELECT address.street AS s FROM employer; """, catalog = "pql", catalogPath = listOf("main"), expected = BagType( StructType( fields = mapOf( "s" to STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Pathing into resolved local variable without qualification and with sensitivity", query = """ SELECT address."street" AS s FROM employer; """, catalog = "pql", catalogPath = listOf("main"), expected = BagType( StructType( fields = mapOf( "s" to STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Pathing into resolved local variable without qualification and with indexing syntax", query = """ SELECT address['street'] AS s FROM employer; """, catalog = "pql", catalogPath = listOf("main"), expected = BagType( StructType( fields = mapOf( "s" to STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Pathing into resolved local variable without qualification and with indexing syntax and fully-qualified FROM", query = """ SELECT e.address['street'] AS s FROM "pql"."main"."employer" AS e; """, expected = BagType( StructType( fields = mapOf( "s" to STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ErrorTestCase( name = "Show that we can't use [<string>] to reference a value in a schema. It can only be used on tuples.", query = """ SELECT VALUE 1 FROM "pql"."main"['employer'] AS e; """, expected = BagType(INT4), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("main", true) ) } ), ErrorTestCase( name = "Show that we can't use [<string>] to reference a schema in a catalog. It can only be used on tuples.", query = """ SELECT VALUE 1 FROM "pql"['main']."employer" AS e; """, expected = BagType(INT4), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("pql", true) ) } ), SuccessTestCase( name = "Tuple indexing syntax on literal tuple with literal string key", query = """ { 'aBc': 1, 'AbC': 2.0 }['AbC']; """, expected = DECIMAL ), // This should fail because the Spec says tuple indexing MUST use a literal string or explicit cast. ErrorTestCase( name = "Array indexing syntax on literal tuple with non-literal and non-cast key", query = """ { 'aBc': 1, 'AbC': 2.0 }['Ab' || 'C']; """, expected = MISSING, problemHandler = assertProblemExists { Problem( sourceLocation = UNKNOWN_PROBLEM_LOCATION, details = PlanningProblemDetails.ExpressionAlwaysReturnsNullOrMissing ) } ), // The reason this is ANY is because we do not have support for constant-folding. We don't know what // CAST('Ab' || 'C' AS STRING) will evaluate to, and therefore, we don't know what the indexing operation // will return. SuccessTestCase( name = "Tuple indexing syntax on literal tuple with explicit cast key", query = """ { 'aBc': 1, 'AbC': 2.0 }[CAST('Ab' || 'C' AS STRING)]; """, expected = ANY ), ) @JvmStatic fun scalarFunctions() = listOf( SuccessTestCase( name = "UPPER on binding tuple of literal string", query = """ SELECT UPPER(some_str) AS upper_str FROM << { 'some_str': 'hello world!' } >> AS t """, expected = BagType( StructType( fields = mapOf( "upper_str" to STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "UPPER on literal string", query = """ UPPER('hello world') """, expected = STRING ), SuccessTestCase( name = "UPPER on global string", query = """ UPPER(os) """, catalog = "pql", catalogPath = listOf("main"), expected = STRING ), SuccessTestCase( name = "UPPER on global string", query = """ UPPER(os) """, catalog = "pql", catalogPath = listOf("main"), expected = STRING ), SuccessTestCase( name = "UPPER on global struct", query = """ UPPER(person.ssn) """, catalog = "pql", catalogPath = listOf("main"), expected = STRING ), SuccessTestCase( name = "UPPER on global nested struct", query = """ UPPER(person.name."first") """, catalog = "pql", catalogPath = listOf("main"), expected = STRING ), SuccessTestCase( name = "UPPER on global table", query = """ SELECT UPPER(breed) AS upper_breed FROM dogs """, catalog = "pql", catalogPath = listOf("main"), expected = BagType( StructType( fields = mapOf( "upper_breed" to STRING, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ) @JvmStatic fun aggregationCases() = listOf( SuccessTestCase( name = "AGGREGATE over INTS, without alias", query = "SELECT a, COUNT(*), SUM(a), MIN(b) FROM << {'a': 1, 'b': 2} >> GROUP BY a", expected = BagType( StructType( fields = mapOf( "a" to INT4, "_1" to INT4, "_2" to INT4.asNullable(), "_3" to INT4.asNullable(), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "AGGREGATE over INTS, with alias", query = "SELECT a, COUNT(*) AS c, SUM(a) AS s, MIN(b) AS m FROM << {'a': 1, 'b': 2} >> GROUP BY a", expected = BagType( StructType( fields = mapOf( "a" to INT4, "c" to INT4, "s" to INT4.asNullable(), "m" to INT4.asNullable(), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "AGGREGATE over DECIMALS", query = "SELECT a, COUNT(*) AS c, SUM(a) AS s, MIN(b) AS m FROM << {'a': 1.0, 'b': 2.0}, {'a': 1.0, 'b': 2.0} >> GROUP BY a", expected = BagType( StructType( fields = mapOf( "a" to StaticType.DECIMAL, "c" to INT4, "s" to StaticType.DECIMAL.asNullable(), "m" to StaticType.DECIMAL.asNullable(), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ) @JvmStatic fun dynamicCalls() = listOf( SuccessTestCase( name = "unary plus on varying numeric types -- this cannot return missing!", query = """ SELECT +t.a AS a FROM << { 'a': CAST(1 AS INT8) }, { 'a': CAST(1 AS INT4) } >> AS t """.trimIndent(), expected = BagType( StructType( fields = mapOf( "a" to unionOf(INT4, INT8), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "unary plus on varying numeric types including missing -- this may return missing", query = """ SELECT +t.a AS a FROM << { 'a': CAST(1 AS INT8) }, { 'a': CAST(1 AS INT4) }, { } >> AS t """.trimIndent(), expected = BagType( StructType( fields = mapOf( "a" to unionOf(INT4, INT8, MISSING), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "unary plus on varying numeric types including string -- this may return missing", query = """ SELECT +t.a AS a FROM << { 'a': CAST(1 AS INT8) }, { 'a': CAST(1 AS INT4) }, { 'a': 'hello world!' } >> AS t """.trimIndent(), expected = BagType( StructType( fields = mapOf( "a" to unionOf(INT4, INT8, MISSING), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "binary plus on varying types -- this will return missing if one of the operands is not a number", query = """ SELECT t.a + t.b AS c FROM << { 'a': CAST(1 AS INT8), 'b': CAST(1.0 AS DECIMAL) }, { 'a': CAST(1 AS INT4), 'b': TRUE }, { 'a': 'hello world!!', 'b': DATE '2023-01-01' } >> AS t """.trimIndent(), expected = BagType( StructType( fields = mapOf( "c" to unionOf(MISSING, DECIMAL), ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), ErrorTestCase( name = """ unary plus on non-compatible type -- this cannot resolve to a dynamic call since no function will ever be invoked. """.trimIndent(), query = """ SELECT VALUE +t.a FROM << { 'a': 'hello world!' } >> AS t """.trimIndent(), expected = BagType(MISSING), problemHandler = assertProblemExists { Problem( sourceLocation = UNKNOWN_PROBLEM_LOCATION, details = PlanningProblemDetails.UnknownFunction( "pos", listOf(STRING) ) ) } ), ErrorTestCase( name = """ unary plus on non-compatible union type -- this cannot resolve to a dynamic call since no function will ever be invoked. """.trimIndent(), query = """ SELECT VALUE +t.a FROM << { 'a': 'hello world!' }, { 'a': <<>> } >> AS t """.trimIndent(), expected = BagType(MISSING), problemHandler = assertProblemExists { Problem( sourceLocation = UNKNOWN_PROBLEM_LOCATION, details = PlanningProblemDetails.UnknownFunction( "pos", listOf(unionOf(STRING, BAG)) ) ) } ), ErrorTestCase( name = """ unary plus on missing type -- this cannot resolve to a dynamic call since no function will ever be invoked. """.trimIndent(), query = """ SELECT VALUE +t.a FROM << { 'NOT_A': 1 } >> AS t """.trimIndent(), expected = BagType(MISSING), problemHandler = assertProblemExists { Problem( sourceLocation = UNKNOWN_PROBLEM_LOCATION, details = PlanningProblemDetails.UnknownFunction( "pos", listOf(MISSING) ) ) } ), ) @JvmStatic fun subqueryCases() = listOf( SuccessTestCase( name = "Subquery IN collection", catalog = "subqueries", key = PartiQLTest.Key("subquery", "subquery-00"), expected = BagType( StructType( fields = mapOf( "x" to INT4, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Subquery scalar coercion", catalog = "subqueries", key = PartiQLTest.Key("subquery", "subquery-01"), expected = BagType( StructType( fields = mapOf( "x" to INT4, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Subquery simple JOIN", catalog = "subqueries", key = PartiQLTest.Key("subquery", "subquery-02"), expected = BagType( StructType( fields = mapOf( "x" to INT4, "y" to INT4, "z" to INT4, "a" to INT4, "b" to INT4, "c" to INT4, ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Subquery scalar coercion", catalog = "subqueries", key = PartiQLTest.Key("subquery", "subquery-03"), expected = BOOL, ), ) } sealed class TestCase { fun toIgnored(reason: String) = when (this) { is IgnoredTestCase -> this else -> IgnoredTestCase(this, reason) } class SuccessTestCase( val name: String, val key: PartiQLTest.Key? = null, val query: String? = null, val catalog: String? = null, val catalogPath: List<String> = emptyList(), val expected: StaticType, val warnings: ProblemHandler? = null, ) : TestCase() { override fun toString(): String = "$name : $query" } class ErrorTestCase( val name: String, val key: PartiQLTest.Key? = null, val query: String? = null, val catalog: String? = null, val catalogPath: List<String> = emptyList(), val note: String? = null, val expected: StaticType? = null, val problemHandler: ProblemHandler? = null, ) : TestCase() { override fun toString(): String = "$name : $query" } class ThrowingExceptionTestCase( val name: String, val query: String, val catalog: String? = null, val catalogPath: List<String> = emptyList(), val note: String? = null, val expectedThrowable: KClass<out Throwable>, ) : TestCase() { override fun toString(): String { return "$name : $query" } } class IgnoredTestCase( val shouldBe: TestCase, reason: String, ) : TestCase() { override fun toString(): String = "Disabled - $shouldBe" } } class TestProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> { return parameters.map { Arguments.of(it) }.stream() } private val parameters = listOf( ErrorTestCase( name = "Pets should not be accessible #1", query = "SELECT * FROM pets", expected = BagType( unionOf( StructType( fields = emptyMap(), contentClosed = false, constraints = setOf( TupleConstraint.Open(true), TupleConstraint.UniqueAttrs(false), ) ), StructType( fields = mapOf( "_1" to StaticType.ANY ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), ) ), ) ), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("pets", false) ) } ), ErrorTestCase( name = "Pets should not be accessible #2", catalog = CATALOG_AWS, query = "SELECT * FROM pets", expected = BagType( unionOf( StructType( fields = emptyMap(), contentClosed = false, constraints = setOf( TupleConstraint.Open(true), TupleConstraint.UniqueAttrs(false), ) ), StructType( fields = mapOf( "_1" to StaticType.ANY ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), ) ), ) ), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("pets", false) ) } ), SuccessTestCase( name = "Project all explicitly", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM pets", expected = TABLE_AWS_DDB_PETS ), SuccessTestCase( name = "Project all implicitly", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT id, breed FROM pets", expected = TABLE_AWS_DDB_PETS ), SuccessTestCase( name = "Test #4", catalog = CATALOG_B, catalogPath = listOf("b"), query = "b", expected = TYPE_B_B_B ), SuccessTestCase( name = "Test #5", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM b", expected = TABLE_AWS_DDB_B ), SuccessTestCase( name = "Test #6", catalog = CATALOG_AWS, catalogPath = listOf("b"), query = "SELECT * FROM b", expected = TABLE_AWS_B_B ), ErrorTestCase( name = "Test #7", query = "SELECT * FROM ddb.pets", expected = BagType( unionOf( StructType( fields = emptyMap(), contentClosed = false, constraints = setOf( TupleConstraint.Open(true), TupleConstraint.UniqueAttrs(false), ) ), StructType( fields = mapOf( "_1" to StaticType.ANY ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), ) ), ) ), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("pets", false) ) } ), SuccessTestCase( name = "Test #10", catalog = CATALOG_B, query = "b.b", expected = TYPE_B_B_B ), SuccessTestCase( name = "Test #11", catalog = CATALOG_B, catalogPath = listOf("b"), query = "b.b", expected = TYPE_B_B_B ), SuccessTestCase( name = "Test #12", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM b.b", expected = TABLE_AWS_B_B ), SuccessTestCase( name = "Test #13", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM ddb.b", expected = TABLE_AWS_DDB_B ), SuccessTestCase( name = "Test #14", query = "SELECT * FROM aws.ddb.pets", expected = TABLE_AWS_DDB_PETS ), SuccessTestCase( name = "Test #15", catalog = CATALOG_AWS, query = "SELECT * FROM aws.b.b", expected = TABLE_AWS_B_B ), SuccessTestCase( name = "Test #16", catalog = CATALOG_B, query = "b.b.b", expected = TYPE_B_B_B ), SuccessTestCase( name = "Test #17", catalog = CATALOG_B, query = "b.b.c", expected = TYPE_B_B_C ), SuccessTestCase( name = "Test #18", catalog = CATALOG_B, catalogPath = listOf("b"), query = "b.b.b", expected = TYPE_B_B_B ), SuccessTestCase( name = "Test #19", query = "b.b.b.c", expected = TYPE_B_B_B_C ), SuccessTestCase( name = "Test #20", query = "b.b.b.b", expected = TYPE_B_B_B_B ), SuccessTestCase( name = "Test #21", catalog = CATALOG_B, query = "b.b.b.b", expected = TYPE_B_B_B_B ), SuccessTestCase( name = "Test #22", catalog = CATALOG_B, query = "b.b.b.c", expected = TYPE_B_B_C ), SuccessTestCase( name = "Test #23", catalog = CATALOG_B, catalogPath = listOf("b"), query = "b.b.b.b", expected = TYPE_B_B_B_B ), SuccessTestCase( name = "Test #24", query = "b.b.b.b.b", expected = TYPE_B_B_B_B_B ), SuccessTestCase( name = "Test #24", catalog = CATALOG_B, query = "b.b.b.b.b", expected = TYPE_B_B_B_B_B ), SuccessTestCase( name = "EQ", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id = 1", expected = TYPE_BOOL ), SuccessTestCase( name = "NEQ", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id <> 1", expected = TYPE_BOOL ), SuccessTestCase( name = "GEQ", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id >= 1", expected = TYPE_BOOL ), SuccessTestCase( name = "GT", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id > 1", expected = TYPE_BOOL ), SuccessTestCase( name = "LEQ", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id <= 1", expected = TYPE_BOOL ), SuccessTestCase( name = "LT", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id < 1", expected = TYPE_BOOL ), SuccessTestCase( name = "IN", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id IN (1, 2, 3)", expected = TYPE_BOOL ), ErrorTestCase( name = "IN Failure", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id IN 'hello'", expected = MISSING, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnknownFunction( "in_collection", listOf(INT4, STRING), ) ) } ), SuccessTestCase( name = "BETWEEN", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id BETWEEN 1 AND 2", expected = TYPE_BOOL ), ErrorTestCase( name = "BETWEEN Failure", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id BETWEEN 1 AND 'a'", expected = MISSING, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnknownFunction( "between", listOf( INT4, INT4, STRING ), ) ) } ), SuccessTestCase( name = "LIKE", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.ship_option LIKE '%ABC%'", expected = TYPE_BOOL ), ErrorTestCase( name = "LIKE Failure", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.ship_option LIKE 3", expected = MISSING, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnknownFunction( "like", listOf(STRING, INT4), ) ) } ), SuccessTestCase( name = "Case Insensitive success", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.CUSTOMER_ID = 1", expected = TYPE_BOOL ), // MISSING = 1 ErrorTestCase( name = "Case Sensitive failure", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.\"CUSTOMER_ID\" = 1", expected = NULL ), SuccessTestCase( name = "Case Sensitive success", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.\"customer_id\" = 1", expected = TYPE_BOOL ), SuccessTestCase( name = "1-Level Junction", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "(order_info.customer_id = 1) AND (order_info.marketplace_id = 2)", expected = StaticType.unionOf(BOOL, NULL) ), SuccessTestCase( name = "2-Level Junction", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "(order_info.customer_id = 1) AND (order_info.marketplace_id = 2) OR (order_info.customer_id = 3) AND (order_info.marketplace_id = 4)", expected = StaticType.unionOf(BOOL, NULL) ), SuccessTestCase( name = "INT and STR Comparison", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id = 'something'", expected = TYPE_BOOL, ), ErrorTestCase( name = "Nonexisting Comparison", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "non_existing_column = 1", // Function resolves to EQ__ANY_ANY__BOOL // Which can return BOOL Or NULL expected = StaticType.unionOf(BOOL, NULL), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("non_existing_column", false) ) } ), ErrorTestCase( name = "Bad comparison", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "order_info.customer_id = 1 AND 1", expected = MISSING, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnknownFunction( "and", listOf(StaticType.BOOL, INT4), ) ) } ), ErrorTestCase( name = "Bad comparison", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "1 AND order_info.customer_id = 1", expected = MISSING, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnknownFunction( "and", listOf(INT4, StaticType.BOOL), ) ) } ), ErrorTestCase( name = "Unknown column", catalog = CATALOG_DB, catalogPath = DB_SCHEMA_MARKETS, query = "SELECT unknown_col FROM orders WHERE customer_id = 1", expected = BagType( StructType( fields = mapOf("unknown_col" to AnyType()), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ), problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UndefinedVariable("unknown_col", false) ) } ), SuccessTestCase( name = "LIMIT INT", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM pets LIMIT 5", expected = TABLE_AWS_DDB_PETS ), ErrorTestCase( name = "LIMIT STR", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM pets LIMIT '5'", expected = TABLE_AWS_DDB_PETS, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnexpectedType(STRING, setOf(INT)) ) } ), SuccessTestCase( name = "OFFSET INT", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM pets LIMIT 1 OFFSET 5", expected = TABLE_AWS_DDB_PETS ), ErrorTestCase( name = "OFFSET STR", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT * FROM pets LIMIT 1 OFFSET '5'", expected = TABLE_AWS_DDB_PETS, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnexpectedType(STRING, setOf(INT)) ) } ), SuccessTestCase( name = "CAST", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT CAST(breed AS INT) AS cast_breed FROM pets", expected = BagType( StructType( fields = mapOf("cast_breed" to unionOf(INT, MISSING)), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "UPPER", catalog = CATALOG_AWS, catalogPath = listOf("ddb"), query = "SELECT UPPER(breed) AS upper_breed FROM pets", expected = BagType( StructType( fields = mapOf("upper_breed" to STRING), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Non-tuples", query = "SELECT a FROM << [ 1, 1.0 ] >> AS a", expected = BagType( StructType( fields = mapOf("a" to ListType(unionOf(INT4, StaticType.DECIMAL))), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Non-tuples in SELECT VALUE", query = "SELECT VALUE a FROM << [ 1, 1.0 ] >> AS a", expected = BagType(ListType(unionOf(INT4, StaticType.DECIMAL))) ), SuccessTestCase( name = "SELECT VALUE", query = "SELECT VALUE [1, 1.0] FROM <<>>", expected = BagType(ListType(unionOf(INT4, StaticType.DECIMAL))) ), SuccessTestCase( name = "Duplicate fields in struct", query = """ SELECT t.a AS a FROM << { 'a': 1, 'a': 'hello' } >> AS t """, expected = BagType( StructType( fields = listOf( StructType.Field("a", unionOf(INT4, STRING)) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Duplicate fields in ordered STRUCT. NOTE: b.b.d is an ordered struct with two attributes (e). First is INT4.", query = """ SELECT d.e AS e FROM << b.b.d >> AS d """, expected = BagType( StructType( fields = listOf( StructType.Field("e", INT4) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Duplicate fields in struct", query = """ SELECT a AS a FROM << { 'a': 1, 'a': 'hello' } >> AS t """, expected = BagType( StructType( fields = listOf( StructType.Field("a", unionOf(INT4, STRING)) ), contentClosed = true, constraints = setOf( TupleConstraint.Open(false), TupleConstraint.UniqueAttrs(true), TupleConstraint.Ordered ) ) ) ), SuccessTestCase( name = "Current User", query = "CURRENT_USER", expected = unionOf(STRING, NULL) ), SuccessTestCase( name = "Trim", query = "trim(' ')", expected = STRING ), SuccessTestCase( name = "Current User Concat", query = "CURRENT_USER || 'hello'", expected = unionOf(STRING, NULL) ), SuccessTestCase( name = "Current User Concat in WHERE", query = "SELECT VALUE a FROM [ 0 ] AS a WHERE CURRENT_USER = 'hello'", expected = BagType(INT4) ), SuccessTestCase( name = "TRIM_2", query = "trim(' ' FROM ' Hello, World! ')", expected = STRING ), SuccessTestCase( name = "TRIM_1", query = "trim(' Hello, World! ')", expected = STRING ), SuccessTestCase( name = "TRIM_3", query = "trim(LEADING ' ' FROM ' Hello, World! ')", expected = STRING ), ErrorTestCase( name = "TRIM_2_error", query = "trim(2 FROM ' Hello, World! ')", expected = MISSING, problemHandler = assertProblemExists { Problem( UNKNOWN_PROBLEM_LOCATION, PlanningProblemDetails.UnknownFunction( "trim_chars", args = listOf(STRING, INT4) ) ) } ), ) } private fun runTest(tc: TestCase) = when (tc) { is SuccessTestCase -> runTest(tc) is ErrorTestCase -> runTest(tc) is ThrowingExceptionTestCase -> runTest(tc) is TestCase.IgnoredTestCase -> runTest(tc) } @OptIn(ExperimentalPartiQLSchemaInferencer::class) private fun runTest(tc: ThrowingExceptionTestCase) { val session = PartiQLPlanner.Session( tc.query.hashCode().toString(), USER_ID, tc.catalog, tc.catalogPath, catalogConfig, Instant.now() ) val collector = ProblemCollector() val ctx = PartiQLSchemaInferencer.Context(session, PLUGINS, collector) val exception = assertThrows<Throwable> { PartiQLSchemaInferencer.infer(tc.query, ctx) Unit } val cause = exception.cause assertNotNull(cause) assertEquals(tc.expectedThrowable, cause::class) } @OptIn(ExperimentalPartiQLSchemaInferencer::class) private fun runTest(tc: SuccessTestCase) { val session = PartiQLPlanner.Session( tc.query.hashCode().toString(), USER_ID, tc.catalog, tc.catalogPath, catalogConfig, Instant.now() ) val collector = ProblemCollector() val ctx = PartiQLSchemaInferencer.Context(session, PLUGINS, collector) val hasQuery = tc.query != null val hasKey = tc.key != null if (hasQuery == hasKey) { error("Test must have one of either `query` or `key`") } val input = tc.query ?: testProvider[tc.key!!]!!.statement val result = PartiQLSchemaInferencer.inferInternal(input, ctx) assert(collector.problems.isEmpty()) { buildString { appendLine(collector.problems.toString()) appendLine() PlanPrinter.append(this, result.first) } } val actual = result.second assert(tc.expected == actual) { buildString { appendLine() appendLine("Expect: ${tc.expected}") appendLine("Actual: $actual") appendLine() PlanPrinter.append(this, result.first) } } } @OptIn(ExperimentalPartiQLSchemaInferencer::class) private fun runTest(tc: ErrorTestCase) { val session = PartiQLPlanner.Session( tc.query.hashCode().toString(), USER_ID, tc.catalog, tc.catalogPath, catalogConfig, Instant.now() ) val collector = ProblemCollector() val ctx = PartiQLSchemaInferencer.Context(session, PLUGINS, collector) val hasQuery = tc.query != null val hasKey = tc.key != null if (hasQuery == hasKey) { error("Test must have one of either `query` or `key`") } val input = tc.query ?: testProvider[tc.key!!]!!.statement val result = PartiQLSchemaInferencer.inferInternal(input, ctx) assert(collector.problems.isNotEmpty()) { buildString { appendLine("Expected to find problems, but none were found.") appendLine() PlanPrinter.append(this, result.first) } } if (tc.expected != null) { assert(tc.expected == result.second) { buildString { appendLine() appendLine("Expect: ${tc.expected}") appendLine("Actual: ${result.second}") appendLine() PlanPrinter.append(this, result.first) } } } assert(collector.problems.isNotEmpty()) { "Expected to find problems, but none were found." } tc.problemHandler?.handle(collector.problems, true) } private fun runTest(tc: TestCase.IgnoredTestCase) { assertThrows<AssertionError> { runTest(tc.shouldBe) } } fun interface ProblemHandler { fun handle(problems: List<Problem>, ignoreSourceLocation: Boolean) } }
280
null
60
526
ddd642dad2d02a8f550aa9247274c689c31c72c2
158,265
partiql-lang-kotlin
Apache License 2.0
src/test/kotlin/io/kotest/example/spring/GreetingControllerTest.kt
kotest
428,635,232
false
{"Kotlin": 2787}
package io.kotest.example.spring import com.ninjasquad.springmockk.MockkBean import io.kotest.core.spec.style.StringSpec import io.mockk.every import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.expectBody import reactor.core.publisher.Mono @SpringBootTest @AutoConfigureWebTestClient class GreetingControllerUnitTest( @MockkBean private val greetingService: GreetingService, private val webTestClient: WebTestClient ) : StringSpec({ "should return the greeting provided by greeting service" { val greeting = Greeting("Welcome someone") every { greetingService.greetingFor("someone") } returns Mono.just(greeting) webTestClient .get() .uri("/greet/someone") .exchange() .expectStatus().isOk .expectBody<Greeting>().isEqualTo(greeting) } "should return a default greeting when greeting service return error" { val defaultGreeting = Greeting("This is default greeting.") every { greetingService.greetingFor("someone") } returns Mono.error(RuntimeException("Boom Boom!")) webTestClient .get() .uri("/greet/someone") .exchange() .expectStatus().isOk .expectBody<Greeting>().isEqualTo(defaultGreeting) } })
6
Kotlin
4
8
d7ac3cf557b5605337782804c5a29309f3eb1a97
1,469
kotest-examples-spring-webflux
Apache License 2.0
datamodel/src/main/kotlin/de/westermann/robots/datamodel/IRobotServer.kt
pixix4
130,015,411
false
null
package de.westermann.robots.datamodel import de.westermann.robots.datamodel.util.Color import de.westermann.robots.datamodel.util.Coordinate import de.westermann.robots.datamodel.util.Energy import de.westermann.robots.datamodel.util.Version /** * @author lars */ interface IRobotServer { fun currentPosition(pos: Coordinate) fun currentColor(color: Color) fun foregroundColor(color: Color) fun backgroundColor(color: Color) fun energy(energy: Energy) fun version(version: Version) fun name(name: String) fun color(color: Color) fun availableColors(colors: List<Color>) }
0
Kotlin
0
0
383475939c2ba1bf95b458edf762e123b10e8509
615
Robots
Apache License 2.0
ui/src/main/java/com/github/abhrp/cryptograph/ui/chart/TimeSpanAdapter.kt
abhrp
154,935,698
false
null
package com.github.abhrp.cryptograph.ui.chart import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.github.abhrp.cryptograph.R import com.github.abhrp.cryptograph.ui.model.ChartPreferenceItem import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.time_span_item.* import javax.inject.Inject class TimeSpanAdapter @Inject constructor() : RecyclerView.Adapter<TimeSpanAdapter.ViewHolder>() { lateinit var list: List<ChartPreferenceItem> var chartOptionClickListener: ChartOptionClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.time_span_item, parent, false) return ViewHolder(itemView) } override fun getItemCount(): Int { return list.count() } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(list[position], position) } fun selectChartPreference(timeSpan: String) { for (item in list) { item.isSelected = item.timeSpan == timeSpan } notifyDataSetChanged() } inner class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun bind(chartPreferenceItem: ChartPreferenceItem, position: Int) { time_span_option.text = chartPreferenceItem.label time_span_option.background = if (chartPreferenceItem.isSelected) time_span_option.resources.getDrawable(R.drawable.option_selected_background, null) else time_span_option.resources.getDrawable(R.drawable.option_background, null) containerView.setOnClickListener { chartOptionClickListener?.onOptionClicked(list[position]) } } } }
1
null
1
1
1582562019efd270cb14b298caf3f1620d99548b
1,999
cryptograph
MIT License
library/src/main/java/com/magicjack/interceptor/internal/data/entity/HttpHeader.kt
skendora
236,436,933
false
null
package com.magicjack.interceptor.internal.data.entity internal data class HttpHeader(val name: String, val value: String)
0
Kotlin
0
0
a622777e44a38665d359c303fd35c209565a7a9a
124
Interceptor
Apache License 2.0
src/test/kotlin/wang/ralph/graphql/KtorGraphQLServerTest.kt
asnowwolf
424,872,944
false
{"Kotlin": 28591, "HTML": 3416}
package wang.ralph.graphql import com.expediagroup.graphql.generator.exceptions.TypeNotSupportedException import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import io.ktor.application.* import io.ktor.auth.* import io.ktor.features.* import io.ktor.http.* import io.ktor.jackson.* import io.ktor.routing.* import io.ktor.server.testing.* import wang.ralph.graphql.schema.LogQuery import wang.ralph.graphql.schema.UserMutation import wang.ralph.graphql.schema.UserQuery import java.text.SimpleDateFormat import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class KtorGraphQLServerTest { @Test fun fetchPlaygroundHtml() { withTestApplication({ routing { graphqlPlayground() } }) { handleRequest(HttpMethod.Get, "/playground").apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Text.Html, response.contentType().withoutParameters()) assertEquals(KtorGraphQLServerTest::class.java.getResourceAsStream("playground-expected.html")!! .reader(Charsets.UTF_8) .readText(), response.content) } } } @Test fun simpleQuery() { withTestApplication({ configureSerialization() configureGraphQL( packageNames = listOf("wang.ralph.graphql"), queries = listOf(UserQuery()), ) routing { graphql() } }) { sendGraphQLQuery("""{ | users { | id | name | groupId | } |}""" ).apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json, response.contentType().withoutParameters()) assertEquals("""{"data":{"users":[{"id":"11","name":"中文1","groupId":"1"},{"id":"12","name":"user2","groupId":"1"},{"id":"21","name":"中文2","groupId":"2"},{"id":"21","name":"user2","groupId":"2"},{"id":"31","name":"user3","groupId":"3"}]}}""", response.content) } } } @Test fun predefinedCustomDataType() { withTestApplication({ configureSerialization() configureGraphQL( packageNames = listOf("wang.ralph.graphql"), queries = listOf(LogQuery()), ) routing { graphql() } }) { sendGraphQLQuery("""{ | latestLog { | uuid | instant | date | calendar | bigDecimal | bigInteger | } |}""" ).apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json, response.contentType().withoutParameters()) assertEquals("""{"data":{"latestLog":{"uuid":"11111111-1111-1111-1111-111111111111","instant":"2000-01-01T00:00:00Z","date":"2000-01-01T00:00:00Z","calendar":"2000-01-01T00:00:00Z","bigDecimal":"1.0","bigInteger":"110181837737166161633331111111111"}}}""", response.content) } } } @Test fun missingCustomDataTypes() { assertFailsWith(TypeNotSupportedException::class) { withTestApplication({ configureSerialization() configureGraphQL( packageNames = listOf("wang.ralph.graphql"), queries = listOf(LogQuery()), scalars = emptyMap() ) routing { graphql() } }) { sendGraphQLQuery("""{ | latestLog { | id | time | } |}""" ) } } } @Test fun nestedQuery() { withTestApplication({ configureSerialization() configureGraphQL( packageNames = listOf("wang.ralph.graphql"), queries = listOf(UserQuery()), ) routing { graphql() } }) { sendGraphQLQuery("""{ | users { | id | name | group { | id | name | } | } |}""" ).apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json, response.contentType().withoutParameters()) assertEquals("""{"data":{"users":[{"id":"11","name":"中文1","group":{"id":"1","name":"group1"}},{"id":"12","name":"user2","group":{"id":"1","name":"group1"}},{"id":"21","name":"中文2","group":{"id":"2","name":"group2"}},{"id":"21","name":"user2","group":{"id":"2","name":"group2"}},{"id":"31","name":"user3","group":null}]}}""", response.content) } } } @Test fun queryByRequestHeader() { withTestApplication({ configureSerialization() configureGraphQL( packageNames = listOf("wang.ralph.graphql"), queries = listOf(UserQuery()), ) routing { graphql() } }) { sendGraphQLQuery( """{ | users { | id | name | token | } |}""", headers = headersOf("X-TOKEN", "SECRET") ).apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json, response.contentType().withoutParameters()) assertEquals("""{"data":{"users":[{"id":"11","name":"中文1","token":"SECRET"},{"id":"12","name":"user2","token":"SECRET"},{"id":"21","name":"中文2","token":"SECRET"},{"id":"21","name":"user2","token":"SECRET"},{"id":"31","name":"user3","token":"SECRET"}]}}""", response.content) } } } @Test fun mutation() { withTestApplication({ configureSerialization() configureGraphQL( packageNames = listOf("wang.ralph.graphql"), queries = listOf(UserQuery()), mutations = listOf(UserMutation()), ) routing { graphql() } }) { sendGraphQLQuery( query = """mutation(${'$'}user: UserInput!) { | createUser(user: ${'$'}user) { | id | } |}""".trimMargin(), variables = mapOf("user" to mapOf("name" to "user4")), ).apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json, response.contentType().withoutParameters()) assertEquals("""{"data":{"createUser":{"id":"9"}}}""", response.content) } } } @Test fun authorization() { withTestApplication({ configureSerialization() configureSecurity() configureGraphQL( packageNames = listOf("wang.ralph.graphql"), queries = listOf(UserQuery()), ) routing { // use optional to make /graphql authenticate("basic", optional = true) { graphql() } } }) { // sendGraphQLQuery( """{ | users { | id | name | groupId | } |}""", ).apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json, response.contentType().withoutParameters()) assertEquals("""{"data":{"users":[{"id":"11","name":"中文1","groupId":"1"},{"id":"12","name":"user2","groupId":"1"},{"id":"21","name":"中文2","groupId":"2"},{"id":"21","name":"user2","groupId":"2"},{"id":"31","name":"user3","groupId":"3"}]}}""", response.content) } sendGraphQLQuery( """{ | currentUser { | id | name | groupId | } |}""", ).apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json, response.contentType().withoutParameters()) assertEquals("""{"errors":[{"message":"Exception while fetching data (/currentUser) : null","locations":[{"line":2,"column":3}],"path":["currentUser"],"extensions":{"classification":"DataFetchingException"}}],"data":null}""", response.content) } } } } private fun Application.configureSerialization() { install(ContentNegotiation) { jackson { } } } private fun Application.configureSecurity() { authentication { basic(name = "basic") { validate { credentials -> UserIdPrincipal(credentials.name) } } } } val mapper = ObjectMapper() .registerModule(JavaTimeModule()) .setDateFormat(SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")) private fun TestApplicationRequest.setGraphQLQuery(query: String, variables: Map<String, Any>) { addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) setBody(mapper.writeValueAsString(GraphQLRequest(query = query.trimMargin(), variables = variables))) } fun TestApplicationEngine.sendGraphQLQuery( query: String, variables: Map<String, Any> = emptyMap(), headers: Headers = Headers.Empty, ) = handleRequest(HttpMethod.Post, "/graphql", setup = { setGraphQLQuery(query, variables) headers.forEach { name, values -> values.forEach { value -> addHeader(name, value) } } })
0
Kotlin
0
0
380fcdc3f83c7c2c4781d5abbba262a49870a2f0
10,778
ktor-graphql
MIT License
app/src/main/java/com/github/pockethub/android/ui/item/code/BlobItem.kt
selfimprW
126,365,704
true
{"Java": 837699, "Kotlin": 167352, "CSS": 10700, "JavaScript": 2333, "HTML": 540}
package com.github.pockethub.android.ui.item.code import android.content.Context import android.text.format.Formatter import com.github.pockethub.android.R import com.github.pockethub.android.core.code.FullTree import com.xwray.groupie.kotlinandroidextensions.Item import com.xwray.groupie.kotlinandroidextensions.ViewHolder import kotlinx.android.synthetic.main.blob_item.* class BlobItem( private val context: Context, val file: FullTree.Entry, private val indented: Boolean ) : Item(file.entry.sha()!!.hashCode().toLong()) { private val indentedPaddingLeft = context.resources.getDimensionPixelSize(R.dimen.blob_indentation) override fun getLayout() = R.layout.blob_item override fun bind(holder: ViewHolder, position: Int) { holder.tv_file.text = file.name holder.tv_size.text = Formatter.formatFileSize(context, file.entry.size()!!.toLong()) val paddingLeft = holder.root.paddingLeft val paddingRight = holder.root.paddingRight val paddingTop = holder.root.paddingTop val paddingBottom = holder.root.paddingBottom if (indented) { holder.root.setPadding(indentedPaddingLeft, paddingTop, paddingRight, paddingBottom) } else { holder.root.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom) } } }
0
Java
0
0
35ee2cc99a99b3d97fd3db5dcb1e68a8e09af227
1,367
PocketHub
Apache License 2.0
src/main/kotlin/com/mybar/bartender/dto/CocktailDto.kt
MimoJanra
772,243,278
false
{"Kotlin": 36134, "Java": 14785}
package com.mybar.bartender.dto import com.mybar.bartender.model.Bar import com.mybar.bartender.model.cocktails.Cocktail import java.math.BigDecimal data class CocktailDto( val name: String, val rating: BigDecimal, val imagePath: String?, val tags: List<String>, val ingredients: List<IngredientDto>, val inventoryItems: List<InventoryItemDto>, val recipeSteps: List<RecipeStepDto>, val barId : Long) { fun toEntity(bar: Bar): Cocktail { return Cocktail( name = this.name, rating = this.rating, imagePath = this.imagePath, bar = bar ) } }
3
Kotlin
0
1
3718c81f7e3265ce514d32a4c11f2e49cc3bcde6
608
bar-backend
Apache License 2.0
app/src/main/java/it/bosler/remotealarm/model/Alarms/AlarmDatabase.kt
maribox
736,473,741
false
{"Kotlin": 25495}
package it.bosler.remotealarm.model.Alarms import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters @Database( entities = [Alarm::class], version = 1 ) @TypeConverters(ScheduleConverter::class) abstract class AlarmDatabase: RoomDatabase() { abstract val dao: AlarmDAO }
0
Kotlin
0
0
cc4da14861653d1e4b8cd8c24cb30e9bdb70682e
326
RemoteAlarm
MIT License
client/app/src/main/java/edu/xww/urchat/data/preserver/ImagePreserver.kt
yanyu-xww
446,417,642
false
{"Kotlin": 96249, "Python": 30238, "Batchfile": 564}
package edu.xww.urchat.data.preserver import android.content.Context import android.graphics.Bitmap import android.os.Environment import android.util.Log import edu.xww.urchat.network.source.DataSource import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.concurrent.locks.ReentrantLock class ImagePreserver { /** * A reentrant lock. */ private val lock = ReentrantLock() /** * Create Image * @param context context * @param fileName file name * @param bitmap Image bitmap * @param force If file is existed force to replace */ fun createImage(context: Context, fileName: String, bitmap: Bitmap, force: Boolean) { synchronized(lock) { try { val picture : File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) if (picture != null && !picture.exists()) picture.mkdir() val imageFile = File("$picture/$fileName") if (imageFile.exists() && force) imageFile.delete() val fileOutputStream = FileOutputStream(imageFile) bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream) fileOutputStream.flush() fileOutputStream.close() } catch (e: IOException) { Log.d("DiskLoader/CreateImage", "/$fileName saving fail $e") } } } /** * Try to pull image from Server, will save to the disk. * Server File will replace the local. * @param context context * @param fileName file name */ fun pullImage(context: Context, fileName: String) { pullImages(context, arrayListOf(fileName)) } /** * Try to pull image from Server, will save to the disk. * Server File will replace the local. * @param context context * @param fileNames files */ fun pullImages(context: Context, fileNames: MutableList<String>) { val rt = DataSource.image(fileNames) for (i in rt) createImage(context, i.key, i.value, true) } }
0
Kotlin
0
0
0091cfd25a2ca953127e2f4f78f2166597a648ee
2,111
UrChat
Apache License 2.0
src/main/java/org/bubenheimer/android/preference/DurationPickerPreferenceDialogFragment.kt
bubenheimer
76,136,695
false
null
/* * Copyright (c) 2015-2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.bubenheimer.android.preference import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import androidx.preference.PreferenceDialogFragmentCompat import org.bubenheimer.android.util.databinding.PreferenceDialogDurationPickerBinding public class DurationPickerPreferenceDialogFragment : PreferenceDialogFragmentCompat() { public companion object { internal fun newInstance(key: String) = DurationPickerPreferenceDialogFragment().apply { arguments = bundleOf(ARG_KEY to key) } private const val SAVE_STATE_DURATION = "DurationPickerPreferenceDialogFragment.text" } private lateinit var binding: PreferenceDialogDurationPickerBinding private var value = 0 private val dialogValue: Int get() { val days = binding.pickerDays.value val hours = binding.pickerHours.value val minutes = binding.pickerMinutes.value return (days * 24 + hours) * 60 + minutes } private val durationPickerPreference: DurationPickerPreference get() = preference as DurationPickerPreference public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) value = savedInstanceState ?.getInt(SAVE_STATE_DURATION, DurationPickerPreference.DEFAULT_VALUE) ?: durationPickerPreference.value } public override fun onBindDialogView(view: View) { super.onBindDialogView(view) binding = PreferenceDialogDurationPickerBinding.bind(view) val daysPicker = binding.pickerDays daysPicker.minValue = 0 daysPicker.maxValue = 30 daysPicker.value = DurationPickerPreference.getDays(value) val hoursPicker = binding.pickerHours hoursPicker.minValue = 0 hoursPicker.maxValue = 23 hoursPicker.value = DurationPickerPreference.getHours(value) val minutesPicker = binding.pickerMinutes minutesPicker.minValue = 0 minutesPicker.maxValue = 59 minutesPicker.value = DurationPickerPreference.getMinutes(value) } public override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) { value = dialogValue val preference = durationPickerPreference if (preference.callChangeListener(value)) { preference.value = value } } } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(SAVE_STATE_DURATION, dialogValue) } }
0
Kotlin
0
0
f7f552d54015a4d8edaa4852588422e04e2e0308
3,226
androidutil
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Diploma.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.Diploma: ImageVector get() { if (_diploma != null) { return _diploma!! } _diploma = Builder(name = "Diploma", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(11.0f, 12.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, 2.0f) horizontalLineToRelative(-3.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f) close() moveTo(17.0f, 9.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, -1.0f) horizontalLineToRelative(-8.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f) horizontalLineToRelative(8.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, -1.0f) close() moveTo(8.0f, 6.0f) horizontalLineToRelative(8.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, -2.0f) horizontalLineToRelative(-8.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f) close() moveTo(20.0f, 19.444f) verticalLineToRelative(3.833f) arcToRelative(0.721f, 0.721f, 0.0f, false, true, -1.231f, 0.51f) lineToRelative(-0.769f, -0.768f) lineToRelative(-0.769f, 0.768f) arcToRelative(0.721f, 0.721f, 0.0f, false, true, -1.231f, -0.51f) verticalLineToRelative(-3.833f) arcToRelative(3.987f, 3.987f, 0.0f, false, true, 2.0f, -7.444f) arcToRelative(3.939f, 3.939f, 0.0f, false, true, 1.0f, 0.142f) verticalLineToRelative(-7.142f) arcToRelative(3.0f, 3.0f, 0.0f, false, false, -3.0f, -3.0f) horizontalLineToRelative(-8.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, false, -3.0f, 3.0f) verticalLineToRelative(12.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, false, 3.0f, 3.0f) horizontalLineToRelative(5.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, 2.0f) horizontalLineToRelative(-5.0f) arcToRelative(5.006f, 5.006f, 0.0f, false, true, -5.0f, -5.0f) verticalLineToRelative(-12.0f) arcToRelative(5.006f, 5.006f, 0.0f, false, true, 5.0f, -5.0f) horizontalLineToRelative(8.0f) arcToRelative(5.006f, 5.006f, 0.0f, false, true, 5.0f, 5.0f) verticalLineToRelative(8.382f) arcToRelative(3.95f, 3.95f, 0.0f, false, true, -1.0f, 6.062f) close() moveTo(20.0f, 16.0f) arcToRelative(2.0f, 2.0f, 0.0f, true, false, -2.0f, 2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, -2.0f) close() } } .build() return _diploma!! } private var _diploma: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,925
icons
MIT License
proj.android_studio/ee-x-core/src/main/java/com/ee/core/Logger.kt
centy
272,264,438
true
{"C++": 1146733, "Java": 813842, "Objective-C": 228466, "Kotlin": 41975, "Ruby": 25824, "Swift": 22742, "Makefile": 18306, "CMake": 11757, "Objective-C++": 9149, "Shell": 6499, "GLSL": 1123, "HTML": 398}
package com.ee.core import android.util.Log /** * Created by enrevol on 4/13/16. */ class Logger { private val _tag: String private var _logLevel = 0 constructor(tag: String) { _tag = tag setDebuggable(true) } constructor(tag: String, debuggable: Boolean) { _tag = tag setDebuggable(debuggable) } fun setDebuggable(debuggable: Boolean) { _logLevel = if (debuggable) { Log.VERBOSE } else { Log.INFO } } constructor(tag: String, logLevel: Int) { _tag = tag _logLevel = logLevel } fun error(message: String) { if (_logLevel <= Log.ERROR) { Log.e(_tag, message) } } fun error(message: String, th: Throwable) { if (_logLevel <= Log.ERROR) { Log.e(_tag, message, th) } } fun warn(message: String) { if (_logLevel <= Log.WARN) { Log.w(_tag, message) } } fun debug(message: String) { if (_logLevel <= Log.DEBUG) { Log.d(_tag, message) } } fun debug(format: String, vararg objects: Any?) { if (_logLevel <= Log.DEBUG) { Log.d(_tag, String.format(format, *objects)) } } fun info(message: String) { if (_logLevel <= Log.INFO) { Log.i(_tag, message) } } fun info(format: String, vararg objects: Any?) { if (_logLevel <= Log.INFO) { Log.i(_tag, String.format(format, *objects)) } } }
0
null
0
0
3ad312378fa600f2801a2031e17b3af6eea0b76a
1,573
ee-x
MIT License
app/src/main/java/com/sakura/anime/presentation/screen/history/HistoryScreen.kt
laqooss
871,490,049
false
{"Kotlin": 596746}
package com.sakura.anime.presentation.screen.history import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import coil.compose.AsyncImage import coil.request.ImageRequest import com.sakura.anime.R import com.sakura.anime.domain.model.History import com.sakura.anime.presentation.component.BackTopAppBar import com.sakura.anime.presentation.component.LoadingIndicator import com.sakura.anime.presentation.component.PopupMenuListItem import com.sakura.anime.presentation.component.SourceBadge import com.sakura.anime.presentation.component.StateHandler import com.sakura.anime.util.CROSSFADE_DURATION import com.sakura.anime.util.LOW_CONTENT_ALPHA import com.sakura.anime.util.SourceMode import com.sakura.anime.util.VIDEO_ASPECT_RATIO @Composable fun HistoryScreen( onBackClick: () -> Unit, onNavigateToAnimeDetail: (detailUrl: String, mode: SourceMode) -> Unit, onNavigateToVideoPlay: (episodeUrl: String, mode: SourceMode) -> Unit ) { val viewModel: HistoryViewModel = hiltViewModel() val historyListState by viewModel.historyList.collectAsState() StateHandler(state = historyListState, onLoading = { LoadingIndicator() }, onFailure = {} ) { resource -> resource.data?.let { histories -> Column( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background) .navigationBarsPadding() ) { BackTopAppBar( title = stringResource(id = R.string.play_history), onBackClick = onBackClick ) LazyColumn( verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.small_padding)) ) { items(histories) { history -> PopupMenuListItem( content = { HistoryItem( history = history, onPlayClick = { episodeUrl, mode -> viewModel.updateHistoryDate(history.detailUrl) onNavigateToVideoPlay(episodeUrl, mode) } ) }, menuText = stringResource(id = R.string.delete), onClick = { onNavigateToAnimeDetail(history.detailUrl, history.sourceMode) }, onMenuItemClick = { viewModel.deleteHistory(history.detailUrl) } ) } } } } } } @Composable fun HistoryItem( modifier: Modifier = Modifier, history: History, onPlayClick: (episodeUrl: String, mode: SourceMode) -> Unit, ) { Surface( modifier = modifier .fillMaxWidth() .height(dimensionResource(id = R.dimen.history_item_height)), ) { Row( modifier = Modifier.padding( horizontal = dimensionResource(id = R.dimen.small_padding), vertical = 4.dp ), horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.small_padding)) ) { SourceBadge( text = history.sourceMode.name, ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(history.imgUrl) .crossfade(CROSSFADE_DURATION) .build(), contentDescription = stringResource(id = R.string.lbl_anime_img), contentScale = ContentScale.Crop, modifier = Modifier .fillMaxHeight() .aspectRatio(VIDEO_ASPECT_RATIO) .clip(RoundedCornerShape(dimensionResource(id = R.dimen.history_cover_radius))) ) } Column( modifier = Modifier .fillMaxHeight(), verticalArrangement = Arrangement.SpaceBetween ) { Text( text = history.title, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.labelLarge, maxLines = 2, ) Column { Text( text = history.lastEpisodeName, color = MaterialTheme.colorScheme.onSurface.copy(alpha = LOW_CONTENT_ALPHA), style = MaterialTheme.typography.bodySmall, ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { val interactionSource = remember { MutableInteractionSource() } Text( text = stringResource(id = R.string.resume_play), color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.bodySmall, modifier = Modifier.clickable( interactionSource = interactionSource, indication = LocalIndication.current ) { onPlayClick(history.lastEpisodeUrl, history.sourceMode) } ) Text( text = history.time, color = MaterialTheme.colorScheme.onSurface.copy(alpha = LOW_CONTENT_ALPHA), style = MaterialTheme.typography.bodySmall, ) } } } } } } } } } }
0
Kotlin
0
0
a1f8ef588689c8d346196d43794bd9eda887a523
7,644
projects
Apache License 2.0
articles/2016-b014b49018b0dc6a8f9fc1fb.awesome.kts
KotlinBy
40,936,978
false
null
import link.kotlin.scripts.dsl.Article import link.kotlin.scripts.dsl.LinkType.* import link.kotlin.scripts.dsl.LanguageCodes.* import java.time.LocalDate // language=Markdown val body = """ In the [previous installment](http://beust.com/weblog/2016/05/27/neural-network-in-kotlin/), I introduced a mystery class `NeuralNetwork` which is capable of calculating different results depending on the data that you train it with. In this article, we’ll take a closer look at this neural network and crunch a few numbers. ## Neural networks overview A neural network is a graph of neurons made of successive layers. The graph is typically split in three parts: the leftmost column of neurons is called the “input layer”, the rightmost columns of neurons is the “output layer” and all the neurons in-between are the “hidden” layer. This hidden layer is the most important part of your graph since it’s responsible for making the calculations. There can be any numbers of hidden layers and any number of neurons in each of them (note that the Kotlin class I wrote for this series of articles only uses one hidden layer). Each edge that connects two neurons has a weight which is used to calculate the output of this neuron. The calculation is a simple addition of each input value multiplied by its weight. Let’s take a look at a quick example: ![](https://docs.google.com/drawings/d/1lnkGCoJ5DsJcXlqXnjmE0oGM6l1wHrf9pRuN-8ZU7Xc/pub?w=480&h=360) This network has two input values, one hidden layer of size two and one output. Our first calculation is therefore: ```kotlin w11-output = 2 * 0.1 + (-3) * (-0.2) = 0.8 w12-output = 2 * (-0.4) + (-3) * 0.3 = -1.7 ``` We’re not quite done: the actual outputs of neurons (also called “activations”) are typically passed to a normalization function first. To get a general intuition for this function, you can think of it as a way to constrain the outputs within the [-1, 1] range, which prevents the values flowing through the network from overflowing or underflowing. Also, it’s useful in practice for this function to have additional properties connected to its derivative but I’ll skip over this part for now. This function is called the “activation function” and the implementation I used in the `NeuralNetwork` class is the [hyperbolic tangent, `tanh`](http://mathworld.wolfram.com/HyperbolicTangent.html). In order to remain general, I’ll just refer to the activation function as `f()`. We therefore refine our first calculations as follows: ```kotlin w11-output = f(2 * 0.1 + (-3) * (-0.2)) w12-output = f(2 * (-0.4) + (-3) * 0.3) ``` There are a few additional details to this calculation in actual neural networks but I’ll skip those for now. Now that we have all our activations for the hidden layer, we are ready to move to the next layer, which happens to be the ouput layer, so we’re almost done: ```kotlin output = f(0.1 * w11-output - 0.2 * w12-output = 0.42 ``` As you can see, calculating the output of a neural network is fairly straightforward and fast, much faster than actually training that network. Once you have created your networks and you are satisfied with its results, you can just pass around the characteristics of that network (weights, sizes, ...) and any device (even phones) can then use that network. ## Revisiting the xor network Let’s go back to the `xor` network we created in the first episode. I created this network as follows: ```kotlin NeuralNetwork(inputSize = 2, hiddenSize = 2, outputSize = 1) ``` We only need two inputs (the two bits) and one output (the result of `a xor b`). These two values are fixed. What is not fixed is the size of the hidden layer, and I decided to pick 2 here, for no particular reason. It’s interesting to tweak these values and see whether your neural network performs better of worse based on these values and there is actually a great deal of both intuition and arbitrary choices that go into these decisions. These values that you use to configure your network before you run it are called “hyper parameters”, in contrast to the other values which get updated while your network runs (e.g. the weights). Let’s now take a look at the weights that our `xor` network came up with, which you can display by running the Kotlin application with <tt>--log 2</tt>: ```plain Input weights: -1.21 -3.36 -1.20 -3.34 1.12 1.67 Output weights: 3.31 -2.85 ``` Let’s put these values on the visual representation of our graph to get a better idea: ![](https://docs.google.com/drawings/d/1vzNDxpKkIP0h6pp8KglUn55a-pLE5PIAaO204ZNqYR0/pub?w=960&h=720) You will notice that the network above contains a neuron called “bias” that I haven’t introduced yet. And I’m not going to just yet besides saying that this bias helps the network avoid edge cases and learn more rapidly. For now, just accept it as an additional neuron whose output is not influenced by the previous layers. Let’s run the graph manually on the input (1,0), which should produce 1: ```kotlin hidden1-1 = 1 * -1.21 hidden1-2 = 0 * -1.20 bias1 = 1 * 1.12 output1 = tanh(-1.21 + 1.12) = -0.09 hidden2-1 = 1 * -3.36 hidden2-2 = 0 * -3.34 bias2 = 1 * 1.67 output2 = tanh(-3.36 + 1.6) = -0.94 // Now that we have the outputs of the hidden layer, we can caculate // our final result by combining them with the output weights: finalOutput = tanh(output1 * 3.31 + output2 * (-2.85)) = 0.98 ``` We have just verified that if we input `(0,1)` into the network, we’ll receive `0.98` in output. Feel free to calculate the other three inputs yourself or maybe just run the `NeuralNetwork` class with a log level of 2, which will show you all these calculations. ## Revisiting the parity network So the calculations hold up but it’s still a bit hard to understand where these weights come from and why they interact in the way they do. Elucidating this will be the topic of the next installment but before I wrap up this article, I’d like to take a quick look at the parity network because its content might look a bit more intuitive to the human eye, while the `xor` network detailed above still seems mysterious. If you train the parity network and you ask the `NeuralNetwotk` class to dump its output, here are the weights that you’ll get: ```plain Input weights: 0.36 -0.36 0.10 -0.09 0.30 -0.30 -2.23 -1.04 0.57 -0.58 Output weights: -1.65 -1.64 ``` If you pay attention, you will notice an interesting detail about these numbers: the weights of the first three neurons of our hidden layer cancel each other out while the two inputs of the fourth neuron reinforce each other. It’s pretty clear that the network has learned that when you are testing the parity of a number in binary format, the only bit that really matters is the least significant one (the last one). All the others can simply be ignored, so the network has learned from the training data that the best way to get close to the desired output is to only pay attention to that last bit and cancel all the other ones out so they don’t take part in the final result. ## Wrapping up This last result is quite remarkable if you think about it, because it really looks like the network learned how to test parity at the formal level (“The output of the network should be the value of the least significant bit, ignore all the others”), inferring that result just from the numeric data we trained it with. Understanding how the network learned how to modify itself to reach this level will be the topic of the next installment of the series. """ Article( title = "Neural Networks in Kotlin (part 2)", url = "http://beust.com/weblog/2016/05/30/neural-networks-in-kotlin-part-2/", categories = listOf( "Kotlin" ), type = article, lang = EN, author = "<NAME>", date = LocalDate.of(2016, 5, 30), body = body )
20
null
1127
9,869
38a336cb6953e0e7a1f0b511aee7902a3996fbb5
7,825
awesome-kotlin
Apache License 2.0
src/structural/adapter/Adapter.kt
daolq3012
96,442,903
false
null
package structural.adapter /** * Created by framgia on 06/07/2017. */ object Adapter { @JvmStatic fun main(args: Array<String>) { val audioPlayer = AudioPlayer() audioPlayer.play("mp3", "beyond_the_horizon.mp3") audioPlayer.play("mp4", "alone.mp4") audioPlayer.play("vlc", "far_far_away.vlc") audioPlayer.play("avi", "mind_me.avi") } }
0
Kotlin
1
5
9c0e6a5f20e8297bf10f32e92048ff8704bea43b
388
KotlinDesignPattern
Creative Commons Attribution 4.0 International
app/src/main/java/com/example/project3quizmaker/MainActivity.kt
zachbaker55
693,930,070
false
{"Kotlin": 8835}
package com.example.project3quizmaker import android.content.Intent import android.graphics.drawable.Drawable import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.ImageView import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView class MainActivity : AppCompatActivity() { /* initializes imageview to add picture */ lateinit var imageView: ImageView var display = 10 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) /* grabs imageview from xml file */ imageView=findViewById(R.id.imageview1) imageView.setImageResource(R.drawable.hated_math_1200x627) val write: TextView =findViewById(R.id.numQuestion) /* click listeners for toggling problem amount */ val clickDash: Button =findViewById(R.id.buttonDash) clickDash.setOnClickListener { if(display>1){ display-- write.text=display.toString(); } } /* adds bubbles to toggle difficulty */ val rgDifficulty: RadioGroup =findViewById(R.id.groupDifficulty) val rgOperation: RadioGroup =findViewById(R.id.groupOperation) val clickPlus: Button =findViewById(R.id.buttonPlus) clickPlus.setOnClickListener { if(display<99){ display++ write.text=display.toString(); } } /* switches page to start quiz */ val clickStart: Button =findViewById(R.id.buttonStart) clickStart.setOnClickListener { val selectedDifficultyId: Int = rgDifficulty.checkedRadioButtonId val selectedOperationId: Int = rgOperation.checkedRadioButtonId if (selectedDifficultyId != -1 && selectedOperationId != -1) { val difficultyButton: RadioButton = findViewById(selectedDifficultyId) val operationButton: RadioButton = findViewById(selectedOperationId) val difficulty: String = difficultyButton.text.toString() val operation: String = operationButton.text.toString() val intent = Intent(this, QuestionPage::class.java) intent.putExtra("operation", operation); intent.putExtra("difficulty", difficulty); intent.putExtra("totalProblems", display) intent.putExtra("correctAnswers", 0) intent.putExtra("wrongAnswers", 0) startActivity(intent) } } } }
0
Kotlin
0
0
9c0293126d7ca626d1de41a67a19fac7bd0dd097
2,787
Project3QuizMaker
Apache License 2.0
app/src/main/java/me/alex/pet/apps/zhishi/presentation/search/SearchFragment.kt
alex-petrakov
327,633,008
false
null
package me.alex.pet.apps.zhishi.presentation.search import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.ViewCompat import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.transition.AutoTransition import androidx.transition.TransitionManager import com.google.android.material.chip.Chip import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import me.alex.pet.apps.zhishi.R import me.alex.pet.apps.zhishi.databinding.FragmentSearchBinding import me.alex.pet.apps.zhishi.presentation.common.MaterialZAxisTransition import me.alex.pet.apps.zhishi.presentation.common.extensions.extendBottomPaddingWithSystemInsets import me.alex.pet.apps.zhishi.presentation.common.extensions.focusAndShowKeyboard import me.alex.pet.apps.zhishi.presentation.common.extensions.hideKeyboard import me.alex.pet.apps.zhishi.presentation.common.extensions.textChanges @AndroidEntryPoint class SearchFragment : Fragment() { private val viewModel by viewModels<SearchViewModel>() private var _binding: FragmentSearchBinding? = null private val binding get() = _binding!! private var lastRenderedState: ViewState? = null private val searchResultsAdapter by lazy { SearchResultsAdapter { ruleId -> viewModel.onClickRule(ruleId) } } private var firstStart = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MaterialZAxisTransition.setupOriginAndDestination(this) firstStart = savedInstanceState?.getBoolean(STATE_FIRST_START, true) ?: true } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSearchBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) prepareView() subscribeToModel() } @OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class) private fun prepareView() = with(binding) { recyclerView.apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { extendBottomPaddingWithSystemInsets() } setHasFixedSize(true) clipToPadding = false layoutManager = LinearLayoutManager(requireContext()) adapter = searchResultsAdapter addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { viewModel.onScrollResults() } } }) } toolbar.setNavigationOnClickListener { viewModel.onBackPressed() } queryEt.textChanges() .debounce(300) .onEach { viewModel.onUpdateQuery(it.toString()) } .launchIn(viewLifecycleOwner.lifecycleScope) if (firstStart) { queryEt.post { queryEt.focusAndShowKeyboard() } firstStart = false } } private fun subscribeToModel() = with(viewModel) { viewState.observe(viewLifecycleOwner) { newState -> render(newState) } viewEffect.observe(viewLifecycleOwner) { effect -> handle(effect) } } private fun render(state: ViewState) = with(binding) { if (lastRenderedState != null) { val autoTransition = AutoTransition().apply { duration = 150 removeTarget(R.id.suggestions_chip_group) } TransitionManager.beginDelayedTransition(contentFrame, autoTransition) } recyclerView.isVisible = state.searchResults.isVisible searchResultsAdapter.submitList(state.searchResults.items) emptyView.isVisible = state.emptyView.isVisible suggestionsView.isVisible = state.suggestionsView.isVisible if (state.suggestionsView != lastRenderedState?.suggestionsView) { val chips = inflateSuggestionChips(state.suggestionsView.suggestions) suggestionsChipGroup.removeAllViews() chips.forEach { suggestionsChipGroup.addView(it) } } lastRenderedState = state } private fun inflateSuggestionChips(suggestions: List<String>) = with(binding) { suggestions.map { suggestion -> val chip = layoutInflater.inflate( R.layout.view_suggestion_chip, suggestionsChipGroup, false ) as Chip chip.apply { text = suggestion id = ViewCompat.generateViewId() setOnClickListener { view -> val chipText = (view as Chip).text queryEt.setText(chipText) queryEt.setSelection(chipText.length) } } } } private fun handle(effect: ViewEffect) { when (effect) { ViewEffect.HIDE_KEYBOARD -> requireActivity().hideKeyboard() } } override fun onSaveInstanceState(outState: Bundle) { outState.putBoolean(STATE_FIRST_START, firstStart) } override fun onDestroyView() { _binding = null super.onDestroyView() } companion object { private const val STATE_FIRST_START = "FIRST_START" fun newInstance() = SearchFragment() } }
0
Kotlin
0
0
5613efb473d3f7830eac2e17f4649335603fb775
6,076
ZhiShi
MIT License
extended-persistence/src/test/kotlin/net/aquadc/persistence/extended/IncrementalTest.kt
Miha-x64
102,399,925
false
null
package net.aquadc.persistence.extended import net.aquadc.persistence.extended.inctemental.Incremental3 import net.aquadc.persistence.extended.inctemental.emptyIncremental import net.aquadc.persistence.extended.inctemental.mapFold import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertSame import org.junit.Test class IncrementalTest { @Test fun saturation() { var inc = emptyIncremental<Incremental3<String, String, String>>() assertNotEquals(inc, inc.saturatingFill().also { inc = it }) // ( ) + a => (a) assertNotEquals(inc, inc.saturatingFill().also { inc = it }) // (a ) + b => (a, b) assertNotEquals(inc, inc.saturatingFill().also { inc = it }) // (a, b) + c => (a, b, c) assertEquals(inc, inc.saturatingFill()) assertSame(inc, inc.saturatingFill()) } private fun Incremental3<String, String, String>.saturatingFill(): Incremental3<String, String, String> = mapFold( { next -> next("a") }, { _, next -> next("b") }, { _, _, next -> next("c") }, { _, _, _ -> this } ) }
11
Kotlin
10
118
d0a804271d0aaaa6368a2addce3ef7f081f5f560
1,135
Lychee
Apache License 2.0
src/main/kotlin/cc/mcyx/paimon/common/plugin/PaimonClassLoader.kt
xiaocheng168
693,567,613
false
{"Java": 49927, "Kotlin": 45331}
package cc.mcyx.paimon.common.plugin import cc.mcyx.paimon.common.PaimonPlugin import cc.mcyx.paimon.common.listener.PaimonAutoListener import cc.mcyx.paimon.common.minecraft.craftbukkit.registerListener import java.lang.reflect.Field import java.util.jar.JarFile open class PaimonClassLoader(val paimon: Paimon) { /** * 加载某个插件 */ open fun loadPlugin() { val jarFile = JarFile(PaimonPlugin.getPluginJarFile().file) //加载类 this.findJarAllClass(jarFile).forEach { loadClass(it) } //无法自动监听所有类 //反射获取插件所有加载列表 val declaredField: Field = Paimon::class.java.classLoader::class.java.getDeclaredField("classes") declaredField.isAccessible = true val classes = declaredField.get(paimon.cl) as Map<String, Class<*>> //获取当前插件主类包路径 val pluginPacket = Class.forName(paimon.description.main).`package`.name //获取插件加载类表 val paimonPluginClass = classes.filter { it.toString().contains(pluginPacket) } //遍历加载列表 paimonPluginClass.values.iterator().forEach { //如果这个类不是接口 if (!it.isInterface) { //判断这个类是否存在 PaimonListener if (it.interfaces.contains(PaimonAutoListener::class.java)) { //如果是Paimon插件 if (it.genericSuperclass == PaimonPlugin::class.java) { registerListener(paimon as PaimonAutoListener) } else registerListener(it.newInstance() as PaimonAutoListener) } } } } /** * 查找jar里的所有类 * @param jarFile jar文件 * @return 类列表 */ open fun findJarAllClass(jarFile: JarFile): MutableList<String> { val classesList = mutableListOf<String>() // STOPSHIP: 判断插件是否重复加载、开始对GUI框架进行编写 jarFile.entries().iterator().forEach { //必须是class文件 且不能是目录 if (!it.isDirectory && it.name.endsWith(".class") && !it.name.startsWith("META-INF")) { val classes = it.name.replace("/", ".").substring(0, it.name.length - 6) classesList.add(classes) } } return classesList } /** * 加载指定类库 * @param classes 加载类绝对路径 */ open fun loadClass(classes: String) { try { Class.forName(classes) paimon.cl.loadClass(classes) } catch (_: Error) { } catch (_: ClassNotFoundException) { } } }
1
Kotlin
0
0
4f7d9822213610986a3ef7e61590cac820b380f3
2,460
Paimon
MIT License
tracker-service/src/main/kotlin/at/ac/tuwien/dse/ss18/group05/dto/Dtos.kt
fuvidani
128,628,639
false
null
package at.ac.tuwien.dse.ss18.group05.dto import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document /** * <h4>About this class</h4> * * <p>Description</p> * * @author <NAME> * @version 1.0.0 * @since 1.0.0 */ data class Vehicle( @Id val identificationNumber: String, val manufacturerId: String, val model: String ) @Document(collection = "tracking_history") data class VehicleDataRecord( @Id val id: String?, val timestamp: Long, val metaData: MetaData, val sensorInformation: SensorInformation, val eventInformation: EventInformation ) data class MetaData( val identificationNumber: String, val model: String ) data class SensorInformation( val location: GpsLocation, val proximityInformation: ProximityInformation, val passengers: Int, val speed: Double ) data class GpsLocation(val lat: Double, val lon: Double) data class ProximityInformation( val distanceToVehicleFrontInCm: Double, val distanceToVehicleBehindInCm: Double ) enum class EventInformation { NEAR_CRASH, CRASH, NONE } data class ManufacturerDataRecord( val id: String?, val timestamp: Long, val vehicleIdentificationNumber: String, val model: String, val location: GpsLocation ) /** * Transforms this VehicleDataRecord into a ManufacturerDataRecord. * * @return a valid, immutable ManufacturerDataRecord */ fun VehicleDataRecord.toManufacturerDataRecord(): ManufacturerDataRecord { return ManufacturerDataRecord( this.id, this.timestamp, this.metaData.identificationNumber, this.metaData.model, this.sensorInformation.location ) }
0
null
2
2
21d0424a6a2f9ce230201a1f960619fdd14059c5
1,722
autonomous-vehicle-data-processing
MIT License
androidbasic/src/main/java/tech/bootloader/androidbasic/extensions/ActivityExtensions.kt
WingLuo
331,299,415
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 8, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 24, "XML": 34, "Java": 16}
package com.lingkj.basic.extensions import android.graphics.Color import android.os.Build import android.util.DisplayMetrics import android.view.View import android.view.WindowManager import androidx.fragment.app.FragmentActivity /** * 沉浸式状态栏 */ fun FragmentActivity.immerseStatusBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = Color.TRANSPARENT window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN } else { window.setFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS ) } } /** * 获取屏幕宽度 */ fun FragmentActivity.getScreenWidth(): Int { val dm = DisplayMetrics() windowManager.defaultDisplay.getMetrics(dm) return dm.widthPixels }
0
Kotlin
0
0
a4292b1820f7b1b1520d56b90cf5f75e16ffb46f
894
AROCQB
Apache License 2.0
app/src/main/java/com/droid47/petpot/base/extensions/LoggerExt.kt
AndroidKiran
247,345,176
false
null
package com.droid47.petpot.base.extensions import android.util.Log import com.droid47.petpot.BuildConfig import org.jetbrains.annotations.NonNls fun isDeveloperMode(): Boolean { return BuildConfig.DEBUG } fun logE(tag: String, msg: String, tr: Throwable) { if (!isDeveloperMode()) return Log.e(tag, msg, tr) } fun logE(@NonNls tag: String, @NonNls msg: String) { if (!isDeveloperMode()) return Log.e(tag, msg) } fun logW(tag: String, msg: String) { if (!isDeveloperMode()) return Log.w(tag, msg) } fun logD(@NonNls tag: String, @NonNls message: String) { if (!isDeveloperMode()) return Log.d(tag, message) } fun logD(@NonNls tag: String, @NonNls msg: String, tr: Throwable) { if (!isDeveloperMode()) return Log.d(tag, msg, tr) }
1
null
1
2
07d9c0c4f0d5bef32d9705f6bb49f938ecc456e3
780
PetPot
Apache License 2.0
gxpbaseeverything/src/main/java/com/peng/gxpbaseeverything/view/custom/view/UpCancelImageView.kt
mudcastles
257,197,366
false
{"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 54, "XML": 79, "Java": 25, "INI": 1}
package com.peng.gxpbaseeverything.view.custom.view import android.content.Context import android.util.AttributeSet import android.view.MotionEvent /** * 可以切换正在按压、将要松开、已经松开三种状态的ImageView * 常用于类似微信语音消息录音按钮(上滑取消发送、按压录音、抬起发送) */ class UpCancelImageView : androidx.appcompat.widget.AppCompatImageView { var mEventListener: OnEventListener? = null private var mCurrStatus = Status.STOP_RECORD private var mLocation = intArrayOf(0, 0) constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } override fun onTouchEvent(event: MotionEvent): Boolean { getLocationOnScreen(mLocation) when (event.action) { MotionEvent.ACTION_DOWN -> { parent.requestDisallowInterceptTouchEvent(true) mCurrStatus = Status.RECORDING mEventListener?.onStartRecordVoice() mEventListener?.onStatusChanged(mCurrStatus) return true } MotionEvent.ACTION_MOVE -> { val isOutBound = isOutBound(event.rawX, event.rawY) if (isOutBound && mCurrStatus != Status.WILL_CANCEL) { mCurrStatus = Status.WILL_CANCEL mEventListener?.onStatusChanged(mCurrStatus) } else if (!isOutBound && mCurrStatus != Status.RECORDING) { mCurrStatus = Status.RECORDING mEventListener?.onStatusChanged(mCurrStatus) } return true } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { mCurrStatus = Status.STOP_RECORD mEventListener?.onStatusChanged(mCurrStatus) if (isOutBound(event.rawX, event.rawY)) { mEventListener?.onCancel() } else { mEventListener?.onEndRecordVoice() } parent.requestDisallowInterceptTouchEvent(false) return true } } return super.onTouchEvent(event) } internal fun isOutBound(x: Float, y: Float): Boolean { return x < mLocation[0] || x > mLocation[0] + measuredWidth || y < mLocation[1] || y > mLocation[1] + measuredHeight } interface OnEventListener { fun onCancel() fun onStartRecordVoice() fun onEndRecordVoice() fun onStatusChanged(newStatus: Status) } enum class Status { RECORDING, WILL_CANCEL, STOP_RECORD } }
0
Kotlin
1
1
93de9d030a6c1bc9d4815790cf9e31be538176c0
2,940
GXP-BaseEverything
Apache License 2.0
library/src/main/java/org/akop/ararat/view/inputmethod/CrosswordInputConnection.kt
0xe1f
59,173,682
false
{"Kotlin": 342157}
// Copyright (c) <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package org.akop.ararat.view.inputmethod import android.view.View import android.view.inputmethod.BaseInputConnection class CrosswordInputConnection(targetView: View) : BaseInputConnection(targetView, false) { var onInputEventListener: OnInputEventListener? = null interface OnInputEventListener { fun onWordEntered(text: CharSequence) fun onWordCancelled() fun onEditorAction(actionCode: Int) } override fun commitText(text: CharSequence, newCursorPosition: Int): Boolean { if (text.isEmpty()) onInputEventListener?.onWordCancelled() return super.commitText(text, newCursorPosition) } override fun performEditorAction(actionCode: Int): Boolean { onInputEventListener?.onEditorAction(actionCode) return super.performEditorAction(actionCode) } override fun setComposingText(text: CharSequence, newCursorPosition: Int): Boolean { onInputEventListener?.onWordEntered(text) return super.setComposingText(text, newCursorPosition) } }
41
Kotlin
3
30
4e8084f5cd3fe2c1fdf30a9eca7d5860835b842d
2,145
ararat
MIT License
src/org/elixir_lang/beam/chunk/debug_info/v1/erl_abstract_code/abstract_code_compiler_options/abstract_code/MapField.kt
KronicDeth
22,329,177
false
{"Kotlin": 2461440, "Elixir": 2165417, "Java": 1582388, "Euphoria": 151683, "Lex": 69822, "HTML": 22466, "Makefile": 499}
package org.elixir_lang.beam.chunk.debug_info.v1.erl_abstract_code.abstract_code_compiler_options.abstract_code import com.ericsson.otp.erlang.OtpErlangObject import com.ericsson.otp.erlang.OtpErlangTuple import org.elixir_lang.beam.chunk.debug_info.v1.erl_abstract_code.abstract_code_compiler_options.AbstractCode import org.elixir_lang.beam.chunk.debug_info.v1.erl_abstract_code.abstract_code_compiler_options.AbstractCode.ifTag object MapField { fun ifToMacroStringDeclaredScope(term: OtpErlangObject, scope: Scope): MacroStringDeclaredScope? = ifTag(term, TAG_SET) { toMacroStringDeclaredScope(it, scope) } private val TAG_SET = setOf("map_field_assoc", "map_field_exact") private fun keyMacroStringDeclaredScope(mapFieldAssociation: OtpErlangTuple, scope: Scope) = toKey(mapFieldAssociation) ?.let { AbstractCode.toMacroStringDeclaredScope(it, scope) } ?: MacroStringDeclaredScope.missing("key", "map field key", mapFieldAssociation) private fun toKey(mapFieldAssociation: OtpErlangTuple): OtpErlangObject? = mapFieldAssociation.elementAt(2) private fun toMacroStringDeclaredScope( mapFieldAssociation: OtpErlangTuple, scope: Scope ): MacroStringDeclaredScope { val (keyMacroString, keyDeclaredScope) = keyMacroStringDeclaredScope(mapFieldAssociation, scope) val (valueMacroString, valueDeclaredScope) = valueMacroStringDeclaredScope(mapFieldAssociation, scope) return MacroStringDeclaredScope( "${keyMacroString.group().string} => ${valueMacroString.group().string}", doBlock = false, keyDeclaredScope.union(valueDeclaredScope) ) } private fun toValue(mapFieldAssociation: OtpErlangTuple): OtpErlangObject? = mapFieldAssociation.elementAt(3) private fun valueMacroStringDeclaredScope(mapFieldAssociation: OtpErlangTuple, scope: Scope) = toValue(mapFieldAssociation) ?.let { AbstractCode.toMacroStringDeclaredScope(it, scope) } ?: MacroStringDeclaredScope.missing("value", "map field value", mapFieldAssociation) }
590
Kotlin
153
1,815
b698fdaec0ead565023bf4461d48734de135b604
2,186
intellij-elixir
Apache License 2.0
src/org/elixir_lang/beam/chunk/debug_info/v1/erl_abstract_code/abstract_code_compiler_options/abstract_code/MapField.kt
KronicDeth
22,329,177
false
{"Kotlin": 2461440, "Elixir": 2165417, "Java": 1582388, "Euphoria": 151683, "Lex": 69822, "HTML": 22466, "Makefile": 499}
package org.elixir_lang.beam.chunk.debug_info.v1.erl_abstract_code.abstract_code_compiler_options.abstract_code import com.ericsson.otp.erlang.OtpErlangObject import com.ericsson.otp.erlang.OtpErlangTuple import org.elixir_lang.beam.chunk.debug_info.v1.erl_abstract_code.abstract_code_compiler_options.AbstractCode import org.elixir_lang.beam.chunk.debug_info.v1.erl_abstract_code.abstract_code_compiler_options.AbstractCode.ifTag object MapField { fun ifToMacroStringDeclaredScope(term: OtpErlangObject, scope: Scope): MacroStringDeclaredScope? = ifTag(term, TAG_SET) { toMacroStringDeclaredScope(it, scope) } private val TAG_SET = setOf("map_field_assoc", "map_field_exact") private fun keyMacroStringDeclaredScope(mapFieldAssociation: OtpErlangTuple, scope: Scope) = toKey(mapFieldAssociation) ?.let { AbstractCode.toMacroStringDeclaredScope(it, scope) } ?: MacroStringDeclaredScope.missing("key", "map field key", mapFieldAssociation) private fun toKey(mapFieldAssociation: OtpErlangTuple): OtpErlangObject? = mapFieldAssociation.elementAt(2) private fun toMacroStringDeclaredScope( mapFieldAssociation: OtpErlangTuple, scope: Scope ): MacroStringDeclaredScope { val (keyMacroString, keyDeclaredScope) = keyMacroStringDeclaredScope(mapFieldAssociation, scope) val (valueMacroString, valueDeclaredScope) = valueMacroStringDeclaredScope(mapFieldAssociation, scope) return MacroStringDeclaredScope( "${keyMacroString.group().string} => ${valueMacroString.group().string}", doBlock = false, keyDeclaredScope.union(valueDeclaredScope) ) } private fun toValue(mapFieldAssociation: OtpErlangTuple): OtpErlangObject? = mapFieldAssociation.elementAt(3) private fun valueMacroStringDeclaredScope(mapFieldAssociation: OtpErlangTuple, scope: Scope) = toValue(mapFieldAssociation) ?.let { AbstractCode.toMacroStringDeclaredScope(it, scope) } ?: MacroStringDeclaredScope.missing("value", "map field value", mapFieldAssociation) }
590
Kotlin
153
1,815
b698fdaec0ead565023bf4461d48734de135b604
2,186
intellij-elixir
Apache License 2.0
screensadaptermvp/src/main/java/com/e16din/screensadapter/mvp/MvpScreensAdapterApplication.kt
e16din
150,167,755
false
null
package com.e16din.screensadapter.mvp /** * To get ScreensAdapter from application. */ interface MvpScreensAdapterApplication { val screensAdapter: MvpScreensAdapter<*, *> }
0
Kotlin
0
0
f427ee19faf6929cd0e51ea6850d75fe8c8f5aee
181
ScreensAdapter
Apache License 2.0
android/app-example/src/main/java/com/badoo/ribs/example/rib/foo_bar/FooBarNode.kt
journeyman
205,386,527
true
{"Kotlin": 593038, "Swift": 402146, "Java": 112878, "Shell": 2571, "Ruby": 1955, "Objective-C": 814}
package com.badoo.ribs.example.rib.foo_bar import android.os.Bundle import android.view.ViewGroup import com.badoo.ribs.core.Node class FooBarNode( viewFactory: ((ViewGroup) -> FooBarView?)?, private val router: FooBarRouter, interactor: FooBarInteractor, savedInstanceState: Bundle? ) : Node<FooBarView>( savedInstanceState = savedInstanceState, identifier = object : FooBar {}, viewFactory = viewFactory, router = router, interactor = interactor ), FooBar.Workflow { }
0
Kotlin
0
0
6c4ae253ab1f052fd25b45f041744655041899fc
510
RIBs
Apache License 2.0
app/src/main/java/com/funny/app/gif/memes/function/store/Store.kt
yibulaxi
616,417,403
false
{"Java": 1087519, "Kotlin": 361539}
package com.funny.app.gif.memes.function.store import com.xm.lib.datastroe.DataStore object Store { fun saveToken(token: String) { DataStore.putString(CacheKey.TOKEN, token) } fun getToken(): String = DataStore.getString(CacheKey.TOKEN) fun saveUserId(userId: Int) { DataStore.putInt(CacheKey.USER_ID, userId) } fun savePhone(token: String) { DataStore.putString(CacheKey.PHONE, token) } fun getPhone(): String = DataStore.getString(CacheKey.PHONE) fun getUserId(): Int = DataStore.getInt(CacheKey.USER_ID) fun saveVersion(version: Int) { DataStore.putInt("version", version) } fun getVersion(): Int = DataStore.getInt("version", Version.INTERNAL) }
1
null
1
1
16c57fc7e91d945966c0876e404f33e75a89c8e9
739
GifSearch
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/kt-55071-compileSharedNative-withDefaultParameters/producer/src/secondCommonMain/kotlin/producer/SecondCommonMain.kt
JetBrains
3,432,266
false
null
package producer internal fun producerSecondCommonMain() = Unit
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
64
kotlin
Apache License 2.0
idea/testData/codeInsight/postfix/arg.kt
damenez
176,209,431
true
{"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1}
fun foo(s: String) { s.arg<caret> }
0
Kotlin
0
2
9a2178d96bd736c67ba914b0f595e42d1bba374d
39
kotlin
Apache License 2.0
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/runners/ArgumentsService.kt
acidburn0zzz
100,211,796
true
{"Kotlin": 101666, "Java": 39111, "CSS": 32}
package jetbrains.buildServer.runners interface ArgumentsService { fun parseToStrings(text: String): Sequence<String> }
1
Kotlin
0
1
46b0a257053bcaeba760efb2ec8c823364bc9377
124
teamcity-dotnet-plugin
Apache License 2.0
src/main/kotlin/com/github/mkulak/kortx/Test.kt
mkulak
96,014,573
false
null
package com.github.mkulak.kortx import io.vertx.core.MultiMap import io.vertx.core.buffer.Buffer import io.vertx.core.http.CaseInsensitiveHeaders import io.vertx.core.http.HttpVersion import io.vertx.core.json.* import io.vertx.ext.web.client.HttpResponse import io.vertx.ext.web.codec.impl.BodyCodecImpl fun mockHttpClient(handler: (HttpRequest) -> HttpResponse<Buffer>) = MockHttpClient(handler) class MockHttpClient(val handler: (HttpRequest) -> HttpResponse<Buffer>) : HttpClient { override fun execute(req: HttpRequest): Future<HttpResponse<Buffer>> { val res = Future<HttpResponse<Buffer>>() res.complete(handler(req)) return res } } fun Any.toJsonResponse(): HttpResponse<Buffer> = MockHttpResponse(200, Buffer.buffer(Json.mapper.writeValueAsString(this))) class MockHttpResponse( val statusCode: Int, val body: Buffer, val statusMessage: String = "", val headers: Map<String, String> = emptyMap() ) : HttpResponse<Buffer> { override fun statusCode(): Int = statusCode override fun bodyAsString(): String = body.toString() override fun bodyAsString(encoding: String): String = body.toString(encoding) override fun bodyAsBuffer(): Buffer = body override fun cookies(): MutableList<String> = ArrayList<String>() override fun version(): HttpVersion = HttpVersion.HTTP_2 override fun trailers(): MultiMap = CaseInsensitiveHeaders() override fun bodyAsJsonArray(): JsonArray = BodyCodecImpl.JSON_ARRAY_DECODER.apply(body) override fun getHeader(headerName: String): String? = headers[headerName] override fun body(): Buffer = body override fun headers(): MultiMap = headers.toMultiMap() override fun statusMessage(): String = statusMessage override fun getTrailer(trailerName: String): String = "" override fun <R> bodyAsJson(type: Class<R>): R = body.asJson<R>(type) override fun bodyAsJsonObject(): JsonObject = body.asJsonObj } class MockTokenInfoProvider : TokenInfoProvider { override fun hasScopes(token: String, scopes: List<String>) = true }
0
Kotlin
0
1
ed0f00995d57c10d157733c0906b2693f44d280e
2,107
kortx
MIT License
sms-core/src/main/kotlin/team/msg/sms/domain/authentication/service/CommandAuthenticationFormService.kt
GSM-MSG
625,717,097
false
{"Kotlin": 529822, "Shell": 1480, "Dockerfile": 288}
package team.msg.sms.domain.authentication.service import team.msg.sms.domain.authentication.model.AuthenticationForm interface CommandAuthenticationFormService { fun save(authenticationForm: AuthenticationForm): AuthenticationForm }
7
Kotlin
0
9
871482bf7f1895f160fe6b6d2b99ff712ae4cd63
239
SMS-BackEnd
MIT License
app/src/main/java/gq/kirmanak/mealient/data/baseurl/VersionDataSource.kt
kirmanak
431,195,533
false
null
package gq.kirmanak.mealient.data.baseurl interface VersionDataSource { suspend fun getVersionInfo(): VersionInfo }
6
Kotlin
1
36
6c759f486b4cd563458f39b1fb7b4e940223d239
121
Mealient
MIT License
src/main/kotlin/net/codetreats/sevdesk/types/CommunicationWay.kt
codetreats
701,844,391
false
{"Kotlin": 23314}
package net.codetreats.sevdesk.types import com.squareup.moshi.* import java.lang.IllegalArgumentException import java.time.LocalDateTime data class CommunicationWay( val id: String, val create: LocalDateTime, val update: LocalDateTime, val contact: ContactObject, val type: CommunicationWayType, val value: String, val key: CommunicationWayKeyObject, val main: Int ) enum class CommunicationWayType { EMAIL, PHONE, WEB, MOBILE } enum class CommunicationWayKey(val value: Int) { PRIVATE(1), WORK(2), FAX(3), MOBILE(4), EMPTY(5), AUTOBOX(6), NEWSLETTER(7), INVOICING(8); companion object { fun from(value: Int) : CommunicationWayKey = CommunicationWayKey.entries.firstOrNull { it.value == value} ?: throw IllegalArgumentException("Invalid CommunicationWayKey '$value") } } class CommunicationWayTypeAdapter: JsonAdapter<CommunicationWayType>() { @FromJson override fun fromJson(reader: JsonReader): CommunicationWayType? = if (reader.peek() != JsonReader.Token.NULL) { CommunicationWayType.valueOf(reader.nextString()) } else { reader.nextNull() } @ToJson override fun toJson(writer: JsonWriter, value: CommunicationWayType?) { writer.value(value?.toString()) } } class CommunicationWayKeyAdapter: JsonAdapter<CommunicationWayKey>() { @FromJson override fun fromJson(reader: JsonReader): CommunicationWayKey? = if (reader.peek() != JsonReader.Token.NULL) { CommunicationWayKey.from(reader.nextInt()) } else { reader.nextNull() } @ToJson override fun toJson(writer: JsonWriter, value: CommunicationWayKey?) { writer.value(value?.value) } }
0
Kotlin
0
0
fb1eaa7661f7237824f36fc0d6720a0a0db83074
1,750
sevdesk-kotlin
MIT License
src/main/kotlin/visibilitymodifiers/package1/OtherClass.kt
thunderbiscuit
315,366,412
false
null
package visibilitymodifiers.package1 // if we try to import a private declaration from another file, we get an error // Cannot access 'privateCallPokemon': it is private in file // import visibilitymodifiers.package1.privateCallPokemon fun main() { // the calls below refer to elements within the package that are public // they do not require imports println(pokemonName) callPokemon("Bulba") val bulbasmooth: Pokemon = Pokemon("Bulbasaur", 1) println(bulbasmooth.name) bulbasmooth.gainXP(20) println(bulbasmooth.xp) // private variables, functions, and classes cannot be imported and therefore accessed // println(privatePokemonName) // Cannot access 'privatePokemonName': it is private in file // privateCallPokemon("Ivysaur") // Cannot access 'privateCallPokemon': it is private in file // val ivysmooth: PrivatePokemon = PrivatePokemon("Ivysmooth", 1) // Cannot access 'PrivatePokemon': it is private in file // println(ivysmooth.name) // note that the gainXP function in PrivatePokemon is public, but because the class is private we cannot access it // ivysmooth.gainXP(20) // println(ivysmooth.xp) // the following declarations have their visibility set as internal // they are from the same package and therefore do not need to be imported println(internalPokemonName) internalCallPokemon("Venusaur") val venusmooth: InternalPokemon = InternalPokemon("Venusmooth", 1) println(venusmooth.name) venusmooth.gainXP(20) println(venusmooth.xp) }
9
Kotlin
0
2
d1cfd85785e096fa904d90c732253f7b932b0282
1,552
kotlin-study
Apache License 2.0
app/src/androidTest/java/com/app/instrumentationtestexample/login/LoginActivityTest.kt
Magno-Ramos
236,069,496
false
null
package com.app.instrumentationtestexample.login import android.app.Activity import android.app.Instrumentation import android.view.View import android.widget.EditText import android.widget.ProgressBar import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.intent.Intents.intended import androidx.test.espresso.intent.Intents.intending import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent import androidx.test.espresso.intent.rule.IntentsTestRule import androidx.test.espresso.matcher.BoundedMatcher import androidx.test.espresso.matcher.ViewMatchers.* import com.app.instrumentationtestexample.R import com.app.instrumentationtestexample.Utils import com.app.instrumentationtestexample.main.MainActivity import org.hamcrest.Description import org.hamcrest.Matchers.not import org.junit.Rule import org.junit.Test class LoginActivityTest { @get:Rule val rule = IntentsTestRule(LoginActivity::class.java, false, true) private val edtEmail = withId(R.id.edt_email) private val edtPassword = withId(R.id.edt_password) private val btnLogin = withId(R.id.btn_login) private val progressBar = withId(R.id.progress_bar) @Test fun whenActivityIsLaunched_shouldDisplayInitialState() { onView(edtEmail).check(matches(isDisplayed())) onView(edtPassword).check(matches(isDisplayed())) onView(edtPassword).check(matches(isDisplayed())) onView(progressBar).check(matches(not(isDisplayed()))) } @Test fun whenEmailIsEmpty_andClickLoginButton_shouldSetEditTextErrorAndRequestFocus() { onView(btnLogin).perform(click()) onView(edtEmail).check(matches(hasErrorText())) onView(edtEmail).check(matches(hasErrorText())) onView(edtEmail).check(matches(hasFocus())) } @Test fun whenPasswordIsEmpty_andClickLoginButton_shouldSetPasswordErrorAndRequestFocus() { onView(edtEmail).perform(typeText("<EMAIL>"), closeSoftKeyboard()) onView(btnLogin).perform(click()) onView(edtPassword).check(matches(hasErrorText())) onView(edtPassword).check(matches(hasFocus())) } @Test fun whenEmailAndPasswordIsNotEmpty_andClickLoginButton_shouldDisableLoginButton() { onView(isAssignableFrom(ProgressBar::class.java)).perform(Utils.replaceProgressBarDrawable()) onView(edtEmail).perform(typeText("<EMAIL>"), closeSoftKeyboard()) onView(edtPassword).perform(typeText("<PASSWORD>"), closeSoftKeyboard()) // don't open main activity val matcher = hasComponent(MainActivity::class.java.name) val result = Instrumentation.ActivityResult(Activity.RESULT_OK, null) intending(matcher).respondWith(result) onView(btnLogin).perform(click()).check(matches(not(isEnabled()))) intended(matcher) } @Test fun whenEmailAndPasswordIsNotEmpty_andClickLoginButton_shouldDisplayProgressBar() { onView(isAssignableFrom(ProgressBar::class.java)).perform(Utils.replaceProgressBarDrawable()) onView(edtEmail).perform(typeText("<EMAIL>"), closeSoftKeyboard()) onView(edtPassword).perform(typeText("<PASSWORD>"), closeSoftKeyboard()) // don't open main activity val matcher = hasComponent(MainActivity::class.java.name) val result = Instrumentation.ActivityResult(Activity.RESULT_OK, null) intending(matcher).respondWith(result) onView(btnLogin).perform(click()) onView(progressBar).check(matches(isDisplayed())) intended(matcher) } @Test fun whenBothFieldsAreFilled_andClickLoginButton_shouldOpenMainActivity() { onView(isAssignableFrom(ProgressBar::class.java)).perform(Utils.replaceProgressBarDrawable()) onView(edtEmail).perform(typeText("<EMAIL>"), closeSoftKeyboard()) onView(edtPassword).perform(typeText("<PASSWORD>"), closeSoftKeyboard()) // don't open main activity val matcher = hasComponent(MainActivity::class.java.name) val result = Instrumentation.ActivityResult(Activity.RESULT_OK, null) intending(matcher).respondWith(result) onView(btnLogin).perform(click()) intended(matcher) } private fun hasErrorText(): BoundedMatcher<View, EditText> { return object : BoundedMatcher<View, EditText>(EditText::class.java) { override fun describeTo(description: Description?) { description?.appendText("has error text:") } override fun matchesSafely(editText: EditText?): Boolean { return editText?.error != null } } } }
0
Kotlin
0
0
2e63b2f8ed7d1840e70593a2c87da86e48a56ab8
4,751
instrumented-tests-example
Apache License 2.0
build-logic/src/main/kotlin/mpeix/plugins/ext/VersionCatalogExt.kt
tonykolomeytsev
203,239,594
false
{"Kotlin": 972736, "JavaScript": 9100, "Python": 2365, "Shell": 46}
package mpeix.plugins.ext import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalog import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.kotlin.dsl.getByType /** * Get project's Version Catalog named 'libs' or throw */ internal val Project.versionCatalog: VersionCatalog get() = extensions .getByType<VersionCatalogsExtension>() .named("libs") internal fun VersionCatalog.requiredVersion(alias: String): String { val version = findVersion(alias) if (version.isPresent) return version.get().requiredVersion error("Can't find version by alias `$alias` in versions catalog") }
19
Kotlin
4
41
15c3c17e33d0ffffc0e269ad0cd6fe47b0bc971a
652
mpeiapp
MIT License
build-logic/src/main/kotlin/mpeix/plugins/ext/VersionCatalogExt.kt
tonykolomeytsev
203,239,594
false
{"Kotlin": 972736, "JavaScript": 9100, "Python": 2365, "Shell": 46}
package mpeix.plugins.ext import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalog import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.kotlin.dsl.getByType /** * Get project's Version Catalog named 'libs' or throw */ internal val Project.versionCatalog: VersionCatalog get() = extensions .getByType<VersionCatalogsExtension>() .named("libs") internal fun VersionCatalog.requiredVersion(alias: String): String { val version = findVersion(alias) if (version.isPresent) return version.get().requiredVersion error("Can't find version by alias `$alias` in versions catalog") }
19
Kotlin
4
41
15c3c17e33d0ffffc0e269ad0cd6fe47b0bc971a
652
mpeiapp
MIT License
client/client-hci/src/commonMain/kotlin/de/jlnstrk/transit/api/hci/model/geo/HciCoord.kt
jlnstrk
229,599,180
false
{"Kotlin": 729374}
package de.jlnstrk.transit.api.hci.model.geo import de.jlnstrk.transit.api.hci.model.graph.HciGraphNode import de.jlnstrk.transit.api.hci.model.HciCommon import kotlinx.serialization.Serializable @Serializable public data class HciCoord( /** The x-coordinate of these coordinates */ public val x: Long, /** The y-coordinate of these coordinates */ public val y: Long, /** The z-coordinate of these coordinates */ public val z: Long? = null, // /** The type of coordinate system used to encode [x], [y] and [z] */ // public val type: Type? = null, /** The index of these coordinates' layer into [HciCommon.layerL] */ public val layerX: Int? = null, /** The index of these coordinates' coordinate system into [HciCommon.crdSysL] */ public val crdSysX: Int? = null, /** The building floor of these coordinates */ public val floor: Int? = null, // TODO: Purpose? public val viewAlternatives: List<HciGraphNode> = emptyList(), ) { @Serializable public enum class Type { FLAT, HAFASGEO, PLANAR, WGS84, } }
0
Kotlin
0
0
9f700364f78ebc70b015876c34a37b36377f0d9c
1,117
transit
Apache License 2.0
src/main/kotlin/dev/sasikanth/android/resource/poet/ResourceItem.kt
msasikanth
590,505,826
false
{"Kotlin": 24322}
package dev.sasikanth.android.resource.poet import org.w3c.dom.Element @ResourceMarker interface ResourceItem { fun build(tagFactory: (tagName: String) -> Element): Element }
9
Kotlin
0
40
45ccb40dd569c7a3b2c11ae809847c98b8fa1300
179
android-resource-poet
Apache License 2.0
library/src/main/kotlin/com/cepgamer/strattester/data/HttpDownloader.kt
sbolotovms
265,016,252
false
{"Kotlin": 69013}
package com.cepgamer.strattester.data import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL abstract class HttpDownloader(private val url: URL) { fun download(): String { val connection = url.openConnection() as HttpURLConnection setUpConnection(connection) val result = connection.responseCode val response = StringBuilder() BufferedReader(InputStreamReader(connection.inputStream)).use { reader -> reader.lines().forEach { response.append(it + "\n") } } return response.toString() } abstract fun setUpConnection(connection: HttpURLConnection) }
2
Kotlin
1
0
de7b797c43b88535d83041fdd0dff1b9ac0b2b21
722
stratTester
MIT License
lib/src/test/java/io/sellmair/disposer/TestLifecycle.kt
sellmair
150,860,212
false
null
package io.sellmair.disposer import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry object TestLifecycle { fun create(): LifecycleRegistry = TestLifecycleOwner().lifecycle } private class TestLifecycleOwner : LifecycleOwner { val lifecycle = LifecycleRegistry(this) override fun getLifecycle(): Lifecycle { return lifecycle } }
0
Kotlin
8
176
c05def0d30def043da83823f2452c1593b34d49d
421
disposer
MIT License
sample/reaktive/app-android/src/main/java/com/arkivanov/mvikotlin/sample/reaktive/app/App.kt
arkivanov
437,014,963
false
{"Kotlin": 481306, "CSS": 842, "JavaScript": 716, "HTML": 583}
package com.arkivanov.mvikotlin.sample.reaktive.app import android.app.Application import com.arkivanov.mvikotlin.sample.database.DefaultTodoDatabase import com.arkivanov.mvikotlin.sample.database.TodoDatabase import com.arkivanov.mvikotlin.timetravel.server.TimeTravelServer class App : Application() { lateinit var database: TodoDatabase private set private val timeTravelServer = TimeTravelServer() override fun onCreate() { super.onCreate() database = DefaultTodoDatabase(context = this) timeTravelServer.start() } }
3
Kotlin
32
814
8ab014968028bc042ed0710c31113537fc9f66ed
575
MVIKotlin
Apache License 2.0
app/src/main/java/com/UMC/zipdabang/config/src/main/SocialLogin/model/GoogleResponse.kt
TeamZipdabang-UMC
585,966,195
false
{"Kotlin": 1461828}
package com.UMC.zipdabang.config.src.main.SocialLogin.model import com.google.gson.annotations.SerializedName data class GoogleResponse( @SerializedName ("status") val status: String, @SerializedName ("email") val email: String, @SerializedName ("token") val token: String )
0
Kotlin
2
0
cbb8399ee418515d282de05876b33fc8de27aa70
289
Zipdabang-Frontend
The Unlicense
app/src/main/java/com/manarelsebaay/amazonaws/core/utils/Extensions.kt
ManarElsebaay13
590,974,967
false
null
package com.manarelsebaay13.amazonaws.core.utils import android.app.Activity import android.content.Intent import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController fun <A : Activity> Activity.openActivityAndClearStack(activity: Class<A>) { Intent(this, activity).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(this) finish() } } fun Fragment.backToPreviousScreen() { findNavController().navigateUp() }
0
Kotlin
0
0
0544aff6ed7ba40fa66f425c5800f4bc7b0e1228
505
amazonaws
The Unlicense
app/src/main/java/com/elementary/tasks/navigation/topfragment/BaseSearchableFragment.kt
naz013
165,067,747
false
{"Kotlin": 2972212, "HTML": 20925}
package com.elementary.tasks.navigation.topfragment import android.content.Context import androidx.viewbinding.ViewBinding import com.elementary.tasks.navigation.SearchableFragmentCallback import com.elementary.tasks.navigation.SearchableFragmentQueryObserver abstract class BaseSearchableFragment<B : ViewBinding> : BaseTopFragment<B>(), SearchableFragmentQueryObserver { protected var searchableFragmentCallback: SearchableFragmentCallback? = null override fun onAttach(context: Context) { super.onAttach(context) if (searchableFragmentCallback == null) { runCatching { searchableFragmentCallback = context as SearchableFragmentCallback? } } } }
0
Kotlin
3
6
f60a6b1f690b4e1becce00e5475b5bf684f99131
680
reminder-kotlin
Apache License 2.0
app/OutWait/app/src/main/java/edu/kit/outwait/waitingQueue/gravityQueue/GravityQueueConverter.kt
OutWait
398,042,615
false
{"Kotlin": 725686}
package edu.kit.outwait.waitingQueue.gravityQueue import edu.kit.outwait.customDataTypes.FixedSlot import edu.kit.outwait.customDataTypes.ReceivedList import edu.kit.outwait.customDataTypes.SpontaneousSlot import edu.kit.outwait.waitingQueue.timeSlotModel.Pause import edu.kit.outwait.waitingQueue.timeSlotModel.TimeSlot import org.joda.time.DateTime import org.joda.time.Interval /** * This class has only one public method ([receivedListToTimeSlotList]) that converts * a received list to a time slot list with help of the gravity algorithm. * More details in the Method description. * */ class GravityQueueConverter { /** * Converts a received list object (the list we received from the server) to a * list of time slots and maps the locally stored auxiliary identifiers to the slots. * Since the received list does not contain starting and ending points of time * for the individual slots, this method applies the gravity algorithm (see design * document, chapter 10.1) to determine those points in time. * * @param receivedList the slot list we received from the server * @param auxiliaryIdentifiers Map with slot codes as keys and their auxiliary * identifiers as values * @return list of time slots: Each client slot with its calculated interval, all free * spaces between two client slots are filled with one pause slot. */ fun receivedListToTimeSlotList( receivedList: ReceivedList, auxiliaryIdentifiers: Map<String, String>, ): List<TimeSlot> { //convert received list to gravity queue and map auxiliary identifiers val gravityQueue = receivedListToGravityQueue(receivedList, auxiliaryIdentifiers) val currentSlotStartedTime = receivedList.currentSlotStartedTime //apply gravity algorithm and fill free space with pauses return gravitySlotListToTimeSlotList(gravityQueue, currentSlotStartedTime, DateTime.now()) } private fun receivedListToGravityQueue( receivedList: ReceivedList, auxiliaryIdentifiers: Map<String, String> ): List<ClientGravitySlot> { val gravityList = mutableListOf<ClientGravitySlot>() for (code in receivedList.order) { /* a slot can either be fixed or spontaneous, but not both */ if (isSpontaneous(code, receivedList)) { gravityList.add(toGravitySlot( getSpontaneous(code, receivedList)!!, auxiliaryIdentifiers) ) } if (isFixed(code, receivedList)) { gravityList.add(toGravitySlot( getFixed(code, receivedList)!!, auxiliaryIdentifiers) ) } } return gravityList } //convert spontaneous slot from received list to spontaneous gravity slot and find its aux private fun toGravitySlot( slot: SpontaneousSlot, auxiliaryIdentifiers: Map<String, String> ) = SpontaneousGravitySlot( slot.slotCode, slot.duration, getAuxiliary(slot.slotCode, auxiliaryIdentifiers) ) //convert spontaneous slot from received list to spontaneous gravity slot and find its aux private fun toGravitySlot( slot: FixedSlot, auxiliaryIdentifiers: Map<String, String> ) = FixedGravitySlot( slot.slotCode, slot.duration, slot.appointmentTime, getAuxiliary(slot.slotCode, auxiliaryIdentifiers) ) /* for given slot code, search aux and return it or return empty string when not in list. */ private fun getAuxiliary(code: String, auxiliaryIdentifiers: Map<String, String>): String { var aux = "" if (auxiliaryIdentifiers.containsKey(code)) { aux = auxiliaryIdentifiers[code]!! } return aux } /* returns fixed slot if the received list contains the fixed slot and elsewise null */ private fun getFixed(code: String, receivedList: ReceivedList): FixedSlot? { for (slot in receivedList.fixed) { if (slot.slotCode == code) { return slot } } return null } /* returns spontaneous slot if the received list contains the fixed slot and elsewise null */ private fun getSpontaneous(code: String, receivedList: ReceivedList): SpontaneousSlot? { for (slot in receivedList.spontaneous) { if (slot.slotCode == code) { return slot } } return null } private fun isFixed(code: String, receivedList: ReceivedList) = (getFixed(code, receivedList) !== null) private fun isSpontaneous(code: String, receivedList: ReceivedList) = (getSpontaneous(code, receivedList) !== null) /* * applies the gravity algorithm and fills free time between client time slots with pause * slots. Takes not only the current slot started time, but also the current time * (as a parameter for testability) to check if the current slot is already running * longer than planned. */ private fun gravitySlotListToTimeSlotList( gravitySlotList: List<ClientGravitySlot>, currentSlotStartedTime: DateTime, now: DateTime, ): List<TimeSlot> { //When the list is empty the algorithm does not have to be executed. if (gravitySlotList.isEmpty()) return listOf<TimeSlot>() //Make a dummy so that the first gravity slot already has a predecessor val firstTimeSlotDummy = if (currentSlotStartedTime + gravitySlotList.first().duration < now) { //Current slot is delaying Pause(Interval( now - gravitySlotList.first().duration, now - gravitySlotList.first().duration )) } else { //Current slot is not delaying Pause(Interval(currentSlotStartedTime, currentSlotStartedTime)) } //push the dummy to the front of the list so that we can start the iteration val timeSlotList = mutableListOf<TimeSlot>(firstTimeSlotDummy) //gravity algorithm for (slot in gravitySlotList) { /* the magic happens in toClientTimeSlot with dynamic polymorphism. Each slot calculates its interval itself. */ timeSlotList.add(slot.toClientTimeSlot(timeSlotList.last())) } //now the dummy can be removed timeSlotList.remove(firstTimeSlotDummy) //insert pauses in free time between slots val listWithPauses = mutableListOf<TimeSlot>() var i: Int = 0 while (i < timeSlotList.size) { listWithPauses.add(timeSlotList[i]) if (i != timeSlotList.lastIndex && timeSlotList[i].interval.end < timeSlotList[i + 1].interval.start) { timeSlotList.add( i + 1, Pause(Interval( timeSlotList[i].interval.end, timeSlotList[i + 1].interval.start )) ) } i++ } return listWithPauses } }
0
Kotlin
0
1
d3b878b82294899006b21a91f48877aa555eee6e
7,294
OutWait
MIT License
app/src/main/java/com/umairadil/androidjetpack/data/repositories/main/MainRepository.kt
umair13adil
139,688,287
false
null
package com.umairadil.androidjetpack.data.repositories.main import com.umairadil.androidjetpack.data.local.MovieGenre import com.umairadil.androidjetpack.data.local.RealmHelper import com.umairadil.androidjetpack.data.local.TVGenres import com.umairadil.androidjetpack.data.network.RestService import com.umairadil.androidjetpack.utils.Constants import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton @Singleton class MainRepository @Inject constructor(private var api: RestService, private var db: RealmHelper) : MainDataSource { override fun getMoviesGenre() { //Do nothing if genre are added if (db.findAll(MovieGenre().javaClass).isNotEmpty()) return api.getMoviesGenre(Constants.API_KEY) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( // named arguments for lambda Subscribers onNext = { val results = it.genres for (genre in results!!) { db.add(MovieGenre(genre.id, genre.name)) } }, onError = { it.printStackTrace() }, onComplete = { } ) } override fun getTVGenre() { //Do nothing if genre are added if (db.findAll(TVGenres().javaClass).isNotEmpty()) return api.getTVGenre(Constants.API_KEY) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( // named arguments for lambda Subscribers onNext = { val results = it.genres for (genre in results!!) { db.add(TVGenres(genre.id, genre.name)) } }, onError = { it.printStackTrace() }, onComplete = { } ) } }
0
Kotlin
4
11
2cf74f50df7329c33cda543a84540c97860c4452
2,335
AndroidJetpackTemplate
The Unlicense
common/domain/src/test/kotlin/no/nav/su/se/bakover/common/domain/NonBlankStringTest.kt
navikt
227,366,088
false
{"Kotlin": 9248077, "Shell": 4372, "TSQL": 1233, "Dockerfile": 800}
package no.nav.su.se.bakover.common.domain import no.nav.su.se.bakover.common.domain.NonBlankString.Companion.toNonBlankString import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows class NonBlankStringTest { @Test fun `exception dersom strengen er blank`() { assertThrows<IllegalArgumentException> { NonBlankString.create(" ") " ".toNonBlankString() } } @Test fun `konstruerer NonBlankString`() { assertDoesNotThrow { NonBlankString.create("a") "a".toNonBlankString() } } }
2
Kotlin
1
1
9fbc1f8db1063c2375380bb776e27299e30591c9
652
su-se-bakover
MIT License
fs-s2/file/fs-file-domain/src/commonMain/kotlin/io/komune/fs/s2/file/domain/model/FileAskMetadataDTO.kt
smartbcity
746,804,672
false
{"Kotlin": 100132, "MDX": 24383, "Makefile": 3498, "JavaScript": 1342, "Dockerfile": 745, "CSS": 102}
package city.smartb.fs.s2.file.domain.model import kotlin.js.JsExport import kotlin.js.JsName import kotlinx.serialization.Serializable @JsExport @JsName("ChatMetadataDTO") interface FileAskMetadataDTO { val targetedFiles: List<String> } @Serializable data class FileAskMetadata( override val targetedFiles: List<String> ): FileAskMetadataDTO
0
Kotlin
0
0
df5a3c98221a86eeaabde180ea5e455096f8d41e
354
connect-fs
Apache License 2.0
data-android/src/main/java/ly/david/data/spotify/SpotifyAccessTokenInterceptor.kt
lydavid
458,021,427
false
null
package ly.david.data.spotify import javax.inject.Inject import kotlinx.coroutines.runBlocking import ly.david.data.AUTHORIZATION import ly.david.data.BEARER import ly.david.data.BuildConfig import ly.david.data.spotify.auth.SpotifyAccessToken import ly.david.data.spotify.auth.SpotifyAuthApi import okhttp3.Interceptor import okhttp3.Response private const val MS_TO_S = 1000L class SpotifyAccessTokenInterceptor @Inject constructor( private val spotifyOAuth: SpotifyOAuth, private val spotifyAuthApi: SpotifyAuthApi ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() val hasAuthorizationHeader = originalRequest.headers.names().contains(AUTHORIZATION) val accessToken = runBlocking { spotifyOAuth.getAccessToken() } val expirationTime = runBlocking { spotifyOAuth.getExpirationTime() } ?: 0L if (hasAuthorizationHeader || (!accessToken.isNullOrEmpty() && expirationTime > System.currentTimeMillis())) { val requestBuilder = originalRequest.newBuilder() if (!accessToken.isNullOrEmpty()) { requestBuilder.header(AUTHORIZATION, "$BEARER $accessToken") } return chain.proceed(requestBuilder.build()) } val newAccessToken = runBlocking { requestNewAccessToken() } spotifyOAuth.saveAccessToken( accessToken = newAccessToken.accessToken, expirationSystemTime = (newAccessToken.expiresIn * MS_TO_S) + System.currentTimeMillis() ) val requestBuilder = originalRequest.newBuilder() .header(AUTHORIZATION, "$BEARER ${newAccessToken.accessToken}") return chain.proceed(requestBuilder.build()) } private suspend fun requestNewAccessToken(): SpotifyAccessToken { return spotifyAuthApi.getAccessToken( clientId = BuildConfig.SPOTIFY_CLIENT_ID, clientSecret = BuildConfig.SPOTIFY_CLIENT_SECRET ) } }
54
Kotlin
0
4
052613fefaeb5a687ee36d0f3889d9a120224994
2,015
MusicSearch
Apache License 2.0
android/quest/src/main/java/org/smartregister/fhircore/quest/data/patient/PatientRepository.kt
issyzac
420,960,297
true
{"Kotlin": 1058894}
/* * Copyright 2021 Ona Systems, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.smartregister.fhircore.quest.data.patient import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import ca.uhn.fhir.rest.gclient.TokenClientParam import com.google.android.fhir.FhirEngine import com.google.android.fhir.logicalId import com.google.android.fhir.search.Order import com.google.android.fhir.search.Search import com.google.android.fhir.search.StringFilterModifier import com.google.android.fhir.search.count import com.google.android.fhir.search.search import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.hl7.fhir.r4.model.CodeableConcept import org.hl7.fhir.r4.model.Coding import org.hl7.fhir.r4.model.Patient import org.hl7.fhir.r4.model.Questionnaire import org.hl7.fhir.r4.model.QuestionnaireResponse import org.smartregister.fhircore.engine.configuration.view.RegisterViewConfiguration import org.smartregister.fhircore.engine.data.domain.util.DomainMapper import org.smartregister.fhircore.engine.data.domain.util.PaginationUtil import org.smartregister.fhircore.engine.data.domain.util.RegisterRepository import org.smartregister.fhircore.engine.ui.questionnaire.QuestionnaireConfig import org.smartregister.fhircore.engine.util.DefaultDispatcherProvider import org.smartregister.fhircore.engine.util.DispatcherProvider import org.smartregister.fhircore.quest.data.patient.model.PatientItem class PatientRepository( override val fhirEngine: FhirEngine, override val domainMapper: DomainMapper<Patient, PatientItem>, private val registerViewConfiguration: MutableLiveData<RegisterViewConfiguration>? = null, private val dispatcherProvider: DispatcherProvider = DefaultDispatcherProvider ) : RegisterRepository<Patient, PatientItem> { fun applyPrimaryFilter(search: Search) { val filter = registerViewConfiguration?.value?.primaryFilter if (filter != null) { search.filter( TokenClientParam(filter.key), Coding().apply { code = filter.code system = filter.system } ) } else search.filter(Patient.ACTIVE, true) } override suspend fun loadData( query: String, pageNumber: Int, loadAll: Boolean ): List<PatientItem> { return withContext(dispatcherProvider.io()) { val patients = fhirEngine.search<Patient> { applyPrimaryFilter(this) if (query.isNotBlank()) { filter(Patient.NAME) { modifier = StringFilterModifier.CONTAINS value = query.trim() } } sort(Patient.NAME, Order.ASCENDING) count = if (loadAll) countAll()?.toInt() else PaginationUtil.DEFAULT_PAGE_SIZE from = pageNumber * PaginationUtil.DEFAULT_PAGE_SIZE } patients.map { domainMapper.mapToDomainModel(it) } } } override suspend fun countAll(): Long = withContext(dispatcherProvider.io()) { fhirEngine.count<Patient> { applyPrimaryFilter(this) } } fun fetchDemographics(patientId: String): LiveData<Patient> { val data = MutableLiveData<Patient>() CoroutineScope(dispatcherProvider.io()).launch { data.postValue(fhirEngine.load(Patient::class.java, patientId)) } return data } fun fetchTestResults(patientId: String): LiveData<List<QuestionnaireResponse>> { val data = MutableLiveData<List<QuestionnaireResponse>>() CoroutineScope(dispatcherProvider.io()).launch { val result = fhirEngine.search<QuestionnaireResponse> { filter(QuestionnaireResponse.SUBJECT) { value = "Patient/$patientId" } } data.postValue(result) } return data } fun fetchTestForms(code: String, system: String): LiveData<List<QuestionnaireConfig>> { val data = MutableLiveData<List<QuestionnaireConfig>>() CoroutineScope(dispatcherProvider.io()).launch { val result = fhirEngine.search<Questionnaire> { filter( Questionnaire.CONTEXT, CodeableConcept().apply { addCoding().apply { this.code = code this.system = system } } ) } data.postValue(result.map { QuestionnaireConfig(it.name, it.title, it.logicalId) }) } return data } }
0
null
0
0
c4eb29dc58e6232dcee2431a77e082af7ed60421
4,896
fhircore
Apache License 2.0
src/main/kotlin/no/nav/helsearbeidsgiver/domene/inntektsmelding/v1/Inntekt.kt
navikt
692,072,545
false
{"Kotlin": 131100}
@file:UseSerializers(LocalDateSerializer::class) package no.nav.helsearbeidsgiver.domene.inntektsmelding.v1 import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import no.nav.helsearbeidsgiver.domene.inntektsmelding.v1.utils.FeiletValidering import no.nav.helsearbeidsgiver.domene.inntektsmelding.v1.utils.Feilmelding import no.nav.helsearbeidsgiver.domene.inntektsmelding.v1.utils.erStoerreEllerLikNullOgMindreEnnMaks import no.nav.helsearbeidsgiver.domene.inntektsmelding.v1.utils.valider import no.nav.helsearbeidsgiver.utils.json.serializer.LocalDateSerializer import java.time.LocalDate @Serializable data class Inntekt( val beloep: Double, val inntektsdato: LocalDate, val naturalytelser: List<Naturalytelse>, val endringAarsak: InntektEndringAarsak?, ) { internal fun valider(): List<FeiletValidering> = listOfNotNull( valider( vilkaar = beloep.erStoerreEllerLikNullOgMindreEnnMaks(), feilmelding = Feilmelding.KREVER_BELOEP_STOERRE_ELLER_LIK_NULL, ), valider( vilkaar = naturalytelser.all(Naturalytelse::erGyldig), feilmelding = Feilmelding.KREVER_BELOEP_STOERRE_ENN_NULL, ), ) }
1
Kotlin
0
0
2f6b46f63d88cca25c3db4122e02ccd679e54a12
1,273
hag-domene-inntektsmelding
MIT License
kernel/src/main/kotlin/eu/simonbinder/kart/kernel/Visitor.kt
tchigher
252,535,879
true
{"Kotlin": 170353, "Dart": 3642}
package eu.simonbinder.kart.kernel import eu.simonbinder.kart.kernel.types.DartType import eu.simonbinder.kart.kernel.types.DartTypeVisitor interface Visitor<R> : TreeVisitor<R>, DartTypeVisitor<R> { fun defaultNode(node: Node): R override fun defaultTreeNode(node: TreeNode): R = defaultNode(node) override fun defaultDartType(node: DartType): R = defaultNode(node) fun visitName(node: Name): R = defaultNode(node) }
0
null
0
0
8d591ad246a4bb3881b90dacf160128467db6e3b
438
kart
MIT License
app/src/main/java/ke/co/tulivuapps/hoteltours/data/repository/DestinationRepositoryImpl.kt
RushiChavan-dev
740,244,295
false
{"Kotlin": 872337}
package ke.co.tulivuapps.hoteltours.data.repository import ke.co.tulivuapps.hoteltours.data.local.dao.DestinationDao import ke.co.tulivuapps.hoteltours.data.model.destination.DestinationFavoriteEntity import ke.co.tulivuapps.hoteltours.data.model.destination.DestinationInfoResponse import ke.co.tulivuapps.hoteltours.data.model.destination.DestinationResponse import ke.co.tulivuapps.hoteltours.data.remote.source.DestinationRemoteDataSource import ke.co.tulivuapps.hoteltours.data.remote.utils.DataState import ke.co.tulivuapps.hoteltours.domain.repository.DestinationRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import retrofit2.Response import javax.inject.Inject /** * Created by Rushi on 12.03.2023 */ class DestinationRepositoryImpl @Inject constructor( private val characterRemoteDataSource: DestinationRemoteDataSource, private val dao: DestinationDao ) : DestinationRepository { override suspend fun getAllDestinations( page: Int, options: Map<String, String> ): Response<DestinationResponse> = characterRemoteDataSource.getAllDestinations(page = page, options = options) override fun getDestination(characterId: Int): Flow<DataState<DestinationInfoResponse>> = flow { emitAll(characterRemoteDataSource.getDestination(characterId = characterId)) } override fun getDestination(url: String): Flow<DataState<DestinationInfoResponse>> = flow { emitAll(characterRemoteDataSource.getDestination(url = url)) } override suspend fun getFilterDestinations( page: Int, options: Map<String, String> ): Response<DestinationResponse> = characterRemoteDataSource.getFilterDestinations(page, options) override suspend fun getFavorite(favoriteId: Int): DestinationFavoriteEntity? = dao.getFavorite(favoriteId) override suspend fun getFavoriteList(): List<DestinationFavoriteEntity> = dao.getFavoriteList() override suspend fun deleteFavoriteById(favoriteId: Int) = dao.deleteFavoriteById(favoriteId) override suspend fun deleteFavoriteList() = dao.deleteFavoriteList() override suspend fun saveFavorite(entity: DestinationFavoriteEntity) = dao.insert(entity) override suspend fun saveFavoriteList(entityList: List<DestinationFavoriteEntity>) = dao.insert(entityList) }
0
Kotlin
0
0
ad74422b1b7930e5665c94cc9368ec69d425ffba
2,373
HotelApp
Apache License 2.0
proto/src/test/kotlin/JsonTest.kt
smartbcity
464,391,371
false
{"JavaScript": 678592, "Kotlin": 186772, "TypeScript": 80011, "Gherkin": 5292, "Java": 5207, "HTML": 1853, "Makefile": 1066, "CSS": 503, "Dockerfile": 368}
import cccev.dsl.cee.indba116.IND_BA_116 import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JsonTest { @Test fun test() { val mapper = ObjectMapper().registerModule(KotlinModule()) val json = mapper.writeValueAsString(IND_BA_116) println(json) } }
0
JavaScript
1
0
a17d720baaac8483a80033b003b7e7e5ac4170ff
471
cccev
Apache License 2.0
src/main/kotlin/org/veupathdb/lib/cli/diamond/opts/QueryStrand.kt
VEuPathDB
848,883,430
false
{"Kotlin": 153381}
package org.veupathdb.lib.cli.diamond.opts import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonValue import com.fasterxml.jackson.databind.JsonNode import org.veupathdb.lib.cli.diamond.util.CliEnum import org.veupathdb.lib.cli.diamond.util.invalid enum class QueryStrand : CliEnum { Both, Plus, Minus, ; override val cliValue get() = toString() @JsonValue override fun toString() = name.lowercase() companion object { @JvmStatic @JsonCreator fun fromJson(json: JsonNode) = when { json.isTextual -> fromString(json.textValue()) else -> invalid(json) } @JvmStatic fun fromString(value: String) = value.lowercase().let { name -> entries.find { it.name == name } } ?: invalid(value) } }
0
Kotlin
0
0
89e07202e347e57276b3a9e459bd89ef495975f3
815
lib-jvm-diamondcli
Apache License 2.0
defitrack-rest/defitrack-protocol-service/src/main/java/io/defitrack/protocol/compound/rewards/CompoundArbitrumRewardProvider.kt
decentri-fi
426,174,152
false
{"Kotlin": 1303020, "Java": 1948, "Dockerfile": 909}
package io.defitrack.protocol.compound.rewards import io.defitrack.common.network.Network import io.defitrack.architecture.conditional.ConditionalOnCompany import io.defitrack.protocol.Company import org.springframework.stereotype.Component @Component @ConditionalOnCompany(Company.COMPOUND) class CompoundArbitrumRewardProvider : CompoundRewardProvider(Network.ARBITRUM)
59
Kotlin
6
10
cf42dccef2f369429412e18b6298fb518eb6d50b
373
defi-hub
MIT License
DailyMovie/app/src/main/java/com/example/dailymovie/adapters/MovieAdapter.kt
jesus33lcc
794,693,138
false
{"Kotlin": 55973, "Java": 5856}
package com.example.dailymovie.adapters import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.dailymovie.R import com.example.dailymovie.client.RetrofitClient import com.example.dailymovie.client.response.MovieDetailsResponse import com.example.dailymovie.models.MovieModel import com.example.dailymovie.utils.Constantes import com.example.dailymovie.views.MovieA import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.concurrent.Executors class MovieAdapter( var listMovies: ArrayList<MovieModel> ) : RecyclerView.Adapter<MovieAdapter.MovieViewHolder>() { class MovieViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title: TextView = itemView.findViewById(R.id.txt_titleMovie) val year: TextView = itemView.findViewById(R.id.txt_yearMovie) val poster: ImageView = itemView.findViewById(R.id.img_posterMovie) val rating: TextView = itemView.findViewById(R.id.txt_voteAverageMovie) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_movie_list, parent, false) return MovieViewHolder(view) } override fun onBindViewHolder(holder: MovieViewHolder, position: Int) { val movie = listMovies[position] holder.title.text = movie.title holder.year.text = movie.releaseDate.take(4) holder.rating.text = "Rating: ${movie.voteAverage}" Glide.with(holder.itemView.context) .load(Constantes.IMAGE_URL + movie.posterPath) .placeholder(R.drawable.ic_baseline_image_24) .error(R.drawable.ic_baseline_image_24) .into(holder.poster) holder.itemView.setOnClickListener { val context = holder.itemView.context val intent = Intent(context, MovieA::class.java).apply { putExtra("MOVIE", movie) } context.startActivity(intent) } } override fun getItemCount(): Int { return listMovies.size } fun updateMoviesList(newMoviesList: ArrayList<MovieModel>) { listMovies.clear() listMovies.addAll(newMoviesList) notifyDataSetChanged() } }
0
Kotlin
0
0
135bcf1bf35433c827ab1b0bcd09150bb8c3dc58
2,525
DailyMovie
MIT License
src/test/kotlin/moe/sdl/tracks/external/zhconvert/ZhConvertTest.kt
Colerar
454,784,355
false
null
package moe.sdl.tracks.external.zhconvert import kotlinx.coroutines.runBlocking import moe.sdl.tracks.config.client import org.junit.jupiter.api.Test class ZhConvertTest { @Test fun convertTest(): Unit = runBlocking { client.client.requestZhConvert( "一隻憂鬱的臺灣烏龜", Converter.CHINA, ).also(::println) } }
1
Kotlin
0
12
5e3cea5d0ded8911dde91676c0f56f6dc9306db0
356
Tracks
MIT License
app/src/test/java/com/brandoncano/capacitorcalculator/util/IsValidCapacitanceTest.kt
bmcano
637,987,066
false
{"Kotlin": 126103}
package com.brandoncano.capacitorcalculator.util import com.brandoncano.capacitorcalculator.constants.Units import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class IsValidCapacitanceTest { @Test fun `check empty and short inputs inputs`() { var emptyResult = IsValidCapacitance.execute("", Units.PF) assertTrue(emptyResult) emptyResult = IsValidCapacitance.execute("", Units.NF) assertTrue(emptyResult) emptyResult = IsValidCapacitance.execute("", Units.UF) assertTrue(emptyResult) // returns true here because the input it too small so calculation does not occur assertTrue(IsValidCapacitance.execute("1", Units.PF)) } @Test fun `check valid pf inputs`() { assertTrue(IsValidCapacitance.execute("10", Units.PF)) assertTrue(IsValidCapacitance.execute("23.0", Units.PF)) assertTrue(IsValidCapacitance.execute("450", Units.PF)) assertTrue(IsValidCapacitance.execute("6700", Units.PF)) assertTrue(IsValidCapacitance.execute("89000", Units.PF)) assertTrue(IsValidCapacitance.execute("130000", Units.PF)) assertTrue(IsValidCapacitance.execute("4600000", Units.PF)) assertTrue(IsValidCapacitance.execute("79000000", Units.PF)) assertTrue(IsValidCapacitance.execute("99000000", Units.PF)) } @Test fun `check valid nf inputs`() { assertTrue(IsValidCapacitance.execute(".010", Units.NF)) assertTrue(IsValidCapacitance.execute("0.01", Units.NF)) assertTrue(IsValidCapacitance.execute(".023", Units.NF)) assertTrue(IsValidCapacitance.execute("0.023", Units.NF)) assertTrue(IsValidCapacitance.execute(".45", Units.NF)) assertTrue(IsValidCapacitance.execute("0.45", Units.NF)) assertTrue(IsValidCapacitance.execute("1", Units.NF)) assertTrue(IsValidCapacitance.execute("6.7", Units.NF)) assertTrue(IsValidCapacitance.execute("89.0", Units.NF)) assertTrue(IsValidCapacitance.execute("130", Units.NF)) assertTrue(IsValidCapacitance.execute("4600", Units.NF)) assertTrue(IsValidCapacitance.execute("79000", Units.NF)) assertTrue(IsValidCapacitance.execute("99000", Units.NF)) } @Test fun `check valid uf inputs`() { assertTrue(IsValidCapacitance.execute(".00001", Units.UF)) assertTrue(IsValidCapacitance.execute("0.00001", Units.UF)) assertTrue(IsValidCapacitance.execute(".000023", Units.UF)) assertTrue(IsValidCapacitance.execute("0.00045", Units.UF)) assertTrue(IsValidCapacitance.execute(".0067", Units.UF)) assertTrue(IsValidCapacitance.execute(".089", Units.UF)) assertTrue(IsValidCapacitance.execute("0.130", Units.UF)) assertTrue(IsValidCapacitance.execute("1", Units.UF)) assertTrue(IsValidCapacitance.execute("4.6", Units.UF)) assertTrue(IsValidCapacitance.execute("79.0", Units.UF)) assertTrue(IsValidCapacitance.execute("99", Units.UF)) } @Test fun `check invalid inputs`() { val values = listOf("abc", "1.1.1", " ", "(1)", "1a", "990000000", "123", " 120", "\n120") values.forEach { assertFalse(IsValidCapacitance.execute(it, Units.PF)) assertFalse(IsValidCapacitance.execute(it, Units.NF)) assertFalse(IsValidCapacitance.execute(it, Units.UF)) } } }
2
Kotlin
0
1
f87b67259bb818f9a85d17bfcced444f1e508e0f
3,449
CapacitorCalculatorApp
MIT License
src/main/kotlin/no/nav/pensjon/simulator/core/exception/BrukerFoedtFoer1943Exception.kt
navikt
753,551,695
false
{"Kotlin": 1584529, "Java": 2774, "Dockerfile": 144}
package no.nav.pensjon.simulator.core.exception class BrukerFoedtFoer1943Exception(message: String) : RuntimeException(message)
0
Kotlin
0
0
bb93f7cafbbc331bf1775d2508e292fab95a3490
129
pensjonssimulator
MIT License
app/src/main/java/com/onirutla/submissiondicoding/ui/home/HomeActivity.kt
onirutlA
309,605,628
false
null
package com.onirutla.submissiondicoding.ui.home import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.onirutla.submissiondicoding.R import kotlinx.android.synthetic.main.activity_home.* class HomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager) view_pager.adapter = sectionsPagerAdapter tabs.setupWithViewPager(view_pager) supportActionBar?.elevation = 0f } }
0
Kotlin
0
0
6f225b6f63310ebf4c1112ffdb209625a406b235
637
Movie-App
Apache License 2.0
app/src/main/java/org/sil/storyproducer/tools/media/AudioPlayer.kt
techteam25
516,120,982
false
null
package org.sil.storyproducer.tools.media import android.content.Context import android.media.MediaPlayer import android.net.Uri import android.util.Log import org.sil.storyproducer.model.Workspace import org.sil.storyproducer.tools.file.getStoryUri import java.io.IOException class AudioPlayer { private var mPlayer: MediaPlayer = MediaPlayer() private var fileExists: Boolean = false private var onCompletionListenerPersist: MediaPlayer.OnCompletionListener? = null var currentPosition: Int get() = if (isAudioPrepared) { mPlayer.currentPosition } else { 0 } set(value) { if (isAudioPrepared) { mPlayer.seekTo(value) } } /** * returns the duration of the audio as an int in milliseconds * @return the duration of the audio as an int */ val audioDurationInMilliseconds: Int get() = if (isAudioPrepared) { mPlayer.duration } else { 0 } /** * returns if the audio is being played or not * @return true or false based on if the audio is being played */ val isAudioPlaying: Boolean get() = isAudioPrepared && mPlayer.isPlaying var isAudioPrepared: Boolean = false private set fun setSource(context: Context, uri: Uri): Boolean { mPlayer.release() mPlayer = MediaPlayer() mPlayer.setOnCompletionListener(onCompletionListenerPersist) mPlayer.setDataSource(context, uri) fileExists = true isAudioPrepared = true mPlayer.prepare() currentPosition = 0 return fileExists } /** * set the audio file from the worskspace data * @return true if the file exists, false if it does not. */ fun setStorySource(context: Context, relPath: String, storyName: String = Workspace.activeStory.title): Boolean { val uri: Uri = getStoryUri(relPath, storyName) ?: return false return setSource(context, uri) } fun playAudio() { currentPosition = 0 resumeAudio() } /** * Pauses the audio if it is currently being played */ fun pauseAudio() { if (mPlayer.isPlaying) { mPlayer.pause() } } /** * Resumes the audio from where it was last paused */ fun resumeAudio() { if (fileExists) { mPlayer.start() } } /** * Stops the audio if it is currently being played */ fun stopAudio() { if (mPlayer.isPlaying) mPlayer.pause() if (currentPosition != 0) currentPosition = 0 } /** * Releases the MediaPlayer object after completion */ fun release() { isAudioPrepared = false mPlayer.release() } /** * Seeks to the parameter in milliseconds * @param msec milliseconds for where to seek to in the audio */ fun seekTo(msec: Int) { if (!fileExists) return mPlayer.seekTo(msec) } /** * sets the completion listener * @param listener handler for OnCompletionListener */ fun onPlayBackStop(listener: MediaPlayer.OnCompletionListener) { onCompletionListenerPersist = listener mPlayer.setOnCompletionListener(listener) } /** * sets the volume of the audio * @param volume the float for the volume from 0.0 to 1.0 */ fun setVolume(volume: Float) { mPlayer.setVolume(volume, volume) } companion object { private val TAG = "AudioPlayer" } }
0
Kotlin
0
0
de4efe2284254a265e028e76e1a38bd822b7a038
3,627
Cedarville
MIT License