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
llama-stack-client-kotlin-core/src/test/kotlin/com/llama_stack_client/api/models/AgentsStepTest.kt
meta-llama
854,913,926
false
{"Kotlin": 2020773, "Shell": 2562}
// File generated from our OpenAPI spec by Stainless. package com.llama_stack_client.api.models import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class AgentsStepTest { @Test fun createAgentsStep() { val agentsStep = AgentsStep.builder() .step( AgentsStep.Step.ofInferenceStep( InferenceStep.builder() .modelResponse( CompletionMessage.builder() .content(CompletionMessage.Content.ofString("string")) .role(CompletionMessage.Role.ASSISTANT) .stopReason(CompletionMessage.StopReason.END_OF_TURN) .toolCalls( listOf( ToolCall.builder() .arguments(ToolCall.Arguments.builder().build()) .callId("call_id") .toolName( ToolCall.ToolName.ofBuiltinTool( ToolCall.ToolName.BuiltinTool.BRAVE_SEARCH ) ) .build() ) ) .build() ) .stepId("step_id") .stepType(InferenceStep.StepType.INFERENCE) .turnId("turn_id") .completedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .startedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .build() ) ) .build() assertThat(agentsStep).isNotNull assertThat(agentsStep.step()) .isEqualTo( AgentsStep.Step.ofInferenceStep( InferenceStep.builder() .modelResponse( CompletionMessage.builder() .content(CompletionMessage.Content.ofString("string")) .role(CompletionMessage.Role.ASSISTANT) .stopReason(CompletionMessage.StopReason.END_OF_TURN) .toolCalls( listOf( ToolCall.builder() .arguments(ToolCall.Arguments.builder().build()) .callId("call_id") .toolName( ToolCall.ToolName.ofBuiltinTool( ToolCall.ToolName.BuiltinTool.BRAVE_SEARCH ) ) .build() ) ) .build() ) .stepId("step_id") .stepType(InferenceStep.StepType.INFERENCE) .turnId("turn_id") .completedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .startedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .build() ) ) } }
0
Kotlin
2
0
ee76c5aec1d582dbbd2759d084ba16b8b74f04ea
3,909
llama-stack-client-kotlin
Apache License 2.0
db-test/src/test/kotlin/org/d7z/test/list/ListContextTest.kt
d7z-team
458,437,220
false
{"Kotlin": 86837, "Java": 987}
package org.d7z.test.list import org.d7z.test.testList import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class ListContextTest { companion object { private const val TEST_KEY = "DATA" } @Test fun get() { testList { this.drop(TEST_KEY) assertTrue(get(TEST_KEY, String::class).isEmpty) getOrCreate(TEST_KEY, String::class) { "data" }.apply { assertTrue(get(TEST_KEY, String::class).isPresent) remove(0) } assertTrue(get(TEST_KEY, String::class).isEmpty) drop(TEST_KEY) assertTrue(get(TEST_KEY, String::class).isEmpty) } } @Test fun getOrCreate() { testList { this.drop(TEST_KEY) assertTrue(get(TEST_KEY, String::class).isEmpty) getOrCreate(TEST_KEY, String::class) { "data" } assertTrue(get(TEST_KEY, String::class).isPresent) drop(TEST_KEY) assertTrue(get(TEST_KEY, String::class).isEmpty) } } @Test fun drop() { testList { this.drop(TEST_KEY) assertTrue(get(TEST_KEY, String::class).isEmpty) getOrCreate(TEST_KEY, String::class) { "data" } assertTrue(get(TEST_KEY, String::class).isPresent) drop(TEST_KEY) assertTrue(get(TEST_KEY, String::class).isEmpty) } } @Test fun exists() { testList { this.drop(TEST_KEY) assertTrue(get(TEST_KEY, String::class).isEmpty) getOrCreate(TEST_KEY, String::class) { "data" } assertTrue(get(TEST_KEY, String::class).isPresent) drop(TEST_KEY) assertFalse(exists(TEST_KEY)) } } }
0
Kotlin
0
0
54eff37823b55ff7060a5d8af998b69ca1ff34e2
1,863
light-db
MIT License
api/src/main/kotlin/net/devslash/FetchDsl.kt
sshkel
377,373,840
true
{"Kotlin": 85801}
package net.devslash import net.devslash.err.RetryOnTransitiveError import java.time.Duration @DslMarker annotation class FetchDSL enum class HttpMethod { GET, POST, DELETE, PUT, HEAD, OPTIONS, PATCH } class UnaryAddBuilder<T> { private var hooks = mutableListOf<T>() operator fun T.unaryPlus() { hooks = (hooks + this).toMutableList() } fun build(): MutableList<T> { return hooks } } data class RateLimitOptions(val enabled: Boolean, val count: Int, val duration: Duration) @FetchDSL open class CallBuilder<T>(private val url: String) { private var cookieJar: String? = null var urlProvider: URLProvider? = null var data: RequestDataSupplier<T>? = null var body: HttpBody? = null var type: HttpMethod = HttpMethod.GET var headers: Map<String, List<Any>>? = null var onError: OnError? = RetryOnTransitiveError() private var preHooksList = mutableListOf<BeforeHook>() private var postHooksList = mutableListOf<AfterHook>() fun before(block: UnaryAddBuilder<BeforeHook>.() -> Unit) { preHooksList.addAll(UnaryAddBuilder<BeforeHook>().apply(block).build()) } fun after(block: UnaryAddBuilder<AfterHook>.() -> Unit) { postHooksList.addAll(UnaryAddBuilder<AfterHook>().apply(block).build()) } fun body(block: BodyBuilder.() -> Unit) { body = BodyBuilder().apply(block).build() } private fun mapHeaders(m: Map<String, List<Any>>?): Map<String, List<Value>>? { return m?.let { map -> map.map { entry -> entry.key to entry.value.map { value -> when (value) { is String -> StrValue(value) is Value -> value else -> throw RuntimeException() } } }.toMap() } } fun build(): Call<T> { val localHeaders = headers if (localHeaders == null || !localHeaders.contains("User-Agent")) { val set = mutableMapOf<String, List<Any>>() if (localHeaders != null) { set.putAll(localHeaders) } set["User-Agent"] = listOf("FetchDSL (Apache-HttpAsyncClient + Kotlin, version not set)") headers = set } return Call( url, urlProvider, mapHeaders(headers), cookieJar, type, data, body, onError, preHooksList, postHooksList ) } } fun replaceString(changes: Map<String, String>, str: String): String { var x = str changes.forEach { x = x.replace(it.key, it.value) } return x } typealias ValueMapper<V> = (V, RequestData) -> V val identityValueMapper: ValueMapper<String> = { v, _ -> v } val indexValueMapper: ValueMapper<String> = { inData, reqData -> val indexes = reqData.mustGet<List<String>>().mapIndexed { index, string -> "!" + (index + 1) + "!" to string }.toMap() inData.let { entry -> return@let replaceString(indexes, entry) } } @FetchDSL class BodyBuilder { private var value: String? = null private var valueMapper: ValueMapper<String>? = null private var formParts: List<FormPart>? = null private var lazyMultipartForm: ((RequestData) -> List<FormPart>)? = null private var formParams: Form? = null private var formMapper: ValueMapper<Map<String, List<String>>>? = null var jsonObject: Any? = null var lazyJsonObject: ((RequestData) -> Any)? = null // This is actually used. The receiver ensures that only the basic case can utilise a non mapped // function @Suppress("unused") fun BodyBuilder.formParams(params: Map<String, List<String>>) { formParams = params formMapper = formIndexed } fun formParams( params: Map<String, List<String>>, mapper: ValueMapper<Map<String, List<String>>> = formIdentity ) { formParams = params formMapper = mapper } @Suppress("unused") fun multipartForm( parts: List<FormPart> ) { this.formParts = parts; } fun multipartForm( lazyForm: RequestData.() -> List<FormPart> ) { this.lazyMultipartForm = lazyForm } @Suppress("unused") fun BodyBuilder.value(value: String) { this.value = value this.valueMapper = identityValueMapper } @Suppress("unused") fun value(value: String, mapper: (String, RequestData) -> String) { this.value = value this.valueMapper = mapper } fun build(): HttpBody { return HttpBody( value, valueMapper, formParams, formMapper, formParts, lazyMultipartForm, jsonObject, lazyJsonObject ) } } @FetchDSL class MultiCallBuilder { private var calls = mutableListOf<Call<*>>() fun <T> call(url: String, block: CallBuilder<T>.() -> Unit = {}) { calls.add(CallBuilder<T>(url).apply(block).build()) } fun calls() = calls } @FetchDSL class SessionBuilder { private var calls = mutableListOf<Call<*>>() private val chained = mutableListOf<List<Call<*>>>() var concurrency = 20 var delay: Long? = null var rateOptions: RateLimitOptions = RateLimitOptions(false, 0, Duration.ZERO) fun rateLimit(count: Int, duration: Duration) { require(!(duration.isNegative || duration.isZero)) { "Invalid duration, must be more than zero" } require(count > 0) { "Count must be positive" } rateOptions = RateLimitOptions(true, count, duration) } @JvmName("genericCall") fun <T> call(url: String, block: CallBuilder<T>.() -> Unit = {}) { calls.add(CallBuilder<T>(url).apply(block).build()) } fun call(url: String, block: CallBuilder<List<String>>.() -> Unit = {}) { calls.add(CallBuilder<List<String>>(url).apply(block).build()) } // TODO: Re-enable when chaining is stable // fun chained(block: MultiCallBuilder.(prev: Previous?) -> Unit = {}) { // if (chained.isNotEmpty()) { // val line = chained.last().line // // } // chained.add(MultiCallBuilder().apply(block).calls()) // } fun build(): Session = Session(calls, concurrency, delay, rateOptions) }
0
null
0
0
e6ca03983e4e13d54211ea9e21f04f0c8bf9cd4c
5,805
fetchDSL
MIT License
employee-directory/app/src/main/java/work/wander/directory/framework/logging/AppLogger.kt
awallace87
793,807,511
false
{"Kotlin": 642774}
package work.wander.directory.framework.logging import android.util.Log import javax.inject.Inject /** * Interface for application logging. * * This interface provides methods for logging messages at different priority levels. * The default priority level is DEBUG. * * @see log for logging a message with a specific priority level. * @see debug for logging a debug message. * @see info for logging an info message. * @see warn for logging a warning message. * @see error for logging an error message. */ interface AppLogger { fun log(priority: Int = Log.DEBUG, message: String) fun log(priority: Int = Log.DEBUG, throwable: Throwable, message: String) fun debug(message: String) = log(Log.DEBUG, message) fun debug(throwable: Throwable, message: String) = log(Log.DEBUG, throwable, message) fun info(message: String) = log(Log.INFO, message) fun info(throwable: Throwable, message: String) = log(Log.INFO, throwable, message) fun warn(message: String) = log(Log.WARN, message) fun warn(throwable: Throwable, message: String) = log(Log.WARN, throwable, message) fun error(message: String) = log(Log.ERROR, message) fun error(throwable: Throwable, message: String) = log(Log.ERROR, throwable, message) } /** * Logger implementation that uses the Android Log class for logging messages. * * This class implements the AppLogger interface and uses the Android Log class to log messages at different priority levels. * The tag for each log message is determined by the class name of the caller. * * @see log for logging a message with a specific priority level. * @see log for logging a message with a specific priority level and a throwable. */ class SystemAppLogger @Inject constructor() : AppLogger { override fun log(priority: Int, message: String) { Log.println(priority, getTagFromCaller(), message) } override fun log(priority: Int, throwable: Throwable, message: String) { Log.println(priority, getTagFromCaller(), "$message\n${Log.getStackTraceString(throwable)}") } companion object { fun getTagFromCaller(): String { val stackTrace = Thread.currentThread().stackTrace // TODO should define better search for caller val caller = stackTrace[4] return caller.className.substringAfterLast('.') } } }
0
Kotlin
0
0
8e9dfa2a66f8a330c6c26a10bad78420f818beeb
2,371
android-sample-apps
Apache License 2.0
app/src/main/java/io/outblock/lilico/page/wallet/WalletFragment.kt
Outblock
435,317,689
false
null
package io.outblock.lilico.page.wallet import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.ActivityResultLauncher import androidx.lifecycle.ViewModelProvider import com.journeyapps.barcodescanner.ScanOptions import com.zackratos.ultimatebarx.ultimatebarx.statusBarHeight import io.outblock.lilico.base.fragment.BaseFragment import io.outblock.lilico.databinding.FragmentWalletBinding import io.outblock.lilico.page.scan.dispatchScanResult import io.outblock.lilico.page.wallet.model.WalletFragmentModel import io.outblock.lilico.page.wallet.presenter.WalletFragmentPresenter import io.outblock.lilico.page.wallet.presenter.WalletHeaderPlaceholderPresenter import io.outblock.lilico.page.wallet.presenter.WalletHeaderPresenter import io.outblock.lilico.utils.launch import io.outblock.lilico.utils.registerBarcodeLauncher class WalletFragment : BaseFragment() { private lateinit var binding: FragmentWalletBinding private lateinit var viewModel: WalletFragmentViewModel private lateinit var presenter: WalletFragmentPresenter private lateinit var headerPresenter: WalletHeaderPresenter private lateinit var headerPlaceholderPresenter: WalletHeaderPlaceholderPresenter private lateinit var barcodeLauncher: ActivityResultLauncher<ScanOptions> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) barcodeLauncher = registerBarcodeLauncher { result -> dispatchScanResult(requireContext(), result.orEmpty()) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentWalletBinding.inflate(inflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { with(binding.root) { setPadding(0, statusBarHeight, 0, 0) } presenter = WalletFragmentPresenter(this, binding) headerPresenter = WalletHeaderPresenter(binding.walletHeader.root) headerPlaceholderPresenter = WalletHeaderPlaceholderPresenter(binding.shimmerPlaceHolder.root) binding.scanButton.setOnClickListener { barcodeLauncher.launch() } viewModel = ViewModelProvider(requireActivity())[WalletFragmentViewModel::class.java].apply { dataListLiveData.observe(viewLifecycleOwner) { presenter.bind(WalletFragmentModel(data = it)) } headerLiveData.observe(viewLifecycleOwner) { headerModel -> headerPresenter.bind(headerModel) headerPlaceholderPresenter.bind(headerModel == null) } } } override fun onResume() { super.onResume() viewModel.load() } }
6
Kotlin
0
2
3be43a8f7c36680f99dc157fe589358728963055
2,777
Lilico-Android
Apache License 2.0
kzmq-cio/src/commonMain/kotlin/org/zeromq/CIO.kt
ptitjes
386,722,015
false
null
/* * Copyright (c) 2021-2022 <NAME> and Kzmq contributors. * Use of this source code is governed by the Apache 2.0 license. */ package org.zeromq public expect object CIO : EngineFactory
21
Kotlin
0
6
1e6c7a35b7dc93b34a8f6da9d56fd5b3335dd790
192
kzmq
Apache License 2.0
src/testData/jvm/expression/destructure/destructure1/Main.kt
XYZboom
767,934,164
false
{"Kotlin": 1295388, "Java": 27485}
class Target { /*<target:int>*/fun component1(): Any { return 123 }/*<target:int/>*/ /*<target:str>*/fun component2(): String { return "comp2" }/*<target:str/>*/ } fun func() { val (/*<source:int>*/int/*<source:int/>*/, /*<source:str>*/str/*<source:str/>*/) = Target(1, "123") }
0
Kotlin
1
0
47dfb26629b3d0a596f51747b04b32622aace7d3
315
psi-reference-extractor
Apache License 2.0
src/main/kotlin/com/lss233/minidb/engine/memory/internal/catalog/AttributeView.kt
lss233
535,925,912
false
null
package com.lss233.minidb.engine.memory.internal.catalog import com.lss233.minidb.engine.memory.Database import com.lss233.minidb.engine.schema.Column import miniDB.parser.ast.fragment.ddl.datatype.DataType class AttributeView(database: Database): PostgresCatalogView(database) { override fun getColumns(): MutableList<Column> = mutableListOf( Column("attrelid", DataType.DataTypeName.INT), Column("attname", DataType.DataTypeName.CHAR), Column("atttypid", DataType.DataTypeName.INT), Column("attstattarget", DataType.DataTypeName.CHAR), Column("attlen", DataType.DataTypeName.CHAR), Column("attnum", DataType.DataTypeName.CHAR), Column("attndims", DataType.DataTypeName.CHAR), Column("attcacheoff", DataType.DataTypeName.CHAR), Column("attbyval", DataType.DataTypeName.CHAR) ) override fun generateData(): MutableList<Array<Any>> = mutableListOf() }
1
null
3
12
8ab3d263e57c61a648856aae269b474201746294
921
MiniDB
MIT License
android/app/src/main/java/com/example/myapplication/ui/listeners/OnChartDateChange.kt
Ozilele
689,018,294
false
{"Kotlin": 98486, "HTML": 144, "Assembly": 27}
package com.example.myapplication.ui.listeners import com.example.myapplication.data.FilterType interface OnChartDateChange { fun onChartDateClick(filterType: FilterType) }
0
Kotlin
0
0
812c583674f35644ccd6c763ee56624043b2ac36
176
StockApp
Apache License 2.0
app/src/main/java/com/migualador/cocktails/presentation/animation_extensions/AnimationExtensions.kt
migualador
719,969,621
false
{"Kotlin": 113009}
package com.migualador.cocktails.presentation.animation_extensions import android.view.View import android.view.animation.AlphaAnimation import android.view.animation.Animation fun View.animateFadeOut() { val animation = AlphaAnimation(1.0f, 0.0f).apply { duration = 200 } animation.setAnimationListener(object: Animation.AnimationListener { override fun onAnimationStart(p0: Animation?) {} override fun onAnimationEnd(p0: Animation?) { this@animateFadeOut.visibility = View.GONE } override fun onAnimationRepeat(p0: Animation?) {} }) this.startAnimation(animation) } fun View.animateDelayedFadeIn() { val animation = AlphaAnimation(0.0f, 1.0f).apply { duration = 200 startOffset = 200 } animation.setAnimationListener(object: Animation.AnimationListener { override fun onAnimationStart(p0: Animation?) { this@animateDelayedFadeIn.visibility = View.VISIBLE } override fun onAnimationEnd(p0: Animation?) {} override fun onAnimationRepeat(p0: Animation?) {} }) this.startAnimation(animation) }
0
Kotlin
0
0
9936484c1a9404d97a93814d2274af6cc20e5315
1,150
android-kotlin-mvvm-architecture
Apache License 2.0
foryouandme/src/main/java/com/foryouandme/domain/usecase/configuration/GetConfigurationUseCase.kt
4YouandMeData
610,425,317
false
null
package com.foryouandme.domain.usecase.configuration import com.foryouandme.domain.policy.Policy import com.foryouandme.domain.policy.Policy.LocalFirst import com.foryouandme.domain.policy.Policy.Network import com.foryouandme.domain.usecase.study.GetStudyUseCase import com.foryouandme.entity.configuration.Configuration import javax.inject.Inject class GetConfigurationUseCase @Inject constructor( private val repository: ConfigurationRepository, private val getStudyUseCase: GetStudyUseCase ) { suspend operator fun invoke(policy: Policy): Configuration = when (policy) { Network -> { repository.fetchConfiguration(getStudyUseCase().phases) .also { repository.saveConfiguration(it) } } LocalFirst -> repository.loadConfiguration() ?: invoke(Network) } }
0
Kotlin
0
0
bc82972689db5052344365ac07c8f6711f5ad7fa
860
4YouandMeAndroid
MIT License
entertainment-lib/src/test/java/de/eso/rxplayer/AudioImplTest.kt
yuriykulikov
158,669,220
false
null
package de.eso.rxplayer import io.reactivex.schedulers.TestScheduler import org.assertj.core.api.Assertions.assertThat import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class AudioImplTest { private val scheduler = TestScheduler() private val audio = AudioImpl(scheduler) @Test fun `all connections are initially stopped`() { Audio.Connection.values() .map { audio.observe(it).blockingFirst() } .let { assertThat(it) } .containsOnly(Audio.AudioState.STOPPED) } }
0
Kotlin
1
2
2e02a170b4aa9e27f10ab50b032aded33570b105
675
rxplayer
MIT License
module_mine/src/main/java/com/czl/module_mine/viewmodel/JobLearningViewModel.kt
pigletzzzzzz
516,985,475
false
{"Kotlin": 723880, "Java": 176802}
package com.czl.module_mine.viewmodel import androidx.databinding.ObservableField import com.czl.lib_base.base.BaseBean import com.czl.lib_base.base.BaseViewModel import com.czl.lib_base.base.MyApplication import com.czl.lib_base.binding.command.BindingAction import com.czl.lib_base.binding.command.BindingCommand import com.czl.lib_base.bus.event.SingleLiveEvent import com.czl.lib_base.data.DataRepository import com.czl.lib_base.data.bean.JobLearnItemBean import com.czl.lib_base.extension.ApiSubscriberHelper import com.czl.lib_base.util.RxThreadHelper /** * 联系邮箱 <EMAIL> * 创建时间: 20:29 * 描述: */ class JobLearningViewModel(application: MyApplication,model:DataRepository):BaseViewModel<DataRepository>(application, model) { var page = 2 var rows = 10 var pid = ObservableField("0") val uc = UiChangeEvent() class UiChangeEvent { var onJobLearnListEvent : SingleLiveEvent<List<JobLearnItemBean>> = SingleLiveEvent() } val onLoadMoreListener: BindingCommand<Void> = BindingCommand(BindingAction { return@BindingAction }) val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction { getJobLearnList() }) fun getJobLearnList(){ val map = mapOf<String, String>( "pid" to pid.get()!! ) model.getJobLearnList(map) .doOnSubscribe { showLoading() } .compose(RxThreadHelper.rxSchedulerHelper(this)) .subscribe(object : ApiSubscriberHelper<BaseBean<List<JobLearnItemBean>>>(){ override fun onResult(t: BaseBean<List<JobLearnItemBean>>) { dismissLoading() if (t.success == true) { if (t.data?.size!! > 0) { uc.onJobLearnListEvent.postValue(t.data) }else{ uc.onJobLearnListEvent.postValue(null) } } } override fun onFailed(msg: String?) { dismissLoading() uc.onJobLearnListEvent.postValue(null) } }) } }
0
Kotlin
0
0
a3276c0149c7d2d3284a6a4d83fa5cb3874664e9
2,175
XPZX-New_Kotlin
Apache License 2.0
feature-governance-impl/src/main/java/io/novafoundation/nova/feature_governance_impl/data/repository/v1/Gov1OffChainReferendaInfoRepository.kt
novasamatech
496,649,319
false
{"Kotlin": 5949531, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_governance_impl.data.repository.v1 import io.novafoundation.nova.common.utils.formatting.parseDateISO_8601 import io.novafoundation.nova.feature_governance_api.data.network.blockhain.model.ReferendumId import io.novafoundation.nova.feature_governance_api.data.network.offchain.model.referendum.OffChainReferendumDetails import io.novafoundation.nova.feature_governance_api.data.network.offchain.model.referendum.OffChainReferendumPreview import io.novafoundation.nova.feature_governance_api.data.repository.OffChainReferendaInfoRepository import io.novafoundation.nova.feature_governance_api.domain.referendum.details.ReferendumTimeline import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.PolkassemblyV1Api import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.request.ParachainReferendumDetailsRequest import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.request.ParachainReferendumPreviewRequest import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.request.ReferendumDetailsRequest import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.request.ReferendumPreviewRequest import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.response.ParachainReferendaPreviewResponse import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.response.ReferendaPreviewResponse import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.response.ReferendumDetailsResponse import io.novafoundation.nova.feature_governance_impl.data.offchain.v1.response.getId import io.novafoundation.nova.runtime.ext.externalApi import io.novafoundation.nova.runtime.multiNetwork.chain.model.Chain class Gov1OffChainReferendaInfoRepository( private val polkassemblyApi: PolkassemblyV1Api ) : OffChainReferendaInfoRepository { override suspend fun referendumPreviews(chain: Chain): List<OffChainReferendumPreview> = runCatching { val externalApi = chain.externalApi<Chain.ExternalApi.GovernanceReferenda>() ?: return emptyList() val polkassemblyNetwork = externalApi.source.network return if (polkassemblyNetwork == null) { referendaRelaychainRequest(externalApi.url) } else { referendaParachainRequest(externalApi.url, polkassemblyNetwork) } }.getOrDefault(emptyList()) private suspend fun referendaRelaychainRequest(url: String): List<OffChainReferendumPreview> { val request = ReferendumPreviewRequest() val response = polkassemblyApi.getReferendumPreviews(url, request) return response.data.posts.map { mapPolkassemblyPostToPreview(it) } } private suspend fun referendaParachainRequest(url: String, network: String): List<OffChainReferendumPreview> { val request = ParachainReferendumPreviewRequest(network) val response = polkassemblyApi.getParachainReferendumPreviews(url, request) return response.data.posts.map { mapParachainPolkassemblyPostToPreview(it) } } override suspend fun referendumDetails(referendumId: ReferendumId, chain: Chain): OffChainReferendumDetails? = runCatching { val externalApi = chain.externalApi<Chain.ExternalApi.GovernanceReferenda>() ?: return null val polkassemblyNetwork = externalApi.source.network val referendumDetails = if (polkassemblyNetwork == null) { detailsRelaychain(externalApi.url, referendumId) } else { detailsParachain(externalApi.url, polkassemblyNetwork, referendumId) } referendumDetails?.let(::mapPolkassemblyPostToDetails) }.getOrNull() private suspend fun detailsRelaychain(url: String, referendumId: ReferendumId): ReferendumDetailsResponse.Post? { val request = ReferendumDetailsRequest(referendumId.value) val response = polkassemblyApi.getReferendumDetails(url, request) return response.data.posts.firstOrNull() } private suspend fun detailsParachain(url: String, network: String, referendumId: ReferendumId): ReferendumDetailsResponse.Post? { val request = ParachainReferendumDetailsRequest(network, referendumId.value) val response = polkassemblyApi.getParachainReferendumDetails(url, request) return response.data.posts.firstOrNull() } private fun mapPolkassemblyPostToPreview(post: ReferendaPreviewResponse.Post): OffChainReferendumPreview { return OffChainReferendumPreview( post.title, ReferendumId(post.getId()), ) } private fun mapParachainPolkassemblyPostToPreview(post: ParachainReferendaPreviewResponse.Post): OffChainReferendumPreview { return OffChainReferendumPreview( post.title, ReferendumId(post.getId()), ) } private fun mapPolkassemblyPostToDetails(post: ReferendumDetailsResponse.Post): OffChainReferendumDetails { val timeline = post.onchainLink ?.onchainReferendum ?.getOrNull(0) ?.referendumStatus ?.map { mapReferendumStatusToTimelineEntry(it) } return OffChainReferendumDetails( title = post.title, description = post.content, proposerName = null, // author of the post on PA might not be equal to on-chain submitter so we want to be safe here proposerAddress = post.onchainLink?.proposerAddress, pastTimeline = timeline ) } private fun mapReferendumStatusToTimelineEntry(status: ReferendumDetailsResponse.Status): ReferendumTimeline.Entry { val timelineState = when (status.status) { "Started" -> ReferendumTimeline.State.CREATED "Passed" -> ReferendumTimeline.State.APPROVED "NotPassed" -> ReferendumTimeline.State.REJECTED "Executed" -> ReferendumTimeline.State.EXECUTED else -> error("Unkonown referendum status") } val statusDate = parseDateISO_8601(status.blockNumber.startDateTime) return ReferendumTimeline.Entry(timelineState, statusDate?.time) } }
5
Kotlin
9
28
fcd118ab5cbedded709ec062ae5d4bc890aaf96d
6,185
nova-android-app
Apache License 2.0
app/src/main/java/com/example/mytrainingpal/composables/TextIconWidget.kt
MichaelBuessemeyer
572,939,495
false
{"Kotlin": 256987}
package com.example.mytrainingpal.composables import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp @Composable fun TextIconWidget(text: String, imageVector: ImageVector) { WidgetCard(hasBorder = false) { Row(modifier = Modifier.wrapContentWidth()) { Text(text = text) Spacer(modifier = Modifier.width(5.dp)) Icon( imageVector = imageVector, contentDescription = "" ) } } }
14
Kotlin
0
2
5ef8c98c684bf2bb863dc6781a457c16ab8bb6e1
873
MyTrainingsPal
Apache License 2.0
core/src/commonMain/kotlin/work/socialhub/kslack/api/methods/SlackApiRequest.kt
uakihir0
794,979,552
false
{"Kotlin": 1320977, "Java": 9455, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
package com.github.seratch.jslack.api.methods /** * A marker interface for Slack API request objects. */ interface SlackApiRequest { val token: String? }
0
Kotlin
0
0
4d1299164adc8b8e638b02e0ca7e46afb10709f8
161
kslack
MIT License
app/src/main/java/com/andb/apps/weather/ui/common/PlaceholderOnLoading.kt
andyburris
229,464,194
false
{"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 71, "XML": 27}
package com.andb.apps.weather.ui.common import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import com.andb.apps.weather.ui.theme.onBackgroundDivider import com.google.accompanist.placeholder.PlaceholderHighlight import com.google.accompanist.placeholder.placeholder import com.google.accompanist.placeholder.shimmer fun Modifier.placeholderOnLoading( color: Color? = null, shape: Shape = CircleShape, highlight: PlaceholderHighlight? = PlaceholderHighlight.shimmer(Color.White.copy(alpha = 0.12f)), ) = composed { val isLoading = LocalIsLoading.current this.placeholder( visible = isLoading, color = color ?: MaterialTheme.colors.onBackgroundDivider, shape = shape, highlight = highlight, ) } val LocalIsLoading = compositionLocalOf { false } @Composable fun ProvideIsLoading(isLoading: Boolean = true, content: @Composable () -> Unit) { CompositionLocalProvider(LocalIsLoading provides isLoading) { content() } }
0
Kotlin
0
0
9428bd90c76af01564557a5f11b0a5c4caee59d4
1,345
Weather
MIT License
shared/src/commonMain/kotlin/App.kt
mamadou94Diop
683,034,694
false
{"Kotlin": 34023, "Ruby": 1790, "Swift": 653, "Shell": 228}
import androidx.compose.runtime.Composable import io.ktor.client.HttpClient import navigation.AppScaffold import theme.AppTheme @Composable fun App() { AppTheme { AppScaffold() } } expect fun getHttpClient() : HttpClient
0
Kotlin
0
0
cbe15318f0d7a41b87903a475813381658191fe5
237
restaurant-app-compose-multiplatform
Apache License 2.0
app/idcloudaccesssample/src/main/java/com/thalesgroup/gemalto/IdCloudAccessSample/viewmodels/AuthenticationViewModel.kt
ThalesGroup
564,335,825
false
null
package com.thalesgroup.gemalto.IdCloudAccessSample.viewmodels import androidx.lifecycle.ViewModel import com.thalesgroup.gemalto.IdCloudAccessSample.data.DataStoreRepo import com.thalesgroup.gemalto.IdCloudAccessSample.utilities.AUTH_TYPE import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.runBlocking import javax.inject.Inject @HiltViewModel class AuthenticationViewModel @Inject constructor( private val dataStoreRepository: DataStoreRepo, ) : ViewModel() { fun storeAuthenticationType(authType: Int) = runBlocking { dataStoreRepository.putInteger(AUTH_TYPE, authType) } fun getAuthenticationType(): Int? = runBlocking { dataStoreRepository.getInteger(AUTH_TYPE) } }
0
Kotlin
0
0
f78bd80cb9683bbdcfa4d8800356611ffb6d526e
737
idcloud-access-sample-android
Apache License 2.0
kotlintest-tests/kotlintest-tests-core/src/test/kotlin/com/sksamuel/kotlintest/data/DataDrivenTestingTest.kt
vinicri
156,184,572
true
{"Kotlin": 719237, "Java": 6857}
package com.sksamuel.kotlintest.data import io.kotlintest.data.forall import io.kotlintest.shouldBe import io.kotlintest.shouldThrow import io.kotlintest.specs.StringSpec import io.kotlintest.tables.row class DataDrivenTestingTest : StringSpec() { init { "square roots" { forall( row(2, 4), row(3, 9), row(4, 16), row(5, 25) ) { root, square -> root * root shouldBe square } } "maximum of two numbers" { forall( row(1, 5, 5), row(5, 1, 5), row(1, 1, 1), row(0, 1, 1), row(1, 0, 1), row(0, 0, 0) ) { a, b, max -> Math.max(a, b) shouldBe max } } "string concat" { forall( row("a", "b", "c", "abc"), row("hel", "lo wo", "rld", "hello world"), row("", "z", "", "z") ) { a, b, c, d -> a + b + c shouldBe d } } "row3 should detect header names from params" { shouldThrow<AssertionError> { forall( row(1, 2, 3) ) { foo, bar, woo -> foo * bar * woo shouldBe 0 } }.message shouldBe "Test failed for (foo, 1), (bar, 2), (woo, 3) with error expected: 0 but was: 6" } "row2 should detect header names from params" { shouldThrow<AssertionError> { forall( row(2, 4) ) { foo, bar -> foo * bar shouldBe 0 } }.message shouldBe "Test failed for (foo, 2), (bar, 4) with error expected: 0 but was: 8" } "row1 should detect header names from params" { shouldThrow<AssertionError> { forall( row(2) ) { foo -> foo shouldBe 0 } }.message shouldBe "Test failed for (foo, 2) with error expected: 0 but was: 2" } "row9 should detect header names from params" { shouldThrow<AssertionError> { forall( row(1, 2, 3, 4, 5, 6, 7, 8, 9) ) { foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9 -> foo1 shouldBe 0 } }.message shouldBe "Test failed for (foo1, 1), (foo2, 2), (foo3, 3), (foo4, 4), (foo5, 5), (foo6, 6), (foo7, 7), (foo8, 8), (foo9, 9) with error expected: 0 but was: 1" } "row10 should detect header names from params" { shouldThrow<AssertionError> { forall( row(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) { foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9, foo10 -> foo1 shouldBe 0 } }.message shouldBe "Test failed for (foo1, 1), (foo2, 2), (foo3, 3), (foo4, 4), (foo5, 5), (foo6, 6), (foo7, 7), (foo8, 8), (foo9, 9), (foo10, 10) with error expected: 0 but was: 1" } } }
0
Kotlin
0
1
cb82314ae7dfe0039f87c49698b3ba4bb008d516
2,724
kotlintest
Apache License 2.0
builder/src/commonMain/kotlin/pw/binom/builder/Table.kt
caffeine-mgn
196,877,393
false
null
package pw.binom.builder class Table { private val headers = ArrayList<String>() private val rows = ArrayList<List<String>>() private fun rowWidth(withHeader: Boolean, index: Int): Int { var max = 0 if (withHeader) max = headers[index].length rows.forEach { max = maxOf(max, it.getOrNull(index)?.length ?: 0) } return max } fun addHeader(name: String): Table { headers += name return this } fun row(vararg values: String) { rows.add(listOf(*values)) } fun print(withHeader: Boolean, out: Appendable) { val width = headers.mapIndexed { index, s -> rowWidth(withHeader, index) } if (withHeader) { headers.forEachIndexed { index, s -> if (index != 0) out.append(" │ ") out.append(s) if (index == headers.lastIndex) { println() } else out.printChar(' ', width[index] - s.length) } for (x in 0 until headers.size) { if (x != 0) out.append("─┼─") out.printChar('─', width[x]) if (x == headers.lastIndex) { println() } } } rows.forEachIndexed { rowIndex, row -> for (column in 0 until headers.size) { if (column != 0) out.append(" │ ") val item = row.getOrNull(column) if (item==null) { out.printChar(' ', width[column]) } else { out.append(row[column]) out.printChar(' ', width[column] - row[column].length) } if (column == headers.lastIndex) { out.append('\n') } } } } } private fun Appendable.printChar(char: Char, count: Int) { for (i in 0 until count) { append(char) } } object ConsoleAppendable : Appendable { override fun append(c: Char): Appendable { print(c) return this } override fun append(csq: CharSequence?): Appendable { print(csq) return this } override fun append(csq: CharSequence?, start: Int, end: Int): Appendable { csq ?: return this (start..end).forEach { append(csq[it]) } return this } }
0
Kotlin
0
0
139606a956de5fc41b8cc92243e7e5905fa8b147
2,539
Builder
Apache License 2.0
shared/src/commonMain/kotlin/repository/settings/SettingsModule.kt
rschattauer
747,667,420
false
{"Kotlin": 87325, "Swift": 6737, "Shell": 190}
package repository.settings import org.koin.dsl.module internal val settingsModule get() = module { single<Settings> { SettingsImpl(dataStore = get()) } }
0
Kotlin
0
2
21dbcf5d3d9e1f6e70f5e87ea432c80cbbf20e15
173
compose_multiplatform
Apache License 2.0
core/src/main/kotlin/org/hyrical/hcf/team/claim/listener/ClaimListener.kt
Hyrical
597,847,737
false
{"Kotlin": 323471, "Java": 30373}
package org.hyrical.hcf.team.claim.listener import com.cryptomorin.xseries.XMaterial import org.bukkit.Material import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.Action import org.bukkit.event.player.PlayerDropItemEvent import org.bukkit.event.player.PlayerInteractEvent import org.hyrical.hcf.team.TeamManager import org.hyrical.hcf.team.claim.LandGrid import org.hyrical.hcf.team.claim.cuboid.Cuboid import org.hyrical.hcf.team.claim.logic.ClaimProcessor import org.hyrical.hcf.utils.translate object ClaimListener : Listener { val claimWand = LandGrid.generateClaimItem() @EventHandler fun interact(event: PlayerInteractEvent) { val player = event.player; if (player.itemInHand.isSimilar(claimWand)) { val team = TeamManager.search(player.uniqueId) ?: return //left click (pos 1) if (event.action == Action.LEFT_CLICK_BLOCK) { if (event.clickedBlock == null) return event.isCancelled = true val claimSession: ClaimProcessor = LandGrid.pendingSession.getOrDefault(player.uniqueId, null) ?: return claimSession.location1 = event.clickedBlock!!.location player.sendMessage(translate("&aUpdated position 1 to &f(" + event.clickedBlock!!.location.blockX + ", " + event.clickedBlock!!.location.blockY + ", " + event.clickedBlock!!.location.blockZ + ")")) } //right click (pos 2) if (event.action == Action.RIGHT_CLICK_BLOCK) { if (event.clickedBlock == null) return event.isCancelled = true val claimSession: ClaimProcessor = LandGrid.pendingSession.getOrDefault(player.uniqueId, null) ?: return claimSession.location2 = event.clickedBlock!!.location player.sendMessage(translate("&aUpdated position 2 to &f(" + event.clickedBlock!!.location.blockX + ", " + event.clickedBlock!!.location.blockY + ", " + event.clickedBlock!!.location.blockZ + ")")) } //finalize if (event.action == Action.LEFT_CLICK_AIR && player.isSneaking) { event.isCancelled = true val claimSession: ClaimProcessor = LandGrid.pendingSession.getOrDefault(player.uniqueId, null) ?: return if (claimSession.location1 != null && claimSession.location2 != null) { val loc1 = claimSession.location1!!.clone() loc1.y = 256.0 val loc2 = claimSession.location2!!.clone() loc2.y = 0.0 //opposing world locations if (loc1.world != loc2.world) { player.sendMessage(translate("&cOne of your claim positions are not in the same word as the other!")) return } //land is occupied if (!LandGrid.playerCanClaim(loc1) || !LandGrid.playerCanClaim(loc2)) { player.sendMessage(translate("&cOne or more of the locations in your claim are unable to be claimed!")) return } val claim = Cuboid(loc1, loc2) team.claims.add(claim) team.save() player.setItemInHand(null) player.updateInventory() LandGrid.pendingSession.remove(player.uniqueId) player.sendMessage(translate("&aAdded a team claim for " + team.name)) } else { player.sendMessage(translate("&cBoth claim positions must be set")) } } } } @EventHandler fun onItemDrop(event: PlayerDropItemEvent) { if (!event.itemDrop.itemStack.isSimilar(claimWand)) return event.isCancelled = true } }
13
Kotlin
0
3
74a1512f3af2db591bcd233d2012e4dbded10e8a
4,013
HCF
MIT License
koin-projects/koin-java/src/main/java/org/koin/java/standalone/KoinJavaStarter.kt
JanStoltman
148,633,650
false
{"AsciiDoc": 31, "Markdown": 5, "Text": 2, "Ignore List": 7, "Gradle": 28, "Shell": 8, "Java Properties": 3, "Batchfile": 1, "INI": 9, "Kotlin": 393, "XML": 76, "CSS": 3, "JSON": 61, "Java": 3, "YAML": 1}
/* * Copyright 2017-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.java.standalone import org.koin.core.Koin import org.koin.dsl.module.Module import org.koin.log.Logger import org.koin.log.PrintLogger import org.koin.standalone.StandAloneContext /** * Java helper to start Koin * * @author Arnaud Giuliani */ object KoinJavaStarter { /** * Koin starter function to load modules and extraProperties * Throw AlreadyStartedException if already started * @param list : Modules * @param useEnvironmentProperties - use environment extraProperties * @param useKoinPropertiesFile - use /koin.extraProperties file * @param extraProperties - extra extraProperties * @param logger - Koin logger */ @JvmOverloads @JvmStatic fun startKoin( list: List<Module>, useEnvironmentProperties: Boolean = false, useKoinPropertiesFile: Boolean = true, extraProperties: Map<String, Any> = HashMap(), logger: Logger = PrintLogger() ): Koin = StandAloneContext.startKoin( list, useEnvironmentProperties, useKoinPropertiesFile, extraProperties, logger ) }
1
null
1
1
1d95f051d02f62aa7cfb6faed899c4eec146c48e
1,753
koin
Apache License 2.0
src/test/kotlin/org/jetbrains/kotlinx/jupyter/test/ConfigTest.kt
Kotlin
63,066,291
false
null
package org.jetbrains.kotlinx.jupyter.test import io.kotest.matchers.shouldBe import jupyter.kotlin.JavaRuntime import org.jetbrains.kotlinx.jupyter.api.KotlinKernelVersion import org.jetbrains.kotlinx.jupyter.defaultRuntimeProperties import org.jetbrains.kotlinx.jupyter.iKotlinClass import org.jetbrains.kotlinx.jupyter.log import org.jetbrains.kotlinx.jupyter.startup.mainClassName import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import kotlin.test.assertNotNull class ConfigTest { @Test fun testBranch() { val branch = defaultRuntimeProperties.currentBranch log.debug("Runtime git branch is: $branch") if (!branch.matches(Regex("pull/[1-9]\\d*"))) { assertEquals(-1, branch.indexOf('/'), "Branch name should be simple") } assertTrue(branch.isNotBlank(), "Branch name shouldn't be blank") val commit = defaultRuntimeProperties.currentSha assertEquals(40, commit.length) } @Test fun testVersion() { val version = defaultRuntimeProperties.version log.debug("Runtime version is: {}", version) assertNotNull(version) } @Test fun testVersionRuntimeHelpers() { val minExpectedVersion = 6 val maxExpectedVersion = 20 assertTrue(JavaRuntime.versionAsInt >= minExpectedVersion) JavaRuntime.assertVersion { it >= minExpectedVersion } JavaRuntime.assertVersionAtLeast(minExpectedVersion) JavaRuntime.assertVersionInRange(minExpectedVersion, maxExpectedVersion) } @Test fun testKernelVersion() { val major = 0 val minor = 8 val micro = 12 val build = 100500 val dev = 2 val fullVersion = KotlinKernelVersion.from(major, minor, micro, build, dev) assertEquals("0.8.12.100500.dev2", fullVersion.toString()) val releaseVersion = KotlinKernelVersion.from("0.8.12") val stableVersion = KotlinKernelVersion.from("0.8.12.100500") val devVersion = KotlinKernelVersion.from("0.8.12.100500.dev2") assertNotNull(fullVersion) assertNotNull(releaseVersion) assertNotNull(stableVersion) assertNotNull(devVersion) for (ver in listOf(fullVersion, releaseVersion, stableVersion, devVersion)) { assertEquals(major, ver.major) assertEquals(minor, ver.minor) assertEquals(micro, ver.micro) } for (ver in listOf(fullVersion, stableVersion, devVersion)) { assertEquals(build, ver.build) } assertNull(releaseVersion.build) for (ver in listOf(fullVersion, devVersion)) { assertEquals(dev, ver.dev) } assertNull(releaseVersion.dev) assertNull(stableVersion.dev) assertTrue(releaseVersion < stableVersion) assertTrue(stableVersion < devVersion) assertEquals(fullVersion, devVersion) assertTrue(KotlinKernelVersion.from("5.0.2")!! > KotlinKernelVersion.from("5.0.1.999")!!) assertNull(KotlinKernelVersion.from("0.-1.2")) assertNull(KotlinKernelVersion.from("5.1.2.3.4")) } @Test fun `kernel main class name should be consistent`() { mainClassName shouldBe iKotlinClass.name } }
57
Kotlin
106
941
f92a3da6c330dd6fc8d730a706720ad48f3ecd69
3,402
kotlin-jupyter
Apache License 2.0
app/src/main/java/com/malikane/mussic/Database/PlaylistBase.kt
Muratthekus
238,066,345
false
{"Kotlin": 43382}
package com.malikane.mussic.Database import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "playlistBase") data class PlaylistBase( @PrimaryKey(autoGenerate = true) var Id:Int=0, var name:String, var description:String, var size:Int=0, var duration:Int=0)
0
Kotlin
1
5
6dad14a84ef4dfda33b67d2e2b102bd62676b1ce
307
Music-Player
MIT License
app/src/main/java/re/notifica/demo/extensions/Date.kt
Notificare
274,510,983
false
null
package re.notifica.demo.extensions import java.time.Duration import java.time.Period import java.time.ZoneId import java.util.* fun Date.asTimeAgo(): String { val start = this.toInstant().atZone(ZoneId.systemDefault()) val end = Calendar.getInstance().time.toInstant().atZone(ZoneId.systemDefault()) val period = Period.between(start.toLocalDate(), end.toLocalDate()) if (period.years >= 1) { return "${period.years}Y" } if (period.months >= 1) { return "${period.months}M" } if (period.days >= 1) { return "${period.days}D" } val duration = Duration.between(start, end) if (duration.toDays() >= 1) { return "${duration.toDays()}D" } if (duration.toHours() >= 1) { return "${duration.toHours()} hr" } if (duration.toMinutes() >= 1) { return "${duration.toMinutes()} min" } if (duration.seconds >= 3) { return "${duration.seconds} sec" } return "now" }
0
Kotlin
0
0
076abe62f7d268096efac66a67b96a582e042af6
997
notificare-jetpack-compose-demo
MIT License
src/commonMain/kotlin/models/Voice.kt
dragneelfps
297,047,080
false
null
package io.github.dragneelfps.kbot.models import kotlinx.serialization.Serializable /** * [https://core.telegram.org/bots/api#voice] */ @Serializable data class Voice( val file_id: String, val file_unique_id: String, val duration: Int, val mime_type: String? = null, val file_size: Int? = null, )
5
Kotlin
2
8
ffd954dd6b28c96cd1c8e5c846f55079bbaa07af
321
telegram-bot.kt
MIT License
app/src/main/java/io/tokend/template/features/trade/history/view/adapter/TradeHistoryItemViewHolder.kt
tokend
153,459,333
false
null
package io.tokend.template.features.trade.history.view.adapter import android.view.View import androidx.core.content.ContextCompat import io.tokend.template.R import io.tokend.template.features.trade.history.model.TradeHistoryRecord import io.tokend.template.view.adapter.base.BaseViewHolder import io.tokend.template.view.util.formatter.AmountFormatter import kotlinx.android.synthetic.main.list_item_trade_history.view.* import java.text.DateFormat class TradeHistoryItemViewHolder( view: View, private val amountFormatter: AmountFormatter, private val dateFormat: DateFormat ) : BaseViewHolder<TradeHistoryRecord>(view) { private val positiveColor: Int by lazy { ContextCompat.getColor(view.context, R.color.received) } private val negativeColor: Int by lazy { ContextCompat.getColor(view.context, R.color.sent) } private val priceText = view.price_text_view private val amountText = view.amount_text_view private val timeText = view.time_text_view override fun bind(item: TradeHistoryRecord) { priceText.text = amountFormatter.formatAssetAmount( item.price, item.quoteAsset, withAssetCode = false, abbreviation = false ) amountText.text = amountFormatter.formatAssetAmount( item.baseAmount, item.baseAsset, withAssetCode = false, abbreviation = true ) timeText.text = dateFormat.format(item.createdAt) priceText.setTextColor( if (item.hasPositiveTrend) positiveColor else negativeColor ) } }
1
null
9
24
297a2dd4b1017f49c37e7a23e4cea0e7682c99d4
1,627
android-client
Apache License 2.0
EtcLiteKotlin/app/src/main/java/com/etc/logger/xlog/JsonLog.kt
XiaYi24
572,422,369
false
{"Kotlin": 74637, "Java": 59063}
package com.etc.logger.xlog import android.util.Log import com.etc.logger.KLog import com.etc.logger.KLogUtil import org.json.JSONArray import org.json.JSONException import org.json.JSONObject /** * Created on 2020/8/11. * @author Holo */ internal object JsonLog { fun printJson(tag: String?, msg: String, headString: String) { var message: String = try { when { msg.startsWith("{") -> { val jsonObject = JSONObject(msg) jsonObject.toString(KLog.JSON_INDENT) } msg.startsWith("[") -> { val jsonArray = JSONArray(msg) jsonArray.toString(KLog.JSON_INDENT) } else -> { msg } } } catch (e: JSONException) { msg } KLogUtil.printLine(tag, true) message = headString + KLog.LINE_SEPARATOR + message val lines = message.split(KLog.LINE_SEPARATOR!!).toTypedArray() for (line in lines) { Log.d(tag, "║ $line") } KLogUtil.printLine(tag, false) } }
0
Kotlin
0
0
6ff6deb7c72a8ffad6621e99bb0eb3f40e4cdb0a
1,166
MvvmProject
Apache License 2.0
kotlin/goi/src/main/kotlin/net/paploo/goi/persistence/database/vocabulary/SqlVocabularyDao.kt
paploo
526,415,165
false
{"Kotlin": 551045, "Ruby": 153592, "Java": 50625, "ANTLR": 2824, "CSS": 1827, "PLpgSQL": 274}
package net.paploo.goi.persistence.database.vocabulary import net.paploo.goi.common.extensions.flatMap import net.paploo.goi.common.extensions.sequenceToResult import net.paploo.goi.domain.data.vocabulary.Vocabulary import net.paploo.goi.persistence.common.BulkWriteDao import net.paploo.goi.persistence.common.ServiceDataSource class SqlVocabularyDao( val dataSource: ServiceDataSource, ) : BulkWriteDao<Vocabulary> { override suspend fun writeAll(values: List<Vocabulary>): Result<Unit> = values.map { VocabularyDomainToRecordTransform().invoke(it) }.sequenceToResult().flatMap { records -> VocabularyWriter().invoke(dataSource, records) } }
3
Kotlin
0
0
88b9e39268e22f071d6825c052395d5a1bf3b8c5
684
goi
MIT License
app/src/main/java/software/galaniberico/moduledroid/MainActivity2.kt
agp221-ua
753,141,684
false
{"Kotlin": 46824}
package software.galaniberico.moduledroid import android.os.Bundle import android.widget.TextView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import software.galaniberico.moduledroid.facade.Facade class MainActivity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main2) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } findViewById<TextView>(R.id.tvOk).text = Facade.getId(this) findViewById<TextView>(R.id.tvCode).text = "${intent.getIntExtra("code", -2)}" } }
1
Kotlin
0
0
bc285fb5e89d65becca1cdba8d5c777cf80511f3
1,007
ModuleDroid
Apache License 2.0
android/src/main/java/com/rnidletimer/RnIdleTimerModule.kt
TheRogue76
571,755,079
false
{"Java": 7387, "Ruby": 3679, "Kotlin": 2776, "Objective-C": 2533, "JavaScript": 1832, "TypeScript": 1810, "Objective-C++": 1716, "C": 103, "Swift": 63}
package com.rnidletimer import android.app.Activity import android.view.WindowManager import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactMethod class RnIdleTimerModule internal constructor(context: ReactApplicationContext) : RnIdleTimerSpec(context) { override fun getName(): String { return NAME } // Example method // See https://reactnative.dev/docs/native-modules-android @ReactMethod override fun setIdleTimerDisabled(status: Boolean) { currentActivity.let { activity: Activity? -> activity?.runOnUiThread { kotlin.run { if (status) { activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } else { activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } } } } companion object { const val NAME = "RnIdleTimer" } }
1
null
1
1
6d1056353a6f8d09a83adf80f7e214966fd47152
928
rn-idle-timer
MIT License
tictactoe/dsl/src/main/kotlin/com/anaplan/engineering/azuki/tictactoe/dsl/TicTacToeRegardlessOf.kt
anaplan-engineering
458,253,960
false
null
package com.anaplan.engineering.azuki.tictactoe.dsl import com.anaplan.engineering.azuki.core.dsl.RegardlessOf import com.anaplan.engineering.azuki.core.system.Action import com.anaplan.engineering.azuki.tictactoe.adapter.api.TicTacToeActionFactory class TicTacToeRegardlessOf(private val actionFactory: TicTacToeActionFactory) : RegardlessOf<TicTacToeActionFactory> { private val actionList = mutableListOf<Action>() fun saveGame(gameName: String) { actionList.add(actionFactory.game.save(gameName)) } override fun actions(): List<Action> = actionList }
1
Kotlin
0
2
016b26faa9e75798f2abb8ea55b23e648449b40b
585
azuki
MIT License
src/main/kotlin/com/deflatedpickle/survivalimprovement/Reference.kt
DeflatedPickle
126,453,191
false
{"Scala": 2007, "Java": 407}
package com.deflatedpickle.survivalimprovement object Reference { const val MOD_ID = "survivalimprovement" const val NAME = "SurvivalImprovement" // Versions follow this format: MCVERSION-MAJORMOD.MAJORAPI.MINOR.PATCH. const val VERSION = "1.12.2-2.0.1.0" const val ACCEPTED_VERSIONS = "[1.12.1, 1.12.2]" const val ADAPTER = "net.shadowfacts.forgelin.KotlinAdapter" }
0
Scala
0
0
3d23fe9bce8a795f551b6f0451417f2d11f819d2
393
SurvivalImprovement
MIT License
src/main/kotlin/com/deflatedpickle/survivalimprovement/Reference.kt
DeflatedPickle
126,453,191
false
{"Scala": 2007, "Java": 407}
package com.deflatedpickle.survivalimprovement object Reference { const val MOD_ID = "survivalimprovement" const val NAME = "SurvivalImprovement" // Versions follow this format: MCVERSION-MAJORMOD.MAJORAPI.MINOR.PATCH. const val VERSION = "1.12.2-2.0.1.0" const val ACCEPTED_VERSIONS = "[1.12.1, 1.12.2]" const val ADAPTER = "net.shadowfacts.forgelin.KotlinAdapter" }
0
Scala
0
0
3d23fe9bce8a795f551b6f0451417f2d11f819d2
393
SurvivalImprovement
MIT License
app/src/main/java/xyz/teamgravity/jetpackworkmanager/data/remote/ImgurApi.kt
raheemadamboev
467,888,679
false
{"Kotlin": 16728}
package xyz.teamgravity.jetpackworkmanager.data.remote import okhttp3.ResponseBody import retrofit2.Response import retrofit2.http.GET interface ImgurApi { companion object { const val BASE_URL = "https://i.imgur.com" } @GET("/X2qa7nQ.jpg") suspend fun downloadImage(): Response<ResponseBody> }
0
Kotlin
0
5
02fbfe5206360b0087c960abd1990b3d82025e4e
322
jetpack-workmanager
Apache License 2.0
src/main/kotlin/org/move/lang/core/psi/ext/MvLetStatement.kt
pontem-network
279,299,159
false
null
package org.move.lang.core.psi.ext import org.move.lang.core.psi.MvLetStatement import org.move.lang.core.types.ty.Ty val MvLetStatement.declaredTy: Ty? get() = this.typeAnnotation?.type?.ty()
1
Kotlin
4
11
a8348f3ab29be141da16bf0cbf86a70f91d61bef
195
intellij-move
MIT License
src/main/kotlin/com/cycode/plugin/components/toolWindow/components/violationCardContentTab/sastViolationCardContentTab/components/companyGuidelines/SastCompanyGuidelines.kt
cycodehq
661,784,325
false
{"Kotlin": 205675}
package com.cycode.plugin.components.toolWindow.components.violationCardContentTab.sastViolationCardContentTab.components.companyGuidelines import com.cycode.plugin.CycodeBundle import com.cycode.plugin.cli.models.scanResult.sast.SastDetection import com.cycode.plugin.components.toolWindow.components.violationCardContentTab.common.htmlSummary.CardHtmlSummary import com.cycode.plugin.components.toolWindow.components.violationCardContentTab.convertMarkdownToHtml import javax.swing.JComponent class SastCompanyGuidelines : CardHtmlSummary() { private fun getCustomGuidelines(detection: SastDetection): String? { val descriptionMarkdown = detection.detectionDetails.customRemediationGuidelines ?: return null return convertMarkdownToHtml(descriptionMarkdown) } fun getContent(detection: SastDetection): JComponent { return getContent( CycodeBundle.message("violationCardCompanyGuidelinesTitle"), getCustomGuidelines(detection) ) } }
0
Kotlin
0
1
b313d772bb78e48dda117702a462792f858290d2
1,009
intellij-platform-plugin
MIT License
app/src/main/java/com/omerguzel/pokedex/extensions/StringExtensions.kt
omerrguzel
720,436,407
false
{"Kotlin": 84274}
package com.omerguzel.pokedex.extensions fun String?.capitalizeFirstLetter(): String? { return this?.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } } fun String.replaceSpecialCharactersWithSpace(): String { return this.replace(Regex("\\s+"), " ") }
0
Kotlin
0
0
e0a0c9061531a18a6159e1394a7638b6ccbbab95
302
Pokedex
The Unlicense
app/src/androidTest/java/de/freenet/espresso_databinding/TestApp.kt
dhartwich1991
157,396,299
false
null
package de.freenet.espresso_databinding import android.app.Application import org.koin.android.ext.android.startKoin class TestApp : Application() { override fun onCreate() { super.onCreate() startKoin(this, emptyList()) } }
0
Kotlin
3
6
1a6ce34eb121bc204b911b78e94a4773be602e2d
251
databinding-espresso
The Unlicense
Keyrnel/src/test/kotlin/com/keyrus/keyrnel/extensions/StringKtTest.kt
keyrusrocks
151,573,114
false
null
package com.keyrus.keyrnel.extensions import org.junit.Test /** * Created by <NAME> on 09/10/2018. */ class StringKtTest { /** * According to RFC 2822, there is a link to valid or invalid email addresses * https://blogs.msdn.microsoft.com/testing123/2009/02/06/email-address-test-cases/ */ @Test fun testIsValidEmail() { // Invalid Emails val invalidEmails = listOf( "plainaddress", "#@%^%#\$@#\$@#.com", "@domain.com", "<NAME> <<EMAIL>>", "email.domain.com", "<EMAIL>", <EMAIL>", "<EMAIL>", "email..<EMAIL>", "あいうえ<EMAIL>", "<EMAIL> (<NAME>)", "email@domain", // "<EMAIL>", // "<EMAIL>", "email@111.222.333.44444", "<EMAIL>") invalidEmails.forEach { assert(!it.isValidEmail()) { "$it is a valid email address" } } // Valid Emails val validEmails = listOf( "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", // "email@172.16.58.3", // "email@[172.16.58.3]", // "\"email\"@domain.com", "12345678<EMAIL>", "<EMAIL>", "<EMAIL><EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>") validEmails.forEach { assert(it.isValidEmail()) { "$it is not a valid email address" } } } @Test fun testRemoveAccent() { // Empty assert("" == "".removeAccent()) // Accent assert("orcpzsiayd" == "orčpžsíáýd".removeAccent()) } }
0
Kotlin
0
0
4b62a4681e02c6c9a223658789e1a757e73c0cf8
1,816
Keyrnel-Android
MIT License
src/main/java/miyucomics/hexical/casting/patterns/OpMagicMissile.kt
miyucomics
757,094,041
false
{"Kotlin": 312812, "Java": 29755, "GLSL": 1353}
package miyucomics.hexical.casting.patterns import at.petrak.hexcasting.api.misc.MediaConstants import at.petrak.hexcasting.api.spell.ParticleSpray import at.petrak.hexcasting.api.spell.RenderedSpell import at.petrak.hexcasting.api.spell.SpellAction import at.petrak.hexcasting.api.spell.casting.CastingContext import at.petrak.hexcasting.api.spell.getVec3 import at.petrak.hexcasting.api.spell.iota.Iota import miyucomics.hexical.entities.MagicMissileEntity import net.minecraft.util.math.MathHelper import net.minecraft.util.math.Vec3d class OpMagicMissile : SpellAction { override val argc = 2 override fun execute(args: List<Iota>, ctx: CastingContext): Triple<RenderedSpell, Int, List<ParticleSpray>> { val headOffset = args.getVec3(0, argc) val straightAxis = ctx.caster.rotationVector val upPitch = (-ctx.caster.pitch + 90) * (Math.PI.toFloat() / 180) val yaw = -ctx.caster.headYaw * (Math.PI.toFloat() / 180) val h = MathHelper.cos(yaw).toDouble() val j = MathHelper.cos(upPitch).toDouble() val upAxis = Vec3d( MathHelper.sin(yaw).toDouble() * j, MathHelper.sin(upPitch).toDouble(), h * j ) val sideAxis = straightAxis.crossProduct(upAxis).normalize() val worldCoords = ctx.caster.eyePos .add(sideAxis.multiply(headOffset.x)) .add(upAxis.multiply(headOffset.y)) .add(straightAxis.multiply(headOffset.z)) ctx.assertVecInRange(worldCoords) val velocity = args.getVec3(1, argc) return Triple(Spell(worldCoords, velocity), MediaConstants.DUST_UNIT, listOf()) } private data class Spell(val position: Vec3d, val velocity: Vec3d) : RenderedSpell { override fun cast(ctx: CastingContext) { val missile = MagicMissileEntity(ctx.world) missile.setPos(position.x, position.y, position.z) missile.setVelocity(velocity.x, velocity.y, velocity.z) missile.owner = ctx.caster ctx.world.spawnEntity(missile) } } }
0
Kotlin
1
1
8acff912fc3e4ccc1503576ab8a16fdfc3261184
1,879
hexical
MIT License
src/main/kotlin/tech/youko/acms/controller/device/AccessibilityController.kt
YukiIsait
804,121,599
false
{"Kotlin": 32952}
package tech.youko.acms.controller.device import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import tech.youko.acms.entity.id.AccessInfoId import tech.youko.acms.service.IAccessInfoService @RestController @RequestMapping("/device/accessibility") class AccessibilityController(private val accessInfoService: IAccessInfoService) { @GetMapping("/access") fun access( @RequestParam deviceId: String, @RequestParam userId: String ): Boolean = accessInfoService.existAccessInfoById(AccessInfoId(deviceId, userId)) @GetMapping("/accessWithToken") @PreAuthorize("isAuthenticated()") fun access( @RequestParam id: String ): Boolean = accessInfoService.existAccessInfoById( AccessInfoId(id, SecurityContextHolder.getContext().authentication.name) ) }
0
Kotlin
0
0
1987f44718607920a3c8b318861578d727e2bfa3
1,134
AccessControlSystem-Server
MIT License
login/domain/src/main/java/dev/vladimirj/login/domain/usecase/IsCiphertextSaved.kt
VladimirWrites
393,602,658
false
null
package dev.vladimirj.login.domain.usecase import dev.vladimirj.login.domain.store.CryptographicStore import javax.inject.Inject class IsCiphertextSaved @Inject constructor( private val cryptographicStore: CryptographicStore ) { operator fun invoke(): Boolean { return cryptographicStore.getCiphertextWrapperFromSharedPrefs() != null } }
0
Kotlin
0
3
b363e2965e18c182136e59e24de4da285ce17e7b
359
LoginExample
Apache License 2.0
Frontend/app/src/main/java/com/example/TeamApp/auth/LoginViewModel.kt
TeamApp-Startup
826,845,157
false
{"Kotlin": 104143, "Java": 12082, "Python": 404}
package com.example.TeamApp.auth import android.content.Context import android.content.Intent import android.util.Log import androidx.activity.result.ActivityResultLauncher import android.widget.Toast import androidx.activity.result.IntentSenderRequest import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.TeamApp.data.User import com.example.TeamApp.event.CreateEventActivity import com.example.TeamApp.R import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.GoogleAuthProvider import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.google.android.gms.auth.api.identity.BeginSignInRequest import com.google.android.gms.auth.api.identity.Identity import com.google.android.gms.common.api.ApiException import com.google.android.gms.tasks.Task import com.facebook.CallbackManager import com.facebook.FacebookCallback import com.facebook.FacebookException import com.facebook.login.LoginManager import com.facebook.login.LoginResult import android.app.Activity class LoginViewModel : ViewModel() { lateinit var signInLauncher: ActivityResultLauncher<IntentSenderRequest> private val _email = MutableLiveData("") val email: LiveData<String> = _email private val _password = MutableLiveData("") val password: LiveData<String> = _password private val _username = MutableLiveData("") val username: LiveData<String> = _username private val _loginSuccess = MutableLiveData<Boolean?>(null) val loginSuccess: LiveData<Boolean?> = _loginSuccess private val _registerSuccess = MutableLiveData<Boolean?>(null) val registerSuccess: LiveData<Boolean?> = _registerSuccess private val auth: FirebaseAuth = FirebaseAuth.getInstance() fun onEmailChange(newUsername: String) { _email.value = newUsername } fun onPasswordChanged(newPassword: String) { _password.value = newPassword } fun logout(context: Context) { FirebaseAuth.getInstance().signOut() val intent = Intent(context, LoginActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } context.startActivity(intent) } fun onLoginClick(context: Context) { val email = _email.value ?: return val password = _password.value ?: return if (email.isNotEmpty() && password.isNotEmpty()) { Log.d("LoginAttempt", "Attempting to log in with email: $email") auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d("Login", "Login successful") _loginSuccess.value = true val intent = Intent(context, CreateEventActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } context.startActivity(intent) } else { Log.e("Login", "Login failed: ${task.exception?.message}") _loginSuccess.value = false } } } else { //Pole hasla i loginu nie moga byc puste Log.d("LoginAttempt", "email or password are null") } } fun signInWithGoogle(context: Context) { val clientId = context.getString(R.string.client_id) Log.d("LoginViewModel", "Client ID: $clientId") val signInRequest = BeginSignInRequest.builder() .setGoogleIdTokenRequestOptions( BeginSignInRequest.GoogleIdTokenRequestOptions.builder() .setSupported(true) .setServerClientId(clientId) .setFilterByAuthorizedAccounts(false) // Allow all accounts .build() ) .build() Identity.getSignInClient(context).beginSignIn(signInRequest) .addOnSuccessListener { result -> Log.d("LoginViewModel", "Google Sign-In success: ${result.pendingIntent}") val intent = result.pendingIntent.intentSender signInLauncher.launch(IntentSenderRequest.Builder(intent).build()) } .addOnFailureListener { e -> Log.e("LoginViewModel", "Google Sign-In failed", e) if (e is ApiException) { Log.e("LoginViewModel", "Status Code: ${e.statusCode}") } } } fun signInWithFacebook(context: Context) { val callbackManager = CallbackManager.Factory.create() LoginManager.getInstance().logOut() LoginManager.getInstance().logInWithReadPermissions( context as Activity, listOf("public_profile", "email") ) LoginManager.getInstance().registerCallback(callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(loginResult: LoginResult) { //Handle successful login Log.d("FacebookLogin", "Success: ${loginResult.accessToken}") val accessToken = loginResult.accessToken // Use the access token to retrieve user data or perform other actions } override fun onCancel() { // Handle login cancellation Log.d("FacebookLogin", "Cancelled") } override fun onError(error: FacebookException) { // Handle login error Log.d("FacebookLogin", "Error: ${error.message}") } }) } fun getToLoginScreen(context: Context) { val intent = Intent(context, LoginActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } context.startActivity(intent) } fun getToRegisterScreen(context: Context){ val intent = Intent(context, RegisterActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } context.startActivity(intent) } fun onRegisterClick(context: Context) { val email = _email.value ?: return val password = _password.value ?: return if (email.isNotEmpty() && password.isNotEmpty()) { // Tymczasowo, niedodana implementacja rejestracji z loginem val username = "xyz" val db = Firebase.firestore val user = User(name = username, email = email) Log.d("RegisterAttempt", "Attempting to register with email: $email") auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { db.collection("users").add(user) Log.d("Register", "Registration successful") _registerSuccess.value = true } else { Log.e("Register", "Registration failed: ${task.exception?.message}") _registerSuccess.value = false } } } else { Log.d("Register", "input field/s are empty") } } fun resetLoginRegisterSuccess() { _loginSuccess.value = null _registerSuccess.value = null } }
0
Kotlin
2
3
6bc5187e1a02583370c4d517d66cdb0e960d25a8
7,566
TeamApp
MIT License
app/src/main/java/com/example/mytrainingpal/model/entities/MusclePainEntryMap.kt
MichaelBuessemeyer
572,939,495
false
{"Kotlin": 256987}
package com.example.mytrainingpal.model import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import com.example.mytrainingpal.model.entities.Muscle import com.example.mytrainingpal.model.entities.MusclePainEntry @Entity( primaryKeys = ["musclePainEntryIdMap", "muscleIdMap"], indices = [Index("musclePainEntryIdMap"), Index("muscleIdMap")], foreignKeys = [ ForeignKey( entity = MusclePainEntry::class, parentColumns = ["musclePainEntryId"], childColumns = ["musclePainEntryIdMap"], onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE ), ForeignKey( entity = Muscle::class, parentColumns = ["muscleId"], childColumns = ["muscleIdMap"], onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE ) ] ) data class MusclePainEntryMap( val musclePainEntryIdMap: Long, val muscleIdMap: Long, var painIntensity: Long, ) object MusclePainEntryMapConstants { const val SEVERE_PAIN: Long = 2 const val MODERATE_PAIN: Long = 1 }
14
Kotlin
0
2
5ef8c98c684bf2bb863dc6781a457c16ab8bb6e1
1,154
MyTrainingsPal
Apache License 2.0
src/main/kotlin/org/raddad/main/alias.kt
fossabot
394,966,615
false
null
package org.raddad.main typealias Constructor<T> = (Warehouse) -> T typealias MutableRegistry = MutableMap<Metadata, Factory> typealias Registry = Map<Metadata, Factory>
0
Kotlin
0
1
17183db5bac300212745927a887281a0f6117732
171
Warehouse
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/s3/CfnAccessGrantDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.s3 import io.cloudshiftdev.awscdkdsl.CfnTagDsl import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.CfnTag import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.s3.CfnAccessGrant import software.constructs.Construct /** * The `AWS::S3::AccessGrant` resource creates an access grant that gives a grantee access to your * S3 data. * * The grantee can be an IAM user or role or a directory user, or group. Before you can create a * grant, you must have an S3 Access Grants instance in the same Region as the S3 data. You can * create an S3 Access Grants instance using the * [AWS::S3::AccessGrantsInstance](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrantsinstance.html) * . You must also have registered at least one S3 data location in your S3 Access Grants instance * using * [AWS::S3::AccessGrantsLocation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrantslocation.html) * . * * **Permissions** - You must have the `s3:CreateAccessGrant` permission to use this resource. * * **Additional Permissions** - For any directory identity - `sso:DescribeInstance` and * `sso:DescribeApplication` * * For directory users - `identitystore:DescribeUser` * * For directory groups - `identitystore:DescribeGroup` * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.s3.*; * CfnAccessGrant cfnAccessGrant = CfnAccessGrant.Builder.create(this, "MyCfnAccessGrant") * .accessGrantsLocationId("accessGrantsLocationId") * .grantee(GranteeProperty.builder() * .granteeIdentifier("granteeIdentifier") * .granteeType("granteeType") * .build()) * .permission("permission") * // the properties below are optional * .accessGrantsLocationConfiguration(AccessGrantsLocationConfigurationProperty.builder() * .s3SubPrefix("s3SubPrefix") * .build()) * .applicationArn("applicationArn") * .s3PrefixType("s3PrefixType") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html) */ @CdkDslMarker public class CfnAccessGrantDsl( scope: Construct, id: String, ) { private val cdkBuilder: CfnAccessGrant.Builder = CfnAccessGrant.Builder.create(scope, id) private val _tags: MutableList<CfnTag> = mutableListOf() /** * The configuration options of the grant location. * * The grant location is the S3 path to the data to which you are granting access. It contains * the `S3SubPrefix` field. The grant scope is the result of appending the subprefix to the * location scope of the registered location. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-accessgrantslocationconfiguration) * * @param accessGrantsLocationConfiguration The configuration options of the grant location. */ public fun accessGrantsLocationConfiguration(accessGrantsLocationConfiguration: IResolvable) { cdkBuilder.accessGrantsLocationConfiguration(accessGrantsLocationConfiguration) } /** * The configuration options of the grant location. * * The grant location is the S3 path to the data to which you are granting access. It contains * the `S3SubPrefix` field. The grant scope is the result of appending the subprefix to the * location scope of the registered location. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-accessgrantslocationconfiguration) * * @param accessGrantsLocationConfiguration The configuration options of the grant location. */ public fun accessGrantsLocationConfiguration( accessGrantsLocationConfiguration: CfnAccessGrant.AccessGrantsLocationConfigurationProperty ) { cdkBuilder.accessGrantsLocationConfiguration(accessGrantsLocationConfiguration) } /** * The ID of the registered location to which you are granting access. * * S3 Access Grants assigns this ID when you register the location. S3 Access Grants assigns the * ID `default` to the default location `s3://` and assigns an auto-generated ID to other * locations that you register. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-accessgrantslocationid) * * @param accessGrantsLocationId The ID of the registered location to which you are granting * access. */ public fun accessGrantsLocationId(accessGrantsLocationId: String) { cdkBuilder.accessGrantsLocationId(accessGrantsLocationId) } /** * The Amazon Resource Name (ARN) of an AWS IAM Identity Center application associated with your * Identity Center instance. * * If the grant includes an application ARN, the grantee can only access the S3 data through * this application. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-applicationarn) * * @param applicationArn The Amazon Resource Name (ARN) of an AWS IAM Identity Center * application associated with your Identity Center instance. */ public fun applicationArn(applicationArn: String) { cdkBuilder.applicationArn(applicationArn) } /** * The user, group, or role to which you are granting access. * * You can grant access to an IAM user or role. If you have added your corporate directory to * AWS IAM Identity Center and associated your Identity Center instance with your S3 Access * Grants instance, the grantee can also be a corporate directory user or group. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-grantee) * * @param grantee The user, group, or role to which you are granting access. */ public fun grantee(grantee: IResolvable) { cdkBuilder.grantee(grantee) } /** * The user, group, or role to which you are granting access. * * You can grant access to an IAM user or role. If you have added your corporate directory to * AWS IAM Identity Center and associated your Identity Center instance with your S3 Access * Grants instance, the grantee can also be a corporate directory user or group. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-grantee) * * @param grantee The user, group, or role to which you are granting access. */ public fun grantee(grantee: CfnAccessGrant.GranteeProperty) { cdkBuilder.grantee(grantee) } /** * The type of access that you are granting to your S3 data, which can be set to one of the * following values: - `READ` – Grant read-only access to the S3 data. * * `WRITE` – Grant write-only access to the S3 data. * * `READWRITE` – Grant both read and write access to the S3 data. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-permission) * * @param permission The type of access that you are granting to your S3 data, which can be set * to one of the following values: - `READ` – Grant read-only access to the S3 data. */ public fun permission(permission: String) { cdkBuilder.permission(permission) } /** * The type of `S3SubPrefix` . * * The only possible value is `Object` . Pass this value if the access grant scope is an object. * Do not pass this value if the access grant scope is a bucket or a bucket and a prefix. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-s3prefixtype) * * @param s3PrefixType The type of `S3SubPrefix` . */ public fun s3PrefixType(s3PrefixType: String) { cdkBuilder.s3PrefixType(s3PrefixType) } /** * The AWS resource tags that you are adding to the access grant. * * Each tag is a label consisting of a user-defined key and value. Tags can help you manage, * identify, organize, search for, and filter resources. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-tags) * * @param tags The AWS resource tags that you are adding to the access grant. */ public fun tags(tags: CfnTagDsl.() -> Unit) { _tags.add(CfnTagDsl().apply(tags).build()) } /** * The AWS resource tags that you are adding to the access grant. * * Each tag is a label consisting of a user-defined key and value. Tags can help you manage, * identify, organize, search for, and filter resources. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-accessgrant.html#cfn-s3-accessgrant-tags) * * @param tags The AWS resource tags that you are adding to the access grant. */ public fun tags(tags: Collection<CfnTag>) { _tags.addAll(tags) } public fun build(): CfnAccessGrant { if (_tags.isNotEmpty()) cdkBuilder.tags(_tags) return cdkBuilder.build() } }
0
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
10,160
awscdk-dsl-kotlin
Apache License 2.0
core/datastore/src/commonMain/kotlin/core/datastore/JsonHandler.kt
odvratnozgodan
860,637,530
false
{"Kotlin": 136956, "Swift": 594, "HTML": 338, "CSS": 102}
package core.datastore import core.common.base.model.JsonException import core.common.base.usecese.DataResult import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json suspend inline fun <reified RM> String.safeFromJson(): DataResult<RM> = withContext(Dispatchers.Default) { try { DataResult.Success(Json.decodeFromString<RM>(this@safeFromJson)) } catch (e: Exception) { DataResult.Error( JsonException.DecodingError( message = e.toString() ) ) } } suspend inline fun <reified RM> RM.safeToJson(): String = withContext(Dispatchers.Default) { Json.encodeToString(this@safeToJson) }
0
Kotlin
0
2
77b18ef241dd823dc817ac236df91fda22215d8c
765
kmp-showcase
MIT License
app/src/main/java/com/aditya/fitfriend_android/utils/PIFlags.kt
this-Aditya
654,565,739
false
null
/** * Copyright 2023 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.aditya.fitfriend_android.utils import android.app.PendingIntent import android.os.Build import android.os.Build.VERSION_CODES fun Int.toPendingIntentFlag(mutable: Boolean = false) = this or when { mutable && Build.VERSION.SDK_INT >= VERSION_CODES.S -> PendingIntent.FLAG_MUTABLE !mutable -> PendingIntent.FLAG_IMMUTABLE else -> 0 }
0
Kotlin
0
0
5580c516ec686a43cd586f22bad204121a31e582
912
FitFriend
Apache License 2.0
gateway/src/main/kotlin/org/heeheepresso/gateway/common/exception/GatewayException.kt
HeeHeePresso
758,780,391
false
{"Kotlin": 120219, "Java": 11246}
package org.heeheepresso.gateway.common.exception import org.heeheepresso.gateway.common.response.StatusCode import org.springframework.http.HttpStatus data class GatewayException( val httpStatus: HttpStatus, val statusCode: StatusCode ) : RuntimeException(statusCode.message) { constructor(statusCode: StatusCode) : this(statusCode.status, statusCode) }
9
Kotlin
0
0
c41fa09c4157c726c21f617e731bb980a99b901a
376
Backend
Apache License 2.0
app/src/test/java/com/sildian/apps/togetrail/hiker/model/dataRequests/HikerSaveDataRequestTest.kt
Sildian
230,769,024
false
{"Kotlin": 660492}
package com.sildian.apps.togetrail.hiker.model.dataRequests import com.google.firebase.FirebaseException import com.sildian.apps.togetrail.common.utils.cloudHelpers.AuthRepository import com.sildian.apps.togetrail.common.utils.cloudHelpers.StorageRepository import com.sildian.apps.togetrail.dataRequestTestSupport.BaseDataRequestTest import com.sildian.apps.togetrail.dataRequestTestSupport.FirebaseSimulator import com.sildian.apps.togetrail.hiker.model.core.Hiker import com.sildian.apps.togetrail.hiker.model.dataRepository.HikerRepository import kotlinx.coroutines.runBlocking import org.junit.Assert.* import org.junit.Test class HikerSaveDataRequestTest: BaseDataRequestTest() { @Test fun given_requestFailure_when_saveHiker_then_checkHikerIsNotSaved() { runBlocking { FirebaseSimulator.requestShouldFail = true try { val hiker = Hiker(id = "HA", name = "Hiker A") val dataRequest = HikerSaveDataRequest( hiker, null, null, AuthRepository(), StorageRepository(), HikerRepository() ) dataRequest.execute() assertEquals("TRUE", "FALSE") } catch (e: FirebaseException) { println(e.message) } assertTrue(FirebaseSimulator.hikers.isEmpty()) } } @Test fun given_nullHiker_when_saveHiker_then_checkHikerIsNotSaved() { runBlocking { try { val dataRequest = HikerSaveDataRequest( null, null, null, AuthRepository(), StorageRepository(), HikerRepository() ) dataRequest.execute() assertEquals("TRUE", "FALSE") } catch (e: NullPointerException) { println(e.message) } assertTrue(FirebaseSimulator.hikers.isEmpty()) } } @Test fun given_hiker_when_saveHiker_then_checkHikerIsSaved() { runBlocking { val hiker = Hiker(id = "HA", name = "Hiker A") val dataRequest = HikerSaveDataRequest( hiker, null, null, AuthRepository(), StorageRepository(), HikerRepository() ) dataRequest.execute() assertNotNull(FirebaseSimulator.hikers.firstOrNull { it.id == "HA" }) } } @Test fun given_hikerWithImages_when_saveHiker_then_checkHikerIsSavedWithImages() { runBlocking { FirebaseSimulator.storageUrls.add("Old image") val hiker = Hiker(id = "HA", name = "Hiker A") val dataRequest = HikerSaveDataRequest( hiker, "Old image", "New image", AuthRepository(), StorageRepository(), HikerRepository() ) dataRequest.execute() val hikerFromDb = FirebaseSimulator.hikers.firstOrNull { it.id == "HA" } assertNotNull(hikerFromDb) assertEquals("New image", hikerFromDb?.photoUrl) assertFalse(FirebaseSimulator.storageUrls.contains("Old image")) assertTrue(FirebaseSimulator.storageUrls.contains("New image")) } } }
1
Kotlin
0
0
cb8e1d926f5e2f0765fe22789ee66cd1ffa7f2be
3,497
TogeTrail-Android
Apache License 2.0
app/src/main/java/com/hha/heinhtetaung/healthcare/delegates/HealthCareDelegate.kt
zack1191
140,570,587
false
{"Kotlin": 20746}
package com.hha.heinhtetaung.healthcare.delegates import com.hha.heinhtetaung.healthcare.data.vo.HealthCareVO /** * Created by E5 on 7/13/2018. */ interface HealthCareDelegate { fun onTapHealthcare(healthcareVO: HealthCareVO) }
0
Kotlin
0
0
e8bbceec33f4518ff7769b08aabbc80e6e908e94
235
PADC-5-HHA-Healthcare
Apache License 2.0
entities/src/commonMain/kotlin/gcu/product/entities/containers/PagerEntity.kt
Ilyandr
612,297,078
false
null
package gcu.product.entities.containers import dev.icerock.moko.parcelize.Parcelable import dev.icerock.moko.parcelize.Parcelize @Parcelize data class PagerEntity( val title: String, val description: String, val imageId: String? ) : Parcelable { fun requireAndroidImageId() = imageId?.toIntOrNull() ?: -1 companion object { private const val SIZE_ERROR_DESCRIPTION = "Pager size elements is not equals!" fun createIosPagerList(titles: Array<String>, descriptions: Array<String>) = if (titles.size != descriptions.size) { throw IllegalArgumentException(SIZE_ERROR_DESCRIPTION) } else { mutableListOf<PagerEntity>().apply { titles.forEachIndexed { index, title -> add( PagerEntity( title = title, description = descriptions[index], imageId = null ) ) } }.toList() } fun createPagerList( titles: Array<String>, descriptions: Array<String>, imagesId: IntArray ) = if (titles.size != descriptions.size || titles.size != imagesId.size) { throw IllegalArgumentException(SIZE_ERROR_DESCRIPTION) } else { mutableListOf<PagerEntity>().apply { titles.forEachIndexed { index, title -> add( PagerEntity( title = title, description = descriptions[index], imageId = imagesId[index].toString() ) ) } }.toList() } } }
0
Kotlin
0
1
8fba8e926b079df86ef5c853e0d1fffcb0e4bc64
1,947
Friendly
Apache License 2.0
src/main/java/br/com/chicorialabs/libghiclient/ui/activity/MainActivity.kt
chicorasia
360,713,234
false
null
package br.com.chicorialabs.libghiclient.ui.activity import android.content.ContentValues import android.database.Cursor import android.net.Uri import android.os.Bundle import android.provider.BaseColumns._ID import android.util.Log import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import br.com.chicorialabs.libghiclient.constants.Constants.Companion.IS_WATCHED import br.com.chicorialabs.libghiclient.constants.Constants.Companion.RATING import br.com.chicorialabs.libghiclient.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val filmRecyclerView: RecyclerView by lazy { binding.mainFilmRecyclerview } private val progressBar: ProgressBar by lazy { binding.mainProgressbar } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) getContentProvider() // Refatoração para aprimorar o app: // criar o ViewModel // criar a classe wrapper para o ContentProviderLiveData (ou o método para } private fun getContentProvider() { try { val url = "content://br.com.chicorialabs.libghi.provider/films" val data = Uri.parse(url) val cursor: Cursor? = contentResolver.query( data, null, null, null, _ID ) Log.i("lib_ghi", "getContentProvider: cursor count: ${cursor?.count}") val adapter = FilmClientAdapter( this@MainActivity, object : FilmClickedListener { override fun filmCheckBoxClickedListener( cursor: Cursor?, isChecked: Boolean, id: Long ) { val url = "content://br.com.chicorialabs.libghi.provider/films" val data = Uri.parse(url) val values = ContentValues().apply { if (isChecked) { put(IS_WATCHED, 1) } else { put(IS_WATCHED, 0) } } val updateUri = contentResolver.update( Uri.withAppendedPath(data, id.toString()), values, "_ID = ?", arrayOf(id.toString()) ) Log.i("lib_ghi", "filmCheckBoxClickedListener: atualizada $updateUri, $id") } override fun filmRatingChangedListener( cursor: Cursor?, rating: Float, id: Long ) { val url = "content://br.com.chicorialabs.libghi.provider/films" val data = Uri.parse(url) val values = ContentValues().apply { put(RATING, rating.toInt()) } contentResolver.update( Uri.withAppendedPath(data, id.toString()), values, "_ID = ?", arrayOf(id.toString()) ) } }, cursor as Cursor ) filmRecyclerView.apply { layoutManager = LinearLayoutManager(this@MainActivity) this.adapter = adapter } } catch (ex: Exception) { ex.printStackTrace() } } }
0
Kotlin
0
0
06c27fcb442d332979bebbcc426ce10f07785abc
4,038
bootcamp-libghi-client
MIT License
src/aws/lambdas/incremental_distribution/cta/src/main/java/uk/nhs/nhsx/circuitbreakers/CircuitBreakerResult.kt
turlodales
289,705,241
true
{"Kotlin": 1762543, "HCL": 516174, "Ruby": 402118, "Python": 95997, "HTML": 10538, "Java": 6060, "Shell": 5028, "Dockerfile": 3728, "Makefile": 780, "JavaScript": 554}
package uk.nhs.nhsx.circuitbreakers import uk.nhs.nhsx.circuitbreakers.CircuitBreakerResult.ResultType.MissingPollingTokenError import uk.nhs.nhsx.circuitbreakers.CircuitBreakerResult.ResultType.Ok import uk.nhs.nhsx.circuitbreakers.CircuitBreakerResult.ResultType.ValidationError class CircuitBreakerResult private constructor( val type: ResultType, val message: String, val responseBody: String ) { enum class ResultType { Ok, ValidationError, MissingPollingTokenError } companion object { fun ok(responseBody: String) = CircuitBreakerResult( type = Ok, message = "", responseBody = responseBody ) fun missingApprovalTokenError() = CircuitBreakerResult( type = MissingPollingTokenError, message = "Circuit Breaker request submitted without approval token", responseBody = "" ) fun validationError() = CircuitBreakerResult( type = ValidationError, message = "Circuit breaker request submitted was invalid", responseBody = "" ) } }
0
Kotlin
0
0
8c67d6e23c7fc79f039c4012238d82131900a4d4
1,129
covid19-app-system-public
MIT License
src/main/kotlin/krayon/editor/sbgn/io/SbgnReader.kt
draeger-lab
156,102,188
true
{"Kotlin": 800067, "Java": 123973, "CSS": 34315, "Inno Setup": 1574}
/* * Copyright (c) 2018 <NAME> * This software is licensed under the Apache License, Version 2.0 (the "License"); you may not use this software 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 krayon.editor.sbgn.io import com.yworks.yfiles.geometry.PointD import com.yworks.yfiles.geometry.RectD import com.yworks.yfiles.geometry.SizeD import com.yworks.yfiles.graph.* import com.yworks.yfiles.graph.portlocationmodels.FreeNodePortLocationModel import krayon.editor.base.style.GraphStyle import krayon.editor.base.style.StyleProperty import krayon.editor.base.style.applyStyle import krayon.editor.base.util.convertToRatioPoint import krayon.editor.base.util.getMainCanvasObject import krayon.editor.base.util.minus import krayon.editor.sbgn.model.* import krayon.editor.sbgn.style.SbgnBuilder import krayon.editor.sbgn.ui.SbgnGraphComponent import krayon.util.asList import org.sbgn.ArcClazz import org.sbgn.GlyphClazz import org.sbgn.bindings.* import org.sbgn.bindings.Map import java.io.InputStream import java.io.StringReader import javax.xml.bind.JAXBContext class SbgnReader { private val krayonNS = "http://krayon.sbgn.ns/v1" private val idStyleMap = mutableMapOf<String,GraphStyle<SbgnType>>() private fun Bbox.toRectD() = RectD(x.toDouble(), y.toDouble(), w.toDouble(), h.toDouble()) private fun Point.toPointD() = PointD(x.toDouble(), y.toDouble()) private fun Port.toPointD() = PointD(x.toDouble(), y.toDouble()) private fun Arc.End.toPointD() = PointD(x.toDouble(), y.toDouble()) private fun Arc.Start.toPointD() = PointD(x.toDouble(), y.toDouble()) private fun Arc.Next.toPointD() = PointD(x.toDouble(), y.toDouble()) private fun Glyph.isSupportingLabel(): Boolean { return clazz != GlyphClazz.OR.toString() && clazz != GlyphClazz.AND.toString() && clazz != GlyphClazz.NOT.toString() } private fun Glyph.ofClazz(vararg clazz: GlyphClazz): Boolean { return clazz.any { this.clazz == it.toString() } } private fun Arc.ofClazz(vararg clazz: ArcClazz): Boolean { return clazz.any { this.clazz == it.toString() } } fun read(input: InputStream, graph: IGraph, graphComponent:SbgnGraphComponent?) { val context = JAXBContext.newInstance("org.sbgn.bindings") val unmarshaller = context.createUnmarshaller() //skip this. extensions crash the parser if namespace tweaker is installed. why? //val reader = XMLReaderFactory.createXMLReader() //val inFilter = NamespaceFilter("http://sbgn.org/libsbgn/0.2") //inFilter.parent = reader //val source = SAXSource(inFilter, InputSource(input)) //val sbgn = unmarshaller.unmarshal(source) as Sbgn val sbgn = unmarshaller.unmarshal(input) as Sbgn // map is a container for the glyphs and arcs val map = sbgn.map if (map.language != "process description") { throw UnsupportedOperationException("Support for diagram type ${map.language} not implemented yet.") } processStyleDefinitions(map.extension) if(graphComponent != null) { val mapStyle = getGraphStyle(map.extension) ?: SbgnBuilder.styleManager.currentStyle if(mapStyle != null) { graphComponent.graphStyle = mapStyle mapStyle.styleTemplateMap[SbgnType.MAP]?.let { graphComponent.applyStyle(graphComponent, it) } } } // we can get a list of glyphs (nodes) in this map with getGlyph() val idMap = HashMap<String, IModelItem>() processGlyphs(graph, idMap, map.glyph, null) processArcs(graph, idMap, map) configurePorts(graph) if(graphComponent != null) establishDrawingOrder(graphComponent) } private fun processStyleDefinitions(ext:SBGNBase.Extension?) { idStyleMap.clear() ext?.any?.forEach { styles -> if(styles.nodeName == "styles" && styles.namespaceURI == krayonNS) { styles.getElementsByTagName("style").asList().forEach { style -> val id = style.attributes.getNamedItem("id")?.nodeValue!! val name = style.attributes.getNamedItem("name")?.nodeValue ?: id val reader = StringReader(style.textContent) val templateMap = SbgnStyleIO().readCss(reader) val graphStyle = GraphStyle(name, false, templateMap).apply { isFileLocal = true } SbgnBuilder.styleManager.normalizeStyle(graphStyle) idStyleMap[id] = graphStyle } } } } private fun establishDrawingOrder(graphComponent: SbgnGraphComponent) { graphComponent.graph.nodes.filter { it.type == SbgnType.COMPARTMENT }.reversed().forEach { graphComponent.graphModelManager.getMainCanvasObject(it).toBack() } } private fun configurePorts(graph:IGraph) { //(I) set port type according to connected edges for (edge in graph.edges) { if (edge.sourceNode.type.isPN() && (edge.type == SbgnType.CONSUMPTION || edge.type == SbgnType.PRODUCTION)) edge.sourcePort.type = SbgnType.INPUT_AND_OUTPUT else if(edge.sourceNode.type.isLogic() && (edge.type == SbgnType.LOGIC_ARC || edge.type.isRegulation())) edge.sourcePort.type = SbgnType.INPUT_AND_OUTPUT if (edge.targetNode.type.isPN() && (edge.type == SbgnType.CONSUMPTION || edge.type == SbgnType.PRODUCTION)) edge.targetPort.type = SbgnType.INPUT_AND_OUTPUT else if(edge.targetNode.type.isLogic() && (edge.type == SbgnType.LOGIC_ARC || edge.type.isRegulation())) edge.targetPort.type = SbgnType.INPUT_AND_OUTPUT } //(II) set port type according to orientation and approximate port location for (node in graph.nodes) { if (node.type.isPN()) { val box = node.layout.toRectD() val isHorizontal = node.orientation == "horizontal" node.ports.forEach { port -> if (graph.edgesAt(port).size() == 0) { val p = box.convertToRatioPoint(port.location) if ((p.x < 0.25 || p.x > 0.75) && isHorizontal) { port.type = SbgnType.INPUT_AND_OUTPUT } else if ((p.y < 0.25 || p.y > 0.75) && !isHorizontal) { port.type = SbgnType.INPUT_AND_OUTPUT } } } } } //add missing ports to PNs and Logic. Heuristic adds an extra port to unoccupied side. for (node in graph.nodes) { if (node.type.isPN() || node.type.isLogic()) { val isHorizontal = node.orientation == "horizontal" if(isHorizontal) { if (node.ports.none { node.layout.convertToRatioPoint(it.location).x < 0.25 }) { graph.addPort(node, FreeNodePortLocationModel.NODE_LEFT_ANCHORED).let { if (isHorizontal) it.type = SbgnType.INPUT_AND_OUTPUT } } if (node.ports.none { node.layout.convertToRatioPoint(it.location).x > 0.75 }) { graph.addPort(node, FreeNodePortLocationModel.NODE_RIGHT_ANCHORED).let { if (isHorizontal) it.type = SbgnType.INPUT_AND_OUTPUT } } } else if(!isHorizontal) { if (node.ports.none { node.layout.convertToRatioPoint(it.location).y < 0.25 }) { graph.addPort(node, FreeNodePortLocationModel.NODE_TOP_ANCHORED).let { if (!isHorizontal) it.type = SbgnType.INPUT_AND_OUTPUT } } if (node.ports.none { node.layout.convertToRatioPoint(it.location).y > 0.75 }) { graph.addPort(node, FreeNodePortLocationModel.NODE_BOTTOM_ANCHORED).let { if (!isHorizontal) it.type = SbgnType.INPUT_AND_OUTPUT } } } } } } private fun processArcs(graph:IGraph, idMap: HashMap<String, IModelItem>, map: Map) { for (arc in map.arc) { var sourcePort: IPort? = null var sourceNode: INode? = null if (arc.source is Port) { sourcePort = idMap[(arc.source as Port).id] as IPort } else if (arc.source is Glyph) { val glyphId = (arc.source as Glyph).id when { idMap[glyphId] is INode -> sourceNode = idMap[glyphId] as INode idMap[glyphId] is IPort -> sourcePort = idMap[glyphId] as IPort else -> println("source of unknown type") } } var targetPort: IPort? = null var targetNode: INode? = null if (arc.target is Port) { targetPort = idMap[(arc.target as Port).id] as IPort } else if (arc.target is Glyph) { val glyphId = (arc.target as Glyph).id when { idMap[glyphId] is INode -> targetNode = idMap[glyphId] as INode idMap[glyphId] is IPort -> targetPort = idMap[glyphId] as IPort else -> println("target of unknown type") } } if (sourcePort == null) { sourcePort = graph.addPort(sourceNode) if (arc.start != null) { graph.setPortLocation(sourcePort, getPortLocation(arc, sourceNode!!,atSource = true )) } } if (targetPort == null) { targetPort = graph.addPort(targetNode) if (arc.end != null) { graph.setPortLocation(targetPort, getPortLocation(arc, targetNode!!, atSource = false)) } } var edge: IEdge? if (sourcePort != null && targetPort != null) { edge = graph.createEdge(sourcePort, targetPort) } else { println("can't find source/target for edge") continue } if (IOTypeMapper.getSbgnType(arc) == SbgnType.NO_TYPE) { println("can't handle arc type " + arc.clazz) } else { edge.type = IOTypeMapper.getSbgnType(arc) } arc.next.forEach { graph.addBend(edge, it.toPointD()) } if (arc.ofClazz(ArcClazz.PRODUCTION, ArcClazz.CONSUMPTION)) { val cardinalityGlyph = arc?.glyph?.firstOrNull { it.ofClazz(GlyphClazz.CARDINALITY) } if (cardinalityGlyph != null) { if (cardinalityGlyph.label?.text != null) { val label = graph.addLabel(edge, cardinalityGlyph.label.text) label.type = SbgnType.CARDINALITY SbgnBuilder.configure(graph, label, cardinalityGlyph.bbox?.toRectD()) } } } edge.graphStyle = getGraphStyle(arc.extension) SbgnBuilder.configure(graph, edge) } } private fun getEdgePoints(arc:Arc, atSource:Boolean):Pair<PointD, PointD> { return if(atSource) { val p1 = if (arc.next.any()) arc.next.first().toPointD() else arc.end.toPointD() val p2 = arc.start.toPointD() Pair(p1,p2) } else { val p1 = if(arc.next.any()) arc.next.last().toPointD() else arc.start.toPointD() val p2 = arc.end.toPointD() Pair(p1,p2) } } private fun getPortLocation(arc: Arc, terminal:INode, atSource:Boolean):PointD { return if(terminal.type.isLogic() || terminal.type.isPN() && arc.ofClazz(ArcClazz.CONSUMPTION, ArcClazz.PRODUCTION)) { arc.start.toPointD() } else { val (p1,p2) = getEdgePoints(arc, atSource) val projection = terminal.layout.center.getProjectionOnLine(p1, p2-p1) val distance = projection.distanceTo(terminal.layout.center) if(distance < 5.0) terminal.layout.center else p2 } } private fun processGlyphs(graph: IGraph, idMap: HashMap<String, IModelItem>, glyphs: List<Glyph>, parent: Glyph?) { //println("processGlyphs for parent " + ((parent?.clazz) ?: "MAP") + " " + (parent?.label?.text ?: "unnamed")) val isCompartment = { it: Glyph -> it.clazz == GlyphClazz.COMPARTMENT.toString() } val isLabel = { it: Glyph -> it.ofClazz(GlyphClazz.UNIT_OF_INFORMATION, GlyphClazz.STATE_VARIABLE) || it.ofClazz(GlyphClazz.ANNOTATION) && it.callout?.target != null } val isPort = { it: Glyph -> it.ofClazz(GlyphClazz.TERMINAL) } val compartmentGlyphs = glyphs.filter(isCompartment).sortedBy { it -> it.compartmentOrder } val labelGlyphs = glyphs.filter(isLabel) val nodeGlyphs = glyphs.filter { !isPort(it) && !isLabel(it) && !isCompartment(it) } val portGlyphs = glyphs.filter(isPort) for (glyph in compartmentGlyphs + nodeGlyphs) { //println(" Glyph with class " + glyph.clazz + " label=" + glyph.label?.text) if (IOTypeMapper.getSbgnType(glyph) == SbgnType.NO_TYPE) { println("Can't handle glyph of type " + glyph.clazz) continue } var rect = if (glyph.bbox != null) glyph.bbox.toRectD() else null if(rect != null) { if (glyph.ofClazz(GlyphClazz.OR, GlyphClazz.AND, GlyphClazz.NOT, GlyphClazz.PROCESS, GlyphClazz.ASSOCIATION, GlyphClazz.DISSOCIATION, GlyphClazz.UNCERTAIN_PROCESS, GlyphClazz.OMITTED_PROCESS)) { glyph.port.forEach { port -> rect = RectD.add(rect, port.toPointD()) } } } val node = graph.createNode() /**SbgnType Assignment */ node.type = IOTypeMapper.getSbgnType(glyph) if (parent != null) { graph.setParent(node, idMap[parent.id] as INode) } else if (glyph.compartmentRef != null) { val compartmentNode = idMap[(glyph.compartmentRef as Glyph).id] as INode graph.setParent(node, compartmentNode) } graph.setIsGroupNode(node, node.type.isComplex() || node.type == SbgnType.COMPARTMENT) val isClone = glyph.clone != null node.setSbgnProperty(SbgnPropertyKey.IS_CLONE, isClone) idMap[glyph.id] = node node.graphStyle = getGraphStyle(glyph.extension) if (glyph.label?.text != null && glyph.isSupportingLabel()) { val label = graph.addLabel(node, glyph.label.text) label.type = SbgnType.NAME_LABEL graph.setNodeLayout(node, rect) //assign node size at this point to obtain correct label param SbgnBuilder.configure(graph, label, glyph.label?.bbox?.toRectD()) } SbgnBuilder.configure(graph, node, rect) //take care. glyph.orientation defaults to "horizontal" even if it is not set at all. //this means we can't rely on it, when set to horizontal. hmmm, use some stupid heuristic if(node.type.isLogic() || node.type.isPN()) { if (glyph.orientation != "horizontal") node.orientation = "vertical" else node.orientation = getOrientationHeuristically(node) } else if(node.type == SbgnType.TAG) { if(glyph.orientation != "horizontal") node.orientation = glyph.orientation else node.orientation = "right" //heuristic based on port point would be better } glyph.port.forEach { port -> val newPort = graph.addPort(node, port.toPointD()) idMap[port.id] = newPort } if (isClone && glyph.clone?.label?.text != null) { val cloneLabel = graph.addLabel(node, glyph.clone.label.text) cloneLabel.type = SbgnType.CLONE_LABEL SbgnBuilder.configure(graph, cloneLabel, glyph.clone.label.bbox?.toRectD()) } if (glyph.glyph.any()) { processGlyphs(graph, idMap, glyph.glyph, glyph) } } processLabelGlyphs(graph, labelGlyphs, idMap, parent) for (glyph in portGlyphs) { if (glyph.ofClazz(GlyphClazz.TERMINAL)) { if (parent != null) { if (glyph.bbox != null && glyph.orientation != null) { val subMapNode = idMap[parent.id] as INode val port = graph.addPort(subMapNode) idMap[glyph.id] = port val portBox = glyph.bbox.toRectD() val portPoint = subMapNode.layout.convertToRatioPoint(when (glyph.orientation) { "right" -> PointD(portBox.x, portBox.centerY) "left" -> PointD(portBox.maxX, portBox.centerY) "up" -> PointD(portBox.centerX, portBox.maxY) "down" -> PointD(portBox.centerX, portBox.y) else -> PointD(portBox.x, portBox.centerY) }) port.apply { type = SbgnType.TERMINAL setSbgnProperty(SbgnPropertyKey.ORIENTATION, glyph.orientation) setSbgnProperty(SbgnPropertyKey.TERMINAL_SIZE, portBox.toSizeD()) setSbgnProperty(SbgnPropertyKey.TERMINAL_LABEL, glyph.label?.text) } SbgnBuilder.configure(graph, port, portPoint) } } else { println("found terminal without a parent") } } } } private fun getGraphStyle(ext: SBGNBase.Extension?):GraphStyle<SbgnType>? { return if(ext != null) { val styleElem = ext.any?.firstOrNull{ it.tagName == "style" && it.namespaceURI == krayonNS} styleElem?.attributes?.getNamedItem("idRef")?.nodeValue?.let { idStyleMap[it] } } else null } private fun getOrientationHeuristically(node:INode):String { var portBox = RectD.fromCenter(node.layout.center, SizeD(1.0,1.0)) node.ports.forEach { portBox = RectD.add(portBox, it.location) } if(portBox.width > 1.0 || portBox.height > 1.0) { if(portBox.width > portBox.height) return "horizontal" else if(portBox.width < portBox.height) return "vertical" } //if that doesn't work: try use node size if(node.layout.width > node.layout.height) return "horizontal" else if(node.layout.width < node.layout.height) return "vertical" //if all fails use some default return "horizontal" } private fun processLabelGlyphs(graph: IGraph, labelGlyphs: List<Glyph>, idMap: HashMap<String, IModelItem>, parent: Glyph?) { for (glyph in labelGlyphs) { if (glyph.ofClazz(GlyphClazz.ANNOTATION)) { if (glyph.callout?.target != null) { val node = idMap[(glyph.callout.target as Glyph).id] as INode val text = glyph.label?.text ?: "<EMPTY>" val label = graph.addLabel(node, text) label.type = SbgnType.CALLOUT_LABEL val labelBox = glyph.bbox?.toRectD() val calloutPoint = if (glyph.callout.point != null) { node.layout.convertToRatioPoint(glyph.callout.point.toPointD()) } else { PointD.ORIGIN } label.setSbgnProperty(SbgnPropertyKey.CALLOUT_POINT, calloutPoint) SbgnBuilder.configure(graph, label, labelBox) } } else if (glyph.ofClazz(GlyphClazz.UNIT_OF_INFORMATION)) { if (parent != null) { val node = idMap[parent.id] as INode val text = glyph.label?.text ?: "???" val label = graph.addLabel(node, text) label.type = SbgnType.UNIT_OF_INFORMATION val labelBox = glyph.bbox?.toRectD() SbgnBuilder.configure(graph, label, labelBox) } } else if (glyph.ofClazz(GlyphClazz.STATE_VARIABLE)) { if (parent != null) { val node = idMap[parent.id] as INode val text = if (glyph.state?.variable != null) (glyph.state?.value ?: "") + "@" + (glyph.state?.variable ?: "") else (glyph.state?.value ?: "") val label = graph.addLabel(node, text) label.type = SbgnType.STATE_VARIABLE val labelBox = glyph.bbox?.toRectD() SbgnBuilder.configure(graph, label, labelBox) } } else { println("Can't handle label type " + glyph.clazz) } } } }
0
Kotlin
0
1
d40dc53b35367a81099b929a22b1b36f8f601a42
22,155
krayon4sbgn
Apache License 2.0
app/storybook/src/main/java/com/yourssu/storybook/atom/SearchTextFieldViewModel.kt
yourssu
364,290,281
false
null
package com.yourssu.storybook.atom import android.app.Application import androidx.lifecycle.MutableLiveData import com.yourssu.design.system.atom.Toggle import com.yourssu.design.undercarriage.base.TextField import com.yourssu.storybook.BaseViewModel class SearchTextFieldViewModel(application: Application): BaseViewModel(application) { val placeholderTextString = MutableLiveData<String>("placeholderText") val isDisable: MutableLiveData<Boolean> = MutableLiveData(false) val disableSelectListener = object : Toggle.SelectedListener { override fun onSelected(boolean: Boolean) { isDisable.value = boolean } } val onPlaceholderTextChangedListener = object : TextField.OnTextChanged { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { s?.toString()?.let { placeholderTextString.value = it } } } }
2
Kotlin
0
9
58364077175f882def5108e654f51667b9d3af36
914
YDS-Android
MIT License
BazaarPay/src/main/java/ir/cafebazaar/bazaarpay/models/Resource.kt
cafebazaar
489,705,723
false
null
package ir.cafebazaar.bazaarpay.models import ir.cafebazaar.bazaarpay.data.bazaar.models.ErrorModel import java.io.Serializable internal data class Resource<out T>( val resourceState: ResourceState, val data: T? = null, val failure: ErrorModel? = null ) : Serializable { val isSuccess = resourceState is ResourceState.Success val isLoading = resourceState is ResourceState.Loading val isEmpty = resourceState is ResourceState.Success && data == null val isError = resourceState is ResourceState.Error fun getError(): Throwable = failure ?: Throwable("null") companion object { fun <T> unKnown( data: T? = null, failure: ErrorModel? = null ) = Resource<T>(ResourceState.UnKnown, data, failure) fun <T> loaded( data: T? = null, failure: ErrorModel? = null ) = Resource<T>(ResourceState.Success, data, failure) fun <T> loading( data: T? = null, failure: ErrorModel? = null ) = Resource<T>(ResourceState.Loading, data, failure) fun <T> failed( data: T? = null, failure: ErrorModel? = null ) = Resource<T>(ResourceState.Error, data, failure) } }
2
Kotlin
1
9
284b5cfcb288172730b7ef1d292a86eb1a6e5f85
1,252
BazaarPay
Apache License 2.0
walletconnect-core/src/test/java/walletconnect/core/cryptography/IsHexTest.kt
jemshit
510,397,898
false
null
/** * MIT License * Copyright (c) 2022 <NAME> */ package walletconnect.core.cryptography import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class IsHexTest { @Test fun validNumbers() { assertTrue("0123456789".isHex()) } @Test fun validChars() { assertTrue("abcdef".isHex()) } @Test fun validCharsUppercase() { assertTrue("ABCDEF".isHex()) } @Test fun validCharsMixedcase() { assertTrue("abCDef".isHex()) } @Test fun validMixed() { assertTrue("012ab3435C57D7e76f".isHex()) } @Test fun invalidChars() { assertFalse("gHij".isHex()) } @Test fun invalidAndValidMixedChars() { assertFalse("abCghI340j".isHex()) } @Test fun invalidCharsValidNumbers() { assertFalse("20984ijH".isHex()) } @Test fun oddLength() { assertFalse("abc".isHex(evenLength = true)) } }
0
Kotlin
2
19
c00c9481a9ce872c8376a0efd7bd2fd7816ef4b5
988
WalletConnect
MIT License
src/main/kotlin/dev/franckyi/karith/impl/KthOperatorImpl.kt
skyecodes
521,620,818
false
{"Kotlin": 95615}
package dev.franckyi.karith.impl import dev.franckyi.karith.api.KthOperator internal data class KthOperatorImpl( override val key: String, override val precedence: Int, override val leftAssociative: Boolean, private val operation: (Double, Double) -> Double ) : KthOperator { override fun apply(left: Double, right: Double): Double = operation(left, right) }
0
Kotlin
0
1
a025ab2a288280e4f3b9a45296dc9a6d39ec6bc1
380
Karith
MIT License
app/src/main/java/cz/muni/fi/umimecesky/game/robots/LevelAdapter.kt
mareksabo
82,814,524
false
null
/* * Copyright (c) 2018 <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 cz.muni.fi.umimecesky.game.robots import androidx.recyclerview.widget.RecyclerView import android.view.View import android.view.ViewGroup import android.widget.TextView import com.akexorcist.roundcornerprogressbar.RoundCornerProgressBar import cz.muni.fi.umimecesky.R import cz.muni.fi.umimecesky.game.shared.model.RaceConcept import cz.muni.fi.umimecesky.game.shared.util.GuiUtil.inflate class LevelAdapter(private val items: List<RaceConcept>, private val listener: (RaceConcept) -> Unit) : RecyclerView.Adapter<LevelAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(parent.inflate(R.layout.column_category_race)) override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(items[position], listener) override fun getItemCount(): Int = items.size class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val sectionName = itemView.findViewById<TextView>(R.id.sectionName) private val currentLevel = itemView.findViewById<TextView>(R.id.currentLevel) private val progressBar = itemView.findViewById<RoundCornerProgressBar>(R.id.levelProgress) fun bind(item: RaceConcept, listener: (RaceConcept) -> Unit) = with(itemView) { sectionName.text = item.name val currentLevelNumber = item.currentLevel currentLevel.text = currentLevelNumber.toString() progressBar.max = (item.numberOfLevels - 1).toFloat() progressBar.progress = (currentLevelNumber - 1).toFloat() progressBar.secondaryProgress = currentLevelNumber.toFloat() setOnClickListener { listener(item) } } } }
1
Kotlin
0
4
488245ce33b0abace0d21a153ac44e348fd6d1f2
2,376
umimecesky
Apache License 2.0
app/src/main/java/com/beam/composecatalog/MyTextAndTextField.kt
breduarm
788,251,717
false
{"Kotlin": 34375}
package com.beam.composecatalog import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.beam.composecatalog.ui.theme.Compose_catalogTheme @Composable fun MyStateHosting() { var entryText by remember { mutableStateOf("Default text") } MyTextFieldStateHosting(entryText = entryText) { entryText = it } } @Composable fun MyTextFieldStateHosting(entryText: String, onValueChange: (String) -> Unit) { TextField(value = entryText, onValueChange = onValueChange) } @Composable fun MyTextFieldOutlined() { var entryText by remember { mutableStateOf("") } Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { OutlinedTextField( modifier = Modifier.padding(24.dp), value = entryText, onValueChange = { entryText = it }, label = { Text(text = "Enter your text here") }, colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = Color.Magenta, unfocusedBorderColor = Color.Cyan, ) ) } } @Composable fun MyTextFieldAdvance() { var entryText by remember { mutableStateOf("") } TextField(value = entryText, onValueChange = { entryText = if (it.contains("a")) { it.replace("a", "") } else { it } }, label = { Text(text = "Enter your text") }) } @Composable fun MyTextField() { var entryText by remember { mutableStateOf("Default text") } TextField(value = entryText, onValueChange = { entryText = it }) } @Composable fun MyText() { Column(modifier = Modifier.fillMaxSize()) { Text(text = "This is a very simple text") Text(text = "This a text with color", color = Color.Magenta) Text(text = "This a text with fontWeight", fontWeight = FontWeight.Bold) Text(text = "This a text with fontFamily cursive", fontFamily = FontFamily.Cursive) Text( text = "This a text with textDecoration line through", textDecoration = TextDecoration.LineThrough ) Text( text = "This a text with textDecoration under line", textDecoration = TextDecoration.Underline ) Text( text = "This a text with textDecoration line through and under line", textDecoration = TextDecoration.combine( listOf(TextDecoration.LineThrough, TextDecoration.Underline) ) ) Text(text = "This is a text with font size", fontSize = 30.sp) } } @Preview(showBackground = true) @Composable fun TextDefaultPreview() { Compose_catalogTheme { MyStateHosting() } }
0
Kotlin
0
0
ed274e84849c70e0c4f732fef8421938a26d2703
3,655
compose_catalog
MIT License
sample/src/main/java/com/wada811/viewlifecycleproperty/sample/SampleActivity.kt
wada811
277,118,088
false
null
package com.wada811.viewlifecycleproperty.sample import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import com.wada811.databinding.dataBinding import com.wada811.viewlifecycleproperty.sample.databinding.SampleActivityBinding import com.wada811.viewlifecycleproperty.sample.databinding.SampleListItemBinding import com.wada811.viewlifecycleproperty.sample.sample1_val_by_lazy.Sample1Activity import com.wada811.viewlifecycleproperty.sample.sample2_var_nullable.Sample2Activity import com.wada811.viewlifecycleproperty.sample.sample3_lateinit_var.Sample3Activity import com.wada811.viewlifecycleproperty.sample.sample4_auto_cleared.Sample4Activity import com.wada811.viewlifecycleproperty.sample.sample5_view_lifecycle.Sample5Activity class SampleActivity : AppCompatActivity(R.layout.sample_activity) { private val binding: SampleActivityBinding by dataBinding() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Samples.values().forEach { sample -> val itemBinding = DataBindingUtil.inflate<SampleListItemBinding>( layoutInflater, R.layout.sample_list_item, binding.container, false ) itemBinding.viewModel = sample itemBinding.root.setOnClickListener { startActivity(sample.createIntent(this@SampleActivity)) } binding.container.addView(itemBinding.root) } } enum class Samples(private val clazz: Class<out Activity>) { Sample1(Sample1Activity::class.java) { override fun toString(): String = "val by lazy" }, Sample2(Sample2Activity::class.java) { override fun toString(): String = "var nullable" }, Sample3(Sample3Activity::class.java) { override fun toString(): String = "lateinit var" }, Sample4(Sample4Activity::class.java) { override fun toString(): String = "AutoClearedValue" }, Sample5(Sample5Activity::class.java) { override fun toString(): String = "ViewLifecycleProperty" }, ; fun createIntent(context: Context) = Intent(context, clazz) } }
0
Kotlin
0
7
68c7e990c9aa7210faf12a8655bb71ccbfce869c
2,403
ViewLifecycleProperty
Apache License 2.0
app/src/main/java/com/gbros/tabslite/data/chord/Chord.kt
More-Than-Solitaire
249,057,023
false
{"Kotlin": 310724}
package com.gbros.tabslite.data.chord import android.util.Log import com.gbros.tabslite.data.AppDatabase import com.gbros.tabslite.utilities.UgApi import kotlin.math.abs private const val LOG_NAME = "tabslite.ICompleteChord" object Chord { // region public methods suspend fun ensureAllChordsDownloaded(chords: List<String>, db: AppDatabase) { // find chords that aren't in the database val alreadyDownloadedChords = db.chordVariationDao().findAll(chords) val chordsToDownload = chords.filter { usedChord -> !alreadyDownloadedChords.contains(usedChord) } // download if (chordsToDownload.isNotEmpty()) { UgApi.updateChordVariations(chordsToDownload, db) } } fun transposeChord(chord: CharSequence, halfSteps: Int): String { val numSteps = abs(halfSteps) val up = halfSteps > 0 val chordParts = chord.split('/').toTypedArray() // handle chords with a base note like G/B for (i in chordParts.indices) { if (chordParts[i] != "") { if (up) { // transpose up for (j in 0 until numSteps) { chordParts[i] = transposeUp(chordParts[i]) } } else { // transpose down for (j in 0 until numSteps) { chordParts[i] = transposeDown(chordParts[i]) } } } } return chordParts.joinToString("/") } open suspend fun getChord(chord: String, db: AppDatabase): List<ChordVariation> { val downloadedChords = db.chordVariationDao().getChordVariations(chord) return downloadedChords.ifEmpty { UgApi.updateChordVariations(listOf(chord), db).getOrDefault(chord, listOf()) } } // endregion // region private methods /** * Helper function to transpose a chord name up by one half step * * @param text: The chord name (e.g. A#m7) to transpose (e.g. Bm7) */ private fun transposeUp(text: String): String { return when { text.startsWith("A#", true) -> "B" + text.substring(2) text.startsWith("Ab", true) -> "A" + text.substring(2) text.startsWith("A", true) -> "A#" + text.substring(1) text.startsWith("Bb", true) -> "B" + text.substring(2) text.startsWith("B", true) -> "C" + text.substring(1) text.startsWith("C#", true) -> "D" + text.substring(2) text.startsWith("C", true) -> "C#" + text.substring(1) text.startsWith("D#", true) -> "E" + text.substring(2) text.startsWith("Db", true) -> "D" + text.substring(2) text.startsWith("D", true) -> "D#" + text.substring(1) text.startsWith("Eb", true) -> "E" + text.substring(2) text.startsWith("E", true) -> "F" + text.substring(1) text.startsWith("F#", true) -> "G" + text.substring(2) text.startsWith("F", true) -> "F#" + text.substring(1) text.startsWith("G#", true) -> "A" + text.substring(2) text.startsWith("Gb", true) -> "G" + text.substring(2) text.startsWith("G", true) -> "G#" + text.substring(1) else -> { Log.e(LOG_NAME, "Weird Chord not transposed: $text") text } } } /** * Helper function to transpose a chord name down by one half step * * @param text: The chord name (e.g. A#m7) to transpose (e.g. Am7) */ private fun transposeDown(text: String): String { return when { text.startsWith("A#", true) -> "A" + text.substring(2) text.startsWith("Ab", true) -> "G" + text.substring(2) text.startsWith("A", true) -> "G#" + text.substring(1) text.startsWith("Bb", true) -> "A" + text.substring(2) text.startsWith("B", true) -> "A#" + text.substring(1) text.startsWith("C#", true) -> "C" + text.substring(2) text.startsWith("C", true) -> "B" + text.substring(1) text.startsWith("D#", true) -> "D" + text.substring(2) text.startsWith("Db", true) -> "C" + text.substring(2) text.startsWith("D", true) -> "C#" + text.substring(1) text.startsWith("Eb", true) -> "D" + text.substring(2) text.startsWith("E", true) -> "D#" + text.substring(1) text.startsWith("F#", true) -> "F" + text.substring(2) text.startsWith("F", true) -> "E" + text.substring(1) text.startsWith("G#", true) -> "G" + text.substring(2) text.startsWith("Gb", true) -> "F" + text.substring(2) text.startsWith("G", true) -> "F#" + text.substring(1) else -> { Log.e(LOG_NAME, "Weird Chord not transposed: $text") text } } } // endregion }
31
Kotlin
4
65
1c934bb1e0c873dd1f9884afe5468c4e4bc5ccd6
4,974
Tabs-Lite
Apache License 2.0
shared/src/commonMain/kotlin/hr/dtakac/prognoza/shared/domain/GetForecastProvider.kt
davidtakac
387,038,134
false
null
package hr.dtakac.prognoza.shared.domain import hr.dtakac.prognoza.shared.domain.data.SettingsRepository import hr.dtakac.prognoza.shared.entity.ForecastProvider class GetForecastProvider internal constructor( private val settingsRepository: SettingsRepository ){ suspend operator fun invoke(): ForecastProvider = settingsRepository.getForecastProvider() }
24
Kotlin
11
194
2ff651b1b6470441fc81066f84271feacc855195
366
prognoza
MIT License
shared/src/commonMain/kotlin/hr/dtakac/prognoza/shared/domain/GetForecastProvider.kt
davidtakac
387,038,134
false
null
package hr.dtakac.prognoza.shared.domain import hr.dtakac.prognoza.shared.domain.data.SettingsRepository import hr.dtakac.prognoza.shared.entity.ForecastProvider class GetForecastProvider internal constructor( private val settingsRepository: SettingsRepository ){ suspend operator fun invoke(): ForecastProvider = settingsRepository.getForecastProvider() }
24
Kotlin
11
194
2ff651b1b6470441fc81066f84271feacc855195
366
prognoza
MIT License
app/src/main/java/jp/yn/android/light/reader/ItemListFragment.kt
yuukiw00w
186,211,214
false
{"Kotlin": 10759, "Ruby": 1176, "Shell": 368}
package jp.yn.android.light.reader import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProviders import androidx.navigation.findNavController import androidx.recyclerview.widget.LinearLayoutManager import jp.co.yahoo.android.repository.item.ItemListRepository import jp.yn.android.light.reader.databinding.ItemListFragmentBinding class ItemListFragment : Fragment() { private lateinit var viewModel: ItemListViewModel private lateinit var binding: ItemListFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DataBindingUtil.inflate(inflater, R.layout.item_list_fragment, container, false) binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders .of(this, ItemListViewModel.Factory(ItemListRepository())) .get(ItemListViewModel::class.java) binding.viewModel = viewModel binding.recyclerView.layoutManager = LinearLayoutManager(context) val adapter = ItemListRecyclerAdapter { view, itemEntity -> val action = ItemListFragmentDirections.actionListToContentFragment(itemEntity) view.findNavController().navigate(action) } binding.recyclerView.adapter = adapter viewModel.onCreate() } }
0
Kotlin
0
0
b325597621616fdcb0a37e2f3d73b613f02e3f90
1,696
QiitaReaderForAndroid
Apache License 2.0
app/src/main/java/jp/cordea/mackerelclient/adapter/MonitorAdapter.kt
CORDEA
50,841,867
false
null
package jp.cordea.mackerelclient.adapter import android.content.Context import com.xwray.groupie.GroupAdapter import com.xwray.groupie.ViewHolder import jp.cordea.mackerelclient.api.response.MonitorDataResponse import jp.cordea.mackerelclient.di.FragmentScope import jp.cordea.mackerelclient.view.MonitorListItem import jp.cordea.mackerelclient.view.MonitorListItemModel import jp.cordea.mackerelclient.view.MonitorSectionListItem import jp.cordea.mackerelclient.view.MonitorSectionListItemModel import javax.inject.Inject import javax.inject.Provider @FragmentScope class MonitorAdapter @Inject constructor( private val context: Context, private val sectionListItem: Provider<MonitorSectionListItem>, private val listItem: Provider<MonitorListItem> ) : GroupAdapter<ViewHolder>() { fun update(items: Map<String, List<MonitorDataResponse>>) { clear() items.forEach { entry -> add(sectionListItem.get().update(MonitorSectionListItemModel(entry.key))) addAll(entry.value.map { listItem.get().update(MonitorListItemModel.from(context, it)) }) } } }
0
Kotlin
1
4
20041d0cec421ec90c376d4259efdca8caee3bdd
1,144
MackerelClient
Apache License 2.0
wear/src/main/java/github/vodianov/hoursignal/dto/settings/MuteSignalRegion.kt
shredd0r
756,834,042
false
{"Kotlin": 19754}
package github.vodianov.hoursignal.dto.settings import kotlinx.serialization.Serializable @Serializable class MuteSignalRegion( val muteWhenCharging: Boolean, val muteWhenDNDOn: Boolean, val muteWhenAirplaneModeOn: Boolean) { }
0
Kotlin
0
0
b922605e2d28cf0d61edf8a0cd16beda19f3821a
241
hour-signal-wear-os
Apache License 2.0
bottom_navigation/android/app/src/main/kotlin/com/cooray/nipuna/bottom_navigation/MainActivity.kt
NipunaCooray
327,271,563
false
{"Dart": 18667, "Swift": 1212, "Kotlin": 415, "Objective-C": 114}
package com.cooray.nipuna.bottom_navigation import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
f78b6095d8038a0f32aaec91ff7a1ab97a41b828
140
flutter-snippets
MIT License
app/src/main/java/com/mburakcakir/taketicket/data/remote/model/event/Genre.kt
mburakcakir
319,590,139
false
null
package com.mburakcakir.taketicket.data.remote.model.event data class Genre( val document_source: DocumentSource, val id: Int, val image: String, val images: Images, val name: String, val primary: Boolean, val slug: String )
0
Kotlin
2
3
d8f1c95a6acac306d349d82c2d1fe91fcb739f09
253
TakeTicket
Apache License 2.0
domain/src/main/java/com/safetyheads/akademiaandroida/domain/repositories/TokenRepository.kt
SafetyHeads
590,936,924
false
null
package com.safetyheads.akademiaandroida.domain.repositories import kotlinx.coroutines.flow.Flow interface TokenRepository{ fun getMessagingToken(): Flow<String> }
7
Kotlin
0
0
c150bf378ff23a047bc23d19753b000f71b88511
169
Akademia-Androida-2023
Apache License 2.0
app/src/main/java/com/johannliebert/jisho/feature_joshi/data/remote/DictionaryAPI.kt
Paulr756756
481,305,351
false
{"Kotlin": 11036}
package com.johannliebert.jisho.feature_joshi.data.remote import com.johannliebert.jisho.feature_joshi.data.remote.dto.WordInfoDto import retrofit2.http.* interface DictionaryAPI { @GET("/api/v2/entries/en/{word}") suspend fun getWordInfo( @Path("word") word:String ) : List<WordInfoDto> }
0
Kotlin
0
0
9115fa835b18560f57e3f8976f0994b199f74820
311
Jisho
MIT License
ERMSCompany/src/main/java/com/kust/erms_company/di/GlideModule.kt
sabghat90
591,653,827
false
null
package com.kust.erms_company.di import com.bumptech.glide.module.AppGlideModule @com.bumptech.glide.annotation.GlideModule class GlideModule : AppGlideModule()
3
Kotlin
1
7
12030507bbd683a1004a19eb9eda78462fe48b81
162
ERMS
MIT License
app/src/main/java/com/example/proyectojunio/provider/SuperheroesProvider.kt
MrSpiderPablo
774,884,267
false
{"Kotlin": 23920, "Java": 7060}
package com.example.proyectojunio.provider import com.example.proyectojunio.R import com.example.proyectojunio.models.Superheroes object SuperheroesProvider { val misSuperheroes = arrayListOf<Superheroes>( Superheroes("Daredevil", "<NAME>", R.drawable.daredevil, "<NAME> creció en el peligroso barrio de Hell's Kitchen." + "Cuando al intentar salvar a un anciano de ser atropellado," + " unos tanques con productos qúimicos se le vuelcan en los ojos, dejandolo" + " completamente ciego pero agudizando sus demás sentidos." + "Cuando su padre es asesinado al negarse a perder en un combate de boxeo," + " Matt decide emprender un camino contra la injusticia y la corrupción," + " convirtiéndose en el diablo guardián de Hell's Kitchen: Daredevil.", "Daredevil #1(abril de 1964)"), Superheroes("Superman", "<NAME>, KAL-EL", R.drawable.superman, "Enviado desde un planeta al borde de la destrucción y criado por una familia de rancheros," + "<NAME> se convierte en el mayor héroe de todos los tiempos: Superman.", "Action Comics #1(abril de 1938"), Superheroes("Batman", "<NAME>", R.drawable.batman, "Al prsenciar la muerte de sus padres a manos de un delincuente de poca monta," + "el joven <NAME> emprenderá un camino de venganza contra aquellos criminales que corrompen su ciudad natal: Gotham.", "Detective Comics #27(abril de 1939)"), Superheroes("Spider-man", "<NAME>", R.drawable.spiderman, "Tras ser mordido por una araña genéticamente modificada, el joven <NAME> adquiere poderes extraordinarios," + "como pegarse a las paredes, fuerza y reflejos sobrehumanos y un gran sentido del humor. Sin embargo, la muerte de su tío de Ben" + "a manos de un criminal al que él dejó escapar le dará una importante lección:" + "Un gran poder conlleva una gran responsabilidad.", "Amazing Fantasy #15(agosto de 1962"), Superheroes("Hulk", "<NAME>", R.drawable.hulk, "Cuando el científico <NAME>, tratando de salvar a un joven llamado <NAME>," + "sufre el impacto de una explosión de rayos gamma, su vida cambia para siempre." + "Cada vez que se enfafa os ufre una situacíon de gran estrés, se transforma en un enorme e incontrolable" + "monstruo verde con fuerza sobrehumana y una rabia incontrolable.", "The Incredible Hulk #1(mayo de 1962)"), Superheroes("Iron Man", "<NAME>", R.drawable.iron_man, "Cuando el fabricante de armas <NAME> es emboscado y secuestrado en Oriente Medio" + "por un grupo de terroristas que buscan usar sus propias armas para sus planes de destrucción," + "un hombre llamado Jinsen le hará ver que puede ser mejor." + "Tras escapar creando una armadura, Tony dedicará el resto de su vida a crear un sinfín de armaduras" + "que le ayudarán a hacer del mundo un lugar mejor.", "Tales of Suspense #39(marzo de 1963)"), Superheroes("Lobezno", "<NAME> Logan", R.drawable.lobezno, "Nacido como un mutante con un gran olfato, factor de curación y garras de hueso replegables," + "a Logan se le implantó el metal concoido como adamantium, volviéndolo completamente indestructible." + "Tras vagar durante un tiempo, terminaría uniéndose a los X-Men," + "un grupo de mutantes que lucha por la igualdad entre humanos y mutantes.", "The Incredible Hulk #180(octubre de 1974)"), Superheroes("<NAME>", "<NAME>, <NAME>, <NAME>", R.drawable.moon_knight, "<NAME>, un conocido mercenario, es asesinado por su antiguo socio, Bushman." + "Sin embargo, es revivido por el antiguo dios egipcio Khonsu," + "convirtiéndolo en su avatar de la luna, su puño de la venganza." + "O al menos eso cree, ya que su trastorno de personalidad múltiple le hace cuestionarse" + "si realmente fue revivido o todo fue una fantasía.", "Werewolf by Night #32(agosto de 1975)"), Superheroes("Wonder Woman", "<NAME>", R.drawable.wonder_woman, "Themyscira es una isla habitada por mujeres bendecidas por los dioses." + "Estas mujeres son conocidas como las amazonas." + "Un día, Hipólita, reina de las amazonas, esculpió una muñeca de barro para pedirle a los dioses" + "que le dieran vida. Ellos aceptaron y conviertieron a la muñeca en una niña llamada Diana," + "quien crecería como una amazona y guardiana de la paz en el mundo de los hombres.", "Wonder Woman Vol 1 #1(agosto de 1942)"), Superheroes("Aquaman", "<NAME>", R.drawable.aquaman, "Mitad humano y mitad atlante, Aquaman es el rey de Atlantis y protector de los siete mares." + "Posee habilidades como superfuerza, supervelocidad, piel impenetrable y la capacidad de comunicarse con la flora marina." + "Es uno de los miembros más venerados de la Liga de la Justicia.", "More Fun Comics #73(noviembre de 1941)"), Superheroes("<NAME>", "<NAME>", R.drawable.capitan_america, "Alistándose en el ejército a pesar de su débil condición física," + "<NAME> recibe el suero del supersoldado, el cuál le dará fuerza y agilidad sobrehumana." + "Combatiendo a los nazis en la Segunda Guerra Mundial, en una de sus misiones " + "Steve resultaría caído en combate y congelado en estado criogénico." + "Al despertar 70 años después, descubre que el mundo ha cambiado.", "Captain America Comics #1(marzo de 1941)"), Superheroes("Thor", "<NAME>", R.drawable.thor, "Thor, hijo de Odín, " + "futuro rey del reino de Aasgard, " + "protector de los nueve reinos." + "Miembro honorable de los Vengadores." + "El Dios del Trueno y su martillo Mjolnir son el temor de sus enemigos.", "Journey Into Mystery #85(agosto de 1962)"), Superheroes("Los Cuatro Fantásticos", "<NAME>, Sue Storm, <NAME>, <NAME>", R.drawable.cuatro_fantasticos, "La primera gran familia de Marvel." + "Tras ser alcanzados por una tormenta cósmica, " + "Reed Richards adquiere el poder de estirar cualquier parte de su cuerpo, " + "Sue Storm obtiene la capacidad de hacerse invisible," + "Johny Storm puede prender su cuerpo de fuego " + "y <NAME> se transforma en una grotesca criatura rocosa. " + "Juntos son los Cuatro Fantásticos", "The Fantastic Four #1(noviembre de 1961)") ) }
0
Kotlin
0
0
d1650e4dcaf2e4c697d9a27bd4154b211c9f077f
7,136
ProyectoFinal
MIT License
application/event-sourced-system3/src/main/kotlin/com/fraktalio/fmodel/example/eventsourcedsystem3/query/application/RestaurantEventHandler.kt
sampingantech
422,002,486
true
{"Kotlin": 194766}
/* * Copyright (c) 2021 Fraktalio D.O.O. 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.fraktalio.fmodel.example.eventsourcedsystem3.query.application import com.fraktalio.fmodel.domain.View import com.fraktalio.fmodel.example.domain.Money import com.fraktalio.fmodel.example.domain.RestaurantEvent import com.fraktalio.fmodel.example.domain.RestaurantId import com.fraktalio.fmodel.example.domain.RestaurantView import com.fraktalio.fmodel.example.eventsourcedsystem3.query.adapter.persistance.MenuItemCoroutineRepository import com.fraktalio.fmodel.example.eventsourcedsystem3.query.adapter.persistance.MenuItemR2DBCEntity import com.fraktalio.fmodel.example.eventsourcedsystem3.query.adapter.persistance.RestaurantCoroutineRepository import com.fraktalio.fmodel.example.eventsourcedsystem3.query.adapter.persistance.RestaurantR2DBCEntity import kotlinx.coroutines.runBlocking import org.axonframework.config.ProcessingGroup import org.axonframework.eventhandling.EventHandler import org.springframework.stereotype.Component import org.springframework.transaction.reactive.TransactionalOperator import org.springframework.transaction.reactive.executeAndAwait import java.util.* @Component @ProcessingGroup("restaurant") internal class RestaurantEventHandler( private val restaurantView: View<RestaurantView?, RestaurantEvent?>, private val restaurantRepository: RestaurantCoroutineRepository, private val menuItemRepository: MenuItemCoroutineRepository, private val operator: TransactionalOperator ) { // ######################################## // ############## EXTENSIONS ############## // ######################################## private fun RestaurantR2DBCEntity?.toRestaurant(menu: RestaurantView.RestaurantMenu) = when { this != null -> RestaurantView( RestaurantId(UUID.fromString(this.id)), this.name, menu, this.status ) else -> null } private fun MenuItemR2DBCEntity.toMenuItem(): RestaurantView.MenuItem = RestaurantView.MenuItem(this.id ?: "", this.menuItemId, this.name, Money(this.price)) private fun RestaurantView.toRestaurantEntity() = RestaurantR2DBCEntity( this.id.identifier.toString(), Long.MIN_VALUE, this.name, this.status, this.menu.cuisine, this.menu.status, this.menu.menuId.toString(), ) private fun RestaurantView.MenuItem.toMenuItemEntity(menuId: String, restaurantId: String) = MenuItemR2DBCEntity( this.id, this.menuItemId, menuId, restaurantId, this.name, this.price.amount ) private suspend fun RestaurantEvent.fetchState(): RestaurantView? { val restaurantEntity: RestaurantR2DBCEntity? = restaurantRepository.findById(this.identifier.identifier.toString()) val menuItemEntities = menuItemRepository.findByRestaurantId(this.identifier.identifier.toString()) return restaurantEntity?.toRestaurant( RestaurantView.RestaurantMenu( UUID.fromString(restaurantEntity.menuId), menuItemEntities.map { it.toMenuItem() }, restaurantEntity.cuisine ) ) } private suspend fun RestaurantView?.save(): RestaurantView? { operator.executeAndAwait { transaction -> try { this?.let { restaurant -> val restaurantEntity = restaurant.toRestaurantEntity() // check if it is Create or Update restaurantEntity.newRestaurant = !restaurantRepository.existsById(restaurant.id.identifier.toString()) val savedRestaurantEntity = restaurantRepository.save(restaurantEntity) restaurant.menu.items.forEach { val menuItemEntity = it.toMenuItemEntity( restaurant.menu.menuId.toString(), restaurant.id.identifier.toString() ) // check if it is Create or Update menuItemEntity.newMenuItem = !menuItemRepository.existsById(it.id) val savedMenuItemEntity = menuItemRepository.save(menuItemEntity) } } } catch (e: Exception) { transaction.setRollbackOnly() throw e } } return this } @EventHandler fun handle(event: RestaurantEvent) { runBlocking { restaurantView.evolve(event.fetchState(), event).save() } } }
1
null
0
0
1c701216078535a808ecc0d3fb295be2fba45211
5,199
fmodel-demos
Apache License 2.0
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/TLTopPeerCategoryCorrespondents.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api /** * topPeerCategoryCorrespondents#637b7ed * * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLTopPeerCategoryCorrespondents : TLAbsTopPeerCategory() { private val _constructor: String = "topPeerCategoryCorrespondents#637b7ed" override val constructorId: Int = CONSTRUCTOR_ID override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLTopPeerCategoryCorrespondents) return false if (other === this) return true return true } companion object { const val CONSTRUCTOR_ID: Int = 0x637b7ed } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
727
kotlogram-resurrected
MIT License
codegen/aws-sdk-codegen/src/main/kotlin/aws/sdk/kotlin/codegen/customization/s3/S3OperationErrorHandler.kt
awslabs
121,333,316
false
{"Kotlin": 1076968, "Smithy": 8546, "TypeScript": 1488, "JavaScript": 1134, "Dockerfile": 391}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.sdk.kotlin.codegen.customization.s3 import software.amazon.smithy.kotlin.codegen.KotlinSettings import software.amazon.smithy.kotlin.codegen.aws.protocols.core.AwsHttpBindingProtocolGenerator import software.amazon.smithy.kotlin.codegen.core.* import software.amazon.smithy.kotlin.codegen.integration.KotlinIntegration import software.amazon.smithy.kotlin.codegen.integration.SectionWriter import software.amazon.smithy.kotlin.codegen.integration.SectionWriterBinding import software.amazon.smithy.kotlin.codegen.model.buildSymbol import software.amazon.smithy.kotlin.codegen.model.expectShape import software.amazon.smithy.kotlin.codegen.rendering.ExceptionBaseClassGenerator import software.amazon.smithy.kotlin.codegen.rendering.protocol.ProtocolGenerator import software.amazon.smithy.model.Model import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.ServiceShape /** * Customized error handling for S3 */ class S3OperationErrorHandler : KotlinIntegration { override fun enabledForService(model: Model, settings: KotlinSettings): Boolean { val service = model.expectShape<ServiceShape>(settings.service) return service.isS3 } override val sectionWriters: List<SectionWriterBinding> get() = listOf(SectionWriterBinding(AwsHttpBindingProtocolGenerator.Sections.RenderThrowOperationError, overrideThrowOperationErrors)) private val overrideThrowOperationErrors = SectionWriter { writer, _ -> val ctx = writer.getContextValue(AwsHttpBindingProtocolGenerator.Sections.RenderThrowOperationError.Context) val op = writer.getContextValue(AwsHttpBindingProtocolGenerator.Sections.RenderThrowOperationError.Operation) renderThrowOperationError(ctx, op, writer) } private fun renderThrowOperationError( ctx: ProtocolGenerator.GenerationContext, op: OperationShape, writer: KotlinWriter, ) { val exceptionBaseSymbol = ExceptionBaseClassGenerator.baseExceptionSymbol(ctx.settings) val setS3ErrorMetadata = buildSymbol { name = "setS3ErrorMetadata" namespace = "${ctx.settings.pkg.name}.internal" } val parseS3ErrorResponse = buildSymbol { name = "parseS3ErrorResponse" namespace = "${ctx.settings.pkg.name}.internal" } val s3ErrorDetails = buildSymbol { name = "S3ErrorDetails" namespace = "${ctx.settings.pkg.name}.internal" } writer.write("val wrappedResponse = call.response.#T(payload)", RuntimeTypes.AwsProtocolCore.withPayload) .write("val wrappedCall = call.copy(response = wrappedResponse)") .write("") writer.withInlineBlock("val errorDetails = try {", "} ") { // customize error matching to handle HeadObject/HeadBucket error responses which have no payload withInlineBlock("if (payload == null) {", "} ") { withInlineBlock("if (call.response.status == #T.NotFound) {", "} ", RuntimeTypes.Http.StatusCode) { write("#T(code = #S)", s3ErrorDetails, "NotFound") } withInlineBlock("else {", "}") { write("#T(code = #L)", s3ErrorDetails, "call.response.status.toString()") } } withInlineBlock("else {", "}") { write("#T(payload)", parseS3ErrorResponse) } } writer.withBlock("catch (ex: Exception) {", "}") { withBlock("throw #T(#S).also {", "}", exceptionBaseSymbol, "Failed to parse response as ${ctx.protocol.name} error") { write("#T(it, wrappedCall.response, null)", setS3ErrorMetadata) } } writer.withBlock("val ex = when(errorDetails.code) {", "}") { op.errors.forEach { err -> val errSymbol = ctx.symbolProvider.toSymbol(ctx.model.expectShape(err)) val errDeserializerSymbol = buildSymbol { name = "${errSymbol.name}Deserializer" namespace = ctx.settings.pkg.serde } write("#S -> #T().deserialize(context, wrappedCall, payload)", err.name, errDeserializerSymbol) } write("else -> #T(errorDetails.message)", exceptionBaseSymbol) } writer.write("") writer.write("#T(ex, wrappedResponse, errorDetails)", setS3ErrorMetadata) writer.write("throw ex") } }
79
Kotlin
49
407
287408211f193624d37678d66b0f31f457017d08
4,641
aws-sdk-kotlin
Apache License 2.0
app/src/main/java/com/myetherwallet/mewconnect/content/data/MessageSignData.kt
MyEtherWallet
152,647,742
false
null
package com.myetherwallet.mewconnect.content.data import com.google.gson.annotations.SerializedName /** * Created by BArtWell on 04.10.2018. */ data class MessageSignData( @SerializedName("address") private val address: String, @SerializedName("sig") private val signature: String )
7
Kotlin
37
49
b55589ed7729c5afd0f81ff4c1177c92df651e45
319
MEWconnect-Android
MIT License
simpleCallApi/src/main/java/com/example/callapi/error/ErrorHandler.kt
MattyOliveira
340,404,295
false
null
package com.example.callapi.error import java.io.IOException import java.net.HttpURLConnection import retrofit2.HttpException class ErrorHandler { fun handlerError(throwable: Throwable): ErrorEntity { return when(throwable) { is IOException -> ErrorEntity.Network is HttpException -> { when(throwable.code()) { HttpURLConnection.HTTP_NOT_FOUND -> ErrorEntity.NotFound HttpURLConnection.HTTP_FORBIDDEN -> ErrorEntity.AccessDenied HttpURLConnection.HTTP_UNAVAILABLE -> ErrorEntity.ServiceUnavailable else -> ErrorEntity.Unknown } } else -> ErrorEntity.Unknown } } }
0
Kotlin
0
3
d963a7742eefbb2316e8d05736835a5d0b8cab98
753
SimpleCallApi
Apache License 2.0
app/src/main/java/com/sunnyweather/android/logic/model/DailyResponse.kt
dreature1328
374,294,248
true
{"Kotlin": 38865, "Java": 4302}
package com.sunnyweather.android.logic.model import com.google.gson.annotations.SerializedName import java.util.* import kotlin.String data class DailyResponse(val code: String,val updateTime: String,val fxLink: String, val daily: List<Daily>,val refer: Refer) { data class Daily(val fxDate: Date,val sunrise: String,val sunset: String,val moonrise: String,val moonset: String,val moonPhase: String,val tempMax: Float, val tempMin: Float,val iconDay: String,val textDay: String,val iconNight: String,val textNight: String,val wind360Day: String,val windDirDay: String,val windScaleDay: String,val windSpeedDay: String,val wind360Night: String,val windDirNight: String,val windScaleNight: String,val windSpeedNight: String,val humidity: Int,val precip: Float,val pressure: Int,val vis: Int,val cloud: Int,val uvIndex: Int) // data class DailyResponse(val code: String,val updateTime: String,val fxLink: String, val daily: Daily,val refer: Refer) { // // data class Daily(val fxDate: List<Date>,val sunrise: List<String>,val sunset: List<String>,val moonrise: List<String>,val moonset: List<String>,val moonPhase: List<String>,val tempMax: List<Float>, val tempMin: List<Float>,val iconDay: List<String>,val textDay: List<String>,val iconNight: List<String>,val textNight: List<String>,val wind360Day: List<String>,val windDirDay: List<String>,val windScaleDay: List<String>,val windSpeedDay: List<String>,val wind360Night: List<String>,val windDirNight: List<String>,val windScaleNight: List<String>,val windSpeedNight: List<String>,val humidity: List<Int>,val precip: List<Int>,val pressure: List<Int>,val vis: List<Int>,val cloud: List<Int>,val uvIndex: List<Int>) data class Refer(val sources: List<String>?,val license: List<String>?) }
0
Kotlin
0
0
bcee76114a508dc5d76eb8e410eecac27b6b3e43
1,762
SunnyWeather
Apache License 2.0
processing-status-api-function-app/src/test/kotlin/test/HealthCheckFunctionTest.kt
CDCgov
679,761,337
false
{"Kotlin": 573145, "Java": 30754, "Python": 12702, "TypeScript": 7647, "JavaScript": 2382}
package test import com.azure.cosmos.CosmosClient import com.azure.cosmos.CosmosContainer import com.azure.cosmos.CosmosDatabase import com.azure.cosmos.util.CosmosPagedIterable import com.microsoft.azure.functions.ExecutionContext import com.microsoft.azure.functions.HttpRequestMessage import com.microsoft.azure.functions.HttpStatus import gov.cdc.ocio.processingstatusapi.cosmos.CosmosContainerManager import gov.cdc.ocio.processingstatusapi.functions.HealthCheckFunction import gov.cdc.ocio.processingstatusapi.model.reports.Report import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import org.mockito.Mockito import org.mockito.Mockito.mock import org.mockito.kotlin.any import org.testng.annotations.BeforeMethod import org.testng.annotations.Test import utils.HttpResponseMessageMock import java.util.* class HealthCheckFunctionTest { private lateinit var request: HttpRequestMessage<Optional<String>> private lateinit var context: ExecutionContext @BeforeMethod fun setUp() { // Initialize any mock objects or dependencies needed for testing request = mock(HttpRequestMessage::class.java) as HttpRequestMessage<Optional<String>> context = mock(ExecutionContext::class.java) // Setup method invocation interception when createResponseBuilder is called to avoid null pointer on real method call. Mockito.doAnswer { invocation -> val status = invocation.arguments[0] as HttpStatus HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status) }.`when`(request).createResponseBuilder(any()) } @Test fun testStatusBack() { mockkObject(CosmosContainerManager) val mockCosmosClient = mockk<CosmosClient>() val mockCosmosDb = mockk<CosmosDatabase>() val mockCosmosContainer = mockk<CosmosContainer>() val items = mockk<CosmosPagedIterable<Report>>() every { mockCosmosClient.getDatabase(any()) } returns mockCosmosDb every { mockCosmosDb.getContainer(any()) } returns mockCosmosContainer every { mockCosmosContainer.queryItems(any<String>(), any(), Report::class.java) } returns items // Create a HealthCheckFunction instance val healthCheckFunction = HealthCheckFunction(request) // call HealthCheckFunction val response = healthCheckFunction.run() assert(response.status == HttpStatus.INTERNAL_SERVER_ERROR) } @Test fun testFailureStatusBack() { val mockCosmosClient = mockk<CosmosClient>() every { mockCosmosClient.getDatabase(any()) } throws (Exception("CosmosDB error")) // Create a HealthCheckFunction instance val healthCheckFunction = HealthCheckFunction(request) // call HealthCheckFunction val response = healthCheckFunction.run() } }
2
Kotlin
0
1
570ec1df411691da32254d5d61f9cdbe1cfabb12
2,861
data-exchange-processing-status
Apache License 2.0
Projects/Reddit/app/src/main/java/ademar/study/reddit/plataform/factories/IntentFactory.kt
ademar111190
76,153,266
false
null
package ademar.study.reddit.plataform.factories import android.content.Intent import javax.inject.Inject class IntentFactory @Inject constructor() { fun makeIntent(): Intent { return Intent() } }
0
Kotlin
1
1
65466ea1c6e4f75ae9791826a428c7dd8e101f98
216
Studies
MIT License
module_home/src/main/java/com/czl/module_home/adapter/RegistrationSettlementPayAdapter.kt
pigletzzzzzz
516,985,475
false
{"Kotlin": 723880, "Java": 176802}
package com.czl.module_home.adapter import androidx.recyclerview.widget.DiffUtil import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder import com.czl.lib_base.binding.command.BindingCommand import com.czl.lib_base.binding.command.BindingConsumer import com.czl.lib_base.data.bean.PayTypeBean import com.czl.module_home.R import com.czl.module_home.databinding.AdapterRegistrationSettlementPayBinding import com.czl.module_home.fragment.RegistrationSettlementFragment /** * 联系邮箱 <EMAIL> * 创建时间: 16:22 * 描述: */ class RegistrationSettlementPayAdapter(val registrationSettlementFragment: RegistrationSettlementFragment) : BaseQuickAdapter<PayTypeBean, BaseDataBindingHolder<AdapterRegistrationSettlementPayBinding>>( R.layout.adapter_registration_settlement_pay ) { override fun convert( holder: BaseDataBindingHolder<AdapterRegistrationSettlementPayBinding>, item: PayTypeBean ) { holder.dataBinding?.apply { datas = item adapter = this@RegistrationSettlementPayAdapter if (item.payName == "支付宝"){ imgPay.setImageResource(R.mipmap.icon_pay_zfb) } if (item.payName == "微信"){ imgPay.setImageResource(R.mipmap.icon_pay_wx) } if (item.select){ imgSelect.setImageResource(R.mipmap.icon_select_yes) }else{ imgSelect.setImageResource(R.mipmap.icon_select_no) } } } val onPayTypeCommand:BindingCommand<Any> = BindingCommand(BindingConsumer { if (it is PayTypeBean){ for (payType:PayTypeBean in data){ if (payType.payName == it.payName){ payType.select = true registrationSettlementFragment.viewModel.payMode.set(payType.payMode) registrationSettlementFragment.viewModel.payName.set(payType.payEnglishName) }else{ payType.select = false } } notifyDataSetChanged() } }) val diffUtil = object : DiffUtil.ItemCallback<PayTypeBean>(){ override fun areItemsTheSame(oldItem: PayTypeBean, newItem: PayTypeBean): Boolean { return oldItem.payName == newItem.payName } override fun areContentsTheSame(oldItem: PayTypeBean, newItem: PayTypeBean): Boolean { return oldItem.select == newItem.select } } }
0
Kotlin
0
0
a3276c0149c7d2d3284a6a4d83fa5cb3874664e9
2,550
XPZX-New_Kotlin
Apache License 2.0
src/main/kotlin/no/elhub/common/orchid/theme/ElhubModule.kt
elhub
378,134,526
false
{"SCSS": 35792, "Kotlin": 9795, "JavaScript": 2867}
package no.elhub.common.orchid.theme import com.eden.orchid.api.registration.OrchidModule import com.eden.orchid.api.theme.Theme import com.eden.orchid.utilities.addToSet class ElhubModule : OrchidModule() { override fun configure() { addToSet<Theme, ElhubTheme>() } }
1
SCSS
1
0
a9700db1c0131d6da802ef6b44545bc22ffb0d19
288
common-orchid-theme
MIT License
domain/src/main/java/danggai/domain/network/changedataswitch/repository/ChangeDataSwitchRepository.kt
danggai
420,838,266
false
null
package danggai.domain.network.changedataswitch.repository import danggai.domain.core.ApiResult import danggai.domain.core.Repository import danggai.domain.network.changedataswitch.entity.ChangeDataSwitch import kotlinx.coroutines.flow.Flow interface ChangeDataSwitchRepository: Repository { suspend fun changeDataSwitch( gameId: Int, switchId: Int, isPublic: Boolean, cookie: String, ds: String, onStart: () -> Unit, onComplete: () -> Unit ): Flow<ApiResult<ChangeDataSwitch>> }
2
Kotlin
0
9
593ced62277665819bd71d97184c4e3eef2a9c9f
546
android_genshin_resin_widget
MIT License
core/src/main/kotlin/com/panelsense/core/model/mqqt/MqttMessage.kt
dawidpodolak
676,995,228
false
{"Kotlin": 209631, "Shell": 408}
package com.panelsense.core.model.mqqt data class MqttMessage( val topic: String, val message: String )
0
Kotlin
0
1
bce29e39342d4a19d027eaff745bc25bd8a7143f
113
android-panelsense
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/twotone/Searchfavorite.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.twotone import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.TwotoneGroup public val TwotoneGroup.Searchfavorite: ImageVector get() { if (_searchfavorite != null) { return _searchfavorite!! } _searchfavorite = Builder(name = "Searchfavorite", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0f, 11.0f) curveTo(20.0f, 15.97f, 15.97f, 20.0f, 11.0f, 20.0f) curveTo(6.03f, 20.0f, 2.0f, 15.97f, 2.0f, 11.0f) curveTo(2.0f, 6.03f, 6.03f, 2.0f, 11.0f, 2.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.4999f, 6.1301f) curveTo(13.1499f, 5.0301f, 13.5599f, 3.6601f, 14.7199f, 3.2901f) curveTo(15.3299f, 3.0901f, 16.0799f, 3.2601f, 16.5099f, 3.8501f) curveTo(16.9099f, 3.2401f, 17.6899f, 3.1001f, 18.2899f, 3.2901f) curveTo(19.4499f, 3.6601f, 19.8599f, 5.0301f, 19.5099f, 6.1301f) curveTo(18.9599f, 7.8801f, 17.0399f, 8.7901f, 16.5099f, 8.7901f) curveTo(15.9699f, 8.7901f, 14.0699f, 7.9001f, 13.4999f, 6.1301f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.9304f, 20.6898f) curveTo(19.4604f, 22.2898f, 20.6704f, 22.4498f, 21.6004f, 21.0498f) curveTo(22.4504f, 19.7698f, 21.8904f, 18.7198f, 20.3504f, 18.7198f) curveTo(19.2104f, 18.7098f, 18.5704f, 19.5998f, 18.9304f, 20.6898f) close() } } .build() return _searchfavorite!! } private var _searchfavorite: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
3,211
VuesaxIcons
MIT License
app/src/main/java/com/moonwinston/motivationaltodolist/ui/settings/SettingsFragment.kt
winstonmoon
321,340,734
false
null
package com.moonwinston.motivationaltodolist.ui.settings import androidx.appcompat.app.AlertDialog import androidx.fragment.app.activityViewModels import androidx.navigation.findNavController import com.moonwinston.motivationaltodolist.BuildConfig import com.moonwinston.motivationaltodolist.R import com.moonwinston.motivationaltodolist.databinding.FragmentSettingsBinding import com.moonwinston.motivationaltodolist.ui.base.BaseFragment import com.moonwinston.motivationaltodolist.ui.main.MainViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class SettingsFragment: BaseFragment<FragmentSettingsBinding, MainViewModel>() { override fun getViewBinding() = FragmentSettingsBinding.inflate(layoutInflater) override val viewModel: MainViewModel by activityViewModels() override fun initViews() { binding.notify.text = resources.getStringArray(R.array.notify_array)[viewModel.notifyIndex.value] binding.theme.text = resources.getStringArray(R.array.theme_array)[viewModel.themeIndex.value] binding.language.text = resources.getStringArray(R.array.language_array)[viewModel.languageIndex.value] binding.versionTextView.text = BuildConfig.VERSION_NAME } override fun initListeners() { binding.backButton.setOnClickListener { it.findNavController().popBackStack() } binding.notifyButton.setOnClickListener { val builder = AlertDialog.Builder(it.context, R.style.CustomAlertDialog) val notifyItems = resources.getStringArray(R.array.notify_array) val checkedItem = viewModel.notifyIndex.value builder.setTitle(resources.getString(R.string.label_notify)) .setSingleChoiceItems(notifyItems, checkedItem) { dialog, which -> binding.notify.text = notifyItems[which] viewModel.setNotify(which) dialog.dismiss() } .setNegativeButton(R.string.button_cancel) { dialog, _ -> dialog?.cancel() } builder.show() } binding.themeButton.setOnClickListener { val builder = AlertDialog.Builder(it.context, R.style.CustomAlertDialog) val themeItems = resources.getStringArray(R.array.theme_array) val checkedItem = viewModel.themeIndex.value builder.setTitle(resources.getString(R.string.label_theme)) .setSingleChoiceItems(themeItems, checkedItem) { dialog, which -> binding.theme.text = themeItems[which] viewModel.setTheme(which) dialog.dismiss() } .setNegativeButton(R.string.button_cancel) { dialog, _ -> dialog?.cancel() } builder.show() } binding.languageButton.setOnClickListener { val builder = AlertDialog.Builder(it.context, R.style.CustomAlertDialog) val languageItems = resources.getStringArray(R.array.language_array) val checkedItem = viewModel.languageIndex.value builder.setTitle(resources.getString(R.string.label_language)) .setSingleChoiceItems(languageItems, checkedItem) { dialog, which -> binding.language.text = languageItems[which] viewModel.setLanguage(which) dialog.dismiss() } .setNegativeButton(R.string.button_cancel) { dialog, _ -> dialog?.cancel() } builder.show() } } override fun initObservers() { } }
5
Kotlin
1
4
4add535cf363de121c4abf2878c07e42b8a8d49b
3,690
motivational-todo-list-android
Apache License 2.0
app/src/main/kotlin/org/geepawhill/jltk/layout/TestShape.kt
GeePawHill
661,747,103
false
null
package org.geepawhill.jltk.layout import org.geepawhill.jltk.parse.LogDetail import org.geepawhill.jltk.parse.TestResult import org.geepawhill.jltk.ui.ShapeAdder class TestShape( override val detail: LogDetail, override val x: Int, val y: Int, val result: TestResult, val tests: List<TestResult> ) : LogShape { override fun add(adder: ShapeAdder) { adder.makeTest(this, org.geepawhill.jltk.layout.ColumnDetail(detail, tests)) } }
0
Kotlin
0
0
fcd6ce06c7d223d82506a0567083187100ea3e70
470
jltk-viewer
MIT License
hardkore-ktor-server/src/test/kotlin/io/github/alonsage/hardkore/ktor/server/KtorServerommandTest.kt
alon-sage
830,704,636
false
{"Kotlin": 204889}
package io.github.alonsage.hardkore.ktor.server import io.ktor.client.HttpClient import io.ktor.client.request.get import io.ktor.client.statement.bodyAsText import io.ktor.http.isSuccess import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.retry import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import kotlin.concurrent.thread import kotlin.test.assertEquals import kotlin.test.assertTrue class KtorServerCommandTest { @Test fun `ktor server started by command responsible`() { withConfiguredHostPort { (host, port) -> val command = thread(start = true, isDaemon = true) { KtorServerCommand().main(emptyArray()) } try { runBlocking { flow { val client = HttpClient() val response = client.get("http://$host:$port/health") assertTrue(response.status.isSuccess()) assertEquals("OK", response.bodyAsText()) emit(Unit) }.retry(20) { delay(250) true }.collect() } } finally { command.interrupt() command.join() } } } }
0
Kotlin
0
0
137d983fed70bca82ff86259949f5b68a0fd73a6
1,421
hardkore-framework
Apache License 2.0
app/src/main/java/tk/zwander/lockscreenwidgets/listeners/WidgetResizeListener.kt
zacharee
262,360,174
false
null
package tk.zwander.lockscreenwidgets.listeners import android.annotation.SuppressLint import android.content.Context import android.view.MotionEvent import android.view.View import tk.zwander.lockscreenwidgets.util.widgetBlockHeight import tk.zwander.lockscreenwidgets.util.widgetBlockWidth import kotlin.math.absoluteValue import kotlin.math.sign /** * A helper class for listening to drag events on the widget resize handles. * Detects a user dragging on the specified resize handle and only triggers * an update if the user has dragged far enough. */ class WidgetResizeListener( private val context: Context, private val which: Which, private val resizeCallback: (Int) -> Unit, private val liftCallback: () -> Unit ) : View.OnTouchListener { enum class Which { LEFT, TOP, RIGHT, BOTTOM } private var origX = 0f private var origY = 0f private var prevX = 0f private var prevY = 0f //The threshold for a drag event. //Either the standard widget width or //height depending on the current handle. private val _thresholdPx: Int get() = context.run { if (which == Which.LEFT || which == Which.RIGHT) widgetBlockWidth else widgetBlockHeight } private var thresholdPx: Int = _thresholdPx @SuppressLint("ClickableViewAccessibility") override fun onTouch(v: View?, event: MotionEvent?): Boolean { when (event?.action) { MotionEvent.ACTION_DOWN -> { origX = event.rawX origY = event.rawY prevX = origX prevY = origY //The user might change the row/col count //after this class has been initialized, //so make sure the threshold stays up-to-date. //While we could just inline the getter with //this variable, it's less resource-intensive //to only update it once per gesture. thresholdPx = _thresholdPx } MotionEvent.ACTION_MOVE -> { val newX = event.rawX val newY = event.rawY val distX = newX - prevX val distY = newY - prevY if (which == Which.LEFT || which == Which.RIGHT) { if (distX.absoluteValue > thresholdPx) { prevX += thresholdPx * distX.sign resizeCallback(distX.sign.toInt()) } } else { if (distY.absoluteValue > thresholdPx) { prevY += thresholdPx * distY.sign resizeCallback(distY.sign.toInt()) } } } MotionEvent.ACTION_UP -> { liftCallback() } } return true } }
1
null
10
59
1b37deab5f279b018d689e2f2b761fbc3315d835
2,876
LockscreenWidgets
MIT License
source/data/src/main/kotlin/de/webis/webisstud/thesis/reimer/data/ModelExtensions.kt
webis-de
261,803,727
false
null
package de.webis.webisstud.thesis.reimer.data import de.webis.webisstud.thesis.reimer.model.Corpus import de.webis.webisstud.thesis.reimer.model.Document import de.webis.webisstud.thesis.reimer.model.Task import de.webis.webisstud.thesis.reimer.model.Topic import java.io.File val Corpus.dataDir get() = Data.corporaDir.resolve(name.toLowerCase()) val Task.dataDir get() = Data.tasksDir.resolve(id.toLowerCase().replace(' ', '-')) private val Task.topicsDir get() = dataDir.resolve("topics") val Topic<*>.dataDir get() = task.topicsDir.resolve(id) val <DocumentType : Document> Iterable<Topic<DocumentType>>.dataDir: File get() { return sorted().run { require(isNotEmpty()) val ids = joinToString(separator = "-") { it.id } first().task.topicsDir.resolve(ids) } } val Topic<*>.files get() = TopicFiles(this) val <DocumentType : Document> Iterable<Topic<DocumentType>>.files get() = TopicFiles(this)
0
Kotlin
3
2
c4deb7783be495458ef9c738ebd43075b3aa9bb2
970
sigir20-sampling-bias-due-to-near-duplicates-in-learning-to-rank
MIT License
src/main/kotlin/br/com/zup/pix/ChavePixExistenteException.kt
josivaldobatista
388,871,641
true
{"Kotlin": 23062}
package br.com.zup.pix class ChavePixExistenteException(message: String?) : RuntimeException(message)
0
Kotlin
0
0
fbfcb5d00ce859673c305239961caad5a8b9994f
102
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
tvm/src/boc/BagOfCellsImpl.kt
ton-community
448,983,229
false
{"Kotlin": 1194581}
package org.ton.boc import io.ktor.utils.io.core.* import org.ton.cell.Cell internal data class BagOfCellsImpl( override val roots: List<Cell> ) : BagOfCells, List<Cell> by roots { constructor(root: Cell) : this(roots = listOf(root)) override fun iterator(): Iterator<Cell> = iterator { yieldAll(roots) roots.forEach { root -> yieldAll(root.treeWalk()) } } override fun toByteArray(): ByteArray = buildPacket { writeBagOfCells(this@BagOfCellsImpl) }.readBytes() override fun toString(): String = buildString { roots.forEach { cell -> Cell.toString(cell, this) } } }
21
Kotlin
24
80
7eb82e9b04a2e518182ebfc56c165fbfcc916be9
675
ton-kotlin
Apache License 2.0
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/Actions.android.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * 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 * * 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:JvmName("AndroidActions") package androidx.compose.ui.test import androidx.compose.ui.platform.ViewRootForTest internal actual fun SemanticsNodeInteraction.performClickImpl(): SemanticsNodeInteraction { return performTouchInput { click() } } @Suppress("DocumentExceptions") // Documented in expect fun actual fun SemanticsNodeInteraction.tryPerformAccessibilityChecks(): SemanticsNodeInteraction { testContext.platform.accessibilityValidator?.let { av -> testContext.testOwner .getRoots(true) .map { // We're on Android, so we're guaranteed a ViewRootForTest (it as ViewRootForTest).view.rootView } .distinct() .run { // Synchronization needs to happen off the UI thread, so only switch to the UI // thread after the call to getRoots, but before the call to forEach so we don't // have to switch thread for each root view. testContext.testOwner.runOnUiThread { forEach { av.check(it) } } } } return this }
29
Kotlin
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
1,724
androidx
Apache License 2.0
ledger/src/main/kotlin/org/knowledger/ledger/chain/solver/StorageSolverState.kt
andrediogo92
122,662,386
false
{"Kotlin": 795385, "Rust": 9666, "Python": 228}
package org.knowledger.ledger.chain.solver import com.github.michaelbull.result.Ok import org.knowledger.ledger.chain.solver.trackers.CollectionTracker import org.knowledger.ledger.chain.solver.trackers.IndexTracker import org.knowledger.ledger.chain.solver.trackers.StorageTracker import org.knowledger.ledger.database.StorageElement import org.knowledger.ledger.database.results.DataFailure import org.knowledger.ledger.results.Outcome import org.knowledger.ledger.results.err import org.knowledger.ledger.results.ok import org.knowledger.ledger.storage.StorageAware import org.knowledger.ledger.storage.cache.BooleanLocking import org.knowledger.ledger.storage.cache.LockState import org.knowledger.ledger.storage.cache.Locking import org.knowledger.ledger.storage.cache.StoragePairs internal data class StorageSolverState( private val storageStack: ArrayDeque<StorageTracker>, private val resolvedStack: MutableList<StorageElement>, private val lockingStack: MutableList<StorageAware>, private val collectionStack: ArrayDeque<IndexTracker>, ) : StorageState { fun noElementsToStore(): Boolean = storageStack.isEmpty() fun hasElementsToStore(): Boolean = storageStack.isNotEmpty() fun purge() { storageStack.clear() resolvedStack.clear() lockingStack.clear() collectionStack.clear() } override fun pushToStore(store: StoragePairs<*>) { storageStack.addLast(StorageTracker.Element(store)) } private fun pushBegin( key: String, element: StorageElement, status: StorageTracker.Status, lock: Locking, ) { collectionStack.addLast(IndexTracker(storageStack.size)) val tracker = StorageTracker.Start(key, element, status, lock) storageStack.addLast(tracker) } override fun pushBeginToStore( key: String, element: StorageElement, status: StorageTracker.Status, lockState: LockState, ) { pushBegin(key, element, status, BooleanLocking(lockState)) } override fun pushBeginAndLock( key: String, element: StorageElement, status: StorageTracker.Status, aware: StorageAware, ) { aware.lock.lock() lockingStack.add(aware) pushBegin(key, element, status, BooleanLocking(LockState.Unlocked)) } override fun pushCollectionToStore( key: String, type: CollectionTracker.Type, ): IndexTracker { val tracker = CollectionTracker(type, when (type) { CollectionTracker.Type.List -> mutableListOf() CollectionTracker.Type.Set -> mutableSetOf() }) val index = IndexTracker(storageStack.size) storageStack.addLast(StorageTracker.Collection(key, tracker)) return index } fun resolveNext(): StorageTracker = storageStack.last() fun advanceNext(): StorageTracker = storageStack.removeLast() fun addResolvedElement(element: StorageElement) { resolvedStack.add(element) } fun resolvedIterator(): Iterator<StorageElement> = resolvedStack.iterator() fun unlockElements() { lockingStack.forEach { it.clearInvalidated() it.lock.release() } } fun trackCollection(index: IndexTracker) { collectionStack.addLast(index) } fun setToStart(tracker: StorageTracker.Start): Outcome<StorageElement?, DataFailure> = when (val start = storageStack[collectionStack.last().index]) { is StorageTracker.Start -> { if (tracker.lock.state == LockState.Unlocked) { start.element.setLinked(tracker.key, tracker.element) tracker.element.ok() } else { Ok(null) } } is StorageTracker.Collection -> { start.tracker.addNew(tracker.element) Ok(null) } is StorageTracker.Error -> DataFailure.UnexpectedClass("Stack index points to Error: $start").err() is StorageTracker.Element -> DataFailure.UnexpectedClass("Stack index points to Element: $start").err() } fun setToCollection(): Outcome<StorageElement, DataFailure> { val tracker = storageStack[collectionStack.last().index] return (tracker as? StorageTracker.Start)?.element?.ok() ?: DataFailure.UnexpectedClass( "Collection tracker points to: $tracker").err() } fun extractStart(): StorageElement = (storageStack[collectionStack.last().index] as StorageTracker.Start).element fun removeLinked(): IndexTracker = collectionStack.removeLast() }
0
Kotlin
1
3
0e5121243b9faf101b6d2ccf5bce60a657a31b4e
4,651
KnowLedger
MIT License
core-ui/src/main/java/io/github/lee/core/ui/BaseActivity.kt
291700351
467,801,205
false
null
@file:Suppress("MemberVisibilityCanBePrivate") package io.github.lee.core.ui import android.content.Context import android.os.Build import android.os.Bundle import android.view.View import android.view.Window import android.widget.FrameLayout import android.widget.Toast import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.annotation.IntRange import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import io.github.lee.core.ui.databinding.LayoutBaseHoverBinding import io.github.lee.core.ui.databinding.LayoutBaseLinearBinding import io.github.lee.core.util.ext.log import io.github.lee.core.util.ext.observe import io.github.lee.core.vm.BaseViewModel import io.github.lee.core.vm.status.PageStatus import qiu.niorgai.StatusBarCompat open class BaseActivity<VB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() { private val mToast by lazy { Toast.makeText(mContent, "", Toast.LENGTH_SHORT) } protected val mContent: Context by lazy { this } protected val vb: VB? by lazy { onCreateVB() } protected val vm: VM? by lazy { onCreateVM() } protected open fun onCreateVB(): VB? = null protected open fun onCreateVM(): VM? = null /**Toolbar是否悬浮在内容上*/ protected open var isHover = false private lateinit var toolbarContainer: FrameLayout private lateinit var contentContainer: FrameLayout protected var mToolbar: Toolbar? = null private set protected var loadingVb: ViewDataBinding? = null private set protected var emptyVb: ViewDataBinding? = null private set protected var errorVb: ViewDataBinding? = null private set override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) onInitData(savedInstanceState) if (isFinishing) { log("The activity ${javaClass.simpleName} is finishing, No UI rendering") return } //隐藏ActionBar hideActionbar() //设置根view显示 val rootView = if (isHover) { val inflate = LayoutBaseHoverBinding.inflate(layoutInflater) toolbarContainer = inflate.coreToolbarContainer contentContainer = inflate.coreContentContainer inflate } else { val inflate = LayoutBaseLinearBinding.inflate(layoutInflater) toolbarContainer = inflate.coreToolbarContainer contentContainer = inflate.coreContentContainer inflate } setContentView(rootView.root) toolbarContainer.removeAllViews() toolbarContainer.visibility = View.GONE contentContainer.removeAllViews() //设置toolbar mToolbar = onCreateToolbar()?.also { toolbarContainer.addView(it) toolbarContainer.visibility = View.VISIBLE it.title = "" setSupportActionBar(it) if (isHover) { toolbarContainer.fitsSystemWindows = true } } //设置loading loadingVb = onCreateLoading()?.also { it.lifecycleOwner = this contentContainer.addView(it.root) } vb?.also { it.lifecycleOwner = this contentContainer.addView(it.root) } emptyVb = onCreateEmpty()?.also { it.lifecycleOwner = this contentContainer.addView(it.root) } errorVb = onCreateError()?.also { it.lifecycleOwner = this contentContainer.addView(it.root) } //===Desc:根据子类实现的view方法 显示不同状态的界面===================================================================================== if (null != loadingVb) { showLoading() } else { if (null != vb) { showSuccess() } else { if (null != emptyVb) { showEmpty(getString(R.string.core_data_empty)) } else { if (null != errorVb) { showError(getString(R.string.core_data_error)) } } } } if (null != vm) { lifecycle.addObserver(vm!!) } //===Desc:===================================================================================== onObserveData() onSetViewListener() onSetViewData() } override fun onDestroy() { super.onDestroy() loadingVb?.unbind() vb?.unbind() emptyVb?.unbind() errorVb?.unbind() if (null != vm) { lifecycle.removeObserver(vm!!) } } //===Desc:===================================================================================== protected open fun onInitData(savedInstanceState: Bundle?) { } protected open fun onObserveData() { vm?.apply { observe(pageStatusLiveData) { val msg = it.msg when (it.status) { PageStatus.LOADING -> this@BaseActivity.showLoading() PageStatus.SUCCESS -> this@BaseActivity.showSuccess() PageStatus.EMPTY -> this@BaseActivity.showEmpty(msg) PageStatus.ERROR -> this@BaseActivity.showError(msg) PageStatus.PROGRESS -> this@BaseActivity.showProgress() PageStatus.HIDE_PROGRESS -> this@BaseActivity.hideProgress() PageStatus.TOAST -> this@BaseActivity.toast(msg!!) PageStatus.LONG_TOAST -> this@BaseActivity.toast(msg!!, true) } } } } protected open fun onSetViewListener() {} protected open fun onSetViewData() {} //===Desc:界面渲染相关===================================================================================== protected open fun onCreateToolbar(): Toolbar? = null protected open fun onCreateLoading(): ViewDataBinding? = null protected open fun onCreateEmpty(): ViewDataBinding? = null protected open fun onCreateError(): ViewDataBinding? = null //===Desc:界面状态相关===================================================================================== protected open fun showLoading() { loadingVb?.root?.visibility = View.VISIBLE vb?.root?.visibility = View.GONE emptyVb?.root?.visibility = View.GONE errorVb?.root?.visibility = View.GONE } protected open fun showSuccess() { vb?.root?.visibility = View.VISIBLE loadingVb?.root?.visibility = View.GONE emptyVb?.root?.visibility = View.GONE errorVb?.root?.visibility = View.GONE } protected open fun showEmpty(msg: String? = "") { emptyVb?.root?.visibility = View.VISIBLE loadingVb?.root?.visibility = View.GONE vb?.root?.visibility = View.GONE errorVb?.root?.visibility = View.GONE } protected open fun showError(msg: String? = "") { errorVb?.root?.visibility = View.VISIBLE loadingVb?.root?.visibility = View.GONE vb?.root?.visibility = View.GONE emptyVb?.root?.visibility = View.GONE } protected open fun toast(msg: String, isLong: Boolean? = false) { mToast.setText(msg) mToast.duration = if (isLong == true) { Toast.LENGTH_LONG } else { Toast.LENGTH_SHORT } mToast.show() } protected open fun showProgress() { } protected open fun hideProgress() { } /////////////////////////////////////////////////////////////////////////// // 一些常用方法 /////////////////////////////////////////////////////////////////////////// //===Desc:===================================================================================== /**隐藏Actionbar*/ protected fun hideActionbar() { requestWindowFeature(Window.FEATURE_NO_TITLE) supportRequestWindowFeature(Window.FEATURE_NO_TITLE) } //===Desc:===================================================================================== protected fun getContentRoot(): FrameLayout = contentContainer protected fun getToolbarRoot(): FrameLayout = toolbarContainer protected fun setToolbarLeftImage( @DrawableRes resId: Int, listener: View.OnClickListener? = null ) { mToolbar?.apply { setNavigationIcon(resId) setNavigationOnClickListener(listener) } } protected fun replaceFragment(fragment: Fragment) { supportFragmentManager.beginTransaction() .replace(getContentRoot().id, fragment) .commitNowAllowingStateLoss() } /** * @param color 状态栏颜色 * @param alpha -1-255 */ protected fun setStatusBarColor( @ColorInt color: Int, @IntRange(from = -1, to = 255) alpha: Int = -1 ) = if (alpha == -1) { StatusBarCompat.setStatusBarColor(this, color) } else { StatusBarCompat.setStatusBarColor(this, color, alpha) } protected fun translucentStatusBar(hideStatusBarBackground: Boolean = false) = StatusBarCompat.translucentStatusBar(this, hideStatusBarBackground) protected fun lightStatusBars(isBlack: Boolean = true) = if (isBlack) { StatusBarCompat.changeToLightStatusBar(this) } else { StatusBarCompat.cancelLightStatusBar(this) } protected fun lightNavigationBars(isBlack: Boolean = true) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return } val root = vb?.root ?: return val windowInsetsController = ViewCompat.getWindowInsetsController(root) windowInsetsController?.isAppearanceLightNavigationBars = isBlack } protected fun showStatusBar(show: Boolean = true) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return } val root = vb?.root ?: return val windowInsetsController = ViewCompat.getWindowInsetsController(root) if (show) { windowInsetsController?.show(WindowInsetsCompat.Type.statusBars()) } else { windowInsetsController?.hide(WindowInsetsCompat.Type.statusBars()) } } }
0
Kotlin
0
0
05228000958e772128acde4da303315bee5c300c
10,477
core-base
MIT License