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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
input_print.kt | JehanKandy | 439,512,444 | false | null |
//print user input values
//impport java scanner
import java.util.Scanner
fun main() {
//set the scanner
val read = Scanner(System.`in`)
println("Enter any Number : ")
//get the input enterded by user
var num = read.nextInt()
println("Your entered Number is "+num)
}
| 0 | Kotlin | 0 | 9 | 6bbd05127075d6eacc2f4ba3b9053a743669c2b1 | 310 | Kotlin-User-input-valuse | MIT License |
design/src/main/java/com/globant/design/theme/Color.kt | johannfjs | 716,976,358 | false | {"Kotlin": 77752} | package com.globant.design.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val White = Color(0xFFFFFFFF)
val Yellow = Color(0xFFF6C700)
val Gray = Color(0xFF9D9C9C)
val DarkGray = Color(0xFF4B4747)
val LightGray = Color(0xFFF5F5F5)
| 0 | Kotlin | 0 | 0 | 37729c911f39a355f8d0724e6a62de0f958b113e | 438 | MovieDbChallenge | Apache License 2.0 |
app/src/main/java/com/ingjuanocampo/jstunner/ui/main/JobSchedulerFragment.kt | ingjuanocampo | 241,919,309 | false | null | package com.ingjuanocampo.jstunner.ui.main
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context.JOB_SCHEDULER_SERVICE
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.ingjuanocampo.jstunner.R
import com.ingjuanocampo.jstunner.NotificationJobService
import kotlinx.android.synthetic.main.job_scheduler_fragment.*
import java.util.concurrent.TimeUnit
class JobSchedulerFragment : Fragment() {
companion object {
fun newInstance() = JobSchedulerFragment()
}
private lateinit var viewModel: JobSchedulerViewModel
private val JOB_ID = 0
private var mScheduler: JobScheduler? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.job_scheduler_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(JobSchedulerViewModel::class.java)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mScheduler = requireContext().getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
// Updates the TextView with the value from the seekbar.
// Updates the TextView with the value from the seekbar.
seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
if (i > 0) {
seekBarProgress.text = getString(R.string.seconds, i)
} else {
seekBarProgress.setText(R.string.not_set)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
scheduleJob.setOnClickListener { scheduleJob() }
cancelJob.setOnClickListener { cancelJobs() }
}
fun scheduleJob() {
val selectedNetworkID = networkOptions.checkedRadioButtonId
var selectedNetworkOption = JobInfo.NETWORK_TYPE_NONE
val seekBarSet = seekBar.progress > 0
when (selectedNetworkID) {
R.id.noNetwork -> selectedNetworkOption = JobInfo.NETWORK_TYPE_NONE
R.id.anyNetwork -> selectedNetworkOption = JobInfo.NETWORK_TYPE_ANY
R.id.wifiNetwork -> selectedNetworkOption = JobInfo.NETWORK_TYPE_UNMETERED
}
val serviceName = ComponentName(
activity?.packageName!!,
NotificationJobService::class.java.name
)
val builder = JobInfo.Builder(JOB_ID, serviceName)
.setRequiredNetworkType(selectedNetworkOption)
.setRequiresDeviceIdle(idleSwitch.isChecked)
.setRequiresCharging(chargingSwitch.isChecked)
builder.setPeriodic(TimeUnit.HOURS.toMillis(getHoursPeriod().toLong()))
if (seekBarSet) {
builder.setOverrideDeadline(seekBar.progress * 1000.toLong())
}
val constraintSet = ((selectedNetworkOption
!= JobInfo.NETWORK_TYPE_NONE) || chargingSwitch.isChecked
|| idleSwitch.isChecked
|| seekBarSet)
if (constraintSet) {
val myJobInfo = builder.build()
mScheduler!!.schedule(myJobInfo)
Toast.makeText(requireContext(), R.string.job_scheduled, Toast.LENGTH_SHORT)
.show()
} else {
Toast.makeText(
requireContext(), R.string.no_constraint_toast,
Toast.LENGTH_SHORT
).show()
}
}
private fun getHoursPeriod(): Int {
return if (hoursPeriod.text.isNotBlank()) {
Integer.valueOf(hoursPeriod.text.toString())
} else {
24
}
}
/**
* onClick method for cancelling all existing jobs.
*/
fun cancelJobs() {
if (mScheduler != null) {
mScheduler!!.cancelAll()
mScheduler = null
Toast.makeText(requireContext(), R.string.jobs_canceled, Toast.LENGTH_SHORT)
.show()
}
}
}
| 0 | Kotlin | 0 | 0 | 097d0f92a761435044c24b2e91bbadd0560f68d9 | 4,597 | JobSchedulerTunner | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/ui/data/Market.kt | QArtur99 | 347,486,797 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.data
data class Market(val name: String, val isArrow: Boolean)
val marketList = listOf(
Market("Week", true),
Market("ETFs", false),
Market("Stocks", false),
Market("Founds", false),
Market("Futures", false),
Market("Bounds", false),
Market("Currencies", false),
)
| 0 | Kotlin | 0 | 0 | 85c83c20e2cc173387202699e8630562fa26e81c | 954 | WeTrade | Apache License 2.0 |
src/main/kotlin/com/github/nenadjakic/eav/dto/converter/EntityRequestToEntityConverter.kt | nenadjakic | 782,709,579 | false | {"Kotlin": 71560} | package com.github.nenadjakic.eav.dto.converter
import com.github.nenadjakic.eav.dto.EntityAddRequest
import com.github.nenadjakic.eav.entity.Entity
import org.modelmapper.AbstractConverter
class EntityRequestToEntityConverter : AbstractConverter<EntityAddRequest, Entity>() {
override fun convert(source: EntityAddRequest?): Entity {
val destination = Entity()
destination.id = null
destination.name = source!!.name
destination.description = source.description
return destination
}
} | 0 | Kotlin | 0 | 1 | 34fd301afc4621e0e87e658486cb64a9a3b87e8e | 536 | eav-platform | MIT License |
ZKSDK/src/main/java/com.zkteam.sdk/base/ZKBaseFragment.kt | ZhuoKeTeam | 194,787,004 | false | null | package com.zkteam.sdk.base
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.ClickUtils
abstract class ZKBaseFragment : Fragment(), IZKBaseView {
companion object {
const val STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN"
}
private val mClickListener = View.OnClickListener { v -> onDebouncingClick(v) }
lateinit var mActivity: Activity
lateinit var mInflater: LayoutInflater
lateinit var mContentView: View
override fun onAttach(context: Context) {
super.onAttach(context)
mActivity = context as Activity
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
val isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN)
val ft = fragmentManager!!.beginTransaction()
if (isSupportHidden) {
ft.hide(this)
} else {
ft.show(this)
}
ft.commitAllowingStateLoss()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mInflater = inflater
setRootLayout(getLayoutId())
return mContentView
}
@SuppressLint("ResourceType")
open fun setRootLayout(@LayoutRes layoutId: Int) {
if (layoutId <= 0) return
mContentView = mInflater.inflate(layoutId, null)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initViews(mContentView)
initListener()
initLifecycleObserve()
val bundle = arguments
initData(bundle)
}
override fun onDestroyView() {
val viewParent = mContentView.parent
if (viewParent != null) {
(viewParent as ViewGroup).removeView(mContentView)
}
super.onDestroyView()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(Companion.STATE_SAVE_IS_HIDDEN, isHidden)
}
fun applyDebouncingClickListener(vararg views: View) {
ClickUtils.applyGlobalDebouncing(views, mClickListener)
}
fun <T : View> findViewById(@IdRes id: Int): T {
return mContentView.findViewById(id)
}
} | 0 | Kotlin | 0 | 2 | e4803e5c96841217d3f817b7b478c78423c46c03 | 2,660 | ZKSDK | Apache License 2.0 |
funcify-feature-eng-data-source/src/main/kotlin/funcify/feature/datasource/tracking/TrackableJsonValuePublisher.kt | anticipasean | 458,910,592 | false | null | package funcify.feature.datasource.tracking
import com.fasterxml.jackson.databind.JsonNode
/**
*
* @author smccarron
* @created 2022-09-05
*/
fun interface TrackableJsonValuePublisher {
fun publishTrackableJsonValue(trackableJsonValue: TrackableValue<JsonNode>)
}
| 0 | Kotlin | 0 | 0 | 202a13324edc1d477c82b3de54a55a4cb72669ad | 275 | funcify-feature-eng | Apache License 2.0 |
src/main/kotlin/com/epam/brn/controller/AudiometryHistoryController.kt | Brain-up | 216,092,521 | false | {"Kotlin": 1057933, "Handlebars": 512629, "TypeScript": 401203, "JavaScript": 168755, "HTML": 45401, "CSS": 30742, "SCSS": 27412, "RAML": 22982, "Makefile": 545, "Shell": 405, "Dockerfile": 185} | package com.epam.brn.controller
import com.epam.brn.dto.request.AudiometryHistoryRequest
import com.epam.brn.dto.response.BrnResponse
import com.epam.brn.enums.BrnRole
import com.epam.brn.service.AudiometryHistoryService
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.http.ResponseEntity
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.annotation.security.RolesAllowed
@RestController
@RequestMapping("/audiometry-history")
@Tag(name = "Audiometry History", description = "Contains actions for audiometry history")
@RolesAllowed(BrnRole.USER)
class AudiometryHistoryController(private val audiometryHistoryService: AudiometryHistoryService) {
@PostMapping
@Operation(summary = "Save speech audiometry history")
fun save(@Validated @RequestBody audiometryHistory: AudiometryHistoryRequest): ResponseEntity<BrnResponse<Long>> =
ResponseEntity.ok().body(BrnResponse(data = audiometryHistoryService.save(audiometryHistory)))
}
| 114 | Kotlin | 26 | 61 | 310cfcae2b9780740554396271444388258ce8da | 1,285 | brn | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/breezeuttamseeds/features/newcollection/model/NewCollectionListResponseModel.kt | DebashisINT | 809,659,083 | false | {"Kotlin": 14710752, "Java": 1021518} | package com.breezeuttamseeds.features.newcollection.model
import com.breezeuttamseeds.app.domain.CollectionDetailsEntity
import com.breezeuttamseeds.base.BaseResponse
import com.breezeuttamseeds.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 | 1b2cedec9da3033f8c88cb67000fda67f0094619 | 514 | UttamSeeds | Apache License 2.0 |
plugins/disablefeed/src/main/kotlin/disablefeed/Plugin.kt | pluginloader | 354,578,063 | false | null | package disablefeed
import org.bukkit.event.entity.FoodLevelChangeEvent
import pluginloader.api.Listener
import pluginloader.api.Load
import pluginloader.api.onlinePlayers
@Load
internal fun onLoad(){
onlinePlayers.forEach{it.foodLevel = 20}
}
@Listener
internal fun onFeed(event: FoodLevelChangeEvent){
event.foodLevel = 20
} | 0 | Kotlin | 0 | 0 | 85942ebdb9f65a5c57ec93285703464cac41a4b8 | 337 | mono | MIT License |
app/src/main/java/com/wreckingballsoftware/forecastfrenzy/ui/results/content/ScoreContent.kt | leewaggoner | 742,904,254 | false | {"Kotlin": 77711} | package com.wreckingballsoftware.forecastfrenzy.ui.results
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.wreckingballsoftware.forecastfrenzy.R
import com.wreckingballsoftware.forecastfrenzy.ui.results.models.GameResultsState
import com.wreckingballsoftware.forecastfrenzy.ui.theme.dimensions
import com.wreckingballsoftware.forecastfrenzy.ui.theme.forecastTypography
@Composable
fun ScoreContent(
modifier: Modifier = Modifier,
state: GameResultsState,
) {
Column(
modifier = modifier.then(Modifier.fillMaxSize()),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = stringResource(id = R.string.you_bet, state.bet),
style = MaterialTheme.forecastTypography.bodyCentered,
)
Spacer(modifier = Modifier.height(MaterialTheme.dimensions.spaceMedium))
Text(
text = stringResource(id = R.string.score_for_round),
style = MaterialTheme.forecastTypography.bodyCentered,
)
Text(
text = "${state.roundScore} plus time bonus ${state.timeBonus}",
style = MaterialTheme.forecastTypography.titleCentered,
)
Spacer(modifier = Modifier.height(MaterialTheme.dimensions.spaceMedium))
Text(
text = stringResource(id = R.string.total_score),
style = MaterialTheme.forecastTypography.bodyCentered,
)
Text(
text = state.totalScore.toString(),
style = MaterialTheme.forecastTypography.headline,
)
}
}
@Preview
@Composable
fun ScoreContentPreview() {
ScoreContent(
state = GameResultsState(
bet = 100,
roundScore = 100,
timeBonus = 10,
totalScore = 1110,
)
)
} | 0 | Kotlin | 0 | 0 | fcf6816a86149ebc403fe31dc713ef97f30b18d5 | 2,246 | forecastfrenzy | Apache License 2.0 |
app/src/main/java/gq/kirmanak/mealient/data/baseurl/VersionDataSource.kt | kirmanak | 431,195,533 | false | {"Kotlin": 461809} | package gq.kirmanak.mealient.data.baseurl
import gq.kirmanak.mealient.datasource.models.VersionInfo
interface VersionDataSource {
suspend fun getVersionInfo(): VersionInfo
} | 9 | Kotlin | 1 | 70 | 888783bf149b950030691e978d3a128119d20ad6 | 180 | Mealient | MIT License |
core/src/main/java/com/ricknout/rugbyranker/core/ui/SpaceItemDecoration.kt | Anhmike | 215,666,476 | true | {"Kotlin": 262314} | package com.ricknout.rugbyranker.core.ui
import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.core.content.res.getDimensionPixelSizeOrThrow
import androidx.core.content.withStyledAttributes
import androidx.recyclerview.widget.RecyclerView
import com.ricknout.rugbyranker.core.R
class SpaceItemDecoration(context: Context) : RecyclerView.ItemDecoration() {
private var paddingTop: Int = 0
private var paddingHorizontal: Int = 0
init {
context.withStyledAttributes(
R.style.ItemDecoration_RugbyRanker_Space,
R.styleable.SpaceItemDecoration
) {
paddingTop = getDimensionPixelSizeOrThrow(R.styleable.SpaceItemDecoration_android_paddingTop)
paddingHorizontal = getDimensionPixelSizeOrThrow(R.styleable.SpaceItemDecoration_paddingHorizontal)
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
outRect.set(paddingHorizontal, paddingTop, paddingHorizontal, 0)
}
}
| 0 | null | 0 | 1 | 53c1889a127ff797c4df9b7651ddc2ddf58546c0 | 1,080 | rugby-ranker | Apache License 2.0 |
oauth2-authorization-server-starter/src/main/kotlin/com/labijie/infra/oauth2/authentication/ResourceOwnerPasswordAuthenticationToken.kt | hongque-pro | 308,310,231 | false | null | package com.labijie.infra.oauth2.authentication
import org.springframework.security.authentication.AbstractAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.oauth2.core.AuthorizationGrantType
import java.util.*
import kotlin.collections.HashSet
class ResourceOwnerPasswordAuthenticationToken(
private val grantType: AuthorizationGrantType,
private val clientPrincipal: Authentication,
scopes: Set<String>?,
additionalParameters: Map<String, Any>?
) :
AbstractAuthenticationToken(Collections.emptyList()) {
/**
* Returns the requested scope(s).
*
* @return the requested scope(s), or an empty `Set` if not available
*/
val scopes: Set<String> = scopes ?: HashSet()
/**
* Returns the additional parameters.
*
* @return the additional parameters
*/
val additionalParameters: Map<String, Any> = additionalParameters?: mapOf()
override fun getPrincipal(): Any {
return clientPrincipal
}
private val credentials: Any = ""
override fun getCredentials(): Any {
return credentials
}
companion object {
private const val serialVersionUID = -6067207202119450764L
}
} | 0 | Kotlin | 0 | 4 | fc246e708730419c80db5000e6e154ba23ec5b69 | 1,255 | infra-oauth2 | Apache License 2.0 |
oauth2-authorization-server-starter/src/main/kotlin/com/labijie/infra/oauth2/authentication/ResourceOwnerPasswordAuthenticationToken.kt | hongque-pro | 308,310,231 | false | null | package com.labijie.infra.oauth2.authentication
import org.springframework.security.authentication.AbstractAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.oauth2.core.AuthorizationGrantType
import java.util.*
import kotlin.collections.HashSet
class ResourceOwnerPasswordAuthenticationToken(
private val grantType: AuthorizationGrantType,
private val clientPrincipal: Authentication,
scopes: Set<String>?,
additionalParameters: Map<String, Any>?
) :
AbstractAuthenticationToken(Collections.emptyList()) {
/**
* Returns the requested scope(s).
*
* @return the requested scope(s), or an empty `Set` if not available
*/
val scopes: Set<String> = scopes ?: HashSet()
/**
* Returns the additional parameters.
*
* @return the additional parameters
*/
val additionalParameters: Map<String, Any> = additionalParameters?: mapOf()
override fun getPrincipal(): Any {
return clientPrincipal
}
private val credentials: Any = ""
override fun getCredentials(): Any {
return credentials
}
companion object {
private const val serialVersionUID = -6067207202119450764L
}
} | 0 | Kotlin | 0 | 4 | fc246e708730419c80db5000e6e154ba23ec5b69 | 1,255 | infra-oauth2 | Apache License 2.0 |
sql/src/main/kotlin/com/smeup/dbnative/sql/SQLUtils.kt | smeup | 307,311,436 | false | {"Kotlin": 333056, "Java": 4787, "Shell": 167} | /*
* Copyright 2020 The Reload project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.smeup.dbnative.sql
import com.smeup.dbnative.file.Record
import com.smeup.dbnative.file.RecordField
fun String.insertSQL(record: Record): String {
val names = record.keys.joinToString { it }
val questionMarks = record.keys.joinToString { "?" }
return "INSERT INTO $this ($names) VALUES($questionMarks)"
}
fun String.updateSQL(record: Record): String {
val namesAndQuestionMarks = record.keys.joinToString { "$it = ?" }
val wheres = record.keys.toList()
val comparations = List(record.size) { Comparison.EQ }
return "UPDATE $this SET $namesAndQuestionMarks ${whereSQL(wheres, comparations)}"
}
fun String.deleteSQL(record: Record): String {
val wheres = record.keys.toList()
val comparations = List(record.size) { Comparison.EQ }
return "DELETE FROM $this ${whereSQL(wheres, comparations)}"
}
fun orderBySQL(keysNames: List<String>, reverse: Boolean = false): String =
if (keysNames.isEmpty()) {
""
} else {
if (reverse) {
"ORDER BY " + keysNames.joinToString(separator = " DESC, ", postfix = " DESC")
} else {
"ORDER BY " + keysNames.joinToString()
}
}
fun whereSQL(wheres: List<String>, comparations: List<Comparison>): String {
return if (wheres.isEmpty()) {
""
} else {
var result = "WHERE "
wheres.forEachIndexed { index, _ -> result += wheres[index] + " " + comparations[index].symbol + " ? AND " }
return result.removeSuffix("AND ")
}
}
fun filePartSQLAndValues(
tableName: String,
movingForward: Boolean,
fileKeys: List<String>,
keys: List<RecordField>,
withEquals: Boolean
): Pair<MutableList<String>, String> {
val queries = mutableListOf<String>()
val values = mutableListOf<String>()
var keys2 = keys
val keys2Size = keys2.size
do {
var lastComparison = if (movingForward) {
Comparison.GT
} else {
Comparison.LT
}
val comparisons = mutableListOf<Comparison>()
keys2.forEachIndexed { index, _ ->
if (index < keys2.size - 1) {
comparisons.add(Comparison.EQ)
} else {
if (keys2.size == keys2Size && withEquals) {
if (lastComparison == Comparison.GT) {
lastComparison = Comparison.GE
} else if (lastComparison == Comparison.LT) {
lastComparison = Comparison.LE
}
}
comparisons.add(lastComparison)
}
}
val sql = "(SELECT * FROM $tableName ${whereSQL(
keys2.map { it.name },
comparisons
)})"
values.addAll(keys2.map { it.value.toString() })
queries.add(sql)
keys2 = keys2.subList(0, keys2.size - 1)
} while (keys2.isNotEmpty())
val sql = queries.joinToString(" UNION ") + " " + orderBySQL(
fileKeys,
reverse = !movingForward
)
return Pair(values, sql)
}
enum class Comparison(val symbol: String) {
EQ("="),
NE("<>"),
GT(">"),
GE(">="),
LT("<"),
LE("<=");
}
fun createMarkerSQL(keysNames: List<String>): String =
if (keysNames.isEmpty()) {
""
} else {
// in HSQLDB CONCAT needs at least two params!
if (keysNames.size == 1) {
"CONCAT( " + keysNames.joinToString() + ", '') AS NATIVE_ACCESS_MARKER"
} else {
"CONCAT( " + keysNames.joinToString() + ") AS NATIVE_ACCESS_MARKER"
}
}
fun calculateMarkerValue(
keys: List<RecordField>,
movingForward: Boolean = true,
withEquals: Boolean = true
): String =
if (keys.isEmpty()) {
""
} else {
val padChar = if (movingForward) {
' '
} else {
'Z'
}
// NOTE: calculate max length of marker using primary fields max length (temp 100 but incorrect)
if (withEquals) {
keys.joinToString("") { it.value }.padEnd(100, padChar)
} else {
keys.joinToString("") { it.value }
}
}
fun markerWhereSQL(movingForward: Boolean, withEquals: Boolean): String {
val comparison = if (movingForward && !withEquals) {
Comparison.GT
} else if (movingForward && withEquals) {
Comparison.GE
} else if (!movingForward && !withEquals) {
Comparison.LT
} else {
Comparison.LE
}
return " WHERE NATIVE_ACCESS_MARKER ${comparison.symbol} ? "
}
| 1 | Kotlin | 1 | 5 | c2df8f99c6cfe729f58563f18fd70a3ea1229fb8 | 5,171 | reload | Apache License 2.0 |
core/src/main/java/com/nicktra/moviedex/core/data/source/remote/response/MovieResponse.kt | nicktra | 461,232,627 | false | null | package com.arya.movieapp.core.data.source.remote.response
import com.google.gson.annotations.SerializedName
data class MovieResponse (
@field:SerializedName("id")
val id: Int,
@field:SerializedName("title")
val title: String,
@field:SerializedName("overview")
val overview: String,
@field:SerializedName("release_date")
val releaseDate: String,
@field:SerializedName("vote_average")
val voteAverage: Float,
@field:SerializedName("popularity")
val popularity: Float,
@field:SerializedName("original_language")
val originalLanguage: String,
@field:SerializedName("poster_path")
val posterPath: String,
@field:SerializedName("backdrop_path")
val backdropPath: String,
) | 0 | Kotlin | 0 | 0 | 4f6769d5bb1beebce97cb517fa810a6ab0ecccdb | 751 | moviedex | MIT License |
app/src/main/java/com/wreckingballsoftware/magicdex/ui/magicdex/MagicDexScreen.kt | leewaggoner | 851,182,076 | false | {"Kotlin": 15288} | package com.wreckingballsoftware.magicdex.ui.magicdex
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.wreckingballsoftware.magicdex.ui.navigation.NavGraph
import org.koin.androidx.compose.getViewModel
@Composable
fun MagicDexScreen(
navGraph: NavGraph,
viewModel: MagicDexViewModel = getViewModel(),
) {
Column {
Column(
modifier = Modifier
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text("Magic Dex Screen")
}
}
} | 0 | Kotlin | 0 | 0 | 28385adff3fea07bc0fee90d85574d727265c408 | 898 | magicdex | Apache License 2.0 |
app/src/androidTest/java/com/initiatetech/initiate_news/RegisterActivityTests.kt | Gemnnn | 747,026,324 | false | {"Kotlin": 104052} | package com.initiatetech.initiate_news
import androidx.test.espresso.Espresso.closeSoftKeyboard
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import com.google.firebase.Firebase
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.auth.auth
import com.initiatetech.initiate_news.register.OtpActivity
import com.initiatetech.initiate_news.register.RegisterActivity
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class RegisterActivityTests {
@get:Rule
val intentsTestRule = IntentsTestRule(RegisterActivity::class.java)
@Test
fun TC_REGISTER_001_RegisterSuccess() {
// Enter a valid email and password
onView(withId(R.id.editTextEmail)).perform(typeText("<EMAIL>"))
closeSoftKeyboard()
onView(withId(R.id.editTextPassword)).perform(typeText("<PASSWORD>"))
closeSoftKeyboard()
// Click register
onView(withId(R.id.buttonRegister)).perform(click())
// Assert that the most recent intent was for OtpActivity
Intents.getIntents().also { intents ->
assertThat(intents).isNotEmpty()
val mostRecentIntent = intents[intents.size - 1] // Get the most recent intent
assertThat(mostRecentIntent.component?.className).isEqualTo(OtpActivity::class.java.name)
}
}
@Test
fun TC_REGISTER_002_RegisterFailEmptyEmailAndPassword() {
// Type a valid email with no password entered
onView(withId(R.id.editTextEmail)).perform(typeText("<EMAIL>"))
// Click register button
onView(withId(R.id.buttonRegister)).perform(click())
// Assert that the intent never moved from RegisterActivity
assertThat(Intents.getIntents()).isEmpty()
}
@Test
fun TC_REGISTER_003_RegisterFailInvalidEmail() {
// Type an invalid email (e.g., missing "@" symbol)
onView(withId(R.id.editTextEmail)).perform(typeText("invalidemail.com"))
// Type a valid password
onView(withId(R.id.editTextPassword)).perform(typeText("<PASSWORD>"))
// Click register button
onView(withId(R.id.buttonRegister)).perform(click())
// Assert that the intent never moved from RegisterActivity
assertThat(Intents.getIntents()).isEmpty()
}
} | 1 | Kotlin | 0 | 1 | 17ec6cb54af0fbcd8bac6973260eed4a42b4a1f7 | 2,759 | Initiate-News | MIT License |
app/src/main/java/com/nizarfadlan/storyu/di/module/StoryModule.kt | nizarfadlan | 797,397,406 | false | {"Kotlin": 148878} | package com.nizarfadlan.storyu.di.module
import com.nizarfadlan.storyu.data.datasource.StoryDataSource
import com.nizarfadlan.storyu.data.repository.StoryRepositoryImpl
import com.nizarfadlan.storyu.domain.repository.StoryRepository
import org.koin.dsl.module
val storyDataSourceModule = module {
single { StoryDataSource(get(), get()) }
}
val storyRepositoryImplModule = module {
factory<StoryRepository> { StoryRepositoryImpl(get()) }
} | 0 | Kotlin | 0 | 0 | 1b92fd28aae3b8bb13e70854eb889f5a2269ae69 | 449 | StoryU | MIT License |
app-compose/src/main/java/com/burrowsapps/pokedex/ui/pokemonlist/PokemonListScreen.kt | jaredsburrows | 805,424,982 | false | {"Kotlin": 75922} | @file:OptIn(ExperimentalMaterial3Api::class)
package com.burrowsapps.pokedex.ui.pokemonlist
import android.content.res.Configuration
import androidx.compose.foundation.clickable
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.burrowsapps.pokedex.R
import com.burrowsapps.pokedex.Screen
import com.burrowsapps.pokedex.data.api.model.PokemonEntry
import com.burrowsapps.pokedex.ui.common.TheToolbar
import com.burrowsapps.pokedex.ui.theme.PokedexTheme
import kotlinx.coroutines.flow.Flow
import java.util.Locale
@Preview(
name = "light",
showBackground = true,
device = Devices.PIXEL,
locale = "en",
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_NO,
)
@Preview(
name = "dark",
showBackground = true,
device = Devices.PIXEL,
locale = "en",
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_YES,
)
@Composable
private fun PokemonListScreenPreview(navController: NavHostController = rememberNavController()) {
PokedexTheme {
PokemonListScreen(navController)
}
}
@Composable
internal fun PokemonListScreen(navController: NavHostController) {
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(rememberTopAppBarState())
val viewModel = hiltViewModel<PokemonListViewModel>()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TheToolbar(
navController = navController,
scrollBehavior = scrollBehavior,
screenName = stringResource(id = R.string.pokemon_list_screen_title),
)
},
) { paddingValues ->
TheContent(
navController = navController,
innerPadding = paddingValues,
flow = viewModel.pokemonList,
)
}
}
@Composable
private fun TheContent(
navController: NavHostController,
innerPadding: PaddingValues,
flow: Flow<PagingData<PokemonEntry>>,
) {
val lazyPokemonItems = flow.collectAsLazyPagingItems()
Column(modifier = Modifier.padding(innerPadding)) {
when {
lazyPokemonItems.loadState.refresh is LoadState.Loading && lazyPokemonItems.itemCount == 0 -> {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
}
lazyPokemonItems.loadState.refresh is LoadState.Error && lazyPokemonItems.itemCount == 0 -> {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
val refreshErrorState = lazyPokemonItems.loadState.refresh as? LoadState.Error
Text(
text = "Error: ${refreshErrorState?.error}",
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
)
}
}
lazyPokemonItems.itemCount == 0 -> {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
text = "No Pokémon found!",
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center,
)
}
}
else -> {
val listState = rememberLazyListState()
LazyColumn(
state = listState,
modifier =
Modifier
.fillMaxSize()
.semantics { contentDescription = "List" },
) {
items(
count = lazyPokemonItems.itemCount,
key = lazyPokemonItems.itemKey { it.name },
) { index ->
val item = lazyPokemonItems[index]!!
PokemonListItem(navController = navController, pokemonEntry = item)
HorizontalDivider()
}
}
}
}
}
}
@Composable
fun PokemonListItem(
navController: NavController,
pokemonEntry: PokemonEntry,
) {
// Extract Pokémon number from URL
val pokemonNumber = pokemonEntry.url.dropLast(1).takeLastWhile { it.isDigit() }
// TODO: Use the official artwork URL
// Prepare the image URL
// val imageUrl =
// "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/$pokemonNumber.png"
val imageUrl =
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/$pokemonNumber.png"
// https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/6.svg
val context = LocalContext.current
// Use Modifier.clickable for the entire Column and Modifier.indication for ripple effect
Column(
modifier =
Modifier
.fillMaxWidth()
.indication(
indication = rememberRipple(bounded = false),
interactionSource = remember { MutableInteractionSource() },
)
.clickable {
navController.navigate(Screen.PokemonInfo.route + "/${pokemonEntry.name}")
}
.padding(16.dp),
) {
Row(
modifier =
Modifier
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
// val requestBuilder =
// buildRequest(
// context = context,
// imageUrl = imageUrl,
// thumbnailUrl = imageUrl,
// override = 85.dp.value.roundToInt(),
// )
//
// // Provide local Glide request builder for GlideImage
// CompositionLocalProvider(LocalGlideRequestBuilder provides requestBuilder) {
// GlideImage(
// imageModel = { imageUrl },
// modifier =
// Modifier
// .size(85.dp)
// .padding(end = 16.dp),
// imageOptions = ImageOptions(contentScale = ContentScale.Crop),
// loading = {
// Box(modifier = Modifier.matchParentSize()) {
// CircularProgressIndicator(
// modifier = Modifier.align(Alignment.Center),
// )
// }
// },
// )
// }
Column(
modifier =
Modifier
.weight(1f)
.align(Alignment.CenterVertically),
) {
Text(
text = pokemonEntry.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() },
style = MaterialTheme.typography.titleLarge,
)
}
Icon(
imageVector = Icons.Filled.ChevronRight,
contentDescription = "Go to details",
modifier =
Modifier
.size(24.dp) // Match the XML icon size
.align(Alignment.CenterVertically),
// Center vertically in the row
)
}
}
}
| 0 | Kotlin | 0 | 0 | 6607e273572b3e0762091ab9fb9b78a2901021a0 | 8,584 | android-pokedex | Apache License 2.0 |
app/src/main/java/com/yunshen/yunapp/ui/componment/Notification.kt | yunshenOwO | 749,653,533 | false | {"Kotlin": 142659} | package com.yunshen.yunapp.ui.componment
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.accompanist.pager.VerticalPager
import com.google.accompanist.pager.rememberPagerState
import com.yunshen.yunapp.viewmodel.MainViewModel
import kotlinx.coroutines.launch
import java.util.Timer
import java.util.TimerTask
@Composable
fun Notification(vm:MainViewModel) {
val virtualCount = Int.MAX_VALUE
val actualCount = vm.notifications.size
val initCountIndex = virtualCount / 2
val pageSate = rememberPagerState(initialPage = initCountIndex)
val currency = rememberCoroutineScope()
val timer = Timer()
timer.schedule(object : TimerTask(){
override fun run() {
currency.launch { pageSate.animateScrollToPage(pageSate.currentPage + 1) }
}
}, 3000, 3000)
Row (modifier = Modifier
.padding(8.dp)
.clip(RoundedCornerShape(8.dp))
.background(Color(0xFF448486))
.height(45.dp)
.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween){
Text(text = "最新通知",
color = Color(0xff149EE7),
fontSize = 14.sp
)
Spacer(modifier = Modifier.width(8.dp))
VerticalPager(count = virtualCount,
modifier = Modifier.weight(1f),
state = pageSate,
horizontalAlignment = Alignment.Start) {
index ->
val actualIndex = (index - initCountIndex).floorMod(actualCount)// val actualIndex = index - (index.floorDiv(actualCount)) * actualCount
Text(text = vm.notifications[actualIndex],
color = Color(0xff333333),
fontSize = 14.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
Text(text = "更多",
color = Color(0xff666666),
fontSize = 14.sp)
}
} | 0 | Kotlin | 0 | 1 | 40045fead43576191d02eae7baf5c7a4a6f5e9e9 | 2,728 | yunApp | MIT License |
tasks-app-shared/src/commonMain/kotlin/net/opatry/tasks/app/ui/screen/aboutScreen.kt | opatry | 860,583,716 | false | {"Kotlin": 622220, "Shell": 11263, "HTML": 451, "Ruby": 196} | /*
* Copyright (c) 2024 Olivier Patry
*
* 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 net.opatry.tasks.app.ui.screen
import ChevronRight
import Copyright
import Earth
import Github
import LucideIcons
import ShieldCheck
import SquareArrowOutUpRight
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.unit.dp
import net.opatry.tasks.resources.Res
import net.opatry.tasks.resources.about_screen_app_version_subtitle
import net.opatry.tasks.resources.about_screen_credits_item
import net.opatry.tasks.resources.about_screen_github_item
import net.opatry.tasks.resources.about_screen_privacy_policy_item
import net.opatry.tasks.resources.about_screen_website_item
import org.jetbrains.compose.resources.stringResource
data class AboutApp(
val name: String,
val version: String,
val aboutLibrariesJsonProvider: suspend () -> String
)
enum class AboutScreenDestination {
About,
Credits,
}
@Composable
expect fun AboutScreen(aboutApp: AboutApp)
private const val TASKFOLIO_WEBSITE_URL = "https://opatry.github.io/taskfolio/"
private const val TASKFOLIO_GITHUB_URL = "https://github.com/opatry/taskfolio"
private const val TASKFOLIO_PRIVACY_POLICY_URL = "https://opatry.github.io/taskfolio/privacy-policy"
@Composable
fun AboutScreenContent(aboutApp: AboutApp, onNavigate: (AboutScreenDestination) -> Unit) {
val uriHandler = LocalUriHandler.current
LazyColumn {
item {
AboutExternalLink(stringResource(Res.string.about_screen_website_item), LucideIcons.Earth) {
uriHandler.openUri(TASKFOLIO_WEBSITE_URL)
}
}
item {
AboutExternalLink(stringResource(Res.string.about_screen_github_item), LucideIcons.Github) {
uriHandler.openUri(TASKFOLIO_GITHUB_URL)
}
}
item {
AboutExternalLink(stringResource(Res.string.about_screen_privacy_policy_item), LucideIcons.ShieldCheck) {
uriHandler.openUri(TASKFOLIO_PRIVACY_POLICY_URL)
}
}
item {
ListItem(
modifier = Modifier.clickable(onClick = { onNavigate(AboutScreenDestination.Credits) }),
leadingContent = { Icon(LucideIcons.Copyright, null) },
headlineContent = { Text(stringResource(Res.string.about_screen_credits_item)) },
trailingContent = { Icon(LucideIcons.ChevronRight, null) },
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun AboutScreenTopAppBar(appName: String, appVersion: String) {
TopAppBar(
title = {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(appName)
// FIXME How to style only the version part taking into account localization?
Text(stringResource(Res.string.about_screen_app_version_subtitle, appVersion), style = MaterialTheme.typography.labelSmall)
}
},
navigationIcon = { AppIcon() }
)
}
@Composable
private fun AppIcon() {
// TODO app icon in compose res
Box(
Modifier
.padding(8.dp)
.fillMaxHeight()
.aspectRatio(1f)
.clip(MaterialTheme.shapes.medium)
.background(Color(0xFF023232)),
contentAlignment = Alignment.Center
) {
Icon(
Icons.Outlined.CheckCircle,
null,
Modifier.fillMaxSize(.7f),
tint = Color(0xFF81FFDE)
)
}
}
@Composable
private fun AboutExternalLink(label: String, icon: ImageVector? = null, onClick: () -> Unit) {
ListItem(
modifier = Modifier.clickable(onClick = onClick),
leadingContent = {
if (icon != null) {
Icon(icon, null)
} else {
Spacer(Modifier.size(24.dp))
}
},
headlineContent = { Text(label) },
trailingContent = { Icon(LucideIcons.SquareArrowOutUpRight, null) },
)
}
| 4 | Kotlin | 0 | 2 | 38907f0e715ccb3c2408edc1f4de9db5f14af4ac | 6,282 | taskfolio | MIT License |
rest-api-server/src/main/kotlin/org/orkg/ContributorProvider.kt | TIBHannover | 197,416,205 | false | {"Kotlin": 6157312, "Cypher": 220623, "Python": 4881, "Shell": 2904, "Groovy": 1936, "HTML": 240, "Batchfile": 82} | package org.orkg
import org.orkg.auth.domain.Role
import org.orkg.auth.output.UserRepository
import org.orkg.common.PageRequests
import org.orkg.eventbus.EventBus
import org.orkg.eventbus.events.UserRegistered
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.stereotype.Component
@Component
class ContributorProvider(
private val eventBus: EventBus,
private val userRepository: UserRepository,
) : ApplicationRunner {
override fun run(args: ApplicationArguments?) {
userRepository.findAll(PageRequests.ALL).forEach { user ->
eventBus.post(
UserRegistered(
id = user.id.toString(),
displayName = user.displayName,
enabled = true,
email = user.email,
roles = user.roles.map { UserRegistered.Role.from(it.name.removePrefix("ROLE_")) }.toSet(),
createdAt = user.createdAt,
observatoryId = user.observatoryId?.toString(),
organizationId = user.organizationId?.toString(),
)
)
}
}
}
| 0 | Kotlin | 0 | 4 | 5f9f6b7de46ae07a9d3d94f00e4be12f707d72b0 | 1,208 | orkg-backend | MIT License |
app/src/main/java/com/example/chessboard_importer/repository/CameraModuleRepository.kt | MarcinGruchala | 374,996,433 | false | null | package com.example.chessboard_importer.repository
import android.graphics.Bitmap
object CameraModuleRepository {
var photoBitmap: Bitmap? = null
}
| 0 | Kotlin | 0 | 8 | d6722183e58701a34aafe626771d6c6f9656adcd | 154 | chessboard-importer-mobile | MIT License |
src/main/kotlin/no/nav/arrangor/ingest/model/Deltaker.kt | navikt | 632,334,837 | false | {"Kotlin": 198055, "PLpgSQL": 635, "Dockerfile": 152} | package no.nav.arrangor.ingest.model
import java.time.LocalDateTime
import java.util.UUID
data class Deltaker(
val id: UUID,
val status: DeltakerStatus,
)
data class DeltakerStatus(
val type: DeltakerStatusType,
val gyldigFra: LocalDateTime,
val opprettetDato: LocalDateTime,
)
enum class DeltakerStatusType {
VENTER_PA_OPPSTART,
DELTAR,
HAR_SLUTTET,
IKKE_AKTUELL,
FEILREGISTRERT,
SOKT_INN,
VURDERES,
VENTELISTE,
AVBRUTT,
FULLFORT,
PABEGYNT_REGISTRERING,
UTKAST_TIL_PAMELDING,
AVBRUTT_UTKAST,
}
val AVSLUTTENDE_STATUSER =
listOf(
DeltakerStatusType.HAR_SLUTTET,
DeltakerStatusType.FULLFORT,
DeltakerStatusType.IKKE_AKTUELL,
DeltakerStatusType.AVBRUTT,
)
val SKJULES_ALLTID_STATUSER =
listOf(
DeltakerStatusType.SOKT_INN,
DeltakerStatusType.VENTELISTE,
DeltakerStatusType.PABEGYNT_REGISTRERING,
DeltakerStatusType.FEILREGISTRERT,
DeltakerStatusType.UTKAST_TIL_PAMELDING,
DeltakerStatusType.AVBRUTT_UTKAST,
)
| 0 | Kotlin | 0 | 0 | d458df77fe4066fa978b02f2706710296afa38a0 | 955 | amt-arrangor | MIT License |
file-management/src/main/java/com/bluewhaleyt/file_management/core/FileExt.kt | BlueWhaleYT | 665,099,127 | false | null | package com.bluewhaleyt.file_management.core
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.util.Locale
fun Uri.toDocumentedUri(): Uri {
return DocumentsContract.buildDocumentUriUsingTree(this, DocumentsContract.getTreeDocumentId(this))
}
fun Uri.toRealFilePath(context: Context, fromDocumentTree: Boolean = false): String {
val uri = if (fromDocumentTree) this.toDocumentedUri() else this
return UriResolver.getPathFromUri(context, uri).toString()
}
fun String.getParentPath(): String? {
return File(this).parent
}
fun String.getFileExtension(): String? {
val dotIndex = this.lastIndexOf('.')
return if (dotIndex > 0 && dotIndex < this.length - 1) {
this.substring(dotIndex + 1)
} else null
}
fun String.getFileContent(wordWrap: Boolean = true): String {
val file = File(this)
val reader = BufferedReader(FileReader(file))
return if (wordWrap) reader.readLines().joinToString("\n")
else reader.readLines().toString()
}
fun String.getFileContentLineCount(): Int {
val file = File(this)
val reader = BufferedReader(FileReader(file))
return reader.readLines().size
}
fun List<File>.basicSort(): List<File> {
return this.sortedWith(compareBy(
{ if (it.isDirectory) 0 else 1 },
{ it.name.lowercase(Locale.ROOT) }
))
} | 0 | Kotlin | 0 | 1 | 24cad14d625908cb4d22a73e9ce07db40327d346 | 1,446 | WhaleUtils | MIT License |
app/src/main/java/com/lonard/camerlangproject/db/consultation/ExpertResponse.kt | lonard2 | 490,593,898 | false | null | package com.lonard.camerlangproject.db.consultation
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class ExpertResponse(
@field:SerializedName("data")
val data: List<ExpertDataItem>,
@field:SerializedName("status")
val status: String
): Parcelable
@Parcelize
data class ExpertDataItem(
@field:SerializedName("image")
val image: String,
@field:SerializedName("score")
val score: Double,
@field:SerializedName("updated_at")
val updatedAt: String,
@field:SerializedName("name")
val name: String,
@field:SerializedName("specialization")
val specialization: String,
@field:SerializedName("created_at")
val createdAt: String,
@field:SerializedName("id")
val id: Int,
@field:SerializedName("status")
val status: String
): Parcelable
| 0 | Kotlin | 2 | 2 | 52f69ed3312071307b5c8c9221a45ccdde6c7351 | 842 | CAMerlang-Mobile-Development | MIT License |
src/main/kotlin/com/allenti/ticketmanager/domain/service/assistant/AssistantService.kt | joaojunceira | 109,283,044 | false | null | package com.allenti.ticketmanager.domain.service.assistant
import com.allenti.ticketmanager.domain.model.Assistant
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Service
interface AssistantService {
fun create(assistantDetails: Assistant) : Mono<Assistant>
fun getByName(name: String?) : Flux<Assistant>
fun get(id: Long): Mono<Assistant>
fun update(assistantDetails: Assistant) : Mono<Boolean>
} | 1 | Kotlin | 0 | 0 | 03a70ae9e6933b760ec1bdbf02836d7d58c172cd | 472 | ticket-manager | Apache License 2.0 |
app/src/main/java/com/qwict/studyplanetandroid/presentation/screens/StudyScreen.kt | Qwict | 698,396,315 | false | {"Kotlin": 140916} | package com.qwict.studyplanetandroid.presentation.screens
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.qwict.studyplanetandroid.domain.model.Planet
import com.qwict.studyplanetandroid.presentation.components.AlertDialog
import com.qwict.studyplanetandroid.presentation.components.study.CustomCountDownTimer
import com.qwict.studyplanetandroid.presentation.viewmodels.StudyViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun ExplorerScreen(
onCancelStudyButtonClicked: () -> Unit = {},
isDiscovering: Boolean,
modifier: Modifier = Modifier,
selectedPlanet: Planet,
studyViewModel: StudyViewModel = hiltViewModel(),
selectedTimeInMinutes: Float,
) {
val openAlertDialog = remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val studyState by remember { studyViewModel.state }
var currentProgress by remember { mutableStateOf(0f) }
LaunchedEffect(true) {
scope.launch {
studyViewModel.resetAction()
Log.i("StudyViewModel", "Started studying, ${studyState.selectedPlanet.name} for $selectedTimeInMinutes minutes; Discovering: $isDiscovering")
studyState.updatedTime = selectedTimeInMinutes.toInt() * 60 * 1000
try {
studyState.selectedTime = selectedTimeInMinutes.toInt() * 60 * 1000
if (isDiscovering) {
studyViewModel.startDiscovering()
} else {
studyViewModel.startExploring()
}
loadProgress({ progress ->
currentProgress = progress
}, studyState.selectedTime.toLong())
if (isDiscovering) {
studyViewModel.stopDiscovering()
} else {
studyViewModel.stopExploring()
}
} catch (e: Exception) {
Log.i("ExplorerScreen", e.toString())
}
}
}
if (isDiscovering) {
}
Column {
ElevatedCard(
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp,
),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface,
),
modifier = Modifier
.fillMaxWidth()
.height(600.dp)
.padding(16.dp),
) {
Column(
modifier = modifier.fillMaxWidth(),
) {
Text(
text = selectedPlanet.name!!,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center,
)
Image(
painter = painterResource(selectedPlanet.imageId),
contentDescription = selectedPlanet.name,
)
Text(
text = (studyState.selectedTime / 1000 / 60).toString() + " Minutes",
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center,
)
}
}
Column(
modifier = modifier
.fillMaxWidth()
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
CustomCountDownTimer(
studyState.hours,
studyState.minutes,
studyState.seconds,
) { studyViewModel.startCountDown() }
LinearProgressIndicator(
modifier = Modifier
.width(300.dp)
.height(10.dp),
progress = currentProgress,
)
OutlinedButton(
onClick = { openAlertDialog.value = true },
modifier = Modifier
.padding(16.dp),
) {
Text(text = "Cancel")
}
}
when {
openAlertDialog.value -> {
AlertDialog(
onDismissRequest = { openAlertDialog.value = false },
onConfirmation = {
onCancelStudyButtonClicked()
openAlertDialog.value = false
},
dialogTitle = "Cancel mining operation?",
dialogText = "Are you sure you want to stop mining ${selectedPlanet.name}? All progress will be lost.",
icon = Icons.Default.Info,
)
}
}
}
}
suspend fun loadProgress(updateProgress: (Float) -> Unit, delay: Long) {
for (i in 1..1000) {
updateProgress(i.toFloat() / 1000)
delay(delay / 1000)
}
}
| 0 | Kotlin | 0 | 0 | 517bb2146071d067d64170a387023170b1959b2e | 6,170 | StudyPlanetAndroid | MIT License |
sbp-users/src/main/kotlin/io/github/tiscs/sbp/snowflake/ConfigProperties.kt | Tiscs | 131,112,310 | false | null | package io.github.tiscs.sbp.snowflake
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties("snowflake")
data class ConfigProperties(
val enabled: Boolean? = null,
val clusterId: Long = 0,
val workerId: Long = 0,
val workerSequence: String? = null,
val clusterIdBits: Int = 5,
val workerIdBits: Int = 5,
val sequenceBits: Int = 12,
val idEpoch: Long = DEFAULT_ID_EPOCH,
)
| 0 | Kotlin | 2 | 5 | c90249a85ae08179906b6a74a2f05a3efbb7049b | 452 | spring-boot-practices | MIT License |
jvm/src/main/kotlin/org/ionproject/core/common/email/EmailService.kt | i-on-project | 242,369,946 | false | null | package org.ionproject.core.common.email
enum class EmailType(val mimeType: String) {
TEXT("text/plain"),
HTML("text/html")
}
abstract class EmailService(val senderEmail: String, val senderName: String) {
abstract suspend fun sendEmail(recipientEmail: String, emailType: EmailType, subject: String, content: String)
}
| 14 | Kotlin | 0 | 3 | 339407d56e66ec164ecdc4172347272d97cc26b3 | 333 | core | Apache License 2.0 |
src/main/kotlin/g2601_2700/s2684_maximum_number_of_moves_in_a_grid/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2601_2700.s2684_maximum_number_of_moves_in_a_grid
// #Medium #Array #Dynamic_Programming #Matrix
// #2023_09_19_Time_509_ms_(100.00%)_Space_67.9_MB_(25.00%)
class Solution {
fun maxMoves(grid: Array<IntArray>): Int {
val h = grid.size
var dp1 = BooleanArray(h)
var dp2 = BooleanArray(h)
var rtn = 0
dp1.fill(true)
for (col in 1 until grid[0].size) {
var f = false
for (row in 0 until h) {
val pr = row - 1
val nr = row + 1
dp2[row] = false
if (pr >= 0 && dp1[pr] && grid[pr][col - 1] < grid[row][col]) {
dp2[row] = true
f = true
}
if (nr < h && dp1[nr] && grid[nr][col - 1] < grid[row][col]) {
dp2[row] = true
f = true
}
if (dp1[row] && grid[row][col - 1] < grid[row][col]) {
dp2[row] = true
f = true
}
}
val t = dp1
dp1 = dp2
dp2 = t
if (!f) break
rtn++
}
return rtn
}
}
| 0 | Kotlin | 20 | 43 | e8b08d4a512f037e40e358b078c0a091e691d88f | 1,215 | LeetCode-in-Kotlin | MIT License |
app/src/main/java/com/kongjak/koreatechboard/fragment/MechatronicsFragment.kt | kongwoojin | 507,629,548 | false | {"Kotlin": 52710} | package com.kongjak.koreatechboard.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.kongjak.koreatechboard.R
class MechatronicsFragment : Fragment() {
lateinit var fragment: Fragment
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_mechatronics, container, false)
val bottomNavView: BottomNavigationView = rootView.findViewById(R.id.bottom_nav_view)
val mechatronicsNotice = BoardFragment()
val mechatronicsNoticeBundle = Bundle()
mechatronicsNoticeBundle.putString("board", "notice")
mechatronicsNoticeBundle.putString("site", "mechatronics")
mechatronicsNotice.arguments = mechatronicsNoticeBundle
val mechatronicsLecture = BoardFragment()
val mechatronicsLectureBundle = Bundle()
mechatronicsLectureBundle.putString("board", "lecture")
mechatronicsLectureBundle.putString("site", "mechatronics")
mechatronicsLecture.arguments = mechatronicsLectureBundle
val mechatronicsBachelor = BoardFragment()
val mechatronicsBachelorBundle = Bundle()
mechatronicsBachelorBundle.putString("board", "bachelor")
mechatronicsBachelorBundle.putString("site", "mechatronics")
mechatronicsBachelor.arguments = mechatronicsBachelorBundle
val mechatronicsJobBoard = BoardFragment()
val mechatronicsJobBoardBundle = Bundle()
mechatronicsJobBoardBundle.putString("board", "job")
mechatronicsJobBoardBundle.putString("site", "mechatronics")
mechatronicsJobBoard.arguments = mechatronicsJobBoardBundle
val mechatronicsFreeBoard = BoardFragment()
val mechatronicsFreeBoardBundle = Bundle()
mechatronicsFreeBoardBundle.putString("board", "free")
mechatronicsFreeBoardBundle.putString("site", "mechatronics")
mechatronicsFreeBoard.arguments = mechatronicsFreeBoardBundle
if (savedInstanceState == null) {
if (!this::fragment.isInitialized) {
fragment = mechatronicsNotice
}
} else {
fragment = parentFragmentManager.getFragment(savedInstanceState, "fragment")!!
}
loadFragment()
bottomNavView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_mechatronics_notice -> {
fragment = mechatronicsNotice
loadFragment()
true
}
R.id.navigation_mechatronics_lecture -> {
fragment = mechatronicsLecture
loadFragment()
true
}
R.id.navigation_mechatronics_bachelor -> {
fragment = mechatronicsBachelor
loadFragment()
true
}
R.id.navigation_mechatronics_job_board -> {
fragment = mechatronicsJobBoard
loadFragment()
true
}
R.id.navigation_mechatronics_free_board -> {
fragment = mechatronicsFreeBoard
loadFragment()
true
}
else -> false
}
}
return rootView
}
private fun loadFragment() {
parentFragmentManager
.beginTransaction()
.replace(R.id.notice_frame_layout, fragment)
.commit()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
parentFragmentManager.putFragment(outState, "fragment", fragment)
}
} | 2 | Kotlin | 0 | 0 | 3808c284acb0de7498600e8d36053dff7b9229ad | 3,990 | koreatech-board-android | MIT License |
compottie/src/commonMain/kotlin/io/github/alexzhirkevich/compottie/dynamic/_DynamicShapeLayerProvider.kt | alexzhirkevich | 730,724,501 | false | {"Kotlin": 883948, "Swift": 601, "HTML": 211} | package io.github.alexzhirkevich.compottie.dynamic
import androidx.compose.ui.util.fastMaxBy
import kotlin.reflect.KClass
@PublishedApi
internal class DynamicShapeLayerProvider(
private val basePath : String? = null,
private val root : DynamicShapeLayerProvider? = null
) : DynamicLayerProvider(), DynamicShapeLayer {
private val nRoot get() = root ?: this
@PublishedApi
internal val shapes = mutableMapOf<String, DynamicShape>()
internal val eachShapes = mutableMapOf<Pair<String?, KClass<out DynamicShape>>, DynamicShape>()
override fun group(vararg path: String, builder: DynamicShapeLayer.() -> Unit) {
DynamicShapeLayerProvider(
basePath = layerPath(basePath, path.joinToString(LayerPathSeparator)),
root = nRoot
).apply(builder)
}
override fun shape(vararg path: String, builder: DynamicShape.() -> Unit) {
this[path.toList()] = DynamicShapeProvider().apply(builder)
}
override fun fill(vararg path: String, builder: DynamicFill.() -> Unit) {
this[path.toList()] = DynamicFillProvider().apply(builder)
}
override fun stroke(vararg path: String, builder: DynamicStroke.() -> Unit) {
this[path.toList()] = DynamicStrokeProvider().apply(builder)
}
override fun ellipse(vararg path: String, builder: DynamicEllipse.() -> Unit) {
this[path.toList()] = DynamicEllipseProvider().apply(builder)
}
override fun rect(vararg path: String, builder: DynamicRect.() -> Unit) {
this[path.toList()] = DynamicRectProvider().apply(builder)
}
override fun polystar(vararg path: String, builder: DynamicPolystar.() -> Unit) {
this[path.toList()] = DynamicPolystarProvider().apply(builder)
}
internal inline operator fun <reified S : DynamicShape> get(path: String): S? =
getInternal(path, S::class) as S?
private inline operator fun <reified T : DynamicShape> set(path: List<String>, instance: T) {
if (path.isNotEmpty()) {
nRoot.shapes[layerPath(basePath, path.joinToString(LayerPathSeparator))] = instance
} else {
nRoot.eachShapes[basePath to T::class] = instance
}
}
private fun <S : DynamicShape> getInternal(path: String, clazz: KClass<S>): DynamicShape? {
(nRoot.shapes[path])?.let { return it }
val key = nRoot.eachShapes.keys
.filter { it.second == clazz }
.fastMaxBy { it.first.orEmpty().commonPrefixWith(path).length }
?.takeIf { it.first?.commonPrefixWith(path)?.length != 0 }
?: return null
return nRoot.eachShapes[key]
}
}
| 6 | Kotlin | 4 | 179 | 8b80f52ab1cf443405435e7b7b2c76d3e1e960d9 | 2,656 | compottie | MIT License |
game/src/main/kotlin/gg/rsmod/game/plugin/PluginRepository.kt | 2011Scape | 578,880,245 | false | {"Kotlin": 8904349, "Dockerfile": 1354} | package gg.rsmod.game.plugin
import com.google.common.collect.HashMultimap
import com.google.common.collect.Multimap
import gg.rsmod.game.Server
import gg.rsmod.game.event.Event
import gg.rsmod.game.model.World
import gg.rsmod.game.model.attr.COMMAND_ARGS_ATTR
import gg.rsmod.game.model.attr.COMMAND_ATTR
import gg.rsmod.game.model.combat.NpcCombatDef
import gg.rsmod.game.model.container.key.*
import gg.rsmod.game.model.entity.*
import gg.rsmod.game.model.shop.Shop
import gg.rsmod.game.model.timer.TimerKey
import gg.rsmod.game.service.Service
import gg.rsmod.util.ServerProperties
import io.github.classgraph.ClassGraph
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import it.unimi.dsi.fastutil.ints.IntOpenHashSet
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap
import it.unimi.dsi.fastutil.objects.ObjectArrayList
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet
import mu.KLogging
import java.net.URLClassLoader
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* A repository that is responsible for storing and executing plugins, as well
* as making sure no plugin collides.
*
* @author Tom <<EMAIL>>
*/
class PluginRepository(
val world: World,
) {
/**
* The total amount of plugins.
*/
private var pluginCount = 0
/**
* Plugins that get executed when the world is initialised.
*/
private val worldInitPlugins = mutableListOf<Plugin.() -> Unit>()
/**
* The plugin that will executed when changing display modes.
*/
private var windowStatusPlugin: (Plugin.() -> Unit)? = null
/**
* The plugin that will be executed when the core module wants
* close the main modal the player has opened.
*
* This is used for things such as the [gg.rsmod.game.message.impl.MoveGameClickMessage].
*/
private var closeModalPlugin: (Plugin.() -> Unit)? = null
/**
* This plugin is used to check if a player has a menu opened and any
* [gg.rsmod.game.model.queue.QueueTask] with a [gg.rsmod.game.model.queue.TaskPriority.STANDARD]
* priority should wait before executing.
*/
private var isMenuOpenedPlugin: (Plugin.() -> Boolean)? = null
/**
* A list of plugins that will be executed upon login.
*/
private val loginPlugins = mutableListOf<Plugin.() -> Unit>()
/**
* A list of plugins that will be executed upon logout.
*/
private val logoutPlugins = mutableListOf<Plugin.() -> Unit>()
/**
* A list of plugins that will be executed upon an [gg.rsmod.game.model.entity.Npc]
* being spawned into the world. Use sparingly.
*/
private val globalNpcSpawnPlugins = mutableListOf<Plugin.() -> Unit>()
/**
* A list of plugins that will be executed upon an [gg.rsmod.game.model.entity.Npc]
* with a specific id being spawned into the world. Use sparingly per npc.
*
* Note: any npc added to this map <strong>will</strong> still invoke the
* [globalNpcSpawnPlugins] plugin.
*/
private val npcSpawnPlugins = Int2ObjectOpenHashMap<MutableList<Plugin.() -> Unit>>()
/**
* The plugin that will handle initiating combat.
*/
private var combatPlugin: (Plugin.() -> Unit)? = null
/**
* The plugin that will handle on death.
*/
private var slayerLogic: (Plugin.() -> Unit)? = null
/**
* A map of plugins that contain custom combat plugins for specific npcs.
*/
private val npcCombatPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map of plugins that will handle spells on npcs depending on the interface
* hash of the spell.
*/
private val spellOnNpcPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains plugins that should be executed when the [TimerKey]
* hits a value of [0] time left.
*/
private val timerPlugins = hashMapOf<TimerKey, Plugin.() -> Unit>()
/**
* A map that contains plugins that should be executed when an interface
* is opened.
*/
private val interfaceOpenPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains plugins that should be executed when an interface
* is closed.
*/
private val interfaceClosePlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains command plugins. The pair has the privilege power
* required to use the command on the left, and the plugin on the right.
*
* The privilege power left value can be set to null, which means anyone
* can use the command.
*/
private val commandPlugins = hashMapOf<String, Pair<String?, Plugin.() -> Unit>>()
/**
* A map of button click plugins. The key is a shifted value of the parent
* and child id.
*/
private val buttonPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map of equipment option plugins.
*/
private val equipmentOptionPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map of plugins that contain plugins that should execute when equipping
* items from a certain equipment slot.
*/
private val equipSlotPlugins: Multimap<Int, Plugin.() -> Unit> = HashMultimap.create()
/**
* A map of plugins that contain plugins that should execute when un-equipping
* items from a certain equipment slot.
*/
private val unequipSlotPlugins: Multimap<Int, Plugin.() -> Unit> = HashMultimap.create()
/**
* A map of plugins that can stop an item from being equipped.
*/
private val equipItemRequirementPlugins = Int2ObjectOpenHashMap<Plugin.() -> Boolean>()
/**
* A map of plugins that are executed when a player equips an item.
*/
private val equipItemPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map of plugins that are executed when a player un-equips an item.
*/
private val unequipItemPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A plugin that executes when a player levels up a skill.
*/
private var skillLevelUps = mutableListOf<(Plugin.() -> Unit)>()
/**
* A plugin that executes when a player experience goes up in a skill.
*/
private var skillExperienceUps = mutableListOf<(Plugin.() -> Unit)>()
private val componentItemSwapPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
private val componentToComponentItemSwapPlugins = Long2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains any plugin that will be executed upon entering a new
* region. The key is the region id and the value is a list of plugins
* that will execute upon entering the region.
*/
private val enterRegionPlugins = Int2ObjectOpenHashMap<MutableList<Plugin.() -> Unit>>()
/**
* A map that contains any plugin that will be executed upon leaving a region.
* The key is the region id and the value is a list of plugins that will execute
* upon leaving the region.
*/
private val exitRegionPlugins = Int2ObjectOpenHashMap<MutableList<Plugin.() -> Unit>>()
/**
* A map that contains any plugin that will be executed upon entering a new
* [gg.rsmod.game.model.region.Chunk]. The key is the chunk id which can be
* calculated via [gg.rsmod.game.model.region.ChunkCoords.hashCode].
*/
private val enterChunkPlugins = Int2ObjectOpenHashMap<MutableList<Plugin.() -> Unit>>()
/**
* A map that contains any plugin that will be executed when leaving a
* [gg.rsmod.game.model.region.Chunk]. The key is the chunk id which can be
* calculated via [gg.rsmod.game.model.region.ChunkCoords.hashCode].
*/
private val exitChunkPlugins = Int2ObjectOpenHashMap<MutableList<Plugin.() -> Unit>>()
/**
* A map that contains items and any associated menu-click and its respective
* plugin logic, if any (would not be in the map if it doesn't have a plugin).
*/
private val itemPlugins = Int2ObjectOpenHashMap<Int2ObjectOpenHashMap<Plugin.() -> Unit>>()
/**
* A map that contains ground items and any associated menu-click and its respective
* plugin logic, if any (would not be in the map if it doesn't have a plugin).
*/
private val groundItemPlugins = Int2ObjectOpenHashMap<Int2ObjectOpenHashMap<Plugin.() -> Unit>>()
/**
* A map that contains Boolean functions that will return false when a ground
* item can not be picked up.
*/
private val groundItemPickupConditions = Int2ObjectOpenHashMap<Plugin.() -> Boolean>()
/**
* A map of plugins that check if an item with the associated key, can be
* dropped on the floor.
*/
private val canDropItemPlugins = Int2ObjectOpenHashMap<Plugin.() -> Boolean>()
/**
* A map that contains objects and any associated menu-click and its respective
* plugin logic, if any (would not be in the map if it doesn't have a plugin).
*/
private val objectPlugins = Int2ObjectOpenHashMap<Int2ObjectOpenHashMap<Plugin.() -> Unit>>()
/**
* A map that contains items and any objects that they may be used on, and it's
* respective plugin logic.
*/
private val itemOnObjectPlugins = Int2ObjectOpenHashMap<Int2ObjectOpenHashMap<Plugin.() -> Unit>>()
/**
* A map that contains all objects that should have their
* respective plugin logic called when any item is used on them.
*/
private val anyItemOnObjectPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains item on item plugins.
*
* Key: (itemId1 << 16) | itemId2
* Value: plugin
*/
private val itemOnItemPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains item on ground item plugins.
*
* Key: (invItem << 16) | groundItem
* Value: plugin
*/
private val itemOnGroundItemPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains magic spell on item plugins.
*
* Key: (fromComponentHash << 32) | toComponentHash
* Value: plugin
*/
private val spellOnItemPlugins = Long2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains magic spell on item plugins.
*
* Key: (fromComponentHash << 32) | toComponentHash
* Value: plugin
*/
private val spellOnGroundItemPlugins = Long2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map of plugins that will handle spells on players depending on the interface
* hash of the spell.
*/
private val spellOnPlayerPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains npcs and any associated menu-click and its respective
* plugin logic, if any (would not be in the map if it doesn't have a plugin).
*/
private val npcPlugins = Int2ObjectOpenHashMap<Int2ObjectOpenHashMap<Plugin.() -> Unit>>()
/**
* A map of plugins for item on npc logic.
*
* Key: (item << 16) | npcId
* Value: plugin
*/
private val itemOnNpcPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map of plugins for any item on npc logic.
*
* Key: npcId
* Value: plugin
*/
private val anyItemOnNpcPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map of plugins for item on player logic.
*
* Key: (item << 16)
* Value: plugin
*/
private val itemOnPlayerPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map that contains npc ids as the key and their interaction distance as
* the value. If map does not contain an npc, it will have the default interaction
*/
private val npcInteractionDistancePlugins = Int2IntOpenHashMap()
/**
* A map that contains object ids as the key and their interaction distance as
* the value. If map does not contain an object, it will have the default interaction
*/
private val objInteractionDistancePlugins = Int2IntOpenHashMap()
/**
* A list of plugins that will be invoked when a ground item is picked up
* by a player.
*/
private val globalGroundItemPickUp = mutableListOf<Plugin.() -> Unit>()
/**
* A list of plugins that will be invoked when a player hits 0 hp.
*/
private val playerPreDeathPlugins = mutableListOf<Plugin.() -> Unit>()
/**
* A list of plugins that will be invoked when a player dies and is teleported
* back to the respawn location (after death animation played out).
*/
private val playerDeathPlugins = mutableListOf<Plugin.() -> Unit>()
/**
* A map of plugins that are invoked when a player interaction option is executed
*/
private val playerOptionPlugins = hashMapOf<String, Plugin.() -> Unit>()
/**
* A list of plugins that will be invoked when an npc hits 0 hp.
*/
private val npcPreDeathPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A list of plugins that will be invoked when an npc dies
* and is de-registered from the world.
*/
private val npcDeathPlugins = Int2ObjectOpenHashMap<Plugin.() -> Unit>()
/**
* A map of plugins that occur when an [Event] is triggered.
*/
private val eventPlugins = Object2ObjectOpenHashMap<Class<out Event>, MutableList<Plugin.(Event) -> Unit>>()
/**
* The int value is calculated via [gg.rsmod.game.model.region.ChunkCoords.hashCode].
*/
internal val multiCombatChunks = IntOpenHashSet()
/**
* The int value is calculated via [gg.rsmod.game.model.Tile.regionId].
*/
internal val multiCombatRegions = IntOpenHashSet()
/**
* Temporarily holds all npc spawns set from plugins for this [PluginRepository].
* This is then passed onto the [World] and is cleared.
*/
internal val npcSpawns = mutableListOf<Npc>()
/**
* Temporarily holds all object spawns set from plugins for this [PluginRepository].
* This is then passed onto the [World] and is cleared.
*/
internal val objSpawns = mutableListOf<DynamicObject>()
/**
* Temporarily holds all ground item spawns set from plugins for this
* [PluginRepository].
* This is then passed onto the [World] and is cleared.
*/
internal val itemSpawns = mutableListOf<GroundItem>()
/**
* A map of [NpcCombatDef]s that have been set by [KotlinPlugin]s.
*/
internal val npcCombatDefs = Int2ObjectOpenHashMap<NpcCombatDef>()
/**
* Holds all valid shops set from plugins for this [PluginRepository].
*/
internal val shops = Object2ObjectOpenHashMap<String, Shop>()
/**
* A list of [Service]s that have been requested for loading by a [KotlinPlugin].
*/
internal val services = mutableListOf<Service>()
/**
* Holds all container keys set from plugins for this [PluginRepository].
*/
val containerKeys =
ObjectOpenHashSet<ContainerKey>().apply {
add(INVENTORY_KEY)
add(EQUIPMENT_KEY)
add(BANK_KEY)
add(RANDOM_EVENT_GIFT_KEY)
}
/**
* Initiates and populates all our plugins.
*/
fun init(
server: Server,
world: World,
jarPluginsDirectory: String,
) {
loadPlugins(server, jarPluginsDirectory)
loadServices(server, world)
spawnEntities()
}
/**
* Locate and load all [KotlinPlugin]s.
*/
private fun loadPlugins(
server: Server,
jarPluginsDirectory: String,
) {
scanPackageForPlugins(server, world)
scanJarDirectoryForPlugins(server, world, Paths.get(jarPluginsDirectory))
}
/**
* Scan our local package to find any and all [KotlinPlugin]s.
*/
private fun scanPackageForPlugins(
server: Server,
world: World,
) {
ClassGraph().enableAllInfo().whitelistModules().scan().use { result ->
val plugins = result.getSubclasses(KotlinPlugin::class.java.name).directOnly()
plugins.forEach { p ->
val pluginClass = p.loadClass(KotlinPlugin::class.java)
val constructor =
pluginClass.getConstructor(
PluginRepository::class.java,
World::class.java,
Server::class.java,
)
constructor.newInstance(this, world, server)
}
}
}
/**
* Scan directory for any JAR file which may contain plugins.
*/
private fun scanJarDirectoryForPlugins(
server: Server,
world: World,
directory: Path,
) {
if (Files.exists(directory)) {
Files.walk(directory).forEach { path ->
if (!path.fileName.toString().endsWith(".jar")) {
return@forEach
}
scanJarForPlugins(server, world, path)
}
}
}
/**
* Scan JAR located in [path] for any and all valid [KotlinPlugin]s and
* initialise them.
*/
private fun scanJarForPlugins(
server: Server,
world: World,
path: Path,
) {
val urls = arrayOf(path.toFile().toURI().toURL())
val classLoader = URLClassLoader(urls, PluginRepository::class.java.classLoader)
ClassGraph().ignoreParentClassLoaders().addClassLoader(classLoader).enableAllInfo().scan().use { result ->
val plugins = result.getSubclasses(KotlinPlugin::class.java.name).directOnly()
plugins.forEach { p ->
val pluginClass = p.loadClass(KotlinPlugin::class.java)
val constructor =
pluginClass.getConstructor(
PluginRepository::class.java,
World::class.java,
Server::class.java,
)
constructor.newInstance(this, world, server)
}
}
}
/**
* Load and initialise [Service]s given to us by [KotlinPlugin]s.
*/
private fun loadServices(
server: Server,
world: World,
) {
services.forEach { service ->
service.init(server, world, ServerProperties())
world.services.add(service)
}
services.forEach { service ->
service.postLoad(server, world)
}
}
/**
* Spawn any and all [gg.rsmod.game.model.entity.Entity]s given to us by
* [KotlinPlugin]s.
*/
private fun spawnEntities() {
npcSpawns.forEach { npc -> world.spawn(npc) }
objSpawns.forEach { obj -> world.spawn(obj) }
itemSpawns.forEach { item -> world.spawn(item) }
}
/**
* Gracefully terminate this repository.
*/
fun terminate() {
npcSpawns.forEach { npc ->
if (npc.isSpawned()) {
world.remove(npc)
}
}
objSpawns.forEach { obj ->
if (obj.isSpawned(world)) {
world.remove(obj)
}
}
itemSpawns.forEach { item ->
if (item.isSpawned(world)) {
world.remove(item)
}
}
world.services.removeAll(services)
}
/**
* Get the total amount of plugins loaded from the plugins path.
*/
fun getPluginCount(): Int = pluginCount
fun getNpcInteractionDistance(npc: Int): Int? = npcInteractionDistancePlugins.getOrDefault(npc, null)
fun getObjInteractionDistance(obj: Int): Int? = objInteractionDistancePlugins.getOrDefault(obj, null)
fun bindWorldInit(plugin: Plugin.() -> Unit) {
worldInitPlugins.add(plugin)
}
fun executeWorldInit(world: World) {
worldInitPlugins.forEach { logic -> world.executePlugin(world, logic) }
}
fun bindSlayerLogic(plugin: Plugin.() -> Unit) {
if (slayerLogic != null) {
logger.error("Slayer logic is already bound")
throw IllegalStateException("Slayer logic is already bound")
}
slayerLogic = plugin
}
fun executeSlayerLogic(pawn: Pawn) {
if (slayerLogic != null) {
pawn.executePlugin(slayerLogic!!)
}
}
fun bindCombat(plugin: Plugin.() -> Unit) {
if (combatPlugin != null) {
logger.error("Combat plugin is already bound")
throw IllegalStateException("Combat plugin is already bound")
}
combatPlugin = plugin
}
fun executeCombat(pawn: Pawn) {
if (combatPlugin != null) {
pawn.executePlugin(combatPlugin!!)
}
}
fun bindNpcCombat(
npc: Int,
plugin: Plugin.() -> Unit,
) {
if (npcCombatPlugins.containsKey(npc)) {
logger.error("Npc is already bound to a combat plugin: $npc")
throw IllegalStateException("Npc is already bound to a combat plugin: $npc")
}
npcCombatPlugins[npc] = plugin
pluginCount++
}
fun executeNpcCombat(n: Npc): Boolean {
val plugin = npcCombatPlugins[n.id] ?: return false
n.executePlugin(plugin)
return true
}
fun bindPlayerPreDeath(plugin: Plugin.() -> Unit) {
playerPreDeathPlugins.add(plugin)
}
fun executePlayerPreDeath(p: Player) {
playerPreDeathPlugins.forEach { plugin -> p.executePlugin(plugin) }
}
fun bindPlayerOption(
option: String,
plugin: Plugin.() -> Unit,
) {
playerOptionPlugins[option] = plugin
}
fun executePlayerOption(
player: Player,
option: String,
): Boolean {
val logic = playerOptionPlugins[option] ?: return false
player.executePlugin(logic)
return true
}
fun bindPlayerDeath(plugin: Plugin.() -> Unit) {
playerDeathPlugins.add(plugin)
}
fun executePlayerDeath(p: Player) {
playerDeathPlugins.forEach { plugin -> p.executePlugin(plugin) }
}
fun bindNpcPreDeath(
npc: Int,
plugin: Plugin.() -> Unit,
) {
npcPreDeathPlugins[npc] = plugin
}
fun executeNpcPreDeath(npc: Npc) {
npcPreDeathPlugins[npc.id]?.let { plugin ->
npc.executePlugin(plugin)
}
}
fun bindNpcDeath(
npc: Int,
plugin: Plugin.() -> Unit,
) {
npcDeathPlugins[npc] = plugin
}
fun executeNpcDeath(npc: Npc) {
npcDeathPlugins[npc.id]?.let { plugin ->
npc.executePlugin(plugin)
}
}
fun bindSpellOnPlayer(
parent: Int,
child: Int,
plugin: Plugin.() -> Unit,
) {
val hash = (parent shl 16) or child
if (spellOnPlayerPlugins.containsKey(hash)) {
logger.error("Spell is already bound to a plugin: [$parent, $child]")
throw IllegalStateException("Spell is already bound to a plugin: [$parent, $child]")
}
spellOnPlayerPlugins[hash] = plugin
pluginCount++
}
fun executeSpellOnPlayer(
p: Player,
parent: Int,
child: Int,
): Boolean {
val hash = (parent shl 16) or child
val plugin = spellOnPlayerPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindSpellOnNpc(
parent: Int,
child: Int,
plugin: Plugin.() -> Unit,
) {
val hash = (parent shl 16) or child
if (spellOnNpcPlugins.containsKey(hash)) {
logger.error("Spell is already bound to a plugin: [$parent, $child]")
throw IllegalStateException("Spell is already bound to a plugin: [$parent, $child]")
}
spellOnNpcPlugins[hash] = plugin
pluginCount++
}
fun executeSpellOnNpc(
p: Player,
parent: Int,
child: Int,
): Boolean {
val hash = (parent shl 16) or child
val plugin = spellOnNpcPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindWindowStatus(plugin: Plugin.() -> Unit) {
if (windowStatusPlugin != null) {
logger.error("Window status is already bound to a plugin")
throw IllegalStateException("Window status is already bound to a plugin")
}
windowStatusPlugin = plugin
}
fun executeWindowStatus(p: Player) {
if (windowStatusPlugin != null) {
p.executePlugin(windowStatusPlugin!!)
} else {
logger.warn { "Window status is not bound to a plugin." }
}
}
fun bindModalClose(plugin: Plugin.() -> Unit) {
if (closeModalPlugin != null) {
logger.error("Modal close is already bound to a plugin")
throw IllegalStateException("Modal close is already bound to a plugin")
}
closeModalPlugin = plugin
}
fun executeModalClose(p: Player) {
if (closeModalPlugin != null) {
p.executePlugin(closeModalPlugin!!)
} else {
logger.warn { "Modal close is not bound to a plugin." }
}
}
fun setMenuOpenedCheck(plugin: Plugin.() -> Boolean) {
if (isMenuOpenedPlugin != null) {
logger.error("\"Menu Opened\" is already bound to a plugin")
throw IllegalStateException("\"Menu Opened\" is already bound to a plugin")
}
isMenuOpenedPlugin = plugin
}
fun isMenuOpened(p: Player): Boolean =
if (isMenuOpenedPlugin !=
null
) {
p.executePlugin(isMenuOpenedPlugin!!)
} else {
false
}
fun <T : Event> bindEvent(
event: Class<T>,
plugin: Plugin.(Event) -> Unit,
) {
val plugins = eventPlugins[event]
if (plugins != null) {
plugins.add(plugin)
} else {
val newList = ObjectArrayList<Plugin.(Event) -> Unit>(1)
newList.add(plugin)
eventPlugins[event] = newList
}
pluginCount++
}
fun <T : Event> executeEvent(
p: Pawn,
event: T,
) {
eventPlugins[event::class.java]?.forEach { plugin ->
p.executePlugin {
plugin.invoke(this, event)
}
}
}
fun bindLogin(plugin: Plugin.() -> Unit) {
loginPlugins.add(plugin)
pluginCount++
}
fun executeLogin(p: Player) {
loginPlugins.forEach { logic -> p.executePlugin(logic) }
}
fun bindLogout(plugin: Plugin.() -> Unit) {
logoutPlugins.add(plugin)
pluginCount++
}
fun executeLogout(p: Player) {
logoutPlugins.forEach { logic -> p.executePlugin(logic) }
}
fun bindComponentItemSwap(
interfaceId: Int,
component: Int,
plugin: Plugin.() -> Unit,
) {
val hash = (interfaceId shl 16) or component
componentItemSwapPlugins[hash] = plugin
}
fun executeComponentItemSwap(
p: Player,
interfaceId: Int,
component: Int,
): Boolean {
val hash = (interfaceId shl 16) or component
val plugin = componentItemSwapPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindComponentToComponentItemSwap(
srcInterfaceId: Int,
srcComponent: Int,
dstInterfaceId: Int,
dstComponent: Int,
plugin: Plugin.() -> Unit,
) {
val srcHash = (srcInterfaceId shl 16) or srcComponent
val dstHash = (dstInterfaceId shl 16) or dstComponent
val combinedHash = ((srcHash shl 32) or dstHash).toLong()
componentToComponentItemSwapPlugins[combinedHash] = plugin
}
fun executeComponentToComponentItemSwap(
p: Player,
srcInterfaceId: Int,
srcComponent: Int,
dstInterfaceId: Int,
dstComponent: Int,
): Boolean {
val srcHash = (srcInterfaceId shl 16) or srcComponent
val dstHash = (dstInterfaceId shl 16) or dstComponent
val combinedHash = ((srcHash shl 32) or dstHash).toLong()
val plugin = componentToComponentItemSwapPlugins[combinedHash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindGlobalNpcSpawn(plugin: Plugin.() -> Unit) {
globalNpcSpawnPlugins.add(plugin)
pluginCount++
}
fun bindNpcSpawn(
npc: Int,
plugin: Plugin.() -> Unit,
) {
val plugins = npcSpawnPlugins[npc]
if (plugins != null) {
plugins.add(plugin)
} else {
npcSpawnPlugins[npc] = arrayListOf(plugin)
}
pluginCount++
}
fun executeNpcSpawn(n: Npc) {
val customPlugins = npcSpawnPlugins[n.id]
if (customPlugins != null && customPlugins.isNotEmpty()) {
customPlugins.forEach { logic -> n.executePlugin(logic) }
}
globalNpcSpawnPlugins.forEach { logic -> n.executePlugin(logic) }
}
fun bindTimer(
key: TimerKey,
plugin: Plugin.() -> Unit,
) {
if (timerPlugins.containsKey(key)) {
logger.error("Timer key is already bound to a plugin: $key")
throw IllegalStateException("Timer key is already bound to a plugin: $key")
}
timerPlugins[key] = plugin
pluginCount++
}
fun executeTimer(
pawn: Pawn,
key: TimerKey,
): Boolean {
val plugin = timerPlugins[key]
if (plugin != null) {
pawn.executePlugin(plugin)
return true
}
return false
}
fun executeWorldTimer(
world: World,
key: TimerKey,
): Boolean {
val plugin = timerPlugins[key]
if (plugin != null) {
world.executePlugin(world, plugin)
return true
}
return false
}
fun bindInterfaceOpen(
interfaceId: Int,
plugin: Plugin.() -> Unit,
) {
if (interfaceOpenPlugins.containsKey(interfaceId)) {
logger.error("Component id is already bound to a plugin: $interfaceId")
throw IllegalStateException("Component id is already bound to a plugin: $interfaceId")
}
interfaceOpenPlugins[interfaceId] = plugin
pluginCount++
}
fun executeInterfaceOpen(
p: Player,
interfaceId: Int,
): Boolean {
val plugin = interfaceOpenPlugins[interfaceId]
if (plugin != null) {
p.executePlugin(plugin)
return true
}
return false
}
fun bindInterfaceClose(
interfaceId: Int,
plugin: Plugin.() -> Unit,
) {
if (interfaceClosePlugins.containsKey(interfaceId)) {
logger.error("Component id is already bound to a plugin: $interfaceId")
throw IllegalStateException("Component id is already bound to a plugin: $interfaceId")
}
interfaceClosePlugins[interfaceId] = plugin
pluginCount++
}
fun executeInterfaceClose(
p: Player,
interfaceId: Int,
): Boolean {
val plugin = interfaceClosePlugins[interfaceId]
if (plugin != null) {
p.executePlugin(plugin)
return true
}
return false
}
fun bindCommand(
command: String,
powerRequired: String? = null,
plugin: Plugin.() -> Unit,
) {
val cmd = command.lowercase()
if (commandPlugins.containsKey(cmd)) {
logger.error("Command is already bound to a plugin: $cmd")
throw IllegalStateException("Command is already bound to a plugin: $cmd")
}
commandPlugins[cmd] = Pair(powerRequired, plugin)
pluginCount++
}
fun executeCommand(
p: Player,
command: String,
args: Array<String>? = null,
): Boolean {
val commandPair = commandPlugins[command]
if (commandPair != null) {
val powerRequired = commandPair.first
val plugin = commandPair.second
if (powerRequired != null && !p.privilege.powers.contains(powerRequired.lowercase())) {
return false
}
p.attr.put(COMMAND_ATTR, command)
if (args != null) {
p.attr.put(COMMAND_ARGS_ATTR, args)
} else {
p.attr.put(COMMAND_ARGS_ATTR, emptyArray())
}
p.executePlugin(plugin)
return true
}
return false
}
fun bindButton(
parent: Int,
child: Int,
plugin: Plugin.() -> Unit,
) {
val hash = (parent shl 16) or child
if (buttonPlugins.containsKey(hash)) {
logger.error("Button hash already bound to a plugin: [parent=$parent, child=$child]")
throw IllegalStateException("Button hash already bound to a plugin: [parent=$parent, child=$child]")
}
buttonPlugins[hash] = plugin
pluginCount++
}
fun executeButton(
p: Player,
parent: Int,
child: Int,
): Boolean {
val hash = (parent shl 16) or child
val plugin = buttonPlugins[hash]
if (plugin != null) {
p.executePlugin(plugin)
return true
}
return false
}
fun bindEquipmentOption(
item: Int,
option: Int,
plugin: Plugin.() -> Unit,
) {
val hash = (item shl 16) or option
if (equipmentOptionPlugins.containsKey(hash)) {
logger.error(RuntimeException("Button hash already bound to a plugin: [item=$item, opt=$option]")) {}
return
}
equipmentOptionPlugins[hash] = plugin
pluginCount++
}
fun executeEquipmentOption(
p: Player,
item: Int,
option: Int,
): Boolean {
val hash = (item shl 16) or option
val plugin = equipmentOptionPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindEquipSlot(
equipSlot: Int,
plugin: Plugin.() -> Unit,
) {
equipSlotPlugins.put(equipSlot, plugin)
pluginCount++
}
fun executeEquipSlot(
p: Player,
equipSlot: Int,
): Boolean {
val plugin = equipSlotPlugins[equipSlot]
if (plugin != null) {
plugin.forEach { logic -> p.executePlugin(logic) }
return true
}
return false
}
fun bindUnequipSlot(
equipSlot: Int,
plugin: Plugin.() -> Unit,
) {
unequipSlotPlugins.put(equipSlot, plugin)
pluginCount++
}
fun executeUnequipSlot(
p: Player,
equipSlot: Int,
): Boolean {
val plugin = unequipSlotPlugins[equipSlot]
if (plugin != null) {
plugin.forEach { logic -> p.executePlugin(logic) }
return true
}
return false
}
fun bindEquipItemRequirement(
item: Int,
plugin: Plugin.() -> Boolean,
) {
if (equipItemRequirementPlugins.containsKey(item)) {
logger.error("Equip item requirement already bound to a plugin: [item=$item]")
throw IllegalStateException("Equip item requirement already bound to a plugin: [item=$item]")
}
equipItemRequirementPlugins[item] = plugin
pluginCount++
}
fun executeEquipItemRequirement(
p: Player,
item: Int,
): Boolean {
val plugin = equipItemRequirementPlugins[item]
if (plugin != null) {
/*
* Plugin returns true if the item can be equipped, false if it
* should block the item from being equipped.
*/
return p.executePlugin(plugin)
}
/*
* Should always be able to wear items by default.
*/
return true
}
fun bindEquipItem(
item: Int,
plugin: Plugin.() -> Unit,
) {
if (equipItemPlugins.containsKey(item)) {
logger.error("Equip item already bound to a plugin: [item=$item]")
throw IllegalStateException("Equip item already bound to a plugin: [item=$item]")
}
equipItemPlugins[item] = plugin
pluginCount++
}
fun executeEquipItem(
p: Player,
item: Int,
): Boolean {
val plugin = equipItemPlugins[item]
if (plugin != null) {
p.executePlugin(plugin)
return true
}
return false
}
fun bindUnequipItem(
item: Int,
plugin: Plugin.() -> Unit,
) {
if (unequipItemPlugins.containsKey(item)) {
logger.error("Unequip item already bound to a plugin: [item=$item]")
throw IllegalStateException("Unequip item already bound to a plugin: [item=$item]")
}
unequipItemPlugins[item] = plugin
pluginCount++
}
fun executeUnequipItem(
p: Player,
item: Int,
): Boolean {
val plugin = unequipItemPlugins[item]
if (plugin != null) {
p.executePlugin(plugin)
return true
}
return false
}
fun bindSkillLevelUp(plugin: Plugin.() -> Unit) {
skillLevelUps.add(plugin)
}
fun bindSkillExperienceUp(plugin: Plugin.() -> Unit) {
skillExperienceUps.add(plugin)
}
fun executeSkillLevelUp(p: Player) {
skillLevelUps.forEach { p.executePlugin(it) }
}
fun executeSkillExperienceUp(p: Player) {
skillExperienceUps.forEach { p.executePlugin(it) }
}
fun bindRegionEnter(
regionId: Int,
plugin: Plugin.() -> Unit,
) {
val plugins = enterRegionPlugins[regionId]
if (plugins != null) {
plugins.add(plugin)
} else {
enterRegionPlugins[regionId] = arrayListOf(plugin)
}
pluginCount++
}
fun executeRegionEnter(
p: Player,
regionId: Int,
) {
enterRegionPlugins[regionId]?.forEach { logic -> p.executePlugin(logic) }
}
fun bindRegionExit(
regionId: Int,
plugin: Plugin.() -> Unit,
) {
val plugins = exitRegionPlugins[regionId]
if (plugins != null) {
plugins.add(plugin)
} else {
exitRegionPlugins[regionId] = arrayListOf(plugin)
}
pluginCount++
}
fun executeRegionExit(
p: Player,
regionId: Int,
) {
exitRegionPlugins[regionId]?.forEach { logic -> p.executePlugin(logic) }
}
fun bindChunkEnter(
chunkHash: Int,
plugin: Plugin.() -> Unit,
) {
val plugins = enterChunkPlugins[chunkHash]
if (plugins != null) {
plugins.add(plugin)
} else {
enterChunkPlugins[chunkHash] = arrayListOf(plugin)
}
pluginCount++
}
fun executeChunkEnter(
p: Player,
chunkHash: Int,
) {
enterChunkPlugins[chunkHash]?.forEach { logic -> p.executePlugin(logic) }
}
fun bindChunkExit(
chunkHash: Int,
plugin: Plugin.() -> Unit,
) {
val plugins = exitChunkPlugins[chunkHash]
if (plugins != null) {
plugins.add(plugin)
} else {
exitChunkPlugins[chunkHash] = arrayListOf(plugin)
}
pluginCount++
}
fun executeChunkExit(
p: Player,
chunkHash: Int,
) {
exitChunkPlugins[chunkHash]?.forEach { logic -> p.executePlugin(logic) }
}
fun bindItem(
id: Int,
opt: Int,
plugin: Plugin.() -> Unit,
) {
val optMap = itemPlugins[id] ?: Int2ObjectOpenHashMap(1)
if (optMap.containsKey(opt)) {
logger.error("Item is already bound to a plugin: $id [opt=$opt]")
throw IllegalStateException("Item is already bound to a plugin: $id [opt=$opt]")
}
optMap[opt] = plugin
itemPlugins[id] = optMap
pluginCount++
}
fun executeItem(
p: Player,
id: Int,
opt: Int,
): Boolean {
val optMap = itemPlugins[id] ?: return false
val logic = optMap[opt] ?: return false
p.executePlugin(logic)
return true
}
fun bindGroundItem(
id: Int,
opt: Int,
plugin: Plugin.() -> Unit,
) {
val optMap = groundItemPlugins[id] ?: Int2ObjectOpenHashMap(1)
if (optMap.containsKey(opt)) {
logger.error("Ground item is already bound to a plugin: $id [opt=$opt]")
throw IllegalStateException("Ground item is already bound to a plugin: $id [opt=$opt]")
}
optMap[opt] = plugin
groundItemPlugins[id] = optMap
pluginCount++
}
fun executeGroundItem(
p: Player,
id: Int,
opt: Int,
): Boolean {
val optMap = groundItemPlugins[id] ?: return false
val logic = optMap[opt] ?: return false
p.executePlugin(logic)
return true
}
fun setGroundItemPickupCondition(
item: Int,
plugin: Plugin.() -> Boolean,
) {
if (groundItemPickupConditions.containsKey(item)) {
val error = IllegalStateException("Ground item pick-up condition already set: $item")
logger.error(error) {}
throw error
}
groundItemPickupConditions[item] = plugin
pluginCount++
}
fun canPickupGroundItem(
p: Player,
item: Int,
): Boolean {
val plugin = groundItemPickupConditions[item] ?: return true
return p.executePlugin(plugin)
}
fun bindCanItemDrop(
item: Int,
plugin: Plugin.() -> Boolean,
) {
if (canDropItemPlugins.containsKey(item)) {
logger.error("Item already bound to a 'can-drop' plugin: $item")
throw IllegalStateException("Item already bound to a 'can-drop' plugin: $item")
}
canDropItemPlugins[item] = plugin
}
fun canDropItem(
p: Player,
item: Int,
): Boolean {
val plugin = canDropItemPlugins[item]
if (plugin != null) {
return p.executePlugin(plugin)
}
return true
}
fun bindItemOnObject(
obj: Int,
item: Int,
lineOfSightDistance: Int = -1,
plugin: Plugin.() -> Unit,
) {
val plugins = itemOnObjectPlugins[item] ?: Int2ObjectOpenHashMap(1)
if (plugins.containsKey(obj)) {
val error = "Item is already bound to an object plugin: $item [obj=$obj]"
logger.error(error)
throw IllegalStateException(error)
}
if (lineOfSightDistance != -1) {
objInteractionDistancePlugins[obj] = lineOfSightDistance
}
plugins[obj] = plugin
itemOnObjectPlugins[item] = plugins
pluginCount++
}
fun bindAnyItemOnObject(
obj: Int,
lineOfSightDistance: Int = -1,
plugin: Plugin.() -> Unit,
) {
if (anyItemOnObjectPlugins.containsKey(obj)) {
val error = "Object is already bound to a plugin: [obj=$obj]"
logger.error(error)
throw IllegalStateException(error)
}
if (lineOfSightDistance != -1) {
objInteractionDistancePlugins[obj] = lineOfSightDistance
}
anyItemOnObjectPlugins[obj] = plugin
pluginCount++
}
fun executeItemOnObject(
p: Player,
obj: Int,
item: Int,
): Boolean {
val logic = itemOnObjectPlugins[item]?.get(obj) ?: anyItemOnObjectPlugins[obj] ?: return false
p.executePlugin(logic)
return true
}
fun bindItemOnItem(
item1: Int,
item2: Int,
plugin: Plugin.() -> Unit,
) {
val max = Math.max(item1, item2)
val min = Math.min(item1, item2)
val hash = (max shl 16) or min
if (itemOnItemPlugins.containsKey(hash)) {
logger.error { "Item on Item pair is already bound to a plugin: [item1=$item1, item2=$item2]" }
throw IllegalStateException("Item on Item pair is already bound to a plugin: [item1=$item1, item2=$item2]")
}
itemOnItemPlugins[hash] = plugin
pluginCount++
}
fun executeItemOnItem(
p: Player,
item1: Int,
item2: Int,
): Boolean {
val max = Math.max(item1, item2)
val min = Math.min(item1, item2)
val hash = (max shl 16) or min
val plugin = itemOnItemPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindItemOnGroundItem(
invItem: Int,
groundItem: Int,
plugin: Plugin.() -> Unit,
) {
val hash = (invItem shl 16) or groundItem
if (itemOnGroundItemPlugins.containsKey(hash)) {
val error =
IllegalStateException(
"Item on Item pair is already bound to a plugin: [inv_item=$invItem, ground_item=$groundItem]",
)
logger.error(error) {}
throw error
}
itemOnGroundItemPlugins[hash] = plugin
pluginCount++
}
fun executeItemOnGroundItem(
p: Player,
invItem: Int,
groundItem: Int,
): Boolean {
val hash = (invItem shl 16) or groundItem
val plugin = itemOnGroundItemPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindSpellOnItem(
fromComponentHash: Int,
plugin: Plugin.() -> Unit,
) {
val hash: Long = (fromComponentHash.toLong() shl 32)
if (spellOnItemPlugins.containsKey(hash)) {
val exception =
RuntimeException(
"Spell on item already bound to a plugin: from=[${fromComponentHash shr 16}, ${fromComponentHash or 0xFFFF}]",
)
logger.error(exception) {}
throw exception
}
spellOnItemPlugins[hash] = plugin
pluginCount++
}
fun bindSpellOnGroundItem(
fromComponentHash: Int,
plugin: Plugin.() -> Unit,
) {
val hash: Long = (fromComponentHash.toLong() shl 32)
if (spellOnGroundItemPlugins.containsKey(hash)) {
val exception =
RuntimeException(
"Spell on ground item already bound to a plugin: from=[${fromComponentHash shr 16}, ${fromComponentHash or 0xFFFF}]",
)
logger.error(exception) {}
throw exception
}
spellOnGroundItemPlugins[hash] = plugin
pluginCount++
}
fun executeSpellOnItem(
p: Player,
fromComponentHash: Int,
): Boolean {
val hash: Long = (fromComponentHash.toLong() shl 32)
val plugin = spellOnItemPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun executeSpellOnGroundItem(
p: Player,
fromComponentHash: Int,
): Boolean {
val hash: Long = (fromComponentHash.toLong() shl 32)
val plugin = spellOnGroundItemPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindObject(
obj: Int,
opt: Int,
lineOfSightDistance: Int = -1,
plugin: Plugin.() -> Unit,
) {
val optMap = objectPlugins[obj] ?: Int2ObjectOpenHashMap(1)
if (optMap.containsKey(opt)) {
logger.error("Object is already bound to a plugin: $obj [opt=$opt]")
throw IllegalStateException("Object is already bound to a plugin: $obj [opt=$opt]")
}
if (lineOfSightDistance != -1) {
objInteractionDistancePlugins[obj] = lineOfSightDistance
}
optMap[opt] = plugin
objectPlugins[obj] = optMap
pluginCount++
}
fun executeObject(
p: Player,
id: Int,
opt: Int,
): Boolean {
val optMap = objectPlugins[id] ?: return false
val logic = optMap[opt] ?: return false
p.executePlugin(logic)
return true
}
fun bindNpc(
npc: Int,
opt: Int,
lineOfSightDistance: Int = -1,
plugin: Plugin.() -> Unit,
) {
val optMap = npcPlugins[npc] ?: Int2ObjectOpenHashMap(1)
if (optMap.containsKey(opt)) {
logger.error("Npc is already bound to a plugin: $npc [opt=$opt]")
throw IllegalStateException("Npc is already bound to a plugin: $npc [opt=$opt]")
}
if (lineOfSightDistance != -1) {
npcInteractionDistancePlugins[npc] = lineOfSightDistance
}
optMap[opt] = plugin
npcPlugins[npc] = optMap
pluginCount++
}
fun executeNpc(
p: Player,
id: Int,
opt: Int,
): Boolean {
val optMap = npcPlugins[id] ?: return false
val logic = optMap[opt] ?: return false
p.executePlugin(logic)
return true
}
fun bindItemOnNpc(
npc: Int,
item: Int,
plugin: Plugin.() -> Unit,
) {
val hash = (item shl 16) or npc
if (itemOnNpcPlugins.containsKey(hash)) {
val error = IllegalStateException("Item on npc is already bound to a plugin: npc=$npc, item=$item")
logger.error(error) {}
throw error
}
itemOnNpcPlugins[hash] = plugin
pluginCount++
}
fun bindAnyItemOnNpc(
npc: Int,
plugin: Plugin.() -> Unit,
) {
if (anyItemOnNpcPlugins.containsKey(npc)) {
val error = IllegalStateException("Any item on npc is already bound to a plugin: npc=$npc")
logger.error(error) {}
throw error
}
anyItemOnNpcPlugins[npc] = plugin
pluginCount++
}
fun bindItemOnPlayer(
item: Int,
plugin: Plugin.() -> Unit,
) {
val hash = (item shl 16)
if (itemOnPlayerPlugins.containsKey(hash)) {
val error = IllegalStateException("Item on player is already bound to a plugin: item=$item")
logger.error(error) {}
throw error
}
itemOnPlayerPlugins[hash] = plugin
pluginCount++
}
fun executeItemOnNpc(
p: Player,
npc: Int,
item: Int,
): Boolean {
val hash = (item shl 16) or npc
val plugin = itemOnNpcPlugins[hash] ?: anyItemOnNpcPlugins[npc] ?: return false
p.executePlugin(plugin)
return true
}
fun executeItemOnPlayer(
p: Player,
item: Int,
): Boolean {
val hash = (item shl 16)
val plugin = itemOnPlayerPlugins[hash] ?: return false
p.executePlugin(plugin)
return true
}
fun bindGlobalGroundItemPickUp(plugin: Plugin.() -> Unit) {
globalGroundItemPickUp.add(plugin)
}
fun executeGlobalGroundItemPickUp(p: Player) {
globalGroundItemPickUp.forEach { plugin ->
p.executePlugin(plugin)
}
}
companion object : KLogging()
}
| 39 | Kotlin | 143 | 34 | e5400cc71bfa087164153d468979c5a3abc24841 | 51,310 | game | Apache License 2.0 |
app/src/main/java/io/appwrite/messagewrite/modules/Appwrite.kt | abnegate | 777,669,864 | false | {"Kotlin": 59858} | package io.appwrite.messagewrite.modules
import android.content.Context
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import io.appwrite.Client
import io.appwrite.services.Account
import io.appwrite.services.Databases
import io.appwrite.services.Functions
import io.appwrite.services.Storage
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object Appwrite {
private const val ENDPOINT = "https://chat.jakebarnby.com/v1"
private const val PROJECT_ID = "chat"
@Provides
@Singleton
fun provideClient(@ApplicationContext context: Context) =
Client(context)
.setEndpoint(ENDPOINT)
.setProject(PROJECT_ID)
@Provides
fun provideAccount(client: Client) = Account(client)
@Provides
fun provideDatabases(client: Client) = Databases(client)
@Provides
fun provideStorage(client: Client) = Storage(client)
@Provides
fun provideFunctions(client: Client) = Functions(client)
} | 0 | Kotlin | 0 | 0 | c8a3574c53c211cb98ea445f645865412716a91a | 1,115 | hackathon-chat | MIT License |
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/database/methods/DatabaseGetChairs.kt | Anton3 | 159,801,334 | true | {"Kotlin": 1382186} | @file:Suppress("unused", "MemberVisibilityCanBePrivate", "SpellCheckingInspection")
package name.anton3.vkapi.generated.database.methods
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import name.anton3.vkapi.generated.common.objects.Object
import name.anton3.vkapi.method.UserServiceMethod
import name.anton3.vkapi.method.VkMethod
import name.anton3.vkapi.vktypes.VkList
/**
* [https://vk.com/dev/database.getChairs]
*
* Returns list of chairs on a specified faculty.
*
* @property facultyId id of the faculty to get chairs from
* @property offset offset required to get a certain subset of chairs
* @property count amount of chairs to get
*/
data class DatabaseGetChairs(
var facultyId: Long,
var offset: Long? = null,
var count: Long? = null
) : VkMethod<VkList<Object>, UserServiceMethod>("database.getChairs", jacksonTypeRef())
| 2 | Kotlin | 0 | 8 | 773c89751c4382a42f556b6d3c247f83aabec625 | 867 | kotlin-vk-api | MIT License |
src/main/kotlin/org/devmpv/telebot/client/openweather/api/data/Weather.kt | devmpv | 428,543,886 | false | {"Kotlin": 25601} | package org.devmpv.telebot.client.openweather.api.data
data class Weather (
val id : Int,
val main : String,
val description : String,
val icon : String
) | 0 | Kotlin | 0 | 0 | 1172b6531cd7708da1f872d2bd52807b64da63f8 | 159 | telebot | MIT License |
backend/src/main/kotlin/com/project/smonkey/domain/smoking/service/DeductedPointService.kt | hackersground-kr | 656,532,644 | false | null | package com.project.smonkey.domain.smoking.service
import com.project.smonkey.domain.smonkey.facade.SMonkeyFacade
import com.project.smonkey.domain.user.facade.UserFacade
import com.project.smonkey.global.payload.BaseResponse
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
/**
* 기본적으로 차감되는 포인트
*/
private const val DeductedPoint: Int = 240
@Service
class DeductedPointService(
private val smonkeyFacade: SMonkeyFacade,
private val userFacade: UserFacade,
) {
@Transactional
fun pointDeducted(): BaseResponse<Unit> {
val user = userFacade.getCurrentUser()
val smonkey = smonkeyFacade.getSMonkeyById(
userId = user.id
)
smonkey.updatePoint(
point = smonkey.point - DeductedPoint
)
return BaseResponse(
status = 201,
message = "success to deducted point",
content = null,
)
}
}
| 0 | Kotlin | 3 | 3 | 6782fb89e747b4b3f7cd8170d480597bb1b99c30 | 982 | smonkey | MIT License |
wui/src/main/kotlin/components/form/validation/StringConstraints.kt | kspar | 160,047,508 | false | {"Kotlin": 1507189, "HTML": 332077, "JavaScript": 104819, "CSS": 98127, "Python": 10567, "Shell": 1148} | package components.form.validation
import translation.Str
object StringConstraints {
class NotBlank(private val showMsg: Boolean) : FieldConstraint<String>() {
override fun validate(value: String, fieldNameForMessage: String) = when {
value.isBlank() -> violation(if (showMsg) "$fieldNameForMessage ${Str.constraintIsRequired}" else "")
else -> null
}
}
class Length(
private val min: Int = 0,
private val max: Int = Int.MAX_VALUE,
) : FieldConstraint<String>() {
override fun validate(value: String, fieldNameForMessage: String) = when {
value.length < min -> violation("$fieldNameForMessage ${Str.constraintTooShort} $min ${if (min == 1) Str.characterSingular else Str.characterPlural}")
value.length > max -> violation("$fieldNameForMessage ${Str.constraintTooLong} $max ${if (max == 1) Str.characterSingular else Str.characterPlural}")
else -> null
}
}
} | 0 | Kotlin | 3 | 4 | 4853542b8948b9a8788f95059d9f4b5751cc5f40 | 989 | easy | MIT License |
wui/src/main/kotlin/components/form/validation/StringConstraints.kt | kspar | 160,047,508 | false | {"Kotlin": 1507189, "HTML": 332077, "JavaScript": 104819, "CSS": 98127, "Python": 10567, "Shell": 1148} | package components.form.validation
import translation.Str
object StringConstraints {
class NotBlank(private val showMsg: Boolean) : FieldConstraint<String>() {
override fun validate(value: String, fieldNameForMessage: String) = when {
value.isBlank() -> violation(if (showMsg) "$fieldNameForMessage ${Str.constraintIsRequired}" else "")
else -> null
}
}
class Length(
private val min: Int = 0,
private val max: Int = Int.MAX_VALUE,
) : FieldConstraint<String>() {
override fun validate(value: String, fieldNameForMessage: String) = when {
value.length < min -> violation("$fieldNameForMessage ${Str.constraintTooShort} $min ${if (min == 1) Str.characterSingular else Str.characterPlural}")
value.length > max -> violation("$fieldNameForMessage ${Str.constraintTooLong} $max ${if (max == 1) Str.characterSingular else Str.characterPlural}")
else -> null
}
}
} | 0 | Kotlin | 3 | 4 | 4853542b8948b9a8788f95059d9f4b5751cc5f40 | 989 | easy | MIT License |
solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Cosine.kt | tuProlog | 230,784,338 | false | {"Kotlin": 3797695, "Java": 18690, "ANTLR": 10366, "CSS": 1535, "JavaScript": 894, "Prolog": 818} | package it.unibo.tuprolog.solve.stdlib.function
import it.unibo.tuprolog.core.Integer
import it.unibo.tuprolog.core.Numeric
import it.unibo.tuprolog.core.Real
import it.unibo.tuprolog.solve.ExecutionContext
import it.unibo.tuprolog.solve.function.UnaryMathFunction
import org.gciatto.kt.math.BigDecimal
import kotlin.math.cos
/**
* Implementation of `cos/1` arithmetic functor
*
* @author Enrico
*/
object Cosine : UnaryMathFunction("cos") {
override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric =
commonBehaviour(integer.decimalValue)
override fun mathFunction(real: Real, context: ExecutionContext): Numeric =
commonBehaviour(real.value)
/** Implements the common behaviour for real and integer */
private fun commonBehaviour(decimal: BigDecimal) =
Numeric.of(cos(decimal.toDouble()))
}
| 76 | Kotlin | 13 | 76 | 4c350d8581c4ba4709c6517433b1096e186b9ef4 | 864 | 2p-kt | Apache License 2.0 |
domain/src/commonMain/kotlin/io/github/lazyengineer/castaway/domain/common/UiEvent.kt | lazy-engineer | 321,396,462 | false | {"Kotlin": 285918, "Swift": 86110, "Ruby": 1720} | package io.github.lazyengineer.castaway.domain.common
interface UiEvent
| 0 | Kotlin | 0 | 2 | 556234559b4f94cdcd5b6c2e5046c9a07ce47e4f | 73 | castaway | MIT License |
modules/gallery/ui/search/src/main/kotlin/nasa/gallery/ui/search/SearchAction.kt | jonapoul | 794,260,725 | false | {"Kotlin": 575458} | package nasa.gallery.ui.search
import androidx.compose.runtime.Immutable
import nasa.gallery.model.FilterConfig
import nasa.gallery.model.NasaId
@Immutable
internal sealed interface SearchAction {
data object NavBack : SearchAction
data class NavToImage(val id: NasaId) : SearchAction
data class EnterSearchTerm(val text: String) : SearchAction
data object PerformSearch : SearchAction
data class SelectPage(val pageNumber: Int) : SearchAction
data class SetFilterConfig(val config: FilterConfig) : SearchAction
data object ToggleExtraConfig : SearchAction
data object ResetExtraConfig : SearchAction
}
| 5 | Kotlin | 0 | 0 | 8ba70d5d04b974e84107b58c4e2ede8879adfc78 | 621 | nasa-android | Apache License 2.0 |
src/test/kotlin/me/syari/niconico/twitter/SwingSimpleAnimationTest.kt | sya-ri | 307,214,545 | false | null | package me.syari.niconico.twitter
import sun.font.*
import java.awt.*
import javax.swing.*
object SwingSimpleAnimationTest {
@JvmStatic
fun main(args: Array<String>) {
JFrame().apply {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE // バツボタンの処理
title = "SwingSimpleAnimationTest" // ウィンドウタイトル
bounds = Rectangle(900, 600) // ウィンドウサイズを指定
setLocationRelativeTo(null) // ウィンドウを中心に配置
add(
AnimationPanel().apply {
start()
}
)
isVisible = true // ウィンドウを表示
}
}
class AnimationPanel : JPanel() {
private val animationTimer = Timer(10) {
repaint()
}
fun start() {
animationTimer.start()
}
private var helloX = 900
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
val fontMetrics = FontDesignMetrics.getMetrics(g.font)
val needBounds = fontMetrics.getStringBounds("Hello", null)
val isVisible = 0 < (helloX + needBounds.width)
if (isVisible) {
g.drawString("Hello", helloX, 100)
helloX --
} else {
helloX = 900
}
}
}
}
| 3 | Kotlin | 0 | 2 | 7edd67978cc04401edcf75bea56cbd53ff7f9e85 | 1,316 | NicoNicoTwitter | Apache License 2.0 |
data/src/main/kotlin/io/zeebe/zeeqs/data/repository/DecisionEvaluationRepository.kt | camunda-community-hub | 237,922,743 | false | {"Kotlin": 233560, "Shell": 973} | package io.zeebe.zeeqs.data.repository
import io.zeebe.zeeqs.data.entity.DecisionEvaluation
import io.zeebe.zeeqs.data.entity.DecisionEvaluationState
import org.springframework.data.domain.Pageable
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.stereotype.Repository
@Repository
interface DecisionEvaluationRepository : PagingAndSortingRepository<DecisionEvaluation, Long> {
fun findAllByDecisionKey(
decisionKey: Long,
pageable: Pageable
): List<DecisionEvaluation>
fun findAllByDecisionKeyAndStateIn(
decisionKey: Long,
stateIn: List<DecisionEvaluationState>,
pageable: Pageable
): List<DecisionEvaluation>
fun countByDecisionKeyAndStateIn(
decisionKey: Long,
stateIn: List<DecisionEvaluationState>
): Long
fun countByDecisionKey(decisionKey: Long): Long
fun findAllByProcessInstanceKeyAndStateIn(
processInstanceKey: Long,
stateIn: List<DecisionEvaluationState>,
pageable: Pageable
): List<DecisionEvaluation>
fun countByProcessInstanceKeyAndStateIn(
processInstanceKey: Long,
stateIn: List<DecisionEvaluationState>
): Long
fun findAllByElementInstanceKey(elementInstanceKey: Long): List<DecisionEvaluation>
fun countByElementInstanceKey(elementInstanceKey: Long): Long
fun findByStateIn(
stateIn: List<DecisionEvaluationState>,
pageable: Pageable
): List<DecisionEvaluation>
fun countByStateIn(stateIn: List<DecisionEvaluationState>): Long
} | 25 | Kotlin | 15 | 62 | 5410f194d430d51f21058b76fe98a5f2464c93ee | 1,583 | zeeqs | Apache License 2.0 |
app/src/main/java/cz/nestresuju/screens/program/first/ProgramFirstConstants.kt | johnondrej | 371,166,772 | false | null | package cz.nestresuju.screens.program.first
/**
* Common constants related to first program.
*/
object ProgramFirstConstants {
const val PHASES = 6
} | 0 | Kotlin | 0 | 0 | 8d7c54c00c865a370ed24a356abd2bfeeef4ed4b | 157 | nestresuju-android | Apache License 2.0 |
app/src/main/java/com/bruce32/psnprofileviewer/profile/ProfileFragment.kt | jbruce2112 | 509,893,709 | false | {"Kotlin": 139600} | package com.bruce32.psnprofileviewer.profile
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.bruce32.psnprofileviewer.common.GlideImageLoader
import com.bruce32.psnprofileviewer.common.ImageLoader
import com.bruce32.psnprofileviewer.databinding.FragmentProfileBinding
import kotlinx.coroutines.launch
class ProfileFragment(
private val viewModelFactorySource: ProfileViewModelFactorySource = ProfileViewModelFactorySourceImpl(),
private val imageLoader: ImageLoader = GlideImageLoader()
) : Fragment() {
private val viewModel: ProfileViewModel by viewModels {
viewModelFactorySource.factory(requireContext())
}
private var _binding: FragmentProfileBinding? = null
private val binding
get() = checkNotNull(_binding) {
"Binding is null"
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentProfileBinding.inflate(layoutInflater)
viewLifecycleOwner.lifecycleScope.launch {
viewModel.profile.collect {
it?.let {
bind(it)
}
}
}
return binding.root
}
private fun bind(viewModel: ProfileStatsViewModel) {
imageLoader.load(
url = viewModel.imageURL,
view = binding.headingImageView
)
binding.headingView.text = viewModel.heading
binding.subheadingView.text = viewModel.subheading
val linearLayout = binding.statsLayout
linearLayout.removeAllViews()
viewModel.stats.forEach { statViewModel ->
val view = ProfileStatItemView(requireContext())
view.viewModel = statViewModel
linearLayout.addView(view)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0 | Kotlin | 0 | 1 | d9b26d225b4b49127027d826f8dcf2988981bb09 | 2,120 | psnprofile-viewer | MIT License |
knocker/src/main/java/com/aquarids/knocker/ui/SliderLayout.kt | xueshanli | 147,759,637 | true | {"Kotlin": 28846} | package com.aquarids.knocker.ui
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Point
import android.graphics.PointF
import android.support.annotation.IntDef
import android.support.v4.math.MathUtils
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.ViewConfiguration
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.Scroller
import com.aquarids.knocker.R
class SliderLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: FrameLayout(context, attrs, defStyleAttr) {
companion object {
const val NONE = 0x00
const val LEFT_TO_RIGHT = 0x01
const val RIGHT_TO_LEFT = 0x10
const val TOP_TO_BOTTOM = 0x100
const val BOTTOM_TO_TOP = 0x1000
const val HORIZONTAL = LEFT_TO_RIGHT or RIGHT_TO_LEFT
const val VERTICAL = TOP_TO_BOTTOM or BOTTOM_TO_TOP
const val ALL = HORIZONTAL or VERTICAL
}
@IntDef(NONE, LEFT_TO_RIGHT, RIGHT_TO_LEFT, TOP_TO_BOTTOM, BOTTOM_TO_TOP, HORIZONTAL, VERTICAL, ALL)
@Retention(AnnotationRetention.SOURCE)
annotation class SliderDirection
private val mScroller: Scroller
private var mSlideBoundary: Float
@SliderDirection
private var mDirection: Int
@SliderDirection
private var mDragDirection: Int = NONE
private val mViewConfig = ViewConfiguration.get(context)
private var mTracker: VelocityTracker? = null
private val mViewInitialPoint = Point()
private val mFingerCapturePoint = PointF()
private var mHasScrolled = false
private var mSlideFinished = true
var listener: SliderListener? = null
init {
val array = context.obtainStyledAttributes(attrs, R.styleable.SliderLayout)
mSlideBoundary = array.getFraction(R.styleable.SliderLayout_boundary, 1, 1, 0.3f)
val interpolator = array.getResourceId(R.styleable.SliderLayout_interpolator, android.R.interpolator.decelerate_cubic)
mScroller = Scroller(context, AnimationUtils.loadInterpolator(context, interpolator))
mDirection = array.getInt(R.styleable.SliderLayout_direction, LEFT_TO_RIGHT)
array.recycle()
}
override fun computeScroll() {
super.computeScroll()
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.currX, mScroller.currY)
postInvalidateOnAnimation()
} else {
if (!mSlideFinished) {
listener?.onSlide(this, mDragDirection, mHasScrolled)
mDragDirection = NONE
mHasScrolled = false
mSlideFinished = true
}
}
}
override fun onInterceptTouchEvent(motionEvent: MotionEvent?): Boolean {
val action = motionEvent?.action ?: return super.onInterceptTouchEvent(motionEvent)
when (action) {
MotionEvent.ACTION_DOWN -> {
mViewInitialPoint.set(scrollX, scrollY)
mFingerCapturePoint.set(motionEvent.rawX, motionEvent.rawY)
}
MotionEvent.ACTION_MOVE -> {
val deltaX = motionEvent.rawX - mFingerCapturePoint.x
val deltaY = motionEvent.rawY - mFingerCapturePoint.y
if (Math.hypot(deltaX.toDouble(), deltaY.toDouble()) > mViewConfig.scaledTouchSlop) {
val dirX = when {
(mDirection and HORIZONTAL) == HORIZONTAL -> if (deltaX > 0) LEFT_TO_RIGHT else RIGHT_TO_LEFT
(mDirection and HORIZONTAL) == LEFT_TO_RIGHT && deltaX > 0 -> LEFT_TO_RIGHT
(mDirection and HORIZONTAL) == RIGHT_TO_LEFT && deltaX < 0 -> RIGHT_TO_LEFT
else -> NONE
}
val dirY = when {
(mDirection and VERTICAL) == VERTICAL -> if (deltaY > 0) TOP_TO_BOTTOM else BOTTOM_TO_TOP
(mDirection and VERTICAL) == TOP_TO_BOTTOM && deltaY > 0 -> TOP_TO_BOTTOM
(mDirection and VERTICAL) == BOTTOM_TO_TOP && deltaY < 0 -> BOTTOM_TO_TOP
else -> NONE
}
mDragDirection = when {
dirX == NONE -> dirY
dirY == NONE -> dirX
Math.abs(deltaX) > Math.abs(deltaY) -> dirX
Math.abs(deltaX) < Math.abs(deltaY) -> dirY
else -> NONE
}
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
mDragDirection = NONE
}
}
return mDragDirection != NONE
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
val action = event?.action ?: return super.onTouchEvent(event)
if (null == mTracker) {
mTracker = VelocityTracker.obtain()
}
mTracker?.addMovement(event)
when (action) {
MotionEvent.ACTION_DOWN -> {
mViewInitialPoint.set(scrollX, scrollY)
mFingerCapturePoint.set(event.rawX, event.rawY)
}
MotionEvent.ACTION_MOVE -> {
val deltaX = event.rawX - mFingerCapturePoint.x
val deltaY = event.rawY - mFingerCapturePoint.y
if (Math.hypot(deltaX.toDouble(), deltaY.toDouble()) > mViewConfig.scaledTouchSlop) {
val dirX = when {
(mDirection and HORIZONTAL) == HORIZONTAL -> if (deltaX > 0) LEFT_TO_RIGHT else RIGHT_TO_LEFT
(mDirection and HORIZONTAL) == LEFT_TO_RIGHT && deltaX > 0 -> LEFT_TO_RIGHT
(mDirection and HORIZONTAL) == RIGHT_TO_LEFT && deltaX < 0 -> RIGHT_TO_LEFT
else -> NONE
}
val dirY = when {
(mDirection and VERTICAL) == VERTICAL -> if (deltaY > 0) TOP_TO_BOTTOM else BOTTOM_TO_TOP
(mDirection and VERTICAL) == TOP_TO_BOTTOM && deltaY > 0 -> TOP_TO_BOTTOM
(mDirection and VERTICAL) == BOTTOM_TO_TOP && deltaY < 0 -> BOTTOM_TO_TOP
else -> NONE
}
mDragDirection = when {
dirX == NONE -> dirY
dirY == NONE -> dirX
Math.abs(deltaX) > Math.abs(deltaY) -> dirX
Math.abs(deltaX) < Math.abs(deltaY) -> dirY
else -> NONE
}
}
if (mDragDirection != NONE) {
var toX = 0f
var toY = 0f
when (mDragDirection) {
LEFT_TO_RIGHT -> toX = MathUtils.clamp(event.rawX - mFingerCapturePoint.x, 0f, width.toFloat())
RIGHT_TO_LEFT -> toX = MathUtils.clamp(event.rawX - mFingerCapturePoint.x, -width.toFloat(), 0f)
TOP_TO_BOTTOM -> toY = MathUtils.clamp(event.rawY - mFingerCapturePoint.y, 0f, height.toFloat())
BOTTOM_TO_TOP -> toY = MathUtils.clamp(event.rawY - mFingerCapturePoint.y, -height.toFloat(), 0f)
}
scrollTo((mViewInitialPoint.x - toX).toInt(), (mViewInitialPoint.y - toY).toInt())
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (mDragDirection != NONE) {
mTracker?.let { tracker ->
tracker.computeCurrentVelocity(60 * 1000)
var toX = 0
var toY = 0
mHasScrolled = false
when (mDragDirection) {
LEFT_TO_RIGHT -> {
if ((Math.abs(tracker.xVelocity) >= mViewConfig.scaledMinimumFlingVelocity && Math.signum(tracker.xVelocity) > 0)
|| (Math.abs(tracker.xVelocity) < mViewConfig.scaledMinimumFlingVelocity && -scrollX > width * mSlideBoundary)) {
mHasScrolled = true
toX = -width
}
}
RIGHT_TO_LEFT -> {
if ((Math.abs(tracker.xVelocity) >= mViewConfig.scaledMinimumFlingVelocity && Math.signum(tracker.xVelocity) < 0)
|| (Math.abs(tracker.xVelocity) < mViewConfig.scaledMinimumFlingVelocity && -scrollX < -width * mSlideBoundary)) {
mHasScrolled = true
toX = width
}
}
TOP_TO_BOTTOM -> {
if ((Math.abs(tracker.yVelocity) >= mViewConfig.scaledMinimumFlingVelocity && Math.signum(tracker.yVelocity) > 0)
|| (Math.abs(tracker.yVelocity) < mViewConfig.scaledMinimumFlingVelocity && -scrollY > height * mSlideBoundary)) {
mHasScrolled = true
toY = -height
}
}
BOTTOM_TO_TOP -> {
if ((Math.abs(tracker.yVelocity) >= mViewConfig.scaledMinimumFlingVelocity && Math.signum(tracker.yVelocity) < 0)
|| (Math.abs(tracker.yVelocity) < mViewConfig.scaledMinimumFlingVelocity && -scrollY < -height * mSlideBoundary)) {
mHasScrolled = true
toY = height
}
}
}
mSlideFinished = false
mScroller.startScroll(scrollX, scrollY, toX - scrollX, toY - scrollY)
invalidate()
}
}
mTracker?.recycle()
mTracker = null
}
}
return true
}
interface SliderListener {
fun onSlide(view: SliderLayout, @SliderDirection direction: Int, hasScrolled: Boolean)
}
} | 0 | Kotlin | 0 | 0 | a8d07c9c80a6b34ba0805d68d93b7883e343d44f | 10,494 | Knocker | Apache License 2.0 |
src/main/kotlin/com/example/domain/reppository/user/UsersRepository.kt | KhubaibKhan4 | 781,401,447 | false | {"Kotlin": 59750} | package com.example.domain.reppository.user
import com.auth0.jwt.JWT
import com.auth0.jwt.JWTVerifier
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.exceptions.JWTVerificationException
import com.auth0.jwt.exceptions.TokenExpiredException
import com.auth0.jwt.interfaces.Payload
import com.example.data.local.table.db.DatabaseFactory
import com.example.data.local.table.user.UserTable
import com.example.data.repository.users.UsersDao
import com.example.domain.model.user.Users
import org.h2.engine.User
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.statements.InsertStatement
import org.jetbrains.exposed.sql.transactions.transaction
import java.security.MessageDigest
import java.util.*
class UsersRepository : UsersDao {
private val jwtSecret: String= "sectret"
private val jwtAudience: String = "jwtAudience"
private val jwtIssuer: String ="jwtIssuer"
private fun rowToResult(row: ResultRow): Users? {
if (row == null) {
return null
} else {
return Users(
id = row[UserTable.id],
username = row[UserTable.username],
email = row[UserTable.email],
password = row[UserTable.password],
fullName = row[UserTable.fullName],
address = row[UserTable.address],
city = row[UserTable.city],
country = row[UserTable.country],
phoneNumber = row[UserTable.phoneNumber],
userRole = row[UserTable.userRole]
)
}
}
override suspend fun insert(
username: String,
email: String,
password: String,
fullName: String,
address: String,
city: String,
country: String,
phoneNumber: String,
userRole: String
): Users? {
var statement: InsertStatement<Number>? = null
DatabaseFactory.dbQuery {
statement = UserTable.insert { users ->
users[UserTable.username] = username
users[UserTable.email] = email
users[UserTable.password] = <PASSWORD>(password)
users[UserTable.fullName] = fullName
users[UserTable.address] = address
users[UserTable.city] = city
users[UserTable.country] = country
users[UserTable.phoneNumber] = phoneNumber
users[UserTable.userRole] = userRole
}
}
return rowToResult(statement?.resultedValues?.get(0)!!)
}
override suspend fun login(email: String, password: String): Users? {
var user: Users? = null
transaction {
val result = UserTable.select { UserTable.email eq email }.singleOrNull()
result?.let { row ->
val storedPassword = row[UserTable.password]
if (verifyPassword(password, storedPassword)) {
user = rowToResult(row)
}
}
}
return user
}
override suspend fun getAllUsers(): List<Users>? =
DatabaseFactory.dbQuery {
UserTable.selectAll().mapNotNull {
rowToResult(it)
}
}
override suspend fun getUserById(id: Long): Users? =
DatabaseFactory.dbQuery {
UserTable.select { UserTable.id.eq(id) }
.map {
rowToResult(it)
}.singleOrNull()
}
override suspend fun deleteUserById(id: Long): Int =
DatabaseFactory.dbQuery {
UserTable.deleteWhere { UserTable.id.eq(id) }
}
override suspend fun updateUsers(
id: Long,
username: String,
email: String,
password: String,
fullName: String,
address: String,
city: String,
country: String,
phoneNumber: String
): Int =
DatabaseFactory.dbQuery {
UserTable.update({ UserTable.id.eq(id) }) { user ->
user[UserTable.id] = id
user[UserTable.username] = username
user[UserTable.email] = email
user[UserTable.password] = <PASSWORD>(password)
user[UserTable.fullName] = fullName
user[UserTable.address] = address
user[UserTable.city] = city
user[UserTable.country]= country
user[UserTable.phoneNumber] = phoneNumber
}
}
private val jwtVerifier : JWTVerifier = JWT.require(Algorithm.HMAC256(jwtSecret))
.withAudience(jwtAudience)
.withIssuer(jwtIssuer)
.build()
private fun generateJwtToken(password: String): String {
val expirationTimeMillis = System.currentTimeMillis() + 3600 * 1000
return JWT.create()
.withAudience(jwtAudience)
.withIssuer(jwtIssuer)
.withSubject(password)
.withExpiresAt(Date(expirationTimeMillis))
.sign(Algorithm.HMAC256(jwtSecret))
}
fun validateJwtToken(token: String): String? {
return try {
val payload: Payload = jwtVerifier.verify(token)
payload.subject
} catch (e: TokenExpiredException) {
println("Token has expired: ${e.message}")
null
} catch (e: JWTVerificationException) {
println("JWT verification failed: ${e.message}")
null
}
}
private fun hashPassword(password: String): String {
val digest = MessageDigest.getInstance("SHA-256")
val hashedBytes = digest.digest(password.toByteArray(Charsets.UTF_8))
return hashedBytes.joinToString("") { "%02x".format(it) }
}
private fun verifyPassword(providedPassword: String, hashedPassword: String): Boolean {
val hashedProvidedPassword = hashPassword(providedPassword)
return hashedProvidedPassword == hashedPassword
}
} | 0 | Kotlin | 0 | 3 | 1f54c3f64a2c60ddb13152c624258187a0d81049 | 6,027 | Flexi-Store-Server | MIT License |
SceytChatUiKit/src/main/java/com/sceyt/sceytchatuikit/sceytconfigs/dateformaters/DateFormatData.kt | sceyt | 549,073,085 | false | null | package com.sceyt.sceytchatuikit.sceytconfigs.dateformaters
data class DateFormatData(
var format: String? = null,
var beginTittle: String = "",
var endTitle: String = ""
) | 0 | Kotlin | 0 | 0 | 0b135841180b7c4fdd66b1b0f7655d8d79fe8a03 | 197 | sceyt-chat-android-uikit | MIT License |
app/src/main/java/com/example/todolist/utilities/TextInputLayoutUtils.kt | Alfser | 393,834,919 | false | null | package com.example.todolist.utilities
import com.google.android.material.textfield.TextInputLayout
var TextInputLayout.text
get() = this.editText?.text.toString()
set(value) {
this.editText?.setText(value)
} | 0 | Kotlin | 0 | 0 | 48cdb4d8911e08fe546b834646a01bd8e513ab6b | 230 | todolist | Apache License 2.0 |
src/main/kotlin/de/flapdoodle/statik/pipeline/documents/DocumentSetsFromFileSets.kt | flapdoodle-oss | 350,813,259 | false | null | package de.flapdoodle.statik.pipeline.documents
import de.flapdoodle.statik.documents.Document
import de.flapdoodle.statik.documents.DocumentSet
import de.flapdoodle.statik.files.FileSet
interface DocumentSetsFromFileSets {
fun scan(fileSets: List<FileSet>): List<DocumentSet>
} | 0 | Kotlin | 1 | 0 | 347ea640ac74ed937f362dfe4d3b42c50c50a8c8 | 284 | de.flapdoodle.static | Apache License 2.0 |
src/main/kotlin/archive/Check.kt | QuietJoon | 163,394,000 | false | {"Kotlin": 149037} | package archive
import ArchiveSetPaths
import Message
import MessageType
import util.checkMissingMultiVolumeFile
import directoryDelimiter
import Path
// TODO: Implement checking missing volume or integrity of archive
fun checkArchiveVolume(packagedFilePaths: Array<ArchiveSetPaths>): Message {
if (packagedFilePaths.size <= 1)
return Pair(MessageType.Warning, "Only one\nArchiveSet")
val paths = mutableListOf<Path>()
for (archiveSetPaths in packagedFilePaths) {
for (archivePaths in archiveSetPaths) {
for (aPath in archivePaths) {
paths.add(aPath.joinToString(separator = directoryDelimiter))
}
}
}
val checks = checkMissingMultiVolumeFile(paths)
val missings = mutableListOf<Path>()
val corrupts = mutableListOf<Path>()
var mcPaths = ""
var isMissing = false
for (check in checks) {
if (check.isMissing) {
isMissing = true
for (missing in check.missingVolumes) {
missings.add(missing)
mcPaths += missing + "\n"
}
for (corrupted in check.corruptedVolumes) {
corrupts.add(corrupted)
mcPaths += corrupted + "\n"
}
}
}
if (isMissing) {
return Pair(MessageType.Critical, "Missing volume\n${mcPaths}")
}
return Pair(MessageType.NoProblem, "No Problem\nwith Archive Volume")
}
| 0 | Kotlin | 0 | 0 | 81ec0bed882c04d2fbdfdc56914547a555195021 | 1,444 | ArchiveDiffer-Kotlin | MIT License |
shuttle/design/src/main/kotlin/shuttle/design/util/Effect.kt | fardavide | 462,194,990 | false | {"Kotlin": 465845, "Shell": 11573} | package shuttle.design.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import kotlinx.coroutines.CoroutineScope
/**
* This is a container for single-use state.
* Use this when you don't want an event to be repeated, for example while emitting an error to the ViewModel
*
* You usually wanna consume this into a `LaunchedEffect` block
*/
class Effect<T : Any> private constructor(private var event: T?) {
/**
* @return the [event] if not consumed, `null` otherwise
*/
fun consume(): T? = event
.also { event = null }
companion object {
fun <T : Any> of(event: T) = Effect(event)
fun <T : Any> empty() = Effect<T>(null)
}
}
fun Effect.Companion.ofUnit() = of(Unit)
/**
* Executes a [LaunchedEffect] in the scope of [effect]
* @param block will be called only when there is an [Effect.event] to consume
*/
@Composable
fun <T : Any> ConsumableLaunchedEffect(effect: Effect<T>, block: suspend CoroutineScope.(T) -> Unit) {
effect.consume()?.let { event ->
LaunchedEffect(event) {
block(event)
}
}
}
| 12 | Kotlin | 1 | 14 | bd4faa49be9c3787b5b8786edc2a014a45969c1e | 1,142 | Shuttle | Apache License 2.0 |
example/spring-data-mongodb/src/main/kotlin/com/github/inflab/example/spring/data/mongodb/repository/atlas/PathSearchRepository.kt | inflearn | 686,606,328 | false | {"Kotlin": 816570} | package com.github.inflab.example.spring.data.mongodb.repository.atlas
import com.github.inflab.spring.data.mongodb.core.aggregation.aggregation
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.aggregate
import org.springframework.data.mongodb.core.aggregation.AggregationResults
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.stereotype.Repository
@Repository
class PathSearchRepository(
private val mongoTemplate: MongoTemplate,
) {
data class Warehouse(val inventory: Int, val color: String)
@Document("cars")
data class Car(
val id: Long,
val type: String,
val make: String,
val description: String,
val warehouse: List<Warehouse>?,
)
/**
* @see <a href="https://www.mongodb.com/docs/atlas/atlas-search/path-construction/#single-field-search">Single Field Search</a>
*/
fun findBySingleField(): AggregationResults<Car> {
val aggregation = aggregation {
search {
text {
query("Ford")
path { +Car::make }
}
}
}
return mongoTemplate.aggregate<Car, Car>(aggregation)
}
/**
* @see <a href="https://www.mongodb.com/docs/atlas/atlas-search/path-construction/#multiple-field-search">Multiple Field Search</a>
*/
fun findByMultipleField(): AggregationResults<Car> {
val aggregation = aggregation {
search {
text {
query("blue")
path {
+Car::make
+Car::description
}
}
}
}
return mongoTemplate.aggregate<Car, Car>(aggregation)
}
/**
* @see <a href="https://www.mongodb.com/docs/atlas/atlas-search/path-construction/#simple-analyzer-example">Simple Analyzer Example</a>
*/
fun findBySimpleAnalyzer(): AggregationResults<Car> {
val aggregation = aggregation {
search {
text {
query("driver")
path {
Car::description multi "simpleAnalyzer"
}
}
}
}
return mongoTemplate.aggregate<Car, Car>(aggregation)
}
/**
* @see <a href="https://www.mongodb.com/docs/atlas/atlas-search/path-construction/#whitespace-analyzer-example">Whitespace Analyzer Example</a>
*/
fun findByWhitespaceAnalyzer(): AggregationResults<Car> {
val aggregation = aggregation {
search {
text {
query("Three")
path {
Car::description multi "simpleAnalyzer"
}
}
}
}
return mongoTemplate.aggregate<Car, Car>(aggregation)
}
/**
* @see <a href="https://www.mongodb.com/docs/atlas/atlas-search/path-construction/#all-fields-search-example">All Fields Search Example</a>
*/
fun findByWildcard(): AggregationResults<Car> {
val aggregation = aggregation {
search {
phrase {
path { wildcard() }
query("red")
}
}
}
return mongoTemplate.aggregate<Car, Car>(aggregation)
}
/**
* @see <a href="https://www.mongodb.com/docs/atlas/atlas-search/path-construction/#nested-field-search-example">Nested Field Search Example</a>
*/
fun findByNestedWildcard(): AggregationResults<Car> {
val aggregation = aggregation {
search {
text {
path { Car::warehouse.ofWildcard() }
query("red")
}
}
}
return mongoTemplate.aggregate<Car, Car>(aggregation)
}
}
| 9 | Kotlin | 6 | 9 | d0a2feb4c518d61003bfd3fcde2f13825ea1e4d5 | 3,966 | spring-data-mongodb-kotlin-dsl | MIT License |
Android/app/src/main/java/live/ditto/pos/core/domain/usecase/IsUsingDemoLocationsUseCase.kt | getditto | 660,393,373 | false | {"Kotlin": 118261, "Swift": 108298, "Shell": 1686} | package live.ditto.pos.core.domain.usecase
import live.ditto.pos.core.domain.repository.CoreRepository
import javax.inject.Inject
class IsUsingDemoLocationsUseCase @Inject constructor(
private val coreRepository: CoreRepository
) {
suspend operator fun invoke(): Boolean {
return coreRepository.isUsingDemoLocations() ?: false
}
}
| 14 | Kotlin | 0 | 3 | 669dcb812c668d172891090bc4925c29757776e7 | 354 | demoapp-pos-kds | MIT License |
app/src/main/java/com/karumi/androidanimations/MainActivity.kt | Karumi | 179,509,306 | false | null | package com.karumi.androidanimations
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
configureToolbar()
}
private fun configureToolbar() {
val navController = findNavController(R.id.hostFragment)
navController.addOnDestinationChangedListener { _, destination, _ ->
collapsingToolbarLayout.isTitleEnabled = false
collapsingToolbarLayout.title = destination.label
}
val appBarConfiguration = AppBarConfiguration(navController.graph)
toolbar.setupWithNavController(navController, appBarConfiguration)
}
}
| 9 | Kotlin | 5 | 22 | 97ba0e1423d701afe243614665655201e0333af4 | 1,006 | AndroidAnimations | Apache License 2.0 |
sampleandroidlib/src/main/java/com/enefce/libraries/sampleandroidlib/SampleAndroidLibMain.kt | enefce | 220,181,606 | false | null | package com.enefce.libraries.sampleandroidlib
class SampleAndroidLibMain(val welcomeString: String = "Welcome to the sample implementation of an Android Library project published on GitHub Packages Registry") | 3 | Kotlin | 34 | 47 | 99b19e128679b5a7155002474d33d49dd6f5f601 | 209 | AndroidLibraryForGitHubPackagesDemo | Apache License 2.0 |
app/src/main/java/com/realitix/mealassistant/viewmodel/ReceipeAddSearchViewModel.kt | realitix | 235,808,420 | false | null | package com.realitix.mealassistant.viewmodel
import androidx.lifecycle.*
import com.realitix.mealassistant.database.entity.MealReceipe
import com.realitix.mealassistant.database.entity.ReceipeStepReceipe
import com.realitix.mealassistant.repository.MealRepository
import com.realitix.mealassistant.repository.ReceipeRepository
import com.realitix.mealassistant.util.MealReceipeEnum
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class ReceipeAddSearchViewModel (
private val receipeRepository: ReceipeRepository,
private val mealRepository: MealRepository,
val objId: Long,
val enumId: Int
) : ViewModel() {
private val receipeSearchTerm: MutableLiveData<String> by lazy { MutableLiveData<String>() }
val receipes = receipeSearchTerm.switchMap { receipeRepository.search(it) }
fun searchReceipes(name: String) {
receipeSearchTerm.value = name
}
fun create(linkedReceipeId: Long) {
when (enumId) {
MealReceipeEnum.RECEIPE -> createReceipeStepReceipe(linkedReceipeId)
MealReceipeEnum.MEAL -> createMealReceipe(linkedReceipeId)
}
}
private fun createReceipeStepReceipe(linkedReceipeId: Long) {
val c = ReceipeStepReceipe(linkedReceipeId, objId)
GlobalScope.launch {
receipeRepository.createReceipeStepReceipe(c)
}
}
private fun createMealReceipe(linkedReceipeId: Long) {
val c = MealReceipe(linkedReceipeId, objId)
GlobalScope.launch {
mealRepository.createMealReceipe(c)
}
}
} | 0 | Kotlin | 0 | 0 | 0ea82b9e83d9e50dc848fe52010ca3bbae1b8e2b | 1,580 | meal-assistant-android | Apache License 2.0 |
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/photos/methods/PhotosSaveOwnerCoverPhotoMethod.kt | alatushkin | 156,866,851 | false | null | package name.alatushkin.api.vk.generated.photos.methods
import com.fasterxml.jackson.core.type.TypeReference
import name.alatushkin.api.vk.VkMethod
import name.alatushkin.api.vk.api.VkSuccess
import name.alatushkin.api.vk.generated.common.Image
/**
* Saves cover photo after successful uploading.
*
* [https://vk.com/dev/photos.saveOwnerCoverPhoto]
* @property [photo] Parameter returned when photos are [vk.com/dev/upload_files|uploaded to server].
* @property [hash] Parameter returned when photos are [vk.com/dev/upload_files|uploaded to server].
*/
class PhotosSaveOwnerCoverPhotoMethod() : VkMethod<Array<Image>>(
"photos.saveOwnerCoverPhoto",
HashMap()
) {
var photo: String? by props
var hash: String? by props
constructor(
photo: String? = null,
hash: String? = null
) : this() {
this.photo = photo
this.hash = hash
}
fun setPhoto(photo: String): PhotosSaveOwnerCoverPhotoMethod {
this.photo = photo
return this
}
fun setHash(hash: String): PhotosSaveOwnerCoverPhotoMethod {
this.hash = hash
return this
}
override val classRef = PhotosSaveOwnerCoverPhotoMethod.classRef
companion object {
val classRef = object : TypeReference<VkSuccess<Array<Image>>>() {}
}
}
| 2 | Kotlin | 3 | 10 | 123bd61b24be70f9bbf044328b98a3901523cb1b | 1,316 | kotlin-vk-api | MIT License |
app/src/main/java/wutheringwavesguide/models/api/characterdetail/Description.kt | nikunj3011 | 810,402,672 | false | {"Kotlin": 247322} | package wutheringwavesguide.models.api.characterdetail
data class Description(
val raw: String
) | 0 | Kotlin | 0 | 0 | 9bf0e2f5bcae9938c522d9aa604777d791c2a9da | 101 | Wuthering.Waves.Android.Kotlin | MIT License |
kotlin-gremlin-ogm/src/main/kotlin/org/apache/tinkerpop/gremlin/ogm/mappers/BiMapper.kt | pm-dev | 128,978,530 | false | {"Kotlin": 352567, "JavaScript": 52832, "TypeScript": 10121, "HTML": 3834, "Python": 1309, "Shell": 1279, "CSS": 196} | package org.apache.tinkerpop.gremlin.ogm.mappers
/**
* A function that is also able to map elements to its co-domain to its domain
*/
interface BiMapper<X : Any?, Y : Any?> {
/**
* Maps an object of type X to an object of type Y. It is expected that the value
* returned by this function could be passed to [inverseMap] and an object equal to
* 'from' would be returned.
*/
fun forwardMap(from: X): Y
/**
* Maps an object of type Y to an object of type X. It is expected that the value
* returned by this function could be passed to [forwardMap] and an object equal to
* 'from' would be returned.
*/
fun inverseMap(from: Y): X
}
| 1 | Kotlin | 6 | 31 | 8197847f310bd9928ff1eccb7733b59830e3c12e | 690 | kotlin-gremlin-ogm | Apache License 2.0 |
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/unlock/UnlockViewModel.kt | aivanovski | 95,774,290 | false | null | package com.ivanovsky.passnotes.presentation.unlock
import androidx.annotation.IdRes
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.github.terrakok.cicerone.Router
import com.ivanovsky.passnotes.BuildConfig
import com.ivanovsky.passnotes.R
import com.ivanovsky.passnotes.data.ObserverBus
import com.ivanovsky.passnotes.data.entity.ConflictResolutionStrategy
import com.ivanovsky.passnotes.data.entity.FSAuthority
import com.ivanovsky.passnotes.data.entity.FileDescriptor
import com.ivanovsky.passnotes.data.entity.Note
import com.ivanovsky.passnotes.data.entity.SyncConflictInfo
import com.ivanovsky.passnotes.data.entity.SyncProgressStatus
import com.ivanovsky.passnotes.data.entity.SyncState
import com.ivanovsky.passnotes.data.entity.SyncStatus
import com.ivanovsky.passnotes.data.repository.keepass.KeepassDatabaseKey
import com.ivanovsky.passnotes.domain.DispatcherProvider
import com.ivanovsky.passnotes.domain.ResourceProvider
import com.ivanovsky.passnotes.domain.interactor.ErrorInteractor
import com.ivanovsky.passnotes.domain.interactor.unlock.UnlockInteractor
import com.ivanovsky.passnotes.extensions.toUsedFile
import com.ivanovsky.passnotes.injection.GlobalInjector
import com.ivanovsky.passnotes.presentation.ApplicationLaunchMode
import com.ivanovsky.passnotes.presentation.ApplicationLaunchMode.AUTOFILL_AUTHORIZATION
import com.ivanovsky.passnotes.presentation.Screens
import com.ivanovsky.passnotes.presentation.Screens.GroupsScreen
import com.ivanovsky.passnotes.presentation.Screens.NewDatabaseScreen
import com.ivanovsky.passnotes.presentation.Screens.SelectDatabaseScreen
import com.ivanovsky.passnotes.presentation.Screens.StorageListScreen
import com.ivanovsky.passnotes.presentation.autofill.model.AutofillStructure
import com.ivanovsky.passnotes.presentation.core.BaseCellViewModel
import com.ivanovsky.passnotes.presentation.core.DefaultScreenStateHandler
import com.ivanovsky.passnotes.presentation.core.ScreenState
import com.ivanovsky.passnotes.presentation.core.ViewModelTypes
import com.ivanovsky.passnotes.presentation.core.event.EventProviderImpl
import com.ivanovsky.passnotes.presentation.core.event.SingleLiveEvent
import com.ivanovsky.passnotes.presentation.core.menu.ScreenMenuItem
import com.ivanovsky.passnotes.presentation.core.widget.ExpandableFloatingActionButton.OnItemClickListener
import com.ivanovsky.passnotes.presentation.groups.GroupsScreenArgs
import com.ivanovsky.passnotes.presentation.note_editor.view.TextTransformationMethod
import com.ivanovsky.passnotes.presentation.selectdb.SelectDatabaseArgs
import com.ivanovsky.passnotes.presentation.server_login.ServerLoginArgs
import com.ivanovsky.passnotes.presentation.storagelist.Action
import com.ivanovsky.passnotes.presentation.unlock.cells.factory.UnlockCellModelFactory
import com.ivanovsky.passnotes.presentation.unlock.cells.factory.UnlockCellViewModelFactory
import com.ivanovsky.passnotes.presentation.unlock.cells.model.DatabaseCellModel
import com.ivanovsky.passnotes.presentation.unlock.cells.viewmodel.DatabaseCellViewModel
import com.ivanovsky.passnotes.presentation.unlock.model.PasswordRule
import com.ivanovsky.passnotes.util.FileUtils
import com.ivanovsky.passnotes.util.StringUtils.EMPTY
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.core.parameter.parametersOf
import java.util.ArrayList
import java.util.regex.Pattern
class UnlockViewModel(
private val interactor: UnlockInteractor,
private val errorInteractor: ErrorInteractor,
private val observerBus: ObserverBus,
private val resourceProvider: ResourceProvider,
private val dispatchers: DispatcherProvider,
private val modelFactory: UnlockCellModelFactory,
private val viewModelFactory: UnlockCellViewModelFactory,
private val router: Router,
private val args: UnlockScreenArgs
) : ViewModel(),
ObserverBus.UsedFileDataSetObserver,
ObserverBus.UsedFileContentObserver,
ObserverBus.SyncProgressStatusObserver {
val screenStateHandler = DefaultScreenStateHandler()
val screenState = MutableLiveData(ScreenState.loading())
val password = MutableLiveData(EMPTY)
val passwordTransformationMethod = MutableLiveData(TextTransformationMethod.PASSWORD)
val hideKeyboardEvent = SingleLiveEvent<Unit>()
val showSnackbarMessage = SingleLiveEvent<String>()
val sendAutofillResponseEvent = SingleLiveEvent<Pair<Note?, AutofillStructure>>()
val fileCellViewModels = MutableLiveData<List<BaseCellViewModel>>()
val isFabButtonVisible = MutableLiveData(false)
val visibleMenuItems = MutableLiveData<List<UnlockMenuItem>>(emptyList())
val fileCellTypes = ViewModelTypes()
.add(DatabaseCellViewModel::class, R.layout.cell_database)
val showResolveConflictDialog = SingleLiveEvent<SyncConflictInfo>()
val fabItems = FAB_ITEMS
.map { (_, resId) -> resourceProvider.getString(resId) }
val fabClickListener = object : OnItemClickListener {
override fun onItemClicked(position: Int) {
onFabItemClicked(position)
}
}
private var selectedFile: FileDescriptor? = null
private var recentlyUsedFiles: List<FileDescriptor>? = null
private val debugPasswordRules: List<PasswordRule>
private var errorPanelButtonAction: ErrorPanelButtonAction? = null
init {
observerBus.register(this)
debugPasswordRules = if (BuildConfig.DEBUG) {
createDebugPasswordRulesForAutoFill()
} else {
emptyList()
}
}
override fun onCleared() {
super.onCleared()
observerBus.unregister(this)
}
override fun onUsedFileDataSetChanged() {
loadData(resetSelection = true)
}
override fun onUsedFileContentChanged(usedFileId: Int) {
loadData(resetSelection = false)
}
fun onScreenStart() {
closeActiveDatabaseIfNeed()
}
fun loadData(resetSelection: Boolean) {
setScreenState(ScreenState.loading())
viewModelScope.launch {
val result = interactor.getRecentlyOpenedFiles()
if (result.isSucceededOrDeferred) {
val files = result.obj
if (files.isNotEmpty()) {
recentlyUsedFiles = files
if (resetSelection) {
selectedFile = null
}
val selectedFile = takeAlreadySelectedOrFirst(files)
if (selectedFile != null) {
setSelectedFile(selectedFile)
} else {
removeSelectedFileCell()
}
setScreenState(ScreenState.data())
} else {
val emptyText = resourceProvider.getString(R.string.no_databases)
setScreenState(ScreenState.empty(emptyText))
}
} else {
val message = errorInteractor.processAndGetMessage(result.error)
setScreenState(ScreenState.error(message))
}
}
}
fun onErrorPanelButtonClicked() {
val action = errorPanelButtonAction ?: return
when (action) {
ErrorPanelButtonAction.RESOLVE_CONFLICT -> {
onResolveConflictButtonClicked()
}
ErrorPanelButtonAction.REMOVE_FILE -> {
onRemoveFileButtonClicked()
}
ErrorPanelButtonAction.AUTHORISATION -> {
onLoginButtonClicked()
}
}
}
fun onResolveConflictConfirmed(resolutionStrategy: ConflictResolutionStrategy) {
val selectFile = selectedFile ?: return
setScreenState(ScreenState.loading())
viewModelScope.launch {
val resolvedConflict = interactor.resolveConflict(selectFile, resolutionStrategy)
if (resolvedConflict.isSucceeded) {
loadData(resetSelection = false)
} else {
setScreenState(
ScreenState.dataWithError(
errorText = errorInteractor.processAndGetMessage(resolvedConflict.error)
)
)
}
}
}
private fun indexOfFile(files: List<FileDescriptor>, fileToFind: FileDescriptor): Int {
return files.indexOfFirst { file -> isFileEqualsByUidAndFsType(file, fileToFind) }
}
private fun isFileEqualsByUidAndFsType(lhs: FileDescriptor, rhs: FileDescriptor): Boolean {
return lhs.uid == rhs.uid && lhs.fsAuthority == rhs.fsAuthority
}
fun onUnlockButtonClicked() {
val password = this.password.value ?: return
val selectedFile = selectedFile ?: return
hideKeyboardEvent.call()
setScreenState(ScreenState.loading())
val key = KeepassDatabaseKey(password)
viewModelScope.launch {
val open = interactor.openDatabase(key, selectedFile)
if (open.isSucceededOrDeferred) {
onDatabaseUnlocked()
} else {
setScreenState(
ScreenState.dataWithError(
errorText = errorInteractor.processAndGetMessage(open.error)
)
)
}
}
}
fun onRefreshButtonClicked() {
loadData(resetSelection = false)
}
private suspend fun onDatabaseUnlocked() {
when (args.appMode) {
AUTOFILL_AUTHORIZATION -> {
val structure = args.autofillStructure ?: return
val autofillNoteResult = interactor.findNoteForAutofill(structure)
if (autofillNoteResult.isSucceeded) {
val note = autofillNoteResult.obj
sendAutofillResponseEvent.call(Pair(note, structure))
} else {
setScreenState(
ScreenState.dataWithError(
errorText = errorInteractor.processAndGetMessage(autofillNoteResult.error)
)
)
}
}
else -> {
clearEnteredPassword()
router.newChain(
GroupsScreen(
GroupsScreenArgs(
appMode = args.appMode,
groupUid = null,
isCloseDatabaseOnExit = true,
autofillStructure = args.autofillStructure,
note = args.note
)
)
)
setScreenState(ScreenState.data())
}
}
}
private fun navigateToFilePicker() {
router.setResultListener(StorageListScreen.RESULT_KEY) { file ->
if (file is FileDescriptor) {
onFilePicked(file)
}
}
router.navigateTo(StorageListScreen(Action.PICK_FILE))
}
fun onPasswordVisibilityButtonClicked() {
val currentTransformation = passwordTransformationMethod.value ?: return
passwordTransformationMethod.value = when (currentTransformation) {
TextTransformationMethod.PASSWORD -> TextTransformationMethod.PLANE_TEXT
TextTransformationMethod.PLANE_TEXT -> TextTransformationMethod.PASSWORD
}
}
private fun onFilePicked(file: FileDescriptor) {
//called when user select file from built-in file picker
setScreenState(ScreenState.loading())
val usedFile = file.toUsedFile(addedTime = System.currentTimeMillis())
viewModelScope.launch {
val result = withContext(dispatchers.Default) {
interactor.saveUsedFileWithoutAccessTime(usedFile)
}
if (result.isSucceededOrDeferred) {
loadData(resetSelection = false)
} else {
setScreenState(ScreenState.data())
val message = errorInteractor.processAndGetMessage(result.error)
showSnackbarMessage.call(message)
}
}
}
private fun navigateToSelectDatabaseScreen() {
val selectedFile = selectedFile ?: return
router.setResultListener(SelectDatabaseScreen.RESULT_KEY) { file ->
if (file is FileDescriptor) {
setSelectedFile(file)
}
}
router.navigateTo(
SelectDatabaseScreen(
SelectDatabaseArgs(
selectedFile = selectedFile
)
)
)
}
private fun onFabItemClicked(position: Int) {
when (position) {
FAB_ITEM_NEW_FILE -> router.navigateTo(NewDatabaseScreen())
FAB_ITEM_OPEN_FILE -> navigateToFilePicker()
}
}
private fun createDebugPasswordRulesForAutoFill(): List<PasswordRule> {
val rules = ArrayList<PasswordRule>()
if (BuildConfig.DEBUG_FILE_NAME_PATTERNS != null && BuildConfig.DEBUG_PASSWORDS != null) {
for (idx in BuildConfig.DEBUG_FILE_NAME_PATTERNS.indices) {
val fileNamePattern = BuildConfig.DEBUG_FILE_NAME_PATTERNS[idx]
val password = BuildConfig.DEBUG_PASSWORDS[idx]
val pattern = Pattern.compile(fileNamePattern)
rules.add(
PasswordRule(
pattern,
password
)
)
}
}
return rules
}
private fun closeActiveDatabaseIfNeed() {
if (interactor.hasActiveDatabase()) {
viewModelScope.launch {
val closeResult = withContext(dispatchers.IO) {
interactor.closeActiveDatabase()
}
if (closeResult.isFailed) {
val message = errorInteractor.processAndGetMessage(closeResult.error)
setScreenState(ScreenState.error(message))
}
}
}
}
private fun takeAlreadySelectedOrFirst(files: List<FileDescriptor>): FileDescriptor? {
if (files.isEmpty()) return null
val selectedFile = this.selectedFile
return if (selectedFile == null) {
files[0]
} else {
val fileIndex = indexOfFile(files, selectedFile)
if (fileIndex != -1) {
selectedFile
} else {
files[0]
}
}
}
private fun setSelectedFile(file: FileDescriptor) {
this.selectedFile = file
val files = recentlyUsedFiles ?: return
fillPasswordIfNeed()
setSelectedFileCell(
modelFactory.createFileCellModel(
file = file,
syncState = null,
isNextButtonVisible = files.size > 1,
onFileClicked = { navigateToSelectDatabaseScreen() }
)
)
viewModelScope.launch {
val syncState = interactor.getSyncState(file)
onSyncStateReceived(file, syncState)
}
}
private fun fillPasswordIfNeed() {
if (!BuildConfig.DEBUG) return
val file = selectedFile ?: return
val fileNameWithoutExtension = FileUtils.removeFileExtensionsIfNeed(file.name)
for (passwordRule in debugPasswordRules) {
if (passwordRule.pattern.matcher(fileNameWithoutExtension).matches()) {
password.value = passwordRule.password
}
}
}
override fun onSyncProgressStatusChanged(
fsAuthority: FSAuthority,
uid: String,
status: SyncProgressStatus
) {
val selectedFile = this.selectedFile ?: return
if (selectedFile.uid == uid && selectedFile.fsAuthority == fsAuthority) {
viewModelScope.launch {
val syncState = interactor.getSyncState(selectedFile)
onSyncStateReceived(selectedFile, syncState)
}
}
}
private fun onSyncStateReceived(file: FileDescriptor, syncState: SyncState) {
if (file != selectedFile) return
val files = recentlyUsedFiles ?: return
setSelectedFileCell(
modelFactory.createFileCellModel(
file = file,
syncState = syncState,
isNextButtonVisible = files.size > 1,
onFileClicked = { navigateToSelectDatabaseScreen() }
)
)
when (syncState.status) {
SyncStatus.CONFLICT -> {
setScreenState(
ScreenState.dataWithError(
errorText = resourceProvider.getString(R.string.sync_conflict_message),
errorButtonText = resourceProvider.getString(R.string.resolve)
)
)
errorPanelButtonAction = ErrorPanelButtonAction.RESOLVE_CONFLICT
}
SyncStatus.ERROR -> {
setScreenState(
ScreenState.dataWithError(
errorText = resourceProvider.getString(R.string.sync_error_message),
errorButtonText = resourceProvider.getString(R.string.remove)
)
)
errorPanelButtonAction = ErrorPanelButtonAction.REMOVE_FILE
}
SyncStatus.AUTH_ERROR -> {
setScreenState(
ScreenState.dataWithError(
errorText = resourceProvider.getString(R.string.sync_auth_error_message),
errorButtonText = resourceProvider.getString(R.string.login)
)
)
errorPanelButtonAction = ErrorPanelButtonAction.AUTHORISATION
}
else -> {
errorPanelButtonAction = null
}
}
}
private fun onResolveConflictButtonClicked() {
val selectedFile = selectedFile ?: return
val lastState = screenState.value ?: return
setScreenState(ScreenState.loading())
viewModelScope.launch {
val conflict = interactor.getSyncConflictInfo(selectedFile)
if (conflict.isSucceeded) {
showResolveConflictDialog.call(conflict.obj)
setScreenState(lastState)
} else {
setScreenState(
ScreenState.dataWithError(
errorText = errorInteractor.processAndGetMessage(conflict.error)
)
)
}
}
}
private fun onRemoveFileButtonClicked() {
val selectedFile = selectedFile ?: return
val lastState = screenState.value ?: return
setScreenState(ScreenState.loading())
viewModelScope.launch {
val removeResult = interactor.removeFromUsedFiles(selectedFile)
if (removeResult.isFailed) {
setScreenState(lastState)
return@launch
}
loadData(resetSelection = true)
}
}
private fun onLoginButtonClicked() {
val selectedFile = selectedFile ?: return
val oldFsAuthority = selectedFile.fsAuthority
router.setResultListener(Screens.ServerLoginScreen.RESULT_KEY) { newFsAuthority ->
if (newFsAuthority is FSAuthority) {
onServerLoginSuccess(
fileUid = selectedFile.uid,
oldFSAuthority = oldFsAuthority,
newFsAuthority = newFsAuthority
)
}
}
router.navigateTo(
Screens.ServerLoginScreen(
ServerLoginArgs(
fsAuthority = oldFsAuthority
)
)
)
}
private fun onServerLoginSuccess(
fileUid: String,
oldFSAuthority: FSAuthority,
newFsAuthority: FSAuthority
) {
setScreenState(ScreenState.loading())
viewModelScope.launch {
val updateResult = interactor.updateUsedFileFsAuthority(
fileUid,
oldFSAuthority,
newFsAuthority
)
if (updateResult.isFailed) {
val message = errorInteractor.processAndGetMessage(updateResult.error)
setScreenState(ScreenState.dataWithError(message))
return@launch
}
loadData(resetSelection = false)
}
}
private fun setSelectedFileCell(model: DatabaseCellModel) {
fileCellViewModels.value = listOf(
viewModelFactory.createCellViewModel(model, EventProviderImpl())
)
}
private fun removeSelectedFileCell() {
fileCellViewModels.value = listOf()
}
private fun clearEnteredPassword() {
password.value = EMPTY
}
private fun setScreenState(state: ScreenState) {
screenState.value = state
isFabButtonVisible.value = getFabButtonVisibility()
visibleMenuItems.value = getVisibleMenuItems()
}
private fun getFabButtonVisibility(): Boolean {
val screenState = this.screenState.value ?: return false
return (screenState.isDisplayingData || screenState.isDisplayingEmptyState) &&
args.appMode == ApplicationLaunchMode.NORMAL
}
private fun getVisibleMenuItems(): List<UnlockMenuItem> {
val screenState = this.screenState.value ?: return emptyList()
return if (screenState.isDisplayingData) {
listOf(UnlockMenuItem.REFRESH)
} else {
emptyList()
}
}
private enum class ErrorPanelButtonAction {
RESOLVE_CONFLICT,
REMOVE_FILE,
AUTHORISATION
}
class Factory(
private val args: UnlockScreenArgs
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return GlobalInjector.get<UnlockViewModel>(
parametersOf(args)
) as T
}
}
enum class UnlockMenuItem(@IdRes override val menuId: Int) : ScreenMenuItem {
REFRESH(R.id.menu_refresh)
}
companion object {
private const val FAB_ITEM_NEW_FILE = 0
private const val FAB_ITEM_OPEN_FILE = 1
private val FAB_ITEMS = listOf(
FAB_ITEM_NEW_FILE to R.string.new_file,
FAB_ITEM_OPEN_FILE to R.string.open_file
)
}
}
| 1 | Kotlin | 0 | 0 | 5278cfff4fe0ab584283f6d2e2135477b5567d3a | 22,689 | passnotes | Apache License 2.0 |
app/src/main/java/com/anyandroid/room/PostsDao.kt | dmc0001 | 601,309,358 | false | null | package com.anyandroid.room
import androidx.room.*
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Single
@Dao
interface PostsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPost(post: Post):Completable
@Query("select * from posts_table")
fun getPosts():Single<List<Post>>
@Delete
fun deletePost(post: Post): Completable
@Update
fun updatePost(post: Post): Completable
} | 0 | Kotlin | 0 | 0 | 0ee7fe9455b2bf24ee42cd4b831f8746eb0481d8 | 453 | working-with-room | MIT License |
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/repositories/TiltaksgjennomforingRepository.kt | navikt | 435,813,834 | false | null | package no.nav.mulighetsrommet.api.repositories
import kotliquery.Row
import kotliquery.queryOf
import no.nav.mulighetsrommet.api.services.Sokefilter
import no.nav.mulighetsrommet.api.utils.PaginationParams
import no.nav.mulighetsrommet.database.Database
import no.nav.mulighetsrommet.database.utils.QueryResult
import no.nav.mulighetsrommet.database.utils.query
import no.nav.mulighetsrommet.domain.dbo.TiltaksgjennomforingDbo
import no.nav.mulighetsrommet.domain.dto.TiltaksgjennomforingAdminDto
import org.intellij.lang.annotations.Language
import org.slf4j.LoggerFactory
import java.util.UUID
class TiltaksgjennomforingRepository(private val db: Database) {
private val logger = LoggerFactory.getLogger(javaClass)
fun upsert(tiltaksgjennomforing: TiltaksgjennomforingDbo): QueryResult<TiltaksgjennomforingDbo> = query {
logger.info("Lagrer tiltaksgjennomføring id=${tiltaksgjennomforing.id}")
@Language("PostgreSQL")
val query = """
insert into tiltaksgjennomforing (id, navn, tiltakstype_id, tiltaksnummer, virksomhetsnummer, start_dato, slutt_dato, enhet)
values (:id::uuid, :navn, :tiltakstype_id::uuid, :tiltaksnummer, :virksomhetsnummer, :start_dato, :slutt_dato, :enhet)
on conflict (id)
do update set navn = excluded.navn,
tiltakstype_id = excluded.tiltakstype_id,
tiltaksnummer = excluded.tiltaksnummer,
virksomhetsnummer = excluded.virksomhetsnummer,
start_dato = excluded.start_dato,
slutt_dato = excluded.slutt_dato,
enhet = excluded.enhet
returning *
""".trimIndent()
queryOf(query, tiltaksgjennomforing.toSqlParameters())
.map { it.toTiltaksgjennomforingDbo() }
.asSingle
.let { db.run(it)!! }
}
fun get(id: UUID): TiltaksgjennomforingAdminDto? {
@Language("PostgreSQL")
val query = """
select tg.id::uuid,
tg.navn,
tiltakstype_id,
tiltaksnummer,
virksomhetsnummer,
start_dato,
slutt_dato,
tiltakskode,
t.navn as tiltakstype_navn,
enhet
from tiltaksgjennomforing tg
join tiltakstype t on t.id = tg.tiltakstype_id
where tg.id = ?::uuid
""".trimIndent()
return queryOf(query, id)
.map { it.toTiltaksgjennomforingAdminDto() }
.asSingle
.let { db.run(it) }
}
fun getAll(pagination: PaginationParams = PaginationParams()): Pair<Int, List<TiltaksgjennomforingAdminDto>> {
@Language("PostgreSQL")
val query = """
select tg.id::uuid,
tg.navn,
tiltakstype_id,
tiltaksnummer,
virksomhetsnummer,
tiltakskode,
start_dato,
slutt_dato,
t.navn as tiltakstype_navn,
enhet,
count(*) over () as full_count
from tiltaksgjennomforing tg
join tiltakstype t on tg.tiltakstype_id = t.id
order by tg.navn asc
limit ? offset ?
""".trimIndent()
val results = queryOf(query, pagination.limit, pagination.offset)
.map {
it.int("full_count") to it.toTiltaksgjennomforingAdminDto()
}
.asList
.let { db.run(it) }
val tiltaksgjennomforinger = results.map { it.second }
val totaltAntall = results.firstOrNull()?.first ?: 0
return Pair(totaltAntall, tiltaksgjennomforinger)
}
fun getAllByTiltakstypeId(
id: UUID,
pagination: PaginationParams = PaginationParams()
): Pair<Int, List<TiltaksgjennomforingAdminDto>> {
@Language("PostgreSQL")
val query = """
select tg.id::uuid,
tg.navn,
tiltakstype_id,
tiltaksnummer,
virksomhetsnummer,
tiltakskode,
start_dato,
slutt_dato,
t.navn as tiltakstype_navn,
enhet,
count(*) over () as full_count
from tiltaksgjennomforing tg
join tiltakstype t on tg.tiltakstype_id = t.id
where tg.tiltakstype_id = ?
order by tg.navn asc
limit ? offset ?
""".trimIndent()
val results = queryOf(query, id, pagination.limit, pagination.offset)
.map {
it.int("full_count") to it.toTiltaksgjennomforingAdminDto()
}
.asList
.let { db.run(it) }
val tiltaksgjennomforinger = results.map { it.second }
val totaltAntall = results.firstOrNull()?.first ?: 0
return Pair(totaltAntall, tiltaksgjennomforinger)
}
fun getAllByEnhet(
enhet: String,
pagination: PaginationParams
): Pair<Int, List<TiltaksgjennomforingAdminDto>> {
@Language("PostgreSQL")
val query = """
select tg.id::uuid,
tg.navn,
tiltakstype_id,
tiltaksnummer,
virksomhetsnummer,
tiltakskode,
start_dato,
slutt_dato,
t.navn as tiltakstype_navn,
enhet,
count(*) over () as full_count
from tiltaksgjennomforing tg
join tiltakstype t on tg.tiltakstype_id = t.id
where enhet = ?
order by tg.navn asc
limit ? offset ?
""".trimIndent()
val results = queryOf(query, enhet, pagination.limit, pagination.offset)
.map {
it.int("full_count") to it.toTiltaksgjennomforingAdminDto()
}
.asList
.let { db.run(it) }
val tiltaksgjennomforinger = results.map { it.second }
val totaltAntall = results.firstOrNull()?.first ?: 0
return Pair(totaltAntall, tiltaksgjennomforinger)
}
fun getAllByNavident(navIdent: String, pagination: PaginationParams): Pair<Int, List<TiltaksgjennomforingAdminDto>> {
logger.info("Henter alle tiltaksgjennomføringer for ansatt")
@Language("PostgreSQL")
val query = """
select tg.id::uuid,
tg.navn,
tiltakstype_id,
tiltaksnummer,
virksomhetsnummer,
tiltakskode,
start_dato,
slutt_dato,
t.navn as tiltakstype_navn,
enhet,
count(*) over () as full_count
from tiltaksgjennomforing tg
join tiltakstype t on tg.tiltakstype_id = t.id
join ansatt_tiltaksgjennomforing a on tg.id = a.tiltaksgjennomforing_id
where a.navident = ?
order by tg.navn asc
limit ? offset ?
""".trimIndent()
val results = queryOf(query, navIdent, pagination.limit, pagination.offset)
.map {
it.int("full_count") to it.toTiltaksgjennomforingAdminDto()
}
.asList
.let { db.run(it) }
val tiltaksgjennomforinger = results.map { it.second }
val totaltAntall = results.firstOrNull()?.first ?: 0
return Pair(totaltAntall, tiltaksgjennomforinger)
}
fun sok(filter: Sokefilter): List<TiltaksgjennomforingAdminDto> {
@Language("PostgreSQL")
val query = """
select tg.id::uuid,
tg.navn,
tiltakstype_id,
tiltaksnummer,
virksomhetsnummer,
tiltakskode,
start_dato,
slutt_dato,
t.navn as tiltakstype_navn,
enhet
from tiltaksgjennomforing tg
join tiltakstype t on tg.tiltakstype_id = t.id
where tiltaksnummer like concat('%', ?, '%')
order by tg.navn asc
""".trimIndent()
return queryOf(query, filter.tiltaksnummer)
.map {
it.toTiltaksgjennomforingAdminDto()
}
.asList
.let { db.run(it) }
}
fun delete(id: UUID): QueryResult<Int> = query {
logger.info("Sletter tiltaksgjennomføring id=$id")
@Language("PostgreSQL")
val query = """
delete from tiltaksgjennomforing
where id = ?::uuid
""".trimIndent()
queryOf(query, id)
.asUpdate
.let { db.run(it) }
}
private fun TiltaksgjennomforingDbo.toSqlParameters() = mapOf(
"id" to id,
"navn" to navn,
"tiltakstype_id" to tiltakstypeId,
"tiltaksnummer" to tiltaksnummer,
"virksomhetsnummer" to virksomhetsnummer,
"start_dato" to startDato,
"slutt_dato" to sluttDato,
"enhet" to enhet
)
private fun Row.toTiltaksgjennomforingDbo() = TiltaksgjennomforingDbo(
id = uuid("id"),
navn = stringOrNull("navn"),
tiltakstypeId = uuid("tiltakstype_id"),
tiltaksnummer = string("tiltaksnummer"),
virksomhetsnummer = stringOrNull("virksomhetsnummer"),
startDato = localDate("start_dato"),
sluttDato = localDateOrNull("slutt_dato"),
enhet = string("enhet")
)
private fun Row.toTiltaksgjennomforingAdminDto() = TiltaksgjennomforingAdminDto(
id = uuid("id"),
tiltakstype = TiltaksgjennomforingAdminDto.Tiltakstype(
id = uuid("tiltakstype_id"),
navn = string("tiltakstype_navn"),
arenaKode = string("tiltakskode")
),
navn = stringOrNull("navn"),
tiltaksnummer = string("tiltaksnummer"),
virksomhetsnummer = stringOrNull("virksomhetsnummer"),
startDato = localDateOrNull("start_dato"),
sluttDato = localDateOrNull("slutt_dato"),
enhet = string("enhet")
)
}
| 1 | null | 1 | 4 | 03c6fe32e0d35716be0f6200beabd99df3d0036c | 10,496 | mulighetsrommet | MIT License |
plugins/testing/simple/src/main/kotlin/org/rsmod/plugins/testing/simple/SimpleGameTestState.kt | rsmod | 293,875,986 | false | {"Kotlin": 812861} | package org.rsmod.plugins.testing.simple
public class SimpleGameTestState {
public fun runGameTest(
scope: SimpleGameTestScope = SimpleGameTestScope(),
testBody: SimpleGameTestScope.() -> Unit
): Unit = testBody(scope)
}
| 2 | Kotlin | 63 | 79 | e1e1a85d7a4d1840ca0738e3401d18ee40424860 | 247 | rsmod | ISC License |
app/src/main/java/kek/plantain/data/delegate/ReadWriteSector.kt | jnkforks | 291,051,435 | true | {"Kotlin": 54589, "Java": 4532} | package kek.plantain.data.delegate
import kek.plantain.data.entity.Sector
open class ReadWriteSector(val sector: Sector, val block: Int, val range: IntRange) | 0 | null | 0 | 0 | 395a6a88620fe2faef64d05f0aa301a9bb8c4ff1 | 159 | Plantain | MIT License |
app/src/main/java/com/weatherxm/usecases/SendFeedbackUseCase.kt | WeatherXM | 728,657,649 | false | {"Kotlin": 1128981} | package com.weatherxm.usecases
import com.weatherxm.data.repository.UserRepository
interface SendFeedbackUseCase {
fun getUserId(): String
}
class SendFeedbackUseCaseImpl(private val userRepository: UserRepository) : SendFeedbackUseCase {
override fun getUserId(): String {
return userRepository.getUserId()
}
}
| 1 | Kotlin | 2 | 9 | eeb403f6da5f4e54e126e71edacf90c102bb0748 | 335 | wxm-android | Apache License 2.0 |
owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt | tanishpvt | 464,454,115 | true | {"INI": 1, "Gradle": 4, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Ignore List": 1, "XML": 11, "YAML": 1, "Text": 1, "Java": 48, "Java Properties": 1, "Kotlin": 52} | /* ownCloud Android Library is available under MIT license
* Copyright (C) 2020 ownCloud GmbH.
*
* 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.educamadrid.cloudeduca.lib.common.http.methods.webdav
import at.bitfire.dav4jvm.Dav4jvm.log
import at.bitfire.dav4jvm.DavOCResource
import at.bitfire.dav4jvm.exception.HttpException
import at.bitfire.dav4jvm.exception.RedirectException
import com.educamadrid.cloudeduca.lib.common.http.HttpConstants
import com.educamadrid.cloudeduca.lib.common.http.methods.HttpBaseMethod
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.net.MalformedURLException
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Wrapper to perform WebDAV (dav4android) calls
*
* @author <NAME>
*/
abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) {
protected var davResource: DavOCResource
override lateinit var response: Response
init {
val httpUrl = url.toHttpUrlOrNull() ?: throw MalformedURLException()
davResource = DavOCResource(
okHttpClient,
httpUrl,
log
)
}
override fun abort() {
davResource.cancelCall()
}
@Throws(Exception::class)
override fun execute(): Int {
return try {
onExecute()
} catch (httpException: HttpException) {
// Modify responses with information gathered from exceptions
if (httpException is RedirectException) {
response = Response.Builder()
.header(
HttpConstants.LOCATION_HEADER, httpException.redirectLocation
)
.code(httpException.code)
.request(request)
.message(httpException.message ?: "")
.protocol(Protocol.HTTP_1_1)
.build()
} else {
// The check below should be included in okhttp library, method ResponseBody.create(
// TODO check most recent versions of okhttp to see if this is already fixed and try to update if so
if (response.body?.contentType() != null) {
val responseBody = (httpException.responseBody ?: "").toResponseBody(response.body?.contentType())
response = response.newBuilder()
.body(responseBody)
.build()
}
}
httpException.code
}
}
//////////////////////////////
// Setter
//////////////////////////////
// Connection parameters
override fun setReadTimeout(readTimeout: Long, timeUnit: TimeUnit) {
super.setReadTimeout(readTimeout, timeUnit)
davResource = DavOCResource(
okHttpClient,
request.url,
log
)
}
override fun setConnectionTimeout(
connectionTimeout: Long,
timeUnit: TimeUnit
) {
super.setConnectionTimeout(connectionTimeout, timeUnit)
davResource = DavOCResource(
okHttpClient,
request.url,
log
)
}
override fun setFollowRedirects(followRedirects: Boolean) {
super.setFollowRedirects(followRedirects)
davResource = DavOCResource(
okHttpClient,
request.url,
log
)
}
override fun setUrl(url: HttpUrl) {
super.setUrl(url)
davResource = DavOCResource(
okHttpClient,
request.url,
log
)
}
override fun setRequestHeader(name: String, value: String) {
super.setRequestHeader(name, value)
davResource = DavOCResource(
okHttpClient,
request.url,
log
)
}
//////////////////////////////
// Getter
//////////////////////////////
override fun setRetryOnConnectionFailure(retryOnConnectionFailure: Boolean) {
super.setRetryOnConnectionFailure(retryOnConnectionFailure)
davResource = DavOCResource(
okHttpClient,
request.url,
log
)
}
override val isAborted: Boolean
get() = davResource.isCallAborted()
}
| 0 | null | 0 | 0 | fb7bfb23e0aeabdcdfaadc48ecbe7c6bca4889b4 | 5,467 | android-library | MIT License |
covid19-stats-bago/app/src/main/java/gov/mm/covid19statsbago/util/services/ProgressInterface.kt | kyawhtut-cu | 252,343,874 | false | null | package gov.mm.covid19statsbago.util.services
interface ProgressInterface {
fun update(
bytesRead: Long,
contentLength: Long,
done: Boolean
)
}
| 0 | Kotlin | 0 | 0 | 6bd6b30d1683b44534989f6f92d4f4ef651c5866 | 177 | covid19-stats-bago | Apache License 2.0 |
platform/android/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapabc/mapabcsdk/testapp/style/CustomGeometrySourceTest.kt | liqingtao | 178,830,280 | false | null | package com.mapabc.mapabcsdk.testapp.style
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.matcher.ViewMatchers.isRoot
import com.mapabc.mapabcsdk.style.sources.CustomGeometrySource.THREAD_POOL_LIMIT
import com.mapabc.mapabcsdk.style.sources.CustomGeometrySource.THREAD_PREFIX
import com.mapabc.mapabcsdk.testapp.action.MapboxMapAction.invoke
import com.mapabc.mapabcsdk.testapp.action.OrientationAction.orientationLandscape
import com.mapabc.mapabcsdk.testapp.action.OrientationAction.orientationPortrait
import com.mapabc.mapabcsdk.testapp.activity.style.GridSourceActivity.ID_GRID_LAYER
import com.mapabc.mapabcsdk.testapp.activity.style.GridSourceActivity.ID_GRID_SOURCE
import com.mapabc.mapabcsdk.testapp.utils.TestingAsyncUtils
import org.junit.Assert
import org.junit.Ignore
import org.junit.Test
class CustomGeometrySourceTest : com.mapabc.mapabcsdk.testapp.activity.BaseTest() {
override fun getActivityClass(): Class<*> = com.mapabc.mapabcsdk.testapp.activity.style.GridSourceActivity::class.java
@Test
@Ignore
fun sourceNotLeakingThreadsTest() {
validateTestSetup()
com.mapabc.mapabcsdk.testapp.action.WaitAction.invoke(4000)
onView(isRoot()).perform(orientationLandscape())
com.mapabc.mapabcsdk.testapp.action.WaitAction.invoke(2000)
onView(isRoot()).perform(orientationPortrait())
com.mapabc.mapabcsdk.testapp.action.WaitAction.invoke(2000)
Assert.assertFalse("Threads should be shutdown when the source is destroyed.",
Thread.getAllStackTraces().keys.filter {
it.name.startsWith(THREAD_PREFIX)
}.count() > THREAD_POOL_LIMIT)
}
@Test
@Ignore
fun threadsShutdownWhenSourceRemovedTest() {
validateTestSetup()
invoke(mapabcMap) { uiController, mapboxMap ->
mapboxMap.style!!.removeLayer(ID_GRID_LAYER)
TestingAsyncUtils.waitForLayer(uiController, mapView)
mapboxMap.style!!.removeSource(ID_GRID_SOURCE)
TestingAsyncUtils.waitForLayer(uiController, mapView)
Assert.assertTrue("There should be no threads running when the source is removed.",
Thread.getAllStackTraces().keys.filter {
it.name.startsWith(com.mapabc.mapabcsdk.style.sources.CustomGeometrySource.THREAD_PREFIX)
}.count() == 0)
}
}
@Test
@Ignore
fun threadsRestartedWhenSourceReAddedTest() {
validateTestSetup()
invoke(mapabcMap) { uiController, mapboxMap ->
mapboxMap.style!!.removeLayer((rule.activity as com.mapabc.mapabcsdk.testapp.activity.style.GridSourceActivity).layer)
TestingAsyncUtils.waitForLayer(uiController, mapView)
mapboxMap.style!!.removeSource(ID_GRID_SOURCE)
TestingAsyncUtils.waitForLayer(uiController, mapView)
mapboxMap.style!!.addSource((rule.activity as com.mapabc.mapabcsdk.testapp.activity.style.GridSourceActivity).source)
mapboxMap.style!!.addLayer((rule.activity as com.mapabc.mapabcsdk.testapp.activity.style.GridSourceActivity).layer)
TestingAsyncUtils.waitForLayer(uiController, mapView)
Assert.assertTrue("Threads should be restarted when the source is re-added to the map.",
Thread.getAllStackTraces().keys.filter {
it.name.startsWith(com.mapabc.mapabcsdk.style.sources.CustomGeometrySource.THREAD_PREFIX)
}.count() == com.mapabc.mapabcsdk.style.sources.CustomGeometrySource.THREAD_POOL_LIMIT)
}
}
} | 1 | null | 1 | 1 | adf029f92a13780e7667be0dd7339c53760ea2a2 | 3,381 | mapbox-gl-native | Apache License 2.0 |
app/src/main/java/com/tourcool/ui/express/ExpressQueryActivity.kt | lygyuyun | 423,540,171 | true | {"Java Properties": 2, "Text": 1, "Gradle": 4, "Ignore List": 3, "Proguard": 2, "XML": 439, "Java": 448, "Kotlin": 51} | package com.tourcool.ui.express
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.view.View
import com.frame.library.core.retrofit.BaseLoadingObserver
import com.frame.library.core.util.SizeUtil
import com.frame.library.core.util.StringUtil
import com.frame.library.core.util.ToastUtil
import com.frame.library.core.widget.titlebar.TitleBarView
import com.tourcool.bean.express.ExpressCompany
import com.tourcool.core.base.BaseResult
import com.tourcool.core.config.RequestConfig
import com.tourcool.core.retrofit.repository.ApiRepository
import com.tourcool.smartcity.R
import com.tourcool.ui.base.BaseCommonTitleActivity
import com.tourcool.widget.searchview.BSearchEdit
import com.trello.rxlifecycle3.android.ActivityEvent
import kotlinx.android.synthetic.main.activity_express_query.*
/**
*@description : 快递查询
*@company :途酷科技
* @author :JenkinsZhou
* @date 2020年11月25日19:02
* @Email: <EMAIL>
*/
class ExpressQueryActivity : BaseCommonTitleActivity(), View.OnClickListener {
private var bSearchEdit: BSearchEdit? = null
private var currentSelectPosition = -1
private val expressList = ArrayList<ExpressCompany>()
override fun getContentLayout(): Int {
return R.layout.activity_express_query
}
override fun initView(savedInstanceState: Bundle?) {
tvQuery.setOnClickListener {
skipDetail()
}
tvExpressCom.post {
initSearchView(viewLineVertical.width.toFloat())
}
tvExpressCom.inputType = InputType.TYPE_NULL
tvExpressCom.setOnClickListener(this)
llExpressContent.setOnClickListener(this)
ivExpressSelect.setOnClickListener(this)
}
override fun setTitleBar(titleBar: TitleBarView?) {
super.setTitleBar(titleBar)
titleBar?.setTitleMainText("快递查询")
}
private fun requestExpressCompany() {
ApiRepository.getInstance().requestExpressCompany().compose(bindUntilEvent(ActivityEvent.DESTROY)).subscribe(object : BaseLoadingObserver<BaseResult<MutableList<ExpressCompany>>>() {
override fun onRequestNext(entity: BaseResult<MutableList<ExpressCompany>>?) {
if (entity == null) {
return
}
if (entity.status == RequestConfig.CODE_REQUEST_SUCCESS && entity.data != null) {
showExpressCompany(entity.data)
} else {
ToastUtil.show(entity.errorMsg)
}
}
})
}
private fun showExpressCompany(list: MutableList<ExpressCompany>?) {
val companyList = ArrayList<String>()
if (list == null) {
ToastUtil.show("未获取到物流公司")
return
}
list.forEach {
companyList.add(it.com)
}
expressList.clear()
expressList.addAll(list)
bSearchEdit!!.setSearchList(companyList)
bSearchEdit!!.showPopup()
}
companion object {
const val EXTRA_EXPRESS_COM_NO = "EXTRA_EXPRESS_COM_NO"
const val EXTRA_EXPRESS_COM_NAME = "EXTRA_EXPRESS_COM_NAME"
const val EXTRA_EXPRESS_NO = "EXTRA_EXPRESS_NO"
const val EXTRA_PHONE = "EXTRA_PHONE"
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.llExpressContent, R.id.ivExpressSelect, R.id.tvExpressCom -> {
requestExpressCompany()
}
else -> {
}
}
}
private fun initSearchView(widthPx: Float) {
//第三个必须要设置窗体的宽度,单位dp
bSearchEdit = BSearchEdit(this, viewLineVertical, SizeUtil.px2dp(widthPx))
bSearchEdit!!.setTimely(false)
bSearchEdit!!.build()
bSearchEdit!!.setTextClickListener { position, text ->
currentSelectPosition = position
tvExpressCom.setText(text!!)
}
}
private fun skipDetail() {
if (TextUtils.isEmpty(etExpressNum.text.toString())) {
ToastUtil.show("请输入快递单号")
return
}
if (TextUtils.isEmpty(tvExpressCom.text.toString())) {
ToastUtil.show("请选择快递公司")
return
}
if (TextUtils.isEmpty(etPhone.text.toString())) {
ToastUtil.show("请输入收货人手机号")
return
}
if (!StringUtil.isPhoneNumber(etPhone.text.toString())) {
ToastUtil.show("请输入正确的手机号")
return
}
if (currentSelectPosition < 0 || currentSelectPosition >= expressList.size) {
ToastUtil.show("未获取到快递公司")
return
}
val intent = Intent()
intent.putExtra(EXTRA_EXPRESS_COM_NO, expressList[currentSelectPosition].no)
intent.putExtra(EXTRA_EXPRESS_COM_NAME, expressList[currentSelectPosition].com)
intent.putExtra(EXTRA_EXPRESS_NO, etExpressNum.text.toString())
intent.putExtra(EXTRA_PHONE, etPhone.text.toString())
intent.setClass(mContext, ExpressDetailActivity::class.java)
startActivity(intent)
}
} | 0 | null | 0 | 0 | 98d190ff99c2c5eb8a542764f118f076d124a226 | 5,066 | SmartCity | Apache License 2.0 |
idea/testData/debugger/tinyApp/src/evaluate/singleBreakpoint/rawTypeskt11831.kt | JakeWharton | 99,388,807 | true | null | package rawTypeskt11831
fun main(args: Array<String>) {
val raw = forTests.MyJavaClass.RawADerived()
val foo = raw.foo(emptyList<String>())
//Breakpoint!
val a = foo
}
// EXPRESSION: foo
// RESULT: 1: I | 0 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 220 | kotlin | Apache License 2.0 |
src/main/kotlin/ParseFontTest.kt | undeadparrot | 109,190,483 | false | null | import com.google.gson.Gson
import java.io.File
data class Font(val face: String, val image: String, val scaleW: Int, val scaleH: Int, val chars: Map<Int, FontChar>) {
fun stringToVertsP3T2(s: String, x: Float = 0f, y: Float = 0f, z: Float = 0f): List<Float> {
var xOffset = 0f
val scale = 0.02f
return s.toCharArray().flatMap { letter ->
val char = chars.getOrDefault(letter.toInt(), chars.values.first())
val x1 = x + xOffset
val x2 = x1 + char.width.toFloat() * scale
val y1 = y + 0f
val y2 = y1 + char.height.toFloat() * scale
val u1 = char.x.toFloat() / scaleW
val v1 = char.y.toFloat() / scaleH
val u2 = u1 + char.width.toFloat() / scaleW
val v2 = v1 + char.height.toFloat() / scaleH
xOffset += char.xadvance.toFloat() * scale
listOf(
x1, y2, z, u1, v1, //topleft
x2, y2, z, u2, v1, //topright
x2, y1, z, u2, v2, //botright
x2, y1, z, u2, v2, //botright
x1, y1, z, u1, v2, //botleft
x1, y2, z, u1, v1 //topleft
)
}
}
companion object {
fun loadFromJsonFile(filename: String) = Gson().fromJson<Font>(File(filename).readText(), Font::class.java)
fun loadFromBmFontFile(filename: String): Font {
val patternCommon = Regex("" +
"common\\s+" +
".*" +
"scaleW=(\\d+)\\s+" +
"scaleH=(\\d+)\\s+" +
".*")
val patternPage = Regex("" +
"page\\s+" +
".*" +
"file=\"(.+)\"" +
".*")
val pattern = Regex("" +
"char\\s+" +
"id=(\\d+)\\s+" +
"x=(-?\\d+)\\s+" +
"y=(-?\\d+)\\s+" +
"width=(-?\\d+)\\s+" +
"height=(-?\\d+)\\s+" +
"xoffset=(-?\\d+)\\s+" +
"yoffset=(-?\\d+)\\s+" +
"xadvance=(-?\\d+)\\s+" +
".*")
var chars = mutableMapOf<Int, FontChar>()
var scaleW = 0
var scaleH = 0
var file = ""
File(filename).forEachLine { line ->
when (line.substring(0, 4)) {
"comm" -> {
val match = patternCommon.matchEntire(line)
if (match !== null) {
val matches = match.groups
scaleW = matches[1]!!.value.toInt()
scaleH = matches[2]!!.value.toInt()
}
}
"page" -> {
val match = patternPage.matchEntire(line)
if (match !== null) {
val matches = match.groups
file = matches[1]!!.value
}
}
"char" -> {
val match = pattern.matchEntire(line)
if (match !== null) {
val matches = match.groups
val char = FontChar(
id = matches[1]!!.value.toInt(),
x = matches[2]!!.value.toInt(),
y = matches[3]!!.value.toInt(),
width = matches[4]!!.value.toInt(),
height = matches[5]!!.value.toInt(),
xoffset = matches[6]!!.value.toInt(),
yoffset = matches[7]!!.value.toInt(),
xadvance = matches[8]!!.value.toInt()
)
chars.set(char.id, char)
}
}
}
}
return Font("Font", file, scaleW, scaleH, chars)
}
}
}
data class FontChar(val id: Int, val x: Int, val y: Int, val width: Int, val height: Int, val xoffset: Int, val yoffset: Int, val xadvance: Int)
fun main(args: Array<String>) {
var obj = Font.loadFromJsonFile("font1xml.json")
Font.loadFromBmFontFile("distanceFont.fnt")
obj.stringToVertsP3T2("Kotlin")
}
| 1 | null | 1 | 1 | e346af7c189c845a89ab59512839ea9eebb38932 | 4,529 | lwjgl-play | MIT License |
airbyte-integrations/connectors/destination-s3/src/test-integration/kotlin/io/airbyte/integrations/destination/s3/S3ParquetDestinationAcceptanceTest.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.integrations.destination.s3
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ObjectNode
import io.airbyte.cdk.integrations.destination.s3.S3BaseParquetDestinationAcceptanceTest
import io.airbyte.cdk.integrations.standardtest.destination.ProtocolVersion
import io.airbyte.cdk.integrations.standardtest.destination.argproviders.DataArgumentsProvider
import io.airbyte.cdk.integrations.standardtest.destination.argproviders.DataArgumentsProvider.Companion.EXCHANGE_RATE_CONFIG
import io.airbyte.cdk.integrations.standardtest.destination.comparator.TestDataComparator
import io.airbyte.commons.json.Jsons.deserialize
import io.airbyte.commons.resources.MoreResources.readResource
import io.airbyte.protocol.models.v0.AirbyteCatalog
import io.airbyte.protocol.models.v0.AirbyteMessage
import io.airbyte.protocol.models.v0.CatalogHelpers
import org.junit.jupiter.api.Test
class S3ParquetDestinationAcceptanceTest : S3BaseParquetDestinationAcceptanceTest() {
override fun getProtocolVersion(): ProtocolVersion {
return ProtocolVersion.V1
}
override fun getTestDataComparator(): TestDataComparator {
return S3AvroParquetTestDataComparator()
}
override val baseConfigJson: JsonNode
get() = S3DestinationTestUtils.baseConfigJsonFilePath
/**
* Quick and dirty test to verify that lzo compression works. Probably has some blind spots
* related to cpu architecture.
*
* Only verifies that it runs successfully, which is sufficient to catch any issues with
* installing the lzo libraries.
*/
@Test
@Throws(Exception::class)
fun testLzoCompression() {
val config = getConfig().deepCopy<JsonNode>()
(config["format"] as ObjectNode).put("compression_codec", "LZO")
val catalog =
deserialize<AirbyteCatalog>(
readResource(
DataArgumentsProvider.EXCHANGE_RATE_CONFIG.getCatalogFileVersion(
ProtocolVersion.V0
)
),
AirbyteCatalog::class.java
)
val configuredCatalog = CatalogHelpers.toDefaultConfiguredCatalog(catalog)
val messages: List<AirbyteMessage> =
readResource(
DataArgumentsProvider.EXCHANGE_RATE_CONFIG.getMessageFileVersion(
ProtocolVersion.V0
)
)
.lines()
.filter { it.isNotEmpty() }
.map { record: String? ->
deserialize<AirbyteMessage>(record, AirbyteMessage::class.java)
}
.toList()
runSyncAndVerifyStateOutput(config, messages, configuredCatalog, false)
}
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 2,856 | airbyte | MIT License |
solutions/src/AccountMerge.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 324, "Java": 15} | class AccountMerge {
fun accountsMerge(accounts: List<List<String>>) : List<List<String>> {
val accountsAsObjects = accounts.map { fromList(it) }
val emailsToAccounts = mutableMapOf<String,MutableList<Account>>()
accountsAsObjects.forEach {
it.emails.forEach {email -> emailsToAccounts.computeIfAbsent(email) { mutableListOf()}.add(it) }
}
val visited = mutableSetOf<String>()
val merged = mutableListOf<Account>()
while (visited.size != emailsToAccounts.size) {
val seedAccount = emailsToAccounts[emailsToAccounts.keys.first { !visited.contains(it) }]
val name = seedAccount!![0].name
val emails = seedAccount!![0].emails.toMutableSet()
val queue = emails.toMutableList()
visited.addAll(emails)
while (queue.isNotEmpty()) {
val email = queue.removeAt(0);
emailsToAccounts[email]!!.flatMap { it.emails }.forEach { addr ->
if (!visited.contains(addr)) {
visited.add(addr)
emails.add(addr)
queue.add(addr)
}
}
}
merged.add(Account(name,emails))
}
return merged.map { it.toList() }
}
private fun fromList(l:List<String>) : Account {
return Account(l[0],(1 until l.size).map { l[it] }.toSet());
}
private data class Account(val name: String, val emails: Set<String>) {
fun toList() : List<String> {
val toList = mutableListOf(this.name)
toList.addAll(emails.sorted())
return toList.toList()
}
}
} | 1 | null | 1 | 1 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,719 | leetcode-solutions | MIT License |
app/src/main/java/io/horizontalsystems/bankwallet/entities/CoinType.kt | herou | 263,455,322 | true | {"Kotlin": 1776882, "Java": 33448, "Ruby": 5803, "Shell": 2024} | package io.horizontalsystems.bankwallet.entities
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import java.math.BigDecimal
sealed class CoinType : Parcelable {
@Parcelize
object Bitcoin : CoinType()
@Parcelize
object Litecoin : CoinType()
@Parcelize
object BitcoinCash : CoinType()
@Parcelize
object Dash : CoinType()
@Parcelize
object Ethereum : CoinType()
@Parcelize
class Erc20(val address: String, val fee: BigDecimal = BigDecimal.ZERO, val minimumRequiredBalance: BigDecimal = BigDecimal.ZERO, val minimumSendAmount: BigDecimal = BigDecimal.ZERO) : CoinType()
@Parcelize
class Binance(val symbol: String) : CoinType()
@Parcelize
object Zcash : CoinType()
@Parcelize
class Eos(val token: String, val symbol: String) : CoinType()
val label: String?
get() = when (this) {
is Erc20 -> "ERC20"
is Eos -> if (symbol != "EOS") "EOSIO" else null
is Binance -> if (symbol != "BNB") "BEP2" else null
else -> null
}
val predefinedAccountType: PredefinedAccountType
get() = when (this) {
Bitcoin, Litecoin, BitcoinCash, Dash, Ethereum, is Erc20 -> PredefinedAccountType.Standard
is Binance -> PredefinedAccountType.Binance
is Eos -> PredefinedAccountType.Eos
Zcash -> PredefinedAccountType.Zcash
}
val swappable: Boolean
get() = this is Ethereum || this is Erc20
fun canSupport(accountType: AccountType) = when (this) {
is Eos -> {
accountType is AccountType.Eos
}
Bitcoin, Litecoin, BitcoinCash, Dash, Ethereum, is Erc20 -> {
accountType is AccountType.Mnemonic && accountType.words.size == 12 && accountType.salt == null
}
is Binance -> {
accountType is AccountType.Mnemonic && accountType.words.size == 24 && accountType.salt == null
}
Zcash -> {
accountType is AccountType.Zcash && accountType.words.size == 24
}
}
}
| 0 | Kotlin | 0 | 1 | a9ebd7e5262ac305e32b18415f9b6e81b36fac54 | 2,092 | unstoppable-wallet-android | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/PropDetector.kt | PineappleSomethingFTC | 736,931,889 | false | {"Gradle": 7, "Markdown": 5, "Java Properties": 1, "Shell": 1, "Text": 4, "Ignore List": 2, "Batchfile": 1, "INI": 1, "Java": 103, "XML": 11, "Kotlin": 2} | package org.firstinspires.ftc.teamcode
import org.opencv.core.*
import com.qualcomm.robotcore.eventloop.opmode.Autonomous
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode
import org.firstinspires.ftc.robotcore.external.Telemetry
import org.opencv.imgproc.Imgproc
import org.openftc.easyopencv.OpenCvCameraRotation
enum class PropPosition {
Left, Center, Right
}
enum class PropColors {
Red, Blue
}
class PropDetector(private val telemetry: Telemetry, private val colorToDetect: PropColors/*, private val frameType: FrameType = FrameType.Input*/) {
// enum class FrameType {
// Input,
// ColorFiltered
// }
private val rects = listOf(
Rect(Point(0.0, 450.0), Point(200.0, 720.0)),
Rect(Point(300.0, 400.0), Point(900.0, 720.0)),
Rect(Point(1000.0, 450.0), Point(1279.0, 720.0))
)
private val positionsMappedToRects = listOf(
PropPosition.Left to rects[0],
PropPosition.Center to rects[1],
PropPosition.Right to rects[2]
)
private val red = Scalar(255.0, 0.0, 0.0) //100% Red
private val green = Scalar(0.0, 255.0, 0.0) //100% Green
private val blue = Scalar(0.0, 0.0, 255.0) //100% Blue
private val white = Scalar(255.0, 255.0, 255.0)
private val rectanglesMappedToBorderColors = listOf(
positionsMappedToRects[0] to red,
positionsMappedToRects[1] to green,
positionsMappedToRects[2] to blue
)
private enum class Colors(val scalar: Scalar) {
MinBlue(Scalar(100.0, 100.0, 100.0)),
MaxBlue(Scalar(115.0, 255.0,255.0)),
MinLowRed(Scalar(0.0,100.0, 100.0)),
MaxLowRed(Scalar(25.0,255.0,255.0)),
MinHighRed(Scalar(160.0, 100.0,100.0)),
MaxHighRed(Scalar(255.0,255.0,255.0)),
}
@Volatile
public var propPosition = PropPosition.Left
private var mat = Mat()
private var redLowMat = Mat()
private var redHighMat = Mat()
private var regions: List<Mat> = listOf()
fun processFrame(frame: Mat): Mat {
Imgproc.cvtColor(frame, mat, Imgproc.COLOR_RGB2HSV)
when (colorToDetect) {
PropColors.Blue -> {
Core.inRange(mat, Colors.MinBlue.scalar, Colors.MaxBlue.scalar, mat)
}
PropColors.Red -> {
Core.inRange(mat, Colors.MinLowRed.scalar, Colors.MaxLowRed.scalar, redLowMat)
Core.inRange(mat, Colors.MinHighRed.scalar, Colors.MaxHighRed.scalar, redHighMat)
Core.bitwise_or(redLowMat, redHighMat, mat)
}
}
regions = positionsMappedToRects.map { it ->
mat.submat(it.second)
}
val values = regions.map { it ->
Core.sumElems(it).`val`[0]
}
val leftValue = values[0]
val centerValue = values[1]
val rightValue = values[2]
propPosition = if (leftValue >= rightValue && leftValue >= centerValue) {
PropPosition.Left
} else if (rightValue >= centerValue) {
PropPosition.Right
} else {
PropPosition.Center
}
telemetry.addLine("propPosition: $propPosition")
// Imgproc.cvtColor(frame, mat, Imgproc.COLOR_RGB2HSV)
// Imgproc.cvtColor(mat, mat, Imgproc.COLOR_GRAY2RGB)
rectanglesMappedToBorderColors.forEach { it ->
val borderColor = if (it.first.first == propPosition) white else it.second
Imgproc.rectangle(frame, it.first.second, borderColor, 3)
}
telemetry.update()
return frame
}
}
@Autonomous
class JamesVisionTest/** Change Depending on robot */: LinearOpMode() {
/** Change Depending on robot */
override fun runOpMode() {
val opencv = OpenCvAbstraction(this)
val tseDetector = PropDetector(telemetry, PropColors.Red)
opencv.init(hardwareMap)
opencv.internalCamera = false
opencv.cameraName = "Webcam 1"
opencv.cameraOrientation = OpenCvCameraRotation.UPRIGHT
hardwareMap.allDeviceMappings.forEach { m ->
println("HW: ${m.deviceTypeClass} ${m.entrySet().map{it.key}.joinToString(",")}")
}
opencv.onNewFrame(tseDetector::processFrame)
tseDetector.propPosition
waitForStart()
/** AUTONOMOUS PHASE */
}
} | 0 | Java | 0 | 0 | aab8ad8c96239c29fc812336e3a1e27ed3c6ce42 | 4,324 | rr5 | BSD 3-Clause Clear License |
paymentsheet/src/main/java/com/stripe/android/paymentsheet/paymentdatacollection/bacs/BacsMandateConfirmationLauncher.kt | stripe | 6,926,049 | false | null | package com.stripe.android.paymentsheet.paymentdatacollection.bacs
import androidx.activity.result.ActivityResultLauncher
import com.stripe.android.paymentsheet.PaymentSheet
internal interface BacsMandateConfirmationLauncher {
fun launch(
data: BacsMandateData,
appearance: PaymentSheet.Appearance
)
}
internal class DefaultBacsMandateConfirmationLauncher(
private val activityResultLauncher: ActivityResultLauncher<BacsMandateConfirmationContract.Args>
) : BacsMandateConfirmationLauncher {
override fun launch(
data: BacsMandateData,
appearance: PaymentSheet.Appearance
) {
activityResultLauncher.launch(
BacsMandateConfirmationContract.Args(
email = data.email,
nameOnAccount = data.name,
sortCode = data.sortCode,
accountNumber = data.accountNumber,
appearance = appearance
)
)
}
}
| 88 | null | 644 | 1,277 | 174b27b5a70f75a7bc66fdcce3142f1e51d809c8 | 965 | stripe-android | MIT License |
Flutter/hangman_flutter/android/app/src/main/kotlin/com/example/hangman_flutter/MainActivity.kt | Mohammadreza99A | 290,041,451 | false | {"Java": 74635, "Dart": 47066, "JavaScript": 28878, "TypeScript": 18934, "HTML": 13850, "Vue": 9190, "Objective-C": 4489, "CSS": 2289, "Starlark": 1932, "Ruby": 893, "Swift": 404, "Kotlin": 274} | package com.example.hangman_flutter
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | Java | 1 | 1 | f5e5625fb36c14cf1f5da2bab0e0c456e6194a20 | 132 | hangman | MIT License |
fluentlenium-kotest/src/test/kotlin/io/fluentlenium/adapter/kotest/describespec/DescribeMetadataSpec.kt | FluentLenium | 2,088,736 | false | null | package io.fluentlenium.adapter.kotest.describespec
import io.fluentlenium.adapter.exception.AnnotationNotFoundException
import io.fluentlenium.adapter.kotest.FluentDescribeSpec
import io.fluentlenium.adapter.kotest.MyAnnotation
import io.fluentlenium.adapter.kotest.OtherAnnotation
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
@MyAnnotation
class DescribeMetadataSpec : FluentDescribeSpec({
it("testClass") {
testClass shouldBe DescribeMetadataSpec::class.java
}
it("testMethodName") {
testMethodName shouldBe "testMethodName"
}
it("testGetClassAnnotation") {
getClassAnnotation(MyAnnotation::class.java).shouldNotBeNull()
shouldThrow<AnnotationNotFoundException> {
getClassAnnotation(OtherAnnotation::class.java).shouldNotBeNull()
}
}
it("testGetMethodAnnotation") {
shouldThrow<AnnotationNotFoundException> {
getMethodAnnotation(OtherAnnotation::class.java).shouldNotBeNull()
}
}
})
| 32 | null | 212 | 867 | 6674ac80b0ab990c1ee5b8417109fc3134f27eeb | 1,094 | FluentLenium | Apache License 2.0 |
app/src/androidTest/java/com/sample/android/tmdb/ui/paging/search/BaseSearchActivity.kt | alirezaeiii | 158,464,119 | false | null | package com.sample.android.tmdb.ui.paging.search
import android.widget.EditText
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.pressImeActionButton
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import com.sample.android.tmdb.BaseIdlingResource
import org.junit.Test
import com.sample.android.tmdb.R
abstract class BaseSearchActivity: BaseIdlingResource() {
@Test
fun shouldBeAbleToSearch() {
onView(isAssignableFrom(EditText::class.java))
.perform(typeText("<NAME>"),
pressImeActionButton())
onView(withId(R.id.recyclerView)).check(matches(isDisplayed()))
}
} | 1 | null | 20 | 161 | a835bc7ca972619717832860dbb3a95ca37994e5 | 794 | TMDb-Paging-Playground | The Unlicense |
app/src/androidTest/java/com/sample/android/tmdb/ui/paging/search/BaseSearchActivity.kt | alirezaeiii | 158,464,119 | false | null | package com.sample.android.tmdb.ui.paging.search
import android.widget.EditText
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.pressImeActionButton
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import com.sample.android.tmdb.BaseIdlingResource
import org.junit.Test
import com.sample.android.tmdb.R
abstract class BaseSearchActivity: BaseIdlingResource() {
@Test
fun shouldBeAbleToSearch() {
onView(isAssignableFrom(EditText::class.java))
.perform(typeText("<NAME>"),
pressImeActionButton())
onView(withId(R.id.recyclerView)).check(matches(isDisplayed()))
}
} | 1 | null | 20 | 161 | a835bc7ca972619717832860dbb3a95ca37994e5 | 794 | TMDb-Paging-Playground | The Unlicense |
packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotProxyService.kt | liu-wanshun | 595,904,109 | true | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.screenshot
import android.content.Intent
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.shade.ShadeExpansionStateManager
import com.android.systemui.statusbar.phone.CentralSurfaces
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Optional
import javax.inject.Inject
/**
* Provides state from the main SystemUI process on behalf of the Screenshot process.
*/
internal class ScreenshotProxyService @Inject constructor(
private val mExpansionMgr: ShadeExpansionStateManager,
private val mCentralSurfacesOptional: Optional<CentralSurfaces>,
@Main private val mMainDispatcher: CoroutineDispatcher,
) : LifecycleService() {
private val mBinder: IBinder = object : IScreenshotProxy.Stub() {
/**
* @return true when the notification shade is partially or fully expanded.
*/
override fun isNotificationShadeExpanded(): Boolean {
val expanded = !mExpansionMgr.isClosed()
Log.d(TAG, "isNotificationShadeExpanded(): $expanded")
return expanded
}
override fun dismissKeyguard(callback: IOnDoneCallback) {
lifecycleScope.launch {
executeAfterDismissing(callback)
}
}
}
private suspend fun executeAfterDismissing(callback: IOnDoneCallback) =
withContext(mMainDispatcher) {
mCentralSurfacesOptional.ifPresentOrElse(
{
it.executeRunnableDismissingKeyguard(
Runnable {
callback.onDone(true)
}, null,
true /* dismissShade */, true /* afterKeyguardGone */,
true /* deferred */
)
},
{ callback.onDone(false) }
)
}
override fun onBind(intent: Intent): IBinder? {
Log.d(TAG, "onBind: $intent")
return mBinder
}
companion object {
const val TAG = "ScreenshotProxyService"
}
}
| 0 | Java | 1 | 2 | e99201cd9b6a123b16c30cce427a2dc31bb2f501 | 2,971 | platform_frameworks_base | Apache License 2.0 |
sipservice/src/main/java/com/phone/sip/models/ConfigureFCMPushNotification.kt | phonedotcom | 646,764,010 | false | {"Git Config": 1, "Gradle": 3, "Markdown": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "YAML": 2, "Proguard": 1, "Java": 315, "XML": 3, "Kotlin": 15} | /*
* Copyright (c) 2023 Phone.com®, All Rights Reserved.
*/
package com.phone.sip.models
import org.jetbrains.annotations.NotNull
data class ConfigureFCMPushNotification(
@NotNull
var pushToken: String,
@NotNull
var versionName: String,
@NotNull
var bundleID: String,
@NotNull
var deviceInfo: String,
@NotNull
var applicationID: String,
@NotNull
var deviceType: String,
@NotNull
var voipId: String,
@NotNull
var voipPhoneID: String
) | 1 | Java | 1 | 1 | c8fb9540398591b98277c84fc0f4d95de3bc2e01 | 501 | pdc-voip-android-sdk | Apache License 2.0 |
app/src/main/java/com/caster/notes/dsl/features/details/presentation/NoteDetailsScreen.kt | aldefy | 306,821,113 | false | null | package com.caster.notes.dsl.features.details.presentation
import android.view.inputmethod.EditorInfo
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.caster.notes.dsl.common.addTo
import com.caster.notes.dsl.common.bind
import com.caster.notes.dsl.features.details.domain.NoteDetailsState
import com.caster.notes.dsl.features.details.domain.NoteRemoved
import com.caster.notes.dsl.features.details.domain.NoteSaveFailure
import com.caster.notes.dsl.features.details.domain.NoteSaved
import com.caster.notes.dsl.features.list.domain.HideLoading
import com.caster.notes.dsl.features.list.domain.ShowLoading
import com.caster.notes.dsl.model.Note
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
interface NoteDetailsScreen : LifecycleObserver {
val event: LiveData<NoteDetailsEvent>
fun bind(
view: NoteDetailsView,
observable: Observable<NoteDetailsState>
): Disposable
}
class NoteDetailsScreenImpl : NoteDetailsScreen {
private val _event = MutableLiveData<NoteDetailsEvent>()
override val event: LiveData<NoteDetailsEvent> = _event
override fun bind(view: NoteDetailsView, observable: Observable<NoteDetailsState>): Disposable {
return CompositeDisposable().apply {
setupContent(view, observable, this)
setupLoading(view, observable, this)
setupError(view, observable, this)
}
}
fun withNote(note: Note, view: NoteDetailsView) {
view.titleET.setText(note.title)
view.contentET.setText(note.content)
}
fun withSaveButtonClick(view: NoteDetailsView) {
view.saveButton.setOnClickListener {
val title = view.getTitle()
val content = view.getContent()
if (title.isEmpty()) {
_event.value = NoteTitleEmptyEvent
return@setOnClickListener
}
if (content.isEmpty()) {
_event.value = NoteContentEmptyEvent
return@setOnClickListener
}
_event.value = SubmitClicked(title, content)
}
}
fun withInputActionDone(view: NoteDetailsView) {
view.contentET.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
view.saveButton.callOnClick()
true
}
false
}
}
private fun setupLoading(
view: NoteDetailsView,
observable: Observable<NoteDetailsState>,
compositeDisposable: CompositeDisposable
) {
observable
.ofType(ShowLoading::class.java)
.map { Unit }
.bind(view.showLoading())
.addTo(compositeDisposable)
observable
.ofType(HideLoading::class.java)
.map { Unit }
.bind(view.hideLoading())
.addTo(compositeDisposable)
}
private fun setupContent(
view: NoteDetailsView,
observable: Observable<NoteDetailsState>,
compositeDisposable: CompositeDisposable
) {
observable
.ofType(NoteRemoved::class.java)
.map {
_event.value = NoteDeletedEvent
Unit
}
.subscribe()
.addTo(compositeDisposable)
observable
.ofType(NoteSaved::class.java)
.map {
_event.value = AddNoteSuccess
Unit
}
.subscribe()
.addTo(compositeDisposable)
}
private fun setupError(
view: NoteDetailsView,
observable: Observable<NoteDetailsState>,
compositeDisposable: CompositeDisposable
) {
observable
.ofType(NoteSaveFailure::class.java)
.map {
_event.value = NoteAddFailedEvent(it.throwable)
Unit
}
.subscribe()
.addTo(compositeDisposable)
}
} | 0 | Kotlin | 0 | 9 | 084e042aa5c2ca10bf7176f61b51a424bf758f3b | 4,105 | Notes-with-Kotlin-DSL | Apache License 2.0 |
feature_autofill_impl/src/main/kotlin/com/eakurnikov/autoque/autofill/impl/internal/data/repositories/AutofillRepository.kt | eakurnikov | 208,430,680 | false | null | package com.eakurnikov.autoque.autofill.impl.internal.data.repositories
import com.eakurnikov.autoque.autofill.impl.internal.data.model.FillDataDto
import com.eakurnikov.autoque.autofill.impl.internal.data.model.FillDataId
import io.reactivex.Completable
import io.reactivex.Single
/**
* Created by eakurnikov on 2019-09-15
*/
interface AutofillRepository {
fun getAllFillData(packageName: String): Single<List<FillDataDto>>
fun getFillData(packageName: String): Single<List<FillDataDto>>
fun getFillDataById(fillDataId: FillDataId): Single<FillDataDto>
fun addFillData(fillDataDto: FillDataDto): Completable
fun updateFillData(fillDataDto: FillDataDto): Completable
} | 0 | null | 0 | 1 | 4465eef7368e2c0633b4a47a5d0ec3c0076130ba | 697 | AutoQue | Apache License 2.0 |
app/src/main/java/com/nexhub/homedia/MainActivity.kt | NexhubFR | 788,051,929 | false | {"Kotlin": 32918} | package com.nexhub.homedia
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.nexhub.homedia.views.server_registration.presentation.ServerScreen
import com.nexhub.homedia.ui.theme.HomediaTheme
import com.nexhub.homedia.utils.managers.JellyfinManager
import com.nexhub.homedia.utils.managers.PreferencesManager
import com.nexhub.homedia.views.home.presentation.HomeScreen
import com.nexhub.homedia.views.quick_connect.presentation.QuickConnectScreen
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HomediaTheme {
AppNavigation()
}
}
}
@Composable
fun AppNavigation() {
val navController = rememberNavController()
val accessToken = PreferencesManager(context = applicationContext).getData("ACCESS_TOKEN", "")
NavHost(
navController = navController,
startDestination = if (accessToken.isNotEmpty()) getString(R.string.home) else getString(R.string.server_registration)
) {
composable(getString(R.string.server_registration)) { ServerScreen(navController) }
composable(getString(R.string.quick_connect)) { QuickConnectScreen(navController) }
composable(getString(R.string.home)) { HomeScreen(navController) }
}
}
} | 0 | Kotlin | 0 | 0 | 2889af0a5d8401eea7baddce1e3cef17e068eb86 | 1,718 | homedia | MIT License |
src/test/kotlin/com/tkroman/kerl/parser/TypeAwareCallBodyParserTest.kt | tkroman | 387,260,318 | false | null | package com.tkroman.kerl.parser
import com.tkroman.kerl.CALL
import com.tkroman.kerl.GEN_CALL_TYPE
import com.tkroman.kerl.REX_CALL_TYPE
import com.tkroman.kerl.model.InvalidRpcCall
import com.tkroman.kerl.model.RpcCall
import com.tkroman.kerl.model.RpcCallType
import com.tkroman.kerl.model.RpcMethod
import com.tkroman.kerl.model.Unknown
import com.tkroman.kerl.model.ValidRpcCall
import io.appulse.encon.terms.Erlang.NIL
import io.appulse.encon.terms.Erlang.atom
import io.appulse.encon.terms.Erlang.bstring
import io.appulse.encon.terms.Erlang.list
import io.appulse.encon.terms.Erlang.map
import io.appulse.encon.terms.Erlang.tuple
import io.appulse.encon.terms.type.ErlangAtom.ATOM_FALSE
import io.appulse.encon.terms.type.ErlangAtom.ATOM_TRUE
import io.appulse.encon.terms.type.ErlangTuple
import kotlin.test.Test
import kotlin.test.assertEquals
internal class TypeAwareCallBodyParserTest {
private val parser = TypeAwareCallBodyParser()
private fun assertBoth(
call: ErlangTuple,
expected: (RpcCallType) -> RpcCall,
) {
assertEquals(expected(REX_CALL_TYPE), parser.parse(call, REX_CALL_TYPE))
assertEquals(expected(GEN_CALL_TYPE), parser.parse(call, GEN_CALL_TYPE))
}
@Test
fun `happy path - non-empty args`() {
val call = tuple(
CALL,
atom("foo"),
atom("bar"),
list(ATOM_TRUE),
)
assertBoth(call) { ValidRpcCall(it, RpcMethod("foo", "bar"), list(ATOM_TRUE)) }
}
@Test
fun `happy path, empty args are represented as empty list`() {
val call = tuple(
CALL,
atom("foo"),
atom("bar"),
)
assertBoth(call) { ValidRpcCall(it, RpcMethod("foo", "bar"), list()) }
}
@Test
fun `happy path, NIL args are represented as empty list`() {
val call = tuple(
CALL,
atom("foo"),
atom("bar"),
NIL,
)
assertBoth(call) { ValidRpcCall(it, RpcMethod("foo", "bar"), list()) }
}
@Test
fun `invalid args - invalid rpc call`() {
val call = tuple(
CALL,
atom("foo"),
atom("bar"),
atom("not a list")
)
assertBoth(call) { InvalidRpcCall(it, "invalid arguments") }
}
@Test
fun `no function - invalid rpc call`() {
val call = tuple(
CALL,
atom("foo"),
)
assertBoth(call) { InvalidRpcCall(it, "no function") }
}
@Test
fun `no module - invalid rpc call`() {
val call = tuple(
CALL,
)
assertBoth(call) { InvalidRpcCall(it, "no module") }
}
@Test
fun `module is a bstring - invalid rpc call`() {
val call = tuple(
CALL,
bstring("not-an-atom")
)
assertBoth(call) { InvalidRpcCall(it, "no module") }
}
@Test
fun `module is a list - invalid rpc call`() {
val call = tuple(
CALL,
list(ATOM_TRUE)
)
assertBoth(call) {
InvalidRpcCall(it, "no module")
}
}
@Test
fun `module is a map - invalid rpc call`() {
val call = tuple(
CALL,
map(ATOM_TRUE, ATOM_FALSE)
)
assertBoth(call) { InvalidRpcCall(it, "no module") }
}
@Test
fun `module is empty - invalid rpc call`() {
val call = tuple(
CALL,
atom("")
)
assertBoth(call) { InvalidRpcCall(it, "no module") }
}
@Test
fun `function is a bstring - invalid rpc call`() {
val call = tuple(
CALL,
atom("foo"),
bstring("bar")
)
assertBoth(call) { InvalidRpcCall(it, "no function") }
}
@Test
fun `function is a list - invalid rpc call`() {
val call = tuple(
CALL,
atom("foo"),
list(ATOM_TRUE)
)
assertBoth(call) { InvalidRpcCall(it, "no function") }
}
@Test
fun `function is a map - invalid rpc call`() {
val call = tuple(
CALL,
atom("foo"),
map(ATOM_TRUE, ATOM_FALSE)
)
assertBoth(call) { InvalidRpcCall(it, "no function") }
}
@Test
fun `function is empty - invalid rpc call`() {
val call = tuple(
CALL,
atom("foo"),
atom("")
)
assertBoth(call) { InvalidRpcCall(it, "no function") }
}
@Test
fun `no call - invalid rpc call`() {
val call = tuple()
assertBoth(call) { InvalidRpcCall(it, "invalid call section") }
}
@Test
fun `call is not atom(call) - invalid rpc call`() {
val call = tuple(
atom("something-else")
)
assertBoth(call) {
InvalidRpcCall(it, "invalid call section")
}
}
@Test
fun `unknown call type`() {
val result = parser.parse(atom("doesnt-matter"), Unknown)
assertEquals(
InvalidRpcCall(Unknown, "unknown call type"),
result
)
}
}
| 0 | Kotlin | 0 | 0 | 994745ada93a016cfc22460b82f573d80c7b6250 | 5,153 | kerl | MIT License |
app/src/main/java/com/starbase/bankwallet/modules/restoremnemonic/RestoreMnemonicModule.kt | Sonar-LaunchPad | 410,111,846 | true | {"Kotlin": 2429867, "Shell": 2039, "Ruby": 966} | package com.starbase.bankwallet.modules.restoremnemonic
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.starbase.bankwallet.core.App
import io.horizontalsystems.bankwallet.core.managers.PassphraseValidator
object RestoreMnemonicModule {
class Factory : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val service = RestoreMnemonicService(com.starbase.bankwallet.core.App.wordsManager, PassphraseValidator())
return RestoreMnemonicViewModel(service, listOf(service)) as T
}
}
}
| 0 | null | 0 | 0 | 1327d5f457ae383bf6849ef8816c859a1536f150 | 652 | unstoppable-wallet-android | MIT License |
app/src/main/java/com/hh/composeplayer/util/ComposeCommon.kt | yellowhai | 403,791,457 | false | null | package com.hh.composeplayer.util
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyGridScope
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.material.TabPosition
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.*
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.PagerState
import kotlin.math.absoluteValue
import kotlin.math.roundToInt
/**
* @ProjectName: HelloComPose
* @Package: com.hh.hellocompose.util
* @Description: 类描述
* @Author: Hai Huang
* @CreateDate: 2021/8/25 9:17
*/
fun Modifier.tabIndicatorOffsetH(
currentTabPosition: TabPosition,
width: Dp = 1.dp
): Modifier = composed(
inspectorInfo = debugInspectorInfo {
name = "tabIndicatorOffset"
value = currentTabPosition
}
) {
val currentTabWidth by animateDpAsState(
targetValue = width,
animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
)
val indicatorOffset by animateDpAsState(
targetValue = currentTabPosition.left,
animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
)
fillMaxWidth()
.wrapContentSize(Alignment.BottomStart)
.offset(x = indicatorOffset + ((currentTabPosition.width - currentTabWidth) / 2))
.width(currentTabWidth)
}
@ExperimentalFoundationApi
inline fun <T> LazyGridScope.itemsH(
items: List<T>,
crossinline itemContent: @Composable LazyItemScope.(item: T) -> Unit
) = items(items.size) {
if(items.isNotEmpty()){
itemContent(items[it])
}
}
@ExperimentalPagerApi
fun Modifier.pagerTabIndicatorOffsetH(
pagerState: PagerState,
tabPositions: List<TabPosition>,
width: Dp = 1.dp
): Modifier = composed {
// If there are no pages, nothing to show
if (pagerState.pageCount == 0) return@composed this
val targetIndicatorOffset: Dp
val indicatorWidth: Dp
val currentTab = tabPositions[pagerState.currentPage]
val targetPage = pagerState.targetPage
val targetTab = targetPage.let { tabPositions.getOrNull(it) }
if (targetTab != null) {
// The distance between the target and current page. If the pager is animating over many
// items this could be > 1
val targetDistance = (targetPage - pagerState.currentPage).absoluteValue
// Our normalized fraction over the target distance
val fraction = (pagerState.currentPageOffset / kotlin.math.max(targetDistance, 1)).absoluteValue
targetIndicatorOffset = lerp(currentTab.left, targetTab.left, fraction)
indicatorWidth = lerp(currentTab.width, targetTab.width, fraction).absoluteValue
} else {
// Otherwise we just use the current tab/page
targetIndicatorOffset = currentTab.left
indicatorWidth = currentTab.width
}
fillMaxWidth()
.wrapContentSize(Alignment.BottomStart)
.offset(x = targetIndicatorOffset + ((currentTab.width - width) / 2))
.width(width)
}
private inline val Dp.absoluteValue: Dp
get() = value.absoluteValue.dp
fun Modifier.ownTabIndicatorOffset(
currentTabPosition: TabPosition,
currentTabWidth: Dp = currentTabPosition.width
): Modifier = composed(
inspectorInfo = debugInspectorInfo {
name = "tabIndicatorOffset"
value = currentTabPosition
}
) {
val indicatorOffset by animateDpAsState(
targetValue = currentTabPosition.left,
animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
)
fillMaxWidth()
.wrapContentSize(Alignment.BottomStart)
.offset(x = indicatorOffset + ((currentTabPosition.width - currentTabWidth) / 2))
.width(currentTabWidth)
}
fun Modifier.percentOffsetX(percent: Float) = this.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.placeRelative(IntOffset((placeable.width * percent).roundToInt(), 0))
}
}
@Stable
class QureytoImageShapes(var hudu: Float = 100f) : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
val path = Path()
path.moveTo(0f, 0f)
path.lineTo(0f, size.height-hudu)
path.quadraticBezierTo(size.width/2f, size.height, size.width, size.height-hudu)
path.lineTo(size.width,0f)
path.close()
return Outline.Generic(path)
}
}
| 0 | Kotlin | 0 | 1 | 390013e6dc7acdb1045a321482475daa2590d2a8 | 5,401 | HhPlayer | Apache License 2.0 |
app/src/main/java/com/solocatapps/mvvmproductlistapp/ui/ProductsDetailFragment.kt | abdurrahimkizilkaya | 624,117,768 | false | null | package com.solocatapps.mvvmproductlistapp.ui
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.navArgs
import coil.load
import com.solocatapps.mvvmproductlistapp.databinding.FragmentProductDetailBinding
import com.solocatapps.mvvmproductlistapp.model.Product
import com.solocatapps.mvvmproductlistapp.util.loadWithCoil
class ProductDetailFragment : Fragment() {
private var _binding: FragmentProductDetailBinding? = null
private val binding get() = _binding!!
private val args : ProductDetailFragmentArgs by navArgs()
companion object {
private const val TAG = "ProductDetailFragment"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentProductDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val product = args.product
setupUI(product)
}
private fun setupUI(product : Product){
val imageLoader = loadWithCoil(requireContext())
binding.apply {
textCategory.text = product.category
imageProduct.load(product.images[0], imageLoader)
textTitle.text = product.title
textDescription.text = product.description
textPrice.text = product.price.toString() + "$"
ratingBar.rating = product.rating.toFloat()
textStock.text = "Available amount: " + product.stock
}
}
} | 0 | Kotlin | 0 | 0 | bd8ce0b4f02b6728cd6a82dc716af084c2957bc2 | 1,883 | MVVM_Retrofit_RxJava_ProductApp | MIT License |
app/src/main/java/com/fatihden/tuto/t0_pick_a_language/basics_of_kotlin/Interfaces/main.kt | dengizfth | 839,480,509 | false | {"Kotlin": 2550} | package com.fatihden.tuto.t0_pick_a_language.basics_of_kotlin.Interfaces
fun main(){
} | 0 | Kotlin | 0 | 0 | 1d97edb8d9f3e34b651035e7e7f20e66d1f05232 | 88 | junior_tutorial_and_guide_kotlin_android | MIT License |
src/main/kotlin/no/nav/syfo/RelationType.kt | purebase | 158,395,714 | false | null | package no.nav.pale
enum class RelationType(val kodeverkVerdi: String) {
MOR("MORA"),
FAR("FARA"),
BARN("BARN"),
FOSTERMOR("FOMO"),
FOSTERFAR("FOFA"),
FOSTERBARN("FOBA"),
EKTEFELLE("EKTE"),
REGISTRERT_PARTNER_MED("REPA"),
;
companion object {
fun fromKodeverkValue(kodeverkValue: String): RelationType? {
return RelationType.values().find { it.kodeverkVerdi == kodeverkValue }
}
}
}
| 0 | Kotlin | 2 | 0 | 8168e978017701b6016ee7d985036c6b94325d35 | 457 | syfosmregler | MIT License |
weibo/Wbclient/app/src/main/java/cn/magicalsheep/wbclient/MainActivity.kt | MagicalSheep | 570,933,605 | false | {"Kotlin": 287381, "Java": 145241, "C": 78070, "Rust": 41263, "HTML": 17978, "CSS": 6500, "Batchfile": 3923, "CMake": 777} | package cn.magicalsheep.wbclient
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import cn.magicalsheep.wbclient.ui.AppContent
import cn.magicalsheep.wbclient.ui.model.HomeViewModel
import cn.magicalsheep.wbclient.ui.model.ProfileViewModel
import cn.magicalsheep.wbclient.ui.navigation.BottomNavigationBar
import cn.magicalsheep.wbclient.ui.navigation.NavigationActions
import cn.magicalsheep.wbclient.ui.navigation.Route
import cn.magicalsheep.wbclient.ui.navigation.TopNavigationBar
import cn.magicalsheep.wbclient.ui.theme.WbclientTheme
import cn.magicalsheep.wbclient.ui.views.LoginPage
import com.google.accompanist.navigation.animation.rememberAnimatedNavController
class MainActivity : ComponentActivity() {
private val homeViewModel: HomeViewModel by viewModels()
private val profileViewModel: ProfileViewModel by viewModels()
@OptIn(ExperimentalAnimationApi::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WbclientTheme {
val navController = rememberAnimatedNavController()
val navigationActions = remember(navController) {
NavigationActions(navController)
}
val navBackStackEntry by navController.currentBackStackEntryAsState()
val selectedDestination =
navBackStackEntry?.destination?.route ?: Route.HOME
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
var isNavBarVisible by remember { mutableStateOf(true) }
val isLogin by profileViewModel.isLogin.collectAsState()
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.inverseOnSurface)
) {
TopNavigationBar(
selectedDestination = selectedDestination,
navigationActions = navigationActions,
onNavigationToSettings = { navigationActions.navigateTo(Route.SETTINGS) },
onNavigationToAbout = { navigationActions.navigateTo(Route.ABOUT) }
)
AppContent(
navController = navController,
navigationActions = navigationActions,
homeViewModel = homeViewModel,
profileViewModel = profileViewModel,
modifier = Modifier
.weight(1f)
.background(MaterialTheme.colorScheme.inverseOnSurface),
snackbarHostState = snackbarHostState,
scope = scope,
onPageDownScroll = { isNavBarVisible = false },
onPageUpScroll = { isNavBarVisible = true }
)
AnimatedVisibility(visible = isNavBarVisible) {
BottomNavigationBar(
selectedDestination = selectedDestination,
navigateToTopLevelDestination = navigationActions::navigateTo
)
}
}
AnimatedVisibility(visible = !isLogin) {
LoginPage(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
profileViewModel = profileViewModel,
snackbarHostState = snackbarHostState,
scope = scope,
onNavigationToHome = { navigationActions.navigateTo(Route.HOME) }
)
}
SnackbarHost(
modifier = Modifier.padding(0.dp, 8.dp),
hostState = snackbarHostState
)
}
}
}
}
} | 0 | Kotlin | 6 | 44 | a550ba111bfbc715ae4bb1bff15eed757bb749bb | 5,241 | lab | MIT License |
feature-walletconnect-impl/src/main/java/jp/co/soramitsu/walletconnect/impl/presentation/WalletConnectInteractorImpl.kt | soramitsu | 278,060,397 | false | {"Kotlin": 4688177, "Java": 18796} | package jp.co.soramitsu.walletconnect.impl.presentation
import co.jp.soramitsu.walletconnect.domain.WalletConnectInteractor
import com.walletconnect.android.cacao.signature.SignatureType
import com.walletconnect.android.utils.cacao.sign
import com.walletconnect.web3.wallet.client.Wallet
import com.walletconnect.web3.wallet.client.Web3Wallet
import com.walletconnect.web3.wallet.utils.CacaoSigner
import jp.co.soramitsu.account.api.domain.interfaces.AccountRepository
import jp.co.soramitsu.account.api.domain.model.MetaAccount
import jp.co.soramitsu.account.api.domain.model.address
import jp.co.soramitsu.common.data.secrets.v2.KeyPairSchema
import jp.co.soramitsu.common.data.secrets.v2.MetaAccountSecrets
import jp.co.soramitsu.common.utils.mapValuesNotNull
import jp.co.soramitsu.core.crypto.mapCryptoTypeToEncryption
import jp.co.soramitsu.core.extrinsic.ExtrinsicBuilderFactory
import jp.co.soramitsu.core.extrinsic.keypair_provider.KeypairProvider
import jp.co.soramitsu.core.models.ChainId
import jp.co.soramitsu.runtime.ext.accountIdOf
import jp.co.soramitsu.runtime.multiNetwork.ChainRegistry
import jp.co.soramitsu.runtime.multiNetwork.chain.ChainsRepository
import jp.co.soramitsu.runtime.multiNetwork.chain.model.Chain
import jp.co.soramitsu.shared_utils.encrypt.MultiChainEncryption
import jp.co.soramitsu.shared_utils.encrypt.SignatureWrapper
import jp.co.soramitsu.shared_utils.encrypt.Signer
import jp.co.soramitsu.shared_utils.extensions.fromHex
import jp.co.soramitsu.shared_utils.extensions.toHexString
import jp.co.soramitsu.wallet.impl.data.network.blockchain.EthereumRemoteSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import org.web3j.crypto.Credentials
import org.web3j.crypto.RawTransaction
import org.web3j.crypto.Sign
import org.web3j.crypto.StructuredDataEncoder
import org.web3j.utils.Numeric
import java.math.BigInteger
@Suppress("LargeClass")
class WalletConnectInteractorImpl(
private val chainsRepository: ChainsRepository,
private val ethereumSource: EthereumRemoteSource,
private val accountRepository: AccountRepository,
private val keypairProvider: KeypairProvider,
private val chainRegistry: ChainRegistry,
private val extrinsicBuilderFactory: ExtrinsicBuilderFactory
) : WalletConnectInteractor {
@Suppress("MagicNumber")
val Chain.caip2id: String
get() {
val namespace = if (isEthereumChain) Caip2Namespace.EIP155 else Caip2Namespace.POLKADOT
val chainId = id.substring(0, Integer.min(id.length, 32))
return namespace.value + ":" + chainId
}
override suspend fun getChains(): List<Chain> = chainsRepository.getChains()
override suspend fun checkChainsSupported(proposal: Wallet.Model.SessionProposal): Result<Boolean> {
val chains = getChains()
val proposalRequiredChains = proposal.requiredNamespaces.flatMap { it.value.chains.orEmpty() }
val supportedChains = chains.filter {
it.caip2id in proposalRequiredChains
}
val isSupported = supportedChains.size >= proposalRequiredChains.size
return Result.success(isSupported)
}
override suspend fun approveSession(
proposal: Wallet.Model.SessionProposal,
selectedWalletIds: Set<Long>,
selectedOptionalChainIds: Set<String>,
onSuccess: (Wallet.Params.SessionApprove) -> Unit,
onError: (Wallet.Model.Error) -> Unit
) {
val chains = getChains()
val allMetaAccounts = withContext(Dispatchers.IO) { accountRepository.allMetaAccounts() }
val requiredSessionNamespaces = proposal.requiredNamespaces.mapValues { proposal ->
val requiredNamespaceChains = chains.filter { chain ->
chain.caip2id in proposal.value.chains.orEmpty()
}
val requiredAccounts = selectedWalletIds.flatMap { walletId ->
requiredNamespaceChains.mapNotNull { chain ->
allMetaAccounts.firstOrNull { it.id == walletId }?.address(chain)?.let { address ->
chain.caip2id + ":" + address
}
}
}
Wallet.Model.Namespace.Session(
chains = proposal.value.chains,
accounts = requiredAccounts,
events = proposal.value.events,
methods = proposal.value.methods
)
}
val optionalSessionNamespaces = if (selectedOptionalChainIds.isEmpty()) {
mapOf()
} else {
proposal.optionalNamespaces.mapValuesNotNull { optional ->
val optionalNamespaceSelectedChains = chains.filter { chain ->
chain.caip2id in optional.value.chains.orEmpty() && chain.caip2id in selectedOptionalChainIds
}
if (optionalNamespaceSelectedChains.isEmpty()) return@mapValuesNotNull null
val optionalAccounts = selectedWalletIds.flatMap { walletId ->
optionalNamespaceSelectedChains.mapNotNull { chain ->
allMetaAccounts.firstOrNull { it.id == walletId }?.address(chain)?.let { address ->
chain.caip2id + ":" + address
}
}
}
val sessionChains = optionalNamespaceSelectedChains.map { it.caip2id }
Wallet.Model.Namespace.Session(
chains = sessionChains,
accounts = optionalAccounts,
events = optional.value.events,
methods = optional.value.methods
)
}
}
val sessionNamespaces = requiredSessionNamespaces.mapValues { required ->
val optional = optionalSessionNamespaces[required.key]
Wallet.Model.Namespace.Session(
chains = (required.value.chains.orEmpty() + optional?.chains.orEmpty()).distinct(),
accounts = (required.value.accounts + optional?.accounts.orEmpty()).distinct(),
events = (required.value.events + optional?.events.orEmpty()).distinct(),
methods = (required.value.methods + optional?.methods.orEmpty()).distinct()
)
} + optionalSessionNamespaces.filter { it.key !in requiredSessionNamespaces.keys }
Web3Wallet.approveSession(
params = Wallet.Params.SessionApprove(
proposerPublicKey = proposal.proposerPublicKey,
namespaces = sessionNamespaces,
relayProtocol = proposal.relayProtocol
),
onSuccess = onSuccess,
onError = onError
)
}
override fun rejectSession(
proposal: Wallet.Model.SessionProposal,
onSuccess: (Wallet.Params.SessionReject) -> Unit,
onError: (Wallet.Model.Error) -> Unit
) {
Web3Wallet.rejectSession(
params = Wallet.Params.SessionReject(
proposal.proposerPublicKey,
"User rejected"
),
onSuccess = onSuccess,
onError = onError
)
}
override fun silentRejectSession(
proposal: Wallet.Model.SessionProposal,
onSuccess: (Wallet.Params.SessionReject) -> Unit,
onError: (Wallet.Model.Error) -> Unit
) {
Web3Wallet.rejectSession(
params = Wallet.Params.SessionReject(
proposal.proposerPublicKey,
"Blockchain not supported by wallet"
),
onSuccess = onSuccess,
onError = onError
)
}
override suspend fun handleSignAction(
chain: Chain,
topic: String,
recentSession: Wallet.Model.SessionRequest,
onSignError: (Exception) -> Unit,
onRequestSuccess: (operationHash: String?, chainId: ChainId?) -> Unit,
onRequestError: (Wallet.Model.Error) -> Unit
) {
val address = recentSession.request.address ?: return
val accountId = chain.accountIdOf(address)
val metaAccount = withContext(Dispatchers.IO) { accountRepository.findMetaAccount(accountId) } ?: return
val signResult = try {
getSignResult(metaAccount, recentSession)
} catch (e: Exception) {
onSignError(e)
return
}
val jsonRpcResponse = if (signResult == null) {
Wallet.Model.JsonRpcResponse.JsonRpcError(
id = recentSession.request.id,
code = 4001,
message = "Error perform sign"
)
} else {
Wallet.Model.JsonRpcResponse.JsonRpcResult(
id = recentSession.request.id,
result = signResult
)
}
Web3Wallet.respondSessionRequest(
params = Wallet.Params.SessionRequestResponse(
sessionTopic = topic,
jsonRpcResponse = jsonRpcResponse
),
onSuccess = {
val operationHash = signResult.takeIf {
recentSession.request.method == WalletConnectMethod.EthereumSendTransaction.method
}
val chainId = chain.id.takeIf {
recentSession.request.method == WalletConnectMethod.EthereumSendTransaction.method
}
onRequestSuccess(operationHash, chainId)
},
onError = onRequestError
)
}
private suspend fun getSignResult(metaAccount: MetaAccount, recentSession: Wallet.Model.SessionRequest): String? =
when (recentSession.request.method) {
WalletConnectMethod.EthereumSign.method,
WalletConnectMethod.EthereumPersonalSign.method -> {
getEthPersonalSignResult(metaAccount, recentSession)
}
WalletConnectMethod.EthereumSignTransaction.method -> {
getEthSignTransactionResult(metaAccount, recentSession)
}
WalletConnectMethod.EthereumSendTransaction.method -> {
getEthSendTransactionResult(metaAccount, recentSession)
}
WalletConnectMethod.EthereumSignTypedData.method,
WalletConnectMethod.EthereumSignTypedDataV4.method -> {
getEthSignTypedResult(metaAccount, recentSession)
}
WalletConnectMethod.PolkadotSignTransaction.method -> {
getPolkadotSignTransaction(recentSession)
}
WalletConnectMethod.PolkadotSignMessage.method -> {
getPolkadotSignMessage(recentSession)
}
else -> null
}
private suspend fun getEthSignTypedResult(
metaAccount: MetaAccount,
recentSession: Wallet.Model.SessionRequest
): String {
val ethSignTypedMessage = recentSession.request.message
val message = StructuredDataEncoder(ethSignTypedMessage).hashStructuredData()
val secrets = accountRepository.getMetaAccountSecrets(metaAccount.id) ?: error("There are no secrets for metaId: ${metaAccount.id}")
val keypairSchema = secrets[MetaAccountSecrets.EthereumKeypair]
val privateKey = keypairSchema?.get(KeyPairSchema.PrivateKey)
val cred = Credentials.create(privateKey?.toHexString())
val signatureData = Sign.signMessage(message, cred.ecKeyPair, false)
val signatureWrapper = SignatureWrapper.Ecdsa(signatureData.v, signatureData.r, signatureData.s)
return signatureWrapper.signature.toHexString(true)
}
private suspend fun getEthSendTransactionResult(
metaAccount: MetaAccount,
recentSession: Wallet.Model.SessionRequest
): String {
val chainId = recentSession.chainId?.removePrefix("${Caip2Namespace.EIP155.value}:") ?: error("No chain")
val secrets = accountRepository.getMetaAccountSecrets(metaAccount.id) ?: error("There are no secrets for metaId: ${metaAccount.id}")
val keypairSchema = secrets[MetaAccountSecrets.EthereumKeypair] ?: error("There are no secrets for metaId: ${metaAccount.id}")
val privateKey = keypairSchema[KeyPairSchema.PrivateKey]
val raw = mapToRawTransaction(recentSession.request.message)
return ethereumSource.sendRawTransaction(
chainId,
raw,
privateKey.toHexString()
).getOrThrow()
}
private suspend fun getEthSignTransactionResult(
metaAccount: MetaAccount,
recentSession: Wallet.Model.SessionRequest
): String {
val chainId = recentSession.chainId?.removePrefix("${Caip2Namespace.EIP155.value}:") ?: error("No chain")
val secrets = accountRepository.getMetaAccountSecrets(metaAccount.id) ?: error("There are no secrets for metaId: ${metaAccount.id}")
val keypairSchema = secrets[MetaAccountSecrets.EthereumKeypair] ?: error("There are no secrets for metaId: ${metaAccount.id}")
val privateKey = keypairSchema[KeyPairSchema.PrivateKey]
val raw = mapToRawTransaction(recentSession.request.message)
return ethereumSource.signRawTransaction(
chainId,
raw,
privateKey.toHexString()
).getOrThrow()
}
private suspend fun getEthPersonalSignResult(
metaAccount: MetaAccount,
recentSession: Wallet.Model.SessionRequest
): String {
val secrets = accountRepository.getMetaAccountSecrets(metaAccount.id) ?: error("There are no secrets for metaId: ${metaAccount.id}")
val keypairSchema = secrets[MetaAccountSecrets.EthereumKeypair]
val privateKey = keypairSchema?.get(KeyPairSchema.PrivateKey) ?: throw IllegalArgumentException("no eth keypair")
return CacaoSigner.sign(
recentSession.request.message,
privateKey,
SignatureType.EIP191
).s
}
private suspend fun getPolkadotSignTransaction(recentSession: Wallet.Model.SessionRequest): String {
val params = JSONObject(recentSession.request.params)
val signPayload = JSONObject(params.getString("transactionPayload"))
val address = signPayload.getString("address")
val genesisHash = signPayload.getString("genesisHash").drop(2)
val tip = signPayload.getString("tip").decodeNumericQuantity()
val chain = chainRegistry.getChain(genesisHash)
val accountId = chain.accountIdOf(address)
val keypair = keypairProvider.getKeypairFor(chain, accountId)
val cryptoType = keypairProvider.getCryptoTypeFor(chain, accountId)
val extrinsicBuilder = extrinsicBuilderFactory.create(chain, keypair, cryptoType, tip)
val signature = extrinsicBuilder.build()
return JSONObject().apply {
put("id", 0)
put("signature", signature)
}.toString()
}
private suspend fun getPolkadotSignMessage(recentSession: Wallet.Model.SessionRequest): String {
val address = recentSession.request.address ?: error("No address")
val data = recentSession.request.message
val allChains = getChains()
val chain = allChains.first { chain -> chain.caip2id == recentSession.chainId }
val accountId = chain.accountIdOf(address)
val keypair = keypairProvider.getKeypairFor(chain, accountId)
val multiChainEncryption = if (chain.isEthereumBased) {
MultiChainEncryption.Ethereum
} else {
val cryptoType = keypairProvider.getCryptoTypeFor(chain, accountId)
val encryption = mapCryptoTypeToEncryption(cryptoType)
MultiChainEncryption.Substrate(encryption)
}
val dataAsByteArray = runCatching {
data.fromHex()
}.getOrElse {
data.encodeToByteArray()
}
val signature = Signer.sign(multiChainEncryption, dataAsByteArray, keypair)
return JSONObject().apply {
put("id", recentSession.request.id)
put("signature", signature.signature.toHexString(true))
}.toString()
}
private fun mapToRawTransaction(request: String): RawTransaction = with(JSONObject(request)) {
RawTransaction.createTransaction(
optString("nonce").safeDecodeNumericQuantity(),
optString("gasPrice").safeDecodeNumericQuantity(),
optString("gasLimit").safeDecodeNumericQuantity(),
getString("to"),
optString("value").safeDecodeNumericQuantity(),
optString("data")
)
}
private fun String.safeDecodeNumericQuantity(): BigInteger? {
return kotlin.runCatching { Numeric.decodeQuantity(this) }.getOrNull()
}
private fun String.decodeNumericQuantity(): BigInteger {
return Numeric.decodeQuantity(this)
}
override fun rejectSessionRequest(
sessionTopic: String,
requestId: Long,
onSuccess: (Wallet.Params.SessionRequestResponse) -> Unit,
onError: (Wallet.Model.Error) -> Unit
) {
Web3Wallet.respondSessionRequest(
params = Wallet.Params.SessionRequestResponse(
sessionTopic = sessionTopic,
jsonRpcResponse = Wallet.Model.JsonRpcResponse.JsonRpcError(
id = requestId,
code = 4001,
message = "User rejected request"
)
),
onSuccess = onSuccess,
onError = onError
)
}
override fun getActiveSessionByTopic(topic: String) = Web3Wallet.getActiveSessionByTopic(topic)
override fun getPendingListOfSessionRequests(topic: String) = Web3Wallet.getPendingListOfSessionRequests(topic)
override fun disconnectSession(
topic: String,
onSuccess: (Wallet.Params.SessionDisconnect) -> Unit,
onError: (Wallet.Model.Error) -> Unit
) {
Web3Wallet.disconnectSession(
params = Wallet.Params.SessionDisconnect(topic),
onSuccess = {
WCDelegate.refreshConnections()
onSuccess(it)
},
onError = onError
)
}
override fun pair(
pairingUri: String,
onSuccess: (Wallet.Params.Pair) -> Unit,
onError: (Wallet.Model.Error) -> Unit
) {
val pairingParams = Wallet.Params.Pair(pairingUri)
Web3Wallet.pair(
params = pairingParams,
onSuccess = onSuccess,
onError = onError
)
}
}
| 9 | Kotlin | 22 | 74 | 7ba51fa5830984ff2f3e3304bcaa18b785cc0a99 | 18,539 | fearless-Android | Apache License 2.0 |
test/src/me/anno/tests/physics/fluid/FluidSim.kt | AntonioNoack | 456,513,348 | false | {"Kotlin": 8906185, "C": 236481, "Java": 11483, "GLSL": 9454, "Lua": 4108} | package me.anno.tests.physics.fluid
import me.anno.Time
import me.anno.ecs.Entity
import me.anno.ecs.components.anim.AnimTexture
import me.anno.ecs.components.mesh.*
import me.anno.ecs.components.mesh.terrain.TerrainUtils
import me.anno.engine.ui.control.DraggingControls
import me.anno.engine.ui.render.ECSMeshShader
import me.anno.engine.ui.render.RenderView
import me.anno.engine.ui.render.SceneView.Companion.testSceneWithUI
import me.anno.gpu.GFX.flat01
import me.anno.gpu.GFXState
import me.anno.gpu.GFXState.renderPurely
import me.anno.gpu.GFXState.useFrame
import me.anno.gpu.blending.BlendMode
import me.anno.gpu.pipeline.PipelineStage.Companion.TRANSPARENT_PASS
import me.anno.gpu.shader.GLSLType
import me.anno.gpu.shader.Renderer.Companion.copyRenderer
import me.anno.gpu.shader.ShaderLib
import me.anno.gpu.shader.builder.ShaderStage
import me.anno.gpu.shader.builder.Variable
import me.anno.input.Input
import me.anno.input.Key
import me.anno.maths.Maths.hasFlag
import me.anno.maths.Maths.max
import me.anno.tests.physics.fluid.FluidSimulator.splashShader
import me.anno.tests.physics.fluid.FluidSimulator.splatShader
import me.anno.ui.Panel
import me.anno.utils.types.Arrays.resize
import org.joml.AABBd
import org.joml.Matrix4x3d
var mx = 0f
var my = 0f
fun step(it: Panel, lx: Float, ly: Float, s: Float, sim: FluidSimulation) {
val dt = Time.deltaTime
renderPurely {
useFrame(copyRenderer) {
// when the user clicks, we spawn an outgoing circle
val pressForce = when {
Input.wasKeyPressed(Key.BUTTON_LEFT) -> +1
Input.wasKeyReleased(Key.BUTTON_LEFT) -> -1
else -> 0
}
if (pressForce != 0) {
splashShader.apply {
useFrame(sim.velocity.read) {
GFXState.blendMode.use(BlendMode.PURE_ADD) {
use()
v1f("strength", 10f * s * pressForce)
v4f("posSize", lx, ly, s, s)
v4f("tiling", 1f, 1f, 0f, 0f)
m4x4("transform")
flat01.draw(splashShader)
}
}
}
}
// user interaction
// velocity.read -> velocity.write
val force = 100f * s / it.height
val dx = mx * force
val dy = my * force
if (dx != 0f || dy != 0f) {
GFXState.blendMode.use(BlendMode.PURE_ADD) {
splatShader.apply {
useFrame(sim.velocity.read) {
use()
v4f("color", dx, dy, 0f, 0f)
v4f("posSize", lx, ly, s, s)
v4f("tiling", 1f, 1f, 0f, 0f)
m4x4("transform")
flat01.draw(splatShader)
}
}
}
mx = 0f
my = 0f
}
sim.step(dt.toFloat())
}
}
}
val fluidMeshShader = object : ECSMeshShader("fluid") {
override fun createVertexStages(flags: Int): List<ShaderStage> {
val defines = createDefines(flags)
val variables = createVertexVariables(flags)
val stage = ShaderStage(
"vertex",
variables + listOf(
Variable(GLSLType.S2D, "heightTex"),
Variable(GLSLType.V1F, "waveHeight")
), defines.toString() +
"localPosition = coords + vec3(0,waveHeight * texture(heightTex,uvs).x,0);\n" + // is output, so no declaration needed
motionVectorInit +
instancedInitCode +
// normalInitCode +
"#ifdef COLORS\n" +
" vec2 texSize = textureSize(heightTex,0);\n" +
" vec2 du = vec2(1.0/texSize.x,0.0), dv = vec2(0.0,1.0/texSize.y);\n" +
" float dx = texture(heightTex,uvs+du).x - texture(heightTex,uvs-du).x;\n" +
" float dz = texture(heightTex,uvs+dv).x - texture(heightTex,uvs-dv).x;\n" +
" normal = normalize(vec3(dx*waveHeight, 1.0, dz*waveHeight));\n" +
" tangent = tangents;\n" +
"#endif\n" +
applyTransformCode +
colorInitCode +
"gl_Position = matMul(transform, vec4(finalPosition, 1.0));\n" +
motionVectorCode +
ShaderLib.positionPostProcessing
)
if (flags.hasFlag(IS_ANIMATED) && AnimTexture.useAnimTextures) stage.add(getAnimMatrix)
if (flags.hasFlag(USES_PRS_TRANSFORM)) stage.add(ShaderLib.quatRot)
return listOf(stage)
}
}
fun createFluidMesh(sim: FluidSimulation, waveHeight: Float): Mesh {
// todo use procedural mesh instead?
val w = sim.width
val h = sim.height
val mesh = Mesh()
TerrainUtils.generateRegularQuadHeightMesh(
w, h, 0, w, false, 1f, mesh,
{ 0f }, { -1 }
)
// generate UVs
val pos = mesh.positions!!
val uvs = mesh.uvs.resize(pos.size / 3 * 2)
for (i in uvs.indices step 2) {
uvs[i] = 0.5f + pos[i / 2 * 3] / w
uvs[i + 1] = 0.5f - pos[i / 2 * 3 + 2] / h
}
mesh.uvs = uvs
mesh.invalidateGeometry()
val fluidMaterial = Material()
fluidMaterial.shader = fluidMeshShader
fluidMaterial.shaderOverrides["heightTex"] = TypeValueV2(GLSLType.S2D) { sim.pressure.read }
fluidMaterial.shaderOverrides["waveHeight"] = TypeValue(GLSLType.V1F, waveHeight)
fluidMaterial.pipelineStage = TRANSPARENT_PASS
fluidMaterial.metallicMinMax.set(1f)
fluidMaterial.roughnessMinMax.set(0f)
fluidMaterial.diffuseBase.w = 1f
fluidMaterial.indexOfRefraction = 1.33f // water
mesh.materials = listOf(fluidMaterial.ref)
return mesh
}
/**
* small gpu fluid simulation
*
* adapted from https://github.com/PavelDoGreat/WebGL-Fluid-Simulation/blob/master/script.js
*
* todo add terrain (2.5d, without overhangs)
* todo add small bodies like boats/ducks/... on the surface
* */
fun main() {
val w = 1024
val h = 1024
val p = 20
val sim = FluidSimulation(w, h, p)
val init = lazy {
// initialize textures
sim.velocity.read.clearColor(0f, 0f, 0f, 1f) // 2d, so -1 = towards bottom right
sim.pressure.read.clearColor(0.5f, 0f, 0f, 1f) // 1d, so max level
// todo initialize sim.particles randomly
sim.particles.read.clearColor(0)
}
val waveHeight = 50f
val mesh = createFluidMesh(sim, waveHeight)
val comp = object : MeshComponent(mesh) {
fun update(ci: RenderView) {
// calculate interaction coordinates
val rayDir = ci.getMouseRayDirection()
val rayPos = ci.cameraPosition
val dist = (waveHeight - rayPos.y) / rayDir.y
val gx = 0.5f + (rayPos.x + dist * rayDir.x) / w
val gz = 0.5f + (rayPos.z + dist * rayDir.z) / h
val lx = if (dist > 0f) gx.toFloat() else 0f
val ly = if (dist > 0f) gz.toFloat() else 0f
// initialize, if needed
init.value
// step physics
step(ci, lx, ly, 0.2f * dist.toFloat() / max(w, h), sim)
}
override fun onUpdate(): Int {
super.onUpdate()
val ci = RenderView.currentInstance
if (ci != null) update(ci)
return 1
}
override fun fillSpace(globalTransform: Matrix4x3d, aabb: AABBd): Boolean {
localAABB.set(mesh.getBounds())
localAABB.minY = -50.0
localAABB.maxY = +50.0
localAABB.transform(globalTransform, globalAABB)
aabb.union(globalAABB)
return true
}
}
val scene = Entity(comp)
// we handle collisions ourselves
comp.collisionMask = 0
testSceneWithUI("FluidSim", scene) {
it.editControls = object : DraggingControls(it.renderer) {
override fun onMouseMoved(x: Float, y: Float, dx: Float, dy: Float) {
super.onMouseMoved(x, y, dx, dy)
if (Input.isLeftDown) {
mx += dx
my += dy
}
}
}
}
} | 0 | Kotlin | 3 | 14 | f401a5e6e71fc42b55028e414667532bce905fbf | 8,468 | RemsEngine | Apache License 2.0 |
multipaysdk/src/main/java/com/inventiv/multipaysdk/ui/authentication/otp/OtpFragment.kt | multinetinventiv | 332,757,520 | false | null | package com.inventiv.multipaysdk.ui.authentication.otp
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.text.HtmlCompat
import androidx.lifecycle.ViewModelProvider
import com.inventiv.multipaysdk.MultiPaySdk
import com.inventiv.multipaysdk.R
import com.inventiv.multipaysdk.base.BaseFragment
import com.inventiv.multipaysdk.data.model.EventObserver
import com.inventiv.multipaysdk.data.model.Resource
import com.inventiv.multipaysdk.data.model.request.RegisterRequest
import com.inventiv.multipaysdk.data.model.type.OtpDirectionFrom
import com.inventiv.multipaysdk.databinding.FragmentOtpMultipaySdkBinding
import com.inventiv.multipaysdk.repository.AuthenticationRepository
import com.inventiv.multipaysdk.repository.OtpRepository
import com.inventiv.multipaysdk.ui.wallet.WalletActivity
import com.inventiv.multipaysdk.util.*
import com.inventiv.multipaysdk.view.listener.SimpleTextWatcher
import java.util.concurrent.TimeUnit
internal class OtpFragment : BaseFragment<FragmentOtpMultipaySdkBinding>() {
private var emailOrGsm: String? = null
private var registerRequest: RegisterRequest? = null
private var otpNavigationArgs: OtpNavigationArgs? = null
private var otpDirectionFrom: OtpDirectionFrom? = null
private lateinit var countDownTimer: CountDownTimer
private val apiService = MultiPaySdk.getComponent().apiService()
private lateinit var viewModel: OtpViewModel
companion object {
fun newInstance(
emailOrGsm: String,
otpNavigationArgs: OtpNavigationArgs,
registerRequest: RegisterRequest? = null,
otpDirectionFrom: OtpDirectionFrom
): OtpFragment =
OtpFragment().apply {
val args = Bundle().apply {
putString(ARG_EMAIL_OR_GSM, emailOrGsm)
putParcelable(ARG_OTP_NAVIGATION, otpNavigationArgs)
putParcelable(ARG_OTP_DIRECTION_FROM, otpDirectionFrom)
putParcelable(ARG_OTP_REGISTER_MODEL, registerRequest)
}
arguments = args
}
}
private var simpleTextWatcher: TextWatcher = object : SimpleTextWatcher {
override fun afterTextChanged(s: Editable?) {
val otpCode = s.toString()
val otpLength = otpCode.length
if (otpLength == resources.getInteger(R.integer.otp_length_multipay_sdk)) {
viewModel.confirmOtp(otpNavigationArgs?.verificationCode, otpCode)
}
}
}
override fun onResume() {
super.onResume()
showToolbar()
toolbarBack()
title(R.string.otp_navigation_title_multipay_sdk)
}
override fun createBinding(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): FragmentOtpMultipaySdkBinding =
FragmentOtpMultipaySdkBinding.inflate(inflater, container, false)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val viewModelFactory = OtpViewModelFactory(
OtpRepository(apiService),
AuthenticationRepository(apiService)
)
viewModel =
ViewModelProvider(this@OtpFragment, viewModelFactory).get(OtpViewModel::class.java)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
subscribeConfirmOtp()
subscribeResendOtp()
subscribeResendOtpFromRegister()
emailOrGsm = arguments?.getString(ARG_EMAIL_OR_GSM)
otpNavigationArgs = arguments?.getParcelable(ARG_OTP_NAVIGATION)
otpDirectionFrom = arguments?.getParcelable(ARG_OTP_DIRECTION_FROM)
registerRequest = arguments?.getParcelable(ARG_OTP_REGISTER_MODEL)
requireBinding().viewPinMultipaySdk.addTextChangedListener(simpleTextWatcher)
toolbar().setNavigationOnClickListener {
requireActivity().onBackPressed()
}
val textOtpDescription = getString(
R.string.otp_description_multipay_sdk,
Formatter.formatPhoneNumber(otpNavigationArgs?.gsmNumber, true)
)
requireBinding().textTitleMultipaySdk.text =
HtmlCompat.fromHtml(textOtpDescription, HtmlCompat.FROM_HTML_MODE_LEGACY)
requireBinding().viewPinMultipaySdk.showKeyboard()
setupAndStartCountDownTimer()
requireBinding().buttonResendMultipaySdk.setOnClickListener {
when (otpDirectionFrom) {
OtpDirectionFrom.LOGIN -> {
viewModel.login(emailOrGsm!!)
}
OtpDirectionFrom.REGISTER -> {
viewModel.register(registerRequest!!)
}
}
requireBinding().viewPinMultipaySdk.setText("")
requireBinding().buttonResendMultipaySdk.visibility = View.GONE
}
}
private fun setupAndStartCountDownTimer() {
val seconds = otpNavigationArgs?.remainingTime?.toLong() ?: 100L
if (::countDownTimer.isInitialized) {
countDownTimer.cancel()
}
countDownTimer = object : CountDownTimer(TimeUnit.SECONDS.toMillis(seconds), 1000) {
override fun onTick(millisUntilFinished: Long) {
val formattedTimerText =
String.format(
getString(R.string.otp_remaining_time_multipay_sdk),
(millisUntilFinished / 1000)
)
requireBinding().textRemainingTimeMultipaySdk.text = formattedTimerText
}
override fun onFinish() {
requireBinding().buttonResendMultipaySdk.visibility = View.VISIBLE
}
}
countDownTimer.start()
}
private fun subscribeConfirmOtp() {
viewModel.confirmOtpResult.observe(viewLifecycleOwner, EventObserver { resource ->
when (resource) {
is Resource.Loading -> {
setLayoutProgressVisibility(View.VISIBLE)
}
is Resource.Success -> {
when (otpDirectionFrom) {
OtpDirectionFrom.LOGIN -> {
startActivity(
WalletActivity.newIntent(requireActivity(), false)
)
requireActivity().finish()
}
OtpDirectionFrom.REGISTER -> {
startActivity(
WalletActivity.newIntent(requireActivity(), true)
)
requireActivity().finish()
}
}
setLayoutProgressVisibility(View.GONE)
}
is Resource.Failure -> {
showSnackBarAlert(resource.error.message)
setLayoutProgressVisibility(View.GONE)
if (resource.error.statusCode == SERVICE_GET_OTP_AGAIN) {
countDownTimer.cancel()
requireBinding().viewPinMultipaySdk.hideKeyboard()
requireBinding().buttonResendMultipaySdk.visibility = View.VISIBLE
}
}
}
})
}
private fun subscribeResendOtp() {
viewModel.loginResult.observe(viewLifecycleOwner, EventObserver { resource ->
when (resource) {
is Resource.Loading -> {
setLayoutProgressVisibility(View.VISIBLE)
}
is Resource.Success -> {
val loginResponse = resource.data
otpNavigationArgs =
OtpNavigationArgs(
loginResponse?.verificationCode,
loginResponse?.gsm,
loginResponse?.remainingTime
)
setupAndStartCountDownTimer()
setLayoutProgressVisibility(View.GONE)
}
is Resource.Failure -> {
showSnackBarAlert(resource.error.message)
setLayoutProgressVisibility(View.GONE)
}
}
})
}
private fun subscribeResendOtpFromRegister() {
viewModel.registerResult.observe(viewLifecycleOwner, EventObserver { resource ->
when (resource) {
is Resource.Loading -> {
setLayoutProgressVisibility(View.VISIBLE)
}
is Resource.Success -> {
val registerResponse = resource.data
otpNavigationArgs =
OtpNavigationArgs(
verificationCode = registerResponse?.verificationCode,
gsmNumber = registerResponse?.gsm,
remainingTime = registerResponse?.remainingTime
)
setupAndStartCountDownTimer()
setLayoutProgressVisibility(View.GONE)
}
is Resource.Failure -> {
showSnackBarAlert(resource.error.message)
setLayoutProgressVisibility(View.GONE)
}
}
})
}
private fun setLayoutProgressVisibility(visibility: Int) {
requireBinding().otpProgressMultipaySdk.layoutProgressMultipaySdk.visibility = visibility
}
override fun onDestroyView() {
requireBinding().viewPinMultipaySdk.removeTextChangedListener(simpleTextWatcher)
countDownTimer.cancel()
super.onDestroyView()
}
} | 0 | Kotlin | 0 | 0 | a13e2f5faa0fcb9cc8479d83b8cdfcbbb3bb2462 | 10,091 | MultiPay-Android-Sdk | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.