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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
common/localization/src/test/java/dev/bwaim/loteria/localization/CardNameTest.kt | Bwaim | 410,120,178 | false | null | /*
* Copyright 2022 Dev Bwaim team
*
* 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.bwaim.loteria.localization
import org.junit.Assert.assertEquals
import org.junit.Test
internal class CardNameTest {
@Test
fun name_map_to_card_name() {
assertEquals(
CardName.CARD_1,
CardName.valueOf("CARD_1"),
)
}
}
| 17 | Kotlin | 1 | 3 | 176b8e4fe60caf907305b6ddac18e0869fdfb688 | 884 | Loteria-Mexicana | Apache License 2.0 |
gonggutong/android/app/src/main/kotlin/com/silverjun/gonggutong/MainActivity.kt | SilverJun | 245,163,132 | false | {"Dart": 110078, "Ruby": 13754, "Swift": 3276, "Kotlin": 3050, "Objective-C": 297} | package com.silverjun.gonggutong
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 72fbe85d2fc1501d3048f912fcf7528c6ac72eee | 129 | MobileAppDevelopment | MIT License |
src/main/kotlin/online/slavok/whitelist/SimpleWhitelist.kt | iSlavok | 828,676,724 | false | {"Kotlin": 16300, "Java": 368} | package online.slavok.whitelist
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback
import net.fabricmc.loader.api.FabricLoader
import online.slavok.whitelist.commands.SimpleWhitelistCommand
import online.slavok.whitelist.config.ConfigManager
import online.slavok.whitelist.database.DatabaseManager
import online.slavok.whitelist.database.JsonManager
import online.slavok.whitelist.database.MySqlManager
import online.slavok.whitelist.events.LoginEvent
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.file.Files
object SimpleWhitelist : ModInitializer {
val logger: Logger = LoggerFactory.getLogger("simple-whitelist")
lateinit var databaseManager: DatabaseManager
lateinit var configManager: ConfigManager
override fun onInitialize() {
LoginEvent().register()
val configDir = FabricLoader.getInstance().configDir
val whitelistDir = configDir.resolve("SimpleWhitelist")
if (!Files.exists(whitelistDir)) {
Files.createDirectories(whitelistDir)
}
configManager = ConfigManager(whitelistDir.resolve("config.json").toFile())
if (configManager.config.databaseType == "mysql") {
databaseManager = MySqlManager(configManager.config.mysqlUrl)
logger.info("Using MySQL database")
} else {
databaseManager = JsonManager(whitelistDir.resolve(configManager.config.jsonFileName).toFile())
logger.info("Using JSON database")
}
CommandRegistrationCallback.EVENT.register { dispatcher, _, _ ->
SimpleWhitelistCommand().register(dispatcher)
}
}
}
| 0 | Kotlin | 0 | 2 | d4bc70c9e0298708f401bff1ae55210e471fec91 | 1,560 | Simple-Whitelist | MIT License |
src/main/kotlin/com/github/rothso/mass/extractor/network/NetworkContext.kt | rothso | 145,013,217 | false | null | package com.github.rothso.mass.extractor.network
import java.util.concurrent.atomic.AtomicInteger
class NetworkContext(val maxConcurrency: AtomicInteger) | 0 | Kotlin | 0 | 0 | 43cd8cc598150ece119b9536e7012c36b2182cdf | 155 | patient-extractor | MIT License |
feature/auth-impl/src/commonMain/kotlin/com/opencritic/auth/domain/AuthUserAgent.kt | MAX-POLKOVNIK | 797,563,657 | false | {"Kotlin": 604244, "Swift": 213504, "Objective-C": 8050} | package com.opencritic.auth.domain
data object AuthUserAgent {
override fun toString(): String =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:124.0) Gecko/20100101 Firefox/124.0"
} | 0 | Kotlin | 0 | 4 | 99c3df65e8620fe5f2d5c16ade0d593357869fa5 | 198 | OpenCritic | Apache License 2.0 |
src/main/java/com/naveenh/mydailynews/repository/NetworkCall.kt | naveenachar | 535,186,286 | false | {"Kotlin": 11678} | package com.naveenh.mydailynews.repository
import android.util.Log
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class NetworkCall {
var BASE_URL: String = "https://newsapi.org/"
// var BASE_URL: String = "https://www.kayak.com/h/mobileapis/directory/"
var retrofit: Retrofit? = null
fun getApiClient(): Retrofit? {
Log.i("Naveen","URL"+BASE_URL)
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build()
}
return retrofit
}
} | 0 | Kotlin | 0 | 0 | 366f24580c85c1ca7dd580d0523924cf42578348 | 633 | dailynews | The Unlicense |
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslProgram.kt | fabmax | 81,503,047 | false | null | package de.fabmax.kool.modules.ksl.lang
import de.fabmax.kool.modules.ksl.KslShaderListener
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
open class KslProgram(val name: String) {
/**
* Debug property: if true generated shader code is dumped to console
*/
var dumpCode = false
var isPrepared = false
private set
private var nextNameIdx = 1
internal fun nextName(prefix: String): String = "${prefix}_${nextNameIdx++}"
val commonUniformBuffer = KslUniformBuffer("CommonUniforms", this)
val uniformBuffers = mutableListOf(commonUniformBuffer)
val uniformSamplers = mutableMapOf<String, KslUniform<*>>()
val dataBlocks = mutableListOf<KslDataBlock>()
val vertexStage = KslVertexStage(this)
val fragmentStage = KslFragmentStage(this)
val stages = listOf(vertexStage, fragmentStage)
val shaderListeners = mutableListOf<KslShaderListener>()
fun vertexStage(block: KslVertexStage.() -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
vertexStage.apply(block)
}
fun fragmentStage(block: KslFragmentStage.() -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
fragmentStage.apply(block)
}
private fun registerSampler(uniform: KslUniform<*>) {
uniformSamplers[uniform.name] = uniform
stages.forEach {
it.globalScope.definedStates += uniform.value
}
}
private inline fun <reified T: KslUniform<*>> getOrCreateSampler(name: String, create: () -> T): T {
val uniform = uniformSamplers[name] ?: create().also { registerSampler(it) }
if (uniform !is T) {
throw IllegalStateException("Existing uniform with name \"$name\" has not the expected type")
}
return uniform
}
fun uniformFloat1(name: String) = commonUniformBuffer.uniformFloat1(name)
fun uniformFloat2(name: String) = commonUniformBuffer.uniformFloat2(name)
fun uniformFloat3(name: String) = commonUniformBuffer.uniformFloat3(name)
fun uniformFloat4(name: String) = commonUniformBuffer.uniformFloat4(name)
fun uniformFloat1Array(name: String, arraySize: Int) = commonUniformBuffer.uniformFloat1Array(name, arraySize)
fun uniformFloat2Array(name: String, arraySize: Int) = commonUniformBuffer.uniformFloat2Array(name, arraySize)
fun uniformFloat3Array(name: String, arraySize: Int) = commonUniformBuffer.uniformFloat3Array(name, arraySize)
fun uniformFloat4Array(name: String, arraySize: Int) = commonUniformBuffer.uniformFloat4Array(name, arraySize)
fun uniformInt1(name: String) = commonUniformBuffer.uniformInt1(name)
fun uniformInt2(name: String) = commonUniformBuffer.uniformInt2(name)
fun uniformInt3(name: String) = commonUniformBuffer.uniformInt3(name)
fun uniformInt4(name: String) = commonUniformBuffer.uniformInt4(name)
fun uniformInt1Array(name: String, arraySize: Int) = commonUniformBuffer.uniformInt1Array(name, arraySize)
fun uniformInt2Array(name: String, arraySize: Int) = commonUniformBuffer.uniformInt2Array(name, arraySize)
fun uniformInt3Array(name: String, arraySize: Int) = commonUniformBuffer.uniformInt3Array(name, arraySize)
fun uniformInt4Array(name: String, arraySize: Int) = commonUniformBuffer.uniformInt4Array(name, arraySize)
fun uniformMat2(name: String) = commonUniformBuffer.uniformMat2(name)
fun uniformMat3(name: String) = commonUniformBuffer.uniformMat3(name)
fun uniformMat4(name: String) = commonUniformBuffer.uniformMat4(name)
fun uniformMat2Array(name: String, arraySize: Int) = commonUniformBuffer.uniformMat2Array(name, arraySize)
fun uniformMat3Array(name: String, arraySize: Int) = commonUniformBuffer.uniformMat3Array(name, arraySize)
fun uniformMat4Array(name: String, arraySize: Int) = commonUniformBuffer.uniformMat4Array(name, arraySize)
fun texture1d(name: String) = getOrCreateSampler(name) { KslUniform(KslVar(name, KslTypeColorSampler1d, false)) }
fun texture2d(name: String) = getOrCreateSampler(name) { KslUniform(KslVar(name, KslTypeColorSampler2d, false)) }
fun texture3d(name: String) = getOrCreateSampler(name) { KslUniform(KslVar(name, KslTypeColorSampler3d, false)) }
fun textureCube(name: String) = getOrCreateSampler(name) { KslUniform(KslVar(name, KslTypeColorSamplerCube, false)) }
fun depthTexture2d(name: String) = getOrCreateSampler(name) { KslUniform(KslVar(name, KslTypeDepthSampler2d, false)) }
fun depthTextureCube(name: String) = getOrCreateSampler(name) { KslUniform(KslVar(name, KslTypeDepthSamplerCube, false)) }
// arrays of textures (this is different to array textures, like, e.g., KslTypeColorSampler2dArray)
fun textureArray1d(name: String, arraySize: Int) = getOrCreateSampler(name) { KslUniformArray(KslArrayGeneric(name, KslTypeColorSampler1d, arraySize, false)) }
fun textureArray2d(name: String, arraySize: Int) = getOrCreateSampler(name) { KslUniformArray(KslArrayGeneric(name, KslTypeColorSampler2d, arraySize, false)) }
fun textureArray3d(name: String, arraySize: Int) = getOrCreateSampler(name) { KslUniformArray(KslArrayGeneric(name, KslTypeColorSampler3d, arraySize, false)) }
fun textureArrayCube(name: String, arraySize: Int) = getOrCreateSampler(name) { KslUniformArray(KslArrayGeneric(name, KslTypeColorSamplerCube, arraySize, false)) }
// arrays of depth textures (this is different to array textures, like, e.g., KslTypeDepthSampler2dArray)
fun depthTextureArray2d(name: String, arraySize: Int) = getOrCreateSampler(name) { KslUniformArray(KslArrayGeneric(name, KslTypeDepthSampler2d, arraySize, false)) }
fun depthTextureArrayCube(name: String, arraySize: Int) = getOrCreateSampler(name) { KslUniformArray(KslArrayGeneric(name, KslTypeDepthSamplerCube, arraySize, false)) }
private fun registerInterStageVar(interStageVar: KslInterStageVar<*>) {
stages.forEach { it.interStageVars += interStageVar }
vertexStage.globalScope.definedStates += interStageVar.input
fragmentStage.globalScope.definedStates += interStageVar.output
}
private fun <S> interStageScalar(type: S, interpolation: KslInterStageInterpolation, name: String):
KslInterStageScalar<S> where S: KslType, S: KslScalar {
val input = KslVarScalar(name, type, true)
val output = KslVarScalar(name, type, false)
return KslInterStageScalar(input, output, KslShaderStageType.VertexShader, interpolation).also { registerInterStageVar(it) }
}
private fun <V, S> interStageVector(type: V, interpolation: KslInterStageInterpolation, name: String):
KslInterStageVector<V, S> where V: KslType, V: KslVector<S>, S: KslType, S: KslScalar {
val input = KslVarVector(name, type, true)
val output = KslVarVector(name, type, false)
return KslInterStageVector(input, output, KslShaderStageType.VertexShader, interpolation).also { registerInterStageVar(it) }
}
fun interStageFloat1(name: String? = null, interpolation: KslInterStageInterpolation = KslInterStageInterpolation.Smooth) =
interStageScalar(KslTypeFloat1, interpolation, name ?: nextName("interStageF1"))
fun interStageFloat2(name: String? = null, interpolation: KslInterStageInterpolation = KslInterStageInterpolation.Smooth) =
interStageVector(KslTypeFloat2, interpolation, name ?: nextName("interStageF2"))
fun interStageFloat3(name: String? = null, interpolation: KslInterStageInterpolation = KslInterStageInterpolation.Smooth) =
interStageVector(KslTypeFloat3, interpolation, name ?: nextName("interStageF3"))
fun interStageFloat4(name: String? = null, interpolation: KslInterStageInterpolation = KslInterStageInterpolation.Smooth) =
interStageVector(KslTypeFloat4, interpolation, name ?: nextName("interStageF4"))
fun interStageInt1(name: String? = null) = interStageScalar(KslTypeInt1, KslInterStageInterpolation.Flat, name ?: nextName("interStageI1"))
fun interStageInt2(name: String? = null) = interStageVector(KslTypeInt2, KslInterStageInterpolation.Flat, name ?: nextName("interStageI2"))
fun interStageInt3(name: String? = null) = interStageVector(KslTypeInt3, KslInterStageInterpolation.Flat, name ?: nextName("interStageI3"))
fun interStageInt4(name: String? = null) = interStageVector(KslTypeInt4, KslInterStageInterpolation.Flat, name ?: nextName("interStageI4"))
private fun <S> interStageScalarArray(type: S, arraySize: Int, interpolation: KslInterStageInterpolation, name: String):
KslInterStageScalarArray<S> where S: KslType, S: KslScalar {
val input = KslArrayScalar(name, type, arraySize, true)
val output = KslArrayScalar(name, type, arraySize, false)
return KslInterStageScalarArray(input, output, KslShaderStageType.VertexShader, interpolation).also { registerInterStageVar(it) }
}
private fun <V, S> interStageVectorArray(type: V, arraySize: Int, interpolation: KslInterStageInterpolation, name: String):
KslInterStageVectorArray<V, S> where V: KslType, V: KslVector<S>, S: KslType, S: KslScalar {
val input = KslArrayVector(name, type, arraySize, true)
val output = KslArrayVector(name, type, arraySize, false)
return KslInterStageVectorArray(input, output, KslShaderStageType.VertexShader, interpolation).also { registerInterStageVar(it) }
}
fun interStageFloat1Array(arraySize: Int, name: String? = null, interpolation: KslInterStageInterpolation = KslInterStageInterpolation.Smooth) =
interStageScalarArray(KslTypeFloat1, arraySize, interpolation, name ?: nextName("interStageF1Array"))
fun interStageFloat2Array(arraySize: Int, name: String? = null, interpolation: KslInterStageInterpolation = KslInterStageInterpolation.Smooth) =
interStageVectorArray(KslTypeFloat2, arraySize, interpolation, name ?: nextName("interStageF2Array"))
fun interStageFloat3Array(arraySize: Int, name: String? = null, interpolation: KslInterStageInterpolation = KslInterStageInterpolation.Smooth) =
interStageVectorArray(KslTypeFloat3, arraySize, interpolation, name ?: nextName("interStageF3Array"))
fun interStageFloat4Array(arraySize: Int, name: String? = null, interpolation: KslInterStageInterpolation = KslInterStageInterpolation.Smooth) =
interStageVectorArray(KslTypeFloat4, arraySize, interpolation, name ?: nextName("interStageF4Array"))
fun interStageInt1Array(arraySize: Int, name: String? = null) =
interStageScalarArray(KslTypeInt1, arraySize, KslInterStageInterpolation.Flat, name ?: nextName("interStageI1Array"))
fun interStageInt2Array(arraySize: Int, name: String? = null) =
interStageVectorArray(KslTypeInt2, arraySize, KslInterStageInterpolation.Flat, name ?: nextName("interStageI2Array"))
fun interStageInt3Array(arraySize: Int, name: String? = null) =
interStageVectorArray(KslTypeInt3, arraySize, KslInterStageInterpolation.Flat, name ?: nextName("interStageI3Array"))
fun interStageInt4Array(arraySize: Int, name: String? = null) =
interStageVectorArray(KslTypeInt4, arraySize, KslInterStageInterpolation.Flat, name ?: nextName("interStageI4Array"))
fun prepareGenerate() {
if (!isPrepared) {
isPrepared = true
stages.forEach { it.prepareGenerate() }
// remove unused uniforms
uniformBuffers.filter { !it.isShared }.forEach {
it.uniforms.values.retainAll { u -> vertexStage.dependsOn(u) || fragmentStage.dependsOn(u) }
}
uniformBuffers.removeAll { it.uniforms.isEmpty() }
// remove unused texture samplers
uniformSamplers.values.retainAll { u -> vertexStage.dependsOn(u) || fragmentStage.dependsOn(u) }
}
}
} | 9 | null | 7 | 78 | 2aeb035ab84e4c660bc11f5167a7f485b4a86da8 | 11,898 | kool | Apache License 2.0 |
JavaFx/src/main/kotlin/io/github/slupik/schemablock/javafx/element/fx/port/holder/PortAccessibility.kt | Slupik | 151,474,227 | false | null | package io.github.slupik.schemablock.javafx.element.fx.port.holder
/**
* All rights reserved & copyright ©
*/
enum class PortAccessibility constructor(
val target: Boolean,
val source: Boolean
) {
TWO_WAY(true, true),
ONLY_SOURCE(false, true),
ONLY_TARGET(true, false),
CONDITIONAL_INPUT(true, true);
} | 1 | null | 1 | 1 | dbcac4d6a9a3ee94710094e8312970b61f3db6f2 | 329 | SchemaBlock | Apache License 2.0 |
mobile_app1/module346/src/main/java/module346packageKt0/Foo1033.kt | uber-common | 294,831,672 | false | null | package module346packageKt0;
annotation class Foo1033Fancy
@Foo1033Fancy
class Foo1033 {
fun foo0(){
module346packageKt0.Foo1032().foo5()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 301 | android-build-eval | Apache License 2.0 |
dbinspector/src/main/kotlin/com/infinum/dbinspector/data/models/local/cursor/output/QueryResult.kt | infinum | 17,116,181 | false | null | package com.infinum.dbinspector.data.models.local.cursor.output
internal data class QueryResult(
val rows: List<Row>,
val nextPage: Int? = null,
val beforeCount: Int = 0,
val afterCount: Int = 0
)
| 0 | Kotlin | 93 | 936 | 10b9ac5013ca01e602976a615e754dff7001f11d | 214 | android_dbinspector | Apache License 2.0 |
demo/src/main/java/de/check24/compose/demo/features/email/AndroidUIEmailActivity.kt | check24-profis | 469,706,312 | false | null | package de.check24.compose.demo.features.email
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import de.check24.compose.demo.R
class AndroidUIEmailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.email)
supportActionBar?.title = "Email"
}
} | 0 | Kotlin | 3 | 11 | abd64a7d2edac0dbedb4d67d3c0f7b49d9173b88 | 397 | jetpack-compose-is-like-android-view | MIT License |
app/src/main/java/com/chungha/mqtt_manager/MainViewModel.kt | hoangchungk53qx1 | 720,692,273 | false | {"Kotlin": 28572} | /*
* MIT License
*
* Copyright (c) 2023 Hoangchungk53qx1
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.chungha.mqtt_manager
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.chungha.mqttworker.MqttManager
import com.chungha.mqttworker.domain.MqttClientOptions
import com.chungha.mqttworker.domain.Topic
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import timber.log.Timber
class MainViewModel : ViewModel() {
init {
MqttManager.messageState
.onEach {
Timber.tag(TAG).d("MessageState > ${it.message}")
}.launchIn(viewModelScope)
MqttManager.connectStatusState
.onEach {
Timber.tag(TAG).d("StatusConnect > ${it.name}")
}.launchIn(viewModelScope)
}
fun connectFirstTimes(
context: Context,
host: String,
userName: String,
password: String
) {
MqttManager.connect(
context = context,
options = MqttClientOptions(
username = userName,
passwords = password,
host = host,
topics = listOf(Topic("firstTopic", Topic.Qos.QOS_2))
)
)
}
fun subscribeTopic(topic: String) {
MqttManager.subscribeListTopic(
topics = listOf(element = Topic(topic = topic, qos = Topic.Qos.QOS_2))
)
}
companion object {
private const val TAG = "MainViewModel"
}
} | 9 | Kotlin | 0 | 4 | f35c5a4450166449df29b5d820800197da3d8bae | 2,603 | mqtt-manager | The Unlicense |
buildSrc/src/main/kotlin/Libs.kt | kobil-systems | 366,416,084 | true | {"Kotlin": 46861} | object Libs {
const val kotlinVersion = "1.4.31"
const val org = "io.kotest.extensions"
object Kotest {
private const val version = "4.4.3"
const val assertionsShared = "io.kotest:kotest-assertions-shared:$version"
const val assertionsCore = "io.kotest:kotest-assertions-core:$version"
const val api = "io.kotest:kotest-framework-api:$version"
const val junit5 = "io.kotest:kotest-runner-junit5-jvm:$version"
}
object Arrow {
private const val version = "0.13.1"
const val core = "io.arrow-kt:arrow-core:$version"
const val fx = "io.arrow-kt:arrow-fx-coroutines:$version"
}
}
| 0 | null | 0 | 0 | 8cbb77bf566374bd4ff9f4b3f7cc9eefef33e1cd | 645 | kotest-assertions-arrow | Apache License 2.0 |
api/src/main/kotlin/com/spothero/rates/api/util/RatesLoader.kt | atholbro | 463,315,697 | false | null | package com.spothero.rates.api.util
import com.github.michaelbull.result.Result
import com.github.michaelbull.result.andThen
import com.github.michaelbull.result.mapError
import com.github.michaelbull.result.runCatching
import com.spothero.rates.api.model.ApiRates
import kotlinx.serialization.SerializationException
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import java.io.IOException
import java.io.InputStream
sealed class RatesError(val cause: Throwable) {
override fun toString(): String = cause.localizedMessage
companion object
}
class RatesGenericError(exception: Throwable) : RatesError(exception)
class RatesIoError(exception: IOException) : RatesError(exception)
class RatesJsonError(exception: SerializationException) : RatesError(exception)
fun RatesError.Companion.mapThrowable(ex: Throwable): RatesError = when (ex) {
is IOException -> RatesIoError(ex)
is SerializationException -> RatesJsonError(ex)
else -> RatesGenericError(ex)
}
fun parseRates(inputStream: InputStream): Result<ApiRates, RatesError> =
runCatching { inputStream.bufferedReader().readText() }
.mapError { RatesError.mapThrowable(it) }
.andThen { parseRates(it) }
fun parseRates(json: String): Result<ApiRates, RatesError> =
runCatching { Json.decodeFromString<ApiRates>(json) }
.mapError { RatesError.mapThrowable(it) }
| 0 | Kotlin | 0 | 0 | 7623b2918671d34328ceab7f0f36979d66a80ade | 1,405 | rates-service | MIT License |
app/src/main/java/com/patrikagroup/features/chat/presentation/AddNewMsgFragment.kt | DebashisINT | 523,714,623 | false | null | package com.patrikagroup.features.chat.presentation
import android.content.Context
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.patrikagroup.R
import com.patrikagroup.app.NetworkConstant
import com.patrikagroup.app.Pref
import com.patrikagroup.app.SearchListener
import com.patrikagroup.app.types.FragType
import com.patrikagroup.app.utils.AppUtils
import com.patrikagroup.base.BaseResponse
import com.patrikagroup.base.presentation.BaseActivity
import com.patrikagroup.base.presentation.BaseFragment
import com.patrikagroup.features.chat.api.ChatRepoProvider
import com.patrikagroup.features.chat.model.GroupUserDataModel
import com.patrikagroup.features.chat.model.GroupUserResponseModel
import com.patrikagroup.features.dashboard.presentation.DashboardActivity
import com.patrikagroup.widgets.AppCustomTextView
import com.elvishew.xlog.XLog
import com.pnikosis.materialishprogress.ProgressWheel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class AddNewMsgFragment : BaseFragment() {
private lateinit var mContext: Context
private lateinit var progress_wheel: ProgressWheel
private lateinit var tv_no_data: AppCustomTextView
private lateinit var rv_user_list: RecyclerView
private lateinit var rl_add_new_msg: RelativeLayout
private var groupUserList: ArrayList<GroupUserDataModel>?= null
private var grpUserAdapter: GroupUserListAdapter?= null
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val view = inflater.inflate(R.layout.fragment_add_new_msg, container, false)
initView(view)
getChatUserListApi()
(mContext as DashboardActivity).setSearchListener(object : SearchListener {
override fun onSearchQueryListener(query: String) {
if (query.isBlank()) {
grpUserAdapter?.refreshList(groupUserList!!)
} else {
grpUserAdapter?.filter?.filter(query)
}
}
})
return view
}
private fun initView(view: View) {
view.apply {
progress_wheel = findViewById(R.id.progress_wheel)
tv_no_data = findViewById(R.id.tv_no_data)
rv_user_list = findViewById(R.id.rv_user_list)
rl_add_new_msg = findViewById(R.id.rl_add_new_msg)
}
progress_wheel.stopSpinning()
rv_user_list.layoutManager = LinearLayoutManager(mContext)
rl_add_new_msg.setOnClickListener(null)
}
private fun getChatUserListApi() {
if (!AppUtils.isOnline(mContext)) {
(mContext as DashboardActivity).showSnackMessage(getString(R.string.no_internet))
return
}
progress_wheel.spin()
val repository = ChatRepoProvider.provideChatRepository()
BaseActivity.compositeDisposable.add(
repository.getGroupUserList()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val response = result as GroupUserResponseModel
XLog.d("Get Group User List STATUS: " + response.status)
if (response.status == NetworkConstant.SUCCESS) {
progress_wheel.stopSpinning()
tv_no_data.visibility = View.GONE
groupUserList = response.group_user_list
setAdapter()
}
else {
progress_wheel.stopSpinning()
(mContext as DashboardActivity).showSnackMessage(response.message!!)
}
}, { error ->
error.printStackTrace()
progress_wheel.stopSpinning()
if (error != null)
XLog.d("Get Group User List ERROR: " + error.localizedMessage)
(mContext as DashboardActivity).showSnackMessage(getString(R.string.something_went_wrong))
})
)
}
private fun setAdapter() {
grpUserAdapter = GroupUserListAdapter(mContext, groupUserList) {
(mContext as DashboardActivity).apply {
newUserModel = it
isRefreshChatUserList = true
onBackPressed()
}
}
rv_user_list.adapter = grpUserAdapter
}
} | 0 | Kotlin | 0 | 0 | 5e066704a07f4438fb1f753f3a314bf3807f1c96 | 5,105 | PatrikaGroup | Apache License 2.0 |
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/behavior/InternalLayerable.kt | Hexworks | 94,116,947 | false | null | package org.hexworks.zircon.internal.behavior
import org.hexworks.cobalt.databinding.api.collection.ObservableList
import org.hexworks.zircon.api.behavior.Layerable
import org.hexworks.zircon.api.graphics.Layer
import org.hexworks.zircon.internal.graphics.InternalLayer
interface InternalLayerable : Layerable, RenderableContainer {
override val layers: ObservableList<out InternalLayer>
fun removeLayer(layer: Layer): Boolean
}
| 42 | null | 138 | 738 | 55a0ccc19a3f1b80aecd5f1fbe859db94ba9c0c6 | 441 | zircon | Apache License 2.0 |
common/src/main/java/jp/co/soramitsu/common/data/network/nomis/NomisResponse.kt | soramitsu | 278,060,397 | false | {"Kotlin": 5738459, "Java": 18796} | package jp.co.soramitsu.common.data.network.nomis
import com.google.gson.annotations.SerializedName
data class NomisResponse(
val data: NomisResponseData
)
data class NomisResponseData(
val address: String,
val score: Double,
val stats: NomisStats
)
data class NomisStats(
val nativeBalanceUSD: Double,
val holdTokensBalanceUSD: Double,
@SerializedName("walletAge")
val walletAgeInMonths: Long,
val totalTransactions: Long,
val totalRejectedTransactions: Long,
@SerializedName("averageTransactionTime")
val averageTransactionTimeInHours: Double,
@SerializedName("maxTransactionTime")
val maxTransactionTimeInHours: Double,
@SerializedName("minTransactionTime")
val minTransactionTimeInHours: Double,
val scoredAt: String
)
| 15 | Kotlin | 30 | 89 | 1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2 | 795 | fearless-Android | Apache License 2.0 |
examples/src/main/kotlin/org/dashj/platform/examples/CreateWallets.kt | dashpay | 258,569,335 | false | null | /**
* Copyright (c) 2020-present, Dash Core Group
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package org.dashevo.examples
import org.bitcoinj.core.Address
import org.bitcoinj.core.Coin
import org.bitcoinj.core.Transaction
import org.bitcoinj.core.TransactionOutput
import org.bitcoinj.evolution.CreditFundingTransaction
import org.bitcoinj.params.EvoNetParams
import org.bitcoinj.params.MobileDevNetParams
import org.bitcoinj.params.TestNet3Params
import org.bitcoinj.utils.BriefLogFormatter
import org.bitcoinj.wallet.AuthenticationKeyChain
import org.bitcoinj.wallet.CoinSelection
import org.bitcoinj.wallet.CoinSelector
import org.bitcoinj.wallet.DeterministicKeyChain
import org.bitcoinj.wallet.DeterministicSeed
import org.bitcoinj.wallet.KeyChain
import org.bitcoinj.wallet.KeyChainGroup
import org.bitcoinj.wallet.SendRequest
import org.bitcoinj.wallet.Wallet
import org.dashevo.Client
import org.dashevo.dashpay.BlockchainIdentity
import org.dashevo.dpp.identity.Identity
import org.dashevo.dpp.util.HashUtils
import java.io.File
import java.io.IOException
import java.security.SecureRandom
import java.util.*
import java.util.concurrent.TimeUnit
import org.bitcoinj.wallet.WalletTransaction
import org.dashevo.dashpay.ContactRequests
import org.dashevo.dashpay.RetryDelayType
import org.dashevo.dashpay.callback.*
import org.dashevo.dpp.document.Document
import org.dashevo.dpp.identifier.Identifier
import org.dashevo.dpp.toHexString
import org.dashevo.platform.DomainDocument
import org.json.JSONObject
fun String.runCommand(workingDir: File): String? {
return try {
val parts = this.split("\\s".toRegex())
val proc = ProcessBuilder(*parts.toTypedArray())
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
proc.waitFor(60, TimeUnit.MINUTES)
proc.inputStream.bufferedReader().readText()
} catch (e: IOException) {
e.printStackTrace()
null
}
}
class CreateWallets {
companion object {
lateinit var sdk: Client
private val PARAMS = EvoNetParams.get()
var configurationFile: String = ""
var network: String = ""
var contact: String = ""
/**
* The first argument must be the location of the configuration file that must include
* rpcuser, rpcuserpassword and server=1
*/
@JvmStatic
fun main(args: Array<String>) {
BriefLogFormatter.initWithSilentBitcoinJ()
if (args.size >= 2) {
network = args[0]
configurationFile = args[1]
contact = args[2]
sdk = Client(network)
println("------------------------------------------------")
println("CreateWallets($network: $configurationFile)")
println()
createWallets()
} else {
println("CreateWallets.kt\nThe first argument is the network and the second must be the path to the .conf file for the devnet\ndash-cli must be in your path")
}
}
private fun runRpc(command: String): String? {
val command = "dash-cli -conf=$configurationFile $command"
return command.runCommand(File("."))
}
private fun createWallets() {
val scanner = Scanner(System.`in`)
val platform = sdk.platform
sdk.isReady()
val secureRandom = SecureRandom()
val addresses = arrayListOf<Address>()
val recoveryPhrases = arrayListOf<String>()
val namesMap = HashMap<String, String>()
var namesToCreate = arrayListOf<String>()
println("Enter the usernames to create (one name per line, `quit` to end the list) ")
var input = scanner.next()
while (input != "quit") {
if (input.length >= 3) {
namesToCreate.add(input)
}
input = scanner.next()
if (input == "quit")
break
}
val total = namesToCreate.size
println("Wallet, Recovery Phrase, First Address")
for (i in 0 until total) {
var entropy = ByteArray(16)
secureRandom.nextBytes(entropy)
entropy = entropy.copyOfRange(0, DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8)
val chain = DeterministicKeyChain.builder().entropy(entropy, Date().time / 1000)
.accountPath(DeterministicKeyChain.BIP44_ACCOUNT_ZERO_PATH_TESTNET).build()
val receiveKey = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS)
val address = Address.fromKey(PARAMS, receiveKey)
addresses.add(address)
val recoveryPhrase = chain.seed!!.mnemonicCode!!.joinToString(" ")
recoveryPhrases.add(recoveryPhrase)
println(
"processing ${i + 1} ${namesToCreate[i]}, $recoveryPhrase, $address"
)
// fund the wallet
val txid = runRpc("sendtoaddress $address 0.05")!!.trim()
if (txid.isEmpty()) {
println("sendtoaddress failed: Is the $network daemon running?")
return
} else {
println("Wallet funding transaction: $txid")
}
// get tx information
val txBytes = runRpc("getrawtransaction $txid")!!.trim()
println(txBytes)
val walletTx = Transaction(PARAMS, HashUtils.fromHex(txBytes))
//create the wallet
val keyChainGroup = KeyChainGroup.builder(PARAMS).addChain(chain).build()
val wallet = Wallet(PARAMS, keyChainGroup)
wallet.initializeAuthenticationKeyChains(wallet.keyChainSeed, null)
wallet.addWalletTransaction(WalletTransaction(WalletTransaction.Pool.UNSPENT, walletTx))
// send the credit funding transaction
val sendRequest = SendRequest.creditFundingTransaction(
PARAMS,
wallet.currentAuthenticationKey(AuthenticationKeyChain.KeyChainType.BLOCKCHAIN_IDENTITY_FUNDING),
Coin.valueOf(1000000)
)
sendRequest.coinSelector = CoinSelector { target, candidates ->
val selected = ArrayList<TransactionOutput>()
val sortedOutputs = ArrayList(candidates)
var total: Long = 0
for (output in sortedOutputs) {
if (total >= target.value) break
selected.add(output)
total += output.value.value
}
CoinSelection(Coin.valueOf(total), selected)
}
val cftx = wallet.sendCoinsOffline(sendRequest) as CreditFundingTransaction
val cftxid = runRpc("sendrawtransaction ${cftx.bitcoinSerialize().toHexString()}")
println("credit funding tx: ${cftx.txId}")
println("credit funding tx sent via rpc: $cftxid")
println("identity id: ${cftx.creditBurnIdentityIdentifier.toStringBase58()}")
println("pubkey hash: ${cftx.creditBurnPublicKeyId}")
// we need to wait until the transaction is confirmed or instantsend
val transaction = runRpc("getrawtransaction ${cftxid!!.trim()} true")
val status = JSONObject(transaction).toMap()
Thread.sleep(5000)
val blockchainIdentity = BlockchainIdentity(platform, cftx, wallet)
blockchainIdentity.registerIdentity(null)
blockchainIdentity.watchIdentity(10, 5000, RetryDelayType.SLOW20, object : RegisterIdentityCallback {
override fun onComplete(uniqueId: String) {
val identityId = platform.client.getIdentityIdByFirstPublicKey(wallet.currentAuthenticationKey(AuthenticationKeyChain.KeyChainType.BLOCKCHAIN_IDENTITY).pubKeyHash)
println("identity found using getIdentityIdByFirstPublicKey: ${identityId}")
blockchainIdentity.addUsername(namesToCreate[i])
val names = blockchainIdentity.getUnregisteredUsernames()
blockchainIdentity.registerPreorderedSaltedDomainHashesForUsernames(names, null)
val set =
blockchainIdentity.getUsernamesWithStatus(BlockchainIdentity.UsernameStatus.PREORDER_REGISTRATION_PENDING)
val saltedDomainHashes = blockchainIdentity.saltedDomainHashesForUsernames(set)
blockchainIdentity.watchPreorder(
saltedDomainHashes,
10,
5000,
RetryDelayType.SLOW20,
object : RegisterPreorderCallback {
override fun onComplete(names: List<String>) {
Thread.sleep(5000)
val preorderedNames = blockchainIdentity.preorderedUsernames()
blockchainIdentity.registerUsernameDomainsForUsernames(preorderedNames, null)
blockchainIdentity.watchUsernames(
preorderedNames,
10,
5000,
RetryDelayType.SLOW20,
object : RegisterNameCallback {
override fun onComplete(names: List<String>) {
println("name registration successful $names")
namesMap[names[0]] = recoveryPhrase
createProfile(blockchainIdentity)
}
override fun onTimeout(incompleteNames: List<String>) {
println("name registration failed $incompleteNames")
}
})
}
override fun onTimeout(incompleteNames: List<String>) {
println("preorder registration failed $incompleteNames")
}
})
}
override fun onTimeout() {
println("Identity registration failed")
}
})
}
// print usernames and associated recovery phrases
println("\nUsername, Recovery Phrase")
for (name in namesMap) {
println("${name.key}, ${name.value}")
}
}
private fun displayNameFromUsername(blockchainIdentity: BlockchainIdentity): String {
val username = blockchainIdentity.currentUsername!!
return if (username.length > 20) {
username.substring(0, 20)
} else {
username
}
}
private fun createProfile(blockchainIdentity: BlockchainIdentity) {
blockchainIdentity.registerProfile(
displayNameFromUsername(blockchainIdentity).toUpperCase(),
"My identity is ${blockchainIdentity.uniqueIdString}.",
null, null, null, null
)
val profile = blockchainIdentity.watchProfile(10, 1000, RetryDelayType.SLOW20, object : UpdateProfileCallback {
override fun onComplete(uniqueId: String, profileDocument: Document) {
println("profile created successfully")
println(profileDocument.toJSON())
blockchainIdentity.updateProfile(
displayNameFromUsername(blockchainIdentity),
"My identity is still ${blockchainIdentity.uniqueIdString}.",
null, null, null, null
)
blockchainIdentity.watchProfile(10, 1000, RetryDelayType.SLOW20, object : UpdateProfileCallback {
override fun onComplete(uniqueId: String, updatedProfileDocument: Document) {
println("profile updated successfully")
println(updatedProfileDocument.toJSON())
sendContactRequest(blockchainIdentity)
}
override fun onTimeout() {
println("update profile failed") }
})
}
override fun onTimeout() {
println("create profile failed")
}
})
}
fun sendContactRequest(blockchainIdentity: BlockchainIdentity) {
if (contact.isNotEmpty()) {
val nameDocument = sdk.platform.names.get(contact)
if (nameDocument != null) {
val domainDocument = DomainDocument(nameDocument)
val identity = sdk.platform.identities.get(domainDocument.dashUniqueIdentityId!!)
val cr = ContactRequests(sdk.platform)
cr.create(blockchainIdentity, identity!!, null)
cr.watchContactRequest(blockchainIdentity.uniqueIdentifier, identity.id, 10, 1000, RetryDelayType.SLOW20,
object: SendContactRequestCallback {
override fun onComplete(fromUser: Identifier, toUser: Identifier) {
println("Contact Request Sent $fromUser->$toUser")
}
override fun onTimeout(fromUser: Identifier, toUser: Identifier) {
println("Contact Request Sent $fromUser->$toUser")
}
})
}
}
}
}
} | 1 | null | 4 | 6 | e56804ff06462994b31309db718c838cf6e77f9d | 14,711 | android-dashpay | MIT License |
telegram/src/main/kotlin/me/ivmg/telegram/entities/CallbackQuery.kt | seven332 | 284,789,498 | false | null | package me.ivmg.telegram.entities
import com.google.gson.annotations.SerializedName as Name
data class CallbackQuery(
val id: String,
val from: User,
val message: Message? = null,
@Name("inline_message_id") val inlineMessageId: String? = null,
val data: String
)
| 0 | null | 0 | 1 | 92f6ab6f96589380f5fba6a0259379b256532c55 | 285 | kotlin-telegram-bot | Apache License 2.0 |
app/src/main/java/com/imn/ivisusample/utils/FileUtils.kt | ImnIrdst | 308,376,567 | false | null | package com.imn.ivisusample.utils
import android.content.Context
import androidx.core.net.toUri
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DataSpec
import com.google.android.exoplayer2.upstream.FileDataSource
import java.io.File
const val WAVE_HEADER_SIZE = 44
val Context.recordFile: File
get() = File(filesDir, "rec.wav")
fun File.toMediaSource(): MediaSource =
DataSpec(this.toUri())
.let { FileDataSource().apply { open(it) } }
.let { DataSource.Factory { it } }
.let { ProgressiveMediaSource.Factory(it, DefaultExtractorsFactory()) }
.createMediaSource(MediaItem.fromUri(this.toUri())) | 13 | null | 13 | 98 | 57a025751bbe79b643e622d4e550d4a28ffc206c | 938 | iiVisu | MIT License |
app/src/main/java/com/elementary/tasks/reminder/build/formatter/AttachmentsFormatter.kt | naz013 | 165,067,747 | false | {"Kotlin": 2971145, "HTML": 20925} | package com.elementary.tasks.reminder.build.formatter
import android.content.Context
import com.elementary.tasks.R
class AttachmentsFormatter(
private val context: Context
) : Formatter<List<String>>() {
override fun format(attachments: List<String>): String {
return if (attachments.isEmpty()) {
context.getString(R.string.builder_no_attachments)
} else {
context.resources.getQuantityString(
R.plurals.x_attachments,
attachments.size,
attachments.size
)
}
}
}
| 0 | Kotlin | 3 | 6 | a6eecfda739be05a4b84e7d47284cd9e2bc782d6 | 525 | reminder-kotlin | Apache License 2.0 |
app/src/main/java/com/imnidasoftware/numberpick/domain/usecases/GetGameSettingsUseCase.kt | Lastlilith | 445,097,126 | false | {"Kotlin": 25758} | package com.imnidasoftware.numberpick.domain.usecases
import com.imnidasoftware.numberpick.domain.entities.GameSettings
import com.imnidasoftware.numberpick.domain.entities.Level
import com.imnidasoftware.numberpick.domain.repository.GameRepository
class GetGameSettingsUseCase(
private val repository: GameRepository
) {
operator fun invoke(level: Level): GameSettings {
return repository.getGameSettings(level)
}
} | 0 | Kotlin | 1 | 5 | 508a432804970931b0edee8395ccc3981b817317 | 439 | CompositionGame | MIT License |
app/src/test/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksViewModelTest.kt | calixtocarolina | 607,315,998 | false | null | package com.example.android.architecture.blueprints.todoapp.tasks
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class TasksViewModelTest {
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
@Test
fun setFilterAllTasks_tasksAddViewVisible() {
// Given a fresh ViewModel
val tasksViewModel = TasksViewModel(ApplicationProvider.getApplicationContext())
// When the filter type is ALL_TASKS
tasksViewModel.setFiltering(TasksFilterType.ALL_TASKS)
// Then the "Add task" action is visible
assertThat(tasksViewModel.tasksAddViewVisible.getOrAwaitValue(), `is`(true))
}
} | 0 | Kotlin | 0 | 0 | ceae7820c79622d6b3ddfde22b74f51e8948f548 | 970 | android-testing | Apache License 2.0 |
app/src/main/java/org/zimmob/zimlx/popup/MainItemView.kt | kknet | 148,614,445 | true | {"Java Properties": 3, "Markdown": 11, "Gradle": 5, "Shell": 1, "YAML": 1, "Batchfile": 1, "Text": 1, "Ignore List": 4, "Proguard": 3, "XML": 308, "Kotlin": 49, "Java": 371, "AIDL": 3, "Protocol Buffer": 2} | package org.zimmob.zimlx.popup
import android.animation.Animator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import org.zimmob.zimlx.R
import org.zimmob.zimlx.Utilities
import org.zimmob.zimlx.anim.PillHeightRevealOutlineProvider
class MainItemView(context: Context, attrs: AttributeSet?, defStyle: Int) : PopupItemView(context, attrs, defStyle) {
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
lateinit var itemContainer: LinearLayout
override fun onFinishInflate() {
super.onFinishInflate()
itemContainer = findViewById(R.id.popup_items)
}
override fun getArrowColor(isArrowAttachedToBottom: Boolean): Int {
return Utilities.resolveAttributeData(context, R.attr.popupColorPrimary)
}
override fun addView(child: View?) {
if (child is PopupItemView)
itemContainer.addView(child)
else
super.addView(child)
}
override fun removeAllViews() {
itemContainer.removeAllViews()
}
fun animateHeightRemoval(heightToRemove: Int, reverse: Boolean): Animator {
val newHeight = height - heightToRemove
return PillHeightRevealOutlineProvider(mPillRect,
backgroundRadius, newHeight, reverse).createRevealAnimator(this, true, false, true)
}
override fun getBackgroundRadius(): Float {
return resources.getDimensionPixelSize(mTheme.backgroundRadius).toFloat()
}
} | 0 | Java | 0 | 0 | 19ff807f1346b389e42e6b81a2b246b6273ee180 | 1,593 | ZimLX | Apache License 2.0 |
server/src/test/kotlin/com/github/vyadh/teamcity/deploys/buildparams/ObfuscatedParameterExtractorTest.kt | vyadh | 160,056,917 | false | null | package com.github.vyadh.teamcity.deploys.buildparams
import com.github.vyadh.teamcity.deploys.processing.BuildMocks.buildTypeWith
import com.github.vyadh.teamcity.deploys.processing.BuildMocks.buildWith
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import jetbrains.buildServer.serverSide.parameters.types.PasswordsSearcher
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
internal class ObfuscatedParameterExtractorTest {
@Test
internal fun extractingNullValue() {
val extractor = ObfuscatedParameterExtractor(passwordsSearcher())
val build = buildWith(emptyMap())
val result = extractor.extract(build, "key") { null }
assertThat(result).isNull()
}
@Test
internal fun extractingDefaultValueWhenKeyBlank() {
val extractor = ObfuscatedParameterExtractor(passwordsSearcher())
val build = buildWith(emptyMap())
val result = extractor.extract(build, "") { "default" }
assertThat(result).isEqualTo("default")
}
@Test
internal fun noObfuscationRequired() {
val extractor = ObfuscatedParameterExtractor(passwordsSearcher("pass"))
val build = buildWith(mapOf(Pair("key", "value")))
val result = extractor.extract(build, "key") { null }
assertThat(result).isEqualTo("value")
}
@Test
internal fun obfuscationOfSecretRequired() {
val extractor = ObfuscatedParameterExtractor(passwordsSearcher("pass"))
val build = buildWith(mapOf(Pair("secret", "! mypasss !")))
val result = extractor.extract(build, "secret") { null }
assertThat(result).isEqualTo("! my******s !")
}
@Test
internal fun obfuscationOfSecretInMultiplePlaces() {
val extractor = ObfuscatedParameterExtractor(passwordsSearcher("pass"))
val build = buildWith(mapOf(Pair("secret", "! passpassopass !")))
val result = extractor.extract(build, "secret") { null }
assertThat(result).isEqualTo("! ************o****** !")
}
@Test
internal fun obfuscationOfDifferentSecrets() {
val extractor = ObfuscatedParameterExtractor(passwordsSearcher("pass", "word"))
val build = buildWith(mapOf(Pair("secret", "! password is my word pass !")))
val result = extractor.extract(build, "secret") { null }
assertThat(result).isEqualTo("! ************ is my ****** ****** !")
}
private fun buildWith(params: Map<String, String>) =
buildWith(buildTypeWith(emptyList()), "any", params)
private fun passwordsSearcher(vararg passwords: String): PasswordsSearcher {
return mock {
on { collectPasswords(any()) } doReturn setOf(*passwords)
}
}
}
| 10 | Kotlin | 5 | 21 | 4a2a73516d87b295e0010c8d55be665847aeb47b | 2,664 | teamcity-deployment-dashboard | Apache License 2.0 |
composeApp/src/commonMain/kotlin/in/procyk/shin/ui/component/EnumChooser.kt | avan1235 | 752,385,367 | false | null | package `in`.procyk.shin.ui
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import applyIf
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun <T> EnumChooser(
entries: Iterable<T>,
value: T,
onValueChange: (T) -> Unit,
presentableName: T.() -> String,
label: String? = null,
fillMaxWidth: Boolean = true,
defaultWidth: Dp = 128.dp,
) {
var expanded by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = { expanded = it },
) {
OutlinedTextField(
readOnly = true,
value = value.presentableName(),
onValueChange = {},
label = label?.let { { Text(label) } },
modifier = Modifier
.menuAnchor()
.height(64.dp)
.applyIf(fillMaxWidth) { fillMaxWidth() }
.width(defaultWidth),
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
},
singleLine = true,
shape = RoundedCornerShape(12.dp),
)
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
) {
entries.forEach { protocol ->
DropdownMenuItem(
text = {
Text(protocol.presentableName())
},
onClick = {
onValueChange(protocol)
expanded = false
},
)
}
}
}
}
| 0 | null | 1 | 1 | 766046232362018c1f126ff30640651aaed6b6ab | 1,976 | shin | MIT License |
app/src/main/java/com/navin/downloadfiletest/data/remote/Networking.kt | navinpd | 251,050,083 | false | null | package com.big.imageloader.data.remote
import com.big.imageloader.BuildConfig
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
object Networking {
lateinit var API_VAL: String
lateinit var API_HOST_VAL: String
fun createNetworking(apiVal: String, apiHost:String, baseUrl: String, cascheDir: File, cascheSize: Long): NetworkService {
API_VAL = apiVal
API_HOST_VAL = apiHost
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(
OkHttpClient.Builder()
.cache(Cache(cascheDir, cascheSize))
.addInterceptor(HttpLoggingInterceptor()
.apply {
level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
else HttpLoggingInterceptor.Level.NONE
})
.build()
)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(
NetworkService::class.java
)
}
} | 1 | null | 1 | 1 | cc3ac944c9bfdaed60a2729f3db466de88a6a390 | 1,374 | WeatherLocator | Apache License 2.0 |
daemon/src/main/kotlin/dev/krud/boost/daemon/configuration/instance/messaging/InstanceDeletedEventMessage.kt | krud-dev | 576,882,508 | false | null | package dev.krud.boost.daemon.configuration.instance.messaging
import dev.krud.boost.daemon.base.messaging.AbstractMessage
import java.util.*
class InstanceDeletedEventMessage(payload: Payload) : AbstractMessage<InstanceDeletedEventMessage.Payload>(payload) {
data class Payload(
val instanceId: UUID,
val parentApplicationId: UUID
)
} | 34 | TypeScript | 3 | 203 | a9fdbd1408a051c2744b3bd06912f727a4041fae | 361 | ostara | Apache License 2.0 |
BiryaniCooker/src/main/java/com/muzammil/biryanicooker/models/Printable.kt | MuhammadMuzammilQadri | 235,782,056 | false | null | package com.muzammil.biryanicooker.models
/**
* Created by Muzammil on 23-Jan-20.
*/
interface Printable {
fun print()
fun uuid() : String {
return hashCode().toString()
}
} | 1 | null | 1 | 1 | ffe119c3dab66af975ba81079e241facc5fdc4c4 | 201 | ExploringDagger | MIT License |
app/src/main/java/com/shicheeng/copymanga/ui/screen/main/home/HomeScreen.kt | shizheng233 | 475,870,275 | false | null | package com.shicheeng.copymanga.ui.screen.main.home
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.shicheeng.copymanga.LocalMainBottomNavigationPadding
import com.shicheeng.copymanga.R
import com.shicheeng.copymanga.data.MainTopicDataModel
import com.shicheeng.copymanga.ui.screen.compoents.ErrorScreen
import com.shicheeng.copymanga.ui.screen.compoents.LoadingScreen
import com.shicheeng.copymanga.ui.screen.compoents.PlainButton
import com.shicheeng.copymanga.util.UIState
import com.shicheeng.copymanga.util.copy
import com.shicheeng.copymanga.viewmodel.HomeViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
homeViewModel: HomeViewModel = hiltViewModel(),
onUUid: (String) -> Unit,
onSearchButtonClick: () -> Unit,
onSettingButtonClick: () -> Unit,
onRecommendHeaderLineClick: () -> Unit,
onRankHeaderLineClick: () -> Unit,
onHotHeaderLineClick: () -> Unit,
onNewestHeaderLineClick: () -> Unit,
onFinishHeaderLineClick: () -> Unit,
onTopicCardClick: (MainTopicDataModel) -> Unit,
onTopicsClickLineClick: () -> Unit,
) {
val uiState by homeViewModel.uiState.collectAsState()
if (uiState is UIState.Loading) {
LoadingScreen()
return
}
if (uiState is UIState.Error<*>) {
ErrorScreen(
errorMessage = (uiState as UIState.Error<*>).errorMessage.message
?: stringResource(id = R.string.error),
secondaryText = stringResource(id = R.string.setting),
onTry = {
homeViewModel.loadData()
},
onSecondaryClick = onSettingButtonClick
)
return
}
val successUIState = uiState as UIState.Success
val layoutDirection = LocalLayoutDirection.current
val listRank = listOf(
stringResource(id = R.string.day_rank),
stringResource(id = R.string.week_rank),
stringResource(id = R.string.month_rank)
)
var selectTabIndex by remember {
mutableIntStateOf(0)
}
val lazyListState = rememberLazyListState()
val paddingBottom = LocalMainBottomNavigationPadding.current
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
val firstVisibleItemIndex by remember {
derivedStateOf { lazyListState.firstVisibleItemIndex }
}
val firstVisibleItemScrollOffset by remember {
derivedStateOf { lazyListState.firstVisibleItemScrollOffset }
}
val animatedTitleAlpha by animateFloatAsState(
if (firstVisibleItemIndex > 0) 1f else 0f, label = "animated_title_alpha",
)
val animatedBgAlpha by animateFloatAsState(
if (firstVisibleItemIndex > 0 || firstVisibleItemScrollOffset > 0) 1f else 0f,
label = "animated_background_alpha",
)
TopAppBar(
title = {
Text(
text = stringResource(id = R.string.app_name),
modifier = Modifier.alpha(animatedTitleAlpha)
)
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(3.dp)
.copy(alpha = animatedBgAlpha)
),
actions = {
PlainButton(
id = androidx.appcompat.R.string.search_menu_title,
drawableRes = R.drawable.ic_manga_search,
onButtonClick = onSearchButtonClick
)
PlainButton(
id = R.string.setting,
drawableRes = R.drawable.ic_setting_outline,
onButtonClick = onSettingButtonClick
)
}
)
}
) { padding ->
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = padding.copy(
layoutDirection = layoutDirection,
bottom = padding.calculateBottomPadding() + paddingBottom,
top = 0.dp
),
state = lazyListState
) {
item(
key = HomeListKey.BANNER,
contentType = HomeListKey.BANNER
) {
Banner(
list = successUIState.content.listBanner,
modifier = Modifier.height(250.dp)
) { model ->
onUUid.invoke(model.uuidManga)
}
}
item(
key = HomeListKey.RECOMMEND,
contentType = HomeListKey.RECOMMEND
) {
HomeBarColumn(
title = stringResource(id = R.string.recommend),
list = successUIState.content.listRecommend,
onHeaderLineClick = onRecommendHeaderLineClick
) {
onUUid.invoke(it.pathWordManga)
}
}
miniLeaderBoard(
selectedTabIndex = selectTabIndex,
onTabClick = { index ->
selectTabIndex = index
},
rankList = listRank,
mainPageDataModel = successUIState.content,
onHeaderLineClick = onRankHeaderLineClick
) {
onUUid.invoke(it.pathWord)
}
item(
key = HomeListKey.HOT,
contentType = HomeListKey.HOT
) {
HomeBarColumn(
title = stringResource(id = R.string.hot_manga),
list = successUIState.content.listHot,
onHeaderLineClick = onHotHeaderLineClick
) {
onUUid.invoke(it.pathWordManga)
}
}
item(
key = HomeListKey.NEWEST,
contentType = HomeListKey.NEWEST
) {
HomeBarColumn(
title = stringResource(id = R.string.new_manga),
list = successUIState.content.listNewest,
onHeaderLineClick = onNewestHeaderLineClick
) {
onUUid.invoke(it.pathWordManga)
}
}
item(
key = HomeListKey.FINISH,
contentType = HomeListKey.FINISH
) {
HomeBarColumn(
title = stringResource(id = R.string.finish_manga),
list = successUIState.content.listFinished,
onHeaderLineClick = onFinishHeaderLineClick
) {
onUUid.invoke(it.pathWordManga)
}
}
item(
key = HomeListKey.TOPICS_RECOMMEND,
contentType = HomeListKey.TOPICS_RECOMMEND
) {
HomePageTopicRow(
list = successUIState.content.topicList,
onTopicBarClick = onTopicsClickLineClick,
onItemClick = onTopicCardClick
)
}
}
}
}
| 2 | Kotlin | 0 | 75 | 6e33c57d0e1b26b4c82cf7779666646ae0422917 | 8,444 | CopyMangaJava | MIT License |
centurion-schemas/src/main/kotlin/com/sksamuel/centurion/records.kt | sksamuel | 13,625,531 | false | {"Kotlin": 173545, "Java": 19565} | package com.sksamuel.centurion
data class Struct(val schema: Schema.Struct, val values: List<Any?>) {
constructor(schema: Schema.Struct, vararg values: Any?) : this(schema, values.asList())
init {
require(schema.fields.size == values.size) { "Schema size ${schema.fields.size} != values size ${values.size}" }
}
private val names by lazy { schema.fields.map { it.name } }
/**
* Return the value of the record for the given [fieldName].
* Will throw an error if the field is not defined in the schema.
*/
operator fun get(fieldName: String): Any? {
val index = names.indexOf(fieldName)
if (index < 0) error("Field $fieldName does not exist in schema $schema")
return values[index]
}
fun iterator(): Iterator<Pair<Schema.Field, Any?>> = schema.fields.zip(values).iterator()
}
class StructBuilder(val schema: Schema.Struct) {
private val values = Array<Any?>(schema.fields.size) { null }
operator fun set(fieldName: String, value: Any?) {
values[schema.indexOf(fieldName)] = value
}
fun clear() {
values.fill(null)
}
fun toStruct(): Struct = Struct(schema, values.toList())
}
| 0 | Kotlin | 46 | 326 | b860180c9b7275c3ec865bc264d332ea063aaa6e | 1,144 | rxhive | Apache License 2.0 |
src/main/kotlin/world/cepi/example/ParryHandler.kt | AtomIsHere | 359,057,548 | false | null | package world.cepi.example
import net.minestom.server.MinecraftServer
import net.minestom.server.entity.LivingEntity
import net.minestom.server.entity.Player
import net.minestom.server.entity.damage.DamageType
import net.minestom.server.entity.damage.EntityDamage
import net.minestom.server.event.entity.EntityDamageEvent
import net.minestom.server.event.player.PlayerUseItemEvent
import net.minestom.server.utils.Vector
import net.minestom.server.utils.time.TimeUnit
object ParryHandler : Handler {
val isParrying = mutableListOf<Player>()
override fun register(playerInit: Player) {
val scheduleManager = MinecraftServer.getSchedulerManager()
playerInit.addEventCallback(PlayerUseItemEvent::class.java) {
with(it) {
if(hand == Player.Hand.OFF && !isParrying.contains(player)) {
isParrying.add(player)
scheduleManager.buildTask {
if(isParrying.contains(player)) {
isParrying.remove(player)
}
}.delay(1, TimeUnit.SECOND).schedule()
}
}
}
playerInit.addEventCallback(EntityDamageEvent::class.java) {
with(it) {
if(damageType is EntityDamage && (damageType as EntityDamage).source is LivingEntity && entity is Player) {
val player = entity as Player
val source = (damageType as EntityDamage).source as LivingEntity
if(isParrying.contains(player)) {
isCancelled = true
source.damage(DamageType.VOID, damage*0.75F) //TODO: Create damage type for parrying
source.velocity = Vector(0.0, 5.0, 0.0)
isParrying.remove(player)
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 4deb553e6acc3518b8200cc89ae2615012f84a5c | 1,909 | TestExtension | MIT License |
app/src/main/java/com/brandoncano/resistancecalculator/model/ctv/ResistorCtvViewModel.kt | bmcano | 501,427,754 | false | {"Kotlin": 215877} | package com.brandoncano.resistancecalculator.model.ctv
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class ResistorCtvViewModel(context: Context): ViewModel() {
private val repository = ResistorCtvRepository.getInstance(context)
private val _resistor = MutableStateFlow(ResistorCtv())
val resistor: StateFlow<ResistorCtv> get() = _resistor
private val _navBarSelection = MutableStateFlow(1)
val navBarSelection: StateFlow<Int> get() = _navBarSelection
init {
viewModelScope.launch {
val loadedResistor = repository.loadResistor()
_resistor.value = loadedResistor
_navBarSelection.value = loadedResistor.navBarSelection
}
}
fun clear() {
_resistor.value = ResistorCtv(navBarSelection = _navBarSelection.value)
repository.clear()
}
fun updateBand(bandNumber: Int, color: String) {
_resistor.value = when (bandNumber) {
1 -> _resistor.value.copy(band1 = color)
2 -> _resistor.value.copy(band2 = color)
3 -> _resistor.value.copy(band3 = color)
4 -> _resistor.value.copy(band4 = color)
5 -> _resistor.value.copy(band5 = color)
6 -> _resistor.value.copy(band6 = color)
else -> _resistor.value
}
repository.saveResistor(_resistor.value)
}
fun saveNavBarSelection(number: Int) {
val navBarSelection = number.coerceIn(0..3)
_navBarSelection.value = navBarSelection
_resistor.value = _resistor.value.copy(navBarSelection = navBarSelection)
repository.saveNavBarSelection(navBarSelection)
}
}
| 4 | Kotlin | 0 | 1 | 32bf41f079990b700059a1ce7adef146c91e525c | 1,835 | ResistanceCalculatorApp | MIT License |
boat-core/src/main/kotlin/xyz/srclab/common/cache/GuavaCache.kt | srclab-projects | 247,777,997 | false | null | package xyz.srclab.common.cache
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import xyz.srclab.common.base.asType
import java.util.concurrent.ExecutionException
import java.util.function.Function
/**
* Base [Cache] implementation using [guava](https://github.com/google/guava).
*/
abstract class BaseGuavaCache<K : Any, V : Any>(
protected open val cache: com.google.common.cache.Cache<K, CacheVal<V>>
) : Cache<K, V> {
override fun getVal(key: K, loader: Function<in K, out V>): CacheVal<V>? {
try {
return cache.get(key) {
CacheVal.of(loader.apply(key))
}
} catch (e: ExecutionException) {
val cause = e.cause
if (cause is NoSuchElementException) {
return null
}
throw CacheException(e)
} catch (e: Exception) {
throw CacheException(e)
}
}
override fun getPresentVal(key: K): CacheVal<V>? {
try {
return cache.getIfPresent(key)
} catch (e: Exception) {
throw CacheException(e)
}
}
override fun put(key: K, value: V) {
try {
cache.put(key, CacheVal.of(value))
} catch (e: Exception) {
throw CacheException(e)
}
}
override fun remove(key: K) {
try {
cache.invalidate(key)
} catch (e: Exception) {
throw CacheException(e)
}
}
override fun clear() {
try {
cache.invalidateAll()
} catch (e: Exception) {
throw CacheException(e)
}
}
override fun cleanUp() {
try {
cache.cleanUp()
} catch (e: Exception) {
throw CacheException(e)
}
}
}
/**
* [Cache] implementation using [guava](https://github.com/google/guava).
*/
open class GuavaCache<K : Any, V : Any>(
cache: com.google.common.cache.Cache<K, CacheVal<V>>
) : BaseGuavaCache<K, V>(cache) {
/**
* Constructs with cache builder.
*/
constructor(builder: Cache.Builder<K, V>) : this(buildGuavaBuilder(builder).build<K, CacheVal<V>>())
override fun getVal(key: K): CacheVal<V>? {
return getPresentVal(key)
}
}
/**
* Loading [Cache] implementation using [guava](https://github.com/google/guava).
*/
open class LoadingGuavaCache<K : Any, V : Any>(
override val cache: LoadingCache<K, CacheVal<V>>
) : BaseGuavaCache<K, V>(cache) {
/**
* Constructs with cache builder.
*/
constructor(builder: Cache.Builder<K, V>) : this(
buildLoadingCaffeine(builder)
)
override fun getVal(key: K): CacheVal<V>? {
try {
return cache.get(key)
} catch (e: ExecutionException) {
val cause = e.cause
if (cause is NoSuchElementException) {
return null
}
throw CacheException(e)
} catch (e: Exception) {
throw CacheException(e)
}
}
}
private fun <K : Any, V : Any> buildGuavaBuilder(builder: Cache.Builder<K, V>): CacheBuilder<K, CacheVal<V>> {
val guavaBuilder = CacheBuilder.newBuilder()
val initialCapacity = builder.initialCapacity
if (initialCapacity !== null) {
guavaBuilder.initialCapacity(initialCapacity)
}
val maxCapacity = builder.maxCapacity
if (maxCapacity !== null) {
guavaBuilder.maximumSize(maxCapacity)
}
val concurrencyLevel = builder.concurrencyLevel
if (concurrencyLevel !== null) {
guavaBuilder.concurrencyLevel(concurrencyLevel)
}
val expireAfterAccess = builder.expireAfterAccess
if (expireAfterAccess !== null) {
guavaBuilder.expireAfterAccess(expireAfterAccess)
}
val expireAfterWrite = builder.expireAfterWrite
if (expireAfterWrite !== null) {
guavaBuilder.expireAfterWrite(expireAfterWrite)
}
val refreshAfterWrite = builder.refreshAfterWrite
if (refreshAfterWrite !== null) {
guavaBuilder.refreshAfterWrite(refreshAfterWrite)
}
return guavaBuilder.asType()
}
private fun <K : Any, V : Any> buildGuavaLoader(loader: Function<in K, out V>?): CacheLoader<K, CacheVal<V>> {
if (loader === null) {
throw IllegalArgumentException("Loader must not be null!")
}
return object : CacheLoader<K, CacheVal<V>>() {
override fun load(key: K): CacheVal<V> {
try {
return CacheVal.of(loader.apply(key))
} catch (e: NoSuchElementException) {
throw e
}
}
}
}
private fun <K : Any, V : Any> buildLoadingCaffeine(builder: Cache.Builder<K, V>): LoadingCache<K, CacheVal<V>> {
val guavaBuilder: CacheBuilder<K, CacheVal<V>> = buildGuavaBuilder(builder)
val cacheLoader: CacheLoader<K, CacheVal<V>> = buildGuavaLoader(builder.loader)
return guavaBuilder.build(cacheLoader)
} | 0 | Kotlin | 1 | 4 | a630d2897d5299af34ec17cfe335f3df3221851e | 4,995 | boat | Apache License 2.0 |
app/src/main/java/com/wan/android/adapter/ImageNetAdapter.kt | qinghuaAndroid | 252,683,218 | false | {"Kotlin": 278208, "Java": 73348} | package com.wan.android.adapter
import android.view.ViewGroup
import android.widget.ImageView
import coil.load
import com.wan.android.R
import com.wan.android.bean.BannerEntity
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.util.BannerUtils
/**
* 自定义布局,网络图片
*/
class ImageNetAdapter(mDatas: List<BannerEntity>?) :
BannerAdapter<BannerEntity, ImageHolder>(mDatas) {
override fun onCreateHolder(parent: ViewGroup, viewType: Int): ImageHolder {
val imageView =
BannerUtils.getView(parent, R.layout.banner_image) as ImageView
return ImageHolder(imageView)
}
override fun onBindView(
holder: ImageHolder,
data: BannerEntity,
position: Int,
size: Int
) {
holder.imageView.load(data.imagePath)
}
} | 1 | Kotlin | 3 | 3 | 35e86bbc06a3ef306d3355432b8dc6cdb7217c1e | 810 | WanAndroid-MVVM | Apache License 2.0 |
app/src/androidTest/java/com/catcompanion/app/MainActivityTest.kt | andrefilipesilva73 | 744,714,931 | false | {"Kotlin": 96650} | package com.catcompanion.app
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.catcompanion.app.ui.theme.CatCompanionAppTheme
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
import org.junit.Rule
/**
* Main Activity Instrumented test, which will execute on an Android device.
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun homeScreenLanding() {
// Start the app
composeTestRule.setContent {
// Call the entry point composable function
CatCompanionAppTheme {
// Call the Main composable function for preview
Main()
}
}
// Look for the main Nav Host
composeTestRule.onNodeWithTag("main_nav_host").assertExists()
// Make sure that Home is loaded
composeTestRule.onNodeWithTag("home_screen").assertExists()
}
} | 0 | Kotlin | 0 | 1 | f8712b7736b08c706e0fa056733ec7bcbccda034 | 1,148 | cat-companion-app | MIT License |
src/main/kotlin/org/example/nicol/infrastructure/computation/VectorUtils.kt | WackyGem | 708,314,425 | false | {"Kotlin": 264088, "TypeScript": 4041, "Shell": 2365, "HTML": 1725, "Makefile": 1208, "CSS": 1146, "JavaScript": 828, "Dockerfile": 709, "Java": 536} | /*
* MIT License
*
* Copyright (c) 2023 Wacky Gem
*
* 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.example.nicol.infrastructure.computation
import kotlin.math.exp
import kotlin.math.sqrt
object VectorUtils {
/**
* This function calculates the RMS normalized vector output by applying the following steps:
*
* 1. Calculate the sum of squares ss of the input vector input:
* ss = ∑_{j=0}^{size-1} (x[[j]])^2
*
* 2. Normalize the sum of squares ss :
* ss = ss/size + 1 * 10^(-5)
* ss = 1/√ss
*
* 3. Normalize and scale the output vector output:
* o[[j]] = weight[[j]] * (ss * x[[j]])
*
* @param output The output vector.
* @param input The input vector.
* @param weight The weight vector.
* @param offset The offset of weight vector
* @param size The size of the vectors.
*/
fun rmsNorm(output: FloatArray, input: FloatArray, weight: FloatArray, offset: Int, size: Int) {
var ss = 0.0f
for (j in 0 until size) {
ss += input[j] * input[j]
}
ss /= size.toFloat()
ss += 1e-5f
ss = 1.0f / sqrt(ss.toDouble()).toFloat()
for (j in 0 until size) {
output[j] = weight[offset + j] * (ss * input[j])
}
}
/**
* This function calculates the softmax normalized vector output by applying the following steps:
*
* 1. Find the maximum value maxVal in the input vector x:
* maxVal = max(x[0], x[1], ..., x[size-1])
*
* 2. Compute the exponential of the differences between each element and the maximum value:
* exp_diff[i] = e^(x[i] - maxVal)
*
* 3. Calculate the sum of the exponential differences:
* sum = ∑_{i=0}^{size-1} exp_diff[i]
*
* 4. Normalize each element in the output vector x by dividing them by the sum:
* x[i] = exp_diff[i] / sum
*
* @param x The input vector containing unnormalized values.
* @param size The size of the vector.
*/
fun softmax(x: FloatArray, offset: Int, size: Int) {
var maxVal = x[0 + offset]
for (i in 1 until size) {
if (x[i + offset] > maxVal) {
maxVal = x[i + offset]
}
}
var sum = 0.0f
for (i in 0 until size) {
x[i + offset] = exp((x[i + offset] - maxVal).toDouble()).toFloat()
sum += x[i + offset]
}
for (i in 0 until size) {
x[i + offset] /= sum
}
}
/**
* This function performs matrix multiplication between a weight matrix and an input vector,
* resulting in an output vector. It follows these steps:
*
* 1. For each row of the weight matrix and corresponding element in the output vector:
* 1.1. Initialize the value for the current element in the output vector as 0.0.
* 1.2. Multiply each element in the row of the weight matrix with the corresponding element in the input vector.
* 1.3. Accumulate the products to calculate the value for the current element in the output vector.
*
* @param output The output vector after matrix multiplication.
* @param input The input vector to be multiplied.
* @param weight The weight matrix for multiplication.
* @param offset The offset of weight vector
* @param col The number of columns in the weight matrix and size of the input vector.
* @param row The number of rows in the weight matrix and size of the output vector.
*/
fun matmul(output: FloatArray, input: FloatArray, weight: FloatArray, offset: Int, col: Int, row: Int) {
// W (d,n) @ x (n,) -> xout (d,)
// by far the most amount of time is spent inside this little function
for (i in 0 until row) {
var value = 0.0f
for (j in 0 until col) {
value += weight[offset + (i * col + j)] * input[j]
}
output[i] = value
}
}
/** Find a max index with [probabilities] vector */
fun argmax(probabilities: FloatArray): Int {
var maxIndex = 0
var maxProbability = probabilities[0]
for (i in 1 until probabilities.size) {
if (probabilities[i] > maxProbability) {
maxIndex = i
maxProbability = probabilities[i]
}
}
return maxIndex
}
/**
* A multinomial distribution sampling algorithm
*
* Randomly samples an index from a [probability] distribution
* based on a given array of probabilities and a random number [coin]
*/
fun mult(probabilities: FloatArray, coin: Float): Int {
var cdf = 0.0f
for (i in probabilities.indices) {
cdf += probabilities[i]
if (coin < cdf) {
return i
}
}
return probabilities.size - 1
}
} | 0 | Kotlin | 2 | 7 | 53e9973692eb0e43157818e29292497ce5d2975f | 5,977 | Nicol | MIT License |
benchmark/src/main/kotlin/com/kevlina/budgetplus/benchmark/Utils.kt | kevinguitar | 517,537,183 | false | null | package com.kevlina.budgetplus.benchmark
import androidx.benchmark.macro.MacrobenchmarkScope
import androidx.test.uiautomator.By
import androidx.test.uiautomator.Until
internal const val APP_PACKAGE = "com.kevlina.budgetplus"
private const val UI_TIMEOUT = 1_000L
internal fun MacrobenchmarkScope.authorize() {
if (!waitForText("Welcome to Budget+")) {
return
}
// Login with Google account
waitForTextAndClick("Continue with Google")
waitForTextAndClick("<EMAIL>")
// Record screen
waitForText("Expense")
}
private fun MacrobenchmarkScope.waitForText(text: String): Boolean {
return device.wait(Until.hasObject(By.text(text)), UI_TIMEOUT)
}
private fun MacrobenchmarkScope.waitForTextAndClick(text: String): Boolean {
val isVisible = waitForText(text)
if (isVisible) {
device.findObject(By.text(text)).click()
}
return isVisible
} | 2 | null | 0 | 9 | 9c964e063efdf797f84f58fcc3e8b17da75f8309 | 902 | budgetplus-android | MIT License |
app/src/main/java/com/sjn/stamp/controller/UserSettingController.kt | sjnyag | 81,733,859 | false | null | package com.sjn.stamp.controller
import android.content.Context
import com.sjn.stamp.model.dao.UserSettingDao
import com.sjn.stamp.utils.PreferenceHelper
import com.sjn.stamp.utils.RealmHelper
class UserSettingController {
var queueIdentifyMediaId: String
get() {
return RealmHelper.realmInstance.use { realm ->
UserSettingDao.getUserSetting(realm).queueIdentifyMediaId
}
}
set(queueIdentifyMediaId) {
return RealmHelper.realmInstance.use { realm ->
UserSettingDao.updateQueueIdentifyMediaId(realm, queueIdentifyMediaId)
}
}
var lastMusicId: String
get() {
return RealmHelper.realmInstance.use { realm ->
UserSettingDao.getUserSetting(realm).lastMusicId
}
}
set(lastMediaId) {
return RealmHelper.realmInstance.use { realm ->
UserSettingDao.updateLastMusicId(realm, lastMediaId)
}
}
fun stopOnAudioLostFocus(): Boolean = false
/*
Realm realm = RealmHelper.getRealmInstance();
UserSetting userSetting = UserSettingDao.getUserSetting(realm);
boolean result = userSetting.getStopOnAudioLostFocus();
realm.close();
return result;
*/
fun hideAlbumArtOnLockScreen(context: Context?) = PreferenceHelper.isHideAlbumArtOnLockScreen(context)
var newSongDays: Int
get() {
return RealmHelper.realmInstance.use { realm ->
UserSettingDao.getUserSetting(realm).newSongDays
}
}
set(newSongDays) {
RealmHelper.realmInstance.use { realm ->
UserSettingDao.updateNewSongDays(realm, newSongDays)
}
}
var mostPlayedSongSize: Int
get() {
return RealmHelper.realmInstance.use { realm ->
UserSettingDao.getUserSetting(realm).mostPlayedSongSize
}
}
set(mostPlayedSongSize) {
RealmHelper.realmInstance.use { realm ->
UserSettingDao.updateMostPlayedSongSize(realm, mostPlayedSongSize)
}
}
}
| 59 | null | 3 | 9 | cb145824f9e06cd17266502a5e85d8a9fa276bb0 | 2,170 | stamp | Apache License 2.0 |
src/main/kotlin/bewis09/bewisclient/widgets/lineWidgets/InventoryWidget.kt | Bewis09 | 755,277,240 | false | {"Kotlin": 166756, "Java": 70587} | package bewis09.bewisclient.widgets.lineWidgets
import bewis09.bewisclient.settingsLoader.SettingsLoader
import bewis09.bewisclient.widgets.Widget
import com.mojang.blaze3d.systems.RenderSystem
import net.minecraft.client.MinecraftClient
import net.minecraft.client.gui.DrawContext
import net.minecraft.util.Identifier
class InventoryWidget: Widget("inventory") {
val Identifier = Identifier("bewisclient","textures/inventory_widget.png")
override fun render(drawContext: DrawContext) {
RenderSystem.setShaderColor(1f,1f,1f,getProperty(Settings.TRANSPARENCY))
drawContext.matrices.scale(getScale(),getScale(),1F)
RenderSystem.enableBlend()
drawContext.drawTexture(Identifier,getPosX(),getPosY(),getOriginalWidth(),getOriginalHeight(),0f,0f,getOriginalWidth(),getOriginalHeight(),180,60)
RenderSystem.disableBlend()
RenderSystem.setShaderColor(1f,1f,1f,1f)
for (i in 0 .. 8) {
for (j in 0 .. 2) {
drawContext.drawItem(MinecraftClient.getInstance().player?.inventory?.getStack(j*9+i+9),getPosX()+i*20+2,getPosY()+j*20+2)
drawContext.drawItemInSlot(MinecraftClient.getInstance().textRenderer,MinecraftClient.getInstance().player?.inventory?.getStack(j*9+i+9),getPosX()+i*20+2,getPosY()+j*20+2)
}
}
drawContext.matrices.scale(1/getScale(),1/getScale(),1F)
}
override fun getOriginalWidth(): Int {
return 180
}
override fun getOriginalHeight(): Int {
return 60
}
override fun getWidgetSettings(): ArrayList<Pair<String, Any>> = arrayListOf(
Pair(id, SettingsLoader.Settings()),
Pair("$id.enabled",true),
Pair("$id.transparency",1F),
Pair("$id.size",1f),
Pair("$id.posX",5f),
Pair("$id.partX",1f),
Pair("$id.posY",5f),
Pair("$id.partY",1f)
)
} | 7 | Kotlin | 0 | 0 | 7a6cb7774e709d1593358658c553a2e4926a7a0c | 1,922 | Bewisclient-2 | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/voltek/newsfeed/data/network/NewsApi.kt | IvanAntsiferov | 86,695,111 | false | null | package com.voltek.newsfeed.data.network
import com.voltek.newsfeed.data.network.entity.NewsApiArticlesResponse
import com.voltek.newsfeed.data.network.entity.NewsApiSourcesResponse
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Query
interface NewsApi {
@GET(ENDPOINT_ARTICLES)
fun fetchArticles(
@Query(PARAM_SOURCE) source: String
): Single<NewsApiArticlesResponse>
@GET(ENDPOINT_SOURCES)
fun fetchSources(): Single<NewsApiSourcesResponse>
}
| 1 | Kotlin | 5 | 14 | 7be151184e0d8c9bca72014adae18979d0fd2859 | 509 | News-Feed-App | Apache License 2.0 |
app/src/main/java/com/belotron/weatherradarhr/FrameSequenceLoader.kt | mtopolnik | 289,857,721 | false | null | package com.belotron.weatherradarhr
import android.content.Context
import com.belotron.weatherradarhr.FetchPolicy.*
import com.belotron.weatherradarhr.gifdecode.BitmapFreelists
import com.belotron.weatherradarhr.gifdecode.GifFrame
import com.belotron.weatherradarhr.gifdecode.GifSequence
import com.belotron.weatherradarhr.gifdecode.ImgDecodeException
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext
import java.io.IOException
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.math.ceil
val frameSequenceLoaders = arrayOf(KradarSequenceLoader(), LradarSequenceLoader())
sealed class FrameSequenceLoader(
val positionInUI: Int,
val title: String,
val minutesPerFrame: Int,
val mapShape: MapShape,
) {
fun correctFrameCount(context: Context): Int =
ceil(context.mainPrefs.animationCoversMinutes.toDouble() / minutesPerFrame).toInt()
// Returns Pair(isOffline, sequence)
abstract suspend fun fetchFrameSequence(
context: Context,
correctFrameCount: Int,
fetchPolicy: FetchPolicy
): Pair<Boolean, FrameSequence<out Frame>?>
}
class NullFrameException: Exception()
class KradarSequenceLoader : FrameSequenceLoader(
positionInUI = 0,
title = "HR",
minutesPerFrame = 5,
mapShape = kradarShape,
) {
private val urlTemplate = "https://vrijeme.hr/radari/anim_kompozit%d.png"
override suspend fun fetchFrameSequence(
context: Context, correctFrameCount: Int, fetchPolicy: FetchPolicy
): Pair<Boolean, PngSequence?> {
// This function is not designed to work correctly for these two fetch policies:
assert(fetchPolicy != ONLY_CACHED) { "fetchPolicy == ONLY_CACHED" }
assert(fetchPolicy != ONLY_IF_NEW) { "fetchPolicy == ONLY_IF_NEW" }
val frames = mutableListOf<PngFrame>()
val sequence = newKradarSequence(frames)
val allocator = BitmapFreelists()
val decoder = sequence.intoDecoder(allocator)
val indexOfFirstFrameAtServer = 26 - correctFrameCount
if (indexOfFirstFrameAtServer < 1) {
throw RuntimeException("Asked for too many frames, max is 25")
}
val isOffline = AtomicBoolean(false)
fun urlForFrameIndex(i: Int) = urlTemplate.format(indexOfFirstFrameAtServer + i)
suspend fun fetchFrame(index: Int, fetchPolicy: FetchPolicy): PngFrame {
val url = urlForFrameIndex(index)
info { "Kradar fetch $url" }
val (lastModified, frame) = try {
fetchPngFrame(context, url, fetchPolicy)
} catch (e: ImageFetchException) {
isOffline.set(true)
val cached = e.cached ?: throw IOException("Fetch error, missing from cache")
Pair(0L, cached as PngFrame)
}
if (frame == null) {
throw NullFrameException()
}
return frame
}
fun timestampInCache(index: Int): Long? {
val url = urlForFrameIndex(index)
val (lastModified, nullableFrame) = fetchPngFromCache(context, url)
val frame = nullableFrame ?: return null
frames.add(frame)
decoder.assignTimestamp(frames.size - 1, KradarOcr::ocrKradarTimestamp)
frames.removeLast()
return frame.timestamp
}
var fetchPolicy = fetchPolicy
try {
val timestamp0InCache = withContext(IO) { timestampInCache(0) }
val timestamp0 = fetchFrame(0, fetchPolicy).let { frame ->
frames.add(frame)
withContext(Default) {
decoder.assignTimestamp(0, KradarOcr::ocrKradarTimestamp)
}
frame.timestamp
}
// Reuse cached images by renaming them to the expected new URLs
// after DHMZ posts a new image and renames the previous images
withContext(IO) {
if (timestamp0InCache == null || timestamp0InCache >= timestamp0) {
info { "timestamp0inCache == null || timestamp0InCache >= timestamp0" }
return@withContext
}
synchronized (CACHE_LOCK) {
val sortedByTimestamp = TreeSet(compareBy(Pair<Int, Long>::second)).apply {
add(Pair(0, timestamp0InCache))
}
info { "Collecting cached DHMZ timestamps" }
for (i in 1.until(correctFrameCount)) {
val timestamp = timestampInCache(i) ?: return@withContext
sortedByTimestamp.add(Pair(i, timestamp))
}
if (sortedByTimestamp.size != correctFrameCount) {
info { "Cached DHMZ timestamps have duplicates" }
return@withContext
}
val urlsHaveDisorder =
sortedByTimestamp.mapIndexed { indexToBe, (indexNow, _) -> indexToBe != indexNow }
.any { it }
if (urlsHaveDisorder) {
info { "DHMZ URLs have disorder" }
sortedByTimestamp.forEach { (index, _) ->
val urlNow = urlForFrameIndex(index)
context.renameCached(urlNow, "$urlNow.tmp")
}
sortedByTimestamp.forEachIndexed { indexToBe, (indexNow, _) ->
val tmpName = "${urlForFrameIndex(indexNow)}.tmp"
context.renameCached(tmpName, urlForFrameIndex(indexToBe))
}
}
val indexOfNewTimestamp0 =
sortedByTimestamp.indexOfFirst { (_, timestamp) -> timestamp == timestamp0 }
.takeIf { it > 0 }
?: return@withContext
info { "DHMZ indexOfTimestamp0 == $indexOfNewTimestamp0, " +
"indexOfFirstFrameAtServer == $indexOfFirstFrameAtServer" }
for ((index, _) in sortedByTimestamp) {
if (index < indexOfNewTimestamp0) {
try {
context.deleteCached(urlForFrameIndex(index))
} catch (e: IOException) {
warn { e.message ?: "<reason missing>" }
return@withContext
}
} else {
val indexToBe = index - indexOfNewTimestamp0
info { "Reusing DHMZ image $index as $indexToBe" }
context.renameCached(urlForFrameIndex(index), urlForFrameIndex(indexToBe))
}
}
}
fetchPolicy = PREFER_CACHED
}
coroutineScope {
1.until(correctFrameCount).map { i ->
async(IO) { fetchFrame(i, fetchPolicy) }
}.forEach {
frames.add(it.await())
}
}
withContext(Default) {
for (i in 1.until(correctFrameCount)) {
decoder.assignTimestamp(i, KradarOcr::ocrKradarTimestamp)
}
val sortedFrames = TreeSet(compareBy(PngFrame::timestamp)).apply {
addAll(sequence.frames)
}
sequence.frames.apply {
clear()
addAll(sortedFrames)
}
}
} catch (e: NullFrameException) {
return Pair(true, null)
} finally {
decoder.dispose()
}
info { "Kradar done fetchFrameSequence, frameCount = ${sequence.frames.size}" }
return Pair(isOffline.get(), sequence)
}
private fun newKradarSequence(frames: MutableList<PngFrame>) = PngSequence(frames, 720, 751)
}
class LradarSequenceLoader : FrameSequenceLoader(
positionInUI = 1,
title = "SLO",
minutesPerFrame = 5,
mapShape = lradarShape,
) {
private val url = "https://meteo.arso.gov.si/uploads/probase/www/observ/radar/si0-rm-anim.gif"
override suspend fun fetchFrameSequence(
context: Context, correctFrameCount: Int, fetchPolicy: FetchPolicy
): Pair<Boolean, GifSequence?> {
val (lastModified, sequence) = try {
fetchGifSequence(context, url, fetchPolicy)
} catch (e: ImageFetchException) {
Pair(0L, e.cached as GifSequence?)
}
if (sequence == null) {
return Pair(true, null)
}
val allocator = BitmapFreelists()
val decoder = sequence.intoDecoder(allocator)
try {
val frames = sequence.frames
withContext(Default) {
(0 until frames.size).forEach { frameIndex ->
decoder.assignTimestamp(frameIndex, LradarOcr::ocrLradarTimestamp)
}
}
} catch (e: ImgDecodeException) {
severe(CcOption.CC_PRIVATE) { "Animated GIF decoding error" }
context.invalidateCache(url)
throw e
} finally {
decoder.dispose()
}
// SLO animated gif has repeated frames at the end, remove the duplicates
val sortedFrames = TreeSet(compareBy(GifFrame::timestamp)).apply {
addAll(sequence.frames)
}
sequence.frames.apply {
clear()
addAll(sortedFrames)
}
return Pair(lastModified == 0L, sequence)
}
}
| 0 | Kotlin | 0 | 1 | b5a025f1907b0c2a715432e111ca09405f7b995b | 9,994 | weather-radar-hr | MIT License |
core/src/commonMain/kotlin/work/socialhub/kmisskey/api/GalleriesResource.kt | uakihir0 | 756,689,268 | false | {"Kotlin": 223847, "Shell": 2146, "Makefile": 315} | package misskey4j.api
import misskey4j.api.request.gallery.*
import misskey4j.api.request.i.IListGalleryPostsRequest
import misskey4j.api.request.users.ListUserGalleryPostsRequest
import misskey4j.api.response.gallery.ListGalleryPostsResponse
import misskey4j.entity.GalleryPost
import misskey4j.entity.share.Response
interface GalleriesResource {
/**
* Get gallery posts.
* @see "https://misskey.io/api-doc.operation/gallery/posts"
*/
fun posts(
request: ListGalleryPostsRequest
): Response<Array<ListGalleryPostsResponse>>
/**
* Get my gallery posts.
* @see "https://misskey.io/api-doc.operation/i/gallery/posts"
*/
fun posts(
request: IListGalleryPostsRequest
): Response<Array<ListGalleryPostsResponse>>
/**
* Get user's gallery posts.
* @see "https://misskey.io/api-doc.operation/users/gallery/posts"
*/
fun posts(
request: ListUserGalleryPostsRequest
): Response<Array<ListGalleryPostsResponse>>
/**
* Show a gallery post.
* @see "https://misskey.io/api-doc.operation/gallery/posts/show"
*/
fun show(
request: ShowGalleryPostRequest
): Response<GalleryPost>
/**
* Create a gallery post.
* @see "https://misskey.io/api-doc.operation/gallery/posts/create"
*/
fun create(
request: CreateGalleryPostRequest
): Response<GalleryPost>
/**
* Delete a gallery post.
*
* @see "https://misskey.io/api-doc.operation/gallery/posts/delete"
*/
fun delete(
request: DeleteGalleryPostRequest
): Response<Unit>
/**
* Update a gallery post.
* @see "https://misskey.io/api-doc.operation/gallery/posts/delete"
*/
fun update(
request: UpdateGalleryPostRequest
): Response<GalleryPost>
/**
* Like a gallery post.
* @see "https://misskey.io/api-doc.operation/gallery/posts/like"
*/
fun like(
request: LikeGalleryPostRequest
): Response<Unit>
/**
* Unlike a gallery post.
*
* @see "https://misskey.io/api-doc.operation/gallery/posts/unlike"
*/
fun like(
request: UnlikeGalleryPostRequest
): Response<Unit>
}
| 1 | Kotlin | 1 | 3 | 744f62ce20e8038edc7b80ce705c8de4fe24a379 | 2,225 | kmisskey | MIT License |
app/src/main/java/com/wildpress/fragments/Diet.kt | Esarac | 536,808,616 | false | {"Kotlin": 76201} | package com.wildpress.fragments
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.gson.Gson
import com.wildpress.R
import com.wildpress.activities.CreateDietActivity
import com.wildpress.components.CardRecyclerView
import com.wildpress.databinding.FragmentDietBinding
import com.wildpress.model.Diet
import com.wildpress.model.User
import com.wildpress.activities.DietViewActivity
class Diet : Fragment(R.layout.fragment_diet) {
private var _binding : FragmentDietBinding? = null
private val binding get() = _binding!!
private lateinit var user: User
//Properties
private lateinit var layoutManager: RecyclerView.LayoutManager
private lateinit var adapter: CardRecyclerView<Diet>
private var diets = ArrayList<Diet>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loadDiets()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentDietBinding.inflate(inflater, container, false)
return binding.root
}
override fun onResume() {
super.onResume()
loadDiets()
this.layoutManager = LinearLayoutManager(context)
this.adapter = CardRecyclerView(this.diets)
this.adapter.setOnItemClickListener(object : CardRecyclerView.onItemClickListener{
override fun <T> onItemClick(item: T) {
val diet = item as Diet
val intent = Intent(activity, DietViewActivity::class.java)
intent.putExtra("diet", diet)
startActivity(intent)
}
})
binding.dietRecyclerView.layoutManager = this.layoutManager
binding.dietRecyclerView.adapter = this.adapter
this.adapter.notifyDataSetChanged()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.createDietBtn.setOnClickListener {
startActivity(Intent(activity, CreateDietActivity::class.java))
}
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
private fun loadDiets(){
val loggedUser = Firebase.auth.currentUser
val userId = loggedUser!!.uid
val user = loadUser()
if(user==null || loggedUser==null){
return
} else{
this.user = user
diets = user.listOfDiet
Firebase.firestore.collection("users").document(userId).get().addOnSuccessListener {
val userOnDataBase = it.toObject(User::class.java)
saveUserLocal(userOnDataBase!!)
}
}
}
private fun loadUser(): User?{
val sp = this.requireActivity().getSharedPreferences("WildPress", Context.MODE_PRIVATE);
val json = sp.getString("user", "NO_USER")
if(json == "NO_USER"){
return null
}else{
return Gson().fromJson(json, User::class.java)
}
}
private fun saveUserLocal(user: User){
if(activity!=null){
val sp = this.requireActivity().getSharedPreferences("WildPress", Context.MODE_PRIVATE);
val json = Gson().toJson(user)
sp.edit().putString("user", json).apply()
}
}
} | 0 | Kotlin | 0 | 0 | e3b055d122434dc729080be3b6dbe6c071ad77f2 | 3,787 | WildPress | MIT License |
src/test/kotlin/passwordStore/crypto/CryptExtensionTest.kt | sciack | 669,479,977 | false | null | package passwordStore.crypto
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import io.mockk.every
import io.mockk.mockk
import kotlin.test.BeforeTest
import kotlin.test.Test
internal class CryptExtensionTest {
private lateinit var crypto: CryptExtension
@BeforeTest
fun setup() {
val secrets = mockk<Secrets>()
crypto = CryptExtension(secrets)
every { secrets.passphrase() } returns "TestPassphrase".toByteArray()
}
@Test
fun `should be able to decrypt a previous encrypted message`() {
val message = "This is a message to encrypt"
assertThat(crypto.decrypt(crypto.crypt(message)), equalTo(message))
}
@Test
fun `should be able to crypt the message`() {
val message = "This is a message to encrypt"
assertThat(crypto.crypt(message), equalTo(message).not())
}
} | 1 | Kotlin | 0 | 0 | 02c2e4bc5555c50998b3ea07c0e34ae2262ebce7 | 904 | kpassword-store | The Unlicense |
app/src/main/java/com/weather/android/WeatherApplication.kt | kokurisann | 506,894,566 | false | {"Kotlin": 9392} | package com.weather.android
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
// 给Weather项目提供一种全局获取Context的方式
class WeatherApplication : Application() {
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
const val TOKEN = "kr7vt3BNhgZ58cIz"
}
override fun onCreate() {
super.onCreate()
context = applicationContext
}
} | 0 | Kotlin | 0 | 0 | ae8dad71f683dc6d9e26b63949a3cbd15d205146 | 461 | Weather | Apache License 2.0 |
XHAW_Application/app/src/main/java/com/vc/xhaw_application/Cooking.kt | chrisbartie | 797,793,307 | false | {"Kotlin": 34666} | package com.vc.xhaw_application
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class Cooking : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cooking)
val logoTextView7 = findViewById<TextView>(R.id.logoTextView7)
val cookingHead = findViewById<TextView>(R.id.cookingHead)
val cookingPrice = findViewById<TextView>(R.id.cookingPrice)
val cookingPurpose = findViewById<TextView>(R.id.cookingPurpose)
val cookingContent = findViewById<TextView>(R.id.cookingContent)
val cookingContent1 = findViewById<TextView>(R.id.cookingContent1)
val cookingContent2 = findViewById<TextView>(R.id.cookingContent2)
val cookingContent3 = findViewById<TextView>(R.id.cookingContent3)
val cookingContent4 = findViewById<TextView>(R.id.cookingContent4)
val cookingPic1 = findViewById<TextView>(R.id.cookingPic1)
val cookingPic2 = findViewById<TextView>(R.id.cookingPic2)
val menuButton8 = findViewById<Button>(R.id.menuButton8)
val backButton6 = findViewById<Button>(R.id.backButton6)
menuButton8?.setOnClickListener {
val intent = Intent(this, Menu::class.java)
startActivity(intent)
}
backButton6?.setOnClickListener {
val intent = Intent(this, Courses::class.java)
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | 7c7b1b83ca7f45455935680250c5d1e5b585b784 | 1,600 | Kotlin-Apps | MIT License |
plugins/advisors/vulnerable-code/src/main/kotlin/VulnerableCodeConfiguration.kt | oss-review-toolkit | 107,540,288 | false | null | /*
* Copyright (C) 2021 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>)
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.plugins.advisors.vulnerablecode
/**
* The configuration for VulnerableCode as security vulnerability provider.
*/
data class VulnerableCodeConfiguration(
/**
* The base URL of the VulnerableCode REST API. By default, the public VulnerableCode instance is used.
*/
val serverUrl: String? = null,
/**
* The optional API key to use.
*/
val apiKey: String? = null
)
| 338 | null | 309 | 1,590 | ed4bccf37bab0620cc47dbfb6bfea8542164725a | 1,182 | ort | Apache License 2.0 |
processor/src/test/kotlin/io/mcarle/konvert/processor/JavaCompatibilityITest.kt | mcarleio | 615,488,544 | false | {"Kotlin": 549656} | package io.mcarle.konvert.processor
import com.tschuchort.compiletesting.SourceFile
import io.mcarle.konvert.converter.SameTypeConverter
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi
import org.junit.jupiter.api.Test
@OptIn(ExperimentalCompilerApi::class)
class JavaCompatibilityITest : KonverterITest() {
@Test
fun java() {
val (compilation) = compileWith(
enabledConverters = listOf(SameTypeConverter()),
code = arrayOf(
SourceFile.kotlin(
name = "Address.kt",
contents =
"""
import io.mcarle.konvert.api.KonvertFrom
import io.mcarle.konvert.api.Mapping
import io.mcarle.konvert.api.Konfig
@KonvertFrom(JavaAddress::class, options = [
Konfig(key = "konvert.enforce-not-null", value = "true")
])
data class Address(val street: String) {
companion object
}
""".trimIndent()
),
SourceFile.java(
name = "JavaAddress.java",
contents =
"""
public class JavaAddress {
private String street_ = "";
public String getStreet() {
return street_;
}
}
""".trimIndent()
)
)
)
val extensionFunctionCode = compilation.generatedSourceFor("AddressKonverter.kt")
println(extensionFunctionCode)
assertSourceEquals(
"""
public fun Address.Companion.fromJavaAddress(javaAddress: JavaAddress): Address = Address(
street = javaAddress.street!!
)
""".trimIndent(),
extensionFunctionCode
)
}
}
| 16 | Kotlin | 6 | 69 | 5861071a3f50006bbcde312a6fe4e35204a60a53 | 1,717 | konvert | Apache License 2.0 |
backend/mandalore-express-domain/src/test/kotlin/com/beyondxscratch/mandaloreexpress/domain/money/AmountShould.kt | davidaparicio | 761,161,576 | false | {"Kotlin": 198124, "JavaScript": 37294, "HTML": 1661, "CSS": 365} | package com.beyondxscratch.mandaloreexpress.domain.money
import com.beyondxscratch.mandaloreexpress.domain.EqualityShould
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import java.math.BigDecimal
class AmountShould : EqualityShould<Amount> {
@Test
fun `not be null`() {
assertThatThrownBy { Amount(BigDecimal.ZERO) }
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage("Amount must be strictly positive")
}
@Test
fun `not be strictly negative`() {
assertThatThrownBy { amount(-3) }
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage("Amount must be strictly positive")
}
@Test
fun `add amounts`() {
val ten = Amount(BigDecimal.TEN)
val one = Amount(BigDecimal.ONE)
val eleven = amount(11)
assertThat(ten + one).isEqualTo(eleven)
}
@Test
fun `subtract amounts`() {
val ten = Amount(BigDecimal.TEN)
val one = Amount(BigDecimal.ONE)
val nine = amount(9)
assertThat(ten - one).isEqualTo(nine)
}
@Test
fun `compare amount to find the highest`() {
val ten = Amount(BigDecimal.TEN)
val one = Amount(BigDecimal.ONE)
assertThat(ten > one).isEqualTo(true)
}
@Test
fun `compare amount to find the lowest`() {
val ten = Amount(BigDecimal.TEN)
val one = Amount(BigDecimal.ONE)
assertThat(one < ten).isEqualTo(true)
}
@Test
fun `compare amount equality`() {
val ten = Amount(BigDecimal.TEN)
assertThat(ten >= ten).isEqualTo(true)
assertThat(ten <= ten).isEqualTo(true)
}
@Test
fun `multiply amount by a scalar`() {
val ten = Amount(BigDecimal.TEN)
val five = BigDecimal(5.0)
val fifty = ten * five
assertThat(fifty).isEqualTo(amount(50.0))
}
} | 8 | Kotlin | 0 | 0 | 05dc41e2a5a5ea47ef5d688177631ffa9923fe11 | 1,997 | model-mitosis | Apache License 2.0 |
superwall/src/main/java/com/superwall/sdk/paywall/manager/PaywallViewControllerCache.kt | superwall | 642,585,064 | false | null | package com.superwall.sdk.paywall.manager
import com.superwall.sdk.paywall.vc.PaywallViewController
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.util.concurrent.ConcurrentHashMap
class PaywallViewControllerCache(
private val deviceLocaleString: String,
) {
private var _activePaywallVcKey: String? = null
private val cache = ConcurrentHashMap<String, PaywallViewController>()
private val singleThreadContext = newSingleThreadContext("com.superwall.paywallcache")
fun getAllPaywallViewControllers(): List<PaywallViewController> =
runBlocking(singleThreadContext) {
cache.values.toList()
}
var activePaywallVcKey: String?
get() = runBlocking(singleThreadContext) { _activePaywallVcKey }
set(value) {
CoroutineScope(singleThreadContext).launch { _activePaywallVcKey = value }.apply { }
}
val activePaywallViewController: PaywallViewController?
get() = runBlocking(singleThreadContext) { _activePaywallVcKey?.let { cache[it] } }
fun save(
paywallViewController: PaywallViewController,
key: String,
) {
CoroutineScope(singleThreadContext).launch { cache[key] = paywallViewController }
}
fun getPaywallViewController(key: String): PaywallViewController? = runBlocking(singleThreadContext) { cache[key] }
fun removePaywallViewController(key: String) {
CoroutineScope(singleThreadContext).launch { cache.remove(key) }
}
fun removeAll() {
CoroutineScope(singleThreadContext).launch {
cache.keys.forEach { key ->
if (key != _activePaywallVcKey) {
cache.remove(key)
}
}
}
}
}
| 6 | null | 3 | 9 | 2582de8d48af7c0ad080e30949d920e8a34d9219 | 1,799 | Superwall-Android | MIT License |
graphene-reader/src/main/kotlin/com/graphene/reader/service/index/model/IndexProperty.kt | hwanjin-jeong | 224,980,912 | false | {"Markdown": 7, "Gradle": 6, "YAML": 17, "Shell": 3, "Text": 5, "Ignore List": 1, "Batchfile": 2, "EditorConfig": 1, "Kotlin": 76, "Java": 158, "ANTLR": 1, "Java Properties": 1, "Mustache": 2, "XML": 3, "Dockerfile": 2, "TOML": 2, "SQL": 1, "Makefile": 1} | package com.graphene.reader.service.index.model
import java.util.ArrayList
import org.springframework.boot.context.properties.ConfigurationProperties
/**
* @author <NAME>
* @author Dark
*
* @since 1.0.0
*/
@ConfigurationProperties("graphene.reader.store.key.handlers.elasticsearch-key-search-handler")
class IndexProperty {
var clusterName: String? = null
var index: String? = null
var tenant: String = "NONE"
var type: String? = null
var cluster: List<String> = ArrayList()
var port: Int = 0
var scroll: Int = 0
var timeout: Int = 0
var maxPaths: Int = 0
override fun toString(): String {
return "IndexProperty{" +
"clusterName=$clusterName" +
", index=$index" +
", type=$type" +
", tenant=$tenant" +
", cluster=$cluster" +
", port=$port" +
", scroll=$scroll" +
", timeout=$timeout" +
", maxPaths=$maxPaths" +
'}'
}
}
| 1 | null | 1 | 1 | 657cd36a37c9bed4de87582ba6c4e0bebbe358c7 | 913 | graphene | MIT License |
src/jvmMain/kotlin/Main.kt | valeter | 661,218,864 | false | null | import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.res.loadImageBitmap
import androidx.compose.ui.res.useResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.WindowState
import androidx.compose.ui.window.singleWindowApplication
fun main() = singleWindowApplication(
title = "fst",
state = WindowState(width = 1280.dp, height = 768.dp),
icon = BitmapPainter(useResource("icon/icon.png", ::loadImageBitmap)),
) {
MainView()
}
| 0 | Kotlin | 0 | 0 | 58d7c2abc7d22f2831b2becf3a142195f4af3b83 | 500 | fst | MIT License |
src/main/kotlin/br/com/webbudget/domain/services/administration/RecoverPasswordService.kt | web-budget | 354,665,828 | false | null | package br.com.webbudget.domain.services.administration
import br.com.webbudget.domain.entities.administration.PasswordRecoverAttempt
import br.com.webbudget.domain.exceptions.InvalidPasswordRecoverTokenException
import br.com.webbudget.domain.mail.RecoverPasswordEmail
import br.com.webbudget.domain.services.MailSenderService
import br.com.webbudget.infrastructure.repository.administration.PasswordRecoverAttemptRepository
import br.com.webbudget.infrastructure.repository.administration.UserRepository
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
private val logger = KotlinLogging.logger {}
@Service
@Transactional(readOnly = true)
class RecoverPasswordService(
@Value("\${web-budget.front-end-url}")
private val frontendUrl: String,
private val userService: UserService,
private val userRepository: UserRepository,
private val mailSenderService: MailSenderService,
private val passwordRecoverAttemptRepository: PasswordRecoverAttemptRepository,
) {
@Transactional
fun registerRecoveryAttempt(userEmail: String) {
val user = userRepository.findByEmail(userEmail)
if (user == null) {
logger.warn { "No user found with e-mail [${userEmail}], ignoring password recover request" }
return
}
val recoverAttempt = PasswordRecoverAttempt(UUID.randomUUID(), user)
passwordRecoverAttemptRepository.persist(recoverAttempt)
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm")
val recoverPasswordUrl = "${frontendUrl}/login/recover-password" +
"?token=${recoverAttempt.token}&email=${user.email}"
val mailMessage = RecoverPasswordEmail(user)
mailMessage.addVariable("recoverPasswordUrl", recoverPasswordUrl)
mailMessage.addVariable("validUntil", recoverAttempt.validity.format(formatter))
mailSenderService.sendEmail(mailMessage)
}
@Transactional
fun recover(newPassword: String, recoveryToken: UUID, userEmail: String) {
val attempt = passwordRecoverAttemptRepository.findByTokenAndUserEmailAndUsedFalse(recoveryToken, userEmail)
?: throw InvalidPasswordRecoverTokenException(userEmail)
if (attempt.validity.isBefore(LocalDateTime.now())) {
logger.debug { "Recover password token has expired on [${attempt.validity}]" }
throw InvalidPasswordRecoverTokenException(userEmail)
}
userService.updatePassword(attempt.user, newPassword, false)
attempt
.apply { this.used = true }
.also { passwordRecoverAttemptRepository.merge(it) }
}
}
| 4 | null | 4 | 7 | 2e4985121985c6dcf1de83b9044ca1c5927c20fb | 2,892 | back-end | Apache License 2.0 |
core-database/src/main/java/com/stefang/app/core/database/entity/CurrencyDbModel.kt | stef-ang | 641,499,246 | false | null | package com.stefang.app.core.database.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "currency")
data class CurrencyDbModel(
@PrimaryKey val code: String,
val name: String
)
| 1 | Kotlin | 0 | 0 | 332a8ca65eef54d50fb3554b6fabf9ffbf4c4bf4 | 224 | CurrencyConverter | Apache License 2.0 |
app/src/main/java/com/joel/jlibtemplate/room/daos/ChallengeDao.kt | jogcaetano13 | 524,525,946 | false | {"Kotlin": 85255} | package com.joel.jlibtemplate.room.daos
import androidx.paging.PagingSource
import androidx.room.*
import com.joel.jlibtemplate.models.Challenge
import kotlinx.coroutines.flow.Flow
@Dao
interface ChallengeDao {
@Query("SELECT * FROM challenges")
fun getChallenges(): PagingSource<Int, Challenge>
@Query("SELECT * FROM challenges LIMIT 1")
suspend fun getChallenge(): Challenge?
@Query("SELECT * FROM challenges")
fun getChallengesFlow(): Flow<List<Challenge>>
@Query("SELECT * FROM challenges")
suspend fun getChallengesSuspended(): List<Challenge>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(challenges: List<Challenge>): List<Long>
@Transaction
suspend fun replace(challenges: List<Challenge>) {
insert(challenges)
}
@Query("DELETE FROM challenges")
suspend fun deleteAll(): Int
} | 0 | Kotlin | 0 | 1 | 491d46c1925a1ffb8120b91a5f2c8e9e701ad4df | 883 | communication | MIT License |
app/src/main/java/com/mrmannwood/hexlauncher/DB.kt | MrMannWood | 298,718,785 | false | null | package com.mrmannwood.hexlauncher
import android.content.Context
import android.graphics.Color
import androidx.core.content.contentValuesOf
import androidx.room.OnConflictStrategy
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import timber.log.Timber
object DB {
private var db: Database? = null
fun get(context: Context): Database {
var database = db
if (database == null) {
synchronized(DB::class) {
database = db
if (database == null) {
database = Room.databaseBuilder(
context.applicationContext,
Database::class.java,
"database"
)
.addMigrations(MIGRATION_9_10)
.fallbackToDestructiveMigration()
.build()
db = database
}
}
}
return database!!
}
}
private val MIGRATION_9_10 = object : Migration(9, 10) {
override fun migrate(db: SupportSQLiteDatabase) {
Timber.d("Running room migration 9 -> 10")
db.execSQL(
"""
CREATE TABLE app_data_new (
component_name TEXT PRIMARY KEY NOT NULL,
label TEXT NOT NULL,
last_update_time INTEGER NOT NULL,
background_color INTEGER NOT NULL,
hidden INTEGER NOT NULL DEFAULT 0,
bgc_override INTEGER,
background_hidden INTEGER NOT NULL DEFAULT 0,
tags TEXT
)
""".trimIndent()
)
LauncherApplication.APPLICATION.appListManager.queryAppList()
.forEach { launcherItem ->
db.insert(
"app_data_new",
OnConflictStrategy.REPLACE,
contentValuesOf(
"component_name" to launcherItem.componentName.flattenToString(),
"label" to launcherItem.label,
"last_update_time" to -1,
"background_color" to Color.TRANSPARENT,
"hidden" to false,
"bgc_override" to null,
"background_hidden" to false,
"tags" to ""
)
)
db.execSQL(
"""
UPDATE app_data_new
SET
last_update_time = (SELECT last_update_time FROM app_data WHERE app_data.package_name = '${launcherItem.packageName}'),
background_color = (SELECT background_color FROM app_data WHERE app_data.package_name = '${launcherItem.packageName}'),
hidden = (SELECT hidden FROM app_data_decoration WHERE app_data_decoration.package_name_dec = '${launcherItem.packageName}'),
bgc_override = (SELECT bgc_override FROM app_data_decoration WHERE app_data_decoration.package_name_dec = '${launcherItem.packageName}'),
background_hidden = (SELECT background_hidden FROM app_data_decoration WHERE app_data_decoration.package_name_dec = '${launcherItem.packageName}'),
tags = (SELECT tags FROM app_data_decoration WHERE app_data_decoration.package_name_dec = '${launcherItem.packageName}')
WHERE component_name = '${launcherItem.componentName.flattenToString()}'
""".trimIndent()
)
}
db.execSQL("DROP TABLE app_data_decoration")
db.execSQL("DROP TABLE app_data")
db.execSQL("ALTER TABLE app_data_new RENAME TO app_data")
}
}
| 15 | Kotlin | 6 | 21 | 3c906dadf67c15464bb3122d5ae72854598302e7 | 3,817 | launcher | Apache License 2.0 |
core/domain/src/main/java/com/example/moviesapp/domain/GetTrendingMoviesUseCase.kt | erinfolami | 832,521,242 | false | {"Kotlin": 162181} | package com.example.moviesapp.domain
import com.example.moviesapp.data.repository.OfflineFirstMoviesAppRepository
import com.example.moviesapp.model.data.TrendingMovies
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
/**
* A use case which returns the Trending Movies.
*/
class GetTrendingMoviesUseCase @Inject constructor(
private val offlineFirstMoviesAppRepository: OfflineFirstMoviesAppRepository
) {
suspend operator fun invoke() : Flow<List<TrendingMovies>> {
return offlineFirstMoviesAppRepository.syncTrendingMovies()
}
} | 0 | Kotlin | 0 | 1 | 656022b0244765d8879611df25b69139223c7db2 | 564 | MoviesApp | Apache License 2.0 |
domain/src/main/java/com/aliasadi/domain/util/DispatchersProvider.kt | AliAsadi | 264,456,753 | false | {"Kotlin": 167332} | package com.aliasadi.domain.util
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.MainCoroutineDispatcher
interface DispatchersProvider {
val io: CoroutineDispatcher
val main: MainCoroutineDispatcher
val default: CoroutineDispatcher
} | 0 | Kotlin | 45 | 358 | d9c57d2c91b75d08c4741ac62caebfde1dd8b77e | 271 | Android-Clean-Architecture | Apache License 2.0 |
domain/src/main/java/com/aliasadi/domain/util/DispatchersProvider.kt | AliAsadi | 264,456,753 | false | {"Kotlin": 167332} | package com.aliasadi.domain.util
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.MainCoroutineDispatcher
interface DispatchersProvider {
val io: CoroutineDispatcher
val main: MainCoroutineDispatcher
val default: CoroutineDispatcher
} | 0 | Kotlin | 45 | 358 | d9c57d2c91b75d08c4741ac62caebfde1dd8b77e | 271 | Android-Clean-Architecture | Apache License 2.0 |
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/projectView/AbstractKotlinProjectViewTest.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.projectView
import com.intellij.ide.projectView.impl.nodes.AbstractPsiBasedNode
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.projectView.TestProjectTreeStructure
import com.intellij.psi.PsiElement
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.assertEqualsToFile
import com.intellij.util.CommonProcessors
import com.intellij.util.ui.tree.TreeUtil
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.test.Directives
import org.jetbrains.kotlin.idea.test.KotlinMultiFileHeavyProjectTestCase
import java.io.File
import javax.swing.tree.DefaultMutableTreeNode
import kotlin.io.path.*
abstract class AbstractKotlinProjectViewTest : KotlinMultiFileHeavyProjectTestCase() {
private lateinit var treeStructure: TestProjectTreeStructure
override fun setUp() {
super.setUp()
treeStructure = TestProjectTreeStructure(project, testRootDisposable)
}
override fun doMultiFileTest(testDataPath: String, globalDirectives: Directives) {
val path = Path(globalDirectives.getValue("PATH"))
val processor = object : CommonProcessors.FindFirstProcessor<VirtualFile>() {
override fun accept(t: VirtualFile): Boolean = Path(t.path).endsWith(path)
}
treeStructure.isShowMembers = globalDirectives.getBooleanValue("SHOW_MEMBERS")
FilenameIndex.processFilesByName(path.name, true, GlobalSearchScope.allScope(project), processor)
val resultFile = processor.foundValue ?: error("$path file is not found")
val pane = treeStructure.createPane()
val psiFile = resultFile.toPsiFile(project)
pane.select(psiFile, resultFile, true)
val tree = pane.tree
PlatformTestUtil.waitWhileBusy(tree)
val node = TreeUtil.findNode(tree.model.root as DefaultMutableTreeNode) {
val userObject = it.userObject
userObject is PsiElement && userObject.containingFile?.virtualFile == resultFile ||
userObject is AbstractPsiBasedNode<*> && (userObject.value as? PsiElement)?.containingFile?.virtualFile == resultFile
} ?: error("node is not found")
PlatformTestUtil.waitForCallback(TreeUtil.selectInTree(node, true, tree))
val psiBasedNode = node.userObject as? AbstractPsiBasedNode<*>
val navigationItem = psiBasedNode?.navigationItem
val actualTree = PlatformTestUtil.print(/* tree = */ tree, /* withSelection = */ true)
assertEqualsToFile(
description = "The tree is different",
expected = File(testDataPath.substringBeforeLast('.') + ".txt"),
actual = sanitizeTree(
"Node: $node\n" +
"User object class: ${psiBasedNode?.let { it::class.simpleName }}\n\n" +
"Value: ${psiBasedNode?.value}\n" +
"Value file: ${filePath(psiBasedNode?.value)}\n\n" +
deepNavigation(navigationItem) + "\n\n" +
actualTree
)
)
}
private fun filePath(element: Any?): String? {
if (element !is PsiElement) return null
val virtualFile = element.containingFile.virtualFile
val fileSystem = virtualFile.fileSystem
val prefixFile = if (fileSystem is JarFileSystem) {
fileSystem.getVirtualFileForJar(virtualFile)?.path?.let(::Path)?.parent!!
} else {
module.moduleNioFile.parent.listDirectoryEntries().single()
}
val path = Path(virtualFile.path)
return path.relativeTo(prefixFile).pathString
}
private fun deepNavigation(element: Any?): String {
if (element == null) return "Navigation item not found"
return buildString {
deepNavigation(element, 0)
}
}
private fun StringBuilder.deepNavigation(element: Any, count: Int) {
appendLine("Navigation item #${count}: $element")
appendLine("Navigation item file #${count}: ${filePath(element)}")
if (element !is PsiElement) return
val navigateElement = element.navigationElement
if (navigateElement == element) return
deepNavigation(navigateElement, count + 1)
}
private fun sanitizeTree(tree: String): String {
val resultSequence = Holder.STDLIB_REGEX.findAll(tree)
var resultString = tree
for (matchResult in resultSequence) {
resultString = resultString.replace(matchResult.value, matchResult.groupValues[1] + matchResult.groupValues[3])
}
return resultString
}
private object Holder {
val STDLIB_REGEX: Regex = Regex("(kotlin-stdlib.*?)(-\\d.*)([.]jar)")
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 5,033 | intellij-community | Apache License 2.0 |
shared/src/commonMain/kotlin/com/mocoding/pokedex/data/di/DataModule.kt | MohamedRejeb | 606,436,499 | false | {"Kotlin": 123809, "Swift": 6252, "Ruby": 2298} | package com.mocoding.pokedex.data.di
import com.mocoding.pokedex.data.repository.PokemonRepository
import com.mocoding.pokedex.data.repository.PokemonRepositoryImpl
import org.koin.dsl.module
val dataModule = module {
single<PokemonRepository> { PokemonRepositoryImpl() }
} | 4 | Kotlin | 48 | 569 | e13c46fdcff7b21353019da9a85438e2088c529d | 279 | Pokedex | Apache License 2.0 |
app/src/main/java/me/shetj/mp3recorder/record/bean/Record.kt | SheTieJun | 207,213,419 | false | {"Kotlin": 301463} | package me.shetj.mp3recorder.record.bean
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* 录音
*/
@Entity(tableName = "record")
class Record {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id: Int = 0
@ColumnInfo(name = "user_id")
var user_id: String ? = null //是否绑定用户,默认不绑定用户
@ColumnInfo(name = "audio_url")
var audio_url: String? = null//保存的路径
@ColumnInfo(name = "audio_name")
var audioName: String? = null//录音的名称
@ColumnInfo(name = "audio_length")
var audioLength: Int = 0//长度
@ColumnInfo(name = "audio_content")
var audioContent: String? = null//内容
@ColumnInfo(name = "otherInfo")
var otherInfo: String? = null// 预览信息
constructor()
constructor(
user_id: String,
audio_url: String,
audioName: String,
audioLength: Int,
content: String
) {
this.user_id = user_id
this.audio_url = audio_url
this.audioName = audioName
this.audioLength = audioLength
this.audioContent = content
}
}
| 0 | Kotlin | 2 | 30 | 75da57f9e5f98779950e736fa40018a141e8c0f9 | 1,115 | Mp3Recorder | MIT License |
Carbon_Katha application/app/src/main/java/project/environment/carby/signin/SignInViewModel.kt | mehulaswar06 | 763,045,541 | false | {"Kotlin": 282027, "CSS": 99243, "HTML": 46982, "TypeScript": 8520, "JavaScript": 4802} | //import androidx.lifecycle.ViewModel
//import kotlinx.coroutines.flow.MutableStateFlow
//import kotlinx.coroutines.flow.asStateFlow
//import kotlinx.coroutines.flow.update
//import project.environment.carby.signin.SignInResult
//import project.environment.carby.signin.SignInState
//
//
//class SignInViewModel: ViewModel() {
//
// private val _state = MutableStateFlow(SignInState())
// val state = _state.asStateFlow()
//
// fun onSignInResult(result: SignInResult) {
// _state.update { it.copy(
// isSignInSuccessful = result.data != null,
// signInError = result.errorMessage
// ) }
// }
//
// fun resetState() {
// _state.update { SignInState() }
// }
//} | 0 | Kotlin | 0 | 0 | 1b4ae7648a72f192668d7da19aa9b1a94f63adaf | 722 | CarbonKatha | MIT License |
app/src/main/java/cisang/com/android_essencial/extensions/Activity_Extensions.kt | Wcisang | 131,050,458 | false | null | package cisang.com.android_essencial.extensions
import android.support.annotation.IdRes
import android.support.v4.app.Fragment
import android.support.v7.app.ActionBar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
/**
* Created by willi on 14/02/2018.
*/
fun AppCompatActivity.onClick(@IdRes viewId: Int, onClick: (v: android.view.View?) -> Unit){
val view = findViewById<View>(viewId)
view.setOnClickListener(onClick)
}
fun AppCompatActivity.setupToolbar(@IdRes id: Int, title: String? = null, upNavigation: Boolean = false): ActionBar {
val toolbar = findViewById<Toolbar>(id)
setSupportActionBar(toolbar)
if (title != null)
supportActionBar?.title = title
supportActionBar?.setDisplayHomeAsUpEnabled(upNavigation)
return supportActionBar!!
}
fun AppCompatActivity.addFragment(@IdRes layoutId: Int, fragment: Fragment) {
fragment.arguments = intent.extras
val ft = supportFragmentManager.beginTransaction()
ft.add(layoutId, fragment)
ft.commit()
}
| 0 | Kotlin | 0 | 0 | 200830614da0a41ed50ef8fb0fcde803d58b85f9 | 1,076 | Android_Essencial | MIT License |
src/main/kotlin/dec22/Main.kt | dladukedev | 318,188,745 | false | null | package dec22
fun parsePlayer(input: String): List<Int> {
return input
.lines()
.map { it.toInt() }
}
fun calculateScore(deck: List<Int>): Long {
return deck.reversed().foldIndexed(0L) { index, acc, card ->
acc + ((index + 1) * card)
}
}
fun main() {
val player1 = parsePlayer(inputPlayer1)
val player2 = parsePlayer(inputPlayer2)
println("------------ PART 1 ------------")
val firstGameResult = playGame(GameState(player1, player2))
val firstGameScore = calculateScore(firstGameResult)
println("result: $firstGameScore")
println("------------ PART 2 ------------")
val (_, secondGameResult) = playRecursiveGame(player1, player2)
val secondGameScore = calculateScore(secondGameResult)
println("result: $secondGameScore")
} | 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 805 | advent-of-code-2020 | MIT License |
app/src/main/java/com/yamanf/shoppingapp/data/api/ApiService.kt | yamanf | 557,850,840 | false | null | package com.yamanf.shoppingapp.data.api
import com.yamanf.shoppingapp.data.model.Products
import com.yamanf.shoppingapp.data.model.ProductsItem
import retrofit2.http.GET
import retrofit2.http.Path
interface ApiService {
@GET("products")
suspend fun getAllProducts():Products
@GET("products/{product_id}")
suspend fun getProductDetail(@Path("product_id") id: String): ProductsItem
} | 0 | Kotlin | 0 | 0 | 6a70f24f614d313e18e69a202ae9e79a93aa8cf7 | 401 | PazaramaBootcamp-FinalProject | Apache License 2.0 |
mobile_app1/module1145/src/main/java/module1145packageKt0/Foo6.kt | uber-common | 294,831,672 | false | null | package module1145packageKt0;
annotation class Foo6Fancy
@Foo6Fancy
class Foo6 {
fun foo0(){
module1145packageKt0.Foo5().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 231 | android-build-eval | Apache License 2.0 |
app/src/main/java/study/android/foodrecipes/adapters/OnRecipeClickListener.kt | mengli | 322,697,848 | false | null | package study.android.foodrecipes.adapters
interface OnRecipeClickListener {
fun onRecipeClick(position: Int)
} | 0 | Kotlin | 0 | 0 | 4df8355c14b3f445e6498c8d21da7c1ac3fc326c | 117 | MVVMFoodRecipes | Apache License 2.0 |
src/main/kotlin/com/cynquil/amethyst/rpg/item/RpgTrinket.kt | cydq | 671,393,100 | false | null | package com.cynquil.amethyst.rpg.item
import com.cynquil.amethyst.group.AmItemGroup
import com.cynquil.amethyst.rpg.Rarity
import com.cynquil.amethyst.rpg.item.RpgItem
import com.cynquil.mango.Mango
import dev.emi.trinkets.api.TrinketsApi
import net.fabricmc.fabric.api.item.v1.FabricItemSettings
import net.minecraft.item.ItemGroup
import net.minecraft.registry.RegistryKey
import net.minecraft.util.Identifier
open class RpgTrinket(
key: Identifier,
rarity: Rarity,
lore: List<String>? = null,
group: AmItemGroup? = null,
settings: Settings = FabricItemSettings()
) : RpgItem(key, rarity, lore, group, settings) {
val trinket = TrinketsApi.getTrinket(this)
override fun register() {
super.register()
TrinketsApi.registerTrinket(this, trinket)
}
} | 0 | Kotlin | 0 | 0 | 2bb505adef54264d5d358b7ac66ef1fc6b8fd89c | 802 | mango | Creative Commons Zero v1.0 Universal |
kotlintest-assertions/src/jsMain/kotlin/io/kotlintest/stackTrace.kt | GlitchyHydra | 178,073,966 | true | {"Kotlin": 1247244, "Java": 5525, "Shell": 125} | package io.kotlintest
actual fun stackTrace(t: Throwable): String? {
TODO()
} | 0 | Kotlin | 0 | 0 | 394eaf7b267c9b2929c3f00d5196042302fa8a27 | 80 | kotlintest | Apache License 2.0 |
analysis/analysis-test-framework/tests/org/jetbrains/kotlin/analysis/test/framework/base/AbstractAnalysisApiBasedSingleModuleTest.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.test.framework.base
import org.jetbrains.kotlin.analysis.test.framework.project.structure.ktModuleProvider
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.model.TestModule
import org.jetbrains.kotlin.test.services.TestModuleStructure
import org.jetbrains.kotlin.test.services.TestServices
abstract class AbstractAnalysisApiBasedSingleModuleTest : AbstractAnalysisApiBasedTest() {
final override fun doTestByModuleStructure(moduleStructure: TestModuleStructure, testServices: TestServices) {
val singleModule = moduleStructure.modules.single()
val ktFiles = testServices.ktModuleProvider.getModuleFiles(singleModule).filterIsInstance<KtFile>()
doTestByFileStructure(ktFiles, singleModule, testServices)
}
protected abstract fun doTestByFileStructure(ktFiles: List<KtFile>, module: TestModule, testServices: TestServices)
} | 162 | null | 5729 | 46,436 | c902e5f56504e8572f9bc13f424de8bfb7f86d39 | 1,132 | kotlin | Apache License 2.0 |
src/main/kotlin/com/swisschain/matching/engine/outgoing/messages/v2/enums/OrderSide.kt | swisschain | 255,464,363 | false | {"Gradle": 2, "Text": 2, "Ignore List": 1, "Markdown": 1, "Kotlin": 578, "XML": 2, "Shell": 2, "Batchfile": 1, "Java": 3, "Protocol Buffer": 14, "Java Properties": 1, "INI": 2, "YAML": 2} | package com.swisschain.matching.engine.outgoing.messages.v2.enums
enum class OrderSide(val id: Int) {
UNKNOWN_ORDER_SIDE(0),
BUY(1),
SELL(2)
} | 1 | null | 1 | 1 | 5ef23544e9c5b21864ec1de7ad0f3e254044bbaa | 155 | Exchange.MatchingEngine | Apache License 2.0 |
ftc-2021-2022-offseason/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomy/AutoBlueCycles.kt | QubeRomania | 491,215,964 | false | {"Java": 210390, "Kotlin": 52111} | package org.firstinspires.ftc.teamcode.autonomy
class AutoBlueCycles {
} | 1 | null | 1 | 1 | 6a19b7460d416fa4bddf442b7ef4dcf539c7ae9b | 73 | ftc-2021-2022-offseason | Apache License 2.0 |
jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/util/TreeCacheTest.kt | jitsi | 9,657,943 | false | null | /*
* Copyright @ 2018 - present 8x8, 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.jitsi.nlj.util
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import java.util.AbstractMap.SimpleImmutableEntry
class TreeCacheTest : ShouldSpec() {
override fun isolationMode() = IsolationMode.InstancePerLeaf
data class Dummy(val data: String)
private val treeCache = TreeCache<Dummy>(16)
/** Shorthand for a Map.Entry mapping [key] to a Dummy containing [dummyVal] */
private fun ed(key: Int, dummyVal: String) = SimpleImmutableEntry(key, Dummy(dummyVal))
init {
context("Reading from an empty TreeCache") {
should("return null") {
treeCache.getEntryBefore(10) shouldBe null
}
should("have size 0") {
treeCache.size shouldBe 0
}
}
context("An entry in a TreeCache") {
treeCache.insert(5, Dummy("A"))
should("be found looking up values after it") {
treeCache.getEntryBefore(10) shouldBe ed(5, "A")
}
should("be found looking up the same value") {
treeCache.getEntryBefore(5) shouldBe ed(5, "A")
}
should("not be found looking up values before it") {
treeCache.getEntryBefore(3) shouldBe null
}
should("not be expired even if values long after it are looked up") {
treeCache.getEntryBefore(10000) shouldBe ed(5, "A")
}
should("cause the tree to have size 1") {
treeCache.size shouldBe 1
}
}
context("Multiple values in a TreeCache") {
treeCache.insert(5, Dummy("A"))
treeCache.insert(10, Dummy("B"))
should("Be looked up properly") {
treeCache.getEntryBefore(13) shouldBe ed(10, "B")
treeCache.size shouldBe 2
}
should("Persist within the cache window") {
treeCache.getEntryBefore(8) shouldBe ed(5, "A")
treeCache.size shouldBe 2
}
should("Not expire an older one if it is the only value outside the cache window") {
treeCache.getEntryBefore(25) shouldBe ed(10, "B")
treeCache.getEntryBefore(8) shouldBe ed(5, "A")
treeCache.size shouldBe 2
}
should("Expire older ones when newer ones are outside the cache window") {
treeCache.getEntryBefore(30) shouldBe ed(10, "B")
treeCache.getEntryBefore(8) shouldBe null
treeCache.size shouldBe 1
}
should("Expire only older ones when later values are inserted") {
treeCache.insert(40, Dummy("C"))
treeCache.getEntryBefore(13) shouldBe ed(10, "B")
treeCache.getEntryBefore(8) shouldBe null
treeCache.size shouldBe 2
}
should("Persist values within the window while expiring values outside it") {
treeCache.insert(15, Dummy("C"))
treeCache.getEntryBefore(8) shouldBe ed(5, "A")
treeCache.getEntryBefore(25) shouldBe ed(15, "C")
treeCache.getEntryBefore(13) shouldBe ed(10, "B")
treeCache.getEntryBefore(8) shouldBe ed(5, "A")
treeCache.size shouldBe 3
treeCache.insert(30, Dummy("D"))
treeCache.getEntryBefore(8) shouldBe null
treeCache.size shouldBe 3
}
}
}
}
| 170 | null | 989 | 2,900 | b7dba8242cfaa84364bf6988cc097611346505c0 | 4,199 | jitsi-videobridge | Apache License 2.0 |
comment/src/main/java/com/abhat/comment/ui/PostDetailState.kt | AnirudhBhat | 257,323,871 | false | null | package com.abhat.comment.ui
import com.abhat.core.model.RedditResponse
sealed class PostDetailState {
data class Loading(val isLoading: Boolean): PostDetailState()
data class Success(val response: RedditResponse?): PostDetailState()
data class Failure(val throwable: Throwable?): PostDetailState()
}
| 1 | null | 1 | 1 | 9036e653ed15d34241dcc5397efc687bae89328f | 315 | Reddit-client | Apache License 2.0 |
sample/src/main/java/io/lamart/glyph/sample/basic/glyphs/rootGlyph.kt | Lamartio | 186,559,963 | false | null | package io.lamart.glyph.sample.basic.glyphs
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toolbar
import io.lamart.glyph.Dispose
import io.lamart.glyph.disposeOf
import io.lamart.glyph.outputOf
import io.lamart.glyph.sample.R
import io.lamart.glyph.sample.basic.SampleGlyph
import io.lamart.glyph.sample.basic.State
fun rootGlyph(): SampleGlyph<State> =
{
val layout = LayoutInflater
.from(parent.context)
.inflate(R.layout.root, parent, false)
.also(parent::addView)
val toolBar: Toolbar = layout.findViewById(R.id.toolBar)
val content: ViewGroup = layout.findViewById(R.id.content)
val disposeCounter: Dispose = +content + outputOf { it.count } + counterGlyph()
disposeOf(
disposeCounter,
{ parent.removeView(layout) }
)
} | 1 | Kotlin | 1 | 2 | 9a12ec4998e3802d237cce06fe66e11212e55a22 | 885 | Glyph | Apache License 2.0 |
detox/android/detox/src/main/java/com/wix/detox/espresso/scroll/DetoxSwiper.kt | wix | 61,204,547 | false | null | package com.wix.detox.espresso.scroll
interface DetoxSwiper {
fun startAt(touchX: Float, touchY: Float)
fun moveTo(targetX: Float, targetY: Float): Boolean
fun finishAt(releaseX: Float, releaseY: Float)
}
| 138 | null | 1760 | 9,233 | a5265001064d8a573c9944634dc4bc6667c41125 | 218 | Detox | MIT License |
app/src/main/java/did/chris/alt/ui/constraintui/coinlist/coinListAdapter/CoinListViewHolder.kt | Flinted | 118,820,530 | false | {"Kotlin": 260564, "Java": 727} | package did.chris.alt.ui.constraintui.coinlist.coinListAdapter
import android.support.constraint.ConstraintLayout
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import did.chris.alt.R
class CoinListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// Properties
var card: ConstraintLayout = itemView.findViewById(R.id.main_card)
var name: TextView = itemView.findViewById(R.id.coin_list_name)
var ticker: TextView = itemView.findViewById(R.id.coin_ticker)
var price: TextView = itemView.findViewById(R.id.coin_price)
var favouriteIcon: ImageView = itemView.findViewById(R.id.coin_list_item_favourite_checkbox)
var oneHourChange: TextView = itemView.findViewById(R.id.coin_1h_change)
var twentyFourHourChange: TextView = itemView.findViewById(R.id.coin_1d_change)
var sevenDayChange: TextView = itemView.findViewById(R.id.coin_1w_change)
var oneHourIndicator: ImageView = itemView.findViewById(R.id.indicator_1h)
var twentyFourHourIndicator: ImageView = itemView.findViewById(R.id.indicator_1d)
var sevenDayIndicator: ImageView = itemView.findViewById(R.id.indicator_1w)
}
| 0 | Kotlin | 0 | 0 | 52fbabc0f24712b5b1721df047da32c8f8301d2a | 1,225 | ALT-Crypto-Tracker | Apache License 2.0 |
core/src/main/kotlin/info/laht/threekt/renderers/shaders/lib/shadow_frag.kt | markaren | 196,544,572 | false | null | package info.laht.threekt.renderers.shaders.lib
internal val __shadow_frag = """
uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
#include <fog_fragment>
}
"""
| 7 | Kotlin | 14 | 187 | 8dc6186d777182da6831cf1c79f39ee2d5960cd7 | 431 | three.kt | MIT License |
Oxygen/bungee/src/main/kotlin/cc/fyre/stark/profile/ProfileMessageListeners.kt | AndyReckt | 364,514,997 | false | {"Java": 12055418, "Kotlin": 766337, "Shell": 5518} | /*
* Copyright (c) 2020.
* Created by YoloSanta
* Created On 10/22/20, 1:23 AM
*/
package cc.fyre.stark.profile
import cc.fyre.stark.Stark
import cc.fyre.stark.core.pidgin.message.handler.IncomingMessageHandler
import cc.fyre.stark.core.pidgin.message.listener.MessageListener
import com.google.gson.JsonObject
import java.util.*
class ProfileMessageListeners : MessageListener {
@IncomingMessageHandler("GRANT_UPDATE")
fun onGrantUpdate(data: JsonObject) {
val uuid = UUID.fromString(data.get("uuid").asString)
val profile = Stark.instance.core.getProfileHandler().pullProfileUpdates(uuid)
profile.apply()
}
@IncomingMessageHandler("PUNISHMENT_UPDATE")
fun onPunishmentUpdate(data: JsonObject) {
val uuid = UUID.fromString(data.get("uuid").asString)
Stark.instance.core.getProfileHandler().pullProfileUpdates(uuid)
}
} | 1 | null | 1 | 1 | 200501c7eb4aaf5709b4adceb053fee6707173fa | 893 | Old-Code | Apache License 2.0 |
MeepMeepTesting/com/noahbres/meepmeep/core/anim/Ease.kt | SpacePianist0 | 575,118,910 | true | {"Java Properties": 2, "Gradle": 8, "Shell": 2, "Markdown": 8, "Git Attributes": 2, "Batchfile": 2, "Ignore List": 5, "Java": 108, "Kotlin": 37, "Gradle Kotlin DSL": 2, "XML": 26, "INI": 1, "Text": 3} | package com.noahbres.meepmeep.core.anim
// Eases based off of https://gist.github.com/gre/1650294
class Ease {
companion object {
@JvmStatic
val LINEAR: (t: Double) -> Double = { it }
@JvmStatic
val EASE_IN_QUAD: (t: Double) -> Double = { it * it }
@JvmStatic
val EASE_OUT_QUAD: (t: Double) -> Double = { it * (2 - it) }
@JvmStatic
val EASE_IN_OUT_QUAD: (t: Double) -> Double = { if (it < 0.5) 2 * it * it else -1 + (4 - 2 * it) * it }
@JvmStatic
val EASE_IN_CUBIC: (t: Double) -> Double = { it * it * it }
@JvmStatic
val EASE_OUT_CUBIC: (t: Double) -> Double = {
var t = it
(--t) * t * t + 1
}
@JvmStatic
val EASE_IN_OUT_CUBIC: (t: Double) -> Double = { if (it < 0.5) 4 * it * it * it else (it - 1) * (2 * it - 2) * (2 * it - 2) + 1 }
@JvmStatic
val EASE_IN_QUART: (t: Double) -> Double = { it * it * it * it }
@JvmStatic
val EASE_OUT_QUART: (t: Double) -> Double = {
var t = it
1 - (--t) * t * t * t
}
@JvmStatic
val EASE_IN_OUT_QUART: (t: Double) -> Double = {
var t = it
if (t < 0.5) 8 * it * it * it * it else 1 - 8 * (--t) * t * t * t
}
@JvmStatic
val EASE_IN_QUINT: (t: Double) -> Double = { it * it * it * it * it }
@JvmStatic
val EASE_OUT_QUINT: (t: Double) -> Double = {
var t = it
1 + (--t) * t * t * t * t
}
@JvmStatic
val EASE_IN_OUT_QUINT: (t: Double) -> Double = {
var t = it
if (t < 0.5) 16 * t * t * t * t * t else 1 + 16 * (--t) * t * t * t * t
}
}
} | 0 | null | 0 | 0 | 006d37c28e67ec7cac1e570ae39323c997f87bd2 | 1,757 | teamcode-2021FORK | MIT License |
app/src/main/java/com/gworks/richedittext/Util.kt | TheAndroidMonk | 116,714,682 | false | {"Gradle": 3, "Java Properties": 2, "Text": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 40, "XML": 14, "Java": 1} | package com.gworks.richedittext
import android.text.Spannable
import android.view.View
import android.view.inputmethod.BaseInputConnection
import android.widget.RelativeLayout
import com.gworks.richedittext.markups.AttributedMarkup
import com.gworks.richedittext.markups.Markup
fun updateSpanFlags(text: Spannable, span: Any?, flags: Int) {
text.setSpan(span, text.getSpanStart(span), text.getSpanEnd(span), flags)
}
/**
* Returns the first index of given char if it is present in the range [start, limit).
* Returns the limit if not present in the range.
*/
fun CharSequence.indexOf(char: Char, start: Int = 0, limit: Int = this.length, ignoreCase: Boolean = false): Int {
val result = indexOf(char, start, ignoreCase)
return if (result >= 0) minOf(result, limit) else limit
}
/**
* Returns the last index of given char if it is present in the range [start, limit).
* Returns the limit if not present in the range.
*/
fun CharSequence.lastIndexOf(char: Char, start: Int = 0, limit: Int = this.length, ignoreCase: Boolean = false): Int {
val result = lastIndexOf(char, start, ignoreCase)
return if (result >= 0) minOf(result, limit) else limit
}
fun CharSequence.leftIndexOf(char: Char, start: Int = this.length, limit: Int = 0): Int {
var st = 0
for (i in minOf(this.length - 1, start) downTo limit) {
if (this[i] == char) {
st = i
break
}
}
return st
}
fun Appendable.appendPlain(text: CharSequence, start: Int = 0, end: Int = start + text.length) {
for (i in start until end) this.append(text[i])
}
/**
* Returns true if a and b are equal, including if they are both null up to a certain range.
* @param a first CharSequence to check
* @param b second CharSequence to check
* @return true if a and b are equal
*/
fun equalsInRange(a: CharSequence?, b: CharSequence?, length: Int, offsetA: Int = 0, offsetB: Int = 0): Boolean {
return (a === b) || matchingLength(a, b, length, offsetA, offsetB) == length
}
fun matchingLength(a: CharSequence?, b: CharSequence?, limit: Int, offsetA: Int = 0, offsetB: Int = 0): Int {
if (a != null && b != null) {
val lim = minOf(limit, minOf(a.length, b.length))
for (i in 0 until lim) {
if (a[offsetA + i] != b[offsetB + i]) return i + 1
}
return lim
}
return -1
}
fun getComposingLength(spanned: Spannable) = getComposingEnd(spanned) - getComposingStart(spanned)
fun getComposingStart(spanned: Spannable) = BaseInputConnection.getComposingSpanStart(spanned)
fun getComposingEnd(spanned: Spannable) = BaseInputConnection.getComposingSpanEnd(spanned)
fun composingRegionChanged(spanned: Spannable, start: Int, end: Int) = getComposingStart(spanned) != start || getComposingEnd(spanned) != end
fun isAttributed(markupType: Class<out Markup>) = AttributedMarkup::class.javaObjectType.isAssignableFrom(markupType)
fun inside(rangeSt: Int, rangeEn: Int, from: Int, to: Int) = from >= rangeSt && to <= rangeEn
fun RelativeLayout.addView(view: View, w: Int, h: Int, rule1: Int, subject1: Int, rule2: Int = -10, subject2: Int = -10, shouldSetId: Boolean = true): RelativeLayout.LayoutParams {
if (shouldSetId)
view.id = View.generateViewId()
val pms = RelativeLayout.LayoutParams(w, h)
pms.addRule(rule1, subject1)
if (rule2 != -10 && subject2 != -10)
pms.addRule(rule2, subject2)
addView(view, pms)
return pms
}
| 0 | Kotlin | 0 | 1 | 1f395cf171ed4ba36138047e417bcc60d4a04f47 | 3,448 | RichEditText | Apache License 2.0 |
app/src/main/java/com/duckduckgo/app/tabs/db/TabsDao.kt | andrey-p | 164,923,819 | false | null | /*
* Copyright (c) 2018 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.app.tabs.db
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
import com.duckduckgo.app.tabs.model.TabEntity
import com.duckduckgo.app.tabs.model.TabSelectionEntity
import javax.inject.Singleton
@Dao
@Singleton
abstract class TabsDao {
@Query("select * from tabs order by position limit 1")
abstract fun firstTab(): TabEntity?
@Query("select * from tabs inner join tab_selection ON tabs.tabId = tab_selection.tabId order by position limit 1")
abstract fun selectedTab(): TabEntity?
@Query("select * from tabs inner join tab_selection ON tabs.tabId = tab_selection.tabId order by position limit 1")
abstract fun liveSelectedTab(): LiveData<TabEntity>
@Query("select * from tabs order by position")
abstract fun tabs(): List<TabEntity>
@Query("select * from tabs order by position")
abstract fun liveTabs(): LiveData<List<TabEntity>>
@Query("select * from tabs where tabId = :tabId")
abstract fun tab(tabId: String): TabEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertTab(tab: TabEntity)
@Update
abstract fun updateTab(tab: TabEntity)
@Delete
abstract fun deleteTab(tab: TabEntity)
@Query("delete from tabs")
abstract fun deleteAllTabs()
@Query("delete from tabs where url IS null")
abstract fun deleteBlankTabs()
@Query("update tabs set position = position + 1 where position >= :position")
abstract fun incrementPositionStartingAt(position: Int)
@Transaction
open fun addAndSelectTab(tab: TabEntity) {
deleteBlankTabs()
insertTab(tab)
insertTabSelection(TabSelectionEntity(tabId = tab.tabId))
}
@Transaction
open fun deleteTabAndUpdateSelection(tab: TabEntity) {
deleteTab(tab)
if (selectedTab() != null) {
return
}
firstTab()?.let {
insertTabSelection(TabSelectionEntity(tabId = it.tabId))
}
}
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertTabSelection(tabSelectionEntity: TabSelectionEntity)
@Transaction
open fun insertTabAtPosition(tab: TabEntity) {
incrementPositionStartingAt(tab.position)
insertTab(tab)
}
fun lastTab(): TabEntity? {
return tabs().lastOrNull()
}
}
| 1 | null | 1 | 1 | e4328e68fda04b2e7d874fd0c974311014afe9fe | 2,954 | Android | Apache License 2.0 |
app/src/main/java/jermaine/technews/ui/bookmarks/BookmarksViewModel.kt | jermainedilao | 124,178,104 | false | {"Gradle": 6, "Markdown": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Proguard": 4, "Java": 3, "XML": 25, "Kotlin": 73, "YAML": 1, "JSON": 2, "Gradle Kotlin DSL": 1} | package jermaine.technews.ui.bookmarks
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import jermaine.domain.articles.interactors.articles.bookmarks.FetchBookmarkedArticleUseCase
import jermaine.domain.articles.interactors.articles.bookmarks.RemoveBookmarkedArticleUseCase
import jermaine.technews.R
import jermaine.technews.base.BaseViewModel
import jermaine.technews.ui.articles.model.ArticleViewObject
import jermaine.technews.ui.articles.model.UIState
import jermaine.technews.ui.articles.util.ViewObjectParser
import jermaine.technews.util.ResourceManager
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class BookmarksViewModel @Inject constructor(
private val resourceManager: ResourceManager,
private val fetchBookmarkedArticleUseCase: FetchBookmarkedArticleUseCase,
private val removeBookmarkedArticleUseCase: RemoveBookmarkedArticleUseCase
) : BaseViewModel() {
private val _uiState: MutableLiveData<UIState> by lazy {
MutableLiveData<UIState>(UIState.Loading)
}
val uiState: LiveData<UIState> = _uiState
private val _bookmarkedArticles by lazy {
MutableLiveData<List<ArticleViewObject>>()
}
val bookmarkedArticles: LiveData<List<ArticleViewObject>> = _bookmarkedArticles
/**
* Returns list of bookmarked articles.
**/
fun fetchBookmarkedArticles(page: Int) {
viewModelScope.launch {
try {
_uiState.postValue(UIState.Loading)
_bookmarkedArticles.value = fetchBookmarkedArticleUseCase
.execute(page)
.map {
ViewObjectParser.articleToViewObjectRepresentation(it, resourceManager)
}
_uiState.postValue(UIState.HasData)
} catch (e: Exception) {
_uiState.postValue(UIState.Error(R.string.error_text))
}
}
}
/**
* Removes bookmarked article.
**/
fun removeBookmarkedArticle(article: ArticleViewObject): Completable =
removeBookmarkedArticleUseCase.execute(article.toDomainRepresentation())
} | 0 | Kotlin | 0 | 2 | 2bb2efc6067db95a5fce7ae16cbbcbda58c08b60 | 2,344 | technews | Apache License 2.0 |
Leetcode-Solution-Kotlin/copyListWithRandomPointer.kt | harshraj9988 | 491,534,142 | false | {"Java": 591477, "Kotlin": 183437, "C++": 86767, "Python": 24653, "JavaScript": 4637} | class CopyListWithRandomPointer {
inner class Node(var `val`: Int) {
var next: Node? = null
var random: Node? = null
}
fun copyRandomList(node: Node?): Node? {
if(node == null) return null
val nodePool = HashMap<Int, Pair<Node, Node>>()
var trav : Node? = node
while(trav != null) {
nodePool[trav.hashCode()] = Pair(trav, Node(trav.`val`))
trav = trav.next
}
trav = node
while(trav != null) {
val old = nodePool[trav.hashCode()]!!.first
val currNode = nodePool[trav.hashCode()]!!.second
if(old.next != null) {
currNode.next = nodePool[old.next!!.hashCode()]!!.second
}
if(old.random != null) {
currNode.random = nodePool[old.random!!.hashCode()]!!.second
}
trav = trav.next
}
return nodePool[node.hashCode()]!!.second
}
} | 1 | null | 1 | 1 | 3fc29ceffe3eaf92d9e6e79bfb097ba0db1c40ad | 966 | LeetCode-solutions | Apache License 2.0 |
java/idea-ui/testSrc/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/SimpleMergeQueueTest.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.ui.configuration.projectRoot.daemon
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.LoggedErrorProcessor
import com.intellij.testFramework.UsefulTestCase.assertOrderedEquals
import com.intellij.util.Alarm.ThreadToUse
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
import java.util.concurrent.Semaphore
class SimpleMergeQueueTest {
private lateinit var disposable: Disposable
@BeforeEach
fun setUp() {
disposable = Disposer.newDisposable()
}
@AfterEach
fun tearDown() {
Disposer.dispose(disposable)
}
@ParameterizedTest
@EnumSource(ThreadToUse::class, names = ["SWING_THREAD", "POOLED_THREAD"])
fun duplicateIsRemoved(threadToUse: ThreadToUse) {
val list = mutableListOf<String>()
executeInQueue(threadToUse) { queue ->
queue.queue(Task("0", "0", list))
queue.queue(Task("1", "1", list))
queue.queue(Task("2", "2", list))
queue.queue(Task("0", "3", list)) // equals to the first task
}
synchronized(list) {
assertOrderedEquals(list, "0", "1", "2")
}
}
@ParameterizedTest
@EnumSource(ThreadToUse::class, names = ["SWING_THREAD", "POOLED_THREAD"])
fun duplicateIsNotRemovedAfterTimeout(threadToUse: ThreadToUse) {
val list = mutableListOf<String>()
val queue = SimpleMergingQueue<Runnable>("test", 100, false, threadToUse, disposable)
queue.queue(Task("0", "0", list))
queue.queue(Task("1", "1", list))
waitForQueue(queue)
queue.queue(Task("0", "0", list))
queue.queue(Task("1", "1", list))
waitForQueue(queue)
synchronized(list) {
assertOrderedEquals(list, "0", "1", "0", "1")
}
}
@ParameterizedTest
@EnumSource(ThreadToUse::class, names = ["SWING_THREAD", "POOLED_THREAD"])
fun errorInTaskDoesNotPreventConsequentTasksFromExecuting(threadToUse: ThreadToUse) {
val list = mutableListOf<String>()
val error = RuntimeException()
// testLogger usually throws. Instead, let's intercept the error. In this case, the test works the same way as in production
val loggerError = LoggedErrorProcessor.executeAndReturnLoggedError {
executeInQueue(threadToUse) { queue ->
queue.queue(Task("0", "0", list))
queue.queue {
throw error // this error should not prevent the next task from execution
}
queue.queue(Task("1", "1", list))
}
}
Assertions.assertEquals(loggerError, error)
synchronized(list) {
assertOrderedEquals(list, "0", "1")
}
}
private fun waitForQueue(queue: SimpleMergingQueue<Runnable>) {
val semaphore = Semaphore(0)
queue.queue(Runnable {
semaphore.release()
})
queue.start()
semaphore.acquire() // wait for tasks to be processed
}
private fun executeInQueue(threadToUse: ThreadToUse, block: (SimpleMergingQueue<Runnable>) -> Unit) {
val queue = SimpleMergingQueue<Runnable>("test", 100, false, threadToUse, disposable)
block(queue)
waitForQueue(queue)
}
private class Task(val equality: String, val text: String, val list: MutableList<String>) : Runnable {
override fun run() {
synchronized(list) {
list += text
}
}
override fun hashCode(): Int {
return equality.hashCode()
}
override fun equals(other: Any?): Boolean {
return other is Task && equality == other.equality
}
}
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 3,735 | intellij-community | Apache License 2.0 |
server/src/main/com/broll/gainea/server/core/events/RandomEvent.kt | Rolleander | 253,573,579 | false | {"Kotlin": 502373, "Java": 305905, "HTML": 1714, "CSS": 1069, "Shell": 104, "Batchfile": 100, "JavaScript": 24} | package com.broll.gainea.server.core.events
import com.broll.gainea.server.core.Game
import com.broll.gainea.server.core.map.AreaType.LAKE
import com.broll.gainea.server.core.map.Continent
import com.broll.gainea.server.core.map.Location
import com.broll.gainea.server.core.utils.getRandomFree
abstract class RandomEvent {
lateinit var game: Game
lateinit var location: Location
fun init(game: Game): Boolean {
this.game = game
val spot = pickSpot()
if (spot != null) {
this.location = spot
}
return spot != null
}
abstract fun pickSpot(): Location?
abstract fun run()
}
fun Game.freeArea() = map.allAreas.getRandomFree()
fun Game.freeContinentArea() =
map.allContinents.flatMap { it.areas }.filter { it.free }.randomOrNull()
fun Game.freeBuildingSpot(onlyContinents: Boolean = false) =
map.allAreas.filter { it.free && it.type != LAKE && (it.container is Continent || !onlyContinents) }
.randomOrNull() | 0 | Kotlin | 0 | 3 | ab47587c08ce2884269653a49c8fd8351cc4349f | 1,005 | Gainea | MIT License |
src/main/java/tdc/Main.kt | metatrading | 162,954,334 | false | null | package tdc
import javafx.application.Application
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
open class Main
fun main(args: Array<String>) {
Application.launch(FXMain::class.java, *args)
} | 1 | null | 1 | 1 | 2cafbddd9a34190f7bf2431e748cdf274c16a890 | 243 | TestDataCreator | The Unlicense |
FetLifeKotlin/app/src/main/java/com/bitlove/fetlife/model/db/FetlifeDatabase.kt | chonamdoo | 125,962,896 | true | {"Java": 1265971, "Kotlin": 80778, "JavaScript": 4113, "Prolog": 457} | package com.bitlove.fetlife.model.db
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.Database
import com.bitlove.fetlife.model.dataobject.entity.*
import com.bitlove.fetlife.model.db.dao.*
@Database(entities = arrayOf(ContentEntity::class, EventEntity::class, ExploreEventEntity::class, ExploreStoryEntity::class, GroupEntity::class, MemberEntity::class, ReactionEntity::class, RelationEntity::class), version = 1)
abstract class FetLifeDatabase : RoomDatabase() {
abstract fun contentDao(): ContentDao
abstract fun memberDao(): MemberDao
abstract fun reactionDao(): ReactionDao
}
| 0 | Java | 0 | 0 | ac680aed9629f51f38322d14df58c56142d49fed | 634 | android-1 | MIT License |
compiler/testData/diagnostics/tests/scopes/kt1248.kt | JakeWharton | 99,388,807 | false | null | // FIR_IDENTICAL
//KT-1248 Control visibility of overrides needed
package kt1248
interface ParseResult<out T> {
public val success : Boolean
public val value : T
}
class Success<T>(<!CANNOT_WEAKEN_ACCESS_PRIVILEGE!>internal<!> override val value : T) : ParseResult<T> {
<!CANNOT_WEAKEN_ACCESS_PRIVILEGE!>internal<!> override val success : Boolean = true
}
| 7 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 371 | kotlin | Apache License 2.0 |
demo/src/main/java/com/nextfaze/devfun/demo/inject/Android.kt | NextFaze | 90,596,780 | false | null | package com.nextfaze.devfun.demo.inject
import android.app.Application
import android.content.Context
import dagger.Module
import dagger.Provides
@Module
class AndroidModule(private val application: Application) {
@Provides internal fun context(): Context = application
@Provides internal fun application() = application
}
| 5 | null | 4 | 51 | cbf83014e478426750a2785b1e4e6a22d6964698 | 333 | dev-fun | Apache License 2.0 |
compiler/testData/diagnostics/tests/noSymbolProvidersDuplicationInDiamond.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // FIR_IDENTICAL
// LANGUAGE: +MultiPlatformProjects
// TARGET_BACKEND: JVM
// MODULE: common
// TARGET_PLATFORM: Common
expect fun g0(): String
// MODULE: intermediate1()()(common)
// TARGET_PLATFORM: Common
// MODULE: intermediate2()()(common)
// TARGET_PLATFORM: Common
// MODULE: main()()(intermediate1, intermediate2)
// TARGET_PLATFORM: JVM
actual fun g0(): String = "OK"
| 7 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 383 | kotlin | Apache License 2.0 |
src/main/kotlin/com/devtkms/mymenuappspring/controller/photo/PhotoController.kt | devtkms | 810,264,963 | false | {"Kotlin": 2678, "Dockerfile": 737} | package com.devtkms.mymenuappspring.controller.photo
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import com.devtkms.mymenuappspring.service.photo.PhotoService
@RestController
@RequestMapping("/api")
class PhotoController @Autowired constructor(private val photoService: PhotoService) {
@PostMapping("/photos")
fun insertPhoto(@RequestParam photoId: Int): Int {
return photoService.uploadPhoto(photoId)
}
} | 0 | Kotlin | 0 | 0 | 1ecbcc51bbcf3572e690056dc36cbd83e04617f2 | 674 | my-menu-app-spring | MIT License |
src/main/kotlin/br/com/zup/pix/registra/NovaChavePixService.kt | taissasantos | 347,969,608 | true | {"Kotlin": 27555} | package br.com.zup.pix.registra
import br.com.zup.pix.external.BancoCentralClient
import br.com.zup.pix.external.CreatePixKeyRequest
import br.com.zup.pix.external.DadosClienteClient
import br.com.zup.pix.repository.ChavePixRespository
import br.com.zup.shared.ChavePixExistenteException
import io.micronaut.http.HttpStatus
import io.micronaut.validation.Validated
import javax.inject.Inject
import javax.inject.Singleton
import javax.transaction.Transactional
import javax.validation.Valid
@Validated
@Singleton
class NovaChavePixService(@Inject val repository: ChavePixRespository,
@Inject val itauClient: DadosClienteClient,
@Inject val bcbClient: BancoCentralClient) {
@Transactional
fun registra(@Valid chaveNova: NovaChavePix): ChavePix{
if(repository.existsByChave(chaveNova.chave))
throw ChavePixExistenteException("chave informada já existe")
val response = itauClient.buscaDadosConta(chaveNova.clientId!!, chaveNova.tipoDeConta!!.name)
val conta = response.body()?.toModel() ?: throw IllegalAccessException("Cliente não localizado no Itau")
val chave = chaveNova.toModel(conta)
repository.save(chave)
val bcbRequest = CreatePixKeyRequest.toRequest(pix = chave)
val bcbResponse = bcbClient.cadastra(bcbRequest)
if(bcbResponse.status != HttpStatus.CREATED){
throw IllegalStateException("Erro ao tentar cadastrar chave no banco central")
}
chave.atualiza(bcbResponse.body()!!.key)
return chave
}
}
| 0 | Kotlin | 0 | 0 | 16ad65e58d9e265566f3bcf6ac338808c9d30076 | 1,593 | orange-talents-01-template-pix-keymanager-grpc | Apache License 2.0 |
app/src/main/java/com/example/rxjavaexample/Adapter.kt | APKolkhede | 313,754,389 | false | null | package com.example.rxjavaexample
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.domain.Character
class Adapter(private val characters: List<Character>) :
RecyclerView.Adapter<Adapter.CharacterViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharacterViewHolder {
val inflatedView = parent.inflate(R.layout.character_view, false)
return CharacterViewHolder(inflatedView)
}
override fun onBindViewHolder(holder: CharacterViewHolder, position: Int) {
holder.bindCharacter(characters[position])
}
override fun getItemCount() = characters.size
class CharacterViewHolder(v: View) : RecyclerView.ViewHolder(v) {
private var characterName: TextView = v.findViewById(R.id.characterName)
private var characterImage: ImageView = v.findViewById(R.id.characterImage)
private var characterStatus: TextView = v.findViewById(R.id.characterStatus)
fun bindCharacter(character: Character) {
characterName.text = character.name
characterStatus.text = character.status
characterImage.loadImage(imageUrl = character.image)
}
}
}
| 0 | Kotlin | 0 | 1 | f82de4af858a85779ba9b55561571259e56986ca | 1,321 | AndroidRetrofitAndRxJava | Apache License 2.0 |
app/src/main/java/com/example/rxjavaexample/Adapter.kt | APKolkhede | 313,754,389 | false | null | package com.example.rxjavaexample
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.domain.Character
class Adapter(private val characters: List<Character>) :
RecyclerView.Adapter<Adapter.CharacterViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharacterViewHolder {
val inflatedView = parent.inflate(R.layout.character_view, false)
return CharacterViewHolder(inflatedView)
}
override fun onBindViewHolder(holder: CharacterViewHolder, position: Int) {
holder.bindCharacter(characters[position])
}
override fun getItemCount() = characters.size
class CharacterViewHolder(v: View) : RecyclerView.ViewHolder(v) {
private var characterName: TextView = v.findViewById(R.id.characterName)
private var characterImage: ImageView = v.findViewById(R.id.characterImage)
private var characterStatus: TextView = v.findViewById(R.id.characterStatus)
fun bindCharacter(character: Character) {
characterName.text = character.name
characterStatus.text = character.status
characterImage.loadImage(imageUrl = character.image)
}
}
}
| 0 | Kotlin | 0 | 1 | f82de4af858a85779ba9b55561571259e56986ca | 1,321 | AndroidRetrofitAndRxJava | Apache License 2.0 |
app/src/test/java/com/check/coupon/repository/CouponRepositoryTest.kt | spkdroid | 248,841,588 | false | null | package com.check.coupon.repository
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.runners.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class CouponRepositoryTest {
@Test
fun checkRepositoryInit() {
var couponRepository = CouponRepository.coupon
Assert.assertNotNull(couponRepository)
}
@Test
fun checkRepositoryApiTest() {
var couponRepository = CouponRepository.coupon
Assert.assertNotNull(couponRepository.api)
GlobalScope.launch {
var api = couponRepository.api.getCoupon().offers
Assert.assertTrue(api.size>0)
}
}
} | 0 | Kotlin | 1 | 0 | f974d8547c2eb37c94deac0b4fbda8077a8f5b73 | 753 | C51 | Apache License 2.0 |
android/app/src/main/kotlin/com/keiydev/flutter_tools_sample/viewplugin/NMethodListViewPlugin.kt | keiydev | 212,962,783 | false | {"Dart": 43291, "Java": 17125, "Kotlin": 6793, "Ruby": 4195, "Swift": 1814, "Objective-C": 37} | package com.keiydev.flutter_tools_sample.viewplugin;
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
class NMethodListViewPlugin : FlutterPlugin {
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
flutterPluginBinding.platformViewRegistry
.registerViewFactory(
NMethodListViewFactory.VIEW_TYPE_ID,
NMethodListViewFactory(flutterPluginBinding.binaryMessenger)
)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
}
} | 0 | Dart | 0 | 0 | 7c82d0df65fc1d2fcfa8abfda3c6103bc0a71d34 | 650 | flutter_tools_sample | Apache License 2.0 |
compose-destinations-codegen/src/main/java/com/ramcosta/composedestinations/codegen/templates/navtype/NavTypeTemplateCommons.kt | raamcosta | 402,228,168 | false | {"Kotlin": 586911} | package com.ramcosta.composedestinations.codegen.templates.navtype
const val NAV_TYPE_NAME = "[NAV_TYPE_NAME]"
const val NAV_TYPE_CLASS_SIMPLE_NAME = "[NAV_TYPE_CLASS_SIMPLE_NAME]"
const val CLASS_SIMPLE_NAME_CAMEL_CASE = "[CLASS_SIMPLE_NAME_CAMEL_CASE]"
const val PARSE_VALUE_CAST_TO_CLASS = "[PARSE_VALUE_CAST_TO_CLASS]"
const val DESTINATIONS_NAV_TYPE_SERIALIZER_TYPE = "[DESTINATIONS_NAV_TYPE_SERIALIZER_TYPE]"
const val SERIALIZER_SIMPLE_CLASS_NAME = "[SERIALIZER_SIMPLE_CLASS_NAME]"
| 52 | Kotlin | 121 | 2,830 | 46099dc0f6066a1fb343b1f107445bfa29cbca15 | 490 | compose-destinations | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.