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
src/commonMain/kotlin/io/chree/vamzer/checker/SecretChecker.kt
chreeio
312,624,395
false
null
package io.chree.vamzer.checker /** * Interface for classes checking if an arbitrary non-null string is * a secret of some type. Such a secret can be, for example, an access * token, a JWT, a public key, etc. * * Implementations of this interface are required to be thread-safe. */ interface SecretChecker { /** * Checks if the specified value is a secret. * * Note, that this method does not check if [value] contains a secret, but * whether the [value] is a secret itself. * * When performing the check, the provided [hints] are used to speed up the process. Let's * assume that we have two checkers: the first one checks if the [value] is a random value * in Base64 encoding, while the second one checks if the [value] is a Base64 encoded JWT. * Clearly, if the first checker determines that the [value] is not a valid * Base64 string, then the second checker can re-use this knowledge and skip its checking * logic altogether. Supported [hints] are specific to implementations. * @param value the value to be checked. * @param hints a map of hints altering/speeding up the check. * @return an object containing whether [value] is a secret */ fun checkIfSecret(value: String, hints: Map<String, Any> = emptyMap()): SecretCheckResult }
0
Kotlin
0
1
542c738950674e53b824e48e8f27836753d2012a
1,327
vamzer
MIT License
src/main/kotlin/Registers.kt
hoodlm
592,554,474
false
{"Kotlin": 111126}
class Registers { companion object { private const val Z_MASK: UByte = 0b1000_0000u private const val N_MASK: UByte = 0b0100_0000u private const val H_MASK: UByte = 0b0010_0000u private const val C_MASK: UByte = 0b0001_0000u } var A: UByte = 0u; var B: UByte = 0u; var C: UByte = 0u; var D: UByte = 0u; var E: UByte = 0u; var F: UByte = 0u; var H: UByte = 0u; var L: UByte = 0u; private var SP: UShort = 0u; private var PC: UShort = 0u; fun setAF(af: UShort) { af.splitHighAndLowBits().also { this.A = it.first this.F = it.second } } fun AF(): UShort { return Pair(this.A, this.F).toUShort() } fun setBC(af: UShort) { af.splitHighAndLowBits().also { this.B = it.first this.C = it.second } } fun BC(): UShort { return Pair(this.B, this.C).toUShort() } fun setDE(af: UShort) { af.splitHighAndLowBits().also { this.D = it.first this.E = it.second } } fun DE(): UShort { return Pair(this.D, this.E).toUShort() } fun setHL(af: UShort) { af.splitHighAndLowBits().also { this.H = it.first this.L = it.second } } fun HL(): UShort { return Pair(this.H, this.L).toUShort() } fun setSP(sp: UShort) { this.SP = sp } fun SP(): UShort { return SP } fun setPC(pc: UShort) { this.PC = pc } fun PC(): UShort { return PC } /* flag accessors/setters, in register F * 7 6 5 4 3 2 1 0 * ---------------------- * Z N H C 0 0 0 0 */ fun flagZ(): Boolean { return checkFlag(Z_MASK) } fun flagN(): Boolean { return checkFlag(N_MASK) } fun flagH(): Boolean { return checkFlag(H_MASK) } fun flagC(): Boolean { return checkFlag(C_MASK) } private fun checkFlag(mask: UByte): Boolean { return F.and(mask).equals(mask) } fun setFlagZ(on: Boolean) { setFlag(on, Z_MASK) } fun setFlagN(on: Boolean) { setFlag(on, N_MASK) } fun setFlagH(on: Boolean) { setFlag(on, H_MASK) } fun setFlagC(on: Boolean) { setFlag(on, C_MASK) } private fun setFlag(on: Boolean, mask: UByte) { if (on) { F = F.or(mask) } else { F = F.and(mask.inv()) } } fun clear() { A = 0u; B = 0u; C = 0u; D = 0u; E = 0u; F = 0u; H = 0u; L = 0u; SP = 0u; PC = 0u; } fun dumpRegisters(): String { return "A=${A.toHexString()}, F=${F.toHexString()}, B=${B.toHexString()}, " + "C=${C.toHexString()}, D=${D.toHexString()}, E=${E.toHexString()}, " + "H=${H.toHexString()}, L=${L.toHexString()}, SP=${SP.toHexString()}, PC=${PC.toHexString()}; " + "flags: C=${flagC()}, H=${flagH()}, Z=${flagZ()}, N=${flagN()}" } }
0
Kotlin
0
0
f000f5d96f1abc6f25ecdb41bbb1068d3d9d576f
3,150
hoodboy
MIT License
common/src/main/java/dev/sasikanth/twine/common/utils/UserClock.kt
msasikanth
516,650,081
false
{"Kotlin": 364930}
package dev.sasikanth.twine.common.utils import java.time.Clock import java.time.Instant import java.time.ZoneId // Copied from: https://github.com/simpledotorg/simple-android/blob/4f1ab825a601520822157623f9b5f1348bf2ee7e/app/src/main/java/org/simple/clinic/util/Clocks.kt abstract class UserClock : Clock() open class RealUserClock(userTimeZone: ZoneId) : UserClock() { private val userClock = Clock.system(userTimeZone) override fun withZone(zone: ZoneId): Clock = userClock.withZone(zone) override fun getZone(): ZoneId = userClock.zone override fun instant(): Instant = userClock.instant() }
1
Kotlin
0
27
6c259de1a818da155a29a3837a85326e1b132955
611
tweet-unroll-android
Apache License 2.0
android/src/main/java/com/blackboxvisionreactnativemercadopagopx/data/PaymentResult.kt
BlackBoxVision
265,727,653
false
null
package com.blackboxvisionreactnativemercadopagopx.data import android.content.Intent import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import com.mercadopago.android.px.core.MercadoPagoCheckout import com.mercadopago.android.px.model.Payment open class PaymentResult { companion object { private const val ID = "id"; private const val STATUS = "status"; private const val STATUS_DETAIL = "statusDetail"; private const val DESCRIPTION = "description" private const val CURRENCY_ID = "currencyId" private const val OPERATION_TYPE = "operationType" private const val PAYMENT_METHOD_ID = "paymentMethodId" private const val PAYMENT_TYPE_ID = "paymentTypeId" private const val ISSUER_ID = "issuerId" private const val INSTALLMENTS = "installments" private const val CAPTURED = "captured" private const val LIVE_MODE = "liveMode" private const val TRANSACTION_AMOUNT = "transactionAmount" fun getPayment(data: Intent?): WritableMap { val pxPayment = data?.getSerializableExtra(MercadoPagoCheckout.EXTRA_PAYMENT_RESULT) as Payment?; val payment = Arguments.createMap(); // Default Payment values if (pxPayment != null) { if (pxPayment.id != null) { payment.putString(ID, pxPayment.id!!.toString()); } else { payment.putNull(ID); } if (pxPayment.paymentStatus != null) { payment.putString(STATUS, pxPayment.paymentStatus); } else { payment.putNull(STATUS); } if (pxPayment.paymentStatusDetail != null) { payment.putString(STATUS_DETAIL, pxPayment.paymentStatusDetail); } else { payment.putNull(STATUS_DETAIL); } // Additional Payment values if (pxPayment.description != null) { payment.putString(DESCRIPTION, pxPayment.description); } else { payment.putNull(DESCRIPTION); } if (pxPayment.currencyId != null) { payment.putString(CURRENCY_ID, pxPayment.currencyId); } else { payment.putNull(CURRENCY_ID); } if (pxPayment.operationType != null) { payment.putString(OPERATION_TYPE, pxPayment.operationType); } else { payment.putNull(OPERATION_TYPE); } if (pxPayment.paymentMethodId != null) { payment.putString(PAYMENT_METHOD_ID, pxPayment.paymentMethodId); } else { payment.putNull(PAYMENT_METHOD_ID); } if (pxPayment.paymentTypeId != null) { payment.putString(PAYMENT_TYPE_ID, pxPayment.paymentTypeId); } else { payment.putNull(PAYMENT_TYPE_ID); } if (pxPayment.issuerId != null) { payment.putString(ISSUER_ID, pxPayment.issuerId); } else { payment.putNull(ISSUER_ID); } if (pxPayment.installments != null) { payment.putInt(INSTALLMENTS, pxPayment.installments); } else { payment.putNull(INSTALLMENTS); } if (pxPayment.captured != null) { payment.putBoolean(CAPTURED, pxPayment.captured); } else { payment.putNull(CAPTURED); } if (pxPayment.liveMode != null) { payment.putBoolean(LIVE_MODE, pxPayment.liveMode); } else { payment.putNull(LIVE_MODE); } if (pxPayment.transactionAmount != null) { payment.putDouble(TRANSACTION_AMOUNT, pxPayment.transactionAmount.toDouble()); } else { payment.putNull(TRANSACTION_AMOUNT); } } return payment; } } }
30
Kotlin
22
98
6fbfcdb0cc5f86c22750655e409e99a0d1af14ce
4,351
react-native-mercadopago-px
MIT License
src/main/kotlin/com/github/gameoholic/grassconflicts/listeners/ProjectileHitListener.kt
Gameoholic
660,924,742
false
null
package com.github.gameoholic.grassconflicts.listeners import com.github.gameoholic.grassconflicts.GrassConflicts import com.github.gameoholic.grassconflicts.datatypes.Team import com.github.gameoholic.grassconflicts.enums.Phase import com.github.gameoholic.grassconflicts.gamemanager.GCPlayer import com.github.gameoholic.grassconflicts.util.VectorInt import net.kyori.adventure.key.Key import net.kyori.adventure.sound.Sound import org.bukkit.Bukkit import org.bukkit.Material import org.bukkit.Particle import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.entity.ProjectileHitEvent object ProjectileHitListener : Listener { @EventHandler fun onProjectileHit(e: ProjectileHitEvent) { if (e.entity.shooter !is Player || e.hitBlock == null) return val player = e.entity.shooter as Player val block = e.hitBlock!! e.entity.remove() var gameManager = GrassConflicts.gameManagers.firstOrNull { gameManager -> gameManager.gamePlayers.any {gcPlayer -> gcPlayer.player.uniqueId == player.uniqueId} } ?: return var gcPlayer: GCPlayer = gameManager.gamePlayers.firstOrNull { gcPlayer -> gcPlayer.player.uniqueId == player.uniqueId} ?: return if (block.location.blockY <= gameManager.gameParameters.corner1Coords.blockY || block.location.blockY > gameManager.gameParameters.buildHeightLimit || block.type == Material.CHEST || block.x > gameManager.gameParameters.corner1Coords.blockX || block.z > gameManager.gameParameters.corner1Coords.blockZ || block.x < gameManager.gameParameters.corner2Coords.blockX || block.z < gameManager.gameParameters.corner2Coords.blockZ) return if (gameManager.phase == Phase.GRASS) { var myceliumCorner1 = //pos VectorInt(gameManager.gameParameters.corner1Coords.blockX, gameManager.gameParameters.corner1Coords.blockY, gameManager.gameParameters.corner1Coords.blockZ) var myceliumCorner2 = //neg VectorInt(gameManager.gameParameters.corner2Coords.blockX, gameManager.gameParameters.corner2Coords.blockY, gameManager.borderZCoordinate + 1) var grassCorner1 = //neg VectorInt(gameManager.gameParameters.corner2Coords.blockX, gameManager.gameParameters.corner2Coords.blockY, gameManager.gameParameters.corner2Coords.blockZ) var grassCorner2 = //pos VectorInt(gameManager.gameParameters.corner1Coords.blockX, gameManager.gameParameters.corner1Coords.blockY, gameManager.borderZCoordinate - 1) var blockInGrassRegion = block.x >= grassCorner1.x && block.z >= grassCorner1.z && block.x <= grassCorner2.x && block.z <= grassCorner2.z var blockInMyceliumRegion = block.x <= myceliumCorner1.x && block.z <= myceliumCorner1.z && block.x >= myceliumCorner2.x && block.z >= myceliumCorner2.z if (gcPlayer.team == Team.GRASS && blockInMyceliumRegion) return if (gcPlayer.team == Team.MYCELIUM && blockInGrassRegion) return } GrassConflicts.world.spawnParticle( Particle.BLOCK_CRACK, block.location.x + 0.5, block.location.y + 0.5, block.location.z + 0.5, 20, 0.0, 0.0, 0.0, 0.1, block.type.createBlockData()) GrassConflicts.world.playSound( Sound.sound( Key.key("minecraft:block.grass.break"), Sound.Source.MASTER, 0.5f, 1.0f), block.x.toDouble(), block.y.toDouble(), block.z.toDouble()) block.type = Material.AIR } }
0
Kotlin
0
0
f1a564617d00e48e23d0f2d4665055574a2bde04
3,834
GrassConflicts
MIT License
src/main/kotlin/fi/aalto/cs/apluscourses/services/PluginSettings.kt
Aalto-LeTech
229,264,372
false
{"Kotlin": 311653, "Python": 15177, "Shell": 2709}
package fi.aalto.cs.apluscourses.services import org.jetbrains.annotations.NonNls object PluginSettings { @NonNls const val REPL_ADDITIONAL_ARGUMENTS_FILE_NAME: String = ".repl-arguments" @NonNls const val MODULE_REPL_INITIAL_COMMANDS_FILE_NAME: String = ".repl-commands" @NonNls const val A_PLUS: String = "A+" // 15 minutes in milliseconds const val UPDATE_INTERVAL: Long = 15L * 60 * 1000 // 15 seconds in milliseconds const val REASONABLE_DELAY_FOR_MODULE_INSTALLATION: Long = 15L * 1000 }
15
Kotlin
7
16
a1e2a0e95360cd1f3b84503cdfe6e3fbd62a7844
542
aplus-courses
MIT License
genogram-android/src/main/kotlin/ffc/genogram/android/Families.kt
NatNT
153,216,363
true
{"Kotlin": 177159}
/* * Copyright (c) 2018 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.genogram.android import ffc.genogram.Family interface Families { fun family(callbackDsl: Callback.() -> Unit) class Callback { lateinit var onSuccess: ((Family) -> Unit) private set lateinit var onFail: ((Throwable?) -> Unit) private set fun onSuccess(onFound: (Family) -> Unit) { this.onSuccess = onFound } fun onFail(onFail: (Throwable?) -> Unit) { this.onFail = onFail } } }
0
Kotlin
0
0
b942dc25b378a84c9699260d9b1d62fadabb57aa
1,166
genogram
Apache License 2.0
genogram-android/src/main/kotlin/ffc/genogram/android/Families.kt
NatNT
153,216,363
true
{"Kotlin": 177159}
/* * Copyright (c) 2018 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.genogram.android import ffc.genogram.Family interface Families { fun family(callbackDsl: Callback.() -> Unit) class Callback { lateinit var onSuccess: ((Family) -> Unit) private set lateinit var onFail: ((Throwable?) -> Unit) private set fun onSuccess(onFound: (Family) -> Unit) { this.onSuccess = onFound } fun onFail(onFail: (Throwable?) -> Unit) { this.onFail = onFail } } }
0
Kotlin
0
0
b942dc25b378a84c9699260d9b1d62fadabb57aa
1,166
genogram
Apache License 2.0
app/src/main/java/com/wenjian/wanandroid/ui/mine/MineFragment.kt
wenjiangit
147,815,372
false
{"Java": 173354, "Kotlin": 161112}
package com.wenjian.wanandroid.ui.mine import android.annotation.SuppressLint import android.view.View import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import com.wenjian.wanandroid.R import com.wenjian.wanandroid.base.BaseFragment import com.wenjian.wanandroid.extension.* import com.wenjian.wanandroid.helper.UserHelper import com.wenjian.wanandroid.model.Event import com.wenjian.wanandroid.model.FlowEventBus import com.wenjian.wanandroid.ui.collect.CollectActivity import com.wenjian.wanandroid.ui.login.LoginActivity import com.wenjian.wanandroid.ui.profile.ProfileActivity import com.wenjian.wanandroid.ui.setting.SettingActivity import com.wenjian.wanandroid.ui.theme.ThemeActivity import de.hdodenhof.circleimageview.CircleImageView /** * Description: MineFragment * Date: 2018/9/6 * * @author <EMAIL> */ class MineFragment : BaseFragment() { private lateinit var mTvUser: TextView private lateinit var mIvAvatar: CircleImageView private lateinit var mTvUserId: TextView private lateinit var mTvLoginRegister: TextView override fun findViews(mRoot: View) { mTvUser = mRoot.findViewById(R.id.tv_username) mIvAvatar = mRoot.findViewById(R.id.iv_avatar) mTvUserId = mRoot.findViewById(R.id.tv_userid) mTvLoginRegister = mRoot.findViewById(R.id.tv_login_register) mRoot.findViewById<ConstraintLayout>(R.id.lay_person) .setOnClickListener { if (UserHelper.isLogin()) { launch(ProfileActivity::class.java) } else { launch(LoginActivity::class.java) } } mRoot.findViewById<ConstraintLayout>(R.id.lay_toolbox) .setOnClickListener { context?.toastInfo("敬请期待") } mRoot.findViewById<ConstraintLayout>(R.id.lay_collect) .setOnClickListener { launch(CollectActivity::class.java) } mRoot.findViewById<ConstraintLayout>(R.id.lay_settings) .setOnClickListener { launch(SettingActivity::class.java) } mRoot.findViewById<ConstraintLayout>(R.id.lay_theme) .setOnClickListener { launch(ThemeActivity::class.java) } } override fun initViews() { super.initViews() updateUserInfo() FlowEventBus.observe<Event.UserInfoRefresh>(viewLifecycleOwner) { updateUserInfo() } } @SuppressLint("SetTextI18n") private fun updateUserInfo() { if (UserHelper.isLogin()) { mTvLoginRegister.gone() mTvUserId.visible() mTvUser.visible() UserHelper.getUserInfo()?.apply { mTvUser.text = username mIvAvatar.loadAvatar(icon) mTvUserId.text = "id : $id" } } else { mTvLoginRegister.visible() mTvUserId.gone() mTvUser.gone() } } override fun getLayoutId(): Int = R.layout.fragment_mine companion object { fun newInstance() = MineFragment() } }
1
null
1
1
7ddd7f6577bee9841c7e2951e4da8d0c93ac4857
3,263
WanAndroid
MIT License
compose-designer/src/com/android/tools/idea/compose/preview/actions/ToggleAutoBuildAction.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.compose.preview.actions import com.android.tools.idea.compose.preview.ComposePreviewBundle.message import com.android.tools.idea.compose.preview.findComposePreviewManagersForContext import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ex.CheckboxAction internal class ToggleAutoBuildAction : CheckboxAction( message("action.auto.build.title"), message("action.auto.build.description"), null) { override fun isSelected(e: AnActionEvent): Boolean = findComposePreviewManagersForContext(e.dataContext).any { it.isAutoBuildEnabled } override fun setSelected(e: AnActionEvent, enabled: Boolean) { findComposePreviewManagersForContext(e.dataContext).forEach { it.isAutoBuildEnabled = enabled } } }
0
null
187
751
16d17317f2c44ec46e8cd2180faf9c349d381a06
1,408
android
Apache License 2.0
demo-app/src/androidTest/java/cash/z/wallet/sdk/sample/demoapp/Iterator.kt
zcash
151,763,639
false
null
@file:Suppress("ktlint:filename") package cash.z.wallet.sdk.sample.demoapp fun <T> Iterator<T>.count(): Int { var count = 0 forEach { count++ } return count }
171
Kotlin
40
47
c0a2c11418d5d31891ba6bcc5aebc377ae317892
174
zcash-android-wallet-sdk
MIT License
app/src/main/java/com/ivoberger/enq/utils/List.kt
ivoberger
157,096,916
false
null
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ivoberger.enq.utils fun <T> List<T>.addToEnd(new: T): List<T> = if (!contains(new)) this + new else this.toMutableList().apply { remove(new) add(new) }
10
Kotlin
2
3
64b8a1d493b2f4dde216e8a7beb23b6d1f57a363
765
EnQ
Apache License 2.0
app/src/main/java/com/annuityfarm/annuityfarmapp/Constants.kt
MuturaDev
752,216,432
false
{"Kotlin": 199460, "Java": 17465}
package com.annuityfarm.annuityfarmapp class Constants { companion object { val FRAG_MESSAGE : String = "FragMessage" val FRAGMENT_MESSAGE : String = "FRAGMENT_MESSAGE" val PROJECTION_CALCULATOR:String = "PROJECTION_CALCULATOR" } }
0
Kotlin
0
0
e36e0086d9b28e30349cf27e603782f652258809
265
AnnuityFarmApp
MIT License
app/src/main/java/com/mbah1/jephthah/fieldservicereporter/features/schedule/EnterScheduleDialog.kt
sproutjeph
668,215,949
false
null
package com.mbah1.jephthah.fieldservicereporter.features.schedule import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.maxkeppeker.sheets.core.models.base.SheetState import com.mbah1.jephthah.fieldservicereporter.R import com.mbah1.jephthah.fieldservicereporter.features.schedule.domain.model.ScheduleModel import com.mbah1.jephthah.fieldservicereporter.features.service_report.presentation.add_edit_report.components.ServiceReportInputField import kotlinx.coroutines.launch @Composable fun EnterScheduleDialog( openDialog: MutableState<Boolean>, scheduleInputState: ScheduleInputState = ScheduleInputState( scheduleDate = mutableStateOf(""), scheduleTime = mutableStateOf(""), scheduleInfo = mutableStateOf(""), ), snackbarHostState: SnackbarHostState, calendarState: SheetState, clockState: SheetState, selectedDate: MutableState<String>, selectedTime: MutableState<String>, onAddSchedule: (scheduleModel: ScheduleModel) -> Unit ) { val scope = rememberCoroutineScope() scheduleInputState.scheduleDate.value = selectedDate.value scheduleInputState.scheduleTime.value = selectedTime.value if (openDialog.value) { AlertDialog( onDismissRequest = { openDialog.value = false }, title = { Text("Enter Your Schedule") }, text = { Column { Button( onClick = { calendarState.show() }, modifier = Modifier .fillMaxWidth(), shape = MaterialTheme.shapes.small ) { Text("Select Date") } Spacer(modifier = Modifier.height(8.dp)) Text(text = "Date: ${selectedDate.value}") Spacer(modifier = Modifier.height(8.dp)) Button( onClick = { clockState.show() }, modifier = Modifier .fillMaxWidth(), shape = MaterialTheme.shapes.small ) { Text("Select Time") } Spacer(modifier = Modifier.height(8.dp)) Text(text = "Time: ${selectedTime.value}") ServiceReportInputField( value = scheduleInputState.scheduleInfo.value, onValueChange = {scheduleInputState.scheduleInfo.value = it}, label = R.string.schedule_details, keyboardType = KeyboardType.Text, maxLine = 5, ) } }, confirmButton = { TextButton(onClick = { if(scheduleInputState.scheduleDate.value.isEmpty() || scheduleInputState.scheduleInfo.value.isEmpty()){ scope.launch { snackbarHostState.showSnackbar("Fill all fields", "Dismiss") } return@TextButton }else{ onAddSchedule( ScheduleModel( scheduleDate = scheduleInputState.scheduleDate.value, scheduleTime = scheduleInputState.scheduleTime.value, scheduleInfo = scheduleInputState.scheduleInfo.value ) ) scope.launch { snackbarHostState.showSnackbar("Schedule Added", "Dismiss") } scheduleInputState.scheduleDate.value = "" scheduleInputState.scheduleTime.value = "" scheduleInputState.scheduleInfo.value = "" openDialog.value = false } }) { Text("Save") } }, dismissButton = { TextButton( onClick = { openDialog.value = false } ) { Text("Dismiss") } }, ) } }
0
Kotlin
0
0
446e0755a8a8d942421498553ed6c29aa9326252
5,311
Field-Service-Reporter
MIT License
typescript/ts-nodes/src/org/jetbrains/dukat/ast/model/nodes/ConstructorNode.kt
epabst
276,985,373
true
{"Kotlin": 2712767, "WebIDL": 323303, "TypeScript": 129206, "JavaScript": 18484, "ANTLR": 11333}
package org.jetbrains.dukat.ast.model.nodes data class ConstructorNode( override val parameters: List<ParameterNode>, val typeParameters: List<TypeValueNode> ) : MemberNode, ParameterOwnerNode
0
null
0
0
02bc203cd219be211b85560b216eb10ecf9720d2
209
dukat
Apache License 2.0
ratings-app/src/commonMain/kotlin/io/ashdavies/playground/ItemPager.kt
ashdavies
36,688,248
false
null
package io.ashdavies.playground import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.channels.ProducerScope import kotlinx.coroutines.channels.produce import kotlinx.coroutines.isActive internal fun interface ItemPager<T : Any> { suspend fun next(count: Int): List<T> } @OptIn(ExperimentalCoroutinesApi::class) internal fun <T : Any> ItemPager(generator: suspend CoroutineScope.() -> List<T>): ItemPager<T> { val backgroundScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) val producer = backgroundScope.produce { while (isActive) sendAll(generator()) } return ItemPager { count -> List(count) { producer.receive() } } } internal suspend fun <T : Any> ItemPager<T>.next(): T { return next(1).first() } private suspend fun <T> ProducerScope<T>.sendAll(items: List<T>) { items.forEach { send(it) } }
25
Kotlin
33
111
cff5622108e0832b87a7aacd425b68b44e64ec0c
978
playground.ashdavies.dev
Apache License 2.0
app/src/main/java/com/example/mvvmhilt/utils/extn/FragmentExtn.kt
anbarasu-seven
643,736,930
false
null
package com.example.mvvmhilt.utils.extn import android.view.inputmethod.InputMethodManager import android.widget.Toast import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment fun Fragment.close() = fragmentManager?.popBackStack() /** * This extension function display a string as a toast msg in fragment *@param message user-defined message */ fun Fragment.showToast(message: String) { Toast.makeText( requireContext(), message, Toast.LENGTH_SHORT ).show() } fun Fragment.hideKeyboard() { val token = requireActivity().currentFocus?.windowToken val imm: InputMethodManager? = ContextCompat.getSystemService(requireActivity(), InputMethodManager::class.java) imm?.hideSoftInputFromWindow(token, 0) }
0
Kotlin
0
1
0b157c69f84e1a384809e3e329a9b03f1e5521e0
783
AndroidCleanArchitectureBaseProjec
MIT License
app/src/main/java/kr/evalon/orderservice/models/OrderItem.kt
yjh04722
433,686,281
true
{"Kotlin": 62962}
package kr.evalon.orderservice.models import com.google.firebase.database.Exclude open class OrderItem( code: String = "", name: String = "", price: Int = 0, categoryCodes: List<String> = emptyList(), count: Int = 0, val optionItems: List<OrderItem> = emptyList() ) : BaseItem(code, name, price, categoryCodes) { constructor(item: BaseItem, options: List<OrderItem> = emptyList()) : this( item.code, item.name, item.price, item.categoryCodes, 1, options ) var count = count private set(value) { field = value } val finalPrice: Int @Exclude get() = (optionItems.map { it.finalPrice }.sum() + price) * count override fun equals(other: Any?): Boolean { return other is OrderItem && other.code == code && other.name == name && other.optionItems == optionItems } fun plus(item: OrderItem) { require(code == item.code) plusCart(item.count) } fun plusCart(delta: Int) { count += delta } }
0
null
0
0
8ef88105e8035e0e8e874b42a1493a1a1c9fe811
1,125
OrderService
MIT License
app/src/main/kotlin/com/nikitvad/oryanmat/trellowidget/BaseViewModel.kt
nikitvad
159,517,115
false
null
package com.nikitvad.oryanmat.trellowidget import android.databinding.BaseObservable import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable abstract class BaseViewModel<T: Navigator> : BaseObservable(){ val compositeDisposable = CompositeDisposable() open fun onBind(){} var navigator:T? = null fun unBind() { compositeDisposable.clear() } fun addDisposable(f: ()->Disposable){ compositeDisposable.add(f.invoke()) } }
0
Kotlin
0
0
c185729effca81fff35b4fba3eb05e6b45d39223
507
TrelloMobile
MIT License
syfosmsak-app/src/main/kotlin/no/nav/syfo/client/DokArkivClient.kt
navikt
145,708,055
false
null
package no.nav.syfo.client import io.ktor.client.HttpClient import io.ktor.client.call.receive import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.request.post import io.ktor.client.statement.HttpStatement import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import net.logstash.logback.argument.StructuredArguments.fields import no.nav.syfo.log import no.nav.syfo.model.AvsenderMottaker import no.nav.syfo.model.Behandler import no.nav.syfo.model.Bruker import no.nav.syfo.model.Dokument import no.nav.syfo.model.Dokumentvarianter import no.nav.syfo.model.JournalpostRequest import no.nav.syfo.model.JournalpostResponse import no.nav.syfo.model.Periode import no.nav.syfo.model.ReceivedSykmelding import no.nav.syfo.model.Sak import no.nav.syfo.model.Status import no.nav.syfo.model.ValidationResult import no.nav.syfo.objectMapper import no.nav.syfo.util.LoggingMeta import no.nav.syfo.validation.validatePersonAndDNumber import java.time.LocalDate import java.time.format.DateTimeFormatter class DokArkivClient( private val url: String, private val stsClient: StsOidcClient, private val httpClient: HttpClient ) { suspend fun createJournalpost( journalpostRequest: JournalpostRequest, loggingMeta: LoggingMeta ): JournalpostResponse = try { log.info( "Kall til dokarkiv Nav-Callid {}, {}", journalpostRequest.eksternReferanseId, fields(loggingMeta) ) val httpResponse = httpClient.post<HttpStatement>(url) { contentType(ContentType.Application.Json) header("Authorization", "Bearer ${stsClient.oidcToken().access_token}") header("Nav-Callid", journalpostRequest.eksternReferanseId) body = journalpostRequest parameter("forsoekFerdigstill", true) }.execute() if (httpResponse.status == HttpStatusCode.Created || httpResponse.status == HttpStatusCode.Conflict) { httpResponse.call.response.receive<JournalpostResponse>() } else { log.error("Mottok uventet statuskode fra dokarkiv: {}, {}", httpResponse.status, fields(loggingMeta)) throw RuntimeException("Mottok uventet statuskode fra dokarkiv: ${httpResponse.status}") } } catch (e: Exception) { log.warn("Oppretting av journalpost feilet: ${e.message}, {}", fields(loggingMeta)) throw e } } fun createJournalpostPayload( receivedSykmelding: ReceivedSykmelding, caseId: String, pdf: ByteArray, validationResult: ValidationResult ) = JournalpostRequest( avsenderMottaker = when (validatePersonAndDNumber(receivedSykmelding.sykmelding.behandler.fnr)) { true -> createAvsenderMottakerValidFnr(receivedSykmelding) else -> createAvsenderMottakerNotValidFnr(receivedSykmelding) }, bruker = Bruker( id = receivedSykmelding.personNrPasient, idType = "FNR" ), dokumenter = listOf( Dokument( dokumentvarianter = listOf( Dokumentvarianter( filnavn = "Sykmelding", filtype = "PDFA", variantformat = "ARKIV", fysiskDokument = pdf ), Dokumentvarianter( filnavn = "Sykmelding json", filtype = "JSON", variantformat = "ORIGINAL", fysiskDokument = objectMapper.writeValueAsBytes(receivedSykmelding.sykmelding) ) ), tittel = createTittleJournalpost(validationResult, receivedSykmelding), brevkode = "NAV 08-07.04 A" ) ), eksternReferanseId = receivedSykmelding.sykmelding.id, journalfoerendeEnhet = "9999", journalpostType = "INNGAAENDE", kanal = "HELSENETTET", sak = Sak( arkivsaksnummer = caseId, arkivsaksystem = "GSAK" ), tema = "SYM", tittel = createTittleJournalpost(validationResult, receivedSykmelding) ) fun createAvsenderMottakerValidFnr(receivedSykmelding: ReceivedSykmelding): AvsenderMottaker = AvsenderMottaker( id = receivedSykmelding.sykmelding.behandler.fnr, idType = "FNR", land = "Norge", navn = receivedSykmelding.sykmelding.behandler.formatName() ) fun createAvsenderMottakerNotValidFnr(receivedSykmelding: ReceivedSykmelding): AvsenderMottaker = AvsenderMottaker( land = "Norge", navn = receivedSykmelding.sykmelding.behandler.formatName() ) fun createTittleJournalpost(validationResult: ValidationResult, receivedSykmelding: ReceivedSykmelding): String { return if (validationResult.status == Status.INVALID) { "Avvist Sykmelding ${getFomTomTekst(receivedSykmelding)}" } else if (receivedSykmelding.sykmelding.avsenderSystem.navn == "Papirsykmelding") { "Sykmelding mottatt på papir ${getFomTomTekst(receivedSykmelding)}" } else { "Sykmelding ${getFomTomTekst(receivedSykmelding)}" } } private fun getFomTomTekst(receivedSykmelding: ReceivedSykmelding) = "${formaterDato(receivedSykmelding.sykmelding.perioder.sortedSykmeldingPeriodeFOMDate().first().fom)} -" + " ${formaterDato(receivedSykmelding.sykmelding.perioder.sortedSykmeldingPeriodeTOMDate().last().tom)}" fun List<Periode>.sortedSykmeldingPeriodeFOMDate(): List<Periode> = sortedBy { it.fom } fun List<Periode>.sortedSykmeldingPeriodeTOMDate(): List<Periode> = sortedBy { it.tom } fun Behandler.formatName(): String = if (mellomnavn == null) { "$etternavn $fornavn" } else { "$etternavn $fornavn $mellomnavn" } fun formaterDato(dato: LocalDate): String { val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") return dato.format(formatter) }
0
Kotlin
0
0
eec389eabe858c1354ab47ca78b753bc2808489b
5,942
syfosmsak
MIT License
syfosmsak-app/src/main/kotlin/no/nav/syfo/client/DokArkivClient.kt
navikt
145,708,055
false
null
package no.nav.syfo.client import io.ktor.client.HttpClient import io.ktor.client.call.receive import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.request.post import io.ktor.client.statement.HttpStatement import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import net.logstash.logback.argument.StructuredArguments.fields import no.nav.syfo.log import no.nav.syfo.model.AvsenderMottaker import no.nav.syfo.model.Behandler import no.nav.syfo.model.Bruker import no.nav.syfo.model.Dokument import no.nav.syfo.model.Dokumentvarianter import no.nav.syfo.model.JournalpostRequest import no.nav.syfo.model.JournalpostResponse import no.nav.syfo.model.Periode import no.nav.syfo.model.ReceivedSykmelding import no.nav.syfo.model.Sak import no.nav.syfo.model.Status import no.nav.syfo.model.ValidationResult import no.nav.syfo.objectMapper import no.nav.syfo.util.LoggingMeta import no.nav.syfo.validation.validatePersonAndDNumber import java.time.LocalDate import java.time.format.DateTimeFormatter class DokArkivClient( private val url: String, private val stsClient: StsOidcClient, private val httpClient: HttpClient ) { suspend fun createJournalpost( journalpostRequest: JournalpostRequest, loggingMeta: LoggingMeta ): JournalpostResponse = try { log.info( "Kall til dokarkiv Nav-Callid {}, {}", journalpostRequest.eksternReferanseId, fields(loggingMeta) ) val httpResponse = httpClient.post<HttpStatement>(url) { contentType(ContentType.Application.Json) header("Authorization", "Bearer ${stsClient.oidcToken().access_token}") header("Nav-Callid", journalpostRequest.eksternReferanseId) body = journalpostRequest parameter("forsoekFerdigstill", true) }.execute() if (httpResponse.status == HttpStatusCode.Created || httpResponse.status == HttpStatusCode.Conflict) { httpResponse.call.response.receive<JournalpostResponse>() } else { log.error("Mottok uventet statuskode fra dokarkiv: {}, {}", httpResponse.status, fields(loggingMeta)) throw RuntimeException("Mottok uventet statuskode fra dokarkiv: ${httpResponse.status}") } } catch (e: Exception) { log.warn("Oppretting av journalpost feilet: ${e.message}, {}", fields(loggingMeta)) throw e } } fun createJournalpostPayload( receivedSykmelding: ReceivedSykmelding, caseId: String, pdf: ByteArray, validationResult: ValidationResult ) = JournalpostRequest( avsenderMottaker = when (validatePersonAndDNumber(receivedSykmelding.sykmelding.behandler.fnr)) { true -> createAvsenderMottakerValidFnr(receivedSykmelding) else -> createAvsenderMottakerNotValidFnr(receivedSykmelding) }, bruker = Bruker( id = receivedSykmelding.personNrPasient, idType = "FNR" ), dokumenter = listOf( Dokument( dokumentvarianter = listOf( Dokumentvarianter( filnavn = "Sykmelding", filtype = "PDFA", variantformat = "ARKIV", fysiskDokument = pdf ), Dokumentvarianter( filnavn = "Sykmelding json", filtype = "JSON", variantformat = "ORIGINAL", fysiskDokument = objectMapper.writeValueAsBytes(receivedSykmelding.sykmelding) ) ), tittel = createTittleJournalpost(validationResult, receivedSykmelding), brevkode = "NAV 08-07.04 A" ) ), eksternReferanseId = receivedSykmelding.sykmelding.id, journalfoerendeEnhet = "9999", journalpostType = "INNGAAENDE", kanal = "HELSENETTET", sak = Sak( arkivsaksnummer = caseId, arkivsaksystem = "GSAK" ), tema = "SYM", tittel = createTittleJournalpost(validationResult, receivedSykmelding) ) fun createAvsenderMottakerValidFnr(receivedSykmelding: ReceivedSykmelding): AvsenderMottaker = AvsenderMottaker( id = receivedSykmelding.sykmelding.behandler.fnr, idType = "FNR", land = "Norge", navn = receivedSykmelding.sykmelding.behandler.formatName() ) fun createAvsenderMottakerNotValidFnr(receivedSykmelding: ReceivedSykmelding): AvsenderMottaker = AvsenderMottaker( land = "Norge", navn = receivedSykmelding.sykmelding.behandler.formatName() ) fun createTittleJournalpost(validationResult: ValidationResult, receivedSykmelding: ReceivedSykmelding): String { return if (validationResult.status == Status.INVALID) { "Avvist Sykmelding ${getFomTomTekst(receivedSykmelding)}" } else if (receivedSykmelding.sykmelding.avsenderSystem.navn == "Papirsykmelding") { "Sykmelding mottatt på papir ${getFomTomTekst(receivedSykmelding)}" } else { "Sykmelding ${getFomTomTekst(receivedSykmelding)}" } } private fun getFomTomTekst(receivedSykmelding: ReceivedSykmelding) = "${formaterDato(receivedSykmelding.sykmelding.perioder.sortedSykmeldingPeriodeFOMDate().first().fom)} -" + " ${formaterDato(receivedSykmelding.sykmelding.perioder.sortedSykmeldingPeriodeTOMDate().last().tom)}" fun List<Periode>.sortedSykmeldingPeriodeFOMDate(): List<Periode> = sortedBy { it.fom } fun List<Periode>.sortedSykmeldingPeriodeTOMDate(): List<Periode> = sortedBy { it.tom } fun Behandler.formatName(): String = if (mellomnavn == null) { "$etternavn $fornavn" } else { "$etternavn $fornavn $mellomnavn" } fun formaterDato(dato: LocalDate): String { val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") return dato.format(formatter) }
0
Kotlin
0
0
eec389eabe858c1354ab47ca78b753bc2808489b
5,942
syfosmsak
MIT License
src/test/kotlin/com/willoutwest/kalahari/scene/MotionTest.kt
wbknez
217,644,047
false
null
package com.willoutwest.kalahari.scene import com.willoutwest.kalahari.math.quaternion import com.willoutwest.kalahari.math.shouldBe import com.willoutwest.kalahari.math.vector3 import io.kotlintest.properties.Gen import io.kotlintest.properties.assertAll import io.kotlintest.specs.ShouldSpec class MotionGenerator : Gen<Motion> { override fun constants(): Iterable<Motion> = emptyList() override fun random(): Sequence<Motion> = generateSequence { Motion(Gen.quaternion().random().first(), Gen.vector3().random().first(), Gen.vector3().random().first()) } } fun Gen.Companion.motion(): Gen<Motion> = MotionGenerator() /** * Test suite for [Motion]. */ class MotionTest : ShouldSpec() { init { "Converting a motion to a transformation matrix" { should("multiply the scale, rotation, and translation matrices " + "in reverse order") { assertAll(Gen.motion()) { motion: Motion -> val rot = motion.rotation.toMatrix() val scale = motion.scale.toScalingMatrix() val trans = motion.translation.toTranslationMatrix() motion.toMatrix().shouldBe(trans * rot * scale) } } } } }
0
Kotlin
0
0
46b1b3de9474dda22291a33b93a9b40b634c29c0
1,311
kalahari
Apache License 2.0
domain/src/main/java/com/dev/domain/usecase/GetArticleDetailUseCase.kt
namdevlondhe
721,257,049
false
{"Kotlin": 57082}
package com.dev.domain.usecase import com.dev.domain.repository.ArticleRepository import javax.inject.Inject class GetArticleDetailUseCase @Inject constructor(private val articleRepository: ArticleRepository) : ArticleDetailUseCase { override suspend fun invoke(id: Int) = articleRepository.getArticleDetails(id) }
0
Kotlin
0
0
774f86686edf6451937d254d72a104f4ebb65a2b
324
Spaceflight-News
Apache License 2.0
utility/error-handler/src/main/kotlin/co/nilin/opex/utility/error/DefaultErrorTranslator.kt
opexdev
370,411,517
false
{"Kotlin": 1498213, "HTML": 43145, "Java": 19673, "PLpgSQL": 17262, "Shell": 7915, "Dockerfile": 5680, "HCL": 823}
package co.nilin.opex.utility.error import co.nilin.opex.utility.error.data.DefaultExceptionResponse import co.nilin.opex.utility.error.data.OpexException import co.nilin.opex.utility.error.spi.ErrorTranslator import co.nilin.opex.utility.error.spi.ExceptionResponse import org.springframework.stereotype.Component @Component class DefaultErrorTranslator : ErrorTranslator { override fun translate(ex: OpexException): ExceptionResponse { return DefaultExceptionResponse( ex.error.name, ex.error.code, ex.message ?: ex.error.message, ex.status ?: ex.error.status, ex.data, ex.crimeScene ) } }
26
Kotlin
14
23
38cb89e3361c4cb7476f68e357f588865f48ee6f
690
core
MIT License
shark/shark-heap-growth/src/test/java/shark/HeapGrowthDetectorJvmTest.kt
square
34,824,499
false
{"Kotlin": 1444933, "Java": 4762, "Shell": 531, "AIDL": 203}
package shark import java.io.File import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import shark.HprofHeapGraph.Companion.openHeapGraph class HeapGrowthDetectorJvmTest { class Leaky class MultiLeaky { val leaky = Leaky() to Leaky() } class CustomLinkedList(var next: CustomLinkedList? = null) @get:Rule val testFolder = TemporaryFolder() val leakies = mutableListOf<Leaky>() val stringLeaks = mutableListOf<String>() var customLeakyLinkedList = CustomLinkedList() val leakyHashMap = HashMap<String, Leaky>() val multiLeakies = mutableListOf<MultiLeaky>() @Test fun `empty scenario leads to no heap growth`() { val detector = simpleDetector().live() val emptyScenario = {} val heapTraversal = detector.detectRepeatedHeapGrowth(emptyScenario) assertThat(heapTraversal.growingNodes).isEmpty() } @Test fun `leaky increase leads to heap growth`() { val detector = simpleDetector().live() val heapTraversal = detector.detectRepeatedHeapGrowth { leakies += Leaky() } assertThat(heapTraversal.growingNodes).isNotEmpty } @Test fun `string leak increase leads to heap growth`() { val detector = simpleDetector().live() var index = 0 val heapTraversal = detector.detectRepeatedHeapGrowth { stringLeaks += "Yo ${++index}" } assertThat(heapTraversal.growingNodes).isNotEmpty } @Test fun `leak increase that ends leads to no heap growth`() { val maxHeapDumps = 10 val stopLeakingIndex = maxHeapDumps / 2 val detector = simpleDetector().live(maxHeapDumps = maxHeapDumps) var index = 0 val heapTraversal = detector.detectRepeatedHeapGrowth { if (++index < stopLeakingIndex) { leakies += Leaky() } } assertThat(heapTraversal.growingNodes).isEmpty() } @Test fun `multiple leaky scenarios per dump leads to heap growth`() { val scenarioLoopsPerDump = 5 val detector = simpleDetector().live(scenarioLoopsPerDump = scenarioLoopsPerDump) val heapTraversal = detector.detectRepeatedHeapGrowth { leakies += Leaky() } assertThat(heapTraversal.growingNodes).hasSize(1) val growingNode = heapTraversal.growingNodes.first() assertThat(growingNode.childrenObjectCountIncrease).isEqualTo(scenarioLoopsPerDump) } @Test fun `custom leaky linked list leads to heap growth`() { val detector = simpleDetector().live() val heapTraversal = detector.detectRepeatedHeapGrowth { customLeakyLinkedList = CustomLinkedList(customLeakyLinkedList) } assertThat(heapTraversal.growingNodes).isNotEmpty } @Test fun `custom leaky linked list reports descendant to root as flattened collection`() { val detector = simpleDetector().live() val heapTraversal = detector.detectRepeatedHeapGrowth { customLeakyLinkedList = CustomLinkedList(customLeakyLinkedList) customLeakyLinkedList = CustomLinkedList(customLeakyLinkedList) customLeakyLinkedList = CustomLinkedList(customLeakyLinkedList) customLeakyLinkedList = CustomLinkedList(customLeakyLinkedList) } assertThat(heapTraversal.growingNodes).hasSize(1) val growingNode = heapTraversal.growingNodes.first() assertThat(growingNode.children.size).isEqualTo(1) assertThat(growingNode.childrenObjectCountIncrease).isEqualTo(4) } @Test fun `growth along shared sub paths reported as single growth of shortest path`() { val detector = simpleDetector().live() val heapTraversal = detector.detectRepeatedHeapGrowth { multiLeakies += MultiLeaky() } assertThat(heapTraversal.growingNodes).hasSize(1) val growingNode = heapTraversal.growingNodes.first() assertThat(growingNode.nodeAndEdgeName).contains("ArrayList") } @Test fun `OpenJdk HashMap virtualized as array`() { val detector = openJdkDetector().live() var index = 0 val heapTraversal = detector.detectRepeatedHeapGrowth { leakyHashMap["key${++index}"] = Leaky() } val growingNode = heapTraversal.growingNodes.first() assertThat(growingNode.nodeAndEdgeName).contains("leakyHashMap") } @Test fun `OpenJdk ArrayList virtualized as array`() { val detector = openJdkDetector().live() val heapTraversal = detector.detectRepeatedHeapGrowth { leakies += Leaky() } val growingNode = heapTraversal.growingNodes.first() assertThat(growingNode.nodeAndEdgeName).contains("leakies") } private fun DiffingHeapGrowthDetector.live( scenarioLoopsPerDump: Int = 1, maxHeapDumps: Int = 5 ): LiveHeapGrowthDetector { return LiveHeapGrowthDetector(maxHeapDumps, ::dumpHeapGraph, scenarioLoopsPerDump, LoopingHeapGrowthDetector(this)) } private fun simpleDetector(): DiffingHeapGrowthDetector { val referenceMatchers = JdkReferenceMatchers.defaults + HeapTraversal.ignoredReferences val referenceReaderFactory = ActualMatchingReferenceReaderFactory(referenceMatchers) val gcRootProvider = MatchingGcRootProvider(referenceMatchers) return DiffingHeapGrowthDetector(referenceReaderFactory, gcRootProvider) } private fun openJdkDetector(): DiffingHeapGrowthDetector { val referenceMatchers = JdkReferenceMatchers.defaults + HeapTraversal.ignoredReferences val referenceReaderFactory = VirtualizingMatchingReferenceReaderFactory( referenceMatchers = referenceMatchers, virtualRefReadersFactory = { graph -> listOf( JavaLocalReferenceReader(graph, referenceMatchers), ) + OpenJdkInstanceRefReaders.values().mapNotNull { it.create(graph) } } ) val gcRootProvider = MatchingGcRootProvider(referenceMatchers) return DiffingHeapGrowthDetector(referenceReaderFactory, gcRootProvider) } private fun dumpHeapGraph(): CloseableHeapGraph { val hprofFolder = testFolder.newFolder() val hprofFile = File(hprofFolder, "${System.nanoTime()}.hprof") JvmTestHeapDumper.dumpHeap(hprofFile.absolutePath) return hprofFile.openHeapGraph() } }
79
Kotlin
3952
29,123
5e37dd661cd404ce2a474af24174ea7421b46f5e
6,104
leakcanary
Apache License 2.0
native/native.tests/testData/klib/header-klibs/compilation/inlineNoRegeneration/lib/lib.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}
package lib var result = "fail" inline fun foo(crossinline s: () -> String) { object { private inline fun test(crossinline z: () -> String) { result = object { //should be marked as public abi as there is no regenerated abject on inline fun run(): String { return "O" } }.run() + z() } fun foo() { test { s() } } }.foo() }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
454
kotlin
Apache License 2.0
app/navigation/src/androidMain/kotlin/com/mindera/kmpexample/presentation/main/MainScene.kt
Mindera
767,105,015
false
{"Kotlin": 89862, "Swift": 422}
package com.mindera.kmpexample.presentation.main import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import com.mindera.kmpexample.currencyexchange.HomeScreenScene import com.mindera.kmpexample.currencyexchange.opensource.OpensourceScene import com.mindera.kmpexample.presentation.main.Destination.CurrencyExchange import com.mindera.kmpexample.presentation.main.Destination.OpenSource import com.mindera.precompose.navigation.NavHost import com.mindera.precompose.navigation.scene import com.mindera.precompose.navigation.transition.NoTransition import moe.tlaster.precompose.navigation.rememberNavigator sealed class Destination( override val route: String, ) : com.mindera.precompose.navigation.Destination { data object CurrencyExchange : Destination("currency-exchange") data object OpenSource : Destination("opensource") } @Composable fun MainScene( /* Callback */ onBack: () -> Unit, ) { val navigator = rememberNavigator() NavHost( navTransition = remember { NoTransition }, navigator = navigator, initialRoute = CurrencyExchange, ) { scene(route = CurrencyExchange) { HomeScreenScene(onBack = onBack, navigator = navigator) } scene(route = OpenSource) { OpensourceScene(navigator = navigator) } } }
0
Kotlin
0
1
1c24d2aeade48da855424296ca036e6c1da1c1b3
1,360
Android-KMP-Template
Apache License 2.0
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/ChevronLeft.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.cssggicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.CssGgIcons public val CssGgIcons.ChevronLeft: ImageVector get() { if (_chevronLeft != null) { return _chevronLeft!! } _chevronLeft = Builder(name = "ChevronLeft", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.243f, 6.343f) lineTo(14.828f, 4.929f) lineTo(7.757f, 12.0f) lineTo(14.828f, 19.071f) lineTo(16.243f, 17.657f) lineTo(10.586f, 12.0f) lineTo(16.243f, 6.343f) close() } } .build() return _chevronLeft!! } private var _chevronLeft: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
1,517
compose-icons
MIT License
src/main/kotlin/net/testusuke/hh/core/Config/Data/BanConfig.kt
testusuke
266,439,339
false
null
package net.testusuke.hh.core.Config.Data import net.testusuke.hh.core.Ban.BanMain import net.testusuke.hh.core.Main import org.bukkit.configuration.file.YamlConfiguration import java.io.File import java.io.IOException class BanConfig(private val main:Main,private val banMain: BanMain) { private lateinit var file: File private var config = YamlConfiguration() init { // create file try { val pluginDirectory = main.dataFolder if(!pluginDirectory.exists())pluginDirectory.mkdir() val dataDirectory = File(pluginDirectory,"/data/") if(!dataDirectory.exists())dataDirectory.mkdir() // config file file = File(dataDirectory, "ban.yml") if(file.exists())file.createNewFile() // Load config = YamlConfiguration.loadConfiguration(file) }catch (e: IOException){ e.printStackTrace() } } private fun saveConfig(){ try { config.save(file) }catch (e: IOException){ e.printStackTrace() } } private fun getConfig(): YamlConfiguration { return config } fun loadMode(){ banMain.mode = config.getBoolean("mode") } fun saveMode(){ config.set("mode",banMain.mode) saveConfig() } }
0
Kotlin
0
1
9d2be7a8a96b881cccf6deeda86e069f6a5e43fb
1,355
HH-Core
Apache License 2.0
app/src/main/java/io/mvpstarter/sample/injection/component/FragmentComponent.kt
opencollective
97,630,908
true
{"Kotlin": 69048}
package io.mvpstarter.sample.injection.component import io.mvpstarter.sample.injection.PerFragment import io.mvpstarter.sample.injection.module.FragmentModule import dagger.Subcomponent /** * This component inject dependencies to all Fragments across the application */ @PerFragment @Subcomponent(modules = arrayOf(FragmentModule::class)) interface FragmentComponent
0
Kotlin
0
1
d9a7496343e21fbe019f3fbe32e7da2bb72a4911
370
kotlin-android-starter
The Unlicense
app/src/main/java/com/intmainreturn00/bookar/presentation/Fonts.kt
intmainreturn00
180,305,353
false
{"Kotlin": 66469, "Java": 7275}
package com.intmainreturn00.bookar.presentation import android.graphics.Typeface import android.widget.TextView enum class PodkovaFont(val path: String) { EXTRA_BOLD("fonts/Podkova-ExtraBold.ttf"), REGULAR("fonts/Podkova-Regular.ttf"), MEDIUM("fonts/Podkova-Medium.ttf"); fun apply(vararg tv: TextView) { for (t in tv) { t.setCustomFont(this) } } } fun TextView.setCustomFont(font: PodkovaFont) { typeface = Typeface.createFromAsset(context?.assets, font.path) }
0
Kotlin
1
16
ff14ba647c0d8ce2f117933cb349edde6eacc216
520
Bookar
MIT License
kotlin-jira-client/kotlin-jira-client-sdk/src/main/kotlin/com/linkedplanet/kotlinjiraclient/sdk/SdkJiraIssueOperator.kt
linked-planet
602,453,377
false
{"Kotlin": 522693, "Java": 744, "Shell": 499}
/*- * #%L * kotlin-jira-client-api * %% * Copyright (C) 2022 - 2023 linked-planet GmbH * %% * 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. * #L% */ package com.linkedplanet.kotlinjiraclient.sdk import arrow.core.Either import arrow.core.left import arrow.core.raise.either import arrow.core.right import com.atlassian.jira.bc.ServiceResult import com.atlassian.jira.bc.issue.search.SearchService import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.event.type.EventDispatchOption import com.atlassian.jira.issue.Issue import com.atlassian.jira.issue.IssueInputParameters import com.atlassian.jira.issue.MutableIssue import com.atlassian.jira.jql.parser.JqlQueryParser import com.atlassian.jira.user.ApplicationUser import com.atlassian.jira.util.ErrorCollection import com.atlassian.jira.util.ErrorCollection.Reason import com.atlassian.jira.util.ErrorCollections import com.atlassian.jira.web.bean.I18nBean import com.atlassian.jira.web.bean.PagerFilter import com.google.gson.JsonObject import com.linkedplanet.kotlinatlassianclientcore.common.api.Page import com.linkedplanet.kotlinatlassianclientcore.common.error.asEither import com.linkedplanet.kotlinjiraclient.api.error.JiraClientError import com.linkedplanet.kotlinjiraclient.api.interfaces.JiraIssueOperator import com.linkedplanet.kotlinjiraclient.api.model.JiraIssue import com.linkedplanet.kotlinjiraclient.sdk.field.SdkJiraField import com.linkedplanet.kotlinjiraclient.sdk.util.IssueJsonConverter import com.linkedplanet.kotlinjiraclient.sdk.util.catchJiraClientError import org.jetbrains.kotlin.util.removeSuffixIfPresent import javax.inject.Named import kotlin.math.ceil @Named object SdkJiraIssueOperator : JiraIssueOperator<SdkJiraField> { override var RESULTS_PER_PAGE: Int = 10 private val issueService by lazy { ComponentAccessor.getIssueService() } private val customFieldManager by lazy { ComponentAccessor.getCustomFieldManager() } private val searchService: SearchService by lazy { ComponentAccessor.getComponent(SearchService::class.java) } private val jiraAuthenticationContext by lazy { ComponentAccessor.getJiraAuthenticationContext() } private val jqlParser by lazy { ComponentAccessor.getComponent(JqlQueryParser::class.java) } private val applicationProperties by lazy { ComponentAccessor.getApplicationProperties() } private val webResourceUrlProvider by lazy { ComponentAccessor.getWebResourceUrlProvider() } private val issueJsonConverter = IssueJsonConverter() private fun user() = jiraAuthenticationContext.loggedInUser override suspend fun createIssue( projectId: Long, issueTypeId: Int, fields: List<SdkJiraField> ): Either<JiraClientError, JiraIssue?> = either { Either.catchJiraClientError { val inputParameters = issueInputParameters(projectId, issueTypeId, fields) val validateCreate = issueService.validateCreate(user(), inputParameters).toEither().bind() val createResult = issueService.create(user(), validateCreate).toEither().bind() toBasicReturnTypeIssue(createResult.issue) }.bind() } private fun toBasicReturnTypeIssue(createdIssue: MutableIssue): JiraIssue { val basePath = applicationProperties.jiraBaseUrl val contextPath = webResourceUrlProvider.baseUrl val fullPath = if (contextPath.isNotEmpty()) "$basePath/$contextPath" else basePath val selfLink = fullPath + "/rest/api/2/issue/" + createdIssue.id return JiraIssue(createdIssue.id.toString(), createdIssue.key, selfLink) } override suspend fun updateIssue( projectId: Long, issueTypeId: Int, issueKey: String, fields: List<SdkJiraField> ): Either<JiraClientError, Unit> = either { Either.catchJiraClientError { val issueId = issueService.getIssue(user(), issueKey).toEither().bind().issue.id val inputParameters = issueInputParameters(projectId, issueTypeId, fields) val validateUpdate = issueService.validateUpdate(user(), issueId, inputParameters) val validationResult = validateUpdate.toEither().bind() issueService.update(user(), validationResult, EventDispatchOption.ISSUE_UPDATED, false).toEither().bind() }.bind() } private fun issueInputParameters( projectId: Long, issueTypeId: Int, fields: List<SdkJiraField> ): IssueInputParameters? { val issueInput = issueService.newIssueInputParameters() issueInput.setSkipScreenCheck(true) issueInput.setSkipLicenceCheck(true) issueInput.setApplyDefaultValuesWhenParameterNotProvided(true) issueInput.setRetainExistingValuesWhenParameterNotProvided(true) issueInput.projectId = projectId issueInput.issueTypeId = issueTypeId.toString() fields.forEach { field -> field.render(issueInput) } return issueInput } override suspend fun deleteIssue(issueKey: String): Either<JiraClientError, Unit> = either { Either.catchJiraClientError { val issueToDelete = issueService.getIssue(user(), issueKey).toEither().bind() val validateDelete = issueService.validateDelete(user(), issueToDelete.issue.id).toEither().bind() issueService.delete(user(), validateDelete, EventDispatchOption.ISSUE_DELETED, false).toEither().bind() }.bind() } private fun <T : ServiceResult> T.toEither(errorTitle: String? = null): Either<JiraClientError, T> = when { this.isValid -> Either.Right(this) else -> Either.Left(jiraClientError(this.errorCollection, errorTitle ?: "${this::class.simpleName?.removeSuffixIfPresent("ServiceResult")}Error")) } private fun ErrorCollection.toEither(errorTitle: String = "SdkError") : Either<JiraClientError, Unit> = when { this.hasAnyErrors() -> jiraClientError(this, errorTitle).left() else -> Unit.right() } private fun jiraClientError(errorCollection: ErrorCollection, errorTitle: String = "SdkError"): JiraClientError { val worstReason: Reason? = Reason.getWorstReason(errorCollection.reasons) val httpStatusSuffix = worstReason?.let { " (${it.httpStatusCode})" } ?: "" return JiraClientError( errorTitle, errorCollection.errorMessages.joinToString() + httpStatusSuffix ) } override suspend fun <T> getIssueById( id: Int, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, T?> = getIssueByKey(id.toString(), parser) override suspend fun <T> getIssueByJQL( jql: String, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, T?> = either { val potentiallyMultipleIssues = getIssuesByJQLPaginated(jql, 0, 1, parser).bind() if (potentiallyMultipleIssues.totalItems < 1) { JiraClientError("Issue not found", "No issue was found.").asEither<JiraClientError, T?>().bind() } potentiallyMultipleIssues.items.first() } override suspend fun <T> getIssuesByIssueType( projectId: Long, issueTypeId: Int, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, List<T>> = getIssuesByJQL("project=$projectId AND issueType=$issueTypeId", parser) override suspend fun <T> getIssuesByTypePaginated( projectId: Long, issueTypeId: Int, pageIndex: Int, pageSize: Int, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, Page<T>> = getIssuesByJQLPaginated("project=$projectId AND issueType=$issueTypeId", pageIndex, pageSize, parser) override suspend fun <T> getIssueByKey( key: String, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, T?> = either { Either.catchJiraClientError { val issueResult = issueService.getIssue(user(), key) if (Reason.getWorstReason(issueResult.errorCollection.reasons) == Reason.NOT_FOUND){ return@catchJiraClientError null } val issue = issueResult.toEither().bind().issue ?: return@catchJiraClientError null issueToConcreteType(issue, parser).bind() }.bind() } override suspend fun <T> getIssuesByJQL( jql: String, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, List<T>> = either { val issuePage = getIssuesByJqlWithPagerFilter(jql, PagerFilter.getUnlimitedFilter(), parser).bind() issuePage.items } override suspend fun <T> getIssuesByJQLPaginated( jql: String, pageIndex: Int, pageSize: Int, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, Page<T>> = getIssuesByJqlWithPagerFilter(jql, PagerFilter.newPageAlignedFilter(pageIndex * pageSize, pageSize), parser) private suspend fun <T> issueToConcreteType( issue: Issue, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, T> { val jsonIssue: JsonObject = issueJsonConverter.createJsonIssue(issue) val customFieldMap = customFieldManager.getCustomFieldObjects(issue).associate { it.name to it.id } return parser(jsonIssue, customFieldMap) } private suspend fun <T> getIssuesByJqlWithPagerFilter( jql: String, pagerFilter: PagerFilter<*>?, parser: suspend (JsonObject, Map<String, String>) -> Either<JiraClientError, T> ): Either<JiraClientError, Page<T>> = either { val user = userOrError().bind() val query = jqlParser.parseQuery(jql) val search = searchService.search(user, query, pagerFilter) val issues = search.results .map { issue -> issueToConcreteType(issue, parser) } .bindAll() val totalItems = search.total val pageSize = pagerFilter?.pageSize ?: 0 val totalPages = ceil(totalItems.toDouble() / pageSize.toDouble()).toInt() val currentPageIndex = pagerFilter?.start?.let { start -> start / pageSize } ?: 0 Page(issues, totalItems, totalPages, currentPageIndex, pageSize) } private fun userOrError() : Either<JiraClientError, ApplicationUser> = either { val applicationUser = user() return applicationUser?.right() ?: jiraClientError( ErrorCollections .create( I18nBean(I18nBean.getLocaleFromUser(applicationUser)) .getText("admin.errors.issues.no.permission.to.see"), Reason.NOT_LOGGED_IN ) ).left() } }
1
Kotlin
0
1
ca29ed2cb8f0e6d2f3c876cade6b5b54c797c0f5
11,668
kotlin-atlassian-client
Apache License 2.0
platform/lib/sdk/src/main/kotlin/io/hamal/lib/sdk/admin/ExecLog.kt
hamal-io
622,870,037
false
{"Kotlin": 1744717, "C": 1398401, "TypeScript": 54320, "C++": 40651, "Lua": 36419, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 456, "CSS": 118}
package io.hamal.lib.sdk.admin import io.hamal.lib.domain._enum.ExecLogLevel import io.hamal.lib.domain.vo.* import io.hamal.lib.http.HttpTemplate import io.hamal.lib.http.body import io.hamal.request.AppendExecLogReq import kotlinx.serialization.Serializable @Serializable data class AdminAppendExecLogCmd( override val level: ExecLogLevel, override val message: ExecLogMessage, override val localAt: LocalAt ) : AppendExecLogReq @Serializable data class AdminExcLogList( val logs: List<AdminExecLog> ) @Serializable data class AdminExecLog( val id: ExecLogId, val execId: ExecId, val level: ExecLogLevel, val message: ExecLogMessage, val localAt: LocalAt, val remoteAt: RemoteAt ) interface AdminExecLogService { fun append(execId: ExecId, cmd: AdminAppendExecLogCmd) } internal class AdminExecLogServiceImpl( private val template: HttpTemplate ) : AdminExecLogService { override fun append(execId: ExecId, cmd: AdminAppendExecLogCmd) { template .post("/v1/execs/{execId}/logs") .path("execId", execId) .body(cmd) .execute() } }
6
Kotlin
0
0
6c7f5cc645ba67fb85df20d9a5d2e18372a012f4
1,151
hamal
Creative Commons Zero v1.0 Universal
client/src/main/kotlin/org/microg/nlp/client/GeocodeClient.kt
microg
17,454,060
false
null
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.nlp.client import android.content.Context import android.location.Address import android.os.Bundle import androidx.lifecycle.Lifecycle import org.microg.nlp.service.api.* import org.microg.nlp.service.api.Constants.STATUS_OK import java.util.concurrent.* import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine class GeocodeClient(context: Context, lifecycle: Lifecycle) : BaseClient<IGeocodeService>(context, lifecycle, { IGeocodeService.Stub.asInterface(it) }) { private val syncThreads: ThreadPoolExecutor = ThreadPoolExecutor(1, Runtime.getRuntime().availableProcessors(), 1, TimeUnit.SECONDS, LinkedBlockingQueue()) override val action: String get() = Constants.ACTION_GEOCODE fun requestGeocodeSync(request: GeocodeRequest, options: Bundle = defaultOptions): List<Address> = executeWithTimeout { withConnectedServiceSync { service -> service.requestGeocodeSync(request, options) } } suspend fun requestGeocode(request: GeocodeRequest, options: Bundle = defaultOptions): List<Address> = withService { service -> suspendCoroutine { service.requestGeocode(request, AddressesCallback(it), options) } } fun requestReverseGeocodeSync(request: ReverseGeocodeRequest, options: Bundle = defaultOptions): List<Address> = executeWithTimeout { withConnectedServiceSync { service -> service.requestReverseGeocodeSync(request, options) } } suspend fun requestReverseGeocode(request: ReverseGeocodeRequest, options: Bundle = defaultOptions): List<Address> = withService { service -> suspendCoroutine { service.requestReverseGeocode(request, AddressesCallback(it), options) } } suspend fun getGeocodeBackends(options: Bundle = defaultOptions): List<String> = withService { service -> suspendCoroutine { service.getGeocodeBackends(StringsCallback(it), options) } } suspend fun setGeocodeBackends(backends: List<String>, options: Bundle = defaultOptions): Unit = withService { service -> suspendCoroutine { service.setGeocodeBackends(backends, StatusCallback(it), options) } } private fun <T> executeWithTimeout(timeout: Long = CALL_TIMEOUT, action: () -> T): T { var result: T? = null val latch = CountDownLatch(1) var err: Exception? = null syncThreads.execute { try { result = action() } catch (e: Exception) { err = e } finally { latch.countDown() } } if (!latch.await(timeout, TimeUnit.MILLISECONDS)) throw TimeoutException() err?.let { throw it } return result ?: throw NullPointerException() } companion object { private const val CALL_TIMEOUT = 10000L } } private class AddressesCallback(private val continuation: Continuation<List<Address>>) : IAddressesCallback.Stub() { override fun onAddresses(statusCode: Int, addresses: List<Address>?) { if (statusCode == STATUS_OK) { continuation.resume(addresses.orEmpty()) } else { continuation.resumeWithException(RuntimeException("Status: $statusCode")) } } }
92
null
215
857
38a857f034d688fe19bcf41030d31478d90668a0
3,516
UnifiedNlp
Apache License 2.0
src/commonMain/kotlin/com/ktmi/tmi/dsl/builder/TwitchScope.kt
wooodenleg
192,805,554
false
null
package com.ktmi.tmi.dsl.builder import com.ktmi.irc.TwitchIRC import com.ktmi.tmi.client.TmiClient import com.ktmi.tmi.messages.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filter import kotlin.coroutines.CoroutineContext /** * Annotation that marks a Twitch DSL composed of [TwitchScope]s */ @DslMarker annotation class TwitchDsl /** * Base class for creating [TwitchDsl] components (scopes) * @param parent parent scope where messages are forwarded and from where main [Flow] of [TwitchMessage]s is retrieved * @param context [CoroutineContext] used for creating [TwitchMessage] listeners */ @TwitchDsl abstract class TwitchScope( val parent: TwitchScope?, context: CoroutineContext ) : CoroutineScope by CoroutineScope(context) { /** * Sends raw (unparsed) message to [TwitchIRC] * This message is sent up the chain of [TwitchScope]s. Each [TwitchScope] can alter this message * @param message string message that will be sent to [TwitchIRC] * @throws NoParentException */ open fun sendRaw(message: String) { parent?.sendRaw(message) ?: throw NoParentException() } /** * Retrieves main [Flow] of [TwitchMessage]s from [TmiClient] * This [Flow] is passed down the chain of [TwitchScope]s and each [TwitchScope] can alter the flow * @throws NoParentException */ open fun getTwitchFlow(): Flow<TwitchMessage> = parent?.getTwitchFlow() ?: throw NoParentException() /** Thrown when no parent is found */ class NoParentException : Exception("Accessing parent of top element") } /** * Scope where all events are available */ abstract class GlobalContextScope( parent: TwitchScope?, context: CoroutineContext ) : TwitchScope(parent, context) /** * Scope where all events are in relation to some **channel** * Events available: [JoinMessage], [LeaveMessage], [UserStateMessage], [RoomStateMessage], * [TextMessage], [ClearChatMessage], [ClearMessage], [NoticeMessage] and [UserNoticeMessage] */ abstract class ChannelContextScope( val channel: String, parent: TwitchScope?, context: CoroutineContext ) : TwitchScope(parent, context) { override fun getTwitchFlow(): Flow<TwitchMessage> { return super.getTwitchFlow() .filter { it.rawMessage.channel == channel.asChannelName } } } /** * Scope where all events are in relation to some **user** * Events available: [JoinMessage], [LeaveMessage], [UserStateMessage], [TextMessage], * [ClearChatMessage], [ClearMessage] and [UserNoticeMessage] */ abstract class UserContextScope( username: String, parent: TwitchScope?, context: CoroutineContext ) : TwitchScope(parent, context) { private val lowerUser = username.toLowerCase() override fun getTwitchFlow(): Flow<TwitchMessage> { return super.getTwitchFlow() .filter { it.rawMessage.author == lowerUser ||it.rawMessage.tags["login"] == lowerUser ||it.rawMessage.tags["display-name"]?.toLowerCase() == lowerUser ||(it is JoinMessage && it.username == lowerUser) ||(it is LeaveMessage && it.username == lowerUser) ||(it is ClearChatMessage && it.bannedUser == lowerUser) } } } /** * Scope where all events are in relation to **UserState** * Events available: [UserStateMessage], [TextMessage] and [UserNoticeMessage] */ abstract class UserStateContextScope( parent: TwitchScope?, context: CoroutineContext ) : TwitchScope(parent, context)
3
Kotlin
1
7
2f0ff8ed51d00a0bc5d868ec413591494fbc2e7e
3,655
TmiK
MIT License
composeApp/src/jvmMain/kotlin/de/cacheoverflow/cashflow/main.kt
Cach30verfl0w
808,336,331
false
{"Kotlin": 103104, "Swift": 661}
/* * Copyright 2024 Cach30verfl0w * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.cacheoverflow.cashflow import androidx.compose.runtime.remember import androidx.compose.ui.window.Window import androidx.compose.ui.window.application import com.arkivanov.decompose.DefaultComponentContext import com.arkivanov.essenty.lifecycle.LifecycleRegistry import de.cacheoverflow.cashflow.ui.components.RootComponent import de.cacheoverflow.cashflow.utils.DesktopPreferencesProvider import de.cacheoverflow.cashflow.utils.DesktopSecurityProvider import de.cacheoverflow.cashflow.utils.security.AbstractSecurityProvider import org.koin.core.context.startKoin import org.koin.core.module.dsl.singleOf import org.koin.dsl.module // TODO: Redesign app for both desktop and mobile val compatibilityModule = module { single<AbstractSecurityProvider> { DesktopSecurityProvider() } singleOf(::DesktopSecurityProvider) single<IPreferencesProvider> { DesktopPreferencesProvider() } singleOf(::DesktopPreferencesProvider) } fun main() = application { startKoin { modules(compatibilityModule, sharedModule) } val root = remember { RootComponent(DefaultComponentContext(LifecycleRegistry())) } Window(onCloseRequest = ::exitApplication, title = "Cash3Fl0w") { App(root) } }
0
Kotlin
0
0
a5cdb3838b6b49de8fd3e249e25e87b7a3141a1f
1,830
cash3fl0w
Apache License 2.0
data/src/main/java/com/mb/data/datastores/VenuesDataStore.kt
michalbujalski
124,138,856
false
null
package com.mb.data.datastores import com.mb.data.entities.VenueEntity import io.reactivex.Observable interface VenuesDataStore : DataStore<VenueEntity>{ fun observeAll(): Observable<List<VenueEntity>> }
1
Kotlin
1
2
d7ad2e74bac4f8100882c23ed48a5a6b79ab4fa3
209
NearbyVenues
MIT License
app/src/main/java/com/kyberswap/android/domain/model/Wallet.kt
KYRDTeam
181,612,742
false
null
package com.kyberswap.android.domain.model import android.os.Parcelable import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey import com.kyberswap.android.util.ext.shortenValue import com.kyberswap.android.util.ext.toBigDecimalOrDefaultZero import com.kyberswap.android.util.ext.toDisplayNumber import com.kyberswap.android.util.ext.toWalletAddress import com.kyberswap.android.util.views.DateTimeHelper import kotlinx.android.parcel.Parcelize import org.consenlabs.tokencore.wallet.Wallet import org.consenlabs.tokencore.wallet.WalletManager import org.jetbrains.annotations.NotNull import java.math.BigDecimal @Parcelize @Entity(tableName = "wallets") data class Wallet( @PrimaryKey @NotNull val address: String = "", val walletId: String = "", val name: String = "", val cipher: String = "", var isSelected: Boolean = false, val mnemonicAvailable: Boolean = false, var unit: String = "USD", var balance: String = "0", @Embedded var promo: Promo? = Promo(), val createAt: Long = 0, val hasBackup: Boolean = false ) : Parcelable { constructor(wallet: Wallet) : this( wallet.address.toWalletAddress(), wallet.id, wallet.metadata.name ) val displayWalletAddress: String get() = address.shortenValue() val walletPath: String get() = WalletManager.storage.keystoreDir.toString() + "/wallets/" + walletId + ".json" val walletAddress: String get() = if (isPromoPayment) promo?.receiveAddress ?: address else address fun isSameWallet(other: com.kyberswap.android.domain.model.Wallet?): Boolean { return this.address == other?.address && this.isSelected == other.isSelected && this.unit == other.unit && this.isPromo == other.isPromo } fun display(): String { val displayBuilder = StringBuilder() if (name.isNotEmpty()) { displayBuilder.append(name).append(" - ") } displayBuilder.append(address.substring(0, 5)) .append("...") .append( address.substring( if (address.length > 6) { address.length - 6 } else address.length ) ) return displayBuilder.toString() } val displayBalance: String get() = if (balance.toBigDecimalOrDefaultZero() > BigDecimal(1E-18)) balance.toBigDecimalOrDefaultZero() .toDisplayNumber() else BigDecimal.ZERO.toDisplayNumber() val isPromo: Boolean get() = promo != null && promo!!.type.isNotEmpty() val isPromoPayment: Boolean get() = isPromo && Promo.PAYMENT == promo?.type val expiredDatePromoCode: String get() = DateTimeHelper.displayDate(promo?.expiredDate) }
1
null
10
26
abd4ab033d188918849e5224cc8204409776391b
2,885
android-app
MIT License
app/src/main/java/com/breezefsmaddischemicocorporation/features/newcollection/model/NewCollectionListResponseModel.kt
DebashisINT
641,390,752
false
null
package com.breezefsmaddischemicocorporation.features.newcollection.model import com.breezefsmaddischemicocorporation.app.domain.CollectionDetailsEntity import com.breezefsmaddischemicocorporation.base.BaseResponse import com.breezefsmaddischemicocorporation.features.shopdetail.presentation.model.collectionlist.CollectionListDataModel /** * Created by Saikat on 15-02-2019. */ class NewCollectionListResponseModel : BaseResponse() { //var collection_list: ArrayList<CollectionListDataModel>? = null var collection_list: ArrayList<CollectionDetailsEntity>? = null }
0
Kotlin
0
0
c08eaf8cb0a1f3ade4f1762526afe1fa3976690d
578
AddisChemicoCorporation
Apache License 2.0
typedlistadapter/src/test/java/pl/allegro/typedlistadapter/TypedListViewHolderFactoryTest.kt
allegro
368,228,194
false
null
package pl.allegro.typedlistadapter import android.view.View import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertFalse import junit.framework.TestCase.assertTrue import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify class TypedListViewHolderFactoryTest { private val viewHolderFactories: TypedListViewHolderFactory<TestItem> = object : TypedListViewHolderFactory<TestItem>( layoutId = 0, viewHolderClass = TestViewHolder::class.java, createViewHolder = { TestViewHolder(it) }, areItemsTheSame = { first, second -> first.id == second.id }, areContentsTheSame = { first, second -> first.message == second.message }, getChangePayload = { _, second -> Payload.Message(second.message) }, ) { } @Test fun `should check if item is not compatible`() { // when val result = viewHolderFactories.isItemCompatible(IncompatibleItem) // then assertFalse(result) } @Test fun `should check if item is compatible`() { // given val item = TestItem(1, "Test message") // when val result = viewHolderFactories.isItemCompatible(item) // then assertTrue(result) } @Test fun `should check if item are same class and are the same`() { // given val oldItem = TestItem(1, "Test message") val newItem = TestItem(1, "Test message") // when val result = viewHolderFactories.hasItemsTheSameClassAndAreTheSame(oldItem, newItem) // then assertTrue(result) } @Test fun `should get change payload`() { // given val oldItem = TestItem(1, "Test message") val newItem = TestItem(1, "New message") // when val result = viewHolderFactories.getChangePayload(oldItem, newItem) // then assertEquals(result, Payload.Message("New message")) } @Test fun `should bind viewHolder`() { // given val item = TestItem(1, "Test message") val viewHolder: TestViewHolder = mock() // when viewHolderFactories.bind(item, viewHolder) // then verify(viewHolder).bind(item) } @Test fun `should bind viewHolder with payloads`() { // given val item = TestItem(1, "Old Message") val viewHolder: TestViewHolder = mock() val payloads = mutableListOf<Any>(Payload.Message("New message")) // when viewHolderFactories.bind(item, viewHolder, payloads) // then verify(viewHolder).bind(item, payloads) } private data class TestItem( val id: Int, val message: String ) : TypedListItem private object IncompatibleItem : TypedListItem private open class TestViewHolder(view: View) : TypedListViewHolder<TestItem>(view) { override fun bind(item: TestItem) { // nop } } private sealed class Payload { data class Message(val message: String) : Payload() } }
0
Kotlin
1
6
157c1b4bcab5dcdfcc52e7ff708d7c09b636501b
3,133
TypedListAdapter
Apache License 2.0
features/login/src/main/java/com/supercaliman/login/domain/UserMapper.kt
SuperCaliMan
280,449,917
false
null
package com.supercaliman.login.domain import com.google.firebase.auth.FirebaseUser import com.supercaliman.core.domain.Mapper import com.supercaliman.core.domain.dto.User import javax.inject.Inject class UserMapper @Inject constructor() : Mapper<FirebaseUser?, User?> { override fun map(data: FirebaseUser?): User? { return if (data != null) { User( uuid = data.uid, providerId = data.providerId, displayName = data.displayName, photoUrl = data.photoUrl.toString(), isEmailVerified = data.isEmailVerified, email = data.email ) } else { null } } }
0
Kotlin
0
1
8961f03823afd25db4624017eea1d5a49ad06d13
713
Notes
Apache License 2.0
domain/src/androidMain/kotlin/gcu/product/friendly/viewmodel/video/VideoPlayerEvent.kt
Ilyandr
612,297,078
false
null
package gcu.product.friendly.viewmodel.video import gcu.product.friendly.source.BaseEvent sealed class VideoPlayerEvent : BaseEvent { object EmptyEvent : VideoPlayerEvent() data class OnLoadVideo(val url: String) : VideoPlayerEvent() object OnClearPlayer : VideoPlayerEvent() }
0
Kotlin
0
1
c106ef8502d8c683d63fe69ac0652d19196e0ebf
294
Friendly
Apache License 2.0
example/src/main/java/org/xmtp/android/example/utils/KeyUtil.kt
xmtp
577,891,020
false
{"Kotlin": 433483, "Java": 25286, "JavaScript": 959, "Python": 539, "Dockerfile": 152, "Shell": 91}
package org.xmtp.android.example.utils import android.accounts.AccountManager import android.content.Context import org.xmtp.android.example.R class KeyUtil(val context: Context) { fun loadKeys(): String? { val accountManager = AccountManager.get(context) val accounts = accountManager.getAccountsByType(context.getString(R.string.account_type)) val account = accounts.firstOrNull() ?: return null return accountManager.getPassword(account) } }
1
Kotlin
10
31
1eb7b1f0534bd5f95e1aeff54088b4c069b2a35f
498
xmtp-android
MIT License
app/src/main/java/com/example/products_store/settings/SettingsViewModel.kt
dorindorsman
786,537,406
false
{"Kotlin": 68682}
package com.example.products_store.settings import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.products_store.data.models.AppLanguage import com.example.products_store.data.models.AppTheme import com.example.products_store.ui.language.LanguageState import com.example.products_store.ui.theme.ThemeState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class SettingsViewModel( private val themeState: ThemeState, private val languageState: LanguageState ) : ViewModel() { companion object { const val TAG = "SettingsViewModel" } fun handle(event: SettingsEvent) { Log.d(TAG, "handle") when (event) { is SettingsEvent.UpdateTheme -> { updateTheme(event.theme) } is SettingsEvent.UpdateLanguage -> { updateLanguage(event.language) } SettingsEvent.Logout -> {} } } fun getTheme() = themeState.theme fun getLanguage() = languageState.language private fun updateTheme(theme: AppTheme) = viewModelScope.launch(Dispatchers.IO) { Log.d(TAG, "updateTheme") themeState.updateTheme(theme) } private fun updateLanguage(language: AppLanguage) = viewModelScope.launch(Dispatchers.IO) { Log.d(TAG, "updateLanguage") languageState.updateLanguage(language) } }
0
Kotlin
0
0
1e282feef4e1135d86ea1de3eee7969ffcd60dd9
1,450
ProductsStore
Apache License 2.0
libopengl/src/main/java/com/example/opengl/opengl/render/MyRender.kt
yudengwei
287,524,563
false
{"Java Properties": 2, "Gradle": 9, "Text": 27, "Ignore List": 1, "INI": 6, "Proguard": 7, "Kotlin": 100, "XML": 44, "JSON": 40, "Java": 33, "GLSL": 1, "CMake": 17, "C++": 16, "C": 5, "Ninja": 8}
package com.example.opengl.opengl.render import android.opengl.GLES20 import android.opengl.GLSurfaceView import com.example.opengl.opengl.flatgraphics.* import javax.microedition.khronos.egl.EGLConfig import javax.microedition.khronos.opengles.GL10 class MyRender : GLSurfaceView.Renderer { private lateinit var mGraphics : FlatGraphics override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) { mGraphics = Triangle() GLES20.glClearColor(1f, 1f, 1f, 1f) } override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) { GLES20.glViewport(0, 0, width, height) mGraphics.onSurfaceChanged(width, height) } override fun onDrawFrame(gl: GL10?) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) mGraphics.draw() } }
1
null
1
1
d6d644e330f5f2b3d43e2451933a30987a5d373e
796
Demo
Apache License 2.0
app/src/test/java/foo/bar/compose/feature/tictactoe/IsWinnerTest.kt
erdo
453,803,966
false
{"Kotlin": 43338}
package foo.bar.compose.feature.tictactoe import foo.bar.compose.feature.tictactoe.Player.* import junit.framework.Assert.assertEquals import org.junit.Test typealias N = Nobody class IsWinnerTest { @Test fun `when empty board, no winners`() { // arrange val board: List<List<Player>> = listOf( listOf(N, N, N), listOf(N, N, N), listOf(N, N, N) ) // act // assert assertEquals(false, isWinner(Nobody, board)) assertEquals(false, isWinner(X, board)) assertEquals(false, isWinner(O, board)) } @Test fun `when board column, x wins, o looses`() { // arrange val board: List<List<Player>> = listOf( listOf(X, O, N), listOf(X, O, O), listOf(X, N, X) ) // act // assert assertEquals(false, isWinner(N, board)) assertEquals(true, isWinner(X, board)) assertEquals(false, isWinner(O, board)) } @Test fun `when board row, x wins, o looses`() { // arrange val board: List<List<Player>> = listOf( listOf(X, X, X), listOf(O, O, N), listOf(O, N, X) ) // act // assert assertEquals(false, isWinner(N, board)) assertEquals(true, isWinner(X, board)) assertEquals(false, isWinner(O, board)) } @Test fun `when board anti-diagonal, x wins, o looses`() { // arrange val board: List<List<Player>> = listOf( listOf(O, O, X), listOf(O, X, N), listOf(X, N, X) ) // act // assert assertEquals(false, isWinner(N, board)) assertEquals(true, isWinner(X, board)) assertEquals(false, isWinner(O, board)) } @Test fun `when board 1, x looses, o looses`() { // arrange val board: List<List<Player>> = listOf( listOf(O, O, X), listOf(X, X, O), listOf(O, O, X) ) // act // assert assertEquals(false, isWinner(N, board)) assertEquals(false, isWinner(X, board)) assertEquals(false, isWinner(O, board)) } @Test fun `when board 2, x looses, o wins`() { // arrange val board: List<List<Player>> = listOf( listOf(O, O, O), listOf(X, X, O), listOf(O, O, X) ) // act // assert assertEquals(false, isWinner(N, board)) assertEquals(false, isWinner(X, board)) assertEquals(true, isWinner(O, board)) } @Test fun `when board 3, x looses, o wins`() { // arrange val board: List<List<Player>> = listOf( listOf(O, O, O), listOf(X, X, O), listOf(O, O, O) ) // act // assert assertEquals(false, isWinner(N, board)) assertEquals(false, isWinner(X, board)) assertEquals(true, isWinner(O, board)) } }
0
Kotlin
0
2
93d5eedb372ec755ef754fd186cacc76bfc198c4
3,058
fore-mvp-compose-tutorial
Apache License 2.0
src/test/kotlin/r2dbcfun/test/DBTestUtil.kt
dkindler
351,886,663
false
null
package r2dbcfun.test import failfast.ContextDSL import failfast.RootContext import io.r2dbc.pool.ConnectionPool import io.r2dbc.pool.ConnectionPoolConfiguration import io.r2dbc.spi.ConnectionFactories import io.r2dbc.spi.ConnectionFactory import io.vertx.pgclient.PgConnectOptions import io.vertx.reactivex.pgclient.PgPool import io.vertx.reactivex.sqlclient.SqlClient import io.vertx.sqlclient.PoolOptions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.withContext import r2dbcfun.dbio.TransactionProvider import r2dbcfun.dbio.TransactionalConnectionProvider import r2dbcfun.dbio.r2dbc.R2DbcDBConnectionFactory import r2dbcfun.dbio.vertx.VertxDBConnectionFactory import r2dbcfun.test.TestConfig.TEST_POOL_SIZE import java.io.BufferedReader import java.time.Duration import java.util.* import kotlin.reflect.KClass object TestConfig { val ALL_PSQL = System.getenv("ALL_PSQL") != null val H2_ONLY = System.getenv("H2_ONLY") != null val TEST_POOL_SIZE = 2 } val schemaSql = DBTestUtil::class.java.getResourceAsStream("/db/migration/V1__create_test_tables.sql").bufferedReader() .use(BufferedReader::readText) class DBTestUtil(val databaseName: String) { private val h2 = H2TestDatabase() val psql13 = PSQLContainer("postgres:13-alpine", databaseName) val postgreSQLContainers = if (TestConfig.ALL_PSQL) listOf( psql13, PSQLContainer("postgres:12-alpine", databaseName), PSQLContainer("postgres:11-alpine", databaseName), PSQLContainer("postgres:10-alpine", databaseName), PSQLContainer("postgres:9-alpine", databaseName) ) else listOf(psql13) val databases = if (TestConfig.H2_ONLY) { listOf(h2) } else listOf(h2) + postgreSQLContainers.map { R2DBCPostgresFactory(it) } + postgreSQLContainers.map { VertxPSQLTestDatabase(it) } val unstableDatabases: List<TestDatabase> = listOf() interface TestDatabase { val name: String suspend fun createDB(): ConnectionProviderFactory fun prepare() {} } inner class H2TestDatabase : TestDatabase { override val name = "H2" override suspend fun createDB(): ConnectionProviderFactory { val uuid = UUID.randomUUID() val databaseName = "$databaseName$uuid" val connectionFactory = ConnectionFactories.get("r2dbc:h2:mem:///$databaseName;DB_CLOSE_DELAY=-1") return R2dbcConnectionProviderFactory(connectionFactory) } } class R2DBCPostgresFactory(private val psqlContainer: PSQLContainer) : TestDatabase { override val name = "R2DBC-${psqlContainer.dockerImage}" override suspend fun createDB(): ConnectionProviderFactory { val db = psqlContainer.preparePostgresDB() return R2dbcConnectionProviderFactory( ConnectionFactories.get("r2dbc:postgresql://test:test@${db.host}:${db.port}/${db.databaseName}"), db ) } } inner class VertxPSQLTestDatabase(val psql: PSQLContainer) : TestDatabase { override val name = "Vertx-${psql.dockerImage}" override suspend fun createDB(): ConnectionProviderFactory { val database = psql.preparePostgresDB() val connectOptions = PgConnectOptions() .setPort(database.port) .setHost(database.host) .setDatabase(database.databaseName) .setUser("test") .setPassword("<PASSWORD>") return VertxConnectionProviderFactory(connectOptions, database) } override fun prepare() { psql.prepare() } } } class VertxConnectionProviderFactory(val poolOptions: PgConnectOptions, val db: AutoCloseable) : ConnectionProviderFactory { val clients = mutableListOf<SqlClient>() override suspend fun create(): TransactionProvider { val client = PgPool.pool(poolOptions, PoolOptions().setMaxSize(TEST_POOL_SIZE)) clients.add(client) val connectionProvider = TransactionalConnectionProvider(VertxDBConnectionFactory(client)) connectionProvider.withConnection { it.execute(schemaSql) } return connectionProvider } override suspend fun close() { clients.forEach { it.close() } db.close() } } class R2dbcConnectionProviderFactory( private val connectionFactory: ConnectionFactory, private val closable: AutoCloseable? = null ) : ConnectionProviderFactory { private val pools = mutableListOf<ConnectionPool>() override suspend fun create(): TransactionProvider { val pool = ConnectionPool( ConnectionPoolConfiguration.builder(connectionFactory) .maxIdleTime(Duration.ofMillis(1000)) .maxSize(TEST_POOL_SIZE) .build() ) pools.add(pool) val dbConnectionFactory = R2DbcDBConnectionFactory(pool) val connectionProvider = TransactionalConnectionProvider(dbConnectionFactory) connectionProvider.withConnection { it.execute(schemaSql) } return connectionProvider } override suspend fun close() { val poolMetrics = buildString { pools.forEach { val metrics = it.metrics.get() append("allocatedSize: ${metrics.allocatedSize()}") append(" acquiredSize: ${metrics.acquiredSize()}") it.disposeLater().awaitFirstOrNull() append("\nallocatedSize: ${metrics.allocatedSize()}") append(" acquiredSize: ${metrics.acquiredSize()}") append(" disposed: ${it.isDisposed}") } } try { closable?.close() } catch (e: Exception) { println("ERROR dropping database. pool metrics:${poolMetrics}") } } } interface ConnectionProviderFactory { suspend fun create(): TransactionProvider suspend fun close() } suspend fun ContextDSL.forAllDatabases( databases: List<DBTestUtil.TestDatabase>, tests: suspend ContextDSL.(suspend () -> TransactionProvider) -> Unit ) { databases.map { db -> context("on ${db.name}") { val createDB = autoClose(db.createDB()) { it.close() } val connectionFactory: suspend () -> TransactionProvider = { createDB.create() } tests(connectionFactory) } } } fun describeOnAllDbs( subject: KClass<*>, databases: List<DBTestUtil.TestDatabase>, disabled: Boolean = false, tests: suspend ContextDSL.(suspend () -> TransactionProvider) -> Unit ) = describeOnAllDbs("the ${subject.simpleName!!}", databases, disabled, tests) fun describeOnAllDbs( contextName: String, databases: List<DBTestUtil.TestDatabase>, disabled: Boolean = false, tests: suspend ContextDSL.(suspend () -> TransactionProvider) -> Unit ): List<RootContext> { return databases.map { testDB -> RootContext("$contextName on ${testDB.name}", disabled) { val createDB = autoClose(withContext(Dispatchers.IO) { testDB.createDB() }) { it.close() } val connectionFactory: suspend () -> TransactionProvider = { createDB.create() } tests(connectionFactory) } } }
0
null
0
0
e35b459f245806125ea5820fbb31ced6e183e209
7,399
r2dbcfun
MIT License
features/home/impl/src/main/java/ru/aleshin/features/home/impl/presentation/ui/overview/views/UndefinedTaskSection.kt
v1tzor
638,022,252
false
null
/* * Copyright 2023 <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 ru.aleshin.features.home.impl.presentation.ui.overview.views import androidx.compose.animation.AnimatedContent import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.togetherWith import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth 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.lazy.LazyListState import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.AssistChip import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.RichTooltipBox import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.rememberRichTooltipState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import ru.aleshin.core.ui.theme.material.surfaceOne import ru.aleshin.core.ui.theme.material.surfaceThree import ru.aleshin.core.ui.theme.material.surfaceTwo import ru.aleshin.core.ui.views.ImportanceBadge import ru.aleshin.core.ui.views.PlaceholderBox import ru.aleshin.core.ui.views.toDaysTitle import ru.aleshin.core.utils.functional.Constants import ru.aleshin.features.home.api.presentation.mappers.mapToIconPainter import ru.aleshin.features.home.impl.presentation.models.categories.CategoriesUi import ru.aleshin.features.home.impl.presentation.models.schedules.UndefinedTaskUi import ru.aleshin.features.home.impl.presentation.theme.HomeThemeRes import java.util.Date /** * @author <NAME> on 02.11.2023. */ @Composable internal fun UndefinedTaskSection( modifier: Modifier = Modifier, isLoading: Boolean, categories: List<CategoriesUi>, tasks: List<UndefinedTaskUi>, onAddOrUpdateTask: (UndefinedTaskUi) -> Unit, onDeleteTask: (UndefinedTaskUi) -> Unit, onExecuteTask: (Date, UndefinedTaskUi) -> Unit, ) { Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(12.dp), ) { Text( modifier = Modifier.padding(horizontal = 16.dp), text = HomeThemeRes.strings.undefinedTasksHeader, color = MaterialTheme.colorScheme.onBackground, style = MaterialTheme.typography.titleSmall, ) AnimatedContent( targetState = isLoading, label = "Undefined tasks", transitionSpec = { fadeIn(animationSpec = tween(600, delayMillis = 90)).togetherWith( fadeOut(animationSpec = tween(300)), ) }, ) { loading -> if (!loading) { UndefinedTaskSectionLazyRow( categories = categories, tasks = tasks, onAddOrUpdateTask = onAddOrUpdateTask, onDeleteIconClick = onDeleteTask, onExecuteButtonClick = onExecuteTask, ) } else { UndefinedTaskSectionLazyRowPlaceholder() } } } } @OptIn(ExperimentalFoundationApi::class) @Composable internal fun UndefinedTaskSectionLazyRow( modifier: Modifier = Modifier, state: LazyListState = rememberLazyListState(), categories: List<CategoriesUi>, tasks: List<UndefinedTaskUi>, onAddOrUpdateTask: (UndefinedTaskUi) -> Unit, onDeleteIconClick: (UndefinedTaskUi) -> Unit, onExecuteButtonClick: (Date, UndefinedTaskUi) -> Unit, flingBehavior: FlingBehavior = rememberSnapFlingBehavior(state), userScrollEnabled: Boolean = true, ) { var openTaskDateChooserDialog by remember { mutableStateOf(false) } var openTaskEditorDialog by remember { mutableStateOf(false) } var editableTask by remember { mutableStateOf<UndefinedTaskUi?>(null) } LazyRow( modifier = modifier, state = state, contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp), flingBehavior = flingBehavior, userScrollEnabled = userScrollEnabled, ) { item { AddUndefinedTaskItem( modifier = Modifier.animateItemPlacement(), isCompact = tasks.isNotEmpty(), onClick = { openTaskEditorDialog = true; editableTask = null }, ) } items(tasks) { undefinedTask -> UndefinedTaskItem( modifier = Modifier.animateItemPlacement(), model = undefinedTask, onClick = { openTaskEditorDialog = true; editableTask = undefinedTask }, onDeleteIconClick = { onDeleteIconClick(undefinedTask) }, onExecuteButtonClick = { openTaskDateChooserDialog = true; editableTask = undefinedTask }, ) } } if (openTaskEditorDialog) { UndefinedTaskEditorDialog( categories = categories, model = editableTask, onDismiss = { openTaskEditorDialog = false }, onConfirm = { onAddOrUpdateTask(it) openTaskEditorDialog = false }, ) } if (openTaskDateChooserDialog) { TaskDateChooserDialog( onDismiss = { openTaskDateChooserDialog = false }, onConfirm = { date -> editableTask?.let { task -> onExecuteButtonClick(date, task) } openTaskDateChooserDialog = false }, ) } } @Composable internal fun UndefinedTaskSectionLazyRowPlaceholder( modifier: Modifier = Modifier, ) { LazyRow( modifier = modifier, contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp), userScrollEnabled = false, ) { items(Constants.Placeholder.ITEMS) { PlaceholderBox( modifier = Modifier.size(165.dp, 170.dp), shape = MaterialTheme.shapes.large, ) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun UndefinedTaskItem( modifier: Modifier = Modifier, enabled: Boolean = true, model: UndefinedTaskUi, onClick: () -> Unit, onDeleteIconClick: () -> Unit, onExecuteButtonClick: () -> Unit, ) { Surface( onClick = onClick, modifier = modifier.size(175.dp, 175.dp), enabled = enabled, shape = MaterialTheme.shapes.large, color = MaterialTheme.colorScheme.surfaceOne(), ) { val scope = rememberCoroutineScope() val tooltipState = rememberRichTooltipState(isPersistent = true) Column( modifier = Modifier.padding(start = 12.dp, end = 8.dp, top = 12.dp, bottom = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { Row( modifier = Modifier.height(32.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, ) { if (model.mainCategory.defaultType != null) { Icon( painter = model.mainCategory.defaultType.mapToIconPainter(), contentDescription = null, tint = MaterialTheme.colorScheme.primary, ) } else { Text( text = model.mainCategory.customName?.first()?.uppercaseChar()?.toString() ?: "*", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleLarge, ) } Spacer(modifier = Modifier.weight(1f)) if (model.deadline != null) { DeadlineView(deadline = model.deadline) } if (model.note != null) { RichTooltipBox( title = { Text(text = HomeThemeRes.strings.noteTitle) }, text = { Text(text = model.note) }, tooltipState = tooltipState, ) { Box( modifier = Modifier .size(32.dp) .clip(MaterialTheme.shapes.small) .background(MaterialTheme.colorScheme.surfaceThree()) .clickable { scope.launch { if (tooltipState.isVisible) tooltipState.dismiss() else tooltipState.show() } }, ) { Icon( modifier = Modifier.size(18.dp).align(Alignment.Center), painter = painterResource(id = HomeThemeRes.icons.notes), contentDescription = null, tint = MaterialTheme.colorScheme.onPrimaryContainer, ) } } } } Column(modifier = Modifier.weight(1f)) { Row( horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( text = model.mainCategory.fetchName() ?: HomeThemeRes.strings.noneTitle, color = MaterialTheme.colorScheme.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleMedium, ) if (model.isImportant) { ImportanceBadge() } } Text( text = model.subCategory?.name ?: HomeThemeRes.strings.noneTitle, color = MaterialTheme.colorScheme.onSurface, maxLines = 2, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium, ) } Row( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, ) { AssistChip( modifier = Modifier.weight(1f).height(32.dp), label = { Text( modifier = Modifier.fillMaxWidth(), text = HomeThemeRes.strings.executeUndefinedTasksTitle, textAlign = TextAlign.Center, ) }, onClick = onExecuteButtonClick, ) IconButton( modifier = Modifier.size(24.dp), onClick = onDeleteIconClick, ) { Icon( modifier = Modifier.size(18.dp), imageVector = Icons.Default.Delete, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } } } } } @Composable internal fun DeadlineView( modifier: Modifier = Modifier, deadline: Date, ) { Surface( modifier = modifier, shape = MaterialTheme.shapes.small, color = MaterialTheme.colorScheme.surfaceTwo(), ) { Row( modifier = Modifier.padding(horizontal = 4.dp, vertical = 6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically, ) { Icon( modifier = Modifier.size(18.dp), painter = painterResource(id = HomeThemeRes.icons.duration), contentDescription = null, tint = MaterialTheme.colorScheme.primary, ) Text( text = (deadline.time - Date().time).toDaysTitle(), color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.labelMedium, ) } } } @Composable internal fun AddUndefinedTaskItem( modifier: Modifier = Modifier, enabled: Boolean = true, isCompact: Boolean = true, onClick: () -> Unit, ) { Surface( onClick = onClick, modifier = modifier.height(170.dp).width(if (isCompact) 48.dp else 165.dp).animateContentSize(), enabled = enabled, shape = MaterialTheme.shapes.large, color = MaterialTheme.colorScheme.surfaceOne(), ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { Icon( imageVector = Icons.Default.Add, contentDescription = null, tint = MaterialTheme.colorScheme.primary, ) } } }
7
null
31
262
4238f8d894ab51859b480d339e6b23ab89d79190
15,558
TimePlanner
Apache License 2.0
app/src/main/java/baltamon/mx/pokedexmvp/pokemones/PokemonesFragmentView.kt
Balthair94
95,622,898
false
null
package baltamon.mx.pokedexmvp.pokemones import baltamon.mx.pokedexmvp.models.NamedAPIResource /** * Created by <NAME> on 02/07/2017. */ interface PokemonesFragmentView { fun showPokemonesList(pokemones: ArrayList<NamedAPIResource>) }
1
null
1
1
589127f5e8ddd4f120269cbba1dc6adb40e05c45
242
PokedexMVP
MIT License
browser-kotlin/src/jsMain/kotlin/web/gamepad/GamepadEvent.types.kt
karakum-team
393,199,102
false
{"Kotlin": 6328455}
// Automatically generated - do not modify! package web.gamepad import seskar.js.JsValue import web.events.EventType sealed external class GamepadEventTypes : GamepadEventTypes_deprecated { @JsValue("gamepadconnected") val GAMEPAD_CONNECTED: EventType<GamepadEvent> @JsValue("gamepaddisconnected") val GAMEPAD_DISCONNECTED: EventType<GamepadEvent> }
1
Kotlin
8
35
6c553c67c6cbf77a802c137d010b143895c7da60
375
types-kotlin
Apache License 2.0
src/client/kotlin/tech/thatgravyboat/skyblockapi/utils/codecs/CodecUtils.kt
SkyblockAPI
861,984,504
false
{"Kotlin": 186785, "Java": 20830}
package tech.thatgravyboat.skyblockapi.utils.codecs import com.mojang.serialization.Codec object CodecUtils { fun <T> set(codec: Codec<T>): Codec<MutableSet<T>> = codec.listOf().xmap({ it.toMutableSet() }, { it.toList() }) fun <T> list(codec: Codec<T>): Codec<MutableList<T>> = codec.listOf().xmap({ it.toMutableList() }, { it }) fun <A, B> map(key: Codec<A>, value: Codec<B>): Codec<MutableMap<A, B>> = Codec.unboundedMap(key, value).xmap({ it.toMutableMap() }, { it }) }
1
Kotlin
3
3
3733d501f27012048237e017e508f7a2ccfcbf58
515
SkyblockAPI
MIT License
mobile_application/app/src/main/java/com/example/aerosense_app/ui/SettingsScreen.kt
PatrickOrjieh
708,475,518
false
{"Kotlin": 173428, "Python": 109733, "HTML": 21740, "JavaScript": 4313, "CSS": 2358}
package com.example.aerosense_app.ui import android.util.Log import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue 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.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import com.example.aerosense_app.FirebaseViewModel import com.example.aerosense_app.R import com.example.aerosense_app.Screen import com.example.aerosense_app.SettingsRequest import com.example.aerosense_app.api.Repository import com.example.aerosense_app.ui.components.NavBar import com.example.aerosense_app.ui.components.SelectionDropDown //Github copilot used when writing some of this code @Composable fun Settings(navController: NavHostController, repository: Repository, firebaseModel: FirebaseViewModel){ var connected by remember { mutableStateOf(true) } var battery by remember { mutableIntStateOf(0) } var sound by remember { mutableStateOf(true) } var notificationFrequency by remember { mutableStateOf("") } val statuses = arrayOf("Only when critical", "Dangerous or below", "Moderate or below") battery = 65 var vibration: Boolean = true // Obtain the token from the ViewModel val token = firebaseModel.firebaseToken Log.d("Token", "Token: $token") // Check if the token is not null if (!token.isNullOrBlank()) { // Use the token to make the API call repository.fetchSettings(token, onSuccess = { settingsRequest -> if (settingsRequest != null) { sound = settingsRequest.sound } if (settingsRequest != null) { vibration = settingsRequest.vibration } if (settingsRequest != null) { notificationFrequency = settingsRequest.notificationFrequency } Log.d("Check settings data", "Settings data: $settingsRequest") }, onError = { errorMessage -> Log.d("Check Settings Data", "Error: $errorMessage") } ) } else { Log.d("SettingsError", "Error: Firebase token is null or blank") } NavBar(navController) Text( text = "Settings", color = Color(0xff1e1e1e), textAlign = TextAlign.Center, style = TextStyle( fontSize = 40.sp, fontWeight = FontWeight.Medium), modifier = Modifier.padding(top = 80.dp)) Image( painter = painterResource(id = R.drawable.separator), contentDescription = "Vector 38", modifier = Modifier .requiredWidth(width = 400.dp) .offset(y = -200.dp)) //Device Management Box( ) { Text( text = "Device Management", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(top = 160.dp) .padding(start = 5.dp) ) //Device connection status Row( modifier = Modifier .padding(top = 190.dp) .padding(start = 5.dp) ) { Box( modifier = Modifier // .offset(y = -115.dp, x = -80.dp) .requiredWidth(width = 180.dp) .requiredHeight(height = 40.dp) .clip(shape = RoundedCornerShape(6.dp)) .background(color = Color.White) .border( border = BorderStroke(4.dp, Color.LightGray), shape = RoundedCornerShape(6.dp) ) ) { Text( text = "Pair Status", textAlign = TextAlign.Center, color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier.padding(start = 35.dp, top = 5.dp) ) } if(connected) { Text( text = "Connected", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(top = 5.dp) .padding(start = 20.dp) ) Image( painter = painterResource(id = R.drawable.tick), contentDescription = "check", modifier = Modifier .requiredWidth(width = 45.dp) .requiredHeight(height = 45.dp) // .offset(y = 5.dp, x = 10.dp) .padding(start = 10.dp) ) } else{ Text( text = "Not Connected", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(top = 5.dp) .padding(start = 20.dp) ) } } //Battery Level Row( modifier = Modifier .padding(top = 245.dp) .padding(start = 5.dp) ) { Box( modifier = Modifier // .offset(y = -115.dp, x = -80.dp) .requiredWidth(width = 180.dp) .requiredHeight(height = 40.dp) .clip(shape = RoundedCornerShape(6.dp)) .background(color = Color.White) .border( border = BorderStroke(4.dp, Color.LightGray), shape = RoundedCornerShape(6.dp) ) ) { Text( text = "Battery Level", textAlign = TextAlign.Center, color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier.padding(start = 30.dp, top = 5.dp) ) } Text( text = "$battery%", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(top = 5.dp) .padding(start = 20.dp) ) } } Image( painter = painterResource(id = R.drawable.separator), contentDescription = "Vector 38", modifier = Modifier .requiredWidth(width = 400.dp) .offset(y = -45.dp) ) Box( modifier = Modifier.padding(top = 145.dp) ) { Text( text = "Notification Settings", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(top = 170.dp) .padding(start = 5.dp) ) //Device connection status Row( modifier = Modifier .padding(top = 220.dp) .padding(start = 5.dp) ) { Box( modifier = Modifier // .offset(y = -115.dp, x = -80.dp) .requiredWidth(width = 180.dp) .requiredHeight(height = 40.dp) .clip(shape = RoundedCornerShape(6.dp)) .background(color = Color.White) .border( border = BorderStroke(4.dp, Color.LightGray), shape = RoundedCornerShape(6.dp) ) ) { Text( text = "Sound", textAlign = TextAlign.Center, color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier.padding(start = 60.dp, top = 5.dp) ) } //radio buttons Box( modifier = Modifier .padding(start = 10.dp) .selectableGroup() ) { RadioButton( selected = sound, onClick = { sound = true val requestBody = SettingsRequest(notificationFrequency, vibration, sound) if (token != null) { repository.updateUserSettings(token, requestBody, onSuccess = { settingsResponse -> Log.d("Settings", "Success: $settingsResponse") }, onError = { errorMessage -> Log.d("Settings", "Error: $errorMessage") } ) } }, modifier = Modifier ) Text( text = "ON", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium), modifier = Modifier .padding(start = 40.dp) .padding(top = 10.dp)) RadioButton( selected = !sound, onClick = { sound = false val requestBody = SettingsRequest(notificationFrequency, vibration, sound) if (token != null) { repository.updateUserSettings(token, requestBody, onSuccess = { settingsResponse -> Log.d("Settings", "Success: $settingsResponse") }, onError = { errorMessage -> Log.d("Settings", "Error: $errorMessage") } ) } }, modifier = Modifier .padding(start = 70.dp)) Text( text = "OFF", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium), modifier = Modifier .padding(start = 110.dp) .padding(top = 10.dp)) } } Row( modifier = Modifier .padding(top = 280.dp) .padding(start = 5.dp) ) { Box( modifier = Modifier .padding(top = 20.dp) .requiredWidth(width = 180.dp) .requiredHeight(height = 40.dp) .clip(shape = RoundedCornerShape(6.dp)) .background(color = Color.White) .border( border = BorderStroke(4.dp, Color.LightGray), shape = RoundedCornerShape(6.dp) ) ) { Text( text = "Frequency", textAlign = TextAlign.Center, color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier.padding(start = 40.dp, top = 5.dp) ) } Log.d("Before passing to dropdown", "Notification frequency: $notificationFrequency") if(notificationFrequency != ""){ SelectionDropDown(statuses, notificationFrequency, sound, token, repository, onItemSelected = { notificationFrequency = it }) } } } Image( painter = painterResource(id = R.drawable.separator), contentDescription = "Vector 38", modifier = Modifier .requiredWidth(width = 400.dp) .padding(top = 355.dp) ) //Account Settings Box( modifier = Modifier.padding(top = 370.dp) ) { Text( text = "Account Settings", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(top = 160.dp) .padding(start = 5.dp) ) Row( modifier = Modifier .padding(top = 190.dp) .padding(start = 5.dp) ) { Box( modifier = Modifier .requiredWidth(width = 180.dp) .requiredHeight(height = 40.dp) .clip(shape = RoundedCornerShape(6.dp)) .background(color = Color.White) .border( border = BorderStroke(4.dp, Color.LightGray), shape = RoundedCornerShape(6.dp) ) ) { Text( text = "Change Password", textAlign = TextAlign.Center, color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(start = 7.dp, top = 5.dp) .clickable { navController.navigate(Screen.ResetPassword.name) } ) } Text( text = "**********", color = Color(0xff1e1e1e), style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(top = 5.dp) .padding(start = 20.dp) ) } Box( modifier = Modifier .padding(top = 245.dp) .padding(start = 10.dp) .requiredWidth(width = 120.dp) .requiredHeight(height = 50.dp) .clip(shape = RoundedCornerShape(23.59.dp)) .background(color = Color(0xfff24822))) { Text( text = "LOGOUT", textAlign = TextAlign.Center, color = Color.White, style = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Medium ), modifier = Modifier .padding(start = 20.dp, top = 10.dp) .clickable { navController.navigate(Screen.Login.name) } ) } } }
1
Kotlin
0
1
c369a08184a8d165eab0f843369255c814f48dbc
17,205
life-sync
MIT License
data/src/main/java/com/no1/taiwan/stationmusicfm/data/repositories/LastFmDataRepository.kt
SmashKs
168,842,876
false
null
/* * Copyright (C) 2019 The Smash Ks Open Project * * 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.no1.taiwan.stationmusicfm.data.repositories import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.AlbumDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.ArtistDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.ArtistPhotosDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.ArtistsDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.TagDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.TagsDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.TopAlbumDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.TrackDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.TracksDMapper import com.no1.taiwan.stationmusicfm.data.data.mappers.lastfm.TracksWithStreamableDMapper import com.no1.taiwan.stationmusicfm.data.delegates.DataMapperDigger import com.no1.taiwan.stationmusicfm.data.stores.DataStore import com.no1.taiwan.stationmusicfm.domain.parameters.Parameterable import com.no1.taiwan.stationmusicfm.domain.repositories.LastFmRepository import com.no1.taiwan.stationmusicfm.ext.exceptions.EmptyException import kotlinx.coroutines.async /** * The data repository for being responsible for selecting an appropriate data store to access * the data. * Also we need to do [async] & [await] one time for getting the data then transform and wrap to Domain layer. * * @property local from database/file/memory data store. * @property remote from remote sever/firebase. * @property diggerDelegate keeping all of the data mapper here. */ class LastFmDataRepository constructor( private val local: DataStore, private val remote: DataStore, diggerDelegate: DataMapperDigger ) : LastFmRepository, DataMapperDigger by diggerDelegate { private val albumMapper by lazy { digMapper(AlbumDMapper::class) } private val artistMapper by lazy { digMapper(ArtistDMapper::class) } private val artistsMapper by lazy { digMapper(ArtistsDMapper::class) } private val tagMapper by lazy { digMapper(TagDMapper::class) } private val tagsMapper by lazy { digMapper(TagsDMapper::class) } private val topAlbumMapper by lazy { digMapper(TopAlbumDMapper::class) } private val trackMapper by lazy { digMapper(TrackDMapper::class) } private val tracksMapper by lazy { digMapper(TracksDMapper::class) } private val tracksWithStreamableMapper by lazy { digMapper(TracksWithStreamableDMapper::class) } private val artistPhotosMapper by lazy { digMapper(ArtistPhotosDMapper::class) } override suspend fun fetchAlbum(parameters: Parameterable) = remote.getAlbumInfo(parameters).album?.run(albumMapper::toModelFrom) ?: throw EmptyException() override suspend fun fetchArtist(parameters: Parameterable) = remote.getArtistInfo(parameters).artist?.run(artistMapper::toModelFrom) ?: throw EmptyException() override suspend fun fetchArtistTopAlbum(parameters: Parameterable) = remote.getArtistTopAlbum(parameters).topAlbums.run(topAlbumMapper::toModelFrom) override suspend fun fetchArtistTopTrack(parameters: Parameterable) = remote.getArtistTopTrack(parameters).topTracks.run(tracksWithStreamableMapper::toModelFrom) override suspend fun fetchSimilarArtistInfo(parameters: Parameterable) = remote.getSimilarArtistInfo(parameters).similarArtist.run(artistsMapper::toModelFrom) override suspend fun fetchArtistPhotoInfo(parameters: Parameterable) = remote.getArtistPhotosInfo(parameters).run(artistPhotosMapper::toModelFrom) override suspend fun fetchTrack(parameters: Parameterable) = remote.getTrackInfo(parameters).track?.run(trackMapper::toModelFrom) ?: throw EmptyException() override suspend fun fetchSimilarTrackInfo(parameters: Parameterable) = remote.getSimilarTrackInfo(parameters).similarTracks.run(tracksMapper::toModelFrom) override suspend fun fetchChartTopTrack(parameters: Parameterable) = remote.getChartTopTrack(parameters).track.run(tracksMapper::toModelFrom) override suspend fun fetchChartTopArtist(parameters: Parameterable) = remote.getChartTopArtist(parameters).artists.run(artistsMapper::toModelFrom) override suspend fun fetchChartTopTag(parameters: Parameterable) = remote.getChartTopTag(parameters).tag.run(tagsMapper::toModelFrom) override suspend fun fetchTag(parameters: Parameterable) = remote.getTagInfo(parameters).tag.run(tagMapper::toModelFrom) override suspend fun fetchTagTopAlbum(parameters: Parameterable) = remote.getTagTopAlbum(parameters).albums.run(topAlbumMapper::toModelFrom) override suspend fun fetchTagTopArtist(parameters: Parameterable) = remote.getTagTopArtist(parameters).topArtists.run(artistsMapper::toModelFrom) override suspend fun fetchTagTopTrack(parameters: Parameterable) = remote.getTagTopTrack(parameters).track.run(tracksMapper::toModelFrom) }
0
Kotlin
1
5
696fadc54bc30fe72f9115bdec2dacdac8cd4394
6,111
StationMusicFM
MIT License
sticker/src/main/java/com/xiaopo/flying/sticker/StickerViewModel.kt
Ruin0x11
325,747,923
false
null
package com.xiaopo.flying.sticker import android.annotation.SuppressLint import android.graphics.Matrix import android.graphics.PointF import android.graphics.RectF import android.os.SystemClock import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import androidx.annotation.IntDef import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.xiaopo.flying.sticker.StickerView.Flip import com.xiaopo.flying.sticker.StickerView.OnStickerAreaTouchListener import timber.log.Timber import kotlin.math.* open class StickerViewModel : ViewModel() { var isLocked: MutableLiveData<Boolean> = MutableLiveData(false) var mustLockToPan: MutableLiveData<Boolean> = MutableLiveData(false) var isCropActive: MutableLiveData<Boolean> = MutableLiveData(false) var rotationEnabled: MutableLiveData<Boolean> = MutableLiveData(false) var constrained: MutableLiveData<Boolean> = MutableLiveData(false) var bringToFrontCurrentSticker = MutableLiveData(true) var canvasMatrix: CustomMutableLiveData<ObservableMatrix> = CustomMutableLiveData(ObservableMatrix()) var stickers: MutableLiveData<ArrayList<Sticker>> = MutableLiveData(ArrayList()) var icons: MutableLiveData<ArrayList<BitmapStickerIcon>> = MutableLiveData(ArrayList()) var activeIcons: MutableLiveData<List<BitmapStickerIcon>> = MutableLiveData(ArrayList(4)) var handlingSticker: MutableLiveData<Sticker?> = MutableLiveData(null) var gestureListener: MutableLiveData<GestureListener> = MutableLiveData() init { gestureListener.value = GestureListener(this) } var currentFileName: String? = null private val onStickerAreaTouchListener: OnStickerAreaTouchListener? = null lateinit var stickerOperationListener: StickerView.OnStickerOperationListener private val stickerWorldMatrix = Matrix() private val stickerScreenMatrix = Matrix() private val moveMatrix = Matrix() private val point = FloatArray(2) private val currentCenterPoint = PointF() private val tmp = FloatArray(2) private var pointerId = -1 private var midPoint = PointF() private val DEFAULT_MIN_CLICK_DELAY_TIME = 200 private var minClickDelayTime = DEFAULT_MIN_CLICK_DELAY_TIME //the first point down position private var downX = 0f private var downY = 0f private var downXScaled = 0f private var downYScaled = 0f private var oldDistance = 0f private var oldRotation = 0f private var previousRotation = 0f private var lastClickTime: Long = 0 @IntDef( ActionMode.NONE, ActionMode.DRAG, ActionMode.ZOOM_WITH_TWO_FINGER, ActionMode.ICON, ActionMode.CLICK, ActionMode.CANVAS_DRAG, ActionMode.CANVAS_ZOOM_WITH_TWO_FINGER ) @kotlin.annotation.Retention(AnnotationRetention.SOURCE) annotation class ActionMode { companion object { const val NONE = 0 const val DRAG = 1 const val ZOOM_WITH_TWO_FINGER = 2 const val ICON = 3 const val CLICK = 4 const val CANVAS_DRAG = 5 const val CANVAS_ZOOM_WITH_TWO_FINGER = 6 } } var currentMode = MutableLiveData(ActionMode.NONE) var currentIcon: MutableLiveData<BitmapStickerIcon?> = MutableLiveData(null) @SuppressLint("ClickableViewAccessibility") val onTouchListener = View.OnTouchListener { v, event -> onTouchEvent(v as StickerView, event) } fun addSticker(sticker: Sticker) { addSticker(sticker, Sticker.Position.CENTER) } fun addSticker(sticker: Sticker, position: Int) { sticker.setCanvasMatrix(canvasMatrix.value!!.getMatrix()) sticker.recalcFinalMatrix() stickers.value!!.add(sticker) handlingSticker.value = sticker stickerOperationListener.onStickerAdded(sticker, position) } fun resetView() { canvasMatrix.value!!.setMatrix(Matrix()) updateCanvasMatrix() } fun updateCanvasMatrix() { for (i in stickers.value!!.indices) { val sticker: Sticker = stickers.value!![i] sticker.setCanvasMatrix(canvasMatrix.value!!.getMatrix()) } stickerOperationListener.onInvalidateView() } fun removeCurrentSticker(): Boolean { if (handlingSticker.value != null) { return removeSticker(handlingSticker.value!!) } else { return false } } fun removeSticker(sticker: Sticker): Boolean { if (stickers.value!!.contains(sticker)) { stickers.value!!.remove(sticker) stickerOperationListener.onStickerDeleted(sticker) if (handlingSticker.value == sticker) { handlingSticker.value = null } stickerOperationListener.onInvalidateView() return true } else { Timber.d("remove: the sticker is not in this StickerView") return false } } fun removeAllStickers() { stickers.value?.clear() if (handlingSticker.value != null) { handlingSticker.value!!.release() handlingSticker.value = null } currentIcon.value = null stickerOperationListener.onInvalidateView() } fun resetCurrentStickerCropping() { handlingSticker.value?.let(this::resetStickerCropping) } private fun resetStickerCropping(sticker: Sticker) { if (isLocked.value != true) { sticker.setCroppedBounds(RectF(sticker.getRealBounds())) stickerOperationListener.onInvalidateView() } } fun resetCurrentStickerZoom() { handlingSticker.value?.let(this::resetStickerZoom) } private fun resetStickerZoom(sticker: Sticker) { if (isLocked.value != true) { val temp2 = floatArrayOf(sticker.centerPoint.x, sticker.centerPoint.y) sticker.matrix.mapPoints(temp2) sticker.matrix.reset() sticker.matrix.postTranslate( temp2[0] - sticker.width / 2f, temp2[1] - sticker.height / 2f ) sticker.recalcFinalMatrix() stickerOperationListener.onInvalidateView() } } fun resetCurrentStickerRotation() { handlingSticker.value?.let(this::resetStickerRotation) } private fun resetStickerRotation(sticker: Sticker) { val rotation = if (sticker.isFlippedVertically) sticker.currentAngle; else -sticker.currentAngle sticker.matrix.postRotate(rotation, sticker.mappedCenterPoint.x, sticker.mappedCenterPoint.y) stickerOperationListener.onInvalidateView() } private fun handleCanvasMotion(view: StickerView, event: MotionEvent): Boolean { handlingSticker.value = null currentIcon.value = null when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { if (!onTouchDownCanvas(event)) { return false } pointerId = event.getPointerId(0) } MotionEvent.ACTION_POINTER_DOWN -> { for (i in 0 until event.pointerCount) { if (event.getPointerId(i) != pointerId) { calculateDown(event) pointerId = event.getPointerId(i) break } } oldDistance = StickerMath.calculateDistance(event) oldRotation = StickerMath.calculateRotation(event) midPoint = calculateMidPoint(event) stickerWorldMatrix.set(canvasMatrix.value!!.getMatrix()) currentMode.value = ActionMode.CANVAS_ZOOM_WITH_TWO_FINGER } MotionEvent.ACTION_MOVE -> { for (i in 0 until event.pointerCount) { if (event.getPointerId(i) != pointerId) { calculateDown(event) pointerId = event.getPointerId(i) break } } handleMoveActionCanvas(event) } MotionEvent.ACTION_UP -> { onTouchUpCanvas(event) } MotionEvent.ACTION_POINTER_UP -> { if (currentMode.value == ActionMode.CANVAS_ZOOM_WITH_TWO_FINGER) { pointerId = -1 if (!onTouchDownCanvas(event)) { return false } } else { onTouchUpCanvas(event) } } } stickerOperationListener.onInvalidateView() return true } /** * @param event MotionEvent received from [)][.onTouchEvent] */ protected fun onTouchDownCanvas(event: MotionEvent): Boolean { currentMode.value = ActionMode.CANVAS_DRAG calculateDown(event) midPoint = calculateMidPoint() oldDistance = StickerMath.calculateDistance(midPoint.x, midPoint.y, downX, downY) oldRotation = StickerMath.calculateRotation(midPoint.x, midPoint.y, downX, downY) stickerWorldMatrix.set(canvasMatrix.value!!.getMatrix()) return true } protected fun onTouchUpCanvas(event: MotionEvent) { val currentTime = SystemClock.uptimeMillis() pointerId = -1 currentMode.value = ActionMode.NONE lastClickTime = currentTime } protected fun handleMoveActionCanvas(event: MotionEvent) { when (currentMode.value) { ActionMode.CANVAS_DRAG -> { moveMatrix.set(stickerWorldMatrix) moveMatrix.postTranslate(event.x - downX, event.y - downY) canvasMatrix.value!!.setMatrix(moveMatrix) updateCanvasMatrix() } ActionMode.CANVAS_ZOOM_WITH_TWO_FINGER -> { val newDistance = StickerMath.calculateDistance(event) //float newRotation = StickerMath.calculateRotation(event); moveMatrix.set(stickerWorldMatrix) moveMatrix.postScale( newDistance / oldDistance, newDistance / oldDistance, midPoint.x, midPoint.y ) //moveMatrix.postRotate(newRotation - oldRotation, midPoint.x, midPoint.y); canvasMatrix.value!!.setMatrix(moveMatrix) updateCanvasMatrix() } } } private fun isMovingCanvas(): Boolean { return currentMode.value == ActionMode.CANVAS_DRAG || currentMode.value == ActionMode.CANVAS_ZOOM_WITH_TWO_FINGER } @SuppressLint("ClickableViewAccessibility") fun onTouchEvent(view: StickerView, event: MotionEvent): Boolean { if (isLocked.value == true || isMovingCanvas()) { return handleCanvasMotion(view, event) } when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { // Timber.d("MotionEvent.ACTION_DOWN event__: %s", event.toString()); if (onStickerAreaTouchListener != null) { onStickerAreaTouchListener.onStickerAreaTouch() } if (!onTouchDown(view, event)) { return if (mustLockToPan.value != true) { handleCanvasMotion(view, event) } else false } } MotionEvent.ACTION_POINTER_DOWN -> { } MotionEvent.ACTION_MOVE -> { handleMoveAction(view, event) } MotionEvent.ACTION_UP -> onTouchUp(view, event) MotionEvent.ACTION_POINTER_UP -> if (currentMode.value == ActionMode.ZOOM_WITH_TWO_FINGER && handlingSticker.value != null) { stickerOperationListener.onStickerZoomFinished(handlingSticker.value!!) if (!onTouchDown(view, event)) { return if (mustLockToPan.value != true) { handleCanvasMotion(view, event) } else false } currentMode.value = ActionMode.DRAG } else { currentMode.value = ActionMode.NONE } } stickerOperationListener.onInvalidateView() return true } /** * @param event MotionEvent received from [)][.onTouchEvent] */ protected fun onTouchDown(view: StickerView, event: MotionEvent): Boolean { currentMode.value = ActionMode.DRAG calculateDown(event) midPoint = StickerMath.calculateMidPoint(handlingSticker.value) oldDistance = StickerMath.calculateDistance(midPoint.x, midPoint.y, downX, downY) oldRotation = StickerMath.calculateRotation(midPoint.x, midPoint.y, downX, downY) currentIcon.value = findCurrentIconTouched() // HACK if application logic is really meant to be handled in the ViewModel, how do you // communicate from the View to the ViewModel? There can't be a GestureDetector in the // ViewModel because it retains the activity's context. view.detectIconGesture(event) if (currentIcon.value != null) { currentMode.value = ActionMode.ICON currentIcon.value!!.onActionDown(view, this, event) // Timber.d("current_icon: %s", currentIcon.getDrawableName()); } else { handlingSticker.value = findHandlingSticker() } handlingSticker.value?.let { stickerWorldMatrix.set(it.getMatrix()) stickerScreenMatrix.set(it.getFinalMatrix()) if (bringToFrontCurrentSticker.value == true) { stickers.value!!.remove(it) stickers.value!!.add(it) } stickerOperationListener.onStickerTouchedDown(it) } return currentIcon.value != null || handlingSticker.value != null } protected fun onTouchUp(view: StickerView, event: MotionEvent) { val touchSlop = ViewConfiguration.get(view.context).scaledTouchSlop val currentTime = SystemClock.uptimeMillis() if (currentMode.value == ActionMode.ICON && currentIcon.value != null && handlingSticker.value != null) { currentIcon.value!!.onActionUp(view, this, event) // Timber.d("current_icon: %s", currentIcon.getDrawableName()); } if (currentMode.value == ActionMode.DRAG && Math.abs(event.x - downX) < touchSlop && Math.abs( event.y - downY ) < touchSlop && handlingSticker.value != null ) { currentMode.value = ActionMode.CLICK stickerOperationListener.onStickerClicked(handlingSticker.value!!) if (currentTime - lastClickTime < minClickDelayTime) { stickerOperationListener.onStickerDoubleTapped(handlingSticker.value!!) } } if (currentMode.value == ActionMode.DRAG && handlingSticker.value != null) { stickerOperationListener.onStickerDragFinished(handlingSticker.value!!) } currentMode.value = ActionMode.NONE lastClickTime = currentTime } private fun screenToWorld(vx: Float, vy: Float): PointF { val vec = floatArrayOf(vx, vy) val a = Matrix() canvasMatrix.value!!.invert(a) a.mapVectors(vec) return PointF(vec[0], vec[1]) } protected fun handleMoveAction(view: StickerView, event: MotionEvent) { when (currentMode.value) { ActionMode.NONE, ActionMode.CLICK -> { } ActionMode.DRAG -> if (handlingSticker.value != null) { moveMatrix.set(stickerWorldMatrix) val vec = screenToWorld(event.x - downX, event.y - downY) moveMatrix.postTranslate(vec.x, vec.y) handlingSticker.value!!.setMatrix(moveMatrix) if (constrained.value == true) { constrainSticker(view, handlingSticker.value!!) } stickerOperationListener.onStickerMoved(handlingSticker.value!!) } ActionMode.ZOOM_WITH_TWO_FINGER -> if (handlingSticker.value != null) { val newDistance = StickerMath.calculateDistanceScaled(event, canvasMatrix.value!!.getMatrix()) val newRotation = StickerMath.calculateRotation(event) moveMatrix.set(stickerWorldMatrix) moveMatrix.postScale( newDistance / oldDistance, newDistance / oldDistance, midPoint.x, midPoint.y ) if (rotationEnabled.value == true) { moveMatrix.postRotate(newRotation - oldRotation, midPoint.x, midPoint.y) } handlingSticker.value!!.setMatrix(moveMatrix) } ActionMode.ICON -> if (handlingSticker.value != null && currentIcon.value != null) { currentIcon.value!!.onActionMove(view, this, event) } } } fun zoomAndRotateCurrentSticker(event: MotionEvent) { zoomAndRotateSticker(handlingSticker.value, event) } fun zoomAndRotateSticker(sticker: Sticker?, event: MotionEvent) { if (sticker != null) { val temp = floatArrayOf(event.x, event.y) val a = Matrix() canvasMatrix.value!!.invert(a) a.mapPoints(temp) val temp2 = floatArrayOf(sticker.centerPointCropped.x, sticker.centerPointCropped.y) stickerWorldMatrix.mapPoints(temp2) //canvasMatrix.mapPoints(temp2); midPoint.x = temp2[0] midPoint.y = temp2[1] val oldDistance = StickerMath.calculateDistance( midPoint.x, midPoint.y, downXScaled, downYScaled ) val newDistance = StickerMath.calculateDistance( midPoint.x, midPoint.y, temp[0], temp[1] ) val newRotation = StickerMath.calculateRotation( midPoint.x, midPoint.y, temp[0], temp[1] ) moveMatrix.set(stickerWorldMatrix) moveMatrix.postScale( newDistance / oldDistance, newDistance / oldDistance, midPoint.x, midPoint.y ) if (rotationEnabled.value == true) { moveMatrix.postRotate(newRotation - oldRotation, midPoint.x, midPoint.y) } handlingSticker.value!!.setMatrix(moveMatrix) } } protected fun constrainSticker(view: StickerView, sticker: Sticker) { var moveX = 0f var moveY = 0f val width: Int = view.getWidth() val height: Int = view.getHeight() sticker.getMappedCenterPoint(currentCenterPoint, point, tmp) if (currentCenterPoint.x < 0) { moveX = -currentCenterPoint.x } if (currentCenterPoint.x > width) { moveX = width - currentCenterPoint.x } if (currentCenterPoint.y < 0) { moveY = -currentCenterPoint.y } if (currentCenterPoint.y > height) { moveY = height - currentCenterPoint.y } sticker.matrix.postTranslate(moveX, moveY) } fun cropCurrentSticker(event: MotionEvent, gravity: Int) { cropSticker(handlingSticker.value, event, gravity) } private fun convertFlippedGravity(sticker: Sticker, gravity: Int): Int = if (sticker.isFlippedHorizontally) { if (sticker.isFlippedVertically) { when (gravity) { BitmapStickerIcon.LEFT_TOP -> BitmapStickerIcon.RIGHT_BOTTOM BitmapStickerIcon.LEFT_BOTTOM -> BitmapStickerIcon.RIGHT_TOP BitmapStickerIcon.RIGHT_TOP -> BitmapStickerIcon.LEFT_BOTTOM BitmapStickerIcon.RIGHT_BOTTOM -> BitmapStickerIcon.LEFT_TOP else -> gravity } } else { when (gravity) { BitmapStickerIcon.LEFT_TOP -> BitmapStickerIcon.RIGHT_TOP BitmapStickerIcon.LEFT_BOTTOM -> BitmapStickerIcon.RIGHT_BOTTOM BitmapStickerIcon.RIGHT_TOP -> BitmapStickerIcon.LEFT_TOP BitmapStickerIcon.RIGHT_BOTTOM -> BitmapStickerIcon.LEFT_BOTTOM else -> gravity } } } else { if (sticker.isFlippedVertically) { when (gravity) { BitmapStickerIcon.LEFT_TOP -> BitmapStickerIcon.LEFT_BOTTOM BitmapStickerIcon.LEFT_BOTTOM -> BitmapStickerIcon.LEFT_TOP BitmapStickerIcon.RIGHT_TOP -> BitmapStickerIcon.RIGHT_BOTTOM BitmapStickerIcon.RIGHT_BOTTOM -> BitmapStickerIcon.RIGHT_TOP else -> gravity } } else { gravity } } protected fun cropSticker(sticker: Sticker?, event: MotionEvent, gravity: Int) { if (sticker == null) { return } val dx = event.x val dy = event.y val inv = Matrix() sticker.canvasMatrix.invert(inv) val inv2 = Matrix() sticker.matrix.invert(inv2) val temp = floatArrayOf(dx, dy) inv.mapPoints(temp) inv2.mapPoints(temp) val cropped = RectF(sticker.getCroppedBounds()) val px = temp[0].toInt() val py = temp[1].toInt() val flippedGravity = convertFlippedGravity(sticker, gravity) when (flippedGravity) { BitmapStickerIcon.LEFT_TOP -> { cropped.left = Math.min(px.toFloat(), cropped.right) cropped.top = Math.min(py.toFloat(), cropped.bottom) } BitmapStickerIcon.RIGHT_TOP -> { cropped.right = Math.max(px.toFloat(), cropped.left) cropped.top = Math.min(py.toFloat(), cropped.bottom) } BitmapStickerIcon.LEFT_BOTTOM -> { cropped.left = Math.min(px.toFloat(), cropped.right) cropped.bottom = Math.max(py.toFloat(), cropped.top) } BitmapStickerIcon.RIGHT_BOTTOM -> { cropped.right = Math.max(px.toFloat(), cropped.left) cropped.bottom = Math.max(py.toFloat(), cropped.top) } } sticker.setCroppedBounds(cropped) } fun duplicateCurrentSticker() { handlingSticker.value?.let { duplicateSticker(it) } } fun duplicateSticker(sticker: Sticker) { val newSticker = DrawableSticker(sticker as DrawableSticker) addSticker(newSticker) } protected fun findCurrentIconTouched(): BitmapStickerIcon? { for (icon in activeIcons.value!!) { val x: Float = icon.x + icon.iconRadius - downXScaled val y: Float = icon.y + icon.iconRadius - downYScaled val distancePow2 = x * x + y * y if (distancePow2 <= ((icon.iconRadius + icon.iconRadius) * 1.2f.toDouble()).pow(2.0) ) { return icon } } return null } /** * find the touched Sticker */ protected fun findHandlingSticker(): Sticker? { stickers.value?.let { for (i in it.indices.reversed()) { if (isInStickerAreaCropped(it[i], downX, downY)) { return it[i] } } } return null } protected fun isInStickerArea(sticker: Sticker, downX: Float, downY: Float): Boolean { tmp[0] = downX tmp[1] = downY return sticker.contains(tmp) } protected fun isInStickerAreaCropped(sticker: Sticker, downX: Float, downY: Float): Boolean { tmp[0] = downX tmp[1] = downY return sticker.containsCropped(tmp) } protected fun calculateMidPoint(event: MotionEvent?): PointF { if (event == null || event.pointerCount < 2) { midPoint.set(0f, 0f) return midPoint } val pts = floatArrayOf(event.getX(0), event.getY(0), event.getX(1), event.getY(1)) //canvasMatrix.mapPoints(pts); val x = (pts[0] + pts[2]) / 2 val y = (pts[1] + pts[3]) / 2 midPoint.set(x, y) return midPoint } protected fun calculateDown(event: MotionEvent?) { if (event == null || event.pointerCount < 1) { downX = 0f downY = 0f downXScaled = 0f downYScaled = 0f return } val pts = floatArrayOf(event.getX(0), event.getY(0)) downX = pts[0] downY = pts[1] val a = Matrix() canvasMatrix.value!!.invert(a) a.mapPoints(pts) downXScaled = pts[0] downYScaled = pts[1] } protected fun calculateMidPoint(): PointF { if (handlingSticker.value == null) { midPoint.set(0f, 0f) return midPoint } handlingSticker.value!!.getMappedCenterPoint(midPoint, point, tmp) return midPoint } fun flipCurrentSticker(direction: Int) { handlingSticker.value?.let { flip(it, direction) } } private fun flip(sticker: Sticker, @Flip direction: Int) { sticker.getCenterPoint(midPoint) if (direction and StickerView.FLIP_HORIZONTALLY > 0) { sticker.matrix.preScale(-1f, 1f, midPoint.x, midPoint.y) sticker.isFlippedHorizontally = !sticker.isFlippedHorizontally } if (direction and StickerView.FLIP_VERTICALLY > 0) { sticker.matrix.preScale(1f, -1f, midPoint.x, midPoint.y) sticker.isFlippedVertically = !sticker.isFlippedVertically } sticker.recalcFinalMatrix() stickerOperationListener.onStickerFlipped(sticker) } fun showCurrentSticker() { handlingSticker.value?.setVisible(true) } fun hideCurrentSticker() { handlingSticker.value?.setVisible(false) } }
4
Kotlin
1
56
3cdd73ff8596cf381f0abf001ec43e9dfbbb9fa2
26,337
DroidRef
MIT License
app/src/main/java/com/bksahabrothersfsm/features/stockAddCurrentStock/api/ShopAddStockProvider.kt
DebashisINT
613,436,962
false
null
package com.bksahabrothersfsm.features.stockAddCurrentStock.api import com.bksahabrothersfsm.features.location.shopRevisitStatus.ShopRevisitStatusApi import com.bksahabrothersfsm.features.location.shopRevisitStatus.ShopRevisitStatusRepository object ShopAddStockProvider { fun provideShopAddStockRepository(): ShopAddStockRepository { return ShopAddStockRepository(ShopAddStockApi.create()) } }
0
Kotlin
0
0
e5cb08722e71a7cdbe27012cf6dc61f0e783559c
412
BKSAHABROTHERS
Apache License 2.0
fingerprint/src/main/java/com/fingerprintjs/android/fingerprint/tools/IdentificationVersionExtensions.kt
fingerprintjs
305,740,280
false
{"Kotlin": 422778}
package com.fingerprintjs.android.fingerprint.tools import android.annotation.SuppressLint import com.fingerprintjs.android.fingerprint.Fingerprinter @SuppressLint("DiscouragedApi") internal fun Fingerprinter.Version.inRange( added: Fingerprinter.Version, removed: Fingerprinter.Version?, ): Boolean { return this.intValue >= added.intValue && (if (removed != null) this.intValue < removed.intValue else true) }
4
Kotlin
76
534
a33e213daa8534a2d2d1e85636f6aba635e75dc1
438
fingerprintjs-android
MIT License
src/main/kotlin/github/samyycx/fisherman/modules/gameconfig/fish/FishConfigParser.kt
samyycX
742,795,853
false
{"Kotlin": 42404, "Java": 351}
package github.samyycx.fisherman.modules.gameconfig.fish import github.samyycx.fisherman.modules.config.ConfigManager import github.samyycx.fisherman.modules.gameconfig.fish.attribute.Attribute import github.samyycx.fisherman.modules.gameconfig.fish.attribute.AttributeParser import github.samyycx.fisherman.modules.gameconfig.fish.basic.FishBaseParser import github.samyycx.fisherman.modules.gameconfig.fish.event.FishEventsParser import github.samyycx.fisherman.modules.lang.OtherUtils.maskObject import org.bukkit.Bukkit import org.bukkit.configuration.ConfigurationSection import taboolib.library.reflex.Reflex.Companion.unsafeInstance import taboolib.module.lang.Level import taboolib.platform.util.sendLang object FishConfigParser { /** * section : 配置文件的section * map : 已经解析好的fishconfig,用于处理层级关系 * * 返回值: * Pair的第一个值只有找不到父模板的时候才不是null,值为父节点的id * Pair的第二个值是解析的结果,如果找不到父模板就是null */ fun parseFromSection(section: ConfigurationSection, map: MutableMap<String, FishConfig>): Pair<String?, FishConfig?> { var fishConfig = FishConfig() if (section.contains("template")) { val requiredTemplate = section.getString("template") if (requiredTemplate !in map) { return requiredTemplate to null } else { fishConfig = map[requiredTemplate]!!.copy() } } fishConfig.id = section.name section.getConfigurationSection("base").let { val base = it?.let { FishBaseParser.parseSection(it) } fishConfig.base = maskObject(fishConfig.base, base) if (fishConfig.base == null) { Bukkit.getConsoleSender().sendLang(Level.ERROR, "Console.Error.Fish-Config-Field-NotFound", section.name, "base" ) return null to null } } section.getConfigurationSection("cooked").let { val cooked = it?.let { FishBaseParser.parseSection(it) } fishConfig.cooked = maskObject(fishConfig.cooked, cooked) fishConfig.cooked = maskObject(fishConfig.base, fishConfig.cooked) } section.getConfigurationSection("attribute")?.let { val newAttributeMap = mutableMapOf<String, Attribute>() for (attributeId in it.getKeys(false)) { var attribute = AttributeParser.parseSection(it.getConfigurationSection(attributeId)!!) val defaultAttribute = ConfigManager.default.getConfigurationSection("FishAttributes") ?.let { it1 -> AttributeParser.parseSection(it1) } attribute = maskObject(defaultAttribute, attribute)!! newAttributeMap[attributeId] = if (fishConfig.attributes != null) { maskObject(fishConfig.attributes!![attributeId], attribute)!! } else { attribute } } fishConfig.attributes = newAttributeMap } section.getConfigurationSection("value")?.let { val newValueMap = mutableMapOf<String, List<String>>() for (service in it.getKeys(false)) { newValueMap[service] = it.getStringList(service) } if (fishConfig.value != null ) { fishConfig.value = (fishConfig.value!! + newValueMap) as MutableMap } else { fishConfig.value = newValueMap } } section.getConfigurationSection("event")?.let { val events = FishEventsParser.parseSection(it) fishConfig.events = maskObject(fishConfig.events, events) } return null to fishConfig } /** * new对象的属性 遮蔽 original对象的属性 * new和original应该为同类 * 特别的,如果这个类中的属性有List,则判断List不为空的时候才遮蔽 */ }
0
Kotlin
0
0
8336b73de9e8461612791651aec6ef9f246e92ac
3,883
Fisherman
MIT License
androidApp/src/androidMain/kotlin/com/mbakgun/mj/di/ViewModelModule.kt
mbakgun
629,040,507
false
{"Kotlin": 62863, "HTML": 3059, "Ruby": 2392, "Swift": 771, "JavaScript": 370, "Shell": 228}
package com.mbakgun.mj.di import org.koin.core.module.dsl.viewModelOf import org.koin.dsl.module import ui.MjImagesViewModel val viewModelModule = module { viewModelOf(::MjImagesViewModel) }
1
Kotlin
23
246
a717059df325cdc53b87f2c1789bcf099795ff1a
197
midjourney-images-compose-multiplatform
MIT License
K_league_info/app/src/main/java/com/example/k_league_info/ui/score/ScoreAdapter.kt
dawit95
286,927,098
false
{"Markdown": 1, "Gradle": 3, "Java Properties": 4, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "JSON": 124, "Kotlin": 22, "XML": 52, "Java": 1, "Text": 5, "Python": 8}
package com.example.k_league_info.ui.score import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.k_league_info.R import com.example.k_league_info.ScoredetailActivity import java.util.* class ScoreAdapter(val context: Context, val scheduleList: ArrayList<ScoreBoard>) : RecyclerView.Adapter<ScoreAdapter.Holder>() { //위젯들(ImageView, TextView)을 변수로 가져옴 inner class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) { val homeImage = itemView.findViewById<ImageView>(R.id.homemark) val awayImage = itemView.findViewById<ImageView>(R.id.awaymark) val homeName = itemView.findViewById<TextView>(R.id.homename) val awayName = itemView.findViewById<TextView>(R.id.awayname) val Score = itemView.findViewById<TextView>(R.id.score) //이제 가져온 위젯들(ImageView, TextView)의 소스, text를 크롤링해온 데이터로 바꿔줌 fun bind(scoreBoard: ScoreBoard, context: Context) { // 홈팀 동기화 homeName.text = scoreBoard.hometeam Score.text = scoreBoard.score var homeResName = "@drawable/" when (scoreBoard.hometeam) { "서울" -> homeResName += "seoul" "부산" -> homeResName += "busan" "광주" -> homeResName += "gwangju" "대구" -> homeResName += "daegu" "전북" -> homeResName += "jeonbuk" "전남" -> homeResName += "jeonnam" "경남" -> homeResName += "gyeonnam" "강원" -> homeResName += "gangwon" "울산" -> homeResName += "ulsan" "포항" -> homeResName += "pohang" "상주" -> homeResName += "sangju" "성남" -> homeResName += "seongnam" "제주" -> homeResName += "jeju" "수원" -> homeResName += "suwon" "인천" -> homeResName += "incheon" } val homeResId = homeImage.resources.getIdentifier(homeResName, "drawable", context.packageName) homeImage.setImageResource(homeResId) //어웨이팀 동기화 awayName.text = scoreBoard.awayteam var awayResName = "@drawable/" when (scoreBoard.awayteam) { "서울" -> awayResName += "seoul" "부산" -> awayResName += "busan" "광주" -> awayResName += "gwangju" "대구" -> awayResName += "daegu" "전북" -> awayResName += "jeonbuk" "전남" -> awayResName += "jeonnam" "강원" -> awayResName += "gangwon" "울산" -> awayResName += "ulsan" "포항" -> awayResName += "pohang" "상주" -> awayResName += "sangju" "성남" -> awayResName += "seongnam" "제주" -> awayResName += "jeju" "수원" -> awayResName += "suwon" "인천" -> awayResName += "incheon" } val awayResId = awayImage.resources.getIdentifier(awayResName, "drawable", context.packageName) awayImage.setImageResource(awayResId) itemView.setOnClickListener { val intent = Intent(context, ScoredetailActivity::class.java) intent.putExtra("homeTeam", scoreBoard.hometeam) intent.putExtra("awayTeam", scoreBoard.awayteam) intent.putExtra("score", scoreBoard.score) intent.putExtra("date", scoreBoard.date) intent.putExtra("scoreDetail", scoreBoard.scoreDetail) context.startActivity(intent) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val view = LayoutInflater.from(context).inflate(R.layout.item_score, parent, false) return Holder(view) } override fun getItemCount(): Int { return scheduleList.size } override fun onBindViewHolder(holder: Holder, position: Int) { holder.bind(scheduleList[position], context) } }
1
Kotlin
4
0
942c9a05d9486b88da88e6d10bcbd98f845cef22
4,179
K_League_info
The Unlicense
core/src/commonMain/kotlin/com/ramitsuri/notificationjournal/core/model/template/JournalEntryTemplate.kt
ramitsuri
667,037,607
false
{"Kotlin": 292214, "Shell": 8329, "Python": 3405, "HTML": 1499, "JavaScript": 1016}
package com.ramitsuri.notificationjournal.core.model.template import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import java.util.UUID @Entity(tableName = "JournalEntryTemplate") @Serializable data class JournalEntryTemplate( @PrimaryKey @ColumnInfo(name = "id") @SerialName("id") val id: String = UUID.randomUUID().toString(), @ColumnInfo(name = "text") @SerialName("text") val text: String, @ColumnInfo(name = "tag") @SerialName("tag") val tag: String, )
0
Kotlin
0
0
54b17d4e73b09617c2ce4fd8eb78fd7d8471a88d
623
notification-journal
MIT License
src/main/java/com/dzen/campfire/server/tables/TTranslatesHistory.kt
timas130
443,572,543
true
{"Kotlin": 1072092}
package com.dzen.campfire.server.tables object TTranslatesHistory { val NAME = "translates_history" val id = "id" val language_id = "language_id" val language_id_from = "language_id_from" val translate_key = "translate_key" val old_text = "old_text" val new_text = "new_text" val history_type = "history_type" val history_creator_id = "history_creator_id" val date_history_created = "date_history_created" val project_key = "project_key" val history_comment = "history_comment" val confirm_account_1 = "confirm_account_1" val confirm_account_2 = "confirm_account_2" val confirm_account_3 = "confirm_account_3" val CREATOR_IMAGE_ID = "(SELECT " + TAccounts.img_id + " FROM " + TAccounts.NAME + " WHERE " + TAccounts.id + "=" + history_creator_id + ")" val CREATOR_SEX = "(SELECT " + TAccounts.sex + " FROM " + TAccounts.NAME + " WHERE " + TAccounts.id + "=" + history_creator_id + ")" val CREATOR_LVL = "(SELECT " + TAccounts.lvl + " FROM " + TAccounts.NAME + " WHERE " + TAccounts.id + "=" + history_creator_id + ")" val CREATOR_KARMA_30 = "(SELECT " + TAccounts.karma_count_30 + " FROM " + TAccounts.NAME + " WHERE " + TAccounts.id + "=" + history_creator_id + ")" val CREATOR_NAME = "(SELECT " + TAccounts.name + " FROM " + TAccounts.NAME + " WHERE " + TAccounts.id + "=" + history_creator_id + ")" val CREATOR_LAST_ONLINE_TIME = "(SELECT " + TAccounts.last_online_time + " FROM " + TAccounts.NAME + " WHERE " + TAccounts.id + "=" + history_creator_id + ")" }
0
Kotlin
0
0
40a2fbdbbdbe6706ed852f7218cb10fd57e50445
1,550
CampfireServer
Apache License 2.0
cipher/src/commonJvmMain/kotlin/diglol/crypto/AesCbc.kt
diglol
398,510,327
false
{"C": 284748, "Kotlin": 239933, "Objective-C": 44341, "JavaScript": 684}
package diglol.crypto import diglol.crypto.random.nextBytes import javax.crypto.Cipher as CipherJvm import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec // https://datatracker.ietf.org/doc/html/rfc3602 actual class AesCbc @JvmOverloads actual constructor( internal actual val key: ByteArray, internal actual val iv: ByteArray? ) : Cipher { init { checkKey() checkIv() } private val keySpec = SecretKeySpec(key, "AES") actual override suspend fun encrypt(plaintext: ByteArray): ByteArray { checkPlaintext(plaintext) try { val cipher = localCipher.get() val realIv = iv ?: nextBytes(IV_SIZE) cipher.init(CipherJvm.ENCRYPT_MODE, keySpec, IvParameterSpec(realIv)) return realIv + cipher.doFinal(plaintext) } catch (e: Exception) { throw Error("Aes cbc encrypt error", e) } } actual override suspend fun decrypt(ciphertext: ByteArray): ByteArray { checkCiphertext(ciphertext) val iv = ciphertext.copyOf(IV_SIZE) val rawCiphertext = ciphertext.copyOfRange(IV_SIZE, ciphertext.size) try { val cipher = localCipher.get() cipher.init(CipherJvm.DECRYPT_MODE, keySpec, IvParameterSpec(iv)) return cipher.doFinal(rawCiphertext) } catch (e: Exception) { throw Error("Aes cbc decrypt error", e) } } actual companion object { private val localCipher = object : ThreadLocal<CipherJvm>() { override fun initialValue(): CipherJvm { return CipherJvm.getInstance("AES/CBC/PKCS5Padding") } } @JvmField actual val IV_SIZE: Int = AES_CBC_IV_SIZE } }
3
C
4
21
af43f5cb73393336ec0e75b4835e3fc4f038db1b
1,621
crypto
Apache License 2.0
lib/src/test/kotlin/com/lemonappdev/konsist/api/ext/list/KoPrimaryConstructorProviderListExtTest.kt
LemonAppDev
621,181,534
false
{"Kotlin": 4854719, "Python": 17926}
package com.lemonappdev.konsist.api.ext.list import com.lemonappdev.konsist.api.declaration.KoPrimaryConstructorDeclaration import com.lemonappdev.konsist.api.provider.KoPrimaryConstructorProvider import io.mockk.every import io.mockk.mockk import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test class KoPrimaryConstructorProviderListExtTest { @Test fun `primaryConstructors returns primary constructors from all declarations`() { // given val primaryConstructor1: KoPrimaryConstructorDeclaration = mockk() val primaryConstructor2: KoPrimaryConstructorDeclaration = mockk() val declaration1: KoPrimaryConstructorProvider = mockk { every { primaryConstructor } returns primaryConstructor1 } val declaration2: KoPrimaryConstructorProvider = mockk { every { primaryConstructor } returns primaryConstructor2 } val declaration3: KoPrimaryConstructorProvider = mockk { every { primaryConstructor } returns null } val declarations = listOf(declaration1, declaration2, declaration3) // when val sut = declarations.primaryConstructors // then sut shouldBeEqualTo listOf(primaryConstructor1, primaryConstructor2) } @Test fun `withPrimaryConstructor() returns declaration with primary constructor`() { // given val declaration1: KoPrimaryConstructorProvider = mockk { every { hasPrimaryConstructor } returns true } val declaration2: KoPrimaryConstructorProvider = mockk { every { hasPrimaryConstructor } returns false } val declarations = listOf(declaration1, declaration2) // when val sut = declarations.withPrimaryConstructor() // then sut shouldBeEqualTo listOf(declaration1) } @Test fun `withoutPrimaryConstructor() returns declaration without primary constructor`() { // given val declaration1: KoPrimaryConstructorProvider = mockk { every { hasPrimaryConstructor } returns true } val declaration2: KoPrimaryConstructorProvider = mockk { every { hasPrimaryConstructor } returns false } val declarations = listOf(declaration1, declaration2) // when val sut = declarations.withoutPrimaryConstructor() // then sut shouldBeEqualTo listOf(declaration2) } }
5
Kotlin
26
995
603d19e179f59445c5f4707c1528a438e4595136
2,609
konsist
Apache License 2.0
app/src/main/java/bry1337/github/io/deliveryman/model/Delivery.kt
Bry1337
200,978,287
false
null
package bry1337.github.io.deliveryman.model import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import bry1337.github.io.deliveryman.util.LocationConverter import com.google.gson.annotations.SerializedName import org.parceler.Parcel /** * Created by edwardbryan.abergas on 08/07/2019. * * @author <EMAIL> */ @Entity data class Delivery(@PrimaryKey var id: Int): Parcelable { @SerializedName("description") var description: String? = null @SerializedName("imageUrl") var imageUrl: String? = null @TypeConverters(LocationConverter::class) @SerializedName("location") var location: Location = Location() constructor(parcel: android.os.Parcel) : this(parcel.readInt()) { description = parcel.readString() imageUrl = parcel.readString() location = parcel.readParcelable(Location::class.java.classLoader) } companion object CREATOR : Parcelable.Creator<Delivery> { override fun createFromParcel(parcel: android.os.Parcel): Delivery { return Delivery(parcel) } override fun newArray(size: Int): Array<Delivery?> { return arrayOfNulls(size) } } override fun writeToParcel(dest: android.os.Parcel?, flags: Int) { dest?.writeInt(this.id) dest?.writeString(this.description) dest?.writeString(this.imageUrl) dest?.writeParcelable(this.location, flags) } override fun describeContents(): Int { return 0 } }
0
Kotlin
0
0
883aaaaa746aae68567660d058a6694107f226a8
1,472
miniature-barnacle
MIT License
app/src/main/java/com/gaboardi/githubtest/repository/stargazers/StargazersRepositoryImpl.kt
sedestrian
195,600,716
false
null
package com.gaboardi.githubtest.repository.stargazers import androidx.annotation.MainThread import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.paging.PagedList import androidx.paging.toLiveData import com.gaboardi.githubtest.datasource.stargazers.local.StargazersBoundaryCallback import com.gaboardi.githubtest.datasource.stargazers.local.StargazersLocalDataSource import com.gaboardi.githubtest.datasource.stargazers.remote.StargazersRemoteDataSource import com.gaboardi.githubtest.db.AppDatabase import com.gaboardi.githubtest.model.base.Listing import com.gaboardi.githubtest.model.base.NetworkState import com.gaboardi.githubtest.model.stargazers.Stargazer import com.gaboardi.githubtest.model.stargazers.StargazerResult import com.gaboardi.githubtest.util.AppExecutors import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.Call import retrofit2.Callback import retrofit2.Response class StargazersRepositoryImpl( val userReposRemoteDataSource: StargazersRemoteDataSource, val userReposLocalDataSource: StargazersLocalDataSource, val appDatabase: AppDatabase, val appExecutors: AppExecutors ): StargazersRepository { override fun queryForStargazers(repoFullName: String, pageSize: Int): Listing<Stargazer> { userReposLocalDataSource.clear() val boundaryCallback = StargazersBoundaryCallback( appExecutors, userReposRemoteDataSource, userReposLocalDataSource, repoFullName, { q, list -> saveToDb(list) }, pageSize ) val refreshTrigger = MutableLiveData<Unit>() val refreshState = Transformations.switchMap(refreshTrigger) { refresh(repoFullName, pageSize) } val config = PagedList.Config.Builder() .setEnablePlaceholders(false) .setPageSize(pageSize) .setPrefetchDistance(1) .build() val livePagedList = userReposLocalDataSource.queryStargazers(repoFullName).toLiveData( config = config, boundaryCallback = boundaryCallback ) return Listing( pagedList = livePagedList, networkState = boundaryCallback.networkState, retry = { boundaryCallback.helper.retryAllFailed() }, refresh = { boundaryCallback.resetErrors() refreshTrigger.value = null }, refreshState = refreshState ) } @MainThread private fun refresh(query: String, pageSize: Int): LiveData<NetworkState> { val networkState = MutableLiveData<NetworkState>() networkState.value = NetworkState.LOADING MainScope().launch { withContext(Dispatchers.IO){ userReposLocalDataSource.clear() userReposRemoteDataSource.getStargazers().call(query, perPage = pageSize) .enqueue(object : Callback<StargazerResult> { override fun onFailure(call: Call<StargazerResult>, t: Throwable) { networkState.value = NetworkState.error(t.message) } override fun onResponse(call: Call<StargazerResult>, response: Response<StargazerResult>) { if (response.isSuccessful) { val body = response.body() if (body != null) { appExecutors.diskIO().execute { saveToDb(response.body()?.users) networkState.postValue(NetworkState.LOADED) } } else networkState.postValue(NetworkState.error("Body empty or error")) } else networkState.postValue(NetworkState.error("Call not successful")) } }) } } return networkState } private fun saveToDb(repos: List<Stargazer>?) { repos?.let { appDatabase.runInTransaction { val start = userReposLocalDataSource.getNextIndex() val data = repos.mapIndexed{ index, stargazer -> stargazer.callPosition = start + index stargazer } userReposLocalDataSource.insert(data) } } } }
1
null
1
1
237c7182575677013ab39919b7bbf142fa6bf705
4,656
GitHub-Test
MIT License
attribution/src/main/java/com/affise/attribution/converter/StringToAffiseReferrerDataConverter.kt
affise
496,592,599
false
{"Kotlin": 859274, "JavaScript": 39328, "HTML": 33916}
package com.affise.attribution.converter import com.affise.attribution.logs.LogsManager import com.affise.attribution.referrer.AffiseReferrerData import org.json.JSONObject /** * Converter from [String] to [AffiseReferrerData] * * @property logsManager for error logging */ class StringToAffiseReferrerDataConverter( private val logsManager: LogsManager ) : Converter<String, AffiseReferrerData?> { /** * Convert [from] String to json AffiseReferrerData */ override fun convert(from: String): AffiseReferrerData? { return try { //Create JSONObject val j = JSONObject(from) //Create referrer data AffiseReferrerData( installReferrer = j.getString(AffiseReferrerData.KEYS.installReferrer), referrerClickTimestampSeconds = j.getLong(AffiseReferrerData.KEYS.referrerClickTimestampSeconds), installBeginTimestampSeconds = j.getLong(AffiseReferrerData.KEYS.installBeginTimestampSeconds), referrerClickTimestampServerSeconds = j.getLong(AffiseReferrerData.KEYS.referrerClickTimestampServerSeconds), installBeginTimestampServerSeconds = j.getLong(AffiseReferrerData.KEYS.installBeginTimestampServerSeconds), installVersion = j.getString(AffiseReferrerData.KEYS.installVersion), googlePlayInstantParam = j.getBoolean(AffiseReferrerData.KEYS.googlePlayInstantParam), ) } catch (e: Exception) { //log error logsManager.addSdkError(e) null } } }
0
Kotlin
0
5
ab7d393c6583208e33cef9e10e01ba9dd752bbcb
1,599
sdk-android
MIT License
graph/graph-adapter-output-spring-data-neo4j-sdn6/src/main/kotlin/eu/tib/orkg/prototype/statements/adapter/output/neo4j/spring/internal/Neo4jStatement.kt
TIBHannover
197,416,205
false
{"Kotlin": 2433821, "Cypher": 215872, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package eu.tib.orkg.prototype.statements.adapter.output.neo4j.spring.internal import eu.tib.orkg.prototype.community.domain.model.ContributorId import eu.tib.orkg.prototype.statements.domain.model.StatementId import eu.tib.orkg.prototype.statements.domain.model.ThingId import java.time.OffsetDateTime import org.springframework.data.neo4j.core.schema.Property import org.springframework.data.neo4j.core.schema.RelationshipId import org.springframework.data.neo4j.core.schema.RelationshipProperties import org.springframework.data.neo4j.core.schema.TargetNode /** * This class cannot be used to save and retrieve statements. It's only purpose is to serve as * a data object when retrieving delegated descriptions for [Neo4jClass]es [Neo4jPredicate]es. */ @RelationshipProperties class Neo4jStatement { @RelationshipId var relationId: Long? = null @Property("statement_id") var id: StatementId? = null @Property("predicate_id") var predicateId: ThingId? = null @TargetNode var targetNode: Neo4jThing? = null @Property("created_by") var createdBy: ContributorId = ContributorId.createUnknownContributor() @Property("created_at") var createdAt: OffsetDateTime? = null }
0
Kotlin
2
5
13cd2ba723dbd061e0dad8e9a9aa02378dd9166d
1,225
orkg-backend
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/ui/submission/fragment/SubmissionDispatcherFragment.kt
CoraLibre
268,867,734
true
null
package de.rki.coronawarnapp.ui.submission.fragment import android.os.Bundle import android.view.View import android.view.accessibility.AccessibilityEvent import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import de.rki.coronawarnapp.R import de.rki.coronawarnapp.databinding.FragmentSubmissionDispatcherBinding import de.rki.coronawarnapp.ui.doNavigate import de.rki.coronawarnapp.ui.main.MainActivity import de.rki.coronawarnapp.util.DialogHelper import de.rki.coronawarnapp.util.ui.viewBindingLazy class SubmissionDispatcherFragment : Fragment(R.layout.fragment_submission_dispatcher) { private val binding: FragmentSubmissionDispatcherBinding by viewBindingLazy() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setButtonOnClickListener() } override fun onResume() { super.onResume() binding.submissionDispatcherRoot.sendAccessibilityEvent(AccessibilityEvent.TYPE_ANNOUNCEMENT) } private fun setButtonOnClickListener() { binding.submissionDispatcherHeader.headerButtonBack.buttonIcon.setOnClickListener { (activity as MainActivity).goBack() } binding.submissionDispatcherContent.submissionDispatcherQr.dispatcherCard.setOnClickListener { checkForDataPrivacyPermission() } binding.submissionDispatcherContent.submissionDispatcherTanCode.dispatcherCard.setOnClickListener { findNavController().doNavigate( SubmissionDispatcherFragmentDirections.actionSubmissionDispatcherFragmentToSubmissionTanFragment() ) } binding.submissionDispatcherContent.submissionDispatcherTanTele.dispatcherCard.setOnClickListener { findNavController().doNavigate( SubmissionDispatcherFragmentDirections.actionSubmissionDispatcherFragmentToSubmissionContactFragment() ) } } private fun checkForDataPrivacyPermission() { val cameraPermissionRationaleDialogInstance = DialogHelper.DialogInstance( requireActivity(), R.string.submission_dispatcher_qr_privacy_dialog_headline, R.string.submission_dispatcher_qr_privacy_dialog_body, R.string.submission_dispatcher_qr_privacy_dialog_button_positive, R.string.submission_dispatcher_qr_privacy_dialog_button_negative, true, { privacyPermissionIsGranted() } ) DialogHelper.showDialog(cameraPermissionRationaleDialogInstance) } private fun privacyPermissionIsGranted() { findNavController().doNavigate( SubmissionDispatcherFragmentDirections.actionSubmissionDispatcherFragmentToSubmissionQRCodeScanFragment() ) } }
5
Kotlin
3
36
8e3d915aa194cae0645ff668cca2114d9bb3d7c2
2,859
CoraLibre-android
Apache License 2.0
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/autoversioning/CheckAutoVersioningByBuildNameInput.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.extension.github.autoversioning import net.nemerosa.ontrack.model.annotations.APIDescription import net.nemerosa.ontrack.model.annotations.APIName @APIName("GitHubCheckAutoVersioningByBuildNameInput") @APIDescription("Input for the auto versioning check for a build identified by its name") data class CheckAutoVersioningByBuildNameInput( val owner: String, val repository: String, @APIDescription("Name of the build") val buildName: String, )
57
Kotlin
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
490
ontrack
MIT License
Application/src/main/java/com/example/android/ui/activity/BaseActivity.kt
Nazmul56
567,401,882
false
{"Java Properties": 5, "YAML": 1, "Gradle": 3, "Shell": 1, "Markdown": 3, "Batchfile": 1, "Text": 17, "Ignore List": 1, "INI": 7, "XML": 279, "Kotlin": 27, "Java": 42, "JSON": 267, "Motorola 68K Assembly": 1, "SQL": 1, "HTML": 1}
package com.example.android.ui.activity import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Bundle import androidx.annotation.LayoutRes import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.view.* import com.example.android.camera2basic.R import com.example.android.utils.U /** * Created by */ abstract class BaseActivity : AppCompatActivity() { //private val cookieManager = SessionCookieManager.instance private val TAG = "BaseActivity" @LayoutRes protected abstract fun getLayoutResId(): Int protected open fun isFullScreenRequired() = false protected open fun isSecurityRequired() = false protected open fun isToColorBars() = true protected open fun getPageTitle(): String? = getString(R.string.app_name) protected open fun getPageSubtitle(): String? = null protected open fun getToolbar() = findViewById<Toolbar>(R.id.toolbar) ?: null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (isFullScreenRequired()) { requestWindowFeature(Window.FEATURE_NO_TITLE) window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) /*View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions);*/ } if (isSecurityRequired()) window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE) overridePendingTransition(getEntryAnimId(), getExitAnimId()) //TODO some time crashed here setContentView(getLayoutResId()) if (isToColorBars() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = ContextCompat.getColor(this, R.color.colorPrimaryDark) window.navigationBarColor = ContextCompat.getColor(this, R.color.colorPrimaryDark) } val toolbar = getToolbar() if (toolbar != null) { setSupportActionBar(toolbar) supportActionBar?.title = getPageTitle() val st = getPageSubtitle() if (U.notEmpty(st)) supportActionBar?.subtitle = st supportActionBar?.setDisplayHomeAsUpEnabled(getDisplayHomeAsUpEnabled()) } } /** * */ protected open fun getDisplayHomeAsUpEnabled() = false protected open fun getEntryAnimId(): Int = R.anim.slide_in_from_right protected open fun getExitAnimId(): Int = R.anim.slide_out fun setLightStatusBar(activity: Activity, view: View) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { view.visibility = View.VISIBLE var flags = view.systemUiVisibility flags = flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR view.systemUiVisibility = flags activity.window.statusBarColor = Color.WHITE } } protected fun signOut(context: Context) { } override fun onBackPressed() { super.onBackPressed() } // override fun onOptionsItemSelected(item: MenuItem?): Boolean { // if (getDisplayHomeAsUpEnabled() && item?.itemId == android.R.id.home) // finish().also { return true } // return super.onOptionsItemSelected(item) // } // region keyboard open-close listener protected open fun getRootLayout(): ViewGroup? = null private val keyboardLayoutListener = ViewTreeObserver.OnGlobalLayoutListener { val rootLayout = getRootLayout() ?: return@OnGlobalLayoutListener val heightDiff = rootLayout.rootView.height - rootLayout.height val contentViewTop = window.findViewById<View>(Window.ID_ANDROID_CONTENT).top val broadcastManager = androidx.localbroadcastmanager.content.LocalBroadcastManager.getInstance(this@BaseActivity) if (heightDiff <= contentViewTop) { onHideKeyboard() val intent = Intent("KeyboardWillHide") broadcastManager.sendBroadcast(intent) } else { val keyboardHeight = heightDiff - contentViewTop onShowKeyboard(keyboardHeight) val intent = Intent("KeyboardWillShow") intent.putExtra("KeyboardHeight", keyboardHeight) broadcastManager.sendBroadcast(intent) } } private var keyboardListenersAttached = false protected open fun onShowKeyboard(keyboardHeight: Int) {} protected open fun onHideKeyboard() {} protected fun attachKeyboardListeners() { if (keyboardListenersAttached) return val rootLayout = getRootLayout() ?: return rootLayout.viewTreeObserver.addOnGlobalLayoutListener(keyboardLayoutListener) keyboardListenersAttached = true } override fun onDestroy() { if (keyboardListenersAttached) getRootLayout()?.viewTreeObserver?.removeOnGlobalLayoutListener(keyboardLayoutListener) super.onDestroy() } // endregion }
1
null
1
1
354f2b321f6cd2f0f11af5fdff8f16b98eed17ee
5,569
HRVDetector
Apache License 2.0
braid-gradle/src/main/java/io/bluebank/braid/BraidPlugin.kt
JonathanScialpi
237,445,305
false
{"JSON": 23, "Maven POM": 11, "XML": 17, "Text": 6, "Ignore List": 15, "Markdown": 21, "YAML": 1, "reStructuredText": 2, "Python": 2, "Shell": 9, "Java Properties": 11, "Kotlin": 269, "Java": 17, "HTML": 12, "CSS": 3, "JavaScript": 27, "PlantUML": 1, "Dockerfile": 2, "OASv2-json": 1, "JSON with Comments": 1, "Batchfile": 5, "Gradle": 6, "INI": 2}
/** * Copyright 2018 Royal Bank of Scotland * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.bluebank.braid import com.typesafe.config.Config import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import org.gradle.api.Plugin import org.gradle.api.Project import java.io.File import java.io.FileOutputStream import java.net.URL import java.nio.channels.Channels import java.nio.file.Files.copy import java.nio.file.StandardCopyOption.REPLACE_EXISTING open class BraidPlugin : Plugin<Project> { companion object { val reader = HoconReader() } override fun apply(project: Project) { val extension = project.extensions .create("braid", BraidPluginExtension::class.java) project.buildDir project.task("braid") .doLast { downloadBraid(project,extension) nodeDirectories(project).forEach { val config = reader.read("${it.absolutePath}/web-server.conf") if(config.hasPath("webAddress")) installBraidTo(project, "${it.absolutePath}", braidProperties(config)) else println("Cant find:${it.absolutePath}/web-server.conf so not creating braid") } } } private fun braidProperties(config: Config): JsonObject { val extension = JsonObject() extension.put("networkAndPort",config.getString("rpcSettings.address")) extension.put("username",config.getConfigList("security.authService.dataSource.users").get(0).getString("user")) extension.put("password",config.getConfigList("security.authService.dataSource.users").get(0).getString("password")) extension.put("port",Integer.parseInt(config.getString("webAddress").split(":")[1])) extension.put("cordapps", JsonArray().add("cordapps")) return extension } private fun nodeDirectories(project: Project) = File("${project.buildDir}/nodes").listFiles().filter { it.isDirectory && !it.name.startsWith(".") } private fun downloadBraid(project: Project, extension: BraidPluginExtension) { val version = extension.version ?: ManifestReader("${extension.releaseRepo}/io/bluebank/braid/braid-server/maven-metadata.xml").releaseVersion() val repo = if (version.contains("SNAPSHOT")) extension.snapshotRepo else extension.releaseRepo val path = "$repo/io/bluebank/braid/braid-server/$version/braid-server-$version.jar" if(repo.startsWith("http")) { URL(path).downloadTo("${project.buildDir}/braid.jar") } else { copy(File(path).toPath(),File("${project.buildDir}/braid.jar").toPath(), REPLACE_EXISTING) } } private fun installBraidTo(project: Project, destinationDirectory: String, config: JsonObject) { project.copy { it.from(project.getPluginFile("/braid.bat")) it.into("$destinationDirectory") } project.copy { it.from(project.getPluginFile("/braid")) it.fileMode = executableFileMode it.into("$destinationDirectory") } project.copy { it.from("${project.buildDir}/braid.jar") it.fileMode = executableFileMode it.into("$destinationDirectory") } // <node address> <username> <password> <port> <openApiVersion> [<cordaAppJar1> <cordAppJar2> File("$destinationDirectory/braid.conf") .writeText(config.encodePrettily()) println("Braid installed at: $destinationDirectory") } val executableFileMode = "0755".toInt(8) } private fun Project.getPluginFile(filePathInJar: String): File { val tmpDir = File(this.buildDir, "tmp") tmpDir.mkdirs() val outputFile = File(tmpDir, filePathInJar) outputFile.outputStream().use { BraidPlugin::class.java.getResourceAsStream(filePathInJar).copyTo(it) } return outputFile } private fun URL.downloadTo(destination: String) { Channels.newChannel(this.openStream()).use { rbc -> FileOutputStream(destination).use { fos -> fos.channel.transferFrom(rbc, 0, Long.MAX_VALUE); } } }
1
null
1
1
ca754e2c58e80486d78779bf4bd2b49b0f0bcae9
4,451
braid-master
Apache License 2.0
kotlin_language/src/com/study/014-kotlin语言的takeUnless内置函数.kt
Tecode
455,788,985
false
{"Java": 409665, "Kotlin": 196048}
package com.study // taleUnless与takeIf的操作相反,false返回userName true返回null class Manager { private var infoValue: String? = null fun getInfoValue() = infoValue fun setInfoValue(value: String) { this.infoValue = value } } fun main() { val manager = Manager() val value = manager.getInfoValue().takeUnless { it.isNullOrBlank() } ?: "valueInfo为null" println(value) // valueInfo为null manager.setInfoValue("OK") val value2 = manager.getInfoValue().takeUnless { it.isNullOrBlank() } ?: "valueInfo为null" println(value2) //OK }
1
null
1
1
78a8c1e661c3a8a3f9b3dee8c6cf806cfec49a98
567
android_learning
MIT License
src/main/kotlin/pl/exbook/exbook/bookinfo/domain/BookInfoSuggestion.kt
Ejden
339,380,956
false
null
package pl.exbook.exbook.bookinfo.domain data class BookInfoSuggestion( val title: String, val subtitle: String?, val author: String )
0
Kotlin
0
1
ac636229a26daf6e82f7f7d0ea1c02f32788c782
148
exbook-backend
The Unlicense
app/src/main/java/com/example/mastertask/Data/User.kt
pp3-mastertask
682,073,681
false
{"Kotlin": 143143}
package com.example.mastertask.Data import com.google.firebase.Timestamp import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.Exclude import com.google.firebase.firestore.IgnoreExtraProperties @IgnoreExtraProperties data class User ( var id: String? = null, var cep: String? = null, var contato: String? = null, var cpf: String? = null, var dataInicio: Timestamp? = null, var dataNascimento: Timestamp? = null, var endereco: String? = null, var habilidades: List<Map<String?, Any?>>? = null, var imagem: String? = null, var nome: String? = null, var numServicosFeitos: Long? = null, var numeroResidencia: Long? = null, var somaAvaliacoes: Double? = null, ) { @Exclude fun toMap(): Map<String, Any?> { return mapOf( "id" to id, "cep" to cep, "contato" to contato, "cpf" to cpf, "dataInicio" to dataInicio, "dataNascimento" to dataNascimento, "endereco" to endereco, "habilidades" to habilidades, "imagem" to imagem, "nome" to nome, "numServicosFeitos" to numServicosFeitos, "numeroResidencia" to numeroResidencia, "somaAvaliacoes" to somaAvaliacoes, ) } }
0
Kotlin
0
1
b21b68d26fedf00434e6c22ff1ec2c48cdf80ad0
1,331
mastertask-mobile
MIT License
app/src/main/java/com/fphoenixcorneae/demo/ui/SimpleHomeActivity.kt
FPhoenixCorneaE
288,119,870
false
null
package com.fphoenixcorneae.demo.ui import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.util.DisplayMetrics import android.util.TypedValue import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.* import android.widget.AdapterView.OnItemClickListener import androidx.appcompat.app.AppCompatActivity import com.fphoenixcorneae.demo.ui.DialogHomeActivity class SimpleHomeActivity : AppCompatActivity() { private val mContext: Context = this private val mItems = arrayOf("Dialog", "Popup") private val mClazzs = arrayOf<Class<*>>( DialogHomeActivity::class.java, PopupHomeActivity::class.java ) private var mDisplayMetrics: DisplayMetrics? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mDisplayMetrics = resources.displayMetrics val lv = ListView(mContext) lv.cacheColorHint = Color.TRANSPARENT lv.setBackgroundColor(Color.WHITE) lv.setFadingEdgeLength(0) lv.adapter = SimpleHomeAdapter() lv.onItemClickListener = OnItemClickListener { parent, view, position, id -> val intent = Intent(mContext, mClazzs[position]) startActivity(intent) } val layoutParams = FrameLayout.LayoutParams(-1, -2) layoutParams.gravity = Gravity.CENTER lv.layoutParams = layoutParams setContentView(lv) window?.setBackgroundDrawable(ColorDrawable(Color.WHITE)) } internal inner class SimpleHomeAdapter : BaseAdapter() { override fun getCount(): Int { return mItems.size } override fun getItem(position: Int): Any? { return null } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView( position: Int, convertView: View?, parent: ViewGroup ): View { val padding = (mDisplayMetrics!!.density * 20).toInt() val tv = TextView(mContext) tv.text = mItems[position] tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f) tv.setTextColor(Color.parseColor("#468ED0")) tv.setGravity(Gravity.CENTER); tv.setPadding(padding, padding, padding, padding) val lp = AbsListView.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT ) tv.layoutParams = lp return tv } } }
0
Kotlin
0
1
9851ad86c5042a4fa5473febada00d6bf356326a
2,713
PrettyDialog
Apache License 2.0
tiktok/src/main/java/com/kyawhut/atsycast/tiktok/TiktokApp.kt
kyawhtut-cu
406,324,527
false
null
package com.kyawhut.atsycast.tiktok import android.content.Context import androidx.fragment.app.Fragment import com.kyawhut.atsycast.share.utils.extension.startActivity import com.kyawhut.atsycast.tiktok.ui.home.HomeActivity import com.kyawhut.atsycast.tiktok.utils.Constants /** * @author kyawhtut * @date 10/4/21 */ object TiktokApp { private fun goToTiktok(routeName: String, context: Context) { context.startActivity<HomeActivity>( Constants.EXTRA_ROUTE_NAME to routeName ) } fun Fragment.goToTiktok(routeName: String) { goToTiktok(routeName, requireContext()) } }
0
Kotlin
4
3
72d56fa28f5be7526f0a9848491ddd87cca3804d
628
atsy-cast
Apache License 2.0
libraries/csm.cloud.common.core/src/main/kotlin/com/bosch/pt/csm/cloud/common/exceptions/UserNotRegisteredException.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.common.exceptions class UserNotRegisteredException : RuntimeException()
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
328
bosch-pt-refinemysite-backend
Apache License 2.0
app/src/main/java/com/jetpack/composepagination/utils/UserSource.kt
MakeItEasyDev
419,510,377
false
null
package com.jetpack.composepagination.utils import androidx.paging.PagingSource import androidx.paging.PagingState import com.jetpack.composepagination.model.UserData import com.jetpack.composepagination.network.ApiClient import retrofit2.HttpException import java.io.IOException class UserSource: PagingSource<Int, UserData>() { override fun getRefreshKey(state: PagingState<Int, UserData>): Int? { return state.anchorPosition } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UserData> { return try { val nextPage = params.key ?: 1 val userList = ApiClient.apiService.getUserList(nextPage) LoadResult.Page( data = userList.data, prevKey = if (nextPage == 1) null else nextPage - 1, nextKey = if (userList.data.isEmpty()) null else userList.page + 1 ) } catch (exception: IOException) { return LoadResult.Error(exception) } catch (exception: HttpException) { return LoadResult.Error(exception) } } }
0
Kotlin
1
4
e86fa6e4e6d986a8f17e28241b2d99bb03489f4f
1,101
Jetpack-Compose-List-Pagination
Apache License 2.0
plugin-bazel/src/main/kotlin/org/jetbrains/bazel/languages/starlark/references/StarlarkResolveProcessor.kt
JetBrains
826,262,028
false
{"Kotlin": 2207852, "Java": 460037, "Starlark": 301920, "Scala": 36560, "Python": 34754, "Lex": 10489, "Shell": 2584, "HTML": 1310, "Rust": 680, "C++": 100}
package org.jetbrains.bazel.languages.starlark.references import com.intellij.util.Processor import org.jetbrains.bazel.languages.starlark.psi.StarlarkElement import org.jetbrains.bazel.languages.starlark.psi.StarlarkNamedElement class StarlarkResolveProcessor(val result: MutableList<StarlarkElement>, private val referenceElement: StarlarkElement) : Processor<StarlarkElement> { override fun process(currentElement: StarlarkElement): Boolean = when { currentElement == referenceElement -> true currentElement.isTargetElement(referenceElement) -> !result.add(currentElement) else -> true } private fun StarlarkElement.isTargetElement(referenceElement: StarlarkElement): Boolean = this is StarlarkNamedElement && referenceElement.name == this.name }
1
Kotlin
6
13
1227a5f7aae8d872687cbb9fdfe4284c9a76ff7f
789
hirschgarten
Apache License 2.0
app/src/main/java/com/anesabml/zalandoar/utils/ProductCategoryConverter.kt
anesabml
295,125,481
false
null
package com.anesabml.zalandoar.utils import androidx.room.TypeConverter import com.anesabml.zalandoar.domain.model.ProductCategory class ProductCategoryConverter { @TypeConverter fun fromString(category: String): ProductCategory = ProductCategory.valueOf(category) @TypeConverter fun stringToProductCategory(category: ProductCategory): String = category.name }
0
Kotlin
0
0
466b55dc35d298962c5953172b7f2c28080f429e
396
zalando-ar
MIT License
app/src/main/java/com/example/diapplication/domain/utils/Constants.kt
rendivy
661,304,960
false
null
package com.example.diapplication.domain.utils object Constants { const val API_TOKEN = "ee6dfd6f5e224f0a8ed134208230407" const val BASE_URL = "http://api.weatherapi.com/v1/" const val CONNECT_TIMEOUT = 10L const val READ_TIMEOUT = 10L const val WRITE_TIMEOUT = 10L const val EMPTY_STRING = "" const val PRIORITY = 100 const val SHORT_SPACE = " " const val PREDICT_DELAY = 300L const val GIT_HUB_KEY = "gitHub" const val ISSUE_KEY = "form" const val GIT_HUB_URL = "https://github.com/rendivy/ShiftAndroid2023" const val FEED_BACK_URL = "https://forms.gle/oLaWJZQYNPdFCDSC6" }
0
Kotlin
0
0
da2a3e4f13d0064699a2073bdce55fd8d9f9da21
628
MonoWeather
MIT License
Bakku/app/src/main/java/com/example/bakku/fragments/HomeSlide1Fragment.kt
GDSC-SKHU
599,948,554
false
null
package com.example.bakku.fragments import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.example.bakku.R import com.example.bakku.data.remote.response.EventResponse import com.example.bakku.utils.ImageTransformer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.net.URL class HomeSlide1Fragment : Fragment { companion object { const val REQUEST_CODE = 1 } //private var mBinding : FragmentHomeSlide1Binding? = null lateinit var frameLayout1 : FrameLayout var mEvent : EventResponse constructor(event: EventResponse) : super() { mEvent = event Log.d("HomeSlide1Fragment", mEvent.imageUrl?.let { Uri.parse(it) }.toString()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val v : View = inflater.inflate(com.example.bakku.R.layout.fragment_home_slide1,container,false) // change image src val imageView = v.findViewById<ImageView>(R.id.imgBanner1) lifecycleScope.launch(Dispatchers.IO) { val bitmap = ImageTransformer.getImageBitmapFromUrl(mEvent.imageUrl) withContext(Dispatchers.Main) { imageView.setImageBitmap(bitmap) } } frameLayout1 = v.findViewById(R.id.frameLayout1) frameLayout1.setOnClickListener{ val fragment = EventFragment(mEvent) val fragmentManager = requireActivity().supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() fragmentTransaction.replace(R.id.homeFragment,fragment) fragmentTransaction.addToBackStack(null) fragmentTransaction.commit() } //return mBinding?.root return v } }
0
Kotlin
0
0
7ceb7e088f73433ce8ef1d05a4773b73413a57e3
2,252
Bakku-Android
MIT License
runtime/runtime-core/native/src/aws/smithy/kotlin/runtime/io/SdkBufferedSinkNative.kt
smithy-lang
294,823,838
false
{"Kotlin": 4171610, "Smithy": 122979, "Python": 1215}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.smithy.kotlin.runtime.io public actual sealed interface SdkBufferedSink : SdkSink { /** * The underlying buffer for this sink */ public actual val buffer: SdkBuffer /** * Write [limit] bytes from [source] starting at [offset] */ public actual fun write(source: ByteArray, offset: Int, limit: Int) /** * Removes [byteCount] bytes from [source] and writes them to this sink. */ public actual fun write(source: SdkSource, byteCount: Long) /** * Write all bytes from [source] to this sink. * @return the number of bytes read which will be 0 if [source] is exhausted */ public actual fun writeAll(source: SdkSource): Long /** * Write [string] as UTF-8 encoded bytes to this sink starting at [start] index up to [endExclusive] index. */ public actual fun writeUtf8(string: String, start: Int, endExclusive: Int) /** * Writes byte [x] to this sink */ public actual fun writeByte(x: Byte) /** * Writes short [x] as a big-endian bytes to this sink */ public actual fun writeShort(x: Short) /** * Writes short [x] as a little-endian bytes to this sink */ public actual fun writeShortLe(x: Short) /** * Writes int [x] as a big-endian bytes to this sink */ public actual fun writeInt(x: Int) /** * Writes int [x] as a little-endian bytes to this sink */ public actual fun writeIntLe(x: Int) /** * Writes long [x] as a big-endian bytes to this sink */ public actual fun writeLong(x: Long) /** * Writes long [x] as a little-endian bytes to this sink */ public actual fun writeLongLe(x: Long) /** * Writes all buffered data to the underlying sink. Like flush, but weaker (ensures data is pushed to the * underlying sink but not necessarily all the way down the chain like [flush] does). Call before this sink * goes out of scope to ensure any buffered data eventually gets to its final destination */ public actual fun emit() }
36
Kotlin
26
82
ad18e2fb043f665df9add82083c17877a23f8610
2,204
smithy-kotlin
Apache License 2.0
enro-fragments-sample/src/main/java/com/ddmeng/example/MainActivity.kt
mengdd
505,520,243
false
{"Kotlin": 75993}
package com.ddmeng.example import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import dagger.hilt.android.AndroidEntryPoint import dev.enro.annotations.NavigationDestination import dev.enro.core.forward import dev.enro.core.navigationHandle @NavigationDestination(MainKey::class) @AndroidEntryPoint class MainActivity : AppCompatActivity() { private val navigation by navigationHandle<MainKey> { defaultKey( MainKey() ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) navigation.forward(FragmentAKey(name = "start", age = 18)) } }
0
Kotlin
1
9
fc316d4cac3ca789a93b191c99ed74a305bf2297
706
bottom-navigation-samples
Apache License 2.0
app/src/main/kotlin/com/sanmer/geomag/model/data/DateTime.kt
SanmerApps
583,580,288
false
{"Kotlin": 237278}
package com.sanmer.geomag.model.data import com.sanmer.geomag.GeomagExt import com.sanmer.geomag.utils.extensions.now import com.sanmer.geomag.utils.extensions.toTimeZone import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone class DateTime private constructor( year: Int, monthNumber: Int, dayOfMonth: Int, hour: Int, minute: Int, second: Int ) { val local = LocalDateTime(year, monthNumber, dayOfMonth, hour, minute, second) val decimalOfLocal get() = GeomagExt.toDecimalYears(local) private val utc get() = local.toTimeZone(TimeZone.UTC) val decimalOfUtc get() = GeomagExt.toDecimalYears(utc) override fun toString(): String { return local.toString() } companion object { fun now(): DateTime { val t = LocalDateTime.now() return DateTime( t.year, t.monthNumber, t.dayOfMonth, t.hour, t.minute, t.second ) } fun parse(isoString: String): DateTime { val t = LocalDateTime.parse(isoString) return DateTime( t.year, t.monthNumber, t.dayOfMonth, t.hour, t.minute, t.second ) } } }
0
Kotlin
2
22
99bcb927217db0bdfaf84d25e10695eae2e58a65
1,359
Geomag
Apache License 2.0
mvi-light/mvi-light-main/src/main/kotlin/com/tipapro/mvilight/main/StatePair.kt
mospolyhelper
259,442,737
false
{"Kotlin": 839539, "Batchfile": 69}
package com.tipapro.mvilight.main data class StatePair<State>( val old: State?, val new: State ) /** * Compares property of old and new states. Property provides by [propSelector] * * @param propSelector function that selects property for comparing. */ inline fun <State, T> StatePair<State>.isChanged(propSelector: State.() -> T) = old == null || propSelector(old) !== propSelector(new) && propSelector(old) != propSelector(new) /** * Compares properties of old and new states and * return if one of properties has changed. * Properties provides by [propSelector] * * @param propSelector function that selects list of properties for comparing. */ inline fun <State, T> StatePair<State>.isAnyChanged(propSelector: State.() -> List<T>) = old == null || isNotEqual(propSelector(old), propSelector(new)) @Suppress("SuspiciousEqualsCombination") fun <T> isNotEqual(l1: List<T>, l2: List<T>): Boolean { if (l1.size != l2.size) throw IllegalStateException("Lists of properties must have equal size") l1.forEachIndexed { index, t -> if (t !== l2[index] && t != l2[index]) return true } return false } inline fun <State, T> StatePair<State>.onChanged(propSelector: State.() -> T, onChangedAction: (State) -> Unit) { if ( old == null || propSelector(old) !== propSelector(new) && propSelector(old) != propSelector(new) ) { onChangedAction(this.new) } } inline fun <State, T> StatePair<State>.onAnyChanged(propSelector: State.() -> List<T>, onChangedAction: (State) -> Unit) { if (old == null || isNotEqual(propSelector(old), propSelector(new))) { onChangedAction(this.new) } }
2
Kotlin
2
8
4f37c3617cf7523f22f03a22d7de2d7ecc74a098
1,707
mospolyhelper-android
MIT License
module-core/src/main/java/langchainkt/memory/chat/TokenWindowChatMemory.kt
c0x12c
655,095,005
false
{"Kotlin": 322914, "Java": 13181}
package langchainkt.memory.chat import java.util.Optional import langchainkt.data.message.ChatMessage import langchainkt.data.message.SystemMessage import langchainkt.internal.Validators import langchainkt.memory.ChatMemory import langchainkt.model.Tokenizer import langchainkt.store.memory.chat.ChatMemoryStore import langchainkt.store.memory.chat.InMemoryChatMemoryStore import org.slf4j.LoggerFactory /** * This chat memory operates as a sliding window of [.maxTokens] tokens. * It retains as many of the most recent messages as can fit into the window. * If there isn't enough space for a new message, the oldest one (or multiple) is discarded. * Messages are indivisible. If a message doesn't fit, it's discarded completely. * * * Once added, a [SystemMessage] is always retained. * Only one [SystemMessage] can be held at a time. * If a new [SystemMessage] with the same content is added, it is ignored. * If a new [SystemMessage] with different content is added, it replaces the previous one. * * * The state of chat memory is stored in [ChatMemoryStore]. */ class TokenWindowChatMemory private constructor(builder: Builder) : ChatMemory { private val id: Any private val maxTokens: Int private val tokenizer: Tokenizer private val store: ChatMemoryStore init { id = builder.id maxTokens = Validators.ensureGreaterThanZero(builder.maxTokens, "maxTokens") tokenizer = builder.tokenizer store = builder.store } override fun id(): Any { return id } override fun add(message: ChatMessage) { val messages = messages() if (message is SystemMessage) { val maybeSystemMessage = findSystemMessage(messages) if (maybeSystemMessage.isPresent) { if (maybeSystemMessage.get() == message) { return // do not add the same system message } else { messages.remove(maybeSystemMessage.get()) // need to replace existing system message } } } messages.add(message) ensureCapacity(messages, maxTokens, tokenizer) store.updateMessages(id, messages) } override fun messages(): MutableList<ChatMessage> { val messages: MutableList<ChatMessage> = ArrayList(store.getMessages(id)) ensureCapacity(messages, maxTokens, tokenizer) return messages } override fun clear() { store.deleteMessages(id) } class Builder { internal var id: Any = "default" internal var maxTokens: Int = 1 internal lateinit var tokenizer: Tokenizer internal var store: ChatMemoryStore = InMemoryChatMemoryStore() /** * @param id The ID of the [ChatMemory]. * If not provided, a "default" will be used. * @return builder */ fun id(id: Any): Builder { this.id = id return this } /** * @param maxTokens The maximum number of tokens to retain. * Chat memory will retain as many of the most recent messages as can fit into `maxTokens`. * Messages are indivisible. If a message doesn't fit, it's discarded completely. * @param tokenizer A [Tokenizer] responsible for counting tokens in the messages. * @return builder */ fun maxTokens(maxTokens: Int, tokenizer: Tokenizer): Builder { this.maxTokens = maxTokens this.tokenizer = tokenizer return this } /** * @param store The chat memory store responsible for storing the chat memory state. * If not provided, an [InMemoryChatMemoryStore] will be used. * @return builder */ fun chatMemoryStore(store: ChatMemoryStore): Builder { this.store = store return this } fun build(): TokenWindowChatMemory { return TokenWindowChatMemory(this) } } companion object { private val log = LoggerFactory.getLogger(TokenWindowChatMemory::class.java) private fun findSystemMessage(messages: List<ChatMessage>): Optional<SystemMessage> { return messages.stream() .filter { message: ChatMessage? -> message is SystemMessage } .map { message: ChatMessage -> message as SystemMessage } .findAny() } private fun ensureCapacity(messages: MutableList<ChatMessage>, maxTokens: Int, tokenizer: Tokenizer) { var currentTokenCount = tokenizer.estimateTokenCountInMessages(messages) while (currentTokenCount > maxTokens) { var messageToRemove = 0 if (messages[0] is SystemMessage) { messageToRemove = 1 } val removedMessage: ChatMessage = messages.removeAt(messageToRemove) val tokenCountOfRemovedMessage = tokenizer.estimateTokenCountInMessage(removedMessage) log.trace("Removing the following message ({} tokens) to comply with the capacity requirements: {}", tokenCountOfRemovedMessage, removedMessage) currentTokenCount -= tokenCountOfRemovedMessage } } fun builder(): Builder { return Builder() } @JvmStatic fun withMaxTokens(maxTokens: Int, tokenizer: Tokenizer): TokenWindowChatMemory { return builder().maxTokens(maxTokens, tokenizer).build() } } }
0
Kotlin
0
0
1dc065a3aec804d53259171f6f95206eb2fdb0b6
5,065
langchainkt
Apache License 2.0
src/main/java/de/iteratec/officemap/exceptions/AlreadyExistsException.kt
iteratec
189,974,402
false
{"HTML": 55513, "Kotlin": 39109, "JavaScript": 21386, "CSS": 9749}
package de.iteratec.officemap.exceptions import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ResponseStatus @ResponseStatus(code = HttpStatus.NOT_ACCEPTABLE, reason = "Entry already exists or conflicting reservation") class AlreadyExistsException : RuntimeException()
0
HTML
0
1
8b326a9782beb35636bba231c6a871e93a38cd79
308
kotlin-training-officemap
Apache License 2.0
src/aoc2022/day01/AoC01.kt
Saxintosh
576,065,000
false
{"Kotlin": 30013}
package aoc2022.day01 import readAll fun main() { fun buildList(txt: String): List<Int> = txt .split("\n\n") .map { it.lines() .sumOf { line -> line.toInt() } } fun part1(txt: String): Int = buildList(txt).max() fun part2(txt: String): Int = buildList(txt).sortedDescending().take(3).sum() readAll(24000, 45000, ::part1, ::part2) }
0
Kotlin
0
0
877d58367018372502f03dcc97a26a6f831fc8d8
363
aoc2022
Apache License 2.0
src/main/kotlin/io/github/durun/lateko/model/structure/StructureExtension.kt
Durun
244,782,805
false
null
package io.github.durun.lateko.model.structure import io.github.durun.lateko.model.Format interface StructureExtension : StructureElement { override fun <R> accept(visitor: StructureVisitor<R>): R = visitor.visit(this) fun renderedAs(format: Format): String }
5
Kotlin
0
1
b5809e171acf41a804b2fbdb4ddb21185bd93e8b
263
lateko
MIT License
ChatroomUIKit/src/main/java/io/agora/chatroom/theme/UIType.kt
apex-wang
728,010,838
false
{"Kotlin": 497622}
package io.agora.chatroom.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp
0
Kotlin
0
0
20b1ff03d06d87d44565e322ccf9abced24264c5
253
test
MIT License
biometrics/src/main/java/com/markoid/biometrics/entities/PromptOptions.kt
knockmark10
217,366,017
false
null
package com.markoid.biometrics.entities import com.markoid.biometrics.states.SecurityLevel data class PromptOptions( val title: String = "Title", val subtitle: String = "Subtitle", val description: String = "Description", val negativeText: String = "Cancel", val securityLevel: SecurityLevel = SecurityLevel.STRONG, val confirmationRequired: Boolean = true )
0
Kotlin
0
0
8d2a0015603b717f17b8a40f19e0dcadf59d5ac7
384
FingerPrintLibrary
MIT License
src/Household.kt
danftang
249,291,624
false
null
import org.apache.commons.math3.distribution.EnumeratedDistribution import org.apache.commons.math3.util.Pair import java.util.function.BooleanSupplier import kotlin.collections.ArrayList import kotlin.random.Random class Household: ArrayList<InfectedAgent>, InfectionLocation { val totalSize: Int // From ONS, Households and Household Composition in England and Wales: 2001-11 constructor(): super(4) { totalSize = EnumeratedDistribution(listOf( Pair(1, 0.30245), Pair(2, 0.34229), Pair(3, 0.15587), Pair(4, 0.12972), Pair(5, 0.04643), Pair(6, 0.02324) )).sample() } fun nUninfected() = totalSize - this.size }
0
Kotlin
0
0
d0c267721f01bc7e3a8912a1e281d53f95a2d42a
722
Covid19
MIT License
openai-client/openai-client-core/src/commonMain/kotlin/com/tddworks/openai/api/OpenAI.kt
tddworks
755,029,221
false
{"Kotlin": 221445}
package com.tddworks.openai.api import com.tddworks.di.getInstance import com.tddworks.openai.api.chat.api.Chat import com.tddworks.openai.api.images.api.Images import com.tddworks.openai.api.legacy.completions.api.Completion import com.tddworks.openai.api.legacy.completions.api.Completions interface OpenAI : Chat, Images, Completions { companion object { const val BASE_URL = "api.openai.com" } } class OpenAIApi : OpenAI, Chat by getInstance(), Images by getInstance(), Completions by getInstance()
0
Kotlin
0
4
5f4fefb1fb90859ee7620887e7e592af65a93408
525
openai-kotlin
Apache License 2.0
src/main/kotlin/com/xmppjingle/bjomeliga/api/SummariesController.kt
xmppjingle
367,998,368
false
null
package com.xmppjingle.bjomeliga.api import com.xmppjingle.bjomeliga.service.SummariesService import com.xmppjingle.bjomeliga.service.SummaryDTO import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* @RestController @CrossOrigin(origins = ["*"]) class SummariesController { var logger: Logger = LoggerFactory.getLogger(SummariesController::class.java) @Autowired lateinit var summariesService: SummariesService @PostMapping(value = ["/summary"]) fun processSummary(@RequestBody summaryDTO: SummaryDTO): ResponseEntity<String> { summariesService.addSummary(summaryDTO) return ResponseEntity.ok("OK") } @GetMapping(value = ["/summary/{id}"]) fun getSummary(@PathVariable(value = "id") id: String): SummaryDTO = summariesService.getSummary(id) }
1
Kotlin
4
4
21237750aa5482f950b17c72565019636e82bea0
967
banda
Apache License 2.0
app/src/main/java/com/talent/animescrap/animesources/AnimeSource.kt
fakeyatogod
371,491,492
false
{"Kotlin": 199041}
package com.talent.animescrap.animesources import com.talent.animescrap.model.AnimeDetails import com.talent.animescrap.model.AnimeStreamLink import com.talent.animescrap.model.SimpleAnime interface AnimeSource { suspend fun animeDetails(contentLink: String): AnimeDetails suspend fun searchAnime(searchedText: String): ArrayList<SimpleAnime> suspend fun latestAnime(): ArrayList<SimpleAnime> suspend fun trendingAnime(): ArrayList<SimpleAnime> suspend fun streamLink( animeUrl: String, animeEpCode: String, extras: List<String>? = null ): AnimeStreamLink }
25
Kotlin
22
290
6e99643d4b02d7164820ed7468e3201373694146
609
AnimeScrap
MIT License
src/test/kotlin/no/nav/familie/ef/iverksett/brukernotifikasjon/SendBrukernotifikasjonVedGOmregningTaskTest.kt
navikt
357,821,728
false
null
package no.nav.familie.ef.iverksett.brukernotifikasjon import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.mockkObject import io.mockk.runs import io.mockk.unmockkObject import io.mockk.verify import no.nav.familie.ef.iverksett.infrastruktur.transformer.toDomain import no.nav.familie.ef.iverksett.iverksetting.IverksettingRepository import no.nav.familie.ef.iverksett.lagIverksett import no.nav.familie.ef.iverksett.repository.findByIdOrThrow import no.nav.familie.ef.iverksett.util.mockFeatureToggleService import no.nav.familie.ef.iverksett.util.opprettIverksettDto import no.nav.familie.kontrakter.ef.felles.BehandlingÅrsak import no.nav.familie.prosessering.domene.Task import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.time.LocalDate import java.util.UUID class SendBrukernotifikasjonVedGOmregningTaskTest { private val iverksettingRepository = mockk<IverksettingRepository>() private val brukernotifikasjonKafkaProducer = mockk<BrukernotifikasjonKafkaProducer>() private val task = SendBrukernotifikasjonVedGOmregningTask(brukernotifikasjonKafkaProducer, iverksettingRepository, mockFeatureToggleService()) @BeforeEach internal fun setUp() { mockkObject(DatoUtil) every { iverksettingRepository.findByIdOrThrow(any()) } .returns(lagIverksett(opprettIverksettDto(behandlingId = UUID.randomUUID(), behandlingÅrsak = BehandlingÅrsak.G_OMREGNING).toDomain())) every { DatoUtil.dagensDato() } returns LocalDate.of(2023, 3, 1) } @AfterEach internal fun tearDown() { unmockkObject(DatoUtil) } @Test internal fun `doTask - skal publisere vedtak til kafka`() { every { brukernotifikasjonKafkaProducer.sendBeskjedTilBruker(any(), any()) } just runs task.doTask(Task(SendBrukernotifikasjonVedGOmregningTask.TYPE, UUID.randomUUID().toString())) verify(exactly = 1) { brukernotifikasjonKafkaProducer.sendBeskjedTilBruker(any(), any()) } } }
4
Kotlin
0
0
6945c18ac332f277ab2cda627b10507d323ecad3
2,063
familie-ef-iverksett
MIT License
korge/src/commonMain/kotlin/com/soywiz/korge/view/effect/Convolute3EffectView.kt
Wolwer1nE
268,762,840
true
{"Kotlin": 1972890, "Java": 182026, "Shell": 1955, "Batchfile": 1618}
package com.soywiz.korge.view.effect import com.soywiz.korag.* import com.soywiz.korag.shader.* import com.soywiz.korge.internal.* import com.soywiz.korge.view.* import com.soywiz.korge.view.filter.* import com.soywiz.korma.geom.* @KorgeDeprecated @Deprecated("Use View.filter instead") class Convolute3EffectView(val kernel: Matrix3D) : EffectView() { companion object { private val u_Weights = Uniform("weights", VarType.Mat3) val KERNEL_GAUSSIAN_BLUR get() = Convolute3Filter.KERNEL_GAUSSIAN_BLUR val KERNEL_BOX_BLUR get() = Convolute3Filter.KERNEL_BOX_BLUR val KERNEL_IDENTITY get() = Convolute3Filter.KERNEL_IDENTITY val KERNEL_EDGE_DETECTION get() = Convolute3Filter.KERNEL_EDGE_DETECTION } val weights by uniforms.storageForMatrix3D(u_Weights, kernel) init { borderEffect = 1 fragment = FragmentShader { DefaultShaders { out setTo vec4(0f.lit, 0f.lit, 0f.lit, 0f.lit) for (y in 0 until 3) { for (x in 0 until 3) { out setTo out + (tex(fragmentCoords + vec2((x - 1).toFloat().lit, (y - 1).toFloat().lit))) * u_Weights[x][y] } } } } } } @KorgeDeprecated @Deprecated("Use View.filter instead") inline fun Container.convolute3EffectView( kernel: Matrix3D = Matrix3D(), callback: @ViewsDslMarker Convolute3EffectView.() -> Unit = {} ) = Convolute3EffectView(kernel).addTo(this).apply(callback)
0
null
0
0
bc4cfa3914518e8588f1146eec6ea9bf76ca1095
1,361
korge
Apache License 2.0
data/network/src/main/kotlin/com/louisfn/somovie/data/network/datasource/MovieRemoteDataSource.kt
LouisFn
571,351,948
false
null
package com.louisfn.somovie.data.network.datasource import androidx.annotation.AnyThread import com.louisfn.somovie.data.network.ApiServiceExecutor import com.louisfn.somovie.data.network.HttpException import com.louisfn.somovie.data.network.StatusCode.RESOURCE_REQUESTED_NOT_FOUND import com.louisfn.somovie.data.network.response.MovieAccountStateResponse import com.louisfn.somovie.data.network.response.MovieDetailsResponse import com.louisfn.somovie.data.network.response.MovieResponse import com.louisfn.somovie.data.network.response.PaginatedResultsResponse import com.louisfn.somovie.domain.exception.MovieNotFoundException import com.louisfn.somovie.domain.model.ExploreCategory import javax.inject.Inject interface MovieRemoteDataSource { @AnyThread suspend fun getMovies( category: ExploreCategory, page: Int ): PaginatedResultsResponse<MovieResponse> @AnyThread suspend fun getPopular(page: Int): PaginatedResultsResponse<MovieResponse> @AnyThread suspend fun getNowPlaying(page: Int): PaginatedResultsResponse<MovieResponse> @AnyThread suspend fun getTopRated(page: Int): PaginatedResultsResponse<MovieResponse> @AnyThread suspend fun getUpcoming(page: Int): PaginatedResultsResponse<MovieResponse> @AnyThread suspend fun getMovieDetails(movieId: Long): MovieDetailsResponse @AnyThread suspend fun getMovieAccountStates(movieId: Long): MovieAccountStateResponse } internal class DefaultMovieRemoteDataSource @Inject constructor( private val executor: ApiServiceExecutor ) : MovieRemoteDataSource { override suspend fun getMovies( category: ExploreCategory, page: Int ): PaginatedResultsResponse<MovieResponse> = when (category) { ExploreCategory.UPCOMING -> getUpcoming(page) ExploreCategory.NOW_PLAYING -> getNowPlaying(page) ExploreCategory.TOP_RATED -> getTopRated(page) ExploreCategory.POPULAR -> getPopular(page) } override suspend fun getPopular(page: Int): PaginatedResultsResponse<MovieResponse> = executor.execute { it.getPopularMovies(page) } override suspend fun getNowPlaying(page: Int): PaginatedResultsResponse<MovieResponse> = executor.execute { it.getNowPlayingMovies(page) } override suspend fun getTopRated(page: Int): PaginatedResultsResponse<MovieResponse> = executor.execute { it.getTopRatedMovies(page) } override suspend fun getUpcoming(page: Int): PaginatedResultsResponse<MovieResponse> = executor.execute { it.getUpcomingMovies(page) } override suspend fun getMovieDetails(movieId: Long): MovieDetailsResponse = executor.execute(mapHttpException = ::mapHttpException) { it.getMovieDetails(movieId) } override suspend fun getMovieAccountStates(movieId: Long): MovieAccountStateResponse = executor.execute(mapHttpException = ::mapHttpException) { it.getMovieAccountStates(movieId) } @AnyThread private fun mapHttpException(e: HttpException) = when (e.statusCode) { RESOURCE_REQUESTED_NOT_FOUND -> MovieNotFoundException() else -> null } }
3
null
6
23
772c90cf46e0056d826344b1f95c559b8101de2d
3,301
SoMovie
MIT License
kotaro/src/commonMain/kotlin/math/Vector3f.kt
Pengiie
411,461,323
false
{"Kotlin": 221838}
package dev.pengie.kotaro.math import kotlin.math.sqrt open class Vector3f(x: Float, y: Float, z: Float) : Vector3<Float>(x, y, z, ArithmeticFloat) { constructor() : this(0f) constructor(value: Float) : this(value, value, value) override fun copy(x: Float, y: Float, z: Float): Vector3<Float> = Vector3f(x, y, z) //override fun plus(left: Float, right: Float): Float = left + right //override fun minus(left: Float, right: Float): Float = left - right //override fun times(left: Float, right: Float): Float = left * right fun length(): Float = sqrt(x*x + y*y + z*z) fun normalize(): Vector3f = this.copy().apply { val length = length() if(length == 0f) return@apply x /= length y /= length z /= length }.toVector3f() override fun toString(): String = "[$x, $y, $z]" companion object { val forward = Vector3f(0f, 0f, -1f) val right = Vector3f(1f, 0f, 0f) val up = Vector3f(0f, 1f, 0f) fun dot(left: Vector3f, right: Vector3f): Float = left.x * right.x + left.y * right.y + left.z * right.z fun cross(left: Vector3f, right: Vector3f): Vector3f = Vector3f( left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x ) } } fun Vector3<Float>.toVector3f(): Vector3f = this as Vector3f
0
Kotlin
1
0
5acefd9beeede767708a666d2b55021369c9a020
1,460
kotarOld
Apache License 2.0