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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
base/src/main/java/com/widget/ItemOffsetDecoration.kt | cuongnv219 | 145,366,148 | false | null | package com.widget
import android.content.Context
import android.graphics.Rect
import androidx.annotation.DimenRes
import androidx.recyclerview.widget.RecyclerView
import android.view.View
class ItemOffsetDecoration(private val mItemOffset: Int) : androidx.recyclerview.widget.RecyclerView.ItemDecoration() {
constructor(context: Context, @DimenRes itemOffsetId: Int) : this(context.resources.getDimensionPixelSize(itemOffsetId))
override fun getItemOffsets(outRect: Rect, view: View, parent: androidx.recyclerview.widget.RecyclerView, state: androidx.recyclerview.widget.RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
outRect.set(mItemOffset, mItemOffset, mItemOffset, mItemOffset)
}
} | 1 | Kotlin | 7 | 7 | d607c04cd634b0ae0a5d6a60c989ad7ac0a74c84 | 744 | mvvm-kotlin | Apache License 2.0 |
src/main/kotlin/io/nshusa/rsam/util/CompressionUtils.kt | GregHib | 138,198,808 | false | {"Kotlin": 283100, "CSS": 1905} | package io.nshusa.rsam.util
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream
import java.*
import java.io.*
import java.nio.ByteBuffer
import java.util.zip.DeflaterOutputStream
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
/**
* A utility class for performing compression/decompression.
*
* @author Graham
*/
object CompressionUtils {
/**
* Bzip2s the specified array, removing the header.
*
* @param uncompressed The uncompressed array.
* @return The compressed array.
* @throws IOException If there is an error compressing the array.
*/
@Throws(IOException::class)
fun bzip2(uncompressed: ByteArray): ByteArray {
val bout = ByteArrayOutputStream()
BZip2CompressorOutputStream(bout, 1).use { os ->
os.write(uncompressed)
os.finish()
val compressed = bout.toByteArray()
val newCompressed = ByteArray(compressed.size - 4) // Strip the header
System.arraycopy(compressed, 4, newCompressed, 0, newCompressed.size)
return newCompressed
}
}
/**
* Debzip2s the compressed array and places the result into the decompressed array.
*
* @param compressed The compressed array, **without** the header.
* @param decompressed The decompressed array.
* @throws IOException If there is an error decompressing the array.
*/
@Throws(IOException::class)
fun debzip2(compressed: ByteArray, decompressed: ByteArray) {
val newCompressed = ByteArray(compressed.size + 4)
newCompressed[0] = 'B'.toByte()
newCompressed[1] = 'Z'.toByte()
newCompressed[2] = 'h'.toByte()
newCompressed[3] = '1'.toByte()
System.arraycopy(compressed, 0, newCompressed, 4, compressed.size)
DataInputStream(BZip2CompressorInputStream(ByteArrayInputStream(newCompressed))).use { `is` -> `is`.readFully(decompressed) }
}
/**
* Degzips the compressed array and places the results into the decompressed array.
*
* @param compressed The compressed array.
* @param decompressed The decompressed array.
* @throws IOException If an I/O error occurs.
*/
@Throws(IOException::class)
fun degzip(compressed: ByteArray, decompressed: ByteArray) {
DataInputStream(GZIPInputStream(ByteArrayInputStream(compressed))).use { `is` -> `is`.readFully(decompressed) }
}
/**
* Degzips **all** of the datain the specified [ByteBuffer].
*
* @param compressed The compressed buffer.
* @return The decompressed array.
* @throws IOException If there is an error decompressing the buffer.
*/
@Throws(IOException::class)
fun degzip(compressed: ByteBuffer): ByteArray {
GZIPInputStream(ByteArrayInputStream(compressed.array())).use { `is` ->
ByteArrayOutputStream().use { out ->
val buffer = ByteArray(1024)
while (true) {
val read = `is`.read(buffer, 0, buffer.size)
if (read == -1) {
break
}
out.write(buffer, 0, read)
}
return out.toByteArray()
}
}
}
/**
* Gzips the specified array.
*
* @param uncompressed The uncompressed array.
* @return The compressed array.
* @throws IOException If there is an error compressing the array.
*/
@Throws(IOException::class)
fun gzip(uncompressed: ByteArray): ByteArray {
val bout = ByteArrayOutputStream()
GZIPOutputStream(bout).use { os ->
os.write(uncompressed)
os.finish()
return bout.toByteArray()
}
}
}
/**
* Default private constructor to prevent instantiation.
*/ | 0 | Kotlin | 4 | 6 | 80ffcfc36f7dd397f1d6e1f6d74d3b5c16c70749 | 3,957 | interface-editor | MIT License |
DSL/com.larsreimann.safeds/src/main/kotlin/com/larsreimann/safeds/validation/expressions/TemplateStringChecker.kt | Safe-DS | 499,036,565 | false | null | package com.larsreimann.safeds.validation.expressions
import com.larsreimann.safeds.safeDS.SdsAbstractTemplateStringPart
import com.larsreimann.safeds.safeDS.SdsTemplateString
import com.larsreimann.safeds.validation.AbstractSafeDSChecker
import com.larsreimann.safeds.validation.codes.ErrorCode
import org.eclipse.xtext.validation.Check
class TemplateStringChecker : AbstractSafeDSChecker() {
@Check
fun missingTemplateExpression(sdsTemplateString: SdsTemplateString) {
sdsTemplateString.expressions
.windowed(size = 2, step = 1)
.forEach { (first, second) ->
if (first is SdsAbstractTemplateStringPart && second is SdsAbstractTemplateStringPart) {
error(
"There must be a template expression between two template string parts.",
second,
null,
ErrorCode.MissingTemplateExpression
)
}
}
}
}
| 36 | Kotlin | 0 | 9 | ea254088688b0f7211e33a15b9f42b536da9692a | 1,018 | DSL | MIT License |
solar/src/main/java/com/chiksmedina/solar/lineduotone/arrows/DoubleAltArrowRight.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.lineduotone.arrows
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.lineduotone.ArrowsGroup
val ArrowsGroup.DoubleAltArrowRight: ImageVector
get() {
if (_doubleAltArrowRight != null) {
return _doubleAltArrowRight!!
}
_doubleAltArrowRight = Builder(
name = "DoubleAltArrowRight", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(11.0f, 19.0f)
lineTo(17.0f, 12.0f)
lineTo(11.0f, 5.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 1.5f, strokeLineCap =
Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(6.9998f, 19.0f)
lineTo(12.9998f, 12.0f)
lineTo(6.9998f, 5.0f)
}
}
.build()
return _doubleAltArrowRight!!
}
private var _doubleAltArrowRight: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 1,971 | SolarIconSetAndroid | MIT License |
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress2030010.kt | qwewqa | 390,928,568 | false | null | package xyz.qwewqa.relive.simulator.core.presets.dress.generated
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute
import xyz.qwewqa.relive.simulator.core.stage.actor.StatData
import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters
import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType
import xyz.qwewqa.relive.simulator.stage.character.Character
import xyz.qwewqa.relive.simulator.stage.character.DamageType
import xyz.qwewqa.relive.simulator.stage.character.Position
/*
import xyz.qwewqa.relive.simulator.core.presets.condition.*
import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress2030010
import xyz.qwewqa.relive.simulator.core.stage.Act
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff
import xyz.qwewqa.relive.simulator.core.stage.dress.DressCategory
import xyz.qwewqa.relive.simulator.core.stage.autoskill.new
import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint
import xyz.qwewqa.relive.simulator.core.stage.buff.*
import xyz.qwewqa.relive.simulator.core.stage.passive.*
import xyz.qwewqa.relive.simulator.core.stage.stageeffect.*
val dress = dress2030010(
name = "漂流者",
acts = listOf(
ActType.Act1.blueprint("強斬撃") {
Act {
/*
%attr%属性攻撃(威力%value%)
target: 前から1番目の敵役
hit_rate1: 100
values1: [147, 154, 161, 168, 176]
times1: 1
*/
}
},
ActType.Act2.blueprint("煌力の斬撃") {
Act {
/*
%attr%属性攻撃(威力%value%)
target: 前から1番目の敵役
hit_rate1: 100
values1: [129, 136, 141, 148, 155]
times1: 1
キラめき回復(%value%)
target: 自身
hit_rate2: 100
values2: [20, 20, 20, 20, 20]
times2: [0, 0, 0, 0, 0]
ACTパワーアップ(%value%)
target: 自身
hit_rate3: 100
values3: [20, 22, 24, 27, 30]
times3: [3, 3, 3, 3, 3]
*/
}
},
ActType.Act3.blueprint("勝利の協奏曲") {
Act {
/*
%attr%属性攻撃(威力%value%)
target: 前から1番目の敵役
hit_rate1: 100
values1: [165, 173, 181, 189, 198]
times1: 1
クリティカル率アップ(%value%)
target: 味方全体
hit_rate2: 100
values2: [10, 12, 14, 17, 20]
times2: [3, 3, 3, 3, 3]
有利属性ダメージアップ(%value%)
target: 味方全体
hit_rate3: 100
values3: [20, 22, 24, 27, 30]
times3: [3, 3, 3, 3, 3]
*/
}
},
ActType.ClimaxAct.blueprint("大物を狙え!") {
Act {
/*
%attr%属性攻撃(威力%value%) (ACTタイプ[通常]の敵役に特攻)
target: ACTパワーが1番高い敵役
hit_rate1: 100
values1: [307, 323, 338, 353, 369]
times1: [1, 1, 1, 1, 1]
*/
}
}
),
autoSkills = listOf(
listOf(
/*
auto skill 1:
与ダメージアップ(%value%)
target: 自身
values: [7, 7, 8, 9, 10]
*/
),
listOf(
/*
auto skill 2:
回避
target: 自身
hit_rate: 100
value: 0
time: 1
*/
),
listOf(
/*
auto skill 3:
有利属性ダメージアップ(%value%)
target: 自身
values: [10, 11, 12, 13, 15]
*/
),
),
unitSkill = null /* 立ち位置後の舞台少女のACTパワーアップ %opt1_value%%(MAX30%) クリティカル威力アップ %opt2_value%%(MAX30%) */,
multipleCA = false,
categories = setOf(),
)
*/
val dress2030010 = PartialDressBlueprint(
id = 2030010,
name = "漂流者",
baseRarity = 4,
cost = 12,
character = Character.Fumi,
attribute = Attribute.Moon,
damageType = DamageType.Special,
position = Position.Back,
positionValue = 34050,
stats = StatData(
hp = 963,
actPower = 191,
normalDefense = 50,
specialDefense = 83,
agility = 187,
dexterity = 5,
critical = 50,
accuracy = 0,
evasion = 0,
),
growthStats = StatData(
hp = 31720,
actPower = 3150,
normalDefense = 820,
specialDefense = 1380,
agility = 3090,
),
actParameters = mapOf(
ActType.Act1 to ActBlueprint(
name = "強斬撃",
type = ActType.Act1,
apCost = 2,
icon = 1,
parameters = listOf(
actParameters96,
actParameters1,
actParameters1,
actParameters1,
actParameters1,
),
),
ActType.Act2 to ActBlueprint(
name = "煌力の斬撃",
type = ActType.Act2,
apCost = 3,
icon = 89,
parameters = listOf(
actParameters36,
actParameters3,
actParameters32,
actParameters1,
actParameters1,
),
),
ActType.Act3 to ActBlueprint(
name = "勝利の協奏曲",
type = ActType.Act3,
apCost = 3,
icon = 20,
parameters = listOf(
actParameters44,
actParameters42,
actParameters32,
actParameters1,
actParameters1,
),
),
ActType.ClimaxAct to ActBlueprint(
name = "大物を狙え!",
type = ActType.ClimaxAct,
apCost = 2,
icon = 195,
parameters = listOf(
actParameters287,
actParameters1,
actParameters1,
actParameters1,
actParameters1,
),
),
),
autoSkillRanks = listOf(1, 4, 9, null),
autoSkillPanels = listOf(0, 0, 5, 0),
rankPanels = growthBoard3,
friendshipPanels = friendshipPattern0,
remakeParameters = listOf(
StatData(
hp = 6900,
actPower = 360,
normalDefense = 150,
specialDefense = 300,
agility = 180,
),
StatData(
hp = 11500,
actPower = 600,
normalDefense = 250,
specialDefense = 500,
agility = 300,
),
StatData(
hp = 18400,
actPower = 960,
normalDefense = 400,
specialDefense = 800,
agility = 480,
),
StatData(
hp = 23000,
actPower = 1200,
normalDefense = 500,
specialDefense = 1000,
agility = 600,
),
),
)
| 0 | Kotlin | 11 | 7 | 70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74 | 6,741 | relight | MIT License |
provider/src/main/kotlin/com/example/CreateClientCommand.kt | felix19350 | 311,480,556 | false | null | package com.example
import kotlinx.serialization.Serializable
@Serializable
data class CreateClientCommand(val firstName: String, val lastName: String, val age: Int) {
fun toClient(id: Long) = Client(
id = id,
firstName = firstName,
lastName = lastName,
age = age
)
fun validate(): Map<String, String> {
val errors: MutableMap<String, String> = mutableMapOf()
if (age < 0) {
errors["client.age.invalid"] = "The age should be a positive number"
}
if (firstName.isBlank() || firstName.isEmpty()) {
errors["client.firstName.invalid"] = "The first name cannot be blank of empty"
}
if (lastName.isBlank() || lastName.isEmpty()) {
errors["client.lastName.invalid"] = "The last name cannot be blank of empty"
}
return errors.toMap()
}
} | 0 | Kotlin | 0 | 1 | b1acda8fd81a103e5bfabdba5a73bb3e9af8cb7c | 885 | pact-ktor-example | MIT License |
remote-api-mock/src/main/java/reactivecircus/releaseprobe/remote/mock/di/MockApiModule.kt | ReactiveCircus | 142,655,149 | false | null | package reactivecircus.releaseprobe.remote.mock.di
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.dsl.module
import reactivecircus.releaseprobe.remote.artifact.api.GoogleMavenService
import reactivecircus.releaseprobe.remote.mock.BuildConfig.NETWORK_TIMEOUT_SECONDS
import reactivecircus.releaseprobe.remote.mock.artifact.api.MockGoogleMavenService
import retrofit2.Retrofit
import retrofit2.mock.MockRetrofit
import retrofit2.mock.NetworkBehavior
import java.util.concurrent.TimeUnit
private const val MOCK_SERVER_PORT = 5_000
private const val DUMMY_URL = "http://localhost:$MOCK_SERVER_PORT/"
val mockApiModule = module {
single {
OkHttpClient.Builder()
.callTimeout(NETWORK_TIMEOUT_SECONDS.toLong(), TimeUnit.SECONDS)
// add logging interceptor
.addInterceptor(
HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BASIC
}
)
.build()
}
single {
Retrofit.Builder()
.baseUrl(DUMMY_URL)
.client(get())
.build()
}
single {
NetworkBehavior.create().apply {
// make sure behavior is deterministic
setVariancePercent(0)
// no delay by default
setDelay(0, TimeUnit.MILLISECONDS)
// no failure by default
setFailurePercent(0)
}
}
single<GoogleMavenService> {
MockGoogleMavenService(
MockRetrofit.Builder(get())
.apply { networkBehavior(get()) }.build().create(GoogleMavenService::class.java)
)
}
}
| 7 | null | 4 | 8 | b97fb5b8f161f29b70db1de6446af76166f42aa4 | 1,684 | release-probe | MIT License |
samples/android/src/main/java/com/smellouk/kamper/samples/CpuActivity.kt | smellouk | 442,266,308 | false | null | package com.smellouk.kamper.samples
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.smellouk.kamper.Kamper
import com.smellouk.kamper.cpu.CpuInfo
import com.smellouk.kamper.cpu.CpuModule
class CpuActivity : AppCompatActivity() {
private var cpuWorkList: List<CpuWork> = emptyList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cpu)
lifecycle.addObserver(Kamper)
val cpuInfoTxt = findViewById<TextView>(R.id.infoTxt)
Kamper.apply {
install(CpuModule)
addInfoListener<CpuInfo> { cpuInfo ->
if (cpuInfo == CpuInfo.INVALID) return@addInfoListener
with(cpuInfo) {
cpuInfoTxt.text = "App: ${appRatio.toPercent()}" +
"\nTotal: ${totalUseRatio.toPercent()}" +
"\nUser: ${userRatio.toPercent()}" +
"\nSystem: ${systemRatio.toPercent()}" +
"\nIO Wait: ${ioWaitRatio.toPercent()}"
}
}
}
cpuWorkList = Utils.startHeavyWorkOnBackgroundThread()
}
override fun onDestroy() {
cpuWorkList.forEach { work -> work.cancel(true) }
super.onDestroy()
}
} | 8 | Kotlin | 0 | 31 | bbc4cad11c11e578a4017b04a1c66f51790a4e88 | 1,390 | kamper | Apache License 2.0 |
device/src/main/java/DeviceManager.kt | jessecollier | 238,049,769 | true | {"Kotlin": 90026, "Shell": 1030} | /*
* Copyright 2018 JUUL Labs, Inc.
*/
package com.juul.able.experimental.device
import android.bluetooth.BluetoothDevice
import com.juul.able.experimental.Able
import java.util.concurrent.ConcurrentHashMap
class DeviceManager {
private val wrapped = ConcurrentHashMap<BluetoothDevice, CoroutinesGattDevice>()
val bluetoothDevices
get() = wrapped.keys().toList()
val coroutinesGattDevices
get() = wrapped.values.toList()
fun wrapped(bluetoothDevice: BluetoothDevice): CoroutinesGattDevice =
wrapped.getOrPut(bluetoothDevice) {
CoroutinesGattDevice(bluetoothDevice)
}
fun remove(bluetoothDevice: BluetoothDevice): CoroutinesGattDevice? {
val removed = wrapped.remove(bluetoothDevice)
if (removed != null) {
removed.dispose()
} else {
Able.warn { "remove ← Bluetooth device $bluetoothDevice not found" }
}
return removed
}
operator fun minusAssign(bluetoothDevice: BluetoothDevice) {
remove(bluetoothDevice)
Able.debug { "close ← Remaining: ${wrapped.values}" }
}
}
| 0 | null | 0 | 0 | 2b16c54d6aaa5a93cc9890c41e36264bbc0323a1 | 1,131 | able | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DimensionReduction.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: DimensionReduction
*
* Full name: System`DimensionReduction
*
* DimensionReduction[{example , example , …}] generates a DimensionReducerFunction[…] that projects from the space defined by the example to a lower-dimensional approximating manifold.
* 1 2 i
* DimensionReduction[examples, n] generates a DimensionReducerFunction[…] for an n-dimensional approximating manifold.
* Usage: DimensionReduction[examples, n, props] generates the specified properties of the dimensionality reduction.
*
* FeatureExtractor -> Identity
* FeatureNames -> Automatic
* FeatureTypes -> Automatic
* FeatureWeights -> Automatic
* Method -> Automatic
* PerformanceGoal -> Automatic
* ProcessorCaching -> False
* RandomSeeding -> 1234
* RecordLog -> True
* TargetDevice -> CPU
* Options: Weights -> Automatic
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/DimensionReduction
* Documentation: web: http://reference.wolfram.com/language/ref/DimensionReduction.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun dimensionReduction(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("DimensionReduction", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 2,043 | mathemagika | Apache License 2.0 |
src/pt/mangalivre/src/eu/kanade/tachiyomi/extension/pt/mangalivre/MangaLivre.kt | tehandeh | 204,132,938 | true | {"Kotlin": 1462664, "Java": 4615, "Shell": 1729} | package eu.kanade.tachiyomi.extension.pt.mangalivre
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.HttpSource
import okhttp3.Response
import java.lang.Exception
class MangaLivre : HttpSource() {
override val name = "MangaLivre"
override val baseUrl = "https://mangalivre.com"
override val lang = "pt"
override val supportsLatest = true
override fun popularMangaRequest(page: Int) = throw Exception(NEED_MIGRATION)
override fun popularMangaParse(response: Response) = throw Exception(NEED_MIGRATION)
override fun latestUpdatesRequest(page: Int) = throw Exception(NEED_MIGRATION)
override fun latestUpdatesParse(response: Response) = throw Exception(NEED_MIGRATION)
override fun searchMangaRequest(page: Int, query: String, filters: FilterList) = throw Exception(NEED_MIGRATION)
override fun searchMangaParse(response: Response) = throw Exception(NEED_MIGRATION)
override fun mangaDetailsParse(response: Response) = throw Exception(NEED_MIGRATION)
override fun chapterListParse(response: Response) = throw Exception(NEED_MIGRATION)
override fun pageListParse(response: Response) = throw Exception(NEED_MIGRATION)
override fun imageUrlParse(response: Response) = throw Exception(NEED_MIGRATION)
companion object {
private const val NEED_MIGRATION = "Catálogo incorporado na nova versão da extensão mangásPROJECT."
}
}
| 0 | Kotlin | 0 | 1 | 46fa48d8d342daf4bc8f507ff62d98f2faa67e6a | 1,430 | tachiyomi-extensions | Apache License 2.0 |
app/src/main/java/edu/iu/eribecke/project3/end.kt | eribecke | 693,432,709 | false | {"Kotlin": 9686} | package edu.iu.eribecke.project3
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class end : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.results)
//getting information from questions class
val correct = intent.getIntExtra("Correct", 1)
val questionNum = intent.getIntExtra("qNum", 1)
val again = findViewById<Button>(R.id.again)
//creating variables for score
var score = findViewById<TextView>(R.id.score)
var displayScore = "$correct out of $questionNum"
//displaying the user's score
score.text = displayScore
//handles what happens when the "DO IT AGAIN" button is clicked
//Will bring user back to the menu screen
again.setOnClickListener {
val i = Intent(this, MainActivity::class.java)
startActivity(i)
}
}
} | 0 | Kotlin | 0 | 0 | 7b02b081ba472035c34497805498b9f67fc2939d | 1,075 | Project3-Arithmetic | Apache License 2.0 |
getenv/src/wasmWasiMain/kotlin/io/getenv.wasmWasi.kt | luca992 | 606,858,479 | false | {"Kotlin": 3282} | package io
import kotlin.wasm.unsafe.UnsafeWasmMemoryApi
import kotlin.wasm.unsafe.withScopedMemoryAllocator
@OptIn(UnsafeWasmMemoryApi::class)
public actual fun getenv(name: String): String? {
withScopedMemoryAllocator { allocator ->
val environCountPtr = allocator.allocate(4)
val environBufSizePtr = allocator.allocate(4)
val resultSizes = wasiEnvironSizesGet(environCountPtr.address.toInt(), environBufSizePtr.address.toInt())
if (resultSizes != 0) error("wasi error code: $resultSizes")
val environCount = environCountPtr.loadInt()
val environBufSize = environBufSizePtr.loadInt()
val environPtrs = allocator.allocate(environCount * 4)
val environBuf = allocator.allocate(environBufSize)
val resultEnviron = wasiEnvironGet(environPtrs.address.toInt(), environBuf.address.toInt())
if (resultEnviron != 0) error("wasi error code: $resultEnviron")
// Parse the environ buffer and split into environment variables
val envVars = mutableListOf<String>()
var currentVar = StringBuilder()
for (i in 0 until environBufSize) {
val byte = (environBuf + i).loadByte()
if (byte.toInt() == 0) {
envVars.add(currentVar.toString())
currentVar = StringBuilder()
} else {
currentVar.append(byte.toInt().toChar())
}
}
// Search for the requested environment variable by name
for (envVar in envVars) {
val (key, value) = envVar.split('=', limit = 2)
if (key == name) {
return value
}
}
}
return null
}
| 0 | Kotlin | 0 | 4 | 039fc8ec6aca5cc9ee48cd1ce6bd0911fbd6d565 | 1,699 | getenv-kt | MIT License |
src/main/kotlin/com/github/shmvanhouten/adventofcode/day15timingiseverything/DiscMachineBuilder.kt | SHMvanHouten | 109,886,692 | false | {"Kotlin": 616528} | package com.github.shmvanhouten.adventofcode.day15timingiseverything
class DiscMachineBuilder {
fun build(rawInput: String): DiscMachine {
var discMachine = DiscMachine()
val instructionList = rawInput.split("\n")
for (instruction in instructionList) {
discMachine = discMachine.addDisc(buildDiscFromInstruction(instruction))
}
return discMachine
}
private fun buildDiscFromInstruction(instruction: String): Disc {
val splitInstruction = instruction.split(" ")
val amountOfPossiblePositions = splitInstruction[3].toInt()
val currentPosition = splitInstruction[11].substring(0, splitInstruction[11].lastIndex).toInt()
return Disc(amountOfPossiblePositions, currentPosition)
}
} | 0 | Kotlin | 0 | 0 | a8abc74816edf7cd63aae81cb856feb776452786 | 780 | adventOfCode2016 | MIT License |
src/main/kotlin/com/github/shmvanhouten/adventofcode/day15timingiseverything/DiscMachineBuilder.kt | SHMvanHouten | 109,886,692 | false | {"Kotlin": 616528} | package com.github.shmvanhouten.adventofcode.day15timingiseverything
class DiscMachineBuilder {
fun build(rawInput: String): DiscMachine {
var discMachine = DiscMachine()
val instructionList = rawInput.split("\n")
for (instruction in instructionList) {
discMachine = discMachine.addDisc(buildDiscFromInstruction(instruction))
}
return discMachine
}
private fun buildDiscFromInstruction(instruction: String): Disc {
val splitInstruction = instruction.split(" ")
val amountOfPossiblePositions = splitInstruction[3].toInt()
val currentPosition = splitInstruction[11].substring(0, splitInstruction[11].lastIndex).toInt()
return Disc(amountOfPossiblePositions, currentPosition)
}
} | 0 | Kotlin | 0 | 0 | a8abc74816edf7cd63aae81cb856feb776452786 | 780 | adventOfCode2016 | MIT License |
app/src/main/java/com/mvaresedev/pokeapp/data/db/mapper/DatabaseMapperImpl.kt | mirkcode | 317,342,198 | false | {"Kotlin": 46346} | package com.mvaresedev.pokeapp.data.db.mapper
import com.mvaresedev.pokeapp.data.db.entities.PokemonEntity
import com.mvaresedev.pokeapp.domain.mapper.DatabaseMapper
import com.mvaresedev.pokeapp.domain.models.Pokemon
class DatabaseMapperImpl : DatabaseMapper {
override fun mapPokemonEntityToDomain(entity: PokemonEntity): Pokemon {
return Pokemon(
id = entity.id,
name = entity.name,
iconUrl = entity.iconUrl,
bigIconUrl = entity.bigIconUrl,
weight = entity.weight,
height = entity.height,
ability = entity.ability,
types = entity.types,
stats = entity.stats
)
}
override fun mapPokemonDomainToEntities(source: List<Pokemon>): List<PokemonEntity> {
return source.map {
PokemonEntity(
id = it.id,
name = it.name,
iconUrl = it.iconUrl,
bigIconUrl = it.bigIconUrl,
weight = it.weight,
height = it.height,
ability = it.ability,
types = it.types,
stats = it.stats
)
}
}
} | 0 | Kotlin | 1 | 18 | 1582c57beb0b4d94f4e5989791bd59ee3cc418c1 | 1,197 | pokeapp | Apache License 2.0 |
logs-core/src/main/kotlin/gma/logs/app/controller/logsinstance/LogsTabViewModel.kt | gilmay | 351,920,603 | false | null | package gma.logs.app.controller.logsinstance
import tornadofx.*
import java.time.Duration
import java.time.LocalDateTime
class LogsTabViewModel : ViewModel() {
override val scope = super.scope as LogsScope
val fromProperty = bind { scope.fromProperty }.apply { onChange { validationContext.validate() } }
val toProperty = bind { scope.toProperty }.apply { onChange { validationContext.validate() } }
val criteriaStringProperty =
bind { scope.criteriaStringProperty }.apply { onChange { validationContext.validate() } }
fun refresh() = scope.refresh()
init {
// Empty Model is initially dirty
runLater {
if (toProperty.value == null || fromProperty.value == null) {
toProperty.value = LocalDateTime.now().withNano(0)
fromProperty.value = toProperty.value.minus(Duration.ofMinutes(15))
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6710339183703c55833e67f82ba12d7141b0cde6 | 915 | logs | Apache License 2.0 |
app/src/main/kotlin/de/markusfisch/android/screentime/graphics/MultiDayChart.kt | markusfisch | 439,125,216 | false | {"Kotlin": 57503, "Shell": 1811, "Makefile": 531} | package de.markusfisch.android.screentime.graphics
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.Rect
import de.markusfisch.android.screentime.app.db
import de.markusfisch.android.screentime.app.prefs
import de.markusfisch.android.screentime.database.DAY_IN_MS
import java.util.Calendar
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
class MultiDayChart(
val width: Int,
private val dp: Float,
private val days: Int,
private val usagePaint: Paint,
private val textPaint: Paint,
private val usageDotPaint: Paint,
private val monthColor: Int
) {
private val linePaint = Paint(textPaint).also { it.strokeWidth = 1f }
private val linePaintBold = Paint(linePaint).also { it.strokeWidth = 2f }
private val monthLinePaint =
Paint(linePaintBold).also { it.strokeWidth = 4f; it.color = monthColor }
private val textBounds = Rect()
private val dayHeight = (24 * dp).roundToInt()
private val padding = (12 * dp).roundToInt()
private val offsetY = (32 * dp).roundToInt()
private val bitmapA = Bitmap.createBitmap(
width,
dayHeight * days + offsetY + padding,
Bitmap.Config.ARGB_8888
)
private val bitmapB = bitmapA.copy(bitmapA.config, true)
private var even = true
fun draw(timestamp: Long): Bitmap = nextBitmap().apply {
Canvas(this).apply {
drawColor(0, PorterDuff.Mode.CLEAR)
drawAt(timestamp)
}
}
private fun nextBitmap(): Bitmap {
// Double buffering to avoid modifying the
// currently displayed bitmap.
even = even xor true
return if (even) bitmapA else bitmapB
}
private fun Canvas.drawAt(timestamp: Long) {
val dayStarts = LongArray(days + 1) { 0 }
var to = prefs.dayStart(timestamp)
for (i in 1..48) {
to = prefs.dayStart(timestamp + i * DAY_IN_MS / 24)
if (to > timestamp) {
break
}
}
var from = to
for (i in 0..days) {
dayStarts[days - i] = from
from = prefs.dayStart(from - 1)
}
drawRecords(dayStarts)
drawHours(prefs.hourOfDayChange)
drawDays(dayStarts)
}
private fun Canvas.drawHours(hourOffset: Int) {
val width = this.width - padding * 2
val height = days * dayHeight
val hours = 24
for (i in 0..hours) {
val x = (i * width / hours + padding).toFloat()
val h = (i + hourOffset) % 24
val paint = when (h % 6 == 0) {
true -> linePaintBold
false -> linePaint
}
if (h % 3 == 0) {
drawTextCenteredAbove("$h", x, offsetY.toFloat())
}
drawLine(x, offsetY.toFloat(), x, (height + offsetY).toFloat(), paint)
}
}
private fun Canvas.drawDays(dayStarts: LongArray) {
val sX = (padding).toFloat()
val eX = (width - padding).toFloat()
val calendar = Calendar.getInstance()
for (d in 0..days) {
val y = d * dayHeight + offsetY
calendar.timeInMillis = dayStarts[days - d]
val paint = if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
monthLinePaint
} else if (calendar.get(Calendar.DAY_OF_WEEK) == calendar.firstDayOfWeek) {
linePaintBold
} else {
linePaint
}
drawLine(sX, y.toFloat(), eX, y.toFloat(), paint)
}
}
/* Q: Why do we iterate over the days?
* A: Because not all days have 24h hours - daytime change. */
private fun Canvas.drawRecords(dayStarts: LongArray) {
val dayUsage = LongArray(days) { 0 }
val dayLastTimestamp = LongArray(days) { 0 }
val minimumDurationLengthen = prefs.minDurationLengthenValue().toLong()
val width = this.width - padding * 2
val drawInOneDay = fun(day: Int, start: Long, end: Long) {
val dayFromTop = days - 1 - day
/* This happened with daytime change. It should be fixed, but if it happens again,
* the app will not crash. */
if (dayFromTop < 0) {
return
}
val s = max(start, dayLastTimestamp[dayFromTop])
if (s <= end) {
dayUsage[dayFromTop] += end - s
dayLastTimestamp[dayFromTop] = end
val e = min(end, DAY_IN_MS)
val top = dayFromTop * dayHeight + offsetY
val bottom = (dayFromTop + 1) * dayHeight + offsetY
val left = (s * width / DAY_IN_MS + padding).toInt()
val right = (e * width / DAY_IN_MS + padding).toInt()
drawRect(Rect(left, top, right, bottom), usagePaint)
}
}
var day = 0
db.forEachRecordBetween(dayStarts.first(), dayStarts.last()) { start, duration ->
while (start > dayStarts[day + 1]) {
day++
}
val end = start + max(duration, minimumDurationLengthen)
var dayE = day
while (end > (dayStarts.getOrNull(dayE + 1) ?: end)) {
dayE++
}
val s = start - dayStarts[day]
val e = end - dayStarts[dayE]
if (day == dayE) {
drawInOneDay(day, s, e)
} else {
drawInOneDay(day, s, dayStarts[day + 1] - dayStarts[day])
for (d in (day + 1)..<dayE) {
drawInOneDay(dayE, 0, dayStarts[d + 1] - dayStarts[d])
}
drawInOneDay(dayE, 0, e)
}
}
for (d in 0..<days) {
drawCircle(
(padding + min(dayUsage[d], DAY_IN_MS) * width / DAY_IN_MS).toFloat(),
offsetY + dayHeight * (d + 0.5f),
dayHeight / 6f,
usageDotPaint
)
}
}
private fun Canvas.drawTextCenteredAbove(
text: String,
x: Float,
y: Float
) {
textPaint.textSize = 12f * dp
textPaint.getTextBounds(text, 0, text.length, textBounds)
drawText(
text,
x - textBounds.centerX().toFloat(),
y - textBounds.height().toFloat(),
textPaint
)
}
}
| 16 | Kotlin | 9 | 94 | 61950468792b7ed5af862c7dc0109442247683ee | 5,360 | ScreenTime | The Unlicense |
src/main/kotlin/dev/igalaxy/comet/modules/discord/CometDiscordModule.kt | iGalaxyYT | 620,156,462 | false | null | package dev.igalaxy.comet.modules.discord
import com.jagrosh.discordipc.IPCClient
import com.jagrosh.discordipc.entities.RichPresence
import com.jagrosh.discordipc.entities.pipe.PipeStatus
import dev.igalaxy.comet.Comet
import dev.igalaxy.comet.modules.CometModule
import org.quiltmc.loader.api.QuiltLoader
import org.quiltmc.qsl.lifecycle.api.client.event.ClientLifecycleEvents
object CometDiscordModule : CometModule {
override val enabled: Boolean
get() = Comet.CONFIG.discordEnabled
private val client = IPCClient(Comet.CONFIG.discordClient.toLong())
private val startTimestamp = System.currentTimeMillis()
init {
client.setListener(CometDiscordIPCListener())
checkClient()
ClientLifecycleEvents.Stopping {
if (client.status == PipeStatus.CONNECTED) {
client.close()
}
}
}
fun checkClient() {
if (enabled) {
client.connect()
} else {
if (client.status == PipeStatus.CONNECTED) {
client.close()
}
}
}
fun clientReady() {
val minecraftVersion = QuiltLoader.getNormalizedGameVersion()
val quiltVersion = QuiltLoader.getModContainer("quilt_loader").get().metadata().version().raw()
val builder = RichPresence.Builder()
builder
.setStartTimestamp(startTimestamp)
.setLargeImage("grass_block", "Minecraft $minecraftVersion")
.setSmallImage("quilt", "Quilt Loader $quiltVersion")
client?.sendRichPresence(builder.build())
}
}
| 0 | Kotlin | 0 | 0 | d8361bc0664af5688214c48b965f2713ae9e7651 | 1,600 | comet | MIT License |
app/src/main/java/mil/nga/msi/datasource/UserDatabase.kt | ngageoint | 588,211,646 | false | {"Kotlin": 1749335} | package mil.nga.msi.datasource
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import mil.nga.msi.datasource.bookmark.Bookmark
import mil.nga.msi.datasource.bookmark.BookmarkDao
@Database(
version = UserDatabase.VERSION,
entities = [
Bookmark::class
]
)
@TypeConverters(
DateTypeConverter::class
)
abstract class UserDatabase : RoomDatabase() {
companion object {
const val VERSION = 1
}
abstract fun bookmarkDao(): BookmarkDao
} | 0 | Kotlin | 0 | 0 | 52dbebc53d32dd93655a0e723c27f521f48a5bbf | 518 | marlin-android | MIT License |
desktop/src/main/kotlin/nebulosa/desktop/view/atlas/Twilight.kt | tiagohm | 568,578,345 | false | null | package nebulosa.desktop.view.atlas
data class Twilight(
override val start: Double,
override val endInclusive: Double,
) : ClosedFloatingPointRange<Double> {
override fun isEmpty() = start >= endInclusive
override fun lessThanOrEquals(a: Double, b: Double) = a <= b
companion object {
@JvmStatic val EMPTY = Twilight(0.0, 0.0)
}
}
| 0 | Kotlin | 0 | 0 | 57780ec339ff4e3ec8d1965b7ddef7879861a814 | 369 | nebulosa | MIT License |
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/medium/CargoBikeMedium.kt | SchweizerischeBundesbahnen | 853,290,161 | false | {"Kotlin": 6728512} | package ch.sbb.compose_mds.sbbicons.medium
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import ch.sbb.compose_mds.sbbicons.MediumGroup
public val MediumGroup.CargoBikeMedium: ImageVector
get() {
if (_cargoBikeMedium != null) {
return _cargoBikeMedium!!
}
_cargoBikeMedium = Builder(name = "CargoBikeMedium", defaultWidth = 36.0.dp, defaultHeight =
36.0.dp, viewportWidth = 36.0f, viewportHeight = 36.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(12.0f, 12.25f)
horizontalLineToRelative(2.75f)
verticalLineToRelative(3.0f)
horizontalLineToRelative(13.377f)
lineToRelative(0.104f, 0.363f)
curveToRelative(0.21f, 0.734f, 0.46f, 1.705f, 0.696f, 2.652f)
arcToRelative(3.503f, 3.503f, 0.0f, false, true, 3.823f, 3.485f)
curveToRelative(0.0f, 1.93f, -1.57f, 3.5f, -3.5f, 3.5f)
curveToRelative(-1.931f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
curveToRelative(0.0f, -1.473f, 0.913f, -2.736f, 2.204f, -3.252f)
curveToRelative(-0.163f, -0.656f, -0.333f, -1.32f, -0.49f, -1.906f)
curveToRelative(-1.268f, 0.975f, -2.755f, 2.231f, -3.992f, 3.305f)
arcToRelative(170.0f, 170.0f, 0.0f, false, false, -2.32f, 2.05f)
lineToRelative(-0.142f, 0.129f)
lineToRelative(-0.036f, 0.033f)
lineToRelative(-0.01f, 0.008f)
lineToRelative(-0.002f, 0.002f)
lineToRelative(-0.337f, -0.369f)
lineToRelative(0.336f, 0.37f)
lineToRelative(-0.143f, 0.13f)
lineTo(10.215f, 22.25f)
arcToRelative(3.505f, 3.505f, 0.0f, false, true, -3.465f, 3.0f)
curveToRelative(-1.931f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
arcToRelative(3.503f, 3.503f, 0.0f, false, true, 5.005f, -3.16f)
lineTo(9.25f, 17.1f)
lineTo(9.25f, 14.75f)
lineTo(7.5f, 14.75f)
verticalLineToRelative(-1.0f)
horizontalLineToRelative(2.75f)
verticalLineToRelative(3.651f)
lineToRelative(-0.084f, 0.126f)
lineToRelative(-1.08f, 1.62f)
arcToRelative(3.5f, 3.5f, 0.0f, false, true, 1.128f, 2.103f)
horizontalLineToRelative(3.536f)
verticalLineToRelative(-8.0f)
lineTo(12.0f, 13.25f)
close()
moveTo(9.2f, 21.25f)
arcToRelative(2.5f, 2.5f, 0.0f, false, false, -0.676f, -1.26f)
lineToRelative(-0.84f, 1.26f)
close()
moveTo(7.693f, 19.435f)
arcTo(2.503f, 2.503f, 0.0f, false, false, 4.25f, 21.75f)
curveToRelative(0.0f, 1.378f, 1.121f, 2.5f, 2.5f, 2.5f)
curveToRelative(1.207f, 0.0f, 2.217f, -0.86f, 2.45f, -2.0f)
lineTo(5.816f, 22.25f)
lineToRelative(0.518f, -0.777f)
close()
moveTo(28.233f, 19.637f)
lineTo(28.196f, 19.483f)
arcToRelative(2.5f, 2.5f, 0.0f, false, false, -1.446f, 2.267f)
curveToRelative(0.0f, 1.378f, 1.121f, 2.5f, 2.5f, 2.5f)
curveToRelative(1.378f, 0.0f, 2.5f, -1.122f, 2.5f, -2.5f)
arcToRelative(2.503f, 2.503f, 0.0f, false, false, -2.58f, -2.499f)
lineToRelative(0.036f, 0.15f)
arcToRelative(260.0f, 260.0f, 0.0f, false, true, 0.49f, 2.062f)
lineToRelative(0.03f, 0.129f)
lineToRelative(0.008f, 0.034f)
lineToRelative(0.002f, 0.008f)
lineToRelative(0.001f, 0.003f)
lineToRelative(-0.487f, 0.113f)
lineToRelative(-0.487f, 0.113f)
verticalLineToRelative(-0.003f)
lineToRelative(-0.003f, -0.008f)
lineToRelative(-0.007f, -0.034f)
lineToRelative(-0.03f, -0.128f)
arcToRelative(253.0f, 253.0f, 0.0f, false, false, -0.49f, -2.053f)
moveTo(14.75f, 21.25f)
horizontalLineToRelative(5.682f)
lineToRelative(0.05f, -0.045f)
lineToRelative(0.532f, -0.477f)
curveToRelative(0.452f, -0.404f, 1.084f, -0.963f, 1.802f, -1.587f)
curveToRelative(1.058f, -0.917f, 2.311f, -1.98f, 3.461f, -2.891f)
lineTo(14.75f, 16.25f)
close()
}
}
.build()
return _cargoBikeMedium!!
}
private var _cargoBikeMedium: ImageVector? = null
| 0 | Kotlin | 0 | 1 | 090a66a40e1e5a44d4da6209659287a68cae835d | 5,368 | mds-android-compose | MIT License |
Ejemplos Kotlin/minip equipos futbol/src/Equipo.kt | Elkillax7 | 129,775,667 | false | null | open class Equipo (nombreEquipo: String, categoriaEquipo: String, numeroJugadores: Int){
} | 0 | Kotlin | 0 | 0 | 19052802eaab8eb60e53444f03bfd6629193bafc | 93 | Aplicaciones-Moviles | MIT License |
camunda-example-domain/src/main/kotlin/br/com/camunda/example/domain/model/Credit.kt | ricardofpu | 146,937,534 | false | null | package br.com.camunda.example.domain.model
import br.com.camunda.example.domain.converter.PaymentTypeConverter
import br.com.camunda.example.domain.entity.DBEntityOnlyCreate
import br.com.camunda.example.domain.enums.PaymentType
import com.fasterxml.jackson.annotation.JsonIgnore
import org.hibernate.annotations.GenericGenerator
import java.math.BigDecimal
import javax.persistence.Convert
import javax.persistence.Entity
import javax.persistence.FetchType
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.Table
import javax.validation.constraints.NotNull
@Entity
@Table(name = "credit")
data class Credit(
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
val id: String = "",
val transactionId: String,
val origin: String,
val description: String? = null,
val valueAmount: Long,
val valueScale: Int,
val valueCurrency: String,
@Convert(converter = PaymentTypeConverter::class)
val type: PaymentType = PaymentType.CREDIT,
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "account_id")
@NotNull
val account: Account
) : DBEntityOnlyCreate() {
fun getAmountAsBigDecimal(): BigDecimal = BigDecimal.valueOf(valueAmount, valueScale)
}
| 0 | Kotlin | 0 | 1 | 1e4179db133ce38e9c86f548887bfd55737a732d | 1,418 | spring-boot-camunda-example | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/manageusersapi/resource/prison/UserRolesControllerTest.kt | ministryofjustice | 406,273,579 | false | {"Kotlin": 501698, "Shell": 7027, "Dockerfile": 1110} | package uk.gov.justice.digital.hmpps.manageusersapi.resource.prison
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import uk.gov.justice.digital.hmpps.manageusersapi.model.PrisonCaseload
import uk.gov.justice.digital.hmpps.manageusersapi.model.PrisonCaseloadRole
import uk.gov.justice.digital.hmpps.manageusersapi.model.PrisonRole
import uk.gov.justice.digital.hmpps.manageusersapi.model.PrisonRoleType
import uk.gov.justice.digital.hmpps.manageusersapi.model.PrisonUsageType
import uk.gov.justice.digital.hmpps.manageusersapi.model.PrisonUserRole
import uk.gov.justice.digital.hmpps.manageusersapi.service.prison.UserRolesService
class UserRolesControllerTest {
private val userRolesService: UserRolesService = mock()
private val userRolesController = UserRolesController(userRolesService)
@Test
fun `get user roles`() {
whenever(userRolesService.getUserRoles("SOME_USER")).thenReturn(createPrisonUserRole())
val userRoles = userRolesController.getUserRoles("SOME_USER")
verify(userRolesService).getUserRoles("SOME_USER")
assertThat(userRoles).isEqualTo(UserRoleDetail.fromDomain(createPrisonUserRole()))
verifyContentMatches(userRoles)
}
private fun verifyContentMatches(actualUserRoles: UserRoleDetail) {
val expectedRoles = createPrisonUserRole()
with(expectedRoles) {
assertThat(actualUserRoles.username).isEqualTo(username)
assertThat(actualUserRoles.active).isEqualTo(active)
assertThat(actualUserRoles.accountType.name).isEqualTo(accountType.name)
assertThat(actualUserRoles.activeCaseload!!.id).isEqualTo(activeCaseload!!.id)
assertThat(actualUserRoles.activeCaseload!!.name).isEqualTo(activeCaseload!!.name)
assertThat(actualUserRoles.dpsRoles.size).isEqualTo(dpsRoles.size)
assertThat(actualUserRoles.dpsRoles[0].name).isEqualTo(dpsRoles[0].name)
assertThat(actualUserRoles.dpsRoles[0].code).isEqualTo(dpsRoles[0].code)
assertThat(actualUserRoles.dpsRoles[0].sequence).isEqualTo(dpsRoles[0].sequence)
assertThat(actualUserRoles.dpsRoles[0].type!!.name).isEqualTo(dpsRoles[0].type!!.name)
assertThat(actualUserRoles.dpsRoles[0].adminRoleOnly).isEqualTo(dpsRoles[0].adminRoleOnly)
assertThat(actualUserRoles.nomisRoles!!.size).isEqualTo(nomisRoles!!.size)
assertThat(actualUserRoles.nomisRoles!![0].roles.size).isEqualTo(nomisRoles!![0].roles.size)
assertThat(actualUserRoles.nomisRoles!![0].roles[0].name).isEqualTo(nomisRoles!![0].roles[0].name)
assertThat(actualUserRoles.nomisRoles!![0].roles[0].code).isEqualTo(nomisRoles!![0].roles[0].code)
assertThat(actualUserRoles.nomisRoles!![0].roles[0].sequence).isEqualTo(nomisRoles!![0].roles[0].sequence)
assertThat(actualUserRoles.nomisRoles!![0].roles[0].type!!.name).isEqualTo(nomisRoles!![0].roles[0].type!!.name)
assertThat(actualUserRoles.nomisRoles!![0].roles[0].adminRoleOnly).isEqualTo(nomisRoles!![0].roles[0].adminRoleOnly)
}
}
private fun createPrisonUserRole(): PrisonUserRole {
val activePrisonCaseload =
PrisonCaseload("TESTING-1234", "TEST-CASELOAD-1")
val prisonRoles = listOf(
PrisonRole(
"test-code",
"test-role",
1,
PrisonRoleType.APP,
false,
null,
),
PrisonRole(
"test-code-2",
"test-role-22",
1,
PrisonRoleType.APP,
false,
null,
),
)
val nomisRoles = listOf(
PrisonCaseloadRole(
activePrisonCaseload,
prisonRoles,
),
)
return PrisonUserRole(
"SOME_USER",
true,
PrisonUsageType.GENERAL,
activePrisonCaseload,
prisonRoles,
nomisRoles,
)
}
}
| 3 | Kotlin | 0 | 0 | cf34b212f7c1bcbb6cfc4d634b42f3fb2ba2b726 | 3,841 | hmpps-manage-users-api | MIT License |
app/src/main/java/project/penadidik/geocoding/ui/search/SearchModelMapper.kt | penadidik | 562,671,216 | false | null | package project.penadidik.geocoding.ui.search
import project.penadidik.geocoding.base.BaseMapper
import project.penadidik.geocoding.domain.model.Direct
import javax.inject.Inject
class SearchModelMapper @Inject constructor() : BaseMapper<Direct, SearchModel> {
override fun mapToPresentation(model: Direct): SearchModel {
val searchModel = SearchModel()
searchModel.apply {
name = model.name
lat = model.lat
lon = model.lon
country = model.country
state = model.state
}
return searchModel
}
override fun mapToDomain(modelItem: SearchModel): Direct {
val direct = Direct()
direct.apply {
name = modelItem.name
lat = modelItem.lat
lon = modelItem.lon
country = modelItem.country
state = modelItem.state
}
return direct
}
} | 0 | Kotlin | 0 | 0 | 48896b285bc1e7fbe73221b5140008a46ae1ee74 | 927 | Geocoding | Apache License 2.0 |
src/main/kotlin/io/github/thiagoddsilva/memorycache/CacheItem.kt | thiagoddsilva | 812,049,522 | false | {"Kotlin": 9092} | package io.github.thiagoddsilva.memorycache
import kotlin.time.Duration
enum class ExpirationMode {
ABSOLUTE,
SLIDING,
NONE
}
class CacheItem(val key: String,
val value: Any,
val duration: Duration?,
val expirationMode: ExpirationMode) {
private val creationTime = System.currentTimeMillis()
private var lastAccessTime = creationTime
fun isExpired(): Boolean {
if (duration == null) {
return false
}
if (expirationMode == ExpirationMode.SLIDING) {
return System.currentTimeMillis() - lastAccessTime > duration.inWholeMilliseconds
}
return System.currentTimeMillis() - creationTime > duration.inWholeMilliseconds
}
fun updateLastAccessTime() {
lastAccessTime = System.currentTimeMillis()
}
} | 0 | Kotlin | 0 | 0 | eaab1d774239a3776de30a6d01385ac5ea9b6915 | 854 | memorycache | MIT License |
task-impl/src/main/java/kasem/sm/task_impl/TaskImpl.kt | kasem-sm | 456,508,892 | false | {"Kotlin": 432676, "Procfile": 53, "Shell": 10} | /*
* Copyright (C) 2022, <NAME>
* All rights reserved.
*/
package kasem.sm.task_impl
import javax.inject.Inject
import kasem.sm.article.daily_read_worker.DailyReadManager
import kasem.sm.authentication.auth_verify_worker.CheckAuthenticationManager
import kasem.sm.task_api.Tasks
import kasem.sm.topic.subscription_manager_worker.ClearSubscriptionLocallyManager
import kasem.sm.topic.subscription_manager_worker.SubscribeTopicManager
import kotlinx.coroutines.flow.Flow
class TaskImpl @Inject constructor(
private val dailyReadManager: DailyReadManager,
private val subscribeTopicManager: SubscribeTopicManager,
private val authenticationManager: CheckAuthenticationManager,
private val clearSubscriptionLocallyManager: ClearSubscriptionLocallyManager
) : Tasks {
override fun executeDailyReader() = dailyReadManager.execute()
override fun executeAuthenticationVerifier() = authenticationManager.execute()
override fun clearUserSubscriptionLocally() = clearSubscriptionLocallyManager.execute()
override fun updateSubscriptionStatus(ids: List<String>): Flow<Result<Unit>> {
return subscribeTopicManager.updateSubscriptionStatus(ids)
}
}
| 25 | Kotlin | 49 | 570 | 02543400476bac4248914c5e943ef58bac5a318a | 1,187 | SlimeKT | Apache License 2.0 |
core/src/main/java/com/oscarg798/amiibowiki/core/models/AgeRating.kt | oscarg798 | 275,942,605 | false | null | /*
* Copyright 2020 Oscar David Gallon Rosero
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
package com.oscarg798.amiibowiki.core.models
sealed class AgeRatingCategory {
object ESRB : AgeRatingCategory()
object PEGI : AgeRatingCategory()
companion object {
fun getCategory(categoryId: Int) = when (categoryId) {
1 -> ESRB
else -> PEGI
}
}
}
sealed class Rating(val id: Int) {
object PEGI3 : Rating(1)
object PEGI7 : Rating(2)
object PEGI12 : Rating(3)
object PEGI16 : Rating(4)
object PEGI18 : Rating(5)
object ESRBRatingPending : Rating(6)
object ESRBEC : Rating(7)
object ESRBEveryone : Rating(8)
object ESRB10 : Rating(9)
object ESRBTeen : Rating(10)
object ESRBMature : Rating(11)
object ESRBAdultsOnly : Rating(12)
companion object {
fun getRating(rating: Int) = when (rating) {
1 -> PEGI3
2 -> PEGI7
3 -> PEGI12
4 -> PEGI16
5 -> PEGI18
6 -> ESRBRatingPending
7 -> ESRBEC
8 -> ESRBEveryone
9 -> ESRB10
10 -> ESRBTeen
11 -> ESRBMature
else -> ESRBAdultsOnly
}
}
}
data class AgeRating(
val category: AgeRatingCategory,
val rating: Rating
)
| 0 | Kotlin | 3 | 10 | e3f7f3f97af3ffb4998a3e8d4cb2144c82a5221c | 2,337 | AmiiboWiki | MIT License |
flx/src/main/java/org/fuusio/flx/core/repl/FlxRepl.kt | Fuusio | 337,071,263 | false | null | /*
* Copyright (C) 2016 - 2021 <NAME>
*
* http://fuusio.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fuusio.flx.core.repl
import org.fuusio.flx.Flx
import org.fuusio.flx.core.*
import org.fuusio.flx.core.error.FlxException
import org.fuusio.flx.core.error.FlxRuntimeException
import org.fuusio.flx.core.parser.FormParser
import org.fuusio.flx.core.parser.ParserError
import org.fuusio.flx.core.parser.ParserObserver
import org.fuusio.flx.core.parser.ParsingContext
import org.fuusio.flx.core.vm.Ctx
class FlxRepl(val ctx: Ctx = Flx.ctx) {
fun parse(string: String, observer: ParserObserver): List<Any> =
FormParser(observer).parse(ParsingContext(), string)
fun eval(string: String, parseObserver: ParserObserver = createObserver()): Any {
val forms = parse(string, parseObserver)
var value: Any = Null
forms.forEach { form -> value = form.eval(ctx) }
return value
}
fun eval(forms: List<Any>): Any {
var value: Any = Null
try {
forms.forEach { form -> value = form.eval(ctx) }
} catch (exception: FlxException) {
// exception.printStackTrace()
ctx.onException(exception)
} catch (exception: Exception) {
//exception.printStackTrace()
ctx.onException(FlxRuntimeException(ctx, exception))
}
return value
}
private fun createObserver() = object : ParserObserver {
override fun onNext(parsingResult: Any) {
// TODO
}
override fun onError(error: ParserError) {
// TODO
}
}
} | 0 | Kotlin | 0 | 9 | 2c37b6c1cf3618f24e991ee764e1e28bf75c85d0 | 2,142 | flx-lisp | Apache License 2.0 |
domain/src/test/java/br/com/lucascordeiro/pokedex/GetPokemonListUseCaseTest.kt | lucas-cordeiro | 293,281,734 | false | null | package br.com.lucascordeiro.pokedex
import br.com.lucascordeiro.pokedex.domain.model.Result
import br.com.lucascordeiro.pokedex.domain.usecase.GetPokemonListUseCaseImpl
import br.com.lucascordeiro.pokedex.helper.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertTrue
import org.junit.Test
class GetPokemonListUseCaseTest {
private val pokemonRepository = FakePokemonRepository()
private val useCase = GetPokemonListUseCaseImpl(
pokemonRepository = pokemonRepository,
errorHandler = FakeErrorHandler()
)
@Test
fun isValidDatabase(){
runBlockingTest {
assertTrue(pokemonRepository.getPokemonsFromDatabase(0,0).first().isEmpty())
val charmander = pokemonRepository.getPokemonByIdFromNetwork(1).first()!!
pokemonRepository.insertPokemonToDatabase(charmander)
assertTrue(pokemonRepository.getPokemonsFromDatabase(0,0).first().size == 1)
}
}
@Test
fun isValidPokemonListUseCase(){
runBlockingTest {
val result = useCase.getPokemons(0,3).first()
assertTrue(result is Result.Success)
val pokemons = (result as Result.Success).data
assertTrue(pokemons.size == 6)
}
}
} | 0 | Kotlin | 2 | 8 | 776241f3c5d142917178cbc48f7fc4b159b93513 | 1,308 | PokedexCompose | MIT License |
app/src/main/java/com/dreamsoftware/tvnexa/ui/features/profiles/blocking/ProfileBlockingChannelsViewModel.kt | sergio11 | 328,373,511 | false | {"Kotlin": 586066} | package com.dreamsoftware.tvnexa.ui.features.profiles.blocking
import com.dreamsoftware.tvnexa.domain.model.ProfileBO
import com.dreamsoftware.tvnexa.domain.model.SimpleChannelBO
import com.dreamsoftware.tvnexa.domain.usecase.impl.BlockChannelUseCase
import com.dreamsoftware.tvnexa.domain.usecase.impl.GetProfileByIdUseCase
import com.dreamsoftware.tvnexa.domain.usecase.impl.SearchChannelsUseCase
import com.dreamsoftware.tvnexa.domain.usecase.impl.UnblockChannelUseCase
import com.dreamsoftware.tvnexa.ui.core.SideEffect
import com.dreamsoftware.tvnexa.ui.core.SupportSearchViewModel
import com.dreamsoftware.tvnexa.ui.core.UiState
import com.dreamsoftware.tvnexa.ui.extensions.EMPTY
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class ProfileBlockingChannelsViewModel @Inject constructor(
private val getProfileByIdUseCase: GetProfileByIdUseCase,
searchChannelsUseCase: SearchChannelsUseCase,
private val blockChannelUseCase: BlockChannelUseCase,
private val unblockChannelUseCase: UnblockChannelUseCase
): SupportSearchViewModel<ProfileBlockingChannelsUiState, ProfileAdvanceSideEffects>(searchChannelsUseCase) {
override val currentTerm: String
get() = uiState.value.term
override fun onTermUpdated(newTerm: String) {
updateState { it.copy(term = newTerm) }
}
override fun onSearchCompletedSuccessfully(channels: List<SimpleChannelBO>) {
updateState { it.copy(channels = channels) }
}
override fun onGetDefaultState(): ProfileBlockingChannelsUiState = ProfileBlockingChannelsUiState()
fun load(profileId: String) {
executeUseCaseWithParams(
useCase = getProfileByIdUseCase,
params = GetProfileByIdUseCase.Params(profileId),
onSuccess = ::onLoadProfileCompleted
)
}
fun onBlockChannel(channel: SimpleChannelBO) {
executeUseCaseWithParams(
useCase = blockChannelUseCase,
params = BlockChannelUseCase.Params(channelId = channel.channelId),
onSuccess = {
onBlockChannelCompleted(channelId = channel.channelId)
}
)
}
fun onUnblockChannel(channel: SimpleChannelBO) {
executeUseCaseWithParams(
useCase = unblockChannelUseCase,
params = UnblockChannelUseCase.Params(channelId = channel.channelId),
onSuccess = {
onUnblockChannelCompleted(channelId = channel.channelId)
}
)
}
private fun onLoadProfileCompleted(profileBO: ProfileBO) {
updateState {
it.copy(profile = profileBO)
}
}
private fun updateChannelCompleted(channelId: String, isBlocked: Boolean) {
updateState { state ->
state.copy(
channels = state.channels.map { channel ->
if (channel.channelId == channelId) {
channel.copy(isBlocked = isBlocked)
} else {
channel
}
}
)
}
}
private fun onBlockChannelCompleted(channelId: String) {
updateChannelCompleted(channelId, isBlocked = true)
}
private fun onUnblockChannelCompleted(channelId: String) {
updateChannelCompleted(channelId, isBlocked = false)
}
}
data class ProfileBlockingChannelsUiState(
override val isLoading: Boolean = false,
override val error: String? = null,
val profile: ProfileBO? = null,
val term: String = String.EMPTY,
val channels: List<SimpleChannelBO> = emptyList(),
): UiState<ProfileBlockingChannelsUiState>(isLoading, error) {
override fun copyState(isLoading: Boolean, error: String?): ProfileBlockingChannelsUiState =
copy(isLoading = isLoading, error = error)
}
sealed interface ProfileAdvanceSideEffects: SideEffect | 0 | Kotlin | 0 | 1 | 30fb84765276b1afcadc27b0ce8ffc15155decc4 | 3,903 | tvnexa_androidtv | Apache License 2.0 |
app/src/androidTest/kotlin/com/dotslashlabs/demo/HomeViewModelTest.kt | shirish87 | 491,229,483 | false | {"Kotlin": 31281} | package com.dotslashlabs.demo
import com.dotslashlabs.demo.data.DemoStore
import com.dotslashlabs.demo.data.entity.Book
import com.dotslashlabs.demo.data.repository.BookRepository
import com.dotslashlabs.demo.ui.screen.home.HomeViewModel
import com.dotslashlabs.demo.ui.screen.home.HomeViewState
import dagger.hilt.android.testing.HiltAndroidTest
import javax.inject.Inject
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
@HiltAndroidTest
class HomeViewModelTest : BaseTest() {
@Inject
lateinit var bookRepository: BookRepository
@Test
fun testHomeViewModel() = runBlocking {
val viewModel = HomeViewModel(
HomeViewState(),
DemoStore(
bookRepository,
),
)
val books = (1..10).map { bookId ->
Book(
bookId = 0,
title = "<NAME> $bookId",
)
}
viewModel.createBooks(books)
assertEquals(books.size, runBlocking { viewModel.booksCount().first() })
}
}
| 0 | Kotlin | 0 | 0 | 951711dede422c97032ef6e329871ca3d9bf4cb0 | 1,114 | android-compose-material-hilt-mavericks-room | Apache License 2.0 |
app/src/main/java/com/rpfcoding/borutocharacterviewer/data/local/dao/HeroRemoteKeyDao.kt | riley0521 | 461,738,945 | false | null | package com.rpfcoding.borutocharacterviewer.data.local.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy.REPLACE
import androidx.room.Query
import com.rpfcoding.borutocharacterviewer.data.local.entity.HeroRemoteKeyEntity
@Dao
interface HeroRemoteKeyDao {
@Query("SELECT * FROM tbl_hero_remote_keys WHERE heroId = :heroId")
suspend fun getRemoteKey(heroId: Int): HeroRemoteKeyEntity?
@Insert(onConflict = REPLACE)
suspend fun addAllRemoteKeys(heroRemoteKeyEntities: List<HeroRemoteKeyEntity>)
@Query("DELETE FROM tbl_hero_remote_keys")
suspend fun deleteAllRemoteKeys()
} | 0 | Kotlin | 0 | 0 | 86baf29435338ac9294224174a2fcc52d37f7945 | 647 | BorutoCharacterViewer | Apache License 2.0 |
TrailTrackerApp/app/src/main/java/app/demo/example/com/trailtracker/routename/RouteNameActivity.kt | bonafonteGuillermo | 148,182,636 | false | null | package app.demo.example.com.trailtracker.routename
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import app.demo.example.com.trailtracker.app.App
import app.demo.example.com.trailtracker.app.BaseView.Companion.EXTRA_ROUTE
import app.demo.example.com.trailtracker.model.Route
import app.demo.example.com.trailtracker.routename.injection.DaggerRouteNameComponent
import app.demo.example.com.trailtracker.routename.injection.RouteNameContextModule
import javax.inject.Inject
/**
*
* Created by Guillermo Bonafonte Criado
*
*/
class RouteNameActivity : AppCompatActivity() {
val ROUTE = "USER_NAME"
@Inject
lateinit var view: IRouteNameView
@Inject
lateinit var presenter: IRouteNamePresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerRouteNameComponent.builder()
.appComponent(App.appComponent)
.routeNameContextModule(RouteNameContextModule(this))
.build()
.inject(this)
setContentView(view.constructView())
view.presenter = presenter
val bundle = intent.extras
if (bundle.getParcelable<Route>(EXTRA_ROUTE) != null){
var route = bundle.getParcelable<Route>(EXTRA_ROUTE)
presenter.onCreate(route)
}else{
presenter.onCreate()
}
}
override fun onDestroy() {
presenter.onDestroy()
super.onDestroy()
}
} | 0 | Kotlin | 0 | 0 | c3b98af96efe75ad8a3b430d84e32cc21ec1b8aa | 1,506 | TrailTracker | Apache License 2.0 |
src/test/kotlin/be/swsb/aoc2021/day13/Day13Test.kt | Sch3lp | 433,542,959 | false | {"Kotlin": 90751} | package be.swsb.aoc2021.day13
import be.swsb.aoc2021.common.FoldInstruction
import be.swsb.aoc2021.common.Point.Companion.at
import be.swsb.aoc2021.common.readLines
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
class Day13Test {
@Nested
inner class SolutionTests {
@Test
fun `solve1 with testInput should return 17 visible dots`() {
val actual = Day13.solve1("day13/testInput.txt".readLines())
assertThat(actual).isEqualTo(17)
}
@Test
fun `solve1 with actualInput should return 731 visible dots`() {
val actual = Day13.solve1("day13/actualInput.txt".readLines())
assertThat(actual).isEqualTo(731)
}
@Test
fun `solve2 with actualInput prints something`() {
val actual = Day13.solve2("day13/actualInput.txt".readLines())
println(actual) // ZKAUCFUC
}
}
@Nested
inner class ParseTests {
@Test
fun `can parse into a Paper and fold instructions`() {
val (paper, foldInstructions) = Day13.parse("day13/testInput.txt".readLines())
assertThat(foldInstructions).containsExactlyInAnyOrder(FoldInstruction.Up(7), FoldInstruction.Left(5))
assertThat(paper).isEqualTo(
Paper(
setOf(
at(6, 10),
at(0, 14),
at(9, 10),
at(0, 3),
at(10, 4),
at(4, 11),
at(6, 0),
at(6, 12),
at(4, 1),
at(0, 13),
at(10, 12),
at(3, 4),
at(3, 0),
at(8, 4),
at(1, 10),
at(2, 14),
at(8, 10),
at(9, 0)
)
)
)
}
@Test
fun `can fold`() {
val (paper, _) = Day13.parse("day13/testInput.txt".readLines())
paper.fold(FoldInstruction.Up(7)).also {
assertThat(it).isEqualTo(
Paper(
setOf(
at(6, 4),
at(0, 0),
at(9, 4),
at(0, 3),
at(10, 4),
at(4, 3),
at(6, 0),
at(6, 2),
at(4, 1),
at(0, 1),
at(10, 2),
at(3, 4),
at(3, 0),
at(1, 4),
at(2, 0),
at(8, 4),
at(9, 0)
)
)
)
}.fold(FoldInstruction.Left(5)).also {
assertThat(it).isEqualTo(
Paper(
setOf(
at(4, 4),
at(0, 0),
at(1, 4),
at(0, 3),
at(0, 4),
at(4, 3),
at(4, 0),
at(4, 2),
at(4, 1),
at(0, 1),
at(0, 2),
at(3, 4),
at(3, 0),
at(2, 0),
at(2, 4),
at(1, 0)
)
)
)
}
}
}
} | 0 | Kotlin | 0 | 0 | 7662b3861ca53214e3e3a77c1af7b7c049f81f44 | 3,930 | Advent-of-Code-2021 | MIT License |
src/main/kotlin/de/jakkoble/utils/Variables.kt | Jakkoble | 539,651,671 | false | {"Kotlin": 47953} | package de.jakkoble.utils
import de.jakkoble.Main
import de.jakkoble.modules.settings.Interval
import net.axay.kspigot.extensions.server
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.NamedTextColor
import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.scheduler.BukkitRunnable
val prefix = "${ChatColor.GOLD}BlockChange ${ChatColor.WHITE}•${ChatColor.GRAY}"
val savePrefix = Component.text()
.append(Component.text("BlockChange ").color(NamedTextColor.GOLD))
.append(Component.text("•").color(NamedTextColor.WHITE))
.build()
var randomBlocks: Long = 0
var latestRoll: Long = 0
var blockInterval: Interval = Interval.THREE_DAYS
var serverOpen: Boolean = true
var allowedPlayers: List<String> = listOf()
fun openServer(open: Boolean) {
if (serverOpen == open) return
serverOpen = open
object: BukkitRunnable() {
override fun run() {
if (open) {
server.consoleSender.sendMessage("$prefix Server is now opened.")
Bukkit.getOnlinePlayers().forEach { it.sendMessage("$prefix Der Server ist nun für alle Spieler geöffnet.") }
} else {
val players = Main.INSTANCE.server.onlinePlayers
server.consoleSender.sendMessage("$prefix Server is now closed - kicked ${players.filter { !allowedPlayers.contains(it.uniqueId.toString()) }.size} players.")
players.forEach {
if (!allowedPlayers.contains(it.uniqueId.toString())) it.kick(Component.text("Der Server ist nun bis morgen 14:00 Uhr geschlossen.").color(NamedTextColor.RED))
it.sendMessage("$prefix Der Server ist nun für alle Spieler geschlossen")
}
}
}
}.runTask(Main.INSTANCE)
} | 0 | Kotlin | 0 | 0 | bc8e1abfccc2615a10a77691177746ca239c065a | 1,736 | BlockChange | MIT License |
library/src/main/java/com/adityaanand/morphdialog/MorphDialog.kt | AdityaAnand1 | 100,109,717 | false | null | package com.adityaanand.morphdialog
import android.app.Activity
import android.app.ActivityOptions
import android.content.Intent
import android.content.res.ColorStateList
import android.os.Build
import android.support.annotation.*
import android.support.design.widget.FloatingActionButton
import com.adityaanand.morphdialog.interfaces.MorphListCallbackMultiChoice
import com.adityaanand.morphdialog.interfaces.MorphListCallbackSingleChoice
import com.adityaanand.morphdialog.interfaces.MorphSingleButtonCallback
import com.adityaanand.morphdialog.utils.MorphDialogAction
import com.afollestad.materialdialogs.util.DialogUtils
import java.util.*
/**
* @author <NAME> (AdityaAnand1)
*/
@Suppress("unused")
class MorphDialog private constructor(var builder: Builder) {
//todo How do we let other devs know that this ^ is mine to avoid conflict?
private val id: Long
init {
//generate a unique ID for each dialog
var temp: Long
do {
temp = Random().nextLong()
} while (temp == 0L)
id = temp
}
private fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode != REQUEST_CODE || data == null || resultCode != Activity.RESULT_OK)
//this is not ours
return
val paramId = data.getLongExtra(Constants.MORPH_DIALOG_ID, 0)
if (this.id != paramId || paramId == 0L)
return //this is some other dialogs call back
if (data.hasExtra(Constants.MORPH_DIALOG_ACTION_TYPE)) //is a button click
handleButtonClick(data.getSerializableExtra(Constants.MORPH_DIALOG_ACTION_TYPE) as MorphDialogAction)
else if (data.hasExtra(Constants.INTENT_KEY_SINGLE_CHOICE_LIST_ITEM_POSITION))
handleSingleChoiceItemSelected(data.getIntExtra(Constants.INTENT_KEY_SINGLE_CHOICE_LIST_ITEM_POSITION, -1),
data.getCharSequenceExtra(Constants.INTENT_KEY_SINGLE_CHOICE_LIST_ITEM_TEXT))
else if (data.hasExtra(Constants.INTENT_KEY_MULTI_CHOICE_LIST_ITEM_TEXTS))
handleMultiChoiceItemSelected(data.getIntegerArrayListExtra(Constants.INTENT_KEY_MULTI_CHOICE_LIST_ITEM_POSITIONS).toTypedArray(),
data.getCharSequenceArrayListExtra(Constants.INTENT_KEY_MULTI_CHOICE_LIST_ITEM_TEXTS).toTypedArray())
}
fun handleButtonClick(actionType: MorphDialogAction) {
when (actionType) {
MorphDialogAction.POSITIVE -> if (builder.onPositiveCallback != null)
builder.onPositiveCallback!!.onClick(this, actionType)
MorphDialogAction.NEGATIVE -> if (builder.onNegativeCallback != null)
builder.onNegativeCallback!!.onClick(this, actionType)
MorphDialogAction.NEUTRAL -> if (builder.onNeutralCallback != null)
builder.onNeutralCallback!!.onClick(this, actionType)
}
if (builder.onAnyCallback != null) {
builder.onAnyCallback!!.onClick(this, actionType)
}
}
fun handleSingleChoiceItemSelected(which: Int, text: CharSequence) {
builder.singleChoiceCallback?.onSelection(this, which, text)
}
fun handleMultiChoiceItemSelected(which: Array<Int>, texts: Array<CharSequence>) {
builder.multiChoiceCallback?.onSelection(this, which, texts)
}
fun show(): MorphDialog {
val intent = Intent(builder.activity, if (builder.data.darkTheme)
MorphDialogActivityDark::class.java
else
MorphDialogActivity::class.java)
intent.putExtra(Constants.MORPH_DIALOG_BUILDER_DATA, builder.data)
intent.putExtra(Constants.MORPH_DIALOG_ID, id)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val options = ActivityOptions.makeSceneTransitionAnimation(
builder.activity, builder.fab, "morph_transition")
builder.activity.startActivityForResult(intent, REQUEST_CODE, options.toBundle())
} else
builder.activity.startActivityForResult(intent, REQUEST_CODE)
return this
}
class Registerer(val requestCode: Int,
val resultCode: Int,
val data: Intent?) {
fun forDialogs(vararg dialogs: MorphDialog?) {
if (requestCode == REQUEST_CODE)
for (dialog in dialogs)
dialog?.onActivityResult(requestCode, resultCode, data)
}
}
class Builder(val activity: Activity, val fab: View) {
val data: DialogBuilderData = DialogBuilderData()
internal var onPositiveCallback: MorphSingleButtonCallback? = null
internal var onNegativeCallback: MorphSingleButtonCallback? = null
internal var onNeutralCallback: MorphSingleButtonCallback? = null
internal var onAnyCallback: MorphSingleButtonCallback? = null
internal var singleChoiceCallback: MorphListCallbackSingleChoice? = null
internal var multiChoiceCallback: MorphListCallbackMultiChoice? = null
fun iconRes(@DrawableRes iconRes: Int): Builder {
data.iconRes = iconRes
return this
}
fun title(@StringRes titleRes: Int): Builder {
title(activity.getText(titleRes))
return this
}
fun title(title: CharSequence): Builder {
data.title = title
return this
}
fun content(@StringRes contentRes: Int): Builder {
content(activity.getText(contentRes))
return this
}
fun content(content: CharSequence): Builder {
data.content = content
return this
}
fun items(vararg items: CharSequence): Builder {
data.items = arrayOf(*items)
return this
}
fun itemsCallbackSingleChoice(callback: MorphListCallbackSingleChoice): Builder {
this.singleChoiceCallback = callback
data.hasSingleChoiceCallback = true
return this
}
fun itemsCallbackSingleChoice(callback: (MorphDialog, Int, CharSequence?) -> Unit): Builder {
this.singleChoiceCallback = object : MorphListCallbackSingleChoice {
override fun onSelection(dialog: MorphDialog, which: Int, text: CharSequence?) {
callback(dialog, which, text)
}
}
data.hasSingleChoiceCallback = true
return this
}
fun alwaysCallSingleChoiceCallback(alwaysCallSingleChoiceCallback: Boolean = true): Builder {
data.alwaysCallSingleChoiceCallback = alwaysCallSingleChoiceCallback
return this
}
fun itemsCallbackMultiChoice(callback: MorphListCallbackMultiChoice): Builder {
this.multiChoiceCallback = callback
data.hasMultiChoiceCallback = true
return this
}
fun itemsCallbackMultiChoice(callback: (MorphDialog, Array<Int>, Array<CharSequence>) -> Unit): Builder {
this.multiChoiceCallback = object : MorphListCallbackMultiChoice {
override fun onSelection(dialog: MorphDialog, which: Array<Int>, texts: Array<CharSequence>) {
callback(dialog, which, texts)
}
}
data.hasMultiChoiceCallback = true
return this
}
fun alwaysCallMultiChoiceCallback(alwaysCallMultiChoiceCallback: Boolean = true): Builder {
data.alwaysCallMultiChoiceCallback = alwaysCallMultiChoiceCallback
return this
}
fun positiveText(@StringRes positiveTextRes: Int): Builder {
positiveText(activity.getText(positiveTextRes))
return this
}
fun positiveText(positiveText: CharSequence): Builder {
data.positiveText = positiveText
return this
}
fun negativeText(@StringRes negativeTextRes: Int): Builder {
negativeText(activity.getText(negativeTextRes))
return this
}
fun negativeText(negativeText: CharSequence): Builder {
data.negativeText = negativeText
return this
}
fun neutralText(@StringRes neutralRes: Int): Builder {
return if (neutralRes == 0) {
this
} else neutralText(this.activity.getText(neutralRes))
}
fun positiveColor(@ColorInt color: Int): Builder {
return positiveColor(DialogUtils.getActionTextStateList(activity, color))
}
fun positiveColorRes(@ColorRes colorRes: Int): Builder {
return positiveColor(DialogUtils.getActionTextColorStateList(this.activity, colorRes))
}
fun positiveColorAttr(@AttrRes colorAttr: Int): Builder {
return positiveColor(
DialogUtils.resolveActionTextColorStateList(this.activity, colorAttr, null))
}
fun positiveColor(colorStateList: ColorStateList): Builder {
this.data.positiveColor = colorStateList
return this
}
fun negativeColor(@ColorInt color: Int): Builder {
return negativeColor(DialogUtils.getActionTextStateList(activity, color))
}
fun negativeColorRes(@ColorRes colorRes: Int): Builder {
return negativeColor(DialogUtils.getActionTextColorStateList(this.activity, colorRes))
}
fun negativeColorAttr(@AttrRes colorAttr: Int): Builder {
return negativeColor(
DialogUtils.resolveActionTextColorStateList(this.activity, colorAttr, null))
}
fun negativeColor(colorStateList: ColorStateList): Builder {
this.data.negativeColor = colorStateList
return this
}
fun neutralColor(@ColorInt color: Int): Builder {
return neutralColor(DialogUtils.getActionTextStateList(activity, color))
}
fun neutralColorRes(@ColorRes colorRes: Int): Builder {
return neutralColor(DialogUtils.getActionTextColorStateList(this.activity, colorRes))
}
fun neutralColorAttr(@AttrRes colorAttr: Int): Builder {
return neutralColor(
DialogUtils.resolveActionTextColorStateList(this.activity, colorAttr, null))
}
fun neutralColor(colorStateList: ColorStateList): Builder {
this.data.neutralColor = colorStateList
return this
}
fun neutralText(message: CharSequence): Builder {
this.data.neutralText = message
return this
}
fun useDarkTheme(darkTheme: Boolean): Builder {
data.darkTheme = darkTheme
return this
}
fun onPositive(callback: MorphSingleButtonCallback): Builder {
this.onPositiveCallback = callback
return this
}
fun onPositive(callback: (MorphDialog, MorphDialogAction) -> Unit): Builder {
this.onPositiveCallback = object : MorphSingleButtonCallback {
override fun onClick(dialog: MorphDialog, which: MorphDialogAction) {
callback(dialog, which)
}
}
return this
}
fun onNegative(callback: MorphSingleButtonCallback): Builder {
this.onNegativeCallback = callback
return this
}
fun onNegative(callback: (MorphDialog, MorphDialogAction) -> Unit): Builder {
this.onNegativeCallback = object : MorphSingleButtonCallback {
override fun onClick(dialog: MorphDialog, which: MorphDialogAction) {
callback(dialog, which)
}
}
return this
}
fun onNeutral(callback: MorphSingleButtonCallback): Builder {
this.onNeutralCallback = callback
return this
}
fun onNeutral(callback: (MorphDialog, MorphDialogAction) -> Unit): Builder {
this.onNeutralCallback = object : MorphSingleButtonCallback {
override fun onClick(dialog: MorphDialog, which: MorphDialogAction) {
callback(dialog, which)
}
}
return this
}
fun onAny(callback: MorphSingleButtonCallback): Builder {
this.onAnyCallback = callback
return this
}
fun onAny(callback: (MorphDialog, MorphDialogAction) -> Unit): Builder {
this.onAnyCallback = object : MorphSingleButtonCallback {
override fun onClick(dialog: MorphDialog, which: MorphDialogAction) {
callback(dialog, which)
}
}
return this
}
fun cancelable(cancelable: Boolean): Builder {
this.data.cancelable = cancelable
this.data.canceledOnTouchOutside = cancelable
return this
}
fun canceledOnTouchOutside(canceledOnTouchOutside: Boolean): Builder {
this.data.canceledOnTouchOutside = canceledOnTouchOutside
return this
}
fun backgroundColor(@ColorInt color: Int): Builder {
this.data.backgroundColor = color
return this
}
fun backgroundColorRes(@ColorRes colorRes: Int): Builder {
return backgroundColor(DialogUtils.getColor(this.activity, colorRes))
}
fun backgroundColorAttr(@AttrRes colorAttr: Int): Builder {
return backgroundColor(DialogUtils.resolveColor(this.activity, colorAttr))
}
fun titleColor(@ColorInt color: Int): Builder {
this.data.titleColor = color
return this
}
fun titleColorRes(@ColorRes colorRes: Int): Builder {
return titleColor(DialogUtils.getColor(this.activity, colorRes))
}
fun titleColorAttr(@AttrRes colorAttr: Int): Builder {
return titleColor(DialogUtils.resolveColor(this.activity, colorAttr))
}
fun contentColor(@ColorInt color: Int): Builder {
this.data.contentColor = color
return this
}
fun contentColorRes(@ColorRes colorRes: Int): Builder {
contentColor(DialogUtils.getColor(this.activity, colorRes))
return this
}
fun contentColorAttr(@AttrRes colorAttr: Int): Builder {
contentColor(DialogUtils.resolveColor(this.activity, colorAttr))
return this
}
fun build(): MorphDialog {
return MorphDialog(this)
}
fun show(): MorphDialog {
return MorphDialog(this).show()
}
}
companion object {
private val REQUEST_CODE = 7324
@JvmStatic
fun registerOnActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Registerer {
return Registerer(requestCode, resultCode, data)
}
}
}
| 6 | null | 65 | 890 | efc465c353c652fea1db240ca926c6ab37c392d1 | 14,980 | Morphing-Material-Dialogs | MIT License |
radar-commons/src/main/java/org/radarbase/producer/io/HttpClientExtensions.kt | RADAR-base | 82,068,774 | false | {"Kotlin": 339724, "Java": 33339} | package org.radarbase.producer.io
import io.ktor.client.HttpClientConfig
import io.ktor.client.engine.cio.CIOEngineConfig
import io.ktor.client.plugins.HttpTimeout
import java.security.cert.X509Certificate
import javax.net.ssl.X509TrustManager
import kotlin.time.Duration
fun HttpClientConfig<*>.timeout(duration: Duration) {
install(HttpTimeout) {
val millis = duration.inWholeMilliseconds
connectTimeoutMillis = millis
socketTimeoutMillis = millis
requestTimeoutMillis = millis
}
}
fun HttpClientConfig<*>.unsafeSsl() {
engine {
if (this is CIOEngineConfig) {
https {
trustManager = UNSAFE_TRUST_MANAGER
}
}
}
}
/** Unsafe trust manager that trusts all certificates. */
private val UNSAFE_TRUST_MANAGER = object : X509TrustManager {
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) = Unit
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) = Unit
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
}
| 3 | Kotlin | 3 | 2 | c759a048ab90d9aabec6a0b870dbc899cfcd90fd | 1,106 | radar-commons | Apache License 2.0 |
tinker/src/main/java/com/liwei/tinker/TinkerManager.kt | liwei49699 | 267,739,678 | false | null | package com.liwei.tinker
class TinkerManager {
} | 1 | null | 1 | 1 | 5ce9094bbfeb86468d560fb29012e0dc29856334 | 49 | OfficeProcess | Apache License 2.0 |
common/src/main/java/me/limeice/common/base/app/AppManager.kt | LimeVista | 123,374,610 | false | {"Java": 182733, "Kotlin": 16687} | @file:Suppress("unused")
package me.limeice.common.base.app
import android.app.Activity
import androidx.annotation.MainThread
import me.limeice.common.base.AndroidScheduler
import me.limeice.common.function.algorithm.util.ArrayStack
import java.util.concurrent.locks.ReentrantReadWriteLock
/**
* Application Manager
*
* <pre>
* author: LimeVista(Lime)
* time : 2018/02/28, last update 2019.02.14
* desc : Application Manager
* github: https://github.com/LimeVista/EasyCommon
* </pre>
*/
class AppManager private constructor() {
private val mActStack: ArrayStack<Activity> = ArrayStack()
private val mRWLock = ReentrantReadWriteLock()
companion object {
@JvmStatic
val inst: AppManager by lazy { AppManager() }
}
/**
* 结束当前Activity
*/
@MainThread
fun finishActivity() {
AndroidScheduler.requireMainThread()
try {
mRWLock.writeLock().lock()
mActStack.pop()?.let {
if (!it.isFinishing) it.finish()
}
} finally {
mRWLock.writeLock().unlock()
}
}
/**
* 添加Activity
*/
fun addActivity(activity: Activity) {
try {
mRWLock.writeLock().lock()
mActStack.push(activity)
} finally {
mRWLock.writeLock().unlock()
}
}
/**
* 当前Activity
*/
fun currentActivity(): Activity? {
try {
mRWLock.readLock().lock()
return mActStack.last()
} finally {
mRWLock.readLock().unlock()
}
}
/**
* 结束指定的Activity
*
* @param activity Activity
*/
@MainThread
fun finishActivity(activity: Activity) {
AndroidScheduler.requireMainThread()
try {
mRWLock.writeLock().lock()
mActStack.remove(activity)
if (!activity.isFinishing)
activity.finish()
} finally {
mRWLock.writeLock().unlock()
}
}
/**
* 移除指定的Activity
*
* @param activity Activity
*/
fun removeActivity(activity: Activity): Boolean {
mRWLock.writeLock().lock()
val result = mActStack.remove(activity)
mRWLock.writeLock().unlock()
return result
}
/**
* 返回到指定的Activity
*/
@MainThread
fun <T> returnToActivity(clazz: Class<T>) where T : Activity {
AndroidScheduler.requireMainThread()
try {
mRWLock.writeLock().lock()
while (mActStack.size() > 0) {
val act = mActStack.pop() ?: continue
if (act.javaClass == clazz) {
mActStack.push(act)
break
} else {
act.finish()
}
}
} finally {
mRWLock.writeLock().unlock()
}
}
/**
* 查找是否存在已初始化好的 Activity
*
* @param clazz Class<T> Activity类名
* @return Activity? 不存在时返回空
*/
fun <T> findActivity(clazz: Class<T>): Activity? where T : Activity {
try {
mRWLock.readLock().lock()
for (act in mActStack) {
if (act.javaClass == clazz)
return act
}
} finally {
mRWLock.readLock().unlock()
}
return null
}
/**
* 是否已经打开指定的activity
* @param clazz Activity类名
* @return
*/
fun <T> isOpenActivity(clazz: Class<T>): Boolean where T : Activity {
var isOpen = false
try {
mRWLock.readLock().lock()
mActStack.forEach { act ->
if (act.javaClass == clazz) {
isOpen = true
return@forEach
}
}
} finally {
mRWLock.readLock().unlock()
}
return isOpen
}
/**
* 遍历打开的 Activity,只读模式
* @param consumer me.limeice.common.function.Consumer<Activity>
*/
fun forEachReadOnly(consumer: me.limeice.common.function.Consumer<Activity>) {
try {
mRWLock.readLock().lock()
mActStack.foreach(consumer)
} finally {
mRWLock.readLock().unlock()
}
}
/**
* 遍历打开的 Activity,读写模式
* @param consumer me.limeice.common.function.Consumer<Activity>
*/
fun forEachReadAndWrite(consumer: me.limeice.common.function.Consumer<Activity>) {
try {
mRWLock.writeLock().lock()
mActStack.foreach(consumer)
} finally {
mRWLock.writeLock().unlock()
}
}
/**
* 退出应用程序
* @param isBackground 是否开开启后台运行
*/
@MainThread
fun appExit(isBackground: Boolean) {
AndroidScheduler.requireMainThread()
try {
finishAll()
} catch (e: Exception) {
// ignore
} finally {
// if not exist background,kill system
if (!isBackground) System.exit(0)
}
}
/**
* 清除所有Activity
*/
private fun finishAll() {
try {
mRWLock.writeLock().lock()
mActStack.forEach { it?.finish() }
mActStack.clear()
} finally {
mRWLock.writeLock().unlock()
}
}
} | 1 | null | 2 | 1 | 567ed8ef85ce6ea220e237a2336130ddc62698a9 | 5,316 | EasyCommon | Apache License 2.0 |
compiler/testData/diagnostics/tests/redeclarations/ParentPackageRedeclaredByClass.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // FILE: a.kt
package a.b
// FILE: b.kt
class <!PACKAGE_OR_CLASSIFIER_REDECLARATION!>a<!>
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 91 | kotlin | Apache License 2.0 |
challenge/flutter/all_samples/material_checkboxlisttile_3/android/app/src/main/kotlin/com/example/material_checkboxlisttile_3/MainActivity.kt | davidzou | 5,868,257 | false | null | package com.example.material_checkboxlisttile_3
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | null | 1 | 4 | 1060f6501c432510e164578d4af60a49cd5ed681 | 144 | WonderingWall | Apache License 2.0 |
compiler/resolution/src/org/jetbrains/kotlin/types/alternativeTypeSubstitution.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.resolve.calls.inference.components.NewTypeSubstitutor
import org.jetbrains.kotlin.types.typeUtil.contains
fun substituteAlternativesInPublicType(type: KotlinType): UnwrappedType {
val substitutor = object : NewTypeSubstitutor {
override fun substituteNotNullTypeWithConstructor(constructor: TypeConstructor): UnwrappedType? {
if (constructor is IntersectionTypeConstructor) {
constructor.getAlternativeType()?.let { alternative ->
return safeSubstitute(alternative.unwrap())
}
}
return null
}
override val isEmpty: Boolean by lazy {
!type.contains { it.constructor is IntersectionTypeConstructor }
}
}
return substitutor.safeSubstitute(type.unwrap())
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,075 | kotlin | Apache License 2.0 |
domain/src/test/java/com/hasegawa/diapp/domain/GetStepsUseCaseTest.kt | AranHase | 55,708,682 | false | {"Gradle": 8, "Java Properties": 2, "Shell": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 1, "Kotlin": 152, "SVG": 5, "Text": 1, "XML": 72, "Proguard": 4, "Java": 3} | /*
* Copyright 2016 <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 com.hasegawa.diapp.domain
import com.hasegawa.diapp.domain.entities.StepEntity
import com.hasegawa.diapp.domain.repositories.StepsRepository
import com.hasegawa.diapp.domain.usecases.GetStepsUseCase
import org.hamcrest.CoreMatchers.*
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
import rx.Subscriber
import rx.lang.kotlin.BehaviorSubject
import rx.schedulers.Schedulers
import java.util.concurrent.CyclicBarrier
import java.util.concurrent.TimeUnit
class GetStepsUseCaseTest {
val et = ExecutionThread(Schedulers.io())
val pet = PostExecutionThread(Schedulers.newThread())
@Mock
var stepsRepository: StepsRepository? = null
val stepsList = listOf(
StepEntity("A", 1, "titleA", "descA", true, "possA"),
StepEntity("B", 3, "titleA", "descA", false, "possB"),
StepEntity("C", 2, "titleA", "descA", false, "possC"),
StepEntity("D", 4, "titleA", "descA", false, "possD")
)
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
val subject = BehaviorSubject(stepsList)
`when`(stepsRepository!!.getSteps()).thenReturn(subject)
`when`(stepsRepository!!.notifyChange()).then { subject.onNext(emptyList()) }
}
@Test
fun execute() {
val useCase = GetStepsUseCase(stepsRepository!!, et, pet)
var completed = false
var result: List<StepEntity>? = null
var calls = 0
val barrier = CyclicBarrier(2)
useCase.execute(object : Subscriber<List<StepEntity>>() {
override fun onCompleted() {
completed = true
}
override fun onError(e: Throwable?) {
throw UnsupportedOperationException()
}
override fun onNext(t: List<StepEntity>?) {
calls++
result = t
barrier.await()
}
})
barrier.await(10, TimeUnit.SECONDS)
assertThat(result, `is`(stepsList.sortedBy { it.position }))
barrier.reset()
stepsRepository!!.notifyChange()
barrier.await(10, TimeUnit.SECONDS)
assertThat(result, `is`(emptyList()))
useCase.unsubscribe()
assertThat(completed, `is`(false))
assertThat(calls, `is`(2))
verify(stepsRepository!!).getSteps()
verify(stepsRepository!!).notifyChange()
verifyNoMoreInteractions(stepsRepository!!)
}
}
| 6 | Kotlin | 1 | 8 | 80e2c6d345a63ce75a1383f52f08bfb1f0a1535b | 3,143 | PassosDoImpeachment-app | Apache License 2.0 |
litho-rendercore/src/test/java/com/facebook/rendercore/debug/DurationValueTest.kt | facebook | 80,179,724 | false | {"Kotlin": 5825848, "Java": 5578851, "C++": 616537, "Starlark": 198527, "JavaScript": 29060, "C": 25074, "Shell": 8243, "CSS": 5558, "CMake": 4783, "Objective-C": 4012} | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.rendercore.debug
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class DurationValueTest {
@Test
fun `to string duration less than 1000 correctly`() {
val duration = Duration(999)
assertThat(duration.value).isEqualTo(999)
assertThat(duration.toString()).isEqualTo("999 ns")
}
@Test
fun `to string less than 1_000_000 correctly`() {
val duration = Duration(999_999)
assertThat(duration.value).isEqualTo(999_999)
assertThat(duration.toString()).isEqualTo("999 µs")
}
@Test
fun `to string more than 1_000_000 correctly`() {
val duration = Duration(999_999_999)
assertThat(duration.value).isEqualTo(999_999_999)
assertThat(duration.toString()).isEqualTo("999 ms")
}
}
| 88 | Kotlin | 765 | 7,703 | 8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0 | 1,504 | litho | Apache License 2.0 |
app/src/main/kotlin/com/github/lipinskipawel/network/MoveEncoder.kt | lipinskipawel | 175,280,061 | false | null | package com.github.lipinskipawel.network
import com.github.lipinskipawel.board.engine.Direction
import com.github.lipinskipawel.board.engine.Direction.*
import com.github.lipinskipawel.board.engine.Move
/**
* This class is able to encode Move class. This class is Thread safe.
* Each Move object contains list of Directions. Direction is mapped as
* followed:
*
* N - 0000 0001
* NE - 0000 0010
* E - 0000 0011
* SE - 0000 0101
* S - 0000 0110
* SW - 0000 0111
* W - 0000 1000
* NW - 0000 1001
*/
class MoveEncoder {
companion object {
fun encode(move: Move): ByteArray {
return move
.move
.map { encode(it) }
.toByteArray()
}
fun decode(byteArray: ByteArray): Move {
val directions: List<Direction> = byteArray
.mapTo(mutableListOf()) { decodeOneByte(it) }
return Move(directions)
}
private fun decodeOneByte(byte: Byte): Direction {
return when (byte.toInt()) {
0x01 -> N
0x02 -> NE
0x03 -> E
0x04 -> SE
0x05 -> S
0x06 -> SW
0x07 -> W
0x08 -> NW
else -> throw Exception("Can not decode: ${byte.toInt()}")
}
}
private fun encode(direction: Direction): Byte {
return when (direction) {
N -> 0x01
NE -> 0x02
E -> 0x03
SE -> 0x04
S -> 0x05
SW -> 0x06
W -> 0x07
NW -> 0x08
else -> throw Exception("Can not encode: $direction")
}
}
}
}
| 3 | null | 1 | 1 | 2d13406cc593083fa9ddf45779a92bdabf6fd236 | 1,779 | LAN-Game | MIT License |
subprojects/logger/logger/src/main/kotlin/com/avito/logger/DefaultLoggerFactory.kt | avito-tech | 230,265,582 | false | {"Kotlin": 3747948, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086} | package com.avito.logger
import com.avito.logger.handler.CompositeLoggingHandler
import com.avito.logger.handler.LoggingHandlerProvider
import com.avito.logger.metadata.LoggerMetadataProvider
import com.avito.logger.metadata.TagLoggerMetadataProvider
internal class DefaultLoggerFactory(
private val metadataProvider: LoggerMetadataProvider,
private val handlerProviders: List<LoggingHandlerProvider>
) : LoggerFactory {
init {
check(handlerProviders.isNotEmpty()) {
"handler providers must contain at least one provider"
}
}
override fun create(tag: String): Logger {
val metadata = metadataProvider.provide(tag)
val handlers = handlerProviders.map { it.provide(metadata) }
val handler = CompositeLoggingHandler(handlers)
return LoggerImpl(handler)
}
}
public class LoggerFactoryBuilder {
private var metadataProvider: LoggerMetadataProvider = TagLoggerMetadataProvider
private val handlerProviders = mutableListOf<LoggingHandlerProvider>()
public fun metadataProvider(provider: LoggerMetadataProvider): LoggerFactoryBuilder {
this.metadataProvider = provider
return this
}
public fun addLoggingHandlerProvider(
provider: LoggingHandlerProvider
): LoggerFactoryBuilder {
handlerProviders.add(provider)
return this
}
public fun newBuilder(): LoggerFactoryBuilder {
return LoggerFactoryBuilder().also { newBuilder ->
newBuilder.metadataProvider = metadataProvider
newBuilder.handlerProviders.addAll(handlerProviders)
}
}
public fun build(): LoggerFactory {
return DefaultLoggerFactory(
metadataProvider = metadataProvider,
handlerProviders = handlerProviders.toList()
)
}
}
| 10 | Kotlin | 50 | 414 | bc94abf5cbac32ac249a653457644a83b4b715bb | 1,831 | avito-android | MIT License |
order-service/src/main/kotlin/com/aleksander/storefront/orderservice/domain/CurrencyCode.kt | Moomba42 | 578,465,129 | false | {"Java": 21341, "Kotlin": 17490, "Groovy": 4948} | package com.aleksander.storefront.orderservice.domain
enum class CurrencyCode(val description: String) {
EUR("Euro Member Countries"),
GBP("United Kingdom Pound"),
PLN("Poland Zloty"),
USD("United States Dollar")
} | 1 | null | 1 | 1 | c727d763aaf85e6167f510add2161b4d357be411 | 231 | storefront | MIT License |
java/spring/pivotal-certfied-professional-core-spring5-developer-exam/pivotal-certfied-professional-core-spring5-developer-exam-chapter10-spring-and-kotlin/src/main/kotlin/com/apress/cems/kotlin/Repositories.kt | fernando-romulo-silva | 230,160,136 | false | null | package com.apress.cems.kotlin
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import java.time.LocalDateTime
import java.util.*
/**
* @author Iuliana Cosmina
* @since 1.0
*/
interface PersonRepo : JpaRepository<Person, Long> {
@Query("select p from Person p where p.username like %?1%")
fun findByUsername(username: String): Optional<Person>
@Query("select p from Person p where p.firstName=:fn and p.lastName=:ln")
fun findByCompleteName(@Param("fn") fn: String, @Param("ln") lastName: String): Optional<Person>
@Query("select p from Person p where p.username like %?1%")
fun findByUsernameLike(username: String): List<Person>
@Query("select p from Person p where p.firstName=:fn")
fun findByFirstName(@Param("fn") firstName: String): List<Person>
@Query("select p from Person p where p.firstName like %?1%")
fun findByFirstNameLike(firstName: String): List<Person>
@Query("select p from Person p where p.lastName=:ln")
fun findByLastName(@Param("ln") lastName: String): List<Person>
@Query("select p from Person p where p.lastName like %?1%")
fun findByLastNameLike(lastName: String): List<Person>
@Query("select p from Person p where p.hiringDate=:hd")
fun findByHiringDate(@Param("hd") date: LocalDateTime): List<Person>
}
interface DetectiveRepo : JpaRepository<Detective, Long>
interface CriminalCaseRepo : JpaRepository<CriminalCase, Long> | 14 | null | 0 | 2 | c6436c19cb2837cb8f1e9dc410d7dca7c3c2499c | 1,546 | myStudies | Apache License 2.0 |
http/http-client-symbol-processor/src/main/kotlin/ru/tinkoff/kora/http/client/symbol/processor/ConfigClassGenerator.kt | Squiry | 772,475,645 | true | {"Java Properties": 1, "Gradle": 98, "Shell": 1, "EditorConfig": 1, "Markdown": 3, "Batchfile": 1, "Text": 2, "Ignore List": 1, "Java": 1446, "Kotlin": 467, "XML": 8, "JSON": 17, "INI": 10, "YAML": 5, "SQL": 3, "OASv3-yaml": 11, "HTML": 2, "OASv2-yaml": 1, "Mustache": 32, "Protocol Buffer": 3} | package ru.tinkoff.kora.http.client.symbol.processor
import com.google.devtools.ksp.getDeclaredFunctions
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.TypeSpec
import ru.tinkoff.kora.http.client.symbol.processor.HttpClientClassNames.declarativeHttpClientConfig
import ru.tinkoff.kora.http.client.symbol.processor.HttpClientClassNames.httpClientOperationConfig
import ru.tinkoff.kora.ksp.common.CommonClassNames.configValueExtractorAnnotation
import ru.tinkoff.kora.ksp.common.KspCommonUtils.generated
class ConfigClassGenerator {
fun generate(declaration: KSClassDeclaration): TypeSpec {
val functions = declaration.getDeclaredFunctions().map { it.simpleName.asString() }
val typeName = declaration.configName()
val tb = TypeSpec.interfaceBuilder(typeName)
.generated(HttpClientSymbolProcessor::class)
.addSuperinterface(declarativeHttpClientConfig)
.addAnnotation(configValueExtractorAnnotation)
functions.forEach { function ->
tb.addFunction(FunSpec.builder(function)
.returns(httpClientOperationConfig)
.addModifiers(KModifier.ABSTRACT)
.build())
}
return tb.build()
}
}
| 0 | null | 0 | 0 | c26f794e60e903a358b0c1ffac9a865507415ff6 | 1,353 | kora | Apache License 2.0 |
stock/stock-client/src/main/java/com/github/daggerok/client/StockWebClient.kt | daggerok | 116,054,568 | false | null | package com.github.daggerok.client
import org.apache.logging.log4j.LogManager
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.messaging.rsocket.RSocketRequester
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Mono
import java.time.Duration.ofSeconds
import java.time.LocalDateTime
data class StockPrice(val symbol: String,
val price: Double,
val time: LocalDateTime)
class StockWebClient(private val webClient: WebClient) {
companion object { private val log = LogManager.getLogger() }
fun pricesFor(symbol: String) =
webClient.get()
.uri("/stocks/{symbol}", symbol)
.retrieve()
.bodyToFlux(StockPrice::class.java)
.retryBackoff(3, ofSeconds(1), ofSeconds(5))
.doOnNext(log::info)
.doOnError(log::warn)
}
class StockRSocketClient(private val rSocketRequester: Mono<RSocketRequester>) {
companion object { private val log = LogManager.getLogger() }
fun pricesFor(symbol: String) = rSocketRequester.flatMapMany { rr ->
rr.route("stocks")
.data(symbol)
.retrieveFlux(StockPrice::class.java)
.retryBackoff(3, ofSeconds(1), ofSeconds(5))
.doOnNext(log::info)
.doOnError(log::warn)
}
}
@Configuration
class StockClientAutoConfiguration {
@Bean
@ConditionalOnMissingBean
fun stockWebClient(webClient: WebClient) = StockWebClient(webClient)
@Bean
@ConditionalOnMissingBean
fun webClient(builder: WebClient.Builder) = builder.baseUrl("http://127.0.0.1:8000").build()
@Bean
@ConditionalOnMissingBean
fun stockRSocketClient(rr: Mono<RSocketRequester>) = StockRSocketClient(rr)
@Bean
@ConditionalOnMissingBean
fun rSocketRequester(builder: RSocketRequester.Builder) = builder.connectTcp("127.0.0.1", 7000)
}
| 2 | Kotlin | 1 | 1 | e3db4a01a204e1e778d46230c1e326905c86b368 | 2,014 | javafx-examples | MIT License |
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/harvest/sync/HarvestToNetworkUpdater.kt | suomenriistakeskus | 78,840,058 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 2, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 4, "Gradle Kotlin DSL": 1, "Kotlin": 1344, "XML": 401, "Java": 161, "Protocol Buffer": 1, "JSON": 1} | package fi.riista.common.domain.harvest.sync
import fi.riista.common.RiistaSDK
import fi.riista.common.database.RiistaDatabase
import fi.riista.common.domain.harvest.HarvestOperationResponse
import fi.riista.common.domain.harvest.HarvestRepository
import fi.riista.common.domain.harvest.model.CommonHarvest
import fi.riista.common.domain.harvest.sync.dto.HarvestDTO
import fi.riista.common.domain.harvest.sync.dto.toCommonHarvest
import fi.riista.common.domain.harvest.sync.dto.toHarvestCreateDTO
import fi.riista.common.domain.harvest.sync.dto.toHarvestDTO
import fi.riista.common.domain.model.EntityImages
import fi.riista.common.network.BackendApiProvider
import fi.riista.common.network.calls.NetworkResponse
internal class HarvestToNetworkUpdater(
val backendApiProvider: BackendApiProvider,
database: RiistaDatabase,
) {
private val repository = HarvestRepository(database)
/**
* Sends the given harvest [harvests] to backend and returns a list containing the updated
* [CommonHarvest]s (most likely [CommonHarvest.rev] will differ).
*/
suspend fun update(username: String, harvests: List<CommonHarvest>): List<CommonHarvest> {
val updatedHarvests: List<CommonHarvest> = harvests.map { harvest ->
when (val updateResponse = sendHarvestToBackend(username, harvest)) {
is HarvestOperationResponse.Error,
is HarvestOperationResponse.SaveFailure,
is HarvestOperationResponse.NetworkFailure -> harvest
is HarvestOperationResponse.Success -> updateResponse.harvest
}
}
return updatedHarvests
}
/**
* Sends the given harvest [harvest] to backend and returns a list containing the updated
* [CommonHarvest]s (most likely [CommonHarvest.rev] will differ).
*/
suspend fun sendHarvestToBackend(username: String, harvest: CommonHarvest): HarvestOperationResponse {
if (harvest.localId == null) {
return HarvestOperationResponse.NetworkFailure(
statusCode = null, errorMessage = "missing local id"
)
}
val backendAPI = backendApiProvider.backendAPI
val networkResponse: NetworkResponse<HarvestDTO> = if (harvest.id == null) {
val createDTO = harvest.toHarvestCreateDTO()
backendAPI.createHarvest(createDTO)
} else {
val updateDTO = harvest.toHarvestDTO() ?: kotlin.run {
return HarvestOperationResponse.Error(
errorMessage = "couldn't create update-dto for harvest ${harvest.id} / ${harvest.localId}"
)
}
backendAPI.updateHarvest(updateDTO)
}
networkResponse.onSuccess { _, data ->
val responseHarvest = data.typed.toCommonHarvest(localId = harvest.localId, modified = false, deleted = false)
return if (responseHarvest != null) {
// Keep local images from local copy, as they are not sent here
try {
HarvestOperationResponse.Success(
harvest = repository.upsertHarvest(
username = username,
harvest = responseHarvest.copy(
images = EntityImages(
remoteImageIds = responseHarvest.images.remoteImageIds,
localImages = harvest.images.localImages,
)
)
)
)
} catch (e: Exception) {
RiistaSDK.crashlyticsLogger.log(e, "Unable to save harvest to DB. id=${responseHarvest.id}")
HarvestOperationResponse.SaveFailure(e.message)
}
} else {
HarvestOperationResponse.NetworkFailure(
statusCode = null,
errorMessage = "Failed to convert successful response to harvest (id = ${data.typed.id})"
)
}
}
networkResponse.onError { statusCode, exception ->
return HarvestOperationResponse.NetworkFailure(statusCode = statusCode, errorMessage = exception?.message)
}
return HarvestOperationResponse.NetworkFailure(
statusCode = null,
errorMessage = "not success nor error (cancelled?)"
)
}
}
| 0 | Kotlin | 0 | 3 | 23645d1abe61c68d649b6d0ca1d16556aa8ffa16 | 4,469 | oma-riista-android | MIT License |
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/harvest/sync/HarvestToNetworkUpdater.kt | suomenriistakeskus | 78,840,058 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 2, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 4, "Gradle Kotlin DSL": 1, "Kotlin": 1344, "XML": 401, "Java": 161, "Protocol Buffer": 1, "JSON": 1} | package fi.riista.common.domain.harvest.sync
import fi.riista.common.RiistaSDK
import fi.riista.common.database.RiistaDatabase
import fi.riista.common.domain.harvest.HarvestOperationResponse
import fi.riista.common.domain.harvest.HarvestRepository
import fi.riista.common.domain.harvest.model.CommonHarvest
import fi.riista.common.domain.harvest.sync.dto.HarvestDTO
import fi.riista.common.domain.harvest.sync.dto.toCommonHarvest
import fi.riista.common.domain.harvest.sync.dto.toHarvestCreateDTO
import fi.riista.common.domain.harvest.sync.dto.toHarvestDTO
import fi.riista.common.domain.model.EntityImages
import fi.riista.common.network.BackendApiProvider
import fi.riista.common.network.calls.NetworkResponse
internal class HarvestToNetworkUpdater(
val backendApiProvider: BackendApiProvider,
database: RiistaDatabase,
) {
private val repository = HarvestRepository(database)
/**
* Sends the given harvest [harvests] to backend and returns a list containing the updated
* [CommonHarvest]s (most likely [CommonHarvest.rev] will differ).
*/
suspend fun update(username: String, harvests: List<CommonHarvest>): List<CommonHarvest> {
val updatedHarvests: List<CommonHarvest> = harvests.map { harvest ->
when (val updateResponse = sendHarvestToBackend(username, harvest)) {
is HarvestOperationResponse.Error,
is HarvestOperationResponse.SaveFailure,
is HarvestOperationResponse.NetworkFailure -> harvest
is HarvestOperationResponse.Success -> updateResponse.harvest
}
}
return updatedHarvests
}
/**
* Sends the given harvest [harvest] to backend and returns a list containing the updated
* [CommonHarvest]s (most likely [CommonHarvest.rev] will differ).
*/
suspend fun sendHarvestToBackend(username: String, harvest: CommonHarvest): HarvestOperationResponse {
if (harvest.localId == null) {
return HarvestOperationResponse.NetworkFailure(
statusCode = null, errorMessage = "missing local id"
)
}
val backendAPI = backendApiProvider.backendAPI
val networkResponse: NetworkResponse<HarvestDTO> = if (harvest.id == null) {
val createDTO = harvest.toHarvestCreateDTO()
backendAPI.createHarvest(createDTO)
} else {
val updateDTO = harvest.toHarvestDTO() ?: kotlin.run {
return HarvestOperationResponse.Error(
errorMessage = "couldn't create update-dto for harvest ${harvest.id} / ${harvest.localId}"
)
}
backendAPI.updateHarvest(updateDTO)
}
networkResponse.onSuccess { _, data ->
val responseHarvest = data.typed.toCommonHarvest(localId = harvest.localId, modified = false, deleted = false)
return if (responseHarvest != null) {
// Keep local images from local copy, as they are not sent here
try {
HarvestOperationResponse.Success(
harvest = repository.upsertHarvest(
username = username,
harvest = responseHarvest.copy(
images = EntityImages(
remoteImageIds = responseHarvest.images.remoteImageIds,
localImages = harvest.images.localImages,
)
)
)
)
} catch (e: Exception) {
RiistaSDK.crashlyticsLogger.log(e, "Unable to save harvest to DB. id=${responseHarvest.id}")
HarvestOperationResponse.SaveFailure(e.message)
}
} else {
HarvestOperationResponse.NetworkFailure(
statusCode = null,
errorMessage = "Failed to convert successful response to harvest (id = ${data.typed.id})"
)
}
}
networkResponse.onError { statusCode, exception ->
return HarvestOperationResponse.NetworkFailure(statusCode = statusCode, errorMessage = exception?.message)
}
return HarvestOperationResponse.NetworkFailure(
statusCode = null,
errorMessage = "not success nor error (cancelled?)"
)
}
}
| 0 | Kotlin | 0 | 3 | 23645d1abe61c68d649b6d0ca1d16556aa8ffa16 | 4,469 | oma-riista-android | MIT License |
woodpecker.acquisition/src/main/kotlin/webint/woodpecker/acquisition/camel/MissionAdderProcessor.kt | gorgia | 189,364,282 | false | {"YAML": 1, "Ignore List": 3, "Maven POM": 4, "Dockerfile": 4, "Text": 2, "Markdown": 2, "JSON": 5, "JavaScript": 10, "HTML": 1, "Vue": 11, "INI": 2, "Kotlin": 53, "Java Properties": 2, "Java": 1} | package webint.woodpecker.acquisition.camel
import org.apache.camel.Exchange
import org.apache.camel.Processor
import org.codehaus.jettison.json.JSONObject
import org.springframework.stereotype.Component
import webint.woodpecker.common.database.mongo.model.Mission
@Component
class MissionAdderProcessor: Processor {
var jsonStatus: JSONObject = JSONObject()
override fun process(exchange: Exchange?) {
val statusString: String? = exchange?.getIn()?.getBody(String::class.java)
this.jsonStatus = JSONObject(statusString)
val mission: Mission? = exchange?.getIn()?.getHeader("mission") as Mission?
if (mission != null) {
this.jsonStatus.put("mission_name", mission.missionName)
this.jsonStatus.put("mission_group", mission.missionGroup)
}
exchange?.getIn()?.body = this.jsonStatus.toString()
}
} | 9 | Kotlin | 0 | 0 | 2390e838e2844a4037bdad945030ca59349e88ba | 883 | woodpecker | Apache License 2.0 |
ViewPager22/app/src/main/java/com/app/mytaxi/ui/pool/PoolAdapter.kt | ajaypro | 225,294,116 | false | null | package com.app.mytaxi.ui.pool
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.app.mytaxi.R
import com.app.mytaxi.data.model.Area
import com.app.mytaxi.ui.base.BaseAdapter
import com.app.mytaxi.ui.base.CommonViewHolder
/**
* Created by <NAME> on 17-11-2019, 23:06
*/
class PoolAdapter(private val locationList: ArrayList<Area>, private val context: Context) :
BaseAdapter<Area, CommonViewHolder>(locationList) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonViewHolder {
return CommonViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_view_pool,
parent,
false
), context
)
}
fun poolData(locationList: List<Area>): List<Area> =
locationList.filter { it.fleetType == "POOLING" }
} | 1 | null | 1 | 1 | 768b70f957cfd6198ad3594c7c50f741542ca674 | 904 | ViewPager2 | Apache License 2.0 |
compose-multiplatform-material2/src/jsMain/kotlin/com/huanshankeji/compose/material2/lazy/ext/LazyDsl.js.kt | huanshankeji | 570,509,992 | false | {"Kotlin": 330635} | package com.huanshankeji.compose.material2.lazy.ext
import androidx.compose.runtime.Composable
import com.huanshankeji.compose.foundation.verticalScrollPlatformModifier
import com.huanshankeji.compose.runtime.DeferredComposableRunner
import com.huanshankeji.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.toAttrs
import dev.petuska.kmdc.list.MDCList
import dev.petuska.kmdc.list.MDCListGroup
import dev.petuska.kmdc.list.MDCListScope
import dev.petuska.kmdc.list.Subheader
import dev.petuska.kmdc.list.item.*
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.ElementScope
import org.w3c.dom.HTMLHeadingElement
import org.w3c.dom.HTMLLIElement
import org.w3c.dom.HTMLUListElement
/**
* This class contains mutable fields.
* @see androidx.compose.foundation.lazy.LazyListScopeImpl
*/
actual class ListScope(
val mdcListScope: MDCListScope<HTMLUListElement>
) {
private val deferredComposableRunner = DeferredComposableRunner()
private fun addComposable(composable: @Composable () -> Unit) =
deferredComposableRunner.addComposable(composable)
@Composable
internal fun ComposableRun(content: ListScope.() -> Unit) =
deferredComposableRunner.ComposableRun { content() }
actual fun item(key: Any?, contentType: Any?, content: @Composable ItemScope.() -> Unit) = addComposable {
mdcListScope.ListItem { ItemScope(this).content() }
}
actual fun items(
count: Int,
key: ((index: Int) -> Any)?,
contentType: (index: Int) -> Any?,
itemContent: @Composable ItemScope.(index: Int) -> Unit
) = addComposable {
repeat(count) { i ->
mdcListScope.ListItem { ItemScope(this).itemContent(i) }
}
}
actual fun group(
key: Any?,
contentType: Any?,
headerContent: @Composable HeaderScope.() -> Unit,
content: ListScope.() -> Unit
) = deferredComposableRunner.addComposable {
MDCListGroup {
Subheader {
HeaderScope(this).headerContent()
}
MDCList {
ListScope(this).ComposableRun(content)
}
}
}
@Composable
actual fun ItemScope.ListItemContent(listItemComponents: ListItemComponents) =
with(listItemComponents) {
mdcListItemScope.Label {
Primary { text() }
secondaryText?.let { Secondary { it() } }
}
}
}
actual class ItemScope(val mdcListItemScope: MDCListItemScope<HTMLLIElement>)
actual class HeaderScope(val headingElementScope: ElementScope<HTMLHeadingElement>)
@Composable
actual fun List(modifier: Modifier, content: ListScope.() -> Unit) =
MDCList(attrs = verticalScrollPlatformModifier.then(modifier.platformModifier).toAttrs()) {
ListScope(this).ComposableRun(content)
}
| 20 | Kotlin | 0 | 16 | 755a2593006cfd9f117793a11efd23f83eecc851 | 2,866 | compose-multiplatform-material | Apache License 2.0 |
adaptive-ui/adaptive-ui-common/src/commonTest/kotlin/hu/simplexion/adaptive/ui/common/testing/fragment/AdaptiveText.kt | spxbhuhb | 788,711,010 | false | {"Kotlin": 1463989, "Java": 17672, "HTML": 2540, "JavaScript": 970} | /*
* Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.adaptive.ui.common.testing.fragment
import hu.simplexion.adaptive.foundation.AdaptiveActual
import hu.simplexion.adaptive.foundation.AdaptiveFragment
import hu.simplexion.adaptive.ui.common.AbstractCommonFragment
import hu.simplexion.adaptive.ui.common.render.CommonRenderData
import hu.simplexion.adaptive.ui.common.support.RawFrame
import hu.simplexion.adaptive.ui.common.support.RawSize
import hu.simplexion.adaptive.ui.common.testing.CommonTestAdapter
import hu.simplexion.adaptive.ui.common.testing.TestReceiver
@AdaptiveActual("test")
open class AdaptiveText(
adapter: CommonTestAdapter,
parent: AdaptiveFragment,
index: Int
) : AbstractCommonFragment<TestReceiver>(adapter, parent, index, 1, 2) {
override val receiver = TestReceiver()
private val content: String
get() = state[0]?.toString() ?: ""
override fun genPatchInternal(): Boolean {
val closureMask = getThisClosureDirtyMask()
if (haveToPatch(closureMask, 1)) {
content
}
if (haveToPatch(closureMask, 1 shl instructionIndex)) {
renderData = CommonRenderData(instructions)
uiAdapter.applyRenderInstructions(this)
}
return false
}
/**
* In web browsers measuring text is not the usual way.
*/
override fun measure(): RawSize = instructedOr { RawSize(content.length * 20.0, 20.0) }
override fun layout(proposedFrame: RawFrame?) {
calcLayoutFrame(proposedFrame)
uiAdapter.applyLayoutToActual(this)
}
} | 13 | Kotlin | 0 | 0 | 2f97d34731f19163e62da8c578802c2915a48572 | 1,692 | adaptive | Apache License 2.0 |
src/main/kotlin/org/grakovne/sideload/kindle/common/validation/ValidationError.kt | GrakovNe | 704,911,851 | false | {"Kotlin": 188270} | package org.grakovne.sideload.kindle.common.validation
open class ValidationError<E : Enum<out E>>(
val code: E
) | 0 | Kotlin | 0 | 4 | 456804a253a49947fa20de0b031c2bb55624f14f | 118 | kindle-sideload | MIT License |
EventSourcing/src/main/kotlin/com/severett/archunitdemo/eventsourcing/serde/InstantSerializer.kt | severn-everett | 619,418,662 | false | {"Kotlin": 62312} | package com.severett.archunitdemo.eventsourcing.serde
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.time.Instant
object InstantSerializer : KSerializer<Instant> {
override val descriptor = PrimitiveSerialDescriptor("Instant", PrimitiveKind.LONG)
override fun deserialize(decoder: Decoder): Instant {
return Instant.ofEpochSecond(decoder.decodeLong())
}
override fun serialize(encoder: Encoder, value: Instant) {
encoder.encodeLong(value.epochSecond)
}
}
| 0 | Kotlin | 0 | 0 | 42549089a04c17f1a2462e346c5d030508a716df | 715 | ArchUnitDemo | Apache License 2.0 |
app/src/main/kotlin/com/mr3y/podcaster/core/sync/SyncNotification.kt | mr3y-the-programmer | 720,570,256 | false | {"Kotlin": 703717, "HTML": 196} | package com.mr3y.podcaster.core.sync
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
import android.content.res.Resources
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.work.ForegroundInfo
import com.mr3y.podcaster.R
import com.mr3y.podcaster.Strings
import com.mr3y.podcaster.ui.resources.EnStrings
private const val SYNC_NOTIFICATION_ID = 10
private const val SYNC_NOTIFICATION_CHANNEL_ID = "SyncNotificationChannel"
/**
* Foreground information when sync workers are being run with a foreground service
*/
fun Context.syncForegroundInfo(): ForegroundInfo {
return if (Build.VERSION.SDK_INT >= 34) {
ForegroundInfo(SYNC_NOTIFICATION_ID, syncWorkNotification(), FOREGROUND_SERVICE_TYPE_SHORT_SERVICE)
} else {
ForegroundInfo(SYNC_NOTIFICATION_ID, syncWorkNotification())
}
}
/**
* Notification displayed when sync workers are being run with a foreground service
*/
private fun Context.syncWorkNotification(): Notification {
val languageCode = Resources.getSystem().configuration.locales[0].language.lowercase()
val strings = Strings[languageCode] ?: EnStrings
val channel = NotificationChannel(
SYNC_NOTIFICATION_CHANNEL_ID,
strings.sync_work_notification_channel_name,
NotificationManager.IMPORTANCE_DEFAULT,
).apply {
description = strings.sync_work_notification_channel_description
}
// Register the channel with the system
val notificationManager: NotificationManager? =
getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
notificationManager?.createNotificationChannel(channel)
return NotificationCompat.Builder(this, SYNC_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(strings.sync_work_notification_title)
.setContentText(strings.sync_work_notification_body)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
}
| 9 | Kotlin | 1 | 26 | fb8212e38ca58b73363a09b5a87ca1bc374ee02a | 2,144 | Podcaster | Apache License 2.0 |
shipments/src/main/java/com/calebk/shipments/ui/composables/ShipmentHistoryCard.kt | CalebKL | 867,208,470 | false | {"Kotlin": 149963} | /*
* Copyright 2024 Movemate
*
* 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.calebk.shipments.ui.composables
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AvTimer
import androidx.compose.material.icons.rounded.History
import androidx.compose.material.icons.rounded.Repeat
import androidx.compose.material3.CardColors
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.calebk.shipments.R
import com.calebk.shipments.models.Category
@Composable
fun ShipmentHistoryCard(modifier: Modifier = Modifier, progress: Category, trackingNumber: String, shippedFrom: String, amount: String) {
OutlinedCard(
modifier = modifier,
colors = CardColors(
contentColor = MaterialTheme.colorScheme.secondary,
containerColor = Color.White,
disabledContentColor = Color.Black,
disabledContainerColor = Color.Black,
),
) {
Row(
modifier = Modifier.padding(top = 12.dp),
) {
Column(
modifier = Modifier
.weight(1f)
.padding(start = 12.dp, bottom = 12.dp),
) {
Surface(
shape = CircleShape,
color = Color.LightGray.copy(alpha = 0.2F),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
) {
when (progress) {
Category.PENDING -> {
Spacer(modifier = Modifier.width(4.dp))
Icon(
modifier = Modifier.size(18.dp),
imageVector = Icons.Rounded.History,
contentDescription = null,
tint = MaterialTheme.colorScheme.tertiary,
)
Spacer(modifier = Modifier.width(4.dp))
Text(
progress.categoryName,
fontSize = 14.sp,
color = MaterialTheme.colorScheme.tertiary,
)
Spacer(modifier = Modifier.width(4.dp))
}
Category.COMPLETED -> {
Spacer(modifier = Modifier.width(4.dp))
Icon(
modifier = Modifier.size(18.dp),
imageVector = Icons.Rounded.AvTimer,
contentDescription = null,
)
Spacer(modifier = Modifier.width(4.dp))
Text(progress.categoryName, fontSize = 14.sp)
Spacer(modifier = Modifier.width(4.dp))
}
Category.IN_PROGRESS -> {
Spacer(modifier = Modifier.width(4.dp))
Icon(
modifier = Modifier.size(18.dp),
imageVector = Icons.Rounded.Repeat,
contentDescription = null,
tint = Color.Green,
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = progress.categoryName,
color = Color.Green,
fontSize = 14.sp,
)
Spacer(modifier = Modifier.width(4.dp))
}
Category.CANCELLED -> {
Spacer(modifier = Modifier.width(4.dp))
Icon(
modifier = Modifier.size(18.dp),
imageVector = Icons.Rounded.AvTimer,
contentDescription = null,
)
Spacer(modifier = Modifier.width(4.dp))
Text(progress.categoryName, fontSize = 14.sp)
Spacer(modifier = Modifier.width(4.dp))
}
}
}
}
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.arriving_today),
style = MaterialTheme.typography.titleMedium,
color = Color.Black,
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.your_delivery_from_is_arriving_today, trackingNumber, shippedFrom),
style = MaterialTheme.typography.bodyMedium,
)
Spacer(modifier = Modifier.height(10.dp))
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = amount,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
)
Spacer(modifier = Modifier.width(6.dp))
Box(
Modifier
.size(6.dp)
.align(Alignment.CenterVertically)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.secondary),
)
Spacer(modifier = Modifier.width(4.dp))
Text(text = stringResource(R.string.sep_20_2023), style = MaterialTheme.typography.bodyMedium)
}
}
Image(
modifier = Modifier
.size(80.dp)
.padding(end = 16.dp)
.align(Alignment.CenterVertically),
painter = painterResource(R.drawable.gray_box),
contentDescription = null,
)
}
}
}
| 0 | Kotlin | 0 | 0 | 3d7a428df7452dd465bf137a5b0b1ea6e5cb8ba7 | 8,237 | Movemate | Apache License 2.0 |
app/src/main/java/com/cafeyvinowinebar/cafe_y_vino_client/ui/carta/carta_display/categories/CategoriesAdapter.kt | dimitriinc | 533,330,209 | false | null | package com.cafeyvinowinebar.cafe_y_vino_client.ui.carta.carta_display.categories
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.cafeyvinowinebar.cafe_y_vino_client.data.data_models.MenuCategoryFirestore
import com.cafeyvinowinebar.cafe_y_vino_client.data.sources.FirebaseStorageSource
import com.cafeyvinowinebar.cafe_y_vino_client.databinding.ListItemMenuBinding
import com.cafeyvinowinebar.cafe_y_vino_client.interfaces.OnItemClickListener
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
class CategoriesAdapter(
options: FirestoreRecyclerOptions<MenuCategoryFirestore>,
val listener: OnItemClickListener,
val fStorage: FirebaseStorageSource
) : FirestoreRecyclerAdapter<MenuCategoryFirestore, CategoriesAdapter.ViewHolder>(options) {
inner class ViewHolder(
private val binding: ListItemMenuBinding
) : RecyclerView.ViewHolder(binding.root) {
init {
binding.apply {
root.setOnClickListener {
if (absoluteAdapterPosition != RecyclerView.NO_POSITION) {
listener.onItemClick(snapshots.getSnapshot(absoluteAdapterPosition))
}
}
}
}
fun bind(model: MenuCategoryFirestore) {
binding.apply {
txtCategoryName.text = model.name
Glide.with(root)
.load(fStorage.getImgReference(model.image!!))
.into(imgCategory)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ListItemMenuBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int, model: MenuCategoryFirestore) {
holder.bind(model)
}
} | 0 | Kotlin | 0 | 0 | 4ec7f76453621fe743501362f832b32fc0f070be | 2,039 | cafe-y-vino-app-client-kotlin | MIT License |
gsonparser/src/main/kotlin/snitch/parsers/GsonJsonParser.kt | memoizr | 322,370,926 | false | null | package snitch.parsers
import com.google.gson.*
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import snitch.parsers.GsonJsonParser.serialized
import snitch.parsing.Parser
import snitch.parsing.ParsingException
import snitch.types.Sealed
import java.lang.reflect.Type
class SealedAdapter : JsonDeserializer<Sealed> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Sealed {
val type = json?.asJsonObject?.get("\$type")?.serialized
val rawType = TypeToken.get(typeOfT).rawType
return rawType.kotlin.sealedSubclasses
.firstOrNull { it.simpleName == type?.replace("\"", "") }
?.let {
Gson().fromJson(json, it.java) as Sealed
} ?: Gson().fromJson(json, rawType) as Sealed
}
}
object GsonJsonParser : Parser {
val builder = GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
.registerTypeAdapterFactory(NullableTypAdapterFactory())
.registerTypeHierarchyAdapter(Sealed::class.java, SealedAdapter())
val gson = builder.create()
override val Any.serialized get() = gson.toJson(this)
override val Any.serializedBytes: ByteArray
get() = TODO("Not yet implemented")
override fun <T : Any> String.parse(klass: Class<T>): T {
return try {
gson.fromJson(this, klass)
} catch (e: JsonSyntaxException) {
throw ParsingException(e)
}
}
inline fun <reified T : Any> String.parseJson(): T {
return try {
gson.fromJson(this, T::class.java)
} catch (e: JsonSyntaxException) {
throw ParsingException(e)
}
}
override fun <T : Any> ByteArray.parse(klass: Class<T>): T = try {
gson.fromJson(JsonReader(this.inputStream().bufferedReader()), klass)
} catch (e: JsonSyntaxException) {
throw ParsingException(e)
}
} | 0 | Kotlin | 2 | 34 | 501b43074653207279fe3646a8f8519520967c3b | 1,961 | snitch | Apache License 2.0 |
topicos/11_caracteres/respostas/NomeValido.kt | erosvitor | 472,988,632 | false | null | import java.util.Scanner
fun main() {
println("Nome válido")
println("")
val leitura = Scanner(System.`in`)
print("Digite o nome completo de uma pessoa: ")
val nome = leitura.nextLine()
var caractere:Char
var nomeValido = true
for (i in nome.indices) {
caractere = nome[i]
if (!caractere.isLetter() && !caractere.isWhitespace()) {
nomeValido = false
break
}
}
if (nomeValido) {
println("O nome informado é válido")
} else {
println("O nome informado é inválido")
}
}
| 0 | Kotlin | 0 | 0 | 9096d68846eec13f91196a75e106855460e7ef1c | 532 | curso-kotlin-fundamentos | MIT License |
modules/fx/arrow-fx/src/main/kotlin/arrow/fx/IOParMap.kt | alexbuczynsky | 242,268,026 | true | {"Kotlin": 3017035, "CSS": 85447, "JavaScript": 26157, "HTML": 22172, "Scala": 8073, "Shell": 6915, "Java": 4465, "Ruby": 1598} | package arrow.fx
import arrow.core.Either
import arrow.core.Left
import arrow.core.None
import arrow.core.Option
import arrow.core.Right
import arrow.core.Tuple2
import arrow.core.Tuple3
import arrow.core.extensions.option.applicative.applicative
import arrow.core.internal.AtomicRefW
import arrow.core.nonFatalOrThrow
import arrow.core.none
import arrow.core.some
import arrow.fx.internal.IOForkedStart
import arrow.fx.internal.Platform
import kotlin.coroutines.CoroutineContext
import arrow.core.extensions.option.applicativeError.handleError
import arrow.core.internal.AtomicBooleanW
/** Mix-in to enable `parMapN` 2-arity on IO's companion directly. */
interface IOParMap {
fun <A, B, C> parMapN(fa: IOOf<A>, fb: IOOf<B>, f: (A, B) -> C): IO<C> =
IO.parMapN(IODispatchers.CommonPool, fa, fb, f)
fun <A, B, C, D> parMapN(fa: IOOf<A>, fb: IOOf<B>, fc: IOOf<C>, f: (A, B, C) -> D): IO<D> =
IO.parMapN(IODispatchers.CommonPool, fa, fb, fc, f)
fun <A, B, C, D, E> parMapN(fa: IOOf<A>, fb: IOOf<B>, fc: IOOf<C>, fd: IOOf<D>, f: (A, B, C, D) -> E): IOOf<E> =
IO.parMapN(IODispatchers.CommonPool, fa, fb, fc, fd, f)
/**
* @see parMapN
*/
fun <A, B, C, D, E, G> parMapN(fa: IOOf<A>, fb: IOOf<B>, fc: IOOf<C>, fd: IOOf<D>, fe: IOOf<E>, f: (A, B, C, D, E) -> G): IO<G> =
IO.parMapN(IODispatchers.CommonPool, fa, fb, fc, fd, fe, f)
/**
* @see parMapN
*/
fun <A, B, C, D, E, G, H> parMapN(fa: IOOf<A>, fb: IOOf<B>, fc: IOOf<C>, fd: IOOf<D>, fe: IOOf<E>, fg: IOOf<G>, f: (A, B, C, D, E, G) -> H): IO<H> =
IO.parMapN(IODispatchers.CommonPool, fa, fb, fc, fd, fe, fg, f)
/**
* @see parMapN
*/
fun <A, B, C, D, E, G, H, I> parMapN(fa: IOOf<A>, fb: IOOf<B>, fc: IOOf<C>, fd: IOOf<D>, fe: IOOf<E>, fg: IOOf<G>, fh: IOOf<H>, f: (A, B, C, D, E, G, H) -> I): IO<I> =
IO.parMapN(IODispatchers.CommonPool, fa, fb, fc, fd, fe, fg, fh, f)
/**
* @see parMapN
*/
fun <A, B, C, D, E, G, H, I, J> parMapN(fa: IOOf<A>, fb: IOOf<B>, fc: IOOf<C>, fd: IOOf<D>, fe: IOOf<E>, fg: IOOf<G>, fh: IOOf<H>, fi: IOOf<I>, f: (A, B, C, D, E, G, H, I) -> J): IO<J> =
IO.parMapN(IODispatchers.CommonPool, fa, fb, fc, fd, fe, fg, fh, fi, f)
/**
* @see parMapN
*/
fun <A, B, C, D, E, G, H, I, J, K> parMapN(fa: IOOf<A>, fb: IOOf<B>, fc: IOOf<C>, fd: IOOf<D>, fe: IOOf<E>, fg: IOOf<G>, fh: IOOf<H>, fi: IOOf<I>, fj: IOOf<J>, f: (A, B, C, D, E, G, H, I, J) -> K): IO<K> =
IO.parMapN(IODispatchers.CommonPool, fa, fb, fc, fd, fe, fg, fh, fi, fj, f)
fun <A, B, C> parMapN(ctx: CoroutineContext, fa: IOOf<A>, fb: IOOf<B>, f: (A, B) -> C): IO<C> = IO.Async(true) { conn, cb ->
// Used to store Throwable, Either<A, B> or empty (null). (No sealed class used for a slightly better performing ParMap2)
val state = AtomicRefW<Any?>(null)
val connA = IOConnection()
val connB = IOConnection()
conn.pushPair(connA, connB)
fun complete(a: A, b: B) {
conn.pop()
cb(try {
Either.Right(f(a, b))
} catch (e: Throwable) {
Either.Left(e.nonFatalOrThrow())
})
}
fun sendError(other: IOConnection, e: Throwable) = when (state.getAndSet(e)) {
is Throwable -> Unit // Do nothing we already finished
else -> other.cancel().fix().unsafeRunAsync { r ->
conn.pop()
cb(Left(r.fold({ e2 -> Platform.composeErrors(e, e2) }, { e })))
}
}
IORunLoop.startCancelable(IOForkedStart(fa, ctx), connA) { resultA ->
resultA.fold({ e ->
sendError(connB, e)
}, { a ->
when (val oldState = state.getAndSet(Left(a))) {
null -> Unit // Wait for B
is Throwable -> Unit // ParMapN already failed and A was cancelled.
is Either.Left<*> -> Unit // Already state.getAndSet
is Either.Right<*> -> complete(a, (oldState as Either.Right<B>).b)
}
})
}
IORunLoop.startCancelable(IOForkedStart(fb, ctx), connB) { resultB ->
resultB.fold({ e ->
sendError(connA, e)
}, { b ->
when (val oldState = state.getAndSet(Right(b))) {
null -> Unit // Wait for A
is Throwable -> Unit // ParMapN already failed and B was cancelled.
is Either.Right<*> -> Unit // IO cannot finish twice
is Either.Left<*> -> complete((oldState as Either.Left<A>).a, b)
}
})
}
}
fun <A, B, C, D> parMapN(ctx: CoroutineContext, fa: IOOf<A>, fb: IOOf<B>, fc: IOOf<C>, f: (A, B, C) -> D): IO<D> = IO.Async(true) { conn, cb ->
val state: AtomicRefW<Option<Tuple3<Option<A>, Option<B>, Option<C>>>> = AtomicRefW(None)
val active = AtomicBooleanW(true)
val connA = IOConnection()
val connB = IOConnection()
val connC = IOConnection()
// Composite cancelable that cancels all ops.
// NOTE: conn.pop() called when cb gets called below in complete.
conn.push(connA.cancel(), connB.cancel(), connC.cancel())
fun complete(a: A, b: B, c: C) {
conn.pop()
val result: Either<Throwable, D> = try {
Either.Right(f(a, b, c))
} catch (e: Throwable) {
Either.Left(e.nonFatalOrThrow())
}
cb(result)
}
fun tryComplete(result: Option<Tuple3<Option<A>, Option<B>, Option<C>>>): Unit =
result.fold({ Unit }, { (a, b, c) -> Option.applicative().map(a, b, c) { (a, b, c) -> complete(a, b, c) } })
fun sendError(other: IOConnection, other2: IOConnection, e: Throwable) =
if (active.getAndSet(false)) { // We were already cancelled so don't do anything.
other.cancel().fix().unsafeRunAsync { r1 ->
other2.cancel().fix().unsafeRunAsync { r2 ->
conn.pop()
cb(Left(r1.fold({ e2 ->
r2.fold({ e3 -> Platform.composeErrors(e, e2, e3) }, { Platform.composeErrors(e, e2) })
}, {
r2.fold({ e3 -> Platform.composeErrors(e, e3) }, { e })
})))
}
}
} else Unit
IORunLoop.startCancelable(IOForkedStart(fa, ctx), connA) { resultA ->
resultA.fold({ e ->
sendError(connB, connC, e)
}, { a ->
tryComplete(state.updateAndGet { current ->
current
.map { it.copy(a = a.some()) }
.handleError { Tuple3(a.some(), none(), none()) }
})
})
}
IORunLoop.startCancelable(IOForkedStart(fb, ctx), connB) { resultB ->
resultB.fold({ e ->
sendError(connA, connC, e)
}, { b ->
tryComplete(state.updateAndGet { current ->
current
.map { it.copy(b = b.some()) }
.handleError { Tuple3(none(), b.some(), none()) }
})
})
}
IORunLoop.startCancelable(IOForkedStart(fc, ctx), connC) { resultC ->
resultC.fold({ e ->
sendError(connA, connB, e)
}, { c ->
tryComplete(state.updateAndGet { current ->
current
.map { it.copy(c = c.some()) }
.handleError { Tuple3(none(), none(), c.some()) }
})
})
}
}
/**
* @see parMapN
*/
fun <A, B, C, D, E> parMapN(
ctx: CoroutineContext,
fa: IOOf<A>,
fb: IOOf<B>,
fc: IOOf<C>,
fd: IOOf<D>,
f: (A, B, C, D) -> E
): IOOf<E> = IO.parMapN(ctx,
IO.parMapN(ctx, fa, fb, ::Tuple2),
IO.parMapN(ctx, fc, fd, ::Tuple2)
) { (a, b), (c, d) ->
f(a, b, c, d)
}
/**
* @see parMapN
*/
fun <A, B, C, D, E, G> parMapN(
ctx: CoroutineContext,
fa: IOOf<A>,
fb: IOOf<B>,
fc: IOOf<C>,
fd: IOOf<D>,
fe: IOOf<E>,
f: (A, B, C, D, E) -> G
): IO<G> = IO.parMapN(ctx,
IO.parMapN(ctx, fa, fb, fc, ::Tuple3),
IO.parMapN(ctx, fd, fe, ::Tuple2)
) { (a, b, c), (d, e) ->
f(a, b, c, d, e)
}
/**
* @see parMapN
*/
fun <A, B, C, D, E, G, H> parMapN(
ctx: CoroutineContext,
fa: IOOf<A>,
fb: IOOf<B>,
fc: IOOf<C>,
fd: IOOf<D>,
fe: IOOf<E>,
fg: IOOf<G>,
f: (A, B, C, D, E, G) -> H
): IO<H> = IO.parMapN(ctx,
IO.parMapN(ctx, fa, fb, fc, ::Tuple3),
IO.parMapN(ctx, fd, fe, fg, ::Tuple3)
) { (a, b, c), (d, e, g) ->
f(a, b, c, d, e, g)
}
/**
* @see parMapN
*/
fun <A, B, C, D, E, G, H, I> parMapN(
ctx: CoroutineContext,
fa: IOOf<A>,
fb: IOOf<B>,
fc: IOOf<C>,
fd: IOOf<D>,
fe: IOOf<E>,
fg: IOOf<G>,
fh: IOOf<H>,
f: (A, B, C, D, E, G, H) -> I
): IO<I> = IO.parMapN(ctx,
IO.parMapN(ctx, fa, fb, fc, ::Tuple3),
IO.parMapN(ctx, fd, fe, ::Tuple2),
IO.parMapN(ctx, fg, fh, ::Tuple2)) { (a, b, c), (d, e), (g, h) ->
f(a, b, c, d, e, g, h)
}
/**
* @see parMapN
*/
fun <A, B, C, D, E, G, H, I, J> parMapN(
ctx: CoroutineContext,
fa: IOOf<A>,
fb: IOOf<B>,
fc: IOOf<C>,
fd: IOOf<D>,
fe: IOOf<E>,
fg: IOOf<G>,
fh: IOOf<H>,
fi: IOOf<I>,
f: (A, B, C, D, E, G, H, I) -> J
): IO<J> = IO.parMapN(ctx,
IO.parMapN(ctx, fa, fb, fc, ::Tuple3),
IO.parMapN(ctx, fd, fe, fg, ::Tuple3),
IO.parMapN(ctx, fh, fi, ::Tuple2)) { (a, b, c), (d, e, g), (h, i) ->
f(a, b, c, d, e, g, h, i)
}
/**
* @see parMapN
*/
fun <A, B, C, D, E, G, H, I, J, K> parMapN(
ctx: CoroutineContext,
fa: IOOf<A>,
fb: IOOf<B>,
fc: IOOf<C>,
fd: IOOf<D>,
fe: IOOf<E>,
fg: IOOf<G>,
fh: IOOf<H>,
fi: IOOf<I>,
fj: IOOf<J>,
f: (A, B, C, D, E, G, H, I, J) -> K
): IO<K> = IO.parMapN(ctx,
IO.parMapN(ctx, fa, fb, fc, ::Tuple3),
IO.parMapN(ctx, fd, fe, fg, ::Tuple3),
IO.parMapN(ctx, fh, fi, fj, ::Tuple3)) { (a, b, c), (d, e, g), (h, i, j) ->
f(a, b, c, d, e, g, h, i, j)
}
}
| 0 | null | 0 | 0 | 754a4467f1fc1a9dcf7a0d5b890e70198a7f51b0 | 9,575 | arrow | Apache License 2.0 |
src/main/kotlin/com/github/akraskovski/trade/desk/stub/domain/model/campaign/Campaign.kt | akraskovski | 166,193,214 | false | null | package com.github.akraskovski.trade.desk.stub.domain.model.campaign
import com.github.akraskovski.trade.desk.stub.domain.model.Availability
import com.github.akraskovski.trade.desk.stub.domain.model.Money
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.util.*
/**
* Domain Campaign object.
*/
@Document
class Campaign(
@field:Id var id: String? = null,
var advertiserId: String? = null,
var name: String? = null,
var description: String? = null,
var budget: Money? = null,
var budgetInImpressions: Int? = null,
var dailyBudget: Money? = null,
var dailyBudgetInImpressions: Int? = null,
var startDate: Date? = null,
var endDate: Date? = null,
var availability: Availability? = null,
var pacingMode: String? = null
)
| 0 | Kotlin | 0 | 0 | c66cd9b5ba08cff5b70403f819ccec91878d97a6 | 841 | trade-desk-stub | Apache License 2.0 |
app/src/main/kotlin/com/wb/albumapp/album/AlbumViewModel.kt | waynils | 756,295,236 | false | {"Kotlin": 99166} | package com.wb.albumapp.album
import androidx.lifecycle.ViewModel
import com.wb.albumApp.R
import com.wb.ui.compose.molecules.toppappbar.TopBarAppData
import com.wb.ui.utils.UIString
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
@HiltViewModel
class AlbumViewModel @Inject constructor(
private val albumUIMapper: AlbumUIMapper
) : ViewModel() {
private val mutableTopBarAppStateFlow: MutableStateFlow<TopBarAppData> =
MutableStateFlow(
TopBarAppData(
title = UIString.Resource(R.string.title_albums),
hasBackButton = false
)
)
val topAppBarStateFlow = mutableTopBarAppStateFlow.asStateFlow()
fun updateTopAppBarList() = mutableTopBarAppStateFlow.tryEmit(
albumUIMapper.toTopAppBarData(R.string.title_albums, hasBackButton = false)
)
fun updateTopAppBarDetail() = mutableTopBarAppStateFlow.tryEmit(
albumUIMapper.toTopAppBarData(R.string.title_album, hasBackButton = true)
)
}
| 0 | Kotlin | 0 | 0 | 57adf7bd499cf1f64633f8c9d427a326208d3c61 | 1,125 | Album-app | Apache License 2.0 |
app/src/main/java/com/imran/jobmob/ui/adapter/IBaseClickListener.kt | imrandev | 324,238,442 | false | null | package com.imran.jobmob.ui.adapter
import android.view.View
interface IBaseClickListener<T> {
fun onItemClicked(view: View?, item: T, position: Int)
} | 0 | Kotlin | 0 | 0 | 2c0095bf9c1c342f57fd551a928064a0f48a3037 | 157 | jobmob | Apache License 2.0 |
app/src/main/java/com/example/ad_demo/ui/view/MainFragment.kt | givemepassxd999 | 688,532,845 | false | {"Kotlin": 19447} | package com.example.ad_demo.ui.view
import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.ad_demo.R
import com.example.ad_demo.data.repository.AdRepositoryImpl
import com.example.ad_demo.databinding.CreateItemBinding
import com.example.ad_demo.databinding.FragmentMainBinding
import com.example.ad_demo.network.ApiService
import com.example.ad_demo.network.AppClientManager
import com.example.ad_demo.ui.adapter.ItemAdapter
import com.example.ad_demo.ui.viewmodel.MainViewModel
import com.example.ad_demo.utils.Status
import com.example.ad_demo.utils.ViewHolderType
import com.example.ad_sdk.ad.AdData
import com.example.ad_sdk.ad.AdLoader
import com.example.ad_sdk.ad.OnAdListener
import com.example.ad_sdk.ad.OnAdLoadedListener
class MainFragment : Fragment() {
private lateinit var fragmentMainBinding: FragmentMainBinding
private lateinit var adViewModel: MainViewModel
private val adapter = ItemAdapter()
private val adList = arrayListOf<AdLoader>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
adViewModel = MainViewModel(
AdRepositoryImpl(
AppClientManager.creteRestfulApiClient().create(
ApiService::class.java
)
)
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
fragmentMainBinding = FragmentMainBinding.inflate(layoutInflater)
return fragmentMainBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(fragmentMainBinding) {
val linearLayoutManager = LinearLayoutManager(context)
dataList.layoutManager = linearLayoutManager
dataList.adapter = adapter
with(adViewModel) {
fetchNews().observe(viewLifecycleOwner) {
when (it.status) {
Status.SUCCESS -> {
progressBar.visibility = View.GONE
adapter.submitList(it.data) {
activity?.let { aty ->
it.data?.let { list ->
adList.add(setAdLoader(activity = aty, dataList, list, 20))
adList.add(setAdLoader(activity = aty, dataList, list, 30))
}
}
}
}
Status.LOADING -> {
progressBar.visibility = View.VISIBLE
}
Status.ERROR -> {
progressBar.visibility = View.GONE
}
}
}
}
}
}
private fun setAdLoader(
activity: Activity,
recyclerView: RecyclerView,
list: ArrayList<ViewHolderType>,
position: Int,
): AdLoader {
val v = createView()
return AdLoader()
.init(activity, recyclerView, position)
.forAd(object : OnAdLoadedListener {
override fun onAdInitCompleted(adData: AdData) {
//create custom view in holder
val info = v.findViewById<TextView>(R.id.text_info)
info.text = adData.adName
info.setBackgroundColor(Color.RED)
list.add(
position,
ViewHolderType.Ad(v, adData)
)
adapter.submitList(list)
}
})
.withAdListener(object : OnAdListener {
override fun onAdImpression() {
//client handle impression event
}
})
}
override fun onDestroyView() {
super.onDestroyView()
adList.forEach {
it.release()
}
}
private fun createView(): View {
val binding = CreateItemBinding.bind(
LayoutInflater.from(context).inflate(R.layout.create_item, null)
)
return binding.root
}
companion object {
fun newInstance(): MainFragment {
return MainFragment()
}
}
} | 0 | Kotlin | 0 | 0 | e5d0c28e384c7a9e06498404c09f157519c8c4db | 4,766 | ad_demo | Apache License 2.0 |
EnumIntegrateX/src/main/kotlin/com/example/demo/view/dashboard/DashboardView.kt | dylandasilva1999 | 385,648,798 | false | null | package com.example.demo.view.dashboard
import com.example.demo.app.Styles
import com.example.demo.controller.dashboard.DashboardController
import com.example.demo.controller.staff.AdminStaffController
import com.example.demo.controller.students.StudentsController
import com.example.demo.model.AdminStaffModel
import com.example.demo.view.funds.FundsView
import com.example.demo.view.staff.StaffView
import com.example.demo.view.students.StudentsView
import com.example.demo.view.subjects.SubjectsView
import com.example.demo.view.dashboard.adminListDashbooard.AdminListDashboardView
import com.example.demo.view.login.LoginView
import javafx.geometry.Pos
import javafx.scene.paint.Color
import javafx.scene.text.FontWeight
import tornadofx.*
class DashboardView : View("Dashboard View") {
//Instance of dashboardController
val dashboardController: DashboardController by inject()
//Instance of studentsController
val studentsController: StudentsController by inject()
//Students List
val students = studentsController.studentsList
//Instance of adminStaffController
val adminStaffController: AdminStaffController by inject()
//AdminStaff List
val adminStaffList = adminStaffController.adminStaffList
//Admin staff
val adminStaff: AdminStaffModel by inject()
//Root Layout
override val root = hbox {
style {
backgroundColor = multi(Styles.mutedDarkBlueColor, Styles.mutedDarkBlueColor, Styles.mutedDarkBlueColor)
}
setPrefSize(1920.0, 1080.0)
//Side Bar Menu
hbox {
hboxConstraints {
alignment = Pos.BASELINE_LEFT
}
useMaxHeight = true
stackpane {
rectangle {
width = 340.0
height = 1080.0
strokeWidth = 1.0
fill = Styles.darkBlueColor
opacity = 1.0
}
vbox {
imageview("side-bar-logo.png") {
vboxConstraints {
marginTop = 30.0
alignment = Pos.TOP_CENTER
}
fitHeight = 60.0
fitWidth = 230.0
isPreserveRatio = true
}
rectangle {
vboxConstraints {
marginTop = 20.0
}
width = 230.0
height = 2.0
strokeWidth = 1.0
fill = Color.WHITE
opacity = 0.1
}
button("Dashboard") {
action {
find(DashboardView::class).refreshable
}
vboxConstraints {
marginTop = 20.0
prefWidth = 230.0
alignment = Pos.CENTER_LEFT
}
imageview("dashboard-menu-icon.png") {
fitHeight = 16.0
fitWidth = 16.0
isPreserveRatio = true
}
style {
fontSize = 20.px
borderWidth += box(1.5.px)
backgroundRadius += box(9.px)
fontFamily = "Source Sans Pro"
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
backgroundColor =
multi(Styles.mutedDarkBlueColor, Styles.mutedDarkBlueColor, Styles.mutedDarkBlueColor)
}
paddingAll = 15.0
paddingLeft = 40.0
}
button("Students") {
action {
find(DashboardView::class).replaceWith(StudentsView::class, sizeToScene = true, centerOnScreen = true, transition = ViewTransition.Fade(0.2.seconds))
}
vboxConstraints {
marginTop = 10.0
prefWidth = 230.0
alignment = Pos.CENTER_LEFT
}
imageview("students-menu-icon.png") {
fitHeight = 22.0
fitWidth = 22.0
isPreserveRatio = true
}
style {
fontSize = 20.px
borderWidth += box(1.5.px)
backgroundRadius += box(9.px)
fontFamily = "Source Sans Pro"
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
backgroundColor = multi(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
}
paddingAll = 12.0
paddingLeft = 34.0
}
button("Subjects") {
action {
find(DashboardView::class).replaceWith(SubjectsView::class, sizeToScene = true, centerOnScreen = true, transition = ViewTransition.Fade(0.2.seconds))
}
vboxConstraints {
marginTop = 10.0
prefWidth = 230.0
alignment = Pos.CENTER_LEFT
}
imageview("subjects-menu-icon.png") {
fitHeight = 18.0
fitWidth = 18.0
isPreserveRatio = true
}
style {
fontSize = 20.px
borderWidth += box(1.5.px)
backgroundRadius += box(9.px)
fontFamily = "Source Sans Pro"
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
backgroundColor = multi(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
}
paddingAll = 12.0
paddingLeft = 38.0
}
button("Staff") {
action {
find(DashboardView::class).replaceWith(StaffView::class, sizeToScene = true, centerOnScreen = true, transition = ViewTransition.Fade(0.2.seconds))
}
vboxConstraints {
marginTop = 10.0
prefWidth = 230.0
alignment = Pos.CENTER_LEFT
}
imageview("staff-menu-icon.png") {
fitHeight = 18.0
fitWidth = 18.0
isPreserveRatio = true
}
style {
fontSize = 20.px
borderWidth += box(1.5.px)
backgroundRadius += box(9.px)
fontFamily = "Source Sans Pro"
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
backgroundColor = multi(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
}
paddingAll = 12.0
paddingLeft = 40.0
}
button("Funds") {
action {
find(DashboardView::class).replaceWith(FundsView::class, sizeToScene = true, centerOnScreen = true, transition = ViewTransition.Fade(0.2.seconds))
}
vboxConstraints {
marginTop = 10.0
prefWidth = 230.0
alignment = Pos.CENTER_LEFT
}
imageview("funds-menu-icon.png") {
fitHeight = 18.0
fitWidth = 18.0
isPreserveRatio = true
}
style {
fontSize = 20.px
borderWidth += box(1.5.px)
backgroundRadius += box(9.px)
fontFamily = "Source Sans Pro"
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
backgroundColor = multi(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
}
paddingAll = 12.0
paddingLeft = 38.0
}
vbox {
vboxConstraints {
alignment = Pos.BOTTOM_LEFT
marginTop = 440.0
}
label("YOUR ACCOUNT") {
vboxConstraints {
alignment = Pos.BOTTOM_LEFT
marginLeft = 55.0
}
style {
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
fontSize = 20.px
fontFamily = "Source Sans Pro"
}
}
rectangle {
vboxConstraints {
marginTop = 10.0
marginLeft = 55.0
}
width = 230.0
height = 2.0
strokeWidth = 1.0
fill = Color.WHITE
opacity = 0.1
}
hbox {
imageview("profile-menu-image.png") {
hboxConstraints {
alignment = Pos.BOTTOM_LEFT
marginLeft = 55.0
marginTop = 20.0
}
fitHeight = 45.0
fitWidth = 45.0
isPreserveRatio = true
}
vbox {
label("Dylan da Silva") {
vboxConstraints {
alignment = Pos.CENTER
marginLeft = 20.0
marginTop = 20.0
}
style {
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
fontSize = 20.px
fontFamily = "Source Sans Pro"
}
}
label("Administrator") {
vboxConstraints {
alignment = Pos.CENTER
marginLeft = 20.0
}
style {
fontWeight = FontWeight.EXTRA_LIGHT
textFill = Color.WHITE
opacity = 0.38
fontSize = 14.px
fontFamily = "Source Sans Pro"
}
}
}
}
button("Sign out") {
vboxConstraints {
marginLeft = 55.0
marginTop = 20.0
marginRight = 55.0
}
action {
find(DashboardView::class).replaceWith(LoginView::class, sizeToScene = true, centerOnScreen = true, transition = ViewTransition.Slide(0.5.seconds))
}
style {
fontSize = 20.px
borderWidth += box(2.5.px)
backgroundRadius += box(9.px)
fontFamily = "Source Sans Pro"
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
backgroundColor = multi(Styles.yellowColor, Styles.yellowColor, Styles.yellowColor)
}
useMaxWidth = true
paddingAll = 15.0
}
}
}
}
}
//Main Content Section (Right Side)
vbox {
vboxConstraints {
alignment = Pos.CENTER_RIGHT
}
useMaxHeight = true
useMaxWidth = true
stackpane {
rectangle {
arcHeight = 90.0
arcWidth = 90.0
width = 1480.0
height = 920.0
strokeWidth = 1.0
fill = Styles.darkBlueColor
opacity = 1.0
}
vbox {
label("Dashboard") {
vboxConstraints {
marginTop = 60.0
marginLeft = 70.0
}
style {
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
fontSize = 36.px
fontFamily = "Source Sans Pro"
}
}
label("Open Window Insitute") {
vboxConstraints {
marginTop = -5.0
marginLeft = 70.0
}
style {
fontWeight = FontWeight.EXTRA_LIGHT
textFill = Color.WHITE
opacity = 0.75
fontSize = 20.px
fontFamily = "Source Sans Pro"
}
}
hbox() {
hboxConstraints {
paddingLeft = 70.0
paddingTop = 30.0
}
stackpane {
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 305.0
height = 200.0
strokeWidth = 1.0
fill = Styles.mutedDarkBlueColor
opacity = 1.0
}
vbox {
imageview("diploma-students-icon.png") {
vboxConstraints {
marginTop = 32.0
marginLeft = 45.0
}
fitHeight = 55.0
fitWidth = 55.0
isPreserveRatio = true
}
label(dashboardController.getTotalDiplomaStudents()) {
vboxConstraints {
marginLeft = 45.0
}
style {
fontWeight = FontWeight.EXTRA_BOLD
textFill = Styles.blueColor
fontSize = 50.px
fontFamily = "Source Sans Pro"
}
}
label("Diploma Students") {
vboxConstraints {
marginTop = -10.0
marginLeft = 45.0
}
style {
fontWeight = FontWeight.EXTRA_LIGHT
textFill = Color.WHITE
fontSize = 22.px
fontFamily = "Source Sans Pro"
}
}
}
}
stackpane {
stackpaneConstraints {
paddingLeft = 40.0
}
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 305.0
height = 200.0
strokeWidth = 1.0
fill = Styles.mutedDarkBlueColor
opacity = 1.0
}
vbox {
imageview("degree-students-icon.png") {
vboxConstraints {
marginTop = 32.0
marginLeft = 45.0
}
fitHeight = 55.0
fitWidth = 55.0
isPreserveRatio = true
}
label(dashboardController.getTotalDegreeStudents()) {
vboxConstraints {
marginLeft = 45.0
}
style {
fontWeight = FontWeight.EXTRA_BOLD
textFill = Styles.yellowColor
fontSize = 50.px
fontFamily = "Source Sans Pro"
}
}
label("Degree Students") {
vboxConstraints {
marginTop = -10.0
marginLeft = 45.0
}
style {
fontWeight = FontWeight.EXTRA_LIGHT
textFill = Color.WHITE
fontSize = 22.px
fontFamily = "Source Sans Pro"
}
}
}
}
stackpane {
stackpaneConstraints {
paddingLeft = 40.0
}
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 305.0
height = 200.0
strokeWidth = 1.0
fill = Styles.mutedDarkBlueColor
opacity = 1.0
}
vbox {
imageview("staff-icon.png") {
vboxConstraints {
marginTop = 32.0
marginLeft = 45.0
}
fitHeight = 55.0
fitWidth = 55.0
isPreserveRatio = true
}
label(dashboardController.getTotalAdminStaff()) {
vboxConstraints {
marginLeft = 45.0
}
style {
fontWeight = FontWeight.EXTRA_BOLD
textFill = Styles.orangeColor
fontSize = 50.px
fontFamily = "Source Sans Pro"
}
}
label("Administrative Staff") {
vboxConstraints {
marginTop = -10.0
marginLeft = 45.0
}
style {
fontWeight = FontWeight.EXTRA_LIGHT
textFill = Color.WHITE
fontSize = 22.px
fontFamily = "Source Sans Pro"
}
}
}
}
stackpane {
stackpaneConstraints {
paddingLeft = 40.0
}
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 305.0
height = 200.0
strokeWidth = 1.0
fill = Styles.mutedDarkBlueColor
opacity = 1.0
}
vbox {
imageview("staff-icon.png") {
vboxConstraints {
marginTop = 32.0
marginLeft = 45.0
}
fitHeight = 55.0
fitWidth = 55.0
isPreserveRatio = true
}
label(dashboardController.getTotalAcademicStaff()) {
vboxConstraints {
marginLeft = 45.0
}
style {
fontWeight = FontWeight.EXTRA_BOLD
textFill = Styles.orangeColor
fontSize = 50.px
fontFamily = "Source Sans Pro"
}
}
label("Academic Staff") {
vboxConstraints {
marginTop = -10.0
marginLeft = 45.0
}
style {
fontWeight = FontWeight.EXTRA_LIGHT
textFill = Color.WHITE
fontSize = 22.px
fontFamily = "Source Sans Pro"
}
}
}
}
}
vbox {
label("Overview") {
vboxConstraints {
marginTop = 30.0
marginLeft = 70.0
}
style {
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
fontSize = 30.px
fontFamily = "Source Sans Pro"
}
}
hbox {
stackpane {
stackpaneConstraints {
paddingLeft = 70.0
paddingTop = 30.0
}
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 305.0
height = 400.0
strokeWidth = 1.0
fill = Styles.blueColor
opacity = 1.0
}
vbox {
label("Admin Staff") {
vboxConstraints {
marginTop = 30.0
marginLeft = 45.0
}
style {
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
fontSize = 22.px
fontFamily = "Source Sans Pro"
}
}
vbox {
var i: Int = 0
for (adminStaff in adminStaffList) {
if(i < 3) {
add(AdminListDashboardView(AdminStaffModel(adminStaff)))
i++
}
}
}
}
}
stackpane {
stackpaneConstraints {
paddingLeft = 40.0
paddingTop = 30.0
}
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 380.0
height = 400.0
strokeWidth = 1.0
fill = Styles.yellowColor
opacity = 1.0
}
vbox {
label("Pool Fund") {
vboxConstraints {
marginTop = 30.0
marginLeft = 45.0
}
style {
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
fontSize = 22.px
fontFamily = "Source Sans Pro"
}
}
vbox {
imageview("pool-fund-graph.png") {
vboxConstraints {
marginTop = 40.0
marginLeft = 40.0
}
fitHeight = 200.0
fitWidth = 300.0
isPreserveRatio = true
}
imageview("pool-fund-icon.png") {
vboxConstraints {
marginTop = 50.0
marginLeft = 40.0
}
fitHeight = 45.0
fitWidth = 45.0
isPreserveRatio = true
}
label("Total") {
vboxConstraints {
marginTop = 15.0
marginLeft = 40.0
}
style {
fontWeight = FontWeight.NORMAL
textFill = Color.WHITE
fontSize = 20.px
fontFamily = "Source Sans Pro"
}
}
label("R${dashboardController.getTotalUniversityPoolFund().toString()}") {
vboxConstraints {
marginTop = -10.0
marginLeft = 40.0
}
style {
fontWeight = FontWeight.EXTRA_BOLD
textFill = Color.WHITE
fontSize = 45.px
fontFamily = "Source Sans Pro"
}
}
}
}
}
vbox {
stackpane {
stackpaneConstraints {
paddingLeft = 40.0
paddingTop = 30.0
}
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 575.0
height = 290.0
strokeWidth = 1.0
fill = Styles.orangeColor
opacity = 1.0
}
vbox {
label("Analytics Overview") {
vboxConstraints {
marginTop = 30.0
marginLeft = 45.0
}
style {
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
fontSize = 22.px
fontFamily = "Source Sans Pro"
}
}
hbox {
stackpane {
stackpaneConstraints {
paddingLeft = 40.0
paddingTop = 25.0
}
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 230.0
height = 170.0
strokeWidth = 1.0
fill = Color.WHITE
opacity = 1.0
}
vbox {
imageview("payment-icon.png") {
vboxConstraints {
marginTop = 30.0
marginLeft = 40.0
}
fitHeight = 45.0
fitWidth = 45.0
isPreserveRatio = true
}
label("180") {
vboxConstraints {
marginLeft = 40.0
}
style {
fontWeight = FontWeight.EXTRA_BOLD
textFill = Styles.orangeColor
fontSize = 40.px
fontFamily = "Source Sans Pro"
}
}
label("Total Payments") {
vboxConstraints {
marginTop = -10.0
marginLeft = 40.0
}
style {
fontWeight = FontWeight.NORMAL
textFill = Styles.orangeColor
fontSize = 20.px
fontFamily = "Source Sans Pro"
}
}
}
}
stackpane {
stackpaneConstraints {
paddingLeft = 30.0
paddingTop = 25.0
}
rectangle {
arcHeight = 60.0
arcWidth = 60.0
width = 230.0
height = 170.0
strokeWidth = 1.0
fill = Color.WHITE
opacity = 1.0
}
vbox {
imageview("withdrawel-icon.png") {
vboxConstraints {
marginTop = 30.0
marginLeft = 40.0
}
fitHeight = 45.0
fitWidth = 45.0
isPreserveRatio = true
}
label("210") {
vboxConstraints {
marginLeft = 40.0
}
style {
fontWeight = FontWeight.EXTRA_BOLD
textFill = Styles.orangeColor
fontSize = 40.px
fontFamily = "Source Sans Pro"
}
}
label("Total Withdrawels") {
vboxConstraints {
marginTop = -10.0
marginLeft = 40.0
}
style {
fontWeight = FontWeight.NORMAL
textFill = Styles.orangeColor
fontSize = 20.px
fontFamily = "Source Sans Pro"
}
}
}
}
}
}
}
stackpane {
stackpaneConstraints {
paddingLeft = 40.0
paddingTop = 30.0
}
rectangle {
arcHeight = 30.0
arcWidth = 30.0
width = 575.0
height = 80.0
strokeWidth = 1.0
fill = Styles.mutedDarkBlueColor
opacity = 1.0
}
label("Disclaimer: All payments are made into main pool fund") {
vboxConstraints {
alignment = Pos.CENTER
}
style {
fontWeight = FontWeight.EXTRA_LIGHT
textFill = Color.WHITE
opacity = 1.0
fontSize = 20.px
fontFamily = "Source Sans Pro"
}
}
}
}
}
}
}
}
paddingAll = 50.0
}
}
} | 0 | Kotlin | 0 | 1 | 33c2b5cb691b2ae205b3c3f48b348f19af529156 | 42,094 | enum-integrateX-tornadofx-app | MIT License |
app/src/main/java/com/github/pakka_papad/data/DataManager.kt | pakka-papad | 539,192,838 | false | {"Kotlin": 407869} | package com.github.pakka_papad.data
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.MediaStore.Audio
import android.widget.Toast
import androidx.compose.runtime.mutableStateListOf
import com.github.pakka_papad.data.components.*
import com.github.pakka_papad.data.music.*
import com.github.pakka_papad.data.notification.ZenNotificationManager
import com.github.pakka_papad.formatToDate
import com.github.pakka_papad.nowplaying.RepeatMode
import com.github.pakka_papad.player.ZenPlayer
import com.github.pakka_papad.toMBfromB
import com.github.pakka_papad.toMS
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.update
import timber.log.Timber
import java.io.File
import java.io.FileNotFoundException
import java.util.*
class DataManager(
private val context: Context,
private val notificationManager: ZenNotificationManager,
private val daoCollection: DaoCollection,
private val scope: CoroutineScope,
) {
val getAll by lazy { GetAll(daoCollection) }
val findCollection by lazy { FindCollection(daoCollection) }
val querySearch by lazy { QuerySearch(daoCollection) }
init {
cleanData()
}
fun cleanData() {
scope.launch {
daoCollection.songDao.getSongs().forEach {
try {
if(!File(it.location).exists()){
launch { daoCollection.songDao.deleteSong(it) }
}
} catch (_: Exception){
}
}
}
}
suspend fun removeFromBlacklist(data: List<BlacklistedSong>){
data.forEach {
Timber.d("bs: $it")
daoCollection.blacklistDao.deleteBlacklistedSong(it)
}
}
suspend fun createPlaylist(playlistName: String) {
if (playlistName.trim().isEmpty()) return
val playlist = PlaylistExceptId(
playlistName = playlistName.trim(),
createdAt = System.currentTimeMillis()
)
daoCollection.playlistDao.insertPlaylist(playlist)
showToast("Playlist $playlistName created")
}
suspend fun deletePlaylist(playlist: Playlist) = daoCollection.playlistDao.deletePlaylist(playlist)
suspend fun deleteSong(song: Song) {
daoCollection.songDao.deleteSong(song)
daoCollection.blacklistDao.addSong(
BlacklistedSong(
location = song.location,
title = song.title,
artist = song.artist,
)
)
}
suspend fun insertPlaylistSongCrossRefs(playlistSongCrossRefs: List<PlaylistSongCrossRef>) =
daoCollection.playlistDao.insertPlaylistSongCrossRef(playlistSongCrossRefs)
suspend fun deletePlaylistSongCrossRef(playlistSongCrossRef: PlaylistSongCrossRef) =
daoCollection.playlistDao.deletePlaylistSongCrossRef(playlistSongCrossRef)
private val _scanStatus = Channel<ScanStatus>(onBufferOverflow = BufferOverflow.DROP_OLDEST)
val scanStatus = _scanStatus.receiveAsFlow()
fun scanForMusic() = scope.launch {
_scanStatus.send(ScanStatus.ScanStarted)
// notificationManager.sendScanningNotification()
val blacklistedSongs = daoCollection.blacklistDao.getBlacklistedSongs()
val blacklistedSongLocations = blacklistedSongs.map { it.location }.toSet()
val selection = Audio.Media.IS_MUSIC + " != 0"
val projection = arrayOf(
Audio.Media.DATA,
Audio.Media.TITLE,
Audio.Media.ALBUM_ID,
Audio.Media.ALBUM,
Audio.Media.SIZE,
Audio.Media.DATE_ADDED,
Audio.Media.DATE_MODIFIED,
Audio.Media._ID
)
val cursor = context.contentResolver.query(
Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
Audio.Media.DATE_ADDED,
null
) ?: return@launch
val totalSongs = cursor.count
var parsedSongs = 0
cursor.moveToFirst()
val mExtractor = MetadataExtractor()
val dataIndex = cursor.getColumnIndex(Audio.Media.DATA)
val titleIndex = cursor.getColumnIndex(Audio.Media.TITLE)
val albumIdIndex = cursor.getColumnIndex(Audio.Media.ALBUM_ID)
val albumIndex = cursor.getColumnIndex(Audio.Media.ALBUM)
val sizeIndex = cursor.getColumnIndex(Audio.Media.SIZE)
val dateAddedIndex = cursor.getColumnIndex(Audio.Media.DATE_ADDED)
val dateModifiedIndex = cursor.getColumnIndex(Audio.Media.DATE_MODIFIED)
val songIdIndex = cursor.getColumnIndex(Audio.Media._ID)
val songCover = Uri.parse("content://media/external/audio/albumart")
val songs = ArrayList<Song>()
val albumArtMap = HashMap<String, String?>()
val artistSet = TreeSet<String>()
val albumArtistSet = TreeSet<String>()
val composerSet = TreeSet<String>()
val genreSet = TreeSet<String>()
val lyricistSet = TreeSet<String>()
do {
try {
val file = File(cursor.getString(dataIndex))
if (blacklistedSongLocations.contains(file.path)) continue
if (!file.exists()) throw FileNotFoundException()
val songMetadata = mExtractor.getSongMetadata(file.path)
val song = Song(
location = file.path,
title = cursor.getString(titleIndex),
album = cursor.getString(albumIndex).trim(),
size = cursor.getFloat(sizeIndex).toMBfromB(),
addedDate = cursor.getString(dateAddedIndex).toLong().formatToDate(),
modifiedDate = cursor.getString(dateModifiedIndex).toLong().formatToDate(),
artist = songMetadata.artist.trim(),
albumArtist = songMetadata.albumArtist.trim(),
composer = songMetadata.composer.trim(),
genre = songMetadata.genre.trim(),
lyricist = songMetadata.lyricist.trim(),
year = songMetadata.year,
comment = songMetadata.comment,
durationMillis = songMetadata.duration,
durationFormatted = songMetadata.duration.toMS(),
bitrate = songMetadata.bitrate,
sampleRate = songMetadata.sampleRate,
bitsPerSample = songMetadata.bitsPerSample,
mimeType = songMetadata.mimeType,
artUri = "content://media/external/audio/media/${cursor.getLong(songIdIndex)}/albumart"
)
songs.add(song)
artistSet.add(song.artist)
albumArtistSet.add(song.albumArtist)
composerSet.add(song.composer)
lyricistSet.add(song.lyricist)
genreSet.add(song.genre)
if (albumArtMap[song.album] == null) {
albumArtMap[song.album] =
ContentUris.withAppendedId(songCover, cursor.getLong(albumIdIndex))
.toString()
}
} catch (e: Exception) {
Timber.e(e.message ?: e.localizedMessage ?: "FILE_DOES_NOT_EXIST")
}
parsedSongs++
_scanStatus.send(ScanStatus.ScanProgress(parsedSongs, totalSongs))
} while (cursor.moveToNext())
cursor.close()
daoCollection.albumDao.insertAllAlbums(albumArtMap.entries.map { (t, u) -> Album(t, u) })
daoCollection.artistDao.insertAllArtists(artistSet.map { Artist(it) })
daoCollection.albumArtistDao.insertAllAlbumArtists(albumArtistSet.map { AlbumArtist(it) })
daoCollection.composerDao.insertAllComposers(composerSet.map { Composer(it) })
daoCollection.lyricistDao.insertAllLyricists(lyricistSet.map { Lyricist(it) })
daoCollection.genreDao.insertAllGenres(genreSet.map { Genre(it) })
daoCollection.songDao.insertAllSongs(songs)
// notificationManager.removeScanningNotification()
_scanStatus.send(ScanStatus.ScanComplete)
}
private fun showToast(message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
private var callback: Callback? = null
private val _queue = mutableStateListOf<Song>()
val queue: List<Song> = _queue
private val _currentSong = MutableStateFlow<Song?>(null)
val currentSong = _currentSong.asStateFlow()
fun moveItem(fromIndex: Int, toIndex: Int) {
_queue.apply { add(toIndex, removeAt(fromIndex)) }
}
suspend fun updateSong(song: Song) {
if (_currentSong.value?.location == song.location) {
_currentSong.update { song }
callback?.updateNotification()
}
for (idx in _queue.indices) {
if (_queue[idx].location == song.location) {
_queue[idx] = song
break
}
}
daoCollection.songDao.updateSong(song)
}
private val _repeatMode = MutableStateFlow<RepeatMode>(RepeatMode.NO_REPEAT)
val repeatMode = _repeatMode.asStateFlow()
fun updateRepeatMode(newRepeatMode: RepeatMode){
_repeatMode.update { newRepeatMode }
}
private var remIdx = 0
@Synchronized
fun setQueue(newQueue: List<Song>, startPlayingFromIndex: Int) {
if (newQueue.isEmpty()) return
_queue.apply {
clear()
addAll(newQueue)
}
_currentSong.value = newQueue[startPlayingFromIndex]
if (callback == null) {
val intent = Intent(context, ZenPlayer::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
remIdx = startPlayingFromIndex
} else {
callback?.setQueue(newQueue, startPlayingFromIndex)
}
}
/**
* Returns true if added to queue else returns false if already in queue
*/
@Synchronized
fun addToQueue(song: Song): Boolean {
if (_queue.any { it.location == song.location }) return false
_queue.add(song)
callback?.addToQueue(song)
return true
}
fun setPlayerRunning(callback: Callback) {
this.callback = callback
this.callback?.setQueue(_queue, remIdx)
}
fun updateCurrentSong(currentSongIndex: Int) {
if (currentSongIndex < 0 || currentSongIndex >= _queue.size) return
_currentSong.update { _queue[currentSongIndex] }
}
fun getSongAtIndex(index: Int): Song? {
if (index < 0 || index >= _queue.size) return null
return _queue[index]
}
fun stopPlayerRunning() {
this.callback = null
_currentSong.update { null }
_queue.clear()
}
interface Callback {
fun setQueue(newQueue: List<Song>, startPlayingFromIndex: Int)
fun addToQueue(song: Song)
fun updateNotification()
}
} | 5 | Kotlin | 11 | 144 | 877648b07dde012cc23acd3f41524c5e8149fcda | 11,425 | Zen | MIT License |
arrow-libs/fx/arrow-fx-coroutines/src/commonMain/kotlin/arrow/fx/coroutines/predef.kt | lukaszkalnik | 427,116,886 | true | {"Kotlin": 1928099, "SCSS": 99659, "JavaScript": 83153, "HTML": 25306, "Java": 7691, "Ruby": 917, "Shell": 98} | package arrow.fx.coroutines
public expect fun timeInMillis(): Long
| 0 | Kotlin | 0 | 1 | 73fa3847df1f04e634a02bba527917389b59d7df | 68 | arrow | Apache License 2.0 |
judokit-android/src/main/java/com/judopay/judokit/android/ui/cardentry/validation/carddetails/CardHolderNameValidator.kt | Judopay | 261,378,339 | false | {"Kotlin": 968387, "Ruby": 5168} | package com.judopay.judokit.android.ui.cardentry.validation.carddetails
import com.judopay.judokit.android.R
import com.judopay.judokit.android.ui.cardentry.model.CardDetailsFieldType
import com.judopay.judokit.android.ui.cardentry.model.FormFieldEvent
import com.judopay.judokit.android.ui.cardentry.validation.ValidationResult
import com.judopay.judokit.android.ui.cardentry.validation.Validator
import com.judopay.judokit.android.ui.common.REG_EX_CARDHOLDER_NAME
private const val MIN_CARDHOLDER_NAME_LENGTH = 4
data class CardHolderNameValidator(override val fieldType: String = CardDetailsFieldType.HOLDER_NAME.name) :
Validator {
private val cardholderNameRegEx = REG_EX_CARDHOLDER_NAME.toRegex()
override fun validate(
input: String,
formFieldEvent: FormFieldEvent,
): ValidationResult {
val shouldNotDisplayMessage = formFieldEvent != FormFieldEvent.FOCUS_CHANGED
val isBlank = input.isBlank()
val isTooShort = input.length < MIN_CARDHOLDER_NAME_LENGTH
val isValidCharactersSet = cardholderNameRegEx.matches(input)
val isNotValid = isBlank || isTooShort || !isValidCharactersSet
val message =
when {
shouldNotDisplayMessage -> R.string.empty
isBlank -> R.string.card_holder_name_required
isTooShort -> R.string.card_holder_name_too_short
!isValidCharactersSet -> R.string.card_holder_name_special_chars
else -> R.string.empty
}
return ValidationResult(!isNotValid, message)
}
}
| 1 | Kotlin | 6 | 4 | d24fd23f06f39594ec40ae81a1f6c726bd29496c | 1,589 | JudoKit-Android | MIT License |
dynamic/src/main/java/com/github/rviannaoliveira/dynamic/xml/presentation/ui/text/TextViewComponentRender.kt | rviannaoliveira | 418,187,280 | false | {"Kotlin": 45741, "C++": 20938, "CMake": 18713, "Dart": 16722, "HTML": 1836, "C": 1425, "Swift": 1158, "Objective-C": 38} | package com.github.rviannaoliveira.dynamic.xml.presentation.ui.text
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.github.rviannaoliveira.dynamic.core.data.convertToVO
import com.github.rviannaoliveira.dynamic.core.data.model.base.SimpleProperties
import com.github.rviannaoliveira.dynamic.core.data.model.text.TextProperties
import com.github.rviannaoliveira.dynamic.core.presentation.DynamicComponent
import com.github.rviannaoliveira.dynamic.core.presentation.DynamicViewListener
import com.github.rviannaoliveira.dynamic.xml.presentation.ui.ViewRenderer
class TextViewComponentRender(override var onClickListener: DynamicViewListener?) :
ViewRenderer<TextViewComponentRender.TextViewHolder>(
DynamicComponent.TEXT_VIEW_COMPONENT.key, DynamicComponent.TEXT_VIEW_COMPONENT.ordinal
) {
inner class TextViewHolder(val textView: TextViewComponent) : RecyclerView.ViewHolder(textView)
override fun bindView(model: SimpleProperties, holder: TextViewHolder, position: Int) {
val textProperties = model.value.convertToVO<TextProperties>()
holder.textView.setProperties(textProperties)
holder.textView.setOnClickListener {
textProperties.actionProperties?.let { actionProperties ->
holder.textView.setOnClickListener {
onClickListener?.invoke(actionProperties)
}
}
}
}
override fun createViewHolder(parent: ViewGroup): TextViewHolder {
return TextViewHolder(TextViewComponent(parent.context))
}
} | 0 | Kotlin | 0 | 0 | 3b3a4781ad5a0366d3b147e9c8cdf8fb3ec31e77 | 1,590 | DynamicView | Apache License 2.0 |
app/src/main/java/com/thetechsamurai/foodonwheelz/authentication/ResetPassword.kt | himanshu-1608 | 276,752,026 | false | null | package com.thetechsamurai.foodonwheelz.authentication
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.thetechsamurai.foodonwheelz.sideUtils.ConnectionManager
import com.thetechsamurai.foodonwheelz.R
import org.json.JSONObject
import java.lang.Exception
class ResetPassword : AppCompatActivity() {
private lateinit var etotp : EditText
private lateinit var etPassword : EditText
private lateinit var etConfirm : EditText
private lateinit var btnSubmit : Button
private var phoneText : String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_reset_password)
if(intent != null) {
phoneText = intent.getStringExtra("UserPhone")
}
etotp = findViewById(R.id.etotp)
etPassword = findViewById(R.id.etpassword)
etConfirm = findViewById(R.id.etconfirmpass)
btnSubmit = findViewById(R.id.btnsubmit)
btnSubmit.setOnClickListener {
val otpText = etotp.text.toString().trim()
val passwordText = etPassword.text.toString().trim()
val confirmText = etConfirm.text.toString().trim()
if(validate(otpText,passwordText,confirmText)) {
if(ConnectionManager().checkConnectivity(this@ResetPassword)) {
resetPassword(otpText,passwordText,phoneText)
} else {
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Error")
dialog.setMessage("Internet connection not found!")
dialog.setPositiveButton("Open Settings"){ _, _ ->
val settingIntent = Intent(Settings.ACTION_WIRELESS_SETTINGS)
startActivity(settingIntent)
finish()
}
dialog.setNeutralButton("Exit"){_,_ ->
ActivityCompat.finishAffinity(this)
}
dialog.show()
}
}
}
}
private fun resetPassword(otpText: String, passwordText: String, phoneText: String?) {
val queue = Volley.newRequestQueue(this@ResetPassword)
val url = "http://13.235.250.119/v2/reset_password/fetch_result"
val jsonParams = JSONObject()
jsonParams.put("mobile_number",phoneText)
jsonParams.put("password",passwordText)
jsonParams.put("otp",otpText)
val jsonObjectRequest = object : JsonObjectRequest(Method.POST,url,jsonParams, Response.Listener {
try{
val data = it.getJSONObject("data")
val success = data.getBoolean("success")
if(success) {
Toast.makeText(this@ResetPassword,data.getString("successMessage"),Toast.LENGTH_LONG).show()
getSharedPreferences("DataFile", Context.MODE_PRIVATE).edit().clear().apply()
val intent = Intent(this@ResetPassword,LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
finish()
} else {
Toast.makeText(this@ResetPassword,data.getString("errorMessage"), Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
Toast.makeText(this@ResetPassword,"OOPS! Some Unexpected Error Occurred!", Toast.LENGTH_SHORT).show()
}
}, Response.ErrorListener {
Toast.makeText(this@ResetPassword,"OOPS! Some Network Error Occurred!", Toast.LENGTH_SHORT).show()
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String,String>()
headers["Content-type"] = "application/json"
headers["token"] = "ec7d33dcf400a8"
return headers
}
}
queue.add(jsonObjectRequest)
}
private fun validate(otpText: String, passwordText: String, confirmText: String): Boolean {
when {
otpText.isEmpty() -> {
etotp.error = "Required"
etotp.requestFocus()
return false
}
otpText.length != 4 -> {
etotp.error = "Incorrect OTP"
etotp.requestFocus()
return false
}
passwordText.isEmpty() -> {
etPassword.error = "Required"
etPassword.requestFocus()
return false
}
passwordText.length <= 4 -> {
etPassword.error = "Use a strong password(Min. Length 6)"
etPassword.requestFocus()
return false
}
confirmText.isEmpty() -> {
etConfirm.error = "Required"
etConfirm.requestFocus()
return false
}
confirmText != passwordText -> {
etConfirm.error = "Confirmed Password is wrong"
etConfirm.requestFocus()
return false
}
else -> {
return true
}
}
}
}
| 1 | Kotlin | 0 | 0 | eb33ddb90b55aa50d06d51616aded73e2fc8a48b | 5,713 | food-on-wheelz | MIT License |
libraries/arch/src/main/java/com/fappslab/libraries/arch/extension/StringExtension.kt | F4bioo | 708,171,476 | false | {"Kotlin": 210868} | package com.fappslab.libraries.arch.extension
fun String?.orDash(): String = this ?: "---"
| 0 | Kotlin | 0 | 1 | 3506b09c7b6b522899486fa45ba9686b404780f2 | 93 | TMDBCompose | MIT License |
app/src/main/java/com/anafthdev/todo/common/TodoViewModel.kt | kafri8889 | 433,024,188 | false | {"Kotlin": 103894} | package com.anafthdev.todo.common
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.anafthdev.todo.model.Category
import com.anafthdev.todo.model.Todo
import javax.inject.Inject
class TodoViewModel @Inject constructor(
val repository: RepositoryI
): ViewModel() {
private val _todoList = MutableLiveData<List<Todo>>()
val todoList: LiveData<List<Todo>> = _todoList
/**
* get To-do list by id, see setTodoByID(id: Int)
*/
private val _todoListByID = MutableLiveData<List<Todo>>()
val todoListByID: LiveData<List<Todo>> = _todoListByID
private val _categoryList = MutableLiveData<List<Category>>()
val categoryList: LiveData<List<Category>> = _categoryList
fun refresh() {
repository.getAllTodo { todo -> _todoList.value = todo }
repository.getAllCategory { categories -> _categoryList.value = categories }
}
fun getAllTodo() = repository.getAllTodo { todo ->
_todoList.value = todo
}
fun updateTodo(todo: Todo) = repository.updateTodo(todo) {
getAllTodo()
}
fun deleteTodo(todo: Todo) = repository.deleteTodo(todo) {
getAllTodo()
}
private fun deleteTodoByCategoryID(categoryID: Int) = repository.deleteTodoByCategoryID(categoryID) {
getAllTodo()
}
fun insertTodo(todo: Todo) = repository.insertTodo(todo) {
getAllTodo()
}
/**
* get To-do List by categoryID
*/
fun getTodoListByID(id: Int) {
repository.getTodoByCategoryID(id) { list ->
_todoListByID.value = list
}
}
fun getAllCategory() = repository.getAllCategory { categories ->
_categoryList.value = categories
}
fun insertCategory(category: Category) = repository.insertCategory(category) {
getAllCategory()
}
fun updateCategory(category: Category) = repository.updateCategory(category) {
getAllCategory()
}
fun deleteCategory(category: Category) = repository.deleteCategory(category) {
deleteTodoByCategoryID(category.id)
getAllCategory()
}
} | 0 | Kotlin | 1 | 10 | 220a5fa6857df319799bdf99d36fc298bc79357d | 1,972 | To-Do_Jetpack_Compose | Apache License 2.0 |
presentation/src/main/kotlin/com/lukelorusso/presentation/view/MaybeScrollableViewPager.kt | lukelorusso | 277,556,469 | false | {"Kotlin": 168897} | package com.lukelorusso.presentation.ui.base
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager
class SwipeViewPager(context: Context, attrs: AttributeSet) : ViewPager(context, attrs) {
private var initialXValue: Float = 0.toFloat()
var direction: SwipeDirection
enum class SwipeDirection {
ALL, LEFT, RIGHT, NONE
}
init {
direction = SwipeDirection.ALL
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
return if (isSwipeAllowed(event)) {
super.onTouchEvent(event)
} else false
}
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
return if (isSwipeAllowed(event)) {
super.onInterceptTouchEvent(event)
} else false
}
private fun isSwipeAllowed(event: MotionEvent): Boolean {
if (this.direction == SwipeDirection.ALL) return true
if (direction == SwipeDirection.NONE)
//disable any swipe
return false
if (event.action == MotionEvent.ACTION_DOWN) {
initialXValue = event.x
return true
}
if (event.action == MotionEvent.ACTION_MOVE) {
try {
val diffX = event.x - initialXValue
if (diffX > 0 && direction == SwipeDirection.RIGHT) {
// swipe from LEFT to RIGHT detected
return false
} else if (diffX < 0 && direction == SwipeDirection.LEFT) {
// swipe from RIGHT to LEFT detected
return false
}
} catch (exception: Exception) {
exception.printStackTrace()
}
}
return true
}
}
| 0 | Kotlin | 2 | 4 | dfc73c9a5286c8a880d3fd238737a09201605058 | 1,903 | ColorBlindClickAndroid | Apache License 2.0 |
wave-core/src/test/kotlin/com/github/dhsavell/wave/core/testutil/DummyIDLinkedObject.kt | dhsavell | 116,500,218 | false | null | package com.github.dhsavell.wave.core.testutil
import sx.blah.discord.handle.obj.IIDLinkedObject
class DummyIDLinkedObject(val id: Long) : IIDLinkedObject {
override fun getLongID(): Long = id
fun getOtherObject(otherID: Long): DummyIDLinkedObject = DummyIDLinkedObject(otherID)
override fun equals(other: Any?): Boolean {
return other is DummyIDLinkedObject && other.id == id
}
override fun hashCode(): Int {
return id.hashCode().shl(7)
}
} | 1 | Kotlin | 1 | 1 | 718b8faadf44c18f8485b6d7d8cc4d0d1196e06b | 485 | wave | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/DatabaseLink.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.filled
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Filled.DatabaseLink: ImageVector
get() {
if (_databaseLink != null) {
return _databaseLink!!
}
_databaseLink = fluentIcon(name = "Filled.DatabaseLink") {
fluentPath {
moveTo(12.0f, 10.0f)
curveToRelative(4.42f, 0.0f, 8.0f, -1.8f, 8.0f, -4.0f)
reflectiveCurveToRelative(-3.58f, -4.0f, -8.0f, -4.0f)
reflectiveCurveToRelative(-8.0f, 1.8f, -8.0f, 4.0f)
reflectiveCurveToRelative(3.58f, 4.0f, 8.0f, 4.0f)
close()
moveTo(18.33f, 10.17f)
curveToRelative(0.59f, -0.3f, 1.17f, -0.67f, 1.67f, -1.12f)
verticalLineToRelative(6.0f)
curveToRelative(-0.24f, -0.03f, -0.5f, -0.05f, -0.75f, -0.05f)
horizontalLineToRelative(-3.5f)
arcToRelative(4.75f, 4.75f, 0.0f, false, false, -4.19f, 7.0f)
curveTo(7.35f, 21.87f, 4.0f, 20.13f, 4.0f, 18.0f)
lineTo(4.0f, 9.05f)
curveToRelative(0.5f, 0.45f, 1.08f, 0.83f, 1.67f, 1.12f)
curveToRelative(1.7f, 0.85f, 3.94f, 1.33f, 6.33f, 1.33f)
curveToRelative(2.4f, 0.0f, 4.63f, -0.48f, 6.33f, -1.33f)
close()
moveTo(23.0f, 19.75f)
arcTo(3.75f, 3.75f, 0.0f, false, false, 19.25f, 16.0f)
horizontalLineToRelative(-0.1f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f)
horizontalLineToRelative(0.15f)
arcToRelative(2.25f, 2.25f, 0.0f, false, true, -0.15f, 4.5f)
lineToRelative(-0.1f, 0.01f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f)
verticalLineToRelative(-0.01f)
horizontalLineToRelative(0.2f)
arcTo(3.75f, 3.75f, 0.0f, false, false, 23.0f, 19.74f)
close()
moveTo(16.5f, 16.75f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.75f, -0.75f)
horizontalLineToRelative(-0.2f)
arcToRelative(3.75f, 3.75f, 0.0f, false, false, 0.2f, 7.5f)
horizontalLineToRelative(0.1f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.1f, -1.5f)
horizontalLineToRelative(-0.15f)
arcToRelative(2.25f, 2.25f, 0.0f, false, true, 0.15f, -4.5f)
horizontalLineToRelative(0.1f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.65f, -0.75f)
close()
moveTo(20.0f, 19.75f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.75f, -0.75f)
horizontalLineToRelative(-3.6f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f)
horizontalLineToRelative(3.6f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.65f, -0.75f)
close()
}
}
return _databaseLink!!
}
private var _databaseLink: ImageVector? = null
| 0 | Kotlin | 0 | 24 | 336c85b59b6a6ad97a522a25a0042cd8e0750474 | 3,320 | compose-fluent-ui | Apache License 2.0 |
app/src/main/java/com/javiermarsicano/androidkotlinboilerplate/common/mvp/BaseMVPFragment.kt | jmarsican | 191,185,799 | false | null | package com.javiermarsicano.androidkotlinboilerplate.common.mvp
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import android.view.ViewGroup
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
abstract class BaseMVPFragment<in V : MVPView, P : MVPPresenter<V>> : Fragment(), MVPView {
protected var fragmentPresenter: P? = null
private var activity: BaseMVPActivity<V, P>? = null
protected abstract fun getPresenter(): P
private var fragmentResultSubscription: Disposable? = null
private val compositeDisposable: CompositeDisposable = CompositeDisposable()
/**
* @return the layoutInfo id for this fragment
*/
@LayoutRes
abstract fun layoutId(): Int
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(layoutId(), container, false)
setHasOptionsMenu(true)
view?.isClickable = true
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fragmentPresenter?.onBindView(this as V)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is BaseMVPActivity<*, *>) {
activity = context as BaseMVPActivity<V, P>?
}
}
override fun onResume() {
super.onResume()
fragmentPresenter?.onResume()
}
override fun onPause() {
super.onPause()
fragmentPresenter?.onPause()
}
override fun onDestroyView() {
fragmentPresenter?.onDestroy()
super.onDestroyView()
}
override fun onDestroy() {
removeFragmentResultSubscription()
super.onDestroy()
}
override fun onDetach() {
super.onDetach()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
menu.clear()
}
private fun removeFragmentResultSubscription() {
if (fragmentResultSubscription?.isDisposed == false) {
fragmentResultSubscription?.dispose()
}
}
override fun showLoading() {
if (activity != null) activity!!.showLoading()
}
override fun hideLoading() {
if (activity != null) activity!!.hideLoading()
}
override fun onError(resId: Int) {
if (activity != null) activity!!.onError(resId)
}
override fun onError(message: String?) {
if (activity != null) activity!!.onError(message)
}
override fun hideKeyboard() {
if (activity != null) activity!!.hideKeyboard()
}
protected fun openLink(link: String) {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
startActivity(browserIntent)
}
/**
* Adds this [Disposable] to [compositeDisposable] to insure that it will be disposed when
* the view is destroyed avoiding any memory leaks.
*/
protected fun Disposable.bindToLifecycle() = apply { compositeDisposable.add(this) }
}
| 0 | Kotlin | 0 | 0 | 392ae399aa325450b07433c7a87785aa6395f6b3 | 3,446 | android-project-template | Apache License 2.0 |
app/src/main/java/com/kryptkode/recounter/redux/State.kt | KryptKode | 294,565,911 | false | null | package com.kryptkode.recounter.redux
interface State | 0 | Kotlin | 0 | 0 | a6e7979caa63facefdf5020580e91e1aaa9c7fec | 54 | ReCounter | Apache License 2.0 |
kotlin-libraries-data/src/test/kotlin/com/baeldung/serialization/kotlinx/polymorphism/ClosedPolymorphismSerializationUnitTest.kt | Baeldung | 260,481,121 | false | {"Kotlin": 1855665, "Java": 48276, "HTML": 4883, "Dockerfile": 292} | package com.baeldung.serialization.kotlinx.polymorphism
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
@Serializable
sealed class Shape { abstract val edges: Int }
@Serializable
data class Circle(override val edges: Int, val radius: Double) : Shape()
@Serializable
@SerialName("SerialRectangle")
data class Rectangle(override val edges: Int, val width: Double, val height: Double): Shape()
class ClosedPolymorphismSerializationUnitTest {
@Test
fun `does not serialize concrete object's type discriminator`() {
// given
val concreteCircle: Circle = Circle(edges = 1, radius = 2.0)
// when
val serializedCircle = Json.encodeToString(concreteCircle)
// then
assertThat(serializedCircle).doesNotContain(""""type":"com.baeldung.serialization.kotlinx.polymorphism.Circle"""")
}
@Test
fun `serializes object with it's type discriminator`() {
// given
val circle: Shape = Circle(edges = 1, radius = 2.0)
// when
val serializedCircle = Json.encodeToString(circle)
val deserializedCircle = Json.decodeFromString<Shape>(serializedCircle)
// then
assertThat(serializedCircle).isEqualTo("""{"type":"com.baeldung.serialization.kotlinx.polymorphism.Circle","edges":1,"radius":2.0}""")
assertThat(deserializedCircle).isInstanceOf(Circle::class.java)
}
@Test
fun `uses custom serial name for object's type discriminator`() {
// given
val rectangle: Shape = Rectangle(edges = 4, width = 4.0, height = 6.0)
// when
val serializedRectangle = Json.encodeToString(rectangle)
// then
assertThat(serializedRectangle).isEqualTo("""{"type":"SerialRectangle","edges":4,"width":4.0,"height":6.0}""")
}
@Test
fun `uses custom discriminator property when serializing`() {
// given
val circle: Shape = Circle(edges = 4, radius = 2.0)
val jsonConfiguration = Json { classDiscriminator = "#customDiscriminatorProperty" }
// when
val serializedCircle = jsonConfiguration.encodeToString(circle)
// then
assertThat(serializedCircle).contains("""{"#customDiscriminatorProperty":"com.baeldung.serialization.kotlinx.polymorphism.Circle","edges":4,"radius":2.0}""")
}
} | 14 | Kotlin | 294 | 465 | f1ef5d5ded3f7ddc647f1b6119f211068f704577 | 2,512 | kotlin-tutorials | MIT License |
meteor-core/src/commonMain/kotlin/io/spherelabs/meteor/viewmodel/CommonViewModel.kt | getspherelabs | 646,328,849 | false | null | package io.spherelabs.meteor.viewmodel
import io.spherelabs.meteor.store.Store
import io.spherelabs.meteorviewmodel.Closeable
import io.spherelabs.meteorviewmodel.viewmodel.ViewModel
import kotlinx.coroutines.launch
public abstract class CommonViewModel<State : Any, Wish : Any, Effect : Any> : ViewModel {
public constructor() : super()
public constructor(closeables: List<Closeable>) : super(*closeables.toTypedArray())
public abstract val store: Store<State, Wish, Effect>
public fun wish(wish: Wish) {
viewModelScope.launch {
store.wish(wish)
}
}
override fun onCleared() {
super.onCleared()
store.cancel()
}
}
| 6 | Kotlin | 1 | 9 | 0e6b5aecfcea88d5c6ff7070df2e0ce07edc5457 | 694 | meteor | Apache License 2.0 |
presentation/src/main/java/com/tamimattafi/pizza/android/presentation/fragments/pizza/gallery/GalleryFragment.kt | tamimattafi | 428,131,583 | false | {"Kotlin": 96172} | package com.tamimattafi.pizza.android.presentation.fragments.pizza.gallery
import android.os.Bundle
import android.view.View
import com.tamimattafi.pizza.android.presentation.R
import com.tamimattafi.pizza.android.presentation.core.mvvm.ModelHostFragment
import com.tamimattafi.pizza.android.presentation.core.navigation.Destination
import com.tamimattafi.pizza.android.presentation.core.navigation.Destination.Fragment.Gallery
import com.tamimattafi.pizza.android.presentation.databinding.FragmentGalleryBinding
import com.tamimattafi.pizza.android.presentation.fragments.global.images.ImagesRecyclerAdapter
import com.tamimattafi.pizza.android.presentation.utils.addPageChangeListener
import com.tamimattafi.pizza.android.presentation.utils.beautifyDouble
import com.tamimattafi.pizza.android.presentation.utils.setClickListener
import javax.inject.Inject
class GalleryFragment : ModelHostFragment<GalleryViewModel, FragmentGalleryBinding, Gallery>(
GalleryViewModel::class.java,
FragmentGalleryBinding::inflate
) {
@Inject
lateinit var imagesAdapter: ImagesRecyclerAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
this.setUpViewPager()
this.setUpListeners()
this.setUpObservers()
}
private fun setUpViewPager() {
viewBinding.pager.adapter = imagesAdapter
}
private fun setUpObservers() = with(viewModel) {
pizzaObservable.observe { pizza ->
setName(pizza.name)
setPrice(pizza.price)
imagesAdapter.updateData(pizza.imageUrls)
updateSelectedItem(viewBinding.pager.currentItem)
}
orderAddObservable.observe {
navigator.toDirection(Destination.Direction.Back)
}
}
private fun setUpListeners() = with(viewBinding) {
btnAddToCart.setClickListener {
viewModel.addPizzaToCart()
}
btnBack.setClickListener {
navigator.toDirection(Destination.Direction.Back)
}
pager.addPageChangeListener(::updateSelectedItem)
}
private fun updateSelectedItem(position: Int) = with(viewBinding) {
val currentItemPosition = position + 1
viewBinding.txtQuantity.text = getString(
R.string.gallery_item_count_template,
currentItemPosition,
imagesAdapter.itemCount
)
}
private fun setName(name: String) {
viewBinding.txtTitle.text = name
}
private fun setPrice(price: Double) {
val formattedPrice = price.beautifyDouble()
viewBinding.txtPrice.text = requireContext().getString(
R.string.price_template,
formattedPrice
)
}
} | 0 | Kotlin | 1 | 0 | b0732e71ca1aeb4b6934fa2ec512c61620adc5b9 | 2,769 | i-pizza-android | Apache License 2.0 |
maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt | mobile-dev-inc | 476,427,476 | false | null | package ios.simctl
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import maestro.utils.MaestroTimer
import util.CommandLineUtils.runCommand
import java.io.File
object Simctl {
data class SimctlError(override val message: String): Throwable(message)
private val homedir = System.getProperty("user.home")
fun list(): SimctlList {
val command = listOf("xcrun", "simctl", "list", "-j")
val process = ProcessBuilder(command).start()
val json = String(process.inputStream.readBytes())
return jacksonObjectMapper().readValue(json)
}
fun awaitLaunch(deviceId: String) {
MaestroTimer.withTimeout(30000) {
if (list()
.devices
.values
.flatten()
.find { it.udid == deviceId }
?.state == "Booted"
) true else null
} ?: throw SimctlError("Device $deviceId did not boot in time")
}
fun awaitShutdown(deviceId: String) {
MaestroTimer.withTimeout(30000) {
if (list()
.devices
.values
.flatten()
.find { it.udid == deviceId }
?.state != "Booted"
) true else null
} ?: throw SimctlError("Device $deviceId did not boot in time")
}
fun launchSimulator(deviceId: String) {
runCommand(
listOf(
"xcrun",
"simctl",
"boot",
deviceId
)
)
var exceptionToThrow: Exception? = null
// Up to 10 iterations => max wait time of 1 second
repeat(10) {
try {
runCommand(
listOf(
"open",
"-a",
"/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app",
"--args",
"-CurrentDeviceUDID",
deviceId
)
)
return
} catch (e: Exception) {
exceptionToThrow = e
Thread.sleep(100)
}
}
exceptionToThrow?.let { throw it }
}
fun reboot(
deviceId: String,
) {
runCommand(
listOf(
"xcrun",
"simctl",
"shutdown",
deviceId
),
waitForCompletion = true
)
awaitShutdown(deviceId)
runCommand(
listOf(
"xcrun",
"simctl",
"boot",
deviceId
),
waitForCompletion = true
)
awaitLaunch(deviceId)
}
fun addTrustedCertificate(
deviceId: String,
certificate: File,
) {
runCommand(
listOf(
"xcrun",
"simctl",
"keychain",
deviceId,
"add-root-cert",
certificate.absolutePath,
),
waitForCompletion = true
)
reboot(deviceId)
}
fun terminate(deviceId: String, bundleId: String) {
// Ignore error return: terminate will fail if the app is not running
ProcessBuilder(
listOf(
"xcrun",
"simctl",
"terminate",
deviceId,
bundleId
)
)
.start()
.waitFor()
}
fun clearAppState(deviceId: String, bundleId: String) {
// Stop the app before clearing the file system
// This prevents the app from saving its state after it has been cleared
terminate(deviceId, bundleId)
// Wait for the app to be stopped
Thread.sleep(1500)
// deletes app data, including container folder
val appDataDirectory = getApplicationDataDirectory(deviceId, bundleId)
ProcessBuilder(listOf("rm", "-rf", appDataDirectory)).start().waitFor()
// forces app container folder to be re-created
val paths = listOf(
"Documents",
"Library",
"Library/Caches",
"Library/Preferences",
"SystemData",
"tmp"
)
val command = listOf("mkdir", appDataDirectory) + paths.map { "$appDataDirectory/$it" }
ProcessBuilder(command).start().waitFor()
}
private fun getApplicationDataDirectory(deviceId: String, bundleId: String): String {
val process = ProcessBuilder(
listOf(
"xcrun",
"simctl",
"get_app_container",
deviceId,
bundleId,
"data"
)
).start()
return String(process.inputStream.readBytes()).trimEnd()
}
fun launch(deviceId: String, bundleId: String) {
runCommand(
listOf(
"xcrun",
"simctl",
"launch",
deviceId,
bundleId,
)
)
}
fun setLocation(deviceId: String, latitude: Double, longitude: Double) {
runCommand(
listOf(
"xcrun",
"simctl",
"location",
deviceId,
"set",
"$latitude,$longitude",
)
)
}
fun openURL(deviceId: String, url: String) {
runCommand(
listOf(
"xcrun",
"simctl",
"openurl",
deviceId,
url,
)
)
}
fun uninstall(deviceId: String, bundleId: String) {
runCommand(
listOf(
"xcrun",
"simctl",
"uninstall",
deviceId,
bundleId
)
)
}
fun clearKeychain(deviceId: String) {
runCommand(
listOf(
"xcrun",
"simctl",
"spawn",
deviceId,
"launchctl",
"stop",
"com.apple.securityd",
)
)
runCommand(
listOf(
"rm", "-rf",
"$homedir/Library/Developer/CoreSimulator/Devices/$deviceId/data/Library/Keychains"
)
)
runCommand(
listOf(
"xcrun",
"simctl",
"spawn",
deviceId,
"launchctl",
"start",
"com.apple.securityd",
)
)
}
fun setPermissions(deviceId: String, bundleId: String, permissions: Map<String, String>) {
val mutable = permissions.toMutableMap()
if (mutable.containsKey("all")) {
val value = mutable.remove("all")
allPermissions.forEach {
when (value) {
"allow" -> mutable.putIfAbsent(it, allowValueForPermission(it))
"deny" -> mutable.putIfAbsent(it, denyValueForPermission(it))
"unset" -> mutable.putIfAbsent(it, "unset")
else -> throw IllegalArgumentException("Permission 'all' can be set to 'allow', 'deny' or 'unset', not '$value'")
}
}
}
val argument = mutable
.filter { allPermissions.contains(it.key) }
.map { "${it.key}=${translatePermissionValue(it.value)}" }
.joinToString(",")
runCommand(
listOf(
"$homedir/.maestro/deps/applesimutils",
"--byId",
deviceId,
"--bundle",
bundleId,
"--setPermissions",
argument
)
)
}
private val allPermissions = listOf(
"calendar",
"camera",
"contacts",
"faceid",
"health",
"homekit",
"location",
"medialibrary",
"microphone",
"motion",
"notifications",
"photos",
"reminders",
"siri",
"speech",
"usertracking",
)
private fun translatePermissionValue(value: String): String {
return when (value) {
"allow" -> "YES"
"deny" -> "NO"
else -> value
}
}
private fun allowValueForPermission(permission: String): String {
return when (permission) {
"location" -> "always"
else -> "YES"
}
}
private fun denyValueForPermission(permission: String): String {
return when (permission) {
"location" -> "never"
else -> "NO"
}
}
}
| 273 | null | 171 | 4,417 | 96920b1f8ff64c705fb33b0abc004449909e65bb | 8,978 | maestro | Apache License 2.0 |
src/main/kotlin/io/ashdavies/databinding/repos/RepoBoundaryCallback.kt | wade1990 | 206,394,885 | true | {"Kotlin": 15166} | package io.ashdavies.databinding.repos
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.paging.PagedList
import io.ashdavies.databinding.database.GitHubDao
import io.ashdavies.databinding.models.Repo
import io.ashdavies.databinding.network.Response
import io.ashdavies.databinding.services.GitHubService
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
internal class RepoBoundaryCallback(
private val service: GitHubService,
private val dao: GitHubDao,
private val query: String
) : PagedList.BoundaryCallback<Repo>() {
private val _error: MutableLiveData<Throwable> = MutableLiveData()
val error: LiveData<Throwable> = _error
private var page: Int = 1
override fun onZeroItemsLoaded() {
requestItems()
}
override fun onItemAtEndLoaded(itemAtEnd: Repo) {
requestItems()
}
private fun requestItems() {
GlobalScope.launch {
val result: Result<Response<Repo>> = runCatching {
service.repos("$query+in:name,description", page, NETWORK_PAGE_SIZE)
}
result.onSuccess {
dao.insert(it.items)
page++
}
result.onFailure {
_error.postValue(it)
}
}
}
companion object {
private const val NETWORK_PAGE_SIZE = 50
}
}
| 0 | null | 0 | 0 | 17d4fa0f540b22677daa8b56dcf8dd113abe4d0c | 1,303 | github-repo-search | Apache License 2.0 |
src/Utils.kt | BionicCa | 574,904,899 | false | {"Kotlin": 20039} | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
fun readInputAsIntsList(name: String) : List<List<Int>> {
val inputArray = readInput(name)
val map = inputArray.flatMapIndexed { index: Int, value: String ->
when {
index == 0 || index == inputArray.lastIndex -> listOf(index)
value.isEmpty() -> listOf(index - 1, index + 1)
else -> emptyList()
}
}
.windowed(size = 2, step = 2) { (from, to) -> inputArray.slice(from..to).map { it.toInt() }}
return map
}
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
fun findCommonCharacter(first: CharArray, second: CharArray): Set<Char> {
val common = first.toMutableSet()
common.retainAll(second.toSet())
return common
}
fun <T> transposeList(list: List<List<T>>): List<MutableList<T>> {
val transposed = mutableListOf<MutableList<T>>()
list.forEach { line ->
line.forEachIndexed { i, value ->
if (transposed.size <= i) transposed.add(i, mutableListOf(value))
else transposed[i].add(value)
}
}
return transposed
} | 0 | Kotlin | 0 | 0 | ed8bda8067386b6cd86ad9704bda5eac81bf0163 | 1,380 | AdventOfCode2022 | Apache License 2.0 |
src/jvmTest/kotlin/io/rippledown/model/rule/RuleTest.kt | TimLavers | 513,037,911 | false | null | package io.rippledown.model
import io.kotest.matchers.collections.shouldContain
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.rippledown.model.rule.Rule
import io.rippledown.model.rule.RuleTestBase
import kotlin.test.Test
internal class RuleTest : RuleTestBase() {
private val conclusion1 = conc("First conclusion")
private val conclusion2 = conc("Second conclusion")
private val conclusion3 = conc("Third conclusion")
@Test
fun adding_a_child_in_the_constructor_should_set_the_parent() {
val child = Rule("c",null, conclusion2, setOf())
val rule = Rule("r",null, conclusion1, setOf(), mutableSetOf(child))
child.parent shouldBe rule
}
@Test
fun adding_a_child_should_set_the_parent() {
val child = Rule("c",null, conclusion2, setOf())
val rule = Rule("r",null, conclusion1, setOf())
rule.addChild(child)
child.parent shouldBe rule
}
@Test
fun should_be_structurally_equal_if_same_conditions_conclusion_and_parent_even_if_different_children() {
val child1 = Rule("c1",null, conclusion2, setOf())
val child2 = Rule("c2",null, conclusion2, setOf())
val rule1 = Rule("r1", null, conclusion1, setOf(), mutableSetOf(child1))
val rule2 = Rule("r2", null, conclusion1, setOf(), mutableSetOf(child2))
rule1 shouldNotBe rule2
rule1.structurallyEqual(rule2) shouldBe true
}
@Test
fun should_be_structurally_equal_if_identical() {
val rule1 = Rule("r",null, conclusion1, setOf())
rule1 shouldBe rule1
rule1.structurallyEqual(rule1) shouldBe true
}
@Test
fun should_be_structurally_equal_if_identical_and_null_conclusion() {
val rule1 = Rule("r",null, null, setOf())
rule1 shouldBe rule1
rule1.structurallyEqual(rule1) shouldBe true
}
@Test
fun should_not_be_structurally_equal_if_different_conditions() {
val rule1 = Rule("r",null, conclusion1, setOf(cond("a")))
val rule2 = Rule("r",null, conclusion1, setOf())
rule1.structurallyEqual(rule2) shouldBe false
rule2.structurallyEqual(rule1) shouldBe false
}
@Test
fun should_not_be_structurally_equal_to_a_root_rule() {
val root = Rule("root",null, null, setOf())
val rule = Rule("rule", root, conclusion1, setOf(cond("a")))
root shouldNotBe rule
rule.structurallyEqual(root) shouldBe false
rule shouldNotBe root
root.structurallyEqual(rule) shouldBe false
}
@Test
fun should_not_be_structurally_equal_if_different_conclusion() {
val rule1 = Rule("r1",null, conclusion1)
val rule2 = Rule("r2",null, conclusion2)
rule1 shouldNotBe rule2
rule1.structurallyEqual(rule2) shouldBe false
rule2.structurallyEqual(rule1) shouldBe false
}
@Test
fun should_not_be_structurally_equal_if_different_parents() {
val parent1 = Rule("p1", null, conclusion1)
val parent2 = Rule("p2", null, conclusion2)
val rule1 = Rule("r1", null, conclusion1)
val rule2 = Rule("r2", null, conclusion1)
parent1.addChild(rule1)
parent2.addChild(rule2)
rule1 shouldNotBe rule2
rule1.structurallyEqual(rule2) shouldBe false
rule2.structurallyEqual(rule1) shouldBe false
}
@Test
fun conditions_are_satisfied_if_empty() {
val rule = Rule("r", null, conclusion1)
rule.conditionsSatisfied(glucoseOnlyCase()) shouldBe true
}
@Test
fun single_condition_which_is_true_for_case() {
val rule = Rule("r", null, conclusion1, setOf(cond("vark")))
rule.conditionsSatisfied(clinicalNotesCase("aardvark")) shouldBe true
}
@Test
fun single_condition_which_is_false_for_case() {
val rule = Rule("r", null, conclusion1, setOf(cond("vark")))
rule.conditionsSatisfied(clinicalNotesCase("aardwolf")) shouldBe false
}
@Test
fun any_condition_false_means_rule_does_not_apply() {
val conditions = setOf(cond("a"), cond("b"), cond("c"), cond("d"))
val rule = Rule("r", null, conclusion1, conditions)
rule.conditionsSatisfied(clinicalNotesCase("abc")) shouldBe false
rule.conditionsSatisfied(clinicalNotesCase("abd")) shouldBe false
rule.conditionsSatisfied(clinicalNotesCase("cbd")) shouldBe false
rule.conditionsSatisfied(clinicalNotesCase("cba")) shouldBe false
}
@Test
fun rule_applies_if_all_true() {
val conditions = setOf(cond("a"), cond("b"), cond("c"), cond("d"))
val rule = Rule("r", null, conclusion1, conditions)
rule.conditionsSatisfied(clinicalNotesCase("abcd")) shouldBe true
rule.conditionsSatisfied(clinicalNotesCase("bcda")) shouldBe true
rule.conditionsSatisfied(clinicalNotesCase("xdcba")) shouldBe true
}
@Test
fun summary() {
val conditions = setOf(cond("a"), cond("b"))
val rule1 = Rule("r1", null, null, conditions)
rule1.summary().conclusion shouldBe null
rule1.summary().conditions.size shouldBe 2
rule1.summary().conditions shouldContain cond("a")
rule1.summary().conditions shouldContain cond("b")
val rule2 = Rule("r2", null, conclusion1, conditions)
rule2.summary().conclusion shouldBe conclusion1
rule1.summary().conditions.size shouldBe 2
rule1.summary().conditions shouldContain cond("a")
rule1.summary().conditions shouldContain cond("b")
}
@Test
fun rule_with_no_children_that_applies_to_case() {
val conditions = setOf(cond("a"))
val rule = Rule("r", null, conclusion1, conditions)
val kase = clinicalNotesCase("ab")
val result = rule.apply(kase, interpretation)
result shouldBe true
checkInterpretation(conclusion1)
}
@Test
fun rule_that_does_not_apply_to_case_and_has_no_children() {
val conditions = setOf(cond("a"))
val rule = Rule("r", null, conclusion1, conditions)
val result = rule.apply(clinicalNotesCase("bc"), interpretation)
result shouldBe false
checkInterpretation()//empty
}
@Test
fun rule_applies_to_case_but_child_does_not() {
val rule = setupRuleWithOneChild()
val result = rule.apply(clinicalNotesCase("ac"), interpretation)
result shouldBe true
checkInterpretation(conclusion1)
}
@Test
fun rule_applies_to_case_and_so_does_child() {
val conditions = setOf(cond("a"))
val rule = Rule("r", null, conclusion1, conditions)
val childConditions = setOf(cond("b"))
val childRule = Rule("c", null, conclusion2, childConditions)
rule.addChild(childRule)
val result = rule.apply(clinicalNotesCase("ab"), interpretation)
result shouldBe true
checkInterpretation(conclusion2)
}
@Test
fun rule_does_not_apply_to_case_but_child_does() {
val rule = setupRuleWithOneChild()
val result = rule.apply(clinicalNotesCase("bc"), interpretation)
result shouldBe false
checkInterpretation()//empty
}
@Test
fun rule_does_not_apply_to_case_nor_does_child() {
val rule = setupRuleWithOneChild()
val result = rule.apply(clinicalNotesCase("xy"), interpretation)
result shouldBe false
checkInterpretation()//empty
}
@Test
fun rule_applies_no_child_does() {
val rule = setupRuleWithTwoChildren()
val result = rule.apply(clinicalNotesCase("a"), interpretation)
result shouldBe true
checkInterpretation(conclusion1)
}
@Test
fun rule_applies_and_one_child_does() {
val rule = setupRuleWithTwoChildren()
val result = rule.apply(clinicalNotesCase("ab"), interpretation)
result shouldBe true
checkInterpretation(conclusion2)
}
@Test
fun rule_applies_and_so_do_both_children() {
val rule = setupRuleWithTwoChildren()
val result = rule.apply(clinicalNotesCase("abc"), interpretation)
result shouldBe true
checkInterpretation(conclusion2, conclusion3)
}
@Test
fun addRuleTest() {
val grandChildConditions = setOf(cond("a"), cond("c"))
val grandChild = Rule("gr", null, conclusion3, grandChildConditions)
val childConditions = setOf(cond("b"))
val childRule = Rule("cr", null, conclusion2, childConditions)
childRule.addChild(grandChild)
childRule.conditions shouldBe childRule.conditions
childRule.conclusion shouldBe childRule.conclusion
val rootConditions = setOf(cond("a"), cond("b"))
val root = Rule("rr", null, conclusion1, rootConditions)
root.addChild(childRule)
root.conclusion shouldBe root.conclusion
root.conditions shouldBe root.conditions
root.childRules() shouldContain(childRule)
val result = root.apply(clinicalNotesCase("abc"), interpretation)
result shouldBe true
checkInterpretation(conclusion3)
}
@Test
fun visitTest() {
val conditions = setOf(cond("a"))
val rule = Rule("r", null, conclusion1, conditions)
val visited = mutableSetOf<Rule>()
val action: ((Rule) -> (Unit)) = {
visited.add(it)
}
rule.visit(action)
visited.size shouldBe 1
visited shouldContain (rule)
}
@Test
fun visit_rule_with_children() {
val rule = setupRuleWithTwoChildren()
val visited = mutableSetOf<Conclusion?>()
val action: ((Rule) -> (Unit)) = {
visited.add(it.conclusion)
}
rule.visit(action)
val expected = mutableSetOf(conclusion1, conclusion2, conclusion3)
visited shouldBe expected
}
@Test
fun visit_deep() {
val rule = setupRuleWithOneChild()
val grandChildConditions = setOf(cond("a"), cond("c"))
val grandChild = Rule("r", null, conclusion3, grandChildConditions)
rule.childRules().first().addChild(grandChild)
val visited = mutableSetOf<Conclusion?>()
val action: ((Rule) -> (Unit)) = {
visited.add(it.conclusion)
}
rule.visit(action)
val expected = mutableSetOf(conclusion1, conclusion2, conclusion3)
visited shouldBe expected
}
@Test
fun rule_should_be_copied() {
val rule = setupRuleWithOneChild()
val copy = rule.copy()
(copy !== rule) shouldBe true
copy.conclusion shouldBe rule.conclusion
copy.conditions shouldBe rule.conditions
copy.childRules() shouldBe rule.childRules()
}
@Test
fun rule_with_null_parent_should_be_copied() {
val rule = setupRuleWithOneChild()
val copy = rule.copy()
(copy !== rule) shouldBe true
copy.parent shouldBe rule.parent
copy.conclusion shouldBe rule.conclusion
copy.conditions shouldBe rule.conditions
copy.childRules() shouldBe rule.childRules()
}
@Test
fun rule_with_not_null_parent_should_be_copied() {
val rule = setupRuleWithOneChild()
rule.parent = Rule("r", null)
val copy = rule.copy()
(copy !== rule) shouldBe true
copy.parent shouldBe Rule("r", null)
copy.conclusion shouldBe rule.conclusion
copy.conditions shouldBe rule.conditions
copy.childRules() shouldBe rule.childRules()
}
@Test
fun child_rules_should_be_copied() {
val rule = setupRuleWithOneChild()
val copy = rule.copy()
val copyChild = copy.childRules().iterator().next()
val ruleChild = rule.childRules().iterator().next()
copyChild shouldBe ruleChild
(copyChild !== ruleChild) shouldBe true
}
@Test
fun conditions_should_be_copied() {
val rule = setupRuleWithOneChild()
val copy = rule.copy()
val copyCondition = copy.conditions.iterator().next()
val ruleCondition = rule.conditions.iterator().next()
copyCondition shouldBe ruleCondition
}
private fun setupRuleWithTwoChildren(): Rule {
val rule = setupRuleWithOneChild()
val childConditions = setOf(cond("c"))
val childRule = Rule("child2", null, conclusion3, childConditions)
rule.addChild(childRule)
return rule
}
private fun setupRuleWithOneChild(): Rule {
val rule = Rule("ruleWithChild", null, conclusion1, setOf(cond("a")))
val childRule = Rule("child1", null, conclusion2, setOf(cond("b")))
rule.addChild(childRule)
return rule
}
private fun checkInterpretation(vararg conclusions: Conclusion) {
checkInterpretation(interpretation, *conclusions)
}
} | 0 | Kotlin | 0 | 0 | 844e2ca383c4e656eed8d8fe0540d5e44214bd12 | 12,842 | OpenRDR | MIT License |
src/main/kotlin/com/xethlyx/adminchat/AdminChat.kt | xethlyx | 405,486,229 | false | {"Kotlin": 7583} | package com.xethlyx.adminchat
import net.md_5.bungee.api.plugin.Plugin
import com.imaginarycode.minecraft.redisbungee.RedisBungee
import com.imaginarycode.minecraft.redisbungee.RedisBungeeAPI
import com.xethlyx.adminchat.commands.AdminChatHandler
import net.luckperms.api.LuckPerms
import net.luckperms.api.LuckPermsProvider
class AdminChat: Plugin() {
companion object {
lateinit var instance: AdminChat
lateinit var redisBungee: RedisBungeeAPI
lateinit var luckPerms: LuckPerms
}
override fun onEnable() {
super.onEnable()
instance = this
redisBungee = RedisBungee.getApi()
luckPerms = LuckPermsProvider.get()
ChatHandler.registerListeners()
proxy.pluginManager.registerCommand(this, AdminChatHandler())
}
override fun onDisable() {
super.onDisable()
ChatHandler.unregisterListeners()
}
} | 0 | Kotlin | 0 | 0 | 6c0c7ad2792e481ac50e9e1e3a631102aa421e12 | 908 | bungee-admin-chat | MIT License |
cosmos-sdk/src/jvmMain/kotlin/cosmos/slashing/v1beta1/slashing.converter.jvm.kt | jdekim43 | 759,720,689 | false | {"Kotlin": 8940168, "Java": 3242559} | // Transform from cosmos/slashing/v1beta1/slashing.proto
@file:GeneratorVersion(version = "0.3.1")
package cosmos.slashing.v1beta1
import com.google.protobuf.ByteString
import com.google.protobuf.Descriptors
import com.google.protobuf.Parser
import google.protobuf.DurationJvmConverter
import google.protobuf.TimestampJvmConverter
import kr.jadekim.protobuf.`annotation`.GeneratorVersion
import kr.jadekim.protobuf.converter.mapper.ProtobufTypeMapper
public object ValidatorSigningInfoJvmConverter :
ProtobufTypeMapper<ValidatorSigningInfo, Slashing.ValidatorSigningInfo> {
public override val descriptor: Descriptors.Descriptor =
Slashing.ValidatorSigningInfo.getDescriptor()
public override val parser: Parser<Slashing.ValidatorSigningInfo> =
Slashing.ValidatorSigningInfo.parser()
public override fun convert(obj: Slashing.ValidatorSigningInfo): ValidatorSigningInfo =
ValidatorSigningInfo(
address = obj.getAddress(),
startHeight = obj.getStartHeight(),
indexOffset = obj.getIndexOffset(),
jailedUntil = TimestampJvmConverter.convert(obj.getJailedUntil()),
tombstoned = obj.getTombstoned(),
missedBlocksCounter = obj.getMissedBlocksCounter(),
)
public override fun convert(obj: ValidatorSigningInfo): Slashing.ValidatorSigningInfo {
val builder = Slashing.ValidatorSigningInfo.newBuilder()
builder.setAddress(obj.address)
builder.setStartHeight(obj.startHeight)
builder.setIndexOffset(obj.indexOffset)
builder.setJailedUntil(TimestampJvmConverter.convert(obj.jailedUntil))
builder.setTombstoned(obj.tombstoned)
builder.setMissedBlocksCounter(obj.missedBlocksCounter)
return builder.build()
}
}
public object ParamsJvmConverter : ProtobufTypeMapper<Params, Slashing.Params> {
public override val descriptor: Descriptors.Descriptor = Slashing.Params.getDescriptor()
public override val parser: Parser<Slashing.Params> = Slashing.Params.parser()
public override fun convert(obj: Slashing.Params): Params = Params(
signedBlocksWindow = obj.getSignedBlocksWindow(),
minSignedPerWindow = obj.getMinSignedPerWindow().toByteArray(),
downtimeJailDuration = DurationJvmConverter.convert(obj.getDowntimeJailDuration()),
slashFractionDoubleSign = obj.getSlashFractionDoubleSign().toByteArray(),
slashFractionDowntime = obj.getSlashFractionDowntime().toByteArray(),
)
public override fun convert(obj: Params): Slashing.Params {
val builder = Slashing.Params.newBuilder()
builder.setSignedBlocksWindow(obj.signedBlocksWindow)
builder.setMinSignedPerWindow(ByteString.copyFrom(obj.minSignedPerWindow))
builder.setDowntimeJailDuration(DurationJvmConverter.convert(obj.downtimeJailDuration))
builder.setSlashFractionDoubleSign(ByteString.copyFrom(obj.slashFractionDoubleSign))
builder.setSlashFractionDowntime(ByteString.copyFrom(obj.slashFractionDowntime))
return builder.build()
}
}
| 0 | Kotlin | 0 | 0 | eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc | 2,921 | chameleon.proto | Apache License 2.0 |
app/src/main/java/tw/firemaples/onscreenocr/utils/KotlinExtensions.kt | pietrocmcosta | 295,492,703 | true | {"Kotlin": 171023, "Java": 160352, "JavaScript": 3060, "Shell": 2536, "HTML": 420} | package tw.firemaples.onscreenocr.utils
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.ListView
import android.widget.TextView
import tw.firemaples.onscreenocr.CoreApplication
import tw.firemaples.onscreenocr.R
import java.util.*
fun ListView.select(position: Int) {
// if (this.isSkipNextSelect(true))
// return
// else
// this.skipNextSelect()
this.setItemChecked(position, true)
this.setSelection(position)
}
fun View.skipNextSelect() {
this.setTag(R.id.skipNextSelect, true)
}
fun View.isSkipNextSelect(clear: Boolean = false): Boolean {
val result = this.getTag(R.id.skipNextSelect) == true
if (clear) this.clearSkipNextSelect()
return result
}
fun View.clearSkipNextSelect() = this.setTag(R.id.skipNextSelect, false)
fun View.setVisible(visible: Boolean) {
this.visibility = if (visible) View.VISIBLE else View.GONE
}
fun Any?.equalsAny(vararg others: Any): Boolean =
others.any { it == this@equalsAny }
fun View.getView(id: Int): View = this.findViewById(id)
fun View.getTextView(id: Int): TextView = this.findViewById(id)
fun View.removeFromParent() = (this.parent as? ViewGroup)?.removeView(this)
fun View.onViewPrepared(callback: (View) -> Unit) {
val view = this
this.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (view.width == 0 || view.height == 0) {
return
}
view.viewTreeObserver.removeOnGlobalLayoutListener(this)
callback(view)
}
})
}
fun View?.safePerformClick() {
try {
this?.performClick()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun Int.asString(): String = CoreApplication.instance.getString(this)
fun Int.asFormatString(vararg args: Any?): String = String.format(Locale.US, this.asString(), *args) | 0 | null | 0 | 0 | f4e3cfbe9f420a9762b99a65b647f0b95546fb5d | 1,969 | EverTranslator | Apache License 2.0 |
confluence-plugin/src/main/java/com/networkedassets/git4c/core/business/Revision.kt | rpaasche | 321,741,515 | true | {"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716} | package com.networkedassets.git4c.core.bussiness
import java.io.Closeable
class Revision(
val revision: String,
private val finished: Closeable
) : Closeable {
override fun close() {
finished.close()
}
} | 0 | Kotlin | 0 | 0 | e55391b33cb70d66bbf5f36ba570fb8822f10953 | 238 | git4c | Apache License 2.0 |
src/main/kotlin/io/github/bayang/jelu/search/MultiLingualNGramAnalyzer.kt | bayang | 426,792,636 | false | {"Kotlin": 633783, "Vue": 418236, "TypeScript": 113503, "CSS": 7963, "Java": 3470, "JavaScript": 3200, "Dockerfile": 1964, "Shell": 1372, "HTML": 726} | package io.github.bayang.jelu.search
import org.apache.lucene.analysis.LowerCaseFilter
import org.apache.lucene.analysis.TokenStream
import org.apache.lucene.analysis.Tokenizer
import org.apache.lucene.analysis.cjk.CJKBigramFilter
import org.apache.lucene.analysis.cjk.CJKWidthFilter
import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter
import org.apache.lucene.analysis.ngram.NGramTokenFilter
import org.apache.lucene.analysis.standard.StandardTokenizer
/**
* see https://github.com/gotson/komga/tree/master/komga/src/main/kotlin/org/gotson/komga/infrastructure/search
* for all the lucene related stuff
*/
class MultiLingualNGramAnalyzer(private val minGram: Int, private val maxGram: Int, private val preserveOriginal: Boolean) : MultiLingualAnalyzer() {
override fun createComponents(fieldName: String): TokenStreamComponents {
val source: Tokenizer = StandardTokenizer()
// run the widthfilter first before bigramming, it sometimes combines characters.
var filter: TokenStream = CJKWidthFilter(source)
filter = LowerCaseFilter(filter)
filter = CJKBigramFilter(filter)
filter = NGramTokenFilter(filter, minGram, maxGram, preserveOriginal)
filter = ASCIIFoldingFilter(filter)
return TokenStreamComponents(source, filter)
}
}
| 16 | Kotlin | 12 | 340 | 32de3210e27f64102052cc596e6602258b433a83 | 1,319 | jelu | MIT License |
csstype-kotlin/src/jsMain/kotlin/web/cssom/GridRow.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
package web.cssom
typealias GridRow = GridLineProperty
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 101 | types-kotlin | Apache License 2.0 |
src/main/kotlin/net/wiredtomato/burgered/recipe/CategorizedSmithingRecipe.kt | wired-tomato | 835,870,549 | false | {"Kotlin": 95855, "Java": 1521} | package net.wiredtomato.burgered.recipe
import net.minecraft.recipe.RecipeCategory
import net.minecraft.recipe.SmithingRecipe
interface CategorizedSmithingRecipe : SmithingRecipe {
fun category(): RecipeCategory
} | 0 | Kotlin | 0 | 0 | c4f7c275fea3d0517ca6f26c5a295c7fa500752a | 219 | burgered | MIT License |
attribution/src/main/java/com/affise/attribution/events/autoCatchingClick/AutoCatchingClickEvent.kt | affise | 496,592,599 | false | {"Kotlin": 859274, "JavaScript": 39328, "HTML": 33916} | package com.affise.attribution.events.autoCatchingClick
import com.affise.attribution.converter.StringToSHA1Converter
import com.affise.attribution.events.Event
import com.affise.attribution.utils.timestamp
import org.json.JSONArray
import org.json.JSONObject
class AutoCatchingClickEvent(
private val isGroup: Boolean,
private val data: List<AutoCatchingClickData>,
private val activityName: String,
private val timeStampMillis: Long = timestamp()
) : Event() {
override fun serialize(): JSONObject = JSONObject().apply {
val serializeData = JSONArray().apply {
data.forEach {
val item = JSONObject().apply {
put("id", it.id ?: "")
put("tag", it.tag ?: "")
put("text", it.text ?: "")
put("view", it.typeView ?: "")
}
put(item)
}
}
put("affise_event_auto_catching_group", isGroup)
put("affise_event_auto_catching_activity", activityName)
put("affise_event_auto_catching_click", serializeData)
put("affise_event_auto_catching_click_timestamp", timeStampMillis)
}
override fun getName(): String = "AutoCatchingClickEvent_${getEventSha1()}"
override fun getCategory(): String = "autoNative"
override fun getUserData(): String = "Auto generate even on click"
private fun getEventSha1() = StringToSHA1Converter().convert(
data.fold(activityName) { acc, value ->
acc + (value.id ?: "")
}
)
} | 0 | Kotlin | 0 | 5 | ab7d393c6583208e33cef9e10e01ba9dd752bbcb | 1,566 | sdk-android | MIT License |
y2021/src/test/kotlin/adventofcode/y2021/Day02Test.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 453707} | package adventofcode.y2021
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class Day02Test {
@Test
fun solvePartOne() {
assertEquals(150, Day02.solvePartOne(testData))
}
@Test
fun solvePartTwo() {
assertEquals(900, Day02.solvePartTwo(testData))
}
private val testData = """forward 5
down 5
forward 8
up 3
down 8
forward 2"""
} | 0 | Kotlin | 0 | 3 | f988b7b77f7b03b7ef4b1269192c9a41abe789f4 | 423 | advent-of-code | MIT License |
src/en/mangabob/src/eu/kanade/tachiyomi/extension/en/mangabob/MangaBob.kt | komikku-app | 720,497,299 | false | {"Kotlin": 6732685, "JavaScript": 2160} | package eu.kanade.tachiyomi.extension.en.mangabob
import eu.kanade.tachiyomi.multisrc.madara.Madara
class MangaBob : Madara("MangaBob", "https://mangabob.com", "en")
| 21 | Kotlin | 5 | 73 | 87609401d853a38484e0e4c4f1f30c7bdb42b172 | 168 | komikku-extensions | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.