path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/sawyern/cookiebot/services/CookieService.kt
sawyern
173,591,137
false
null
package sawyern.cookiebot.services import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Lazy import org.springframework.stereotype.Service import sawyern.cookiebot.exception.CookieException import sawyern.cookiebot.models.Cookie import sawyern.cookiebot.models.Season import sawyern.cookiebot.repository.CookieRepository @Service class CookieService @Autowired constructor( private val cookieRepository: CookieRepository, private val seasonService: SeasonService, @Lazy private val accountService: AccountService ) { private val logger: Logger = LoggerFactory.getLogger(CookieService::class.java) fun giveCookieTo(senderId: String, receiverId: String, numCookies: Int) { if (numCookies <= 0) throw CookieException("Invalid number of cookies: $numCookies") val senderCookies = cookieRepository.findByAccountDiscordIdAndSeason(senderId, seasonService.getCurrentSeason()) if (senderCookies.size < numCookies) throw CookieException("Not enough cookies to give") var cookiesGiven = 0 val receiverAccount = accountService.getAccount(receiverId) for (cookie in senderCookies) { cookie.account = receiverAccount cookieRepository.save(cookie) cookiesGiven++ if (cookiesGiven == numCookies) break } if (logger.isInfoEnabled) { val senderAccount = accountService.getAccount(senderId) logger.info("Transferred $numCookies cookies from ${senderAccount.username} to ${receiverAccount.username}") } } fun getCookiesForAccount(discordId: String, season: Season = seasonService.getCurrentSeason()): Int { return cookieRepository.findByAccountDiscordIdAndSeason(discordId, season).size } fun generateCookie(discordId: String, numCookies: Int = 1, season: Season = seasonService.getCurrentSeason()) { val account = accountService.getAccount(discordId) for(i in 1..numCookies) { val cookie = Cookie(account, season) cookieRepository.save(cookie) } logger.info("Generated $numCookies cookies for ${account.username}") } }
3
Kotlin
0
1
90e46956dc1b84e9f9fb0d467516f13cd08e4762
2,335
cookiebot
Apache License 2.0
app/src/main/java/com/hoc/comicapp/ui/chapter_detail/ChapterDetailViewModel.kt
hoang06kx1
216,228,666
true
{"Kotlin": 353295}
package com.hoc.comicapp.ui.chapter_detail import com.hoc.comicapp.base.BaseViewModel import com.hoc.comicapp.domain.models.getMessage import com.hoc.comicapp.domain.thread.RxSchedulerProvider import com.hoc.comicapp.ui.chapter_detail.ChapterDetailPartialChange.InitialRetryLoadChapterPartialChange import com.hoc.comicapp.ui.chapter_detail.ChapterDetailPartialChange.RefreshPartialChange.Error import com.hoc.comicapp.ui.chapter_detail.ChapterDetailPartialChange.RefreshPartialChange.Success import com.hoc.comicapp.ui.chapter_detail.ChapterDetailViewIntent.* import com.hoc.comicapp.ui.chapter_detail.ChapterDetailViewState.Chapter import com.hoc.comicapp.utils.Some import com.hoc.comicapp.utils.exhaustMap import com.hoc.comicapp.utils.notOfType import com.hoc.comicapp.utils.toOptional import com.jakewharton.rxrelay2.PublishRelay import io.reactivex.Observable import io.reactivex.ObservableTransformer import io.reactivex.rxkotlin.* class ChapterDetailViewModel( private val interactor: ChapterDetailInteractor, rxSchedulerProvider: RxSchedulerProvider, private val isDownloaded: Boolean ) : BaseViewModel<ChapterDetailViewIntent, ChapterDetailViewState, ChapterDetailSingleEvent>() { override val initialState = ChapterDetailViewState.initial() private val intentS = PublishRelay.create<ChapterDetailViewIntent>() private val currentChapter get() = state.value.detail?.chapter ?: error("State is null") private val nextChapter: Chapter? get() { val detail = (state.value.detail as? ChapterDetailViewState.Detail.Data) ?: return null return detail.nextChapterLink?.let { nextChapterLink -> detail .chapters .find { it.link == nextChapterLink } ?.name ?.let { Chapter(name = it, link = nextChapterLink) } } } private val prevChapter: Chapter? get() { val detail = (state.value.detail as? ChapterDetailViewState.Detail.Data) ?: return null return detail.prevChapterLink?.let { prevChapterLink -> detail .chapters .find { it.link == prevChapterLink } ?.name ?.let { Chapter(name = it, link = prevChapterLink) } } } private val refreshProcessor = ObservableTransformer<Refresh, ChapterDetailPartialChange> { intents -> intents.exhaustMap { interactor .refresh(currentChapter, isDownloaded) .doOnNext { when (it) { is Error -> sendMessageEvent(message = "Refresh error occurred: ${it.error.getMessage()}") is Success -> sendMessageEvent(message = "Refresh success") } } } } private val retryProcessor = ObservableTransformer<Retry, ChapterDetailPartialChange> { intents -> intents.exhaustMap { interactor .getChapterDetail(currentChapter, isDownloaded) .doOnNext { if (it is InitialRetryLoadChapterPartialChange.Error) { sendMessageEvent(message = "Retry error occurred: ${it.error.getMessage()}") } } .cast<ChapterDetailPartialChange>() } } private val loadChapterProcessor = ObservableTransformer<LoadChapter, ChapterDetailPartialChange> { intents -> intents .switchMap { intent -> interactor .getChapterDetail(intent.chapter, isDownloaded) .doOnNext { if (it is InitialRetryLoadChapterPartialChange.Error) { sendMessageEvent("Load ${intent.chapter.name} error occurred: ${it.error.getMessage()}") } } } } private val intentToChanges = ObservableTransformer<ChapterDetailViewIntent, ChapterDetailPartialChange> { intents -> Observable.mergeArray( Observable.mergeArray( intents.ofType(), intents.ofType<Initial>().map { LoadChapter(it.chapter) }, intents.ofType<LoadNextChapter>() .map { nextChapter.toOptional() } .ofType<Some<Chapter>>() .map { it.value } .map(::LoadChapter), intents.ofType<LoadPrevChapter>() .map { prevChapter.toOptional() } .ofType<Some<Chapter>>() .map { it.value } .map(::LoadChapter) ) .distinctUntilChanged() .compose(loadChapterProcessor), intents.ofType<Refresh>().compose(refreshProcessor), intents.ofType<Retry>().compose(retryProcessor) ) } override fun processIntents(intents: Observable<ChapterDetailViewIntent>) = intents.subscribe(intentS)!! init { intentS .compose(intentFilter) .publish { intents -> Observables.combineLatest( intents .compose(intentToChanges) .scan(initialState) { vs, change -> change.reducer(vs) }, intents .ofType<ChangeOrientation>() .map { it.orientation } ) { state, orientation -> state.copy(orientation = orientation) } } .observeOn(rxSchedulerProvider.main) .subscribeBy(onNext = ::setNewState) .addTo(compositeDisposable) } /** * Send [message] */ private fun sendMessageEvent(message: String) = sendEvent(ChapterDetailSingleEvent.MessageEvent(message)) private companion object { /** * Only take 1 [ChapterDetailViewIntent.Initial] */ @JvmStatic private val intentFilter = ObservableTransformer<ChapterDetailViewIntent, ChapterDetailViewIntent> { it.publish { shared -> Observable.mergeArray( shared .ofType<Initial>() .take(1), shared.notOfType<Initial, ChapterDetailViewIntent>() ) } } } }
0
null
0
0
8ff2ea495d56c2d73bfd5cfc4c6244d2b7c8faaa
5,748
ComicReaderApp_MVI_Coroutine_RxKotlin_Jetpack
MIT License
app/src/main/java/com/cusufcan/firebasepdf/adapter/PDFFilesAdapter.kt
cusufcan
835,146,079
false
{"Kotlin": 16221}
package com.cusufcan.firebasepdf.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.cusufcan.firebasepdf.databinding.PdfItemBinding import com.cusufcan.firebasepdf.model.PDFFile class PDFFilesAdapter(private val listener: PDFClickListener) : ListAdapter<PDFFile, PDFFilesAdapter.PDFFilesViewHolder>(PDFDiffCallback()) { inner class PDFFilesViewHolder(private val binding: PdfItemBinding) : RecyclerView.ViewHolder(binding.root) { init { binding.root.setOnClickListener { listener.onPDFClicked(getItem(adapterPosition)) } } fun bind(data: PDFFile) { binding.fileName.text = data.fileName } } class PDFDiffCallback : DiffUtil.ItemCallback<PDFFile>() { override fun areItemsTheSame(oldItem: PDFFile, newItem: PDFFile) = oldItem.downloadUrl == newItem.downloadUrl override fun areContentsTheSame(oldItem: PDFFile, newItem: PDFFile) = oldItem == newItem } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PDFFilesViewHolder { val binding = PdfItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return PDFFilesViewHolder(binding) } override fun onBindViewHolder(holder: PDFFilesViewHolder, position: Int) { holder.bind(getItem(position)) } interface PDFClickListener { fun onPDFClicked(pdfFile: PDFFile) } }
0
Kotlin
0
1
1514fc371041679ae6d60a9d4302146f70e2bd6b
1,619
firebase_pdf
MIT License
features/home/src/main/kotlin/press/advent/dynamicfeatures/home/ui/di/HomeModule.kt
jeffnyauke
254,036,844
false
null
/* * * Copyright (c) 2020 <EMAIL> * * 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 press.advent.dynamicfeatures.home.ui.di import androidx.annotation.VisibleForTesting import androidx.annotation.VisibleForTesting.PRIVATE import dagger.Module import dagger.Provides import press.advent.commons.ui.extensions.viewModel import press.advent.core.di.scopes.FeatureScope import press.advent.dynamicfeatures.home.ui.HomeFragment import press.advent.dynamicfeatures.home.ui.HomeViewModel /** * Class that contributes to the object graph [HomeComponent]. * * @see Module */ @Module class HomeModule( @VisibleForTesting(otherwise = PRIVATE) val fragment: HomeFragment ) { /** * Create a provider method binding for [HomeViewModel]. * * @return Instance of view model. * @see Provides */ @Provides @FeatureScope fun providesHomeViewModel() = fragment.viewModel { HomeViewModel() } }
0
Kotlin
0
0
0960891558650bd167c0c923cbf29f124981f3ea
1,477
TheAdventPress
Apache License 2.0
Android/app/src/main/java/com/ismin/android/WomanService.kt
clemstarosta
568,705,563
false
{"Kotlin": 26874, "TypeScript": 6593, "JavaScript": 1226}
package com.ismin.android import retrofit2.Call import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST interface WomanService { @GET("women") fun getAllWomen(): Call<List<Woman>> @POST("women") fun addWoman(@Body() woman: Woman): Call<Woman> }
0
Kotlin
0
0
0e243dae4b38f381648c5409953c8ffbdadf62d4
287
ProjectISMIN
MIT License
coreactor/src/test/java/com/sumera/coreactor/CoreactorFragmentTest.kt
SumeraMartin
213,146,164
false
{"Kotlin": 241583}
package com.sumera.coreactor import androidx.fragment.app.testing.FragmentScenario import androidx.lifecycle.Lifecycle import androidx.test.ext.junit.runners.AndroidJUnit4 import com.sumera.coreactor.contract.event.EventBehaviour import com.sumera.coreactor.testutils.CoroutineRule import com.sumera.coreactor.testutils.testcoreactor.DecrementAction import com.sumera.coreactor.testutils.testcoreactor.DelayedDecrementAction import com.sumera.coreactor.testutils.testcoreactor.IncrementAction import com.sumera.coreactor.testutils.testcoreactor.MultipleDecrementAction import com.sumera.coreactor.testutils.testcoreactor.SendEventAction import com.sumera.coreactor.testutils.testcoreactor.TestCounterState import com.sumera.coreactor.testutils.testcoreactor.TestEvent import com.sumera.coreactor.testutils.testfragment.TestCounterFragment import io.mockk.verify import io.mockk.verifySequence import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class CoreactorFragmentTest { val coroutineRule = CoroutineRule() @Before fun setUp() { coroutineRule.setUp() } @After fun tearDown() { coroutineRule.tearDown() } @Test fun `coreactor should propagate the default state`() { // GIVEN val scenario = FragmentScenario.launch(TestCounterFragment::class.java) scenario.moveToState(Lifecycle.State.RESUMED) // WHEN // THEN scenario.onFragment { fragment -> verifySequence { fragment.mockView.onState( TestCounterState( 0 ) ) } } } @Test fun `coreactor should propagate changed state when action is send`() { // GIVEN val scenario = FragmentScenario.launch(TestCounterFragment::class.java) scenario.moveToState(Lifecycle.State.RESUMED) // WHEN scenario.onFragment { fragment -> fragment.action(IncrementAction) } // THEN scenario.onFragment { fragment -> verifySequence { fragment.mockView.onState( TestCounterState( 0 ) ) fragment.mockView.onState( TestCounterState( 1 ) ) } } } @Test fun `coreactor should propagate changed states when multiple actions are send`() { // GIVEN val scenario = FragmentScenario.launch(TestCounterFragment::class.java) scenario.moveToState(Lifecycle.State.RESUMED) // WHEN scenario.onFragment { fragment -> fragment.action(IncrementAction) fragment.action(IncrementAction) fragment.action(IncrementAction) fragment.action(DecrementAction) } // THEN scenario.onFragment { fragment -> verifySequence { fragment.mockView.onState( TestCounterState( 0 ) ) fragment.mockView.onState( TestCounterState( 1 ) ) fragment.mockView.onState( TestCounterState( 2 ) ) fragment.mockView.onState( TestCounterState( 3 ) ) fragment.mockView.onState( TestCounterState( 2 ) ) } } } @Test fun `coreactor should propagate changed states when multiple reducers are send`() { // GIVEN val scenario = FragmentScenario.launch(TestCounterFragment::class.java) scenario.moveToState(Lifecycle.State.RESUMED) // WHEN scenario.onFragment { fragment -> fragment.action(MultipleDecrementAction) } // THEN scenario.onFragment { fragment -> verifySequence { fragment.mockView.onState( TestCounterState( 0 ) ) fragment.mockView.onState( TestCounterState( -1 ) ) fragment.mockView.onState( TestCounterState( -2 ) ) fragment.mockView.onState( TestCounterState( -3 ) ) } } } @Test fun `coreactor should propagate changed states when delayed action is send`() { // GIVEN val scenario = FragmentScenario.launch(TestCounterFragment::class.java) scenario.moveToState(Lifecycle.State.RESUMED) // WHEN scenario.onFragment { fragment -> fragment.action(DelayedDecrementAction) fragment.action(IncrementAction) fragment.action(IncrementAction) coroutineRule.advanceTimeBy(1000) } // THEN scenario.onFragment { fragment -> verifySequence { fragment.mockView.onState( TestCounterState( 0 ) ) fragment.mockView.onState( TestCounterState( 1 ) ) fragment.mockView.onState( TestCounterState( 2 ) ) fragment.mockView.onState( TestCounterState( 1 ) ) } } } @Test fun `coreactor should send event when event action is send`() { // GIVEN val scenario = FragmentScenario.launch(TestCounterFragment::class.java) scenario.moveToState(Lifecycle.State.RESUMED) // WHEN scenario.onFragment { fragment -> fragment.action( SendEventAction( "message", EventBehaviour.DISPATCH_EVERY_TIME ) ) } // THEN scenario.onFragment { fragment -> verify { fragment.mockView.onEvent( TestEvent( "message", EventBehaviour.DISPATCH_EVERY_TIME ) ) } } } @Test fun `coreactor should emit the previous state after recreate`() { // GIVEN val scenario = FragmentScenario.launch(TestCounterFragment::class.java) // WHEN scenario.onFragment { fragment -> fragment.action(IncrementAction) } scenario.recreate() // THEN scenario.onFragment { fragment -> verifySequence { fragment.mockView.onState( TestCounterState( 1 ) ) } } } @Test fun `coreactor should emit the previous state after recreate with delayed action and receive state produced by delayed reducer`() { // GIVEN val scenario = FragmentScenario.launch(TestCounterFragment::class.java) // WHEN scenario.onFragment { fragment -> fragment.action(IncrementAction) fragment.action(DelayedDecrementAction) } scenario.recreate() coroutineRule.advanceTimeBy(1000) // THEN scenario.onFragment { fragment -> verifySequence { fragment.mockView.onState( TestCounterState( 1 ) ) fragment.mockView.onState( TestCounterState( 0 ) ) } } } }
0
Kotlin
0
4
ce065d6a0a6573d63ca3262ef4dee11fb3c565af
8,420
Coreactor
MIT License
app/src/main/java/com/zxhhyj/music/logic/bean/PlayMemoryBean.kt
ZXHHYJ
675,785,532
false
{"Kotlin": 465253}
package com.zxhhyj.music.logic.bean data class PlayMemoryBean(val index: Int? = null, val playlist: List<SongBean>? = null)
0
Kotlin
1
16
eaa34f1577aed5585e2c2253d73ca6741a0dc0d1
125
StarMusic
Apache License 2.0
markdown-editor/src/jvmMain/kotlin/me/okonecny/markdowneditor/view/RenderContext.kt
konecny-ondrej
784,920,382
false
{"Kotlin": 223790}
package me.okonecny.markdowneditor.view import androidx.compose.runtime.Composable import androidx.compose.ui.text.AnnotatedString import me.okonecny.markdowneditor.MappedText import me.okonecny.markdowneditor.MarkdownDocument interface RenderContext<in BaseNode> { val document: MarkdownDocument val activeAnnotationTags: Set<String> @Composable fun handleLinks(): (Int, List<AnnotatedString.Range<String>>) -> Unit @Composable fun parseInlines(inlines: Iterable<BaseNode>): MappedText @Composable fun <T : BaseNode> renderBlocks(blocks: Iterable<T>) @Composable fun <T : BaseNode> renderBlock(block: T) }
1
Kotlin
0
6
0e1f0019178329dd2f8194bbd760355228ee989c
652
compose-markdown-editor
MIT License
main/src/main/java/com/work/theIsle/openSourceFramework/glide/GlideActivity.kt
Tiannuo
498,562,269
false
{"Kotlin": 218272, "Java": 43175}
package com.work.theIsle.openSourceFramework.glide import androidx.activity.viewModels import androidx.databinding.DataBindingUtil import com.alibaba.android.arouter.facade.annotation.Route import com.work.baselib.activity.BaseActivity import com.work.baselib.arouter.RouterPath.PATH_GLIDEACTIVITY import com.work.theIsle.R import com.work.theIsle.constant.Constant.IMG_URL import com.work.theIsle.databinding.ActivityGlideBinding @Route(path = PATH_GLIDEACTIVITY) class GlideActivity : BaseActivity() { private lateinit var binding: ActivityGlideBinding private val glideVM: GlideViewModel by viewModels() override fun initView() { binding = DataBindingUtil.setContentView(this, R.layout.activity_glide) binding.lifecycleOwner = this binding.glideVm = glideVM binding.btnTest.setOnClickListener { binding.imgUrl = IMG_URL glideVM.notifyImgData() } } override fun initData() { } }
0
Kotlin
2
4
bf02c12830d80c6bcf7441c50c3f685d322fdf53
976
AndroidWork
Apache License 2.0
data/RF01241/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF01241" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 20 to 21 81 to 82 } value = "#41308c" } color { location { 23 to 27 75 to 79 } value = "#a676fa" } color { location { 30 to 33 69 to 72 } value = "#2b626d" } color { location { 39 to 40 62 to 63 } value = "#d3ade4" } color { location { 42 to 49 53 to 60 } value = "#cfd0f7" } color { location { 112 to 120 181 to 189 } value = "#d465d9" } color { location { 138 to 141 158 to 161 } value = "#d1bc6e" } color { location { 22 to 22 80 to 80 } value = "#1e8af5" } color { location { 28 to 29 73 to 74 } value = "#d787b2" } color { location { 34 to 38 64 to 68 } value = "#621859" } color { location { 41 to 41 61 to 61 } value = "#f854b2" } color { location { 50 to 52 } value = "#0c5f10" } color { location { 121 to 137 162 to 180 } value = "#946bbc" } color { location { 142 to 157 } value = "#cfe345" } color { location { 1 to 19 } value = "#e227d2" } color { location { 83 to 111 } value = "#46e933" } color { location { 190 to 195 } value = "#01fa2a" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
2,635
Rfam-for-RNArtist
MIT License
modules/core/arrow-instances-data/src/main/kotlin/arrow/instances/statet.kt
simonbasle
146,276,825
true
{"Kotlin": 1510912, "CSS": 186873, "JavaScript": 66545, "HTML": 11364, "Java": 4465, "Shell": 3043}
package arrow.instances import arrow.Kind import arrow.core.* import arrow.data.* import arrow.instance import arrow.typeclasses.* @instance(StateT::class) interface StateTFunctorInstance<F, S> : Functor<StateTPartialOf<F, S>> { fun FF(): Functor<F> override fun <A, B> Kind<StateTPartialOf<F, S>, A>.map(f: (A) -> B): StateT<F, S, B> = fix().map(FF(), f) } @instance(StateT::class) interface StateTApplicativeInstance<F, S> : StateTFunctorInstance<F, S>, Applicative<StateTPartialOf<F, S>> { override fun FF(): Monad<F> override fun <A, B> Kind<StateTPartialOf<F, S>, A>.map(f: (A) -> B): StateT<F, S, B> = fix().map(FF(), f) override fun <A> just(a: A): StateT<F, S, A> = StateT(FF().just({ s: S -> FF().just(Tuple2(s, a)) })) override fun <A, B> Kind<StateTPartialOf<F, S>, A>.ap(ff: Kind<StateTPartialOf<F, S>, (A) -> B>): StateT<F, S, B> = fix().ap(FF(), ff) override fun <A, B> Kind<StateTPartialOf<F, S>, A>.product(fb: Kind<StateTPartialOf<F, S>, B>): StateT<F, S, Tuple2<A, B>> = fix().product(FF(), fb.fix()) } @instance(StateT::class) interface StateTMonadInstance<F, S> : StateTApplicativeInstance<F, S>, Monad<StateTPartialOf<F, S>> { override fun <A, B> Kind<StateTPartialOf<F, S>, A>.map(f: (A) -> B): StateT<F, S, B> = fix().map(FF(), f) override fun <A, B> Kind<StateTPartialOf<F, S>, A>.flatMap(f: (A) -> Kind<StateTPartialOf<F, S>, B>): StateT<F, S, B> = fix().flatMap(FF(), f) override fun <A, B> tailRecM(a: A, f: (A) -> StateTOf<F, S, Either<A, B>>): StateT<F, S, B> = StateT.tailRecM(FF(), a, f) override fun <A, B> Kind<StateTPartialOf<F, S>, A>.ap(ff: Kind<StateTPartialOf<F, S>, (A) -> B>): StateT<F, S, B> = ff.fix().map2(FF(), fix()) { f, a -> f(a) } } @instance(StateT::class) interface StateTSemigroupKInstance<F, S> : SemigroupK<StateTPartialOf<F, S>> { fun FF(): Monad<F> fun SS(): SemigroupK<F> override fun <A> Kind<StateTPartialOf<F, S>, A>.combineK(y: Kind<StateTPartialOf<F, S>, A>): StateT<F, S, A> = fix().combineK(FF(), SS(), y) } @instance(StateT::class) interface StateTApplicativeErrorInstance<F, S, E> : StateTApplicativeInstance<F, S>, ApplicativeError<StateTPartialOf<F, S>, E> { override fun FF(): MonadError<F, E> override fun <A> raiseError(e: E): Kind<StateTPartialOf<F, S>, A> = StateT.lift(FF(), FF().raiseError(e)) override fun <A> Kind<StateTPartialOf<F, S>, A>.handleErrorWith(f: (E) -> Kind<StateTPartialOf<F, S>, A>): StateT<F, S, A> = StateT(FF().just({ s -> FF().run { runM(FF(), s).handleErrorWith { e -> f(e).runM(FF(), s) } } })) } @instance(StateT::class) interface StateTMonadErrorInstance<F, S, E> : StateTApplicativeErrorInstance<F, S, E>, StateTMonadInstance<F, S>, MonadError<StateTPartialOf<F, S>, E> /** * Alias for[StateT.Companion.applicative] */ fun <S> StateApi.applicative(): Applicative<StateTPartialOf<ForId, S>> = StateT.applicative<ForId, S>(Id.monad()) /** * Alias for [StateT.Companion.functor] */ fun <S> StateApi.functor(): Functor<StateTPartialOf<ForId, S>> = StateT.functor<ForId, S>(Id.monad()) /** * Alias for [StateT.Companion.monad] */ fun <S> StateApi.monad(): Monad<StateTPartialOf<ForId, S>> = StateT.monad<ForId, S>(Id.monad()) class StateTContext<F, S, E>(val ME: MonadError<F, E>) : StateTMonadErrorInstance<F, S, E> { override fun FF(): MonadError<F, E> = ME } class StateTContextPartiallyApplied<F, S, E>(val ME: MonadError<F, E>) { infix fun <A> extensions(f: StateTContext<F, S, E>.() -> A): A = f(StateTContext(ME)) } fun <F, S, E> ForStateT(ME: MonadError<F, E>): StateTContextPartiallyApplied<F, S, E> = StateTContextPartiallyApplied(ME) class StateTMonadContext<S> : StateTMonadInstance<ForId, S> { override fun FF(): Monad<ForId> = Id.monad() } class StateContextPartiallyApplied<S>() { infix fun <A> extensions(f: StateTMonadContext<S>.() -> A): A = f(StateTMonadContext()) } fun <S> ForState(): StateContextPartiallyApplied<S> = StateContextPartiallyApplied()
0
Kotlin
0
0
bdc00446cad4eea45ffd2e34d4eeff2f138a6ac0
4,006
arrow
Apache License 2.0
app/src/main/java/cn/wthee/pcrtool/data/network/FileService.kt
wthee
277,015,110
false
{"Kotlin": 1473133}
package cn.wthee.pcrtool.data.network import okhttp3.ResponseBody import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path /** * 数据库 */ interface FileService { /** * 根据文件名 [file]下载文件 */ @GET("{file}") fun getFile(@Path("file") file: String): Call<ResponseBody> }
0
Kotlin
3
58
5623e3ffdce349b74ba24c80add3137f1c01146a
308
pcr-tool
Apache License 2.0
src/test/kotlin/org/move/lang/parser/SpecsParsingTest.kt
pontem-network
279,299,159
false
{"Kotlin": 2191000, "Move": 39421, "Lex": 5509, "HTML": 2114, "Java": 1275}
package org.move.lang.parser import org.move.utils.tests.parser.MvParsingTestCase class SpecsParsingTest: MvParsingTestCase("specs") { fun `test scopes`() = doTest() fun `test conditions`() = doTest() fun `test forall exists`() = doTest() fun `test pragma`() = doTest() fun `test apply`() = doTest() fun `test spec statements`() = doTest(true, false) fun `test spec file`() = doTest() fun `test spec properties`() = doTest() fun `test spec variables`() = doTest() fun doTest() { super.doTest(true, true) } }
3
Kotlin
29
69
d090ecd542bb16f414cc1cf2dcbe096ca37536af
564
intellij-move
MIT License
app/src/main/java/com/franzliszt/magicmusic/route/musicplayer/service/MusicService.kt
FranzLiszt-1847
753,088,527
false
{"Kotlin": 879960, "Java": 1923}
package com.franzliszt.magicmusic.route.musicplayer.service import android.content.Intent import android.os.Build import androidx.media3.common.Player import androidx.media3.session.MediaSession import androidx.media3.session.MediaSessionService import com.franzliszt.magicmusic.route.musicplayer.notification.MusicNotificationManager import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MusicService:MediaSessionService() { @Inject lateinit var mediaSession: MediaSession @Inject lateinit var notificationManager: MusicNotificationManager override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationManager.startNotificationService( mediaSession = mediaSession, mediaSessionService = this ) } return super.onStartCommand(intent, flags, startId) } override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession = mediaSession override fun onDestroy() { super.onDestroy() mediaSession.apply { release() if (player.playbackState != Player.STATE_IDLE) { player.seekTo(0) player.playWhenReady = false player.stop() } } } }
0
Kotlin
1
1
dcbc4c0cb9c0478e617423812712659df52a3b7d
1,398
MagicPlayer
Apache License 2.0
libs/messaging/message-bus/src/main/kotlin/net/corda/messagebus/api/consumer/CordaConsumerRebalanceListener.kt
corda
346,070,752
false
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.messagebus.api.consumer import net.corda.messagebus.api.CordaTopicPartition /** * A callback interface that the user can implement to trigger custom actions when the set of partitions assigned to the * consumer changes. */ interface CordaConsumerRebalanceListener { /** * This method will be called during a rebalance operation when the consumer has to give up some partitions. * It can also be called when consumer is being closed or is unsubscribing. * It is recommended that offsets should be committed in this callback to prevent duplicate data. * * @param partitions The list of partitions that were assigned to the consumer and now need to be revoked (may not * include all currently assigned partitions, i.e. there may still be some partitions left) * */ fun onPartitionsRevoked(partitions: Collection<CordaTopicPartition>) /** * This method will be called after the partition re-assignment completes and before the consumer * starts fetching data, and only as the result of a poll(long) call. * <p> * It is guaranteed that under normal conditions all the processes in a consumer group will execute their * [onPartitionsRevoked] callback before any instance executes its [onPartitionsAssigned] callback. * During exceptional scenarios, partitions may be migrated without the old owner being notified (i.e. their * [onPartitionsRevoked] callback not triggered), and later when the old owner consumer realized this event, * the [onPartitionsLost] callback will be triggered by the consumer then. * * @param partitions The list of partitions that are now assigned to the consumer (previously owned partitions will * NOT be included, i.e. this list will only include newly added partitions) */ fun onPartitionsAssigned(partitions: Collection<CordaTopicPartition>); /** * This method will not be called during normal execution as the owned partitions would * first be revoked by calling the [onPartitionsRevoked], before being reassigned * to other consumers during a rebalance event. However, during exceptional scenarios when the consumer realizes * that it does not own this partition any longer, i.e. not revoked via a normal rebalance event, then this method * would be invoked. By default, it will just trigger [onPartitionsRevoked]. * * @param partitions The list of partitions that were assigned to the consumer and now have been reassigned * to other consumers. With the current protocol this will always include all the consumer's * previously assigned partitions, but this may change in future protocols (ie there would still * be some partitions left) */ fun onPartitionsLost(partitions: Collection<CordaTopicPartition>) = onPartitionsRevoked(partitions) }
14
Kotlin
27
69
0766222eb6284c01ba321633e12b70f1a93ca04e
2,966
corda-runtime-os
Apache License 2.0
harmonysoft-sql/src/main/kotlin/tech/harmonysoft/oss/sql/dsl/table/Table.kt
harmonhsoft-tech
517,062,754
false
{"Kotlin": 622506, "Gherkin": 23480, "Shell": 517, "JavaScript": 378}
package tech.harmonysoft.oss.sql.dsl.table import tech.harmonysoft.oss.sql.dsl.Sql data class Table( val name: String?, val select: Sql.Select?, val alias: String?, val schemaName: String? ) { constructor(name: String, alias: String? = null, schemaName: String? = null) : this( name = name, select = null, alias = alias, schemaName = schemaName ) constructor(select: Sql.Select?, alias: String?) : this( name = null, select = select, alias = alias, schemaName = null ) init { if (name != null && select != null) { throw IllegalArgumentException("table should have only name or select") } } override fun toString(): String { return buildString { name?.let { schemaName?.let { append("$schemaName.") } append(name) } select?.let { append("(${select.sql})") } alias?.let { append(" $alias") } } } }
1
Kotlin
1
2
a87acdf44ee44e84100bbcb7facc0697c638b4ab
1,129
harmonysoft-kotlin-libs
MIT License
src/main/kotlin/tools/Combinations.kt
wrabot
739,807,905
false
{"Kotlin": 19706}
package tools fun <T> List<T>.combinations(length: Int = size): List<List<T>> = if (length <= 0 || isEmpty()) listOf(emptyList()) else flatMap { first -> minus(first).combinations(length - 1).map { listOf(first) + it } } fun <T> enumerate(base: Int, length: Int, prefix: List<Int> = emptyList(), block: (List<Int>) -> T): List<T> = if (length <= 0) listOf(block(prefix)) else (0 until base).flatMap { enumerate(base, length - 1, prefix + it, block) }
0
Kotlin
0
0
fd2da26c0259349fbc9719e694d58549e7f040a0
473
competitive-tools
Apache License 2.0
project/src/main/kotlin/cga/exercise/components/camera/PerspectiveCamera.kt
itsAltamas
396,089,178
true
{"Kotlin": 103779, "GLSL": 24426}
package cga.exercise.components.camera import cga.exercise.components.geometry.Transformable import cga.exercise.components.shader.ShaderProgram import org.joml.Matrix4f import org.joml.Vector3f import java.lang.Exception import java.lang.Math.PI class PerspectiveCamera constructor(var fov : Float, var aspectRatio : Float, var nearPlane : Float, var farPlane : Float) : Transformable() , ICamera { override fun getCalculateViewMatrix() : Matrix4f { val eye = getWorldPosition() val center = Vector3f(eye).sub(getWorldZAxis()) val up = getWorldYAxis() return Matrix4f().lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z) } override fun getCalculateProjectionMatrix() : Matrix4f{ if(fov <= 0 || fov >= PI) throw Exception("Must be 0 < foV < PI") if(aspectRatio <= 0) throw Exception("Must be aspectRatio > 0") return Matrix4f().perspective(fov, aspectRatio, nearPlane, farPlane) } override fun bind(shader: ShaderProgram) { shader.setUniform("projection_matrix", getCalculateProjectionMatrix(), false) shader.setUniform("view_matrix", getCalculateViewMatrix(), false) } }
0
Kotlin
0
0
4babb82a385fb502750e63a7cd4f0f6ae9b65619
1,199
CGA_Project
MIT License
app/src/main/java/com/programmer2704/stoxxwatch/app/AppModule.kt
prgrm274
378,989,070
false
null
package com.programmer2704.stoxxwatch.app import android.app.Application import android.content.Context import com.programmer2704.stoxxwatch.annotations.ApplicationContext import com.programmer2704.stoxxwatch.data.AppDatabaseManager import com.programmer2704.stoxxwatch.data.DatabaseManager import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class AppModule constructor(private val app: Application){ @Provides @Singleton @ApplicationContext fun provideContext(): Context = app.applicationContext @Provides @Singleton fun provideDatabaseManager(@ApplicationContext context: Context): DatabaseManager = AppDatabaseManager(context) }
0
Kotlin
0
0
29b9e5a325eed42f34e6ac27d2b1a007c060ab07
708
stoxxwatch
MIT License
src/main/kotlin/api/graphql/Queries.kt
Nimeggis
648,951,082
false
null
package api.graphql import api.graphql.config.user import api.model.User import api.repository.UserRepository import com.expediagroup.graphql.server.operations.Query import graphql.schema.DataFetchingEnvironment import org.springframework.stereotype.Component @Component class Queries(private val userRepository: UserRepository) : Query { suspend fun user(dfe: DataFetchingEnvironment): User { return dfe.user } }
0
Kotlin
0
1
ebeb4959aff39bb0b19ccd5a396e0be2100d58dc
433
IntelliCards-BE
MIT License
gradle-plugin/src/main/kotlin/io/github/manriif/supabase/functions/serve/ServeInspect.kt
manriif
818,790,032
false
{"Kotlin": 172967}
/** * Copyright (c) 2024 Maanrifa Bacar Ali * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.manriif.supabase.functions.serve import org.gradle.api.tasks.Input /** * Behaviour of inspection during function serving. * More explanations on [Supabase Docs](https://supabase.com/docs/reference/cli/supabase-functions-serve). */ data class ServeInspect( /** * Activates the inspector capability. */ @Input var mode: Mode = Mode.Brk, /** * Allows the creation of an inspector session for the main worker which is not allowed by * default. */ @Input var main: Boolean = false, /** * Adds the debug flag to the serve command. */ @Input var debug: Boolean = false ) { /** * Available inspection modes. */ enum class Mode(internal val value: String) { /** * Simply allows a connection without additional behavior. It is not ideal for short * scripts, but it can be useful for long-running scripts where you might occasionally want * to set breakpoints. */ Run("run"), /** * Same as [Run] mode, but additionally sets a breakpoint at the first line to pause script * execution before any code runs. */ Brk("brk"), /** * Similar to [Brk] mode, but instead of setting a breakpoint at the first line, it pauses * script execution until an inspector session is connected. */ Wait("wait") } }
0
Kotlin
0
14
fd9350fa6287f2bd2bc95e5f030058c5cef9411e
2,566
supabase-edge-functions-kt
MIT License
src/test/kotlin/com/github/simy4/poc/TemplatesPocApplicationTest.kt
SimY4
41,303,846
false
{"Kotlin": 39316, "JavaScript": 16842, "HTML": 6412, "Dockerfile": 559}
package com.github.simy4.poc import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT import org.springframework.test.context.junit.jupiter.SpringExtension @ExtendWith(SpringExtension::class) @SpringBootTest(webEnvironment = RANDOM_PORT) class TemplatesPocApplicationTest { @Test fun contextLoads() {} }
0
Kotlin
0
2
bd21ba971b2d9116b5c15207082bfa8f6a8b8e52
482
TemplatesPOC
MIT License
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/Extensions.kt
feelfreelinux
97,154,881
false
null
package io.github.feelfreelinux.wykopmobilny.utils import android.app.Activity import android.content.ContentResolver import android.content.ContextWrapper import android.graphics.drawable.Drawable import android.net.Uri import android.provider.OpenableColumns import android.text.SpannableStringBuilder import android.view.View import android.widget.ImageView import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.bumptech.glide.signature.ObjectKey import io.github.feelfreelinux.wykopmobilny.glide.GlideApp import io.github.feelfreelinux.wykopmobilny.utils.api.parseDate import io.github.feelfreelinux.wykopmobilny.utils.api.parseDateJavaTime import io.github.feelfreelinux.wykopmobilny.utils.recyclerview.ViewHolderDependentItemDecorator import org.ocpsoft.prettytime.PrettyTime import org.threeten.bp.Duration import org.threeten.bp.LocalDate import org.threeten.bp.LocalTime import org.threeten.bp.Period import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.DateTimeParseException import java.util.Locale var View.isVisible: Boolean get() = visibility == View.VISIBLE set(value) { visibility = if (value) View.VISIBLE else View.GONE } fun SpannableStringBuilder.appendNewSpan(text: CharSequence, what: Any, flags: Int): SpannableStringBuilder { val start = length append(text) setSpan(what, start, length, flags) return this } fun View.getActivityContext(): Activity? { var context = context while (context is ContextWrapper) { if (context is Activity) { return context } context = context.baseContext } return null } fun androidx.recyclerview.widget.RecyclerView.prepare() { setItemViewCacheSize(20) drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH isDrawingCacheEnabled = true layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) (itemAnimator as androidx.recyclerview.widget.SimpleItemAnimator).supportsChangeAnimations = false addItemDecoration(ViewHolderDependentItemDecorator(context)) } fun androidx.recyclerview.widget.RecyclerView.prepareNoDivider() { setItemViewCacheSize(20) drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH isDrawingCacheEnabled = true layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) } fun ImageView.loadImage(url: String, signature: Int? = null) { if (signature == null) { GlideApp.with(context) .load(url) .into(this) } else { GlideApp.with(context) .load(url) .apply( RequestOptions() .signature(ObjectKey(signature)) ) .into(this) } } fun String.toPrettyDate(): String { return PrettyTime(Locale("pl")).format(parseDate(this)) } fun String.toDurationPrettyDate(): String { val period = Period.between(parseDateJavaTime(this), LocalDate.now()) if (period.years > 1 && period.months > 0) { return "${period.years} lata ${period.months} mies." } else if (period.years > 1 && period.months == 0) { return "${period.years} lata" } else if (period.years == 1 && period.months > 0) { return "${period.years} rok ${period.months} mies." } else if (period.years == 1 && period.months == 0) { return "${period.years} rok" } else if (period.years == 0 && period.months > 0) { return "${period.months} mies." } else if (period.months == 0 && period.days > 0) { return "${period.days} dni" } else { val durationTime = LocalTime.parse(this, DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss", Locale.GERMAN)) val duration = Duration.between(durationTime, LocalTime.now()) if (period.days == 0 && duration.toHours().toInt() > 0) { return "${duration.toHours().toInt()} godz." } else if (duration.toHours().toInt() == 0) { return "${duration.toMinutes().toInt()} min." } } return PrettyTime(Locale("pl")).formatDurationUnrounded(parseDate(this)) } fun Uri.queryFileName(contentResolver: ContentResolver): String { var result: String? = null if (scheme == "content") { val cursor = contentResolver.query(this, null, null, null, null) try { if (cursor != null && cursor.moveToFirst()) { result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) } } finally { cursor!!.close() } } if (result == null) { result = path val cut = result!!.lastIndexOf('/') if (cut != -1) { result = result.substring(cut + 1) } } return result } /** * Parse YouTube timestamp from string to milliseconds value. * * Original value comes from 't' parameter from youtube url and is given in seconds. YouTube player needs this * value in milliseconds. * * Parameter 't' can be in following formats: * '3' we can assume that this values is in seconds * '3m', '5m30s', '1h30m30s' needs conversion using ISO 8601. * * @return time in milliseconds, null if value cannot be converted. * */ fun String.youtubeTimestampToMsOrNull(): Int? { val timestamp = this.toLongOrNull() if (timestamp != null) { return Duration.ofSeconds(timestamp).toMillis().toInt() } return try { Duration.parse("PT${this}").toMillis().toInt() } catch (e: DateTimeParseException) { null } } class KotlinGlideRequestListener(val failedListener: (GlideException?) -> Unit, val successListener: () -> Unit) : RequestListener<Drawable> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean { failedListener(e) return false } override fun onResourceReady( resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { successListener() return false } }
47
Kotlin
51
166
ec6365b9570818a7ee00c5b512f01cedead30867
6,281
WykopMobilny
MIT License
app/src/main/kotlin/io/dolphin/move/android/features/permissions/presentation/PermissionsUiState.kt
dolphin-technologies
603,088,245
false
{"Kotlin": 623694}
package io.dolphin.move.android.features.permissions.presentation import androidx.compose.ui.graphics.Color import io.dolphin.move.android.R import io.dolphin.move.android.ui.theme.white data class PermissionsUiState( val locationButtonText: Int = R.string.btn_continue, val locationButtonColor: Color = white, val motionButtonText: Int = R.string.btn_continue, val motionButtonColor: Color = white, val phoneCallButtonText: Int = R.string.btn_continue, val phoneCallButtonColor: Color = white, val overlayButtonText: Int = R.string.btn_continue, val overlayButtonColor: Color = white, val batteryButtonText: Int = R.string.btn_continue, val batteryButtonColor: Color = white, val notificationsButtonText: Int = R.string.btn_continue, val notificationsButtonColor: Color = white, val bluetoothButtonText: Int = R.string.btn_continue, val bluetoothButtonColor: Color = white, )
1
Kotlin
0
0
24a66fa84ac22a6de358b76ad158c042363ca55b
942
MOVE-App-Android
Apache License 2.0
crypto/presentation/src/main/java/dev/ohoussein/crypto/presentation/components/CryptoListScreen.kt
OHoussein
388,247,123
false
null
@file:Suppress("LongParameterList") package dev.ohoussein.crypto.presentation.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Snackbar import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import dev.ohoussein.crypto.presentation.debug.DataPreview.previewListCrypto import dev.ohoussein.crypto.presentation.model.Crypto import dev.ohoussein.crypto.presentation.viewmodel.HomeViewModel import dev.ohoussein.cryptoapp.common.resource.Resource import dev.ohoussein.cryptoapp.common.resource.Status import dev.ohoussein.cryptoapp.core.designsystem.base.CryptoAppScaffold import dev.ohoussein.cryptoapp.core.designsystem.base.StateError import dev.ohoussein.cryptoapp.core.designsystem.base.StateLoading import dev.ohoussein.cryptoapp.core.designsystem.theme.CryptoAppTheme import dev.ohoussein.cryptoapp.core.formatter.ErrorMessageFormatter import dev.ohoussein.cryptoapp.crypto.presentation.R @Suppress("TopLevelPropertyNaming") const val CryptoListTestTag = "CryptoListTestTag" @Suppress("TopLevelPropertyNaming") const val CryptoItemTestTag = "CryptoItemTestTag" @Composable fun CryptoList( modifier: Modifier = Modifier, cryptoList: List<Crypto>, onClick: (Crypto) -> Unit, onRefresh: () -> Unit, isRefreshing: Boolean, ) { SwipeRefresh( state = rememberSwipeRefreshState(isRefreshing), onRefresh = onRefresh, ) { LazyColumn( modifier = modifier .fillMaxSize() .testTag(CryptoListTestTag) ) { items(cryptoList) { crypto -> CryptoItem( modifier = Modifier .testTag(CryptoItemTestTag + crypto.base.id) .fillMaxWidth(), crypto = crypto, onClick = onClick, ) } } } } @Composable fun CryptoListStateScreen( modifier: Modifier = Modifier, cryptoList: List<Crypto>?, cryptoListState: Resource<Unit>, errorMessageMapper: ErrorMessageFormatter, onClick: (Crypto) -> Unit, onRefresh: () -> Unit, ) { when { cryptoList != null -> { Box( modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter ) { CryptoList( cryptoList = cryptoList, onClick = onClick, onRefresh = onRefresh, isRefreshing = cryptoListState.status == Status.LOADING ) if (cryptoListState.status == Status.ERROR) { Snackbar( modifier = Modifier.padding(8.dp), action = { TextButton(onClick = onRefresh) { Text(text = stringResource(id = R.string.core_retry)) } } ) { Text(text = errorMessageMapper.map(cryptoListState.error)) } } } } cryptoListState.status == Status.ERROR -> { StateError( message = errorMessageMapper.map(cryptoListState.error), onRetryClick = onRefresh, ) } else -> { StateLoading() } } } @Composable fun CryptoListScreen( viewModel: HomeViewModel, errorMessageMapper: ErrorMessageFormatter, onClick: (Crypto) -> Unit, ) { val cryptoListState: Resource<Unit> by viewModel.syncState.observeAsState(Resource.loading<Unit>()) val cryptoList: List<Crypto>? by viewModel.topCryptoList.observeAsState() CryptoAppScaffold { CryptoListStateScreen( cryptoList = cryptoList, cryptoListState = cryptoListState, errorMessageMapper = errorMessageMapper, onClick = onClick, onRefresh = { viewModel.refresh(force = true) } ) } } @Preview(showSystemUi = true, showBackground = true) @Composable private fun PreviewCryptoList() { CryptoAppTheme { CryptoList( cryptoList = previewListCrypto, onClick = {}, onRefresh = {}, isRefreshing = false, ) } }
0
Kotlin
0
2
34c2cc5c2c50ef966e869d3eb8ac958f0ca6a8e2
5,126
android-crypto-app
Apache License 2.0
corellium/domain/src/main/kotlin/flank/corellium/domain/run/test/android/step/InstallApks.kt
manuyavuz
382,144,152
true
{"Kotlin": 1837804, "Java": 445714, "Swift": 50324, "Shell": 11210, "Objective-C": 10006, "Dart": 9705, "HTML": 7235, "Gherkin": 4210, "TypeScript": 2717, "Ruby": 2272, "JavaScript": 1764, "SCSS": 1365, "Batchfile": 1319, "EJS": 1061, "Go": 159}
package flank.corellium.domain.run.test.android.step import flank.corellium.api.AndroidApps import flank.corellium.domain.RunTestCorelliumAndroid import flank.corellium.domain.RunTestCorelliumAndroid.InstallApks import flank.corellium.domain.step import flank.shard.Shard import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect /** * The step is installing required software on android instances. * * require: * * [RunTestCorelliumAndroid.Context.authorize] * * [RunTestCorelliumAndroid.Context.prepareShards] * * [RunTestCorelliumAndroid.Context.invokeDevices] */ internal fun RunTestCorelliumAndroid.Context.installApks() = step(InstallApks) { out -> require(shards.size <= ids.size) { "Not enough instances, required ${shards.size} but was $ids.size" } val apks = prepareApkToInstall() api.installAndroidApps(apks).collect { event -> InstallApks.Status(event).out() } // If tests will be executed too fast just after the // app installed, the instrumentation will fail delay(8_000) this } private fun RunTestCorelliumAndroid.State.prepareApkToInstall(): List<AndroidApps> = shards.mapIndexed { index, list: List<Shard.App> -> AndroidApps( instanceId = ids[index], paths = list.flatMap { app -> app.tests.map { test -> test.name } + app.name } ) }
0
null
0
0
c1452e7a586c01b063cdb26f9a2157854659f345
1,351
flank
Apache License 2.0
ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/BuiltinAuthenticationSourceProvider.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.model.security import org.springframework.stereotype.Component @Component class BuiltinAuthenticationSourceProvider : AuthenticationSourceProvider { companion object { const val ID = "built-in" val SOURCE = AuthenticationSource( provider = ID, key = "", name = "Built-in", isEnabled = true, isAllowingPasswordChange = true ) } override val id: String = ID override val sources = listOf(SOURCE) }
60
Kotlin
27
90
aaf7a8cdca185d15c5ff7854483f484f7ebd3a2e
553
ontrack
MIT License
app/src/main/java/com/nimble/nimblerewards/usecases/wallet/FetchNbgSymbolUseCase.kt
nimblehq
198,597,484
false
null
package com.nimble.nimblerewards.usecases.wallet import com.nimble.nimblerewards.data.exceptions.AppError import com.nimble.nimblerewards.data.exceptions.NimbleGoldError.FetchNbgSymbolError import com.nimble.nimblerewards.data.repositories.BlockChainRepository import com.nimble.nimblerewards.usecases.RxScheduler.IoThread import com.nimble.nimblerewards.usecases.RxScheduler.MainThread import com.nimble.nimblerewards.usecases.UseCase import io.reactivex.Single import javax.inject.Inject class FetchNbgSymbolUseCase @Inject constructor( ioThread: IoThread, mainThread: MainThread, private val blockChainRepository: BlockChainRepository ) : UseCase<String, String>(ioThread, mainThread) { override fun create(address: String): Single<String> { return blockChainRepository.fetchNbgSymbol(address) } override fun convertError(throwable: Throwable): (Throwable) -> AppError { return ::FetchNbgSymbolError } }
0
Kotlin
0
1
9af94e7d76cd8d681d46ad06d711da2eeab76233
955
nimble-rewards-android
MIT License
app/src/main/java/com/nimble/nimblerewards/usecases/wallet/FetchNbgSymbolUseCase.kt
nimblehq
198,597,484
false
null
package com.nimble.nimblerewards.usecases.wallet import com.nimble.nimblerewards.data.exceptions.AppError import com.nimble.nimblerewards.data.exceptions.NimbleGoldError.FetchNbgSymbolError import com.nimble.nimblerewards.data.repositories.BlockChainRepository import com.nimble.nimblerewards.usecases.RxScheduler.IoThread import com.nimble.nimblerewards.usecases.RxScheduler.MainThread import com.nimble.nimblerewards.usecases.UseCase import io.reactivex.Single import javax.inject.Inject class FetchNbgSymbolUseCase @Inject constructor( ioThread: IoThread, mainThread: MainThread, private val blockChainRepository: BlockChainRepository ) : UseCase<String, String>(ioThread, mainThread) { override fun create(address: String): Single<String> { return blockChainRepository.fetchNbgSymbol(address) } override fun convertError(throwable: Throwable): (Throwable) -> AppError { return ::FetchNbgSymbolError } }
0
Kotlin
0
1
9af94e7d76cd8d681d46ad06d711da2eeab76233
955
nimble-rewards-android
MIT License
kotlin-example/src/kotlin/common/PIXI.kt
7hens
119,668,810
false
null
package common import modules.PIXI import modules.Rx fun PIXI.DisplayObject.moveTo(targetX: Int, targetY: Int, duration: Double): Rx.Observable<Double> { val speedX = (targetX - x) / duration val speedY = (targetY - y) / duration return App.timer(duration) .doOnNext { deltaTime: Double -> this.x += speedX.times(deltaTime).toInt() this.y += speedY.times(deltaTime).toInt() } .doOnComplete { this.x = targetX this.y = targetY } }
0
Kotlin
0
0
c48fe432296fe84832ca07ffe25b48060fd160cc
555
js-example
Apache License 2.0
projects/android/secure/src/main/java/io/swath/microsoft/security/database/entities/Application.kt
AzureAD
448,733,315
false
{"HTML": 5728885, "Kotlin": 53219, "JavaScript": 39484, "CSS": 34202, "Java": 24432, "TypeScript": 23817}
package io.swath.microsoft.security.database.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Application( @ColumnInfo(name="ClientId") @PrimaryKey val clientId: String, @ColumnInfo(name="Name") val name: String, @ColumnInfo(name="Version") val version: String )
3
HTML
3
2
ea8b89c3867de2af13f73331e4c410e756fe2c3e
347
declaredaccess
MIT License
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderChapterItem.kt
Koykoy200078
255,896,733
true
{"Kotlin": 1823468, "Shell": 1179}
package eu.kanade.tachiyomi.ui.reader import android.content.res.ColorStateList import android.text.format.DateUtils import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.items.AbstractItem import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.util.system.getResourceColor import kotlinx.android.synthetic.main.chapters_item.* import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.util.Date class ReaderChapterItem(val chapter: Chapter, val manga: Manga, val isCurrent: Boolean) : AbstractItem<ReaderChapterItem.ViewHolder> () { var name: String? = null var description: String? = null val decimalFormat = DecimalFormat("#.###", DecimalFormatSymbols().apply { decimalSeparator = '.' }) /** defines the type defining this item. must be unique. preferably an id */ override val type: Int get() = R.id.reader_chapter_layout /** defines the layout which will be used for this item in the list */ override val layoutRes: Int get() = R.layout.reader_chapter_item override var identifier: Long get() = chapter.id!! set(value) {} override fun getViewHolder(v: View): ViewHolder { return ViewHolder(v) } class ViewHolder(view: View) : FastAdapter.ViewHolder<ReaderChapterItem>(view) { var chapterTitle: TextView = view.findViewById(R.id.chapter_title) var chapterSubtitle: TextView = view.findViewById(R.id.chapter_scanlator) var bookmarkButton: FrameLayout = view.findViewById(R.id.bookmark_layout) var bookmarkImage: ImageView = view.findViewById(R.id.bookmark_image) private var readColor = view.context.getResourceColor(android.R.attr.textColorHint) private var unreadColor = view.context.getResourceColor(android.R.attr.textColorPrimary) private var activeColor = view.context.getResourceColor(android.R.attr.colorAccent) private var unbookmark = ContextCompat.getDrawable(view.context, R.drawable .ic_bookmark_border_24dp) private var bookmark = ContextCompat.getDrawable(view.context, R.drawable .ic_bookmark_24dp) override fun bindView(item: ReaderChapterItem, payloads: List<Any>) { val chapter = item.chapter val manga = item.manga chapterTitle.text = when (manga.displayMode) { Manga.DISPLAY_NUMBER -> { val number = item.decimalFormat.format(chapter.chapter_number.toDouble()) itemView.context.getString(R.string.chapter_, number) } else -> chapter.name } val statuses = mutableListOf<String>() if (chapter.date_upload > 0) { statuses.add( DateUtils.getRelativeTimeSpanString( chapter.date_upload, Date().time, DateUtils.HOUR_IN_MILLIS ).toString() ) } if (!chapter.scanlator.isNullOrBlank()) { statuses.add(chapter.scanlator!!) } chapterTitle.setTextColor( when { item.isCurrent -> activeColor chapter.read -> readColor else -> unreadColor } ) chapterSubtitle.setTextColor( when { item.isCurrent -> activeColor chapter.read -> readColor else -> unreadColor } ) bookmarkImage.setImageDrawable(if (chapter.bookmark) bookmark else unbookmark) bookmarkImage.imageTintList = ColorStateList.valueOf(if (chapter.bookmark) activeColor else readColor) chapterSubtitle.text = statuses.joinToString(" • ") } override fun unbindView(item: ReaderChapterItem) { chapterTitle.text = null chapterSubtitle.text = null } } }
0
null
0
0
3d6ad28437a9eb7b9d4df008798516ca69352b4d
4,340
tachiyomiJ2K
Apache License 2.0
src/main/kotlin/com/ekino/oss/crypto/EncryptDecrypt.kt
ekino
224,213,814
false
null
package com.ekino.oss.crypto import java.nio.charset.StandardCharsets import java.security.GeneralSecurityException import java.util.Base64 import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec object EncryptDecrypt { private const val CIPHER_TRANSFORMATION = "AES/CBC/PKCS5PADDING" private const val ALGORITHM = "AES" private val secretKeySpec: SecretKeySpec by lazy { val secretKey = requireNotNull(EncryptCredentialsHolder.SECRET) { "SECRET has to be initialized" } SecretKeySpec(secretKey.toByteArray(StandardCharsets.UTF_8), ALGORITHM) } private val ivParameterSpec: IvParameterSpec by lazy { val ivKey = requireNotNull(EncryptCredentialsHolder.IV) { "IV key has to be initialized" } IvParameterSpec(ivKey.toByteArray(StandardCharsets.UTF_8)) } private val encrypter: Cipher by lazy { Cipher.getInstance(CIPHER_TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec) } } private val decrypter: Cipher by lazy { Cipher.getInstance(CIPHER_TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec) } } @Throws(GeneralSecurityException::class) fun encrypt(toBeEncrypt: String): String { val toBeEncryptedBytes = toBeEncrypt.toByteArray() val encrypted = synchronized(encrypter) { encrypter.doFinal(toBeEncryptedBytes) } return Base64.getEncoder().encodeToString(encrypted) } @Throws(GeneralSecurityException::class) fun decrypt(encrypted: String): String { val encryptedBytes = Base64.getDecoder().decode(encrypted) val decryptedBytes = synchronized(decrypter) { decrypter.doFinal(encryptedBytes) } return String(decryptedBytes) } }
3
Kotlin
0
4
b1438272c8470eda2c249358267c10af58ec2487
1,725
hibernate-crypto-types
MIT License
konsole/src/main/kotlin/com/varabyte/konsole/runtime/internal/executor/KonsoleExecutor.kt
varabyte
397,769,020
false
null
package com.varabyte.konsole.runtime.internal.executor import java.util.concurrent.Executors internal val KonsoleExecutor = Executors.newSingleThreadExecutor { r -> Thread(r, "Konsole Thread").apply { // This thread is never stopped so allow the program to quit even if it's running isDaemon = true } }
30
Kotlin
3
59
af08aaba5a68eb168b20fad0ffd0cc87d8a11bf8
328
konsole
Apache License 2.0
src/main/kotlin/Main.kt
jisungbin
780,422,418
false
{"Kotlin": 21934}
/* * Developed by <NAME> 2024. * * Licensed under the MIT. * Please see full license: https://github.com/jisungbin/strings-desktop/blob/main/LICENSE */ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.WindowState import androidx.compose.ui.window.singleWindowApplication import extendedspan.rememberSquigglyUnderlineAnimator private val WindowSize = DpSize(width = 400.dp, height = 600.dp) fun main() = singleWindowApplication( state = WindowState(size = WindowSize), title = "strings", ) { val nodes = remember { listOf( StringNode( id = "1", value = "Hello, world!", wrongRange = 0..4, wrongDescription = "Hello -> Bye", ), StringNode( id = "2", value = "Hello, School!", ), ) } MaterialTheme { val underlineAnimator = rememberSquigglyUnderlineAnimator() LazyColumn( modifier = Modifier .fillMaxSize() .background(color = MaterialTheme.colorScheme.background), verticalArrangement = Arrangement.spacedBy(12.dp), contentPadding = remember { PaddingValues(all = 16.dp) }, ) { items(items = nodes, key = StringNode::id) { node -> StringNodeUI( modifier = Modifier .fillMaxWidth() .wrapContentHeight(), node = node, underlineAnimator = underlineAnimator, ) } } } }
2
Kotlin
0
2
4989eae3d8f9ad078bd2a1c75500276edae6aa5b
2,003
strings-desktop
MIT License
src/main/kotlin/io/sip3/twig/ce/controller/UserController.kt
sip3io
234,018,899
false
{"Kotlin": 301428}
/* * Copyright 2018-2024 SIP3.IO, Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sip3.twig.ce.controller import io.sip3.twig.ce.service.user.UserService import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses import io.swagger.v3.oas.annotations.tags.Tag import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @Tag(name = "Users API", description = "User Controller") @RestController @RequestMapping("/users") class UserController { @Autowired private lateinit var userService: UserService @Operation(summary = "Get User profile") @ApiResponses( ApiResponse(responseCode = "200", description = "Returns User profile"), ApiResponse(responseCode = "500", description = "InternalServerError"), ApiResponse(responseCode = "504", description = "ConnectionTimeoutError") ) @GetMapping( value = ["/profile"], produces = [MediaType.APPLICATION_JSON_VALUE] ) fun get(): Map<String, Any> { return userService.getProfile() } }
2
Kotlin
4
60
2dd547759131b701e562c5491238d1fef7b5cf82
1,874
sip3-twig-ce
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/WeatherScreen.kt
MarioNoll
349,129,357
false
{"Kotlin": 112565}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.lifecycle.viewmodel.compose.viewModel import com.example.androiddevchallenge.ui.WeatherBox @Composable fun WeatherScreen() { val viewModel = viewModel(WeatherViewModel::class.java) val viewState by viewModel.viewState.collectAsState() WeatherBox( inputListener = viewModel, forecastListItemListener = viewModel, viewState = viewState ) }
0
Kotlin
0
1
1a9b93677e258398c4c92fad1d700c924a0a4a21
1,184
android-dev-challenge-compose-week4
Apache License 2.0
src/main/kotlin/com/bushka/bittrex/network/BittrexException.kt
ColeKainz
288,023,403
false
null
package com.bushka.bittrex.network class BittrexException(msg: String) : RuntimeException(msg)
0
Kotlin
4
2
ec77e3077253acf23f7f8d4c6d7587f601882474
95
bittrex-kotlin-client
MIT License
platform/platform-api/src/com/intellij/openapi/observable/operation/core/PromiseUtil.kt
JetBrains
2,489,216
false
{"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.observable.operation.core import com.intellij.openapi.Disposable import com.intellij.openapi.concurrency.awaitPromise import com.intellij.openapi.concurrency.waitForPromise import com.intellij.openapi.observable.dispatcher.getPromise import com.intellij.openapi.observable.util.getPromise import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.use import kotlinx.coroutines.TimeoutCancellationException import org.jetbrains.annotations.ApiStatus import org.jetbrains.concurrency.Promise import java.util.concurrent.TimeoutException import kotlin.coroutines.cancellation.CancellationException import kotlin.time.Duration fun ObservableOperationTrace.getOperationSchedulePromise(parentDisposable: Disposable): Promise<Nothing?> = scheduleObservable.getPromise(parentDisposable) fun ObservableOperationTrace.getOperationStartPromise(parentDisposable: Disposable): Promise<Nothing?> = startObservable.getPromise(parentDisposable) fun ObservableOperationTrace.getOperationFinishPromise(parentDisposable: Disposable): Promise<Nothing?> = finishObservable.getPromise(parentDisposable) fun ObservableOperationTrace.getOperationCompletionPromise(parentDisposable: Disposable): Promise<Nothing?> = getPromise(parentDisposable) { disposable, listener -> withCompletedOperation(disposable) { listener(null) } } fun <R> ObservableOperationTrace.waitForOperation( startTimeout: Duration, finishTimeout: Duration, action: ThrowableComputable<R, Throwable> ): R = waitForOperation(startTimeout, finishTimeout, { waitForPromise(it) }, { action.compute() }) suspend fun <R> ObservableOperationTrace.awaitOperation( startTimeout: Duration, finishTimeout: Duration, action: suspend () -> R ): R = waitForOperation(startTimeout, finishTimeout, { awaitPromise(it) }, { action() }) fun ObservableOperationTrace.waitForOperationCompletion( completionTimeout: Duration ): Unit = waitForOperationCompletion(completionTimeout) { waitForPromise(it) } suspend fun ObservableOperationTrace.awaitOperationCompletion( completionTimeout: Duration ): Unit = waitForOperationCompletion(completionTimeout) { awaitPromise(it) } @ApiStatus.Internal inline fun <R> ObservableOperationTrace.waitForOperation( startTimeout: Duration, finishTimeout: Duration, wait: Promise<*>.(Duration) -> Unit, action: () -> R ): R { return Disposer.newDisposable("waitForOperation for $name").use { parentDisposable -> val startPromise = getOperationStartPromise(parentDisposable) val finishPromise = getOperationFinishPromise(parentDisposable) runCatching { action() }.onSuccess { runCatching { startPromise.wait(startTimeout) } .throwOnFailureAndWrapTimeout { "Operation '$name' didn't started during $startTimeout.\n$this" } runCatching { finishPromise.wait(finishTimeout) } .throwOnFailureAndWrapTimeout { "Operation '$name' didn't finished during $finishTimeout.\n$this" } }.onFailureCatching { runCatching { startPromise.wait(startTimeout) } .onSuccess { runCatching { finishPromise.wait(finishTimeout) } .throwOnFailureAndWrapTimeout { "Operation '$name' didn't finished during $finishTimeout.\n$this" } } }.getOrThrow() } } @ApiStatus.Internal inline fun ObservableOperationTrace.waitForOperationCompletion( completionTimeout: Duration, wait: Promise<*>.(Duration) -> Unit, ) { return Disposer.newDisposable("waitForOperationCompletion for $name").use { parentDisposable -> val completionPromise = getOperationCompletionPromise(parentDisposable) runCatching { completionPromise.wait(completionTimeout) } .throwOnFailureAndWrapTimeout { "Operation '$name' didn't completed during $completionTimeout.\n$this" } } } @ApiStatus.Internal private fun <T> Result<T>.wrapTimeoutException(lazyMessage: () -> String): Result<T> { return try { Result.success(getOrThrow()) } catch (exception: TimeoutException) { Result.failure(OperationTimeoutException(lazyMessage(), exception)) } catch (exception: TimeoutCancellationException) { Result.failure(OperationTimeoutException(lazyMessage(), exception)) } catch (exception: Throwable) { Result.failure(exception) } } @ApiStatus.Internal fun <T> Result<T>.throwOnFailureAndWrapTimeout(lazyMessage: () -> String) { wrapTimeoutException(lazyMessage).getOrThrow() } private class OperationTimeoutException(message: String, cause: Throwable) : CancellationException(message) { init { initCause(cause) } }
1
null
1
1
0d546ea6a419c7cb168bc3633937a826d4a91b7c
4,746
intellij-community
Apache License 2.0
compiler/testData/codegen/box/dynamic/namedArgumentsMixedPositions.kt
alejes
82,387,788
false
{"Java": 23189191, "Kotlin": 20707963, "JavaScript": 222016, "HTML": 48522, "Protocol Buffer": 47590, "Lex": 18051, "Groovy": 15954, "ANTLR": 9797, "CSS": 9358, "IDL": 6533, "Shell": 4704, "Batchfile": 3721}
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS // JVM_TARGET: 1.8 // WITH_REFLECT class A { fun function1(x: Int, y: Int = 2, z: Int = 8, u: Int = 45, v: Int = -28): Int { return x + 10 * y + 100 * z + 913 * u + 843 * v } } fun box(): String { val a: dynamic = A() return if (a.function1(10, v = 54, z = 11).toString() == "87737") "OK" else "FAIL" }
1
null
1
1
6175c5fbf70e3f03a2e4c10bf3aa4a6af896896c
424
kotlin-dynamic-compiler
Apache License 2.0
ChineseMedicine/dragable_image_viewer/src/main/java/com/draggable/library/extension/ImageViewerHelper.kt
Ketty0725
689,530,479
false
{"Java": 3206321, "Vue": 691518, "JavaScript": 383465, "FreeMarker": 88698, "Kotlin": 79692, "HTML": 28942, "SCSS": 18194, "CSS": 1611, "Dockerfile": 1259, "Batchfile": 392}
@file:JvmName("ImageViewerHelper") package com.draggable.library.extension import android.content.Context import android.graphics.Rect import android.view.View import com.draggable.library.core.DraggableParamsInfo import com.draggable.library.extension.entities.DraggableImageInfo object ImageViewerHelper { private val TAG = javaClass.simpleName class ImageInfo( val thumbnailUrl: String, val originUrl: String = "", val imgSize: Long = 0 ) @JvmStatic fun showSimpleImage( context: Context, url: String, thumbUrl: String = "", view: View? = null, showDownLoadBtn: Boolean = true ) { showImages( context, if (view == null) null else listOf(view), listOf( ImageInfo( thumbUrl, url ) ), showDownLoadBtn = showDownLoadBtn ) } fun showImages( context: Context, images: List<String>, index: Int = 0, showDownLoadBtn: Boolean = true ) { val imgInfos = ArrayList<ImageInfo>() images.forEach { imgInfos.add( ImageInfo( it, it ) ) } showImagesWithSingleView( context, null, imgInfos, index, showDownLoadBtn ) } fun showSimpleImage( context: Context, imgInfo: ImageInfo, view: View? = null, showDownLoadBtn: Boolean = true ) { showImages( context, if (view == null) null else listOf(view), listOf(imgInfo), showDownLoadBtn = showDownLoadBtn ) } @JvmStatic fun showImages( context: Context, views: List<View>?, imgInfos: List<ImageInfo>, index: Int = 0, showDownLoadBtn: Boolean = true ) { if (imgInfos.isEmpty()) return //多张图片开启复杂的方式显示 val draggableImageInfos = ArrayList<DraggableImageInfo>() imgInfos.forEachIndexed { index, imageInfo -> if (views != null && index < views.size) { draggableImageInfos.add( createImageDraggableParamsWithWHRadio( views[index], imageInfo.originUrl, imageInfo.thumbnailUrl, imageInfo.imgSize, showDownLoadBtn ) ) } else { draggableImageInfos.add( createImageDraggableParamsWithWHRadio( null, imageInfo.originUrl, imageInfo.thumbnailUrl, imageInfo.imgSize, showDownLoadBtn ) ) } } ImagesViewerActivity.start(context, draggableImageInfos, index) } fun showImagesWithSingleView( context: Context, view: View?, imgInfos: List<ImageInfo>, picIndex: Int = 0, showDownLoadBtn: Boolean = true ){ if (imgInfos.isEmpty()) return //多张图片开启复杂的方式显示 val draggableImageInfos = ArrayList<DraggableImageInfo>() imgInfos.forEachIndexed { index, imageInfo -> if (view != null && index == picIndex) { draggableImageInfos.add( createImageDraggableParamsWithWHRadio( view, imageInfo.originUrl, imageInfo.thumbnailUrl, imageInfo.imgSize, showDownLoadBtn ) ) } else { draggableImageInfos.add( createImageDraggableParamsWithWHRadio( null, imageInfo.originUrl, imageInfo.thumbnailUrl, imageInfo.imgSize, showDownLoadBtn ) ) } } ImagesViewerActivity.start(context, draggableImageInfos, picIndex) } /** * 根据宽高比,显示一张图片 * @param whRadio 图片宽高比 * */ private fun createImageDraggableParamsWithWHRadio( view: View?, originUrl: String, thumbUrl: String, imgSize: Long = 0, showDownLoadBtn: Boolean = true ): DraggableImageInfo { val draggableInfo: DraggableImageInfo if (view != null) { val location = IntArray(2) view.getLocationInWindow(location) // val windowRect = Rect() // view.getWindowVisibleDisplayFrame(windowRect) val top = location[1] draggableInfo = DraggableImageInfo( originUrl, thumbUrl, DraggableParamsInfo( location[0], top, view.width, view.height ), imgSize, showDownLoadBtn ) } else { draggableInfo = DraggableImageInfo(originUrl, thumbUrl, imageSize = imgSize,imageCanDown = showDownLoadBtn) } draggableInfo.adjustImageUrl() return draggableInfo } }
1
null
1
1
e3dbd069512aa442dd97b70c282a2c110cd6d5d5
5,493
xlbc
Apache License 2.0
app/src/main/java/android/example/health/LoginScreen.kt
HarshRaghav
543,518,159
false
{"Java": 155422, "Kotlin": 146387}
package android.example.health import android.content.Intent import android.example.health.Constants.GlobalData import android.example.health.daos.UserDao import android.example.health.models.User import android.example.health.networkUtils.CheckNetworkConnection import android.example.health.utils.LocalPersistenceManager import android.os.Bundle import android.os.SystemClock import android.util.Log import android.view.View import android.widget.LinearLayout import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatTextView import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.ApiException import com.google.android.gms.tasks.Task import com.google.android.material.button.MaterialButton import com.google.android.material.textfield.TextInputEditText import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.GoogleAuthProvider import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withContext import java.util.regex.Pattern class LoginScreen : AppCompatActivity() { private lateinit var btnLogin: MaterialButton private lateinit var textViewForgetPassword: AppCompatTextView private var mLastClickTime: Long = 0 private val mClickWaitTime: Long = 3000 private lateinit var editTextEmailId: TextInputEditText private lateinit var editTextLoginPassword: TextInputEditText private val TAG = LoginScreen::class.java.simpleName private lateinit var EmailRegex: String private lateinit var EmailPattern: Pattern private lateinit var googleSignIn: GoogleSignInClient private val RC_SIGN_IN = 1234 private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login_screen) val client = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build() auth = Firebase.auth googleSignIn = GoogleSignIn.getClient(this, client) btnLogin = findViewById<View>(R.id.btn_login) as MaterialButton editTextEmailId = findViewById<View>(R.id.login_email_id) as TextInputEditText editTextLoginPassword = findViewById<View>(R.id.login_password) as TextInputEditText textViewForgetPassword = findViewById<View>(R.id.txt_view_forgetPassword) as AppCompatTextView (findViewById<View>(R.id.google_button) as LinearLayout).setOnClickListener (View.OnClickListener { if (SystemClock.elapsedRealtime() - mLastClickTime < mClickWaitTime) { return@OnClickListener } mLastClickTime = SystemClock.elapsedRealtime() if (CheckNetworkConnection.isNetworkAvailable(this@LoginScreen)) { signIn() } else { GlobalData.showSnackbar( this@LoginScreen, findViewById<View>(android.R.id.content), "No Internet Connection", GlobalData.ColorType.ERROR ) } }) btnLogin.setOnClickListener(View.OnClickListener { if (SystemClock.elapsedRealtime() - mLastClickTime < mClickWaitTime) { return@OnClickListener } mLastClickTime = SystemClock.elapsedRealtime() if (CheckNetworkConnection.isNetworkAvailable(this@LoginScreen)) { loginMethod(editTextEmailId.text.toString(), editTextLoginPassword.text.toString()) } else { GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "No Internet Connection", GlobalData.ColorType.ERROR ) } }) textViewForgetPassword.setOnClickListener(View.OnClickListener { if (SystemClock.elapsedRealtime() - mLastClickTime < mClickWaitTime) { return@OnClickListener } mLastClickTime = SystemClock.elapsedRealtime() val intent = Intent(this@LoginScreen, ForgotPasswordActivity::class.java) startActivity(intent) }) //editTextEmailId.setText(LocalPersistenceManager.getLocalPersistenceManager().getUserEmail()==null? "":LocalPersistenceManager.getLocalPersistenceManager().getUserEmail()); } private fun isAllFieldValidated(): Boolean { EmailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\." + "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + "A-Z]{2,7}$" EmailPattern = Pattern.compile(EmailRegex) var isAllFieldValid = true if (editTextEmailId.text.toString().trim { it <= ' ' } == "") { GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "Enter Email ID", GlobalData.ColorType.ERROR ) isAllFieldValid = false }else if (!EmailPattern.matcher(editTextEmailId.text.toString().trim { it <= ' ' }) .matches() ) { GlobalData.showSnackbar( this@LoginScreen, findViewById<View>(android.R.id.content), "Entered Email ID is not in proper format", GlobalData.ColorType.ERROR ) isAllFieldValid = false } else if (editTextLoginPassword.text.toString().trim { it <= ' ' } == "") { GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "Enter password", GlobalData.ColorType.ERROR ) isAllFieldValid = false } return isAllFieldValid } private fun signIn() { val signInIntent = googleSignIn.signInIntent startActivityForResult(signInIntent, RC_SIGN_IN) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) handleSignInResult(task) } } private fun handleSignInResult(task: Task<GoogleSignInAccount>?) { try { val account = task?.getResult(ApiException::class.java)!! firebaseAuthWithGoogle(account.idToken!!) } catch (e: ApiException){ GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "Please try again", GlobalData.ColorType.ERROR ) } } private fun firebaseAuthWithGoogle(idToken: String) { //Sign-in val credential = GoogleAuthProvider.getCredential(idToken, null) GlobalScope.launch(Dispatchers.IO) { val auth = auth.signInWithCredential(credential).await() val firebaseUser = auth.user withContext(Dispatchers.Main) { updateGoogleUI(firebaseUser) } } } private fun updateGoogleUI(firebaseUser: FirebaseUser?) { if(firebaseUser != null) { val user = User( firebaseUser.uid, firebaseUser.displayName.toString(), firebaseUser.photoUrl.toString() ) val usersDao = UserDao() usersDao.addUser(user) LocalPersistenceManager.getLocalPersistenceManager().userName = user.name val mainActivityIntent = Intent(this@LoginScreen, HomeScreenActivity::class.java) startActivity(mainActivityIntent) finish() } } private fun loginMethod(email : String, password : String){ try { if (isAllFieldValidated()) { auth.signInWithEmailAndPassword( email, password ).addOnCompleteListener(this) { task -> if (task.isSuccessful) { val user = auth.currentUser update(user) } else { if (task.exception?.toString() == "com.google.firebase.auth.FirebaseAuthInvalidUserException: There is no user record corresponding to this identifier. The user may have been deleted.") { GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "User does not exist.", GlobalData.ColorType.ERROR ) update(null) } else if (task.exception?.toString() == "com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The email address is badly formatted."){ GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "Email is badly formatted.", GlobalData.ColorType.ERROR ) update(null) } else if (task.exception?.toString() == "com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The password is invalid or the user does not have a password."){ GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "Invalid username or password.", GlobalData.ColorType.ERROR ) update(null) } } } } } catch (e: Exception) { GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "Please try again", GlobalData.ColorType.ERROR ) update(null) } } private fun update(firebaseUser: FirebaseUser?){ if(firebaseUser != null) { GlobalScope.launch { val userDao = UserDao() val user = userDao.getUserById(firebaseUser.uid).await().toObject(User::class.java)!! Log.v("Ishita", "login") LocalPersistenceManager.getLocalPersistenceManager().userName = user.name userDao.loginUser(user) } val mainActivityIntent = Intent(this@LoginScreen, HomeScreenActivity::class.java) startActivity(mainActivityIntent) finish() } } override fun onDestroy() { super.onDestroy() googleSignIn.signOut().addOnCompleteListener(this) { task -> if(task.isSuccessful){ updateGoogleUI(null) } else { GlobalData.showSnackbar( this@LoginScreen, findViewById(android.R.id.content), "Please try again", GlobalData.ColorType.ERROR ) } } } }
1
null
1
1
8765c88b2d33ed7af77bb854dd59a7dc4ec0bddc
12,117
digicure
Apache License 2.0
funker/src/main/java/at/dibiasi/funker/utils/BluetoothDeviceFinder.kt
ddibiasi
190,774,420
false
null
package at.dibiasi.funker.utils import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.util.Log import at.dibiasi.funker.error.BluetoothDisabledException import at.dibiasi.funker.error.NoBluetoothException import io.reactivex.Observable import io.reactivex.ObservableEmitter import kotlin.NoSuchElementException private const val TAG = "## BluetoothHelper" class BluetoothDeviceFinder(private val context: Context) { companion object { private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter() /** * Searches bonded devices and doesn't look for new ones * is NOT async * @return Bluetoothdevice? */ fun searchBonded(address: String): BluetoothDevice? { Log.d(TAG, "Starting search") val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices return try { pairedDevices?.first { it.address == address } } catch (e: NoSuchElementException) { Log.e(TAG, "No previously paired device found") null } } } private var addressToBeSearchedFor: String = "" private var indefiniteSearch: Boolean = false private var emitter: ObservableEmitter<BluetoothDevice>? = null /** * Searches for specified bluetooth device * This method is threaded and therefor async * @return Emits when ever a device is found */ fun search( address: String = "", checkPaired: Boolean = false, indefinite: Boolean = false ): Observable<BluetoothDevice> { Log.d(TAG, "Starting search") return Observable.create { emitter = it indefiniteSearch = indefinite Log.d(TAG, "Setting up helper") checkAdapter() addressToBeSearchedFor = address registerReceiver() if (checkPaired) checkPairedDevices() startDiscovery() } } private fun checkAdapter() { if (bluetoothAdapter == null) { // is bluetooth available on this device emitter?.onError(NoBluetoothException()) } if (bluetoothAdapter?.isEnabled != true) { // enable bluetooth if not enabled Log.e(TAG, "Bluetooth is disabled") emitter?.onError(BluetoothDisabledException()) } } private fun registerReceiver() { val filter = IntentFilter(BluetoothDevice.ACTION_FOUND) filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) context.registerReceiver(deviceReceiver, filter) } /** * Glue method, searches for new devices */ private fun startDiscovery() { bluetoothAdapter?.let { btAdapter -> Log.d(TAG, "Starting bluetooth discovery") if (btAdapter.isDiscovering) { btAdapter.cancelDiscovery() } btAdapter.startDiscovery() } } fun stopSearch() { Log.d(TAG, "Cancel bluetooth discovery") indefiniteSearch = false bluetoothAdapter?.cancelDiscovery() emitter?.onComplete() try { context.unregisterReceiver(deviceReceiver) } catch (ex: IllegalArgumentException) { Log.d(TAG, "Broadcast deviceReceiver already unregistered") } } /** * Checks previously paired devices */ private fun checkPairedDevices() { Log.d(TAG, "Checking already paired devices") val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices pairedDevices?.forEach { device -> emitDevice(device) } } /** * Emits device to the initialized observable */ private fun emitDevice(device: BluetoothDevice) { val evaluation: Boolean = if (addressToBeSearchedFor.isEmpty()) { true // All devices shall be emited } else { device.address == addressToBeSearchedFor // only device with matching address } if (evaluation) { Log.d(TAG, "Found match: ${device.name} , ${device.address}") emitter?.onNext(device) if (addressToBeSearchedFor.isNotEmpty()) stopSearch() } } /** * BroadcastReceiver for ACTION_FOUND. Needs to be public. */ val deviceReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { intent.action?.let { action -> when (action) { BluetoothDevice.ACTION_FOUND -> { val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) Log.d(TAG, "Found device: ${device.name} , ${device.address}") emitDevice(device) } BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> { Log.d(TAG, "Finished discovery") if (indefiniteSearch){ startDiscovery() }else{ stopSearch() } } else -> { Log.d(TAG, action) } } } } } }
0
null
5
7
02c2d398a178017448fd0e655d31c05bd43fe0bd
5,622
Funker
MIT License
proxy/src/main/kotlin/kingmc/platform/proxy/ProxiedServer.kt
Kingsthere
599,960,106
false
null
package kingmc.platform.proxy import kingmc.platform.Server /** * A `ProxiedServer` represent a sub-server that `ProxyServer` could forward to * * @since 0.0.8 * @author kingsthere */ interface ProxiedServer : Server { /** * The `ServerInfo` for this `ProxiedServer` */ val serverInfo: ServerInfo }
0
Kotlin
0
0
ec098cefd4f82dcd3f9d55430b5a187122d75db6
323
kingmc-platform
MIT License
app/src/main/java/io/exzocoin/wallet/modules/sendevm/confirmation/SendEvmConfirmationModule.kt
rexdev0211
403,525,735
false
{"Kotlin": 2356794, "Shell": 2039, "Ruby": 966}
package io.exzocoin.wallet.modules.sendevm.confirmation import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavOptions import io.exzocoin.wallet.core.App import io.exzocoin.wallet.core.ethereum.EthereumFeeViewModel import io.exzocoin.wallet.core.ethereum.EvmCoinServiceFactory import io.exzocoin.wallet.core.ethereum.EvmTransactionService import io.exzocoin.wallet.core.factories.FeeRateProviderFactory import io.exzocoin.wallet.modules.sendevm.SendEvmData import io.exzocoin.wallet.modules.sendevm.SendEvmModule import io.exzocoin.wallet.modules.sendevmtransaction.SendEvmTransactionService import io.exzocoin.wallet.modules.sendevmtransaction.SendEvmTransactionViewModel import io.exzocoin.coinkit.models.CoinType import io.exzocoin.core.findNavController import io.horizontalsystems.ethereumkit.core.EthereumKit import io.horizontalsystems.ethereumkit.core.EthereumKit.NetworkType object SendEvmConfirmationModule { class Factory( private val evmKit: EthereumKit, private val sendEvmData: SendEvmData ) : ViewModelProvider.Factory { private val feeCoin by lazy { when (evmKit.networkType) { NetworkType.EthMainNet, NetworkType.EthRopsten, NetworkType.EthKovan, NetworkType.EthRinkeby -> App.coinKit.getCoin(CoinType.Ethereum)!! NetworkType.BscMainNet -> App.coinKit.getCoin(CoinType.BinanceSmartChain)!! } } private val transactionService by lazy { val feeRateProvider = FeeRateProviderFactory.provider(feeCoin)!! EvmTransactionService(evmKit, feeRateProvider, 20) } private val coinServiceFactory by lazy { EvmCoinServiceFactory(feeCoin, App.coinKit, App.currencyManager, App.xRateManager) } private val sendService by lazy { SendEvmTransactionService(sendEvmData, evmKit, transactionService, App.activateCoinManager) } @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { return when (modelClass) { SendEvmTransactionViewModel::class.java -> { SendEvmTransactionViewModel(sendService, coinServiceFactory) as T } EthereumFeeViewModel::class.java -> { EthereumFeeViewModel(transactionService, coinServiceFactory.baseCoinService) as T } else -> throw IllegalArgumentException() } } } fun start(fragment: Fragment, navigateTo: Int, navOptions: NavOptions, sendData: SendEvmData) { val arguments = bundleOf( SendEvmModule.transactionDataKey to SendEvmModule.TransactionDataParcelable(sendData.transactionData), SendEvmModule.additionalInfoKey to sendData.additionalInfo ) fragment.findNavController().navigate(navigateTo, arguments, navOptions) } }
0
Kotlin
1
0
1ed5d80490ecf1574499cafa5aad922c4ea9a362
3,065
exzo-android-wallet-main
MIT License
data/src/main/kotlin/com/ilgiz/kitsu/data/remote/dtos/anime/CoverImage.kt
ilgiz05
493,465,307
false
null
package com.ilgiz.kitsu.data.remote.dtos.anime import com.google.gson.annotations.SerializedName import com.ilgiz.kitsu.domain.models.anime.CoverImageModel data class CoverImage( @SerializedName("tiny") val tiny: String, @SerializedName("small") val small: String, @SerializedName("large") val large: String, @SerializedName("original") val original: String, @SerializedName("meta") val meta: MetaX ) fun CoverImage.toDomain() = CoverImageModel( tiny, small, large, original, meta.toDomain() )
0
Kotlin
0
0
f9d4b4b9899bc2faa3fc992233c3187774d3d8d8
557
lesson7.kotlin3
MIT License
domain/src/commonMain/kotlin/ly/david/musicsearch/domain/search/results/usecase/GetSearchResults.kt
lydavid
458,021,427
false
{"Kotlin": 1354694, "HTML": 674577, "Python": 3489, "Shell": 1543, "Ruby": 955}
package ly.david.musicsearch.domain.search.results.usecase import ly.david.musicsearch.core.models.network.MusicBrainzEntity import ly.david.musicsearch.domain.search.results.SearchResultsRepository import org.koin.core.annotation.Single @Single class GetSearchResults( private val searchResultsRepository: SearchResultsRepository, ) { operator fun invoke( entity: MusicBrainzEntity, query: String, ) = searchResultsRepository.observeSearchResults(entity, query) }
102
Kotlin
0
6
5e15119a3c55efa932e37afced1b56609e988fe6
495
MusicSearch
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/CheeseAlt.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.CheeseAlt: ImageVector get() { if (_cheeseAlt != null) { return _cheeseAlt!! } _cheeseAlt = Builder(name = "CheeseAlt", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(0.0f, 16.0f) curveToRelative(0.0f, 1.52f, 0.27f, 3.07f, 0.79f, 4.61f) curveToRelative(0.69f, 2.03f, 2.6f, 3.39f, 4.74f, 3.39f) horizontalLineToRelative(13.47f) curveToRelative(2.76f, 0.0f, 5.0f, -2.24f, 5.0f, -5.0f) verticalLineToRelative(-7.49f) curveToRelative(0.0f, -1.88f, -0.9f, -3.68f, -2.41f, -4.81f) lineTo(13.79f, 0.88f) curveToRelative(-1.8f, -1.2f, -4.1f, -1.16f, -5.75f, 0.08f) curveTo(2.74f, 4.92f, 0.87f, 11.16f, 0.79f, 11.39f) curveTo(0.27f, 12.93f, 0.0f, 14.48f, 0.0f, 16.0f) close() moveTo(19.99f, 8.0f) lineTo(5.53f, 8.0f) curveToRelative(-0.4f, 0.0f, -0.78f, 0.05f, -1.16f, 0.14f) curveToRelative(0.96f, -1.69f, 2.51f, -3.81f, 4.87f, -5.57f) curveToRelative(0.98f, -0.73f, 2.35f, -0.75f, 3.4f, -0.05f) lineToRelative(7.35f, 5.49f) close() moveTo(2.0f, 16.0f) curveToRelative(0.0f, -1.3f, 0.23f, -2.64f, 0.68f, -3.96f) curveToRelative(0.42f, -1.22f, 1.56f, -2.04f, 2.84f, -2.04f) lineTo(21.7f, 10.0f) curveToRelative(0.19f, 0.47f, 0.3f, 0.99f, 0.3f, 1.51f) verticalLineToRelative(7.49f) curveToRelative(0.0f, 1.65f, -1.35f, 3.0f, -3.0f, 3.0f) lineTo(5.53f, 22.0f) curveToRelative(-1.29f, 0.0f, -2.43f, -0.82f, -2.84f, -2.04f) curveToRelative(-0.45f, -1.33f, -0.68f, -2.66f, -0.68f, -3.96f) close() } } .build() return _cheeseAlt!! } private var _cheeseAlt: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,920
icons
MIT License
app/src/main/java/com/project22/myapplication/screens/ImageSender.kt
reuben21
390,672,747
false
{"Kotlin": 155492}
package com.project22.myapplication.screens import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.project22.myapplication.R class ImageSender : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_image_sender) } }
0
Kotlin
0
0
ebea676857bd06960b249031ed589dd2ee0430e0
360
TravelMate
MIT License
src/main/kotlin/korrit/kotlin/openapi/model/Response.kt
Koriit
217,255,706
false
null
package com.korrit.kotlin.openapi.model import com.korrit.kotlin.openapi.YAML_INDENT /** * Describes a single response from an API Operation. * * Representation of [Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responseObject). * * @property code HTTP response code. * @property content Descriptions of potential response payloads * @property description A short description of the response. * @property headers Response headers definitions. * * @WIP */ class Response( val code: String, val content: List<MediaType>?, val description: String, val headers: List<Header>? ) { /** * Returns YAML representation. */ override fun toString(): String { val spec = StringBuilder().apply { appendLine() appendLine("description: >-") append(description.prependIndent(YAML_INDENT)) headers?.let { appendLine() append("headers:") val out = StringBuilder() for (header in headers) { out.apply { appendLine() append(header.toString()) } } append(out.toString().prependIndent(YAML_INDENT)) } content?.let { appendLine() append("content:") for (media in content) { appendLine() append(media.toString().prependIndent(YAML_INDENT)) } } } return "\"$code\":" + spec.toString().prependIndent(YAML_INDENT) } }
2
Kotlin
0
0
c0860640c17e8356e1ca1c14bd049b890da807cd
1,684
openapi-matcher
MIT License
app/src/main/java/com/jdagnogo/welovemarathon/tips/data/TipsMapper.kt
jdagnogo
424,252,162
false
{"Kotlin": 625180}
package com.jdagnogo.welovemarathon.tips.data import androidx.annotation.Keep import com.jdagnogo.welovemarathon.tips.domain.Tips @Keep class TipsMapper { fun toTips(entities: List<TipsEntity>): List<Tips> { return entities.map { it.toTips() } } fun toTipsEntities(tips: List<Tips>): List<TipsEntity> { return tips.map { it.toTipsEntity() } } }
0
Kotlin
0
0
e82d9fb221b605ce996a68dc938692273279f662
420
WeLoveMArathon
The Unlicense
src/main/kotlin/org/rust/ide/fixes/RsConvertBlockToLoopFix.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.fixes import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.lang.core.psi.RsBlockExpr import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.RsWhileExpr import org.rust.lang.core.psi.ext.RsLabelReferenceOwner import org.rust.lang.core.psi.ext.ancestorStrict class RsConvertBlockToLoopFix(element: RsBlockExpr): LocalQuickFixAndIntentionActionOnPsiElement(element) { override fun getFamilyName(): String = "Convert to loop" override fun getText(): String = familyName override fun invoke(project: Project, file: PsiFile, editor: Editor?, blockExpr: PsiElement, endElement: PsiElement) { val rsBlockExpr = blockExpr as RsBlockExpr val labelName = rsBlockExpr.labelDecl?.name ?: return rsBlockExpr.replace(RsPsiFactory(project).createLoop(rsBlockExpr.block.text, labelName)) } }
1,805
Kotlin
368
4,389
f121641a20b22cc2006077e83fd5a28183ccf243
1,161
intellij-rust
MIT License
Entrega/app/src/main/java/com/jjmorillo/ladespensademicasa/database/AppDatabase.kt
jjmorleo
356,499,729
false
null
package com.jjmorillo.ladespensademicasa.database import android.content.Context import androidx.room.* import androidx.sqlite.db.SupportSQLiteDatabase import com.jjmorillo.ladespensademicasa.application.App import com.jjmorillo.ladespensademicasa.database.converter.Converters import com.jjmorillo.ladespensademicasa.database.daos.* import com.jjmorillo.ladespensademicasa.database.entities.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @Database(entities = arrayOf(Usuario::class, Tornillo::class, Producto::class, Pedido::class, PedidosProductosCrossRef::class ), version = 1) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun usuarioDao(): UsuarioDao //ESTO ES UNA FUNCION ABSTRACTA Y VA A DEVOLVER UN UsuarioDAO y se llama usuarioDao() abstract fun mainDao(): MainDao abstract fun tornilloDao(): TornilloDao abstract fun productoDao(): ProductoDao abstract fun pedidoDao(): PedidoDao companion object { private var instance: AppDatabase? = null private const val NAME_DB = "La despensa de mi casa" fun newInstance(context: Context): AppDatabase { if (instance == null) {//AQUI INICIALIZAMOS LA BASE DE DATOS instance = Room.databaseBuilder(context, AppDatabase::class.java, NAME_DB) .addCallback(callback) .build() } return instance!! } //CALLBACK ES UNA ASBTRACT CLAAS POR ESO SE LE PONE OBJECT //EN ESTE CASO CUANDO PONEMOS LAS LLAVES LO QUE HACEMOS ES UNA IMPLEMENTACION DE ONCREATE //ESTO SE REALIZA CUANDO QUEREMOS PREINSERTAR DATOS AL INICIO private val callback: Callback = object : Callback() { override fun onCreate(db: SupportSQLiteDatabase) { super.onCreate(db) GlobalScope.launch { //INSERCION DE DATOS //AQUI PODEMOS INSERTAR UN USUARIO DE FORMA PREDETERMINADA withContext(Dispatchers.IO) {//ESTO SERIA UN EJEMPLO DE COMO INSERTAR USUARIO EN LA BASE DE DATOS PARA SIEMPRE App.obtenerDB().productoDao().save(Producto("Cereales con chocolate belga", "kollbram", "Cereales con chocolate belga 375 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/cerealeschocolatebelga.jpg?alt=media&token=<PASSWORD>", 7.33, 2.75,"prueba")) App.obtenerDB().productoDao().save(Producto("galletas cookies", "gullon", "galletas de trigo con chocolate 250 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletascookies.jpg?alt=media&token=<PASSWORD>", 0.85, 1.85,"prueba")) App.obtenerDB().productoDao().save(Producto("Galletas Dinosaurus", "ARTIACH", "Galletas Dinosaurus Huevo Artiach 140 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletasdinosaurus.jpg?alt=media&token=<PASSWORD>", 10.00, 1.40,"prueba")) App.obtenerDB().productoDao().save(Producto("cereale integrales sin gluten", "hacendado", "cereales sin gluten 450 g ", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/cerealesintegraleseco.jpg?alt=media&token=<PASSWORD>", 11.17, 3.35,"prueba")) App.obtenerDB().productoDao().save(Producto("estrellas de chocolate", "lu principe", "estrella de galletas de chocolate 150 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletasestrella.jpg?alt=media&token=<PASSWORD>", 0.95, 1.18,"prueba")) App.obtenerDB().productoDao().save(Producto( "galletas oreo original", "mondelez", "pack galletas oreo 154 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletasoreo.jpg?alt=media&token=8dbc8715-eb7e-4984-a8bf-91fc25ff1944", 6.80, 2.99,"prueba")) App.obtenerDB().productoDao().save(Producto("galletas de chocolate", "carrefour", "Galletas chocolate con leche Digestive Carrefour 300 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletaschocolate.jpg?alt=media&token=aa6773d4-a8c7-4e40-af62-114059812902", 2.67, 0.80,"prueba")) App.obtenerDB().productoDao().save(Producto("Galleta flakes choco", "cuetara", "Galleta flakes choco cuetara 550g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletachocoflakes.jpg?alt=media&token=<PASSWORD>", 4.45, 2.45,"prueba")) App.obtenerDB().productoDao().save(Producto("galleta principe mini", "principe", "galleta de chocolate 160 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletasprincipemini.jpg?alt=media&token=2d6df324-82b7-4e35-aa50-d8ab87912398", 9.06, 1.45,"prueba")) App.obtenerDB().productoDao().save(Producto("galleta chips ahoy", "chips ahoy", "irresistibles con chocolate 125 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/chipsahoy.jpg?alt=media&token=7d0cfd34-507c-4570-87ba-a4886596710c", 0.70, 1.18,"prueba")) App.obtenerDB().productoDao().save(Producto("galletas con naranja", "flora", "galletas de cereales 160 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletanaranja.jpg?alt=media&token=12782671-ad35-47b5-9ac7-5b96b8038b94", 0.45, 1.65,"prueba")) App.obtenerDB().productoDao().save(Producto("Galletas rellena cacao", "nocilla", "Galletas rellena con crema de cacao Nocilla 120 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletasnocilla.jpg?alt=media&token=<PASSWORD>", 0.85, 2.74,"prueba")) App.obtenerDB().productoDao().save(Producto("galletas de café", "reglero", "café regelo colombianos 260 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletascafe.jpg?alt=media&token=c44e0e86-aebc-4c1d-b732-c9148125edf8", 0.95, 3.52,"prueba")) App.obtenerDB().productoDao().save(Producto("galletas bio", "gullón", "bio organic digestive 270 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletasbio.jpg?alt=media&token=59a514bd-595f-40d1-988a-10aaa10b3624", 0.89, 3.29,"prueba")) App.obtenerDB().productoDao().save(Producto("Azafrán en hebras", "CARMENCITA", "Azafrán en hebras Carmencita 0,375 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/azafr%C3%A1n.jpg?alt=media&token=12a87307-2752-4d8e-9497-26fe40f744cf", 72.90, 2.90,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Levadura", "ROYAL", "Levadura Royal pack de 6 sobres de 16 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/levadura.jpg?alt=media&token=733b7f9e-f9a4-4dc3-b149-6bb54fc5b0bc", 23.25, 2.29,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Arroz", "SOS", "Arroz redondo Sos 1 kg.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/arrozsos.jpg?alt=media&token=646a9edc-ccaa-4917-a1b7-3394b2440d5b", 1.55, 1.55,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Alubia blanca", "LUENGO", "Alubia blanca categoría extra Luengo 1 kg.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/alubialuengo.jpg?alt=media&token=1ff3aa61-a114-437c-9d95-3e7032d7f5bc", 2.75, 2.75,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Lenteja pardina", "LUENGO", "Lenteja pardina categoría extra Luengo 1 kg.x", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/lentejaluengo.jpg?alt=media&token=6d822201-4eac-40da-a3d8-68e2c99be8e9", 3.05, 3.05,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Aceite de oliva", "DCOOP", "Aceite de oliva virgen extra Dcoop garrafa 5 l.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/aceiteoliva.jpg?alt=media&token=<PASSWORD>", 2.09, 10.45,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Mayonesa", "HELLMANN'S", "Mayonesa tarro 650 ml.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/mayonesa.jpg?alt=media&token=<KEY>", 3.06, 1.99,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Macarrones", "GALLO", "Macarrones plumas nº6 750 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/macarr%C3%B3ngallo.jpg?alt=media&token=d64a1d6f-9047-4eee-a44c-9790981a4053", 1.69, 1.27,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Vinagre balsámico", "CARREFOUR", "Vinagre balsámico de módena Carrefour 250 ml.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/vinagrevalsamico.jpg?alt=media&token=<PASSWORD>", 4.60, 1.15,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Berengena", "VERDURAS", "Berenjena a granel 500 g arpox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/berengena.jpg?alt=media&token=a21d6c36-4ba3-4ed8-aece-27a16729c623", 3.83, 1.15,"alimentacion")) App.obtenerDB().productoDao().save(Producto("Coca Cola zero", "COCACOLA", "Coca Cola zero azúcar pack 4 botellas 2 l.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/cocacolazero.jpg?alt=media&token=cd68289a-f816-47af-a670-ce9011ff3979", 0.84, 6.76,"bebida")) App.obtenerDB().productoDao().save(Producto("Aquarius sabor limón zero", "ACUARIUSZERO", "Aquarius sabor limón zero botella 1.5 l.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/acuariolimon.jpg?alt=media&token=<PASSWORD>", 1.15, 1.72,"bebida")) App.obtenerDB().productoDao().save(Producto("Vino Semidulce", "DIAMANTE", "Diamante Semidulce Sin Crianza", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/diamante.jpg?alt=media&token=4556e200-a79c-4b0c-ad13-ce7ba957cda8", 3.99, 3.99,"bebida")) App.obtenerDB().productoDao().save(Producto("Fanta naranja", "COCACOLA", "Refresco de naranja Fanta con gas pack de 2 botellas de 2 l.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/fantanaranja.jpg?alt=media&token=e9c2b5e9-387e-4d81-a694-1dda9465b705", 0.57, 2.28,"bebida")) App.obtenerDB().productoDao().save(Producto("Vino Blanco", "FOUR LINES", "Four Lines Blanco 2020", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/fourlineblanco.jpg?alt=media&token=<PASSWORD>", 5.50, 5.50,"bebida")) App.obtenerDB().productoDao().save(Producto("Gaseosa", "LA CASERA", "Gaseosa La Casera cero calorías pack de 4 botellas de 1,5 l.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/gaseosa.jpg?alt=media&token=<PASSWORD>", 0.55, 3.30,"bebida")) App.obtenerDB().productoDao().save(Producto("Whisky", "<NAME>", "<NAME> Double Black Whisky", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/joniwalker.jpg?alt=media&token=4d645ebf-a41a-425a-9a05-aefae7a311d3", 39.86, 27.90,"bebida")) App.obtenerDB().productoDao().save(Producto("Vino Rioja", "<NAME> ", "<NAME> 2017", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/riojaluisca%C3%B1a.jpg?alt=media&token=4ac12d92-ebbc-488b-a10f-ea4963bfe8c3", 10.50, 10.50,"bebida")) App.obtenerDB().productoDao().save(Producto("Tónica Schweppes zero", "SCHWEPPES", "Tónica Schweppes zero lata 25 cl.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/tonicalatazero.jpg?alt=media&token=804ecf7b-5400-4b73-a51b-648214e05603", 2.88, 0.72,"bebida")) App.obtenerDB().productoDao().save(Producto("Vino frizzante", "YLLERA", "Yllera 5.5 Verdejo Frizzante", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yllera.jpg?alt=media&token=4e54030a-fa49-4f4f-9737-9e2d1bd76967", 5.69, 5.69,"bebida")) App.obtenerDB().productoDao().save(Producto("Detergente ropa", "ARIEL", "Detergente líquido Alpine Ariel 50 lavados.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/ariel.jpg?alt=media&token=a0b4ad6b-266c-403e-a2af-0d5eb1fd5f16", 0.28, 13.95,"drogueria")) App.obtenerDB().productoDao().save(Producto("Limpiador desinfectante", "SANYTOL", "Limpiador desinfectante multiusos sin lejía Sanytol 750 ml", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/desinfectante.jpg?alt=media&token=f524421b-65b0-414e-8f2e-9f537d04d232", 3.13, 2.35,"drogueria")) App.obtenerDB().productoDao().save(Producto("Limpiador de baño", "DON LIMPIO", "Limpiador de baño Don Limpio 1,5 l.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/donlimpio.jpg?alt=media&token=94c6dce2-6491-4367-b55c-4e045465b206", 1.50, 2.25,"drogueria")) App.obtenerDB().productoDao().save(Producto("Lavavajillas a mano", "FAIRY", "Lavavajillas a mano Fairy Ultra Poder 650 ml.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/fairy.jpg?alt=media&token=431d8ffc-9c08-453c-b5a7-040169e3b644", 4.62, 3.00,"drogueria")) App.obtenerDB().productoDao().save(Producto("Lejía", "CONEJO", "Lejía acción total Conejo 2 l.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/lejia.jpg?alt=media&token=600dd6f4-2047-4e77-9dc3-291f48d3964a", 0.89, 1.79,"drogueria")) App.obtenerDB().productoDao().save(Producto("Caja de pañuelos", "KLEENEX", "Caja de pañuelos Family Kleenex 140 ud.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/pa%C3%B1uelos.jpg?alt=media&token=cfcf2216-eafc-4af8-ba29-2f65528c5974", 0.01, 1.80,"drogueria")) App.obtenerDB().productoDao().save(Producto("Papel higiénico", "SCOTTEX", "Papel higiénico acolchado toque de seda Scottex 24 rollos.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/papelhigienico.jpg?alt=media&token=f47d62b4-9065-4a1c-b88f-bec5036ba4c7", 0.44, 10.50,"drogueria")) App.obtenerDB().productoDao().save(Producto("Quitagrasas", "KH-7 ", "Quitagrasas original KH-7 recambio 750 ml.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/quitagrasas.jpg?alt=media&token=535a02bd-ae21-4a9a-b1fb-4b15afa772c8", 3.59, 2.69,"drogueria")) App.obtenerDB().productoDao().save(Producto("Servilletas", "RENOVA", "Set de Servilletas 1 capa de Celulosa RENOVA 200 200pz - Blancas", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/servilletas.jpg?alt=media&token=646767a5-1403-4492-8554-f119066a659a", 0.01, 0.92,"drogueria")) App.obtenerDB().productoDao().save(Producto("Suavizante concentrado", "FLOR", "Suavizante concentrado azul Flor 72 lavados.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/suavizante.jpg?alt=media&token=f4fc4fb7-06a3-43a6-a6cf-6b0f6b717fe9", 0.05, 3.94,"drogueria")) App.obtenerDB().productoDao().save(Producto("Mango", "FRUTA", "Mango nacional a granel 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/mango.jpg?alt=media&token=821eab35-bcb4-4c2b-9a85-9ba1844e2da8", 1.12, 2.25,"fruta")) App.obtenerDB().productoDao().save(Producto("Kiwi", "ZESPRI", "Kiwi Zespri 1 Kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/kiwizespri.jpg?alt=media&token=552202bb-c089-49c0-80b1-341ad96bb24e", 3.99, 3.99,"fruta")) App.obtenerDB().productoDao().save(Producto("Piña", "MONTE", "Piña del Monte premium pieza 1,5 Kg aprox ", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/pi%C3%B1a.jpg?alt=media&token=f68691c6-0767-4b51-83f0-ea1cebd39c35", 1.49, 2.23,"fruta")) App.obtenerDB().productoDao().save(Producto("Calabacín", "VERDURA", "Calabacín la despensa a granel 1 kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/calabacin.jpg?alt=media&token=<PASSWORD>", 1.19, 1.19,"fruta")) App.obtenerDB().productoDao().save(Producto("Calabaza sepallo", "VERDURA", "Calabaza sepallo a granel 1,5 kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/calabaza.jpg?alt=media&token=<PASSWORD>", 1.25, 1.87,"fruta")) App.obtenerDB().productoDao().save(Producto("Cebolla dulce selección", "FUENTE", "Cebolla dulce selección 1 Kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/cebollafuente.jpg?alt=media&token=<PASSWORD>", 1.99, 1.99,"fruta")) App.obtenerDB().productoDao().save(Producto("Aguacate", "FRUTA", "Aguacate de origen nacional 500 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/aguacate.jpg?alt=media&token=<PASSWORD>", 4.00, 2.00,"fruta")) App.obtenerDB().productoDao().save(Producto("Espárrago verde", "VERDURAS", "Espárrago verde manojo de 300 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/esparrago.jpg?alt=media&token=<PASSWORD>", 3.83, 1.15,"fruta")) App.obtenerDB().productoDao().save(Producto("Berengena", "VERDURAS", "Berenjena a granel 500 g arpox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/berengena.jpg?alt=media&token=<PASSWORD>", 3.83, 1.15,"fruta")) App.obtenerDB().productoDao().save(Producto("Plátano", "COPLACA", "Plátano de Canarias 500 g arpox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/platano.jpg?alt=media&token=90896c21-7f5d-4c9b-ab43-7683cb059e74", 3.95, 2.00,"fruta")) App.obtenerDB().productoDao().save(Producto("Preparado de carne picada", "AVINATUR", "Preparado de carne picada de vacuno 2x450 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/carnepicada.jpg?alt=media&token=585dd623-59fa-4d10-bad8-8bed90db2374", 5.21, 4.69,"carne")) App.obtenerDB().productoDao().save(Producto("Lomo de cerdo adobado", "PAVOFRIO", "Lomo de cerdo adobado fileteado 650 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/lomoadobado.jpg?alt=media&token=<PASSWORD>", 6.50, 4.22,"carne")) App.obtenerDB().productoDao().save(Producto("Pechuga de pollo", "PAVISO", "Pechuga de pollo certificado en filetes 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/pechugapollo.jpg?alt=media&token=52d951e2-df39-4c9e-8777-2d458aa47bad", 8.29, 4.14,"carne")) App.obtenerDB().productoDao().save(Producto("Entrecot de vacuno", "PAVISO", "Entrecot de vacuno para la piedra 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/entrcotternera.jpg?alt=media&token=4c5ac398-d85c-4f06-84df-b5845c63ba1a", 10.95, 5.45,"carne")) App.obtenerDB().productoDao().save(Producto("Trozo lomo cerdo ", "AVINATUR", "Trozo de lomo de cerdo 1,2 kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/trozolomocerdo.jpg?alt=media&token=b6145be6-220b-4bc1-a0eb-a36be36cfb76", 3.95, 4.74,"carne")) App.obtenerDB().productoDao().save(Producto("Pechuga de pollo campero", "PAVISO", "Pechuga de pollo campero fileteada 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/pechugacampero.jpg?alt=media&token=<PASSWORD>", 13.99, 6.99,"carne")) App.obtenerDB().productoDao().save(Producto("Hamburguesa añojo", "AVINATUR", "Hamburguesa añojo 6x90 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/hamburguesaa%C3%B1ojo.jpg?alt=media&token=<PASSWORD>", 6.28, 3.39,"carne")) App.obtenerDB().productoDao().save(Producto("Chuleta aguja de cerdo ", "AVINATUR", "Chuleta aguja de cerdo 1 kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/chuletacerdo.jpg?alt=media&token=<PASSWORD>", 3.99, 3.99,"carne")) App.obtenerDB().productoDao().save(Producto("Solomillo vacuno", "CANALVISO", "solomillo vacuno 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/solomillovacuno.jpg?alt=media&token=<PASSWORD>", 19.95, 9.97,"carne")) App.obtenerDB().productoDao().save(Producto("Jamoncitos de pollo", "AVINATUR", "Jamoncitos de pollo 1 kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/jamoncitospollo.jpg?alt=media&token=<PASSWORD>", 3.45, 3.45,"carne")) App.obtenerDB().productoDao().save(Producto("Yogur bífidus", "DANONE", "Yogur bífidus desnatado edulcorado natural Danone Activia pack de 8 unidades de 120 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yogurbifidus.jpg?alt=media&token=<PASSWORD>", 3.06, 3.06,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yogur con bolitas", "NESTLÉ", "Yogur con bolitas cubiertas de chocolate Mix-in Nestlé Kit Kat pack de 2 unidades de 115 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yogurbolitas.jpg?alt=media&token=<PASSWORD>", 6.52, 1.50,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yogur leche de cabra", "GOSHUA", "Yogur natural de leche de cabra Goshua 125 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yogurcabra.jpg?alt=media&token=<PASSWORD>", 8.76, 2.19,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yogur con fresa", "NESTLÉ", "Yogur con fresa Nestlé La Lechera sin gluten pack de 2 unidades de 125 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yogurfresa.jpg?alt=media&token=<PASSWORD>", 4.56, 1.14,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yogur de fresa con grageas", "NESTLÉ", "Yogur de fresa con grageas de chocolate Nestlé Smarties pack de 2 unidades de 128 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yogurgragea.jpg?alt=media&token=<PASSWORD>", 5.86, 1.50,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yogur agrupado", "DANONE", "Yogur de fresa, macedonia, galleta y fresa-plátano Danone sin gluten pack de 12 unidades", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yogurmacedonia.jpg?alt=media&token=<PASSWORD>", 1.93, 2.78,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yogur de mango", "PASTORET", "Yogur de mango ecológico Pastoret 135 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yogurmango.jpg?alt=media&token=39c4b686-82e7-48ea-9571-a5031cce5626", 10.52, 1.42,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yoyur melocotón", "LALECHERA", "Yogur con melocotón Nestlé La Lechera sin gluten pack de 2 unidades de 125 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yogurmelocoton.jpg?alt=media&token=<PASSWORD>", 4.56, 1.14,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yogur griego ", "DANONE", "Yogur griego con stracciatella Danone Oikos sin gluten pack de 4 unidades de 110 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yoguroikos.jpg?alt=media&token=fbb64724-12ed-483e-aeaf-84dc995ce71d", 4.82, 2.12,"lacteos")) App.obtenerDB().productoDao().save(Producto("Yogur con leche de oveja", "GOSHUA", "Yogur con leche de oveja natural Goshua pack de 2 unidades de 125 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/yoguroveja.jpg?alt=media&token=45c60054-4221-4aa1-95f3-760b8f3a573a", 7.36, 1.84,"lacteos")) App.obtenerDB().productoDao().save(Producto("Aguacate", "FRUTA", "Aguacate de origen nacional 500 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/aguacate.jpg?alt=media&token=<PASSWORD>", 4.00, 2.00,"novedad")) App.obtenerDB().productoDao().save(Producto("Calabacín", "FRUTA", "Calabacín nacional a granel 1 kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/calabacin.jpg?alt=media&token=<PASSWORD>", 1.19, 1.19,"novedad")) App.obtenerDB().productoDao().save(Producto("Cebolla dulce selección", "FUENTE", "Cebolla dulce selección 1 Kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/cebollafuente.jpg?alt=media&token=<PASSWORD>", 1.99, 1.99,"novedad")) App.obtenerDB().productoDao().save(Producto("galletas cookies", "gullon", "galletas de trigo con chocolate 250 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletascookies.jpg?alt=media&token=<PASSWORD>", 0.85, 1.85,"novedad")) App.obtenerDB().productoDao().save(Producto("estrellas de chocolate", "lu principe", "estrella de galletas de chocolate 150 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletasestrella.jpg?alt=media&token=<PASSWORD>", 0.95, 1.18,"novedad")) App.obtenerDB().productoDao().save(Producto("galletas oreo original", "mondelez", "pack galletas oreo 154 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletasoreo.jpg?alt=media&token=<PASSWORD>", 6.80, 2.99,"novedad")) App.obtenerDB().productoDao().save(Producto("galletas de chocolate", "carrefour", "Galletas chocolate con leche Digestive Carrefour 300 g.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletaschocolate.jpg?alt=media&token=aa6773d4-a8c7-4e40-af62-114059812902", 2.67, 0.80,"novedad")) App.obtenerDB().productoDao().save(Producto("Galleta flakes choco", "cuetara", "Galleta flakes choco cuetara 550g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/galletachocoflakes.jpg?alt=media&token=<PASSWORD>", 4.45, 2.45,"novedad")) App.obtenerDB().productoDao().save(Producto("Pan picos", "PANADERA", "Pan de picos la despensa 1 ud", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/panpicos.jpg?alt=media&token=<PASSWORD>", 1.68, 0.57,"pan")) App.obtenerDB().productoDao().save(Producto("Pan de pueblo", "PANADERA", "Pan de pueblo sin aditivos 800 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/panpueblo.jpg?alt=media&token=<PASSWORD>", 1.44, 1.15,"pan")) App.obtenerDB().productoDao().save(Producto("Pan payés", "PANADERA", "Pan payés grande Hecho aquí Carrefour 800 gx", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/panpayes.jpg?alt=media&token=<PASSWORD>", 2.55, 2.55,"pan")) App.obtenerDB().productoDao().save(Producto("Pan antaño", "PANADERA", "Pan de antaño Carrefour 1 ud", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/pananta%C3%B1o.jpg?alt=media&token=<PASSWORD>", 3.62, 1.45,"pan")) App.obtenerDB().productoDao().save(Producto("Pan gallego ", "PANADERA", "Pan gallego de cereales sin lactosa 70 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/pangallego.jpg?alt=media&token=<PASSWORD>", 4.14, 0.29,"pan")) App.obtenerDB().productoDao().save(Producto("Berlina bombón", "PANADERA", "Berlinas bombón 4 ud", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/berlinabombon.jpg?alt=media&token=<PASSWORD>", 5.37, 1.15,"pan")) App.obtenerDB().productoDao().save(Producto("Bretzel de chocolate", "PANADERA", "Bretzel de chocolate y mantequilla 100 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/brezelchocolate.jpg?alt=media&token=<PASSWORD>", 8.50, 0.85,"pan")) App.obtenerDB().productoDao().save(Producto("Magdalena", "PANADERA", "Magdalenas caseras 420 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/magdalena.jpg?alt=media&token=<PASSWORD>", 7.12, 2.99,"pan")) App.obtenerDB().productoDao().save(Producto("Pastel manzana", "PANADERA", "Pastel de manzana 125 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/pastelmanzana.jpg?alt=media&token=<PASSWORD>", 6.80, 0.85,"pan")) App.obtenerDB().productoDao().save(Producto("Bizcocho", "PANADERA", "Bizcocho casero 500 g", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/bizcocho.jpg?alt=media&token=<PASSWORD>", 6.00, 3.00,"pan")) App.obtenerDB().productoDao().save(Producto("Lubina", "PESCADO", "Lubina de ración 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/lubina.jpg?alt=media&token=<PASSWORD>", 6.45, 3.22,"pescado")) App.obtenerDB().productoDao().save(Producto("Dorada", "PESCADO", "Dorada de ración 500 g aprox.", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/dorada.jpg?alt=media&token=94598e24-cfa3-4bed-8c76-8db6a04fbee7", 7.45, 3.75,"pescado")) App.obtenerDB().productoDao().save(Producto("Lomo Atún", "PESCADO", "Lomo de atún 300 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/lomoatun.jpg?alt=media&token=<PASSWORD>", 10.90, 3.27,"pescado")) App.obtenerDB().productoDao().save(Producto("Lenguado", "PESCADO", "Lenguado ración 125 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/lenguado.jpg?alt=media&token=0bc6447b-ac4b-495f-9c75-b52eaab606db", 11.90, 1.49,"pescado")) App.obtenerDB().productoDao().save(Producto("Gallo", "PESCADO", "Gallo ración 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/gallo.jpg?alt=media&token=<PASSWORD>", 7.99, 3.99,"pescado")) App.obtenerDB().productoDao().save(Producto("Boquerones", "PESCADO", "Boquerones 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/boquerones.jpg?alt=media&token=<PASSWORD>", 3.90, 1.95,"pescado")) App.obtenerDB().productoDao().save(Producto("Bacaladilla", "PESCADO'S", "Bacaladilla 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/bacaladilla.jpg?alt=media&token=c96528dd-f177-473a-994b-5b9cbb5c5dc9", 1.95, 0.99,"pescado")) App.obtenerDB().productoDao().save(Producto("Trucha", "PESCADO", "Trucha asalmonada Círculo de Calidad 500 g aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/trucha.jpg?alt=media&token=38b21256-5908-41a9-8e60-980f3b271f07", 6.25, 3.12,"pescado")) App.obtenerDB().productoDao().save(Producto("Salmón", "PESCADO", "Salmón Calidad y Origen Carrefour 1 ud de 3 kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/salmon.jpg?alt=media&token=<PASSWORD>", 8.75, 21.87,"pescado")) App.obtenerDB().productoDao().save(Producto("Pescadilla", "PESCADO", "Pescadilla fina 1 kg aprox", "https://firebasestorage.googleapis.com/v0/b/la-despensa-de-mi-casa.appspot.com/o/pescadilla.jpg?alt=media&token=<PASSWORD>", 5.90, 5.90,"pescado")) } } } } /* private fun insertProductos(): List<Producto> { val productos = mutableListOf<Producto>() }*/ } }
0
Kotlin
0
0
1f555d30c298501215655317578de2c8cc3ea465
33,524
la-despensa-de-mi-casa
MIT License
cli/src/commonMain/me/strangepan/tasks/cli/command/TaskOption.kt
StrangePan
231,948,379
false
{"Kotlin": 385988, "Swift": 54126}
package me.strangepan.tasks.cli.command import omnia.cli.`in`.Parameter import omnia.cli.`in`.StringOption class TaskOption( longName: String, shortName: String, description: String, repeatable: Parameter.Repeatable) : StringOption(longName, shortName, description, repeatable, "task")
0
Kotlin
0
3
8ed915321725fe086a2ab21b8cc68dbd0c14251c
297
tasks
The Unlicense
src/main/kotlin/com/spring/ioc/BeanDefinitionReader.kt
WeipingGan
479,587,223
false
{"Kotlin": 19550}
package com.spring.ioc interface BeanDefinitionReader { fun loadBeanDefinition(location: String) }
0
Kotlin
0
0
f0bc4827a57897515cf4a6dbd1a43a4bd0628c1f
104
tiny-spring-kotlin
Apache License 2.0
ECommerceApp/app/src/main/java/com/android/ecommerceapp/model/enums/MessageType.kt
oguzhansatilmis
746,560,331
false
{"Kotlin": 26141}
package com.android.ecommerceapp.model.enums enum class MessageType { SUCCESS,ERROR,WARNING }
0
Kotlin
0
0
3cf784cf3bab132c3cc892f655cbab93c7506f07
98
E-Commerce-App
MIT License
app/src/main/java/br/com/joaovq/mydailypet/reminder/presentation/viewmodel/ReminderViewModel.kt
joaovq
650,739,082
false
{"Kotlin": 326547, "Ruby": 1076}
package br.com.joaovq.mydailypet.reminder.presentation.viewmodel import androidx.lifecycle.viewModelScope import br.com.joaovq.core.util.intent.ValidateState import br.com.joaovq.mydailypet.reminder.presentation.viewintent.ReminderIntent import br.com.joaovq.mydailypet.reminder.presentation.viewstate.ReminderState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ReminderViewModel @Inject constructor( private val editReminderUseCase: br.com.joaovq.reminder_domain.usecases.EditReminderUseCase, private val getReminderUseCase: br.com.joaovq.reminder_domain.usecases.GetReminderUseCase, private val validateFieldText: br.com.joaovq.reminder_domain.usecases.ValidateFieldText, private val deleteReminderUseCase: br.com.joaovq.reminder_domain.usecases.DeleteReminderUseCase, @br.com.joaovq.core.di.IODispatcher private val dispatcher: CoroutineDispatcher, ) : br.com.joaovq.core_ui.presenter.BaseViewModel<ReminderIntent, ReminderState?>() { override val _state: MutableStateFlow<ReminderState?> = MutableStateFlow(null) val state = _state.asStateFlow() private val _validName: MutableStateFlow<ValidateState> = MutableStateFlow( ValidateState(), ) val validName = _validName.asStateFlow() private val _validDescription: MutableStateFlow<ValidateState> = MutableStateFlow(ValidateState()) val validDescription = _validDescription.asStateFlow() override fun dispatchIntent(intent: ReminderIntent) { when (intent) { is ReminderIntent.EditReminder -> { updateReminder(intent.id, intent.reminder) } is ReminderIntent.DeleteReminder -> deleteReminder(intent.id, intent.reminder) is ReminderIntent.GetReminder -> { getReminderById(intent.id) } } } private fun getReminderById(id: Int) { viewModelScope.launch(dispatcher) { try { getReminderUseCase(id).collectLatest { reminder -> _state.value = ReminderState.Success( br.com.joaovq.core_ui.R.string.message_success, reminder, ) } } catch (e: Exception) { e.printStackTrace() _state.value = ReminderState.Success( br.com.joaovq.core_ui.R.string.message_error, ) } } } private fun updateReminder(id: Int, reminder: br.com.joaovq.reminder_domain.model.Reminder) { viewModelScope.launch(dispatcher) { val stateName = validateFieldText(reminder.name) val stateDescription = validateFieldText(reminder.description) _validName.value = stateName _validDescription.value = stateDescription val stateList = listOf( stateName, stateDescription, ) if (validateForms(stateList)) { try { editReminderUseCase( reminder.copy(id = id), ) _state.value = ReminderState.Success( br.com.joaovq.core_ui.R.string.message_success, ) } catch (e: Exception) { e.printStackTrace() _state.value = ReminderState.Success( br.com.joaovq.core_ui.R.string.message_error, ) } } } } private fun deleteReminder(id: Int, reminder: br.com.joaovq.reminder_domain.model.Reminder) { viewModelScope.launch(dispatcher) { try { deleteReminderUseCase(reminder.copy(id = id)) _state.value = ReminderState.SuccessDelete } catch (e: Exception) { e.printStackTrace() _state.value = ReminderState.Error( exception = e, ) } } } private fun validateForms(states: List<ValidateState>) = states.all { it.isValid } }
1
Kotlin
0
0
ce80c4b481c996fc02c0f22689954edf8154d588
4,382
MyDailyPet
MIT License
app/src/main/java/com/minosai/oneclick/ui/preferences/OneClickPreferencesFragment.kt
devshaaran
175,267,743
true
{"Kotlin": 88321}
package com.minosai.oneclick.ui.preferences import android.app.Activity import android.os.Bundle import androidx.navigation.Navigation.findNavController import androidx.preference.EditTextPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import com.minosai.oneclick.R class OneClickPreferencesFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences_oneclick, rootKey) val displayNamePreference = findPreference<EditTextPreference>("display_name") displayNamePreference.summaryProvider = EditTextPreference.SimpleSummaryProvider.getInstance() val aboutPreference = findPreference<Preference>("about") aboutPreference.setOnPreferenceClickListener { findNavController(activity as Activity, R.id.toolbar_fref_fragment).navigate(R.id.action_settingsFragment_to_aboutFragment) true } } }
0
Kotlin
1
0
e1dd0d5c7afeb3ba2f9b988d6fc88917a48224a6
1,030
One-Click
Apache License 2.0
src/main/kotlin/com/github/borgoat/markovaldo/MarkovChainBuilder.kt
borgoat
487,199,974
false
{"Kotlin": 17320, "Nix": 97}
package com.github.borgoat.markovaldo import kotlinx.atomicfu.AtomicLong import kotlinx.atomicfu.atomic class MarkovChainBuilder(val scanner: Scanner = Scanner(), val order: Int = 3) { private val probs = mutableMapOf<List<Token>, MutableMap<Token, AtomicLong>>() fun add(text: CharSequence) { val tokens = scanner.scanTokens(text) val tokenState = ArrayDeque<Token>() tokens.forEach { if (tokenState.isNotEmpty()) { val innerMap = probs.getOrPut(tokenState.takeLast(order)) { mutableMapOf() } innerMap.getOrPut(it) { atomic(0L) }.incrementAndGet() } tokenState.add(it) } } fun build(): MarkovChain { val edges = probs.mapValues { generateProbabilityDistribution(it.value) } return MarkovChain(order, edges) } private fun generateProbabilityDistribution(map: Map<Token, AtomicLong>): ProbabilityDistribution<Token> { val list = map.map { WeightedItem(it.key, it.value.value.toULong()) } return ProbabilityDistribution(items = list) } }
0
Kotlin
0
0
21a0b723cc7e0d8f002aef885d49900beccc11a8
1,101
markovaldo
MIT License
app/src/main/java/com/jonareas/rentapp/data/dao/HouseDao.kt
soymegh
434,097,806
false
null
package com.jonareas.rentapp.data.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Query import com.jonareas.rentapp.data.model.House @Dao abstract class HouseDao :BaseDao<House> { @Query("SELECT * FROM house") abstract fun getAll(): LiveData<List<House>> }
0
Kotlin
0
0
6fa758b84bece723d05546cebcf65449dcc9aaaf
303
NewRentApp
MIT License
features/addneew/src/main/java/me/pitok/addneew/di/builder/AddNeewsComponentBuilder.kt
hamedsj
287,844,014
false
null
package me.pitok.addneew.di.builder import me.pitok.addneew.di.components.AddNeewsComponent import me.pitok.addneew.di.components.DaggerAddNeewsComponent import me.pitok.androidcore.builder.AndroidCoreComponentBuilder import me.pitok.coroutines.di.builder.CoroutinesComponentBuilder import me.pitok.dependencyinjection.ComponentBuilder import me.pitok.neew.di.NeewsComponentBuilder object AddNeewsComponentBuilder: ComponentBuilder<AddNeewsComponent>(){ override fun initComponent(): AddNeewsComponent { return DaggerAddNeewsComponent .builder() .coroutinesComponent(CoroutinesComponentBuilder.getComponent()) .neewsComponent(NeewsComponentBuilder.getComponent()) .androidCoreComponent(AndroidCoreComponentBuilder.getComponent()) .build() } }
0
Kotlin
3
11
c94f16608febecb17edeb4bd6798dbe6b741d56c
821
GoodNews
Apache License 2.0
z2-boot/src/commonMain/kotlin/hu/simplexion/z2/auth/util/password.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1313600, "CSS": 126893, "Java": 8222, "HTML": 1560, "JavaScript": 975}
package hu.simplexion.z2.auth.util import hu.simplexion.z2.auth.model.PasswordCheck import hu.simplexion.z2.auth.model.SecurityPolicy fun SecurityPolicy.policyErrors(newPassword: String): MutableList<PasswordCheck> { val errors = mutableListOf<PasswordCheck>() if (passwordLengthMinimum != 0 && newPassword.length < passwordHistoryLength) errors += PasswordCheck.Length if (uppercaseMinimum != 0 && newPassword.count { it.isUpperCase() } < uppercaseMinimum) errors += PasswordCheck.Uppercase if (digitMinimum != 0 && newPassword.count { it.isDigit() } < digitMinimum) errors += PasswordCheck.Digit if (specialCharacterMinimum != 0 && newPassword.count { ! it.isLetterOrDigit() } < specialCharacterMinimum) errors += PasswordCheck.Special if (sameCharacterMaximum != 0) { val charMap = mutableMapOf<Char, Int>() for (char in newPassword.toCharArray()) { val count = charMap.getOrPut(char) { 0 } + 1 charMap[char] = count if (count > sameCharacterMaximum) { errors += PasswordCheck.Same break } } } val entropyValue = calculatePasswordEntropy(newPassword) if (entropyValue < minEntropy.min) errors += PasswordCheck.Strength return errors }
0
Kotlin
0
1
8e6ca51d1ff452643ba43f83877285534f5059d6
1,287
z2
Apache License 2.0
data/src/main/java/com/luckhost/data/network/retrofit/ApiService.kt
LuckHost
818,856,648
false
{"Kotlin": 71125}
package com.luckhost.data.network.retrofit import com.luckhost.data.network.dto.AccountAnswerBody import com.luckhost.data.network.dto.AccountParams import com.luckhost.data.network.dto.CreateNoteRequest import com.luckhost.data.network.dto.LoginAnswerBody import com.luckhost.data.network.dto.LoginRequest import com.luckhost.data.network.dto.RefreshToken import com.luckhost.data.network.dto.VerifyTokenAnswer import com.luckhost.data.network.dto.VerifyTokenRequest import com.luckhost.data.storage.models.Note import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.PATCH import retrofit2.http.POST import retrofit2.http.Path interface ApiService { @POST("auth/login") suspend fun login(@Body request: LoginRequest): LoginAnswerBody @POST("auth/register") suspend fun register(@Body request: LoginRequest): AccountAnswerBody @POST("auth/refresh") suspend fun refreshToken(@Body request: RefreshToken) @POST("auth/verify") suspend fun verifyToken(@Body request: VerifyTokenRequest): VerifyTokenAnswer @GET("account") suspend fun getAccountParams(@Header("Authorization") token: String): AccountAnswerBody @PATCH("account") suspend fun changeAccountParams(@Header("Authorization") token: String, @Body request: AccountParams) @GET("account/notes") suspend fun getAllNotes(@Header("Authorization") token: String): Note @POST("account/notes") suspend fun createNewNote(@Body note: CreateNoteRequest): Note // still in development on the server @PATCH("account/notes/{id}") suspend fun changeNoteById(@Header("Authorization") token: String, @Path("id") id: Int, @Body request: Note, ) }
0
Kotlin
0
0
0afba24df78091364cfdc549becd554e884c8dd3
1,814
anynote_android
The Unlicense
app/src/main/java/com/example/job_seeker/domain/usecase/validator/auth/MatchingPasswordValidatorUseCase.kt
Lasha-Ilashvili
783,891,258
false
{"Kotlin": 68837}
package com.example.job_seeker.domain.usecase.validator.auth import com.example.job_seeker.R import javax.inject.Inject class MatchingPasswordValidatorUseCase @Inject constructor() { operator fun invoke(password: String, matchingPassword: String): Pair<Boolean, Int> = (password == matchingPassword) to R.string.matching_password_error }
0
Kotlin
0
0
ad7fef56994ccc367e1ab47305f6f8085bd9d9a6
354
Job_Seeker
The Unlicense
src/main/kotlin/org/crystal/intellij/psi/CrEnum.kt
asedunov
353,165,557
false
null
package org.crystal.intellij.psi import com.intellij.lang.ASTNode import org.crystal.intellij.parser.CR_ENUM_DEFINITION import org.crystal.intellij.stubs.api.CrEnumStub class CrEnum : CrModuleLikeDefinition<CrEnum, CrEnumStub>, CrSuperTypeAware { constructor(stub: CrEnumStub) : super(stub, CR_ENUM_DEFINITION) constructor(node: ASTNode) : super(node) override fun accept(visitor: CrVisitor) = visitor.visitEnum(this) }
15
Kotlin
3
30
5dc69f80df256131bbca575ac0e0f3d05e12965f
435
intellij-crystal-lang
Apache License 2.0
src/serverMain/kotlin/money/tegro/market/server/repository/RoyaltyRepository.kt
TegroTON
491,519,429
false
{"Kotlin": 198445, "HTML": 3914, "JavaScript": 2388, "Dockerfile": 242}
package money.tegro.market.server.repository import io.github.reactivecircus.cache4k.Cache import money.tegro.market.contract.nft.RoyaltyContract import money.tegro.market.server.service.ReferenceBlockService import money.tegro.market.toRaw import mu.KLogging import org.kodein.di.DI import org.kodein.di.DIAware import org.kodein.di.instance import org.ton.block.AddrStd import org.ton.block.MsgAddressInt import org.ton.lite.client.LiteClient import java.util.* class RoyaltyRepository(override val di: DI) : DIAware { private val liteClient: LiteClient by instance() private val approvalRepository: ApprovalRepository by instance() private val cache: Cache<MsgAddressInt, Optional<RoyaltyContract>> by instance() private val referenceBlockService: ReferenceBlockService by instance() suspend fun get(royalty: MsgAddressInt): RoyaltyContract? = cache.get(royalty) { if (approvalRepository.isDisapproved(royalty)) { // Explicitly forbiddenden logger.debug { "address=${royalty.toRaw()} was disapproved" } Optional.empty() } else { logger.debug { "fetching royalty address=${royalty.toRaw()}" } RoyaltyContract.of(royalty as AddrStd, liteClient, referenceBlockService.last()) .let { Optional.ofNullable(it) } } } .orElse(null) companion object : KLogging() }
11
Kotlin
4
0
bd82acf423a4d4e1a00c3eac6347aa7cf18eee5f
1,438
TON-Marketplace-NFT-All
MIT License
spirala1/app/src/main/java/ba/etf/rma23/projekat/MainActivity.kt
afrljak1
668,739,940
false
null
package ba.etf.rma23.projekat import android.content.Context import android.content.IntentFilter import android.content.res.Configuration import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import ba.etf.rma23.projekat.data.repositories.GameReview import ba.etf.rma23.projekat.data.repositories.GameReviewDatabase //import ba.etf.rma23.R import com.google.android.material.bottomnavigation.BottomNavigationView import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainActivity : AppCompatActivity() { private val filter = IntentFilter("android.net.conn.CONNECTIVITY_CHANGE") override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { findViewById<BottomNavigationView>(R.id.bottom_nav).visibility= View.GONE } else { findViewById<BottomNavigationView>(R.id.bottom_nav).visibility = View.VISIBLE } } override fun onCreate(savedInstanceState: Bundle?) { //implementiran navcontroller super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val database = GameReviewDatabase.getDatabase(this) val gameReviewDao = database.gameReviewDao() val gameReview = GameReview(rating = 5, review = "Odlična igra!", igdb_id = 21, online = true, "", "") /* val databaseName = "gamereviews" val context: Context = applicationContext GameReviewDatabase.deleteDatabase(context, databaseName) */ GlobalScope.launch { gameReviewDao.insertReview(gameReview) withContext(Dispatchers.Main) { } } val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = navHostFragment.navController val navView: BottomNavigationView = findViewById(R.id.bottom_nav) navView.setupWithNavController(navController) } }
0
Kotlin
0
1
a512cf5e292f9ace30ed93b723979ec634ca4d11
2,307
RMA
MIT License
component/http-service-impl/src/main/kotlin/mikufan/cx/vtool/component/httpser/impl/api/VocaDbSongByPvApi.kt
CXwudi
748,516,931
false
{"Kotlin": 70236}
package mikufan.cx.vtool.component.httpser.impl.api import com.fasterxml.jackson.databind.JsonNode import mikufan.cx.vtool.shared.model.vocadb.PvService import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.service.annotation.GetExchange import org.springframework.web.service.annotation.HttpExchange /** * Interface for interacting with the VocaDB API. * Provides methods for fetching songs by PV. */ @HttpExchange("/api") interface VocaDbSongByPvApi { /** * Fetches a song by its PV. * @param pvId The ID of the PV. * @param pvService The service of the PV. * @return The song as a JsonNode, or null if not found. */ @GetExchange("/songs/byPv") fun getSongByPv( @RequestParam pvId: String, @RequestParam pvService: PvService, ): JsonNode? }
2
Kotlin
0
0
f196755387d2f50c58d4078cef4b2341ff4e0875
817
vsonglist-toolkit
MIT License
Edu-Cpp/testSrc/com/jetbrains/edu/cpp/CppUtilTest.kt
aspineon
271,016,030
true
{"Kotlin": 2436418, "Java": 626749, "HTML": 131922, "CSS": 12844, "Python": 3994, "JavaScript": 315}
package com.jetbrains.edu.cpp import com.intellij.psi.PsiFileFactory import com.jetbrains.cmake.CMakeLanguage import com.jetbrains.edu.coursecreator.CCTestCase class CppUtilTest : CCTestCase() { private fun findCMakeCommandTestBase(cMakeFile: String, commandName: String, shouldFind: Boolean = true) { val mockPsiFile = PsiFileFactory.getInstance(myFixture.project).createFileFromText(CMakeLanguage.INSTANCE, cMakeFile) val result = mockPsiFile.findCMakeCommand(commandName) if (shouldFind) { kotlin.test.assertNotNull(result) assert(result.name.equals(commandName, true)) } else { assertNull(result) } } fun `test find CMake command - project`() = findCMakeCommandTestBase( """ |#some text | |project(name) | |# some text """.trimMargin(), "project") fun `test find CMake command - ProJEct`() = findCMakeCommandTestBase( """ | #some text | | ProJEct(name) """.trimMargin(), "project" ) fun `test find CMake command - inline call`() = findCMakeCommandTestBase( """ | message("Hi!") project(name) message("By!") """.trimMargin(), "project" ) fun `test find CMake command - no command`() = findCMakeCommandTestBase( """ | #some text | message("empty me )=") | # no text ;) """.trimMargin(), "project", false ) }
0
null
0
0
ccb9d1072da3d214e0c03914b13af36c14f56bce
1,472
educational-plugin
Apache License 2.0
src/Day05/Day05.kt
suttonle24
573,260,518
false
{"Kotlin": 26321}
package Day05 import readInput fun main() { fun getStacks(input: List<String>): ArrayDeque<ArrayDeque<Char>> { val itr = input.listIterator(); var stacks = ArrayDeque<ArrayDeque<Char>>(); for ((i, line) in itr.withIndex()) { val lineArray = line.toCharArray(); var currentStack = 1; for((j, char) in lineArray.withIndex()) { if(j !== 0 && j % 4 == 0) { val thisChar = lineArray[j-3]; var thisStack = ArrayDeque<Char>(); // check to see if this stack has already been created try { thisStack = stacks[currentStack - 1]; } catch (ex : Exception) { // Add the new stack because it doesn't yet exist stacks.addLast(thisStack); } currentStack++; if (lineArray[j-2] == ']') { thisStack.addLast(thisChar); } } else if(j == lineArray.size - 1) { val thisChar = lineArray[j-1]; var thisStack = ArrayDeque<Char>(); // check to see if this stack has already been created try { thisStack = stacks[currentStack - 1]; } catch (ex : Exception) { // Add the new stack because it doesn't yet exist stacks.addLast(thisStack); } if (lineArray[j] == ']') { thisStack.addLast(thisChar); } break; } } if (line.length == 0) { break; } } return stacks; } fun instructionParser(instructionString: String): ArrayDeque<Int> { val instructionArray = instructionString.split(' '); var instructions = ArrayDeque<Int>(); instructions.addLast(Integer.parseInt(instructionArray[1])); // "amount" instructions.addLast(Integer.parseInt(instructionArray[3])); // "from" instructions.addLast(Integer.parseInt(instructionArray[5])); // "to" return instructions; } fun getInstructions(input: List<String>): ArrayDeque<ArrayDeque<Int>> { val itr = input.listIterator(); var instructions = ArrayDeque<ArrayDeque<Int>>(); for ((i, line) in itr.withIndex()) { if(line.contains("move")){ instructions.addLast(instructionParser(line)); } } return instructions; } fun printAnswer(stacks: ArrayDeque<ArrayDeque<Char>>) { var answer = ""; stacks.map { var topChar = it[0]; answer += topChar; } println(answer); } fun part1(input: List<String>): Int { fun processStacks( stacks: ArrayDeque<ArrayDeque<Char>>, instructions: ArrayDeque<ArrayDeque<Int>>) { for ((i, instruction) in instructions.withIndex()) { val move = instruction[0]; val from = instruction[1] - 1; // account for zero-index val to = instruction[2] - 1; // account for zero-index for(i in 1 .. move) { stacks[to].addFirst(stacks[from].removeFirst()); } } } var stacks: ArrayDeque<ArrayDeque<Char>> = getStacks(input); var instructions: ArrayDeque<ArrayDeque<Int>> = getInstructions(input); processStacks(stacks, instructions); printAnswer(stacks); return input.size } fun part2(input: List<String>): Int { fun processStacks( stacks: ArrayDeque<ArrayDeque<Char>>, instructions: ArrayDeque<ArrayDeque<Int>>) { for ((i, instruction) in instructions.withIndex()) { val move = instruction[0]; val from = instruction[1] - 1; // account for zero-index val to = instruction[2] - 1; // account for zero-index var tempStack = ArrayDeque<Char>(); for(i in 1 .. move) { tempStack.addLast(stacks[from].removeFirst()); } stacks[to] = ArrayDeque<Char>(tempStack + stacks[to]); } } var stacks: ArrayDeque<ArrayDeque<Char>> = getStacks(input); var instructions: ArrayDeque<ArrayDeque<Int>> = getInstructions(input); processStacks(stacks, instructions); printAnswer(stacks); return input.size } val input = readInput("Day05/Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
039903c7019413d13368a224fd402625023d6f54
4,836
AoC-2022-Kotlin
Apache License 2.0
Explore/Learn/Introduction to Data Structure/Binary Tree/Binary Tree Level Order Traversal/LevelTraversal.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 290109, "Python": 206027, "Rust": 82753, "C++": 71067, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
/** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun levelOrder(root: TreeNode?): List<List<Int>> { if (root == null) return emptyList() val output = mutableListOf<MutableList<Int>>() val queue = mutableListOf<TreeNode>() queue.add(root) while (queue.size > 0) { val curr = mutableListOf<Int>() for (i in 1..queue.size) { val node = queue.removeAt(0) curr.add(node.`val`) if (node.left != null) { queue.add(node.left) } if (node.right != null) { queue.add(node.right) } } output.add(curr) } return output } }
0
Kotlin
0
1
a96d39cd0217f2e8b4e43b8c0472e30c3bb0ad44
982
leet-code
MIT License
natureremocontroller/src/main/java/com/fishwaffle/natureremo/controller/models/SensorValue.kt
Fishwaffle
160,526,858
false
null
/* * Copyright (c) 2019 FishWaffle. */ package com.fishwaffle.natureremo.controller.models import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.fishwaffle.natureremo.controller.NatureRemo.isIgnoreUnknown import java.io.Serializable /** センサーの値 * @param value 値 * @param created_at 作成日時 * */ @JsonIgnoreProperties(ignoreUnknown = isIgnoreUnknown) data class SensorValue(@JsonProperty("val") var value: Float, var created_at: String?) : Serializable
0
Kotlin
1
0
00424daa4034e4f546146195168215985492149d
527
NatureRemoTaskerPlugin
MIT License
app/src/main/java/com/mahmutalperenunal/flagquiz/model/FlagsModel.kt
mahmutaunal
726,414,523
false
{"Kotlin": 18490}
package com.mahmutalperenunal.flagquiz.model data class FlagsModel( val id: Int, val countryName: String, val flagName: String )
0
Kotlin
0
0
da56c74c186f5c3176b5ec841267f4c05ba29a72
141
FlagQuizGame
MIT License
app/src/main/java/com/example/damian/loginapp/DatabaseHelper.kt
dBanasiak
153,232,821
false
null
package com.example.damian.loginapp import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper class DatabaseHelper(context: Context):SQLiteOpenHelper(context, dbname, factory, version) { override fun onCreate(db: SQLiteDatabase?) { if (db != null) { db.execSQL("create table passwords(id integer primary key autoincrement, password varchar(60))") } } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } fun insertPassword(password:String) { val db: SQLiteDatabase = writableDatabase val values: ContentValues = ContentValues() values.put("password", password) db.insert("passwords", null,values) db.close() } // fun resetPassword() { // val db: SQLiteDatabase = writableDatabase // onCreate(db) // } fun passwordPresent(password: String): Boolean { val db = writableDatabase val query = "select * from passwords where password = $password" val cursor = db.rawQuery(query, null) if(cursor.count <= 0) { cursor.close() return false } cursor.close() return true } companion object { internal val dbname = "userDB" internal val factory = null internal val version = 1 } }
0
Kotlin
0
0
dc74b350acc4ef0fdeaff109f2ffdd612d7e8785
1,549
AndroidNotepad
Apache License 2.0
Kotlin/app/src/main/java/dk/coded/emia/View/MyAppGlideModule.kt
SKrotkih
121,634,559
false
{"Java": 225271, "Kotlin": 211055, "Shell": 1038}
package dk.coded.emia.View import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule @GlideModule class MyAppGlideModule : AppGlideModule()
1
Java
1
2
c277bd010388a8d4f03292e4f2d645c43f9d9dac
181
eMia-Android
MIT License
plugin/src/main/kotlin/com/teamwanari/appcenter/AppCenterPlugin.kt
TeamWanari
152,721,994
false
null
package com.teamwanari.appcenter import org.gradle.api.Plugin import org.gradle.api.Project class AppCenterPlugin : Plugin<Project> { override fun apply(project: Project) { project.extensions.create(APP_CENTER_EXTENSION, AppCenterPluginExtension::class.java) project.tasks.create("appCenterUpload", AppCenterUploadTask::class.java) } }
4
Kotlin
8
15
ba1aa9217edcadcbe5a0f85b932fc7aa6b391c6b
362
appcenter-publish-plugin
MIT License
app/src/main/java/com/mokresh/analyticsdashboard/models/Value.kt
MohammedMokresh
259,672,680
false
null
package com.mokresh.analyticsdashboard.models import com.google.gson.annotations.SerializedName data class Value( @SerializedName("key") val key: String, @SerializedName("value") val value: Int )
0
Kotlin
0
0
b5c81b900ceee655bb4442042d292fd49b3a6912
214
Analytic-Dashboard
Apache License 2.0
kotlin-sdk/kotlin/src/main/kotlin/io/logto/sdk/core/http/HttpGet.kt
logto-io
397,657,445
false
null
package io.logto.sdk.core.http import com.google.gson.JsonSyntaxException import io.logto.sdk.core.exception.ResponseException inline fun <reified T : Any> httpGet( uri: String, headers: Map<String, String>?, completion: HttpCompletion<T>, ) { httpGet(uri, headers) httpRawGet@{ throwable, response -> throwable?.let { completion.onComplete(throwable, null) return@httpRawGet } try { completion.onComplete(null, gson.fromJson(response, T::class.java)) } catch (jsonSyntaxException: JsonSyntaxException) { completion.onComplete( ResponseException(ResponseException.Type.ERROR_RESPONSE, jsonSyntaxException), null, ) } } } inline fun <reified T : Any> httpGet(uri: String, completion: HttpCompletion<T>) = httpGet(uri, null, completion) fun httpGet(uri: String, completion: HttpEmptyCompletion) = makeRequest(uri, null, null, completion) @JvmName("httpRawGet") fun httpGet( uri: String, headers: Map<String, String>?, completion: HttpRawStringCompletion, ) = makeRequest(uri, null, headers, completion) @JvmName("httpRawGet") fun httpGet(uri: String, completion: HttpRawStringCompletion) = httpGet(uri, null, completion)
2
null
6
7
a567276291eabb4a4136bd9b4161474311a9a28e
1,293
kotlin
MIT License
evervault-common/src/test/java/com/evervault/sdk/common/utils/getEnv.kt
evervault
650,073,299
false
{"Kotlin": 322869, "Java": 1240, "Shell": 273}
package com.evervault.sdk.common.utils fun getenv(key: String): String = System.getenv(key)
2
Kotlin
1
4
89c0cb593ec4d43f5c0befd279aee2742329ab95
92
evervault-android
MIT License
backend/src/main/kotlin/com/guysrobot/muxlive/model/Comment.kt
GuysRGithub
576,203,426
false
null
package com.guysrobot.muxlive.model import com.guysrobot.muxlive.dto.CommentDto import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document import java.util.UUID @Document(value = "Comment") data class Comment( @Id private val id: String = UUID.randomUUID().toString(), private val text: String, private val authorId: String, private val likes: Int = 0, private val disLikes: Int = 0 ) { fun toDTO(): CommentDto { return CommentDto(text = text, authorId = authorId) } }
0
Kotlin
0
0
96ce751bc91729ba90883b23fecf4631fdf6e74c
560
MuxLive
Apache License 2.0
app/src/main/java/io/agapps/motchecker/MainActivity.kt
AlexMGreen
484,774,505
false
null
package io.agapps.motchecker import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.ui.Modifier import androidx.core.view.WindowCompat import androidx.navigation.compose.rememberNavController import dagger.hilt.android.AndroidEntryPoint import io.agapps.core.ui.theme.MOTCheckerTheme import io.agapps.motchecker.navigation.AppNavHost @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) setContent { MOTCheckerTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { AppNavHost(navController = rememberNavController()) } } } } }
0
Kotlin
0
0
fc190a765d904f9ff18f0720ba9b7398edc6d29b
1,116
mot-checker
Apache License 2.0
app/src/main/kotlin/pro/respawn/flowmvi/sample/view/NoBaseClassViewModel.kt
respawn-app
477,143,989
false
null
package pro.respawn.flowmvi.sample.view import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.delay import pro.respawn.flowmvi.ActionShareBehavior import pro.respawn.flowmvi.ReducerScope import pro.respawn.flowmvi.launchedStore import pro.respawn.flowmvi.sample.R import pro.respawn.flowmvi.sample.view.BasicActivityAction.ShowSnackbar import pro.respawn.flowmvi.sample.view.BasicActivityIntent.ClickedFab import pro.respawn.flowmvi.sample.view.BasicActivityState.DisplayingContent import pro.respawn.flowmvi.updateState import pro.respawn.flowmvi.sample.view.BasicActivityAction as Action import pro.respawn.flowmvi.sample.view.BasicActivityIntent as Intent import pro.respawn.flowmvi.sample.view.BasicActivityState as State // See also BaseClassViewModel // if you don't want to extend MVIViewModel(), use composition instead class NoBaseClassViewModel : ViewModel() { // implement MVIProvider, or just expose store if you want val store by launchedStore<State, Intent, Action>( scope = viewModelScope, initial = DisplayingContent(0), behavior = ActionShareBehavior.Share(), ) { reduce(it) } private suspend fun ReducerScope<State, Intent, Action>.reduce(intent: Intent) { when (intent) { is ClickedFab -> { ShowSnackbar(R.string.started_processing).send() // Doing long operations will delay intent processing. New intents will NOT result in new coroutines being launched // This means, if we get another intent while delay() is running, it will be processed independently and will start // after this invocation completes. // to solve this, use launchRecovering() (example in BaseClassViewModel.kt) delay(1000) ShowSnackbar(R.string.finished_processing).send() } } updateState<DisplayingContent, _> { copy(counter = counter + 1) } } }
0
Kotlin
0
5
e5e85ab1344eff1e43e53218b86a5f27280f3a9a
2,019
FlowMVI
Apache License 2.0
basick/src/main/java/com/mozhimen/basick/utilk/datatype/UtilKCollections.kt
mozhimen
353,952,154
false
null
package com.mozhimen.basick.utilk.datatype /** * @ClassName UtilKCollections * @Description TODO * @Author mozhimen / <NAME> * @Date 2022/11/27 0:24 * @Version 1.0 */ object UtilKCollections { /** * 将一个Collection的Item中的某个Element组合起来成一个新Collection * @param iterable Iterable<T> * @param predicate Function1<T, I> * @return List<I> */ @JvmStatic fun <T, I> combineElement2List(iterable: Iterable<T>, predicate: (T) -> I): List<I> { return combineElement2List(iterable, ArrayList(), predicate) } /** * 将一个Collection的Item中的某个Element组合起来成一个新Collection * @param iterable Iterable<T> * @param newCollection C * @param predicate Function1<T, I> * @return C */ @JvmStatic fun <T, I, C : MutableCollection<in I>> combineElement2List(iterable: Iterable<T>, newCollection: C, predicate: (T) -> I): C { for (element in iterable) if (!newCollection.contains(predicate(element))) newCollection.add(predicate(element)) return newCollection } /** * map2String * @param map Map<*, *> * @return String */ @JvmStatic fun map2String(map: Map<*, *>): String { if (map.isEmpty()) return "map is empty" val stringBuilder = StringBuilder() stringBuilder.append("\n").append("{").append("\n").append("\t") val iterator: Iterator<*> = map.entries.iterator() while (iterator.hasNext()) { val (key, value) = iterator.next() as Map.Entry<*, *> stringBuilder.append(String.format("\t%1\$s : %2\$s", key.toString(), value.toString())) stringBuilder.append("\n") } stringBuilder.append("}") return stringBuilder.toString() } /** * list2String * @param list List<*> * @return String */ @JvmStatic fun list2String(list: List<*>): String { if (list.isEmpty()) return "list is empty" val stringBuilder = StringBuilder() stringBuilder.append("\n").append("{\n ") for (obj in list) { if (obj is List<*>) stringBuilder.append(list2String(obj)) else stringBuilder.append(obj.toString()).append(" ,\n ") } stringBuilder.append("}") return stringBuilder.toString() } }
0
Kotlin
0
2
5077b41303c564a4f7acd8e7df03133ebf1e04f2
2,299
SwiftKit
Apache License 2.0
JBossLoggingElasticsearchLogger/src/main/kotlin/net/codinux/log/elasticsearch/errorhandler/JBossLoggingErrorHandler.kt
codinux-gmbh
399,611,177
false
null
package net.codinux.log.elasticsearch.errorhandler import org.jboss.logmanager.Level import org.jboss.logmanager.Logger open class JBossLoggingErrorHandler(loggerName: String) : ErrorHandler { constructor() : this(JBossLoggingErrorHandler::class.java) constructor(loggerClass: Class<*>) : this(loggerClass.name) protected open val log = Logger.getLogger(loggerName) override fun logError(message: String, e: Throwable?) { log.log(Level.ERROR, message, e) } override fun logInfo(message: String) { log.info(message) } }
0
Kotlin
0
0
6bf928523a7c0e788a27b42e89e712c46029e2c5
573
ElasticsearchLogger
Apache License 2.0
app/src/main/java/com/agenda/up/DatePickerFragment.kt
Araujo-Alisson
596,383,449
false
null
package com.agenda.up import android.app.DatePickerDialog import android.app.Dialog import android.os.Bundle import android.widget.DatePicker import androidx.fragment.app.DialogFragment import java.util.Calendar class DatePickerFragment(val callback: (year:String,month:String,dayofmonth:String) -> Unit): DialogFragment(), DatePickerDialog.OnDateSetListener { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val c: Calendar = Calendar.getInstance() val ano = c.get(Calendar.YEAR) val mes = c.get(Calendar.MONDAY) val dia = c.get(Calendar.DAY_OF_MONTH) return DatePickerDialog(requireContext(),this,ano,mes,dia) } override fun onDateSet(p0: DatePicker?, ano: Int, mes: Int, dia: Int) { val anoString = ano.toString() val mesString = (mes + 1).toString() val diaString = dia.toString() callback(anoString,mesString, diaString) } }
1
Kotlin
0
0
1a74801e3a82982d024fb85defa664396ade2eb9
940
Up
Apache License 2.0
src/main/kotlin/info/cepheus/axon/infrastructure/transaction/jta/JtaTransactionManager.kt
cepheus-info
428,205,383
false
null
package info.cepheus.axon.infrastructure.transaction.jta import org.axonframework.common.transaction.Transaction import org.axonframework.common.transaction.TransactionManager import java.util.logging.Logger import javax.transaction.Status import javax.transaction.SystemException import javax.transaction.TransactionSynchronizationRegistry import javax.transaction.UserTransaction /** * Provides the [TransactionManager] for Axon. * * @author JohT */ class JtaTransactionManager protected constructor(private val userTransaction: UserTransaction?, private val transactionRegistry: TransactionSynchronizationRegistry?) : TransactionManager { /** * {@inheritDoc} */ override fun startTransaction(): Transaction { if (isTransactionynchronizationRegistryAvailable) { return ParticipatingRegisteredTransaction.usingRegistry(transactionRegistry!!) } return if (isUserTransactionAvailable) { if (isInTransaction) { ParticipatingUserTransaction.usingUserTransaction(userTransaction!!) } else LeadingUserTransaction.usingUserTransaction(userTransaction!!) } else NoTransaction.INSTANCE } private val isUserTransactionAvailable: Boolean get() = userTransaction != null private val isInTransaction: Boolean get() = try { userTransaction!!.status != Status.STATUS_NO_TRANSACTION } catch (e: SystemException) { LOGGER.info("UserTransaction not availalbe: " + e.message) false } catch (e: IllegalStateException) { LOGGER.info("UserTransaction not availalbe: " + e.message) false } catch (e: UnsupportedOperationException) { LOGGER.info("UserTransaction not availalbe: " + e.message) false } private val isTransactionynchronizationRegistryAvailable: Boolean get() = transactionRegistry != null override fun toString(): String { return ("JtaTransactionManager [userTransaction=" + userTransaction + ", transactionRegistry=" + transactionRegistry + "]") } companion object { private val LOGGER = Logger.getLogger(JtaTransactionManager::class.java.getName()) fun using(user: UserTransaction?, registry: TransactionSynchronizationRegistry?): TransactionManager { return JtaTransactionManager(user, registry) } } }
0
Kotlin
0
0
64decafdee0c0eb5ad8617366d7b6e241aa7d5d0
2,488
cepheus_axon_extension
MIT License
app/src/main/java/com/mhss/app/mynews/ui/MainActivity.kt
mhss1
435,140,771
false
{"Kotlin": 47296}
package com.mhss.app.mynews.ui import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatDelegate import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.mhss.app.mynews.R import androidx.preference.PreferenceManager import androidx.work.* import com.mhss.app.mynews.data.wokers.RefreshArticlesWorker import com.mhss.app.mynews.databinding.ActivityMainBinding import com.mhss.app.mynews.util.Constants import dagger.hilt.android.AndroidEntryPoint import java.util.concurrent.TimeUnit @AndroidEntryPoint class MainActivity : AppCompatActivity() , SharedPreferences.OnSharedPreferenceChangeListener{ private lateinit var binding: ActivityMainBinding private lateinit var preferenceManager: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) preferenceManager = PreferenceManager.getDefaultSharedPreferences(this) setTheme(preferenceManager.getString("theme", "")) val navHost = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment val navController = navHost.navController binding.bottomNavigationView.setupWithNavController(navController) navController.addOnDestinationChangedListener { _, destination, _ -> when (destination.id) { R.id.mainFragment, R.id.discoverFragment, R.id.settingsFragment -> showBottomNav() else -> hideBottomNav() } } setupRefreshWork(ExistingPeriodicWorkPolicy.KEEP) } private fun hideBottomNav() { binding.bottomNavigationView.visibility = View.GONE } private fun showBottomNav() { binding.bottomNavigationView.visibility = View.VISIBLE } private fun setupRefreshWork(policy: ExistingPeriodicWorkPolicy){ val inputData = workDataOf("country" to preferenceManager.getString("country", "us")) val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val refreshRequest = PeriodicWorkRequestBuilder<RefreshArticlesWorker>(12, TimeUnit.HOURS) .setInputData(inputData) .setConstraints(constraints) .build() WorkManager.getInstance(this).enqueueUniquePeriodicWork( Constants.REFRESH_WORKER_NAME, policy, refreshRequest) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { println("called and key is $key") if (key == "theme") setTheme(sharedPreferences?.getString(key, "Dark")) else if(key == "country") setupRefreshWork(ExistingPeriodicWorkPolicy.REPLACE) } private fun setTheme(theme: String?){ when (theme) { "Dark" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) "Light" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) } } override fun onResume() { super.onResume() preferenceManager.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() preferenceManager.unregisterOnSharedPreferenceChangeListener(this) } }
0
Kotlin
2
5
d467ae36adc2f1ef8225052f7d25512f7465f0ab
3,736
MyNews
Apache License 2.0
android-common/src/main/java/com/cren90/android/common/inject/modules/ResourceModule.kt
dfyz8-g
527,884,279
false
{"Kotlin": 154083}
package com.cren90.android.common.inject.modules import com.cren90.android.common.providers.resources.* import com.cren90.android.common.providers.system.AndroidSystemProvider import com.cren90.android.common.providers.system.DateFormatProvider import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Suppress("unused") @Module(includes = [CoreModule::class]) @InstallIn(SingletonComponent::class) abstract class ResourceModule { @Binds @Singleton abstract fun provideColorProvider(provider: AndroidResourceProvider): ColorProvider @Binds @Singleton abstract fun provideDrawableProvider(provider: AndroidResourceProvider): DrawableProvider @Binds @Singleton abstract fun provideDimenProvider(provider: AndroidResourceProvider): DimenProvider @Binds @Singleton abstract fun provideIntegerProvider(provider: AndroidResourceProvider): IntegerProvider @Binds @Singleton abstract fun provideLayoutManagerProvider(provider: AndroidResourceProvider): LayoutManagerProvider @Binds @Singleton abstract fun provideStringProvider(provider: AndroidResourceProvider): StringProvider @Binds @Singleton abstract fun provideBooleanProvider(provider: AndroidResourceProvider): BooleanProvider @Binds @Singleton abstract fun provideDateProvider(provider: AndroidSystemProvider): DateFormatProvider }
0
null
0
0
80aee8afce6ef6cf87fb71c1c5c4c88f0f9fe162
1,482
android-core-libs
Apache License 2.0
src/main/kotlin/watch/gnag/website/routes/SiteRouter.kt
btkelly
78,223,124
false
{"Kotlin": 20000, "HTML": 10377, "CSS": 4700, "JavaScript": 1332}
package watch.gnag.website.routes import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.reactive.function.server.router import watch.gnag.website.handlers.SiteHandler @Configuration class SiteRouter(private val siteHandler: SiteHandler) { @Bean fun siteRoutes() = router { GET("/", siteHandler::index) GET("/configHelper", siteHandler::configHelper) } }
0
Kotlin
0
2
2eb9fe41c442329891ef2f4d24d879c523c27b86
473
gnag-website
Apache License 2.0
scientist4k-core/src/main/kotlin/com/github/squirrelgrip/scientist4k/core/model/sample/Sample.kt
SquirrelGrip
247,915,957
true
{"Kotlin": 234965, "JavaScript": 2164, "HTML": 1653, "CSS": 930}
package com.github.squirrelgrip.scientist4k.core.model.sample import com.fasterxml.jackson.annotation.JsonProperty import com.github.squirrelgrip.scientist4k.core.model.ExperimentOption import java.time.Instant import java.util.* data class Sample( @JsonProperty("id") val id: String, @JsonProperty("sampleScore") val sampleScore: Int, @JsonProperty("runOptions") val runOptions: EnumSet<ExperimentOption> = ExperimentOption.DEFAULT ) { @JsonProperty("startTime") val startTime: Instant = Instant.now() private val _notes: MutableMap<String, Any> = mutableMapOf() val notes: Map<String, Any> @JsonProperty("notes") get() = _notes.toMap() fun addNote(noteKey: String, note: Any) { _notes[noteKey] = note } fun exceedsThreshold(sampleThreshold: Int): Boolean { return sampleScore >= sampleThreshold } }
0
Kotlin
0
2
5c88eb2bf0275c1c8ad139a78c9a1222f499ce4e
895
Scientist4K
MIT License
document/document-rpc-bootstrap/src/test/kotlin/org/myddd/vertx/document/bootstrap/TestGuiceModule.kt
mydddOrg
394,499,704
false
null
package org.myddd.vertx.document.bootstrap import io.vertx.core.Vertx import org.myddd.vertx.distributed.application.DistributedIdApplication import org.myddd.vertx.document.application.DocumentApplication import org.myddd.vertx.document.domain.DistributeID import org.myddd.vertx.document.domain.DocumentRepository import org.myddd.vertx.document.infra.DocumentRepositoryHibernate import org.myddd.vertx.document.infra.GrpcDistributeID import org.myddd.vertx.grpc.GrpcInstanceProvider import org.myddd.vertx.grpc.ServiceDiscoveryGrpcInstanceProvider class TestGuiceModule(vertx: Vertx): AbstractWebModule(vertx) { override fun configure() { super.configure() bind(DocumentRepository::class.java).to(DocumentRepositoryHibernate::class.java) bind(DistributeID::class.java).to(GrpcDistributeID::class.java) bind(DocumentApplication::class.java) //test need bind(DistributedIdApplication::class.java) } }
0
Kotlin
0
4
42557972bbecc6f2a15a324e2deffdf254182ff0
961
myddd-vertx-micro-scaffold
MIT License
tests/src/test/kotlin/io/github/mirkofelice/plugins/AbstractTest.kt
mirko-felice
634,173,598
false
null
package io.github.mirkofelice.plugins import io.github.mirkofelice.api.CheckerType import io.github.mirkofelice.api.Testkit import io.kotest.core.spec.style.StringSpec abstract class AbstractTest(body: StringSpec.() -> Unit) : StringSpec(body) private const val projectName = "tests" internal fun Testkit.runTestsInsideProject( testFolder: String, checkerType: CheckerType = CheckerType.KOTLIN, forwardOutput: Boolean = false ) { test(projectName, DEFAULT_TEST_FOLDER.replace("main", "test") + testFolder, checkerType, forwardOutput) }
2
Kotlin
0
0
813ad27aa566971e5c509dd547bbd3594db6c113
556
gradle-plugin-testkit
MIT License
app/src/main/java/com/noble/news/model/entity/Category.kt
NobleXL
509,033,346
false
{"Kotlin": 125083}
package com.noble.news.model.entity /** * @author 小寒 * @version 1.0 * @date 2022/7/1 11:11 */ /** * 分类 * * @property title */ data class Category( val title: String, val id: String ) /** * Category Response * * @property data List<Category> * @constructor */ data class CategoryResponse(var data: List<Category>) : BaseResponse() { }
0
Kotlin
0
0
41cd4f60d71ff5696dd4035826698bf7ff3a6a44
358
News
Apache License 2.0
src/main/kotlin/uk/gov/justice/hmpps/architecture/model/HMPPSDomainEvents.kt
ministryofjustice
272,753,130
false
{"Kotlin": 197063, "Shell": 1167}
package uk.gov.justice.hmpps.architecture.model import com.structurizr.model.Model import com.structurizr.model.SoftwareSystem import com.structurizr.view.ViewSet import uk.gov.justice.hmpps.architecture.HMPPSSoftwareSystem import uk.gov.justice.hmpps.architecture.annotations.Tags class HMPPSDomainEvents private constructor() { companion object : HMPPSSoftwareSystem { lateinit var topic: SoftwareSystem override fun defineModelEntities(model: Model) { topic = model.addSoftwareSystem( "hmpps-domain-events", "Domain-wide Event Topic implemented with AWS Simple Notification Service" ) .apply { Tags.SOFTWARE_AS_A_SERVICE.addTo(this) Tags.TOPIC.addTo(this) } } override fun defineRelationships() {} override fun defineViews(views: ViewSet) {} } }
5
Kotlin
3
17
fa0cdff7ca4679a9a5d223b0213a8899d955c057
842
hmpps-architecture-as-code
MIT License
clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/util.kt
perek
156,259,199
false
null
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.clouddriver.saga import com.fasterxml.jackson.annotation.JsonTypeName /** * Get the name of the provided [command] instance. * */ internal fun getStepCommandName(command: SagaCommand): String = getStepCommandName(command.javaClass) /** * Get the name of the provided [commandClass]. * * TODO(rz): Do we want our own annotation instead of relying on [JsonTypeName]? */ internal fun getStepCommandName(commandClass: Class<SagaCommand>): String = commandClass.getAnnotation(JsonTypeName::class.java)?.value ?: commandClass.simpleName
1
null
1
1
a6122b1121f70abf3936c9589bbbcff716124e02
1,171
clouddriver
Apache License 2.0
layout-ui/src/main/java/com/android/tools/property/panel/impl/support/ImageFocusListener.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.property.panel.impl.support import com.android.tools.property.panel.impl.model.BasePropertyEditorModel import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import java.awt.event.FocusListener import javax.swing.JComponent /** * [FocusListener] that can be used in controls using models derived from [BasePropertyEditorModel]. * * Here: scroll the component into with when focus is gained. */ class ImageFocusListener(private val component: JComponent) : FocusAdapter() { override fun focusGained(event: FocusEvent) { component.scrollRectToVisible(component.bounds) } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,245
android
Apache License 2.0
common/src/main/java/com/yuriikonovalov/common/application/usecases/datasources/DeleteTransferSource.kt
yuriikonovalov
563,974,428
false
{"Kotlin": 872022}
package com.yuriikonovalov.common.application.usecases.datasources import com.yuriikonovalov.common.application.entities.Transfer import kotlinx.coroutines.flow.Flow interface DeleteTransferSource { suspend fun deleteTransfer(transferId: Long) fun getTransfer(transferId: Long): Flow<Transfer?> }
0
Kotlin
0
0
8063508f836512fc8f8a0ba18f794bb895ee2449
306
budgethub
MIT License
src/main/java/io/outfoxx/typescriptpoet/DecoratorSpec.kt
outfoxx
121,184,058
false
null
/* * Copyright 2017 Outfox, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.outfoxx.typescriptpoet /** A generated function or class decorator declaration. */ class DecoratorSpec internal constructor( builder: Builder ) : Taggable(builder.tags.toImmutableMap()) { val name = builder.name val parameters = builder.parameters val factory = builder.factory internal fun emit(codeWriter: CodeWriter) { codeWriter.emitCode(CodeBlock.of("@%Q", name)) if (parameters.isNotEmpty()) { codeWriter.emitCode("(") parameters.forEachIndexed { index, (first, second) -> if (index > 0 && index < parameters.size) { codeWriter.emitCode(",%W") } if (first != null) { codeWriter.emit("/* $first */ ") } codeWriter.emitCode(second) } codeWriter.emitCode(")") } else if (factory ?: parameters.isNotEmpty()) { codeWriter.emit("()") } } override fun toString() = buildCodeString { emit(this) } fun toBuilder(): Builder { val builder = Builder(name) builder.parameters += parameters builder.factory = factory return builder } class Builder internal constructor( val name: SymbolSpec ) : Taggable.Builder<Builder>() { internal val parameters = mutableListOf<Pair<String?, CodeBlock>>() internal var factory: Boolean? = null fun asFactory() = apply { this.factory = true } fun addParameter(name: String? = null, format: String, vararg args: Any?) = apply { parameters += name to CodeBlock.of(format, *args) } fun addParameter(name: String? = null, codeBlock: CodeBlock) = apply { parameters += name to codeBlock } fun build(): DecoratorSpec { return DecoratorSpec(this) } } companion object { @JvmStatic fun builder(name: String): Builder { return Builder(SymbolSpec.from(name)) } @JvmStatic fun builder(name: SymbolSpec): Builder { return Builder(name) } } }
0
Kotlin
2
36
8036c156e3f1d6a4542c45a469a5dad9b7923abc
2,540
typescriptpoet
Apache License 2.0
composeApp/src/commonMain/kotlin/util/extension/Flow.kt
KamilSucharski
783,215,410
false
{"Kotlin": 39364, "Swift": 594}
package util.extension import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map inline fun <T> Flow<T?>.filterNotNull(): Flow<T> { return filter { it != null } .map { it!! } }
0
Kotlin
0
0
5c958505d3f770a2afd27c3ee4597d168faecfac
241
i_am_steve_kmm
Apache License 2.0
src/main/kotlin/decima/Intellijdbc.kt
decimalib
757,054,145
false
{"Kotlin": 5849}
package decima import java.sql.CallableStatement import java.sql.Connection import java.sql.PreparedStatement import java.sql.ResultSet import java.sql.Statement /** * Ensures the [transaction] block received is executed as a single unit of work. Atomic transactions * ensure that either all the SQL statements within the transaction are executed successfully and * the changes are committed to the database, or none of them are executed and the changes are rolled back. * This guarantees that the data is left in a consistent state, even if an error or failure occurs * during the transaction. * @param transaction a set of SQL statements. * @return the result of the [transaction] block. */ inline fun <T> Connection.setAtomicTransaction(crossinline transaction: () -> T): T = runCatching { autoCommit = false val result = transaction() commit() result }.onFailure { rollback() }.also { autoCommit = true close() }.getOrThrow() /** * Sets all parameters of an **SQL statement** by the received declaration order * without the need to indicate the parameter type. * * Example of usage: * ``` * val query = "SELECT * from student as s where s.name = ? and s.age = ?" * val statement = connection.setPreparedStatement(query, "John", 20) * // which equals to this JDBC code: * val statement = connection.prepareStatement(query) * statement.setString(1, "John") * statement.setInt(2, 20) * ``` * @param query SQL query as a string. * @param parameters parameters to set. * @return a complete [PreparedStatement]. * */ fun <T : Any?> Connection.setPreparedStatement( query: String, vararg parameters: T ): PreparedStatement { val statement = prepareStatement(query) setStatementParameters(parameters, statement) return statement } /** * Prepares a **stored procedure** or **function** with all parameters set by the received declaration order, * without the need to indicate the parameter type. * * Example of usage: * ``` * val statement = connection.setCallableStatement( * "getStudent", studentId, classId * ) * // which equals to this JDBC code: * val statement = connection.prepareCall("{ call getStudent(?, ?) }") * statement.setObject(1, studentId) * statement.setObject(2, classId) * ``` * @param routineName name of the stored procedure or function. * @param parameters parameters to set. * @return a complete [CallableStatement]. * @see [setCallableStatement], [executeAndClose] */ fun <T : Any?> Connection.setCallableStatement( routineName: String, vararg parameters: T ): CallableStatement { // (?, ..., ?) val questionMarks = parameters.joinToString(", ", "(", ")") { "?" } // Example: { call getStudent(?, ?) } val sqlString = "{ call $routineName $questionMarks }" val statement = prepareCall(sqlString) setStatementParameters(parameters, statement) return statement } /** * Sets all parameters of an SQL statement by the received declaration order without the need to indicate the parameter type. * @param parameters parameters to set. * @param statement a complete [PreparedStatement]. */ private fun <T : Any?> setStatementParameters(parameters: Array<out T>, statement: PreparedStatement) { parameters.forEachIndexed { index, param -> statement.setObject(index + 1, param) } } /** * Closes a [PreparedStatement] immediately after executing an update statement. * @see , [executeQueryAndClose]. */ fun PreparedStatement.executeUpdateAndClose(): Int = executeUpdate().also { use {} } /** * Closes a [PreparedStatement] and the created [ResultSet] immediately after executing the [block] function. * This method is not recommended if the [ResultSet] is to be kept after, * for that use the regular [PreparedStatement.executeQuery] and close the [PreparedStatement] manually after. * * Example of usage: * ``` * preparedstatement.executeQueryAndClose { rs -> * while(rs.next()) { * println(rs.getString("name")) * } * } * ``` * @param block function to handle the [ResultSet]. * @return the result of the [block] function. * @see , [executeUpdateAndClose] */ inline fun <reified T> PreparedStatement.executeQueryAndClose(crossinline block: (ResultSet) -> T): T = use { stmt -> stmt.executeQuery().use { rs -> block(rs) } } /** * Closes a [CallableStatement] immediately after executing a procedure or function that is * defined in the database. * * Example of usage: * ``` * val statement = connection.setCallableStatement( * "getStudent", studentId, classId * ) * val result = statement.executeAndClose() * ``` * @return true if the first result is a [ResultSet] object; false if it is an update count or there are no results. * @see [setCallableStatement] */ fun CallableStatement.executeAndClose(): Boolean = execute().also { use {} } /** * Closes a [Statement] immediately after executing the received script that may contain one or more SQL-completed statements. * * Example of usage: * ``` * val script = """ * CREATE TABLE student ( * id INT PRIMARY KEY, * name VARCHAR(255) NOT NULL * ); * INSERT INTO student (id, name) VALUES (1, 'John'); * INSERT INTO student (id, name) VALUES (2, 'Mary'); * INSERT INTO student (id, name) VALUES (3, 'Paul'); * """.trimIndent() * val result = connection.createStatement().executeScriptAndClose(script) * ``` * @param script SQL script as a string. * @return true if the first result is a [ResultSet] object; false if it is an update count or there are no results. * @see [executeAndClose], [executeQueryAndClose], [executeUpdateAndClose] */ fun Statement.executeScriptAndClose(script: String): Boolean = execute(script).also { use {} }
0
Kotlin
0
0
f8d521005b6c8d864bdf02f69d3019e6b3d4fc17
5,849
intellijdbc
MIT License