path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/ahmadhamwi/tabsync_example/model/Item.kt | Ahmad-Hamwi | 398,466,672 | false | null | package com.ahmadhamwi.tabsync_example.model
class Item(val content: String) {
} | 0 | Kotlin | 6 | 78 | f9a75544576675422f8b8c6be4a7a8e922bbdd5a | 81 | TabSync | Apache License 2.0 |
cache/src/main/kotlin/com/asadmshah/rplace/cache/BitmapCacheImpl.kt | asadmshah | 93,749,947 | false | null | package com.asadmshah.rplace.cache
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.subjects.ReplaySubject
import io.reactivex.subjects.Subject
import org.slf4j.LoggerFactory
internal class BitmapCacheImpl(observable: Observable<Pair<Long, ByteArray>>) : BitmapCache {
companion object {
private val LOGGER = LoggerFactory.getLogger(BitmapCacheImpl::class.java)
}
private val subject: Subject<Pair<Long, ByteArray>> = ReplaySubject.createWithSize(1)
init {
observable.subscribe(subject)
}
override fun readLatest(): Single<Pair<Long, ByteArray>> {
return subject
.take(1)
.singleOrError()
}
} | 0 | Kotlin | 0 | 0 | 17f33f12c98a4ef36f365d3ea9a9da0f7c2220f2 | 711 | rplace-server | The Unlicense |
sample/src/main/kotlin/com/davemorrissey/labs/subscaleview/test/MainActivity.kt | Eric-wish | 772,836,916 | true | {"Java Properties": 1, "YAML": 2, "Gradle Kotlin DSL": 4, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Text": 2, "Ignore List": 1, "TOML": 1, "INI": 1, "XML": 24, "Java": 1, "Kotlin": 32} | package com.davemorrissey.labs.subscaleview.test
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import com.davemorrissey.labs.subscaleview.test.R.string
import com.davemorrissey.labs.subscaleview.test.animation.AnimationActivity
import com.davemorrissey.labs.subscaleview.test.basicfeatures.BasicFeaturesActivity
import com.davemorrissey.labs.subscaleview.test.configuration.ConfigurationActivity
import com.davemorrissey.labs.subscaleview.test.databinding.MainActivityBinding
import com.davemorrissey.labs.subscaleview.test.eventhandling.EventHandlingActivity
import com.davemorrissey.labs.subscaleview.test.eventhandlingadvanced.AdvancedEventHandlingActivity
import com.davemorrissey.labs.subscaleview.test.extension.ExtensionActivity
import com.davemorrissey.labs.subscaleview.test.imagedisplay.ImageDisplayActivity
import com.davemorrissey.labs.subscaleview.test.viewpager.ViewPagerActivity
class MainActivity : AppCompatActivity() {
private lateinit var binding: MainActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = MainActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
actionBar?.setTitle(string.main_title)
binding.basicFeatures.setOnClickListener {
startActivity(BasicFeaturesActivity::class.java)
}
binding.imageDisplay.setOnClickListener {
startActivity(ImageDisplayActivity::class.java)
}
binding.eventHandling.setOnClickListener {
startActivity(EventHandlingActivity::class.java)
}
binding.advancedEventHandling.setOnClickListener {
startActivity(AdvancedEventHandlingActivity::class.java)
}
binding.viewPagerGalleries.setOnClickListener {
startActivity(ViewPagerActivity::class.java)
}
binding.animation.setOnClickListener {
startActivity(AnimationActivity::class.java)
}
binding.extension.setOnClickListener {
startActivity(ExtensionActivity::class.java)
}
binding.configuration.setOnClickListener {
startActivity(ConfigurationActivity::class.java)
}
binding.github.setOnClickListener {
openGitHub()
}
}
private fun startActivity(activity: Class<out Activity?>) {
startActivity(Intent(this, activity))
}
private fun openGitHub() {
startActivity(
Intent(Intent.ACTION_VIEW).apply {
data = "https://github.com/tachiyomiorg/subsampling-scale-image-view".toUri()
}
)
}
} | 0 | Java | 0 | 0 | b8e1b0ed2b2e10916213ab2b7dc6d967ba9ba4fe | 2,764 | subsampling-scale-image-view | Apache License 2.0 |
src/main/kotlin/nitrolang/backend/wasm/WasmBuilder.kt | cout970 | 699,028,788 | false | {"Markdown": 2, "Gradle Kotlin DSL": 2, "ANTLR": 2, "INI": 2, "Shell": 2, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Text": 1, "Kotlin": 86, "Java": 6, "JSON with Comments": 1, "HTML": 3, "HTTP": 1, "XML": 2} | package nitrolang.backend.wasm
import nitrolang.ast.*
import nitrolang.backend.*
import nitrolang.parsing.ANNOTATION_EXTERN
import nitrolang.parsing.ANNOTATION_WASM_INLINE
import nitrolang.parsing.ANNOTATION_WASM_NAME
const val PTR_SIZE: Int = 4
// Utility to convert an already type-checked LstProgram into a WasmModule
open class WasmBuilder(
val program: LstProgram,
val module: WasmModule,
) : IBuilder {
var initialMemoryAddr: Int = 0
var root: MonoBuilder? = null
val stringCache = mutableMapOf<String, Int>()
companion object {
fun compile(program: LstProgram, out: Appendable) {
val module = WasmModule()
MonoBuilder(program, WasmBuilder(program, module)).compileAll()
CodePrinter(out).wasmModule(module)
}
}
override fun init(root: MonoBuilder) {
this.root = root
// Null value
module.addSection(WasmDataSection(module.sectionOffset, intToWasm(0), "Null value"))
// Memory instance
initialMemoryAddr = module.sectionOffset
module.addSection(WasmDataSection(module.sectionOffset, ByteArray(12), "Memory instance"))
}
override fun finish() {
val start = WasmFunction(
name = "\$_start_main",
params = emptyList(),
result = WasmPrimitive.i32,
comment = "Init constants and call main",
exportName = "_start_main",
sourceFunction = null,
)
module.initializers.forEach { (mono, wasmFunc) ->
// memory_copy_internal(target: Int, value: Int, len: Int)
start.instructions += WasmInst("i32.const ${mono.offset}")
start.instructions += WasmInst("call ${wasmFunc.name}")
if (mono.type.isEncodedInRef()) {
val prim = mono.type.getReferencePrimitive()
start.instructions += WasmInst("$prim.store")
} else if (mono.type.isIntrinsic()) {
start.instructions += WasmInst("i32.store")
} else {
start.instructions += WasmInst("i32.const ${mono.size}")
start.instructions += WasmInst("call \$memory_copy_internal")
start.instructions += WasmInst("drop")
}
}
if (program.compilerOptions.runTests) {
module.functions
module.functions.forEach { func ->
val sourceFunction: LstFunction = func.sourceFunction ?: return@forEach
if (sourceFunction.isTest) {
pushString(func.exportName, start)
pushString(sourceFunction.getTestName() ?: sourceFunction.fullName, start)
start.instructions += WasmInst("call \$run_test")
start.instructions += WasmInst("drop")
}
}
start.instructions += WasmInst("i32.const 0")
} else {
start.instructions += WasmInst("call \$main")
}
module.functions += start
// Override section with address where the heap starts
// @formatter:off
module.sectionOffset = pad(module.sectionOffset)
val memoryInstance = byteArrayOf(
/* capacity */ *intToWasm(module.memoryCapacity - module.sectionOffset),
/* len */ *intToWasm(0),
/* bytes */ *intToWasm(module.sectionOffset)
)
// @formatter:on
module.sections[1].data = memoryInstance
}
override fun compileImport(func: LstFunction, mono: MonoFunction, name: ConstString, lib: ConstString) {
val params = mutableListOf<WasmVar>()
for (param in mono.code.params) {
params += WasmVar(
kind = WasmVarKind.Param,
name = param.finalName(),
type = monoTypeToPrimitive(param.type),
monoType = param.type,
)
}
val def = WasmFunction(
name = mono.finalName,
params = params,
result = monoTypeToPrimitive(mono.returnType),
comment = func.toString(),
sourceFunction = func,
)
module.imports += WasmImport(
module = lib.value,
functionName = name.value,
function = def
)
}
override fun preCompileConst(const: LstConst, mono: MonoConst) {
mono.offset = module.sectionOffset
mono.size = mono.type.heapSize()
val section = WasmDataSection(mono.offset, ByteArray(mono.size), "${const.fullName} at ${mono.offset}")
module.addSection(section)
mono.section = section
}
override fun compileConst(const: LstConst, mono: MonoConst) {
var value: ByteArray? = null
if (const.body.nodes.size == 1) {
value = when (val last = const.body.nodes.last()) {
is LstInt -> intToWasm(last.value)
is LstFloat -> floatToWasm(last.value)
is LstBoolean -> intToWasm(if (last.value) 1 else 0)
is LstNothing -> intToWasm(0)
else -> null
}
}
if (value != null) {
mono.section!!.data = value
return
}
val wasmFunction = WasmFunction(
name = "\$init_const_${mono.instance.ref.id}",
params = emptyList(),
result = monoTypeToPrimitive(mono.type),
comment = "${const.fullName} at ${mono.offset}",
sourceFunction = null,
)
compileConstInit(mono, wasmFunction)
module.initializers += mono to wasmFunction
}
fun compileConstInit(const: MonoConst, wasmFunc: WasmFunction) {
const.code.variables.forEach { variable ->
wasmFunc.locals += WasmVar(
kind = WasmVarKind.Local,
name = variable.finalName(),
type = monoTypeToPrimitive(variable.type),
monoType = variable.type,
)
}
for (inst in const.code.instructions) {
compileInstruction(inst, wasmFunc)
}
module.functions += wasmFunc
}
override fun compileFunction(lst: LstFunction?, func: MonoFunction) {
val params = mutableListOf<WasmVar>()
func.code.params.map { variable ->
params += WasmVar(
kind = WasmVarKind.Param,
name = if (variable.name == "_") null else variable.finalName(),
type = monoTypeToPrimitive(variable.type),
monoType = variable.type,
)
}
val main = if (func.name == "main") "main" else null
val wasmName = func.annotations.find { it.name == ANNOTATION_WASM_NAME }
val wasmNameValue = (wasmName?.args?.get("name") as? ConstString)?.value
val extern = func.annotations.find { it.name == ANNOTATION_EXTERN }
var externName = (extern?.args?.get("name") as? ConstString)?.value
// If the function is autogenerated, we don't want to export it.
// It could generate duplicated exports
if (func.signature.function?.autogenerate == true) {
externName = null
}
var exportName = main ?: wasmNameValue ?: externName ?: ""
if (lst != null && lst.isTest) {
exportName = "test_${lst.ref.id}"
}
val wasmFunc = WasmFunction(
name = func.finalName,
params = params,
result = monoTypeToPrimitive(func.returnType),
comment = func.signature.toString(),
exportName = exportName,
sourceFunction = lst,
)
func.code.variables.forEach { variable ->
wasmFunc.locals += WasmVar(
kind = WasmVarKind.Local,
name = variable.finalName(),
type = monoTypeToPrimitive(variable.type),
monoType = variable.type,
)
}
for (inst in func.code.instructions) {
compileInstruction(inst, wasmFunc)
}
module.functions += wasmFunc
}
override fun onCompileLambda(mono: MonoFunction) {
module.lambdaLabels += mono.finalName
}
override fun onCompileFunctionCall(
mono: MonoCode,
function: LstFunction,
inst: LstFunCall,
finalType: MonoType
): Boolean {
val inline = function.getAnnotation(ANNOTATION_WASM_INLINE)
val opcode = inline?.args?.get("opcode") as? ConstString
// Just a wasm opcode
if (opcode != null) {
inst.arguments.forEach { ref -> root!!.consumer(inst.span, ref) }
mono.instructions += MonoInline(mono.nextId(), inst.span, opcode.value)
root!!.provider(inst.span, inst.ref, finalType)
return true
}
return false
}
fun compileInstruction(inst: MonoInstruction, wasmFunc: WasmFunction) {
// Different kind of comments to help debugging .wat files
// wasmFunc.instructions += WasmInst("; $inst ;")
when (inst) {
is MonoConsumer -> error("MonoConsumer")
is MonoProvider -> error("MonoProvider")
is MonoNoop -> Unit
is MonoAutogenerate -> autogenerateFunction(inst.signature, wasmFunc)
is MonoDrop -> {
wasmFunc.instructions += WasmInst("drop")
}
is MonoDup -> {
wasmFunc.instructions += WasmInst("local.tee ${inst.auxLocal.finalName()}")
wasmFunc.instructions += WasmInst("local.get ${inst.auxLocal.finalName()}")
}
is MonoSwap -> {
wasmFunc.instructions += WasmInst("local.set ${inst.auxLocal0.finalName()}")
wasmFunc.instructions += WasmInst("local.set ${inst.auxLocal1.finalName()}")
wasmFunc.instructions += WasmInst("local.get ${inst.auxLocal0.finalName()}")
wasmFunc.instructions += WasmInst("local.get ${inst.auxLocal1.finalName()}")
}
is MonoComment -> {
wasmFunc.instructions += WasmInst("; ${inst.msg} ;")
}
is MonoBoolean -> {
wasmFunc.instructions += WasmInst(if (inst.value) "i32.const 1" else "i32.const 0")
}
is MonoFloat -> {
wasmFunc.instructions += WasmInst("f32.const ${inst.value}")
}
is MonoInt -> {
wasmFunc.instructions += WasmInst("i32.const ${inst.value}")
}
is MonoLong -> {
wasmFunc.instructions += WasmInst("i64.const ${inst.value}")
}
is MonoNothing -> {
wasmFunc.instructions += WasmInst("i32.const 0")
}
is MonoString -> {
pushString(inst.value, wasmFunc)
}
is MonoMemoryLoad -> {
val prim = monoTypeToPrimitive(inst.type)
if (inst.offset != 0) {
wasmFunc.instructions += WasmInst("i32.const ${inst.offset}")
wasmFunc.instructions += WasmInst("i32.add")
}
wasmFunc.instructions += WasmInst("$prim.load")
}
is MonoLambdaCall -> {
val wasmFuncType = funcTypeToWasm(inst.functionType, true)
wasmFunc.instructions += WasmInst("call_indirect $wasmFuncType")
}
is MonoFunCall -> {
wasmFunc.instructions += WasmInst("call ${inst.function.finalName}")
}
is MonoInline -> {
wasmFunc.instructions += WasmInst(inst.inline)
}
is MonoGetFieldAddress -> {
wasmFunc.instructions += WasmInst("i32.const ${inst.field.offset}")
wasmFunc.instructions += WasmInst("i32.add")
}
is MonoUnreachable -> {
wasmFunc.instructions += WasmInst("unreachable")
}
is MonoLambdaInit -> {
// $1 = memory_alloc_internal(size_of<Type>)
wasmFunc.instructions += WasmInst("i32.const ${inst.type.heapSize()}")
wasmFunc.instructions += WasmInst("call \$memory_alloc_internal")
wasmFunc.dup(WasmPrimitive.i32)
val index = module.lambdaLabels.indexOf(inst.lambda.finalName)
val msg = "Lambda function \$${inst.lambda.name} at index $index in \$lambdas"
wasmFunc.instructions += WasmInst("; $msg ;")
wasmFunc.instructions += WasmInst("i32.const $index")
wasmFunc.instructions += WasmInst("i32.store")
inst.localUpValues.forEach { (lambdaVar, functionVar) ->
val slot = lambdaVar.upValueSlot
val prim = monoTypeToPrimitive(lambdaVar.type)
wasmFunc.instructions += WasmInst("; Copy upValue ref to slot $slot ;")
wasmFunc.dup(WasmPrimitive.i32)
wasmFunc.instructions += WasmInst("i32.const ${PTR_SIZE + slot * PTR_SIZE}")
wasmFunc.instructions += WasmInst("i32.add")
wasmFunc.instructions += WasmInst("local.get ${functionVar.finalName()}")
wasmFunc.instructions += WasmInst("${prim}.store")
}
}
is MonoIfChoose -> {
wasmFunc.instructions += WasmInst("select", needsWrapping = false)
}
is MonoIfStart -> {
wasmFunc.instructions += WasmInst("if", needsWrapping = false)
}
is MonoIfElse -> {
wasmFunc.instructions += WasmInst("else", needsWrapping = false)
}
is MonoLoadConst -> {
if (inst.const.offset == 0) error("Constant not initialized: Invalid offset")
if (inst.const.type.isIntrinsic()) {
wasmFunc.instructions += WasmInst("i32.const ${inst.const.offset}")
val prim = monoTypeToPrimitive(inst.const.type)
wasmFunc.instructions += WasmInst("$prim.load")
} else {
wasmFunc.instructions += WasmInst("i32.const ${inst.const.offset}")
}
}
is MonoCreateUpValue -> {
val ptrType = inst.upValue.type
val type = ptrType.params.first()
wasmFunc.instructions += WasmInst("i32.const ${type.heapSize()}")
wasmFunc.instructions += WasmInst("call \$memory_alloc_internal")
wasmFunc.instructions += WasmInst("local.set ${inst.upValue.finalName()}")
}
is MonoInitUpValue -> {
val selfParam = wasmFunc.params.first().name
wasmFunc.instructions += WasmInst("local.get $selfParam")
wasmFunc.instructions += WasmInst("i32.const ${PTR_SIZE + inst.upValue.upValueSlot * PTR_SIZE}")
wasmFunc.instructions += WasmInst("i32.add")
wasmFunc.instructions += WasmInst("i32.load")
wasmFunc.instructions += WasmInst("local.set ${inst.upValue.finalName()}")
}
is MonoLoadUpValue -> {
val ptrType = inst.upValue.type.params.first()
val prim = ptrType.getReferencePrimitive()
wasmFunc.instructions += WasmInst("local.get ${inst.upValue.finalName()}")
wasmFunc.instructions += WasmInst("$prim.load")
}
is MonoStoreUpValue -> {
val ptrType = inst.upValue.type.params.first()
val prim = ptrType.getReferencePrimitive()
wasmFunc.instructions += WasmInst("local.get ${inst.upValue.finalName()}")
wasmFunc.swap(WasmPrimitive.i32, prim)
wasmFunc.instructions += WasmInst("$prim.store")
}
is MonoLoadParam -> {
wasmFunc.instructions += WasmInst("local.get ${inst.param.finalName()}")
}
is MonoLoadVar -> {
wasmFunc.instructions += WasmInst("local.get ${inst.variable.finalName()}")
}
is MonoStoreVar -> {
wasmFunc.instructions += WasmInst("local.set ${inst.variable.finalName()}")
}
is MonoLoadField -> {
val instancePrim = monoTypeToPrimitive(inst.instanceType)
if (instancePrim !== WasmPrimitive.i32) {
error("Instance is not a pointer!")
}
val fieldType = inst.field.type
val prim = monoTypeToPrimitive(fieldType)
when (inst.field.size) {
0 -> {
wasmFunc.instructions += WasmInst("drop")
wasmFunc.instructions += WasmInst("i32.const 0")
}
1 -> {
wasmFunc.instructions += WasmInst("i32.load8_u")
}
2 -> {
wasmFunc.instructions += WasmInst("i32.load16_s")
}
else -> {
wasmFunc.instructions += WasmInst("$prim.load")
}
}
}
is MonoStoreField -> {
val instancePrim = monoTypeToPrimitive(inst.instanceType)
if (instancePrim !== WasmPrimitive.i32) {
error("Instance is not a pointer!")
}
val fieldType = inst.field.type
val prim = monoTypeToPrimitive(fieldType)
when (inst.field.size) {
0 -> {
wasmFunc.instructions += WasmInst("drop")
wasmFunc.instructions += WasmInst("drop")
}
1 -> {
wasmFunc.instructions += WasmInst("i32.store8", needsWrapping = false)
}
2 -> {
wasmFunc.instructions += WasmInst("i32.store16", needsWrapping = false)
}
else -> {
wasmFunc.instructions += WasmInst("$prim.store", needsWrapping = false)
}
}
}
is MonoReturn -> {
wasmFunc.instructions += WasmInst("return")
}
is MonoStartLoop -> {
wasmFunc.instructions += WasmInst("loop", needsWrapping = false)
}
is MonoStartBlock -> {
wasmFunc.instructions += WasmInst("block", needsWrapping = false)
}
is MonoJump -> {
wasmFunc.instructions += WasmInst("br ${inst.depth}")
}
is MonoEndBlock -> {
wasmFunc.instructions += WasmInst("end", needsWrapping = false)
}
}
}
fun autogenerateFunction(signature: MonoFuncSignature, wasmFunc: WasmFunction) {
val extern = signature.function?.getAnnotation(ANNOTATION_EXTERN) ?: error("Extern annotation not found")
val externName = (extern.args["name"] as ConstString)
when (externName.value) {
"array_new" -> {
val itemSize = signature.typeParams.first().arraySize()
wasmFunc.locals += WasmVar(
kind = WasmVarKind.Local,
name = "\$dup",
type = WasmPrimitive.i32,
monoType = null
)
// Calculate size
wasmFunc.instructions += WasmInst("i32.const 4")
wasmFunc.instructions += WasmInst("local.get \$len")
wasmFunc.instructions += WasmInst("i32.const $itemSize")
wasmFunc.instructions += WasmInst("i32.mul")
wasmFunc.instructions += WasmInst("i32.add")
// Alloc array
wasmFunc.instructions += WasmInst("call \$memory_alloc_internal")
// Store len in the first 4 bytes
wasmFunc.instructions += WasmInst("local.tee \$dup")
wasmFunc.instructions += WasmInst("local.get \$len")
wasmFunc.instructions += WasmInst("i32.store")
// return array
wasmFunc.instructions += WasmInst("local.get \$dup")
wasmFunc.instructions += WasmInst("return")
}
"array_len" -> {
wasmFunc.instructions += WasmInst("local.get \$this")
wasmFunc.instructions += WasmInst("i32.load")
wasmFunc.instructions += WasmInst("return")
}
"array_get" -> {
val itemType = signature.typeParams.first()
val itemSize = itemType.arraySize()
if (itemSize == 0) {
wasmFunc.instructions += WasmInst("i32.const 0")
wasmFunc.instructions += WasmInst("return")
return
}
// Pointer to the beginning of the array
wasmFunc.instructions += WasmInst("local.get \$this")
wasmFunc.instructions += WasmInst("i32.const 4")
wasmFunc.instructions += WasmInst("i32.add")
// Offset into the array
wasmFunc.instructions += WasmInst("local.get \$index")
wasmFunc.instructions += WasmInst("i32.const $itemSize")
wasmFunc.instructions += WasmInst("i32.mul")
// Add the offset to the pointer to get the address of the item
wasmFunc.instructions += WasmInst("i32.add")
// Load the item and return it
when (itemType.base) {
is MonoOption -> wasmFunc.instructions += WasmInst("i32.load")
is MonoLambda -> wasmFunc.instructions += WasmInst("i32.load")
is MonoStruct -> {
when (itemType.base.instance.fullName) {
"Never", "Nothing" -> error("Zero size type")
"Byte", "Boolean" -> wasmFunc.instructions += WasmInst("i32.load8_u")
"Short" -> wasmFunc.instructions += WasmInst("i32.load16")
"Float" -> wasmFunc.instructions += WasmInst("f32.load")
"Long" -> wasmFunc.instructions += WasmInst("i64.load")
// Int, Ptr, RawArray, Char, etc.
else -> wasmFunc.instructions += WasmInst("i32.load")
}
}
}
wasmFunc.instructions += WasmInst("return")
}
"array_set" -> {
val itemType = signature.typeParams.first()
val itemSize = itemType.arraySize()
if (itemSize == 0) {
wasmFunc.instructions += WasmInst("i32.const 0")
wasmFunc.instructions += WasmInst("return")
return
}
// Pointer to the beginning of the array
wasmFunc.instructions += WasmInst("local.get \$this")
wasmFunc.instructions += WasmInst("i32.const 4")
wasmFunc.instructions += WasmInst("i32.add")
// Offset into the array
wasmFunc.instructions += WasmInst("local.get \$index")
wasmFunc.instructions += WasmInst("i32.const $itemSize")
wasmFunc.instructions += WasmInst("i32.mul")
// Add the offset to the pointer to get the address of the item
wasmFunc.instructions += WasmInst("i32.add")
// Load the item and store it
wasmFunc.instructions += WasmInst("local.get \$value")
when (itemType.base) {
is MonoOption -> wasmFunc.instructions += WasmInst("i32.store")
is MonoLambda -> wasmFunc.instructions += WasmInst("i32.store")
is MonoStruct -> {
when (itemType.base.instance.fullName) {
"Never", "Nothing" -> error("Zero size type")
"Byte", "Boolean" -> wasmFunc.instructions += WasmInst("i32.store8")
"Short" -> wasmFunc.instructions += WasmInst("i32.store16")
"Float" -> wasmFunc.instructions += WasmInst("f32.store")
"Long" -> wasmFunc.instructions += WasmInst("i64.store")
// Int, Ptr, RawArray, Char, etc.
else -> wasmFunc.instructions += WasmInst("i32.store")
}
}
}
// Return nothing
wasmFunc.instructions += WasmInst("i32.const 0")
wasmFunc.instructions += WasmInst("return")
}
"array_fill" -> {
val itemType = signature.typeParams.first()
val itemSize = itemType.arraySize()
if (itemSize == 0) {
wasmFunc.instructions += WasmInst("i32.const 0")
wasmFunc.instructions += WasmInst("return")
return
}
wasmFunc.locals += WasmVar(
kind = WasmVarKind.Local,
name = "\$index",
type = WasmPrimitive.i32,
monoType = null
)
wasmFunc.locals += WasmVar(
kind = WasmVarKind.Local,
name = "\$limit",
type = WasmPrimitive.i32,
monoType = null
)
wasmFunc.locals += WasmVar(
kind = WasmVarKind.Local,
name = "\$ptr",
type = WasmPrimitive.i32,
monoType = null
)
// Pointer to the beginning of the array
wasmFunc.instructions += WasmInst("local.get \$this")
wasmFunc.instructions += WasmInst("i32.const 4")
wasmFunc.instructions += WasmInst("i32.add")
// Save current ptr, and keep a copy for the loop
wasmFunc.instructions += WasmInst("local.set \$ptr")
// Max value of ptr to break the loop
wasmFunc.instructions += WasmInst("local.get \$this")
wasmFunc.instructions += WasmInst("i32.load")
wasmFunc.instructions += WasmInst("i32.const $itemSize")
wasmFunc.instructions += WasmInst("i32.mul")
wasmFunc.instructions += WasmInst("local.get \$ptr")
wasmFunc.instructions += WasmInst("i32.add")
wasmFunc.instructions += WasmInst("local.set \$limit")
// Loop
wasmFunc.instructions += WasmInst("block", needsWrapping = false)
wasmFunc.instructions += WasmInst("loop", needsWrapping = false)
// if (ptr >= limit) break
wasmFunc.instructions += WasmInst("local.get \$ptr")
wasmFunc.instructions += WasmInst("local.get \$limit")
wasmFunc.instructions += WasmInst("i32.ge_s")
wasmFunc.instructions += WasmInst("if", needsWrapping = false)
wasmFunc.instructions += WasmInst("br 2")
wasmFunc.instructions += WasmInst("end", needsWrapping = false)
// Load the item and store it
wasmFunc.instructions += WasmInst("local.get \$ptr")
wasmFunc.instructions += WasmInst("local.get \$value")
when (itemType.base) {
is MonoOption -> wasmFunc.instructions += WasmInst("i32.store")
is MonoLambda -> wasmFunc.instructions += WasmInst("i32.store")
is MonoStruct -> {
when (itemType.base.instance.fullName) {
"Never", "Nothing" -> error("Zero size type")
"Byte", "Boolean" -> wasmFunc.instructions += WasmInst("i32.store8")
"Short" -> wasmFunc.instructions += WasmInst("i32.store16")
"Float" -> wasmFunc.instructions += WasmInst("f32.store")
"Long" -> wasmFunc.instructions += WasmInst("i64.store")
// Int, Ptr, RawArray, Char, etc.
else -> wasmFunc.instructions += WasmInst("i32.store")
}
}
}
// ptr++
wasmFunc.instructions += WasmInst("local.get \$ptr")
wasmFunc.instructions += WasmInst("i32.const $itemSize")
wasmFunc.instructions += WasmInst("i32.add")
wasmFunc.instructions += WasmInst("local.set \$ptr")
// goto loop
wasmFunc.instructions += WasmInst("br 0")
// loop end
wasmFunc.instructions += WasmInst("end", needsWrapping = false)
wasmFunc.instructions += WasmInst("end", needsWrapping = false)
// Return nothing
wasmFunc.instructions += WasmInst("i32.const 0")
wasmFunc.instructions += WasmInst("return")
}
"int_get_ordering" -> {
// this == other
wasmFunc.instructions += WasmInst("local.get 0")
wasmFunc.instructions += WasmInst("local.get 1")
wasmFunc.instructions += WasmInst("i32.eq")
wasmFunc.instructions += WasmInst("if", needsWrapping = false)
// Load Ordering::Less
val monoConstLess = root!!.consts.values.find { it.instance.fullName == "Ordering::Equals" }!!
wasmFunc.instructions += WasmInst("i32.const ${monoConstLess.offset}")
wasmFunc.instructions += WasmInst("return")
wasmFunc.instructions += WasmInst("end", needsWrapping = false)
// this < other
wasmFunc.instructions += WasmInst("local.get 0")
wasmFunc.instructions += WasmInst("local.get 1")
wasmFunc.instructions += WasmInst("i32.lt_s")
wasmFunc.instructions += WasmInst("if", needsWrapping = false)
val monoConstEqual = root!!.consts.values.find { it.instance.fullName == "Ordering::Less" }!!
wasmFunc.instructions += WasmInst("i32.const ${monoConstEqual.offset}")
wasmFunc.instructions += WasmInst("return")
wasmFunc.instructions += WasmInst("end", needsWrapping = false)
// else
val monoConstGreater = root!!.consts.values.find { it.instance.fullName == "Ordering::Greater" }!!
wasmFunc.instructions += WasmInst("i32.const ${monoConstGreater.offset}")
wasmFunc.instructions += WasmInst("return")
}
else -> error("Unknown autogenerated function: ${signature.fullName}")
}
}
private fun pushString(value: String, wasmFunc: WasmFunction) {
if (value !in stringCache) {
// Align to 4 bytes for the 32bit length field
module.sectionOffset = pad(module.sectionOffset)
val bytes = value.encodeToByteArray()
val start = module.sectionOffset
val contentStart = module.sectionOffset + PTR_SIZE * 3
val size = intToWasm(bytes.size)
val contentsPtr = intToWasm(contentStart)
val hash = intToWasm(-1)
module.addSection(WasmDataSection(start, byteArrayOf(*size, *contentsPtr, *hash), "String Instance"))
module.addSection(WasmDataSection(contentStart, byteArrayOf(*size, *bytes), "String($size) \"${value}\""))
stringCache[value] = start
}
wasmFunc.instructions += WasmInst("i32.const ${stringCache[value]}")
}
fun monoTypeToPrimitive(mono: MonoType): WasmPrimitive {
return when {
mono.isFloat() -> WasmPrimitive.f32
mono.isLong() -> WasmPrimitive.i64
else -> WasmPrimitive.i32
}
}
fun MonoType.getReferencePrimitive(): WasmPrimitive {
return when {
isFloat() -> WasmPrimitive.f32
isLong() -> WasmPrimitive.i64
isInt() -> WasmPrimitive.i32
else -> WasmPrimitive.i32
}
}
fun funcTypeToWasm(mono: MonoType, lambda: Boolean): String {
if (!mono.isFunction() && !mono.isLambda()) error("Invalid type $mono")
return buildString {
if (lambda) {
append("(param ")
append(WasmPrimitive.i32)
append(")")
append(" ")
}
mono.params.dropLast(1).forEach { p ->
append("(param ")
append(monoTypeToPrimitive(p))
append(")")
append(" ")
}
append("(result ")
append(monoTypeToPrimitive(mono.params.last()))
append(")")
}
}
}
| 0 | Java | 0 | 3 | 9f501d19da02bd7022ac9029f23cd1d19205d150 | 33,458 | NitroLang | MIT License |
airbyte-cdk/java/airbyte-cdk/dependencies/src/test/kotlin/io/airbyte/workers/helper/ConnectorConfigUpdaterTest.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.workers.helper
import io.airbyte.api.client.generated.DestinationApi
import io.airbyte.api.client.generated.SourceApi
import io.airbyte.api.client.invoker.generated.ApiException
import io.airbyte.api.client.model.generated.*
import io.airbyte.commons.json.Jsons
import io.airbyte.protocol.models.Config
import java.util.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.Mockito
internal class ConnectorConfigUpdaterTest {
private val mSourceApi: SourceApi = Mockito.mock(SourceApi::class.java)
private val mDestinationApi: DestinationApi = Mockito.mock(DestinationApi::class.java)
private var connectorConfigUpdater: ConnectorConfigUpdater? = null
@BeforeEach
@Throws(ApiException::class)
fun setUp() {
Mockito.`when`(mSourceApi.getSource(SourceIdRequestBody().sourceId(SOURCE_ID)))
.thenReturn(SourceRead().sourceId(SOURCE_ID).name(SOURCE_NAME))
Mockito.`when`(
mDestinationApi.getDestination(
DestinationIdRequestBody().destinationId(DESTINATION_ID)
)
)
.thenReturn(DestinationRead().destinationId(DESTINATION_ID).name(DESTINATION_NAME))
connectorConfigUpdater = ConnectorConfigUpdater(mSourceApi, mDestinationApi)
}
@Test
@Throws(ApiException::class)
fun testPersistSourceConfig() {
val newConfiguration = Config().withAdditionalProperty("key", "new_value")
val configJson = Jsons.jsonNode(newConfiguration.additionalProperties)
val expectedSourceUpdate =
SourceUpdate().sourceId(SOURCE_ID).name(SOURCE_NAME).connectionConfiguration(configJson)
Mockito.`when`(mSourceApi.updateSource(Mockito.any()))
.thenReturn(SourceRead().connectionConfiguration(configJson))
connectorConfigUpdater!!.updateSource(SOURCE_ID, newConfiguration)
Mockito.verify(mSourceApi).updateSource(expectedSourceUpdate)
}
@Test
@Throws(ApiException::class)
fun testPersistDestinationConfig() {
val newConfiguration = Config().withAdditionalProperty("key", "new_value")
val configJson = Jsons.jsonNode(newConfiguration.additionalProperties)
val expectedDestinationUpdate =
DestinationUpdate()
.destinationId(DESTINATION_ID)
.name(DESTINATION_NAME)
.connectionConfiguration(configJson)
Mockito.`when`(mDestinationApi.updateDestination(Mockito.any()))
.thenReturn(DestinationRead().connectionConfiguration(configJson))
connectorConfigUpdater!!.updateDestination(DESTINATION_ID, newConfiguration)
Mockito.verify(mDestinationApi).updateDestination(expectedDestinationUpdate)
}
companion object {
private val SOURCE_ID: UUID = UUID.randomUUID()
private const val SOURCE_NAME = "source-stripe"
private val DESTINATION_ID: UUID = UUID.randomUUID()
private const val DESTINATION_NAME = "destination-google-sheets"
}
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 3,131 | airbyte | MIT License |
build-logic/convention/src/main/kotlin/MultiplatformApplicationComposeConventionPlugin.kt | satoshun-android-example | 282,540,221 | false | null | import io.github.satoshun.example.configureMultiplatformCompose
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
import org.jetbrains.compose.ComposeExtension
class MultiplatformApplicationComposeConventionPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
with(pluginManager) {
apply("kotlin-multiplatform")
apply("org.jetbrains.compose")
}
extensions.configure<ComposeExtension> {
configureMultiplatformCompose(this)
}
}
}
} | 7 | Kotlin | 0 | 2 | 87dfff55b1755f8ec059152cdf32a776d1986390 | 566 | Template | Apache License 2.0 |
src/main/kotlin/net/lexadily/tech/cq/detekt/codeclimate/DetektCodeClimateReport.kt | lexa-diky | 688,103,970 | false | {"Kotlin": 6870} | package net.lexadily.tech.cq.detekt.codeclimate
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Detektion
import io.gitlab.arturbosch.detekt.api.OutputReport
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class DetektCodeClimateReport : OutputReport() {
private lateinit var config: CodeClimateReportConfig
private val mapper = DetektionToReportMapper()
private val jsonEncoder by lazy {
Json {
prettyPrint = config.prettyPrint
encodeDefaults = true
}
}
override val ending: String = "json"
override val id: String = "code-climate"
override val name: String = "code-climate"
override fun init(config: Config) {
super.init(config)
this.config = CodeClimateReportConfig.from(config)
}
override fun render(detektion: Detektion): String {
require(::config.isInitialized) { "report configuration was not initialized" }
return mapper.map(detektion)
.let(jsonEncoder::encodeToString)
}
}
| 0 | Kotlin | 0 | 1 | 74de88bf628754dbcfa3513d090591d689e2bd79 | 1,090 | detekt-code-climate-report | The Unlicense |
app/src/main/java/com/sikandar/callrecording/FileUploadService.kt | Er-Sikandar | 872,814,308 | false | {"Kotlin": 19968} | package com.sikandar.callrecording
import okhttp3.MultipartBody
import retrofit2.Call
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
interface FileUploadService {
@Multipart
@POST("api/Audio")
fun uploadAudioFile(
// @Part("description") description: RequestBody,
@Part file: MultipartBody.Part
): Call<UploadResponse>
}
| 0 | Kotlin | 0 | 0 | ffa2f8af0f560a2750d7cd0a0955157423e337dc | 393 | CallRecording | Apache License 2.0 |
app/src/androidTest/java/com/example/androiddevchallenge/details/FakePuppyDetails.kt | arkivanov | 342,410,429 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.details
import com.example.androiddevchallenge.details.PuppyDetails.Model
import kotlinx.coroutines.flow.MutableStateFlow
class FakePuppyDetails(
model: Model = Model(),
private val onPhoneNumberClicked: () -> Unit = {}
) : PuppyDetails {
override val models: MutableStateFlow<Model> = MutableStateFlow(model)
override fun onCloseClicked() {
}
override fun onPhotoClicked() {
}
override fun onBreedNameClicked() {
}
override fun onPhoneNumberClicked() {
onPhoneNumberClicked.invoke()
}
}
| 0 | Kotlin | 0 | 5 | 753201f65d7a00f0c6b9eedc3a06680d36eec162 | 1,202 | android-dev-challenge-compose-1 | Apache License 2.0 |
app/src/main/java/ir/heydarii/musicmanager/base/BaseActivity.kt | reach2nasrudeen | 286,565,720 | true | {"Kotlin": 66397, "Java": 2636} | package ir.heydarii.musicmanager.base
import dagger.android.support.DaggerAppCompatActivity
/**
* All activities inherit this class, so our hands will be open in the future
* to do some common things in them
*/
open class BaseActivity : DaggerAppCompatActivity()
| 0 | null | 0 | 0 | 9be27b5c91e654dfea08371187cf1d8e5ab0beff | 268 | MusicManager | Apache License 2.0 |
app/src/main/java/com/example/cookingrecipe/apidata/Length.kt | real-Darkshadow | 571,245,039 | false | null | package com.example.cookingrecipe.apidata
data class Length(
val number: Int,
val unit: String
) | 0 | Kotlin | 0 | 0 | 35115fa9998bbd10bdd8d14c4916478bdeaf5a72 | 105 | CookingRecipe | MIT License |
core/src/main/java/com/reift/core/domain/usecase/favorite/FavoriteInteractor.kt | ReihanFatilla | 523,763,069 | false | null | package com.reift.core.domain.usecase.favorite
import com.reift.core.domain.model.movie.Movie
import com.reift.core.domain.model.tv.Tv
import com.reift.core.domain.repository.favorite.FavoriteRepository
import kotlinx.coroutines.flow.Flow
class FavoriteInteractor(
private val favoriteRepository: FavoriteRepository
): FavoriteUseCase {
override fun getFavoriteMovies(): Flow<List<Movie>> {
return favoriteRepository.getFavoriteMovies()
}
override fun getFavoriteTv(): Flow<List<Tv>> {
return favoriteRepository.getFavoriteTv()
}
} | 0 | Kotlin | 2 | 4 | 6558f6ba3ed176dcc6f23e2f1bc9ed2e8699d079 | 570 | Movo | MIT License |
src/main/kotlin/xyz/gnarbot/gnar/Configuration.kt | MG8853 | 350,430,768 | true | {"Kotlin": 308133, "Java": 84910} | package xyz.gnarbot.gnar
import com.google.common.reflect.TypeToken
import ninja.leaping.configurate.hocon.HoconConfigurationLoader
import xyz.gnarbot.gnar.utils.get
import xyz.gnarbot.gnar.utils.toDuration
import java.io.File
import java.time.Duration
class Configuration(file: File) {
private val loader = HoconConfigurationLoader.builder().setFile(file).build()
private var config = loader.load()
val name: String = config["bot", "name"].getString("Octave")
val prefix: String = config["commands", "prefix"].getString("_")
val game: String = config["bot", "game"].getString("${prefix}help | %d")
val admins: List<Long> = config["commands", "administrators"].getList(TypeToken.of(Long::class.javaObjectType))
val musicEnabled: Boolean = config["music", "enabled"].getBoolean(true)
val searchEnabled: Boolean = config["music", "search"].getBoolean(true)
val queueLimit: Int = config["music", "queue limit"].getInt(20)
val musicLimit: Int = config["music", "limit"].getInt(500)
val durationLimitText: String = config["music", "duration limit"].getString("2 hours")
val durationLimit: Duration = durationLimitText.toDuration()
val voteSkipCooldownText: String = config["music", "vote skip cooldown"].getString("35 seconds")
val voteSkipCooldown: Duration = voteSkipCooldownText.toDuration()
val voteSkipDurationText: String = config["music", "vote skip duration"].getString("20 seconds")
val voteSkipDuration: Duration = voteSkipDurationText.toDuration()
val ipv6Block: String = config["bot", "ipv6block"].getString(null)
val ipv6Exclude: String = config["bot", "ipv6Exclude"].getString(null)
val sentryDsn: String = config["bot", "sentry"].getString(null)
val bucketFactor: Int = config["bot", "bucketFactor"].getInt(8)
}
| 0 | Kotlin | 0 | 1 | 35113ef2755c1884e188f77b2da454e509653832 | 1,814 | Octave | MIT License |
src/main/java/uk/gov/justice/hmpps/casenotes/repository/OffenderCaseNoteAmendmentRepository.kt | ministryofjustice | 195,988,411 | false | {"Kotlin": 364652, "Java": 47044, "PLpgSQL": 5831, "Mustache": 1803, "Dockerfile": 1357, "Shell": 580} | package uk.gov.justice.hmpps.casenotes.repository
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.stereotype.Repository
import uk.gov.justice.hmpps.casenotes.model.OffenderCaseNoteAmendment
import java.util.UUID
@Repository
interface OffenderCaseNoteAmendmentRepository : JpaSpecificationExecutor<OffenderCaseNoteAmendment>, JpaRepository<OffenderCaseNoteAmendment, UUID>
| 5 | Kotlin | 1 | 1 | 93b0e4c04886b5445d17d0a687897ca78c76a605 | 486 | offender-case-notes | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/FileChartPie.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.FileChartPie: ImageVector
get() {
if (_fileChartPie != null) {
return _fileChartPie!!
}
_fileChartPie = Builder(name = "FileChartPie", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(14.414f, 0.0f)
lineTo(5.0f, 0.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f)
lineTo(2.0f, 24.0f)
lineTo(22.0f, 24.0f)
lineTo(22.0f, 7.586f)
lineTo(14.414f, 0.0f)
close()
moveTo(15.0f, 3.414f)
lineToRelative(3.586f, 3.586f)
horizontalLineToRelative(-3.586f)
lineTo(15.0f, 3.414f)
close()
moveTo(4.0f, 22.0f)
lineTo(4.0f, 3.0f)
curveToRelative(0.0f, -0.551f, 0.448f, -1.0f, 1.0f, -1.0f)
lineTo(13.0f, 2.0f)
verticalLineToRelative(7.0f)
horizontalLineToRelative(7.0f)
verticalLineToRelative(13.0f)
lineTo(4.0f, 22.0f)
close()
moveTo(12.0f, 10.0f)
curveToRelative(-2.757f, 0.0f, -5.0f, 2.243f, -5.0f, 5.0f)
reflectiveCurveToRelative(2.243f, 5.0f, 5.0f, 5.0f)
reflectiveCurveToRelative(5.0f, -2.243f, 5.0f, -5.0f)
reflectiveCurveToRelative(-2.243f, -5.0f, -5.0f, -5.0f)
close()
moveTo(12.0f, 18.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, -1.346f, -3.0f, -3.0f)
reflectiveCurveToRelative(1.346f, -3.0f, 3.0f, -3.0f)
verticalLineToRelative(3.0f)
lineToRelative(2.757f, -1.182f)
curveToRelative(0.156f, 0.363f, 0.243f, 0.762f, 0.243f, 1.182f)
curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f)
close()
}
}
.build()
return _fileChartPie!!
}
private var _fileChartPie: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,939 | icons | MIT License |
app/src/test/kotlin/com/denwehrle/boilerplate/test/ContactDataManagerTest.kt | denwehrle | 116,159,269 | false | null | package com.denwehrle.boilerplate.test
import com.denwehrle.boilerplate.data.local.helper.DatabaseHelper
import com.denwehrle.boilerplate.data.local.helper.PreferenceHelper
import com.denwehrle.boilerplate.data.manager.contact.ContactDataManager
import com.denwehrle.boilerplate.data.mapper.ContactMapper
import com.denwehrle.boilerplate.data.remote.endpoints.ContactService
import com.nhaarman.mockito_kotlin.whenever
import junit.framework.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
/**
* @author <NAME>
*/
@RunWith(MockitoJUnitRunner::class)
class ContactDataManagerTest {
private lateinit var contactDataManager: ContactDataManager
@Mock
lateinit var preferenceHelper: PreferenceHelper
@Mock
lateinit var contactService: ContactService
@Mock
lateinit var contactMapper: ContactMapper
@Mock
lateinit var databaseHelper: DatabaseHelper
@Before
fun setUp() {
contactDataManager = ContactDataManager(preferenceHelper, databaseHelper, contactService, contactMapper)
}
@Test
fun setWelcomeDoneAndCheck() {
assertEquals(false, contactDataManager.isWelcomeDone())
// set value but preferenceHelper so return expected value
contactDataManager.setWelcomeDone()
whenever(contactDataManager.isWelcomeDone()).thenReturn(true)
assertEquals(true, contactDataManager.isWelcomeDone())
}
} | 0 | Kotlin | 4 | 4 | 57dcc43cc818e6efd076df6b1438f9d8a9458ed9 | 1,516 | boilerplate-kotlin | Apache License 2.0 |
src/main/kotlin/de/skyrising/aoc2021/day17.kt | skyrising | 317,830,992 | false | null | package de.skyrising.aoc2021
class BenchmarkDay17 : BenchmarkDayV1(17)
fun registerDay17() {
val test = "target area: x=20..30, y=-10..-5"
puzzleS(17, "Trick Shot") {
val target = parseInput17(it)
val x2 = target.first.last
val y1 = target.second.first
var maxY = 0
for (x in 1..x2) {
for (y in 1..-y1) {
val result = ProbeState(0, 0, x, y).simulate(target)
if (result.hit) {
maxY = maxOf(maxY, result.maxY)
//println("$x,$y ${result.maxY}")
}
}
}
maxY
}
puzzleS(17, "Trick Shot v2") {
val target = parseInput17(it)
val vy = -target.second.first - 1
vy * (vy + 1) / 2
}
puzzleS(17, "Part Two") {
val target = parseInput17(it)
val x2 = target.first.last
val y1 = target.second.first
var hits = 0
for (x in 1..x2) {
for (y in y1..-y1) {
val result = ProbeState(0, 0, x, y).simulate(target)
if (result.hit) {
hits++
//println("$x,$y ${result.maxY}")
}
}
}
hits
}
}
private fun parseInput17(input: CharSequence): Pair<IntRange, IntRange> {
val comma = input.indexOf(',')
val (x1, x2) = input.substring(15, comma).split("..").map(String::toInt)
val (y1, y2) = input.substring(comma + 4).trimEnd().split("..").map(String::toInt)
return Pair(x1..x2, y1..y2)
}
data class ProbeState(val x: Int, val y: Int, val vx: Int, val vy: Int) {
fun step(): ProbeState {
val x = this.x + vx
val y = this.y + vy
val vx = if (this.vx > 0) this.vx - 1 else 0
val vy = this.vy - 1
return ProbeState(x, y, vx, vy)
}
fun simulate(target: Pair<IntRange, IntRange>): ProbeResult {
var state = this
var steps = 0
var maxY = state.y
//println(target)
while (true) {
//println(state)
if (state.x in target.first && state.y in target.second) return ProbeResult(true, state.x, state.y, maxY)
if (state.x > target.first.last || state.y < target.second.first) return ProbeResult(false, state.x, state.y, maxY)
state = state.step()
maxY = maxOf(maxY, state.y)
steps++
}
}
}
data class ProbeResult(val hit: Boolean, val x: Int, val y: Int, val maxY: Int) | 0 | Kotlin | 0 | 0 | 78ad82b1dac38cb28f4cbb6c89431b81cc60d507 | 2,504 | aoc2020 | MIT License |
feature/record/src/main/kotlin/com/recorder/feature/record/Navigation.kt | aarash709 | 440,068,432 | false | null | package com.recorder.feature.record
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.core.tween
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
const val RECORDER_ROUTE = "RECORDER_ROUTE"
fun NavController.toRecorder(navOptions: NavOptions? = null) {
navigate(RECORDER_ROUTE, navOptions)
}
fun NavGraphBuilder.recorder(
onNavigateToPlaylist: () -> Unit
){
composable(
route = RECORDER_ROUTE,
enterTransition = {
when (initialState.destination.route) {
else -> slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(350),
initialOffset = { it/3 }
)
}
},
exitTransition = {
when (targetState.destination.route) {
else -> slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(350),
targetOffset = { (it/3) }
)
}
}){
Record(
onNavigateToPlaylist = { onNavigateToPlaylist() }
)
}
} | 4 | null | 1 | 3 | 92db18f8e48abeda960876443e1315ff0970a55a | 1,367 | VoiceRecorder | Apache License 2.0 |
RetryAlertDialog/app/src/main/java/com/example/retryalertdialogfilekotlin/OhterDialogConfirmeAllDelete.kt | john526 | 296,261,260 | false | null | package com.example.retryalertdialogfilekotlin
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
class OhterDialogConfirmeAllDelete : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?):Dialog {
val build = AlertDialog.Builder(activity)
val inflater = activity?.layoutInflater
build.setView(inflater?.inflate(R.layout.delete_file_layout,null))
.setPositiveButton("Yes I sure",null)
.setNegativeButton("No I not sure",null)
.setTitle("This is the all documents ")
return build.create()
}
} | 0 | Kotlin | 0 | 1 | 9385cbac9d984d7aac9976f7d6c39363e04b2ae2 | 670 | KotlinBasicUi | MIT License |
app/src/main/java/tr/com/gndg/self/SelfApp.kt | Cr3bain | 840,332,370 | false | {"Kotlin": 567278} | package tr.com.gndg.self
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import tr.com.gndg.self.ui.navigation.SelfNavHost
@Composable
fun SelfApp(navController: NavHostController = rememberNavController()) {
SelfNavHost(navController = navController)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SelfTopAppBar(
title: String,
canNavigateBack: Boolean,
modifier: Modifier = Modifier,
scrollBehavior: TopAppBarScrollBehavior? = null,
navigateBack: () -> Unit = {},
navigateUp: () -> Unit = {},
action: @Composable RowScope.() -> Unit
) {
TopAppBar(title = { Text(title) },
modifier = modifier,
scrollBehavior = scrollBehavior,
navigationIcon = {
if (canNavigateBack) {
IconButton(onClick = navigateBack) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = stringResource(R.string.back_button)
)
}
}
},
actions = action
)
} | 0 | Kotlin | 0 | 0 | 12e58c3753a642bfd922d9cca44486eef3453e88 | 1,752 | self | Apache License 2.0 |
src/main/kotlin/com/github/weery28/json/JsonParser.kt | weery28 | 121,548,614 | false | null | package com.github.weery28.json
interface JsonParser {
fun <T> encode(json: String, pClass: Class<T>): T
} | 0 | Kotlin | 0 | 10 | fb96ac60c08d03982bd2e487545c96cc010cc521 | 112 | vjooqx | MIT License |
backend/src/main/kotlin/com/github/quillraven/toilapp/model/db/ToiletDistanceInfo.kt | Quillraven | 287,994,436 | false | null | package com.github.quillraven.toilapp.model.db
import com.github.quillraven.toilapp.model.dto.ToiletOverviewDto
import org.bson.types.ObjectId
data class ToiletDistanceInfo(
val id: ObjectId = ObjectId(),
val title: String = "",
val disabled: Boolean = false,
val toiletCrewApproved: Boolean = false,
val distance: Double = 0.0
) {
fun createToiletOverviewDto(
previewURL: String,
rating: Double
) = ToiletOverviewDto(
id = id.toHexString(),
title = title,
distance = distance,
previewURL = previewURL,
rating = rating,
disabled = disabled,
toiletCrewApproved = toiletCrewApproved
)
}
| 0 | Kotlin | 0 | 1 | 38363726abea4b16de831d3a888dd500ff2d11d3 | 691 | toilapp | MIT License |
ui-screenshots/src/test/kotlin/com/alexvanyo/composelife/ui/cells/CellWindowSnapshotTests.kt | alexvanyo | 375,146,193 | false | null | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alexvanyo.composelife.ui.cells
import com.alexvanyo.composelife.ui.util.BasePaparazziTest
import org.junit.Test
class CellWindowSnapshotTests : BasePaparazziTest() {
@Test
fun immutable_cell_window_preview() {
snapshot {
ImmutableCellWindowPreview()
}
}
@Test
fun mutable_cell_window_preview() {
snapshot {
MutableCellWindowPreview()
}
}
}
| 11 | Kotlin | 0 | 7 | 15effbb45db9602bfd0f4256dd4f98a057ebf6cd | 1,054 | composelife | Apache License 2.0 |
app/src/main/java/com/msdc/baobuzz/interfaces/CoachResult.kt | muchaisam | 709,855,143 | false | {"Kotlin": 205280} | package com.msdc.baobuzz.interfaces
sealed class CoachResult<out T> {
data class Success<out T>(val data: T) : CoachResult<T>()
data class Error<T>(val exception: Exception) : CoachResult<T>()
}
| 0 | Kotlin | 0 | 2 | e9fde94658550e4aa723fae89488b8d8109be6b4 | 204 | BaoBuzz | MIT License |
app/src/main/java/com/pokerio/app/components/PlayerView.kt | poker-io | 610,675,009 | false | null | package com.pokerio.app.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import com.pokerio.app.R
import com.pokerio.app.utils.Player
import com.pokerio.app.utils.PlayerProvider
@Composable
@Preview
fun PlayerView(
@PreviewParameter(PlayerProvider::class) player: Player
) {
Column(
modifier = Modifier.width(IntrinsicSize.Min),
horizontalAlignment = Alignment.CenterHorizontally
) {
Card(
modifier = Modifier
.padding(horizontal = 4.dp)
.width(IntrinsicSize.Max),
shape = RoundedCornerShape(
topStart = 0.dp,
topEnd = 0.dp,
bottomStart = 8.dp,
bottomEnd = 8.dp
)
) {
Text(player.nickname)
Text("Funds: ${player.funds}")
}
OutlinedCard(
modifier = Modifier
.padding(4.dp)
.width(IntrinsicSize.Max)
) {
Text("Bet: ${player.bet}")
}
if (player.folded) {
Text(
stringResource(R.string.fold),
color = Color.Gray
)
}
}
}
| 6 | Kotlin | 0 | 0 | ed4d0336c285e572da838486172885141eede00c | 1,882 | pokerio-android | MIT License |
android/app/src/main/kotlin/com/example/student_ai/MainActivity.kt | Avadhkumar-geek | 640,198,035 | false | null | package com.example.student_ai
import android.os.Build
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.setDecorFitsSystemWindows(false)
}
}
}
| 1 | Dart | 1 | 14 | efd35f68b45b871d8e6591716253d573b32fd72f | 406 | StudentAI | MIT License |
spesialist-api/src/main/kotlin/no/nav/helse/spesialist/api/SaksbehandlerTilganger.kt | navikt | 244,907,980 | false | {"Kotlin": 2707881, "PLpgSQL": 29508, "HTML": 1741, "Dockerfile": 195} | package no.nav.helse.spesialist.api
import java.util.UUID
class SaksbehandlerTilganger(
private val gruppetilganger: List<UUID>,
private val kode7Saksbehandlergruppe: UUID,
private val beslutterSaksbehandlergruppe: UUID,
private val skjermedePersonerSaksbehandlergruppe: UUID,
private val stikkprøveSaksbehandlergruppe: UUID,
private val spesialsakSaksbehandlergruppe: UUID,
) {
fun harTilgangTilKode7() = kode7Saksbehandlergruppe in gruppetilganger
fun harTilgangTilBeslutterOppgaver() = beslutterSaksbehandlergruppe in gruppetilganger
fun harTilgangTilSkjermedePersoner() = skjermedePersonerSaksbehandlergruppe in gruppetilganger
fun hartilgangTilStikkprøve() = stikkprøveSaksbehandlergruppe in gruppetilganger
fun hartilgangTilSpesialsaker() = spesialsakSaksbehandlergruppe in gruppetilganger
}
| 9 | Kotlin | 1 | 0 | 7898ecf1fbeaa835a61dc9039b48d093119c78b5 | 847 | helse-spesialist | MIT License |
src/main/kotlin/com/nivabit/kuery/dml/UpdateStatement.kt | mapleskip | 61,174,242 | true | {"Kotlin": 47795} | package com.nivabit.kuery.dml
import com.nivabit.kuery.*
import com.nivabit.kuery.sqlite.*
class DeleteStatement<T: Table>(
val subject: Statement<T>,
val whereClause: WhereClause<T>?) {
fun toString(dialect: Dialect): String {
return dialect.build(this)
}
override fun toString(): String {
return toString(SQLiteDialect)
}
} | 0 | Kotlin | 0 | 0 | 275992a5df21777c1631c05a9c6a28562979bb47 | 377 | kuery | MIT License |
src/main/kotlin/com/nivabit/kuery/dml/UpdateStatement.kt | mapleskip | 61,174,242 | true | {"Kotlin": 47795} | package com.nivabit.kuery.dml
import com.nivabit.kuery.*
import com.nivabit.kuery.sqlite.*
class DeleteStatement<T: Table>(
val subject: Statement<T>,
val whereClause: WhereClause<T>?) {
fun toString(dialect: Dialect): String {
return dialect.build(this)
}
override fun toString(): String {
return toString(SQLiteDialect)
}
} | 0 | Kotlin | 0 | 0 | 275992a5df21777c1631c05a9c6a28562979bb47 | 377 | kuery | MIT License |
app/src/main/java/com/example/compose_music_player/ui/homeview/viewmodel/HomeViewModelFactory.kt | AdonayMejia | 640,360,318 | false | null | package com.example.compose_music_player.ui.homeview.viewmodel
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.compose_music_player.model.repository.SongRepository
import com.example.compose_music_player.ui.songsettingview.viewmodel.SongSettingViewModel
class HomeViewModelFactory(
private val songRepository: SongRepository,
private val context: Context,
private val songSettingViewModel: SongSettingViewModel
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(HomeViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return HomeViewModel(songRepository, context, songSettingViewModel) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| 0 | Kotlin | 0 | 0 | 1bb15c59e05f3780a4822df59a414e452751c22a | 885 | Compose_MusicPlayer | MIT License |
src/main/kotlin/info/modoff/modeoff/client/plot/PlotManagerClient.kt | JamiesWhiteShirt | 101,624,564 | true | {"Kotlin": 58039} | package info.modoff.modeoff.client.plot
import info.modoff.modeoff.common.plot.Plot
import info.modoff.modeoff.common.plot.PlotLayout
import info.modoff.modeoff.common.plot.PlotManager
class PlotManagerClient(override val allPlots: List<Plot>) : PlotManager() {
}
| 0 | Kotlin | 0 | 0 | 381020fbcd8893bdfb6b586dd86f427505a4ef8f | 266 | ModeratorOff | MIT License |
app/src/main/kotlin/com/example/helloworld/HelloworldApplication.kt | andygolubev | 771,951,552 | false | {"Kotlin": 1706, "HCL": 1526} | package com.example.helloworld
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@SpringBootApplication
class HelloWorldApplication
fun main(args: Array<String>) {
runApplication<HelloWorldApplication>(*args)
}
@RestController
class HelloWorldController {
@GetMapping("/hello")
fun sayHello(): Map<String, String> = mapOf("message" to "Hello, World!")
} | 0 | Kotlin | 0 | 0 | 9c708ca256fa5852fb9ffa6da823d94ea8d7b01c | 555 | aws-devops-pro-exam-practice | MIT License |
app/src/main/java/com/androidarchitecture/view/fragment/MainFragment.kt | basion | 95,683,784 | true | {"Kotlin": 48812, "Java": 1076} | package com.androidarchitecture.view.fragment
import android.arch.lifecycle.Observer
import android.support.v4.app.Fragment
import android.os.Bundle
import com.androidarchitecture.R
import com.androidarchitecture.core.BaseFragment
import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.EditText
import com.androidarchitecture.entity.Task
import com.androidarchitecture.view.adapter.TaskAdapter
import com.androidarchitecture.view.model.TaskViewModel
/**
* Created by binary on 5/20/17.
*/
class MainFragment : BaseFragment() {
private lateinit var taskViewModel: TaskViewModel
private lateinit var taskAdapter: TaskAdapter
private val taskList = mutableListOf<Task>()
companion object {
fun newInstance(): Fragment = MainFragment()
}
//region BaseFragment
override fun getContentViewID(): Int = R.layout.fragment_main
override fun initView(savedInstanceState: Bundle?) {
view?.findViewById(R.id.fab)?.setOnClickListener { showAddDialog() }
initRecycleView()
taskViewModel = ViewModelProviders.of(this@MainFragment).get(TaskViewModel::class.java)
taskViewModel.taskDataSource = getAppComponent()?.taskDataSource()!!
taskViewModel.getTasks()?.observe(this@MainFragment, Observer {
taskList.clear()
it?.let {
taskList.addAll(it)
taskAdapter.notifyDataSetChanged()
}
})
}
//endregion
//region Utility API
private fun initRecycleView() {
val taskRecycleView = view?.findViewById(R.id.task_list) as RecyclerView
taskRecycleView.layoutManager = LinearLayoutManager(context)
taskAdapter = TaskAdapter(taskList)
taskRecycleView.adapter = taskAdapter
}
private fun showAddDialog() {
AlertDialog.Builder([email protected]).apply {
setTitle(getString(R.string.add_to_todo_list))
val input = EditText([email protected])
setView(input)
setPositiveButton("OK", { d, _ -> taskViewModel.addTask(input.text.toString()); d.cancel() })
setNegativeButton("Cancel", { d, _ -> d.cancel() })
show()
}
}
//endregion
} | 0 | Kotlin | 0 | 0 | 83a5d274b0e49869499e2b263721c2cfb57c5231 | 2,384 | AndroidArchitecture | MIT License |
benchmark/src/main/kotlin/com/linecorp/kotlinjdsl/benchmark/sample/query/select/SelectQuery3.kt | line | 442,633,985 | false | {"Kotlin": 1959613, "JavaScript": 5144, "Shell": 1023} | package com.linecorp.kotlinjdsl.benchmark.sample.query.select
import com.linecorp.kotlinjdsl.benchmark.sample.entity.employee.Employee
import com.linecorp.kotlinjdsl.dsl.jpql.jpql
import com.linecorp.kotlinjdsl.querymodel.jpql.select.SelectQuery
object SelectQuery3 : () -> SelectQuery<*> {
override fun invoke(): SelectQuery<*> {
data class DerivedEntity(
val employeeId: Long,
val count: Long,
)
return jpql {
val subquery = select<DerivedEntity>(
path(Employee::employeeId).`as`(expression("employeeId")),
count(Employee::employeeId).`as`(expression("count")),
).from(
entity(Employee::class),
join(Employee::departments),
).groupBy(
path(Employee::employeeId),
).having(
count(Employee::employeeId).greaterThan(1L),
)
select(
count(DerivedEntity::employeeId),
).from(
subquery.asEntity(),
)
}
}
}
| 4 | Kotlin | 86 | 705 | 3a58ff84b1c91bbefd428634f74a94a18c9b76fd | 1,093 | kotlin-jdsl | Apache License 2.0 |
app/src/main/java/com/calvinnor/progress/app/ProgressApp.kt | calvinnor | 126,571,244 | false | null | package com.calvinnor.progress.app
import android.app.Application
import android.content.Context
import com.calvinnor.progress.data_layer.TaskDatabase
import com.calvinnor.progress.data_layer.TaskRepo
import com.calvinnor.progress.injection.initialise
/**
* Application class.
*
* Initialise all required 3rd party libraries and utility classes here.
*/
class ProgressApp : Application() {
companion object {
lateinit var appContext: Context
}
override fun onCreate() {
super.onCreate()
appContext = applicationContext
initDatabase()
initDagger()
}
private fun initDatabase() {
TaskDatabase.init(this)
TaskRepo.initialise()
}
private fun initDagger() {
initialise()
}
}
| 0 | Kotlin | 2 | 1 | 56f554ce179eea2b601b6e570467abc94b3ce818 | 776 | Progress | MIT License |
app/src/main/java/com/calvinnor/progress/app/ProgressApp.kt | calvinnor | 126,571,244 | false | null | package com.calvinnor.progress.app
import android.app.Application
import android.content.Context
import com.calvinnor.progress.data_layer.TaskDatabase
import com.calvinnor.progress.data_layer.TaskRepo
import com.calvinnor.progress.injection.initialise
/**
* Application class.
*
* Initialise all required 3rd party libraries and utility classes here.
*/
class ProgressApp : Application() {
companion object {
lateinit var appContext: Context
}
override fun onCreate() {
super.onCreate()
appContext = applicationContext
initDatabase()
initDagger()
}
private fun initDatabase() {
TaskDatabase.init(this)
TaskRepo.initialise()
}
private fun initDagger() {
initialise()
}
}
| 0 | Kotlin | 2 | 1 | 56f554ce179eea2b601b6e570467abc94b3ce818 | 776 | Progress | MIT License |
server/src/main/java/com/android/identity/wallet/server/ServerConfiguration.kt | openwallet-foundation-labs | 248,844,077 | false | {"Kotlin": 3789539, "Java": 591756, "Swift": 28030, "JavaScript": 27336, "HTML": 13661, "Shell": 372, "CSS": 200, "C": 104} | package com.android.identity.wallet.server
import com.android.identity.flow.server.Configuration
import jakarta.servlet.ServletConfig
class ServerConfiguration(private val servletConfig: ServletConfig) : Configuration {
override fun getValue(key: String): String? {
val value = servletConfig.getInitParameter(key)
return value
}
companion object {
private const val TAG = "ServerConfiguration"
}
} | 101 | Kotlin | 80 | 157 | abfe1919a41f9f954b5c067e8371195b518c44a6 | 441 | identity-credential | Apache License 2.0 |
src/main/kotlin/my/chaster/extension/fitness/stepsperperiod/StepsPerPeriodHistory.kt | Encelus | 384,208,614 | false | null | package my.chaster.extension.fitness.stepsperperiod
import my.chaster.chaster.ChasterLockId
import my.chaster.chaster.ChasterUserId
import my.chaster.chaster.WithChasterUserId
import my.chaster.jpa.AbstractEntity
import my.chaster.jpa.AbstractEntityId
import my.chaster.util.isAfterOrEqual
import my.chaster.util.isBeforeOrEqual
import java.time.Duration
import java.time.Instant
import java.util.UUID
import javax.persistence.Column
import javax.persistence.Embeddable
import javax.persistence.Entity
import javax.persistence.Table
@Entity
@Table(name = "steps_per_period_history")
class StepsPerPeriodHistory(
@Column(name = "chaster_user_id", nullable = false, updatable = false)
override val chasterUserId: ChasterUserId,
@Column(name = "chaster_lock_id", nullable = false, updatable = false)
val chasterLockId: ChasterLockId,
@Column(name = "period_start", nullable = false, updatable = false)
val periodStart: Instant,
@Column(name = "period_end", nullable = false, updatable = false)
val periodEnd: Instant,
@Column(name = "steps", nullable = false)
var steps: Int,
) : AbstractEntity<StepsPerPeriodHistoryId>(StepsPerPeriodHistoryId()), WithChasterUserId {
@Column(name = "applied_punishment")
var appliedPunishment: Duration? = null
@Column(name = "is_final")
var isFinal: Boolean = false
fun isActive(now: Instant): Boolean {
return periodStart.isBeforeOrEqual(now)
&& periodEnd.isAfterOrEqual(now)
}
fun setFinal(punishment: Duration?) {
appliedPunishment = punishment
isFinal = true
}
}
@Embeddable
class StepsPerPeriodHistoryId(id: UUID = randomId()) : AbstractEntityId(id) | 3 | Kotlin | 0 | 1 | 8a486fab94c5d038f64770d4db99859b8ffd2ef0 | 1,622 | MyChaster | The Unlicense |
app/src/main/java/com/example/inventory/ui/item/ItemDetailsViewModel.kt | giannaSchneider | 630,093,721 | false | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.inventory.ui.item
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.inventory.data.*
import com.example.inventory.ui.home.HomeUiState
import com.example.inventory.ui.home.HomeViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/**
* ViewModel to retrieve, update and delete an item from the [ItemsRepository]'s data source.
*/
class ItemDetailsViewModel(
savedStateHandle: SavedStateHandle,
private val itemsRepository: ItemsRepository,
private val routinesRepository: RoutinesRepository,
private val clockRoutineRepository: ClockRoutineRepository,
private val multiRoutineRepository: MultiRoutineRepository,
private val mixRoutineRepository: MixRoutineRepository
) : ViewModel() {
private val itemId: Int = checkNotNull(savedStateHandle[ItemDetailsDestination.itemIdArg])
/**
* Holds the item details ui state. The data is retrieved from [ItemsRepository] and mapped to
* the UI state.
*/
val uiState: StateFlow<ItemDetailsUiState> =
itemsRepository.getItemStream(itemId)
.filterNotNull()
.map {
ItemDetailsUiState(outOfStock = it.quantity <= 0, itemDetails = it.toItemDetails())
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(TIMEOUT_MILLIS),
initialValue = ItemDetailsUiState()
)
val itemUiState2: StateFlow<ItemUiState2> =
routinesRepository.getAllTimerRoutinesStream().map { ItemUiState2(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(ItemDetailsViewModel.TIMEOUT_MILLIS),
initialValue = ItemUiState2()
)
val itemUiState3: StateFlow<ItemUiState3> =
clockRoutineRepository.getAllClockRoutinesStream().map { ItemUiState3(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(ItemDetailsViewModel.TIMEOUT_MILLIS),
initialValue = ItemUiState3()
)
val itemUiState4: StateFlow<ItemUiState4> =
multiRoutineRepository.getAllMultiRoutinesStream().map { ItemUiState4(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(ItemDetailsViewModel.TIMEOUT_MILLIS),
initialValue = ItemUiState4()
)
val itemUiState5: StateFlow<ItemUiState5> =
mixRoutineRepository.getAllMixRoutinesStream().map { ItemUiState5(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(ItemDetailsViewModel.TIMEOUT_MILLIS),
initialValue = ItemUiState5()
)
/**
* Reduces the item quantity by one and update the [ItemsRepository]'s data source.
*/
fun reduceQuantityByOne() {
viewModelScope.launch {
val currentItem = uiState.value.itemDetails.toItem()
if (currentItem.quantity > 0) {
itemsRepository.updateItem(currentItem.copy(quantity = currentItem.quantity - 1))
}
}
}
/**
* Deletes the item from the [ItemsRepository]'s data source.
*/
suspend fun deleteItem() {
itemsRepository.deleteItem(uiState.value.itemDetails.toItem())
}
companion object {
private const val TIMEOUT_MILLIS = 5_000L
}
}
/**
* UI state for ItemDetailsScreen
*/
data class ItemDetailsUiState(
val outOfStock: Boolean = true,
val itemDetails: ItemDetails = ItemDetails(),
)
data class ItemUiState2(val timerRoutineList: List<TimerRoutine> = listOf())
data class ItemUiState3(val clockRoutineList: List<ClockRoutine> = listOf())
data class ItemUiState4(val multiRoutineList: List<MultiRoutine> = listOf())
data class ItemUiState5(val mixRoutineList: List<MixRoutine> = listOf())
| 0 | Kotlin | 0 | 0 | 8cc6409d3a0c1e427ea80b5e0ae0adcc516bed73 | 4,861 | SMPApp | Apache License 2.0 |
notebooks/visualization/src/org/jetbrains/plugins/notebooks/editor/NonIncrementalCellLines.kt | ed4becky | 397,401,841 | true | null | package org.jetbrains.plugins.notebooks.editor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.util.TextRange
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ContainerUtil
/**
* inspired by [org.jetbrains.plugins.notebooks.editor.NotebookCellLinesImpl],
* calculates all markers and intervals from scratch for each document update
*/
class NonIncrementalCellLines private constructor(private val document: Document,
private val cellLinesLexer: NotebookCellLinesLexer,
private val intervalsGenerator: (Document, List<NotebookCellLines.Marker>) -> List<NotebookCellLines.Interval>) : NotebookCellLines {
private var markers: List<NotebookCellLines.Marker> = emptyList()
private var intervals: List<NotebookCellLines.Interval> = emptyList()
private val documentListener = createDocumentListener()
override val intervalListeners = EventDispatcher.create(NotebookCellLines.IntervalListener::class.java)
override val intervalsCount: Int
get() = intervals.size
override var modificationStamp: Long = 0
private set
init {
document.addDocumentListener(documentListener)
updateIntervalsAndMarkers()
}
override fun getIterator(ordinal: Int): ListIterator<NotebookCellLines.Interval> =
intervals.listIterator(ordinal)
override fun getIterator(interval: NotebookCellLines.Interval): ListIterator<NotebookCellLines.Interval> {
check(interval == intervals[interval.ordinal])
return intervals.listIterator(interval.ordinal)
}
override fun intervalsIterator(startLine: Int): ListIterator<NotebookCellLines.Interval> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val ordinal = intervals.find { startLine <= it.lines.last }?.ordinal ?: intervals.size
return intervals.listIterator(ordinal)
}
override fun markersIterator(startOffset: Int): ListIterator<NotebookCellLines.Marker> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val ordinal = markers.find { startOffset == it.offset || startOffset < it.offset + it.length }?.ordinal ?: markers.size
return markers.listIterator(ordinal)
}
private fun updateIntervalsAndMarkers() {
markers = cellLinesLexer.markerSequence(document.charsSequence, 0, 0).toList()
intervals = intervalsGenerator(document, markers)
}
private fun notifyChanged(oldCells: List<NotebookCellLines.Interval>,
oldAffectedCells: List<NotebookCellLines.Interval>,
newCells: List<NotebookCellLines.Interval>,
newAffectedCells: List<NotebookCellLines.Interval>) {
if (oldCells == newCells) {
return
}
val trimAtBegin = oldCells.zip(newCells).takeWhile { (oldCell, newCell) ->
oldCell == newCell &&
oldCell != oldAffectedCells.firstOrNull() && newCell != newAffectedCells.firstOrNull()
}.count()
val trimAtEnd = oldCells.asReversed().zip(newCells.asReversed()).takeWhile { (oldCell, newCell) ->
oldCell.type == newCell.type && oldCell.size == newCell.size &&
oldCell != oldAffectedCells.lastOrNull() && newCell != newAffectedCells.lastOrNull()
}.count()
++modificationStamp
intervalListeners.multicaster.segmentChanged(
trimmed(oldCells, trimAtBegin, trimAtEnd),
trimmed(newCells, trimAtBegin, trimAtEnd)
)
}
private fun createDocumentListener() = object : DocumentListener {
private var oldAffectedCells: List<NotebookCellLines.Interval> = emptyList()
override fun beforeDocumentChange(event: DocumentEvent) {
oldAffectedCells = getAffectedCells(intervals, document, TextRange(event.offset, event.offset + event.oldLength))
}
override fun documentChanged(event: DocumentEvent) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
val oldIntervals = intervals
updateIntervalsAndMarkers()
val newAffectedCells = getAffectedCells(intervals, document, TextRange(event.offset, event.offset + event.newLength))
notifyChanged(oldIntervals, oldAffectedCells, intervals, newAffectedCells)
}
}
companion object {
private val map = ContainerUtil.createConcurrentWeakMap<Document, NotebookCellLines>()
fun get(document: Document, lexerProvider: NotebookCellLinesLexer,
intervalsGenerator: (Document, List<NotebookCellLines.Marker>) -> List<NotebookCellLines.Interval>): NotebookCellLines =
map.computeIfAbsent(document) {
NonIncrementalCellLines(document, lexerProvider, intervalsGenerator)
}
}
}
private fun <T> trimmed(list: List<T>, trimAtBegin: Int, trimAtEnd: Int) =
list.subList(trimAtBegin, list.size - trimAtEnd)
private val NotebookCellLines.Interval.size: Int
get() = lines.last + 1 - lines.first
private fun getAffectedCells(intervals: List<NotebookCellLines.Interval>,
document: Document,
textRange: TextRange): List<NotebookCellLines.Interval> {
val firstLine = document.getLineNumber(textRange.startOffset).let { line ->
if (document.getLineEndOffset(line) == textRange.startOffset) line + 1 else line
}
val endLine = document.getLineNumber(textRange.endOffset).let { line ->
if (document.getLineStartOffset(line) == textRange.endOffset) line - 1 else line
}
return intervals.dropWhile {
it.lines.last < firstLine
}.takeWhile {
it.lines.first <= endLine
}
} | 0 | null | 0 | 0 | a5f5cb78a9eb8461a9679bcdf9d41b0de8cdd15c | 5,712 | intellij-community | Apache License 2.0 |
app/src/main/java/com/example/foodfood/api/createFoodFromBookmark/CreateFoodFromBookmark.kt | CAUSOLDOUTMEN | 690,046,919 | false | {"Kotlin": 196710} | package com.example.foodfood.api.createFoodFromBookmark
data class CreateFoodFromBookmark(
val favoriteFoodId: Long,
val userId: Long
) | 1 | Kotlin | 0 | 0 | c0eb1fd0ef4f567c91d71e6ba2c25760d2cea9f1 | 144 | Diareat_frontend | Apache License 2.0 |
app/src/main/java/com/roxana/recipeapp/cooking/ui/IngredientView.kt | roxanapirlea | 383,507,335 | false | null | package com.roxana.recipeapp.cooking.ui
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import com.roxana.recipeapp.common.utilities.formatIngredient
import com.roxana.recipeapp.cooking.IngredientState
import com.roxana.recipeapp.ui.basecomponents.CheckableText
@Composable
fun IngredientView(
ingredient: IngredientState,
modifier: Modifier = Modifier,
onCheckChanged: (Boolean) -> Unit = {}
) {
val formattedIngredient = formatIngredient(
ingredient.name,
ingredient.quantityForSelectedPortion,
ingredient.quantityType
)
val decoration = if (ingredient.isChecked) TextDecoration.LineThrough else TextDecoration.None
CheckableText(
checked = ingredient.isChecked,
onCheckedChange = onCheckChanged,
modifier = modifier.padding(vertical = 4.dp)
) {
Text(
formattedIngredient,
textDecoration = decoration,
style = MaterialTheme.typography.bodyMedium
)
}
}
| 0 | Kotlin | 0 | 1 | 8dc3e7040d806893dddd4538e15dd3a40faa80a4 | 1,248 | RecipeApp | Apache License 2.0 |
analytics-connector/src/test/java/com/amplitude/analytics/connector/IdentityStoreTest.kt | amplitude | 370,462,801 | false | {"Kotlin": 233499, "Java": 11419, "JavaScript": 1355} | package com.amplitude.analytics.connector
import com.amplitude.api.Identify
import com.amplitude.analytics.connector.util.toUpdateUserPropertiesMap
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert
import org.junit.Test
class IdentityStoreTest {
@Test
fun `test editIdentity, setUserId setDeviceId, getIdentity, success`() {
val identityStore = IdentityStoreImpl()
identityStore.editIdentity()
.setUserId("user_id")
.setDeviceId("device_id")
.commit()
val identity = identityStore.getIdentity()
Assert.assertEquals(Identity("user_id", "device_id"), identity)
}
@Test
fun `test editIdentity, setUserId setDeviceId, identity listener called`() {
val expectedIdentity = Identity("user_id", "device_id")
val identityStore = IdentityStoreImpl()
var listenerCalled = false
identityStore.addIdentityListener {
Assert.assertEquals(expectedIdentity, it)
listenerCalled = true
}
identityStore.editIdentity()
.setUserId("user_id")
.setDeviceId("device_id")
.commit()
Assert.assertTrue(listenerCalled)
}
@Test
fun `test setIdentity, getIdentity, success`() {
val expectedIdentity = Identity("user_id", "device_id")
val identityStore = IdentityStoreImpl()
identityStore.setIdentity(expectedIdentity)
val identity = identityStore.getIdentity()
Assert.assertEquals(expectedIdentity, identity)
}
@Test
fun `test setIdentity, identity listener called`() {
val expectedIdentity = Identity("user_id", "device_id")
val identityStore = IdentityStoreImpl()
var listenerCalled = false
identityStore.addIdentityListener {
Assert.assertEquals(expectedIdentity, it)
listenerCalled = true
}
identityStore.setIdentity(expectedIdentity)
Assert.assertTrue(listenerCalled)
}
@Test
fun `test setIdentity with unchanged identity, identity listener not called`() {
val expectedIdentity = Identity("user_id", "device_id")
val identityStore = IdentityStoreImpl()
identityStore.setIdentity(expectedIdentity)
identityStore.addIdentityListener {
Assert.fail("identity listener should not be called")
}
identityStore.setIdentity(expectedIdentity)
}
@Test
fun `test updateUserProperties, set`() {
val identityStore = IdentityStoreImpl()
identityStore.editIdentity()
.updateUserProperties(mapOf("\$set" to mapOf("key1" to "value1")))
.commit()
val identity = identityStore.getIdentity()
Assert.assertEquals(
Identity(userProperties = mapOf("key1" to "value1")),
identity
)
}
@Test
fun `test updateUserProperties, unset`() {
val identityStore = IdentityStoreImpl()
identityStore.setIdentity(
Identity(userProperties = mapOf(
"key" to "value",
"other" to true,
"final" to 4.2
))
)
identityStore.editIdentity()
.updateUserProperties(
mapOf("\$unset" to mapOf("other" to "-", "final" to "-"))
).commit()
val identity = identityStore.getIdentity()
Assert.assertEquals(
Identity(userProperties = mapOf("key" to "value")),
identity,
)
}
@Test
fun `test updateUserProperties, clearAll`() {
val identityStore = IdentityStoreImpl()
identityStore.setIdentity(
Identity(userProperties = mapOf(
"key" to listOf(-3, -2, -1, 0),
"key2" to mapOf("wow" to "cool"),
"key3" to 3,
"key4" to false,
))
)
identityStore.editIdentity()
.updateUserProperties(
mapOf("\$clearAll" to mapOf())
).commit()
val identity = identityStore.getIdentity()
Assert.assertEquals(Identity(), identity)
}
@Test
fun `test identify to user properties map, set`() {
val identityStore = IdentityStoreImpl()
val identify = Identify()
.set("string", "string")
.set("int", 32)
.set("bool", true)
.set("double", 4.2)
.set("jsonArray", JSONArray().put(0).put(1.1).put(true).put("three"))
.set("jsonObject", JSONObject().put("key", "value"))
identityStore.editIdentity()
.updateUserProperties(identify.userPropertiesOperations.toUpdateUserPropertiesMap())
.commit()
val identity = identityStore.getIdentity()
Assert.assertEquals(
Identity(userProperties = mapOf(
"string" to "string",
"int" to 32,
"bool" to true,
"double" to 4.2,
"jsonArray" to listOf(0, 1.1, true, "three"),
"jsonObject" to mapOf("key" to "value"),
)),
identity
)
}
@Test
fun `test identify to user properties map, unset`() {
val identityStore = IdentityStoreImpl()
identityStore.setIdentity(Identity(userProperties = mapOf("key" to "value")))
val identify = Identify().unset("key")
identityStore.editIdentity()
.updateUserProperties(identify.userPropertiesOperations.toUpdateUserPropertiesMap())
.commit()
val identity = identityStore.getIdentity()
Assert.assertEquals(Identity(), identity)
}
@Test
fun `test identify to user properties map, clearAll`() {
val identityStore = IdentityStoreImpl()
val identify = Identify()
.set("string", "string")
.set("int", 32)
.set("bool", true)
.set("double", 4.2)
.set("jsonArray", JSONArray().put(0).put(1.1).put(true).put("three"))
.set("jsonObject", JSONObject().put("key", "value"))
identityStore.editIdentity()
.updateUserProperties(identify.userPropertiesOperations.toUpdateUserPropertiesMap())
.commit()
val clear = Identify().clearAll()
identityStore.editIdentity()
.updateUserProperties(clear.userPropertiesOperations.toUpdateUserPropertiesMap())
.commit()
val identity = identityStore.getIdentity()
Assert.assertEquals(Identity(), identity)
}
}
| 3 | Kotlin | 2 | 4 | e91f19cb1f96c2a3fc5cd2483a2eb8b27e4a783e | 6,550 | experiment-android-client | MIT License |
api/src/main/kotlin/com/example/in/common/config/SwaggerConfig.kt | PARKPARKWOO | 737,782,254 | false | {"Kotlin": 358272, "Dockerfile": 124} | package com.example.`in`.common.config
import com.example.`in`.common.config.SwaggerConfig.Companion.AUTHORIZATION_BEARER_SECURITY_SCHEME_NAME
import io.swagger.v3.oas.models.Components
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Info
import io.swagger.v3.oas.models.security.SecurityScheme
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
open class SwaggerConfig {
@Bean
open fun openAPI(): OpenAPI = OpenAPI()
.components(
Components().addSecuritySchemes(
AUTHORIZATION_BEARER_SECURITY_SCHEME_NAME,
AuthorizationBearerSecurityScheme,
),
)
.info(info())
private fun info() = Info().title("health-api")
.description(
"""
Service(MVP 개발 이후) 명 입력
을 위한 API 명세서 입니다.
""".trimIndent(),
)
.version("1")
companion object {
const val AUTHORIZATION_BEARER_SECURITY_SCHEME_NAME = "Authorization: Bearer ACCESS_TOKEN"
}
}
val AuthorizationBearerSecurityScheme: SecurityScheme = SecurityScheme()
.name(AUTHORIZATION_BEARER_SECURITY_SCHEME_NAME)
.type(SecurityScheme.Type.HTTP)
.scheme("Bearer")
.bearerFormat("JWT")
| 9 | Kotlin | 0 | 0 | fbf1272971e226519cd9919011fff785650994d3 | 1,316 | barbellrobot-backend | Apache License 2.0 |
testing/node-driver/src/main/kotlin/net/corda/testing/node/MockNetwork.kt | rodrigofnp | 121,883,701 | true | {"Kotlin": 5133387, "Java": 242891, "CSS": 23334, "Shell": 6524, "Groovy": 2128, "Gherkin": 1892, "Batchfile": 1332, "PowerShell": 777} | package net.corda.testing.node
import com.google.common.jimfs.Jimfs
import net.corda.core.concurrent.CordaFuture
import net.corda.core.crypto.random63BitValue
import net.corda.core.flows.FlowLogic
import net.corda.core.identity.CordaX500Name
import net.corda.core.identity.Party
import net.corda.core.node.NodeInfo
import net.corda.node.VersionInfo
import net.corda.node.internal.StartedNode
import net.corda.node.services.api.StartedNodeServices
import net.corda.node.services.config.NodeConfiguration
import net.corda.node.services.messaging.MessagingService
import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.nodeapi.internal.persistence.DatabaseTransaction
import net.corda.nodeapi.internal.persistence.TransactionIsolationLevel
import net.corda.testing.core.DUMMY_NOTARY_NAME
import net.corda.testing.node.internal.InternalMockNetwork
import net.corda.testing.node.internal.setMessagingServiceSpy
import rx.Observable
import java.math.BigInteger
import java.nio.file.Path
/**
* Extend this class in order to intercept and modify messages passing through the [MessagingService] when using the [InMemoryMessagingNetwork].
*/
open class MessagingServiceSpy(val messagingService: MessagingService) : MessagingService by messagingService
/**
* @param entropyRoot the initial entropy value to use when generating keys. Defaults to an (insecure) random value,
* but can be overridden to cause nodes to have stable or colliding identity/service keys.
* @param configOverrides add/override behaviour of the [NodeConfiguration] mock object.
*/
@Suppress("unused")
data class MockNodeParameters(
val forcedID: Int? = null,
val legalName: CordaX500Name? = null,
val entropyRoot: BigInteger = BigInteger.valueOf(random63BitValue()),
val configOverrides: (NodeConfiguration) -> Any? = {},
val version: VersionInfo = MockServices.MOCK_VERSION_INFO) {
fun setForcedID(forcedID: Int?): MockNodeParameters = copy(forcedID = forcedID)
fun setLegalName(legalName: CordaX500Name?): MockNodeParameters = copy(legalName = legalName)
fun setEntropyRoot(entropyRoot: BigInteger): MockNodeParameters = copy(entropyRoot = entropyRoot)
fun setConfigOverrides(configOverrides: (NodeConfiguration) -> Any?): MockNodeParameters = copy(configOverrides = configOverrides)
}
/** Helper builder for configuring a [InternalMockNetwork] from Java. */
@Suppress("unused")
data class MockNetworkParameters(
val networkSendManuallyPumped: Boolean = false,
val threadPerNode: Boolean = false,
val servicePeerAllocationStrategy: InMemoryMessagingNetwork.ServicePeerAllocationStrategy = InMemoryMessagingNetwork.ServicePeerAllocationStrategy.Random(),
val initialiseSerialization: Boolean = true,
val notarySpecs: List<MockNetworkNotarySpec> = listOf(MockNetworkNotarySpec(DUMMY_NOTARY_NAME)),
val maxTransactionSize: Int = Int.MAX_VALUE) {
fun setNetworkSendManuallyPumped(networkSendManuallyPumped: Boolean): MockNetworkParameters = copy(networkSendManuallyPumped = networkSendManuallyPumped)
fun setThreadPerNode(threadPerNode: Boolean): MockNetworkParameters = copy(threadPerNode = threadPerNode)
fun setServicePeerAllocationStrategy(servicePeerAllocationStrategy: InMemoryMessagingNetwork.ServicePeerAllocationStrategy): MockNetworkParameters = copy(servicePeerAllocationStrategy = servicePeerAllocationStrategy)
fun setInitialiseSerialization(initialiseSerialization: Boolean): MockNetworkParameters = copy(initialiseSerialization = initialiseSerialization)
fun setNotarySpecs(notarySpecs: List<MockNetworkNotarySpec>): MockNetworkParameters = copy(notarySpecs = notarySpecs)
fun setMaxTransactionSize(maxTransactionSize: Int): MockNetworkParameters = copy(maxTransactionSize = maxTransactionSize)
}
/** Represents a node configuration for injection via [MockNetworkParameters] **/
data class MockNetworkNotarySpec(val name: CordaX500Name, val validating: Boolean = true) {
constructor(name: CordaX500Name) : this(name, validating = true)
}
/** A class that represents an unstarted mock node for testing. **/
class UnstartedMockNode private constructor(private val node: InternalMockNetwork.MockNode) {
companion object {
internal fun create(node: InternalMockNetwork.MockNode): UnstartedMockNode {
return UnstartedMockNode(node)
}
}
val id get() : Int = node.id
/** Start the node **/
fun start() = StartedMockNode.create(node.start())
}
/** A class that represents a started mock node for testing. **/
class StartedMockNode private constructor(private val node: StartedNode<InternalMockNetwork.MockNode>) {
companion object {
internal fun create(node: StartedNode<InternalMockNetwork.MockNode>): StartedMockNode {
return StartedMockNode(node)
}
}
val services get() : StartedNodeServices = node.services
val id get() : Int = node.internals.id
val info get() : NodeInfo = node.services.myInfo
val network get() : MessagingService = node.network
/** Register a flow that is initiated by another flow **/
fun <F : FlowLogic<*>> registerInitiatedFlow(initiatedFlowClass: Class<F>): Observable<F> = node.registerInitiatedFlow(initiatedFlowClass)
/**
* Attach a [MessagingServiceSpy] to the [InternalMockNetwork.MockNode] allowing
* interception and modification of messages.
*/
fun setMessagingServiceSpy(messagingServiceSpy: MessagingServiceSpy) = node.setMessagingServiceSpy(messagingServiceSpy)
/** Stop the node **/
fun stop() = node.internals.stop()
/** Receive a message from the queue. */
fun pumpReceive(block: Boolean = false): InMemoryMessagingNetwork.MessageTransfer? {
return (services.networkService as InMemoryMessagingNetwork.TestMessagingService).pumpReceive(block)
}
/** Returns the currently live flows of type [flowClass], and their corresponding result future. */
fun <F : FlowLogic<*>> findStateMachines(flowClass: Class<F>): List<Pair<F, CordaFuture<*>>> = node.smm.findStateMachines(flowClass)
fun <T> transaction(statement: () -> T): T {
return node.database.transaction {
statement()
}
}
}
/**
* A mock node brings up a suite of in-memory services in a fast manner suitable for unit testing.
* Components that do IO are either swapped out for mocks, or pointed to a [Jimfs] in memory filesystem or an in
* memory H2 database instance.
*
* Mock network nodes require manual pumping by default: they will not run asynchronous. This means that
* for message exchanges to take place (and associated handlers to run), you must call the [runNetwork]
* method.
*
* You can get a printout of every message sent by using code like:
*
* LogHelper.setLevel("+messages")
*
* By default a single notary node is automatically started, which forms part of the network parameters for all the nodes.
* This node is available by calling [defaultNotaryNode].
*/
open class MockNetwork(
val cordappPackages: List<String>,
val defaultParameters: MockNetworkParameters = MockNetworkParameters(),
val networkSendManuallyPumped: Boolean = defaultParameters.networkSendManuallyPumped,
val threadPerNode: Boolean = defaultParameters.threadPerNode,
val servicePeerAllocationStrategy: InMemoryMessagingNetwork.ServicePeerAllocationStrategy = defaultParameters.servicePeerAllocationStrategy,
val initialiseSerialization: Boolean = defaultParameters.initialiseSerialization,
val notarySpecs: List<MockNetworkNotarySpec> = defaultParameters.notarySpecs,
val maxTransactionSize: Int = defaultParameters.maxTransactionSize) {
@JvmOverloads
constructor(cordappPackages: List<String>, parameters: MockNetworkParameters = MockNetworkParameters()) : this(cordappPackages, defaultParameters = parameters)
private val internalMockNetwork: InternalMockNetwork = InternalMockNetwork(cordappPackages, defaultParameters, networkSendManuallyPumped, threadPerNode, servicePeerAllocationStrategy, initialiseSerialization, notarySpecs, maxTransactionSize)
val defaultNotaryNode get() : StartedMockNode = StartedMockNode.create(internalMockNetwork.defaultNotaryNode)
val defaultNotaryIdentity get() : Party = internalMockNetwork.defaultNotaryIdentity
val notaryNodes get() : List<StartedMockNode> = internalMockNetwork.notaryNodes.map { StartedMockNode.create(it) }
val nextNodeId get() : Int = internalMockNetwork.nextNodeId
/** Create a started node with the given identity. **/
fun createPartyNode(legalName: CordaX500Name? = null): StartedMockNode = StartedMockNode.create(internalMockNetwork.createPartyNode(legalName))
/** Create a started node with the given parameters. **/
fun createNode(parameters: MockNodeParameters = MockNodeParameters()): StartedMockNode = StartedMockNode.create(internalMockNetwork.createNode(parameters))
/** Create a started node with the given parameters.
* @param legalName the node's legal name.
* @param forcedID a unique identifier for the node.
* @param entropyRoot the initial entropy value to use when generating keys. Defaults to an (insecure) random value,
* but can be overridden to cause nodes to have stable or colliding identity/service keys.
* @param configOverrides add/override behaviour of the [NodeConfiguration] mock object.
* @param version the mock node's platform, release, revision and vendor versions.
*/
@JvmOverloads
fun createNode(legalName: CordaX500Name? = null,
forcedID: Int? = null,
entropyRoot: BigInteger = BigInteger.valueOf(random63BitValue()),
configOverrides: (NodeConfiguration) -> Any? = {},
version: VersionInfo = MockServices.MOCK_VERSION_INFO): StartedMockNode {
val parameters = MockNodeParameters(forcedID, legalName, entropyRoot, configOverrides, version)
return StartedMockNode.create(internalMockNetwork.createNode(parameters))
}
/** Create an unstarted node with the given parameters. **/
fun createUnstartedNode(parameters: MockNodeParameters = MockNodeParameters()): UnstartedMockNode = UnstartedMockNode.create(internalMockNetwork.createUnstartedNode(parameters))
/** Create an unstarted node with the given parameters.
* @param legalName the node's legal name.
* @param forcedID a unique identifier for the node.
* @param entropyRoot the initial entropy value to use when generating keys. Defaults to an (insecure) random value,
* but can be overridden to cause nodes to have stable or colliding identity/service keys.
* @param configOverrides add/override behaviour of the [NodeConfiguration] mock object.
* @param version the mock node's platform, release, revision and vendor versions.
*/
@JvmOverloads
fun createUnstartedNode(legalName: CordaX500Name? = null,
forcedID: Int? = null,
entropyRoot: BigInteger = BigInteger.valueOf(random63BitValue()),
configOverrides: (NodeConfiguration) -> Any? = {},
version: VersionInfo = MockServices.MOCK_VERSION_INFO): UnstartedMockNode {
val parameters = MockNodeParameters(forcedID, legalName, entropyRoot, configOverrides, version)
return UnstartedMockNode.create(internalMockNetwork.createUnstartedNode(parameters))
}
/** Start all nodes that aren't already started. **/
fun startNodes() = internalMockNetwork.startNodes()
/** Stop all nodes. **/
fun stopNodes() = internalMockNetwork.stopNodes()
/** Block until all scheduled activity, active flows and network activity has ceased. **/
fun waitQuiescent() = internalMockNetwork.waitQuiescent()
/**
* Asks every node in order to process any queued up inbound messages. This may in turn result in nodes
* sending more messages to each other, thus, a typical usage is to call runNetwork with the [rounds]
* parameter set to -1 (the default) which simply runs as many rounds as necessary to result in network
* stability (no nodes sent any messages in the last round).
*/
@JvmOverloads
fun runNetwork(rounds: Int = -1) = internalMockNetwork.runNetwork(rounds)
/** Get the base directory for the given node id. **/
fun baseDirectory(nodeId: Int): Path = internalMockNetwork.baseDirectory(nodeId)
}
| 0 | Kotlin | 0 | 0 | b8fa44d721ef4ffbe422db2fd1cc2f26d0f3b586 | 12,540 | corda | Apache License 2.0 |
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/vstorage/lvm/pool/extend/ExtendLvmPoolTest.kt | soloturn | 164,455,794 | true | {"Kotlin": 1728202, "Gherkin": 74051, "HTML": 73962, "JavaScript": 53966, "CSS": 754} | package com.github.kerubistan.kerub.planner.steps.vstorage.lvm.pool.extend
import com.github.kerubistan.kerub.GB
import com.github.kerubistan.kerub.TB
import com.github.kerubistan.kerub.model.LvmStorageCapability
import com.github.kerubistan.kerub.model.config.HostConfiguration
import com.github.kerubistan.kerub.model.config.LvmPoolConfiguration
import com.github.kerubistan.kerub.model.dynamic.HostDynamic
import com.github.kerubistan.kerub.model.dynamic.HostStatus
import com.github.kerubistan.kerub.model.dynamic.SimpleStorageDeviceDynamic
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.testHost
import com.github.kerubistan.kerub.testHostCapabilities
import org.junit.Test
import java.util.UUID
import kotlin.test.assertTrue
class ExtendLvmPoolTest {
@Test
fun take() {
val lvmStorageId = UUID.randomUUID()
val host = testHost.copy(
capabilities = testHostCapabilities.copy(
storageCapabilities = listOf(
LvmStorageCapability(
id = lvmStorageId,
size = 2.TB,
physicalVolumes = mapOf("/dev/sda" to 2.TB),
volumeGroupName = "test-vg"
)
)
)
)
val original = OperationalState.fromLists(
hosts = listOf(host),
hostDyns = listOf(
HostDynamic(
id = testHost.id,
status = HostStatus.Up,
storageStatus = listOf(
SimpleStorageDeviceDynamic(
id = lvmStorageId,
freeCapacity = 600.GB
)
)
)
),
hostCfgs = listOf(
HostConfiguration(
id = testHost.id,
storageConfiguration = listOf(
LvmPoolConfiguration(
poolName = "test-pool",
size = 256.GB,
vgName = "test-vg"
)
)
)
)
)
val state = ExtendLvmPool(vgName = "test-vg", pool = "test-pool", host = host, addSize = 128.GB)
.take(original)
assertTrue {
val configuration = state.hosts[host.id]!!.config!!.storageConfiguration.single()
as LvmPoolConfiguration
configuration.poolName == "test-pool"
&& configuration.size == 128.GB + 256.GB
&& configuration.vgName == "test-vg"
}
}
} | 0 | Kotlin | 0 | 1 | 42b70cb9a182af4923a7f960c6df98284e03bab2 | 2,175 | kerub | Apache License 2.0 |
educational-core/src/com/jetbrains/edu/learning/taskDescription/ui/check/CheckMessagePanel.kt | renuacpro | 390,257,792 | true | {"Kotlin": 3480129, "HTML": 1875210, "Java": 531269, "CSS": 12158, "Python": 5553, "JavaScript": 315} | package com.jetbrains.edu.learning.taskDescription.ui.check
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ArrayUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.jetbrains.edu.learning.checker.CheckResult
import com.jetbrains.edu.learning.checker.CheckResultDiff
import com.jetbrains.edu.learning.taskDescription.ui.EduBrowserHyperlinkListener
import com.jetbrains.edu.learning.taskDescription.ui.createTextPane
import java.awt.BorderLayout
import java.awt.Font
import javax.swing.*
import javax.swing.event.HyperlinkListener
import kotlin.math.min
import kotlin.math.roundToInt
class CheckMessagePanel private constructor() : JPanel() {
private val messagePane: JTextPane = createTextPane().apply {
border = JBUI.Borders.emptyTop(16)
}
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
border = JBUI.Borders.emptyLeft(FOCUS_BORDER_WIDTH)
add(messagePane)
}
var messageShortened: Boolean = false
override fun isVisible(): Boolean =
componentCount > 1 || messagePane.document.getText(0, messagePane.document.length).isNotEmpty()
private fun setMessage(message: String) {
val lines = message.lines()
val displayMessage = if (message.length > MAX_MESSAGE_LENGTH || lines.size > MAX_LINES_NUMBER) {
messageShortened = true
// we could potentially cut message in the middle of html tag
val messageLinesCut = lines.subList(0, min(lines.size, MAX_LINES_NUMBER)).joinToString("\n")
messageLinesCut.substring(0, min(messageLinesCut.length, MAX_MESSAGE_LENGTH)) + "..."
}
else {
messageShortened = false
message
}
messagePane.text = StringUtil.replace(displayMessage, listOf(" ", "\n"), listOf(" ", "<br>"))
}
private fun setHyperlinkListener(listener: HyperlinkListener) {
messagePane.addHyperlinkListener(listener)
}
private fun setDiff(diff: CheckResultDiff) {
val expected = createLabeledComponent(diff.expected, "Expected")
val actual = createLabeledComponent(diff.actual, "Actual")
UIUtil.mergeComponentsWithAnchor(expected, actual)
add(expected)
add(actual)
}
private fun createLabeledComponent(resultText: String, labelText: String): LabeledComponent<JComponent> {
val lines = resultText.lines()
val displayMessage = if (lines.size > MAX_LINES_NUMBER)
lines.subList(0, MAX_LINES_NUMBER).joinToString("\n") + "..."
else resultText
val textPane = MultiLineLabel(displayMessage).apply {
// `JBUI.Fonts.create` implementation scales font size.
// Also, at the same time `font.size` returns scaled size.
// So we have to pass non scaled font size to create font with correct size
font = JBUI.Fonts.create(Font.MONOSPACED, (font.size / JBUIScale.scale(1f)).roundToInt())
verticalAlignment = JLabel.TOP
}
val labeledComponent = LabeledComponent.create<JComponent>(textPane, labelText, BorderLayout.WEST)
labeledComponent.label.foreground = UIUtil.getLabelDisabledForeground()
labeledComponent.label.verticalAlignment = JLabel.TOP
labeledComponent.border = JBUI.Borders.emptyTop(8)
return labeledComponent
}
companion object {
val FOCUS_BORDER_WIDTH = if (SystemInfo.isMac) 3 else if (SystemInfo.isWindows) 0 else 2
const val MAX_MESSAGE_LENGTH = 300
const val MAX_LINES_NUMBER = 3
@JvmStatic
fun create(checkResult: CheckResult): CheckMessagePanel {
val messagePanel = CheckMessagePanel()
messagePanel.setMessage(checkResult.message)
messagePanel.setHyperlinkListener(checkResult.hyperlinkListener ?: EduBrowserHyperlinkListener.INSTANCE)
if (checkResult.diff != null) {
messagePanel.setDiff(checkResult.diff)
}
return messagePanel
}
}
}
private class MultiLineLabelUI : com.intellij.openapi.ui.MultiLineLabelUI() {
private var text: String? = null
private var lines: Array<String> = ArrayUtil.EMPTY_STRING_ARRAY
// Almost identical with original implementation
// except it doesn't trim lines
override fun splitStringByLines(str: String?): Array<String> {
if (str == null) return ArrayUtil.EMPTY_STRING_ARRAY
if (str == text) return lines
val convertedStr = convertTabs(str, 2)
text = convertedStr
lines = convertedStr.lines().toTypedArray()
return lines
}
}
private class MultiLineLabel(text: String?) : com.intellij.openapi.ui.ex.MultiLineLabel(text) {
override fun updateUI() {
setUI(MultiLineLabelUI())
}
}
| 0 | null | 0 | 0 | 3e157fda0179bdaf8a1a8125a587d908db285f9f | 4,643 | educational-plugin | Apache License 2.0 |
chatkit-core/src/main/kotlin/com/pusher/chatkit/SynchronousChatManager.kt | pusher | 106,020,436 | false | null | package com.pusher.chatkit
import com.pusher.chatkit.cursors.CursorService
import com.pusher.chatkit.files.FilesService
import com.pusher.chatkit.messages.MessageService
import com.pusher.chatkit.messages.multipart.UrlRefresher
import com.pusher.chatkit.presence.Presence
import com.pusher.chatkit.presence.PresenceService
import com.pusher.chatkit.presence.PresenceSubscriptionEvent
import com.pusher.chatkit.pushnotifications.BeamsTokenProviderService
import com.pusher.chatkit.pushnotifications.PushNotifications
import com.pusher.chatkit.rooms.RoomConsumer
import com.pusher.chatkit.rooms.RoomEvent
import com.pusher.chatkit.rooms.RoomService
import com.pusher.chatkit.users.UserInternalEvent
import com.pusher.chatkit.users.UserService
import com.pusher.chatkit.users.UserSubscription
import com.pusher.chatkit.users.UserSubscriptionEvent
import com.pusher.chatkit.util.makeSafe
import com.pusher.platform.Instance
import com.pusher.platform.Locator
import com.pusher.platform.logger.Logger
import com.pusher.platform.tokenProvider.TokenProvider
import com.pusher.util.Result
import com.pusher.util.asFailure
import com.pusher.util.asSuccess
import elements.Error
import elements.Errors
class SynchronousChatManager : AppHookListener {
constructor(
instanceLocator: String,
userId: String,
dependencies: ChatkitDependencies
) : this(instanceLocator, userId, dependencies, DefaultPlatformClientFactory())
internal constructor(
instanceLocator: String,
userId: String,
dependencies: ChatkitDependencies,
platformClientFactory: PlatformClientFactory
) {
this.instanceLocator = instanceLocator
this.userId = userId
this.dependencies = dependencies
this.platformClientFactory = platformClientFactory
tokenProvider = DebounceTokenProvider(
dependencies.tokenProvider
.also { (it as? ChatkitTokenProvider)?.userId = userId }
)
logger = dependencies.logger
coreLegacyV2Client = createPlatformClient(InstanceType.CORE_LEGACY_V2)
coreClient = createPlatformClient(InstanceType.CORE)
cursorsClient = createPlatformClient(InstanceType.CURSORS)
presenceClient = createPlatformClient(InstanceType.PRESENCE)
filesClient = createPlatformClient(InstanceType.FILES)
beams = dependencies.pushNotifications?.newBeams(
Locator(instanceLocator).id,
BeamsTokenProviderService(createPlatformClient(InstanceType.BEAMS_TOKEN_PROVIDER))
)
urlRefresher = UrlRefresher(coreClient)
cursorService = CursorService(cursorsClient, logger)
filesService = FilesService(filesClient)
presenceService =
PresenceService(
myUserId = userId,
logger = logger,
client = presenceClient,
consumer = this::consumePresenceSubscriptionEvent
)
userService = UserService(coreClient, presenceService)
roomService =
RoomService(
coreLegacyV2Client,
coreClient,
urlRefresher,
userService,
cursorService,
this::consumeRoomSubscriptionEvent,
dependencies.logger
)
messageService = MessageService(
coreLegacyV2Client,
coreClient,
userService,
roomService,
urlRefresher,
filesService
)
}
private val instanceLocator: String
private val userId: String
private val dependencies: ChatkitDependencies
private val platformClientFactory: PlatformClientFactory
private val tokenProvider: TokenProvider
private val logger: Logger
private val coreLegacyV2Client: PlatformClient
private val coreClient: PlatformClient
private val cursorsClient: PlatformClient
private val presenceClient: PlatformClient
private val filesClient: PlatformClient
private val beams: PushNotifications?
private val eventConsumers = mutableListOf<ChatManagerEventConsumer>()
private val urlRefresher: UrlRefresher
internal val cursorService: CursorService
private val filesService: FilesService
private val presenceService: PresenceService
internal val userService: UserService
internal val roomService: RoomService
internal val messageService: MessageService
private lateinit var userSubscription: UserSubscription
private lateinit var currentUser: SynchronousCurrentUser
private fun emit(event: ChatEvent) {
eventConsumers.forEach { consumer ->
consumer(event)
}
}
private val populatedInitialStateLock = Object()
private var populatedInitialState = false
fun connect(listeners: ChatListeners): Result<SynchronousCurrentUser, Error> =
connect(listeners.toCallback())
@JvmOverloads
fun connect(consumer: ChatManagerEventConsumer = {}): Result<SynchronousCurrentUser, Error> {
eventConsumers += { event -> makeSafe(logger) { consumer(event) } }
// The room service filters and translates some global events (e.g. RoomUpdated), forwarding
// them to the relevant room subscriptions
// The room service has ensured the safety of its own consumers.
eventConsumers += roomService::distributeGlobalEvent
dependencies.appHooks.register(this)
userSubscription = UserSubscription(
userId = userId,
client = coreClient,
listeners = ::consumeUserSubscriptionEvent,
logger = logger
)
return userSubscription.initialState().map { initialState ->
currentUser = newCurrentUser(initialState)
logger.verbose("Current User initialised")
roomService.populateInitial(initialState)
cursorService.populateInitial(initialState)
emit(ChatEvent.CurrentUserReceived(currentUser))
synchronized(populatedInitialStateLock) {
populatedInitialState = true
populatedInitialStateLock.notify() // there should be only one thread waiting
}
currentUser
}
}
override fun onAppOpened() {
presenceService.goOnline()
}
override fun onAppClosed() {
presenceService.goOffline()
}
private fun consumeUserSubscriptionEvent(incomingEvent: UserSubscriptionEvent) {
synchronized(populatedInitialStateLock) { // wait for initial state to be processed first
// loop for spurious wakeup protection https://en.wikipedia.org/wiki/Spurious_wakeup
while (!populatedInitialState) populatedInitialStateLock.wait()
}
if (incomingEvent is UserSubscriptionEvent.InitialState) {
currentUser.updateWithPropertiesOf(newCurrentUser(incomingEvent))
}
val appliedEvents = roomService.roomStore.applyUserSubscriptionEvent(incomingEvent) +
cursorService.applyEvent(incomingEvent)
return appliedEvents.forEach { event ->
emit(transformUserInternalEvent(event))
}
}
private fun consumeRoomSubscriptionEvent(roomId: String): RoomConsumer = { event ->
consumeEvents(listOf(transformRoomSubscriptionEvent(roomId, event)))
}
private fun consumePresenceSubscriptionEvent(event: PresenceSubscriptionEvent) =
consumeEvents(transformPresenceSubscriptionEvent(event))
private fun consumeEvents(events: List<ChatEvent>) {
events.forEach(this::emit)
}
private fun transformUserInternalEvent(event: UserInternalEvent): ChatEvent =
when (event) {
is UserInternalEvent.AddedToRoom ->
ChatEvent.AddedToRoom(event.room)
is UserInternalEvent.RemovedFromRoom ->
ChatEvent.RemovedFromRoom(event.roomId)
is UserInternalEvent.RoomUpdated ->
ChatEvent.RoomUpdated(event.room)
is UserInternalEvent.RoomDeleted ->
ChatEvent.RoomDeleted(event.roomId)
is UserInternalEvent.UserJoinedRoom ->
userService.fetchUserBy(event.userId).fold(
onSuccess = { user ->
val room = roomService.roomStore[event.roomId]!!
ChatEvent.UserJoinedRoom(user, room)
},
onFailure = { ChatEvent.ErrorOccurred(it) }
)
is UserInternalEvent.UserLeftRoom ->
userService.fetchUserBy(event.userId).fold(
onSuccess = { user ->
val room = roomService.roomStore[event.roomId]!!
ChatEvent.UserLeftRoom(user, room)
},
onFailure = { ChatEvent.ErrorOccurred(it) }
)
is UserInternalEvent.NewCursor ->
ChatEvent.NewReadCursor(event.cursor)
is UserInternalEvent.ErrorOccurred ->
ChatEvent.ErrorOccurred(event.error)
}
private fun transformRoomSubscriptionEvent(roomId: String, event: RoomEvent): ChatEvent =
when (event) {
is RoomEvent.UserStartedTyping ->
roomService.getJoinedRoom(roomId).map { room ->
ChatEvent.UserStartedTyping(event.user, room) as ChatEvent
}.recover { ChatEvent.ErrorOccurred(it) }
is RoomEvent.UserStoppedTyping ->
roomService.getJoinedRoom(roomId).map { room ->
ChatEvent.UserStoppedTyping(event.user, room) as ChatEvent
}.recover { ChatEvent.ErrorOccurred(it) }
else ->
ChatEvent.NoEvent
}
private fun transformPresenceSubscriptionEvent(event: PresenceSubscriptionEvent): List<ChatEvent> {
val newStates = when (event) {
is PresenceSubscriptionEvent.PresenceUpdate -> listOf(event.presence)
else -> listOf()
}
return newStates.map { newState ->
newState.userId
}.let { userIDs ->
userService.fetchUsersBy(userIDs.toSet())
}.map { users ->
newStates.map { newState ->
newState to users.getValue(newState.userId)
}.filter { (newState, user) ->
newState.presence != user.presence
}.map { (newState, user) ->
val oldState = user.presence
user.presence = newState.presence
when (newState.presence) {
is Presence.Online -> ChatEvent.PresenceChange(user, newState.presence, oldState)
is Presence.Offline -> ChatEvent.PresenceChange(user, newState.presence, oldState)
is Presence.Unknown -> ChatEvent.NoEvent
}
}
}.recover {
listOf(ChatEvent.ErrorOccurred(it))
}
}
private fun newCurrentUser(initialState: UserSubscriptionEvent.InitialState) =
SynchronousCurrentUser(
id = initialState.currentUser.id,
avatarURL = initialState.currentUser.avatarURL,
customData = initialState.currentUser.customData,
name = initialState.currentUser.name,
chatManager = this,
pushNotifications = beams,
client = createPlatformClient(InstanceType.CORE)
)
/**
* Tries to close all pending subscriptions and resources
*/
fun close(): Result<Unit, Error> = try {
dependencies.appHooks.unregister(this)
userSubscription.unsubscribe()
roomService.close()
presenceService.close()
cursorService.close()
dependencies.okHttpClient?.connectionPool()?.evictAll()
eventConsumers.clear()
Unit.asSuccess()
} catch (e: Throwable) {
Errors.other(e).asFailure()
}
private fun createPlatformClient(type: InstanceType): PlatformClient {
val instance = Instance(
locator = instanceLocator,
serviceName = type.serviceName,
serviceVersion = type.version,
dependencies = dependencies
)
return platformClientFactory.createPlatformClient(dependencies.okHttpClient.let { client ->
when (client) {
null -> instance
else -> instance.copy(baseClient = instance.baseClient.copy(client = client))
}
}, tokenProvider)
}
fun disablePushNotifications(): Result<Unit, Error> {
if (beams != null) {
return beams.stop()
} else {
throw IllegalStateException("Push Notifications dependency is not available. " +
"Did you provide a Context to AndroidChatkitDependencies?")
}
}
}
internal enum class InstanceType(val serviceName: String, val version: String = "v1") {
CORE_LEGACY_V2("chatkit", "v2"),
CORE("chatkit", "v7"),
CURSORS("chatkit_cursors", "v2"),
PRESENCE("chatkit_presence", "v2"),
FILES("chatkit_files"),
BEAMS_TOKEN_PROVIDER("chatkit_beams_token_provider")
}
| 12 | Kotlin | 14 | 54 | 4bc7d96059a8d6ec66032c84819f77149b6c3296 | 13,641 | chatkit-android | MIT License |
ejson/src/test/kotlin/com/eygraber/ejson/KeyDirTests.kt | eygraber | 374,549,580 | false | {"Kotlin": 34734, "Shell": 1351} | package com.eygraber.ejson
import com.google.common.jimfs.Configuration
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import uk.org.webcompere.systemstubs.environment.EnvironmentVariables
import uk.org.webcompere.systemstubs.jupiter.SystemStub
import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension
@ExtendWith(SystemStubsExtension::class)
class KeyDirTests {
@Test
fun `when there is no keydir an error is thrown`() = usingFileSystem { fs ->
val ejson = Ejson(filesystem = fs)
assertThrowsWithMessage<IllegalStateException>(
"Decryption failed: couldn't read key file $PUBLIC_KEY"
) {
ejson.decrypt(
"""
|{"_public_key": "$PUBLIC_KEY"}
""".trimMargin()
)
}
}
@Test
fun `when the keydir doesn't exist an error is thrown`() = usingFileSystem { fs ->
val ejson = Ejson(
overrideKeyDir = fs.getPath("fake"),
filesystem = fs
)
assertThrowsWithMessage<IllegalStateException>(
"Decryption failed: couldn't read key file $PUBLIC_KEY (fake/$PUBLIC_KEY)"
) {
ejson.decrypt(
"""
|{"_public_key": "$PUBLIC_KEY"}
""".trimMargin()
)
}
}
@Test
fun `when the default keydir is used no error is thrown`() = usingFileSystem { fs ->
fs.withDefaultKeyDir { kp, ejson ->
val encrypted = ejson.assertEncryptSucceededJson(
kp.createValidSecretsJson("secret" to "Keep it secret, keep it safe!")
)
ejson.assertDecryptSucceededJson(encrypted.toString())
}
}
@SystemStub
@Suppress("unused")
private val envVars = EnvironmentVariables("EJSON_KEYDIR", "/tmp/ejsonKeyDir")
@Test
fun `when the envvar keydir is used no error is thrown`() = usingFileSystem(Configuration.unix()) { fs ->
fs.withEnvVarKeyDir { kp, ejson ->
val encrypted = ejson.assertEncryptSucceededJson(
kp.createValidSecretsJson("secret" to "Keep it secret, keep it safe!")
)
ejson.assertDecryptSucceededJson(encrypted.toString())
}
}
@Test
fun `when the override keydir is used no error is thrown`() = usingFileSystem { fs ->
fs.withOverrideKeyDir("some/path") { kp, ejson ->
val encrypted = ejson.assertEncryptSucceededJson(
kp.createValidSecretsJson("secret" to "Keep it secret, keep it safe!")
)
ejson.assertDecryptSucceededJson(encrypted.toString())
}
}
companion object {
const val PUBLIC_KEY = "1234567890123456789012345678901234567890123456789012345678901234"
}
}
| 3 | Kotlin | 0 | 1 | d23c1d1a15bd71aec5d56440712a7e4532eda95d | 2,546 | ejson-kotlin | MIT License |
src/test/kotlin/com/lykke/matching/engine/services/LimitOrderServiceDustTest.kt | MioGreen | 108,066,733 | true | {"Kotlin": 485839, "Java": 39868} | package com.lykke.matching.engine.services
import com.lykke.matching.engine.daos.Asset
import com.lykke.matching.engine.daos.AssetPair
import com.lykke.matching.engine.daos.TradeInfo
import com.lykke.matching.engine.database.TestBackOfficeDatabaseAccessor
import com.lykke.matching.engine.database.TestFileOrderDatabaseAccessor
import com.lykke.matching.engine.database.TestMarketOrderDatabaseAccessor
import com.lykke.matching.engine.database.TestWalletDatabaseAccessor
import com.lykke.matching.engine.database.buildWallet
import com.lykke.matching.engine.database.cache.AssetPairsCache
import com.lykke.matching.engine.database.cache.AssetsCache
import com.lykke.matching.engine.holders.AssetsHolder
import com.lykke.matching.engine.holders.AssetsPairsHolder
import com.lykke.matching.engine.holders.BalancesHolder
import com.lykke.matching.engine.notification.BalanceUpdateNotification
import com.lykke.matching.engine.notification.QuotesUpdate
import com.lykke.matching.engine.order.OrderStatus
import com.lykke.matching.engine.outgoing.messages.JsonSerializable
import com.lykke.matching.engine.outgoing.messages.LimitOrdersReport
import com.lykke.matching.engine.outgoing.messages.OrderBook
import com.lykke.matching.engine.utils.MessageBuilder.Companion.buildLimitOrder
import com.lykke.matching.engine.utils.MessageBuilder.Companion.buildLimitOrderWrapper
import org.junit.Before
import org.junit.Test
import java.util.concurrent.LinkedBlockingQueue
import kotlin.test.assertEquals
class LimitOrderServiceDustTest {
var testDatabaseAccessor = TestFileOrderDatabaseAccessor()
var testMarketDatabaseAccessor = TestMarketOrderDatabaseAccessor()
val testWalletDatabaseAcessor = TestWalletDatabaseAccessor()
var testBackOfficeDatabaseAccessor = TestBackOfficeDatabaseAccessor()
val tradesInfoQueue = LinkedBlockingQueue<TradeInfo>()
val quotesNotificationQueue = LinkedBlockingQueue<QuotesUpdate>()
val orderBookQueue = LinkedBlockingQueue<OrderBook>()
val rabbitOrderBookQueue = LinkedBlockingQueue<JsonSerializable>()
val balanceUpdateQueue = LinkedBlockingQueue<JsonSerializable>()
val limitOrdersQueue = LinkedBlockingQueue<JsonSerializable>()
val assetsHolder = AssetsHolder(AssetsCache(testBackOfficeDatabaseAccessor, 60000))
val assetsPairsHolder = AssetsPairsHolder(AssetPairsCache(testWalletDatabaseAcessor, 60000))
val balancesHolder = BalancesHolder(testWalletDatabaseAcessor, assetsHolder, LinkedBlockingQueue<BalanceUpdateNotification>(), balanceUpdateQueue, setOf("Client3"))
@Before
fun setUp() {
testDatabaseAccessor = TestFileOrderDatabaseAccessor()
testWalletDatabaseAcessor.clear()
testBackOfficeDatabaseAccessor.addAsset(Asset("USD", 2, "USD"))
testBackOfficeDatabaseAccessor.addAsset(Asset("BTC", 8, "BTC"))
testWalletDatabaseAcessor.addAssetPair(AssetPair("BTCUSD", "BTC", "USD", 8, 8))
testWalletDatabaseAcessor.insertOrUpdateWallet(buildWallet("Client1", "BTC", 1000.0))
testWalletDatabaseAcessor.insertOrUpdateWallet(buildWallet("Client1", "USD", 1000.0))
testWalletDatabaseAcessor.insertOrUpdateWallet(buildWallet("Client2", "BTC", 1000.0))
testWalletDatabaseAcessor.insertOrUpdateWallet(buildWallet("Client2", "USD", 1000.0))
}
@Test
fun testAddAndMatchLimitOrderWithDust1() {
val service = SingleLimitOrderService(GenericLimitOrderService(testDatabaseAccessor, assetsHolder, assetsPairsHolder, balancesHolder, tradesInfoQueue, quotesNotificationQueue), limitOrdersQueue, orderBookQueue, rabbitOrderBookQueue, assetsHolder, assetsPairsHolder, emptySet(), balancesHolder, testMarketDatabaseAccessor)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client1", price = 3200.0, volume = -0.05)))
assertEquals(1, limitOrdersQueue.size)
var result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(1, result.orders.size)
assertEquals(OrderStatus.InOrderBook.name, result.orders[0].order.status)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client2", price = 3200.0, volume = 0.04997355)))
assertEquals(1, limitOrdersQueue.size)
result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(2, result.orders.size)
assertEquals(OrderStatus.Matched.name, result.orders[0].order.status)
assertEquals(OrderStatus.Processing.name, result.orders[1].order.status)
assertEquals(1000 - 0.04997355, testWalletDatabaseAcessor.getBalance("Client1", "BTC"))
assertEquals(1159.92, testWalletDatabaseAcessor.getBalance("Client1", "USD"))
assertEquals(1000 + 0.04997355, testWalletDatabaseAcessor.getBalance("Client2", "BTC"))
assertEquals(840.08, testWalletDatabaseAcessor.getBalance("Client2", "USD"))
}
@Test
fun testAddAndMatchLimitOrderWithDust2() {
val service = SingleLimitOrderService(GenericLimitOrderService(testDatabaseAccessor, assetsHolder, assetsPairsHolder, balancesHolder, tradesInfoQueue, quotesNotificationQueue), limitOrdersQueue, orderBookQueue, rabbitOrderBookQueue, assetsHolder, assetsPairsHolder, emptySet(), balancesHolder, testMarketDatabaseAccessor)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client1", price = 3200.0, volume = -0.05)))
assertEquals(1, limitOrdersQueue.size)
var result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(1, result.orders.size)
assertEquals(OrderStatus.InOrderBook.name, result.orders[0].order.status)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client2", price = 3200.0, volume = 0.05002635)))
assertEquals(1, limitOrdersQueue.size)
result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(2, result.orders.size)
assertEquals(OrderStatus.Processing.name, result.orders[0].order.status)
assertEquals(OrderStatus.Matched.name, result.orders[1].order.status)
assertEquals(999.95, testWalletDatabaseAcessor.getBalance("Client1", "BTC"))
assertEquals(1160.0, testWalletDatabaseAcessor.getBalance("Client1", "USD"))
assertEquals(1000.05, testWalletDatabaseAcessor.getBalance("Client2", "BTC"))
assertEquals(840.0, testWalletDatabaseAcessor.getBalance("Client2", "USD"))
}
@Test
fun testAddAndMatchLimitOrderWithDust3() {
val service = SingleLimitOrderService(GenericLimitOrderService(testDatabaseAccessor, assetsHolder, assetsPairsHolder, balancesHolder, tradesInfoQueue, quotesNotificationQueue), limitOrdersQueue, orderBookQueue, rabbitOrderBookQueue, assetsHolder, assetsPairsHolder, emptySet(), balancesHolder, testMarketDatabaseAccessor)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client1", price = 3200.0, volume = 0.05)))
assertEquals(1, limitOrdersQueue.size)
var result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(1, result.orders.size)
assertEquals(OrderStatus.InOrderBook.name, result.orders[0].order.status)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client2", price = 3200.0, volume = -0.04997355)))
assertEquals(1, limitOrdersQueue.size)
result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(2, result.orders.size)
assertEquals(OrderStatus.Matched.name, result.orders[0].order.status)
assertEquals(OrderStatus.Processing.name, result.orders[1].order.status)
assertEquals(1000 + 0.04997355, testWalletDatabaseAcessor.getBalance("Client1", "BTC"))
assertEquals(840.09, testWalletDatabaseAcessor.getBalance("Client1", "USD"))
assertEquals(1000 - 0.04997355, testWalletDatabaseAcessor.getBalance("Client2", "BTC"))
assertEquals(1159.91, testWalletDatabaseAcessor.getBalance("Client2", "USD"))
}
@Test
fun testAddAndMatchLimitOrderWithDust4() {
val service = SingleLimitOrderService(GenericLimitOrderService(testDatabaseAccessor, assetsHolder, assetsPairsHolder, balancesHolder, tradesInfoQueue, quotesNotificationQueue), limitOrdersQueue, orderBookQueue, rabbitOrderBookQueue, assetsHolder, assetsPairsHolder, emptySet(), balancesHolder, testMarketDatabaseAccessor)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client1", price = 3200.0, volume = 0.05)))
assertEquals(1, limitOrdersQueue.size)
var result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(1, result.orders.size)
assertEquals(OrderStatus.InOrderBook.name, result.orders[0].order.status)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client2", price = 3200.0, volume = -0.05002635)))
assertEquals(1, limitOrdersQueue.size)
result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(2, result.orders.size)
assertEquals(OrderStatus.Processing.name, result.orders[0].order.status)
assertEquals(OrderStatus.Matched.name, result.orders[1].order.status)
assertEquals(1000.05, testWalletDatabaseAcessor.getBalance("Client1", "BTC"))
assertEquals(840.0, testWalletDatabaseAcessor.getBalance("Client1", "USD"))
assertEquals(999.95, testWalletDatabaseAcessor.getBalance("Client2", "BTC"))
assertEquals(1160.0, testWalletDatabaseAcessor.getBalance("Client2", "USD"))
}
@Test
fun testAddAndMatchLimitOrderWithDust5() {
val service = SingleLimitOrderService(GenericLimitOrderService(testDatabaseAccessor, assetsHolder, assetsPairsHolder, balancesHolder, tradesInfoQueue, quotesNotificationQueue), limitOrdersQueue, orderBookQueue, rabbitOrderBookQueue, assetsHolder, assetsPairsHolder, emptySet(), balancesHolder, testMarketDatabaseAccessor)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client1", price = 3200.0, volume = -0.05)))
assertEquals(1, limitOrdersQueue.size)
var result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(1, result.orders.size)
assertEquals(OrderStatus.InOrderBook.name, result.orders[0].order.status)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client2", price = 3200.0, volume = 0.0499727)))
assertEquals(1, limitOrdersQueue.size)
result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(2, result.orders.size)
assertEquals(OrderStatus.Matched.name, result.orders[0].order.status)
assertEquals(OrderStatus.Processing.name, result.orders[1].order.status)
assertEquals(999.9500273, testWalletDatabaseAcessor.getBalance("Client1", "BTC"))
assertEquals(1159.92, testWalletDatabaseAcessor.getBalance("Client1", "USD"))
assertEquals(1000.0499727, testWalletDatabaseAcessor.getBalance("Client2", "BTC"))
assertEquals(840.08, testWalletDatabaseAcessor.getBalance("Client2", "USD"))
}
@Test
fun testAddAndMatchLimitOrderWithDust6() {
val service = SingleLimitOrderService(GenericLimitOrderService(testDatabaseAccessor, assetsHolder, assetsPairsHolder, balancesHolder, tradesInfoQueue, quotesNotificationQueue), limitOrdersQueue, orderBookQueue, rabbitOrderBookQueue, assetsHolder, assetsPairsHolder, emptySet(), balancesHolder, testMarketDatabaseAccessor)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client1", price = 3200.0, volume = 0.05)))
assertEquals(1, limitOrdersQueue.size)
var result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(1, result.orders.size)
assertEquals(OrderStatus.InOrderBook.name, result.orders[0].order.status)
service.processMessage(buildLimitOrderWrapper(buildLimitOrder(assetId = "BTCUSD", clientId = "Client2", price = 3200.0, volume = -0.0499727)))
assertEquals(1, limitOrdersQueue.size)
result = limitOrdersQueue.poll() as LimitOrdersReport
assertEquals(2, result.orders.size)
assertEquals(OrderStatus.Matched.name, result.orders[0].order.status)
assertEquals(OrderStatus.Processing.name, result.orders[1].order.status)
assertEquals(1000.0499727, testWalletDatabaseAcessor.getBalance("Client1", "BTC"))
assertEquals(840.09, testWalletDatabaseAcessor.getBalance("Client1", "USD"))
assertEquals(999.9500273, testWalletDatabaseAcessor.getBalance("Client2", "BTC"))
assertEquals(1159.91, testWalletDatabaseAcessor.getBalance("Client2", "USD"))
}
} | 0 | Kotlin | 0 | 0 | 2c21756b3617b63cfb44fef31eae44715fc1b917 | 12,877 | MatchingEngine | MIT License |
app/src/main/java/ren/imyan/sniper/ui/request/RequestDialog.kt | Snipdroid | 612,700,604 | false | null | package ren.imyan.sniper.ui.request
import android.app.Activity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import ren.imyan.sniper.R
import ren.imyan.sniper.databinding.DialogRequestBinding
class RequestDialog(activity: Activity) {
private val binding = DialogRequestBinding.inflate(activity.layoutInflater, null, false)
private val dialog =
MaterialAlertDialogBuilder(
activity,
com.google.android.material.R.style.ThemeOverlay_Material3_MaterialAlertDialog_Centered
).setView(binding.root).setTitle(R.string.uploading)
.setIcon(R.drawable.outline_cloud_upload_24)
.setCancelable(false)
.setPositiveButton(R.string.cancel) { _, _ -> }.create()
fun show() {
dialog.show()
binding.apply {
loading.isIndeterminate = true
}
}
fun updateProgress(progress: Int, max: Int) {
binding.loading.apply {
setMax(max)
setProgressCompat(progress, true)
}
}
fun dismiss() {
dialog.dismiss()
}
} | 0 | Kotlin | 0 | 0 | 5b6739d4e3705011a444a7b88ed73978fe6739d5 | 1,102 | Sniper | MIT License |
app/src/main/java/ren/imyan/sniper/ui/request/RequestDialog.kt | Snipdroid | 612,700,604 | false | null | package ren.imyan.sniper.ui.request
import android.app.Activity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import ren.imyan.sniper.R
import ren.imyan.sniper.databinding.DialogRequestBinding
class RequestDialog(activity: Activity) {
private val binding = DialogRequestBinding.inflate(activity.layoutInflater, null, false)
private val dialog =
MaterialAlertDialogBuilder(
activity,
com.google.android.material.R.style.ThemeOverlay_Material3_MaterialAlertDialog_Centered
).setView(binding.root).setTitle(R.string.uploading)
.setIcon(R.drawable.outline_cloud_upload_24)
.setCancelable(false)
.setPositiveButton(R.string.cancel) { _, _ -> }.create()
fun show() {
dialog.show()
binding.apply {
loading.isIndeterminate = true
}
}
fun updateProgress(progress: Int, max: Int) {
binding.loading.apply {
setMax(max)
setProgressCompat(progress, true)
}
}
fun dismiss() {
dialog.dismiss()
}
} | 0 | Kotlin | 0 | 0 | 5b6739d4e3705011a444a7b88ed73978fe6739d5 | 1,102 | Sniper | MIT License |
src/main/kotlin/Interfaces.kt | Muhammad-Shayan-Haider | 611,615,684 | false | null | fun main() {
}
// In interfaces, all methods are by default abstract. A class can implement multiple interfaces.
// Interfaces can define common behaviours to implement. We can implement polymorphism using interfaces as well.
interface Draggable {
val dragSpeed: Int
fun drag()
} | 0 | Kotlin | 0 | 0 | 676c8698e8a910534f0d43ed4ab5e7231b83ab60 | 290 | kotlin-learning | MIT License |
view/src/main/java/cmm/apps/esmorga/view/eventList/model/EventListUiState.kt | cmm-apps-android | 797,188,002 | false | {"Kotlin": 72481} | package cmm.apps.esmorga.view.eventList.model
data class EventListUiState(
val loading: Boolean = false,
val eventList: List<EventUiModel> = emptyList(),
val error: String? = null
)
data class EventUiModel(
val imageUrl: String?,
val cardTitle: String,
val cardSubtitle1: String,
val cardSubtitle2: String
)
sealed class EventListEffect {
data object ShowNoNetworkPrompt : EventListEffect()
}
| 1 | Kotlin | 0 | 0 | f547cb5fc70daf2873c95af3a92aa26d4b765f12 | 429 | EsmorgaAndroid | The Unlicense |
app/src/main/java/com/ealva/toque/db/GenreMediaDao.kt | pandasys | 311,981,753 | false | null | /*
* Copyright 2021 Eric A. Snell
*
* 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.ealva.toque.db
import com.ealva.toque.common.Millis
import com.ealva.toque.persist.GenreIdList
import com.ealva.toque.persist.MediaId
import com.ealva.welite.db.TransactionInProgress
import com.ealva.welite.db.expr.bindLong
import com.ealva.welite.db.expr.eq
import com.ealva.welite.db.statements.deleteWhere
import com.ealva.welite.db.statements.insertValues
import com.ealva.welite.db.table.OnConflict
interface GenreMediaDao {
/**
* Insert or replace all genres for [newMediaId]
*/
fun TransactionInProgress.replaceMediaGenres(
genreIdList: GenreIdList,
newMediaId: MediaId,
createTime: Millis
)
companion object {
operator fun invoke(): GenreMediaDao = GenreMediaDaoImpl()
}
}
private val INSERT_GENRE_MEDIA = GenreMediaTable.insertValues(OnConflict.Ignore) {
it[genreId].bindArg()
it[mediaId].bindArg()
it[createdTime].bindArg()
}
private val BIND_MEDIA_ID = bindLong()
private val DELETE_MEDIA = GenreMediaTable.deleteWhere { mediaId eq BIND_MEDIA_ID }
private class GenreMediaDaoImpl : GenreMediaDao {
override fun TransactionInProgress.replaceMediaGenres(
genreIdList: GenreIdList,
newMediaId: MediaId,
createTime: Millis
) {
DELETE_MEDIA.delete { it[BIND_MEDIA_ID] = newMediaId.value }
genreIdList.forEach { newGenreId ->
INSERT_GENRE_MEDIA.insert {
it[genreId] = newGenreId.value
it[mediaId] = newMediaId.value
it[createdTime] = createTime()
}
}
}
}
| 0 | Kotlin | 0 | 0 | 9a765c89eab66523bd4b50bee4907c4eedec93e8 | 2,080 | toque | Apache License 2.0 |
app/src/main/java/tt/kao/sakuraprogress/ui/PetalFalling.kt | silviusko | 102,094,339 | false | null | package tt.kao.sakuraprogress.ui
import android.graphics.Matrix
import android.util.Log
import java.util.*
/**
* @author luke_kao
*/
class PetalFalling {
companion object {
private const val PETAL_FLOATING_TIME = 3000
private const val PETAL_ROTATION_TIME = 2000
}
private val random = Random()
private var count = 0
var progressWidth: Int = 0
var progressHeight: Int = 0
var petalWidth: Int = 0
var petalHeight: Int = 0
val petals = ArrayList<Petal>()
var petalFallingStartTime = 0L
var floatTime = PETAL_FLOATING_TIME
var rotateTime = PETAL_ROTATION_TIME
fun bloom(num: Int) {
prune()
for (i in 0 until num) {
val petal = Petal(
id = count++,
angle = random.nextInt(360),
direction = if (random.nextBoolean()) 1 else -1,
startTime = System.currentTimeMillis() + random.nextInt(floatTime),
amplitudeSeed = random.nextInt(num) + 1,
x = progressWidth.toFloat()
)
petals.add(petal)
}
Log.d("PetalFalling", "Petals size:${petals.size}")
}
private fun prune() {
petals.filter { it.x <= 0 }
.forEach { petals.remove(it) }
}
fun newMatrix(petal: Petal, currentTime: Long): Matrix {
val matrix = Matrix()
calculateLocation(currentTime, petal, matrix)
calculateRotation(currentTime, petal, matrix)
return matrix
}
private fun calculateLocation(currentTime: Long, petal: Petal, matrix: Matrix) {
val intervalTime = currentTime - petal.startTime
if (intervalTime < 0) return
val fraction = intervalTime.toFloat() / floatTime
petal.x = progressWidth - progressWidth * fraction
calculateAmplitude(currentTime, petal)
matrix.postTranslate(petal.x, petal.y)
// Log.d("SakuraProgress", "x:${petal.x}, y:${petal.y}")
}
private fun calculateAmplitude(currentTime: Long, petal: Petal) {
val intervalTime = currentTime - petal.startTime
if (intervalTime < 0) return
val w = 2f * Math.PI / progressWidth
val h = petal.amplitudeSeed * Math.PI / 10
petal.y = (Math.sin(w * petal.x + h) * progressHeight / 2 + progressHeight / 2f).toFloat()
}
private fun calculateRotation(currentTime: Long, petal: Petal, matrix: Matrix) {
val rotateFactor = (currentTime - petal.startTime) % rotateTime / rotateTime.toFloat()
val angle = rotateFactor * 360 * petal.direction
val rotate = petal.angle + angle
matrix.postRotate(rotate, petal.x + petalWidth / 2f, petal.y + petalHeight / 2f)
}
} | 0 | Kotlin | 0 | 1 | 5b5a4d6bd8c225094b99f08c4dcb0b224d2004c6 | 2,760 | Sakura-Progress | Apache License 2.0 |
ktor-server/ktor-server-host-common/jvm/src/io/ktor/server/engine/DefaultTransformJvm.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.engine
import io.ktor.http.*
import io.ktor.http.cio.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.util.*
import io.ktor.util.pipeline.*
import io.ktor.utils.io.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.jvm.javaio.*
import io.ktor.utils.io.streams.*
import kotlinx.coroutines.*
import java.io.*
internal actual suspend fun PipelineContext<ApplicationReceiveRequest, ApplicationCall>.defaultPlatformTransformations(
query: ApplicationReceiveRequest
): Any? {
val channel = query.value as? ByteReadChannel ?: return null
return when (query.typeInfo.type) {
InputStream::class -> receiveGuardedInputStream(channel)
MultiPartData::class -> multiPartData(channel)
else -> null
}
}
@OptIn(InternalAPI::class)
internal actual fun PipelineContext<*, ApplicationCall>.multiPartData(rc: ByteReadChannel): MultiPartData {
val contentType = call.request.header(HttpHeaders.ContentType)
?: throw IllegalStateException("Content-Type header is required for multipart processing")
val contentLength = call.request.header(HttpHeaders.ContentLength)?.toLong()
return CIOMultipartDataBase(
coroutineContext + Dispatchers.Unconfined,
rc,
contentType,
contentLength
)
}
internal actual fun ByteReadPacket.readTextWithCustomCharset(charset: Charset): String =
inputStream().reader(charset).readText()
private fun receiveGuardedInputStream(channel: ByteReadChannel): InputStream {
checkSafeParking()
return channel.toInputStream()
}
private fun checkSafeParking() {
check(safeToRunInPlace()) {
"Acquiring blocking primitives on this dispatcher is not allowed. " +
"Consider using async channel or " +
"doing withContext(Dispatchers.IO) { call.receive<InputStream>().use { ... } } instead."
}
}
| 302 | null | 806 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 2,097 | ktor | Apache License 2.0 |
app/src/main/kotlin/net/primal/android/feed/api/mediator/FeedRemoteMediator.kt | PrimalHQ | 639,579,258 | false | {"Kotlin": 2548226} | package net.primal.android.feed.api.mediator
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.withTransaction
import java.io.IOException
import java.time.Instant
import kotlin.time.Duration
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import net.primal.android.core.coroutines.CoroutineDispatcherProvider
import net.primal.android.core.ext.hasReposts
import net.primal.android.core.ext.hasUpwardsPagination
import net.primal.android.core.ext.isBookmarkFeed
import net.primal.android.db.PrimalDatabase
import net.primal.android.feed.api.FeedApi
import net.primal.android.feed.api.model.FeedRequestBody
import net.primal.android.feed.api.model.FeedResponse
import net.primal.android.feed.db.FeedPost
import net.primal.android.feed.db.FeedPostDataCrossRef
import net.primal.android.feed.db.FeedPostRemoteKey
import net.primal.android.feed.db.FeedPostSync
import net.primal.android.feed.db.sql.ChronologicalFeedWithRepostsQueryBuilder
import net.primal.android.feed.db.sql.ExploreFeedQueryBuilder
import net.primal.android.feed.db.sql.FeedQueryBuilder
import net.primal.android.feed.repository.persistToDatabaseAsTransaction
import net.primal.android.networking.sockets.errors.NostrNoticeException
import net.primal.android.networking.sockets.errors.WssException
import net.primal.android.nostr.ext.findFirstEventId
import net.primal.android.nostr.model.NostrEvent
import net.primal.android.nostr.model.primal.content.ContentPrimalPaging
import timber.log.Timber
@ExperimentalPagingApi
class FeedRemoteMediator(
private val dispatcherProvider: CoroutineDispatcherProvider,
private val feedDirective: String,
private val userId: String,
private val feedApi: FeedApi,
private val database: PrimalDatabase,
) : RemoteMediator<Int, FeedPost>() {
private val feedQueryBuilder: FeedQueryBuilder = when {
feedDirective.hasReposts() -> ChronologicalFeedWithRepostsQueryBuilder(
feedDirective = feedDirective,
userPubkey = userId,
)
else -> ExploreFeedQueryBuilder(
feedDirective = feedDirective,
userPubkey = userId,
)
}
private val lastRequests: MutableMap<LoadType, Pair<FeedRequestBody, Long>> = mutableMapOf()
private fun FeedPost?.isOlderThan(duration: Duration): Boolean {
if (this == null) return true
val postFeedCreateAt = Instant.ofEpochSecond(this.data.feedCreatedAt)
return postFeedCreateAt < Instant.now().minusSeconds(duration.inWholeSeconds)
}
private suspend fun shouldRefreshLatestFeed(): Boolean {
return newestFeedPostInDatabaseOrNull().isOlderThan(1.days)
}
private suspend fun shouldRefreshNonLatestFeed(feedDirective: String): Boolean {
val lastCachedAt = withContext(dispatcherProvider.io()) {
database.feedPostsRemoteKeys().lastCachedAt(directive = feedDirective)
} ?: return true
return lastCachedAt < Instant.now().minusSeconds(3.minutes.inWholeSeconds).epochSecond
}
private suspend fun shouldResetLocalCache() =
when {
feedDirective.hasUpwardsPagination() -> shouldRefreshLatestFeed()
feedDirective.isBookmarkFeed() -> true
else -> shouldRefreshNonLatestFeed(feedDirective)
}
override suspend fun initialize(): InitializeAction {
return when {
shouldResetLocalCache() -> InitializeAction.LAUNCH_INITIAL_REFRESH
else -> InitializeAction.SKIP_INITIAL_REFRESH
}
}
@Suppress("CyclomaticComplexMethod")
override suspend fun load(loadType: LoadType, state: PagingState<Int, FeedPost>): MediatorResult {
Timber.i("feed_directive $feedDirective load called ($loadType)")
return try {
if (loadType == LoadType.REFRESH && state.hasFeedPosts() && !shouldResetLocalCache()) {
throw UnnecessaryRefreshSync()
}
val remoteKey = when (loadType) {
LoadType.PREPEND -> findFirstFeedPostRemoteKey(state = state)
LoadType.APPEND -> findLastFeedPostRemoteKey(state = state)
else -> null
}
if (remoteKey == null && loadType != LoadType.REFRESH) {
throw RemoteKeyNotFoundException()
}
withContext(dispatcherProvider.io()) {
syncFeed(
loadType = loadType,
pagingState = state,
remoteKey = remoteKey,
)
}
Timber.w("feed_directive $feedDirective load exit 6")
MediatorResult.Success(endOfPaginationReached = false)
} catch (error: IOException) {
Timber.w(error, "feed_directive $feedDirective load exit 7")
MediatorResult.Error(error)
} catch (error: NostrNoticeException) {
Timber.w(error, "feed_directive $feedDirective load exit 8")
MediatorResult.Error(error)
} catch (error: NoSuchFeedPostException) {
Timber.w(error, "feed_directive $feedDirective load exit 2")
MediatorResult.Success(endOfPaginationReached = true)
} catch (error: RemoteKeyNotFoundException) {
Timber.w(error, "feed_directive $feedDirective load exit 3")
MediatorResult.Error(error)
} catch (error: UnnecessaryRefreshSync) {
Timber.w(error, "feed_directive $feedDirective load exit 1")
MediatorResult.Success(endOfPaginationReached = false)
} catch (error: WssException) {
Timber.w(error, "feed_directive $feedDirective load exit 5")
MediatorResult.Error(error)
} catch (error: RepeatingRequestBodyException) {
Timber.w(error, "feed_directive $feedDirective load exit 4")
MediatorResult.Success(endOfPaginationReached = true)
}
}
private suspend fun FeedRemoteMediator.syncFeed(
loadType: LoadType,
pagingState: PagingState<Int, FeedPost>,
remoteKey: FeedPostRemoteKey?,
) {
val pageSize = pagingState.config.pageSize
val (request, response) = when (loadType) {
LoadType.REFRESH -> syncRefresh(pageSize = pageSize)
LoadType.PREPEND -> syncPrepend(remoteKey = remoteKey)
LoadType.APPEND -> syncAppend(remoteKey = remoteKey, pageSize = pageSize)
}
val pagingEvent = response.paging
val shouldDeleteLocalData = loadType == LoadType.REFRESH &&
pagingState.hasFeedPosts() && shouldResetLocalCache()
database.withTransaction {
if (shouldDeleteLocalData) {
database.feedPostsRemoteKeys().deleteByDirective(feedDirective)
database.feedsConnections().deleteConnectionsByDirective(feedDirective)
database.posts().deleteOrphanPosts()
}
response.persistToDatabaseAsTransaction(userId = userId, database = database)
val feedEvents = response.posts + response.reposts
feedEvents.processRemoteKeys(pagingEvent)
feedEvents.processFeedConnections()
}
if (loadType == LoadType.PREPEND) {
response.processSyncCount()
}
lastRequests[loadType] = request to Instant.now().epochSecond
}
private suspend fun syncRefresh(pageSize: Int): Pair<FeedRequestBody, FeedResponse> {
val requestBody = FeedRequestBody(
directive = feedDirective,
userPubKey = userId,
limit = pageSize,
)
val response = retry(times = 1, delay = RETRY_DELAY) {
val response = withContext(dispatcherProvider.io()) { feedApi.getFeed(body = requestBody) }
response.paging ?: throw WssException("PagingEvent not found.")
response
}
return requestBody to response
}
private suspend fun syncPrepend(remoteKey: FeedPostRemoteKey?): Pair<FeedRequestBody, FeedResponse> {
val requestBody = FeedRequestBody(
directive = feedDirective,
userPubKey = userId,
limit = 500,
since = remoteKey?.untilId,
until = Instant.now().epochSecond,
order = "asc",
)
lastRequests[LoadType.PREPEND]?.let { (lastRequest, lastRequestAt) ->
if (lastRequest == requestBody && lastRequestAt.isRequestCacheExpired()) {
throw RepeatingRequestBodyException()
}
}
val feedResponse = retry(times = 1, delay = RETRY_DELAY) {
val response = withContext(dispatcherProvider.io()) { feedApi.getFeed(body = requestBody) }
if (response.paging == null) throw WssException("PagingEvent not found.")
response
}
return requestBody to feedResponse
}
private suspend fun syncAppend(remoteKey: FeedPostRemoteKey?, pageSize: Int): Pair<FeedRequestBody, FeedResponse> {
val requestBody = FeedRequestBody(
directive = feedDirective,
userPubKey = userId,
limit = pageSize,
until = remoteKey?.sinceId,
)
lastRequests[LoadType.APPEND]?.let { (lastRequest, lastRequestAt) ->
if (lastRequest == requestBody && lastRequestAt.isRequestCacheExpired()) {
throw RepeatingRequestBodyException()
}
}
val feedResponse = retry(times = 1, delay = RETRY_DELAY) {
val response = withContext(dispatcherProvider.io()) { feedApi.getFeed(body = requestBody) }
if (response.paging == null) throw WssException("PagingEvent not found.")
response
}
return requestBody to feedResponse
}
private suspend fun FeedResponse.processSyncCount() {
val prependSyncCount = this.posts.size + this.reposts.size
val repostedNoteIds = this.reposts
.sortedByDescending { it.createdAt }
.mapNotNull { it.tags.findFirstEventId() }
val noteIds = this.posts
.sortedByDescending { it.createdAt }
.map { it.id }
// Prepend syncs always include and the last known item
if (prependSyncCount > 1) {
withContext(dispatcherProvider.io()) {
database.withTransaction {
val actualCount = prependSyncCount - 1
val postIds = repostedNoteIds + noteIds
database.feedPostsSync().upsert(
data = FeedPostSync(
timestamp = Instant.now().epochSecond,
feedDirective = feedDirective,
count = actualCount,
postIds = postIds,
),
)
}
}
}
}
private suspend fun List<NostrEvent>.processRemoteKeys(pagingEvent: ContentPrimalPaging?) {
Timber.i("feed_directive $feedDirective writing remote keys using $pagingEvent")
if (pagingEvent?.sinceId != null && pagingEvent.untilId != null) {
database.withTransaction {
val remoteKeys = this.map {
FeedPostRemoteKey(
eventId = it.id,
directive = feedDirective,
sinceId = pagingEvent.sinceId,
untilId = pagingEvent.untilId,
cachedAt = Instant.now().epochSecond,
)
}
database.feedPostsRemoteKeys().upsert(remoteKeys)
}
}
}
private fun List<NostrEvent>.processFeedConnections() {
database.feedsConnections().connect(
data = this.map {
FeedPostDataCrossRef(
feedDirective = feedDirective,
eventId = it.id,
)
},
)
}
private fun Long.isRequestCacheExpired() = (Instant.now().epochSecond - this) < LAST_REQUEST_EXPIRY
private suspend fun <T> retry(
times: Int,
delay: Long,
block: suspend () -> T,
): T {
repeat(times) {
try {
Timber.i("Executing retry $it.")
return block()
} catch (error: WssException) {
Timber.w(error, "Attempting FeedRemoteMediator.retry() in $delay millis.")
delay(delay)
}
}
return block()
}
private suspend fun findFirstFeedPostRemoteKey(state: PagingState<Int, FeedPost>): FeedPostRemoteKey? {
val firstItem = state.firstItemOrNull()
?: newestFeedPostInDatabaseOrNull()
?: throw NoSuchFeedPostException()
return withContext(dispatcherProvider.io()) {
Timber.i(
"feed_directive $feedDirective looking for firstItem postId=${firstItem.data.postId}" +
" and repostId=${firstItem.data.repostId}",
)
database.feedPostsRemoteKeys().find(
postId = firstItem.data.postId,
repostId = firstItem.data.repostId,
directive = feedDirective,
)
}
}
private suspend fun findLastFeedPostRemoteKey(state: PagingState<Int, FeedPost>): FeedPostRemoteKey? {
val lastItem = state.lastItemOrNull()
?: oldestFeedPostInDatabaseOrNull()
?: throw NoSuchFeedPostException()
return withContext(dispatcherProvider.io()) {
Timber.i(
"feed_directive $feedDirective looking for lastItem postId=${lastItem.data.postId}" +
" and repostId=${lastItem.data.repostId}",
)
database.feedPostsRemoteKeys().find(
postId = lastItem.data.postId,
repostId = lastItem.data.repostId,
directive = feedDirective,
)
}
}
private suspend fun oldestFeedPostInDatabaseOrNull() =
withContext(dispatcherProvider.io()) {
database.feedPosts()
.oldestFeedPosts(query = feedQueryBuilder.oldestFeedPostsQuery(limit = 1))
.firstOrNull()
}
private suspend fun newestFeedPostInDatabaseOrNull() =
withContext(dispatcherProvider.io()) {
database.feedPosts()
.newestFeedPosts(query = feedQueryBuilder.newestFeedPostsQuery(limit = 1))
.firstOrNull()
}
private fun PagingState<Int, FeedPost>.hasFeedPosts() = firstItemOrNull() != null || lastItemOrNull() != null
private inner class NoSuchFeedPostException : RuntimeException()
private inner class RepeatingRequestBodyException : RuntimeException()
private inner class RemoteKeyNotFoundException : RuntimeException()
private inner class UnnecessaryRefreshSync : RuntimeException()
companion object {
private val LAST_REQUEST_EXPIRY = 10.seconds.inWholeSeconds
private val RETRY_DELAY = 500.milliseconds.inWholeMilliseconds
}
}
| 71 | Kotlin | 12 | 98 | 438072af7f67762c71c5dceffa0c83dedd8e2e85 | 15,406 | primal-android-app | MIT License |
bidon/src/main/java/org/bidon/sdk/adapter/AdAuctionParams.kt | bidon-io | 504,568,127 | false | null | package org.bidon.sdk.adapter
/**
* Created by <NAME> on 06/02/2023.
*/
interface AdAuctionParams {
val adUnitId: String?
} | 1 | Kotlin | 0 | 0 | a624344c96c08ee05c026daed8ca7634f56daf0f | 130 | bidon-sdk-android | Apache License 2.0 |
nebulosa-time/src/main/kotlin/nebulosa/time/Timescale.kt | tiagohm | 568,578,345 | false | {"Kotlin": 2562989, "TypeScript": 464111, "HTML": 237584, "JavaScript": 49239, "SCSS": 13679, "Python": 2817, "Makefile": 160} | package nebulosa.time
sealed interface Timescale {
val ut1: UT1
val utc: UTC
val tai: TAI
val tt: TT
val tcg: TCG
val tdb: TDB
val tcb: TCB
}
| 4 | Kotlin | 2 | 4 | b122c890df5ad63f828c468cb600310ddbcec99b | 178 | nebulosa | MIT License |
app/src/main/java/com/fsyy/listener/ui/homepage/AppBarStateChangeListener.kt | happyfsyy | 292,861,842 | false | null | /*
* 项目名:Listener
* 作者:@happy_fsyy
* 联系我:https://github.com/happyfsyy
* Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package com.fsyy.listener.ui.homepage
import com.fsyy.listener.utils.LogUtils
import com.google.android.material.appbar.AppBarLayout
import kotlin.math.abs
abstract class AppBarStateChangeListener :AppBarLayout.OnOffsetChangedListener{
private var mCurrentState= STATE_EXPANDED
companion object{
const val STATE_EXPANDED=1 //扩展
const val STATE_INTERMEDIATE=2 //中间
const val STATE_COLLAPSED=3 //折叠
}
override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
LogUtils.e("垂直方向的偏移量是$verticalOffset")
LogUtils.e("appBarLayout的totalScrollRange是${appBarLayout.totalScrollRange}")
var percent= abs(verticalOffset)/appBarLayout.totalScrollRange.toFloat()
if(verticalOffset==0){
if(mCurrentState!= STATE_EXPANDED){
onStateChanged(appBarLayout,STATE_EXPANDED)
mCurrentState= STATE_EXPANDED
}
}else if(abs(verticalOffset)>=appBarLayout.totalScrollRange){
if(mCurrentState!= STATE_COLLAPSED){
onStateChanged(appBarLayout, STATE_COLLAPSED)
mCurrentState= STATE_COLLAPSED
}
}else{
onPercentChanged(percent)
if(mCurrentState!= STATE_INTERMEDIATE){
onStateChanged(appBarLayout, STATE_INTERMEDIATE)
mCurrentState= STATE_INTERMEDIATE
}
}
}
abstract fun onStateChanged(appBarLayout: AppBarLayout,state:Int)
abstract fun onPercentChanged(percent:Float)
} | 0 | Kotlin | 0 | 0 | a954386b0202d17f2942bfb894f9ad37eba87d7f | 2,013 | Listener | MIT License |
sample/src/main/java/jp/co/c_lis/mangaview/android/WithViewPager2Activity.kt | keiji | 289,465,108 | false | null | package jp.co.c_lis.mangaview.android
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import dev.keiji.mangaview.Config
import dev.keiji.mangaview.DoubleTapZoomHelper
import dev.keiji.mangaview.EdgeNavigationHelper
import dev.keiji.mangaview.Mode
import dev.keiji.mangaview.layer.BitmapLayer
import dev.keiji.mangaview.widget.HorizontalRtlLayoutManager
import dev.keiji.mangaview.widget.MangaView
import dev.keiji.mangaview.widget.Page
import dev.keiji.mangaview.widget.PageAdapter
import dev.keiji.mangaview.widget.SinglePageLayoutManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
private val FILE_NAMES = arrayOf(
"comic_001bj_2.jpg",
"comic_001bj_3.jpg",
"comic_001bj_4.jpg",
"comic_001bj_5.jpg",
"comic_001bj_6.jpg",
"comic_001bj_7.jpg",
"comic_001bj_8.jpg",
"comic_001bj_9.jpg",
"comic_001bj_10.jpg",
"comic_001bj_11.jpg",
"comic_001bj_12.jpg",
"comic_001bj_1.jpg",
)
private const val GITHUB_MARK_FILE_NAME = "GitHub-Mark-120px-plus.png"
private const val GITHUB_REPOSITORY_URL = "https://github.com/keiji/mangaview"
class WithViewPager2Activity : AppCompatActivity() {
companion object {
private val TAG = WithViewPager2Activity::class.java.simpleName
private const val PAGE_WIDTH = 859
private const val PAGE_HEIGHT = 1214
private const val DOUBLE_TAP_SCALE = 3.0F
}
private val coroutineScope = CoroutineScope(Dispatchers.Main)
private var viewPager: ViewPager2? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
@Suppress("DEPRECATION")
this.window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
setContentView(R.layout.activity_with_viewpager2)
viewPager = findViewById<ViewPager2>(R.id.viewpager).also { viewpager ->
viewpager.adapter = MyAdapter(layoutInflater, assets, coroutineScope)
ViewCompat.setLayoutDirection(viewpager, ViewCompat.LAYOUT_DIRECTION_RTL)
}
}
override fun onDestroy() {
super.onDestroy()
coroutineScope.cancel()
}
class MangaViewHolder(
itemView: View,
private val assetManager: AssetManager,
private val coroutineScope: CoroutineScope
) : RecyclerView.ViewHolder(itemView) {
private val mangaView = itemView.findViewById<MangaView>(R.id.manga_view)
private val doubleTapZoomHelper = DoubleTapZoomHelper(maxScale = DOUBLE_TAP_SCALE)
private val edgeNavigationHelper = EdgeNavigationHelper()
fun bind() {
mangaView.config = Config(
mode = Mode.Normal,
resetScaleOnPageChanged = true,
)
mangaView.layoutManager = HorizontalRtlLayoutManager()
mangaView.pageLayoutManager = SinglePageLayoutManager()
mangaView.adapter =
SimpleAdapter(assetManager, FILE_NAMES, coroutineScope, PAGE_WIDTH, PAGE_HEIGHT)
doubleTapZoomHelper.attachToMangaView(mangaView)
edgeNavigationHelper.attachToMangaView(mangaView)
}
fun unbind() {
doubleTapZoomHelper.detachToMangaView(mangaView)
edgeNavigationHelper.detachToMangaView(mangaView)
}
}
class ProjectPageHolder(
itemView: View,
private val assetManager: AssetManager,
private val coroutineScope: CoroutineScope
) : RecyclerView.ViewHolder(itemView) {
private val imageView = itemView.findViewById<ImageView>(R.id.image_view)
private val textView = itemView.findViewById<TextView>(R.id.project_url)
init {
ViewCompat.setLayoutDirection(itemView, ViewCompat.LAYOUT_DIRECTION_LOCALE)
}
fun bind() {
textView.text = GITHUB_REPOSITORY_URL
coroutineScope.launch(Dispatchers.IO) {
assetManager.open(GITHUB_MARK_FILE_NAME).use {
val bitmap = BitmapFactory.decodeStream(it)
showBitmap(bitmap)
}
}
}
private suspend fun showBitmap(bitmap: Bitmap) = withContext(Dispatchers.Main) {
imageView.setImageBitmap(bitmap)
}
}
class UnknownHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class MyAdapter(
private val inflater: LayoutInflater,
private val assetManager: AssetManager,
private val coroutineScope: CoroutineScope
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val VIEW_TYPE_MANGA_VIEW = 0
private const val VIEW_TYPE_LAST_PAGE = 1
private const val VIEW_TYPE_UNKNOWN = -1
}
override fun getItemViewType(position: Int): Int {
return when (position) {
0 -> VIEW_TYPE_MANGA_VIEW
1 -> VIEW_TYPE_LAST_PAGE
else -> VIEW_TYPE_UNKNOWN
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW_TYPE_MANGA_VIEW -> MangaViewHolder(
inflater.inflate(
R.layout.view_item_manga_view,
parent,
false
),
assetManager,
coroutineScope
)
VIEW_TYPE_LAST_PAGE -> ProjectPageHolder(
inflater.inflate(
R.layout.view_item_last_page,
parent,
false
),
assetManager,
coroutineScope
)
else -> UnknownHolder(inflater.inflate(R.layout.view_item_unknown, parent, false))
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is MangaViewHolder -> {
holder.bind()
}
is ProjectPageHolder -> {
holder.bind()
}
}
}
override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
super.onViewRecycled(holder)
when (holder) {
is MangaViewHolder -> {
holder.unbind()
}
}
}
override fun getItemCount(): Int = 2
}
class SimpleAdapter(
private val assetManager: AssetManager,
private val fileNames: Array<String>,
private val coroutineScope: CoroutineScope,
private val pageWidth: Int,
private val pageHeight: Int
) : PageAdapter() {
override val pageCount = fileNames.size
override fun getPageWidth(index: Int) = pageWidth
override fun getPageHeight(index: Int) = pageHeight
override fun onConstructPage(index: Int, page: Page) {
if (index < 0) {
return
}
if (index >= fileNames.size) {
return
}
val fileName = fileNames[index]
page.addLayer(BitmapLayer(AssetBitmapSource(assetManager, fileName, coroutineScope)))
}
}
}
| 2 | Kotlin | 1 | 35 | 0c59dac934e585c75b48de1df4aaf976e5c84cc3 | 8,001 | mangaview | Apache License 2.0 |
app/src/main/java/com/yudhisthereal/nurturenest/ui/screens/unauthenticated/register/RegisterViewModel.kt | yudhisthereal | 742,462,133 | false | {"Kotlin": 16022} | package com.yudhisthereal.nurturenest.ui.screens.unauthenticated.register
| 0 | Kotlin | 0 | 0 | f9414b6caba36b5581a3c50af5fd1ea31b41ae97 | 75 | NurtureNest-FrontEnd | Apache License 2.0 |
tooling/src/main/kotlin/org/mint/tooling/android/CleanDeviceStateTask.kt | ing-bank | 620,378,707 | false | null | package org.mint.tooling.android
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import org.mint.tooling.android.CleanDeviceStateTask.CleanDeviceStateTask.cmd
open class CleanDeviceStateTask : DefaultTask() {
@get:Input
lateinit var packageName: String
@TaskAction
fun clean() {
ADBCommand.exec("$cmd $packageName", logger)
}
object CleanDeviceStateTask {
const val cmd = "adb shell pm clear"
}
}
| 0 | Kotlin | 2 | 4 | abf96d311b3ebb1bba2a331a353126c653225be9 | 505 | mint | MIT License |
src/test/kotlin/no/nav/helse/sporenstreks/web/dto/ValidationTestUtils.kt | navikt | 249,433,776 | false | null | package no.nav.helse.sporenstreks.web.dto
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.assertThrows
import org.valiktor.ConstraintViolationException
import kotlin.reflect.KProperty1
fun <B, A> validationShouldFailFor(field: KProperty1<B, A>, block: () -> Unit): Exception {
val thrown = assertThrows<ConstraintViolationException>(block)
Assertions.assertThat(thrown.constraintViolations).hasSize(1)
Assertions.assertThat(thrown.constraintViolations.first().property).isEqualTo(field.name)
return thrown
}
fun validationShouldFailFor(propertyPath: String, block: () -> Unit): Exception {
val thrown = assertThrows<ConstraintViolationException>(block)
Assertions.assertThat(thrown.constraintViolations).hasSize(1)
Assertions.assertThat(thrown.constraintViolations.first().property).isEqualTo(propertyPath)
return thrown
}
fun <B, A> validationShouldFailNTimesFor(field: KProperty1<B, A>, numViolations: Int, block: () -> Unit): Exception {
val thrown = assertThrows<ConstraintViolationException>(block)
Assertions.assertThat(thrown.constraintViolations).hasSize(numViolations)
Assertions.assertThat(thrown.constraintViolations.first().property).isEqualTo(field.name)
return thrown
}
| 4 | Kotlin | 0 | 2 | d6ff76bfa9e17c426087a220209687bc37683346 | 1,256 | sporenstreks | MIT License |
src/main/kotlin/com/teamfusion/spyglassplus/SpyglassPlus.kt | andantet | 713,761,600 | false | {"Kotlin": 43820, "Java": 5532} | package com.teamfusion.spyglassplus
import com.teamfusion.spyglassplus.enchantment.SpyglassPlusEnchantments
import com.teamfusion.spyglassplus.event.IndicateHandler
import com.teamfusion.spyglassplus.event.ItemUsageCallback
import com.teamfusion.spyglassplus.handler.ScrutinyScrollHandler
import com.teamfusion.spyglassplus.item.SpyglassPlusItemGroups
import com.teamfusion.spyglassplus.item.SpyglassPlusItems
import com.teamfusion.spyglassplus.networking.SpyglassPlusPacketTypes
import com.teamfusion.spyglassplus.tag.SpyglassPlusEntityTypeTags
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking
import org.slf4j.LoggerFactory
object SpyglassPlus : ModInitializer {
const val MOD_ID = "spyglassplus"
const val MOD_NAME = "Spyglass+"
private val logger = LoggerFactory.getLogger(MOD_NAME)
override fun onInitialize() {
logger.info("Initializing $MOD_NAME")
SpyglassPlusItems
SpyglassPlusItemGroups
SpyglassPlusEnchantments
SpyglassPlusEntityTypeTags
registerEvents()
}
private fun registerEvents() {
ServerPlayNetworking.registerGlobalReceiver(SpyglassPlusPacketTypes.C2S_SCRUTINY_UPDATE, ScrutinyScrollHandler())
val indicateHandler = IndicateHandler()
ItemUsageCallback.EVENT.register(indicateHandler)
ServerTickEvents.END_SERVER_TICK.register(indicateHandler)
}
}
| 0 | Kotlin | 0 | 0 | 9a49e49c18bcfaca2191de5044abd6d3acb71fda | 1,504 | spyglassplus | MIT License |
systembar/src/main/java/cn/quibbler/systembar/NavigationBarObserver.kt | quibbler01 | 565,090,154 | false | {"Kotlin": 180633} | package cn.quibbler.systembar
import android.app.Application
import android.database.ContentObserver
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
/**
* Display and hide of navigation bar.
* Currently, Huawei, Xiaomi, VOVO and Android 10 mobile phones with navigation bar are supported
*/
object NavigationBarObserver : ContentObserver(Handler(Looper.getMainLooper())) {
private val mListeners = ArrayList<OnNavigationBarListener>()
private var mApplication: Application? = null
private var mIsRegister = false
fun register(application: Application?) {
mApplication = application
mApplication?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && it.contentResolver != null && !mIsRegister) {
var uri: Uri? = null
var uri1: Uri? = null
var uri2: Uri? = null
if (isHuaWei || isEMUI()) {
if (isEMUI3_x() || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
uri = Settings.System.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_EMUI)
} else {
uri = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_EMUI)
}
} else if (isXiaoMi || isMIUI()) {
uri = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_MIUI);
uri1 = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_MIUI_HIDE)
} else if (isVivo || isFuntouchOrOriginOs()) {
uri = Settings.Secure.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_VIVO)
} else if (isOppo || isColorOs()) {
uri = Settings.Secure.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_OPPO)
} else if (isSamsung) {
val i = Settings.Global.getInt(it.contentResolver, IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG_OLD, -1)
if (i == -1) {
uri = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG);
uri1 = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG_GESTURE_TYPE);
uri2 = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG_GESTURE)
} else {
uri = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG_OLD)
}
} else {
uri = Settings.Secure.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_DEFAULT)
}
if (uri != null) {
it.contentResolver.registerContentObserver(uri, true, this)
mIsRegister = true
}
if (uri1 != null) {
it.contentResolver.registerContentObserver(uri1, true, this)
}
if (uri2 != null) {
it.contentResolver.registerContentObserver(uri2, true, this)
}
}
}
}
override fun onChange(selfChange: Boolean) {
super.onChange(selfChange)
mListeners.let {
if (mListeners.isNotEmpty()) {
val bean: GestureBean = getGestureBean(mApplication)
var show: Boolean = false
if (bean.isGesture) {
if (bean.checkNavigation && mApplication != null) {
val navigationBarHeight = BarConfig.getNavigationBarHeightInternal(mApplication!!)
show = navigationBarHeight > 0
} else {
show = false
}
} else {
show = true
}
for (onNavigationBarListener in mListeners) {
onNavigationBarListener.onNavigationBarChange(show, bean.type)
}
}
}
}
fun addOnNavigationBarListener(listener: OnNavigationBarListener?) {
listener?.let {
if (!mListeners.contains(it)) {
mListeners.add(it)
}
}
}
fun removeOnNavigationBarListener(listener: OnNavigationBarListener?) {
listener?.let {
mListeners.remove(it)
}
}
} | 0 | Kotlin | 0 | 0 | 8c1d31a2d77ada61cb35a8d05fff8f753f48d2a2 | 4,374 | SystemBar | Apache License 2.0 |
systembar/src/main/java/cn/quibbler/systembar/NavigationBarObserver.kt | quibbler01 | 565,090,154 | false | {"Kotlin": 180633} | package cn.quibbler.systembar
import android.app.Application
import android.database.ContentObserver
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
/**
* Display and hide of navigation bar.
* Currently, Huawei, Xiaomi, VOVO and Android 10 mobile phones with navigation bar are supported
*/
object NavigationBarObserver : ContentObserver(Handler(Looper.getMainLooper())) {
private val mListeners = ArrayList<OnNavigationBarListener>()
private var mApplication: Application? = null
private var mIsRegister = false
fun register(application: Application?) {
mApplication = application
mApplication?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && it.contentResolver != null && !mIsRegister) {
var uri: Uri? = null
var uri1: Uri? = null
var uri2: Uri? = null
if (isHuaWei || isEMUI()) {
if (isEMUI3_x() || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
uri = Settings.System.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_EMUI)
} else {
uri = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_EMUI)
}
} else if (isXiaoMi || isMIUI()) {
uri = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_MIUI);
uri1 = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_MIUI_HIDE)
} else if (isVivo || isFuntouchOrOriginOs()) {
uri = Settings.Secure.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_VIVO)
} else if (isOppo || isColorOs()) {
uri = Settings.Secure.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_OPPO)
} else if (isSamsung) {
val i = Settings.Global.getInt(it.contentResolver, IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG_OLD, -1)
if (i == -1) {
uri = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG);
uri1 = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG_GESTURE_TYPE);
uri2 = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG_GESTURE)
} else {
uri = Settings.Global.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_SAMSUNG_OLD)
}
} else {
uri = Settings.Secure.getUriFor(IMMERSION_NAVIGATION_BAR_MODE_DEFAULT)
}
if (uri != null) {
it.contentResolver.registerContentObserver(uri, true, this)
mIsRegister = true
}
if (uri1 != null) {
it.contentResolver.registerContentObserver(uri1, true, this)
}
if (uri2 != null) {
it.contentResolver.registerContentObserver(uri2, true, this)
}
}
}
}
override fun onChange(selfChange: Boolean) {
super.onChange(selfChange)
mListeners.let {
if (mListeners.isNotEmpty()) {
val bean: GestureBean = getGestureBean(mApplication)
var show: Boolean = false
if (bean.isGesture) {
if (bean.checkNavigation && mApplication != null) {
val navigationBarHeight = BarConfig.getNavigationBarHeightInternal(mApplication!!)
show = navigationBarHeight > 0
} else {
show = false
}
} else {
show = true
}
for (onNavigationBarListener in mListeners) {
onNavigationBarListener.onNavigationBarChange(show, bean.type)
}
}
}
}
fun addOnNavigationBarListener(listener: OnNavigationBarListener?) {
listener?.let {
if (!mListeners.contains(it)) {
mListeners.add(it)
}
}
}
fun removeOnNavigationBarListener(listener: OnNavigationBarListener?) {
listener?.let {
mListeners.remove(it)
}
}
} | 0 | Kotlin | 0 | 0 | 8c1d31a2d77ada61cb35a8d05fff8f753f48d2a2 | 4,374 | SystemBar | Apache License 2.0 |
app/src/main/java/com/pyamsoft/tetherfi/main/MainEntry.kt | pyamsoft | 475,225,784 | false | null | package com.pyamsoft.tetherfi.main
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.PagerState
import com.google.accompanist.pager.rememberPagerState
import com.pyamsoft.pydroid.arch.SaveStateDisposableEffect
import com.pyamsoft.pydroid.ui.inject.ComposableInjector
import com.pyamsoft.pydroid.ui.inject.rememberComposableInjector
import com.pyamsoft.pydroid.ui.util.LifecycleEffect
import com.pyamsoft.pydroid.ui.util.rememberNotNull
import com.pyamsoft.tetherfi.ObjectGraph
import com.pyamsoft.tetherfi.qr.QRCodeEntry
import com.pyamsoft.tetherfi.server.widi.WiDiNetworkStatus
import com.pyamsoft.tetherfi.settings.SettingsDialog
import javax.inject.Inject
import kotlinx.coroutines.flow.collectLatest
import timber.log.Timber
internal class MainInjector @Inject internal constructor() : ComposableInjector() {
@JvmField @Inject internal var viewModel: MainViewModeler? = null
override fun onInject(activity: FragmentActivity) {
ObjectGraph.ActivityScope.retrieve(activity).inject(this)
}
override fun onDispose() {
viewModel = null
}
}
@Composable
@OptIn(ExperimentalPagerApi::class)
private fun WatchTabSwipe(
pagerState: PagerState,
allTabs: SnapshotStateList<MainView>,
) {
// Watch for a swipe causing a page change and update accordingly
LaunchedEffect(
pagerState,
allTabs,
) {
snapshotFlow { pagerState.currentPage }
.collectLatest { index ->
val page = allTabs[index]
Timber.d("Page swiped: $page")
}
}
}
@Composable
@OptIn(ExperimentalPagerApi::class)
private fun MountHooks(
viewModel: MainViewModeler,
pagerState: PagerState,
allTabs: SnapshotStateList<MainView>,
) {
WatchTabSwipe(
pagerState = pagerState,
allTabs = allTabs,
)
LaunchedEffect(viewModel) { viewModel.bind(scope = this) }
LifecycleEffect {
object : DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) {
viewModel.handleRefreshConnectionInfo()
}
}
}
}
@Composable
@OptIn(ExperimentalPagerApi::class)
fun MainEntry(
modifier: Modifier = Modifier,
appName: String,
) {
val component = rememberComposableInjector { MainInjector() }
val viewModel = rememberNotNull(component.viewModel)
val pagerState = rememberPagerState()
val allTabs = rememberAllTabs()
val state = viewModel.state
MountHooks(
viewModel = viewModel,
pagerState = pagerState,
allTabs = allTabs,
)
SaveStateDisposableEffect(viewModel)
MainScreen(
modifier = modifier,
appName = appName,
state = state,
pagerState = pagerState,
allTabs = allTabs,
onSettingsOpen = { viewModel.handleOpenSettings() },
onShowQRCode = { viewModel.handleOpenQRCodeDialog() },
onRefreshGroup = { viewModel.handleRefreshConnectionInfo() },
onRefreshConnection = { viewModel.handleRefreshConnectionInfo() },
)
val isSettingsOpen by state.isSettingsOpen.collectAsState()
if (isSettingsOpen) {
SettingsDialog(
onDismiss = { viewModel.handleCloseSettings() },
)
}
val isShowingQRCodeDialog by state.isShowingQRCodeDialog.collectAsState()
if (isShowingQRCodeDialog) {
val group by state.group.collectAsState()
(group as? WiDiNetworkStatus.GroupInfo.Connected)?.also { grp ->
QRCodeEntry(
ssid = grp.ssid,
password = <PASSWORD>,
onDismiss = { viewModel.handleCloseQRCodeDialog() },
)
}
}
}
| 4 | Kotlin | 2 | 44 | 88c8cf695258ce5421157c238bf2364abad73837 | 3,782 | tetherfi | Apache License 2.0 |
GURU_Hemjee/app/src/main/java/com/harahamzzi/android/FinalOKDialog.kt | Harahamzzi | 447,871,826 | false | {"Kotlin": 563880} | package com.harahamzzi.android
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
// 최종 확인 Dialog를 띄우기 위한 클래스
class FinalOKDialog(context: Context, title: String, okString: String, isNeedDrawable: Boolean, val picSource: Int?) {
private val dialog = Dialog(context)
//팝업 제목, 확인 버튼 글자, 씨앗 표시 유무
private var title: String = title
private var okString: String = okString
private var isNeedDrawable: Boolean = isNeedDrawable
//팝업의 위젯
private lateinit var pop_finalOkTitleTextView: TextView //팝업 제목
private lateinit var pop_plainOkButton: Button //확인 버튼(택스트)
private lateinit var pop_seedImageView: ImageView // 타이틀의 씨앗 이미지
private lateinit var pop_okPopMainImageView: ImageView //햄찌 확인 이미지
//팝업 표시
fun alertDialog(){
dialog.show()
dialog.setCancelable(false) // 화면 밖 터치시 팝업창이 닫히지 않게 함
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) // 배경 색 투명화
dialog.setContentView(R.layout.popup_final_ok)
//위젯 연결
pop_finalOkTitleTextView = dialog.findViewById(R.id.pop_finalOkTitleTextView)
pop_plainOkButton = dialog.findViewById(R.id.pop_plainOkButton)
pop_seedImageView = dialog.findViewById(R.id.seedImage)
pop_okPopMainImageView = dialog.findViewById(R.id.pop_okPopMainImageView)
//주어진 사진 표시
if(picSource != null){
pop_okPopMainImageView.setImageResource(picSource)
}
//확인 버튼
pop_plainOkButton.text = okString
pop_plainOkButton.setOnClickListener{
onClickListener.onClicked(true)
dialog.dismiss()
}
// 타이틀
pop_finalOkTitleTextView.text = title
if(isNeedDrawable){
pop_seedImageView.visibility = View.VISIBLE
} else {
pop_seedImageView.visibility = View.GONE
}
}
//인자를 넘겨주기 위한 클릭 인터페이스(팝업을 띄우는 화면에서 처리)
interface ButtonClickListener {
fun onClicked(isConfirm: Boolean)
}
private lateinit var onClickListener: ButtonClickListener
fun setOnClickedListener(listener: ButtonClickListener) {
onClickListener = listener
}
} | 0 | Kotlin | 0 | 2 | 876d1e4813e6369af1f1f433e631e94c1ab2908e | 2,366 | Android_GURU | Apache License 2.0 |
hotelSelection-backend/src/main/kotlin/de/xxx/hotelselection/usecase/mapper/HotelMapper.kt | Angular2Guy | 864,806,605 | false | {"Kotlin": 21768, "TypeScript": 21608, "HTML": 3329, "SCSS": 2505, "Java": 1929, "JavaScript": 744, "Shell": 396} | /**
* Copyright 2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.xxx.hotelselection.usecase.mapper
import de.xxx.hotelselection.domain.model.dto.HotelDto
import de.xxx.hotelselection.domain.model.entity.Hotel
import org.springframework.stereotype.Component
import java.util.*
@Component
class HotelMapper(val bookingMapper: BookingMapper) {
fun toHotelDto(hotel: Hotel): HotelDto {
return HotelDto(hotel.id.toString(), hotel.hotelName, hotel.city, this.bookingMapper.toDtos(hotel.bookings))
}
fun toHotelEntity(hotelDto: HotelDto): Hotel {
val myHotel = Hotel(
Optional.ofNullable(hotelDto.id).stream().map { UUID.fromString(it) }.findFirst().orElse(null),
hotelDto.hotelName,
hotelDto.city,
mutableSetOf()
)
val myBookings = this.bookingMapper.toEntities(hotelDto.bookings, myHotel)
myHotel.bookings.plus(myBookings)
return myHotel
}
} | 0 | Kotlin | 1 | 1 | 5d5dcd493eb298513f91eda0c7a4dd0ff2d4f0b1 | 1,451 | AngularMicroFrontendsAndMicroServices | Apache License 2.0 |
decompose-router/src/iosMain/kotlin/io/github/xxfast/decompose/router/RouterContext.kt | xxfast | 599,478,957 | false | {"Kotlin": 49642, "Swift": 981, "HTML": 338, "CSS": 171} | package io.github.xxfast.decompose.router
import com.arkivanov.essenty.backhandler.BackDispatcher
import com.arkivanov.essenty.lifecycle.LifecycleRegistry
fun defaultRouterContext(): RouterContext {
val backDispatcher = BackDispatcher()
val lifecycle = LifecycleRegistry()
return RouterContext(lifecycle = lifecycle, backHandler = backDispatcher)
}
| 9 | Kotlin | 5 | 153 | c844de1a4068940111fc961a99b38e85bd19303b | 358 | Decompose-Router | Apache License 2.0 |
app/src/main/java/com/mahdikh/scrolltotop/MainActivity.kt | mahdi-khosravi-sh | 401,202,353 | false | null | package com.mahdikh.scrolltotop
import androidx.appcompat.app.AppCompatActivity
import com.mahdikh.vision.scrolltotop.widget.ScrollToTop
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.recyclerview.widget.RecyclerView
import com.mahdikh.vision.scrolltotop.animator.*
class MainActivity : AppCompatActivity() {
private lateinit var scrollToTop: ScrollToTop
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.adapter = RecyclerViewAdapter()
scrollToTop = findViewById(R.id.scrollToTop)
scrollToTop.setupWithRecyclerView(recyclerView)
scrollToTop.isSmoothScroll = true
scrollToTop.animator = FadeAnimator()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (item.isCheckable) {
item.isChecked = !item.isChecked
}
when (id) {
R.id.item_fade -> {
scrollToTop.animator = FadeAnimator()
}
R.id.item_fly -> {
scrollToTop.animator = FlyAnimator()
}
R.id.item_scale -> {
scrollToTop.animator = ScaleAnimator()
}
R.id.item_slide -> {
scrollToTop.animator = SlideAnimator()
}
R.id.item_noAnimator -> {
scrollToTop.animator = null
}
R.id.item_smoothScroll -> {
scrollToTop.isSmoothScroll = item.isChecked
}
R.id.item_heavyCheckup -> {
scrollToTop.isHeavyCheckup = item.isChecked
}
R.id.item_shortScroll -> {
scrollToTop.isShortScroll = item.isChecked
}
}
return true
}
} | 0 | Kotlin | 0 | 2 | f146538c9096b5e18daef2041cbde5f05029169c | 2,101 | scrolltotop | Apache License 2.0 |
src/test/kotlin/ui/CoordinateTest.kt | chlesaec | 398,859,394 | false | {"Kotlin": 170546} | package ui
import commons.Coordinate
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
internal class CoordinateTest {
@Test
fun testPlus() {
val result = Coordinate(2.0, -3.0) + Coordinate(5.0, 1.0)
Assertions.assertEquals(Coordinate(7.0, -2.0), result)
}
@Test
fun testMinus() {
val result = Coordinate(2.0, -3.0) - Coordinate(5.0, 1.0)
Assertions.assertEquals(Coordinate(-3.0, -4.0), result)
}
@Test
fun testTimes() {
val result = Coordinate(2.0, -3.0) * 3.0
Assertions.assertEquals(Coordinate(6.0, -9.0), result)
}
@Test
fun testLength() {
val result = Coordinate(4.0, -3.0).length()
Assertions.assertEquals(5.0, result)
}
@Test
fun testOrtho() {
val first = Coordinate(4.0, -3.0)
val result = first.ortho()
Assertions.assertEquals(0.0, result * first, 0.00001)
val sec = Coordinate(0.0, -3.0)
val result2 = sec.ortho()
Assertions.assertEquals(0.0, result2 * sec, 0.00001)
}
@Test
fun testDistanceToSegment() {
val H1 = Coordinate(1.0, 1.0)
val H2 = Coordinate(6.0, 1.0)
val pointOnSegment = Coordinate(3.0, 1.0)
val dist = pointOnSegment.distanceToSegment(H1, H2)
Assertions.assertEquals(0.0, dist, 0.00001)
val dist2 = pointOnSegment.distanceToSegment(H2, H1)
Assertions.assertEquals(0.0, dist2, 0.00001)
val pointOut = Coordinate(3.0, 2.0)
val distOut = pointOut.distanceToSegment(H1, H2)
Assertions.assertEquals(1.0, distOut, 0.00001)
val distOut2 = pointOut.distanceToSegment(H2, H1)
Assertions.assertEquals(1.0, distOut2, 0.00001)
val B2 = Coordinate(5.0, 5.0)
val pointOnB2 = Coordinate(3.0, 3.0)
val dist3 = pointOnB2.distanceToSegment(H1, B2)
Assertions.assertEquals(0.0, dist3, 0.00001)
val dist3Bis = pointOnB2.distanceToSegment(B2, H1)
Assertions.assertEquals(0.0, dist3Bis, 0.00001)
val V2 = Coordinate(1.0, 6.0)
val pointOnSegmentV= Coordinate(1.0, 4.0)
val distV = pointOnSegmentV.distanceToSegment(H1, V2)
Assertions.assertEquals(0.0, distV, 0.00001)
val distV2 = pointOnSegmentV.distanceToSegment(V2, H1)
Assertions.assertEquals(0.0, distV2, 0.00001)
val pointOutV = Coordinate(0.0, 4.0)
val distOutV = pointOutV.distanceToSegment(H1, V2)
Assertions.assertEquals(1.0, distOutV, 0.00001)
val distOutV2 = pointOutV.distanceToSegment(V2, H1)
Assertions.assertEquals(1.0, distOutV2, 0.00001)
}
}
| 0 | Kotlin | 0 | 0 | cef98e41cddcabbe78b9af4d1e530da6d4445295 | 2,666 | Streams | Apache License 2.0 |
app/src/main/java/com/example/italianplacesmonth/ui/theme/Shapes.kt | PaoloCaldera | 745,440,597 | false | {"Kotlin": 28533} | package com.example.italianplacesmonth.ui.theme
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.material3.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
large = CutCornerShape(bottomStart = 16.dp, topEnd = 16.dp),
medium = CutCornerShape(bottomStart = 16.dp, topEnd = 16.dp),
small = CutCornerShape(bottomStart = 8.dp, topEnd = 8.dp)
) | 0 | Kotlin | 0 | 0 | de6f1e3fc56870c48fb58e7f61b4a799db357753 | 397 | italianPlacesMonth | MIT License |
src/day12/Day12.kt | HGilman | 572,891,570 | false | null | package day12
import lib.Point2D
import lib.directionsClockwise
import readInput
import java.util.LinkedList
import kotlin.math.min
fun main() {
val input = readInput("day12/input")
val h = input.size
val w = input[0].length
var start = Point2D(0, 0)
var end = Point2D(0, 0)
val heights = List(h) { y ->
List(w) { x ->
val char = input[y][x]
val point = Point2D(x, y)
if (char == 'S') {
start = point
}
if (char == 'E') {
end = point
}
height(char)
}
}
fun shortestDistance(start: Point2D, end: Point2D): Int {
val distances: List<MutableList<Int>> = List(h) {
MutableList(w) { Int.MAX_VALUE }
}
distances[start.y][start.x] = 0
val queue = LinkedList<Point2D>()
queue.offer(start)
var res = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val currentPoint = queue.poll()
if (currentPoint == end) {
res = distances[currentPoint.y][currentPoint.x]
break
}
for (d in directionsClockwise) {
val newPoint = currentPoint + d
if (newPoint.x in 0 until w && newPoint.y in 0 until h) {
if (heights[newPoint.y][newPoint.x] - heights[currentPoint.y][currentPoint.x] <= 1) {
val newDistance = distances[currentPoint.y][currentPoint.x] + 1
if (newDistance < distances[newPoint.y][newPoint.x]) {
distances[newPoint.y][newPoint.x] = newDistance
queue.offer(newPoint)
}
}
}
}
}
return res
}
println(shortestDistance(start, end))
var ans = Int.MAX_VALUE
for (y in 0 until h) {
for (x in 0 until w) {
if (input[y][x] == 'a') {
ans = min(ans, shortestDistance(Point2D(x, y), end))
}
}
}
println(ans)
}
fun height(c: Char): Int {
val char: Char = when (c) {
'S' -> {
'a'
}
'E' -> {
'z'
}
else -> {
c
}
}
return char - 'a'
} | 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 2,350 | advent-of-code-2022 | Apache License 2.0 |
plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34ReporterProvider.kt | JLLeitschuh | 84,131,083 | false | {"Kotlin": 283487, "Java": 615} | package org.jlleitschuh.gradle.ktlint.reporter
import com.pinterest.ktlint.core.ReporterProvider
import java.io.PrintStream
class Ktlint34ReporterProvider(val reporterProvider: ReporterProvider) : GenericReporterProvider<Ktlint34Reporter> {
override fun get(outputStream: PrintStream, opt: Map<String, String>): Ktlint34Reporter {
return Ktlint34Reporter(reporterProvider.get(outputStream, opt))
}
override val id: String
get() = reporterProvider.id
}
| 82 | Kotlin | 154 | 1,301 | 0f75ad1fd4409d78facd3286193c0dafd0676eac | 483 | ktlint-gradle | MIT License |
ktfx-listeners/src/test/kotlin/javafx/stage/WindowTest.kt | hendraanggrian | 102,934,147 | false | null | package ktfx.listeners
import javafx.stage.BaseWindowTest
import javafx.stage.Window
import javafx.stage.WindowEvent
class WindowTest : BaseWindowTest() {
override fun Window.callOnCloseRequest(action: (WindowEvent) -> Unit) = onCloseRequest(action)
override fun Window.callOnShowing(action: (WindowEvent) -> Unit) = onShowing(action)
override fun Window.callOnShown(action: (WindowEvent) -> Unit) = onShown(action)
override fun Window.callOnHiding(action: (WindowEvent) -> Unit) = onHiding(action)
override fun Window.callOnHidden(action: (WindowEvent) -> Unit) = onHidden(action)
} | 1 | Kotlin | 2 | 16 | d7b8aec230fef877ae067d14cb0bc21c53e3d361 | 606 | ktfx | Apache License 2.0 |
src/main/kotlin/com/github/gbrowser/GBrowserMainPanel.kt | edgafner | 294,787,892 | false | {"Kotlin": 118488} | package com.github.gbrowser
import com.github.gbrowser.actions.*
import com.github.gbrowser.gcef.GBCefBrowser
import com.github.gbrowser.gcef.GBRequestHandler
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.Constraints
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.ui.SimpleToolWindowPanel
import com.intellij.ui.jcef.JBCefBrowser
import com.intellij.ui.jcef.JBCefBrowserBase.ErrorPage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.cef.handler.CefLoadHandler
import javax.swing.Icon
class GBrowserMainPanel(private val initialUrl: String,
private val callback: (Icon) -> Unit,
private val contentCs: CoroutineScope) : SimpleToolWindowPanel(true, true), Disposable {
private val jbCefBrowser: JBCefBrowser = GBCefBrowser(initialUrl)
init {
val toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.CONTEXT_TOOLBAR, buildToolbar(), true).apply {
targetComponent = this@GBrowserMainPanel
}
jbCefBrowser.setErrorPage { errorCode, errorText, failedUrl ->
if (errorCode == CefLoadHandler.ErrorCode.ERR_ABORTED) null
else ErrorPage.DEFAULT.create(errorCode, errorText, failedUrl)
}
jbCefBrowser.setProperty(JBCefBrowser.Properties.FOCUS_ON_SHOW, true)
jbCefBrowser.setProperty(JBCefBrowser.Properties.FOCUS_ON_NAVIGATION, true)
jbCefBrowser.cefBrowser.client.removeRequestHandler()
jbCefBrowser.cefBrowser.client.addRequestHandler(GBRequestHandler())
setContent(jbCefBrowser.component)
setToolbar(toolbar.component)
}
private fun buildToolbar(): DefaultActionGroup {
val toolbar = DefaultActionGroup()
val backButton = GBackAction(jbCefBrowser, AllIcons.Actions.Back)
val forwardButton = GForwardAction(jbCefBrowser, AllIcons.Actions.Forward)
val refreshButton = GRefreshAction(jbCefBrowser, AllIcons.Actions.Refresh)
val homeButton = GHomeAction(jbCefBrowser, AllIcons.Nodes.HomeFolder)
val bookMarksMenuAction = GBookMarksMenuAction(jbCefBrowser)
val gBrowserOptionsActionGroup = GBrowserOptionsActionGroup(jbCefBrowser)
val bus = ApplicationManager.getApplication().messageBus
bus.connect().subscribe(SettingsChangedAction.TOPIC, object : SettingsChangedAction {
override fun settingsChanged() {
LOG.info("Setting changed was invoked")
contentCs.launch {
try {
bookMarksMenuAction.updateView()
}
catch (e: Exception) {
AllIcons.General.Web
}
}
}
})
val urlTextField = GSearchFieldAction(initialUrl, "Web address", AllIcons.Actions.Refresh, jbCefBrowser, callback, contentCs)
jbCefBrowser.cefBrowser.client.addDisplayHandler(CefUrlChangeHandler { url -> urlTextField.setText(url ?: "") })
toolbar.add(backButton)
toolbar.add(forwardButton)
toolbar.add(refreshButton)
toolbar.add(homeButton)
toolbar.add(bookMarksMenuAction)
toolbar.addSeparator()
toolbar.add(urlTextField)
toolbar.addSeparator()
toolbar.add(gBrowserOptionsActionGroup, Constraints.LAST)
return toolbar
}
override fun dispose() {
jbCefBrowser.dispose()
}
companion object {
val LOG = logger<GBrowserMainPanel>()
}
}
| 9 | Kotlin | 16 | 59 | 9327e1e67ba17f3c452bed71b0915c16fc97a112 | 3,598 | GBrowser | Apache License 2.0 |
app/src/main/java/com/example/tmdbclient/presentation/di/core/RemoteDataSourceModule.kt | vishal-singh07 | 692,960,958 | false | {"Kotlin": 56877} | package com.example.tmdbclient.presentation.di.core
import com.example.tmdbclient.BuildConfig
import com.example.tmdbclient.data.api.TMDBService
import com.example.tmdbclient.data.repository.artists.datasource.ArtistRemoteDataSource
import com.example.tmdbclient.data.repository.artists.datasourceImpl.ArtistRemoteDataSourceImpl
import com.example.tmdbclient.data.repository.movies.datasource.MovieRemoteDataSource
import com.example.tmdbclient.data.repository.movies.datasourceImpl.MovieRemoteDataSourceImpl
import com.example.tmdbclient.data.repository.tvshows.datasource.TvShowRemoteDataSource
import com.example.tmdbclient.data.repository.tvshows.datasourceImpl.TvShowRemoteDataSourceImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class RemoteDataSourceModule() {
@Singleton
@Provides
fun providesMovieRemoteDataSource(tmdbService: TMDBService): MovieRemoteDataSource {
return MovieRemoteDataSourceImpl(tmdbService,BuildConfig.API_KEY)
}
@Singleton
@Provides
fun providesArtistRemoteDataSource(tmdbService: TMDBService): ArtistRemoteDataSource {
return ArtistRemoteDataSourceImpl(tmdbService,BuildConfig.API_KEY)
}
@Singleton
@Provides
fun providesTvShowRemoteDataSource(tmdbService: TMDBService): TvShowRemoteDataSource {
return TvShowRemoteDataSourceImpl(tmdbService,BuildConfig.API_KEY)
}
} | 0 | Kotlin | 0 | 0 | 35986439d4ddff6de5a3668ba5f5573c269e50c4 | 1,530 | TMDBClientApp | Apache License 2.0 |
MyStudentData/app/src/main/java/com/dicoding/mystudentdata/MainViewModel.kt | reskimulud | 477,543,802 | false | {"Kotlin": 122658, "Java": 1207} | package com.dicoding.mystudentdata
import androidx.lifecycle.*
import androidx.paging.PagedList
import com.dicoding.mystudentdata.database.Student
import com.dicoding.mystudentdata.database.StudentAndUniversity
import com.dicoding.mystudentdata.helper.SortType
import kotlinx.coroutines.launch
class MainViewModel(private val studentRepository: StudentRepository) : ViewModel() {
private val _sort = MutableLiveData<SortType>()
init {
_sort.value = SortType.ASCENDING
}
fun changeSortType(sortType: SortType) {
_sort.value = sortType
}
fun getAllStudent(): LiveData<PagedList<Student>> = Transformations.switchMap(_sort) {
studentRepository.getAllStudent(it)
}
fun getAllStudentAndUniversity(): LiveData<List<StudentAndUniversity>> = studentRepository.getAllStudentAndUniversity()
// private fun insertAllData() = viewModelScope.launch {
// studentRepository.insertAllData()
// }
}
class ViewModelFactory(private val repository: StudentRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return MainViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
} | 0 | Kotlin | 1 | 1 | 7eeb7b9b398fa0125e3b9312b4da70ac22d8e052 | 1,365 | bpaai-dicoding | MIT License |
sectionrecyclerview/src/main/java/com/github/fajaragungpramana/sectionrecyclerview/SectionRecyclerViewAdapter.kt | fajaragungpramana | 345,262,822 | false | null | package com.github.fajaragungpramana.sectionrecyclerview
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
abstract class SectionRecyclerViewAdapter<VH : SectionRecyclerViewHolder, M : Section>(private val listSection: List<M>) :
RecyclerView.Adapter<VH>() {
protected abstract fun viewHolder(view: View): VH
override fun getItemCount() = listSection.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH =
viewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.adapter_section_recyclerview,
parent,
false
)
)
override fun onBindViewHolder(holder: VH, position: Int) {
holder.bindSectionTitle(listSection[position].titleSection, position)
}
override fun getItemId(position: Int) = position.toLong()
override fun getItemViewType(position: Int) = position
} | 0 | Kotlin | 1 | 6 | b45c98ac930b0508196867977c6e3197e46d182d | 1,013 | section-recyclerview | Apache License 2.0 |
src/main/kotlin/net/exoego/intellij/digdag/DigdagTypeDefOrModule.kt | exoego | 877,164,760 | false | {"Kotlin": 147222, "Lex": 15999, "Java": 2160} | package net.exoego.intellij.digdag
interface DigdagTypeDefOrModule {
/** Same as what Pkl CLI uses for error messages. */
val displayName: String
} | 0 | Kotlin | 0 | 1 | e0d4919b0b72554da632cc922d438681641220e8 | 156 | intellij-digdag | Apache License 2.0 |
buildSrc/src/main/java/Plugin.kt | onirutlA | 476,949,602 | false | null | object Plugin {
// To be used in Project build.gradle.kts
object Gradle {
const val safeArg = "androidx.navigation.safeargs.kotlin:androidx.navigation.safeargs.kotlin.gradle.plugin:${Versions.nav}"
const val mapsSecret = "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:${Versions.mapsplaform_secrets}"
const val daggerHilt = "com.google.dagger:hilt-android-gradle-plugin:${Versions.hilt}"
const val kotlin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}"
}
// To be used in Module build.gradle.kts
const val daggerHilt = "dagger.hilt.android.plugin"
const val safeArg = "androidx.navigation.safeargs.kotlin"
const val mapsSecret = "com.google.android.libraries.mapsplatform.secrets-gradle-plugin"
}
| 0 | Kotlin | 0 | 0 | 1d3f5f14032b5535ac536cee5f7119a69034dcf0 | 814 | MovFlex | MIT License |
src/commonMain/kotlin/com/inari/firefly/physics/animation/AnimationData.kt | AndreasHefti | 387,557,032 | false | null | package com.inari.firefly.physics.animation
import com.inari.firefly.core.*
import com.inari.firefly.core.api.EntityIndex
import com.inari.firefly.core.api.NULL_COMPONENT_INDEX
import com.inari.util.*
import com.inari.util.geom.*
import kotlin.jvm.JvmField
interface AnimatedDataBuilder<D : AnimatedData> {
fun create(): D
}
abstract class AnimatedData {
var entityIndex: EntityIndex = NULL_COMPONENT_INDEX
internal set
val paused: Boolean
get() = entityIndex != NULL_COMPONENT_INDEX && active && Pausing.isPaused(Entity[entityIndex].groups)
var active = false
internal set
var finished = false
internal set
@JvmField var duration = 0L
@JvmField var normalizedTime = 0f
@JvmField var suspend = false
@JvmField var looping = false
@JvmField var inverseOnLoop = false
@JvmField var resetOnFinish = true
@JvmField var inversed = false
@JvmField var nextAnimation: AnimatedData? = null
@JvmField var condition: (AnimatedData) -> Boolean = { !finished }
@JvmField var callback: () -> Unit = VOID_CALL
@JvmField val animationController = CReference(Control)
fun <AD : AnimatedData> withNextAnimation(builder: AnimatedDataBuilder<AD>, configure: AD.() -> Unit) {
val result = builder.create()
result.also(configure)
nextAnimation = result
}
internal fun init(entityIndex: Int) {
this.entityIndex = entityIndex
initialize()
}
internal fun applyTimeStep(timeStep: Float): Boolean {
normalizedTime += timeStep
if (normalizedTime >= 1.0f) {
normalizedTime = 0.0f
if (suspend || !looping) {
finish()
nextAnimation?.active = true
return false
} else {
if (inverseOnLoop)
inversed = !inversed
}
}
return true
}
private fun finish() {
active = false
finished = true
if (resetOnFinish)
reset()
callback()
}
abstract fun initialize()
protected abstract fun reset()
}
@ComponentDSL
class EasedFloatData private constructor() : AnimatedData() {
@JvmField var startValue = 0f
@JvmField var endValue = 0f
@JvmField var easing: EasingFunction = Easing.LINEAR
@JvmField var animatedProperty: (Int) -> FloatPropertyAccessor = { _ -> throw IllegalStateException() }
internal lateinit var accessor: FloatPropertyAccessor
companion object : AnimatedDataBuilder<EasedFloatData> {
override fun create() = EasedFloatData()
}
override fun initialize() {
accessor = animatedProperty(entityIndex)
}
override fun reset() = accessor(startValue)
}
abstract class CurveData protected constructor() : AnimatedData() {
@JvmField var animatedXProperty: (Int) -> FloatPropertyAccessor = VOID_FLOAT_PROPERTY_ACCESSOR_PROVIDER
@JvmField var animatedYProperty: (Int) -> FloatPropertyAccessor = VOID_FLOAT_PROPERTY_ACCESSOR_PROVIDER
@JvmField var animatedRotationProperty: (Int) -> FloatPropertyAccessor = VOID_FLOAT_PROPERTY_ACCESSOR_PROVIDER
internal lateinit var accessorX: FloatPropertyAccessor
internal lateinit var accessorY: FloatPropertyAccessor
internal lateinit var accessorRot: FloatPropertyAccessor
override fun initialize() {
accessorX = animatedXProperty(entityIndex)
accessorY = animatedYProperty(entityIndex)
accessorRot = animatedRotationProperty(entityIndex)
}
}
@ComponentDSL
class BezierCurveData private constructor() : CurveData() {
@JvmField var curve = CubicBezierCurve()
@JvmField var easing: EasingFunction = Easing.LINEAR
override fun reset() {
accessorX(curve.p0.x)
accessorY(curve.p0.y)
accessorRot(ZERO_FLOAT)
}
companion object : AnimatedDataBuilder<BezierCurveData> {
override fun create() = BezierCurveData()
}
}
@ComponentDSL
class BezierSplineData private constructor() : CurveData() {
var spline = BezierSpline()
set(value) {
field = value
duration = value.splineDuration
}
companion object : AnimatedDataBuilder<BezierSplineData> {
override fun create() = BezierSplineData()
}
override fun reset() {
spline.getAtNormalized(ZERO_FLOAT).curve.also {
accessorX(it.p0.x)
accessorY(it.p0.y)
accessorRot(GeomUtils.radToDeg(CubicBezierCurve.bezierCurveAngleX(it, ZERO_FLOAT)))
}
}
}
@ComponentDSL
class IntFrameData private constructor() : AnimatedData() {
var timeline: Array<out IntFrame> = emptyArray()
set(value) {
field = value
duration = field.fold(0L) { acc, frame -> acc + frame.timeInterval }
}
@JvmField var animatedProperty: (Int) -> IntPropertyAccessor = { _ -> throw IllegalStateException() }
internal lateinit var accessor: IntPropertyAccessor
override fun initialize() {
accessor = animatedProperty(entityIndex)
}
override fun reset() = accessor(timeline[0].value)
companion object : AnimatedDataBuilder<IntFrameData> {
override fun create() = IntFrameData()
}
interface IntFrame {
val timeInterval: Long
val value: Int
}
}
| 6 | Kotlin | 0 | 11 | 2149d1a5e32e3d3f5a627d224b6a542c97b4731e | 5,348 | flyko-lib | Apache License 2.0 |
app/src/main/java/tw/zero/aainputinjector/OverlayService.kt | itszero | 339,962,051 | false | null | package tw.zero.aainputinjector
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Binder
import android.os.IBinder
import android.view.*
import android.view.WindowManager.LayoutParams
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
class OverlayService : Service() {
private var overlayView: View? = null
private var currentAppFacet: AAFacetType = AAFacetType.UNKNOWN_FACET
private var isEyeRideInstalled = false
private var isEyeRideConnected = false
inner class LocalBinder : Binder() {
// Return this instance of LocalService so clients can call public methods
fun getService(): OverlayService = this@OverlayService
}
private val binder = LocalBinder()
override fun onBind(intent: Intent?): IBinder? {
return binder
}
val isOverlayActive
get() = overlayView != null
private val facetUpdateReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val facetTypeStr = intent!!.getStringExtra("facetType")
val facetType = AAFacetType.valueOf(facetTypeStr!!)
currentAppFacet = facetType
updateView(null)
}
}
private val captainRiderReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
isEyeRideConnected = intent!!.getBooleanExtra("isConnected", false)
updateView(null)
}
}
override fun onCreate() {
super.onCreate()
registerReceiver(facetUpdateReceiver, IntentFilter(Utils.intent_facet_changed))
registerReceiver(captainRiderReceiver, IntentFilter(Utils.intent_eyeride_report))
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(facetUpdateReceiver)
unregisterReceiver(captainRiderReceiver)
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
overlayView?.let {
windowManager.removeView(it)
overlayView = null
}
}
fun startOverlay() {
isEyeRideInstalled = packageManager.getInstalledPackages(0).firstOrNull {
it.packageName == "com.eyelights.intercom"
} != null
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
overlayView = createView()
val params = LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
)
params.gravity = Gravity.NO_GRAVITY
params.x = 0
params.y = 0
windowManager.addView(overlayView, params)
sendBroadcast(Intent(Utils.intent_checkin))
}
fun stopOverlay() {
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
overlayView?.let {
windowManager.removeView(it)
overlayView = null
}
}
private fun createView(): View {
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val interceptorLayout = object : FrameLayout(this) {
var startY: Float = 0f
var initialY: Float = 0f
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
if (!super.dispatchTouchEvent(ev)) {
when (ev!!.action) {
MotionEvent.ACTION_DOWN -> {
startY = ev.rawY
initialY =
(overlayView!!.layoutParams as WindowManager.LayoutParams).y.toFloat()
}
MotionEvent.ACTION_MOVE -> {
overlayView!!.updateLayoutParams<WindowManager.LayoutParams> {
y = (initialY + ev.rawY - startY).toInt()
}
windowManager.updateViewLayout(
overlayView!!,
overlayView!!.layoutParams
)
}
}
}
return true
}
}
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.controller, interceptorLayout)
view.findViewById<ImageButton>(R.id.btn_prev).setOnClickListener {
Utils.sendKeyEvent(this, AAKeyCode.KEYCODE_ROTARY_CONTROLLER, -1)
}
view.findViewById<ImageButton>(R.id.btn_enter).setOnClickListener {
Utils.sendKeyEvent(this, AAKeyCode.KEYCODE_ENTER, 0)
}
view.findViewById<ImageButton>(R.id.btn_next).setOnClickListener {
Utils.sendKeyEvent(this, AAKeyCode.KEYCODE_ROTARY_CONTROLLER, 1)
}
view.findViewById<ImageButton>(R.id.btn_home).setOnClickListener {
Utils.sendKeyEvent(this, AAKeyCode.KEYCODE_HOME, 0)
}
view.findViewById<ImageButton>(R.id.btn_up).setOnClickListener {
Utils.sendKeyEvent(this, AAKeyCode.KEYCODE_DPAD_UP, 0)
}
view.findViewById<ImageButton>(R.id.btn_down).setOnClickListener {
Utils.sendKeyEvent(this, AAKeyCode.KEYCODE_DPAD_DOWN, 0)
}
view.findViewById<ImageButton>(R.id.btn_vol_up).setOnClickListener {
sendBroadcast(Intent(Utils.intent_eyeride_vol_up))
}
view.findViewById<ImageButton>(R.id.btn_vol_down).setOnClickListener {
sendBroadcast(Intent(Utils.intent_eyeride_vol_down))
}
updateView(view)
return view
}
private fun updateView(view: View?) {
val viewToUse = (view ?: overlayView) ?: return
viewToUse.findViewById<ImageButton>(R.id.btn_alt_app).setOnClickListener {
if (currentAppFacet !== AAFacetType.NAVIGATION) {
Utils.sendKeyEvent(this, AAKeyCode.KEYCODE_NAVIGATION, 0)
} else {
Utils.sendKeyEvent(this, AAKeyCode.KEYCODE_MEDIA, 0)
}
}
viewToUse.findViewById<ImageButton>(R.id.btn_alt_app).setImageResource(
if (currentAppFacet == AAFacetType.NAVIGATION) R.drawable.ic_music else R.drawable.ic_nav
)
viewToUse.findViewById<LinearLayout>(R.id.layout_eyeride_volume).visibility =
if (isEyeRideInstalled) LinearLayout.VISIBLE else LinearLayout.GONE
viewToUse.findViewById<ImageButton>(R.id.btn_vol_up).isEnabled = isEyeRideConnected
viewToUse.findViewById<ImageButton>(R.id.btn_vol_up)
.backgroundTintList =
ColorStateList.valueOf(if (isEyeRideConnected) Color.rgb(0xD5, 0, 0) else Color.BLACK)
viewToUse.findViewById<ImageButton>(R.id.btn_vol_down).isEnabled = isEyeRideConnected
viewToUse.findViewById<ImageButton>(R.id.btn_vol_down)
.backgroundTintList =
ColorStateList.valueOf(if (isEyeRideConnected) Color.rgb(0xD5, 0, 0) else Color.BLACK)
}
}
| 0 | Kotlin | 0 | 0 | 2d8edfe47a9fa1ccbc158f8f427157ae83db70a3 | 7,596 | AAInputInjector | MIT License |
FastBarCodeScan/core/src/main/java/cn/zengcanxiang/fastbarcodescan/core/SupportScanType.kt | zengcanxiang | 341,458,328 | false | null | package cn.zengcanxiang.fastbarcodescan.core
/**
* 支持的二维码扫码类型
*/
enum class SupportScanType(
val str: String
) {
QR_CODE(
"qr_code"
)
}
| 0 | Kotlin | 0 | 2 | b81c724f177776c8cb55477aa6a3b55f3abe5a82 | 159 | fastbarcodescan | Apache License 2.0 |
app/src/main/kotlin/dev/lotr/app/ui/books/BooksScreen.kt | kitfist0 | 419,467,934 | false | null | package dev.lotr.app.ui.books
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import dev.lotr.app.R
import dev.lotr.app.ui.common.ColumnHeader
import dev.lotr.app.ui.common.ColumnSimpleItem
import dev.lotr.app.ui.common.ErrorScreen
import dev.lotr.app.ui.common.LoadingProgress
import dev.lotr.domain.common.Result
import dev.lotr.domain.model.Book
@Composable
fun BooksScreen(
viewModel: BooksViewModel,
modifier: Modifier = Modifier,
) {
when (val state = viewModel.stateFlow.collectAsState().value) {
is Result.Loading -> LoadingProgress(modifier)
is Result.Success -> Body(
books = state.data,
onBookClick = { bookId -> viewModel.onBookClicked(bookId) },
modifier,
)
is Result.Error -> ErrorScreen(
message = state.message,
onRetryClicked = { viewModel.fetchData() },
modifier,
)
}
}
@Composable
private fun Body(
books: List<Book>,
onBookClick: (String) -> Unit,
modifier: Modifier,
) {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = modifier
.fillMaxSize()
.statusBarsPadding(),
) {
item {
ColumnHeader(stringResource(R.string.app_name))
}
items(books) { book ->
ColumnSimpleItem(
itemId = book.id,
text = book.name,
onItemClick = onBookClick,
)
}
}
}
@Preview(showBackground = true)
@Composable
private fun BooksScreenPreview() {
Body(
books = listOf(
Book("5cf58077b53e011a64671582", "The Fellowship Of The Ring"),
Book("5cf58077b53e011a64671583", "The Two Towers"),
Book("5cf58077b53e011a64671584", "The Return Of The King"),
),
onBookClick = {},
modifier = Modifier,
)
}
| 0 | Kotlin | 0 | 0 | fb54f0fa694fcbfddfb5d5c74e910120b67b2c78 | 2,246 | ComposeLotrApp | Apache License 2.0 |
app/src/main/java/com/example/todoapp/data/models/Priority.kt | unon4all | 781,257,339 | false | {"Kotlin": 85753} | package com.example.todoapp.data.models
import androidx.compose.ui.graphics.Color
import com.example.todoapp.ui.theme.HighPriorityColor
import com.example.todoapp.ui.theme.LowPriorityColor
import com.example.todoapp.ui.theme.MediumPriorityColor
/**
* Enum class representing different priorities with associated colors.
*/
enum class Priority(val color: Color) {
/**
* Represents high priority tasks.
*/
HIGH(HighPriorityColor),
/**
* Represents medium priority tasks.
*/
MEDIUM(MediumPriorityColor),
/**
* Represents low priority tasks.
*/
LOW(LowPriorityColor),
/**
* Represents tasks with no specified priority.
*/
NONE(Color.Transparent),
}
| 0 | Kotlin | 0 | 0 | fe6bbabc3e33564e37da5aef543cabd18c8e8d6e | 725 | To-Do-App | MIT License |
core/src/main/kotlin/com/acmerobotics/roadrunner/trajectory/Trajectory.kt | henopied | 242,858,073 | false | null | package com.acmerobotics.roadrunner.trajectory
import com.acmerobotics.roadrunner.geometry.Pose2d
import com.acmerobotics.roadrunner.path.Path
import com.acmerobotics.roadrunner.profile.MotionProfile
/**
* Trajectory backed by a [Path] and a [MotionProfile].
*
* @param path path
* @param profile motion profile
*/
class Trajectory @JvmOverloads constructor(
val path: Path,
val profile: MotionProfile,
val markers: List<AbsoluteTemporalMarker> = emptyList()
) {
fun duration() = profile.duration()
operator fun get(time: Double) = path[profile[time].x]
fun velocity(time: Double): Pose2d {
val motionState = profile[time]
return path.deriv(motionState.x) * motionState.v
}
fun acceleration(time: Double): Pose2d {
val motionState = profile[time]
return path.secondDeriv(motionState.x) * motionState.v * motionState.v +
path.deriv(motionState.x) * motionState.a
}
fun start() = path[0.0, 0.0]
fun end() = path[path.length(), 1.0]
}
| 1 | null | 1 | 2 | 19d779986d174601e08dda636cb043b1dddd84d7 | 1,032 | road-runner | MIT License |
src/main/kotlin/es/upv/mist/cauder/erlang/ProcessScheduler.kt | SackCastellon | 338,811,836 | false | null | package es.upv.mist.cauder.erlang
enum class ProcessScheduler(val key: String) {
ROUND_ROBIN("round_robin"), FCFS("fcfs")
}
| 0 | Kotlin | 0 | 0 | b118a78bb1bb8c891d30ef89e40f2320a0895e0b | 129 | cauder-ui | MIT License |
app/src/main/java/com/example/mymenu/MainActivity.kt | jdagnogo | 227,371,435 | false | null | package com.example.mymenu
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| 0 | Kotlin | 0 | 0 | a9f83ed7c37fe0d6142b4d5cdff0a447446e90cb | 301 | MyMenu | Apache License 2.0 |
example/src/main/java/app/futured/arkitekt/sample/domain/GetStateUseCase.kt | futuredapp | 124,508,581 | false | {"Kotlin": 357272, "Java": 1724, "Ruby": 1104} | package app.futured.arkitekt.sample.domain
import app.futured.arkitekt.rxusecases.usecases.MaybeUseCase
import io.reactivex.Maybe
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class GetStateUseCase @Inject constructor() : MaybeUseCase<Boolean, Boolean>() {
companion object {
private const val DELAY_MS = 3000L
}
override fun prepare(emitSuccess: Boolean) = Maybe.create<Boolean> { emitter ->
if (emitSuccess) {
emitter.onSuccess(true)
} else {
emitter.onComplete()
}
}.delay(DELAY_MS, TimeUnit.MILLISECONDS)
}
| 10 | Kotlin | 9 | 120 | 2a3d089342a53f4a09e6055a9076275974dc3f04 | 605 | arkitekt | MIT License |
repository/src/main/java/com/iniongun/tivbible/repository/room/verse/IVersesRepo.kt | IniongunIsaac | 222,639,477 | false | null | package com.iniongun.tivbible.repository.room.verse
import com.iniongun.tivbible.entities.BookAndChapterAndVerse
import com.iniongun.tivbible.entities.Verse
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
/**
* Created by <NAME> on 2019-11-24
* For Tiv Bible project
*/
interface IVersesRepo {
fun addVerses(verses: List<Verse>): Completable
fun getAllVerses(): Observable<List<Verse>>
fun getVerseById(verseId: String): Single<Verse>
fun getVersesByBook(bookId: String): Observable<List<Verse>>
fun getVersesByText(searchText: String): Observable<List<Verse>>
fun getVersesByTextAndChapter(searchText: String, chapterId: String): Observable<List<Verse>>
fun getVersesByChapter(chapterId: String): Observable<List<Verse>>
fun deleteVerses(verses: List<Verse>): Completable
fun getBooksAndChaptersAndVersesByText(searchText: String): Observable<List<BookAndChapterAndVerse>>
fun getBooksAndChaptersAndVersesByTextAndChapter(searchText: String, chapterId: String): Observable<List<BookAndChapterAndVerse>>
fun getBooksAndChaptersAndVersesByTextAndChapterAndBook(searchText: String, chapterId: String, bookId: String): Observable<List<BookAndChapterAndVerse>>
} | 0 | Kotlin | 2 | 7 | 63da6ec716325a23b24d7071e53d5845ba56fa3c | 1,262 | Tiv-Bible | MIT License |
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/data/source/network/dto/singleproduct/SampleConsumptionDto.kt | ryanw-mobile | 794,752,204 | false | {"Kotlin": 1112930, "Ruby": 2466, "Swift": 693} | /*
* Copyright (c) 2024. <NAME>
* https://github.com/ryanw-mobile
* Sponsored by RW MobiMedia UK Limited
*
*/
package com.rwmobi.kunigami.data.source.network.dto.singleproduct
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class SampleConsumptionDto(
@SerialName("electricity_single_rate") val electricitySingleRate: ConsumptionDetailDto,
@SerialName("electricity_dual_rate") val electricityDualRate: DualRateConsumptionDetailDto,
@SerialName("dual_fuel_single_rate") val dualFuelSingleRate: DualFuelConsumptionDetailDto,
@SerialName("dual_fuel_dual_rate") val dualFuelDualRate: DualRateConsumptionDetailDto,
)
| 24 | Kotlin | 10 | 98 | e1e73f5b44baaef5ab87fd10db21775d442a3172 | 689 | OctoMeter | Apache License 2.0 |
app/src/main/java/com/dicoding/edival/ui/tutorial/TutorialSlide.kt | EDIVAL-Edible-Eval | 727,729,297 | false | {"Kotlin": 33826} | package com.dicoding.edival.ui.tutorial
data class TutorialSlide(
val title: String,
val description: String,
val picture: Int
)
| 0 | Kotlin | 0 | 0 | 004222b75925084b7bd27fe762dda274c02a7703 | 143 | edival-md | MIT License |
sdk/src/commonMain/kotlin/com/symbiosis/sdk/crosschain/testnet/AvalancheFujiEthRinkeby.kt | symbiosis-finance | 473,611,783 | false | {"Kotlin": 563820, "Swift": 5851, "Ruby": 1700} | package com.symbiosis.sdk.crosschain.testnet
import com.symbiosis.sdk.crosschain.DefaultCrossChain
import com.symbiosis.sdk.crosschain.StablePools
import com.symbiosis.sdk.networks.AvalancheFuji
import com.symbiosis.sdk.networks.EthRinkeby
import com.symbiosis.sdk.swap.crosschain.NerveStablePool
import dev.icerock.moko.web3.Web3
import dev.icerock.moko.web3.Web3Executor
class AvalancheFujiEthRinkeby(
avalancheFujiExecutor: Web3Executor,
ethRinkebyExecutor: Web3Executor
) : TestnetCrossChain() {
constructor(avalancheFujiUrl: String, ethRinkebyUrl: String) :
this(Web3(avalancheFujiUrl), Web3(ethRinkebyUrl))
override val fromNetwork = AvalancheFuji(avalancheFujiExecutor)
override val toNetwork = EthRinkeby(ethRinkebyExecutor)
override val stablePool: NerveStablePool =
StablePools.AVALANCHE_FUJI_USDT_ETH_RINKEBY_sUSDC_POOL(fromNetwork, toNetwork)
}
| 0 | Kotlin | 2 | 4 | e8b1c424c62a847a5339039864223e65fdb2cbae | 904 | mobile-sdk | Apache License 2.0 |
src/main/kotlin/newturbine/channel.kt | jingibus | 520,120,821 | false | null | package newturbine/*
* Copyright (C) 2022 Square, 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.
*/
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.ChannelResult
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.channels.ReceiveChannel
/**
* Returns the most recent item that has already been received.
* If channel was closed with no item being received
* previously, this function will throw an [AssertionError]. If channel
* was closed with an exception, this function will throw the underlying exception.
*
* @throws AssertionError if no item was emitted.
*/
public fun <T> ReceiveChannel<T>.expectMostRecentItem(): T {
var result: ChannelResult<T>? = null
var prevResult: ChannelResult<T>?
while (true) {
prevResult = result
result = tryReceive()
result.exceptionOrNull()?.let { throw it }
if (!result.isSuccess) {
break
}
}
if (prevResult?.isSuccess == true) return prevResult.getOrThrow()
throw TurbineAssertionError("No item was found", cause = null)
}
/**
* Assert that there are no unconsumed events which have already been received.
*
* A channel in the closed state will always emit either [Event.Complete] or [Event.Error] when read, so
* [expectNoEvents] will only succeed on an empty [ReceiveChannel] that is not closed.
*
* @throws AssertionError if unconsumed events are found.
*/
public fun <T> ReceiveChannel<T>.expectNoEvents() {
val result = tryReceive()
if (result.isSuccess || result.isClosed) result.unexpectedResult("no events")
}
/**
* Assert that an event was received and return it.
* This function will suspend if no events have been received.
*
* This function will always return a terminal event on a closed [ReceiveChannel].
*/
public suspend fun <T> ReceiveChannel<T>.awaitEvent(): Event<T> =
try {
Event.Item(receive())
} catch (e: CancellationException) {
throw e
} catch (e: ClosedReceiveChannelException) {
Event.Complete
} catch (e: Exception) {
Event.Error(e)
}
/**
* Assert that the next event received was non-null and return it.
* This function will not suspend. On JVM and Android, it will attempt to throw if invoked in a suspending context.
*
* @throws AssertionError if the next event was completion or an error.
*/
public fun <T> ReceiveChannel<T>.takeEvent(): Event<T> {
assertCallingContextIsNotSuspended()
return takeEventUnsafe()
?: unexpectedEvent(null, "an event")
}
internal fun <T> ReceiveChannel<T>.takeEventUnsafe(): Event<T>? {
return tryReceive().toEvent()
}
/**
* Assert that the next event received was an item and return it.
* This function will not suspend. On JVM and Android, it will attempt to throw if invoked in a suspending context.
*
* @throws AssertionError if the next event was completion or an error, or no event.
*/
public fun <T> ReceiveChannel<T>.takeItem(): T {
val event = takeEvent()
return (event as? Event.Item)?.value ?: unexpectedEvent(event, "item")
}
/**
* Assert that the next event received is [Event.Complete].
* This function will not suspend. On JVM and Android, it will attempt to throw if invoked in a suspending context.
*
* @throws AssertionError if the next event was completion or an error.
*/
public fun <T> ReceiveChannel<T>.takeComplete() {
val event = takeEvent()
if (event !is Event.Complete) unexpectedEvent(event, "complete")
}
/**
* Assert that the next event received is [Event.Error], and return the error.
* This function will not suspend. On JVM and Android, it will attempt to throw if invoked in a suspending context.
*
* @throws AssertionError if the next event was completion or an error.
*/
public fun <T> ReceiveChannel<T>.takeError(): Throwable {
val event = takeEvent()
return (event as? Event.Error)?.throwable ?: unexpectedEvent(event, "error")
}
/**
* Assert that the next event received was an item and return it.
* This function will suspend if no events have been received.
*
* @throws AssertionError if the next event was completion or an error.
*/
public suspend fun <T> ReceiveChannel<T>.awaitItem(): T =
when (val result = awaitEvent()) {
is Event.Item -> result.value
else -> unexpectedEvent(result, "item")
}
/**
* Assert that [count] item events were received and ignore them.
* This function will suspend if no events have been received.
*
* @throws AssertionError if one of the events was completion or an error.
*/
public suspend fun <T> ReceiveChannel<T>.skipItems(count: Int) {
repeat(count) { index ->
when (val event = awaitEvent()) {
Event.Complete, is Event.Error -> {
val cause = (event as? Event.Error)?.throwable
throw TurbineAssertionError("Expected $count items but got $index items and $event", cause)
}
is Event.Item<T> -> { /* Success */ }
}
}
}
/**
* Assert that attempting to read from the [ReceiveChannel] yields [ClosedReceiveChannelException], indicating
* that it was closed without an exception.
*
* @throws AssertionError if the next event was an item or an error.
*/
public suspend fun <T> ReceiveChannel<T>.awaitComplete() {
val event = awaitEvent()
if (event != Event.Complete) {
unexpectedEvent(event, "complete")
}
}
/**
* Assert that attempting to read from the [ReceiveChannel] yields an exception, indicating
* that it was closed with an exception.
*
* @throws AssertionError if the next event was an item or completion.
*/
public suspend fun <T> ReceiveChannel<T>.awaitError(): Throwable {
val event = awaitEvent()
return (event as? Event.Error)?.throwable
?: unexpectedEvent(event, "error")
}
internal fun <T> ChannelResult<T>.toEvent(): Event<T>? {
val cause = exceptionOrNull()
return if (isSuccess) Event.Item(getOrThrow())
else if (cause != null) Event.Error(cause)
else if (isClosed) Event.Complete
else null
}
private fun <T> ChannelResult<T>.unexpectedResult(expected: String): Nothing = unexpectedEvent(toEvent(), expected)
private fun unexpectedEvent(event: Event<*>?, expected: String): Nothing {
val cause = (event as? Event.Error)?.throwable
val eventAsString = event?.toString() ?: "no items"
throw TurbineAssertionError("Expected $expected but found $eventAsString", cause)
}
| 0 | Kotlin | 0 | 3 | c044626e0ba613054aaa9387d060d2811fb72d85 | 6,816 | coroutines-testing | Apache License 2.0 |
extension-viewer-promotion/src/main/kotlin/fr/o80/twitck/extension/promotion/ViewerPromotion.kt | olivierperez | 283,750,838 | false | null | package fr.o80.twitck.extension.promotion
import fr.o80.twitck.lib.api.Pipeline
import fr.o80.twitck.lib.api.bean.Importance
import fr.o80.twitck.lib.api.bean.Video
import fr.o80.twitck.lib.api.bean.event.MessageEvent
import fr.o80.twitck.lib.api.exception.ExtensionDependencyException
import fr.o80.twitck.lib.api.extension.HelpExtension
import fr.o80.twitck.lib.api.extension.PointsExtension
import fr.o80.twitck.lib.api.extension.SoundExtension
import fr.o80.twitck.lib.api.extension.StorageExtension
import fr.o80.twitck.lib.api.service.Messenger
import fr.o80.twitck.lib.api.service.ServiceLocator
import fr.o80.twitck.lib.api.service.TwitchApi
import fr.o80.twitck.lib.api.service.time.StorageFlagTimeChecker
import fr.o80.twitck.lib.api.service.time.TimeChecker
import fr.o80.twitck.lib.api.service.ConfigService
import java.time.Duration
import java.time.Instant
class ViewerPromotion(
private val channel: String,
private val promotionMessages: Collection<String>,
private val ignoredLogins: Collection<String>,
private val maxVideoAgeToPromote: Duration,
private val promotionTimeChecker: TimeChecker,
private val twitchApi: TwitchApi,
private val command: ViewerPromotionCommand,
help: HelpExtension?
) {
init {
help?.registerCommand(SHOUT_OUT_COMMAND)
}
fun interceptMessageEvent(messenger: Messenger, messageEvent: MessageEvent): MessageEvent {
if (channel != messageEvent.channel)
return messageEvent
if (messageEvent.viewer.login in ignoredLogins) {
return messageEvent
}
promotionTimeChecker.executeIfNotCooldown(messageEvent.viewer.login) {
promoteViewer(messenger, messageEvent)
}
return messageEvent
}
private fun promoteViewer(messenger: Messenger, messageEvent: MessageEvent) {
val lastVideo = twitchApi.getVideos(messageEvent.viewer.userId, 1)
.filter { (it.publishedAt.toInstant() + maxVideoAgeToPromote).isAfter(Instant.now()) }
.takeIf { it.isNotEmpty() }
?.first()
?: return
val randomMessage = promotionMessages.random().formatViewer(messageEvent, lastVideo)
messenger.sendWhenAvailable(messageEvent.channel, randomMessage, Importance.HIGH)
}
private fun String.formatViewer(messageEvent: MessageEvent, video: Video): String =
this.replace("#USER#", messageEvent.viewer.displayName)
.replace("#URL#", video.url)
.replace("#GAME#", video.game)
companion object {
fun installer(
pipeline: Pipeline,
serviceLocator: ServiceLocator,
configService: ConfigService
): ViewerPromotion? {
val config = configService.getConfig(
"viewer_promotion.json",
ViewerPromotionConfiguration::class
)
?.takeIf { it.enabled }
?: return null
serviceLocator.loggerFactory.getLogger(ViewerPromotion::class)
.info("Installing ViewerPromotion extension...")
val storage = serviceLocator.extensionProvider.firstOrNull(StorageExtension::class)
?: throw ExtensionDependencyException("ViewerPromotion", "Storage")
val help = serviceLocator.extensionProvider.firstOrNull(HelpExtension::class)
val points = serviceLocator.extensionProvider.firstOrNull(PointsExtension::class)
val sound = serviceLocator.extensionProvider.firstOrNull(SoundExtension::class)
val promotionTimeChecker = StorageFlagTimeChecker(
storage,
ViewerPromotion::class.java.name,
"promotedAt",
Duration.ofSeconds(config.data.secondsBetweenTwoPromotions)
)
return ViewerPromotion(
channel = config.data.channel.name,
promotionMessages = config.data.promotionMessages,
ignoredLogins = config.data.ignoreViewers,
maxVideoAgeToPromote = Duration.ofDays(config.data.daysSinceLastVideoToPromote),
promotionTimeChecker = promotionTimeChecker,
twitchApi = serviceLocator.twitchApi,
command = ViewerPromotionCommand(
channel = config.data.channel.name,
storage = storage,
sound = sound,
points = points,
i18n = config.data.i18n
),
help = help
).also { viewerPromotion ->
pipeline.requestChannel(viewerPromotion.channel)
pipeline.interceptMessageEvent { messenger, messageEvent ->
viewerPromotion.interceptMessageEvent(messenger, messageEvent)
}
pipeline.interceptWhisperCommandEvent { messenger, commandEvent ->
viewerPromotion.command.interceptWhisperCommandEvent(
messenger,
commandEvent
)
}
pipeline.interceptCommandEvent { messenger, commandEvent ->
viewerPromotion.command.interceptCommandEvent(messenger, commandEvent)
}
}
}
}
}
| 0 | Kotlin | 1 | 5 | bb2828260ae6837f87ebb71bce11e383be514f53 | 5,319 | TwitckBot | Apache License 2.0 |
shared/src/androidMain/kotlin/com/jittyandiyan/shared/core/platform/expectations/PlatformExpectations.kt | jittya | 361,707,096 | false | null | package com.jittyandiyan.shared.core.platform.expectations
import android.content.Context
import android.os.Bundle
import com.jittyandiyan.mobile.KMMTDB
import com.jittyandiyan.shared.core.dependencyInjection.AndroidKoinComponents
import com.jittyandiyan.shared.core.models.BundleExtras
import com.jittyandiyan.shared.core.platform.Android
import com.jittyandiyan.shared.core.platform.Platform
import com.russhwolf.settings.AndroidSettings
import com.russhwolf.settings.Settings
import com.squareup.sqldelight.android.AndroidSqliteDriver
import com.squareup.sqldelight.db.SqlDriver
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import org.koin.core.module.Module
import org.koin.dsl.module
internal actual val ApplicationDispatcher: CoroutineDispatcher = Dispatchers.Main
internal actual val Dispatchers_Default: CoroutineDispatcher=Dispatchers.Default
actual fun getAppContextAsKoinBean(appContext: Any): Module {
appContext as Context
return module {
single<Context> { appContext }
}
}
actual val sqlDriverModule: Module
get() = module {
single<SqlDriver> { AndroidSqliteDriver(KMMTDB.Schema, get(), "KMMTB.db") }
}
actual class BundleX {
val bundle = Bundle()
actual constructor(extras: BundleExtras)
{
extras.getKeys().forEach { key ->
extras.getValue(key)?.let { value->
if (value is String)
{
bundle.putString(key,value)
}
else if (value is Boolean)
{
bundle.putBoolean(key,value)
}
else if (value is Int)
{
bundle.putInt(key,value)
}
else if (value is Long)
{
bundle.putLong(key,value)
}
else if (value is Float)
{
bundle.putFloat(key,value)
}
else if (value is Double)
{
bundle.putDouble(key,value)
}
}
}
}
}
actual val platform:Platform = Android("Android",android.os.Build.VERSION.SDK_INT)
actual val keyValueStore: Settings
get() = AndroidSettings(AndroidKoinComponents().androidContext.getSharedPreferences("KeyValueStore", Context.MODE_PRIVATE))
| 0 | Kotlin | 6 | 125 | 3a30c984b215b6df4a90d4a7a5ce965127b9ca09 | 2,412 | KMMT | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.