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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
domain/src/main/java/com/centaury/domain/movies/interactor/GetAllSearchMovies.kt
|
Centauryal
| 213,598,833
| false
| null |
package com.centaury.domain.movies.interactor
import com.centaury.domain.UseCase
import com.centaury.domain.model.Search
import com.centaury.domain.movies.MoviesRepository
import io.reactivex.Observable
import javax.inject.Inject
/**
* @Author Centaury (<EMAIL>)
* Created by Centaury on 2/17/21.
*/
class GetAllSearchMovies @Inject constructor(
private val moviesRepository: MoviesRepository
) : UseCase<List<Search>, GetAllSearchMovies.Params>() {
override fun buildUseCase(params: Params): Observable<List<Search>> =
moviesRepository.getSearchMoviesAll(params.query)
data class Params(val query: String)
}
| 0
|
Kotlin
|
0
| 0
|
1dbd08100eb19fc004b6af06fe0d7a3d6b500c46
| 636
|
CatalogueMovie-Jetpack
|
Apache License 2.0
|
compiler/testData/klib/syntheticAccessors/privateMember/crossFilePrivateLeak/leakingPrivateMethodThroughReference.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// IGNORE_BACKEND: ANY
// ^^^ Muted because accessor for function/constructor/property references are not generated. To be fixed in KT-69797.
// FILE: A.kt
class A {
private fun privateMethod() = "OK"
public inline fun publicInlineFunction() = ::privateMethod
}
// FILE: main.kt
fun box(): String {
return A().publicInlineFunction().invoke()
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 359
|
kotlin
|
Apache License 2.0
|
cinescout/utils/kotlin/src/commonMain/kotlin/cinescout/utils/kotlin/EitherUtils.kt
|
fardavide
| 280,630,732
| false
| null |
package cinescout.utils.kotlin
import arrow.core.Either
import arrow.core.flatMap
import arrow.core.left
import arrow.core.recover
import arrow.core.right
import cinescout.error.NetworkError
import cinescout.model.NetworkOperation
fun <A, B> Either<A, B>.mapToUnit(): Either<A, Unit> = map { }
operator fun <A, B> Either<A, List<B>>.plus(other: Either<A, List<B>>): Either<A, List<B>> =
this.flatMap { list1 ->
other.map { list2 ->
list1 + list2
}
}
fun <A, B> sum(first: Either<A, List<B>>, second: Either<A, List<B>>): Either<A, List<B>> = first + second
fun <B> Either<NetworkOperation, List<B>>.handleSkippedAsEmpty(): Either<NetworkError, List<B>> =
recover { networkOperation ->
when (networkOperation) {
is NetworkOperation.Skipped -> emptyList<B>().right()
is NetworkOperation.Error -> networkOperation.error.left()
}.bind()
}
| 10
|
Kotlin
|
2
| 6
|
7a875cd67a3df0ab98af520485122652bd5de560
| 924
|
CineScout
|
Apache License 2.0
|
demoapp/composeApp/src/iosMain/kotlin/at/asitplus/cryptotest/App.ios.kt
|
a-sit-plus
| 700,518,667
| false
|
{"Kotlin": 1106936, "Swift": 554}
|
package at.asitplus.cryptotest
import at.asitplus.signum.supreme.os.PlatformSigningProvider
import at.asitplus.signum.supreme.os.SigningProvider
actual val Provider: SigningProvider = PlatformSigningProvider
| 17
|
Kotlin
|
2
| 41
|
d40a11909be205a55e424699323cb0044433bf81
| 210
|
signum
|
Apache License 2.0
|
appsferry-adapter/src/main/java/com/appsferry/adapter/AdapterSDK.kt
|
AppInf
| 678,269,313
| false
| null |
package com.appsferry.adapter
import com.appsferry.core.CoreComponent
import com.appsferry.core.CoreParams
import com.appsferry.core.parameters.Parameters
import com.appsferry.core.parameters.appid
import com.appsferry.core.parameters.cv
import com.appsferry.core.parameters.smid
object AdapterSDK {
@JvmStatic
fun initSdk(params: AhParams) {
params.appid?.let {
Parameters.getInstance().appid = it
}
params.cv?.let {
Parameters.getInstance().cv = it
}
params.smid?.let {
Parameters.getInstance().smid = it
}
// core
CoreComponent.setParams(
CoreParams().withHttpParams(
params.bizUrlHost,
params.uploadUrlHost,
params.analyticsUrlHost
)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
d9bdccb5789a774f01682160b1e3a237bc15c3d7
| 837
|
appsferry-adapter-android
|
Apache License 2.0
|
storage/src/main/java/br/pedroso/tweetsentiment/storage/di/cache/CacheModule.kt
|
felipepedroso
| 124,307,018
| true
| null |
package br.pedroso.tweetsentiment.storage.di.cache
import br.pedroso.tweetsentiment.domain.di.DependenciesTags.NETWORK_CACHE_DIR
import org.koin.android.ext.koin.androidContext
import org.koin.core.qualifier.named
import org.koin.dsl.module
val cacheModule = module {
single(named(NETWORK_CACHE_DIR)) {
androidContext().cacheDir
}
}
| 0
|
Kotlin
|
1
| 10
|
32b675c791302861bfad8049ab1c4650b554b689
| 351
|
tweet-sentiment
|
MIT License
|
app/src/main/java/com/fintech15/loanadvisor/utils/Utils.kt
|
Fintech-Team-15
| 564,190,962
| false
| null |
package com.fintech15.loanadvisor.utils
import com.google.android.material.textfield.TextInputLayout
fun validatePassword(passwordTextInputLayout: TextInputLayout) {
val password = passwordTextInputLayout.editText?.text.toString()
if (Validator.isEmptyString(password)) passwordTextInputLayout.error =
"Password cannot be empty" else passwordTextInputLayout.error = ""
if (!Validator.isValidPassword(password)) passwordTextInputLayout.error =
"Password should be greater than 6 characters" else passwordTextInputLayout.error = ""
}
fun validateEmail(emailTextInputLayout: TextInputLayout) {
val email = emailTextInputLayout.editText?.text.toString()
if (Validator.isEmptyString(email)) emailTextInputLayout.error =
"Email cannot be empty" else emailTextInputLayout.error = ""
if (!Validator.isEmailAddress(email)) emailTextInputLayout.error =
"Please enter a valid email address" else emailTextInputLayout.error = ""
}
| 11
|
Kotlin
|
1
| 0
|
f749a48c2e4bd3fb8d7f277ab2a44000d5ec73be
| 983
|
Loan-Advisor-App
|
MIT License
|
next/kmp/browser/src/commonMain/kotlin/org/dweb_browser/browser/util/StringUtil.kt
|
BioforestChain
| 594,577,896
| false
|
{"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818}
|
package org.dweb_browser.browser.util
/**
* 判断字符串是否是 dweb link
*/
fun String.regexDeepLink() = Regex("dweb:.+").matchEntire(this.trim())?.groupValues?.firstOrNull()
| 66
|
Kotlin
|
5
| 20
|
6db1137257e38400c87279f4ccf46511752cd45a
| 168
|
dweb_browser
|
MIT License
|
app/src/main/java/utn/frba/mobile/konzern/contact/ui/ContactFragment.kt
|
UTN-FRBA-Mobile
| 261,071,131
| false
| null |
package utn.frba.mobile.konzern.contact.ui
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.contact_fragment_layout.*
import utn.frba.mobile.konzern.R
import utn.frba.mobile.konzern.contact.model.Contact
import utn.frba.mobile.konzern.contact.repository.ContactRepository
import java.lang.RuntimeException
class ContactFragment : Fragment() {
private lateinit var contactView : ContactView
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is ContactView) {
contactView = context
} else {
throw RuntimeException("$context must be ContactView")
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.contact_fragment_layout, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getContactDataFormRepository()
}
private fun getContactDataFormRepository() {
ContactRepository().getContactData(object : ContactRepository.ContactRepositoryInterface {
override fun onComplete(consorcioInfo: Contact?) {
setInfoFromDatabase(consorcioInfo)
}
override fun onFailure() {
contactView.errorGettinContactInfo()
}
})
}
private fun setInfoFromDatabase(consorcioInfo: Contact?) {
vContactProgressBar.visibility = View.GONE
consorcioInfo?.let {
vContactName.text = it.name
Glide.with(this).load(it.imageUrl).error(R.drawable.consorcio_placeholder).into(vContactImage)
vContactPhone.text = it.phone
vContactAttentionTime.text = it.attentionTime
vContactEmail.text = it.email
vContactAddress.text = it.address
vContactExtraInfo.text = it.extraInfo
}
}
companion object {
fun newInstance() = ContactFragment()
}
interface ContactView {
fun errorGettinContactInfo()
}
}
| 0
|
Kotlin
|
0
| 0
|
d8b1261be749d03a5ef8b0866054206e6f76e00f
| 2,339
|
Konzern
|
MIT License
|
app/src/main/java/io/nosyntax/foundation/core/utility/Coroutines.kt
|
nosyntax-io
| 683,553,348
| false
|
{"Kotlin": 199456}
|
package io.nosyntax.foundation.core.utility
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
fun <T> ComponentActivity.collectLatestOnLifecycleStarted(flow: Flow<T>, collect: suspend (T) -> Unit) {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
flow.collectLatest(collect)
}
}
}
| 3
|
Kotlin
|
0
| 0
|
a29b2eb06368848ebca9f10a107e314484092ce2
| 567
|
nosyntax-foundation-android
|
MIT License
|
order-service/domain/core/src/main/kotlin/com/food/ordering/system/order/service/domain/core/IOrderDomainService.kt
|
ani2fun
| 558,480,625
| false
|
{"Kotlin": 161253, "PLpgSQL": 4264, "Shell": 113}
|
package com.food.ordering.system.order.service.domain.core
import com.food.ordering.system.order.service.domain.core.entity.Order
import com.food.ordering.system.order.service.domain.core.entity.Restaurant
import com.food.ordering.system.order.service.domain.core.event.OrderCancelledEvent
import com.food.ordering.system.order.service.domain.core.event.OrderCreatedEvent
import com.food.ordering.system.order.service.domain.core.event.OrderPaidEvent
/**
* General explanation for domain service interfaces:
*
* The `IOrderDomainService` interface defines methods for managing orders within the domain.
* It handles various aspects of the order lifecycle, including validation, initiation, payment processing,
* approval, and cancellation.
*
* Key points:
* - The methods within this interface return domain events such as `OrderCreatedEvent`, `OrderPaidEvent`,
* and `OrderCancelledEvent`, which will be handled by the application service.
*
* - The approach here is to create and return domain events within the domain service, while the actual
* event firing process occurs in the application service.
*
* - This separation is crucial to ensure that the event firing happens after the successful persistence of
* underlying business operations into the database.
*
* - The domain service's primary responsibility is to encapsulate complex business logic, especially logic
* that doesn't fit neatly into any entity class or requires access to multiple aggregates.
*
* - By delegating repository calls to the application service, the domain core module remains dedicated to
* implementing and maintaining business logic, preventing it from being cluttered with event publishing
* or tracking concerns.
*
* In summary, the `IOrderDomainService` serves as an intermediary layer between the domain core, where business
* logic resides, and the application service, which manages event handling. This separation ensures that
* domain events are correctly created and handled in a structured manner, supporting a clean and organized
* Domain-Driven Design approach.
*/
interface IOrderDomainService {
/**
* This method validates and initiates an order by calling the necessary business methods from the provided
* order and restaurant entities. It takes the order and restaurant entities as parameters and returns an
* OrderCreatedEvent.
*/
fun validateAndInitiateOrder(order: Order, restaurant: Restaurant): OrderCreatedEvent
fun payOrder(order: Order): OrderPaidEvent
fun approveOrder(order: Order)
fun cancelOrderPayment(order: Order, failureMessages: List<String>): OrderCancelledEvent
fun cancelOrder(order: Order, failureMessages: List<String>)
}
| 0
|
Kotlin
|
0
| 0
|
66422bb8028aa8aae767de9fc2fdcdc31e2613d7
| 2,740
|
food-ordering-system
|
Apache License 2.0
|
bones/src/main/java/pro/horovodovodo4ka/bones/BoneSibling.kt
|
sobolbobol
| 165,265,973
| true
|
{"Kotlin": 72849, "Java": 1145}
|
package pro.horovodovodo4ka.bones
import androidx.annotation.CallSuper
/**
* Base interface representing bone sibling.
*/
interface BoneSibling<T : Bone> {
/**
* Bone, that holds that sibling
*/
var bone: T
/**
* Called by bone on different state changes that requires updating of UI
*/
@CallSuper
fun refreshUI() {
bone.sibling?.onRefresh()
}
/**
* Called after [BoneSibling.refreshUI] called.
*
* Default implementation notifies parent bone sibling about UI changes on current level of hierarchy.
*/
@CallSuper
fun onRefresh() {
bone.parentBone?.sibling?.onRefresh()
}
/**
* Should not be used directly. Used by internal API, links bone with it's sibling.
*/
fun <V : Bone> link(bone: V) {
@Suppress("UNCHECKED_CAST")
(bone as? T)?.also { this.bone = it }
}
/**
* Called each time bone calls [Bone.notifyChange] method. Can be used to refresh sibling's content to new bone state.
*/
fun onBoneChanged() {}
}
| 0
|
Kotlin
|
0
| 0
|
c45506e59950176360cf93b008b2d4c72e6df6ce
| 1,070
|
bones
|
The Unlicense
|
app/src/main/java/com/github/ojh102/timary/util/extension/PrimitiveExtensions.kt
|
ojh102
| 131,490,034
| false
| null |
package com.github.ojh102.timary.util.extension
import android.content.res.Resources
val Int.toPx: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.toDp: Int
get() = (this / Resources.getSystem().displayMetrics.density).toInt()
| 0
|
Kotlin
|
3
| 17
|
fd625388b87a80a717ab817d8345fe0d655863c8
| 272
|
Timary
|
Apache License 2.0
|
src/commonMain/kotlin/matt/json/oldfx/common/common.kt
|
mgroth0
| 365,610,033
| false
|
{"Kotlin": 43166}
|
package matt.json.oldfx.common
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import matt.json.oldfx.toJsonElement
import matt.json.ser.MyJsonSerializer
import matt.json.toJsonString
import matt.json.toPrettyJsonString
fun jsonArray(
vararg elements: Any?,
serializeNulls: Boolean = false
): JsonArray =
buildJsonArray {
addAll(elements.filter { serializeNulls || it != null }.map { it?.toJsonElement() ?: JsonNull })
}
fun jsonArray(
elements: Iterable<Any?>,
serializeNulls: Boolean = false
) =
jsonArray(*elements.toList().toTypedArray(), serializeNulls = serializeNulls)
fun jsonObj(
map: Map<*, *>,
serializers: List<MyJsonSerializer<*>> = listOf()
): JsonObject = jsonObj(*map.map { it.key to it.value }.toTypedArray(), serializers = serializers)
fun jsonObj(
vararg entries: Pair<*, *>,
serializeNulls: Boolean = false,
serializeEmptyLists: Boolean = true,
serializers: List<MyJsonSerializer<*>> = listOf()
): JsonObject =
buildJsonObject {
entries.filter { serializeNulls || it.second != null }.forEach {
val key = it.first
val value = it.second
key as String
val j = value?.toJsonElement(serializers = serializers) ?: JsonNull
if ((serializeNulls || j !is JsonNull) && (serializeEmptyLists || j !is JsonArray || j.isNotEmpty())) put(
key, j
)
}
}
fun jsonObjString(
vararg entries: Pair<*, *>
) = jsonObj(*entries).toJsonString()
fun prettyJsonObjString(
vararg entries: Pair<*, *>
) = jsonObj(*entries).toPrettyJsonString()
| 0
|
Kotlin
|
0
| 0
|
9ef854b00dc87ca3fbce8aed7b711fa3deb6d329
| 1,805
|
json
|
MIT License
|
app/src/main/java/com/hakmar/employeelivetracking/features/store_detail_tasks/data/remote/dto/CheckListItemDto.kt
|
enginemre
| 584,733,724
| false
| null |
package com.hakmar.employeelivetracking.features.store_detail_tasks.data.remote.dto
import com.google.gson.annotations.SerializedName
data class CheckListItemDto(
@SerializedName("id")
val id: Int,
@SerializedName("task_type")
val taskType: String,
@SerializedName("text")
val text: String
)
| 0
|
Kotlin
|
0
| 0
|
5e348e0a5aac89b4e60607a14a4ef9bbd68545a5
| 318
|
employee_live_tracking
|
The Unlicense
|
pyrexia-android/app/src/main/java/com/cryptomcgrath/pyrexia/thermostat/ThermostatReducer.kt
|
cryptomcgrath
| 541,272,434
| false
| null |
package com.cryptomcgrath.pyrexia.thermostat
import com.edwardmcgrath.blueflux.core.ReducerFun
internal val thermostatReducerFun: ReducerFun<ThermostatState> = { inState, event ->
val state = inState ?: ThermostatState()
when(event) {
is ThermostatEvent.NewStatList -> {
state.copy(
statList = event.statList,
connectionError = null,
isLoading = false,
isUpdating = false
)
}
is ThermostatEvent.ConnectionError -> {
state.copy(
connectionError = event.throwable,
isLoading = false,
isUpdating = false
)
}
is ThermostatEvent.Init -> {
state.copy(
selectedStatId = event.id
)
}
is ThermostatEvent.SetLoading -> {
state.copy(
isLoading = event.isLoading
)
}
is ThermostatEvent.NewHistory -> {
val newHistory = state.history.toMutableMap()
event.historyList.forEach {
newHistory[it.id] = it
}
state.copy(
history = newHistory,
historyOffset = event.offset
)
}
is ThermostatEvent.SetUpdating -> {
state.copy(
isUpdating = event.updating
)
}
else -> state
}
}
| 2
|
Kotlin
|
0
| 3
|
d4185cf36a4e4b37f504fa4fcb1ea3b15b5e2f1c
| 1,466
|
pyrexia-android
|
MIT License
|
src/main/kotlin/sapala/s2sauthservice/S2sAuthServiceApplication.kt
|
MateuszSapala
| 755,249,872
| false
|
{"Kotlin": 17223}
|
package sapala.s2sauthservice
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.boot.runApplication
import org.springframework.context.event.EventListener
import sapala.s2sauthservice.config.Env
import sapala.s2sauthservice.services.TokenService
import sapala.s2sauthservice.services.TokenSynchronizationService
@SpringBootApplication
class S2sAuthServiceApplication(private val env: Env, private val tokenSynchronizationService: TokenSynchronizationService) {
companion object {
val log: Logger = LoggerFactory.getLogger(S2sAuthServiceApplication::class.java)
}
@EventListener(ApplicationReadyEvent::class)
fun afterStartup() {
tokenSynchronizationService.requestKeySynchronizationOnOtherInstances()
log.info("Swagger UI available at: https://localhost:{}/swagger-ui/index.html", env.port())
}
}
fun main(args: Array<String>) {
runApplication<S2sAuthServiceApplication>(*args)
}
| 0
|
Kotlin
|
0
| 0
|
1a419f9ea24a8dcb36c0e73a80ca83ead547486c
| 1,101
|
s2s-auth-service
|
Apache License 2.0
|
collection-utils-sample/src/main/java/com/guardanis/collections/sample/glide/SampleGlideModule.kt
|
mattsilber
| 48,820,964
| false
|
{"Java": 93592, "Kotlin": 40943}
|
package com.guardanis.collections.sample.glide
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
@GlideModule
class SampleGlideModule: AppGlideModule()
| 5
|
Java
|
1
| 0
|
50853d4ed712d7b406cf51eb632e08834e8975dc
| 200
|
collection-utils
|
Apache License 2.0
|
src/test/kotlin/com/epam/brn/controller/ExerciseControllerTest.kt
|
Brain-up
| 216,092,521
| false
|
{"Kotlin": 1057984, "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.service.RoleService
import com.epam.brn.dto.ExerciseDto
import com.epam.brn.dto.NoiseDto
import com.epam.brn.dto.request.exercise.ExercisePhrasesCreateDto
import com.epam.brn.dto.request.exercise.ExerciseSentencesCreateDto
import com.epam.brn.dto.request.exercise.ExerciseWordsCreateDto
import com.epam.brn.dto.request.exercise.Phrases
import com.epam.brn.dto.request.exercise.SetOfWords
import com.epam.brn.dto.response.ExerciseWithWordsResponse
import com.epam.brn.enums.BrnLocale
import com.epam.brn.service.ExerciseService
import com.epam.brn.upload.CsvUploadService
import io.kotest.matchers.shouldBe
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import io.mockk.just
import io.mockk.mockk
import io.mockk.verify
import org.apache.http.HttpStatus
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.web.multipart.MultipartFile
@ExtendWith(MockKExtension::class)
internal class ExerciseControllerTest {
@InjectMockKs
lateinit var exerciseController: ExerciseController
@MockK
lateinit var exerciseService: ExerciseService
@MockK
lateinit var csvUploadService: CsvUploadService
@MockK
lateinit var roleService: RoleService
@Test
fun `should get exercises for user and series`() {
// GIVEN
val subGroupId: Long = 2
val exercise = ExerciseDto(subGroupId, 1, "name", 1, NoiseDto(0, ""))
val listExercises = listOf(exercise)
every { exerciseService.findExercisesBySubGroupForCurrentUser(subGroupId) } returns listExercises
every { roleService.isCurrentUserAdmin() } returns false
// WHEN
@Suppress("UNCHECKED_CAST")
val actualResultData: List<ExerciseDto> =
exerciseController.getExercisesBySubGroup(subGroupId).body?.data as List<ExerciseDto>
// THEN
verify(exactly = 1) { exerciseService.findExercisesBySubGroupForCurrentUser(subGroupId) }
assertTrue(actualResultData.contains(exercise))
}
@Test
fun `should get exercise by id`() {
// GIVEN
val exerciseID: Long = 1
val exercise = ExerciseDto(2, 1, "exe", 1, NoiseDto(0, ""))
every { exerciseService.findExerciseById(exerciseID) } returns exercise
// WHEN
@Suppress("UNCHECKED_CAST")
val actualResultData: ExerciseDto = exerciseController.getExercisesByID(exerciseID).body?.data as ExerciseDto
// THEN
verify(exactly = 1) { exerciseService.findExerciseById(exerciseID) }
assertEquals(actualResultData, exercise)
}
@Test
fun `loadExercises should return http status 201`() {
// GIVEN
val seriesId = 1L
val file = mockk<MultipartFile>()
every { csvUploadService.loadExercises(seriesId, file) } just Runs
// WHEN
val loadExercises = exerciseController.loadExercises(seriesId, file)
// THEN
loadExercises.statusCodeValue shouldBe HttpStatus.SC_CREATED
}
@Test
fun `createExerciseWords should return http status 204`() {
// GIVEN
val exerciseWordsCreateDto = ExerciseWordsCreateDto(
locale = BrnLocale.RU,
subGroup = "subGroup",
level = 1,
exerciseName = "exerciseName",
words = listOf("word1", "word2"),
noiseLevel = 0
)
val exerciseDto = mockk<ExerciseDto>()
every { exerciseService.createExercise(exerciseWordsCreateDto) } returns exerciseDto
// WHEN
val createdExercise = exerciseController.createExercise(exerciseWordsCreateDto)
// THEN
verify(exactly = 1) { exerciseService.createExercise(exerciseWordsCreateDto) }
createdExercise.statusCodeValue shouldBe HttpStatus.SC_CREATED
}
@Test
fun `createExercisePhrases should return http status 204`() {
// GIVEN
val exercisePhrasesCreateDto = ExercisePhrasesCreateDto(
locale = BrnLocale.RU,
subGroup = "subGroup",
level = 1,
exerciseName = "exerciseName",
phrases = Phrases(shortPhrase = "shortPhrase", longPhrase = "longPhrase"),
noiseLevel = 0
)
val exerciseDto = mockk<ExerciseDto>()
every { exerciseService.createExercise(exercisePhrasesCreateDto) } returns exerciseDto
// WHEN
val createdExercise = exerciseController.createExercise(exercisePhrasesCreateDto)
// THEN
verify(exactly = 1) { exerciseService.createExercise(exercisePhrasesCreateDto) }
createdExercise.statusCodeValue shouldBe HttpStatus.SC_CREATED
}
@Test
fun `createExerciseSentences should return http status 204`() {
// GIVEN
val exerciseSentencesCreateDto = ExerciseSentencesCreateDto(
locale = BrnLocale.RU,
subGroup = "subGroup",
level = 1,
exerciseName = "exerciseName",
orderNumber = 1,
words = SetOfWords()
)
val exerciseDto = mockk<ExerciseDto>()
every { exerciseService.createExercise(exerciseSentencesCreateDto) } returns exerciseDto
// WHEN
val createdExercise = exerciseController.createExercise(exerciseSentencesCreateDto)
// THEN
verify(exactly = 1) { exerciseService.createExercise(exerciseSentencesCreateDto) }
createdExercise.statusCodeValue shouldBe HttpStatus.SC_CREATED
}
@Test
fun `getExercisesBySubGroup should return data with http status 200`() {
// GIVEN
val subGroupId = 1L
val exerciseResponse = mockk<ExerciseDto>()
every { exerciseService.findExercisesWithTasksBySubGroup(subGroupId) } returns listOf(exerciseResponse)
every { roleService.isCurrentUserAdmin() } returns true
// WHEN
val exercises = exerciseController.getExercisesBySubGroup(subGroupId)
// THEN
verify(exactly = 1) { exerciseService.findExercisesWithTasksBySubGroup(subGroupId) }
exercises.statusCodeValue shouldBe HttpStatus.SC_OK
exercises.body!!.data shouldBe listOf(exerciseResponse)
}
@Test
fun`getExercisesByWord should return data with http status 200`() {
// GIVEN
val word = "word"
val exerciseResponse = mockk<ExerciseWithWordsResponse>()
every { exerciseService.findExercisesByWord(word) } returns listOf(exerciseResponse)
// WHEN
val exercises = exerciseController.getExercisesByWord(word)
// THEN
verify(exactly = 1) { exerciseService.findExercisesByWord(word) }
exercises.statusCodeValue shouldBe HttpStatus.SC_OK
exercises.body!!.data shouldBe listOf(exerciseResponse)
}
}
| 114
|
Kotlin
|
26
| 61
|
1cf4d44cd6e342e0f37cd45bfb092d74ba211af6
| 7,020
|
brn
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/com/autolua/autolua2/activity/ui/my/MyFragment.kt
|
lizhizhuanshu
| 817,824,738
| false
|
{"Kotlin": 186351, "C++": 166018, "Lua": 59924, "Java": 54951, "C": 4551, "CMake": 4544, "AIDL": 697}
|
package com.autolua.autolua2.activity.ui.my
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.autolua.autolua2.databinding.FragmentMyBinding
import com.autolua.autolua2.engine.AutoLuaEngineService
import com.autolua.autolua2.engine.AutoLuaEngineServiceImp
class MyFragment:Fragment() {
private var _binding: FragmentMyBinding? = null
private val binding get() = _binding!!
private var engineService:AutoLuaEngineService? = null
private val engineObserver = {state:AutoLuaEngineService.State ->
Log.d("MyFragment","engine state state:$state")
changeViewWithState(state)
}
private fun changeViewWithState(state:AutoLuaEngineService.State){
when(state){
AutoLuaEngineService.State.IDLE -> {
binding.engineSwitch.isChecked = false
binding.engineSwitch.isEnabled = true
}
AutoLuaEngineService.State.STARTING -> {
binding.engineSwitch.isChecked = true
binding.engineSwitch.isEnabled = false
}
AutoLuaEngineService.State.RUNNING ->{
binding.engineSwitch.isChecked = true
binding.engineSwitch.isEnabled = true
}
AutoLuaEngineService.State.STOPPING -> {
binding.engineSwitch.isChecked = false
binding.engineSwitch.isEnabled = false
}
}
}
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val engine = service as AutoLuaEngineService
engineService = engine
engine.addObserver(0,engineObserver)
changeViewWithState(engine.getState())
}
override fun onServiceDisconnected(name: ComponentName?) {
engineService = null
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Intent(requireContext(),AutoLuaEngineServiceImp::class.java).also { intent ->
requireContext().bindService(intent,serviceConnection,0)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMyBinding.inflate(inflater, container, false)
val root: View = binding.root
changeViewWithState(engineService?.getState()?:AutoLuaEngineService.State.IDLE)
binding.engineSwitch.setOnClickListener {
if(binding.engineSwitch.isChecked){
engineService?.start()
}else{
engineService?.stop()
}
// changeViewWithState(engineService?.getState()?:AutoLuaEngineService.State.IDLE)
}
return root
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
changeViewWithState(engineService?.getState()?:AutoLuaEngineService.State.IDLE)
}
}
| 0
|
Kotlin
|
0
| 1
|
4a989db6a88c8142d73b673771d60c0c401b7aca
| 3,101
|
autolua2
|
MIT License
|
app/src/main/java/com/kotlincoders/nftexplorer/home/data/remote/dto/nfts/Meta.kt
|
Kotlin-Coders
| 731,346,931
| false
|
{"Kotlin": 72714}
|
package com.kotlincoders.nftexplorer.home.data.remote.dto.nft_collection_assets
data class Meta(
val hasNextPage: Boolean,
val hasPreviousPage: Boolean,
val itemCount: Int,
val limit: Int,
val page: Int,
val pageCount: Int
)
| 0
|
Kotlin
|
0
| 0
|
dc4a729af2d91997670e890e2d34eb1d0a423f8d
| 249
|
NFT-Explorer
|
MIT License
|
serverless-simulator/opendc/opendc-compute/src/main/kotlin/com/atlarge/opendc/compute/virt/service/HypervisorView.kt
|
atlarge-research
| 297,702,102
| false
|
{"Jupyter Notebook": 11330813, "Kotlin": 547073, "Python": 15018, "R": 1048}
|
package com.atlarge.opendc.compute.virt.service
import com.atlarge.opendc.compute.core.Server
import com.atlarge.opendc.compute.virt.driver.VirtDriver
import java.util.UUID
class HypervisorView(
val uid: UUID,
var server: Server,
var numberOfActiveServers: Int,
var availableMemory: Long,
var provisionedCores: Int
) {
lateinit var driver: VirtDriver
}
| 0
|
Jupyter Notebook
|
1
| 2
|
11c772bcb3fc7a7c2590d6ed6ab979b78cb9fec9
| 379
|
opendc-serverless
|
MIT License
|
app/src/main/java/com/example/weatherchek/model/Clouds.kt
|
linero-tech
| 372,452,895
| false
| null |
package com.example.weatherchek.model
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Clouds(
@SerializedName("all")
val all: Int? = null
) : Parcelable
| 0
|
Kotlin
|
3
| 0
|
e2a7f0265774098ccb08f721fb0dba1a68e2c5d5
| 256
|
module-303---app-2-weather-app-team-2
|
MIT License
|
app/src/main/java/com/example/mvp/network/MealApi.kt
|
SawThanDar18
| 189,199,119
| false
| null |
package com.example.mvp.network
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface MealApi {
@GET("api/json/v1/1/latest.php")
fun getLatestMeals(): Call<LatestMealResponse>
@GET("api/json/v1/1/search.php/")
fun getSearchMeals(@Query("s") keyword : String) : Call<SearchMealsResponse>
@GET("api/json/v1/1/lookup.php/")
fun getDetailMeals(@Query("i") keyword: String) : Call<DetailMealsResponse>
}
| 0
|
Kotlin
|
0
| 0
|
fcf2be669cad38b9525f634b2dde402d1c360b76
| 459
|
MVP
|
Apache License 2.0
|
detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/DetektMessageCollectorSpec.kt
|
arturbosch
| 71,729,669
| false
| null |
package io.gitlab.arturbosch.detekt.core
import io.mockk.Called
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.spekframework.spek2.Spek
import org.spekframework.spek2.lifecycle.CachingMode
import org.spekframework.spek2.style.specification.describe
internal object DetektMessageCollectorSpec : Spek({
describe("DetektMessageCollector") {
val debugPrinter: (() -> String) -> Unit by memoized(CachingMode.TEST) {
mockk {
every { this@mockk.invoke(any()) } returns Unit
}
}
val warningPrinter: (String) -> Unit by memoized(CachingMode.TEST) {
mockk {
every { this@mockk.invoke(any()) } returns Unit
}
}
val subject by memoized(CachingMode.TEST) {
DetektMessageCollector(
minSeverity = CompilerMessageSeverity.INFO,
debugPrinter = debugPrinter,
warningPrinter = warningPrinter,
)
}
describe("message with min severity") {
beforeEachTest { subject.report(CompilerMessageSeverity.INFO, "message", null) }
it("prints the message") {
val slot = slot<() -> String>()
verify { debugPrinter.invoke(capture(slot)) }
assertThat(slot.captured()).isEqualTo("info: message")
}
it("adds up to the message count") {
subject.printIssuesCountIfAny()
verify {
warningPrinter(
"The BindingContext was created with 1 issues. " +
"Run detekt with --debug to see the error messages."
)
}
}
}
describe("message with higher severity than the min severity") {
beforeEachTest { subject.report(CompilerMessageSeverity.WARNING, "message", null) }
it("prints the message") {
val slot = slot<() -> String>()
verify { debugPrinter.invoke(capture(slot)) }
assertThat(slot.captured()).isEqualTo("warning: message")
}
it("adds up to the message count") {
subject.printIssuesCountIfAny()
verify {
warningPrinter(
"The BindingContext was created with 1 issues. " +
"Run detekt with --debug to see the error messages."
)
}
}
}
describe("message with lower severity than the min severity") {
beforeEachTest { subject.report(CompilerMessageSeverity.LOGGING, "message", null) }
it("ignores the message") {
verify { debugPrinter wasNot Called }
}
it("doesn't add up to the message count") {
subject.printIssuesCountIfAny()
verify { warningPrinter wasNot Called }
}
}
}
})
| 144
|
Kotlin
|
572
| 4,243
|
08eac68caa24ced140cc017d4de3b258a470232b
| 3,174
|
detekt
|
Apache License 2.0
|
android-sdk/src/main/kotlin/com.onemillionbot.sdk/presentation/chat/adapter/ChatViewHolderFactory.kt
|
1millionbot
| 359,427,689
| false
| null |
package com.onemillionbot.sdk.presentation.chat.adapter
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.onemillionbot.sdk.core.ViewHolderFactory
import com.onemillionbot.sdk.presentation.chat.ChatViewModel
class ChatViewHolderFactory(
private val fragment: Fragment,
private val chatViewModel: ChatViewModel
) : ViewHolderFactory<RecyclerView.ViewHolder> {
override fun invoke(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
ChatAdapter.TYPE_USER_TEXT -> MessageUserTextViewHolder.create(parent, chatViewModel)
ChatAdapter.TYPE_BOT_TEXT -> MessageBotTextViewHolder.create(parent, chatViewModel)
ChatAdapter.TYPE_BOT_WRITING -> MessageBotWritingViewHolder.create(parent)
ChatAdapter.TYPE_BOT_IMAGE -> MessageBotImageViewHolder.create(fragment, parent, chatViewModel)
ChatAdapter.TYPE_BOT_VIDEO -> MessageBotVideoViewHolder.create(chatViewModel, fragment, parent)
ChatAdapter.TYPE_BOT_CARD_IMAGE -> MessageBotCardImageViewHolder.create(chatViewModel, fragment, parent)
ChatAdapter.TYPE_BOT_CARD_TEXT -> MessageBotCardTextViewHolder.create(chatViewModel, parent)
else -> throw IllegalAccessException("Invalid view type: $viewType")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
456a54c0d0ab814bfebf7d307aad39f795805533
| 1,384
|
android-sdk
|
MIT License
|
src/PlusMinus.kt
|
cusufcan
| 825,345,714
| false
|
{"Kotlin": 51628}
|
/*
* Complete the 'plusMinus' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/
fun plusMinus(arr: Array<Int>): Unit {
// Write your code here
var positive = 0
var negative = 0
var zero = 0
val n = arr.size.toDouble()
for (i in arr) {
if (i > 0) positive++
else if (i < 0) negative++
else zero++
}
println(positive / n)
println(negative / n)
println(zero / n)
}
fun main(args: Array<String>) {
val n = readln().trim().toInt()
val arr = readln().trimEnd().split(" ").map { it.toInt() }.toTypedArray()
plusMinus(arr)
}
| 0
|
Kotlin
|
0
| 1
|
d27182e95d072595ce84d124aa30dea54c4b319a
| 627
|
hacker_rank_challenges
|
MIT License
|
plugins/settings-sync/tests/com/intellij/settingsSync/MockSettingsSyncIdeMediator.kt
|
jwren
| 31,697,927
| true
| null |
package com.intellij.settingsSync
import com.intellij.util.io.isFile
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Path
import kotlin.streams.toList
internal class MockSettingsSyncIdeMediator : SettingsSyncIdeMediator {
private val files = mutableMapOf<String, String>()
override fun applyToIde(snapshot: SettingsSnapshot) {
for (fileState in snapshot.fileStates) {
if (fileState is FileState.Modified) {
files[fileState.file] = String(fileState.content, Charset.defaultCharset())
}
else {
files.remove(fileState.file)
}
}
}
override fun activateStreamProvider() {
}
override fun removeStreamProvider() {
}
override fun collectFilesToExportFromSettings(appConfigPath: Path): () -> Collection<Path> {
return getAllFilesFromSettings(appConfigPath)
}
companion object {
fun getAllFilesFromSettings(appConfigPath: Path): () -> Collection<Path> {
return {
Files.walk(appConfigPath).filter { it.isFile() }.toList()
}
}
}
}
| 0
| null |
0
| 0
|
bf2402af3a3443a462b128488b32b5b0130b1534
| 1,060
|
intellij-community
|
Apache License 2.0
|
src/main/java/kr/pe/ecmaxp/thumbsf/signal/ControlStopSignal.kt
|
EcmaXp
| 126,013,640
| false
| null |
package kr.pe.ecmaxp.thumbsf.signal
class ControlStopSignal(value: Any? = null) : ControlSignal(value)
| 3
|
Python
|
7
| 42
|
ddc36c39f119db8d7509d326a7ec0a2e327ffb07
| 105
|
OpenPython
|
MIT License
|
src/jvmMain/kotlin/cn/netdiscovery/monica/ui/controlpanel/ai/experiment/NavigationHost.kt
|
fengzhizi715
| 791,824,947
| false
|
{"Kotlin": 693053}
|
package cn.netdiscovery.monica.ui.controlpanel.ai.experiment
import androidx.compose.runtime.Composable
/**
*
* @FileName:
* cn.netdiscovery.monica.ui.controlpanel.ai.experiment.NavigationHost
* @author: <NAME>
* @date: 2024/9/23 20:06
* @version: V1.0 <描述当前版本功能>
*/
class NavigationHost(
val navController: NavController,
val contents: @Composable NavigationGraphBuilder.() -> Unit
) {
@Composable
fun build() {
NavigationGraphBuilder().renderContents()
}
inner class NavigationGraphBuilder(
val navController: NavController = this@NavigationHost.navController
) {
@Composable
fun renderContents() {
this@NavigationHost.contents(this)
}
}
}
/**
* Composable to build the Navigation Host
*/
@Composable
fun NavigationHost.NavigationGraphBuilder.composable(
route: String,
content: @Composable () -> Unit
) {
if (navController.currentScreen.value == route) {
content()
}
}
| 0
|
Kotlin
|
7
| 77
|
a71763a11707c5639e6b34ccde92fbd874dee4cc
| 1,003
|
Monica
|
Apache License 2.0
|
Live_Web/src/test/kotlin/com/example/Live_Web/Controllers/UserControllerTest.kt
|
eddiezhao
| 637,263,925
| false
| null |
package com.example.Live_Web.Controllers
import com.example.Live_Web.Models.User
import com.example.Live_Web.Models.UserPost
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jsonMapper
import org.json.JSONObject
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.*
import kotlin.test.BeforeTest
import kotlin.test.Ignore
@SpringBootTest
@AutoConfigureMockMvc
internal class UserControllerTest @Autowired constructor(
val mockMvc: MockMvc,
val objectMapper: ObjectMapper
) {
val BASE_URL = "/api/user"
val USERNAME = "Mickey_Rat"
val PASSWORD = "<PASSWORD>"
var ID = "nvd36ii2eK35GERKKdYde7qutyVJE93s" // CHANGE THIS
@Test
fun `Should Crete user` () {
val userPost = UserPost(USERNAME, "Door2Darkness")
mockMvc.post(BASE_URL) {
contentType = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(userPost)
}
.andDo{ print() }
.andExpect {
status { isCreated() }
}
val json = mockMvc.get("$BASE_URL/username/${userPost.username}")
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$.username") {value(USERNAME)}
jsonPath("$.password") {value("<PASSWORD>")}
}
.andReturn ()
ID = JSONObject(json.getResponse().getContentAsString())["id"] as String
print(ID)
}
@Test
fun `Should Patch a User` () {
val userPost = UserPost(USERNAME, PASSWORD)
mockMvc.patch(BASE_URL) {
contentType = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(userPost)
}
.andDo{ print() }
.andExpect {
status { isOk() }
}
mockMvc.get("$BASE_URL/username/${userPost.username}")
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$.id") {value(ID)}
jsonPath("$.username") {value(USERNAME)}
jsonPath("$.password") {value(<PASSWORD>)}
}
}
@Test
fun `Should return user with ID` () {
val id = ID
mockMvc.get("$BASE_URL/id/$id")
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$.username") {value(USERNAME)}
jsonPath("$.password") {value(<PASSWORD>)}
}
}
@Test
fun `Should return user with Username` () {
val username = USERNAME
mockMvc.get("$BASE_URL/username/$username")
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$.id") {value(ID)}
jsonPath("$.password") {value(<PASSWORD>)}
}
}
@Test
fun `User ID doesn't exist and returns not found` () {
val id = "NoSuchID"
mockMvc.get("$BASE_URL/id/$id")
.andDo{ print() }
.andExpect {
status { isNotFound() }
}
}
@Test
fun `User username doesn't exist and returns not found` () {
val username = "NoSuchUsername"
mockMvc.get("$BASE_URL/username/$username")
.andDo{ print() }
.andExpect {
status { isNotFound() }
}
}
@Test
fun `Should Delete a User by username` () {
val username = USERNAME
mockMvc.delete("$BASE_URL/username/$username")
.andDo{ print() }
.andExpect {
status { isNoContent() }
}
mockMvc.get("$BASE_URL/username/${username}")
.andDo{ print() }
.andExpect {
status { isNotFound() }
}
}
@Test
fun `Should validate valid user` () {
val user = UserPost("TestUSer", "<PASSWORD>")
mockMvc.post("$BASE_URL/verify")
{
contentType = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(user)
}
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$.valid") {value(true)}
}
}
@Test
fun `Should validate invalid user (username)` () {
val user = UserPost("NotAnFBISpy", "<PASSWORD>")
mockMvc.get("$BASE_URL/verify")
{
contentType = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(user)
}
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$.valid") {value(false)}
}
}
@Test
fun `Should validate invalid user (password)` () {
val user = UserPost("TestUSer", "<PASSWORD>")
mockMvc.get("$BASE_URL/verify")
{
contentType = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(user)
}
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$.valid") {value(false)}
}
}
@Test
fun `Should get files of users` () {
mockMvc.get("$BASE_URL/getFiles/TestUSer")
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$[0].id") {value("rcMGpCGcADJ0CTaDtIh1pwDFRE3J4UEK")}
jsonPath("$[0].name") {value("file.pdf")}
}
}
@Test
fun `Should get shared files of users` () {
mockMvc.get("$BASE_URL/shared/Tw1YmkTVtrdCTAQxaZJAyni0mVQaBZf1")
.andDo{ print() }
.andExpect {
status { isOk() }
content { contentType(MediaType.APPLICATION_JSON) }
jsonPath("$[0].id") {value("rcMGpCGcADJ0CTaDtIh1pwDFRE3J4UEK")}
jsonPath("$[0].name") {value("file.pdf")}
}
}
@Test
@Ignore
fun `Should Delete a User by id` () {
val id = "UserID123"
mockMvc.delete("$BASE_URL/id/$id")
.andDo{ print() }
.andExpect {
status { isNoContent() }
}
mockMvc.get("$BASE_URL/id/${id}")
.andDo{ print() }
.andExpect {
status { isNotFound() }
}
}
@Test
@Ignore
fun `User ID doesn't exist and returns not found when deleting` () {
val id = "NoSuchID"
mockMvc.delete("$BASE_URL/id/$id")
.andDo{ print() }
.andExpect {
status { isNotFound() }
}
}
@Test
@Ignore
fun `User username doesn't exist and returns not found when deleting` () {
val username = "NoSuchUsername"
mockMvc.delete("$BASE_URL/username/$username")
.andDo{ print() }
.andExpect {
status { isNotFound() }
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9f7a7b38fd75084f1808e6b082b7bd1b136bb095
| 7,908
|
LivePDF-File-Share
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/ui/home/Home.kt
|
IvetteHernandez
| 347,413,806
| 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.home
import androidx.annotation.DrawableRes
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.FabPosition
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Spa
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.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.R
import com.example.androiddevchallenge.ui.theme.MyTheme
import com.example.androiddevchallenge.ui.theme.elevation
import com.example.androiddevchallenge.ui.theme.green
@Composable
fun Home(onTap: () -> Unit = {}) {
Scaffold(
bottomBar = {
Button(
onClick = onTap,
modifier = Modifier
.fillMaxWidth()
.height(64.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.surface
),
shape = MaterialTheme.shapes.large,
) {
Text(
"Positions",
style = MaterialTheme.typography.subtitle1,
color = MaterialTheme.colors.onSurface,
)
}
}
) {
Column(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
BottomNavigation(
elevation = 0.dp,
backgroundColor = Color.Transparent
) {
BottomNavigationItem(
icon = {},
label = {
Text(
"ACCOUNT",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.onBackground,
)
},
selected = true,
onClick = {}
)
BottomNavigationItem(
icon = {},
label = {
Text(
"WATCHLIST",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.onBackground,
)
},
selected = false,
onClick = {}
)
BottomNavigationItem(
icon = {},
label = {
Text(
"PROFILE",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.onBackground,
)
},
selected = false,
onClick = {}
)
}
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Balance",
style = MaterialTheme.typography.subtitle1,
color = MaterialTheme.colors.onBackground,
modifier = Modifier.paddingFromBaseline(top = 32.dp, bottom = 8.dp)
)
Text(
text = "$73,589.01",
style = MaterialTheme.typography.h1,
color = MaterialTheme.colors.onBackground,
modifier = Modifier.paddingFromBaseline(48.dp, 24.dp)
)
Text(
text = "+412.35 today",
style = MaterialTheme.typography.subtitle1,
color = green,
modifier = Modifier.paddingFromBaseline(16.dp, 32.dp)
)
Button(
onClick = {},
modifier = Modifier
.fillMaxWidth()
.height(48.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.primary
),
shape = MaterialTheme.shapes.large,
) {
Text(
"TRANSACT",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.onPrimary,
)
}
Spacer(modifier = Modifier.height(16.dp))
LazyRow(
content = {
item {
Spacer(modifier = Modifier.height(12.dp))
}
item {
OptionsButton {
Text(
"Week",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.primary,
)
}
}
item {
OptionsButton {
Text(
"ETFs",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.primary,
)
}
}
item {
OptionsButton {
Text(
"Stock",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.primary,
)
}
}
item {
OptionsButton {
Text(
"Funds",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.primary,
)
}
}
item {
OptionsButton {
Text(
"Other",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.primary,
)
}
}
}
)
Image(
painterResource(R.drawable.ic_home_illos),
contentDescription = null,
contentScale = ContentScale.FillWidth,
)
}
}
}
@Composable
fun OptionsButton(
content: @Composable () -> Unit
) {
OutlinedButton(
onClick = {},
modifier = Modifier
.height(40.dp)
.padding(start = 4.dp, end = 4.dp),
border = BorderStroke(
ButtonDefaults.OutlinedBorderSize,
color = MaterialTheme.colors.onBackground
),
colors = ButtonDefaults.outlinedButtonColors(
backgroundColor = Color.Transparent,
),
shape = MaterialTheme.shapes.large,
) {
content()
}
}
| 0
|
Kotlin
|
0
| 0
|
c7a4d7ddfbeeffd5df17c807dd06625ee19e7c1e
| 9,718
|
android-dev-challenge-compose-week-3-americas
|
Apache License 2.0
|
app/src/main/kotlin/ru/cherryperry/amiami/model/CurrencyRepository.kt
|
wargry
| 139,280,084
| true
|
{"Kotlin": 102696}
|
package ru.cherryperry.amiami.model
import ru.cherryperry.amiami.data.network.server.ExchangeRate
import ru.cherryperry.amiami.domain.currency.GetCurrentRatesUseCase
import rx.Observable
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class CurrencyRepository @Inject constructor(
private val getCurrentRatesUseCase: GetCurrentRatesUseCase
) {
fun exchangeRate(forceNetwork: Boolean): Observable<ExchangeRate> {
return getCurrentRatesUseCase.run(Any())
.toObservable()
}
}
| 0
|
Kotlin
|
0
| 0
|
ada84ecfc0a574380f49446048be4e550a7ed018
| 535
|
Amiami-android-app
|
Apache License 2.0
|
Strohm/android/strohm-native/src/test/java/dev/strohmnative/SubscriptionsTest.kt
|
StrohmNative
| 318,874,527
| false
| null |
package dev.strohmnative
import android.content.Context
import android.webkit.WebView
import com.google.gson.Gson
import kotlinx.collections.immutable.PersistentList
import org.junit.jupiter.api.Assertions.*
import org.mockito.ArgumentCaptor
import org.mockito.Mockito.*
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
val propsSpec: PropsSpec = mapOf(
"name" to arrayListOf("user", "name"),
"city" to arrayListOf("user", "address", "city")
)
val noop: HandlerFunction = {}
object SubscriptionsSpec: Spek({
describe("Subscriptions") {
lateinit var strohmNative: StrohmNative
lateinit var webViewMock: WebView
beforeEachTest {
val mockContext = mock(Context::class.java)
strohmNative = StrohmNative(mockContext)
webViewMock = mock(WebView::class.java)
strohmNative.webView = webViewMock
}
context("when subscribing before load finishes") {
var subscriptionComplete: Boolean = false
beforeEachTest {
subscriptionComplete = false
strohmNative.subscribe(propsSpec, noop) {
subscriptionComplete = true
}
}
it("remembers pending subscription details") {
assertEquals(1, strohmNative.subscriptions.pendingSubscriptions?.count())
}
it("is not yet complete") {
assertEquals(false, subscriptionComplete)
}
it("has nothing pending after load finishes") {
strohmNative.whenLoadingFinished()
assertEquals(null, strohmNative.subscriptions.pendingSubscriptions)
}
it("calls completion handler after load finishes") {
strohmNative.whenLoadingFinished()
assertEquals(true, subscriptionComplete)
}
}
context("when subscribing after load finishes") {
var subscriptionComplete: Boolean = false
beforeEachTest {
strohmNative.whenLoadingFinished()
subscriptionComplete = false
strohmNative.subscribe(propsSpec, noop) {
subscriptionComplete = true
}
}
it("is complete") {
assertEquals(true, subscriptionComplete)
}
it("has called subscribe on the web view") {
val jsCodeCaptor = ArgumentCaptor.forClass(String::class.java)
verify(webViewMock, times(1))
.evaluateJavascript(jsCodeCaptor.capture(), any())
val expected = """strohm_native\.flow\.subscribe_from_native\(".*", ?"(.*)"\)"""
assertLinesMatch(listOf(expected), listOf(jsCodeCaptor.value))
val matchResult = expected.toRegex().matchEntire(jsCodeCaptor.value)
val matchedSerializedPropsSpec = matchResult!!.groups[1]!!.value
val unescaped = matchedSerializedPropsSpec.replace("\\\"", "\"")
val parsed = Gson().fromJson(unescaped, HashMap::class.java)
assertEquals(propsSpec["name"], parsed["name"])
assertEquals(propsSpec["city"], parsed["city"])
}
}
context("when subscribed") {
var receivedProps: Props? = null
var subscriptionId: UUID? = null
val handlerFn: HandlerFunction = { receivedProps = it }
beforeEachTest {
receivedProps = null
subscriptionId = null
strohmNative.whenLoadingFinished()
subscriptionId = strohmNative.whenSubscriptionCompletes(propsSpec, handlerFn)
}
it("receives prop updates") {
val props = mapOf("name" to "foo")
strohmNative.whenIncoming(props, subscriptionId!!)
assertEquals(props, receivedProps)
}
it("does not receive props for someone else") {
var otherProps: Props? = null
val otherId = strohmNative.whenSubscriptionCompletes(propsSpec) { props ->
otherProps = props
}
strohmNative.whenIncoming(mapOf("name" to "foo"), otherId)
assertNull(receivedProps)
assertNotNull(otherProps)
}
it("does not receive props after unsubscribe") {
strohmNative.unsubscribe(subscriptionId!!)
strohmNative.whenIncoming(mapOf("name" to "foo"), subscriptionId!!)
assertNull(receivedProps)
}
it("calls unsubscribe on the web view when unsubscribing") {
reset(webViewMock)
strohmNative.unsubscribe(subscriptionId!!)
val jsCodeCaptor = ArgumentCaptor.forClass(String::class.java)
verify(webViewMock, times(1))
.evaluateJavascript(jsCodeCaptor.capture(), any())
val expected = """strohm_native\.flow\.unsubscribe_from_native\("(.*)"\)"""
assertLinesMatch(listOf(expected), listOf(jsCodeCaptor.value))
val matchResult = expected.toRegex().matchEntire(jsCodeCaptor.value)
val matchedSubscriptionId = matchResult!!.groups[1]!!.value
assertEquals(subscriptionId!!.toString(), matchedSubscriptionId)
}
}
}
})
/* Strohm class extension methods for testing */
fun StrohmNative.whenLoadingFinished() {
this.loadingFinished()
}
fun StrohmNative.whenSubscriptionCompletes(propsSpec: PropsSpec, handlerFn: HandlerFunction): UUID {
val future = CompletableFuture<UUID>()
this.subscribe(propsSpec, handlerFn) { uuid ->
future.complete(uuid)
}
return future.get(1, TimeUnit.SECONDS)
}
fun StrohmNative.whenIncoming(props: Props, subscriptionId: UUID) {
this.subscriptions.handlePropsUpdate(props, subscriptionId)
}
/* Subscriptions class extension methods for testing */
internal val Subscriptions.pendingSubscriptions: PersistentList<() -> Unit>?
get() {
val holder = BooleanArray(1)
val pending = _pendingSubscriptions.get(holder)
val isUsingPending = holder[0]
return if (isUsingPending) pending else null
}
| 0
|
HTML
|
0
| 0
|
7d0b02c225addc947c7f4993a60d4dc981c28f00
| 6,499
|
strohm-native
|
MIT License
|
swan-hooks/src/main/java/com/bomber/swan/hooks/pthread/PthreadHook.kt
|
YoungTr
| 469,053,611
| false
|
{"C++": 866022, "Kotlin": 767975, "Java": 322150, "C": 302325, "CMake": 18112, "Shell": 389}
|
package com.bomber.swan.hooks.pthread
import androidx.annotation.Keep
import com.bomber.swan.hooks.AbsHook
class PthreadHook private constructor() : AbsHook() {
companion object {
val TAG = "Swan.Pthread"
val INSTANCE: PthreadHook = PthreadHook()
}
val hookThreadName = HashSet<String>()
var enableQuicken = true
var enableLog = true
var configured = false
var threadTraceEnable = true
var hookInstalled = false
var enableTracePthreadRelease = true
override fun getNativeLibraryName(): String {
return "swan-pthreadhook"
}
fun dump(path: String) {
if (status == Status.COMMIT_SUCCESS) {
dumpNative(path)
}
}
override fun onConfigure(): Boolean {
addHookThreadNameNative(hookThreadName.toArray(Array(0) { "" }))
enableQuickenNative(enableQuicken)
enableTracePthreadReleaseNative(enableTracePthreadRelease)
enableLoggerNative(enableLog)
return true
}
override fun onHook(enableDebug: Boolean): Boolean {
if (!hookInstalled) {
installHooksNative(enableDebug)
hookInstalled = true
}
return true
}
@Keep
private external fun addHookThreadNameNative(threadNames: Array<String>)
@Keep
private external fun enableQuickenNative(enableQuick: Boolean)
@Keep
private external fun enableLoggerNative(enableLogger: Boolean)
@Keep
private external fun enableTracePthreadReleaseNative(enableTrace: Boolean)
@Keep
private external fun installHooksNative(enableDebug: Boolean)
private external fun dumpNative(path: String)
}
| 0
|
C++
|
1
| 8
|
65169f46a5af9af3ce097d2cbb67b8f34e9df3f1
| 1,677
|
Swan
|
Apache License 2.0
|
client/src/main/kotlin/tech/figure/classification/asset/client/domain/ContractAction.kt
|
FigureTechnologies
| 490,476,548
| false
| null |
package tech.figure.classification.asset.client.domain
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.protobuf.ByteString
import io.provenance.scope.util.toByteString
/**
* An interface that denotes that instances of the implementor will be able to convert themselves to a [ByteString],
* which is used in blockchain Tx messages to compose their bodies.
*/
interface ContractAction {
fun toBase64Msg(objectMapper: ObjectMapper): ByteString = objectMapper.writeValueAsString(this).toByteString()
}
| 10
|
Kotlin
|
0
| 0
|
22bcc00e4bfc6e332fd33713e49424f5bc930ed8
| 528
|
asset-classification-libs
|
Apache License 2.0
|
androidbaselib/src/main/java/com/ashiqur/androidbaselib/util/helper/SnackbarUtil.kt
|
ashiqursuperfly
| 254,910,443
| false
| null |
package com.ashiqur.androidbaselib.util.helper
import android.os.Build
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.ashiqur.androidbaselib.R
import com.ashiqur.androidbaselib.base.BaseApplication
import com.google.android.material.snackbar.Snackbar
object SnackbarUtil {
fun showLongSnackBar(
view: View,
message: String,
colorRes: Int = R.color.colorPrimary
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
val snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG)
snackbar.view.setBackgroundColor(ContextCompat.getColor(BaseApplication.getApplicationContext(), colorRes))
snackbar.show()
}
else
Toast.makeText(view.context, message, Toast.LENGTH_LONG).show()
}
fun showShortSnackBar(
view: View,
message: String
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
val snackbar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT)
snackbar.view.setBackgroundColor(ContextCompat.getColor(BaseApplication.getApplicationContext(), R.color.colorPrimary))
snackbar.show()
}
else
Toast.makeText(view.context, message, Toast.LENGTH_SHORT).show()
}
}
| 0
|
Kotlin
|
0
| 1
|
e2b29baae9c847d8c3fcd0287777b52a18f8d712
| 1,363
|
Android-Utils
|
MIT License
|
src/main/kotlin/net/wrony/aoc2023/a2/Main.kt
|
kopernic-pl
| 727,133,267
| false
|
{"Kotlin": 23297}
|
package net.wrony.aoc2023.a2
import kotlin.io.path.Path
import kotlin.io.path.readText
data class Draw(val reds: Int, val greens: Int, val blues: Int) {
constructor(): this(0,0,0)
operator fun plus(other: Draw): Draw =
Draw(reds + other.reds, greens + other.greens, blues + other.blues)
fun power(): Int = reds * greens * blues
override fun toString(): String = "|r$reds, g$greens, b$blues|"
}
data class Game(val id: Int, val draws: List<Draw>) {
fun isPossible(reds: Int, greens: Int, blues: Int): Boolean {
return draws.all { it.reds<= reds && it.greens <= greens && it.blues <= blues}
}
fun fewestCubes(): Draw {
return Draw(draws.maxOf { it.reds }, draws.maxOf { it.greens }, draws.maxOf { it.blues })
}
}
fun lineToGameAndDraws(line: String) : Pair<Int, List<List<String>>> {
return line.split(": ")
.let { (gamePart, drawsPart) ->
gamePart.removePrefix("Game ").toInt() to drawsPart.split("; ").map { it.split(", ") }
}
}
fun parseDraw(draw: List<String>): Draw {
return draw.map {
val (count, color) = it.split(" ")
when (color) {
"red" -> Draw(count.toInt(), 0, 0)
"green" -> Draw(0, count.toInt(), 0)
"blue" -> Draw(0, 0, count.toInt())
else -> throw Exception("Unknown color $color")
}
}.fold(Draw()) { acc, d -> acc + d }
}
fun main() {
println (
Path("src/main/resources/2.txt").readText().lineSequence()
.map { lineToGameAndDraws(it) }
.map { (gameId, draws) -> Game(gameId, draws.map { parseDraw(it) }) }
.filter { it.isPossible(12, 13, 14) }
.sumOf { it.id }
)
//tried 279 - X
//tried 2416 - OK
println (
Path("src/main/resources/2.txt").readText().lineSequence()
.map { lineToGameAndDraws(it) }
.map { (gameId, draws) -> Game(gameId, draws.map { parseDraw(it) }) }
.map { it.fewestCubes() }
.sumOf { it.power() }
)
//tried 63307 - OK
}
| 0
|
Kotlin
|
0
| 0
|
cbd2920ff054088928fb147c8ca6bed7388a3e05
| 2,055
|
aoc-2023-kotlin
|
MIT License
|
app/src/main/java/com/example/quoteofday/data/local/QuoteDao.kt
|
Ftm-amani
| 617,451,628
| false
| null |
package com.example.quoteofday.data.local
import androidx.lifecycle.LiveData
import androidx.room.*
import com.example.quoteofday.data.models.Quotes
import kotlinx.coroutines.flow.Flow
@Dao
interface QuoteDao {
@Query("SELECT * from quotes_table")
// fun getAllQuotes(): LiveData<List<Quotes>>
fun getAllQuotes(): Flow<List<Quotes>>
@Query("SELECT * from quotes_table")
fun getOneQuote(): Flow<Quotes>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(quotes: Quotes)
@Delete
suspend fun delete(quotes: Quotes)
}
| 0
|
Kotlin
|
0
| 0
|
bad45bbba88c8679a89e26150720414e0ec61a52
| 592
|
quote-of-day
|
Apache License 2.0
|
app/src/main/java/dev/arkbuilders/arkdrop/MainActivity.kt
|
ARK-Builders
| 786,456,358
| false
|
{"Kotlin": 65774}
|
package dev.arkbuilders.arkdrop
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import dev.arkbuilders.arkdrop.presentation.navigation.BottomTab
import dev.arkbuilders.arkdrop.presentation.navigation.TransfersDestination
import dev.arkbuilders.arkdrop.presentation.navigation.navRegistration
import dev.arkbuilders.arkdrop.presentation.permission.PermissionManager
import dev.arkbuilders.arkdrop.ui.theme.ARKDropTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Register ActivityResult handler
val requestPermissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results ->
// Handle permission requests results
// See the permission example in the Android platform samples: https://github.com/android/platform-samples
}
PermissionManager.initialize(requestPermissions)
PermissionManager.requestPermission(baseContext)
setContent {
ARKDropTheme {
// A surface container using the 'background' color from the theme
val navController = rememberNavController()
val currentBackStack by navController.currentBackStackEntryAsState()
val currentDestination = currentBackStack?.destination
val scope = rememberCoroutineScope()
Scaffold(
bottomBar = {
BottomTab(
navController = navController,
currentDestination = currentDestination
)
}) { innerPadding ->
NavHost(
navController,
startDestination = TransfersDestination.route,
Modifier.padding(innerPadding)
) {
navRegistration(navController)
}
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
ARKDropTheme {
Greeting("Android")
}
}
| 1
|
Kotlin
|
0
| 0
|
df09f7079dbb458c81dc89fb83d327de5ff1918d
| 3,010
|
ARK-Drop
|
MIT License
|
app/src/main/java/pl/better/foodzilla/ui/navigation/BottomBarNavGraph.kt
|
kambed
| 612,140,416
| false
| null |
package pl.better.foodzilla.ui.navigation
import com.ramcosta.composedestinations.annotation.NavGraph
import com.ramcosta.composedestinations.annotation.RootNavGraph
@RootNavGraph
@NavGraph
annotation class BottomBarNavGraph(
val start: Boolean = false
)
| 1
|
Kotlin
|
0
| 3
|
94a8993b3aefc6271cea6ffd95546cb8c02802f4
| 260
|
FoodzillaFrontendAndroid
|
Apache License 2.0
|
hobbits/src/integrationTest/kotlin/org/apache/tuweni/hobbits/InteractionTest.kt
|
Consensys
| 693,991,624
| true
|
{"SVG": 2, "Java Properties": 2, "Markdown": 64, "Gradle": 64, "Shell": 3, "EditorConfig": 1, "YAML": 13760, "Git Attributes": 1, "Batchfile": 1, "Text": 33, "Ignore List": 2, "Git Config": 1, "Kotlin": 393, "TOML": 8, "Java": 443, "XML": 18, "JSON": 17343, "JavaScript": 4, "CSS": 1, "HTML": 8, "SQL": 5, "INI": 3, "ANTLR": 2, "Public Key": 1, "Dockerfile": 2}
|
// Copyright The Tuweni Authors
// SPDX-License-Identifier: Apache-2.0
package org.apache.tuweni.hobbits
import io.vertx.core.Vertx
import kotlinx.coroutines.runBlocking
import org.apache.tuweni.bytes.Bytes
import org.apache.tuweni.junit.VertxExtension
import org.apache.tuweni.junit.VertxInstance
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
@ExtendWith(VertxExtension::class)
class TCPPersistentTest {
@Test
fun testTwoTCPConnections(@VertxInstance vertx: Vertx) {
val ref = AtomicReference<Message>()
val newPort = AtomicInteger()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
runBlocking {
client1.createTCPEndpoint(
"foo",
networkInterface = "127.0.0.1",
port = 0,
handler = ref::set,
portUpdateListener = newPort::set,
)
client1.start()
client2.start()
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.TCP,
"127.0.0.1",
newPort.get(),
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
client1.stop()
client2.stop()
}
@Disabled
@Test
fun testTwoTCPConnectionsWithTLS(@VertxInstance vertx: Vertx) {
val ref = AtomicReference<Message>()
val newPort = AtomicInteger()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
runBlocking {
client1.createTCPEndpoint(
"foo",
networkInterface = "127.0.0.1",
port = 0,
handler = ref::set,
tls = true,
portUpdateListener = newPort::set,
)
client1.start()
client2.start()
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.TCP,
"127.0.0.1",
newPort.get(),
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
client1.stop()
client2.stop()
}
@Test
fun testTwoEndpoints(@VertxInstance vertx: Vertx) {
val ref = AtomicReference<Message>()
val ref2 = AtomicReference<Message>()
val newPort = AtomicInteger()
val newPort2 = AtomicInteger()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
runBlocking {
client1.createTCPEndpoint(
"foo",
networkInterface = "127.0.0.1",
port = 0,
handler = ref::set,
portUpdateListener = newPort::set,
)
client1.createTCPEndpoint(
"bar",
networkInterface = "127.0.0.1",
port = 0,
handler = ref2::set,
portUpdateListener = newPort2::set,
)
client1.start()
client2.start()
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.TCP,
"127.0.0.1",
newPort.get(),
)
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.TCP,
"127.0.0.1",
newPort2.get(),
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
assertEquals(Bytes.fromHexString("deadbeef"), ref2.get().body)
client1.stop()
client2.stop()
}
}
@ExtendWith(VertxExtension::class)
class HTTPTest {
@Test
fun testTwoHTTPConnections(@VertxInstance vertx: Vertx) {
val ref = AtomicReference<Message>()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
val newPort = AtomicInteger()
runBlocking {
client1.createHTTPEndpoint(
"foo",
networkInterface = "127.0.0.1",
port = 0,
handler = ref::set,
portUpdateListener = newPort::set,
)
client1.start()
client2.start()
client2.sendMessage(
Message(
protocol = Protocol.PING,
body = Bytes.fromHexString("deadbeef"),
headers = Bytes.random(16),
),
Transport.HTTP,
"127.0.0.1",
newPort.get(),
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
client1.stop()
client2.stop()
}
@Test
fun testTwoEndpoints(@VertxInstance vertx: Vertx) {
val ref = AtomicReference<Message>()
val ref2 = AtomicReference<Message>()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
val newPort = AtomicInteger()
val newPort2 = AtomicInteger()
runBlocking {
client1.createHTTPEndpoint(
"foo",
networkInterface = "127.0.0.1",
port = 0,
handler = ref::set,
portUpdateListener = newPort::set,
)
client1.createHTTPEndpoint(
"bar",
networkInterface = "127.0.0.1",
port = 0,
handler = ref2::set,
portUpdateListener = newPort2::set,
)
client1.start()
client2.start()
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.HTTP,
"127.0.0.1",
newPort.get(),
)
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.HTTP,
"127.0.0.1",
newPort2.get(),
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
assertEquals(Bytes.fromHexString("deadbeef"), ref2.get().body)
client1.stop()
client2.stop()
}
}
@ExtendWith(VertxExtension::class)
class UDPTest {
@Test
fun testTwoUDPConnections(@VertxInstance vertx: Vertx) {
val ref = AtomicReference<Message>()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
runBlocking {
client1.createUDPEndpoint("foo", "localhost", 15000, ref::set)
client1.start()
client2.start()
client2.sendMessage(
Message(
protocol = Protocol.PING,
body = Bytes.fromHexString("deadbeef"),
headers = Bytes.random(16),
),
Transport.UDP,
"localhost",
15000,
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
client1.stop()
client2.stop()
}
@Test
fun testTwoEndpoints(@VertxInstance vertx: Vertx) {
val ref = AtomicReference<Message>()
val ref2 = AtomicReference<Message>()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
runBlocking {
client1.createUDPEndpoint("foo", "localhost", 16000, ref::set)
client1.createUDPEndpoint("bar", "localhost", 16001, ref2::set)
client1.start()
client2.start()
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.UDP,
"localhost",
16000,
)
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.UDP,
"localhost",
16001,
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
assertEquals(Bytes.fromHexString("deadbeef"), ref2.get().body)
client1.stop()
client2.stop()
}
}
@ExtendWith(VertxExtension::class)
class WebSocketTest {
@Test
fun testTwoWSConnections(@VertxInstance vertx: Vertx) {
vertx.exceptionHandler { it.printStackTrace() }
val ref = AtomicReference<Message>()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
val newPort = AtomicInteger()
runBlocking {
client1.createWSEndpoint(
"foo",
networkInterface = "127.0.0.1",
port = 0,
handler = ref::set,
portUpdateListener = newPort::set,
)
client1.start()
client2.start()
client2.sendMessage(
Message(
protocol = Protocol.PING,
body = Bytes.fromHexString("deadbeef"),
headers = Bytes.random(16),
),
Transport.WS,
"127.0.0.1",
newPort.get(),
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
client1.stop()
client2.stop()
}
@Test
fun testTwoEndpoints(@VertxInstance vertx: Vertx) {
val ref = AtomicReference<Message>()
val ref2 = AtomicReference<Message>()
val client1 = HobbitsTransport(vertx)
val client2 = HobbitsTransport(vertx)
val newPort = AtomicInteger()
val newPort2 = AtomicInteger()
runBlocking {
client1.exceptionHandler { it.printStackTrace() }
client2.exceptionHandler { it.printStackTrace() }
client1.createWSEndpoint(
"foo",
networkInterface = "127.0.0.1",
port = 0,
handler = ref::set,
portUpdateListener = newPort::set,
)
client1.createWSEndpoint(
"bar",
networkInterface = "127.0.0.1",
port = 0,
handler = ref2::set,
portUpdateListener = newPort2::set,
)
client1.start()
client2.start()
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.WS,
"127.0.0.1",
newPort.get(),
)
client2.sendMessage(
Message(protocol = Protocol.PING, body = Bytes.fromHexString("deadbeef"), headers = Bytes.random(16)),
Transport.WS,
"127.0.0.1",
newPort2.get(),
)
}
Thread.sleep(200)
assertEquals(Bytes.fromHexString("deadbeef"), ref.get().body)
assertEquals(Bytes.fromHexString("deadbeef"), ref2.get().body)
client1.stop()
client2.stop()
}
}
| 1
|
Java
|
2
| 0
|
d780a654afc90f5fd3c16540d592259487e0a190
| 10,223
|
tuweni
|
Apache License 2.0
|
src/main/java/thedarkcolour/futuremc/entity/bee/ai/StingAI.kt
|
Pidrosax
| 257,567,349
| false
|
{"Text": 2, "INI": 3, "Gradle": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 52, "Kotlin": 170, "JSON": 390}
|
package thedarkcolour.futuremc.entity.bee.ai
import net.minecraft.entity.ai.EntityAIAttackMelee
import thedarkcolour.futuremc.entity.bee.BeeEntity
class StingAI(private val bee: BeeEntity, speedIn: Double, useLongMemory: Boolean) : EntityAIAttackMelee(bee, speedIn, useLongMemory) {
override fun shouldExecute(): Boolean {
return super.shouldExecute() && bee.isAngry() && !bee.hasStung()
}
override fun shouldContinueExecuting(): Boolean {
return shouldExecute()
}
}
| 1
| null |
1
| 1
|
b343d2a134eab9575b1f9b45422862b2e964e74a
| 501
|
Future-MC
|
FSF All Permissive License
|
app/src/main/java/com/rafaelpilartes/historyapp/MainActivity.kt
|
JeciraMiguel
| 784,273,060
| false
|
{"Kotlin": 7491}
|
package com.rafaelpilartes.historyapp
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
// Array of famous people
private val famousPeople = mapOf(
"<NAME>" to Pair(95, "South African anti-apartheid revolutionary."),
"<NAME>" to Pair(52, "Renowned English playwright and poet."),
"<NAME>" to Pair(76, "German theoretical physicist."),
"<NAME>" to Pair(67, "Italian Renaissance polymath."),
"<NAME>" to Pair(66, "Polish-French physicist and chemist."),
"<NAME>" to Pair(78, "Indian pacifist leader."),
"<NAME>" to Pair(56, "German composer and pianist."),
"<NAME>" to Pair(56, "Co-founder of Apple Inc."),
"Cleopatra" to Pair(39, "Last ruler of the Ptolemaic Kingdom of Egypt."),
"<NAME>" to Pair(35, "Austrian composer."),
"<NAME>" to Pair(60, "Russian revolutionary."),
"<NAME>" to Pair(87, "Albanian-Indian Roman Catholic nun and missionary."),
"<NAME>" to Pair(91, "Spanish painter, sculptor, and printmaker."),
"<NAME>" to Pair(84, "American inventor."),
"<NAME> King Jr." to Pair(39, "American civil rights leader."),
"<NAME>" to Pair(77, "Italian astronomer, physicist, and engineer."),
"<NAME>" to Pair(84, "English mathematician, physicist, and astronomer."),
"<NAME>" to Pair(37, "Dutch Post-Impressionist painter."),
"<NAME>" to Pair(56, "16th President of the United States."),
"<NAME>" to Pair(73, "English naturalist, geologist, and biologist."),
"<NAME>" to Pair(46, "35th President of the United States."),
"<NAME>" to Pair(90, "British statesman, army officer, and writer."),
"<NAME>" to Pair(32, "King of Macedonia."),
"<NAME>" to Pair(74, "American writer and humorist."),
"Michelangelo" to Pair(88, "Italian sculptor, painter, and architect."),
"<NAME>" to Pair(64, "German philosopher, economist, and political theorist."),
"<NAME>" to Pair(47, "Mexican painter."),
"<NAME>" to Pair(46, "French philosopher, author, and journalist."),
"<NAME>" to Pair(55, "American poet."),
"<NAME>" to Pair(42, "American singer and actor."),
"<NAME>" to Pair(59, "Russian novelist."),
"<NAME>" to Pair(80, "American actor and film director."),
"<NAME>" to Pair(76, "English theoretical physicist, cosmologist, and author."),
"<NAME>" to Pair(41, "English novelist."),
"<NAME>" to Pair(65, "American entrepreneur and animator."),
"<NAME>" to Pair(70, "German inventor of the printing press."),
"<NAME>" to Pair(92, "American civil rights activist."),
"<NAME>" to Pair(36, "American actress, model, and singer."),
"<NAME>" to Pair(30, "English novelist and poet."),
"<NAME>" to Pair(82, "Chinese communist revolutionary and founding father of the People's Republic of China."),
"<NAME>" to Pair(65, "German composer and musician."),
"<NAME>" to Pair(87, "American author, political activist, and lecturer."),
"<NAME>" to Pair(63, "32nd President of the United States."),
"<NAME>" to Pair(46, "French physicist, husband of <NAME>."),
"<NAME>" to Pair(82, "American astronaut and the first person to walk on the Moon."),
"<NAME>" to Pair(87, "British stateswoman and former Prime Minister of the United Kingdom."),
"<NAME>" to Pair(83, "Austrian neurologist and the founder of psychoanalysis."),
"<NAME>" to Pair(46, "English novelist, essayist, journalist, and critic."),
"Homer" to Pair(20, "Legendary Greek author of the epic poems the 'Iliad' and the 'Odyssey'.")
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val editTextAge = findViewById<EditText>(R.id.editTextAge)
val buttonFind = findViewById<Button>(R.id.buttonFind)
val buttonClear = findViewById<Button>(R.id.buttonClear)
val textViewResult = findViewById<TextView>(R.id.textViewResult) // Correct declaration of textViewResult
// OnClickListener for the "Find" button
buttonFind.setOnClickListener {
val ageText = editTextAge.text.toString().toIntOrNull()
if (ageText != null && ageText in 20..100) {
val famousPerson = findFamousPerson(ageText)
// Set the result text view with the result or "No matches" if no match is found
textViewResult.text = famousPerson ?: "No matches."
// Log the result
Log.d("FindFamousPerson", famousPerson ?: "No matches.")
} else {
// Set the result text view with an error message
textViewResult.text = "The age is invalid or out of range (20-100)."
// Log the error message
Log.d("FindFamousPerson", "The age is invalid or out of range (20-100).")
}
}
// OnClickListener for the "Clear" button
buttonClear.setOnClickListener {
// Clear the age edit text
editTextAge.text.clear()
// Clear the result text view
textViewResult.text = ""
}
}
// Function to find a famous person with the same age
private fun findFamousPerson(age: Int): String? {
for ((famousName, pair) in famousPeople) {
val deathAge = pair.first
val famousOccupation = pair.second
if (age == deathAge) {
// Return a formatted string if a match is found
return "You are $age years old, which is the same age as $famousName. $famousName was a $famousOccupation."
}
}
// Return null if no match is found
return null
}
}
| 0
|
Kotlin
|
0
| 0
|
eb2799946a8d8dc073fada126afeec855e45848e
| 6,069
|
HistoryApp
|
MIT License
|
src/test/kotlin/io/github/yearnlune/excel/ExcelExporterWIthS3Test.kt
|
yearnlune
| 503,232,925
| false
|
{"Kotlin": 50330}
|
package io.github.yearnlune.excel
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.hamcrest.core.Is
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import java.time.LocalDateTime
import java.util.*
@Suppress("SpringJavaInjectionPointsAutowiringInspection")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
class ExcelExporterWIthS3Test {
@Autowired
private lateinit var appProperties: AppProperties
@Autowired
private lateinit var excelExporter: ExcelExporter
@Test
@DisplayName("S3를 통한 다운로드 링크로 엑셀 추출하기")
fun exportAsDownloadUrl() {
/* GIVEN */
val excelMeta = ExcelMeta(
headers = arrayOf(
ExcelMeta.Header("아이디"),
ExcelMeta.Header("나이"),
ExcelMeta.Header("가입일")
),
contents = arrayOf(ExcelMeta.Content(arrayOf("Identification", 22, LocalDateTime.now())))
)
val objectKey = UUID.randomUUID().toString()
/* WHEN */
val downloadUrl = excelExporter.exportAsDownloadUrl(excelMeta, objectKey)
/* THEN */
MatcherAssert.assertThat(
downloadUrl,
CoreMatchers.`is`("http://${appProperties.host}:${appProperties.port}/${appProperties.bucket}/excel/$objectKey.xlsx")
)
}
@Test
@DisplayName("S3를 통한 다운로드 링크로 정의되지 않은 템플릿 엑셀 추출하기")
fun exportAsDownloadUrl_withNotExistTemplate() {
/* GIVEN */
val excelMeta = ExcelMeta(
headers = arrayOf(
ExcelMeta.Header("아이디"),
ExcelMeta.Header("나이"),
ExcelMeta.Header("가입일")
),
contents = arrayOf(ExcelMeta.Content(arrayOf("Identification", 22, LocalDateTime.now())))
)
val creatorName = "NOT_EXIST"
val objectKey = UUID.randomUUID().toString()
val exception = assertThrows<NotFoundCreatorException> {
/* WHEN */
this.excelExporter.exportAsDownloadUrl(excelMeta, objectKey, creatorName)
}
/* THEN */
MatcherAssert.assertThat(exception.message, Is.`is`("COULD NOT FOUND [$creatorName] Excel Creator"))
}
}
| 0
|
Kotlin
|
0
| 0
|
f722831fa5489d5bb3e19c2fdad79c6775c2367f
| 2,473
|
excel-exporter
|
MIT License
|
src/main/kotlin/com/github/juzraai/cordis/crawler/modules/processors/CordisProjectCrawler.kt
|
juzraai
| 14,644,476
| false
|
{"Kotlin": 60620, "HTML": 2201}
|
package com.github.juzraai.cordis.crawler.modules.processors
import com.github.juzraai.cordis.crawler.model.*
import com.github.juzraai.cordis.crawler.modules.*
import com.github.juzraai.cordis.crawler.modules.parsers.*
import com.github.juzraai.cordis.crawler.modules.readers.*
import com.github.juzraai.cordis.crawler.modules.readers.caches.*
import mu.*
/**
* @author <NAME>
*/
class CordisProjectCrawler : ICordisCrawlerRecordProcessor {
companion object : KLogging()
private var modules: CordisCrawlerModuleRegistry? = null
override fun initialize(configuration: CordisCrawlerConfiguration, modules: CordisCrawlerModuleRegistry) {
this.modules = modules
}
override fun process(cordisCrawlerRecord: CordisCrawlerRecord): CordisCrawlerRecord {
return cordisCrawlerRecord.apply {
logger.trace("Reading project XML: $rcn")
val xml = readProjectXml(rcn)
if (null != xml) {
// TODO [v2.1] would be great not to rewrite every processed file...
// TODO [v2.1] maybe remember which cache returned the file?
logger.trace("Caching project XML: $rcn")
cacheProjectXml(xml, rcn)
logger.trace("Parsing project XML: $rcn")
project = parseProjectXml(xml)
}
}
}
private fun readProjectXml(rcn: Long) =
modules!!.ofType(ICordisProjectXmlReader::class.java).asSequence()
.mapNotNull { it.projectXmlByRcn(rcn) }
.firstOrNull()
private fun cacheProjectXml(xml: String, rcn: Long) {
modules!!.ofType(ICordisProjectXmlCache::class.java)
.onEach { it.cacheProjectXml(xml, rcn) }
}
private fun parseProjectXml(xml: String) =
modules!!.ofType(ICordisProjectXmlParser::class.java).asSequence()
.mapNotNull { it.parseProjectXml(xml) }
.firstOrNull()
}
| 4
|
Kotlin
|
0
| 1
|
62bfd6ef3423954782689dccde153518c2ea4245
| 1,723
|
cordis-projects-crawler
|
MIT License
|
src/main/kotlin/no/nav/fia/arbeidsgiver/sporreundersokelse/domene/Tema.kt
|
navikt
| 644,356,194
| false
|
{"Kotlin": 193080, "Dockerfile": 214}
|
package no.nav.fia.arbeidsgiver.sporreundersokelse.domene
import io.ktor.http.HttpStatusCode
import java.util.UUID
import no.nav.fia.arbeidsgiver.http.Feil
data class Tema(
val id: Int,
val navn: String,
val spørsmål: List<Spørsmål>,
) {
fun indeksFraSpørsmålId(spørsmålId: UUID): Int {
val indeks = spørsmål.indexOfFirst { it.id == spørsmålId }
if (indeks == -1) {
throw Feil(feilmelding = "Spørsmål med id $spørsmålId ble ikke funnet", feilkode = HttpStatusCode.NotFound)
}
return indeks
}
fun hentNesteSpørsmål(spørsmålId: UUID): Spørsmål? {
val gjeldeneSpørsmålIdx = indeksFraSpørsmålId(spørsmålId = spørsmålId)
return spørsmål.elementAtOrNull(gjeldeneSpørsmålIdx + 1)
}
fun hentForrigeSpørsmål(spørsmålId: UUID): Spørsmål? {
val gjeldeneSpørsmålIdx = indeksFraSpørsmålId(spørsmålId = spørsmålId)
return spørsmål.elementAtOrNull(gjeldeneSpørsmålIdx - 1)
}
}
fun List<Tema>.spørsmålFraId(spørsmålId: UUID) =
this.flatMap { it.spørsmål }.firstOrNull { it.id == spørsmålId }
?: throw Feil("Fant ikke spørsmål $spørsmålId i spørreundersøkelse", feilkode = HttpStatusCode.NotFound)
fun List<Tema>.temaFraSpørsmålId(spørsmålId: UUID) =
this.find { tema ->
tema.spørsmål.any { spørsmål ->
spørsmål.id == spørsmålId
}
} ?: throw Feil("Fant ikke tema til spørsmålId $spørsmålId", feilkode = HttpStatusCode.NotFound)
| 0
|
Kotlin
|
0
| 0
|
fda8190d28f181f648d85617c81cc718b5ba20a9
| 1,478
|
fia-arbeidsgiver
|
MIT License
|
src/main/kotlin/me/mairwunnx/covid19/handlers/ServerEventHandler.kt
|
MairwunNx
| 251,269,586
| false
| null |
package me.mairwunnx.covid19.handlers
import me.mairwunnx.covid19.api.purgeVirusStateMap
import me.mairwunnx.covid19.api.store.CoronavirusStore
import net.minecraftforge.api.distmarker.Dist
import net.minecraftforge.event.world.WorldEvent
import net.minecraftforge.eventbus.api.SubscribeEvent
import net.minecraftforge.fml.DistExecutor
import net.minecraftforge.fml.event.server.FMLServerStartingEvent
import net.minecraftforge.fml.event.server.FMLServerStoppingEvent
import java.io.File
@Suppress("unused")
object ServerEventHandler {
@SubscribeEvent
fun onServerStarting(event: FMLServerStartingEvent) = initializeCoronavirusStore(event)
@SubscribeEvent
fun onServerSaving(
@Suppress("UNUSED_PARAMETER") event: WorldEvent.Save
) = CoronavirusStore.save()
@SubscribeEvent
fun onServerShuttingDown(
@Suppress("UNUSED_PARAMETER") event: FMLServerStoppingEvent
) {
CoronavirusStore.save()
purgeVirusStateMap()
ItemDropHandler.purgeConditionsItemMaps()
}
private fun initializeCoronavirusStore(event: FMLServerStartingEvent) {
DistExecutor.runWhenOn(Dist.CLIENT) {
Runnable {
CoronavirusStore.init("saves${File.separator}${event.server.folderName}")
}
}
DistExecutor.runWhenOn(Dist.DEDICATED_SERVER) {
Runnable {
CoronavirusStore.init(event.server.folderName)
}
}
}
}
| 1
|
Kotlin
|
0
| 2
|
57b61e27da77de17a493320e92970b8a556b19a2
| 1,466
|
COVID-19-Mod
|
MIT License
|
app/src/main/java/com/example/quranme/ui/quiz/PilihanQuiz.kt
|
bwahyuh
| 703,551,880
| false
|
{"Kotlin": 128308}
|
package com.example.quranme.ui.quiz
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import android.util.Log
import androidx.compose.ui.platform.LocalContext
import com.example.quranme.R
import com.example.quranme.compose.ui.theme.QuranMeTheme
class PilihanQuiz : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
QuranMeTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
PilihanQuizContent()
}
}
}
}
}
@Composable
fun PilihanQuizBackground() {
val context = LocalContext.current
Surface(
modifier = Modifier.fillMaxSize(),
color = Color(0xFF040C23)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.Start
) {
Text(
text = "Pilih Level",
style = TextStyle(
fontSize = 28.sp,
fontFamily = FontFamily(Font(R.font.poppins_bold)),
fontWeight = FontWeight(700),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Center
)
)
Spacer(modifier = Modifier.height(16.dp))
AlifLevelCard(context)
Spacer(modifier = Modifier.height(16.dp))
LamLevelCard(context)
Spacer(modifier = Modifier.height(16.dp))
JimLevelCard(context)
Spacer(modifier = Modifier.height(16.dp))
WowLevelCard(context)
}
}
}
@Composable
fun AlifLevelCard(context: Context) {
Box(
modifier = Modifier
.clickable {
Log.d("PilihanQuiz", "AlifLevelCard clicked")
val intent = Intent(context, IsiQuiz::class.java)
context.startActivity(intent)
}
.width(349.dp)
.height(110.dp)
.background(color = Color(0xFFC589D4), shape = RoundedCornerShape(size = 15.dp))
) {
Row(
modifier = Modifier
.padding(16.dp)
.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.ngaji),
contentDescription = "image description",
contentScale = ContentScale.FillBounds,
modifier = Modifier
.width(68.43137.dp)
.height(57.dp)
)
Spacer(modifier = Modifier.width(16.dp))
Column {
Text(
text = "Alif Level",
style = TextStyle(
fontSize = 20.sp,
fontFamily = FontFamily(Font(R.font.poppins_bold)),
fontWeight = FontWeight(500),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Start
),
modifier = Modifier
.fillMaxWidth()
.height(24.dp)
)
Text(
text = "Selesaikan tantangan berikut untuk menguji pemahaman mu!",
style = TextStyle(
fontSize = 12.sp,
fontFamily = FontFamily(Font(R.font.poppins_light)),
fontWeight = FontWeight(300),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Start
),
modifier = Modifier
.fillMaxWidth()
.height(30.dp)
)
}
}
}
}
@Composable
fun LamLevelCard(context: Context) {
Box(
modifier = Modifier
.clickable { /* implementasi navigasi untuk Lam Level */ }
.width(349.dp)
.height(110.dp)
.background(color = Color(0xFFA06262), shape = RoundedCornerShape(size = 15.dp))
) {
Row(
modifier = Modifier
.padding(16.dp)
.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.ngaji3),
contentDescription = "image description",
contentScale = ContentScale.FillBounds,
modifier = Modifier
.width(68.43137.dp)
.height(57.dp)
)
Spacer(modifier = Modifier.width(16.dp))
Column(
modifier = Modifier
.fillMaxHeight()
.align(Alignment.CenterVertically)
) {
Text(
text = "Lam Level",
style = TextStyle(
fontSize = 20.sp,
fontFamily = FontFamily(Font(R.font.poppins_bold)),
fontWeight = FontWeight(500),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Start
),
modifier = Modifier
.fillMaxWidth()
.height(24.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Selesaikan tantangan berikut untuk menguji pemahaman mu!",
style = TextStyle(
fontSize = 12.sp,
fontFamily = FontFamily(Font(R.font.poppins_light)),
fontWeight = FontWeight(300),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Start
),
modifier = Modifier
.fillMaxWidth()
.height(30.dp)
)
}
}
}
}
@Composable
fun JimLevelCard(context: Context) {
Box(
modifier = Modifier
.clickable { /* implementasi navigasi untuk Jim Level */ }
.width(349.dp)
.height(110.dp)
.background(color = Color(0xFFDBAC35), shape = RoundedCornerShape(size = 15.dp))
) {
Row(
modifier = Modifier
.padding(16.dp)
.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.ngaji2),
contentDescription = "image description",
contentScale = ContentScale.FillBounds,
modifier = Modifier
.width(68.43137.dp)
.height(57.dp)
)
Spacer(modifier = Modifier.width(16.dp))
Column(
modifier = Modifier
.fillMaxHeight()
.align(Alignment.CenterVertically)
) {
Text(
text = "Jim Level",
style = TextStyle(
fontSize = 20.sp,
fontFamily = FontFamily(Font(R.font.poppins_bold)),
fontWeight = FontWeight(500),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Start
),
modifier = Modifier
.fillMaxWidth()
.height(24.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Selesaikan tantangan berikut untuk menguji pemahaman mu!",
style = TextStyle(
fontSize = 12.sp,
fontFamily = FontFamily(Font(R.font.poppins_light)),
fontWeight = FontWeight(300),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Start
),
modifier = Modifier
.fillMaxWidth()
.height(30.dp)
)
}
}
}
}
@Composable
fun WowLevelCard(context: Context) {
Box(
modifier = Modifier
.clickable { /* implementasi navigasi untuk Wow Level */ }
.width(349.dp)
.height(110.dp)
.background(color = Color(0xFF7F4B6A), shape = RoundedCornerShape(size = 15.dp))
) {
Row(
modifier = Modifier
.padding(16.dp)
.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.ngaji2),
contentDescription = "image description",
contentScale = ContentScale.FillBounds,
modifier = Modifier
.width(68.43137.dp)
.height(57.dp)
)
Spacer(modifier = Modifier.width(16.dp))
Column(
modifier = Modifier
.fillMaxHeight()
.align(Alignment.CenterVertically)
) {
Text(
text = "Wow Level",
style = TextStyle(
fontSize = 20.sp,
fontFamily = FontFamily(Font(R.font.poppins_bold)),
fontWeight = FontWeight(500),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Start
),
modifier = Modifier
.fillMaxWidth()
.height(24.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Selesaikan tantangan berikut untuk menguji pemahaman mu!",
style = TextStyle(
fontSize = 12.sp,
fontFamily = FontFamily(Font(R.font.poppins_light)),
fontWeight = FontWeight(300),
color = Color(0xFFFFFFFF),
textAlign = TextAlign.Start
),
modifier = Modifier
.fillMaxWidth()
.height(30.dp)
)
}
}
}
}
@Composable
fun PilihanQuizContent() {
PilihanQuizBackground()
}
@Preview(showBackground = true)
@Composable
fun PilihanQuizPreview() {
QuranMeTheme {
PilihanQuizContent()
}
}
| 0
|
Kotlin
|
1
| 0
|
2d91f93eabc691731372f01f9d88a94a8aa3a724
| 11,969
|
QuranMe
|
MIT License
|
app/src/sharedTest/java/ru/luckycactus/steamroulette/util/fakes/FakeClock.kt
|
luckycactus
| 196,364,852
| false
| null |
package ru.luckycactus.steamroulette.util.fakes
import ru.luckycactus.steamroulette.domain.core.Clock
import kotlin.time.Duration
class FakeClock(
private var current: Long = System.currentTimeMillis()
) : Clock {
override fun currentTimeMillis() = current
fun advanceTimeBy(offset: Duration) {
current += offset.toLongMilliseconds()
}
fun set(millis: Long) {
current = millis
}
fun setToSystem() {
set(System.currentTimeMillis())
}
}
| 0
|
Kotlin
|
0
| 5
|
c6c2b00ca77f8224145ef3182b1910bd249d76ba
| 496
|
steam-roulette
|
Apache License 2.0
|
app/shared/analytics/impl/src/commonMain/kotlin/build/wallet/analytics/events/EventTrackerImpl.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10551861, "Kotlin": 6455657, "Rust": 1874547, "Swift": 629125, "Python": 329146, "HCL": 257498, "Shell": 97542, "TypeScript": 81148, "C++": 64770, "Meson": 64252, "JavaScript": 36229, "Just": 26345, "Ruby": 9265, "Dockerfile": 5755, "Makefile": 3839, "Open Policy Agent": 1456, "Procfile": 80}
|
package build.wallet.analytics.events
import build.wallet.account.analytics.AppInstallation
import build.wallet.account.analytics.AppInstallationDao
import build.wallet.analytics.events.screen.EventTrackerScreenInfo
import build.wallet.analytics.v1.Action
import build.wallet.analytics.v1.Action.ACTION_APP_SCREEN_IMPRESSION
import build.wallet.analytics.v1.Event
import build.wallet.bitkey.keybox.KeyboxConfig
import build.wallet.f8e.F8eEnvironment.Production
import build.wallet.keybox.KeyboxDao
import build.wallet.keybox.config.TemplateKeyboxConfigDao
import build.wallet.logging.LogLevel
import build.wallet.logging.log
import build.wallet.logging.logFailure
import build.wallet.money.display.BitcoinDisplayPreferenceRepository
import build.wallet.money.display.FiatCurrencyPreferenceRepository
import build.wallet.platform.device.DeviceInfoProvider
import build.wallet.platform.device.DevicePlatform
import build.wallet.platform.settings.LocaleCountryCodeProvider
import build.wallet.platform.settings.LocaleCurrencyCodeProvider
import build.wallet.queueprocessor.Processor
import com.github.michaelbull.result.get
import com.github.michaelbull.result.getOr
import com.github.michaelbull.result.getOrElse
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
class EventTrackerImpl(
private val appCoroutineScope: CoroutineScope,
private val clock: Clock,
private val appDeviceIdDao: AppDeviceIdDao,
private val deviceInfoProvider: DeviceInfoProvider,
private val keyboxDao: KeyboxDao,
private val templateKeyboxConfigDao: TemplateKeyboxConfigDao,
private val countryCodeProvider: LocaleCountryCodeProvider,
private val eventProcessor: Processor<QueueAnalyticsEvent>,
private val hardwareInfoProvider: HardwareInfoProvider,
private val appInstallationDao: AppInstallationDao,
private val platformInfoProvider: PlatformInfoProvider,
private val sessionIdProvider: SessionIdProvider,
private val eventStore: EventStore,
private val analyticsTrackingEnabledFeatureFlag: AnalyticsTrackingEnabledFeatureFlag,
private val bitcoinDisplayPreferenceRepository: BitcoinDisplayPreferenceRepository,
private val fiatCurrencyPreferenceRepository: FiatCurrencyPreferenceRepository,
private val localeCurrencyCodeProvider: LocaleCurrencyCodeProvider,
) : EventTracker {
override fun track(action: Action) {
track(
action = action,
screenId = null
)
}
override fun track(eventTrackerScreenInfo: EventTrackerScreenInfo) {
// Early return if this screen should not be tracked.
// The reason [EventTrackerScreenInfo] would still be present for the screen is because
// it also serves as the screen's ID, so it is needed to maintain screen uniqueness,
// especially for form screens.
if (!eventTrackerScreenInfo.eventTrackerShouldTrack) {
return
}
track(
action = ACTION_APP_SCREEN_IMPRESSION,
screenId =
when (val context = eventTrackerScreenInfo.eventTrackerScreenIdContext) {
null ->
eventTrackerScreenInfo.eventTrackerScreenId.name
else ->
"${eventTrackerScreenInfo.eventTrackerScreenId.name}_${context.name}"
}
)
}
private fun track(
action: Action,
screenId: String?,
) {
appCoroutineScope.launch {
// TODO(W-3387): use account ID from in-progress recovery when there is
// no active or onboarding keybox present.
val keybox = keyboxDao.getActiveOrOnboardingKeybox()
val accountId = keybox.get()?.fullAccountId?.serverId.orEmpty()
val keysetId = keybox.get()?.activeSpendingKeyset?.localId.orEmpty()
val platformInfo = platformInfoProvider.getPlatformInfo()
val f8eEnvironment = getKeyboxConfig()?.f8eEnvironment ?: Production // assume prod when no keybox is available
// In case of iOS we rely on a generated appDeviceId stored in the keychain.
// Due to lack of availability of a similar solution on Android, we use ANDROID_ID instead.
var appDeviceId = platformInfo.device_id
if (deviceInfoProvider.getDeviceInfo().devicePlatform == DevicePlatform.IOS) {
appDeviceId = appDeviceIdDao.getOrCreateAppDeviceIdIfNotExists().getOr("UNKNOWN")
}
val appInstallationId =
appInstallationDao.getOrCreateAppInstallation()
.getOrElse {
log(LogLevel.Error, throwable = it.cause) { "Failed to get App Installation" }
AppInstallation(localId = "", hardwareSerialNumber = null)
}.localId
val bitcoinDisplayUnit = bitcoinDisplayPreferenceRepository.bitcoinDisplayUnit.value
val fiatCurrencyPreference =
fiatCurrencyPreferenceRepository.fiatCurrencyPreference.value
?: fiatCurrencyPreferenceRepository.defaultFiatCurrency.value
val event =
Event(
event_time = clock.now().toString(),
session_id = sessionIdProvider.getSessionId(),
account_id = accountId,
action = action,
country = countryCodeProvider.countryCode(),
locale_currency = localeCurrencyCodeProvider.localeCurrencyCode() ?: "",
platform_info = platformInfo,
hw_info = hardwareInfoProvider.getHardwareInfo(),
screen_id = screenId ?: "",
app_device_id = appDeviceId,
keyset_id = keysetId,
app_installation_id = appInstallationId,
fiat_currency_preference = fiatCurrencyPreference.textCode.code,
bitcoin_display_preference = bitcoinDisplayUnit.name
)
// Always add the event to the local store
eventStore.add(event)
// But only actually track the event if the feature flag is on
if (analyticsTrackingEnabledFeatureFlag.flagValue().value.value) {
eventProcessor.process(QueueAnalyticsEvent(f8eEnvironment, event))
.logFailure { "Failed to append event to queue: $event" }
}
}
}
private suspend fun getKeyboxConfig(): KeyboxConfig? {
return when (val keybox = keyboxDao.getActiveOrOnboardingKeybox().getOr(null)) {
// when null, we try to grab the config from the template keybox
null -> templateKeyboxConfigDao.config().first().getOr(null)
else -> keybox.config
}
}
}
| 0
|
C
|
6
| 74
|
b7401e0b96f9378cbd96eb01914a4f888e0a9303
| 6,319
|
bitkey
|
MIT License
|
logic-auth-server/src/main/kotlin/io/lonmstalker/springkube/service/impl/TokenServiceImpl.kt
|
lonmstalker
| 634,331,522
| false
| null |
package io.lonmstalker.springkube.service.impl
import io.lonmstalker.springkube.config.properties.AppProperties
import io.lonmstalker.springkube.constants.JwtConstants.EMAIL
import io.lonmstalker.springkube.constants.JwtConstants.FIRST_NAME
import io.lonmstalker.springkube.constants.JwtConstants.LOGIN_TIME
import io.lonmstalker.springkube.constants.JwtConstants.ROLE
import io.lonmstalker.springkube.constants.JwtConstants.USER_GROUP_ID
import io.lonmstalker.springkube.constants.JwtConstants.USER_ID
import io.lonmstalker.springkube.constants.JwtConstants.USER_NAME
import io.lonmstalker.springkube.enums.TokenType
import io.lonmstalker.springkube.helper.ClockHelper
import io.lonmstalker.springkube.model.CreateTokenSettings
import io.lonmstalker.springkube.model.User
import io.lonmstalker.springkube.model.UserToken
import io.lonmstalker.springkube.model.UserTokenInfo
import io.lonmstalker.springkube.repository.TokenRepository
import io.lonmstalker.springkube.service.TokenService
import org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType.BEARER
import org.springframework.security.oauth2.jwt.JwtClaimsSet
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.jwt.JwtEncoder
import org.springframework.security.oauth2.jwt.JwtEncoderParameters
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Instant
import java.time.ZoneOffset
import java.util.*
@Service
class TokenServiceImpl(
private val jwtEncoder: JwtEncoder,
private val jwtDecoder: JwtDecoder,
private val clockHelper: ClockHelper,
private val tokenRepository: TokenRepository, appProperties: AppProperties,
) : TokenService {
private val issuer = appProperties.auth.issuer
private val tokenProperties = appProperties.token
override fun parseToken(token: String): UUID =
this.jwtDecoder
.decode(token)
.getClaim<String>(USER_ID)
.run { UUID.fromString(this) }
@Transactional
override fun createToken(user: User, client: String, settings: CreateTokenSettings): UserTokenInfo {
val issuedAt = clockHelper.clockInstant()
val accessToken = this.createToken(issuedAt, user, TokenType.ACCESS, client)
val refreshToken = if (settings.createRefreshToken) {
this.createToken(issuedAt, user, TokenType.REFRESH, client)
} else {
null
}
this.update(accessToken, refreshToken)
return UserTokenInfo(
BEARER.value,
issuedAt.plusSeconds(TokenType.ACCESS.toTtl()),
setOf(user.role.name),
accessToken.value,
refreshToken?.value
)
}
private fun update(accessToken: UserToken, refreshToken: UserToken?) {
this.tokenRepository.deleteByClientAndUserId(accessToken.userId, accessToken.client)
if (refreshToken != null) {
this.tokenRepository.saveAll(listOf(accessToken, refreshToken))
} else {
this.tokenRepository.save(accessToken)
}
}
private fun createToken(issuedAt: Instant, user: User, type: TokenType, client: String): UserToken =
JwtClaimsSet.builder()
.issuer(this.issuer)
.issuedAt(issuedAt)
.expiresAt(issuedAt.plusSeconds(type.toTtl()))
.claims { user.fillClaims(it, type) }
.subject(user.username)
.build()
.run { jwtEncoder.encode(JwtEncoderParameters.from(this)) }
.tokenValue
.run {
UserToken(
userId = user.id,
value = this,
client = client,
createdDate = issuedAt,
type = type
)
}
private fun User.fillClaims(claims: MutableMap<String, Any>, type: TokenType) {
claims[USER_ID] = this.id
claims[USER_NAME] = this.username
if (type == TokenType.ACCESS) {
claims[ROLE] = this.role
claims[EMAIL] = this.email
claims[FIRST_NAME] = this.firstName
claims[LOGIN_TIME] = this.lastLogin!!.toEpochSecond(ZoneOffset.UTC)
claims[USER_GROUP_ID] = this.userGroupId
}
}
private fun TokenType.toTtl() =
if (this == TokenType.ACCESS) {
tokenProperties.accessTtl
} else {
tokenProperties.refreshTtl
}
}
| 0
|
Kotlin
|
0
| 0
|
d94bd56bf4d4ce5e5163840f369eba993431a10a
| 4,509
|
spring-kube
|
Apache License 2.0
|
app/src/main/java/com/wzc/constraintlayoutexamples/ConstraintSet2Activity.kt
|
jhwsx
| 200,464,796
| false
| null |
package com.wzc.constraintlayoutexamples
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.constraintlayout.widget.ConstraintSet
import com.wzc.constraintlayoutexamples.databinding.ActivityConstraintSet2StartBinding
class ConstraintSet2Activity : AppCompatActivity() {
private lateinit var binding: ActivityConstraintSet2StartBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityConstraintSet2StartBinding.inflate(layoutInflater)
setContentView(binding.root)
var flag = true
binding.constraintLayout.setOnClickListener {
ConstraintSet().apply {
isForceId = false
flag = !flag
clone(this@ConstraintSet2Activity,
if (flag) R.layout.activity_constraint_set_2_start else R.layout.activity_constraint_set_2_end)
applyTo(binding.constraintLayout)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ab469531fa104ab7199ef67b46c26830f61c512f
| 1,018
|
ConstraintLayoutExamples
|
Apache License 2.0
|
version-catalogs-generator/src/main/kotlin/io/github/andrewk2112/versioncatalogsgenerator/codegenerators/values/PluginValuesCodeGenerator.kt
|
andrew-k-21-12
| 497,585,003
| false
|
{"Kotlin": 327904, "JavaScript": 7404, "HTML": 726}
|
package io.github.andrewk2112.versioncatalogsgenerator.codegenerators.values
import io.github.andrewk2112.versioncatalogsgenerator.codegenerators.CodeEmitters
import io.github.andrewk2112.versioncatalogsgenerator.codegenerators.CommonCodeGeneration
import io.github.andrewk2112.versioncatalogsgenerator.codegenerators.ValuesCodeGenerator
import io.github.andrewk2112.versioncatalogsgenerator.codegenerators.ValuesCodeGenerator.GeneratedCode
import io.github.andrewk2112.versioncatalogsgenerator.extensions.lowerCamelCaseFromKebabOrSnakeCase
import io.github.andrewk2112.versioncatalogsgenerator.extensions.toGeneratedCode
import io.github.andrewk2112.versioncatalogsgenerator.models.ParsedVersionCatalog
import io.github.andrewk2112.versioncatalogsgenerator.utility.Reference
/**
* Generates the code for catalog's plugins.
*/
internal class PluginValuesCodeGenerator(private val codeGeneration: CommonCodeGeneration) : ValuesCodeGenerator {
// Interface.
internal fun generatePluginInterfaceCode(visibilityModifierPrefix: String): String = """
${visibilityModifierPrefix}interface Plugin {
val id: String
val version: String?
}
""".trimIndent()
override fun generateValuesCode(visibilityModifierPrefix: String, catalog: ParsedVersionCatalog): GeneratedCode? {
val cachedPropertyName = Reference<String?>(null)
return codeGeneration
.generateCodeBlocks(
catalog.plugins?.entries,
{ generateInterfaceCode(visibilityModifierPrefix, it, cachedPropertyName) },
{ generateImplementationCode(visibilityModifierPrefix, it, cachedPropertyName) }
)
?.toGeneratedCode()
}
// Code generation.
private fun generateInterfaceCode(
visibilityModifierPrefix: String,
codeEmitters: CodeEmitters<Map.Entry<String, ParsedVersionCatalog.Plugin>>,
cachedPropertyName: Reference<String?>,
): String = """
${visibilityModifierPrefix}interface Plugins {${codeEmitters.emitCode {
cachedPropertyName.value = it.key.lowerCamelCaseFromKebabOrSnakeCase()
"\n val $cachedPropertyName: Plugin"
}}
}
""".trimIndent()
private fun generateImplementationCode(
visibilityModifierPrefix: String,
codeEmitters: CodeEmitters<Map.Entry<String, ParsedVersionCatalog.Plugin>>,
cachedPropertyName: Reference<String?>
): String = """
${visibilityModifierPrefix}val plugins = object : Plugins {${codeEmitters.emitCode {
"""
override val $cachedPropertyName = object : Plugin {
override val id = "${it.value.id}"
override val version = ${codeGeneration.escape(it.value.version)}
}
""".trimEnd()
}}
}
""".trimIndent()
}
| 0
|
Kotlin
|
0
| 2
|
1b4ad239fd3c0f46336208146a32d2d45729e2fa
| 2,734
|
kjs-box
|
MIT License
|
redwood-compose/src/jsMain/kotlin/app/cash/redwood/compose/PlatformSet.kt
|
cashapp
| 305,409,146
| false
|
{"Kotlin": 2089205, "Swift": 20649, "Objective-C": 4497, "Java": 1583, "Shell": 253, "HTML": 235, "C": 129}
|
/*
* Copyright (C) 2024 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
package app.cash.redwood.compose
@JsName("Set")
internal external class JsSet<T> {
fun add(element: T)
fun clear()
fun forEach(block: (T) -> Unit)
}
internal actual typealias PlatformSet<T> = JsSet<T>
internal actual inline fun <T> platformSetOf(): PlatformSet<T> {
return JsSet()
}
internal actual inline operator fun <T> PlatformSet<T>.plusAssign(element: T) {
add(element)
}
internal actual inline fun <T> PlatformSet<T>.forEach(crossinline block: (T) -> Unit) {
forEach { block(it) }
}
internal actual inline fun <T> PlatformSet<T>.clear() {
clear()
}
| 108
|
Kotlin
|
73
| 1,648
|
3f14e622c2900ec7e0dfaff5bd850c95a7f29937
| 1,214
|
redwood
|
Apache License 2.0
|
plot-stem/src/commonMain/kotlin/org/jetbrains/letsPlot/core/spec/front/tiles/PlotGeomTilesBase.kt
|
JetBrains
| 176,771,727
| false
|
{"Kotlin": 6208444, "Python": 1154980, "Shell": 3495, "C": 3039, "JavaScript": 931, "Dockerfile": 94}
|
/*
* Copyright (c) 2024. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.core.spec.front.tiles
import org.jetbrains.letsPlot.core.plot.base.*
import org.jetbrains.letsPlot.core.plot.base.theme.FontFamilyRegistry
import org.jetbrains.letsPlot.core.plot.base.theme.Theme
import org.jetbrains.letsPlot.core.plot.builder.GeomLayer
import org.jetbrains.letsPlot.core.plot.builder.assemble.PlotFacets
import org.jetbrains.letsPlot.core.plot.builder.assemble.PlotGeomTiles
import org.jetbrains.letsPlot.core.plot.builder.coord.CoordProvider
import org.jetbrains.letsPlot.core.spec.config.LayerConfig
abstract class PlotGeomTilesBase(
scaleByAesBeforeFacets: Map<Aes<*>, Scale>,
override val mappersNP: Map<Aes<*>, ScaleMapper<*>>,
override val coordProvider: CoordProvider,
override val containsLiveMap: Boolean
) : PlotGeomTiles {
override val xyContinuousTransforms: Pair<Transform?, Transform?> = Pair(
scaleByAesBeforeFacets.getValue(Aes.X).transform.let { if (it is ContinuousTransform) it else null },
scaleByAesBeforeFacets.getValue(Aes.Y).transform.let { if (it is ContinuousTransform) it else null }
)
override fun coreLayersByTile(): List<List<GeomLayer>> {
return layersByTile().map { layers ->
layers.filterNot { it.isMarginal }
}
}
override fun marginalLayersByTile(): List<List<GeomLayer>> {
return layersByTile().map { layers ->
layers.filter { it.isMarginal }.filterNot { it.isLiveMap }
}
}
companion object {
fun create(
layerConfigs: List<LayerConfig>,
facets: PlotFacets,
coordProvider: CoordProvider,
scaleByAesBeforeFacets: Map<Aes<*>, Scale>,
mappersByAesNP: Map<Aes<*>, ScaleMapper<*>>, // all non-positional mappers
theme: Theme,
fontRegistry: FontFamilyRegistry
): PlotGeomTilesBase {
require(hasLayers(layerConfigs)) { "No layers in plot" }
return when {
facets.isDefined && isFacettable(layerConfigs, facets) -> FacetedPlotGeomTiles.create(
layerConfigs,
facets,
scaleByAesBeforeFacets,
mappersByAesNP,
coordProvider,
theme,
fontRegistry,
)
else -> SimplePlotGeomTiles.create(
layerConfigs,
scaleByAesBeforeFacets,
mappersByAesNP,
coordProvider,
theme,
fontRegistry,
)
}
}
private fun hasLayers(layerConfigs: List<LayerConfig>): Boolean {
return layerConfigs.any { !it.isMarginal }
}
private fun isFacettable(layerConfigs: List<LayerConfig>, facets: PlotFacets): Boolean {
return layerConfigs.any {
facets.isFacettable(it.combinedData)
}
}
}
}
| 124
|
Kotlin
|
46
| 1,355
|
d04f1915cbbae4745d9dbddad6af6a1da1c2bb66
| 3,147
|
lets-plot
|
MIT License
|
src/main/java/com/pangea/raas/remote/UserAgentInterceptor.kt
|
gopangea
| 296,634,589
| false
| null |
package com.pangea.raas.remote
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
class UserAgentInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originRequest = chain.request()
val requestWithUserAgent = originRequest.newBuilder()
.header("x-pangea-user-agent", ApiClientHelper.getUserAgent())
.build()
return chain.proceed(requestWithUserAgent)
}
}
| 0
|
Kotlin
|
0
| 0
|
1afb3432705cec3da2f5862b5a63be9ff96ee210
| 512
|
sdk-raas-android
|
Apache License 2.0
|
common/src/commonMain/kotlin/io/sunland/chainpass/common/component/ExtendedLazyList.kt
|
sunlandx
| 421,030,005
| false
| null |
package io.sunland.chainpass.common.component
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.*
enum class LazyListScrollDirection { FORWARD, BACKWARD }
@Composable
fun LazyListState.scrollDirection(): LazyListScrollDirection {
val prevFirstVisibleItemIndexState = remember { mutableStateOf(firstVisibleItemIndex) }
val prevFirstVisibleItemScrollOffsetState = remember { mutableStateOf(firstVisibleItemScrollOffset) }
return remember {
derivedStateOf {
if (prevFirstVisibleItemIndexState.value != firstVisibleItemIndex) {
if (prevFirstVisibleItemIndexState.value > firstVisibleItemIndex) {
LazyListScrollDirection.BACKWARD
} else LazyListScrollDirection.FORWARD
} else {
if (prevFirstVisibleItemScrollOffsetState.value >= firstVisibleItemScrollOffset) {
LazyListScrollDirection.BACKWARD
} else LazyListScrollDirection.FORWARD
}.also {
prevFirstVisibleItemIndexState.value = firstVisibleItemIndex
prevFirstVisibleItemScrollOffsetState.value = firstVisibleItemScrollOffset
}
}
}.value
}
| 0
|
Kotlin
|
0
| 4
|
005321f0e2d44792d3591431e4abbdae4349f2c4
| 1,242
|
chain-pass
|
Apache License 2.0
|
Sushi/app/src/main/java/com/destructo/sushi/ui/common/characterDetails/CharacterMangaography.kt
|
destructo570
| 302,356,237
| false
| null |
package com.destructo.sushi.ui.common.characterDetails
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.destructo.sushi.MANGA_ID_ARG
import com.destructo.sushi.R
import com.destructo.sushi.databinding.FragmentCharacterMangaographyBinding
import com.destructo.sushi.ui.base.BaseFragment
import com.destructo.sushi.util.GridSpacingItemDeco
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class CharacterMangaography : BaseFragment() {
private lateinit var mangaoAdapter: PersonAdapter
private lateinit var mangaoRecyclerView: RecyclerView
private val characterViewModel: CharacterViewModel
by viewModels(ownerProducer = {requireParentFragment()})
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding =
FragmentCharacterMangaographyBinding
.inflate(inflater, container, false).apply {
lifecycleOwner = viewLifecycleOwner
}
mangaoRecyclerView = binding.mangaographyRecyclerMain
mangaoRecyclerView.layoutManager = GridLayoutManager(context,3)
mangaoRecyclerView.addItemDecoration(GridSpacingItemDeco(3,25,true))
mangaoRecyclerView.setHasFixedSize(true)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
mangaoAdapter = PersonAdapter(PersonListener {
it?.let { navigateToMangaDetails(it) }
})
characterViewModel.character.observe(viewLifecycleOwner){character->
mangaoAdapter.submitList(character.mangaography)
mangaoRecyclerView.adapter = mangaoAdapter
}
}
private fun navigateToMangaDetails(mangaMalId: Int){
this.findNavController().navigate(
R.id.mangaDetailsFragment,
bundleOf(Pair(MANGA_ID_ARG, mangaMalId)),
getAnimNavOptions()
)
}
}
| 3
|
Kotlin
|
5
| 21
|
68317c04caa596103d3fd32b0f34fe43b189a721
| 2,274
|
Sushi-Unofficial-MAL-Client
|
Apache License 2.0
|
app/src/main/java/io/access/kotlintraining/Sample.kt
|
aHarukaAkaba
| 181,993,434
| true
|
{"Kotlin": 2415}
|
package io.access.kotlintraining
import java.util.Random
fun welcome() {
println("welcome to ACCESS!")
}
fun hello() {
println("hello world")
}
fun fizzbuzz(i: Int) : String{
return when {
i % 15 == 0 -> "FizzBuzz"
i % 3 == 0 -> "Fizz"
i % 5 == 0 -> "Buzz"
else -> i.toString()
}
}
fun isLeapYear(year: Int): Boolean {
if (year % 100 == 0 && year % 400 != 0) {
return false
}
return year % 4 == 0
}
fun power(a: Int, n: Int): Long {
if (a < 0 || n < 0) {
println("inputs must be positive. return 0")
return 0
}
var ans: Long = 1
for (i in 0 until n) {
ans *= a
}
return ans
}
fun Int.isOdd() = this % 2 != 0
fun Int.isEven() = this % 2 == 0
class Dice(private val n: Int) {
private var limit = 100
private val random = Random()
fun roll() : Int {
if (this.limit <= 0) {
throw Exception("I was broken")
}
--this.limit
return random.nextInt(n)
}
}
class MyCustomClass {
var counter: Int = 0
var propertyWithCounter: Int = 0
set(i) {
++counter
field = i
}
}
class NabeAtsu {
private var counter = 0
fun next(): String {
this.counter += 1
return if (this.counter % 3 == 0 || "3" in this.counter.toString()) {
"Aho"
}else {
this.counter.toString()
}
}
}
fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) {
//clientとmassageがnullならリターン
if (client == null || message == null) return
val personalInfo = client.personalInfo
val email = personalInfo?.email
email?.let{mailer.sendMessage(it, message)}
}
// コンパイル通すための諸々
class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
fun sendMessage(email: String, message: String)
}
fun main(args: Array<String>) {
}
| 0
|
Kotlin
|
0
| 0
|
1866b4a7f3cdd33f660931fc54414e1c0574b1b1
| 1,952
|
KotlinTraining
|
MIT License
|
app/src/main/java/com/dania/productfinder/ui/common/ProductListAdapter.kt
|
daniachan
| 335,151,127
| false
| null |
package com.dania.productfinder.ui.common
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingComponent
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import timber.log.Timber
import com.dania.productfinder.AppExecutors
import com.dania.productfinder.R
import com.dania.productfinder.databinding.ProductItemBinding
import com.dania.productfinder.vo.Product
class ProductListAdapter (
private val dataBindingComponent: DataBindingComponent,
appExecutors: AppExecutors,
private val showFullName: Boolean,
private val repoClickCallback: ((Product) -> Unit)?
) : DataBoundListAdapter<Product, ProductItemBinding>(
appExecutors = appExecutors,
diffCallback = object : DiffUtil.ItemCallback<Product>() {
override fun areItemsTheSame(oldItem: Product, newItem: Product): Boolean {
return oldItem.productID == newItem.productID
}
override fun areContentsTheSame(oldItem: Product, newItem: Product): Boolean {
return oldItem.productID == newItem.productID
}
}
) {
override fun createBinding(parent: ViewGroup): ProductItemBinding {
val binding = DataBindingUtil.inflate<ProductItemBinding>(
LayoutInflater.from(parent.context),
R.layout.product_item,
parent,
false,
dataBindingComponent
)
binding.root.setOnClickListener {
binding.plpRecod?.let {
repoClickCallback?.invoke(it)
}
}
return binding
}
override fun bind(binding: ProductItemBinding, item: Product) {
binding.plpRecod = item
}
}
| 0
|
Kotlin
|
0
| 0
|
a7cf8399e5c9e73b7ecadadc78b57b20dfae40c4
| 1,799
|
ProductFinder
|
MIT License
|
src/test/kotlin/ui/settings/reducer/SelectCategoryReducerTest.kt
|
gmatyszczak
| 171,290,380
| false
|
{"Kotlin": 192668}
|
package ui.settings.reducer
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runBlockingTest
import model.Category
import model.CategoryScreenElements
import model.ScreenElement
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import ui.settings.SettingsAction.SelectCategory
import ui.settings.SettingsState
@ExperimentalCoroutinesApi
class SelectCategoryReducerTest {
val state = MutableStateFlow(SettingsState())
lateinit var reducer: SelectCategoryReducer
val categoryScreenElement = CategoryScreenElements(
Category(),
listOf(ScreenElement(name = "test"))
)
val initialState = SettingsState(
categories = listOf(categoryScreenElement)
)
@BeforeEach
fun setup() {
state.value = initialState
reducer = SelectCategoryReducer(state)
}
@Test
fun `when index out of bounds on invoke`() = runBlockingTest {
reducer.invoke(SelectCategory(10))
state.value shouldBeEqualTo initialState.copy(
selectedCategoryIndex = null,
selectedElementIndex = null,
)
}
@Test
fun `when index in bounds on invoke`() = runBlockingTest {
reducer.invoke(SelectCategory(0))
state.value shouldBeEqualTo initialState.copy(
selectedCategoryIndex = 0,
selectedElementIndex = 0,
)
}
}
| 6
|
Kotlin
|
28
| 147
|
baf6d12b12c210e835e2513d9e6d6c1e279c8115
| 1,510
|
screen-generator-plugin
|
Apache License 2.0
|
app/src/main/java/es/dam/pi/vinilaapp_v3/viewmodel/PhotosViewModel.kt
|
ptrdck
| 815,297,387
| false
|
{"Kotlin": 199701, "JavaScript": 1824}
|
package es.dam.pi.vinilaapp_v3.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.ktx.storage
import es.dam.pi.vinilaapp_v3.R
import es.dam.pi.vinilaapp_v3.data.api.ApiService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
class PhotosViewModel(private val apiService: ApiService) : ViewModel() {
private val _photos = MutableStateFlow<List<Any>>(emptyList())
val photos: StateFlow<List<Any>> = _photos
init {
fetchPhotos()
}
private fun fetchPhotos() {
viewModelScope.launch {
val storageReference = Firebase.storage.reference.child("aboutus")
val localPhotos = listOf(
R.drawable.vinilos1,
R.drawable.vinilos2,
R.drawable.vinilos3
)
try {
val remotePhotos = mutableListOf<String>()
val result = storageReference.listAll().await()
for (fileRef in result.items) {
val url = fileRef.downloadUrl.await().toString()
remotePhotos.add(url)
}
_photos.value = localPhotos + remotePhotos
} catch (e: Exception) {
_photos.value = localPhotos // En caso de error, solo se cargan las fotos locales
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
279319fa596dca86bf61271ba6906de6fe7187ce
| 1,529
|
VinilApp_release
|
MIT License
|
src/main/kotlin/io/github/hootisman/StickMain.kt
|
hootisman
| 714,118,356
| false
|
{"Kotlin": 32501, "Java": 7985}
|
package io.github.hootisman
import io.github.hootisman.block.StickBlocks
import io.github.hootisman.entity.StickEntities
import io.github.hootisman.item.StickItems
import io.github.hootisman.network.StickServerPackets
import io.github.hootisman.network.ShiftDownC2SPacket
import net.fabricmc.api.ModInitializer
import org.slf4j.LoggerFactory
object StickMain : ModInitializer {
const val MOD_ID: String = "stick"
private val logger = LoggerFactory.getLogger(MOD_ID)
override fun onInitialize() {
// This code runs as soon as Minecraft is in a mod-load-ready state.
// However, some things (like resources) may still be uninitialized.
// Proceed with mild caution.
logger.info("Hello Fabric world!")
StickItems.addItems()
StickEntities.addEntityTypes()
StickBlocks.addBlocks()
StickServerPackets.registerPacket(ShiftDownC2SPacket.handler)
}
}
| 0
|
Kotlin
|
0
| 0
|
41755b4810bcce82faeed5d559ec5ccfb38b6da6
| 868
|
Stick
|
Creative Commons Zero v1.0 Universal
|
archive/114/solve.kt
|
daniellionel01
| 435,306,139
| false
| null |
/*
=== #114 Counting block combinations I - Project Euler ===
A row measuring seven units in length has red blocks with a minimum length of three units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one grey square. There are exactly seventeen ways of doing this.
How many ways can a row measuring fifty units in length be filled?
NOTE: Although the example above does not lend itself to the possibility, in general it is permitted to mix block sizes. For example, on a row measuring eight units in length you could use red (3), grey (1), and red (4).
Difficulty rating: 35%
*/
fun solve(x: Int): Int {
return x*2;
}
fun main() {
val a = solve(10);
println("solution: $a");
}
| 0
|
Kotlin
|
0
| 1
|
1ad6a549a0a420ac04906cfa86d99d8c612056f6
| 753
|
euler
|
MIT License
|
shared/src/commonMain/kotlin/io/github/edwinchang24/shengjidisplay/components/SuitPicker.kt
|
EdwinChang24
| 770,688,696
| false
|
{"Kotlin": 161507, "JavaScript": 1109, "HTML": 235}
|
package io.github.edwinchang24.shengjidisplay.components
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import io.github.edwinchang24.shengjidisplay.interaction.PressableWithEmphasis
import io.github.edwinchang24.shengjidisplay.model.Suit
import org.jetbrains.compose.resources.painterResource
@Composable
fun SuitPicker(suit: Suit?, setSuit: (Suit) -> Unit, modifier: Modifier = Modifier) {
Row(horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = modifier) {
Suit.entries.forEach {
PressableWithEmphasis {
OutlinedCard(
onClick = { setSuit(it) },
border =
BorderStroke(
width =
animateDpAsState(
targetValue =
if (suit == it) 4.dp
else CardDefaults.outlinedCardBorder().width,
label = "",
)
.value,
color =
if (suit == it) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.outlineVariant,
),
interactionSource = interactionSource,
modifier = Modifier.weight(1f),
) {
Image(
painterResource(it.icon),
null,
modifier =
Modifier.pressEmphasis()
.padding(16.dp)
.size(32.dp)
.align(Alignment.CenterHorizontally),
)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
00a021b103b8e14f24fc2b59dd074b0171df3bf1
| 2,573
|
sheng-ji-display
|
MIT License
|
library/games/src/main/kotlin/xyz/fcampbell/rxplayservices/games/RxGamesMetadata.kt
|
francoiscampbell
| 75,945,848
| true
| null |
package xyz.fcampbell.rxplayservices.games
import android.content.Context
import com.google.android.gms.common.api.Scope
import com.google.android.gms.games.Game
import com.google.android.gms.games.Games
import com.google.android.gms.games.GamesMetadata
import io.reactivex.Observable
import xyz.fcampbell.rxplayservices.base.ApiClientDescriptor
import xyz.fcampbell.rxplayservices.base.ApiDescriptor
import xyz.fcampbell.rxplayservices.base.RxPlayServicesApi
/**
* Wraps [Games.GamesMetadata]
*/
@Suppress("unused")
class RxGamesMetadata(
apiClientDescriptor: ApiClientDescriptor,
gamesOptions: Games.GamesOptions,
vararg scopes: Scope
) : RxPlayServicesApi<GamesMetadata, Games.GamesOptions>(
apiClientDescriptor,
ApiDescriptor(Games.API, Games.GamesMetadata, gamesOptions, *scopes)
) {
constructor(
context: Context,
gamesOptions: Games.GamesOptions,
vararg scopes: Scope
) : this(ApiClientDescriptor(context), gamesOptions, *scopes)
fun getCurrentGame(): Observable<Game> {
return map { getCurrentGame(it) }
}
fun loadGame(): Observable<GamesMetadata.LoadGamesResult> {
return fromPendingResult { loadGame(it) }
}
}
| 1
|
Kotlin
|
2
| 10
|
b7461e4534a81d78f7bf70a6047395b059e61c3c
| 1,241
|
RxPlayServices
|
Apache License 2.0
|
app/src/main/java/com/qisan/wanandroid/entity/Tag.kt
|
Jeremyzwc
| 493,134,082
| false
|
{"Kotlin": 298769}
|
package com.qisan.wanandroid.entity
import com.google.gson.annotations.SerializedName
/**
* Created by qisan 2022/5/27
* com.qisan.wanandroid.entity
*/
data class Tag(
@SerializedName("name") val name: String,
@SerializedName("url") val url: String
)
| 0
|
Kotlin
|
11
| 74
|
785edb5d407fb845fbeab049e3f8542e6fc7cdce
| 264
|
WanAndroidAppKotlinMVVM
|
Apache License 2.0
|
src/main/kotlin/com/sergiosusa/steamtradingcardshelper/model/Cards.kt
|
sergiosusa
| 555,746,356
| false
| null |
package com.sergiosusa.steamtradingcardshelper.model
class Cards(
val id: Int,
val title: String,
val own: Int,
val classId: String,
) {
}
| 0
|
Kotlin
|
0
| 0
|
db983c638447d0655cf947b372cdf36413f68778
| 156
|
steam-trading-cards-helper
|
MIT License
|
app/src/main/java/com/scudderapps/moviesup/viewmodel/CastDetailViewModel.kt
|
m-scudder
| 252,821,750
| false
|
{"Kotlin": 293411}
|
package com.scudderapps.moviesup.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.scudderapps.moviesup.models.common.MovieCredits
import com.scudderapps.moviesup.models.common.TvCredits
import com.scudderapps.moviesup.models.main.PeopleDetails
import com.scudderapps.moviesup.models.main.PeopleImages
import com.scudderapps.moviesup.repository.cast.CastDetailRepository
import io.reactivex.disposables.CompositeDisposable
class CastDetailViewModel(
private val peopleDetailRepository: CastDetailRepository,
peopleId: Int
) :
ViewModel() {
private val compositeDisposable = CompositeDisposable()
val peopleDetails: LiveData<PeopleDetails> by lazy {
peopleDetailRepository.fetchingPeoplesDetails(compositeDisposable, peopleId)
}
val movieCredits: LiveData<MovieCredits> by lazy {
peopleDetailRepository.fetchingMovieCredits(compositeDisposable, peopleId)
}
val peopleImages: LiveData<PeopleImages> by lazy {
peopleDetailRepository.fetchingPeopleImages(compositeDisposable, peopleId)
}
val tvCredits : LiveData<TvCredits> by lazy {
peopleDetailRepository.fetchingTvCredits(compositeDisposable, peopleId)
}
override fun onCleared() {
super.onCleared()
compositeDisposable.dispose()
}
}
| 0
|
Kotlin
|
1
| 2
|
000f1539946ad0298f53252464de90bcfe238c83
| 1,338
|
MovieTime
|
MIT License
|
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/query/settings/QueryProcessorsListener.kt
|
rhdunn
| 62,201,764
| false
| null |
/*
* Copyright (C) 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.processor.query.settings
import uk.co.reecedunn.intellij.plugin.processor.query.QueryProcessorSettings
import java.util.*
interface QueryProcessorsListener : EventListener {
fun onAddProcessor(processor: QueryProcessorSettings)
fun onEditProcessor(index: Int, processor: QueryProcessorSettings)
fun onRemoveProcessor(index: Int)
}
| 47
|
Kotlin
|
4
| 25
|
d363dad28df1eb17c815a821c87b4f15d2b30343
| 977
|
xquery-intellij-plugin
|
Apache License 2.0
|
app/src/main/java/com/sdss/workout/program/RepeatProgramSetup.kt
|
charmas3r
| 374,553,434
| true
|
{"Kotlin": 182117, "Swift": 21514, "Ruby": 2200, "HTML": 560}
|
package com.sdss.workout.program
import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.sdss.workout.R
import com.sdss.workout.drawer.DrawerItems
import com.sdss.workout.ui.buttons.DropdownMenuItemContent
import com.sdss.workout.ui.buttons.PrimaryDropdownMenu
@Composable
fun RepeatProgramSetupScreen(navController: NavController?) {
ProgramSetupTemplate(
primaryBtnTitle = stringResource(id = R.string.programs_finish_btn),
onPrimaryClick = {
navController?.navigate(DrawerItems.Home.route) {
popUpTo(DrawerItems.Home.route)
}
}
) {
RepeatProgramSetupLayout()
}
}
@Composable
fun RepeatProgramSetupLayout() {
Column(Modifier.padding(16.dp)) {
Text(text = stringResource(id = R.string.programs_repeat_title))
Spacer(modifier = Modifier.height(8.dp))
Row {
PrimaryDropdownMenu(
items = dropDownItems(),
menuModifier = Modifier.width(120.dp),
firstItemModifier = Modifier
.height(60.dp)
.padding(start = 16.dp, top = 32.dp)
)
}
}
}
private fun dropDownItems(): List<DropdownMenuItemContent> {
return listOf(
DropdownMenuItemContent(
isFirstPosition = true,
titleRes = R.string.programs_no_repeat,
onClick = {
Log.d("DropdownMenu", "menu item clicked")
}
),
DropdownMenuItemContent(
isFirstPosition = false,
titleRes = R.string.programs_repeats_one_time,
onClick = {
Log.d("DropdownMenu", "menu item clicked")
},
),
DropdownMenuItemContent(
isFirstPosition = false,
titleRes = R.string.programs_repeat_two_times,
onClick = {
Log.d("DropdownMenu", "menu item clicked")
},
),
DropdownMenuItemContent(
isFirstPosition = false,
titleRes = R.string.programs_repeat_three_times,
onClick = {
Log.d("DropdownMenu", "menu item clicked")
},
),
DropdownMenuItemContent(
isFirstPosition = false,
titleRes = R.string.programs_repeat_four_times,
onClick = {
Log.d("DropdownMenu", "menu item clicked")
},
)
)
}
| 0
|
Kotlin
|
0
| 0
|
946c3deb810fdc01d5738457b2322457f6f08071
| 2,704
|
WorkoutApp
|
Apache License 2.0
|
app/src/main/java/com/androidtraining/personalrutineapp/entity/Gender.kt
|
jiahaoliuliu
| 219,960,665
| true
|
{"Kotlin": 8864}
|
package com.androidtraining.personalrutineapp.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
import io.reactivex.annotations.NonNull
@Entity
data class Gender(
@PrimaryKey(autoGenerate = true)
@NonNull
val id: Int? = null,
val name: String)
| 0
|
Kotlin
|
0
| 0
|
c1c4a1de23b2a15a18e0bc3a16e3b19a6de44d8e
| 294
|
PersonalRutineApp
|
Apache License 2.0
|
src/main/java/com/aillen/shopmall/module/card/Card.kt
|
anlonglong
| 138,116,731
| false
|
{"Kotlin": 234110, "HTML": 390}
|
package com.aillen.shopmall.module.card
import cn.bmob.v3.BmobObject
/**
* Created by anlonglong on 2018/6/6.
* Email: <EMAIL>
*/
data class Card(var S_OID:String?,
var card_money:String?,
var store_name:String,
var img_url:String?,
var endTime:String?,
var type:Int?):BmobObject()
enum class Type(val type:Int){
TYPE_COMMON(0x00),
TYPE_SPECIA(0X01),
TYPE_NEW(0X02);
}
| 0
|
Kotlin
|
2
| 2
|
6ceafeca69702605c08a04957c57ab66bff01d08
| 465
|
ShopMall
|
Apache License 2.0
|
core/src/jvmMain/kotlin/info/laht/threekt/textures/CubeTexture.kt
|
jonike
| 199,983,331
| true
|
{"Kotlin": 581556, "GLSL": 105344}
|
package info.laht.threekt.textures
class CubeTexture: Texture()
| 0
|
Kotlin
|
0
| 0
|
6704a3cea0e5d754304f945929bb4a257a5be6bd
| 64
|
three.kt
|
MIT License
|
app/src/main/kotlin/me/sweetll/tucao/rxdownload/entity/DownloadMission.kt
|
blackbbc
| 78,953,199
| false
|
{"Java": 836993, "Kotlin": 528146, "Makefile": 3468}
|
package me.sweetll.tucao.rxdownload.entity
import android.annotation.SuppressLint
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.sweetll.tucao.extension.sumByLong
import me.sweetll.tucao.rxdownload.db.TucaoDatabase
@Entity(tableName = "DownloadMission")
data class DownloadMission(
var hid: String = "",
var order: Int = 0,
var title: String = "",
var type: String = "",
@PrimaryKey var vid: String = ""
) {
@TypeConverters(BeanListConverter::class)
var beans: MutableList<DownloadBean> = mutableListOf()
@Transient
var request: Disposable? = null
var pause: Boolean = true
val taskName: String
get() = "$title/p$order"
val downloadLength: Long
get() = beans.sumByLong { it.downloadLength }
val contentLength: Long
get() = beans.sumByLong { it.contentLength }
@SuppressLint("CheckResult")
fun exec(execs: (DownloadMissionDao.() -> Unit)) {
Observable.create<Any> {
TucaoDatabase.db.missionDao().execs()
}.subscribeOn(Schedulers.io())
}
}
| 13
|
Java
|
204
| 1,016
|
35fe73f11b10d63f482a1fc819ac4cadec72d8c9
| 1,239
|
Tucao
|
MIT License
|
src/main/kotlin/me/peckb/aoc/_2023/calendar/day02/Day02.kt
|
peckb1
| 433,943,215
| false
|
{"Kotlin": 956123}
|
package me.peckb.aoc._2023.calendar.day02
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import kotlin.math.max
class Day02 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::game) { games ->
val maxRed = 12
val maxGreen = 13
val maxBlue = 14
games.filter { game ->
game.rounds.none { round ->
round.red > maxRed || round.blue > maxBlue || round.green > maxGreen
}
}.sumOf { it.id }
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::game) { games ->
games.sumOf { game ->
var minRequiredRed = 0
var minRequiredBlue = 0
var minRequiredGreen = 0
game.rounds.forEach { round ->
minRequiredRed = max(minRequiredRed, round.red)
minRequiredBlue = max(minRequiredBlue, round.blue)
minRequiredGreen = max(minRequiredGreen, round.green)
}
minRequiredRed * minRequiredGreen * minRequiredBlue
}
}
private fun game(line: String): Game {
val (gameIdString, roundData) = line.split(": ")
val id = gameIdString.split(" ").last().toInt()
val roundStrings = roundData.split("; ")
val rounds = roundStrings.map { roundInformation ->
var red = 0
var blue = 0
var green = 0
roundInformation.split(", ")
.forEach { colourInformation ->
val (count, colour) = colourInformation.split(" ")
when (colour) {
"red" -> red = count.toInt()
"blue" -> blue = count.toInt()
"green" -> green = count.toInt()
}
}
Round(red, green, blue)
}
return Game(id, rounds)
}
data class Game(val id: Int, val rounds: List<Round>)
data class Round(val red: Int, val green: Int, val blue: Int)
}
| 0
|
Kotlin
|
1
| 3
|
732eaf95804825a542c1cbddbc55053383f9127b
| 1,905
|
advent-of-code
|
MIT License
|
src/main/kotlin/com/npwork/localise/CacheConfig.kt
|
npwork
| 235,997,538
| false
| null |
package com.npwork.localise
import java.time.temporal.ChronoUnit
// Java 8 can't conver
data class CacheConfig(val file: String,
val duration: Long = 10,
val unit: ChronoUnit = ChronoUnit.MINUTES)
| 0
|
Kotlin
|
0
| 1
|
a917773f94656a024d3415bbfb1a935c8f46d5ad
| 245
|
kotlin-localise
|
Apache License 2.0
|
app/src/main/java/com/example/myapplication/ui/onboarding/OnboardingAdapterDelegates.kt
|
neckbosov
| 406,866,009
| false
|
{"Kotlin": 76693}
|
package com.example.myapplication.ui.onboarding
import com.example.myapplication.databinding.ItemOnboardingTextBinding
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
fun onboardingTextAdapterDelegate() =
adapterDelegateViewBinding<String, CharSequence, ItemOnboardingTextBinding>(
viewBinding = { layoutInflater, parent ->
ItemOnboardingTextBinding.inflate(layoutInflater, parent, false)
},
block = {
bind {
binding.textView.text = item
}
}
)
| 1
|
Kotlin
|
0
| 1
|
443d5aeec757f9cb41bf87f04c682aa9e7a50149
| 564
|
spbu-2021-mobile-development
|
MIT License
|
app/src/main/java/com/illu/demo/ui/mine/rank/minepoints/MinePointsActivity.kt
|
mosquitoxiang
| 624,018,018
| false
| null |
//package com.illu.demo.ui.mine.rank.minepoints
//
//import androidx.appcompat.app.AppCompatActivity
//import android.os.Bundle
//import android.view.LayoutInflater
//import android.view.View
//import androidx.core.view.isVisible
//import androidx.lifecycle.Observer
//import com.illu.demo.R
//import com.illu.demo.base.BaseVmActivity
//import com.illu.demo.common.loadmore.CommonLoadMoreView
//import com.illu.demo.common.loadmore.LoadMoreStatus
//import kotlinx.android.synthetic.main.activity_mine_points.*
//import kotlinx.android.synthetic.main.header_mine_points.view.*
//
//class MinePointsActivity : BaseVmActivity<MinePointsViewModel>() {
//
// private lateinit var mAdapter: MinePointsAdapter
// private lateinit var mHeaderView: View
//
// override fun viewModelClass(): Class<MinePointsViewModel> = MinePointsViewModel::class.java
//
// override fun getLayoutId(): Int = R.layout.activity_mine_points
//
// override fun initView() {
// titleBar.setOnTitleBarListener(this)
// mHeaderView = LayoutInflater.from(this).inflate(R.layout.header_mine_points, null)
// mAdapter = MinePointsAdapter().apply {
// bindToRecyclerView(rv)
// setLoadMoreView(CommonLoadMoreView())
// setOnLoadMoreListener({
// mViewModel.loadMore()
// }, rv)
// }
// swipeRefreshLayout.run {
// setColorSchemeResources(R.color.textColorPrimary)
// setProgressBackgroundColorSchemeResource(R.color.bgColorPrimary)
// setOnRefreshListener { mViewModel.refreshData() }
// }
// reloadView.setOnClickListener {
// mViewModel.refreshData()
// }
// }
//
// override fun initData() {
// mViewModel.refreshData()
// }
//
// override fun observer() {
// super.observer()
// mViewModel.run {
// refreshStatus.observe(this@MinePointsActivity, Observer {
// swipeRefreshLayout.isRefreshing = it
// })
// loadMoreStatus.observe(this@MinePointsActivity, Observer {
// when (it) {
// LoadMoreStatus.COMPLETED -> mAdapter.loadMoreComplete()
// LoadMoreStatus.END -> mAdapter.loadMoreEnd()
// LoadMoreStatus.ERROR -> mAdapter.loadMoreFail()
// else -> return@Observer
// }
// })
// reloadStatus.observe(this@MinePointsActivity, Observer {
// reloadView.isVisible = it
// })
// minePoints.observe(this@MinePointsActivity, Observer {
// if (mAdapter.headerLayoutCount == 0) {
// mAdapter.setHeaderView(mHeaderView)
// }
// mHeaderView.tvTotalPoints.text = it.coinCount.toString()
// mHeaderView.tvLevelRank.text = getString(R.string.level_rank, it.level, it.rank)
// })
// minePointsList.observe(this@MinePointsActivity, Observer {
// mAdapter.setNewData(it)
// })
// }
// }
//
//}
| 0
|
Kotlin
|
0
| 0
|
f426367fb3d129889ebd323bf9b0339605b8caf5
| 3,101
|
wanandroid-compose
|
Apache License 2.0
|
ui/src/main/kotlin/com/magical/ui/utils/StatusBarUtils.kt
|
raedev
| 523,271,921
| false
|
{"Kotlin": 44785}
|
package com.magical.ui.utils
import android.app.Activity
/**
* 状态栏工具
* @author RAE
* @date 2022/10/18
* @copyright Copyright (c) https://github.com/raedev All rights reserved.
*/
object StatusBarUtils {
/**
* 设置状态栏为黑色字体和图标
*/
fun setStatusBarLightMode(activity: Activity) {
}
}
| 0
|
Kotlin
|
0
| 0
|
45b39463bb41bb197f00ce543d9dbb9eaabacb08
| 307
|
MagicalUI
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/plcoding/EXRTComposeMultiplatform/profile/presentaion/TabNavigationActivity.kt
|
TDICK7
| 711,635,145
| false
|
{"Kotlin": 48259, "Swift": 817, "Shell": 228}
|
package com.plcoding.EXRTComposeMultiplatform.profile.presentaion
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import cafe.adriel.voyager.core.annotation.ExperimentalVoyagerApi
import cafe.adriel.voyager.navigator.tab.CurrentTab
import cafe.adriel.voyager.navigator.tab.LocalTabNavigator
import cafe.adriel.voyager.navigator.tab.Tab
import cafe.adriel.voyager.navigator.tab.TabDisposable
import cafe.adriel.voyager.navigator.tab.TabNavigator
import com.plcoding.EXRTComposeMultiplatform.profile.domain.BottomNavigationItem
import com.plcoding.EXRTComposeMultiplatform.profile.presentaion.tabs.LeaderboardTab
import com.plcoding.EXRTComposeMultiplatform.profile.presentaion.tabs.ProfileTab
import com.plcoding.EXRTComposeMultiplatform.profile.presentaion.tabs.WorkoutTab
class TabNavigationActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Content()
}
}
@OptIn(ExperimentalVoyagerApi::class, ExperimentalMaterial3Api::class)
@Composable
fun Content() {
TabNavigator(
ProfileTab,
tabDisposable = {
TabDisposable(
navigator = it,
tabs = listOf(ProfileTab, LeaderboardTab, WorkoutTab)
)
}
) { tabNavigator ->
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = tabNavigator.current.options.title) }
)
},
content = {
CurrentTab()
},
bottomBar = {
BottomAppBar {
TabNavigationItem(ProfileTab)
}
}
)
}
}
@Composable
private fun RowScope.TabNavigationItem(tab: Tab) {
val tabNavigator = LocalTabNavigator.current
BottomNavigationItem(
title = "BottomAppItem",
hasNews = true,
selectedIcon = tabNavigator.current.key == tab.key,
)
}
}
| 2
|
Kotlin
|
0
| 0
|
9fda375504ba95777669d853b9519f7988c12825
| 2,469
|
EXRT
|
Apache License 2.0
|
src/main/kotlin/ChatTheSpire/command/TreasureChestOpenCommand.kt
|
FylmTM
| 246,153,979
| false
| null |
package ChatTheSpire.command
import ChatTheSpire.util.Automation
import ChatTheSpire.util.Job
import ChatTheSpire.util.SafeSpire
import ChatTheSpire.util.SpireInternals
import com.megacrit.cardcrawl.rooms.TreasureRoom
import com.megacrit.cardcrawl.rooms.TreasureRoomBoss
import org.apache.logging.log4j.LogManager
private val logger = LogManager.getLogger(TreasureChestOpenCommand::class.java.name)
object TreasureChestOpenCommand : Command {
override val prefix: String = "t"
override val syntax: String = "t - open treasure chest"
override fun execute(parameters: List<Int>, doAction: Boolean): Boolean {
if (parameters.isNotEmpty()) {
logger.info("Parameters are not supported")
return false
}
val chest = when (val room = SafeSpire.room) {
is TreasureRoom -> room.chest
is TreasureRoomBoss -> room.chest
else -> null
}
if (chest == null) {
logger.info("We are not in treasure room")
return false
}
if (chest.isOpen) {
logger.info("Chest is already open")
return false
}
val hb = SpireInternals.chestHitbox(chest)
if (doAction) {
Job.execute {
hb?.let {
Automation.click(hb)
Automation.rest()
}
}
}
return true
}
}
| 0
|
Kotlin
|
0
| 0
|
898f415a1d9f2a20d8d91bd89ff7b3f1bf7cf53d
| 1,444
|
ChatTheSpire
|
MIT License
|
src/main/kotlin/de/doctari/kotlinTutorial/kotlinxSerialization/slide_01.kt
|
doctariDev
| 454,115,767
| false
|
{"Kotlin": 104723}
|
package de.doctari.kotlinTutorial.kotlinxSerialization
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
/* **************************************************************************************
* **************************************************************************************
*
* ᐅ @Serializable makes custom (data) classes serializable
* ᐅ custom enum/sealed by default
* ᐅ built-in primitive types, String and Collections types by default
* ᐅ use serialization API for de/serializing: encodeToString / encodeToStream ...
* ᐅ choose between formats JSON, CBOR, protocol buffers, ...
*
* **************************************************************************************
* ************************************************************************************** */
@Serializable
data class Dog(val name: String, val age: Int)
fun main() {
val dog1 = Dog("Spark", 4)
val json = Json.encodeToString(dog1)
println("The dog is \n\t $dog1")
println("Its json is \n\t $json")
val dog2: Dog = Json.decodeFromString(json)
println("The deserialized dog is \n\t $dog2")
}
| 0
|
Kotlin
|
0
| 1
|
00594b25490c54d75e0496dd58078a24fc5da3cc
| 1,235
|
kotlin-tutorials
|
Apache License 2.0
|
lib/src/main/kotlin/com/ibm/cloud/appconfiguration/android/sdk/configurations/ConfigurationUpdateListener.kt
|
IBM
| 329,794,175
| false
| null |
/**
* Copyright 2021 IBM Corp. All Rights Reserved.
*
* 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.ibm.cloud.appconfiguration.android.sdk.configurations
// Listener for the client app
interface ConfigurationUpdateListener {
// This method will be called when latest configurations are fetched from the server
fun onConfigurationUpdate()
}
| 0
|
Kotlin
|
3
| 0
|
5da29b0c71f9d56f99414aeceb55dbe26b8b883e
| 877
|
appconfiguration-android-client-sdk
|
Apache License 2.0
|
src/test/kotlin/com/resnik/profile/TestProfile.kt
|
mtresnik
| 389,679,744
| false
| null |
package com.resnik.profile
import com.resnik.math.linear.array.ArrayPoint2d
import com.resnik.math.plot.Plot2d
import org.junit.Ignore
import org.junit.Test
import javax.swing.ImageIcon
import javax.swing.JLabel
import javax.swing.JOptionPane
class TestProfile {
@Ignore
@Test
fun test1() {
val profiler = NovelProfiler(threshold=0)
profiler.init()
var a = 5000
for(i in 0..a){
repeat(a - i){
println("i:$i")
}
profiler.record()
}
println(profiler.getStamps().size)
val points = profiler.getStamps().mapIndexed{x, y ->
ArrayPoint2d(x.toDouble(), (y - profiler.init).toDouble())
}.toMutableList()
val plot2d = Plot2d()
plot2d.add(points)
val image = plot2d.plot(drawPoints = false)
val icon = ImageIcon(image)
val label = JLabel(icon)
JOptionPane.showMessageDialog(null, label)
}
}
| 0
|
Kotlin
|
0
| 0
|
ee65a8c3589524fa642d657ff0e5dcde587c9de9
| 976
|
math
|
Apache License 2.0
|
scripts/src/main/java/io/github/fate_grand_automata/scripts/models/EnemyTarget.kt
|
ArthurKun21
| 743,056,546
| false
|
{"Kotlin": 1454408}
|
package io.github.fate_grand_automata.scripts.models
sealed class EnemyTarget(
val autoSkillCode: Char,
) {
data object A3 : EnemyTarget('1')
data object B3 : EnemyTarget('2')
data object C3 : EnemyTarget('3')
// 6 enemy formation
data object A6 : EnemyTarget('4')
data object B6 : EnemyTarget('5')
data object C6 : EnemyTarget('6')
data object D6 : EnemyTarget('7')
data object E6 : EnemyTarget('8')
data object F6 : EnemyTarget('9')
// Raid
data object RaidBoss : EnemyTarget('R')
data object RaidMinion1 : EnemyTarget('X')
data object RaidMinion2 : EnemyTarget('Y')
data object RaidMinion3 : EnemyTarget('Z')
companion object {
val list by lazy {
listOf(
A3, B3, C3,
A6, B6, C6, D6, E6, F6,
RaidBoss, RaidMinion1, RaidMinion2, RaidMinion3
)
}
val autoTargetList by lazy {
listOf(
A3, B3, C3,
A6, B6, C6, D6, E6, F6,
)
}
val threeEnemyFormationList by lazy {
listOf(
A3, B3, C3
)
}
val sixEnemyFormationCharList by lazy {
listOf(
A6.autoSkillCode, B6.autoSkillCode, C6.autoSkillCode,
D6.autoSkillCode, E6.autoSkillCode, F6.autoSkillCode
)
}
val raidFormationCharList by lazy {
listOf(
RaidBoss.autoSkillCode,
RaidMinion1.autoSkillCode, RaidMinion2.autoSkillCode, RaidMinion3.autoSkillCode
)
}
}
}
enum class EnemyFormation(val enabled: Boolean = true) {
THREE,
SIX,
RAID(false)
}
| 22
|
Kotlin
|
0
| 1
|
049fdfc02c85c0cb2cd4d9507a02e4faa4df7137
| 1,743
|
FGA-Preview
|
MIT License
|
zipline/src/hostMain/kotlin/app/cash/zipline/internal/EventListenerAdapter.kt
|
cashapp
| 41,445,081
| false
|
{"C": 2214152, "Kotlin": 1352475, "C++": 39612, "Shell": 1471, "CMake": 871, "JavaScript": 313}
|
/*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline.internal
import app.cash.zipline.Call
import app.cash.zipline.CallResult
import app.cash.zipline.EventListener
import app.cash.zipline.Zipline
import app.cash.zipline.ZiplineService
import app.cash.zipline.internal.bridge.Endpoint
/** Adapts the endpoint listener to add a constant Zipline parameter. */
internal class EventListenerAdapter(
val delegate: EventListener,
val zipline: Zipline,
) : Endpoint.EventListener() {
override fun bindService(name: String, service: ZiplineService) {
delegate.bindService(zipline, name, service)
}
override fun takeService(name: String, service: ZiplineService) {
delegate.takeService(zipline, name, service)
}
override fun serviceLeaked(name: String) {
delegate.serviceLeaked(zipline, name)
}
override fun callStart(call: Call): Any? {
return delegate.callStart(zipline, call)
}
override fun callEnd(call: Call, result: CallResult, startValue: Any?) {
delegate.callEnd(zipline, call, result, startValue)
}
}
| 83
|
C
|
154
| 2,043
|
e7ad22ac5110a20686035b616aef190814472d19
| 1,623
|
zipline
|
Apache License 2.0
|
app/src/main/java/com/ehayvan/app/modules/launchscreen/data/model/LaunchScreenModel.kt
|
E-Hayvan
| 729,275,618
| false
|
{"Kotlin": 74911}
|
package com.ehayvan.app.modules.launchscreen.`data`.model
import com.ehayvan.app.R
import com.ehayvan.app.appcomponents.di.MyApp
import kotlin.String
data class LaunchScreenModel(
/**
* TODO Replace with dynamic value
*/
var txtLanguage: String? = MyApp.getInstance().resources.getString(R.string.lbl_e_h_yv_n)
)
| 0
|
Kotlin
|
0
| 0
|
5966d27f1bcadf876f51bec47ad5923691b3b833
| 326
|
e_hayvan_android
|
MIT License
|
mvrx/src/test/kotlin/com/airbnb/mvrx/TestMvRxActivity.kt
|
luozejiaqun
| 157,853,404
| true
|
{"Kotlin": 141016, "Java": 140}
|
package com.airbnb.mvrx
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
open class TestMvRxActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.Theme_AppCompat_NoActionBar)
}
}
| 0
|
Kotlin
|
0
| 2
|
68957133773ca8d32bfa5ff6438b7862cacf28f1
| 312
|
DiMvRx
|
Apache License 2.0
|
src/main/kotlin/com/marcoeckstein/binance/api/client/prvt/account/AssetBalance.kt
|
marco-eckstein
| 340,113,530
| false
|
{"Kotlin": 161467}
|
@file:UseSerializers(BigDecimalAsPlainStringSerializer::class)
package com.marcoeckstein.binance.api.client.prvt.account
import com.marcoeckstein.binance.api.lib.jvm.BigDecimalAsPlainStringSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import java.math.BigDecimal
@Serializable
data class AssetBalance(
val asset: String,
val free: BigDecimal,
val locked: BigDecimal,
// More properties omitted
)
| 0
|
Kotlin
|
3
| 3
|
caa883355bc10946cb137bcc806d75a9003d32b2
| 466
|
binance-api-kotlin
|
MIT License
|
app/src/test/java/sample/study/happytwitter/presentation/usertweets/finduser/FindUserViewModelTest.kt
|
andretortolano
| 146,738,903
| false
| null |
package sample.study.happytwitter.presentation.usertweets.finduser
import com.nhaarman.mockito_kotlin.any
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.observers.TestObserver
import okhttp3.MediaType
import okhttp3.ResponseBody
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
import retrofit2.HttpException
import retrofit2.Response
import sample.study.happytwitter.base.network.NetworkingViewState
import sample.study.happytwitter.base.network.NetworkingViewState.Error
import sample.study.happytwitter.data.twitter.ITwitterRepo
import sample.study.happytwitter.data.twitter.TwitterUser
import sample.study.happytwitter.presentation.usertweets.finduser.FindUserViewState.Companion.ERROR_USER_DISABLED
import sample.study.happytwitter.presentation.usertweets.finduser.FindUserViewState.Companion.ERROR_USER_NOT_FOUND
import sample.study.happytwitter.utils.schedulers.ISchedulerProvider
import sample.study.happytwitter.utils.schedulers.MockSchedulerProvider
@RunWith(MockitoJUnitRunner::class)
class FindUserViewModelTest {
@Mock
private lateinit var twitterRepository: ITwitterRepo
private lateinit var schedulerProvider: ISchedulerProvider
private lateinit var viewModel: FindUserViewModel
private lateinit var testObserver: TestObserver<FindUserViewState>
private val lastPosition
get() = testObserver.values().lastIndex
private val validUser = TwitterUser(1, "valid user", "valid", "valid description", "", "", "")
@Before
fun before() {
schedulerProvider = MockSchedulerProvider()
viewModel = FindUserViewModel(twitterRepository, schedulerProvider)
testObserver = viewModel.states()
.test()
}
@Test
fun `Initial ViewState`() {
testObserver.assertValueAt(lastPosition, FindUserViewState(null, false, NetworkingViewState.Idle))
}
@Test
fun `SearchUserAction - Verify Searching will emit`() {
`when`(twitterRepository.getUser(any())).thenReturn(Observable.just(validUser))
viewModel.actions(Observable.just(FindUserAction.SearchUserAction("username")))
testObserver.assertValueAt(lastPosition - 1) { viewState -> viewState.searchUserNetworking == NetworkingViewState.Loading }
testObserver.assertValueAt(lastPosition) { viewState -> viewState.searchUserNetworking != NetworkingViewState.Loading }
}
@Test
fun `SearchUserAction - Success`() {
`when`(twitterRepository.getUser(any())).thenReturn(Observable.just(validUser))
viewModel.actions(Observable.just(FindUserAction.SearchUserAction("username")))
testObserver.assertValueAt(lastPosition, FindUserViewState(validUser, false, NetworkingViewState.Success))
}
@Test
fun `SearchUserAction - UserNotFound`() {
val response =
Response.error<Void>(404, ResponseBody.create(MediaType.parse(""), "{\"errors\": [{\"code\":50, \"message\": \"User not found.\"}]}"))
`when`(twitterRepository.getUser(any())).thenReturn(Observable.error(HttpException(response)))
viewModel.actions(Observable.just(FindUserAction.SearchUserAction("username")))
testObserver.assertValueAt(lastPosition) { state -> (state.searchUserNetworking as Error).errorMessage == ERROR_USER_NOT_FOUND }
}
@Test
fun `SearchUserAction - UserDisabled`() {
val response =
Response.error<Void>(402, ResponseBody.create(MediaType.parse(""), "{\"errors\": [{\"code\":63, \"message\": \"User not found.\"}]}"))
`when`(twitterRepository.getUser(any())).thenReturn(Observable.error(HttpException(response)))
viewModel.actions(Observable.just(FindUserAction.SearchUserAction("username")))
testObserver.assertValueAt(lastPosition) { state -> (state.searchUserNetworking as Error).errorMessage == ERROR_USER_DISABLED }
}
@Test
fun `ChangeUserAction - not empty`() {
viewModel.actions(Observable.just(FindUserAction.ChangeUserAction("a")))
testObserver.assertValueAt(lastPosition, FindUserViewState(isUserNameValid = true))
}
@Test
fun `ChangeUserAction - empty`() {
viewModel.actions(Observable.just(FindUserAction.ChangeUserAction("")))
testObserver.assertValueAt(lastPosition, FindUserViewState(isUserNameValid = false))
}
}
| 4
|
Kotlin
|
2
| 1
|
1e5ae5de3806091c684f08f642a5276a0d246575
| 4,299
|
happytwitter
|
Apache License 2.0
|
app/src/main/java/cz/ikem/dci/zscanner/screen_message/PatientAdapter.kt
|
ikem-cz
| 183,602,578
| false
| null |
package cz.ikem.dci.zscanner.screen_message
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import cz.ikem.dci.zscanner.R
import cz.ikem.dci.zscanner.webservices.HttpClient
import cz.ikem.dci.zscanner.webservices.Patient
import kotlinx.android.synthetic.main.patient_suggestion_row.view.*
class PatientAdapter(private val mContext: Context, val mViewModel: CreateMessageViewModel) : BaseAdapter(), Filterable {
private val TAG = PatientAdapter::class.java.simpleName
var mSuggestions: List<Patient> = listOf()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var view: View?
view = if (convertView == null) {
val inflater: LayoutInflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.patient_suggestion_row, parent, false)!!
} else {
convertView
}
view.suggestion_name_textview.text = mSuggestions[position].name
view.suggestion_bid_textview.text = mSuggestions[position].bid
return view
}
override fun getItem(position: Int): Patient {
return mSuggestions[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return mSuggestions.size
}
private val mFilter: Filter = object : Filter() {
private var lastFilteredConstraint : String = ""
override fun performFiltering(constraint: CharSequence?): Filter.FilterResults {
lastFilteredConstraint = constraint.toString()
mViewModel.loadingSuggestions.postValue(true)
mViewModel.tooManySuggestions.postValue(false)
try {
val filterResults = Filter.FilterResults()
if (constraint != null) {
val response = HttpClient().getApiServiceBackend().searchPatients(constraint.toString()).execute()
// Assign the data to the FilterResults
filterResults.values = response.body()!!
filterResults.count = response.body()!!.count()
}
return filterResults
} catch (e: Exception) {
return Filter.FilterResults()
}
}
override fun publishResults(constraint: CharSequence?, results: Filter.FilterResults?) {
if (constraint.toString() == lastFilteredConstraint) {
mViewModel.loadingSuggestions.postValue(false)
if (((constraint != null) && (constraint.toString().length >= 3)) && (results == null || results.count == 0)) { // if above completion threshold and cannot suggest anything
mViewModel.noSuggestions.postValue(true)
} else {
mViewModel.noSuggestions.postValue(false)
}
if ((results != null) && (results.count > 15)) {
mViewModel.tooManySuggestions.postValue(true)
} else {
mViewModel.tooManySuggestions.postValue(false)
}
}
if (results != null && results.count > 0) {
mSuggestions = results.values as List<Patient>
notifyDataSetChanged()
} else {
notifyDataSetInvalidated()
}
}
}
override fun getFilter(): Filter {
return mFilter
}
}
| 1
|
Kotlin
|
0
| 2
|
c1a5d7a449f3fed3da429bda154428ecdb4a8d42
| 3,720
|
zscanner-android
|
MIT License
|
app/src/main/java/eu/caraus/appsflastfm/data/remote/lastFm/LastFmApiKeyInterceptor.kt
|
alexandrucaraus
| 144,028,779
| false
|
{"Kotlin": 202701}
|
package eu.caraus.appsflastfm.data.remote.lastFm
import okhttp3.Interceptor
import okhttp3.Response
class LastFmApiKeyInterceptor( private val apiKey : String) : Interceptor {
companion object {
const val LAST_FM_API_KEY = "<KEY>"
}
override fun intercept( chain: Interceptor.Chain?) : Response {
val httpUrl = chain?.request()?.url()?.newBuilder()?.
addQueryParameter("api_key", apiKey )?.
addQueryParameter("format","json")?.
build()
val request = chain?.request()?.newBuilder()?.url( httpUrl!!)?.build()
return chain?.proceed( request!!)!!
}
}
| 0
|
Kotlin
|
0
| 0
|
fb9b4a218fa4c09b23b253eb75ee62456b4b47ff
| 686
|
ShowCase-AppsFactoryLastFmMvp
|
MIT License
|
src/main/kotlin/com/pineypiney/game_engine/level_editor/util/KeyBinds.kt
|
PineyPiney
| 491,900,499
| false
|
{"Kotlin": 619793, "GLSL": 26595}
|
package com.pineypiney.game_engine.level_editor.util
import com.pineypiney.game_engine.level_editor.PixelEngine
import com.pineypiney.game_engine.util.ResourceKey
import com.pineypiney.game_engine.util.extension_functions.getOrNull
import com.pineypiney.game_engine.util.input.ControlType
import org.lwjgl.glfw.GLFW
class KeyBinds {
companion object{
private val defaultKeyBinds: Map<ResourceKey, KeyBind> = mapOf(
ResourceKey("key/left") to KeyBind(GLFW.GLFW_KEY_A),
ResourceKey("key/right") to KeyBind(GLFW.GLFW_KEY_D),
ResourceKey("key/sprint") to KeyBind(GLFW.GLFW_KEY_LEFT_SHIFT),
ResourceKey("key/jump") to KeyBind(GLFW.GLFW_KEY_SPACE),
ResourceKey("key/primary") to KeyBind(GLFW.GLFW_MOUSE_BUTTON_1, ControlType.MOUSE),
ResourceKey("key/secondary") to KeyBind(GLFW.GLFW_MOUSE_BUTTON_2, ControlType.MOUSE),
ResourceKey("key/attack") to KeyBind(GLFW.GLFW_MOUSE_BUTTON_1, ControlType.MOUSE),
ResourceKey("key/fullscreen") to KeyBind(GLFW.GLFW_KEY_F),
)
val keyBinds: MutableMap<ResourceKey, KeyBind> = defaultKeyBinds.toMutableMap()
fun isActive(id: ResourceKey): Boolean{
val bind = keyBinds.getOrNull(id) ?: return false
return bind.state > 0
}
fun setKeyBind(key: ResourceKey, bind: KeyBind){
if(keyBinds[key] != null) keyBinds[key] = bind
else{
PixelEngine.logger.info("There is no keybinding for $key")
}
}
@Throws(NoSuchElementException::class)
fun getKeyBinding(key: ResourceKey): KeyBind {
return keyBinds[key] ?: defaultKeyBinds[key] ?:
throw NoSuchElementException("There is no key registered for $key")
}
fun getKeyBindingForKey(key: Short, type: ControlType): KeyBind?{
return keyBinds.values.firstOrNull { bind -> bind.key == key && bind.controlType == type }
}
}
}
| 0
|
Kotlin
|
0
| 0
|
74c81a1c5fc742f99896cc74a5bc3eca6113447c
| 2,006
|
GameEngine
|
MIT License
|
src/main/kotlin/com/criteo/gradle/findjars/FindJarsPlugin.kt
|
criteo
| 167,344,257
| false
| null |
package com.criteo.gradle.findjars
import org.gradle.api.Plugin
import org.gradle.api.Project
open class FindJarsPlugin : Plugin<Project> {
override fun apply(project: Project) {
with(project.tasks) {
create("findJars", FindJarsTask::class.java) {
it.description = "Find jars in a given configuration."
it.group = "debug"
}
}
}
}
| 1
|
Kotlin
|
6
| 44
|
b62504f0037edd8eb451a21818085184f6757b72
| 412
|
findjars
|
Apache License 2.0
|
Healthcare-app/android/MDBRealmDoctor/app/src/main/java/com/wekanmdb/storeinventory/model/embededclass/Codable_Concept.kt
|
realm
| 422,284,529
| false
|
{"Kotlin": 966534, "Swift": 867269, "Objective-C": 232478, "TypeScript": 75527, "JavaScript": 32651, "HTML": 2365, "Ruby": 2276, "Less": 31}
|
package com.wekanmdb.storeinventory.model.embededclass
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.RealmClass
import io.realm.annotations.Required
@RealmClass(embedded = true)
open class Codable_Concept (
var coding: RealmList<Coding> = RealmList(),
var text: String? = null
) : RealmObject() {}
| 0
|
Kotlin
|
1
| 8
|
e57077e2c26a75db4e80dd40909f12dca4a431e0
| 344
|
realm-sync-demos
|
Apache License 2.0
|
Healthcare-app/android/MDBRealmDoctor/app/src/main/java/com/wekanmdb/storeinventory/model/embededclass/Codable_Concept.kt
|
realm
| 422,284,529
| false
|
{"Kotlin": 966534, "Swift": 867269, "Objective-C": 232478, "TypeScript": 75527, "JavaScript": 32651, "HTML": 2365, "Ruby": 2276, "Less": 31}
|
package com.wekanmdb.storeinventory.model.embededclass
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.RealmClass
import io.realm.annotations.Required
@RealmClass(embedded = true)
open class Codable_Concept (
var coding: RealmList<Coding> = RealmList(),
var text: String? = null
) : RealmObject() {}
| 0
|
Kotlin
|
1
| 8
|
e57077e2c26a75db4e80dd40909f12dca4a431e0
| 344
|
realm-sync-demos
|
Apache License 2.0
|
app/src/main/java/com/breezebppoddar/features/survey/api/SurveyDataProvider.kt
|
DebashisINT
| 518,335,697
| false
|
{"Kotlin": 14689181, "Java": 1021110}
|
package com.breezebppoddar.features.survey.api
import com.breezebppoddar.features.photoReg.api.GetUserListPhotoRegApi
import com.breezebppoddar.features.photoReg.api.GetUserListPhotoRegRepository
object SurveyDataProvider{
fun provideSurveyQ(): SurveyDataRepository {
return SurveyDataRepository(SurveyDataApi.create())
}
fun provideSurveyQMultiP(): SurveyDataRepository {
return SurveyDataRepository(SurveyDataApi.createImage())
}
}
| 0
|
Kotlin
|
0
| 0
|
297531612f36f84abcf33edf6809dacc55c3ac99
| 469
|
BPPODDARHOSPITAL
|
Apache License 2.0
|
android/src/oldarch/AiSpec.kt
|
szymonrybczak
| 831,019,305
| false
|
{"Objective-C++": 16011, "TypeScript": 9410, "Objective-C": 4474, "Ruby": 3291, "JavaScript": 2844, "Kotlin": 2214, "C": 103, "Swift": 54}
|
package com.ai
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.Promise
abstract class AiSpec internal constructor(context: ReactApplicationContext) :
ReactContextBaseJavaModule(context) {
abstract fun multiply(a: Double, b: Double, promise: Promise)
}
| 1
|
Objective-C++
|
2
| 34
|
01f3a17061800d2bcd61a77564a15d5c2c0af9e5
| 361
|
react-native-ai
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.