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
core/src/debug/kotlin/ru/mobileup/template/core/debug_tools/RealDebugTools.kt
MobileUpLLC
485,284,340
false
null
package ru.mobileup.template.core.debug_tools import android.content.Context import com.chuckerteam.chucker.api.ChuckerCollector import com.chuckerteam.chucker.api.ChuckerInterceptor import com.chuckerteam.chucker.api.RetentionManager import me.aartikov.replica.client.ReplicaClient import me.aartikov.replica.devtools.ReplicaDevTools import me.nemiron.hyperion.networkemulation.NetworkEmulatorInterceptor import okhttp3.Interceptor import ru.mobileup.template.core.error_handling.ServerException import java.io.IOException class RealDebugTools( context: Context, replicaClient: ReplicaClient ) : DebugTools { private val networkEmulatorInterceptor = NetworkEmulatorInterceptor( context, failureExceptionProvider = { IOException(ServerException(cause = null)) } ) private val replicaDebugTools = ReplicaDevTools(replicaClient, context) private val chuckerCollector = ChuckerCollector( context = context, showNotification = false, retentionPeriod = RetentionManager.Period.ONE_HOUR ) private val chuckerInterceptor = ChuckerInterceptor .Builder(context) .collector(chuckerCollector) .build() override val interceptors: List<Interceptor> = listOf( networkEmulatorInterceptor, chuckerInterceptor ) override fun launch() { replicaDebugTools.launch() } @Suppress("DEPRECATION") override fun collectNetworkError(exception: Exception) { chuckerCollector.onError("DebugTools", exception) } }
1
null
2
8
75c3350979d4d2a92d8b685194b80ef3747201e9
1,547
MobileUp-Android-Template
MIT License
app/src/main/java/jp/osdn/gokigen/thetaview/brainwave/BrainwaveSummaryData.kt
MRSa
747,974,948
false
{"Kotlin": 321183}
package jp.osdn.gokigen.thetaview.brainwave import kotlin.experimental.and @ExperimentalUnsignedTypes class BrainwaveSummaryData { // 3-byte value : delta (0.5 - 2.75Hz), theta (3.5 - 6.75Hz), low-alpha (7.5 - 9.25Hz), high-alpha (10 - 11.75Hz), low-beta (13 - 16.75Hz), high-beta (18 - 29.75Hz), low-gamma (31 - 39.75Hz), and mid-gamma (41 - 49.75Hz). private var delta : ULong = 0u private var theta : ULong = 0u private var lowAlpha : ULong = 0u private var highAlpha : ULong = 0u private var lowBeta : ULong= 0u private var highBeta : ULong = 0u private var lowGamma : ULong = 0u private var midGamma : ULong = 0u private var poorSignal = 0 private var attention = 0 private var mediation = 0 fun update(packet: ByteArray): Boolean { var ret = false try { val length = packet.size if (length < 36) { return ret } poorSignal = packet[4].toInt() delta = ((packet[7].toUByte() and 0xff.toUByte()).toULong() * 65536u + (packet[8].toUByte() and 0xff.toUByte()).toULong() * 256u + (packet[9].toUByte() and 0xff.toUByte()).toULong()) theta = ((packet[10].toUByte() and 0xff.toUByte()).toULong() * 65536u + (packet[11].toUByte() and 0xff.toUByte()).toULong() * 256u + (packet[12].toUByte() and 0xff.toUByte()).toULong()) lowAlpha = ((packet[13].toUByte() and 0xff.toUByte()).toULong() * 65536u + (packet[14].toUByte() and 0xff.toUByte()).toULong() * 256u + (packet[15].toUByte() and 0xff.toUByte()).toULong()) highAlpha = ((packet[16].toUByte() and 0xff.toUByte()).toULong() * 65536u + (packet[17].toUByte() and 0xff.toUByte()).toULong() * 256u + (packet[18].toUByte() and 0xff.toUByte()).toULong()) lowBeta = ((packet[19].toUByte() and 0xff.toUByte()).toULong() * 65536u + (packet[20].toUByte() and 0xff.toUByte()).toULong() * 256u + (packet[21].toUByte() and 0xff.toUByte()).toULong()) highBeta = ((packet[22].toUByte() and 0xff.toUByte()).toULong() * 65536u + (packet[23].toUByte() and 0xff.toUByte()).toULong() * 256u + (packet[24].toUByte() and 0xff.toUByte()).toULong()) lowGamma = ((packet[25].toUByte() and 0xff.toUByte()).toULong() * 65536u + (packet[26].toUByte() and 0xff.toUByte()).toULong() * 256u + (packet[27].toUByte() and 0xff.toUByte()).toULong()) midGamma = ((packet[28].toUByte() and 0xff.toUByte()).toULong() * 65536u + (packet[29].toUByte() and 0xff.toUByte()).toULong() * 256u + (packet[30].toUByte() and 0xff.toUByte()).toULong()) attention = ((packet[32] and 0xff.toByte()).toInt()) mediation = ((packet[34] and 0xff.toByte()).toInt()) ret = true } catch (e: Exception) { e.printStackTrace() } return ret } fun isSkinConnected(): Boolean { return poorSignal != 200 } fun getPoorSignal(): Int { return poorSignal } fun getDelta(): Long { return delta.toLong() } fun getTheta(): Long { return theta.toLong() } fun getLowAlpha(): Long { return lowAlpha.toLong() } fun getHighAlpha(): Long { return highAlpha.toLong() } fun getLowBeta(): Long { return lowBeta.toLong() } fun getHighBeta(): Long { return highBeta.toLong() } fun getLowGamma(): Long { return lowGamma.toLong() } fun getMidGamma(): Long { return midGamma.toLong() } fun getAttention(): Int { return attention } fun getMediation(): Int { return mediation } }
0
Kotlin
0
0
a4ecad82ba955919de2bb16e18da2a2b6c2c7cfc
3,740
ThetaView
Apache License 2.0
liveview-android/src/androidTest/java/com/dockyard/liveviewtest/liveview/runner/LiveViewTestRunner.kt
liveview-native
459,214,950
false
{"Kotlin": 891540, "Elixir": 5480}
package com.dockyard.liveviewtest.liveview.runner import android.os.Bundle import com.karumi.shot.ShotTestRunner class LiveViewTestRunner : ShotTestRunner() { override fun onCreate(args: Bundle) { // This parameter must be passed via command line in order to generate the screenshot // reference images. This is done using `android.testInstrumentationRunnerArguments`. // ./gradlew executeScreenshotTests -Precord -Pandroid.testInstrumentationRunnerArguments.record=true isRecording = args.containsKey("record") super.onCreate(args) } companion object { var isRecording: Boolean = false private set } }
56
Kotlin
2
67
240f7357a7c4df2623268c39b6a93a57e2f49b96
682
liveview-client-jetpack
MIT License
app/src/main/java/io/homeassistant/companion/android/util/icondialog/IconDialogFragment.kt
home-assistant
179,008,173
false
{"Kotlin": 2639109, "Ruby": 3180}
package io.homeassistant.companion.android.util.icondialog import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.DialogFragment import com.mikepenz.iconics.typeface.IIcon import io.homeassistant.companion.android.util.compose.HomeAssistantAppTheme import kotlin.math.min class IconDialogFragment(callback: (IIcon) -> Unit) : DialogFragment() { companion object { const val TAG = "IconDialogFragment" } private val onSelect = callback override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return ComposeView(requireContext()).also { it.clipToPadding = true } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (view as ComposeView).setContent { HomeAssistantAppTheme { IconDialogContent( onSelect = onSelect ) } } } override fun onResume() { super.onResume() val params = dialog?.window?.attributes ?: return params.width = min( (resources.displayMetrics.widthPixels * 0.9).toInt(), TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 480f, resources.displayMetrics).toInt() ) params.height = min( (resources.displayMetrics.heightPixels * 0.9).toInt(), TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 500f, resources.displayMetrics).toInt() ) dialog?.window?.attributes = params } }
190
Kotlin
636
2,296
11367c2193316cec9579791b38006fab094293de
1,800
android
Apache License 2.0
src/test/kotlin/no/nav/syfo/LegeerklaringMapperTest.kt
navikt
192,538,863
false
{"Kotlin": 177545, "Dockerfile": 278}
package no.nav.syfo import no.nav.helse.eiFellesformat.XMLEIFellesformat import no.nav.syfo.model.toLegeerklaring import no.nav.syfo.util.extractLegeerklaering import no.nav.syfo.util.fellesformatUnmarshaller import no.nav.syfo.util.getFileAsString import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.io.StringReader import java.time.LocalDateTime import java.util.UUID internal class LegeerklaringMapperTest { @Test internal fun `Tester mapping fra fellesformat til Legeerklaring format`() { val felleformatLe = fellesformatUnmarshaller.unmarshal( StringReader(getFileAsString("src/test/resources/fellesformat_le.xml")), ) as XMLEIFellesformat val legeerklaringxml = extractLegeerklaering(felleformatLe) val legeerklaering = legeerklaringxml.toLegeerklaring( legeerklaringId = UUID.randomUUID().toString(), fellesformat = felleformatLe, signaturDato = LocalDateTime.of(2017, 11, 5, 0, 0, 0), behandlerNavn = "Navn Navnesen", ) assertEquals(false, legeerklaering.arbeidsvurderingVedSykefravaer) assertEquals(true, legeerklaering.arbeidsavklaringspenger) assertEquals(false, legeerklaering.yrkesrettetAttforing) assertEquals(false, legeerklaering.uforepensjon) assertEquals("Kari", legeerklaering.pasient.fornavn) assertEquals("Setesdal", legeerklaering.pasient.mellomnavn) assertEquals("Nordmann", legeerklaering.pasient.etternavn) assertEquals("12349812345", legeerklaering.pasient.fnr) assertEquals("NAV Sagene", legeerklaering.pasient.navKontor) assertEquals("Hjemmeaddresse 2", legeerklaering.pasient.adresse) assertEquals(1234, legeerklaering.pasient.postnummer) assertEquals("Dokumentforfalsker", legeerklaering.pasient.yrke) assertEquals("NAV IKT", legeerklaering.pasient.arbeidsgiver.navn) assertEquals("Oppdiktet gate 32", legeerklaering.pasient.arbeidsgiver.adresse) assertEquals(1234, legeerklaering.pasient.arbeidsgiver.postnummer) assertEquals("Ukjentby", legeerklaering.pasient.arbeidsgiver.poststed) assertEquals("K74", legeerklaering.sykdomsopplysninger.hoveddiagnose?.kode) assertEquals("82-01-Le", legeerklaering.sykdomsopplysninger.hoveddiagnose?.tekst) assertEquals("U99", legeerklaering.sykdomsopplysninger.bidiagnose.firstOrNull()?.kode) assertEquals("Nyresvikt kronisk", legeerklaering.sykdomsopplysninger.bidiagnose.firstOrNull()?.tekst) assertEquals(LocalDateTime.of(2017, 11, 5, 0, 0, 0), legeerklaering.sykdomsopplysninger.arbeidsuforFra) assertEquals("vethellerikkehvasomskalhit", legeerklaering.sykdomsopplysninger.sykdomshistorie) assertEquals("vetikkehvasomskalhit", legeerklaering.sykdomsopplysninger.statusPresens) assertEquals(false, legeerklaering.sykdomsopplysninger.borNavKontoretVurdereOmDetErEnYrkesskade) assertEquals(LocalDateTime.of(2017, 10, 14, 0, 0, 0), legeerklaering.sykdomsopplysninger.yrkesSkadeDato) assertEquals("Dra p� fisketur med en guide", legeerklaering.plan?.utredning?.tekst) assertEquals(LocalDateTime.of(2017, 11, 5, 0, 0, 0), legeerklaering.plan?.utredning?.dato) assertEquals(3, legeerklaering.plan?.utredning?.antattVentetIUker) assertEquals("Dra p� fisketur med en guide", legeerklaering.plan?.behandling?.tekst) assertEquals(LocalDateTime.of(2017, 11, 5, 0, 0, 0), legeerklaering.plan?.behandling?.dato) assertEquals(3, legeerklaering.plan?.behandling?.antattVentetIUker) assertEquals("Burde dra ut p� fisketur for � slappe av", legeerklaering.plan?.utredningsplan) assertEquals("Trenger � slappe av med litt fisking", legeerklaering.plan?.behandlingsplan) assertEquals("Trenger ikke ny vurdering", legeerklaering.plan?.vurderingAvTidligerePlan) assertEquals("Den gamle planen fungerte ikke", legeerklaering.plan?.narSporreOmNyeLegeopplysninger) assertEquals("Trenger � slappe av med litt fisking", legeerklaering.plan?.videreBehandlingIkkeAktueltGrunn) assertEquals(true, legeerklaering.forslagTilTiltak.behov) assertEquals(false, legeerklaering.forslagTilTiltak.kjopAvHelsetjenester) assertEquals(false, legeerklaering.forslagTilTiltak.reisetilskudd) assertEquals(false, legeerklaering.forslagTilTiltak.aktivSykmelding) assertEquals(false, legeerklaering.forslagTilTiltak.hjelpemidlerArbeidsplassen) assertEquals(false, legeerklaering.forslagTilTiltak.arbeidsavklaringspenger) assertEquals(false, legeerklaering.forslagTilTiltak.friskmeldingTilArbeidsformidling) assertEquals("Den gamle planen fungerte ikke", legeerklaering.forslagTilTiltak.andreTiltak) assertEquals("", legeerklaering.forslagTilTiltak.naermereOpplysninger) assertEquals("Trenger lettere arbeid", legeerklaering.forslagTilTiltak.tekst) assertEquals("Kan ikke lengre danse", legeerklaering.funksjonsOgArbeidsevne.vurderingFunksjonsevne) assertEquals(false, legeerklaering.funksjonsOgArbeidsevne.inntektsgivendeArbeid) assertEquals(false, legeerklaering.funksjonsOgArbeidsevne.hjemmearbeidende) assertEquals(false, legeerklaering.funksjonsOgArbeidsevne.student) assertEquals("", legeerklaering.funksjonsOgArbeidsevne.annetArbeid) assertEquals("Ingen dans", legeerklaering.funksjonsOgArbeidsevne.kravTilArbeid) assertEquals(false, legeerklaering.funksjonsOgArbeidsevne.kanGjenopptaTidligereArbeid) assertEquals(true, legeerklaering.funksjonsOgArbeidsevne.kanGjenopptaTidligereArbeidNa) assertEquals(false, legeerklaering.funksjonsOgArbeidsevne.kanGjenopptaTidligereArbeidEtterBehandling) assertEquals("Ikke tunge l�ft", legeerklaering.funksjonsOgArbeidsevne.kanIkkeGjenopptaNaverendeArbeid) assertEquals(true, legeerklaering.funksjonsOgArbeidsevne.kanTaAnnetArbeid) assertEquals(true, legeerklaering.funksjonsOgArbeidsevne.kanTaAnnetArbeidNa) assertEquals(false, legeerklaering.funksjonsOgArbeidsevne.kanTaAnnetArbeidEtterBehandling) assertEquals("Ingen dans", legeerklaering.funksjonsOgArbeidsevne.kanIkkeTaAnnetArbeid) assertEquals(false, legeerklaering.prognose.vilForbedreArbeidsevne) assertEquals("Ikke varig.", legeerklaering.prognose.anslattVarighetSykdom) assertEquals("Ikke varig.", legeerklaering.prognose.anslattVarighetFunksjonsnedsetting) assertEquals("Ikke varig.", legeerklaering.prognose.anslattVarighetNedsattArbeidsevne) assertEquals("Sikker.", legeerklaering.arsakssammenheng) assertEquals("Andre opplysninger", legeerklaering.andreOpplysninger) assertEquals(false, legeerklaering.kontakt.skalKontakteBehandlendeLege) assertEquals(false, legeerklaering.kontakt.skalKontakteArbeidsgiver) assertEquals(false, legeerklaering.kontakt.skalKontakteBasisgruppe) assertEquals("DPS", legeerklaering.kontakt.kontakteAnnenInstans) assertEquals(true, legeerklaering.kontakt.onskesKopiAvVedtak) assertEquals("", legeerklaering.pasientenBurdeIkkeVite) assertEquals(true, legeerklaering.tilbakeholdInnhold) assertEquals(LocalDateTime.of(2017, 11, 5, 0, 0, 0), legeerklaering.signatur.dato) assertEquals("LEGESEN TEST LEGE", legeerklaering.signatur.navn) assertEquals("Oppdiktet gate 203", legeerklaering.signatur.adresse) assertEquals("1234", legeerklaering.signatur.postnummer) assertEquals("Oslo", legeerklaering.signatur.poststed) assertEquals("", legeerklaering.signatur.signatur) assertEquals("98765432", legeerklaering.signatur.tlfNummer) assertEquals(LocalDateTime.of(2017, 11, 5, 0, 0, 0), legeerklaering.signaturDato) } @Test internal fun `Tester mapping fra fellesformat til Legeerklaring format hvis navn mangler`() { val felleformatLe = fellesformatUnmarshaller.unmarshal( StringReader(getFileAsString("src/test/resources/fellesformat_le_utennavn.xml")), ) as XMLEIFellesformat val legeerklaringxml = extractLegeerklaering(felleformatLe) val legeerklaering = legeerklaringxml.toLegeerklaring( legeerklaringId = UUID.randomUUID().toString(), fellesformat = felleformatLe, signaturDato = LocalDateTime.of(2017, 11, 5, 0, 0, 0), behandlerNavn = "Navn Navnesen", ) assertEquals("Navn Navnesen", legeerklaering.signatur.navn) } }
1
Kotlin
1
0
c64088d0e5c5ee9db77e3342d50c0b52b3c250b1
8,607
pale-2
MIT License
features/categories/src/main/java/com/aliumujib/artic/categories/ui/CategoryListFragment.kt
aliumujib
210,103,091
false
{"Kotlin": 448725}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliumujib.artic.categories.ui import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.aliumujib.artic.views.models.CategoryUIModel import com.aliumujib.artic.articles.models.CategoryUIModelMapper import com.aliumujib.artic.categories.databinding.FragmentCategoriesBinding import com.aliumujib.artic.categories.di.CategoryListModule import com.aliumujib.artic.categories.di.DaggerCategoryListComponent import com.aliumujib.artic.categories.presentation.CategoryListIntent import com.aliumujib.artic.categories.presentation.CategoryListViewModel import com.aliumujib.artic.categories.presentation.CategoryListViewState import com.aliumujib.artic.categories.ui.adapter.CategoryClickListener import com.aliumujib.artic.categories.ui.adapter.CategoryListAdapter import com.aliumujib.artic.mobile_ui.ApplicationClass import com.aliumujib.artic.views.ext.* import com.aliumujib.artic.views.mvi.MVIView import com.aliumujib.artic.views.recyclerview.ListSpacingItemDecorator import com.aliumujib.artic.views.cleanup.autoDispose import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.ConflatedBroadcastChannel import kotlinx.coroutines.flow.* import javax.inject.Inject @ExperimentalCoroutinesApi class CategoryListFragment : Fragment(), MVIView<CategoryListIntent, CategoryListViewState>, CategoryClickListener { @Inject lateinit var categoryListAdapter: CategoryListAdapter @Inject lateinit var viewModel: CategoryListViewModel @Inject lateinit var categoryUIModelMapper: CategoryUIModelMapper private var _binding: FragmentCategoriesBinding by autoDispose() private val binding get() = _binding private val _loadInitialIntent = ConflatedBroadcastChannel<CategoryListIntent>() private val loadInitialIntent = _loadInitialIntent.asFlow().take(1) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentCategoriesBinding.inflate(inflater, container, false) return _binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.processIntent(intents()) } override fun onAttach(context: Context) { super.onAttach(context) initDependencyInjection() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initializeViews() nonNullObserve(viewModel.states(), ::render) _loadInitialIntent.offer(CategoryListIntent.LoadCategoriesListIntent) } private fun initializeViews() { val linearLayoutManager = LinearLayoutManager(requireContext()) binding.categories.apply { removeAllDecorations() addItemDecoration( ListSpacingItemDecorator( context.dpToPx(32), context.dpToPx(16) ) ) layoutManager = linearLayoutManager adapter = categoryListAdapter } } private fun initDependencyInjection() { DaggerCategoryListComponent .builder() .coreComponent(ApplicationClass.coreComponent(requireContext())) .categoryListModule(CategoryListModule(this)) .build() .inject(this) } override fun render(state: CategoryListViewState) { when { !state.isLoading && (state.error == null) -> presentSuccessState( categoryUIModelMapper.mapToUIList( state.data ) ) state.error != null -> presentErrorState( state.error ) state.isLoading -> presentLoadingState() } } private fun presentSuccessState(data: List<CategoryUIModel>) { binding.loading.hide() if (data.isNotEmpty()) { binding.emptyView.hide() binding.errorView.hide() binding.categories.show() } else { binding.emptyView.show() binding.errorView.hide() binding.categories.hide() } categoryListAdapter.submitList(data) } private fun presentErrorState(error: Throwable) { binding.emptyView.hide() binding.loading.hide() binding.categories.hide() binding.errorView.show() error.message?.let { binding.errorView.setErrorViewText(it) } Toast.makeText(context, error.message, Toast.LENGTH_LONG).show() } private fun presentLoadingState() { binding.loading.show() binding.categories.hide() binding.emptyView.hide() binding.errorView.hide() } override fun intents(): Flow<CategoryListIntent> { return loadInitialIntent.filter { categoryListAdapter.isEmpty() } } override fun onCategoryClick(categoryUIModel: CategoryUIModel) { findNavController().navigate(CategoryListFragmentDirections.actionCategoryListFragmentToCategoryDetailsFragment(categoryUIModel)) } override fun onDestroy() { _binding.categories.adapter = null super.onDestroy() } }
0
Kotlin
6
47
ad986536632f532d0d24aa3847bdef33ab7a5d16
6,148
Artic
Apache License 2.0
14_HATEOAS/rest-with-spring-boot-and-kotlin-erudio/src/main/kotlin/br/com/erudio/controller/PersonController.kt
leandrocgsi
471,486,043
false
null
package br.com.application.controller import br.com.application.data.vo.v1.PersonVO import br.com.application.data.vo.v2.PersonVO as PersonVOV2 import br.com.application.services.PersonService import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/person") class PersonController { @Autowired private lateinit var service: PersonService @GetMapping(produces = [MediaType.APPLICATION_JSON_VALUE]) fun findAll(): List<PersonVO> { return service.findAll() } @GetMapping(value = ["/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE]) fun findById(@PathVariable(value = "id") id : Long ) : PersonVO { return service.findById(id) } @PostMapping(consumes = [MediaType.APPLICATION_JSON_VALUE], produces = [MediaType.APPLICATION_JSON_VALUE]) fun create(@RequestBody person: PersonVO ) : PersonVO { return service.create(person) } @PostMapping(value = ["/v2"], consumes = [MediaType.APPLICATION_JSON_VALUE], produces = [MediaType.APPLICATION_JSON_VALUE]) fun createV2(@RequestBody person: PersonVOV2) : PersonVOV2 { return service.createV2(person) } @PutMapping(consumes = [MediaType.APPLICATION_JSON_VALUE], produces = [MediaType.APPLICATION_JSON_VALUE]) fun update(@RequestBody person: PersonVO ) : PersonVO { return service.create(person) } @DeleteMapping(value = ["/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE]) fun delete(@PathVariable(value = "id") id : Long ) : ResponseEntity<*>{ service.delete(id) return ResponseEntity.noContent().build<Any>() } }
0
null
2
21
26f2f450b93bb647f64b12d3b67cac3642913fb9
2,366
rest-with-spring-boot-and-kotlin-erudio
Apache License 2.0
app/src/main/java/com/google/firebase/example/fireeats/util/FirestoreInitializer.kt
firebase
105,568,229
false
null
package com.google.firebase.example.fireeats.util import android.content.Context import androidx.startup.Initializer import com.google.firebase.example.fireeats.BuildConfig import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class FirestoreInitializer : Initializer<FirebaseFirestore> { // The host '10.0.2.2' is a special IP address to let the // Android emulator connect to 'localhost'. private val FIRESTORE_EMULATOR_HOST = "10.0.2.2" private val FIRESTORE_EMULATOR_PORT = 8081 override fun create(context: Context): FirebaseFirestore { val firestore = Firebase.firestore // Use emulators only in debug builds if (BuildConfig.DEBUG) { firestore.useEmulator(FIRESTORE_EMULATOR_HOST, FIRESTORE_EMULATOR_PORT) } return firestore } // No dependencies on other libraries override fun dependencies(): MutableList<Class<out Initializer<*>>> = mutableListOf() }
10
null
156
262
6a833afd107d3bece1436bb2cec6ec1588c6c3a5
1,039
friendlyeats-android
Apache License 2.0
app/src/main/java/com/niyaj/popos/features/reports/presentation/ReportsEvent.kt
skniyajali
579,613,644
false
null
package com.niyaj.popos.features.reports.presentation sealed class ReportsEvent { data class SelectDate(val date: String) : ReportsEvent() data class OnChangeOrderType(val orderType: String = "") : ReportsEvent() data class OnChangeCategoryOrderType(val orderType: String = "") : ReportsEvent() data class OnSelectCategory(val categoryName: String) : ReportsEvent() object PrintReport : ReportsEvent() object RefreshReport : ReportsEvent() object GenerateReport : ReportsEvent() }
4
Kotlin
0
1
43bffb61e5634c11887f32eb08448f09fa95d51e
518
POS-Application
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/Blur.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.Blur: ImageVector get() { if (_blur != null) { return _blur!! } _blur = fluentIcon(name = "Regular.Blur") { fluentPath { moveTo(3.0f, 12.0f) arcToRelative(9.0f, 9.0f, 0.0f, false, true, 13.98f, -7.5f) lineTo(12.0f, 4.5f) arcToRelative(7.5f, 7.5f, 0.0f, true, false, 0.0f, 15.0f) lineTo(12.0f, 18.0f) horizontalLineToRelative(6.7f) arcTo(9.0f, 9.0f, 0.0f, false, true, 3.0f, 12.0f) close() moveTo(18.23f, 5.5f) lineTo(12.0f, 5.5f) lineTo(12.0f, 7.0f) horizontalLineToRelative(7.48f) arcToRelative(9.05f, 9.05f, 0.0f, false, false, -1.25f, -1.5f) close() moveTo(12.0f, 8.0f) horizontalLineToRelative(8.06f) curveToRelative(0.24f, 0.48f, 0.44f, 0.98f, 0.59f, 1.5f) lineTo(12.0f, 9.5f) lineTo(12.0f, 8.0f) close() moveTo(20.88f, 10.5f) lineTo(12.0f, 10.5f) lineTo(12.0f, 12.0f) horizontalLineToRelative(9.0f) curveToRelative(0.0f, -0.51f, -0.04f, -1.01f, -0.12f, -1.5f) close() moveTo(12.0f, 13.0f) horizontalLineToRelative(8.95f) arcToRelative(8.96f, 8.96f, 0.0f, false, true, -0.3f, 1.5f) lineTo(12.0f, 14.5f) lineTo(12.0f, 13.0f) close() moveTo(20.3f, 15.5f) lineTo(12.0f, 15.5f) lineTo(12.0f, 17.0f) horizontalLineToRelative(7.48f) curveToRelative(0.32f, -0.47f, 0.6f, -0.97f, 0.81f, -1.5f) close() } } return _blur!! } private var _blur: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,201
compose-fluent-ui
Apache License 2.0
src/test/kotlin/com/example/realworld/unit/handler/ExceptionHandlerTest.kt
brunohenriquepj
367,784,702
false
null
package com.example.realworld.unit.handler import com.example.realworld.dto.ErrorResponse import com.example.realworld.handler.ExceptionHandler import com.example.realworld.util.builder.common.StringBuilder import io.kotest.matchers.collections.shouldContainAll import org.junit.jupiter.api.Test class ExceptionHandlerTest { private val handler = ExceptionHandler() @Test fun `handle should return default message`() { // arrange val message = StringBuilder().build() val exception = Exception(message) val expected = ErrorResponse.of("An internal error occurred!") // act val actual = handler.handle(exception) // assert actual.errors.body.toList() shouldContainAll expected.errors.body.toList() } }
7
Kotlin
0
2
a3da13258606924f185b249545955e142f783b92
786
spring-boot-kotlin-realworld
MIT License
src/test/kotlin/com/example/realworld/unit/handler/ExceptionHandlerTest.kt
brunohenriquepj
367,784,702
false
null
package com.example.realworld.unit.handler import com.example.realworld.dto.ErrorResponse import com.example.realworld.handler.ExceptionHandler import com.example.realworld.util.builder.common.StringBuilder import io.kotest.matchers.collections.shouldContainAll import org.junit.jupiter.api.Test class ExceptionHandlerTest { private val handler = ExceptionHandler() @Test fun `handle should return default message`() { // arrange val message = StringBuilder().build() val exception = Exception(message) val expected = ErrorResponse.of("An internal error occurred!") // act val actual = handler.handle(exception) // assert actual.errors.body.toList() shouldContainAll expected.errors.body.toList() } }
7
Kotlin
0
2
a3da13258606924f185b249545955e142f783b92
786
spring-boot-kotlin-realworld
MIT License
app/src/main/java/fr/free/nrw/commons/contributions/WikipediaInstructionsDialogFragment.kt
misaochan
43,427,766
false
null
package fr.free.nrw.commons.contributions import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.fragment.app.DialogFragment import fr.free.nrw.commons.R import kotlinx.android.synthetic.main.dialog_add_to_wikipedia_instructions.* /** * Dialog fragment for displaying instructions for editing wikipedia */ class WikipediaInstructionsDialogFragment : DialogFragment() { var contribution: Contribution? = null var callback: Callback? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.dialog_add_to_wikipedia_instructions, container) } override fun onViewCreated( view: View, savedInstanceState: Bundle? ) { super.onViewCreated(view, savedInstanceState) contribution = arguments!!.getParcelable(ARG_CONTRIBUTION) tv_wikicode.setText(contribution?.wikiCode) instructions_cancel.setOnClickListener { dismiss() } instructions_confirm.setOnClickListener { callback?.onConfirmClicked(contribution, checkbox_copy_wikicode.isChecked) } dialog!!.window.setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN ) } /** * Callback for handling confirm button clicked */ interface Callback { fun onConfirmClicked(contribution: Contribution?, copyWikicode: Boolean) } companion object { val ARG_CONTRIBUTION = "contribution" @JvmStatic fun newInstance(contribution: Contribution): WikipediaInstructionsDialogFragment { val frag = WikipediaInstructionsDialogFragment() val args = Bundle() args.putParcelable(ARG_CONTRIBUTION, contribution) frag.arguments = args return frag } } }
1
null
1
3
3c6c05016ed1750c110a4670229126bc8ef789a9
2,020
apps-android-commons
Apache License 2.0
plugins/amazonq/chat/jetbrains-community/src/software/aws/toolkits/jetbrains/services/amazonq/webview/Browser.kt
aws
91,485,909
false
null
// Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.amazonq.webview import com.intellij.openapi.Disposable import com.intellij.ui.jcef.JBCefJSQuery import org.cef.CefApp import software.aws.toolkits.jetbrains.services.amazonq.util.createBrowser import java.util.function.Function typealias MessageReceiver = Function<String, JBCefJSQuery.Response> /* Displays the web view for the Amazon Q tool window */ class Browser(parent: Disposable) { val jcefBrowser = createBrowser(parent) val receiveMessageQuery = JBCefJSQuery.create(jcefBrowser) fun init(isGumbyAvailable: Boolean) { // register the scheme handler to route http://mynah/ URIs to the resources/assets directory on classpath CefApp.getInstance() .registerSchemeHandlerFactory( "http", "mynah", AssetResourceHandler.AssetResourceHandlerFactory(), ) loadWebView(isGumbyAvailable) } fun component() = jcefBrowser.component fun post(message: String) = jcefBrowser .cefBrowser .executeJavaScript("window.postMessage(JSON.stringify($message))", jcefBrowser.cefBrowser.url, 0) // Load the chat web app into the jcefBrowser private fun loadWebView(isGumbyAvailable: Boolean) { // setup empty state. The message request handlers use this for storing state // that's persistent between page loads. jcefBrowser.setProperty("state", "") // load the web app jcefBrowser.loadHTML(getWebviewHTML(isGumbyAvailable)) } /** * Generate index.html for the web view * @return HTML source */ private fun getWebviewHTML(isGumbyAvailable: Boolean): String { val postMessageToJavaJsCode = receiveMessageQuery.inject("JSON.stringify(message)") val jsScripts = """ <script type="text/javascript" src="$WEB_SCRIPT_URI" defer onload="init()"></script> <script type="text/javascript"> const init = () => { mynahUI.createMynahUI( { postMessage: message => { $postMessageToJavaJsCode } }, false, // change to true to enable weaverbird $isGumbyAvailable, // whether /transform is available ); } </script> """.trimIndent() return """ <!DOCTYPE html> <html> <head> <title>AWS Q</title> $jsScripts </head> <body> </body> </html> """.trimIndent() } companion object { private const val WEB_SCRIPT_URI = "http://mynah/js/mynah-ui.js" } }
519
null
220
757
a81caf64a293b59056cef3f8a6f1c977be46937e
3,014
aws-toolkit-jetbrains
Apache License 2.0
src/test/kotlin/eu/pretix/jsonlogic/JsonLogicTests.kt
pretix
440,528,125
true
{"Kotlin": 24536}
package eu.pretix.jsonlogic import com.fasterxml.jackson.databind.ObjectMapper import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test /** * Runs official tests from jsonlogic.com */ private const val testUrl = "http://jsonlogic.com/tests.json" class JsonLogicTests { private fun readResource(filename: String): String { return JsonLogicTests::class.java.classLoader.getResource(filename).readText() } @Test fun officialTests() { val tests = ObjectMapper().readValue(readResource("tests.json"), List::class.java) val l = JsonLogic() for (t in tests) { when (t) { is List<*> -> { System.out.println(t.toString() + " - " + ObjectMapper().writeValueAsString(t[0])) val result = l.apply( ObjectMapper().writeValueAsString(t[0]), ObjectMapper().writeValueAsString(t[1]) ) var expected = t[2] if (result is Double && expected is Int) { expected = expected.toString().toDouble() } if (result is List<*> && result.firstOrNull() is Double && expected is List<*> && expected.firstOrNull() is Int) { expected = expected.map { it.toString().toDouble() } } if (result is List<*> && result.isEmpty() && expected is List<*> && expected.isEmpty()) { expected = result } assertEquals( expected, result ) } is String -> { } else -> { assert(false) } } } } @Test fun simple() { val jsonLogic = JsonLogic() val result = jsonLogic.apply("{\"==\":[1,1]}") assertEquals(true, result) } @Test fun compoundString() { val jsonLogic = JsonLogic() val result = jsonLogic.apply( "{\"and\" : [" + " { \">\" : [3,1] }," + " { \"<\" : [1,3] }" + "] }" ) assertEquals(true, result) } @Test fun compound() { val jsonLogic = JsonLogic() val logic = mapOf( "and" to listOf( mapOf(">" to listOf(3, 1)), mapOf("<" to listOf(1, 3)) ) ) val result = jsonLogic.apply(logic) assertEquals(true, result) } @Test fun dataString() { val jsonLogic = JsonLogic() val result = jsonLogic.apply( "{ \"var\" : [\"a\"] }", // Rule "{ \"a\" : 1.2, \"b\" : 2 }" // Data ) assertEquals(1.2, result) } @Test fun data() { val jsonLogic = JsonLogic() val logic = mapOf("var" to listOf("a")) val data = mapOf("a" to 1, "b" to 2) val result = jsonLogic.apply(logic, data) assertEquals(1, result) } @Test fun array() { val jsonLogic = JsonLogic() val result = jsonLogic.apply( "{\"var\" : 1 }", // Rule "[ \"apple\", \"banana\", \"carrot\" ]" // Data ) assertEquals("banana", result) } @Test fun customOperation1() { fun plus(list: List<Any?>?, @Suppress("UNUSED_PARAMETER") data: Any?): Any? { try { if (list != null && list.size > 1) return list[0].toString().toDouble() + list[1].toString().toDouble() } catch (e: Exception) { } return null } val jsonLogic = JsonLogic() jsonLogic.addOperation("plus", ::plus) val result = jsonLogic.apply("{\"plus\":[23, 19]}", null) assertEquals(42.0, result) } @Test fun customOperation2() { val jsonLogic = JsonLogic() jsonLogic.addOperation("sqrt") { l, _ -> try { if (l != null && l.size > 0) Math.sqrt(l[0].toString().toDouble()) else null } catch (e: Exception) { null } } val result = jsonLogic.apply("{\"sqrt\":\"9\"}") assertEquals(3.0, result) } @Test fun customOperation3() { val jsonLogic = JsonLogic() jsonLogic.addOperation("Math.random") { _, _ -> Math.random() } val result = jsonLogic.apply("{\"Math.random\":[]}", "{}") assert(result as Double in 0.0..1.0) } @Test fun customOperation4() { val jsonLogic = JsonLogic() jsonLogic.addOperation("pow") { l, _ -> try { if (l != null && l.size > 1) Math.pow(l[0].toString().toDouble(), l[1].toString().toDouble()) else null } catch (e: Exception) { null } } val result = jsonLogic.apply(mapOf("pow" to listOf(3, 2))) assertEquals(9.0, result) } fun unknownCustomOperation() { Assertions.assertThrows(NotImplementedError::class.java) { val jsonLogic = JsonLogic() jsonLogic.apply(mapOf("hello" to listOf(1, 2, 3)), safe = false) } } @Test fun unknownCustomOperationSafe() { val jsonLogic = JsonLogic() val result = jsonLogic.apply(mapOf("hello" to listOf(1, 2, 3)), safe = true) assertEquals(false, result) } @Test fun stringComparisonBug() { val jsonLogic = JsonLogic() val logic = mapOf("===" to listOf(mapOf("var" to listOf("a")), "two")) val data = mapOf("a" to "one") val result = jsonLogic.apply(logic, data) assertEquals(false, result) } @Test fun nullTest() { val jsonLogic = JsonLogic() val result = jsonLogic.apply(null) assertEquals(null, result) } @Test fun log() { val jsonLogic = JsonLogic() val logic = mapOf("log" to "apple") val result = jsonLogic.apply(logic) assertEquals("apple", result) } @Test fun truthyNull() { assertEquals(false, null.truthy) } @Test fun truthyString() { assertEquals(true, "hello".truthy) } @Test fun truthyArray() { assertEquals(true, arrayOf(1).truthy) } @Test fun truthyEmptyArray() { assertEquals(false, emptyArray<Int>().truthy) } @Test fun truthyOther() { class Other() assertEquals(true, Other().truthy) } @Test fun doubleListOther() { class Other() val jsonLogic = JsonLogic() val logic = mapOf("+" to listOf(1, 2, Other())) val result = jsonLogic.apply(logic) assertEquals(3.0, result) } @Test fun doubleValueException() { val jsonLogic = JsonLogic() val logic = mapOf("+" to listOf(1, 2, "hello")) val result = jsonLogic.apply(logic) assertEquals(3.0, result) } @Test fun inOther() { val jsonLogic = JsonLogic() val logic = mapOf("in" to 1) val result = jsonLogic.apply(logic) assertEquals(false, result) } @Test fun minusMore() { val jsonLogic = JsonLogic() val logic = mapOf("-" to listOf(2, 1, 1)) val result = jsonLogic.apply(logic) assertEquals(1.0, result) } @Test fun minusNone() { val jsonLogic = JsonLogic() val logic = mapOf("-" to listOf<Int>()) val result = jsonLogic.apply(logic) assertEquals(null, result) } @Test fun compareOther() { class Other() val jsonLogic = JsonLogic() val logic = mapOf("==" to listOf(1, Other())) val result = jsonLogic.apply(logic) assertEquals(false, result) } @Test fun compareAnyComparables() { class Other() : Comparable<Other> { override fun compareTo(other: Other) = 0 } val jsonLogic = JsonLogic() val logic = mapOf("==" to listOf(Other(), Other())) val result = jsonLogic.apply(logic) assertEquals(true, result) } @Test fun compareWithOtherComparable() { class Other() : Comparable<Other> { override fun compareTo(other: Other) = 0 } val jsonLogic = JsonLogic() val logic = mapOf("==" to listOf(1, Other())) val result = jsonLogic.apply(logic) assertEquals(false, result) } @Test fun compareNullWithOtherComparable() { class Other() : Comparable<Other> { override fun compareTo(other: Other) = 0 } val jsonLogic = JsonLogic() val logic = mapOf("==" to listOf(null, Other())) val result = jsonLogic.apply(logic) assertEquals(false, result) } @Test fun compareNulls() { val jsonLogic = JsonLogic() val logic = mapOf("==" to listOf(null, null)) val result = jsonLogic.apply(logic) assertEquals(true, result) } @Test fun compareListOfMore() { val jsonLogic = JsonLogic() val logic = mapOf("<" to listOf(1, 2, 3, 4)) val result = jsonLogic.apply(logic) assertEquals(false, result) } @Test fun substrMoreParams() { val jsonLogic = JsonLogic() val logic = mapOf("substr" to listOf("jsonlogic", 4, 5, 6)) val result = jsonLogic.apply(logic) assertEquals(null, result) } @Test fun substrExtreme() { val jsonLogic = JsonLogic() val logic = mapOf("substr" to listOf("jsonlogic", 0, 0)) val result = jsonLogic.apply(logic) assertEquals(null, result) } @Test fun invalidList() { val jsonLogic = JsonLogic() val logic = mapOf("none" to 1) val result = jsonLogic.apply(logic) assertEquals(true, result) } @Test fun getInvalidVar() { val jsonLogic = JsonLogic() val logic = mapOf("var" to "a.") val data = mapOf("a" to mapOf("b" to 1)) val result = jsonLogic.apply(logic, data) assertEquals(null, result) } @Test fun compareBooleanWithString() { val jsonLogic = JsonLogic() val logic = mapOf("==" to listOf("true", true)) val result = jsonLogic.apply(logic) assertEquals(true, result) } }
0
Kotlin
0
1
91a79fee81276ef97689a0cc31984b5d2832166c
10,570
json-logic-kotlin
MIT License
kaspresso/src/main/kotlin/com/kaspersky/kaspresso/device/exploit/Exploit.kt
KasperskyLab
208,070,025
false
null
package com.kaspersky.kaspresso.device.exploit import com.kaspersky.kaspresso.annotations.RequiresAdbServer /** * The interface for exploitation. * * Required: Started AdbServer * 1. Download a file "kaspresso/artifacts/desktop.jar" * 2. Start AdbServer => input in cmd "java jar path_to_file/desktop.jar" * Methods demanding to use AdbServer in the default implementation of this interface are marked. * But nobody can't deprecate you to write implementation that doesn't require AdbServer. */ interface Exploit { /** * Toggles the orientation of the device. */ @RequiresAdbServer fun rotate() /** * Sets the specific [DeviceOrientation] of the device. * * Required Permissions: INTERNET. * * @param deviceOrientation the desired orientation of the device. */ @RequiresAdbServer fun setOrientation(deviceOrientation: DeviceOrientation) /** * Sets the device's auto-rotation, whether it is enabled or not, via shell. * * Required Permissions: INTERNET. * * @param enabled the desired auto-rotation state. */ @RequiresAdbServer fun setAutoRotationEnabled(enabled: Boolean) /** * Presses back button on the device. * * @param failTestIfAppUnderTestClosed if set to true, an exception will be thrown when Espresso navigates * outside the application or process under test. */ fun pressBack(failTestIfAppUnderTestClosed: Boolean = false) /** * Presses home button on the device. * * @return true if successful, else return false. */ fun pressHome(): Boolean enum class DeviceOrientation { Portrait, Landscape } }
55
null
150
1,784
9c94128c744d640dcd646b86de711d2a1b9c3aa1
1,727
Kaspresso
Apache License 2.0
src/test/kotlin/com/fasterxml/jackson/module/kotlin/test/github/Github356.kt
FasterXML
23,404,083
false
null
package com.fasterxml.jackson.module.kotlin.test.github import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import org.junit.Test import kotlin.test.assertEquals class TestGithub356 { private val mapper = jacksonObjectMapper() @Test fun deserializeInlineClass() { assertEquals( ClassWithInlineMember(InlineClass("bar")), mapper.readValue("""{"inlineClassProperty":"bar"}""") ) } @Test fun serializeInlineClass() { assertEquals( """{"inlineClassProperty":"bar"}""", mapper.writeValueAsString(ClassWithInlineMember(InlineClass("bar"))) ) } @Test fun deserializeValueClass() { assertEquals( ClassWithValueMember(ValueClass("bar")), mapper.readValue("""{"valueClassProperty":"bar"}""") ) } @Test fun serializeValueClass() { assertEquals( """{"valueClassProperty":"bar"}""", mapper.writeValueAsString(ClassWithValueMember(ValueClass("bar"))) ) } } @JvmInline value class InlineClass(val value: String) @JsonDeserialize(builder = ClassWithInlineMember.JacksonBuilder::class) data class ClassWithInlineMember(val inlineClassProperty: InlineClass) { data class JacksonBuilder constructor(val inlineClassProperty: String) { fun build() = ClassWithInlineMember(InlineClass(inlineClassProperty)) } } @JvmInline value class ValueClass(val value: String) @JsonDeserialize(builder = ClassWithValueMember.JacksonBuilder::class) data class ClassWithValueMember(val valueClassProperty: ValueClass) { data class JacksonBuilder constructor(val valueClassProperty: String) { fun build() = ClassWithValueMember(ValueClass(valueClassProperty)) } }
77
Kotlin
175
932
fa8ee76a8a00443aa6e8cc401c4e0868219d2d5b
1,909
jackson-module-kotlin
Apache License 2.0
app/src/main/java/giuliolodi/gitnav/data/DataManagerImpl.kt
GLodi
67,536,967
false
null
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.data import android.content.Context import android.graphics.Bitmap import giuliolodi.gitnav.di.scope.AppContext import giuliolodi.gitnav.data.api.ApiHelper import giuliolodi.gitnav.data.model.RequestAccessTokenResponse import giuliolodi.gitnav.data.prefs.PrefsHelper import io.reactivex.Completable import io.reactivex.Flowable import org.eclipse.egit.github.core.* import org.eclipse.egit.github.core.event.Event import org.eclipse.egit.github.core.service.UserService import javax.inject.Inject import javax.inject.Singleton /** * Created by giulio on 12/05/2017. */ @Singleton class DataManagerImpl : DataManager { private val TAG = "DataManager" private val mContext: Context private val mApiHelper: ApiHelper private val mPrefsHelper: PrefsHelper @Inject constructor(@AppContext context: Context, apiHelper: ApiHelper, prefsHelper: PrefsHelper) { mContext = context mApiHelper = apiHelper mPrefsHelper = prefsHelper } override fun tryAuthentication(username: String, password: String): Completable { return Completable.fromAction { val token: String val user: User try { token = apiAuthToGitHub(username, password) } catch (e: Exception) { throw e } if (!token.isEmpty()) { try { val userService: UserService = UserService() userService.client.setOAuth2Token(getToken()) user = userService.getUser(username) storeUser(user) mPrefsHelper.storeAccessToken(token) } catch (e: Exception) { throw e } } } } override fun downloadUserInfoFromToken(token: String): Completable { return Completable.fromAction { val user: User if (!token.isEmpty()) { try { val userService: UserService = UserService() userService.client.setOAuth2Token(token) user = userService.user storeUser(user) mPrefsHelper.storeAccessToken(token) } catch (e: Exception) { throw e } } } } override fun updateUser(user: User): Completable { return Completable.fromAction { if (mPrefsHelper.getUsername() == user.login) { try { storeUser(user) } catch (e: Exception) { throw e } } } } override fun storeAccessToken(token: String) { mPrefsHelper.storeAccessToken(token) } override fun getToken(): String { return mPrefsHelper.getToken() } override fun pageEvents(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> { return mApiHelper.apiPageEvents(mPrefsHelper.getToken(), username?.let { username } ?: mPrefsHelper.getUsername(), pageN, itemsPerPage) } override fun pageUserEvents(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> { return mApiHelper.apiPageUserEvents(mPrefsHelper.getToken(), username?.let { username } ?: mPrefsHelper.getUsername(), pageN, itemsPerPage) } override fun getUser(username: String): Flowable<User> { return apiGetUser(mPrefsHelper.getToken(), username) } override fun storeUser(user: User) { mPrefsHelper.storeUser(user) } override fun getFullname(): String? { return mPrefsHelper.getFullname() } override fun getEmail(): String? { return mPrefsHelper.getEmail() } override fun getUsername(): String { return mPrefsHelper.getUsername() } override fun getPic(): Bitmap { return mPrefsHelper.getPic() } override fun pageRepos(username: String?, pageN: Int, itemsPerPage: Int, filter: HashMap<String, String>?): Flowable<List<Repository>> { if (username == null) return mApiHelper.apiPageRepos(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage, filter) else return mApiHelper.apiPageRepos(mPrefsHelper.getToken(), username, pageN, itemsPerPage, filter) } override fun getTrending(period: String): Flowable<Repository> { return mApiHelper.apiGetTrending(mPrefsHelper.getToken(), period) } override fun pageStarred(pageN: Int, itemsPerPage: Int, filter: HashMap<String, String>?): Flowable<List<Repository>> { return mApiHelper.apiPageStarred(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage, filter) } override fun getFollowed(username: String): Flowable<String> { if (mPrefsHelper.getUsername() == username) return Flowable.just("u") else return mApiHelper.apiGetFollowed(mPrefsHelper.getToken(), username) } override fun pageFollowers(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { if (username == null) return mApiHelper.apiGetFollowers(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage) else return mApiHelper.apiGetFollowers(mPrefsHelper.getToken(), username, pageN, itemsPerPage) } override fun pageFollowing(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { if (username == null) return mApiHelper.apiGetFollowing(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage) else return mApiHelper.apiGetFollowing(mPrefsHelper.getToken(), username, pageN, itemsPerPage) } override fun followUser(username: String): Completable { if (username != mPrefsHelper.getUsername()) return mApiHelper.apiFollowUser(mPrefsHelper.getToken(), username) return Completable.error(Exception()) } override fun unfollowUser(username: String): Completable { if (username != mPrefsHelper.getUsername()) return mApiHelper.apiUnfollowUser(mPrefsHelper.getToken(), username) return Completable.error(Exception()) } override fun pageGists(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> { if (username == null) return mApiHelper.apiPageGists(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage) else return mApiHelper.apiPageGists(mPrefsHelper.getToken(), username, pageN, itemsPerPage) } override fun pageStarredGists(pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> { return mApiHelper.apiPageStarredGists(mPrefsHelper.getToken(), pageN, itemsPerPage) } override fun getGist(gistId: String): Flowable<Gist> { return mApiHelper.apiGetGist(mPrefsHelper.getToken(), gistId) } override fun getGistComments(gistId: String): Flowable<List<Comment>> { return mApiHelper.apiGetGistComments(mPrefsHelper.getToken(), gistId) } override fun starGist(gistId: String): Completable { return mApiHelper.apiStarGist(mPrefsHelper.getToken(), gistId) } override fun unstarGist(gistId: String): Completable { return mApiHelper.apiUnstarGist(mPrefsHelper.getToken(), gistId) } override fun isGistStarred(gistId: String): Flowable<Boolean> { return mApiHelper.apiIsGistStarred(mPrefsHelper.getToken(), gistId) } override fun searchRepos(query: String, filter: HashMap<String,String>): Flowable<List<Repository>> { return mApiHelper.apiSearchRepos(mPrefsHelper.getToken(), query, filter) } override fun searchUsers(query: String, filter: HashMap<String,String>): Flowable<List<SearchUser>> { return mApiHelper.apiSearchUsers(mPrefsHelper.getToken(), query, filter) } override fun searchCode(query: String): Flowable<List<CodeSearchResult>> { return mApiHelper.apiSearchCode(mPrefsHelper.getToken(), query) } override fun isRepoStarred(owner: String, name: String): Flowable<Boolean> { return mApiHelper.apiIsRepoStarred(mPrefsHelper.getToken(), owner, name) } override fun getRepo(owner: String, name: String): Flowable<Repository> { return mApiHelper.apiGetRepo(mPrefsHelper.getToken(), owner, name) } override fun starRepo(owner: String, name: String): Completable { return mApiHelper.apiStarRepo(mPrefsHelper.getToken(), owner, name) } override fun unstarRepo(owner: String, name: String): Completable { return mApiHelper.apiUnstarRepo(mPrefsHelper.getToken(), owner, name) } override fun getReadme(owner: String, name: String): Flowable<String> { return mApiHelper.apiGetReadme(mPrefsHelper.getToken(), owner, name) } override fun getRepoCommits(owner: String, name: String): Flowable<List<RepositoryCommit>> { return mApiHelper.apiGetRepoCommits(mPrefsHelper.getToken(), owner, name) } override fun getContributors(owner: String, name: String): Flowable<List<Contributor>> { return mApiHelper.apiGetContributors(mPrefsHelper.getToken(), owner, name) } override fun getContent(owner: String, name: String, path: String): Flowable<List<RepositoryContents>> { return mApiHelper.apiGetContent(mPrefsHelper.getToken(), owner, name, path) } override fun pageStargazers(owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { return mApiHelper.apiPageStargazers(mPrefsHelper.getToken(), owner, name, pageN, itemsPerPage) } override fun pageIssues(owner: String, name: String, pageN: Int, itemsPerPage: Int, hashMap: HashMap<String,String>): Flowable<List<Issue>> { return mApiHelper.apiPageIssues(mPrefsHelper.getToken(), owner, name, pageN, itemsPerPage, hashMap) } override fun pageForks(owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<Repository>> { return mApiHelper.apiPageForks(mPrefsHelper.getToken(), owner, name, pageN, itemsPerPage) } override fun forkRepo(owner: String, name: String): Completable { return mApiHelper.apiForkRepo(mPrefsHelper.getToken(), owner, name) } override fun getIssue(owner: String, name: String, issueNumber: Int): Flowable<Issue> { return mApiHelper.apiGetIssue(mPrefsHelper.getToken(), owner, name, issueNumber) } override fun getIssueComments(owner: String, name: String, issueNumber: Int): Flowable<List<Comment>> { return mApiHelper.apiGetIssueComments(mPrefsHelper.getToken(), owner, name, issueNumber) } override fun setTheme(theme: String) { return mPrefsHelper.setTheme(theme) } override fun getTheme(): String { return mPrefsHelper.getTheme() } override fun getCommit(owner: String, name: String, sha: String): Flowable<RepositoryCommit> { return mApiHelper.apiGetCommit(mPrefsHelper.getToken(), owner, name, sha) } override fun getCommitComments(owner: String, name: String, sha: String): Flowable<List<CommitComment>> { return mApiHelper.apiGetCommitComments(mPrefsHelper.getToken(), owner, name, sha) } override fun apiAuthToGitHub(username: String, password: String): String { return mApiHelper.apiAuthToGitHub(username, password) } override fun apiPageEvents(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> { return mApiHelper.apiPageEvents(token, username, pageN, itemsPerPage) } override fun apiPageUserEvents(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> { return mApiHelper.apiPageUserEvents(token, username, pageN, itemsPerPage) } override fun apiGetUser(token: String, username: String): Flowable<User> { return mApiHelper.apiGetUser(token, username) } override fun apiPageRepos(token: String, username: String, pageN: Int, itemsPerPage: Int, filter: HashMap<String,String>?): Flowable<List<Repository>> { return mApiHelper.apiPageRepos(token, username, pageN, itemsPerPage, filter) } override fun apiGetTrending(token: String, period: String): Flowable<Repository> { return mApiHelper.apiGetTrending(token, period) } override fun apiPageStarred(token: String, username: String, pageN: Int, itemsPerPage: Int, filter: HashMap<String, String>?): Flowable<List<Repository>> { return mApiHelper.apiPageStarred(token, username, pageN, itemsPerPage, filter) } override fun apiGetFollowed(token: String, username: String): Flowable<String> { return mApiHelper.apiGetFollowed(token, username) } override fun apiGetFollowers(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { return mApiHelper.apiGetFollowers(token, username, pageN, itemsPerPage) } override fun apiGetFollowing(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { return mApiHelper.apiGetFollowers(token, username, pageN, itemsPerPage) } override fun apiFollowUser(token: String, username: String): Completable { return mApiHelper.apiFollowUser(token, username) } override fun apiUnfollowUser(token: String, username: String): Completable { return mApiHelper.apiUnfollowUser(token, username) } override fun apiPageGists(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> { return mApiHelper.apiPageGists(token, username, pageN, itemsPerPage) } override fun apiPageStarredGists(token: String, pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> { return mApiHelper.apiPageStarredGists(token, pageN, itemsPerPage) } override fun apiGetGist(token: String, gistId: String): Flowable<Gist> { return mApiHelper.apiGetGist(token, gistId) } override fun apiGetGistComments(token: String, gistId: String): Flowable<List<Comment>> { return mApiHelper.apiGetGistComments(token, gistId) } override fun apiStarGist(token: String, gistId: String): Completable { return mApiHelper.apiStarGist(token, gistId) } override fun apiUnstarGist(token: String, gistId: String): Completable { return mApiHelper.apiUnstarGist(token, gistId) } override fun apiIsGistStarred(token: String, gistId: String): Flowable<Boolean> { return mApiHelper.apiIsGistStarred(token, gistId) } override fun apiSearchRepos(token: String, query: String, filter: HashMap<String,String>): Flowable<List<Repository>> { return mApiHelper.apiSearchRepos(token, query, filter) } override fun apiSearchUsers(token: String, query: String, filter: HashMap<String,String>): Flowable<List<SearchUser>> { return mApiHelper.apiSearchUsers(token, query, filter) } override fun apiSearchCode(token: String, query: String): Flowable<List<CodeSearchResult>> { return mApiHelper.apiSearchCode(token, query) } override fun apiIsRepoStarred(token: String, owner: String, name: String): Flowable<Boolean> { return mApiHelper.apiIsRepoStarred(token, owner, name) } override fun apiGetRepo(token: String, owner: String, name: String): Flowable<Repository> { return mApiHelper.apiGetRepo(token, owner, name) } override fun apiStarRepo(token: String, owner: String, name: String): Completable { return mApiHelper.apiStarRepo(token, owner, name) } override fun apiUnstarRepo(token: String, owner: String, name: String): Completable { return mApiHelper.apiUnstarRepo(token, owner, name) } override fun apiGetReadme(token: String, owner: String, name: String): Flowable<String> { return mApiHelper.apiGetReadme(token, owner, name) } override fun apiGetRepoCommits(token: String, owner: String, name: String): Flowable<List<RepositoryCommit>> { return mApiHelper.apiGetRepoCommits(token, owner, name) } override fun apiGetContributors(token: String, owner: String, name: String): Flowable<List<Contributor>> { return mApiHelper.apiGetContributors(token, owner, name) } override fun apiGetContent(token: String, owner: String, name: String, path: String): Flowable<List<RepositoryContents>> { return mApiHelper.apiGetContent(token, owner, name, path) } override fun apiPageStargazers(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { return mApiHelper.apiPageStargazers(token, owner, name, pageN, itemsPerPage) } override fun apiPageIssues(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int, hashMap: HashMap<String,String>): Flowable<List<Issue>> { return mApiHelper.apiPageIssues(token, owner, name, pageN, itemsPerPage, hashMap) } override fun apiPageForks(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<Repository>> { return mApiHelper.apiPageForks(token, owner, name, pageN, itemsPerPage) } override fun apiForkRepo(token: String, owner: String, name: String): Completable { return mApiHelper.apiForkRepo(token, owner, name) } override fun apiRequestAccessToken(clientId: String, clientSecret: String, code: String, redirectUri: String, state: String): Flowable<RequestAccessTokenResponse> { return mApiHelper.apiRequestAccessToken(clientId, clientSecret, code, redirectUri, state) } override fun apiGetIssue(token: String, owner: String, name: String, issueNumber: Int): Flowable<Issue> { return mApiHelper.apiGetIssue(token, owner, name, issueNumber) } override fun apiGetIssueComments(token: String, owner: String, name: String, issueNumber: Int): Flowable<List<Comment>> { return mApiHelper.apiGetIssueComments(token, owner, name, issueNumber) } override fun apiGetCommit(token: String, owner: String, name: String, sha: String): Flowable<RepositoryCommit> { return mApiHelper.apiGetCommit(token, owner, name, sha) } override fun apiGetCommitComments(token: String, owner: String, name: String, sha: String): Flowable<List<CommitComment>> { return mApiHelper.apiGetCommitComments(token, owner, name, sha) } }
3
null
5
26
3311c38d74dc1e7d28cba344815aa908e6915e64
19,102
GitNav
Apache License 2.0
app/src/main/java/giuliolodi/gitnav/data/DataManagerImpl.kt
GLodi
67,536,967
false
null
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.data import android.content.Context import android.graphics.Bitmap import giuliolodi.gitnav.di.scope.AppContext import giuliolodi.gitnav.data.api.ApiHelper import giuliolodi.gitnav.data.model.RequestAccessTokenResponse import giuliolodi.gitnav.data.prefs.PrefsHelper import io.reactivex.Completable import io.reactivex.Flowable import org.eclipse.egit.github.core.* import org.eclipse.egit.github.core.event.Event import org.eclipse.egit.github.core.service.UserService import javax.inject.Inject import javax.inject.Singleton /** * Created by giulio on 12/05/2017. */ @Singleton class DataManagerImpl : DataManager { private val TAG = "DataManager" private val mContext: Context private val mApiHelper: ApiHelper private val mPrefsHelper: PrefsHelper @Inject constructor(@AppContext context: Context, apiHelper: ApiHelper, prefsHelper: PrefsHelper) { mContext = context mApiHelper = apiHelper mPrefsHelper = prefsHelper } override fun tryAuthentication(username: String, password: String): Completable { return Completable.fromAction { val token: String val user: User try { token = apiAuthToGitHub(username, password) } catch (e: Exception) { throw e } if (!token.isEmpty()) { try { val userService: UserService = UserService() userService.client.setOAuth2Token(getToken()) user = userService.getUser(username) storeUser(user) mPrefsHelper.storeAccessToken(token) } catch (e: Exception) { throw e } } } } override fun downloadUserInfoFromToken(token: String): Completable { return Completable.fromAction { val user: User if (!token.isEmpty()) { try { val userService: UserService = UserService() userService.client.setOAuth2Token(token) user = userService.user storeUser(user) mPrefsHelper.storeAccessToken(token) } catch (e: Exception) { throw e } } } } override fun updateUser(user: User): Completable { return Completable.fromAction { if (mPrefsHelper.getUsername() == user.login) { try { storeUser(user) } catch (e: Exception) { throw e } } } } override fun storeAccessToken(token: String) { mPrefsHelper.storeAccessToken(token) } override fun getToken(): String { return mPrefsHelper.getToken() } override fun pageEvents(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> { return mApiHelper.apiPageEvents(mPrefsHelper.getToken(), username?.let { username } ?: mPrefsHelper.getUsername(), pageN, itemsPerPage) } override fun pageUserEvents(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> { return mApiHelper.apiPageUserEvents(mPrefsHelper.getToken(), username?.let { username } ?: mPrefsHelper.getUsername(), pageN, itemsPerPage) } override fun getUser(username: String): Flowable<User> { return apiGetUser(mPrefsHelper.getToken(), username) } override fun storeUser(user: User) { mPrefsHelper.storeUser(user) } override fun getFullname(): String? { return mPrefsHelper.getFullname() } override fun getEmail(): String? { return mPrefsHelper.getEmail() } override fun getUsername(): String { return mPrefsHelper.getUsername() } override fun getPic(): Bitmap { return mPrefsHelper.getPic() } override fun pageRepos(username: String?, pageN: Int, itemsPerPage: Int, filter: HashMap<String, String>?): Flowable<List<Repository>> { if (username == null) return mApiHelper.apiPageRepos(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage, filter) else return mApiHelper.apiPageRepos(mPrefsHelper.getToken(), username, pageN, itemsPerPage, filter) } override fun getTrending(period: String): Flowable<Repository> { return mApiHelper.apiGetTrending(mPrefsHelper.getToken(), period) } override fun pageStarred(pageN: Int, itemsPerPage: Int, filter: HashMap<String, String>?): Flowable<List<Repository>> { return mApiHelper.apiPageStarred(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage, filter) } override fun getFollowed(username: String): Flowable<String> { if (mPrefsHelper.getUsername() == username) return Flowable.just("u") else return mApiHelper.apiGetFollowed(mPrefsHelper.getToken(), username) } override fun pageFollowers(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { if (username == null) return mApiHelper.apiGetFollowers(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage) else return mApiHelper.apiGetFollowers(mPrefsHelper.getToken(), username, pageN, itemsPerPage) } override fun pageFollowing(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { if (username == null) return mApiHelper.apiGetFollowing(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage) else return mApiHelper.apiGetFollowing(mPrefsHelper.getToken(), username, pageN, itemsPerPage) } override fun followUser(username: String): Completable { if (username != mPrefsHelper.getUsername()) return mApiHelper.apiFollowUser(mPrefsHelper.getToken(), username) return Completable.error(Exception()) } override fun unfollowUser(username: String): Completable { if (username != mPrefsHelper.getUsername()) return mApiHelper.apiUnfollowUser(mPrefsHelper.getToken(), username) return Completable.error(Exception()) } override fun pageGists(username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> { if (username == null) return mApiHelper.apiPageGists(mPrefsHelper.getToken(), mPrefsHelper.getUsername(), pageN, itemsPerPage) else return mApiHelper.apiPageGists(mPrefsHelper.getToken(), username, pageN, itemsPerPage) } override fun pageStarredGists(pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> { return mApiHelper.apiPageStarredGists(mPrefsHelper.getToken(), pageN, itemsPerPage) } override fun getGist(gistId: String): Flowable<Gist> { return mApiHelper.apiGetGist(mPrefsHelper.getToken(), gistId) } override fun getGistComments(gistId: String): Flowable<List<Comment>> { return mApiHelper.apiGetGistComments(mPrefsHelper.getToken(), gistId) } override fun starGist(gistId: String): Completable { return mApiHelper.apiStarGist(mPrefsHelper.getToken(), gistId) } override fun unstarGist(gistId: String): Completable { return mApiHelper.apiUnstarGist(mPrefsHelper.getToken(), gistId) } override fun isGistStarred(gistId: String): Flowable<Boolean> { return mApiHelper.apiIsGistStarred(mPrefsHelper.getToken(), gistId) } override fun searchRepos(query: String, filter: HashMap<String,String>): Flowable<List<Repository>> { return mApiHelper.apiSearchRepos(mPrefsHelper.getToken(), query, filter) } override fun searchUsers(query: String, filter: HashMap<String,String>): Flowable<List<SearchUser>> { return mApiHelper.apiSearchUsers(mPrefsHelper.getToken(), query, filter) } override fun searchCode(query: String): Flowable<List<CodeSearchResult>> { return mApiHelper.apiSearchCode(mPrefsHelper.getToken(), query) } override fun isRepoStarred(owner: String, name: String): Flowable<Boolean> { return mApiHelper.apiIsRepoStarred(mPrefsHelper.getToken(), owner, name) } override fun getRepo(owner: String, name: String): Flowable<Repository> { return mApiHelper.apiGetRepo(mPrefsHelper.getToken(), owner, name) } override fun starRepo(owner: String, name: String): Completable { return mApiHelper.apiStarRepo(mPrefsHelper.getToken(), owner, name) } override fun unstarRepo(owner: String, name: String): Completable { return mApiHelper.apiUnstarRepo(mPrefsHelper.getToken(), owner, name) } override fun getReadme(owner: String, name: String): Flowable<String> { return mApiHelper.apiGetReadme(mPrefsHelper.getToken(), owner, name) } override fun getRepoCommits(owner: String, name: String): Flowable<List<RepositoryCommit>> { return mApiHelper.apiGetRepoCommits(mPrefsHelper.getToken(), owner, name) } override fun getContributors(owner: String, name: String): Flowable<List<Contributor>> { return mApiHelper.apiGetContributors(mPrefsHelper.getToken(), owner, name) } override fun getContent(owner: String, name: String, path: String): Flowable<List<RepositoryContents>> { return mApiHelper.apiGetContent(mPrefsHelper.getToken(), owner, name, path) } override fun pageStargazers(owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { return mApiHelper.apiPageStargazers(mPrefsHelper.getToken(), owner, name, pageN, itemsPerPage) } override fun pageIssues(owner: String, name: String, pageN: Int, itemsPerPage: Int, hashMap: HashMap<String,String>): Flowable<List<Issue>> { return mApiHelper.apiPageIssues(mPrefsHelper.getToken(), owner, name, pageN, itemsPerPage, hashMap) } override fun pageForks(owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<Repository>> { return mApiHelper.apiPageForks(mPrefsHelper.getToken(), owner, name, pageN, itemsPerPage) } override fun forkRepo(owner: String, name: String): Completable { return mApiHelper.apiForkRepo(mPrefsHelper.getToken(), owner, name) } override fun getIssue(owner: String, name: String, issueNumber: Int): Flowable<Issue> { return mApiHelper.apiGetIssue(mPrefsHelper.getToken(), owner, name, issueNumber) } override fun getIssueComments(owner: String, name: String, issueNumber: Int): Flowable<List<Comment>> { return mApiHelper.apiGetIssueComments(mPrefsHelper.getToken(), owner, name, issueNumber) } override fun setTheme(theme: String) { return mPrefsHelper.setTheme(theme) } override fun getTheme(): String { return mPrefsHelper.getTheme() } override fun getCommit(owner: String, name: String, sha: String): Flowable<RepositoryCommit> { return mApiHelper.apiGetCommit(mPrefsHelper.getToken(), owner, name, sha) } override fun getCommitComments(owner: String, name: String, sha: String): Flowable<List<CommitComment>> { return mApiHelper.apiGetCommitComments(mPrefsHelper.getToken(), owner, name, sha) } override fun apiAuthToGitHub(username: String, password: String): String { return mApiHelper.apiAuthToGitHub(username, password) } override fun apiPageEvents(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> { return mApiHelper.apiPageEvents(token, username, pageN, itemsPerPage) } override fun apiPageUserEvents(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> { return mApiHelper.apiPageUserEvents(token, username, pageN, itemsPerPage) } override fun apiGetUser(token: String, username: String): Flowable<User> { return mApiHelper.apiGetUser(token, username) } override fun apiPageRepos(token: String, username: String, pageN: Int, itemsPerPage: Int, filter: HashMap<String,String>?): Flowable<List<Repository>> { return mApiHelper.apiPageRepos(token, username, pageN, itemsPerPage, filter) } override fun apiGetTrending(token: String, period: String): Flowable<Repository> { return mApiHelper.apiGetTrending(token, period) } override fun apiPageStarred(token: String, username: String, pageN: Int, itemsPerPage: Int, filter: HashMap<String, String>?): Flowable<List<Repository>> { return mApiHelper.apiPageStarred(token, username, pageN, itemsPerPage, filter) } override fun apiGetFollowed(token: String, username: String): Flowable<String> { return mApiHelper.apiGetFollowed(token, username) } override fun apiGetFollowers(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { return mApiHelper.apiGetFollowers(token, username, pageN, itemsPerPage) } override fun apiGetFollowing(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { return mApiHelper.apiGetFollowers(token, username, pageN, itemsPerPage) } override fun apiFollowUser(token: String, username: String): Completable { return mApiHelper.apiFollowUser(token, username) } override fun apiUnfollowUser(token: String, username: String): Completable { return mApiHelper.apiUnfollowUser(token, username) } override fun apiPageGists(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> { return mApiHelper.apiPageGists(token, username, pageN, itemsPerPage) } override fun apiPageStarredGists(token: String, pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> { return mApiHelper.apiPageStarredGists(token, pageN, itemsPerPage) } override fun apiGetGist(token: String, gistId: String): Flowable<Gist> { return mApiHelper.apiGetGist(token, gistId) } override fun apiGetGistComments(token: String, gistId: String): Flowable<List<Comment>> { return mApiHelper.apiGetGistComments(token, gistId) } override fun apiStarGist(token: String, gistId: String): Completable { return mApiHelper.apiStarGist(token, gistId) } override fun apiUnstarGist(token: String, gistId: String): Completable { return mApiHelper.apiUnstarGist(token, gistId) } override fun apiIsGistStarred(token: String, gistId: String): Flowable<Boolean> { return mApiHelper.apiIsGistStarred(token, gistId) } override fun apiSearchRepos(token: String, query: String, filter: HashMap<String,String>): Flowable<List<Repository>> { return mApiHelper.apiSearchRepos(token, query, filter) } override fun apiSearchUsers(token: String, query: String, filter: HashMap<String,String>): Flowable<List<SearchUser>> { return mApiHelper.apiSearchUsers(token, query, filter) } override fun apiSearchCode(token: String, query: String): Flowable<List<CodeSearchResult>> { return mApiHelper.apiSearchCode(token, query) } override fun apiIsRepoStarred(token: String, owner: String, name: String): Flowable<Boolean> { return mApiHelper.apiIsRepoStarred(token, owner, name) } override fun apiGetRepo(token: String, owner: String, name: String): Flowable<Repository> { return mApiHelper.apiGetRepo(token, owner, name) } override fun apiStarRepo(token: String, owner: String, name: String): Completable { return mApiHelper.apiStarRepo(token, owner, name) } override fun apiUnstarRepo(token: String, owner: String, name: String): Completable { return mApiHelper.apiUnstarRepo(token, owner, name) } override fun apiGetReadme(token: String, owner: String, name: String): Flowable<String> { return mApiHelper.apiGetReadme(token, owner, name) } override fun apiGetRepoCommits(token: String, owner: String, name: String): Flowable<List<RepositoryCommit>> { return mApiHelper.apiGetRepoCommits(token, owner, name) } override fun apiGetContributors(token: String, owner: String, name: String): Flowable<List<Contributor>> { return mApiHelper.apiGetContributors(token, owner, name) } override fun apiGetContent(token: String, owner: String, name: String, path: String): Flowable<List<RepositoryContents>> { return mApiHelper.apiGetContent(token, owner, name, path) } override fun apiPageStargazers(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<User>> { return mApiHelper.apiPageStargazers(token, owner, name, pageN, itemsPerPage) } override fun apiPageIssues(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int, hashMap: HashMap<String,String>): Flowable<List<Issue>> { return mApiHelper.apiPageIssues(token, owner, name, pageN, itemsPerPage, hashMap) } override fun apiPageForks(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<Repository>> { return mApiHelper.apiPageForks(token, owner, name, pageN, itemsPerPage) } override fun apiForkRepo(token: String, owner: String, name: String): Completable { return mApiHelper.apiForkRepo(token, owner, name) } override fun apiRequestAccessToken(clientId: String, clientSecret: String, code: String, redirectUri: String, state: String): Flowable<RequestAccessTokenResponse> { return mApiHelper.apiRequestAccessToken(clientId, clientSecret, code, redirectUri, state) } override fun apiGetIssue(token: String, owner: String, name: String, issueNumber: Int): Flowable<Issue> { return mApiHelper.apiGetIssue(token, owner, name, issueNumber) } override fun apiGetIssueComments(token: String, owner: String, name: String, issueNumber: Int): Flowable<List<Comment>> { return mApiHelper.apiGetIssueComments(token, owner, name, issueNumber) } override fun apiGetCommit(token: String, owner: String, name: String, sha: String): Flowable<RepositoryCommit> { return mApiHelper.apiGetCommit(token, owner, name, sha) } override fun apiGetCommitComments(token: String, owner: String, name: String, sha: String): Flowable<List<CommitComment>> { return mApiHelper.apiGetCommitComments(token, owner, name, sha) } }
3
null
5
26
3311c38d74dc1e7d28cba344815aa908e6915e64
19,102
GitNav
Apache License 2.0
composeApp/src/wasmJsMain/kotlin/augmy/interactive/com/main.kt
Let-s-build-something
867,003,530
false
{"Kotlin": 108818, "HTML": 2487, "JavaScript": 1633, "CSS": 690}
package augmy.interactive.com import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.window.ComposeViewport import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import augmy.interactive.com.base.LocalOnBackPress import augmy.interactive.com.injection.commonModule import augmy.interactive.com.navigation.DEFAULT_START_DESTINATION import kotlinx.browser.document import kotlinx.browser.window import kotlinx.coroutines.delay import org.koin.core.context.startKoin // paranoid check private var isAppInitialized = false // Define an interface for your global state external interface GlobalAppState { var kotlinApp: Boolean? } @OptIn(ExperimentalComposeUiApi::class) fun main() { if(isAppInitialized.not()) { (window as? GlobalAppState)?.kotlinApp = true startKoin { modules(commonModule) } isAppInitialized = true } document.body?.let { body -> try { ComposeViewport(body) { val navController = rememberNavController() val currentEntry = navController.currentBackStackEntryAsState() //val currentRoute = currentEntry.value?.destination?.route ?: window.location.pathname CompositionLocalProvider( LocalOnBackPress provides { window.history.go(-1) } ) { App( navController = navController, //startDestination = window.location.pathname ) } /*LaunchedEffect(currentEntry.value) { if(currentEntry.value != null && window.location.pathname != currentRoute ) { window.location.pathname = currentRoute } }*/ //https://developer.mozilla.org/en-US/docs/Web/API/Location LaunchedEffect(window.location.pathname) { delay(500) // navigate to correct route only if arguments are required, otherwise startDestination is sufficient if(window.location.pathname != DEFAULT_START_DESTINATION) { navController.navigate(route = window.location.pathname) } } } }catch (e: Exception) { e.printStackTrace() } } }
0
Kotlin
0
1
b352de83416659e791829eb89c464512e397d9ee
2,659
website-brand
Apache License 2.0
src/main/kotlin/org/arend/toolWindow/errors/tree/ArendErrorTreeListener.kt
JetBrains
96,068,447
false
null
package org.arend.toolWindow.errors.tree import org.arend.typechecking.error.ArendError interface ArendErrorTreeListener { fun errorAdded(arendError: ArendError) {} fun errorRemoved(arendError: ArendError) {} }
45
null
12
90
b11d0906f9a0d9680675a418cdc50b98e2d33c92
220
intellij-arend
Apache License 2.0
src/main/java/jp/osak/haggledehaghag/viewmodel/TokenView.kt
haggle-de-haghag
363,896,456
false
{"TypeScript": 133798, "Kotlin": 50837, "HTML": 7203, "JavaScript": 3623, "CSS": 946, "SCSS": 844, "Java": 231}
package jp.osak.haggledehaghag.viewmodel import jp.osak.haggledehaghag.model.TokenWithAmount data class TokenView( val id: Int, // token id val title: String, val text: String, val amount: Int, ) { constructor(t: TokenWithAmount) : this(t.token.id, t.token.title, t.token.text, t.amount) }
7
TypeScript
0
0
d11bcb3f9c2805e3f212c92200674eab4e1c8193
312
haggle-de-haghag
MIT License
app/src/main/kotlin/com/github/plplmax/notes/ui/note/NoteViewModel.kt
plplmax
469,630,612
false
null
/* * MIT License * * Copyright (c) 2022 Maksim Ploski * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.plplmax.notes.ui.note import androidx.lifecycle.ViewModel import com.github.plplmax.notes.domain.notes.model.InitialNote import com.github.plplmax.notes.domain.notes.model.Note import com.github.plplmax.notes.domain.notes.usecase.CreateNoteUseCase import com.github.plplmax.notes.domain.notes.usecase.EditNoteUseCase import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject interface NoteViewModel { fun submitNote(note: Note) fun submitText(text: String) @HiltViewModel class Base @Inject constructor( private val createNoteUseCase: CreateNoteUseCase, private val editNoteUseCase: EditNoteUseCase ) : ViewModel(), NoteViewModel { var note: Note? = null private set override fun submitNote(note: Note) { this.note = note } override fun submitText(text: String) { if (text.trim().isEmpty()) return note = if (note == null) { createNoteUseCase(InitialNote(text)) } else { val editedNote = Note(note!!.id, text) editNoteUseCase(editedNote) editedNote } } } }
0
Kotlin
0
1
8690d42601b792cbccdc213a3978fa8e9fa78554
2,356
notes
MIT License
komga/src/main/kotlin/org/gotson/komga/infrastructure/security/KomgaPrincipal.kt
weblate
337,108,059
true
{"Kotlin": 649407, "Vue": 319074, "TypeScript": 80153, "JavaScript": 2803, "Shell": 1904, "HTML": 704, "Dockerfile": 608, "Sass": 309, "CSS": 252}
package org.gotson.komga.infrastructure.security import org.gotson.komga.domain.model.KomgaUser import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.UserDetails class KomgaPrincipal( val user: KomgaUser ) : UserDetails { override fun getAuthorities(): MutableCollection<out GrantedAuthority> { return user.roles.map { it.name } .toMutableSet() .apply { add("USER") } .map { SimpleGrantedAuthority("ROLE_$it") } .toMutableSet() } override fun isEnabled() = true override fun getUsername() = user.email override fun isCredentialsNonExpired() = true override fun getPassword() = <PASSWORD> override fun isAccountNonExpired() = true override fun isAccountNonLocked() = true }
0
null
0
1
09c35a4f1fb15e5142f3d29feea01c2616a04dcd
869
komga
MIT License
vtp-pensjon-application/src/main/kotlin/no/nav/pensjon/vtp/mocks/oppgave/sak/SakRestTjeneste.kt
navikt
254,055,233
false
null
package no.nav.pensjon.vtp.mocks.oppgave.sak import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import no.nav.pensjon.vtp.mocks.oppgave.gask.sak.v1.GsakRepo import no.nav.pensjon.vtp.testmodell.personopplysning.PersonModellRepository import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.server.ResponseStatusException @RestController @Api(tags = ["Gsak repository"]) @RequestMapping("/rest/api/sak") class SakRestTjeneste(private val personModellRepository: PersonModellRepository, private val gsakRepo: GsakRepo) { @PostMapping @ApiOperation(value = "", notes = "Lager nytt saksnummer fra sekvens", response = OpprettSakResponseDTO::class) fun foreldrepengesoknadErketype(@RequestBody requestDTO: OpprettSakRequestDTO): OpprettSakResponseDTO { if (requestDTO.lokalIdent.isEmpty()) { throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Request mangler påkrevde verdier") } val sak = gsakRepo.leggTilSak( requestDTO.lokalIdent .mapNotNull { ident: String -> personModellRepository.findById(ident) }, requestDTO.fagområde, requestDTO.fagsystem, requestDTO.sakstype ) return OpprettSakResponseDTO(sak.sakId) } }
3
Kotlin
0
1
8f6cd906d9af506afb1c4dfe2234a136d52e2e69
1,572
vtp-pensjon
MIT License
src/main/kotlin/com/mcjeffr/shotbowplayercountapi/models/Count.kt
McJeffr
289,536,253
false
null
package com.mcjeffr.shotbowplayercountapi.models import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.mcjeffr.shotbowplayercountapi.utils.CountDeserializer import java.time.Instant /** * This class represents all the recorded counts at a specific point in time. * * @author McJeffr */ @JsonDeserialize(using = CountDeserializer::class) class Count( val timestamp: Instant = Instant.now(), val components: MutableList<CountComponent> = mutableListOf() ) { override fun toString(): String { return "Count(timestamp=$timestamp, components=$components)" } }
0
Kotlin
0
0
0f4b3168fc91f24f8b2e825cfb3648c0c3efddfb
609
shotbow-playercount-api
MIT License
modules/data/src/main/java/eu/automateeverything/data/plugins/PluginCategory.kt
tomaszbabiuk
488,678,209
true
{"Java Properties": 16, "Gradle": 28, "Shell": 1, "Markdown": 15, "Batchfile": 1, "Text": 1, "Ignore List": 2, "Kotlin": 415, "SVG": 64, "INI": 2, "Java": 199, "HTML": 5, "JSON": 2, "JavaScript": 12, "Vue": 48}
/* * Copyright (c) 2019-2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.automateeverything.data.plugins enum class PluginCategory { Hardware, Objects, Icons, Access, Others }
0
null
1
0
f1163bb95b9497c70ed48db0bcaf4e7050218e7a
734
automate-everything
Apache License 2.0
src/main/kotlin/org/rust/lang/core/parser/util.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.lang.core.parser import com.intellij.lang.LanguageParserDefinitions import com.intellij.lang.PsiBuilder import com.intellij.lang.PsiBuilderFactory import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.openapi.project.Project import org.rust.lang.RsLanguage import org.rust.lang.core.psi.RsElementTypes fun Project.createRustPsiBuilder(text: CharSequence): PsiBuilder { val parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(RsLanguage) ?: error("No parser definition for language $RsLanguage") val lexer = parserDefinition.createLexer(this) return PsiBuilderFactory.getInstance().createBuilder(parserDefinition, lexer, text) } /** Creates [PsiBuilder] suitable for Grammar Kit generated methods */ fun Project.createAdaptedRustPsiBuilder(text: CharSequence): PsiBuilder { val b = GeneratedParserUtilBase.adapt_builder_( RsElementTypes.FUNCTION, createRustPsiBuilder(text), RustParser(), RustParser.EXTENDS_SETS_ ) // Equivalent to `GeneratedParserUtilBase.enter_section_`. // Allows to call `RustParser.*` methods without entering the section GeneratedParserUtilBase.ErrorState.get(b).currentFrame = GeneratedParserUtilBase.Frame() return b } inline fun <T> PsiBuilder.probe(action: () -> T): T { val mark = mark() try { return action() } finally { mark.rollbackTo() } } fun PsiBuilder.rawLookupText(steps: Int): CharSequence { val start = rawTokenTypeStart(steps) val end = rawTokenTypeStart(steps + 1) return if (start == -1 || end == -1) "" else originalText.subSequence(start, end) } fun PsiBuilder.Marker.close(result: Boolean): Boolean { if (result) { drop() } else { rollbackTo() } return result }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
1,925
intellij-rust
MIT License
app/src/main/java/com/skydoves/githubfollows/view/adapter/GithubUserAdapter.kt
morristech
119,827,224
true
{"Kotlin": 55251, "Java": 16814}
package com.skydoves.githubfollows.view.adapter import android.view.View import com.skydoves.githubfollows.R import com.skydoves.githubfollows.models.Follower import com.skydoves.githubfollows.models.GithubUser import com.skydoves.githubfollows.view.viewholder.BaseViewHolder import com.skydoves.githubfollows.view.viewholder.GithubUserHeaderViewHolder import com.skydoves.githubfollows.view.viewholder.GithubUserViewHolder /** * Developed by skydoves on 2018-01-21. * Copyright (c) 2018 skydoves rights reserved. */ class GithubUserAdapter(val delegate_header: GithubUserHeaderViewHolder.Delegate, val delegate: GithubUserViewHolder.Delegate) : BaseAdapter() { private val section_header = 0 private val section_follower = 1 init { addSection(ArrayList<GithubUser>()) addSection(ArrayList<Follower>()) } fun updateHeader(githubUser: GithubUser) { sections[section_header].clear() sections[section_header].add(githubUser) notifyDataSetChanged() } fun addFollowList(followers: List<Follower>) { sections[section_follower].addAll(followers) notifyDataSetChanged() } fun clearAll() { sections[section_header].clear() sections[section_follower].clear() notifyDataSetChanged() } override fun layout(sectionRow: BaseAdapter.SectionRow): Int { when(sectionRow.section()) { section_header -> return R.layout.layout_detail_header else -> return R.layout.item_github_user } } override fun viewHolder(layout: Int, view: View): BaseViewHolder { when(layout) { R.layout.layout_detail_header -> return GithubUserHeaderViewHolder(view, delegate_header) else -> return GithubUserViewHolder(view, delegate) } } }
0
Kotlin
0
0
cd4b4aa8b215aadac4cafa62c5b15b687446ecfd
1,849
GithubFollows
MIT License
app/src/main/java/academy/bangkit/lanting/di/RemoteModule.kt
fhrii
368,801,393
false
null
package academy.bangkit.lanting.di import academy.bangkit.lanting.data.remote.RemoteAPI import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) class RemoteModule { @Provides fun provideAPIService() = RemoteAPI.Service }
1
Kotlin
1
1
224efe4e6cda949249e0b543aac56e9d5d57cd35
342
lanting
MIT License
app/src/main/java/com/example/android/guesstheword/MainActivity.kt
joyce93
225,303,031
false
null
/* * Copyright (C) 2019 Google 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.example.android.guesstheword import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders /** * Creates an Activity that hosts all of the fragments in the app */ class MainActivity : AppCompatActivity() { lateinit var vModel: MyDataModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) //vModel = ViewModelProviders.of(this).get(myDataModel::class.java) display() //btnAdd.setOnClickListener(){ vModel.count++ //txView.setText(VModel.count.toString()) } } fun display(){ // txtView.text = vModel.count.toSting() } }
1
null
1
1
5d410b03d2fc4ac62022326810aa2281b1e9dce9
1,372
GuessTheWord-Starter
Apache License 2.0
guides/micronaut-data-access-mybatis/kotlin/src/test/kotlin/example/micronaut/GenreControllerTest.kt
micronaut-projects
326,986,278
false
null
package example.micronaut import example.micronaut.domain.Genre import example.micronaut.genre.GenreSaveCommand import example.micronaut.genre.GenreUpdateCommand import io.micronaut.core.type.Argument import io.micronaut.http.HttpHeaders import io.micronaut.http.HttpRequest import io.micronaut.http.HttpResponse import io.micronaut.http.HttpStatus.CREATED import io.micronaut.http.HttpStatus.NO_CONTENT import io.micronaut.http.client.BlockingHttpClient import io.micronaut.http.client.HttpClient import io.micronaut.http.client.annotation.Client import io.micronaut.http.client.exceptions.HttpClientResponseException import io.micronaut.http.uri.UriBuilder import io.micronaut.http.uri.UriTemplate import io.micronaut.test.extensions.junit5.annotation.MicronautTest import jakarta.inject.Inject import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import java.util.Collections @MicronautTest // <1> class GenreControllerTest { @Inject @field:Client("/") lateinit var httpClient: HttpClient // <2> @Test fun supplyAnInvalidOrderTriggersValidationFailure() { assertThrows(HttpClientResponseException::class.java) { client.retrieve( HttpRequest.GET<Any>("/genres/list?order=foo"), Argument.of(List::class.java, Genre::class.java)) } } @Test fun testFindNonExistingGenreReturns404() { assertThrows(HttpClientResponseException::class.java) { client.retrieve(HttpRequest.GET<Any>("/genres/99"), Argument.of(Genre::class.java)) } } @Test fun testGenreCrudOperations() { val genreIds = mutableListOf<Long>() var response = saveGenre("DevOps") genreIds.add(entityId(response)!!) assertEquals(CREATED, response.status) response = saveGenre("Microservices") // <3> assertEquals(CREATED, response.status) val id = entityId(response) genreIds.add(id!!) var genre = show(id) assertEquals("Microservices", genre.name) response = update(id, "Micro-services") assertEquals(NO_CONTENT, response.status) genre = show(id) assertEquals("Micro-services", genre.name) var genres = listGenres(ListingArguments.builder().build()) assertEquals(2, genres.size) genres = listGenres(ListingArguments.builder().max(1).build()) assertEquals(1, genres.size) assertEquals("DevOps", genres[0].name) genres = listGenres(ListingArguments.builder().max(1).order("desc").sort("name").build()) assertEquals(1, genres.size) assertEquals("Micro-services", genres[0].name) genres = listGenres(ListingArguments.builder().max(1).offset(10).build()) assertEquals(0, genres.size) // cleanup: for (genreId in genreIds) { response = delete(genreId) assertEquals(NO_CONTENT, response.status) } } private fun listGenres(args: ListingArguments): List<Genre> { val uri = args.of(UriBuilder.of("/genres/list")) val request: HttpRequest<*> = HttpRequest.GET<Any>(uri) return client.retrieve(request, Argument.of(List::class.java, Genre::class.java)) as List<Genre> // <4> } private fun show(id: Long?): Genre { val uri = UriTemplate.of("/genres/{id}").expand(Collections.singletonMap<String, Any?>("id", id)) val request: HttpRequest<*> = HttpRequest.GET<Any>(uri) return client.retrieve(request, Genre::class.java) } private fun update(id: Long?, name: String): HttpResponse<Any> { val request: HttpRequest<*> = HttpRequest.PUT("/genres", GenreUpdateCommand(id!!, name)) return client.exchange(request) // <5> } private fun delete(id: Long): HttpResponse<Any> { val request: HttpRequest<*> = HttpRequest.DELETE<Any>("/genres/$id") return client.exchange(request) } private fun entityId(response: HttpResponse<Any>): Long? { val value = response.header(HttpHeaders.LOCATION) ?: return null val path = "/genres/" val index = value.indexOf(path) return if (index != -1) { java.lang.Long.valueOf(value.substring(index + path.length)) } else null } private val client: BlockingHttpClient get() = httpClient.toBlocking() private fun saveGenre(genre: String): HttpResponse<Any> { val request: HttpRequest<*> = HttpRequest.POST("/genres", GenreSaveCommand(genre)) // <3> return client.exchange(request) } }
209
null
31
36
f40e50dc8f68cdb3080cb3802d8082ada9ca6787
4,650
micronaut-guides
Creative Commons Attribution 4.0 International
application/KotlinConcepts/app/src/main/java/com/istudio/app/modules/module_demos/kotlin_annotations/utils/stringDef/UserStatus.kt
devrath
339,281,472
false
{"Kotlin": 478593, "Java": 3273}
package com.istudio.app.modules.module_demos.kotlin_annotations.utils.stringDef import androidx.annotation.StringDef object UserStatus { const val ACTIVE = "active" const val IN_ACTIVE = "inactive" const val BANNED = "banned" @Retention(AnnotationRetention.SOURCE) @StringDef(ACTIVE, IN_ACTIVE, BANNED) annotation class Status }
0
Kotlin
22
246
b87ccbc3cba789ec81744acde724274137204283
359
KotlinAlchemy
Apache License 2.0
src/main/kotlin/com/hakim/ui/broker/TestListener.kt
HaKIMus
511,521,860
false
null
package com.hakim.ui.broker import io.micronaut.configuration.kafka.annotation.KafkaKey import io.micronaut.configuration.kafka.annotation.KafkaListener import io.micronaut.configuration.kafka.annotation.OffsetReset import io.micronaut.configuration.kafka.annotation.Topic @KafkaListener(offsetReset = OffsetReset.EARLIEST) class TestListener { @Topic("test") fun receive(@KafkaKey key: String, message: String) { println("Received message: $message with key: $key") } }
0
Kotlin
0
0
68c85942634a099e6c83dae2341eb875eeb5037d
492
sparkles
MIT License
features/favorite-coins/src/commonMain/kotlin/com/mathroda/favorites/state/MarketState.kt
MathRoda
507,060,394
false
{"Kotlin": 446115, "Swift": 4323, "Ruby": 2379, "Java": 624}
package com.mathroda.favorites.state import com.mathroda.domain.CoinById data class MarketState( private val loading: Boolean = false, val coin: CoinById? = null, val error: String = "" ) { val isLoading: Boolean get() = loading && coin != null }
0
Kotlin
41
297
cf303ba50bad35a816253bee5b27beee5ea364b8
273
DashCoin
Apache License 2.0
app/src/main/java/id/co/woiapp/data/remote/service/LoginService.kt
bintangeditya
340,482,979
false
null
package id.co.woiapp.data.remote.service import id.co.woiapp.data.entities.Book import id.co.woiapp.data.entities.RootResponse import id.co.woiapp.data.entities.User import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST interface LoginService { // @GET("book/userId/6") // suspend fun login() : Response<RootResponse<Book>> @POST("user/login") suspend fun login(@Body body:User) : Response<RootResponse<User>> }
0
Kotlin
0
0
a88ef6c24baa270b03c3637d4f95beb335316e5b
479
WorkOnItApp
Apache License 2.0
app/src/main/java/com/example/instagramclone/main/MyPostsScreen.kt
slatqh
700,506,198
false
{"Kotlin": 67631}
package com.devkm.snapmania.main import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.devkm.snapmania.DestinationScreen import com.devkm.snapmania.R import com.devkm.snapmania.SnapManiaViewModel import com.devkm.snapmania.data.PostData data class PostRow( var post1: PostData? = null, var post2: PostData? = null, var post3: PostData? = null ) { fun isFull() = post1 != null && post2 != null && post3 != null fun add(post: PostData) { if (post1 == null) { post1 = post } else if (post2 == null) { post2 = post } else if (post3 == null) { post3 = post } } } @Composable fun MyPostsScreen(navController: NavController, viewModel: SnapManiaViewModel) { val newPostImageLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent(), ) { uri -> uri.let { val encoded = Uri.encode(uri.toString()) val route = DestinationScreen.NewPost.createRoute(encoded) navController.navigate(route) } } val userData = viewModel.userData.value val isLoading = viewModel.inProgress.value val postsLoading = viewModel.refreshPostsProgress.value val posts = viewModel.posts.value Column { Column(modifier = Modifier.weight(1f)) { Row { ProfileImage(userData?.imageUrl) { newPostImageLauncher.launch("image/*") } Text( text = "32\nposts", modifier = Modifier .weight(1f) .align(Alignment.CenterVertically), textAlign = TextAlign.Center ) Text( text = "$23\nfollowers", modifier = Modifier .weight(1f) .align(Alignment.CenterVertically), textAlign = TextAlign.Center ) Text( text = "${userData?.following?.size ?: 0}\nfollowing", modifier = Modifier .weight(1f) .align(Alignment.CenterVertically), textAlign = TextAlign.Center ) } Column(modifier = Modifier.padding(8.dp)) { val usernameDisplay = if (userData?.userName == null) "" else "@${userData.userName}" Text(text = userData?.name ?: "", fontWeight = FontWeight.Bold) Text(text = usernameDisplay) Text(text = userData?.bio ?: "") } OutlinedButton( onClick = { navigateTo(navController, DestinationScreen.Profile) }, modifier = Modifier .padding(8.dp) .fillMaxWidth(), colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent), elevation = ButtonDefaults.buttonElevation( defaultElevation = 0.dp, pressedElevation = 0.dp, disabledElevation = 0.dp ), shape = RoundedCornerShape(10) ) { Text(text = "Edit Profile", color = Color.Black) } PostList( isContextLoading = isLoading, postsLoading = postsLoading, posts = posts, modifier = Modifier .weight(1f) .padding(1.dp) .fillMaxSize() ) { post -> navigateTo( navController = navController, DestinationScreen.SinglePost, NavParam("post", post) ) } } BottomNavigationMenu( selectedItem = BottomNavigationItem.POSTS, navController = navController ) } if (isLoading) CommonProgressSpinner() } @Composable fun ProfileImage(imageUrl: String?, onClick: () -> Unit) { Box(modifier = Modifier .padding(top = 16.dp) .clickable { onClick.invoke() }) { UserImageCard( userImage = imageUrl, modifier = Modifier .padding(8.dp) .size(80.dp) ) Card( shape = CircleShape, border = BorderStroke(width = 2.dp, color = Color.White), modifier = Modifier .size(32.dp) .align(Alignment.BottomEnd) .padding(bottom = 8.dp, end = 8.dp) ) { Image( painter = painterResource(id = R.drawable.baseline_add_24), contentDescription = null, modifier = Modifier .background(Color.Blue) ) } } } @Composable fun PostList( isContextLoading: Boolean, postsLoading: Boolean, posts: List<PostData>, modifier: Modifier, onPostClick: (PostData) -> Unit ) { if (postsLoading) { CommonProgressSpinner() } else if (posts.isEmpty()) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { if (!isContextLoading) Text(text = "No posts available") } } else { LazyColumn(modifier = modifier) { val rows = arrayListOf<PostRow>() var currentRow = PostRow() rows.add(currentRow) for (post in posts) { if (currentRow.isFull()) { currentRow = PostRow() rows.add(currentRow) } currentRow.add(post = post) } items(items = rows) { row -> PostsRow(item = row, onPostClick = onPostClick) } } } } @Composable fun PostsRow(item: PostRow, onPostClick: (PostData) -> Unit) { Row( modifier = Modifier .fillMaxWidth() .height(120.dp) ) { PostImage(imageUrl = item.post1?.postImage, modifier = Modifier .weight(1f) .clickable { item.post1?.let { post -> onPostClick(post) } } ) PostImage(imageUrl = item.post2?.postImage, modifier = Modifier .weight(1f) .clickable { item.post2?.let { post -> onPostClick(post) } } ) PostImage(imageUrl = item.post3?.postImage, modifier = Modifier .weight(1f) .clickable { item.post3?.let { post -> onPostClick(post) } } ) } } @Composable fun PostImage(imageUrl: String?, modifier: Modifier) { Box(modifier = modifier) { var modifier = Modifier .padding(1.dp) .fillMaxSize() if (imageUrl == null) { modifier = modifier.clickable(enabled = false) {} } CommonImage(data = imageUrl, modifier = modifier, contentScale = ContentScale.Crop) } }
0
Kotlin
0
0
b1222df400489503f3f47e31b6a1485f58f9c14e
8,680
instagramClone-Android
MIT License
src/main/kotlin/com/bridgecrew/analytics/AnalyticsService.kt
bridgecrewio
644,310,885
false
null
package com.bridgecrew.analytics import com.bridgecrew.services.scan.FullScanStateService import com.bridgecrew.services.scan.ScanTaskResult import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import java.text.SimpleDateFormat import java.util.Date import java.util.concurrent.TimeUnit @Service class AnalyticsService(val project: Project) { private val LOG = logger<AnalyticsService>() var fullScanData: FullScanAnalyticsData? = null private var fullScanNumber = 0 var wereFullScanResultsDisplayed = false var wereSingleFileScanResultsDisplayed = false val wereResultsDisplayed get() = (wereSingleFileScanResultsDisplayed || wereFullScanResultsDisplayed) fun fullScanButtonWasPressed() { val fullScanButtonWasPressedDate = Date() fullScanNumber += 1 LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - full scan button was pressed") fullScanData = FullScanAnalyticsData(fullScanNumber) fullScanData!!.buttonPressedTime = fullScanButtonWasPressedDate } fun fullScanStarted() { LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - full scan started") fullScanData!!.scanStartedTime = Date() } fun fullScanByFrameworkStarted(framework: String) { LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - full scan started for framework $framework") fullScanData!!.frameworksScanTime[framework] = FullScanFrameworkScanTimeData(Date()) } fun fullScanByFrameworkFinished(framework: String) { fullScanData!!.frameworksScanTime[framework]!!.endTime = Date() fullScanData!!.frameworksScanTime[framework]!!.totalTimeMinutes = fullScanData!!.frameworksScanTime[framework]!!.endTime.time - fullScanData!!.frameworksScanTime[framework]!!.startTime.time LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - full scan finished for framework $framework and took ${fullScanData!!.frameworksScanTime[framework]!!.totalTimeMinutes} ms") } fun fullScanFinished() { fullScanData!!.scanFinishedTime = Date() LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - full scan finished") } fun fullScanFrameworkFinishedNoErrors(framework: String) { LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - framework $framework finished with no errors") } fun fullScanResultsWereFullyDisplayed() { if (fullScanData!!.isFullScanFinished()) { fullScanData!!.resultsWereFullyDisplayedTime = Date() LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - full scan results are fully displayed") logFullScanAnalytics() wereFullScanResultsDisplayed = true } } fun singleFileScanResultsWereFullyDisplayed() { wereSingleFileScanResultsDisplayed = true } fun fullScanFrameworkError(framework: String) { LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - error while scanning framework $framework") } fun fullScanFrameworkDetectedVulnerabilities(framework: String, numberOfVulnerabilities: Int) { LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - $numberOfVulnerabilities security issues were detected while scanning framework $framework") } fun fullScanParsingError(framework: String, failedFilesSize: Int) { LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - parsing error while scanning framework $framework in $failedFilesSize files}") } private fun logFullScanAnalytics() { var maximumScanFramework = 0L var minimumScanFramework = 0L var maximumFramework = "" var minimumFramework = "" fullScanData!!.frameworksScanTime.forEach { framework -> if (framework.value.totalTimeMinutes >= maximumScanFramework) { maximumScanFramework = framework.value.totalTimeMinutes maximumFramework = framework.key if (minimumFramework.isEmpty()) { minimumScanFramework = framework.value.totalTimeMinutes minimumFramework = framework.key } } if (framework.value.totalTimeMinutes <= minimumScanFramework) { minimumScanFramework = framework.value.totalTimeMinutes minimumFramework = framework.key } } val dateFormatter = SimpleDateFormat("dd/M/yyyy hh:mm:ss") val frameworkScansFinishedWithErrors: MutableMap<String, ScanTaskResult> = project.service<FullScanStateService>().frameworkScansFinishedWithErrors LOG.info("Prisma Cloud Plugin Analytics - scan #${fullScanNumber} - full scan analytics:\n" + "full scan took ${formatTimeAsString(fullScanData!!.buttonPressedTime, fullScanData!!.resultsWereFullyDisplayedTime)} minutes from pressing on the scan button to fully display the results\n" + "full scan took ${formatTimeAsString(fullScanData!!.scanStartedTime, fullScanData!!.scanFinishedTime)} minutes from starting Prisma Cloud scans and finishing Prisma Cloud scans for all frameworks\n" + "full scan took ${formatTimeAsString(fullScanData!!.buttonPressedTime, fullScanData!!.scanStartedTime)} minutes from pressing on the scan button to starting Prisma Cloud scan\n" + "full scan took ${formatTimeAsString(fullScanData!!.scanFinishedTime, fullScanData!!.resultsWereFullyDisplayedTime)} minutes from finishing Prisma Cloud scans for all frameworks to fully display the results\n" + "framework scan $maximumFramework took the most - ${formatTimeAsString(fullScanData!!.frameworksScanTime[maximumFramework]!!.startTime, fullScanData!!.frameworksScanTime[maximumFramework]!!.endTime)} minutes\n" + "framework scan $minimumFramework took the least - ${formatTimeAsString(fullScanData!!.frameworksScanTime[minimumFramework]!!.startTime, fullScanData!!.frameworksScanTime[minimumFramework]!!.endTime)} minutes\n" + "${frameworkScansFinishedWithErrors.size} frameworks was finished with errors: ${frameworkScansFinishedWithErrors.keys}\n" + "frameworks scans:\n" + "${fullScanData!!.frameworksScanTime.map { (framework, scanResults) -> "framework $framework took ${formatTimeAsString(scanResults.startTime, scanResults.endTime)} minutes to be scanned\n" } }\n" + "full scan button pressed on ${dateFormatter.format(fullScanData!!.buttonPressedTime)}\n" + "full scan started on ${dateFormatter.format(fullScanData!!.scanStartedTime)}\n" + "full scan finished on ${dateFormatter.format(fullScanData!!.scanFinishedTime)}\n" + "full scan results displayed on ${dateFormatter.format(fullScanData!!.resultsWereFullyDisplayedTime)}\n" ) } private fun formatTimeAsString(startTime: Date, endTime: Date): String { val minutes = TimeUnit.MILLISECONDS.toMinutes(endTime.time - startTime.time) val seconds = TimeUnit.MILLISECONDS.toSeconds(endTime.time - startTime.time) - (minutes * 60) val secondsString = if (seconds < 10) { "0${seconds}" } else "${seconds}" return "${minutes}:${secondsString}" } data class FullScanAnalyticsData(val scanNumber: Int) { lateinit var buttonPressedTime: Date lateinit var scanStartedTime: Date val frameworksScanTime: MutableMap<String, FullScanFrameworkScanTimeData> = mutableMapOf() lateinit var scanFinishedTime: Date lateinit var resultsWereFullyDisplayedTime: Date fun isFullScanFinished() = ::scanFinishedTime.isInitialized fun isFullScanStarted() = ::scanStartedTime.isInitialized } data class FullScanFrameworkScanTimeData(val startTime: Date) { var endTime: Date = Date() var totalTimeMinutes = 0L } }
11
Kotlin
0
0
890fd364497db79b125490b0cd074443318b90a5
8,185
prisma-cloud-jetbrains-ide
Apache License 2.0
shared/src/commonMain/kotlin/util/ImageProvider.kt
mbakgun
629,040,507
false
{"Kotlin": 63999, "Ruby": 2296, "Swift": 771, "HTML": 453, "Shell": 228}
package util import androidx.compose.ui.unit.Dp data class ImageProvider(val columnCount: Int, val itemHeight: Dp) internal expect fun getImageProvider(): ImageProvider
2
Kotlin
19
220
9d1de4c3dcddf23cdba4a94bbb213f07eb81c608
172
midjourney-images-compose-multiplatform
MIT License
src/main/kotlin/slatemagic/shape/spring/SpellShapeFrame.kt
Jempasam
717,593,852
false
{"Kotlin": 146073, "Java": 1020}
package slabmagic.shape.spring import slabmagic.shape.SpellShape import slabmagic.shape.painter.GraphicsPainter import java.awt.Color import java.awt.Graphics import javax.swing.JPanel class SpellShapeFrame(val shape: SpellShape, val color: Color): JPanel(){ override fun paint(g: Graphics) { super.paint(g) val b=g.clipBounds g.color= Color.BLACK g.fillRect(0,0,b.width,b.height) val drawer= GraphicsPainter(g, color, b.width/2-b.height*3/8, b.height/2-b.height*3/8, b.height*3/4, b.height*3/4 ) shape.draw(drawer, System.currentTimeMillis()/1000.0) } }
0
Kotlin
0
0
c91b03b212ea6be392fa3723183fd27b1ef7f8e2
658
SlateMagic
Creative Commons Zero v1.0 Universal
src/test/kotlin/common/UnitTest.kt
HugoTigre
169,423,160
false
null
package common import org.junit.jupiter.api.Tag import org.junit.jupiter.api.extension.ExtendWith import org.mockito.junit.jupiter.MockitoExtension @ExtendWith(MockitoExtension::class) @Tag("integration") annotation class IntegrationTest
0
Kotlin
0
0
423f06cb5cc6ff09dee9b6bd1504087a525d84ba
240
demo-kafka-cli
MIT License
app/src/main/java/zlc/season/bracerapp/MainActivity.kt
df13954
326,544,320
true
{"Kotlin": 50466}
package zlc.season.bracerapp import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import zlc.season.bracer.start class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { ParamsActivity().apply { }.start(this) } button2.setOnClickListener { MutableParamsActivity().start(this) } } }
0
null
0
0
5d11c1f2ab6f70d66a2046cf5d981aeb208eec03
580
Bracer
Apache License 2.0
compiler/testData/diagnostics/tests/constantEvaluator/isPure/unaryMinusIndepWoExpType.kt
JetBrains
3,432,266
false
null
package test // val p1: true <!DEBUG_INFO_CONSTANT_VALUE("true")!>val p1 = -1<!> // val p2: false <!DEBUG_INFO_CONSTANT_VALUE("false")!>val p2 = -1.toLong()<!> // val p3: false <!DEBUG_INFO_CONSTANT_VALUE("false")!>val p3 = -1.toByte()<!> // val p4: false <!DEBUG_INFO_CONSTANT_VALUE("false")!>val p4 = -1.toInt()<!> // val p5: false <!DEBUG_INFO_CONSTANT_VALUE("false")!>val p5 = -1.toShort()<!>
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
402
kotlin
Apache License 2.0
drop-in/src/main/java/com/adyen/checkout/dropin/internal/ui/ActionComponentDialogFragment.kt
Adyen
91,104,663
false
null
/* * Copyright (c) 2022 Adyen N.V. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by josephj on 31/8/2022. */ package com.adyen.checkout.dropin.internal.ui import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.fragment.app.viewModels import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import com.adyen.checkout.action.core.GenericActionComponent import com.adyen.checkout.action.core.internal.provider.GenericActionComponentProvider import com.adyen.checkout.components.core.ActionComponentCallback import com.adyen.checkout.components.core.ActionComponentData import com.adyen.checkout.components.core.CheckoutConfiguration import com.adyen.checkout.components.core.ComponentError import com.adyen.checkout.components.core.action.Action import com.adyen.checkout.core.AdyenLogLevel import com.adyen.checkout.core.PermissionHandlerCallback import com.adyen.checkout.core.exception.CancellationException import com.adyen.checkout.core.exception.CheckoutException import com.adyen.checkout.core.internal.util.adyenLog import com.adyen.checkout.dropin.R import com.adyen.checkout.dropin.databinding.FragmentGenericActionComponentBinding import com.adyen.checkout.dropin.internal.util.arguments import com.google.android.material.bottomsheet.BottomSheetBehavior import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import com.adyen.checkout.ui.core.R as UICoreR @SuppressWarnings("TooManyFunctions") internal class ActionComponentDialogFragment : DropInBottomSheetDialogFragment(), ActionComponentCallback { private var _binding: FragmentGenericActionComponentBinding? = null private val binding: FragmentGenericActionComponentBinding get() = requireNotNull(_binding) private val actionComponentViewModel: ActionComponentViewModel by viewModels() private val action: Action by arguments(ACTION) private val checkoutConfiguration: CheckoutConfiguration by arguments(CHECKOUT_CONFIGURATION) private lateinit var actionComponent: GenericActionComponent private var permissionCallback: PermissionHandlerCallback? = null private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { resultsMap -> resultsMap.firstNotNullOf { result -> val requestedPermission = result.key val isGranted = result.value if (isGranted) { adyenLog(AdyenLogLevel.DEBUG) { "Permission $requestedPermission granted" } permissionCallback?.onPermissionGranted(requestedPermission) } else { adyenLog(AdyenLogLevel.DEBUG) { "Permission $requestedPermission denied" } permissionCallback?.onPermissionDenied(requestedPermission) } permissionCallback = null } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) adyenLog(AdyenLogLevel.DEBUG) { "onCreate" } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentGenericActionComponentBinding.inflate(inflater) setInitViewState(BottomSheetBehavior.STATE_EXPANDED) return binding.root } override fun onCreateDialog(savedInstanceState: Bundle?) = super.onCreateDialog(savedInstanceState).apply { window?.setWindowAnimations(UICoreR.style.AdyenCheckout_BottomSheet_NoWindowEnterDialogAnimation) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adyenLog(AdyenLogLevel.DEBUG) { "onViewCreated" } initObservers() binding.header.isVisible = false try { val analyticsManager = dropInViewModel.analyticsManager val dropInOverrideParams = dropInViewModel.getDropInOverrideParams() actionComponent = GenericActionComponentProvider(analyticsManager, dropInOverrideParams).get( fragment = this, checkoutConfiguration = checkoutConfiguration, callback = this, ) actionComponent.setOnRedirectListener { protocol.onRedirect() } if (shouldFinishWithAction()) { binding.buttonFinish.apply { isVisible = true setOnClickListener { protocol.finishWithAction() } } } binding.componentView.attach(actionComponent, viewLifecycleOwner) } catch (e: CheckoutException) { handleError(ComponentError(e)) } } override fun onAdditionalDetails(actionComponentData: ActionComponentData) { onActionComponentDataChanged(actionComponentData) } override fun onError(componentError: ComponentError) { adyenLog(AdyenLogLevel.DEBUG) { "onError" } handleError(componentError) } override fun onPermissionRequest(requiredPermission: String, permissionCallback: PermissionHandlerCallback) { this.permissionCallback = permissionCallback adyenLog(AdyenLogLevel.DEBUG) { "Permission request information dialog shown" } AlertDialog.Builder(requireContext()) .setTitle(R.string.checkout_rationale_title_storage_permission) .setMessage(R.string.checkout_rationale_message_storage_permission) .setOnDismissListener { adyenLog(AdyenLogLevel.DEBUG) { "Permission $requiredPermission requested" } requestPermissionLauncher.launch(arrayOf(requiredPermission)) } .setPositiveButton(UICoreR.string.error_dialog_button) { dialog, _ -> dialog.dismiss() } .show() } private fun initObservers() { actionComponentViewModel.eventsFlow .flowWithLifecycle(viewLifecycleOwner.lifecycle) .onEach { when (it) { ActionComponentFragmentEvent.HANDLE_ACTION -> { handleAction(action) } } } .launchIn(viewLifecycleOwner.lifecycleScope) } fun handleAction(action: Action) { actionComponent.handleAction(action, requireActivity()) } override fun onBackPressed(): Boolean { // polling will be canceled by lifecycle event when { shouldFinishWithAction() -> { protocol.finishWithAction() } dropInViewModel.shouldSkipToSinglePaymentMethod() -> { protocol.terminateDropIn() } else -> { protocol.showPaymentMethodsDialog() } } return true } override fun onCancel(dialog: DialogInterface) { adyenLog(AdyenLogLevel.DEBUG) { "onCancel" } if (shouldFinishWithAction()) { protocol.finishWithAction() } else { protocol.terminateDropIn() } } private fun onActionComponentDataChanged(actionComponentData: ActionComponentData?) { adyenLog(AdyenLogLevel.DEBUG) { "onActionComponentDataChanged" } if (actionComponentData != null) { protocol.requestDetailsCall(actionComponentData) } } private fun handleError(componentError: ComponentError) { when (componentError.exception) { is CancellationException -> { adyenLog(AdyenLogLevel.DEBUG) { "Flow was cancelled by user" } onBackPressed() } else -> { adyenLog(AdyenLogLevel.ERROR) { componentError.errorMessage } protocol.showError(null, getString(R.string.action_failed), componentError.errorMessage, true) } } } private fun shouldFinishWithAction(): Boolean { return !GenericActionComponent.PROVIDER.providesDetails(action) } fun handleIntent(intent: Intent) { adyenLog(AdyenLogLevel.DEBUG) { "handleAction" } actionComponent.handleIntent(intent) } override fun onDestroyView() { _binding = null super.onDestroyView() } companion object { private const val ACTION = "ACTION" private const val CHECKOUT_CONFIGURATION = "CHECKOUT_CONFIGURATION" fun newInstance( action: Action, checkoutConfiguration: CheckoutConfiguration, ): ActionComponentDialogFragment { return ActionComponentDialogFragment().apply { arguments = Bundle().apply { putParcelable(ACTION, action) putParcelable(CHECKOUT_CONFIGURATION, checkoutConfiguration) } } } } }
36
null
66
120
2e4fe733c112518b9ec75fcf2dca1aaa711b2458
9,207
adyen-android
MIT License
app/src/test/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsUtilsTest.kt
graffiti75
617,140,886
false
null
package com.example.android.architecture.blueprints.todoapp.statistics import com.example.android.architecture.blueprints.todoapp.data.Task import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertEquals import org.junit.Test class StatisticsUtilsTest { /** * If there's no completed task and one active task, * then there are 100% percent active tasks and 0% completed tasks. */ @Test fun getActiveAndCompletedStats_noCompleted_returnsHundredZero() { // Create an active tasks (the false makes this active) val tasks = listOf<Task>( Task("title", "desc", isCompleted = false) ) // Call our function val result = getActiveAndCompletedStats(tasks) // Check the result assertThat(result.completedTasksPercent, `is`(0f)) // assertEquals(result.completedTasksPercent, 0f) assertThat(result.activeTasksPercent, `is`(100f)) // assertEquals(result.activeTasksPercent, 100f) } /** * If there's 2 completed tasks and 3 active tasks, * then there are 40% percent completed tasks and 60% active tasks. */ @Test fun getActiveAndCompletedStats_both_returnsFortySixty() { // Create an active tasks (the false makes this active) val tasks = listOf<Task>( Task("title", "desc", isCompleted = true), Task("title", "desc", isCompleted = true), Task("title", "desc", isCompleted = false), Task("title", "desc", isCompleted = false), Task("title", "desc", isCompleted = false) ) // Call our function val result = getActiveAndCompletedStats(tasks) // Check the result assertEquals(result.completedTasksPercent, 40f) assertEquals(result.activeTasksPercent, 60f) } @Test fun getActiveAndCompletedStats_empty_returnsZeros() { // Create an active tasks (the false makes this active) val tasks = emptyList<Task>() // Call our function val result = getActiveAndCompletedStats(tasks) // Check the result assertEquals(result.completedTasksPercent, 0f) assertEquals(result.activeTasksPercent, 0f) } @Test fun getActiveAndCompletedStats_error_returnsZeros() { // Create an active tasks (the false makes this active) val tasks = null // Call our function val result = getActiveAndCompletedStats(tasks) // Check the result assertEquals(result.completedTasksPercent, 0f) assertEquals(result.activeTasksPercent, 0f) } }
0
Kotlin
0
0
86ee2e29f4edaed26cefcf56cee6445623c8391d
2,366
ToDoTesting
Apache License 2.0
player/src/main/java/com/gang/test/player/dtpv/youtube/views/CircleClipTapView.kt
pacoblack
607,573,689
false
{"Gradle": 5, "JSON": 864, "Java Properties": 8, "Markdown": 5, "Shell": 2, "Text": 24, "HTML": 1, "Batchfile": 2, "INI": 8, "Proguard": 11, "XML": 556, "Kotlin": 191, "Java": 335, "SQL": 4, "Unix Assembly": 2, "Motorola 68K Assembly": 9, "Ignore List": 1}
package com.ntduc.videoplayer.video.player.dtpv.youtube.views import android.animation.Animator import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.view.View import androidx.core.content.ContextCompat import com.ntduc.videoplayer.R /** * View class * * Draws a arc shape and provides a circle scaling animation. * Used by [YouTubeOverlay][com.github.vkay94.dtpv.youtube.YouTubeOverlay]. */ class CircleClipTapView(context: Context, attrs: AttributeSet?) : View(context, attrs) { private val backgroundPaint: Paint = Paint() private val circlePaint: Paint = Paint() private var widthPx: Int private var heightPx: Int // Background private val shapePath: Path private var isLeft: Boolean // Circle private var cX: Float private var cY: Float private var currentRadius: Float private var minRadius: Int private var maxRadius: Int // Animation private var valueAnimator: ValueAnimator? private var forceReset: Boolean private var arcSize: Float /* Getter and setter */ var performAtEnd: Runnable init { widthPx = 0 heightPx = 0 // Background shapePath = Path() isLeft = true cX = 0f cY = 0f currentRadius = 0f minRadius = 0 maxRadius = 0 valueAnimator = null forceReset = false backgroundPaint.style = Paint.Style.FILL backgroundPaint.isAntiAlias = true backgroundPaint.color = ContextCompat.getColor( context, R.color.dtpv_yt_background_circle_color ) circlePaint.style = Paint.Style.FILL circlePaint.isAntiAlias = true circlePaint.color = ContextCompat.getColor(context, R.color.dtpv_yt_tap_circle_color) // Pre-configuations depending on device display metrics val dm = context.resources.displayMetrics widthPx = dm.widthPixels heightPx = dm.heightPixels minRadius = (30f * dm.density).toInt() maxRadius = (400f * dm.density).toInt() updatePathShape() valueAnimator = circleAnimator arcSize = 80f performAtEnd = Runnable { } } fun getArcSize(): Float { return arcSize } fun setArcSize(value: Float) { arcSize = value updatePathShape() } var circleBackgroundColor: Int get() = backgroundPaint.color set(value) { backgroundPaint.color = value } var circleColor: Int get() = circlePaint.color set(value) { circlePaint.color = value } var animationDuration: Long get() = if (valueAnimator != null) valueAnimator!!.duration else 650L set(value) { circleAnimator!!.duration = value } /* Methods */ /* Circle */ fun updatePosition(x: Float, y: Float) { cX = x cY = y val newIsLeft = x <= (resources.displayMetrics.widthPixels / 2).toFloat() if (isLeft != newIsLeft) { isLeft = newIsLeft updatePathShape() } } private fun invalidateWithCurrentRadius(factor: Float) { currentRadius = minRadius.toFloat() + (maxRadius - minRadius).toFloat() * factor invalidate() } /* Background */ private fun updatePathShape() { val halfWidth = widthPx.toFloat() * 0.5f shapePath.reset() val w = if (isLeft) 0.0f else widthPx.toFloat() val f = if (isLeft) 1 else -1 shapePath.moveTo(w, 0.0f) shapePath.lineTo(f.toFloat() * (halfWidth - arcSize) + w, 0.0f) shapePath.quadTo( f.toFloat() * (halfWidth + arcSize) + w, heightPx.toFloat() / 2f, f.toFloat() * (halfWidth - arcSize) + w, heightPx.toFloat() ) shapePath.lineTo(w, heightPx.toFloat()) shapePath.close() invalidate() } /* Animation */ private val circleAnimator: ValueAnimator? get() { if (valueAnimator == null) { valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f) valueAnimator?.duration = animationDuration valueAnimator?.addUpdateListener { animation -> invalidateWithCurrentRadius( animation.animatedValue as Float ) } valueAnimator?.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator) { visibility = VISIBLE } override fun onAnimationEnd(animation: Animator) { if (!forceReset) performAtEnd.run() } override fun onAnimationCancel(animation: Animator) {} override fun onAnimationRepeat(animation: Animator) {} }) } return valueAnimator } fun resetAnimation(body: Runnable) { forceReset = true circleAnimator!!.end() body.run() forceReset = false circleAnimator!!.start() } fun endAnimation() { circleAnimator!!.end() } /* Others: Drawing and Measurements */ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) widthPx = w heightPx = h updatePathShape() } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) // Background canvas?.clipPath(shapePath) canvas?.drawPath(shapePath, backgroundPaint) // Circle canvas?.drawCircle(cX, cY, currentRadius, circlePaint) } }
0
Java
0
0
eab622a0f037418f1d8149139f5ac479f0845637
5,970
my_kotlin_android
Apache License 2.0
reactive-core-jakarta/src/test/kotlin/com/linecorp/kotlinjdsl/querydsl/where/ReactiveQueryDslImplWhereTest.kt
line
442,633,985
false
null
package com.linecorp.kotlinjdsl.querydsl.where import com.linecorp.kotlinjdsl.query.clause.where.WhereClause import com.linecorp.kotlinjdsl.query.spec.predicate.AndSpec import com.linecorp.kotlinjdsl.query.spec.predicate.OrSpec import com.linecorp.kotlinjdsl.query.spec.predicate.PredicateSpec import com.linecorp.kotlinjdsl.querydsl.QueryDslImpl import com.linecorp.kotlinjdsl.test.WithKotlinJdslAssertions import io.mockk.mockk import org.junit.jupiter.api.Test internal class QueryDslImplWhereTest : WithKotlinJdslAssertions { @Test fun noWhere() { // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause(PredicateSpec.empty) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause(PredicateSpec.empty) ) } @Test fun nullInWhere() { // given val predicateSpec: PredicateSpec? = null // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) where(predicateSpec) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause(PredicateSpec.empty) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause(PredicateSpec.empty) ) } @Test fun where() { // given val predicateSpec: PredicateSpec = mockk() // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) where(predicateSpec) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause(predicateSpec) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause(predicateSpec) ) } @Test fun whereAndVararg() { // given val nullPredicateSpec: PredicateSpec? = null val predicateSpec1: PredicateSpec = mockk() val predicateSpec2: PredicateSpec = mockk() // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) whereAnd(nullPredicateSpec, predicateSpec1, predicateSpec2) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause(AndSpec(listOf(predicateSpec1, predicateSpec2))) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause(AndSpec(listOf(predicateSpec1, predicateSpec2))) ) } @Test fun whereAndList() { // given val nullPredicateSpec: PredicateSpec? = null val predicateSpec1: PredicateSpec = mockk() val predicateSpec2: PredicateSpec = mockk() // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) whereAnd(listOf(nullPredicateSpec, predicateSpec1, predicateSpec2)) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause(AndSpec(listOf(predicateSpec1, predicateSpec2))) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause(AndSpec(listOf(predicateSpec1, predicateSpec2))) ) } @Test fun whereOrVararg() { // given val nullPredicateSpec: PredicateSpec? = null val predicateSpec1: PredicateSpec = mockk() val predicateSpec2: PredicateSpec = mockk() // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) whereOr(nullPredicateSpec, predicateSpec1, predicateSpec2) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause(OrSpec(listOf(predicateSpec1, predicateSpec2))) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause(OrSpec(listOf(predicateSpec1, predicateSpec2))) ) } @Test fun whereOrList() { // given val nullPredicateSpec: PredicateSpec? = null val predicateSpec1: PredicateSpec = mockk() val predicateSpec2: PredicateSpec = mockk() // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) whereOr(listOf(nullPredicateSpec, predicateSpec1, predicateSpec2)) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause(OrSpec(listOf(predicateSpec1, predicateSpec2))) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause(OrSpec(listOf(predicateSpec1, predicateSpec2))) ) } @Test fun wheres() { // given val nullPredicateSpec: PredicateSpec? = null val predicateSpec1: PredicateSpec = mockk() val predicateSpec2: PredicateSpec = mockk() // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) where(nullPredicateSpec) where(predicateSpec1) where(predicateSpec2) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause(AndSpec(listOf(predicateSpec1, predicateSpec2))) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause(AndSpec(listOf(predicateSpec1, predicateSpec2))) ) } @Test fun allTypeWheres() { // given val nullPredicateSpec: PredicateSpec? = null val predicateSpec1: PredicateSpec = mockk() val predicateSpec2: PredicateSpec = mockk() // when val actual = QueryDslImpl(Data1::class.java).apply { select(distinct = true, Data1::class.java) from(entity(Data1::class)) where(nullPredicateSpec) where(predicateSpec1) whereAnd(nullPredicateSpec, predicateSpec1, predicateSpec2) whereOr(nullPredicateSpec, predicateSpec1, predicateSpec2) } // then val criteriaQuerySpec = actual.createCriteriaQuerySpec() assertThat(criteriaQuerySpec.where).isEqualTo( WhereClause( AndSpec( listOf( predicateSpec1, AndSpec(listOf(predicateSpec1, predicateSpec2)), OrSpec(listOf(predicateSpec1, predicateSpec2)) ) ) ) ) val subquerySpec = actual.createSubquerySpec() assertThat(subquerySpec.where).isEqualTo( WhereClause( AndSpec( listOf( predicateSpec1, AndSpec(listOf(predicateSpec1, predicateSpec2)), OrSpec(listOf(predicateSpec1, predicateSpec2)) ) ) ) ) } class Data1 }
26
Kotlin
60
504
f28908bf432cf52f73a9573b1ac2be5eb4b2b7dc
8,415
kotlin-jdsl
Apache License 2.0
core/model/src/main/kotlin/ru/resodostudios/cashsense/core/model/data/Subscription.kt
f33lnothin9
674,320,726
false
null
package ru.resodostudios.cashsense.core.model.data import kotlinx.datetime.Instant import java.math.BigDecimal data class Subscription( val id: String, val title: String, val amount: BigDecimal, val currency: String, val paymentDate: Instant, val notificationDate: Instant?, val repeatingInterval: Long? )
0
null
3
8
0117df61689868a7c0196246e0fb4caaed3f1b5a
335
cashsense
Apache License 2.0
app/src/main/java/com/cindaku/nftar/modules/PicassoModule.kt
metacdq
564,567,451
false
{"Kotlin": 180571}
package com.cindaku.nftar.modules import com.squareup.picasso.Picasso import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class PicassoModule { @Provides @Singleton fun getPicasso(): Picasso{ return Picasso.get() } }
0
Kotlin
1
0
5c6eb7dbc44ece846b9b01d365a1f32e1ce80284
272
nftar-android
MIT License
platform/lang-impl/src/com/intellij/execution/runners/ConsoleTitleGen.kt
androidports
115,100,208
false
null
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.execution.runners import com.intellij.execution.ExecutionHelper import com.intellij.execution.process.ProcessHandler import com.intellij.execution.ui.RunContentDescriptor import com.intellij.openapi.project.Project import java.util.stream.Collectors /** * @author traff */ open class ConsoleTitleGen @JvmOverloads constructor(private val myProject: Project, private val consoleTitle: String, private val shouldAddNumberToTitle: Boolean = true) { fun makeTitle(): String { if (shouldAddNumberToTitle) { val activeConsoleNames = getActiveConsoles(consoleTitle) var max = 0 for (name in activeConsoleNames) { if (max == 0) { max = 1 } try { val num = Integer.parseInt(name.substring(consoleTitle.length + 1, name.length - 1)) if (num > max) { max = num } } catch (ignored: Exception) { //skip } } if (max >= 1) { return consoleTitle + "(" + (max + 1) + ")" } } return consoleTitle } protected open fun getActiveConsoles(consoleTitle: String): List<String> { val consoles = ExecutionHelper.collectConsolesByDisplayName(myProject) { dom -> dom.contains(consoleTitle) } return consoles.filter({ input -> val handler = input.processHandler handler != null && !handler.isProcessTerminated }).map({ it.displayName }); } }
6
null
1
4
6e4f7135c5843ed93c15a9782f29e4400df8b068
2,044
intellij-community
Apache License 2.0
test-utils/testData/api/overridee/javaOverrideInSource.kt
google
297,744,725
false
{"Kotlin": 2173589, "Shell": 5321, "Java": 3893}
/* * Copyright 2023 Google LLC * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * * 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. */ // WITH_RUNTIME // TEST PROCESSOR: OverrideeProcessor // EXPECTED: // JavaSubject.Subject: // Subject.abstractFun() -> Base.abstractFun() // Subject.abstractFunWithGenericArg(t:String) -> Base.abstractFunWithGenericArg(t:T) // Subject.abstractGrandBaseFun() -> GrandBase.abstractGrandBaseFun() // Subject.nonOverridingMethod() -> null // Subject.openFun() -> Base.openFun() // Subject.openFunWithGenericArg(t:String) -> Base.openFunWithGenericArg(t:T) // Subject.openGrandBaseFun() -> GrandBase.openGrandBaseFun() // Subject.overriddenAbstractGrandBaseFun() -> Base.overriddenAbstractGrandBaseFun() // Subject.overriddenGrandBaseFun() -> Base.overriddenGrandBaseFun() // Subject.staticMethod() -> null // END // FILE: dummy.kt class Dummy // FILE: JavaSubject.java public class JavaSubject { static abstract class GrandBase { void openGrandBaseFun() {} abstract void abstractGrandBaseFun(); void overriddenGrandBaseFun() {} abstract void overriddenAbstractGrandBaseFun(); } static abstract class Base<T> extends GrandBase { void openFun() {} abstract void abstractFun(); T openFunWithGenericArg(T t) { return null; } abstract T abstractFunWithGenericArg(T t); void overriddenGrandBaseFun() {} void overriddenAbstractGrandBaseFun() {} } static abstract class Subject extends Base<String> { void openFun() {} void abstractFun() {} String openFunWithGenericArg(String t) { return null; } String abstractFunWithGenericArg(String t) { return null; } String nonOverridingMethod() { return null; } void overriddenGrandBaseFun() {} void overriddenAbstractGrandBaseFun() {} void openGrandBaseFun() {} void abstractGrandBaseFun() {} static String staticMethod() { return null; } } }
370
Kotlin
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
2,637
ksp
Apache License 2.0
app/src/main/java/org/oppia/android/app/onboarding/OnboardingViewModel.kt
harshpatel63
330,956,278
true
{"Kotlin": 5294875, "Starlark": 152600, "Java": 32457, "Shell": 8681}
package org.oppia.android.app.onboarding import androidx.databinding.ObservableField import androidx.lifecycle.ViewModel import org.oppia.android.app.viewmodel.ObservableViewModel import javax.inject.Inject /** [ViewModel] for [OnboardingFragment]. */ class OnboardingViewModel @Inject constructor() : ObservableViewModel() { val slideNumber = ObservableField<Int>(0) val totalNumberOfSlides = TOTAL_NUMBER_OF_SLIDES fun slideChanged(slideIndex: Int) { slideNumber.set(slideIndex) } }
0
Kotlin
0
1
c42dca3eb6c69821784063fb18621a81473735ce
500
oppia-android
Apache License 2.0
community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/createProject/CreateMavenProjectAndConfigureKotlinGuiTest.kt
weiqiangzheng
146,094,397
false
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectWizard.kotlin.createProject import com.intellij.ide.projectWizard.kotlin.model.* import com.intellij.testGuiFramework.util.* import org.junit.Test class CreateMavenProjectAndConfigureKotlinGuiTest : KotlinGuiTestCase() { @Test @JvmName("maven_cfg_jvm") fun createMavenAndConfigureKotlinJvm() { val groupName = "group_maven_jvm" val projectName = testMethod.methodName val kotlinVersion = KotlinTestProperties.kotlin_artifact_version val kotlinKind = KotlinKind.JVM val extraTimeOut = 4000L if (!isIdeFrameRun()) return createMavenProject( projectPath = projectFolder, group = groupName, artifact = projectName) waitAMoment(extraTimeOut) configureKotlinJvmFromMaven(kotlinVersion) waitAMoment(extraTimeOut) saveAndCloseCurrentEditor() editPomXml( kotlinVersion = kotlinVersion, kotlinKind = kotlinKind ) waitAMoment(extraTimeOut) mavenReimport() waitAMoment(extraTimeOut) checkInProjectStructure { checkLibrariesFromMavenGradle( buildSystem = BuildSystem.Maven, kotlinVersion = kotlinVersion, expectedJars = kotlinLibs[kotlinKind]!!.mavenProject.jars.getJars(kotlinVersion) ) checkFacetInOneModule( defaultFacetSettings[TargetPlatform.JVM18]!!, projectName, "Kotlin" ) } } @Test @JvmName("maven_cfg_js") fun createMavenAndConfigureKotlinJs() { val groupName = "group_maven_js" val projectName = testMethod.methodName val kotlinVersion = KotlinTestProperties.kotlin_artifact_version val kotlinKind = KotlinKind.JS val extraTimeOut = 4000L if (!isIdeFrameRun()) return createMavenProject( projectPath = projectFolder, group = groupName, artifact = projectName) waitAMoment(extraTimeOut) configureKotlinJsFromMaven(kotlinVersion) waitAMoment(extraTimeOut) saveAndCloseCurrentEditor() editPomXml( kotlinVersion = kotlinVersion, kotlinKind = kotlinKind ) waitAMoment(extraTimeOut) mavenReimport() waitAMoment(extraTimeOut) checkInProjectStructure { checkLibrariesFromMavenGradle( buildSystem = BuildSystem.Maven, kotlinVersion = kotlinVersion, expectedJars = kotlinLibs[kotlinKind]!!.mavenProject.jars.getJars(kotlinVersion) ) checkFacetInOneModule( defaultFacetSettings[TargetPlatform.JavaScript]!!, projectName, "Kotlin" ) } } override fun isIdeFrameRun(): Boolean = if (KotlinTestProperties.isActualKotlinUsed() && !KotlinTestProperties.isArtifactPresentInConfigureDialog) { logInfo("The tested artifact ${KotlinTestProperties.kotlin_artifact_version} is not present in the configuration dialog. This is not a bug, but the test '${testMethod.methodName}' is skipped (though marked as passed)") false } else true /*@Test @Ignore @JvmName("maven_jvm_from_file") fun createMavenAndConfigureKotlinJvmFromFile() { val groupName = "group_maven_jvm" val artifactName = "art_maven_jvm" createMavenProject( projectPath = projectFolder.absolutePath, group = groupName, artifact = artifactName) waitAMoment(10000) // configureKotlinJvm(libInPlugin = false) createKotlinFile( projectName = testMethod.methodName, packageName = "src/main/java", fileName = "K1" ) waitAMoment(10000) }*/ }
0
null
0
1
b803c8dc2b996ad983a5d1d4de21c6eae06eec78
3,637
intellij-community
Apache License 2.0
app/src/main/java/fr/free/nrw/commons/upload/structure/depictions/DepictModel.kt
commons-app
42,032,884
false
{"Java": 1801851, "Kotlin": 1433772, "PHP": 3156, "Shell": 1449, "Makefile": 595}
package fr.free.nrw.commons.upload.structure.depictions import fr.free.nrw.commons.explore.depictions.DepictsClient import fr.free.nrw.commons.nearby.Place import fr.free.nrw.commons.repository.UploadRepository import io.github.coordinates2country.Coordinates2Country import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.processors.BehaviorProcessor import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton /** * The model class for depictions in upload */ @Singleton class DepictModel @Inject constructor(private val depictsClient: DepictsClient) { val nearbyPlaces: BehaviorProcessor<List<Place>> = BehaviorProcessor.createDefault(emptyList()) companion object { private const val SEARCH_DEPICTS_LIMIT = 25 } /** * Search for depictions */ fun searchAllEntities(query: String, repository: UploadRepository): Flowable<List<DepictedItem>> { return if (query.isBlank()) { nearbyPlaces.switchMap { places: List<Place> -> val qids = mutableSetOf<String>() for(place in places) { place.wikiDataEntityId?.let { qids.add(it) } } repository.uploads.forEach { item -> if(item.gpsCoords != null && item.gpsCoords.imageCoordsExists) { Coordinates2Country.countryQID(item.gpsCoords.decLatitude, item.gpsCoords.decLongitude)?.let { qids.add("Q$it") } } } getPlaceDepictions(ArrayList(qids)).toFlowable() } } else networkItems(query) } /** * Provides [DepictedItem] instances via a [Single] for a given list of ids, providing an * empty list if no places/country are provided or if there is an error */ fun getPlaceDepictions(qids: List<String>): Single<List<DepictedItem>> = qids.toIds().let { ids -> if (ids.isNotEmpty()) depictsClient.getEntities(ids) .map{ it.entities() .values .mapIndexed { index, entity -> DepictedItem(entity)} } .onErrorResumeWithEmptyList() else Single.just(emptyList()) } fun getDepictions(ids: String): Single<List<DepictedItem>> = if (ids.isNotEmpty()) depictsClient.getEntities(ids) .map{ it.entities() .values .mapIndexed { _, entity -> DepictedItem(entity)} } .onErrorResumeWithEmptyList() else Single.just(emptyList()) private fun networkItems(query: String): Flowable<List<DepictedItem>> { return depictsClient.searchForDepictions(query, SEARCH_DEPICTS_LIMIT, 0) .onErrorResumeWithEmptyList() .toFlowable() } fun cleanUp() { nearbyPlaces.offer(emptyList()) } } private fun List<String>.toIds() = mapNotNull { it }.joinToString("|") private fun <T> Single<List<T>>.onErrorResumeWithEmptyList() = onErrorResumeNext { t: Throwable -> Single.just(emptyList<T>()).also { Timber.e(t) } }
571
Java
1179
997
93f1e1ec299a78dac8a013ea21414272c1675e7b
3,330
apps-android-commons
Apache License 2.0
src/main/kotlin/com/theapache64/stackzy/ui/feature/MainActivity.kt
arkivanov
352,727,599
true
{"Kotlin": 206547}
package com.theapache64.stackzy.ui.feature import androidx.compose.ui.unit.IntSize import com.arkivanov.decompose.extensions.compose.jetbrains.rememberRootComponent import com.theapache64.cyclone.core.Activity import com.theapache64.cyclone.core.Intent import com.theapache64.stackzy.App import com.theapache64.stackzy.ui.navigation.NavHostComponent import com.theapache64.stackzy.ui.theme.StackzyTheme import androidx.compose.desktop.Window as setContent class MainActivity : Activity() { companion object { fun getStartIntent(): Intent { return Intent(MainActivity::class).apply { // data goes here } } } override fun onCreate() { super.onCreate() setContent( title = App.appArgs.appName, undecorated = App.CUSTOM_TOOLBAR, size = IntSize(1024, 600), ) { StackzyTheme( title = App.appArgs.appName, subTitle = "(${App.appArgs.version})", customToolbar = App.CUSTOM_TOOLBAR ) { // Igniting navigation rememberRootComponent(factory = ::NavHostComponent) .render() } } } }
0
null
0
3
4d5a6004b3e05f12e004ad528aec5f94105171e0
1,251
stackzy
Apache License 2.0
app/src/main/java/com/example/fragmentlifecycle/BlankFragment.kt
Devanshsati
802,178,084
false
{"Kotlin": 3351}
package com.example.fragmentlifecycle import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment class BlankFragment : Fragment() { override fun onAttach(context: Context) { super.onAttach(context) Log.d("TAG", "onAttach") Toast.makeText(context, "onAttach", Toast.LENGTH_SHORT).show() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("TAG", "onCreate") Toast.makeText(context, "onCreate", Toast.LENGTH_SHORT).show() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { Log.d("TAG", "onCreateView") Toast.makeText(context, "onCreateView", Toast.LENGTH_SHORT).show() return inflater.inflate(R.layout.fragment_blank, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Log.d("TAG", "onViewCreated") Toast.makeText(context, "onViewCreated", Toast.LENGTH_SHORT).show() } override fun onResume() { super.onResume() Log.d("TAG", "onResume") Toast.makeText(context, "onResume", Toast.LENGTH_SHORT).show() } override fun onPause() { super.onPause() Log.d("TAG", "onPause") Toast.makeText(context, "onPause", Toast.LENGTH_SHORT).show() } override fun onDestroy() { super.onDestroy() Log.d("TAG", "onDestroy") Toast.makeText(context, "onDestroy", Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
0
50c577599f6d38206a07846fa8c5d5f74dce7a10
1,793
FragmentLifeCycle-Android
Apache License 2.0
app/src/main/java/dev/esnault/bunpyro/android/display/compose/SimpleScreen.kt
esnaultdev
242,479,002
false
null
package dev.esnault.bunpyro.android.display.compose import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.navigation.NavController /** * A simple screen with a top app bar and some [content] below. */ @Composable fun SimpleScreen( navController: NavController?, title: String, content: @Composable () -> Unit ) { AppTheme { Scaffold( topBar = { TopAppBar( title = { Text(title) }, navigationIcon = { NavigateBackIcon(navController = navController) } ) }, content = { content() } ) } }
2
Kotlin
1
9
89b3c7dad2c37c22648c26500016d6503d27019e
789
BunPyro
Intel Open Source License
src/me/anno/ecs/components/cache/AnimationCache.kt
AntonioNoack
456,513,348
false
null
package me.anno.ecs.components.cache import me.anno.cache.CacheSection import me.anno.ecs.components.anim.AnimTexture import me.anno.ecs.components.anim.Animation import me.anno.ecs.components.anim.Skeleton import me.anno.ecs.prefab.PrefabByFileCache import me.anno.io.files.FileReference object AnimationCache : PrefabByFileCache<Animation>(Animation::class) { var timeout = 10_000L val animTexCache = CacheSection("AnimTextures") operator fun get(skeleton: Skeleton) = getTexture(skeleton) fun getTexture(skeleton: Skeleton): AnimTexture { return animTexCache.getEntry(skeleton.prefab!!.source, timeout, false) { _ -> AnimTexture(skeleton) } as AnimTexture } fun invalidate(animation: Animation, skeleton: Skeleton) { getTexture(skeleton).invalidate(animation) } fun invalidate(animation: Animation, skeleton: FileReference = animation.skeleton) { invalidate(animation, SkeletonCache[skeleton] ?: return) } }
0
Kotlin
0
7
bacd7c79b8b34765d157012a08d728008c4b2d9a
994
RemsEngine
Apache License 2.0
compiler/testData/codegen/box/invokedynamic/sam/kt51868_contravariantGenericSam.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// IGNORE_BACKEND_FIR: JVM_IR // FIR status: "ClassCastException: String cannot be cast to StringBuilder". // FIR always takes the parameter type and erases type projections in it to obtain the SAM type. This is incorrect, see KT-51868 and KT-52428. // TARGET_BACKEND: JVM // JVM_TARGET: 1.8 // WITH_STDLIB // CHECK_BYTECODE_TEXT // JVM_IR_TEMPLATES // 0 java/lang/invoke/LambdaMetafactory // FILE: box.kt fun box(): String { var result = "Fail" val r = Request { obj: CharSequence -> result = obj as String } r.deliver("OK") return result } // FILE: Request.java public class Request { private final Consumer<? super StringBuilder> consumer; public Request(Consumer<? super StringBuilder> consumer) { this.consumer = consumer; } public void deliver(Object response) { deliverResponse(consumer, response); } public <K extends CharSequence> void deliverResponse(final Consumer<K> consumer, Object rawResponse) { K response = (K) rawResponse; consumer.accept(response); } } // FILE: Consumer.java public interface Consumer<T extends CharSequence> { void accept(T t); }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,170
kotlin
Apache License 2.0
app/src/main/java/com/smtm/mvvm/data/db/entity/mapper/UserDocumentEntityMapper.kt
asus4862
293,993,826
false
null
package com.smtm.mvvm.data.db.entity.mapper import com.smtm.mvvm.data.db.entity.BookmarkEntity import com.smtm.mvvm.data.repository.user.model.UserDocument /** * **/ object UserDocumentEntityMapper { fun toEntity(imageDocument: UserDocument): BookmarkEntity { return imageDocument.run { BookmarkEntity( id, book_id, login, avatar_url, isFavorite ) } } fun fromEntityList(imageDocumentEntityList: List<BookmarkEntity>): List<UserDocument> { return imageDocumentEntityList.map { fromEntity(it) } } fun fromEntity(imageDocumentEntity: BookmarkEntity): UserDocument { return imageDocumentEntity.run { UserDocument( id, book_id, login, avatar_url, isFavorite ) } } }
0
Kotlin
0
0
c535bd319d7a77fb9d5df8524313026d1b3ce2da
941
MVVMArchitecture
Apache License 2.0
app/src/main/java/com/smtm/mvvm/data/db/entity/mapper/UserDocumentEntityMapper.kt
asus4862
293,993,826
false
null
package com.smtm.mvvm.data.db.entity.mapper import com.smtm.mvvm.data.db.entity.BookmarkEntity import com.smtm.mvvm.data.repository.user.model.UserDocument /** * **/ object UserDocumentEntityMapper { fun toEntity(imageDocument: UserDocument): BookmarkEntity { return imageDocument.run { BookmarkEntity( id, book_id, login, avatar_url, isFavorite ) } } fun fromEntityList(imageDocumentEntityList: List<BookmarkEntity>): List<UserDocument> { return imageDocumentEntityList.map { fromEntity(it) } } fun fromEntity(imageDocumentEntity: BookmarkEntity): UserDocument { return imageDocumentEntity.run { UserDocument( id, book_id, login, avatar_url, isFavorite ) } } }
0
Kotlin
0
0
c535bd319d7a77fb9d5df8524313026d1b3ce2da
941
MVVMArchitecture
Apache License 2.0
addressbook-main/src/main/kotlin/com/addressbook/aop/LoggingAspect.kt
dredwardhyde
164,920,046
false
null
package com.addressbook.aop import com.fasterxml.jackson.databind.ObjectMapper import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation.Around import org.aspectj.lang.annotation.Aspect import org.slf4j.LoggerFactory import org.springframework.stereotype.Component @Aspect @Component class LoggingAspect { private val logger = LoggerFactory.getLogger(LoggingAspect::class.java) @Around("@annotation(com.addressbook.annotations.LoggedGetRequest) " + "|| @annotation(com.addressbook.annotations.LoggedPostRequest)") @Throws(Throwable::class) fun logExecutionTime(joinPoint: ProceedingJoinPoint): Any? { val start = System.currentTimeMillis() val proceed = joinPoint.proceed() val executionTime = System.currentTimeMillis() - start logger.info(joinPoint.signature.toString() + " executed in " + executionTime + "ms") if (logger.isDebugEnabled) logger.debug(ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(proceed)) return proceed } }
0
null
7
9
cb69285f5b796bb2c0c3930120a4e1b287132ae7
1,055
addressbook
Apache License 2.0
addressbook-main/src/main/kotlin/com/addressbook/aop/LoggingAspect.kt
dredwardhyde
164,920,046
false
null
package com.addressbook.aop import com.fasterxml.jackson.databind.ObjectMapper import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation.Around import org.aspectj.lang.annotation.Aspect import org.slf4j.LoggerFactory import org.springframework.stereotype.Component @Aspect @Component class LoggingAspect { private val logger = LoggerFactory.getLogger(LoggingAspect::class.java) @Around("@annotation(com.addressbook.annotations.LoggedGetRequest) " + "|| @annotation(com.addressbook.annotations.LoggedPostRequest)") @Throws(Throwable::class) fun logExecutionTime(joinPoint: ProceedingJoinPoint): Any? { val start = System.currentTimeMillis() val proceed = joinPoint.proceed() val executionTime = System.currentTimeMillis() - start logger.info(joinPoint.signature.toString() + " executed in " + executionTime + "ms") if (logger.isDebugEnabled) logger.debug(ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(proceed)) return proceed } }
0
null
7
9
cb69285f5b796bb2c0c3930120a4e1b287132ae7
1,055
addressbook
Apache License 2.0
plugins/kotlinx-serialization/testData/diagnostics/NullabilityIncompatible.kt
JetBrains
3,432,266
false
null
// FIR_IDENTICAL // WITH_STDLIB // FILE: annotation.kt package kotlinx.serialization import kotlin.annotation.* /* Until the annotation is added to the serialization runtime, we have to create an annotation with that name in the project itself */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class KeepGeneratedSerializer // FILE: test.kt import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* @Serializable(NopeNullableSerializer::class) class Nope {} class NopeNullableSerializer: KSerializer<Nope?> { override val descriptor: SerialDescriptor get() = TODO() override fun deserialize(decoder: Decoder): Nope? = TODO() override fun serialize(encoder: Encoder, value: Nope?) = TODO() } @Serializer(forClass = FooKept::class) object FooKeptSerializer @Serializable class Foo(val foo: <!SERIALIZER_NULLABILITY_INCOMPATIBLE("NopeNullableSerializer; Nope")!>Nope<!>) @Serializable(FooKeptSerializer::class) @KeepGeneratedSerializer class FooKept(val foo: <!SERIALIZER_NULLABILITY_INCOMPATIBLE("NopeNullableSerializer; Nope")!>Nope<!>)
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,154
kotlin
Apache License 2.0
clients/graphql-kotlin-client-serialization/src/test/kotlin/com/expediagroup/graphql/client/serialization/data/EnumQuery.kt
ExpediaGroup
148,706,161
false
null
/* * Copyright 2021 Expedia, 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 * * 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.expediagroup.graphql.client.serialization.data import com.expediagroup.graphql.client.serialization.data.enums.TestEnum import com.expediagroup.graphql.client.types.GraphQLClientRequest import kotlinx.serialization.Required import kotlinx.serialization.Serializable import kotlin.reflect.KClass @Serializable class EnumQuery( override val variables: Variables ) : GraphQLClientRequest<EnumQuery.Result> { @Required override val query: String = "ENUM_QUERY" @Required override val operationName: String = "EnumQuery" override fun responseType(): KClass<Result> = Result::class @Serializable data class Variables( val enum: TestEnum? = null ) @Serializable data class Result( val enumResult: TestEnum = TestEnum.__UNKNOWN ) }
68
null
345
1,739
d3ad96077fc6d02471f996ef34c67066145acb15
1,404
graphql-kotlin
Apache License 2.0
room/compiler-processing/src/main/java/androidx/room/compiler/processing/XExecutableElement.kt
easyandroid-cc
367,029,992
true
{"Java Properties": 49, "Shell": 65, "INI": 3, "Text": 4795, "Gradle": 562, "Markdown": 84, "Ignore List": 36, "Java": 5498, "XML": 14013, "HTML": 17, "Kotlin": 4945, "Python": 32, "JSON": 46, "Proguard": 44, "Protocol Buffer": 37, "Protocol Buffer Text Format": 54, "CMake": 3, "C++": 5, "SVG": 4, "Ant Build System": 5, "Batchfile": 13, "AIDL": 132, "ANTLR": 1, "YAML": 5, "JavaScript": 1, "CSS": 1, "JSON with Comments": 1, "desktop": 1, "Gradle Kotlin DSL": 2, "TOML": 1}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing /** * Represents a method, constructor or initializer. * * @see [javax.lang.model.element.ExecutableElement] */ interface XExecutableElement : XHasModifiers, XElement { /** * The element that declared this executable. * * @see requireEnclosingTypeElement */ val enclosingElement: XElement /** * The list of parameters that should be passed into this method. * * @see [isVarArgs] */ val parameters: List<XExecutableParameterElement> /** * Returns true if this method receives a vararg parameter. */ fun isVarArgs(): Boolean } /** * Checks the enclosing element is a TypeElement and returns it, otherwise, * throws [IllegalStateException]. */ fun XExecutableElement.requireEnclosingTypeElement(): XTypeElement { return enclosingElement as? XTypeElement ?: error("Required enclosing type element for $this but found $enclosingElement") }
0
null
0
1
7cbc7c6d26449a2896afd8eb332d32fc8e00cc2e
1,593
androidx
Apache License 2.0
examples/plugin/src/io/github/tozydev/patek/examples/commands/GmGuiCommand.kt
tozydev
773,615,401
false
{"Kotlin": 128971, "Java": 2674}
package io.github.tozydev.patek.examples.commands import dev.jorel.commandapi.kotlindsl.playerExecutor import io.github.tozydev.patek.commands.command import io.github.tozydev.patek.examples.gui.gameModeGui fun gmGuiCommand() = command("gmGui") { withShortDescription("Open the game mode GUI") withPermission("commands.gmGui") withUsage("/gmGui") playerExecutor { player, _ -> gameModeGui().open(player) } }
0
Kotlin
0
1
f5b0fd5ba40c51dd53934d3bb5b41052675fb205
471
patek
MIT License
backend/src/main/kotlin/com/lucasalfare/flrefs/main/usecase/UserServices.kt
LucasAlfare
794,789,183
false
{"Kotlin": 66207, "HTML": 5527, "Dockerfile": 664}
package com.lucasalfare.flrefs.main.usecase import com.lucasalfare.flrefs.main.domain.model.dto.LoginRequestDTO import com.lucasalfare.flrefs.main.domain.repository.UserRepository object UserServices { lateinit var userRepository: UserRepository suspend fun create(email: String, plainPassword: String) = userRepository.create(email, plainPassword) suspend fun readByLogin(loginRequestDTO: LoginRequestDTO) = userRepository.readByEmail(loginRequestDTO.email) }
0
Kotlin
0
1
f4a30a613070681dacd0965aa751187e46e351b0
479
FL-Refs
MIT License
compiler/testData/codegen/boxAgainstJava/sam/kt11519Constructor.kt
JakeWharton
99,388,807
true
null
// SKIP_JDK6 // FILE: Custom.java class Custom<K, V> { private K k; private V v; public Custom(K k, V v) { this.k = k; this.v = v; } public interface MBiConsumer<T, U> { void accept(T t, U u); } public void forEach(MBiConsumer<? super K, ? super V> action) { action.accept(k, v); } } // FILE: 1.kt import java.util.Arrays fun box(): String { val instance = Custom<String, String>("O", "K") var result = "fail" instance.forEach { a, b -> result = a + b } val superInterfaces = Arrays.toString((Class.forName("_1Kt\$box$1")).genericInterfaces) if (superInterfaces != "[Custom\$MBiConsumer<java.lang.String, java.lang.String>]") { return "fail: $superInterfaces" } return result }
181
Kotlin
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
800
kotlin
Apache License 2.0
idea/testData/codeInsight/moveUpDown/parametersAndArguments/classParams6.kt
JakeWharton
99,388,807
true
null
// MOVE: up // IS_APPLICABLE: false class A( <caret>b: Int, c: Int, a: Int ) { }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
106
kotlin
Apache License 2.0
app/src/main/java/com/pratthamarora/proman/model/User.kt
PratthamArora
266,790,024
false
null
package com.rizeq.promana.model import android.os.Parcel import android.os.Parcelable data class User( val id: String = "", val name: String = "", val email: String = "", val image: String = "", val mobile: Long = 0, val fcmToken: String = "" ) : Parcelable { constructor(source: Parcel) : this( source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readLong(), source.readString()!! ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(id) writeString(name) writeString(email) writeString(image) writeLong(mobile) writeString(fcmToken) } companion object { @JvmField val CREATOR: Parcelable.Creator<User> = object : Parcelable.Creator<User> { override fun createFromParcel(source: Parcel): User = User(source) override fun newArray(size: Int): Array<User?> = arrayOfNulls(size) } } }
0
null
4
9
0db90b3ba2fc17afbb8dcb9cf8b3ab5a7b2c0c77
1,095
ProMan
MIT License
units-common/src/commonMain/kotlin/repo/IUnitRepository.kt
crowdproj
508,534,078
false
{"Kotlin": 228068, "Dockerfile": 467}
package com.crowdproj.units.common.repo interface IUnitRepository { suspend fun createUnit(rq: DbUnitRequest): DbUnitResponse suspend fun readUnit(rq: DbUnitIdRequest): DbUnitResponse suspend fun updateUnit(rq: DbUnitRequest): DbUnitResponse suspend fun deleteUnit(rq: DbUnitIdRequest): DbUnitResponse suspend fun searchUnit(rq: DbUnitFilterRequest): DbUnitsResponse suspend fun suggestUnit(rq: DbUnitRequest): DbUnitResponse companion object { val NONE = object: IUnitRepository { override suspend fun createUnit(rq: DbUnitRequest): DbUnitResponse { TODO("Not yet implemented") } override suspend fun readUnit(rq: DbUnitIdRequest): DbUnitResponse { TODO("Not yet implemented") } override suspend fun updateUnit(rq: DbUnitRequest): DbUnitResponse { TODO("Not yet implemented") } override suspend fun deleteUnit(rq: DbUnitIdRequest): DbUnitResponse { TODO("Not yet implemented") } override suspend fun searchUnit(rq: DbUnitFilterRequest): DbUnitsResponse { TODO("Not yet implemented") } override suspend fun suggestUnit(rq: DbUnitRequest): DbUnitResponse { TODO("Not yet implemented") } } } }
1
Kotlin
2
0
7d0023a952e540ccd45769d61ceab8acd700bc6b
1,387
crowdproj-units
Apache License 2.0
desktopApp/src/commonMain/kotlin/com/foreverrafs/superdiary/JvmAnalytics.kt
rafsanjani
315,355,130
false
{"Kotlin": 319164, "Shell": 1002, "Swift": 851, "Ruby": 816}
package com.foreverrafs.superdiary import com.foreverrafs.superdiary.core.analytics.AnalyticsEvents import com.foreverrafs.superdiary.core.analytics.AnalyticsTracker class JvmAnalytics : AnalyticsTracker { override fun trackEvent(event: AnalyticsEvents) { TODO("Implement JVM analytics") } }
12
Kotlin
0
8
79839cf672e3e911835bcfa63b31760afab71cce
310
superdiary
MIT License
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/Menu.desktop.kt
JetBrains
351,708,598
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 androidx.compose.ui.window import androidx.compose.runtime.AbstractApplier import androidx.compose.runtime.Composable import androidx.compose.runtime.ComposeNode import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionContext import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCompositionContext import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.asAwtImage import androidx.compose.ui.input.key.KeyShortcut import androidx.compose.ui.input.key.toSwingKeyStroke import androidx.compose.ui.node.Ref import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.util.AddRemoveMutableList import java.awt.CheckboxMenuItem import java.awt.Menu import java.awt.MenuItem import java.awt.event.KeyEvent import java.lang.UnsupportedOperationException import javax.swing.AbstractButton import javax.swing.Icon import javax.swing.ImageIcon import javax.swing.JCheckBoxMenuItem import javax.swing.JComponent import javax.swing.JMenu import javax.swing.JMenuBar import javax.swing.JMenuItem import javax.swing.JPopupMenu import javax.swing.JRadioButtonMenuItem private val DefaultIconSize = Size(16f, 16f) /** * Composes the given composable into the MenuBar. * * The new composition can be logically "linked" to an existing one, by providing a * [parentComposition]. This will ensure that invalidations and CompositionLocals will flow * through the two compositions as if they were not separate. * * @param parentComposition The parent composition reference to coordinate * scheduling of composition updates. * If null then default root composition will be used. * @param content Composable content of the MenuBar. */ fun JMenuBar.setContent( parentComposition: CompositionContext, content: @Composable (MenuBarScope.() -> Unit) ): Composition { val applier = MutableListApplier(asMutableList()) val composition = Composition(applier, parentComposition) val scope = MenuBarScope() composition.setContent { scope.content() } return composition } /** * Composes the given composable into the Menu. * * The new composition can be logically "linked" to an existing one, by providing a * [parentComposition]. This will ensure that invalidations and CompositionLocals will flow * through the two compositions as if they were not separate. * * @param parentComposition The parent composition reference to coordinate * scheduling of composition updates. * If null then default root composition will be used. * @param content Composable content of the Menu. */ fun Menu.setContent( parentComposition: CompositionContext, content: @Composable (MenuScope.() -> Unit) ): Composition { val applier = MutableListApplier(asMutableList()) val composition = Composition(applier, parentComposition) val scope = MenuScope(AwtMenuScope()) composition.setContent { scope.content() } return composition } /** * Composes the given composable into the Menu. * * The new composition can be logically "linked" to an existing one, by providing a * [parentComposition]. This will ensure that invalidations and CompositionLocals will flow * through the two compositions as if they were not separate. * * @param parentComposition The parent composition reference to coordinate * scheduling of composition updates. * If null then default root composition will be used. * @param content Composable content of the Menu. */ fun JMenu.setContent( parentComposition: CompositionContext, content: @Composable (MenuScope.() -> Unit) ): Composition { val applier = JMenuItemApplier(this) val composition = Composition(applier, parentComposition) val scope = MenuScope(SwingMenuScope()) composition.setContent { scope.content() } return composition } // This menu is used by Tray @Composable private fun AwtMenu( text: String, enabled: Boolean, content: @Composable MenuScope.() -> Unit ) { val menu = remember(::Menu) val compositionContext = rememberCompositionContext() DisposableEffect(Unit) { val composition = menu.setContent(compositionContext, content) onDispose { composition.dispose() } } ComposeNode<Menu, MutableListApplier<MenuItem>>( factory = { menu }, update = { set(text, Menu::setLabel) set(enabled, Menu::setEnabled) } ) } // TODO(demin): consider making MenuBarScope/MenuScope as an interface // after b/165812010 will be fixed /** * Receiver scope which is used by [JMenuBar.setContent] and [FrameWindowScope.MenuBar]. */ class MenuBarScope internal constructor() { /** * Adds menu to the menu bar * * @param text text of the menu that will be shown on the menu bar * @param enabled is this menu item can be chosen * @param mnemonic character that corresponds to some key on the keyboard. * When this key and Alt modifier will be pressed - menu will be open. * If the character is found within the item's text, the first occurrence * of it will be underlined. * @param content content of the menu (sub menus, items, separators, etc) */ @Composable fun Menu( text: String, mnemonic: Char? = null, enabled: Boolean = true, content: @Composable MenuScope.() -> Unit ) { val menu = remember(::JMenu) val compositionContext = rememberCompositionContext() DisposableEffect(Unit) { val composition = menu.setContent(compositionContext, content) onDispose { composition.dispose() } } ComposeNode<JMenu, MutableListApplier<JComponent>>( factory = { menu }, update = { set(text, JMenu::setText) set(enabled, JMenu::setEnabled) set(mnemonic, JMenu::setMnemonic) } ) } } internal interface MenuScopeImpl { @Composable fun Menu( text: String, enabled: Boolean, mnemonic: Char?, content: @Composable MenuScope.() -> Unit ) @Composable fun Separator() @Composable fun Item( text: String, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onClick: () -> Unit ) @Composable fun CheckboxItem( text: String, checked: Boolean, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onCheckedChange: (Boolean) -> Unit ) @Composable fun RadioButtonItem( text: String, selected: Boolean, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onClick: () -> Unit ) } private class AwtMenuScope : MenuScopeImpl { /** * Adds sub menu to the menu * * @param text text of the menu that will be shown in the menu * @param enabled is this menu item can be chosen * @param content content of the menu (sub menus, items, separators, etc) */ @Composable override fun Menu( text: String, enabled: Boolean, mnemonic: Char?, content: @Composable MenuScope.() -> Unit ) { if (mnemonic != null) { throw UnsupportedOperationException("java.awt.Menu doesn't support mnemonic") } AwtMenu( text, enabled, content ) } @Composable override fun Separator() { ComposeNode<MenuItem, MutableListApplier<MenuItem>>( // item with name "-" has different look factory = { MenuItem("-") }, update = {} ) } @Composable override fun Item( text: String, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onClick: () -> Unit ) { if (icon != null) { throw UnsupportedOperationException("java.awt.Menu doesn't support icon") } if (mnemonic != null) { throw UnsupportedOperationException("java.awt.Menu doesn't support mnemonic") } if (shortcut != null) { throw UnsupportedOperationException("java.awt.Menu doesn't support shortcut") } val currentOnClick by rememberUpdatedState(onClick) ComposeNode<MenuItem, MutableListApplier<MenuItem>>( factory = { MenuItem().apply { addActionListener { currentOnClick() } } }, update = { set(text, MenuItem::setLabel) set(enabled, MenuItem::setEnabled) } ) } @Composable override fun CheckboxItem( text: String, checked: Boolean, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onCheckedChange: (Boolean) -> Unit ) { if (icon != null) { throw UnsupportedOperationException("java.awt.Menu doesn't support icon") } if (mnemonic != null) { throw UnsupportedOperationException("java.awt.Menu doesn't support mnemonic") } if (shortcut != null) { throw UnsupportedOperationException("java.awt.Menu doesn't support shortcut") } val currentOnCheckedChange by rememberUpdatedState(onCheckedChange) val checkedState = rememberStateChanger( CheckboxMenuItem::setState, CheckboxMenuItem::getState ) ComposeNode<CheckboxMenuItem, MutableListApplier<JComponent>>( factory = { CheckboxMenuItem().apply { addItemListener { checkedState.fireChange(this, currentOnCheckedChange) } } }, update = { set(text, CheckboxMenuItem::setLabel) set(checked, checkedState::set) set(enabled, CheckboxMenuItem::setEnabled) } ) } @Composable override fun RadioButtonItem( text: String, selected: Boolean, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onClick: () -> Unit ) { throw UnsupportedOperationException("java.awt.Menu doesn't support RadioButtonItem") } } private class SwingMenuScope : MenuScopeImpl { /** * Adds sub menu to the menu * * @param text text of the menu that will be shown in the menu * @param enabled is this menu item can be chosen * @param content content of the menu (sub menus, items, separators, etc) */ @Composable override fun Menu( text: String, enabled: Boolean, mnemonic: Char?, content: @Composable MenuScope.() -> Unit ) { ComposeNode<JMenu, JMenuItemApplier>( factory = { JMenu() }, update = { set(text, JMenu::setText) set(enabled, JMenu::setEnabled) set(mnemonic, JMenu::setMnemonic) }, content = { val scope = MenuScope(this) scope.content() } ) } @Composable override fun Separator() { ComposeNode<JPopupMenu.Separator, JMenuItemApplier>( // item with name "-" has different look factory = { JPopupMenu.Separator() }, update = {} ) } @Composable override fun Item( text: String, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onClick: () -> Unit ) { val currentOnClick by rememberUpdatedState(onClick) val awtIcon = rememberAwtIcon(icon) ComposeNode<JMenuItem, JMenuItemApplier>( factory = { JMenuItem().apply { addActionListener { currentOnClick() } } }, update = { set(text, JMenuItem::setText) set(awtIcon, JMenuItem::setIcon) set(enabled, JMenuItem::setEnabled) set(mnemonic, JMenuItem::setMnemonic) } ) } @Composable override fun CheckboxItem( text: String, checked: Boolean, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onCheckedChange: (Boolean) -> Unit, ) { val currentOnCheckedChange by rememberUpdatedState(onCheckedChange) val awtIcon = rememberAwtIcon(icon) val checkedState = rememberStateChanger( JCheckBoxMenuItem::setState, JCheckBoxMenuItem::getState ) ComposeNode<JCheckBoxMenuItem, JMenuItemApplier>( factory = { JCheckBoxMenuItem().apply { addItemListener { checkedState.fireChange(this, currentOnCheckedChange) } } }, update = { set(text, JCheckBoxMenuItem::setText) set(checked, checkedState::set) set(awtIcon, JCheckBoxMenuItem::setIcon) set(enabled, JCheckBoxMenuItem::setEnabled) set(mnemonic, JCheckBoxMenuItem::setMnemonic) set(shortcut, JCheckBoxMenuItem::setShortcut) } ) } @Composable override fun RadioButtonItem( text: String, selected: Boolean, icon: Painter?, enabled: Boolean, mnemonic: Char?, shortcut: KeyShortcut?, onClick: () -> Unit, ) { val currentOnClick by rememberUpdatedState(onClick) val awtIcon = rememberAwtIcon(icon) val selectedState = rememberStateChanger( JRadioButtonMenuItem::setSelected, JRadioButtonMenuItem::isSelected ) ComposeNode<JRadioButtonMenuItem, JMenuItemApplier>( factory = { JRadioButtonMenuItem().apply { addItemListener { selectedState.fireChange(this) { currentOnClick() } } } }, update = { set(text, JRadioButtonMenuItem::setText) set(selected, selectedState::set) set(awtIcon, JRadioButtonMenuItem::setIcon) set(enabled, JRadioButtonMenuItem::setEnabled) set(mnemonic, JRadioButtonMenuItem::setMnemonic) set(shortcut, JRadioButtonMenuItem::setShortcut) } ) } } // we use `class MenuScope` and `interface MenuScopeImpl` instead of just `interface MenuScope` // because of b/165812010 /** * Receiver scope which is used by [Menu.setContent], [MenuBarScope.Menu], [Tray] */ class MenuScope internal constructor(private val impl: MenuScopeImpl) { /** * Adds sub menu to the menu * * @param text text of the menu that will be shown in the menu * @param enabled is this menu item can be chosen * @param mnemonic character that corresponds to some key on the keyboard. * When this key will be pressed - menu will be open. * If the character is found within the item's text, the first occurrence * of it will be underlined. * @param content content of the menu (sub menus, items, separators, etc) */ @Composable fun Menu( text: String, enabled: Boolean = true, mnemonic: Char? = null, content: @Composable MenuScope.() -> Unit ): Unit = impl.Menu( text, enabled, mnemonic, content ) /** * Adds separator to the menu */ @Composable fun Separator() = impl.Separator() /** * Adds item to the menu * * @param text text of the item that will be shown in the menu * @param icon icon of the item * @param enabled is this item item can be chosen * @param mnemonic character that corresponds to some key on the keyboard. * When this key will be pressed - [onClick] will be triggered. * If the character is found within the item's text, the first occurrence * of it will be underlined. * @param shortcut key combination which triggers [onClick] action without * navigating the menu hierarchy. * @param onClick action that should be performed when the user clicks on the item */ @Composable fun Item( text: String, icon: Painter? = null, enabled: Boolean = true, mnemonic: Char? = null, shortcut: KeyShortcut? = null, onClick: () -> Unit ): Unit = impl.Item(text, icon, enabled, mnemonic, shortcut, onClick) /** * Adds item with checkbox to the menu * * @param text text of the item that will be shown in the menu * @param checked whether checkbox is checked or unchecked * @param icon icon of the item * @param enabled is this item item can be chosen * @param mnemonic character that corresponds to some key on the keyboard. * When this key will be pressed - [onCheckedChange] will be triggered. * If the character is found within the item's text, the first occurrence * of it will be underlined. * @param shortcut key combination which triggers [onCheckedChange] action without * navigating the menu hierarchy. * @param onCheckedChange callback to be invoked when checkbox is being clicked, * therefore the change of checked state in requested */ @Composable fun CheckboxItem( text: String, checked: Boolean, icon: Painter? = null, enabled: Boolean = true, mnemonic: Char? = null, shortcut: KeyShortcut? = null, onCheckedChange: (Boolean) -> Unit ): Unit = impl.CheckboxItem( text, checked, icon, enabled, mnemonic, shortcut, onCheckedChange ) /** * Adds item with radio button to the menu * * @param text text of the item that will be shown in the menu * @param selected boolean state for this button: either it is selected or not * @param icon icon of the item * @param enabled is this item item can be chosen * @param mnemonic character that corresponds to some key on the keyboard. * When this key will be pressed - [onClick] will be triggered. * If the character is found within the item's text, the first occurrence * of it will be underlined. * @param shortcut key combination which triggers [onClick] action without * navigating the menu hierarchy. * @param onClick callback to be invoked when the radio button is being clicked */ @Composable fun RadioButtonItem( text: String, selected: Boolean, icon: Painter? = null, enabled: Boolean = true, mnemonic: Char? = null, shortcut: KeyShortcut? = null, onClick: () -> Unit ): Unit = impl.RadioButtonItem( text, selected, icon, enabled, mnemonic, shortcut, onClick ) } private class MutableListApplier<T>( private val list: MutableList<T> ) : AbstractApplier<T?>(null) { override fun insertTopDown(index: Int, instance: T?) { list.add(index, instance!!) } override fun insertBottomUp(index: Int, instance: T?) { // Ignore, we have plain list } override fun remove(index: Int, count: Int) { for (i in index + count - 1 downTo index) { list.removeAt(i) } } @Suppress("UNCHECKED_CAST") override fun move(from: Int, to: Int, count: Int) { (list as MutableList<T?>).move(from, to, count) } override fun onClear() { list.clear() } } // Copied from androidx/compose/ui/graphics/vector/Vector.kt private inline fun <T> performMove( from: Int, to: Int, count: Int, getItem: (Int) -> T, removeItem: (Int) -> Unit, insertItem: (T, Int) -> Unit ) { if (from > to) { var current = to repeat(count) { val node = getItem(from) removeItem(from) insertItem(node, current) current++ } } else { repeat(count) { val node = getItem(from) removeItem(from) insertItem(node, to - 1) } } } internal abstract class JComponentApplier(root: JComponent) : AbstractApplier<JComponent>(root) { override fun onClear() { root.removeAll() } override fun insertBottomUp(index: Int, instance: JComponent) { // Ignored as the tree is built top-down. } override fun insertTopDown(index: Int, instance: JComponent) { current.add(instance, index) } override fun move(from: Int, to: Int, count: Int) { val current = current performMove( from, to, count, getItem = { current.getComponent(it) }, removeItem = { current.remove(it) }, insertItem = { item, idx -> current.add(item, idx) } ) } override fun remove(index: Int, count: Int) { val current = current for (i in index + count - 1 downTo index) { current.remove(i) } } } internal class JMenuItemApplier(root: JMenu) : JComponentApplier(root) { override fun onEndChanges() { // If the menu is changed while the popup is open, we need to ask the popup to remeasure // itself. (root as JMenu).popupMenu.pack() } } private fun JMenuBar.asMutableList(): MutableList<JComponent> { return object : AddRemoveMutableList<JComponent>() { override val size: Int get() = [email protected] override fun get(index: Int) = [email protected](index) override fun performAdd(element: JComponent) { [email protected](element) } override fun performRemove(index: Int) { [email protected](index) } } } private fun Menu.asMutableList(): MutableList<MenuItem> { return object : AddRemoveMutableList<MenuItem>() { override val size: Int get() = [email protected] override fun get(index: Int) = [email protected](index) override fun performAdd(element: MenuItem) { [email protected](element) } override fun performRemove(index: Int) { [email protected](index) } } } private fun AbstractButton.setMnemonic(char: Char?) { mnemonic = KeyEvent.getExtendedKeyCodeForChar(char?.code ?: 0) } private fun JMenuItem.setShortcut(shortcut: KeyShortcut?) { accelerator = shortcut?.toSwingKeyStroke() } @Composable private fun rememberAwtIcon(painter: Painter?): Icon? { val density = LocalDensity.current val layoutDirection = LocalLayoutDirection.current return remember(painter, density, layoutDirection) { painter ?.asAwtImage(density, layoutDirection, DefaultIconSize) ?.let(::ImageIcon) } } @Composable private fun <R, V> rememberStateChanger( set: R.(V) -> Unit, get: R.() -> V ): ComposeState<R, V> = remember { ComposeState(set, get) } /** * Helper class to change state without firing a listener, and fire a listener without state change * * The purpose is to make Swing's state behave as it was attribute in stateless Compose widget. * For example, ComposeState don't fire `onCheckedChange` if we change `checkbox.checked`, * and don't change `checkbox.checked` if user clicks on checkbox. */ private class ComposeState<R, V>( private val set: R.(V) -> Unit, private val get: R.() -> V, ) { private var needEatEvent = false private val ref = Ref<V>() fun set(receiver: R, value: V) { try { needEatEvent = true receiver.set(value) ref.value = value } finally { needEatEvent = false } } fun fireChange(receiver: R, onChange: (V) -> Unit) { if (!needEatEvent) { onChange(receiver.get()) set(receiver, ref.value!!) // prevent internal state change } } }
30
null
950
59
3fbd775007164912b34a1d59a923ad3387028b97
25,460
androidx
Apache License 2.0
intellij-idea/src/main/kotlin/com/itangcent/intellij/config/rule/PsiFieldContext.kt
Earth-1610
178,314,657
false
{"Kotlin": 1216447, "Java": 35079, "Shell": 3153}
package com.itangcent.intellij.config.rule import com.intellij.psi.PsiDocCommentOwner import com.intellij.psi.PsiElement import com.intellij.psi.PsiField import com.intellij.psi.PsiModifierListOwner import com.itangcent.common.utils.SimpleExtensible import com.itangcent.common.utils.cache import com.itangcent.intellij.jvm.element.ExplicitField import com.itangcent.intellij.psi.PsiClassUtils open class PsiFieldContext : SimpleExtensible, RuleContext { protected var psiField: PsiField constructor(psiField: PsiField) { this.psiField = psiField } override fun getResource(): PsiElement { return psiField } override fun getName(): String? { return this.cache("_name") { PsiClassUtils.qualifiedNameOfField(psiField) } } override fun getSimpleName(): String? { return this.cache("_simpleName") { psiField.name } } override fun asPsiDocCommentOwner(): PsiDocCommentOwner { return psiField } override fun asPsiModifierListOwner(): PsiModifierListOwner { return psiField } override fun toString(): String { return getName() ?: "anonymous" } } class ExplicitFieldContext : PsiFieldContext { private var explicitField: ExplicitField constructor(explicitField: ExplicitField) : super(explicitField.psi()) { this.explicitField = explicitField } override fun getCore(): Any? { return explicitField } }
0
Kotlin
5
8
af802e7ea26b233610c9d35af89365c93f48158b
1,458
intellij-kotlin
Apache License 2.0
reactive-albums-api/src/test/kotlin/nl/juraji/reactive/albums/api/pictures/PictureCommandControllerTest.kt
Juraji
290,577,996
false
null
package nl.juraji.reactive.albums.api.pictures import com.fasterxml.jackson.databind.ObjectMapper import com.marcellogalhardo.fixture.Fixture import com.marcellogalhardo.fixture.next import com.ninjasquad.springmockk.MockkBean import io.mockk.every import io.mockk.mockk import nl.juraji.reactive.albums.api.ApiTestConfiguration import nl.juraji.reactive.albums.domain.directories.DirectoryId import nl.juraji.reactive.albums.domain.pictures.PictureId import nl.juraji.reactive.albums.domain.pictures.PictureType import nl.juraji.reactive.albums.domain.tags.TagId import nl.juraji.reactive.albums.query.projections.PictureProjection import nl.juraji.reactive.albums.query.projections.TagProjection import nl.juraji.reactive.albums.util.returnsEmptyMono import nl.juraji.reactive.albums.util.returnsFluxOf import nl.juraji.reactive.albums.util.returnsMonoOf import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Qualifier import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest import org.springframework.context.annotation.Import import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.expectBody import org.springframework.test.web.reactive.server.expectBodyList import java.time.LocalDateTime @ActiveProfiles("test") @ExtendWith(SpringExtension::class) @Import(ApiTestConfiguration::class) @WebFluxTest(PictureCommandController::class) @AutoConfigureWebTestClient internal class PictureCommandControllerTest { private val fixture = Fixture { register(PictureType::class) { PictureType.JPEG } register(LocalDateTime::class) { LocalDateTime.now() } register(PictureProjection::class) { PictureProjection(nextString(), nextString(), nextString(), nextString(), next()) } } @MockkBean private lateinit var pictureCommandsService: PictureCommandsService @Autowired private lateinit var webTestClient: WebTestClient @Autowired @Qualifier("objectMapper") private lateinit var objectMapper: ObjectMapper @Test fun `rescanDuplicates should init duplicate scan`() { val pictureId = PictureId() every { pictureCommandsService.rescanDuplicates(pictureId.identifier) } returnsMonoOf pictureId webTestClient.post() .uri("/api/pictures/$pictureId/rescan-duplicates") .accept(MediaType.TEXT_PLAIN) .exchange() .expectStatus().isOk .expectBody<String>() .isEqualTo(pictureId.identifier) } @Test fun `unlinkDuplicateMatch should init match unlink`() { val pictureId = PictureId() val targetId = PictureId() every { pictureCommandsService.unlinkDuplicateMatch(pictureId.identifier, targetId.identifier) }.returnsEmptyMono() webTestClient.delete() .uri("/api/pictures/$pictureId/duplicate-matches/$targetId") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk .expectBody().isEmpty } @Test fun `movePicture should init picture move`() { val pictureId = PictureId() val targetDirectoryId = DirectoryId() val resultProjection: PictureProjection = fixture.next() val expectedJson: String = objectMapper.writeValueAsString(resultProjection) every { pictureCommandsService.movePicture(pictureId.identifier, targetDirectoryId.identifier) } returnsMonoOf resultProjection webTestClient.post() .uri("/api/pictures/$pictureId/move?targetDirectoryId=$targetDirectoryId") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk .expectBody().json(expectedJson) } @Test fun `deletePicture should init picture delete`() { val pictureId = PictureId() every { pictureCommandsService.deletePicture(pictureId.identifier, true) } returnsMonoOf pictureId webTestClient.delete() .uri("/api/pictures/$pictureId?deletePhysicalFile=true") .accept(MediaType.TEXT_PLAIN) .exchange() .expectStatus().isOk .expectBody<String>() .isEqualTo(pictureId.identifier) } @Test fun `linkTag should init tag link`() { val pictureId = PictureId() val tagId = TagId() val resultProjection: List<TagProjection> = listOf(mockk(relaxed = true)) every { pictureCommandsService.linkTag(pictureId.identifier, tagId.identifier) } returnsFluxOf resultProjection webTestClient.post() .uri("/api/pictures/$pictureId/tags/$tagId") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk .expectBodyList<TagProjection>().hasSize(1) } @Test fun `unlinkTag should init tag unlink`() { val pictureId = PictureId() val tagId = TagId() val resultProjection: List<TagProjection> = listOf(mockk(relaxed = true)) every { pictureCommandsService.unlinkTag(pictureId.identifier, tagId.identifier) } returnsFluxOf resultProjection webTestClient.delete() .uri("/api/pictures/$pictureId/tags/$tagId") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk .expectBodyList<TagProjection>().hasSize(1) } }
0
Kotlin
0
1
205927ceb1ce19e27e2b2aa83f61eeda968613d1
5,942
reactive-albums
MIT License
uikit/src/main/java/com/sendbird/uikit/internal/extensions/MessageListAdapterExtensions.kt
sendbird
350,188,329
false
null
package com.sendbird.uikit.internal.extensions import com.sendbird.uikit.activities.adapter.MessageListAdapter import com.sendbird.uikit.internal.interfaces.OnSubmitButtonClickListener private var submitButtonClickListener: OnSubmitButtonClickListener? = null internal var MessageListAdapter.submitButtonClickListener: OnSubmitButtonClickListener? get() = com.sendbird.uikit.internal.extensions.submitButtonClickListener set(value) { com.sendbird.uikit.internal.extensions.submitButtonClickListener = value }
1
null
43
34
28c5f2f88014060dedf7a22003a3dba4da84cb42
530
sendbird-uikit-android
MIT License
src/main/kotlin/fr/shikkanime/dtos/ConfigDto.kt
Shikkanime
725,527,999
false
{"Kotlin": 628695, "FreeMarker": 142641, "JavaScript": 2805, "SCSS": 1949, "Dockerfile": 1019, "Shell": 812, "Fluent": 69}
package fr.shikkanime.dtos import java.util.* data class ConfigDto( val uuid: UUID?, val propertyKey: String?, var propertyValue: String?, )
4
Kotlin
0
4
82a29d666167ae9583952042e752d95631ef44bf
155
core
Apache License 2.0
kotlin/src/main/kotlin/net/timafe/angkor/service/UserService.kt
tillkuhn
219,713,329
false
null
package net.timafe.angkor.service import net.timafe.angkor.domain.User import net.timafe.angkor.domain.dto.UserSummary import net.timafe.angkor.domain.enums.EntityType import net.timafe.angkor.repo.UserRepository import net.timafe.angkor.security.SecurityUtils import net.timafe.angkor.security.ServiceAccountToken import org.springframework.cache.annotation.CacheEvict import org.springframework.security.authentication.AbstractAuthenticationToken import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.ZonedDateTime import java.util.* /** * Manage [User] * Check https://github.com/rajithd/spring-boot-oauth2/blob/master/src/main/java/com/rd/security/UserDetailsService.java */ @Service class UserService( private val userRepository: UserRepository, private val cacheService: CacheService, private val mailService: MailService, ) : AbstractEntityService<User, UserSummary, UUID>(userRepository) { @Transactional @CacheEvict( cacheNames = [UserRepository.USERS_BY_LOGIN_CACHE, UserRepository.USER_SUMMARIES_CACHE], allEntries = true ) fun createUser(attributes: Map<String, Any>) { val subject = attributes[SecurityUtils.JWT_SUBJECT_KEY] as String val id = SecurityUtils.safeConvertToUUID(subject) ?: UUID.randomUUID() val cognitoUsername = attributes[SecurityUtils.COGNITO_USERNAME_KEY] as String? val login = cognitoUsername ?: subject val name = attributes["name"] ?: login val roles = SecurityUtils.getRolesFromAttributes(attributes) log.info("[${entityType()}] Create new local db user $id (sub=$subject)") this.save( User( id = id, login = login, email = attributes["email"] as String?, firstName = attributes["given_name"] as String?, lastName = attributes["family_name"] as String?, name = name as String?, lastLogin = ZonedDateTime.now(), roles = ArrayList(roles) ) ) } @CacheEvict(cacheNames = [UserRepository.USERS_BY_LOGIN_CACHE], allEntries = true) override fun save(item: User): User { return super.save(item) } @Transactional(readOnly = true) // this is important (issue with IT tests) fun findUser(attributes: Map<String, Any>): User? { val sub = attributes[SecurityUtils.JWT_SUBJECT_KEY] as String val cognitoUsername = attributes[SecurityUtils.COGNITO_USERNAME_KEY] as String? val login = cognitoUsername ?: sub val email = attributes["email"] as String? val id: UUID? = SecurityUtils.safeConvertToUUID(sub) val users = userRepository.findByLoginOrEmailOrId(login.lowercase(), email?.lowercase(), id) if (users.size > 1) { throw IllegalStateException("Expected max 1 user for $login, $email, $id - but found ${users.size}") } return if (users.isNotEmpty()) users[0] else null } /** * Gets the current User (DB Entity) based on information provided by the SecurityContext's Authentication */ @Transactional(readOnly = true) fun getCurrentUser(): User? { val auth = SecurityContextHolder.getContext().authentication // Note: For MockTestUser etc. we also support UsernamePasswordAuthenticationToken to extract subject from sub // When invoked from a @Scheduled job, we get a warning here which we should compensate. // TODO e.g. like this https://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-invoking-a-secured-method-from-a-scheduled-job/ // or https://stackoverflow.com/questions/63346374/how-to-configure-graceful-shutdown-using-delegatingsecuritycontextscheduledexecu if (auth !is AbstractAuthenticationToken) { log.warn("${super.logPrefix()} Unsupported AuthClass=${auth?.javaClass}, expected ${OAuth2LoginAuthenticationToken::class.java}") return null } val attributes = extractAttributesFromAuthToken(auth) return findUser(attributes) } fun getServiceAccountToken(callerClass: Class<*>): ServiceAccountToken { val login = callerClass.simpleName.lowercase() val users = userRepository.findByLoginOrEmailOrId(login,null,null) if (users.size != 1) { throw IllegalStateException("Expected max 1 service account user for $login - but found ${users.size}") } return ServiceAccountToken(login,users[0].id!!) } /** * Extracts the principals / tokens attribute map, currently supports instances of * OAuth2AuthenticationToken and OAuth2LoginAuthenticationToken */ fun extractAttributesFromAuthToken(authToken: AbstractAuthenticationToken): Map<String, Any> = when (authToken) { // For OAuth2 Tokens, the Principal is of type OAuth2User is OAuth2AuthenticationToken -> authToken.principal.attributes is OAuth2LoginAuthenticationToken -> authToken.principal.attributes // no Attributes since principal is just an Object of type ...userDetails.User (with username / password) // but we also have authorities is UsernamePasswordAuthenticationToken -> getAttributesForUsernamePasswordAuth(authToken) // JwtAuthenticationToken not yet supported, would use authToken.tokenAttributes else -> throw IllegalArgumentException("Unsupported auth token, UserService can't handle ${authToken.javaClass}!") } /** * Request removal of user data */ fun removeMe(user: User) { // let - avoid ‘property’ is a mutable property that could have been changed by this time issues // https://medium.com/android-news/lets-talk-about-kotlin-s-let-extension-function-5911213cf8b9 // let captures the value T for thread-safe reading // If the value is an optional, you probably want to unwrap it first with ?. so that your T is not an optional // ere we use the elvis operator ?: to guarantee we run one of the conditional branches. If property exists, // then we can capture and use its value, if the value is null we can ensure we show an error. user.email?.let { mailService.prepareAndSend(it, "Request for user deletion received" , "<p>Dear User,<br /><br />We received your request for <i>user data deletion</i> and will process it asap. Thanks for using our services! </p><p>Your Admin Team</p>") } ?: throw IllegalArgumentException("User ${user.login} has no mail address") } fun extractIdTokenFromAuthToken(authToken: AbstractAuthenticationToken): String = when (val prince = authToken.principal) { is DefaultOidcUser -> prince.idToken.tokenValue else -> throw IllegalArgumentException("Unsupported principal class, UserService can't handle ${prince.javaClass}!") } private fun getAttributesForUsernamePasswordAuth(authToken: UsernamePasswordAuthenticationToken): Map<String, Any> { val prince = authToken.principal return if (prince is org.springframework.security.core.userdetails.User) { mapOf(SecurityUtils.JWT_SUBJECT_KEY to prince.username) } else { mapOf() } } // Currently, we use @CacheEvict annotation, but this may be useful if we need to evict from within the service fun clearCaches() { cacheService.clearCache(UserRepository.USER_SUMMARIES_CACHE) cacheService.clearCache(UserRepository.USERS_BY_LOGIN_CACHE) // From khipster // cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE)?.evict(user.login!!) } // Required by EntityService Superclass override fun entityType(): EntityType { return EntityType.User } }
23
null
4
9
b467cdf5f7e73c9dd2d6130ca5ca44d129f094c1
8,346
angkor
Apache License 2.0
library/src/main/java/com/cube/styleguide/adapter/viewholder/ColorItemViewHolder.kt
3sidedcube
620,468,694
false
null
package com.cube.styleguide.adapter.viewholder import android.view.LayoutInflater import android.widget.LinearLayout import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.cube.styleguide.R import com.cube.styleguide.databinding.ColorBannerViewBinding import com.cube.styleguide.databinding.ColorItemViewBinding import com.cube.styleguide.utils.Extensions.secondPart class ColorItemViewHolder(private val binding: ColorBannerViewBinding) : RecyclerView.ViewHolder(binding.root) { private fun getMiddlePosition(colors: List<Pair<String, Int>>?): Int { return if (colors?.size?.mod(2) == 1) { colors.size.div(2f).toInt() } else { -1 } } fun populate(list: List<Pair<String, Int>>?) { binding.colorContainer.removeAllViews() val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f) list?.forEachIndexed { index, pair -> val colorItemView = ColorItemViewBinding.inflate(LayoutInflater.from(itemView.context)) colorItemView.root.layoutParams = params populateView(colorItemView, getMiddlePosition(list) == index, pair) binding.colorContainer.addView(colorItemView.root) } } private fun populateView(colorItemView: ColorItemViewBinding, isMiddle: Boolean, colorPair: Pair<String, Int>) { val context = itemView.context colorItemView.apply { colorName.text = colorPair.first.secondPart() if (isMiddle) { headerTitle.setBackgroundColor(ContextCompat.getColor(context, R.color.guidestyle_black)) headerTitle.setTextColor(ContextCompat.getColor(context, R.color.guidestyle_white)) colorName.setBackgroundColor(ContextCompat.getColor(context, R.color.guidestyle_black)) colorName.setTextColor(ContextCompat.getColor(context, R.color.guidestyle_white)) val name = colorPair.first.split("_") if (name.size > 1) { headerTitle.text = name[0] } } else { headerTitle.setBackgroundColor(ContextCompat.getColor(context, R.color.guidestyle_white)) headerTitle.setTextColor(ContextCompat.getColor(context, R.color.guidestyle_black)) colorName.setBackgroundColor(ContextCompat.getColor(context, R.color.guidestyle_white)) colorName.setTextColor(ContextCompat.getColor(context, R.color.guidestyle_black)) } color.setBackgroundColor(ContextCompat.getColor(context, colorPair.second)) color.text = Integer.toHexString(ContextCompat.getColor(context, colorPair.second)) } } }
0
Kotlin
0
0
ed6857ecc447b5062c90284424d261e94844a0b3
2,482
guidestyle-android-client
Apache License 2.0
serverless-simulator/opendc/opendc-compute/src/test/kotlin/com/atlarge/opendc/compute/virt/HypervisorTest.kt
atlarge-research
297,702,102
false
{"Jupyter Notebook": 11330813, "Kotlin": 547073, "Python": 15018, "R": 1048}
/* * MIT License * * Copyright (c) 2020 atlarge-research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.atlarge.opendc.compute.virt import com.atlarge.odcsim.SimulationEngineProvider import com.atlarge.opendc.compute.core.ProcessingUnit import com.atlarge.opendc.compute.core.Flavor import com.atlarge.opendc.compute.core.ProcessingNode import com.atlarge.opendc.compute.core.image.FlopsApplicationImage import com.atlarge.opendc.compute.metal.driver.SimpleBareMetalDriver import com.atlarge.opendc.compute.virt.driver.VirtDriver import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import java.util.ServiceLoader import java.util.UUID /** * Basic test-suite for the hypervisor. */ internal class HypervisorTest { /** * A smoke test for the bare-metal driver. */ @OptIn(ExperimentalCoroutinesApi::class) @Test fun smoke() { val provider = ServiceLoader.load(SimulationEngineProvider::class.java).first() val system = provider("test") val root = system.newDomain("root") root.launch { val vmm = HypervisorImage val workloadA = FlopsApplicationImage(UUID.randomUUID(), "<unnamed>", emptyMap(), 1_000, 1) val workloadB = FlopsApplicationImage(UUID.randomUUID(), "<unnamed>", emptyMap(), 2_000, 1) val driverDom = root.newDomain("driver") val cpuNode = ProcessingNode("Intel", "Xeon", "amd64", 1) val cpus = List(1) { ProcessingUnit(cpuNode, it, 2000.0) } val metalDriver = SimpleBareMetalDriver(driverDom, UUID.randomUUID(), "test", emptyMap(), cpus, emptyList()) metalDriver.init() metalDriver.setImage(vmm) val node = metalDriver.start() node.server?.events?.onEach { println(it) }?.launchIn(this) delay(5) val flavor = Flavor(1, 0) val vmDriver = metalDriver.refresh().server!!.services[VirtDriver] vmDriver.events.onEach { println(it) }.launchIn(this) val vmA = vmDriver.spawn("a", workloadA, flavor) vmA.events.onEach { println(it) }.launchIn(this) val vmB = vmDriver.spawn("b", workloadB, flavor) vmB.events.onEach { println(it) }.launchIn(this) } runBlocking { system.run() system.terminate() } } }
0
Jupyter Notebook
1
2
11c772bcb3fc7a7c2590d6ed6ab979b78cb9fec9
3,614
opendc-serverless
MIT License
app/android/ui/core/public/src/main/kotlin/build/wallet/ui/components/status/StatusBanner.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.ui.components.status import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import build.wallet.statemachine.core.Icon import build.wallet.ui.components.icon.IconImage import build.wallet.ui.components.icon.IconStyle import build.wallet.ui.components.label.Label import build.wallet.ui.components.label.LabelTreatment import build.wallet.ui.compose.thenIf import build.wallet.ui.model.icon.IconImage import build.wallet.ui.model.icon.IconModel import build.wallet.ui.model.icon.IconSize import build.wallet.ui.model.status.StatusBannerModel import build.wallet.ui.theme.WalletTheme import build.wallet.ui.tokens.LabelType // All status banners currently use a warning background color val StatusBannerModel.backgroundColor: Color @Composable get() = WalletTheme.colors.warning @Composable fun StatusBanner(model: StatusBannerModel) { Column( modifier = Modifier .fillMaxWidth() .background(model.backgroundColor) .thenIf(model.onClick != null) { model.onClick?.let { Modifier.clickable( indication = null, interactionSource = remember { MutableInteractionSource() }, onClick = it ) } ?: Modifier } .padding(horizontal = 20.dp) .padding(top = 12.dp, bottom = 16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Row(verticalAlignment = Alignment.CenterVertically) { StatusBannerLabel(text = model.title, type = LabelType.Body3Medium) model.onClick?.let { IconImage( modifier = Modifier.padding(start = 4.dp), model = IconModel( iconImage = IconImage.LocalImage(Icon.SmallIconInformationFilled), iconSize = IconSize.XSmall ), style = IconStyle( color = WalletTheme.colors.warningForeground ) ) } } model.subtitle?.let { StatusBannerLabel(text = it, type = LabelType.Body4Regular) } } } @Composable private fun StatusBannerLabel( text: String, type: LabelType, ) { Label( text = text, type = type, treatment = LabelTreatment.Unspecified, color = WalletTheme.colors.warningForeground, alignment = TextAlign.Center ) }
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
2,902
bitkey
MIT License
app/src/main/java/com/example/tmdbapi/screens/commons/StandardScaffold.kt
EliYakubov7
791,484,600
false
{"Kotlin": 106735}
package com.example.tmdbapi.screens.commons import androidx.compose.foundation.layout.PaddingValues import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.currentBackStackEntryAsState import com.example.tmdbapi.model.BottomNavItem import com.example.tmdbapi.ui.theme.primaryDark import com.example.tmdbapi.ui.theme.primaryGray import com.example.tmdbapi.ui.theme.primaryPink @OptIn(ExperimentalMaterial3Api::class) @Composable fun StandardScaffold( navController: NavController, showBottomBar: Boolean = true, items: List<BottomNavItem> = listOf( BottomNavItem.Home, BottomNavItem.Favorites ), content: @Composable (paddingValues: PaddingValues) -> Unit, ) { Scaffold( bottomBar = { if(showBottomBar) { BottomNavigation( backgroundColor = primaryDark, contentColor = Color.White, elevation = 5.dp ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry?.destination items.forEach { item -> BottomNavigationItem( icon = { Icon(painterResource(id = item.icon), contentDescription = item.title) }, label = { Text(text = item.title, fontSize = 10.sp) }, selectedContentColor = primaryPink, unselectedContentColor = primaryGray, alwaysShowLabel = true, selected = currentDestination?.route?.contains(item.destination.route) == true, onClick = { navController.navigate(item.destination.route) { navController.graph.startDestinationRoute?.let { screenRoute -> popUpTo(screenRoute) { saveState = true } } launchSingleTop = true restoreState = true } } ) } } } } ) { paddingValues -> content(paddingValues) } }
0
Kotlin
0
0
6f688c61bc2e4987be664794bf068d2e92b7e911
3,118
Movies-App
Apache License 2.0
main/src/main/kotlin/desktopnotification/desktopnotification.kt
sacchie
394,621,052
false
null
package main.desktopnotification import main.Client import main.Notification import main.NotificationId import main.keywordmatch.matchKeyword import java.time.OffsetDateTime import java.time.ZoneOffset typealias Updater = (update: (cur: Set<NotificationId>) -> Set<NotificationId>) -> Unit interface Service { fun run(update: Updater, client: Client, keywords: List<String>) { update { curr -> val newlyFetched = client.fetchNotifications().filter { it.mentioned || keywords.any { keyword -> matchKeyword(it, keyword) } } val now = OffsetDateTime.now(ZoneOffset.UTC) val toSend = newlyFetched.filter { it.id !in curr } .filter { it.timestamp > now.minusMinutes(5) } send(toSend) curr + toSend.map { it.id } } } fun send(notifications: List<Notification>) }
25
Kotlin
2
0
91467034ecc0d53827241b96fccc980ca8b58393
865
satchi
MIT License
shared/src/commonMain/kotlin/com/shady/dogskmm/entities/Breed.kt
Shady-Selim
436,758,919
false
{"Kotlin": 13931, "Swift": 4751}
package com.shady.dogskmm.entities import kotlinx.serialization.Serializable @Serializable data class Breed( val id : Int, val name : String ) /*val weight : WeightHeight, val height : WeightHeight, val id : Int, val name : String, val bred_for : String, val breed_group : String, val life_span : String, val temperament : String, val origin : String, val reference_image_id : String*/
0
Kotlin
0
0
9a478398113b7d4f2de6a288c10f0b71c2118636
397
Dogs-KMM
Apache License 2.0
zircon.core/src/main/kotlin/org/codetome/zircon/api/builder/graphics/BoxBuilder.kt
mdr0id
142,499,841
true
{"Kotlin": 772586, "Java": 70338}
package org.codetome.zircon.api.builder.graphics import org.codetome.zircon.api.Size import org.codetome.zircon.api.TextCharacter import org.codetome.zircon.api.builder.Builder import org.codetome.zircon.api.builder.TextCharacterBuilder import org.codetome.zircon.api.graphics.Box import org.codetome.zircon.api.graphics.BoxType import org.codetome.zircon.api.graphics.StyleSet import org.codetome.zircon.internal.graphics.DefaultBox data class BoxBuilder(private var size: Size = Size.create(3, 3), private var style: StyleSet = StyleSetBuilder.defaultStyle(), private var boxType: BoxType = BoxType.BASIC, private var filler: Char = TextCharacter.empty().getCharacter()) : Builder<Box> { /** * Sets the size for the new [org.codetome.zircon.api.graphics.Box]. * Default is 3x3. */ fun size(size: Size) = also { this.size = size } /** * Sets the style for the resulting [org.codetome.zircon.api.graphics.Box]. */ fun style(style: StyleSet) = also { this.style = style } /** * The new [org.codetome.zircon.api.graphics.Box] will be filled by this [Char]. * Defaults to `EMPTY` character. */ fun filler(filler: Char) = also { this.filler = filler } /** * Sets the [BoxType] for the resulting [org.codetome.zircon.api.graphics.Box]. */ fun boxType(boxType: BoxType) = also { this.boxType = boxType } override fun build(): Box = DefaultBox( size = size, filler = TextCharacterBuilder.newBuilder() .styleSet(style) .character(filler) .build(), styleSet = style, boxType = boxType) override fun createCopy() = copy() companion object { /** * Creates a new [BoxBuilder] to build [org.codetome.zircon.api.graphics.Box]es. */ fun newBuilder() = BoxBuilder() } }
0
Kotlin
0
0
58cade5b8ecb2663d6880d3220db70f6e7bb6f91
2,019
zircon
MIT License
app/src/androidTest/java/com/chesire/nekome/helpers/AuthProviderExtensions.kt
ashishkharcheiuforks
256,973,577
true
{"Kotlin": 498067, "Ruby": 7559, "JavaScript": 64}
package com.chesire.nekome.helpers import com.chesire.nekome.kitsu.AuthProvider /** * Tells the [AuthProvider] that a user is logged in, used to skip login. */ fun AuthProvider.login() { accessToken = "fakeAccessToken" }
0
null
0
0
c941c4e1fed0ed76ff28948d9d9bfe7fa280117f
229
Nekome
Apache License 2.0
WeatherApp/app/src/main/java/mobg/g58093/weather_app/network/responses/WeatherResponse.kt
FilipeDevs
743,950,504
false
{"Kotlin": 106084}
package mobg.g58093.weather_app.network.responses import kotlinx.serialization.Serializable @Serializable data class WeatherResponse( val coord: Coords, val main: MainWeatherInfo, val weather: List<WeatherInfo>, val sys: SysInfo, val wind: WindInfo, val visibility: Int, val name: String, val timezone : Int )
0
Kotlin
0
1
829b681f18c1d8afeec243c9ca35f348cea38d20
354
weatherAppAndroid
MIT License
library/src/main/java/com/wahidabd/library/utils/coroutine/EmitResource.kt
wahidabd
705,005,842
false
{"Kotlin": 201319}
package com.wahidabd.library.utils.coroutine import com.wahidabd.library.data.Resource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow /** * Created by Wahid on 3/27/2023. * Github wahidabd. */ abstract class EmitResource <Request, Response> { private var result: Flow<Resource<Response>> = flow { emit(Resource.Loading()) when(val response = createCall().first()){ is Resource.Loading -> {} is Resource.Default -> {} is Resource.Empty -> {} is Resource.Failure -> { emit(Resource.fail(response.message)) } is Resource.Success -> { saveCallResult(response.data) } } } protected abstract suspend fun createCall(): Flow<Resource<Request>> protected abstract suspend fun saveCallResult(data: Request) fun asFlow(): Flow<Resource<Response>> = result }
0
Kotlin
0
7
e4b36cd6bfe6a60540c98aad4308c1dbb812c20a
978
onelib
MIT License
tests-with-me/src/main/java/com/github/aivanovski/testswithme/flow/runner/listener/FlowLifecycleListener.kt
aivanovski
815,197,496
false
{"Kotlin": 800559, "Clojure": 13655, "Shell": 1883, "Scala": 850, "Dockerfile": 375}
package com.github.aivanovski.testswithme.flow.runner.listener import arrow.core.Either import com.github.aivanovski.testswithme.entity.Flow import com.github.aivanovski.testswithme.entity.exception.FlowExecutionException import com.github.aivanovski.testswithme.flow.commands.StepCommand interface FlowLifecycleListener { fun onFlowStarted(flow: Flow) fun onFlowFinished( flow: Flow, result: Either<FlowExecutionException, Any> ) fun onStepStarted( flow: Flow, command: StepCommand, stepIndex: Int, attemptIndex: Int ) fun onStepFinished( flow: Flow, command: StepCommand, stepIndex: Int, result: Either<FlowExecutionException, Any> ) }
0
Kotlin
0
0
0366b4dc9afc396dcb782c2bf1cb8ad230895a18
751
tests-with-me
Apache License 2.0
Hora_Codar3-Kotlin/Act3(exc3).kt
cunhagustavo
862,427,443
false
{"Kotlin": 23694}
//3 - Escreva um algoritmo para imprimir os números de 1 (inclusive) a 10 (inclusive) em ordem decrescente. //Exemplo: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 fun main(){ var cont = 11 while (cont > 1){ cont = cont - 1 println("$cont") } }
0
Kotlin
0
0
ccdff9b1585380a2bd93b6ddf2bb588acea49bdf
254
Hora_Codar_Kotlin
MIT License
detekt-rules-naming/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/MatchingDeclarationName.kt
detekt
71,729,669
false
null
package io.gitlab.arturbosch.detekt.rules.naming import io.gitlab.arturbosch.detekt.api.ActiveByDefault import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Configuration import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.config import org.jetbrains.kotlin.com.intellij.psi.PsiFile import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtTypeAlias import org.jetbrains.kotlin.psi.psiUtil.isPrivate /** * "If a Kotlin file contains a single non-private class (potentially with related top-level declarations), * its name should be the same as the name of the class, with the .kt extension appended. * If a file contains multiple classes, or only top-level declarations, * choose a name describing what the file contains, and name the file accordingly. * Use camel humps with an uppercase first letter (e.g. ProcessDeclarations.kt). * * The name of the file should describe what the code in the file does. * Therefore, you should avoid using meaningless words such as "Util" in file names." - Official Kotlin Style Guide * * More information at: https://kotlinlang.org/docs/coding-conventions.html * * <noncompliant> * * class Foo // FooUtils.kt * * fun Bar.toFoo(): Foo = ... * fun Foo.toBar(): Bar = ... * * </noncompliant> * * <compliant> * * class Foo { // Foo.kt * fun stuff() = 42 * } * * fun Bar.toFoo(): Foo = ... * * </compliant> */ @ActiveByDefault(since = "1.0.0") class MatchingDeclarationName(config: Config) : Rule( config, "If a source file contains only a single non-private top-level class or object, " + "the file name should reflect the case-sensitive name plus the .kt extension." ) { @Configuration("name should only be checked if the file starts with a class or object") private val mustBeFirst: Boolean by config(true) @Configuration("kotlin multiplatform targets, used to allow file names like `MyClass.jvm.kt`") private val multiplatformTargets: List<String> by config(COMMON_KOTLIN_KMP_PLATFORM_TARGET_SUFFIXES) override fun visitKtFile(file: KtFile) { val declarations = file.declarations .asSequence() .filterIsInstance<KtClassOrObject>() .filterNot { it.isPrivate() } .toList() fun matchesFirstClassOrObjectCondition(): Boolean = !mustBeFirst || mustBeFirst && declarations.first() === file.declarations.first() fun hasNoMatchingTypeAlias(filename: String): Boolean = file.declarations.filterIsInstance<KtTypeAlias>().all { it.name != filename } if (declarations.size == 1 && matchesFirstClassOrObjectCondition()) { val declaration = declarations.first() val declarationName = declaration.name val filename = file.fileNameWithoutSuffix(multiplatformTargets) if (declarationName != filename && hasNoMatchingTypeAlias(filename)) { val entity = Entity.atName(declaration) report( CodeSmell( Entity(entity.name, entity.signature, entity.location, file), "The file name '$filename' " + "does not match the name of the single top-level declaration '$declarationName'." ) ) } } } companion object { private val COMMON_KOTLIN_KMP_PLATFORM_TARGET_SUFFIXES = listOf( "ios", "android", "js", "jvm", "native", "iosArm64", "iosX64", "macosX64", "mingwX64", "linuxX64" ) } } /** * Removes kotlin specific file name suffixes, e.g. .kt. * Note, will not remove other possible/known file suffixes like '.java' */ internal fun PsiFile.fileNameWithoutSuffix(multiplatformTargetSuffixes: List<String> = emptyList()): String { val fileName = this.name val suffixesToRemove = multiplatformTargetSuffixes.map { platform -> ".$platform.kt" } + listOf(".kt", ".kts") for (suffix in suffixesToRemove) { if (fileName.endsWith(suffix)) { return fileName.removeSuffix(suffix) } } return fileName }
190
null
772
6,253
c5d7ed3da2824534d0e15f8404ad4f1c59fb553c
4,436
detekt
Apache License 2.0
dependency-injection/src/main/java/studio/lunabee/di/RepositoryModule.kt
LunabeeStudio
624,544,471
false
null
/* * Copyright (c) 2023-2023 Lunabee Studio * * 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. * * Created by Lunabee Studio / Date - 4/7/2023 - for the oneSafe6 SDK. * Last modified 4/7/23, 12:30 AM */ package studio.lunabee.di import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityRetainedComponent import dagger.hilt.android.scopes.ActivityRetainedScoped import dagger.hilt.components.SingletonComponent import studio.lunabee.onesafe.domain.repository.AutoLockRepository import studio.lunabee.onesafe.domain.repository.ClipboardRepository import studio.lunabee.onesafe.domain.repository.ForceUpgradeRepository import studio.lunabee.onesafe.domain.repository.IconRepository import studio.lunabee.onesafe.domain.repository.IndexWordEntryRepository import studio.lunabee.onesafe.domain.repository.PasswordGeneratorConfigRepository import studio.lunabee.onesafe.domain.repository.RecentSearchRepository import studio.lunabee.onesafe.domain.repository.SafeItemDeletedRepository import studio.lunabee.onesafe.domain.repository.SafeItemFieldRepository import studio.lunabee.onesafe.domain.repository.SafeItemKeyRepository import studio.lunabee.onesafe.domain.repository.SafeItemRepository import studio.lunabee.onesafe.domain.repository.SecurityOptionRepository import studio.lunabee.onesafe.domain.repository.UrlMetadataRepository import studio.lunabee.onesafe.repository.repository.AutoLockRepositoryImpl import studio.lunabee.onesafe.repository.repository.ClipboardRepositoryImpl import studio.lunabee.onesafe.repository.repository.ForceUpgradeRepositoryImpl import studio.lunabee.onesafe.repository.repository.IconRepositoryImpl import studio.lunabee.onesafe.repository.repository.IndexWordEntryRepositoryImpl import studio.lunabee.onesafe.repository.repository.PasswordGeneratorConfigRepositoryImpl import studio.lunabee.onesafe.repository.repository.RecentSearchRepositoryImpl import studio.lunabee.onesafe.repository.repository.SafeItemDeletedRepositoryImpl import studio.lunabee.onesafe.repository.repository.SafeItemFieldRepositoryImpl import studio.lunabee.onesafe.repository.repository.SafeItemKeyRepositoryImpl import studio.lunabee.onesafe.repository.repository.SafeItemRepositoryImpl import studio.lunabee.onesafe.repository.repository.SecurityOptionRepositoryImpl import studio.lunabee.onesafe.repository.repository.UrlMetadataRepositoryImpl import javax.inject.Singleton @Module @InstallIn(ActivityRetainedComponent::class) interface RepositoryModule { @Binds @ActivityRetainedScoped fun bindSafeItemRepository(safeItemRepository: SafeItemRepositoryImpl): SafeItemRepository @Binds @ActivityRetainedScoped fun bindSafeItemDeletedRepository(safeItemDeletedRepository: SafeItemDeletedRepositoryImpl): SafeItemDeletedRepository @Binds @ActivityRetainedScoped fun bindSafeItemKeyRepository(safeItemKeyRepository: SafeItemKeyRepositoryImpl): SafeItemKeyRepository @Binds @ActivityRetainedScoped fun bindSafeItemFieldRepository(safeItemFieldRepository: SafeItemFieldRepositoryImpl): SafeItemFieldRepository @Binds @ActivityRetainedScoped fun bindIconRepository(iconRepository: IconRepositoryImpl): IconRepository @Binds @ActivityRetainedScoped fun bindUrlMetadataRepository(urlMetadataRepository: UrlMetadataRepositoryImpl): UrlMetadataRepository @Binds @ActivityRetainedScoped fun bindIndexWordEntryRepository(indexWordEntryRepository: IndexWordEntryRepositoryImpl): IndexWordEntryRepository @Binds @ActivityRetainedScoped fun bindForceUpgradeRepository(forceUpgradeRepositoryImpl: ForceUpgradeRepositoryImpl): ForceUpgradeRepository @Binds @ActivityRetainedScoped fun bindsRecentSearchRepository(recentSearchRepositoryImpl: RecentSearchRepositoryImpl): RecentSearchRepository @Binds @ActivityRetainedScoped fun bindsPasswordGeneratorConfigRepository( passwordGeneratorConfigRepositoryImpl: PasswordGeneratorConfigRepositoryImpl, ): PasswordGeneratorConfigRepository } @Module @InstallIn(SingletonComponent::class) interface RepositoryGlobalModule { @Binds @Singleton fun bindSecurityOptionRepository(securityOptionRepository: SecurityOptionRepositoryImpl): SecurityOptionRepository @Binds @Singleton fun bindClipboardRepository(clipboardRepository: ClipboardRepositoryImpl): ClipboardRepository @Binds @Singleton fun bindAutoLockRepository(autoLockRepositoryImpl: AutoLockRepositoryImpl): AutoLockRepository }
0
Kotlin
0
0
9e5d38b7c54e500062c4d8efcc61a753a7c6ddce
5,074
oneSafe6_SDK_Android
Apache License 2.0
backend/src/main/kotlin/metrik/project/infrastructure/github/feign/GithubFeignClient.kt
thoughtworks
351,856,572
false
null
package metrik.project.infrastructure.github.feign import feign.RequestInterceptor import feign.RequestTemplate import metrik.project.infrastructure.github.feign.response.BranchResponse import metrik.project.infrastructure.github.feign.response.CommitResponse import metrik.project.infrastructure.github.feign.response.MultipleRunResponse import metrik.project.infrastructure.github.feign.response.SingleRunResponse import org.springframework.cloud.openfeign.FeignClient import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestParam import java.net.URI @FeignClient( value = "github-api", url = "https://this-is-a-placeholder.com", decode404 = true, configuration = [GithubFeignClientConfiguration::class] ) interface GithubFeignClient { @GetMapping("/{owner}/{repo}/actions/runs") fun retrieveMultipleRuns( baseUrl: URI, @RequestHeader("credential") credential: String, @PathVariable("owner") owner: String, @PathVariable("repo") repo: String, @RequestParam("per_page", required = false) perPage: Int? = null, @RequestParam("page", required = false) pageIndex: Int? = null ): MultipleRunResponse? @GetMapping("/{owner}/{repo}/actions/runs/{runId}") fun retrieveSingleRun( baseUrl: URI, @RequestHeader("credential") credential: String, @PathVariable("owner") owner: String, @PathVariable("repo") repo: String, @PathVariable("runId") runId: String, ): SingleRunResponse? @GetMapping("/{owner}/{repo}/commits") @Suppress("LongParameterList") fun retrieveCommits( baseUrl: URI, @RequestHeader("credential") credential: String, @PathVariable("owner") owner: String, @PathVariable("repo") repo: String, @RequestParam("since", required = false) since: String? = null, @RequestParam("until", required = false) until: String? = null, @RequestParam("sha", required = false) branch: String? = null, @RequestParam("per_page", required = false) perPage: Int? = null, @RequestParam("page", required = false) pageIndex: Int? = null, ): List<CommitResponse>? @GetMapping("/{owner}/{repo}/branches") fun retrieveBranches( baseUrl: URI, @RequestHeader("credential") credential: String, @PathVariable("owner") owner: String, @PathVariable("repo") repo: String, ): List<BranchResponse>? } class GithubFeignClientConfiguration : RequestInterceptor { override fun apply(template: RequestTemplate?) { val token = "Bearer " + template!!.headers()["credential"]!!.first() template.header("Authorization", token) template.removeHeader("credential") } }
19
null
86
348
def6a52cb7339f6a422451710083177b9c79689a
2,904
metrik
MIT License
app/src/main/java/com/codepath/apps/restclienttemplate/TimelineActivity.kt
WazahatAttar
469,019,168
false
null
package com.codepath.apps.restclienttemplate import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.codepath.apps.restclienttemplate.models.Tweet import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler import okhttp3.Headers class TimelineActivity : AppCompatActivity() { lateinit var client: TwitterClient lateinit var rvTweets: RecyclerView lateinit var adapter: TweetsAdapter lateinit var swipeContainer: SwipeRefreshLayout val tweets = ArrayList<Tweet>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_timeline) client=TwitterApplication.getRestClient(this) swipeContainer= findViewById(R.id.swipeContainer) swipeContainer.setOnRefreshListener { Log.i("Wizzy","Refreshing timeline") populateHomeTimeline() } swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); adapter= TweetsAdapter(tweets) rvTweets= findViewById(R.id.rvTweets) rvTweets.layoutManager= LinearLayoutManager(this) rvTweets.adapter = adapter populateHomeTimeline() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.compose) { val intent = Intent(this, ComposeActivity::class.java) startActivityForResult(intent, REQUEST_CODE) } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if(resultCode == RESULT_OK && requestCode== REQUEST_CODE){ val tweet = data?.getParcelableExtra<Tweet>("tweet")!! tweets.add(0, tweet) adapter.notifyItemInserted(0) rvTweets.smoothScrollToPosition(0) } super.onActivityResult(requestCode, resultCode, data) } fun populateHomeTimeline() { client.getHomeTimeline(object : JsonHttpResponseHandler(){ override fun onFailure( statusCode: Int, headers: Headers?, response: String?, throwable: Throwable? ) { } override fun onSuccess(statusCode: Int, headers: Headers, json: JSON) { Log.i("Wizzy","Success yo!! ") adapter.clear() val jsnArray = json.jsonArray val newTweets = Tweet.fromJsonArray(jsnArray) tweets.addAll(newTweets) adapter.notifyDataSetChanged() swipeContainer.setRefreshing(false) } }) } companion object{ val REQUEST_CODE = 10 } }
2
Kotlin
0
0
cb46047ce88eb3dac788752874fb5d54c5311b35
3,352
RestClientTemplateKotlin
Apache License 2.0
falkon-dao/src/test/kotlin/com/jayrave/falkon/dao/query/QueryBuilderImplTest.kt
jayrave
65,279,209
false
null
package com.jayrave.falkon.dao.query import com.jayrave.falkon.dao.lib.qualifiedName import com.jayrave.falkon.dao.query.testLib.* import com.jayrave.falkon.dao.testLib.TableForTest import com.jayrave.falkon.sqlBuilders.lib.JoinInfo import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Predicate.OneArgPredicate import org.assertj.core.api.Assertions.assertThat import org.junit.Test /** * As of July 25, 2016, [com.jayrave.falkon.dao.query.lenient.QueryBuilderImpl] is being used * by [QueryBuilderImpl] under the hood. Therefore, this test class has only a few smoke tests * that touches almost all the functionality of [QueryBuilderImpl] */ class QueryBuilderImplTest { @Test fun testQueryingWithoutSettingAnything() { val bundle = Bundle.default() val table = bundle.table val engine = bundle.engine val querySqlBuilder = bundle.querySqlBuilder val builder = QueryBuilderImpl(table, querySqlBuilder) val actualQuery = builder.build() builder.compile() // build expected query val expectedSql = buildQuerySql(tableName = table.name, querySqlBuilder = querySqlBuilder) val expectedQuery = QueryImpl(listOf(table.name), expectedSql, emptyList()) // Verify assertQueryEquality(actualQuery, expectedQuery) assertThat(engine.compiledStatementsForQuery).hasSize(1) val statement = engine.compiledStatementsForQuery.first() assertThat(statement.tableNames).containsOnly(table.name) assertThat(statement.sql).isEqualTo(expectedSql) assertThat(statement.boundArgs).isEmpty() } @Test fun testQueryWithAllOptions() { val bundle = Bundle.default() val table = bundle.table val tableForJoin = TableForTest("table_for_join") val querySqlBuilder = bundle.querySqlBuilder val builder = QueryBuilderImpl(table, querySqlBuilder) builder .distinct() .select(table.int) .join(table.long, tableForJoin.blob) .where().eq(table.double, 5.0) .groupBy(table.blob) .orderBy(table.nullableFloat, true) .limit(5) .offset(8) // build & compile val actualQuery = builder.build() builder.compile() // build expected query val primaryTableName = table.name val expectedSql = buildQuerySql( tableName = primaryTableName, querySqlBuilder = bundle.querySqlBuilder, distinct = true, columns = listOf(SelectColumnInfoForTest(table.int.qualifiedName, null)), joinInfos = listOf(JoinInfoForTest( JoinInfo.Type.INNER_JOIN, table.long.qualifiedName, tableForJoin.name, tableForJoin.blob.qualifiedName )), whereSections = listOf(OneArgPredicate( OneArgPredicate.Type.EQ, table.double.qualifiedName )), groupBy = listOf(table.blob.qualifiedName), orderBy = listOf(OrderInfoForTest(table.nullableFloat.qualifiedName, true)), limit = 5, offset = 8 ) val expectedQuery = QueryImpl( listOf(table.name, tableForJoin.name), expectedSql, listOf(5.0) ) // Verify val engine = bundle.engine assertQueryEquality(actualQuery, expectedQuery) assertThat(engine.compiledStatementsForQuery).hasSize(1) val statement = engine.compiledStatementsForQuery.first() assertThat(statement.tableNames).containsOnly(table.name, tableForJoin.name) assertThat(statement.sql).isEqualTo(expectedSql) assertThat(statement.boundArgs).hasSize(1) assertThat(statement.doubleBoundAt(1)).isEqualTo(5.0) } }
6
Kotlin
2
12
ce42d553c578cd8e509bbfd7effc5d56bf3cdedd
3,894
falkon
Apache License 2.0
Project/app/src/main/java/com/kotlin/jaesungchi/jetpack_navigation/ThirdFragment.kt
Jaesungchi
245,988,193
false
null
package com.kotlin.jaesungchi.jetpack_navigation import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.Fragment import androidx.navigation.Navigation class ThirdFragment : Fragment(){ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_third_screen,container,false) view.findViewById<Button>(R.id.to_first_from_third).setOnClickListener{ Navigation.findNavController(view).navigate(R.id.action_global_first_screen) } view.findViewById<Button>(R.id.to_second_from_third).setOnClickListener{ Navigation.findNavController(view).navigate(R.id.action_global_second_screen) } return view } }
0
Kotlin
0
0
b4221b3934f3a721bc9d46363094f95c3c392d63
923
Jetpack-Navigation-Example
Apache License 2.0
Project/app/src/main/java/com/kotlin/jaesungchi/jetpack_navigation/ThirdFragment.kt
Jaesungchi
245,988,193
false
null
package com.kotlin.jaesungchi.jetpack_navigation import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.Fragment import androidx.navigation.Navigation class ThirdFragment : Fragment(){ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_third_screen,container,false) view.findViewById<Button>(R.id.to_first_from_third).setOnClickListener{ Navigation.findNavController(view).navigate(R.id.action_global_first_screen) } view.findViewById<Button>(R.id.to_second_from_third).setOnClickListener{ Navigation.findNavController(view).navigate(R.id.action_global_second_screen) } return view } }
0
Kotlin
0
0
b4221b3934f3a721bc9d46363094f95c3c392d63
923
Jetpack-Navigation-Example
Apache License 2.0
forgerock-auth/src/test/java/org/forgerock/android/auth/callback/BooleanAttributeInputCallbackTest.kt
ForgeRock
215,203,638
false
{"Java": 1350991, "Kotlin": 942810, "CSS": 2849, "FreeMarker": 2042, "C++": 785, "Makefile": 330}
/* * Copyright (c) 2023 ForgeRock. All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package org.forgerock.android.auth.callback import androidx.test.ext.junit.runners.AndroidJUnit4 import org.assertj.core.api.Assertions import org.json.JSONException import org.json.JSONObject import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class BooleanAttributeInputCallbackTest { @Test @Throws(JSONException::class) fun basicTest() { val raw = JSONObject("""{ "type": "BooleanAttributeInputCallback", "output": [ { "name": "name", "value": "happy" }, { "name": "prompt", "value": "Happy" }, { "name": "required", "value": true }, { "name": "policies", "value": { "policyRequirements": [ "VALID_TYPE" ], "fallbackPolicies": null, "name": "happy", "policies": [ { "policyRequirements": [ "VALID_TYPE" ], "policyId": "valid-type", "params": { "types": [ "boolean" ] } } ], "conditionalPolicies": null } }, { "name": "failedPolicies", "value": [] }, { "name": "validateOnly", "value": false }, { "name": "value", "value": false } ], "input": [ { "name": "IDToken2", "value": false }, { "name": "IDToken2validateOnly", "value": false } ] }""") val callback = BooleanAttributeInputCallback(raw, 0) Assertions.assertThat(callback.name).isEqualTo("happy") Assertions.assertThat(callback.prompt).isEqualTo("Happy") Assertions.assertThat(callback.isRequired).isTrue Assertions.assertThat(callback.policies.getString("name")).isEqualTo("happy") Assertions.assertThat(callback.failedPolicies).isEmpty() Assertions.assertThat(callback.validateOnly).isFalse Assertions.assertThat(callback.value).isFalse } }
22
Java
23
35
e423b0918be31db87c0cefff5dbaadee4a578989
3,107
forgerock-android-sdk
MIT License
src/day25/Day25.kt
dkoval
572,138,985
false
null
package day25 import readInput private const val DAY_ID = "25" fun main() { val snafuToIntDigits = mapOf('=' to -2, '-' to -1, '0' to 0, '1' to 1, '2' to 2) val intToSnafuDigits = mapOf(0 to '0', 1 to '1', 2 to '2', -2 to '=', -1 to '-') fun snafuToInt(num: String): Long { var ans = 0L for (digit in num) { ans *= 5 ans += snafuToIntDigits[digit]!! } return ans } fun intToSnafu(num: Long): String { // x % 5 is in {0, 1, 2, 3, 4} // now, remap the value to get a SNAFU digit // 0 -> 0, 1 -> 1, 2 -> 2, 3 -> -2, 4 -> -1 fun lastSnafuDigit(x: Long): Int { return ((x + 2) % 5 - 2).toInt() } var x = num val sb = StringBuilder() while (x > 0) { val digit = lastSnafuDigit(x) sb.append(intToSnafuDigits[digit]) x /= 5 x += if (digit < 0) 1 else 0 } return sb.reverse().toString() } fun part1(input: List<String>): String { val x = input.sumOf { snafuToInt(it) } return intToSnafu(x) } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == "2=-1=0") // base10 = 4890, snafu = 2=-1=0 val input = readInput("day${DAY_ID}/Day${DAY_ID}") println(part1(input)) // answer = 2-20=01--0=0=0=2-120 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
1,462
aoc-2022-in-kotlin
Apache License 2.0