path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/test/kotlin/no/nav/ApplicationTest.kt
navikt
505,610,197
false
{"Kotlin": 120859, "Shell": 313, "Dockerfile": 102}
package no.nav import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.testing.* import no.nav.plugins.configureMonitoring import no.nav.plugins.configureOpenApi import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class ApplicationTest { @Test internal fun testRoot() { testApplication { application { configureOpenApi() configureMonitoring() } val response = client.get("/swagger-ui") assertEquals(HttpStatusCode.OK, response.status) assertTrue(response.bodyAsText().contains("swagger-ui")) } } }
3
Kotlin
0
0
82279abcf326b96736bdb7f19cb36fd5626f3eee
790
modia-robot-api
MIT License
src/main/kotlin/com/atlassian/performance/tools/jiraactions/api/page/AdminAccess.kt
atlassian
162,422,950
false
null
package com.atlassian.performance.tools.jiraactions.api.page import com.atlassian.performance.tools.jiraactions.Patience import com.atlassian.performance.tools.jiraactions.api.WebJira import com.atlassian.performance.tools.jiraactions.api.webdriver.sendKeysWhenClickable import org.openqa.selenium.By import org.openqa.selenium.WebDriver import org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable class AdminAccess( private val driver: WebDriver, private val jira: WebJira, private val password: String ) { private val dropAdminRightsLocator = By.cssSelector( "#websudo-drop-from-protected-page, #websudo-drop-from-normal-page" ) private val passwordLocator = By.id( "login-form-authenticatePassword" ) fun isPrompted(): Boolean { if (isDropNotificationPresent()) { return false } return Patience().test { driver.isElementPresent(passwordLocator) } } fun isGranted(): Boolean { if (isDropNotificationPresent()) { return true } jira.goToSystemInfo() val granted = isPrompted().not() driver.navigate().back() return granted } /** * Navigates to a known admin page in order to gain admin access. * Useful as a workaround for dysfunctional admin pages, which don't enforce the admin access on their own. */ fun gainProactively() { jira.goToSystemInfo() gain() val navigation = driver.navigate() navigation.back() navigation.back() } fun gain() { driver.findElement(passwordLocator).sendKeysWhenClickable(driver, password) driver.findElement(By.id("login-form-submit")).click() } fun drop() { if (!isDropNotificationPresent()) { jira.goToDashboard().waitForDashboard() if (!isGranted()) { return } } driver.wait(elementToBeClickable(dropAdminRightsLocator)).click() DashboardPage(driver).waitForDashboard() if(isDropNotificationPresent()) { throw Exception("Unexpected state: Admin access was still present after dropping it") } } internal fun runWithAccess(runnable: () -> Unit) { val prompted = isPrompted() if (prompted) { gain() } runnable() if (prompted) { drop() } } private fun isDropNotificationPresent() = driver.findElements(dropAdminRightsLocator).isNotEmpty() }
8
null
31
26
10b363eda1e171f8342eaeeb6deac843b1d34df3
2,568
jira-actions
Apache License 2.0
app/src/main/java/im/status/keycard/connect/Registry.kt
status-im
218,495,731
false
null
package im.status.keycard.connect import android.annotation.SuppressLint import android.app.Activity import android.nfc.NfcAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import im.status.keycard.android.NFCCardManager import im.status.keycard.connect.card.CardScriptExecutor import im.status.keycard.connect.card.ScriptListener import im.status.keycard.connect.data.PINCache import im.status.keycard.connect.data.PairingManager import im.status.keycard.connect.data.SettingsManager import im.status.keycard.connect.net.EthereumRPC import im.status.keycard.connect.net.WalletConnect import im.status.keycard.connect.net.WalletConnectListener import org.walletconnect.Session @SuppressLint("StaticFieldLeak") object Registry { lateinit var pinCache: PINCache private set lateinit var pairingManager: PairingManager private set lateinit var settingsManager: SettingsManager private set lateinit var mainActivity: Activity private set lateinit var scriptExecutor: CardScriptExecutor private set lateinit var cardManager: NFCCardManager private set lateinit var nfcAdapter: NfcAdapter private set lateinit var walletConnect: WalletConnect private set lateinit var ethereumRPC: EthereumRPC private set private fun moshiAddKotlin() { val factories = Moshi::class.java.getDeclaredField("BUILT_IN_FACTORIES") factories.isAccessible = true @Suppress("UNCHECKED_CAST") val value = factories.get(null) as java.util.ArrayList<Any> value.add(0, KotlinJsonAdapterFactory()) } fun init(activity: Activity, listener: ScriptListener, wcListener: WalletConnectListener) { //TODO: remove this hack, it is needed now because KEthereum does not add the KotlinJsonAdapterFactory moshiAddKotlin() this.mainActivity = activity pairingManager = PairingManager(activity) pinCache = PINCache() settingsManager = SettingsManager(activity) nfcAdapter = NfcAdapter.getDefaultAdapter(activity) scriptExecutor = CardScriptExecutor(listener) cardManager = NFCCardManager() cardManager.setCardListener(scriptExecutor) cardManager.start() ethereumRPC = EthereumRPC(settingsManager.rpcEndpoint) walletConnect = WalletConnect(wcListener, settingsManager.bip32Path, settingsManager.chainID) } }
5
Kotlin
11
21
5650f448ece63135b6e385e7146ee91430473911
2,501
keycard-connect
Apache License 2.0
reporter-pivotal/src/main/java/debug_artist/reporter_pivotaltracker/PivotalService.kt
rwdxll
116,653,954
true
{"Kotlin": 53190, "Java": 22482, "Prolog": 3398, "Shell": 1895, "IDL": 489}
package debug_artist.reporter_pivotaltracker import io.reactivex.Observable import okhttp3.MultipartBody import retrofit2.Response import retrofit2.http.* interface PivotalService { @POST("/services/v5/projects/{project_id}/stories") fun postStory(@Path("project_id") projectId: String, @Body story: StoryRequestBody): Observable<Response<Story>> @POST("/services/v5/projects/{project_id}/stories/{story_id}/comments ") fun postComment(@Path("project_id") projectId: String, @Path("story_id") storyId: String, @Body comment: Comment): Observable<Response<Any>> @Multipart @POST("/services/v5/projects/{project_id}/uploads") fun upload(@Path("project_id") projectId: String, @Part file: MultipartBody.Part): Observable<Response<Attachment>> }
0
Kotlin
0
0
22b9b2f2e0104ad99e3869cba30fb50f0223a5d5
827
debug-artist
Apache License 2.0
app/src/main/java/com/example/android/navigation/GameOverFragment.kt
luannguyen252
423,660,854
false
{"Kotlin": 15235}
package com.example.android.navigation import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.navigation.findNavController import com.example.android.navigation.databinding.FragmentGameOverBinding class GameOverFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding: FragmentGameOverBinding = DataBindingUtil.inflate( inflater, R.layout.fragment_game_over, container, false) binding.tryAgainButton.setOnClickListener { view: View -> view.findNavController().navigate(GameOverFragmentDirections.actionGameOverFragmentToGameFragment()) } return binding.root } }
0
Kotlin
0
1
b989b19eb46bf08118510cab4429f9e906cfc2a3
914
my-android-journey
MIT License
app/src/test/kotlin/no/nav/k9punsj/rest/server/PunsjJournalpostInfoRoutesTest.kt
navikt
216,808,662
false
null
package no.nav.k9punsj.rest.server import com.fasterxml.jackson.module.kotlin.convertValue import io.mockk.junit5.MockKExtension import kotlinx.coroutines.runBlocking import no.nav.k9punsj.TestSetup import no.nav.k9punsj.db.datamodell.JsonB import no.nav.k9punsj.journalpost.SøkUferdigJournalposter import no.nav.k9punsj.objectMapper import no.nav.k9punsj.util.WebClientUtils.awaitStatuscode import no.nav.k9punsj.wiremock.k9SakToken import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.web.reactive.function.BodyInserters @ExtendWith(SpringExtension::class, MockKExtension::class) class PunsjJournalpostInfoRoutesTest{ private val client = TestSetup.client private val k9sakToken = "Bearer ${no.nav.helse.dusseldorf.testsupport.jws.NaisSts.k9SakToken()}" @Test fun `Får en liste med journalpostIder som ikke er ferdig behandlet av punsj`(): Unit = runBlocking { val res = client.get().uri { it.pathSegment("api", "journalpost", "uferdig", "1000000000000").build() }.header(HttpHeaders.AUTHORIZATION, k9sakToken) val status = res.awaitStatuscode() assertEquals(HttpStatus.OK, status) } @Test fun `Får en liste med journalpostIder som ikke er ferdig behandlet av punsj post`(): Unit = runBlocking { val json : JsonB = objectMapper().convertValue(SøkUferdigJournalposter("1000000000000", null)) val res = client.post().uri { it.pathSegment("api", "journalpost", "uferdig").build()} .header(HttpHeaders.AUTHORIZATION, k9sakToken) .body(BodyInserters.fromValue(json)) val status = res.awaitStatuscode() assertEquals(HttpStatus.OK, status) } }
9
Kotlin
2
1
d42013d04a36b05bce1750c912ae186626f45049
1,961
k9-punsj
MIT License
data/src/main/java/ca/bc/gov/data/datasource/remote/MedicationRemoteDataSource.kt
bcgov
414,797,174
false
{"Kotlin": 1344329, "Java": 582146}
package ca.bc.gov.data.datasource.remote import ca.bc.gov.common.const.MESSAGE_INVALID_RESPONSE import ca.bc.gov.common.const.PROTECTIVE_WORD_ERROR_CODE import ca.bc.gov.common.const.SERVER_ERROR import ca.bc.gov.common.exceptions.MyHealthException import ca.bc.gov.common.exceptions.ProtectiveWordException import ca.bc.gov.data.datasource.remote.api.HealthGatewayPrivateApi import ca.bc.gov.data.datasource.remote.model.base.Action import ca.bc.gov.data.datasource.remote.model.response.MedicationStatementResponse import ca.bc.gov.data.utils.safeCall import javax.inject.Inject /* * Created by amit_metri on 08,February,2022 */ class MedicationRemoteDataSource @Inject constructor( private val healthGatewayPrivateApi: HealthGatewayPrivateApi ) { suspend fun getMedicationStatement( accessToken: String, hdid: String, protectiveWord: String? ): MedicationStatementResponse { val response = safeCall { healthGatewayPrivateApi.getMedicationStatement(hdid, accessToken, protectiveWord) } ?: throw MyHealthException(SERVER_ERROR, MESSAGE_INVALID_RESPONSE) if (response.error != null && response.error.action != Action.REFRESH) { if (response.error.action?.code == Action.PROTECTED.code) { throw ProtectiveWordException(PROTECTIVE_WORD_ERROR_CODE, response.error.message) } throw MyHealthException(SERVER_ERROR, response.error.message) } // TODO: 08/02/22 Response validations to be placed return response } }
6
Kotlin
5
5
fb45bb6e75c979c509f6424ace7f4028a5577bb0
1,558
myhealthBC-android
Apache License 2.0
app/src/main/java/com/example/androidfirebaselogin/views/services/RegisterService.kt
justapixel
371,198,966
false
null
package com.example.androidfirebaselogin.views.services import android.app.DatePickerDialog import android.os.Bundle import android.widget.ArrayAdapter import android.widget.DatePicker import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import com.example.androidfirebaselogin.R import com.example.androidfirebaselogin.extensions.Extensions.toast import com.example.androidfirebaselogin.utils.FirebaseUtils import com.google.firebase.firestore.FirebaseFirestore import kotlinx.android.synthetic.main.activity_register_service.* import java.text.SimpleDateFormat import java.util.* // https://www.tutorialkart.com/kotlin-android/android-datepicker-kotlin-example/ class RegisterService : AppCompatActivity() { lateinit var serviceType: String lateinit var selectedServiceType: String lateinit var descService: String lateinit var dateService: String lateinit var clientSelect: String private val calend: Calendar = Calendar.getInstance() lateinit var signUpInputArray: Array<EditText> private val store = FirebaseFirestore.getInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register_service) signUpInputArray = arrayOf(serviceTypeInput, descInputEditText, datePickerInputEditText, clientInputEditText) datePickerInputEditText.setText("--/--/----") serviceType = intent.getStringExtra("serviceType")!! val items = listOf<String>("Eixo e Suspensão", "Alinhamento", "Motor e Eletrica", "Freios e Cambagem") val adapter = ArrayAdapter(this, R.layout.dropdown_item, items) serviceTypeInput.setAdapter(adapter) serviceTypeInput.setText(serviceType, false) val dateSetListener = DatePickerDialog.OnDateSetListener { _: DatePicker, year, monthOfYear, dayofMonth -> calend.set(Calendar.YEAR, year) calend.set(Calendar.MONTH, monthOfYear) calend.set(Calendar.DAY_OF_MONTH, dayofMonth) updateDateInView() } datePickerInputEditText.setOnClickListener { DatePickerDialog( this@RegisterService, dateSetListener, // set DatePickerDialog to point to today's date when it loads up calend.get(Calendar.YEAR), calend.get(Calendar.MONTH), calend.get(Calendar.DAY_OF_MONTH) ).show() } store.collection("users").whereEqualTo("type", "Cliente").get().addOnSuccessListener { documents -> val arrayClientList = ArrayList<String>() for(document in documents){ arrayClientList.add(document.get("email") as String) } val clientAdapter = ArrayAdapter(this, R.layout.dropdown_item, arrayClientList) clientInputEditText.setAdapter(clientAdapter) clientInputEditText.threshold = 3 }.addOnFailureListener { toast("Falha ao buscar clientes") } cancelButton.setOnClickListener{ finish() } createServiceButton.setOnClickListener { createService() } } private fun updateDateInView(){ val myFormat = "dd/MM/yyyy" val sdf = SimpleDateFormat(myFormat, Locale.US) datePickerInputEditText.setText(sdf.format(calend.time)) } private fun notEmpty(): Boolean = descInputEditText.text.toString().trim().isNotEmpty() && datePickerInputEditText.text.toString().trim().isNotEmpty() && clientInputEditText.text.toString().trim().isNotEmpty() && serviceTypeInput.text.toString().trim().isNotEmpty() private fun createService (){ if (notEmpty()){ signUpInputArray.forEach { input -> if (input.text.toString().trim().isEmpty()) { input.error = "Não pode ser vazio" } } } selectedServiceType = serviceTypeInput.text.toString() descService = descInputEditText.text.toString() dateService = datePickerInputEditText.text.toString() clientSelect = clientInputEditText.text.toString() val service = hashMapOf<String, Any>( "id" to FirebaseUtils.firebaseAuth.uid.toString(), "type" to selectedServiceType, "description" to descService, "date" to dateService, "userId" to clientSelect, "status" to "Em andamento" ) store.collection("services") .document() .set(service) .addOnCompleteListener { storeTask -> if(storeTask.isSuccessful){ finish() } else { toast("Falha ao adicionar serviço!") } } } }
0
Kotlin
0
0
f81b880036f900b94680175be4574f811cc04659
4,938
AndroidFirebaseLogin
MIT License
bidrag-beregn-særbidrag/src/main/kotlin/no/nav/bidrag/beregn/særbidrag/core/felles/FellesBeregning.kt
navikt
248,744,235
false
{"Kotlin": 1930941}
package no.nav.bidrag.beregn.særbidrag.core.felles import no.nav.bidrag.beregn.core.bo.Periode import no.nav.bidrag.beregn.core.bo.SjablonPeriode import no.nav.bidrag.beregn.core.bo.SjablonPeriodeNavnVerdi import java.math.BigDecimal import java.time.LocalDate open class FellesBeregning { // Mapper ut sjablonverdier til ResultatBeregning (dette for å sikre at kun sjabloner som faktisk er brukt legges ut i grunnlaget for beregning) protected fun byggSjablonResultatListe( sjablonNavnVerdiMap: Map<String, BigDecimal>, sjablonPeriodeListe: List<SjablonPeriode>, ): List<SjablonPeriodeNavnVerdi> { val sjablonPeriodeNavnVerdiListe = mutableListOf<SjablonPeriodeNavnVerdi>() sjablonNavnVerdiMap.forEach { (sjablonNavn: String, sjablonVerdi: BigDecimal) -> sjablonPeriodeNavnVerdiListe.add( SjablonPeriodeNavnVerdi( periode = hentPeriode(sjablonPeriodeListe = sjablonPeriodeListe, sjablonNavn = sjablonNavn), navn = sjablonNavn, verdi = sjablonVerdi, ), ) } return sjablonPeriodeNavnVerdiListe.sortedBy { it.navn } } private fun hentPeriode(sjablonPeriodeListe: List<SjablonPeriode>, sjablonNavn: String): Periode = sjablonPeriodeListe .filter { it.sjablon.navn == modifiserSjablonNavn(sjablonNavn) } .map { it.getPeriode() } .firstOrNull() ?: Periode(datoFom = LocalDate.MIN, datoTil = LocalDate.MAX) // Enkelte sjablonnavn må justeres for å finne riktig dato private fun modifiserSjablonNavn(sjablonNavn: String) = when { sjablonNavn == "UnderholdBeløp" || sjablonNavn == "BoutgiftBeløp" -> "Bidragsevne" sjablonNavn.startsWith("Trinnvis") -> "TrinnvisSkattesats" else -> sjablonNavn } }
6
Kotlin
0
1
f51a1b676e058fe653499d1ebf8fcaa90358963d
1,839
bidrag-beregn-felles
MIT License
features/numbers-trivia/src/main/java/br/com/andretortolano/numbers_trivia/ui/NumbersTriviaActivity.kt
andretortolano
300,768,631
false
null
package br.com.andretortolano.numbers_trivia.ui import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import br.com.andretortolano.numbers_trivia.R import br.com.andretortolano.numbers_trivia.databinding.NumbersTriviaBinding import br.com.andretortolano.numbers_trivia.di.DaggerFeatureComponent import br.com.andretortolano.numbers_trivia.presentation.NumbersTriviaViewModel import br.com.andretortolano.numbers_trivia.presentation.NumbersTriviaViewModelFactory import br.com.andretortolano.shared.di.SharedComponent import dagger.hilt.android.EntryPointAccessors import javax.inject.Inject class NumbersTriviaActivity : AppCompatActivity() { companion object { fun getIntent(context: Context): Intent { return Intent(context, NumbersTriviaActivity::class.java) } } @Inject lateinit var viewModelFactory: NumbersTriviaViewModelFactory private val viewModel by lazy { viewModelFactory.getViewModel(this) } private var _binding: NumbersTriviaBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { DaggerFeatureComponent.builder() .context(this) .featureDependencies(EntryPointAccessors.fromApplication(applicationContext, SharedComponent::class.java)) .build() .inject(this) super.onCreate(savedInstanceState) _binding = NumbersTriviaBinding.inflate(layoutInflater) setContentView(binding.root) viewModel.state.observe(this, { renderState(it) }) binding.searchNumber .setOnClickListener { viewModel.searchNumberTrivia(binding.number.text.toString().toLong()) } binding.searchRandom .setOnClickListener { viewModel.searchRandomTrivia() } } override fun onDestroy() { super.onDestroy() _binding = null } private fun renderState(state: NumbersTriviaViewModel.ViewState) { when (state) { NumbersTriviaViewModel.ViewState.Idle -> renderIdleState() NumbersTriviaViewModel.ViewState.Loading -> renderLoadingState() is NumbersTriviaViewModel.ViewState.NumberTriviaFound -> renderFoundState(state) NumbersTriviaViewModel.ViewState.NumberTriviaNotFound -> renderNotFoundState() NumbersTriviaViewModel.ViewState.NoConnection -> renderNoConnectivityState() } } private fun renderIdleState() { binding.trivia.visibility = View.GONE binding.triviaLoader.visibility = View.GONE } private fun renderLoadingState() { binding.trivia.visibility = View.GONE binding.triviaLoader.visibility = View.VISIBLE } private fun renderFoundState(state: NumbersTriviaViewModel.ViewState.NumberTriviaFound) { binding.trivia.text = state.numberTrivia.trivia binding.trivia.visibility = View.VISIBLE binding.triviaLoader.visibility = View.GONE } private fun renderNotFoundState() { binding.trivia.text = getString(R.string.no_trivia_found) binding.trivia.visibility = View.VISIBLE binding.triviaLoader.visibility = View.GONE } private fun renderNoConnectivityState() { binding.trivia.text = getString(R.string.no_connection) binding.triviaLoader.visibility = View.GONE } }
0
Kotlin
2
1
3bddd900279ec1c8ab31af4289f59355440edf96
3,448
clean-architecture-sample
Apache License 2.0
src/main/kotlin/org/urielserv/uriel/core/database/schemas/CommandsSchema.kt
UrielHabboServer
729,131,075
false
null
package org.urielserv.uriel.core.database.schemas import org.ktorm.schema.Table import org.ktorm.schema.boolean import org.ktorm.schema.int import org.ktorm.schema.text import org.urielserv.uriel.game.command_system.CommandInfo object CommandsSchema : Table<CommandInfo>("commands") { val id = int("id").primaryKey().bindTo { it.id } val name = text("name").bindTo { it.name } val description = text("description").bindTo { it.description } val enabled = boolean("enabled").bindTo { it.enabled } val invokers = text("invokers").bindTo { it.rawInvokers } }
0
null
0
7
5ed582f93a604182f05f63d3057524d021513f99
581
Uriel
MIT License
src/test/kotlin/day14_extended_polymerization/ExtendedPolymerizationKtTest.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day14_extended_polymerization import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test private val WORKED_EXAMPLE = """ NNCB CH -> B HH -> N CB -> H NH -> C HB -> C HC -> B HN -> C NN -> C BH -> H NC -> B NB -> B BN -> B BB -> N BC -> B CC -> N CN -> C """.trimIndent() internal class ExtendedPolymerizationKtTest { @Test fun solve0() { assertEquals(1, solve(WORKED_EXAMPLE, 0)) } @Test fun solve1() { assertEquals(1, solve(WORKED_EXAMPLE, 1)) } @Test fun solve2() { assertEquals(5, solve(WORKED_EXAMPLE, 2)) } @Test fun solve3() { assertEquals(7, solve(WORKED_EXAMPLE, 3)) } @Test fun partOne() { assertEquals(1588, partOne(WORKED_EXAMPLE)) } @Test fun partTwo() { assertEquals(2188189693529, partTwo(WORKED_EXAMPLE)) } }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
960
aoc-2021
MIT License
core/src/main/kotlin/ru/mobileup/core/error_handling/ErrorHandler.kt
MobileUpLLC
495,305,519
false
{"Kotlin": 82696}
package ru.mobileup.core.error_handling import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.receiveAsFlow import me.aartikov.sesame.localizedstring.LocalizedString import ru.mobileup.core.message.data.MessageService import ru.mobileup.core.message.domain.MessageData import timber.log.Timber class ErrorHandler(private val messageService: MessageService) { private val unauthorizedEventChannel = Channel<Unit>(Channel.UNLIMITED) val unauthorizedEventFlow = unauthorizedEventChannel.receiveAsFlow() fun handleError(throwable: Throwable, showError: Boolean = true) { Timber.e(throwable) when { throwable is UnauthorizedException -> { unauthorizedEventChannel.trySend(Unit) } showError -> { messageService.showMessage(MessageData(text = throwable.errorMessage)) } } } fun handleErrorRetryable( throwable: Throwable, retryActionTitle: LocalizedString, retryAction: () -> Unit ) { Timber.e(throwable) when (throwable) { is UnauthorizedException -> { unauthorizedEventChannel.trySend(Unit) } else -> { messageService.showMessage( MessageData( text = throwable.errorMessage, actionTitle = retryActionTitle, action = retryAction ) ) } } } }
0
Kotlin
1
3
4f486b7a96775d262e8cd179ef70d7f0e2531f0b
1,550
Push-Notifications-Android
MIT License
core/model/src/main/java/earth/core/networkmodel/SignupRequestBody.kt
darkwhite220
733,589,658
false
{"Kotlin": 422132}
package earth.core.networkmodel data class SignupRequestBody( val nomprenom: String, val email: String, val telephone: String, val username: String, val reference: String, val newpass: String, val cfnewpass: String, val captcha: String, val btnAction: String, )
0
Kotlin
0
1
77d7bd5af138079eb25e2c8f6a728546dbab4cab
301
AlgeriaBillsOnline
The Unlicense
app/src/main/java/com/vlad1m1r/kotlintest/MyApplication.kt
VladimirWrites
86,824,178
false
null
/* * Copyright 2017 <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.vlad1m1r.kotlintest import android.app.Application import com.vlad1m1r.kotlintest.di.coroutineModule import com.vlad1m1r.kotlintest.di.dataModule import com.vlad1m1r.kotlintest.di.photosModule import org.koin.android.ext.android.startKoin class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin(this, listOf(dataModule, photosModule, coroutineModule)) } }
0
Kotlin
6
25
7bb76c69b41c2769b49e4f4f445452839f3cd5c2
1,022
KotlinSample
Apache License 2.0
platform/workspace/storage/testEntities/testSrc/com/intellij/platform/workspace/storage/testEntities/entities/WithNullsMultipleOpposite.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.platform.workspace.storage.testEntities.entities import com.intellij.platform.workspace.storage.EntitySource import com.intellij.platform.workspace.storage.GeneratedCodeApiVersion import com.intellij.platform.workspace.storage.MutableEntityStorage import com.intellij.platform.workspace.storage.WorkspaceEntity import com.intellij.platform.workspace.storage.EntityType import com.intellij.platform.workspace.storage.annotations.Child interface ParentWithNullsOppositeMultiple : WorkspaceEntity { val parentData: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : ParentWithNullsOppositeMultiple, WorkspaceEntity.Builder<ParentWithNullsOppositeMultiple> { override var entitySource: EntitySource override var parentData: String } companion object : EntityType<ParentWithNullsOppositeMultiple, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(parentData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ParentWithNullsOppositeMultiple { val builder = builder() builder.parentData = parentData builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ParentWithNullsOppositeMultiple, modification: ParentWithNullsOppositeMultiple.Builder.() -> Unit) = modifyEntity( ParentWithNullsOppositeMultiple.Builder::class.java, entity, modification) var ParentWithNullsOppositeMultiple.Builder.children: @Child List<ChildWithNullsOppositeMultiple> by WorkspaceEntity.extension() //endregion interface ChildWithNullsOppositeMultiple : WorkspaceEntity { val childData: String val parentEntity: ParentWithNullsOppositeMultiple? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ChildWithNullsOppositeMultiple, WorkspaceEntity.Builder<ChildWithNullsOppositeMultiple> { override var entitySource: EntitySource override var childData: String override var parentEntity: ParentWithNullsOppositeMultiple? } companion object : EntityType<ChildWithNullsOppositeMultiple, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(childData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildWithNullsOppositeMultiple { val builder = builder() builder.childData = childData builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ChildWithNullsOppositeMultiple, modification: ChildWithNullsOppositeMultiple.Builder.() -> Unit) = modifyEntity( ChildWithNullsOppositeMultiple.Builder::class.java, entity, modification) //endregion val ParentWithNullsOppositeMultiple.children: List<@Child ChildWithNullsOppositeMultiple> by WorkspaceEntity.extension()
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,232
intellij-community
Apache License 2.0
app/src/main/java/com/spacer/example/presentation/extensions/FragmentExtensions.kt
spacer-dev
404,248,319
false
null
package com.spacer.example.presentation.extensions import android.app.AlertDialog import androidx.fragment.app.Fragment import com.spacer.example.R import com.spacer.example.presentation.common.dialog.DialogMessage import com.spacer.example.presentation.common.progress.LoadingOption import com.spacer.example.presentation.main.MainActivity import com.spacer.sdk.data.SPRError object FragmentExtensions { private val Fragment.mainActivity get() = activity as? MainActivity fun Fragment.startLoading(option: LoadingOption = LoadingOption.Overlay) = mainActivity?.startLoading(option) fun Fragment.stopLoading() = mainActivity?.stopLoading() fun Fragment.showSuccessDialog(message: DialogMessage) { AlertDialog.Builder(activity) .setTitle(message.title) .setMessage(message.body) .show() } fun Fragment.showErrorDialog(error: SPRError) { AlertDialog.Builder(activity) .setTitle(context?.getString(R.string.error_title)) .setMessage(error.toString()) .show() } }
0
Kotlin
0
0
f48e5413d765d4a3895eec242d7909288e636ed5
1,080
spacer-sdk-android
MIT License
src/test/kotlin/com/github/avrokotlin/avro4k/io/AvroJsonOutputStreamTest.kt
avro-kotlin
194,962,508
false
null
package com.github.avrokotlin.avro4k.io import com.github.avrokotlin.avro4k.Avro import io.kotest.core.spec.style.StringSpec import io.kotest.inspectors.forAll import io.kotest.matchers.string.shouldContain import kotlinx.serialization.Serializable import java.io.ByteArrayOutputStream class AvroJsonOutputStreamTest : StringSpec({ @Serializable data class Work(val name: String, val year: Int) @Serializable data class Composer(val name: String, val birthplace: String, val works: List<Work>) val ennio = Composer("<NAME>", "rome", listOf(Work("legend of 1900", 1986), Work("ecstasy of gold", 1969))) val hans = Composer("<NAME>", "frankfurt", listOf(Work("batman begins", 2007), Work("dunkirk", 2017))) "AvroJsonOutputStream should write schemas" { val baos = ByteArrayOutputStream() Avro.default.openOutputStream(Composer.serializer()) { encodeFormat = AvroEncodeFormat.Json }.to(baos).write(ennio).write(hans).close() val jsonString = String(baos.toByteArray()) // the schema should be written in a json stream listOf("name", "birthplace", "works", "year").forAll { jsonString.shouldContain(it) } } })
27
null
36
187
f550163d19c60a1071df84f5c9671cb9e35364f4
1,227
avro4k
Apache License 2.0
core/src/main/kotlin/materialui/components/expansionpanelsummary/ExpansionPanelSummaryElementBuilder.kt
nikanorov
275,884,338
false
null
package materialui.components.expansionpanelsummary import kotlinext.js.jsObject import kotlinx.html.BUTTON import kotlinx.html.Tag import kotlinx.html.TagConsumer import materialui.components.buttonbase.ButtonBaseElementBuilder import materialui.components.getValue import materialui.components.iconbutton.IconButtonElementBuilder import materialui.components.iconbutton.iconButton import materialui.components.setValue import react.* class ExpansionPanelSummaryElementBuilder<T: Tag> internal constructor( type: ComponentType<ExpansionPanelSummaryProps>, classMap: List<Pair<Enum<*>, String>>, factory: (TagConsumer<Unit>) -> T ) : ButtonBaseElementBuilder<T, ExpansionPanelSummaryProps>(type, classMap, factory) { var Tag.expanded: Boolean? by materialProps var Tag.expandIcon: ReactElement? by materialProps var Tag.IconButtonProps: Props? by materialProps fun Tag.expandIcon(block: RBuilder.() -> Unit) { expandIcon = buildElement(block) } fun Tag.iconButtonProps(block: IconButtonElementBuilder<BUTTON>.() -> Unit) { IconButtonProps = buildElement { iconButton(block = block) }.props } fun <T2: Tag> Tag.iconButtonProps(factory: (TagConsumer<Unit>) -> T2, block: IconButtonElementBuilder<T2>.() -> Unit) { IconButtonProps = buildElement { iconButton(factory = factory, block = block) }.props } fun <P: Props> Tag.iconButtonProps(block: P.() -> Unit) { IconButtonProps = jsObject(block) } }
0
null
0
1
e4ece75415d9d844fbaa202ffc91f04c8415b4a4
1,463
kotlin-material-ui
MIT License
composeApp/src/commonMain/kotlin/eu/heha/cyclone/ui/ComicsViewModel.kt
sihamark
614,073,078
false
{"Kotlin": 97200, "Swift": 692}
package eu.heha.cyclone.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.heha.cyclone.model.ComicRepository import kotlinx.coroutines.launch class ComicsViewModel( private val comicRepository: ComicRepository ) : ViewModel() { val comics = comicRepository.comics fun wipeData() { viewModelScope.launch { comicRepository.wipeData() } } }
0
Kotlin
0
0
ae9a9ab8a11d212db7be0c0051752ba90d359661
425
ComicReader
Apache License 2.0
tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt
iterativelyhq
288,536,262
true
{"Java": 2118258, "Kotlin": 84292, "Groovy": 6460, "Shell": 1721}
package com.mparticle.tooling import org.json.JSONArray import org.json.JSONException import org.json.JSONObject data class ValidationResult(val eventType: String? = null, val data: ValidationResultData? = null, val error: DataPlanError? = null) { var originalString: String? = null companion object { fun from(json: String?): List<ValidationResult>? { return try { val jsonArray = JSONObject(json).getJSONArray("results") from(jsonArray) } catch (jse: JSONException) { listOf(ValidationResult().apply { originalString = json }) } } fun from(json: JSONArray): List<ValidationResult> { val validationResults = ArrayList<ValidationResult>() for(i in 0..json.length() - 1) { val validationResultJson = json.getJSONObject(i) val eventType = validationResultJson.optString("event_type") val data = ValidationResultData.from(validationResultJson.optJSONObject("data")) validationResults.add( ValidationResult(eventType, data) ) } return validationResults } } } data class ValidationResultData(val match: ValidationResultMatch?, val validationErrors: List<ValidationResultErrors>) { companion object { fun from(json: JSONObject?): ValidationResultData? { return json?.let { ValidationResultData(ValidationResultMatch.from(it.optJSONObject("match")), ValidationResultErrors.from(it.optJSONArray("validation_errors"))) } } } } data class ValidationResultMatch(val type: String, val criteria: Map<String, String>) { companion object { fun from(json: JSONObject?): ValidationResultMatch? { return json?.let { val type = it.optString("type") val criteria = it.optJSONObject("criteria")?.toHashMap() ?: hashMapOf() ValidationResultMatch(type, criteria) } } } } data class ValidationResultErrors(val validationErrorType: ValidationErrorType, val errorPointer: String?, val key: String?, val expected: String?, val actual: String?, val schemaKeyworkd: String?) { companion object { fun from(json: JSONArray): List<ValidationResultErrors> { val validationResultErrors = ArrayList<ValidationResultErrors>() for(i in 0..json.length() - 1) { val jsonObject = json.getJSONObject(i) val validationErrorTypeString = jsonObject.getString("validation_error_type") val validationErrorType = ValidationErrorType.forName(validationErrorTypeString) val errorPointer = jsonObject.optString("error_pointer") val key = jsonObject.optString("key") val expected = jsonObject.optString("expected") val actual = jsonObject.optString("actual") val schemaKeyword = jsonObject.optString("schema_keyword") validationResultErrors.add(ValidationResultErrors(validationErrorType, errorPointer, key, expected, actual, schemaKeyword)) } return validationResultErrors } } } enum class ValidationErrorType(val text: String) { Unplanned("unplanned"), MissingRequied("missing_required"), InvalidValue("invalid_value"), Unknown("unknown"); companion object { fun forName(text: String): ValidationErrorType { return values().first { it.text == text } } } } fun JSONObject.toHashMap(): HashMap<String, String> { val keys = keys() as? Iterator<String> val map = HashMap<String, String>() while(keys?.hasNext() == true) { val key = keys.next() map.put(key, getString(key)) } return map }
0
Java
0
1
6c3957e5ed71365c6709988d81b01c3c34eee853
3,864
mparticle-android-sdk
Apache License 2.0
app/src/main/java/com/mrboomdev/awery/util/ContentType.kt
MrBoomDeveloper
741,957,442
false
{"Java": 638908, "Kotlin": 251651}
package com.mrboomdev.awery.util enum class ContentType(val mimeType: String) { JSON("application/json"), APK("application/vnd.android.package-archive"), ANY("*/*"); override fun toString(): String { return mimeType } }
36
Java
0
199
8deadd4ccd331dd5adcc722caf7df1c350e058a2
249
Awery
Microsoft Public License
shared/src/main/java/com/google/samples/apps/iosched/shared/data/FirestoreExtensions.kt
google
18,347,476
false
null
/* * Copyright 2019 Google LLC * * 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.google.samples.apps.iosched.shared.data import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.FirebaseFirestore fun FirebaseFirestore.document2019(): DocumentReference = // This is a prefix for Firestore document for 2019 collection("google_io_events").document("2019")
77
null
6259
21,755
738e1e008096fad5f36612325275e80c33dbe436
926
iosched
Apache License 2.0
samples/journeyapp/src/main/java/com/pingidentity/samples/journeyapp/journey/JourneyViewModel.kt
ForgeRock
830,216,912
false
{"Kotlin": 452482}
/* * Copyright (c) 2024. PingIdentity. All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.pingidentity.samples.journeyapp.journey import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.pingidentity.journey.Journey import com.pingidentity.journey.module.Oidc import com.pingidentity.journey.start import com.pingidentity.logger.Logger import com.pingidentity.logger.STANDARD import com.pingidentity.orchestrate.ContinueNode import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch val forgeblock = Journey { logger = Logger.STANDARD serverUrl = "https://openam-sdks.forgeblocks.com/am" realm = "alpha" cookie = "5421aeddf91aa20" forceAuth = true // Oidc as module module(Oidc) { clientId = "AndroidTest" discoveryEndpoint = "https://openam-sdks.forgeblocks.com/am/oauth2/alpha/.well-known/openid-configuration" scopes = mutableSetOf("openid", "email", "address", "profile", "phone") redirectUri = "org.forgerock.demo:/oauth2redirect" //storage = dataStore } } val localhost = Journey { logger = Logger.STANDARD serverUrl = "http://192.168.86.32:8080/openam" realm = "root" // Oidc as module module(Oidc) { clientId = "AndroidTest" discoveryEndpoint = "http://192.168.86.32:8080/openam/oauth2/.well-known/openid-configuration" scopes = mutableSetOf("openid", "email", "address", "profile", "phone") redirectUri = "org.forgerock.demo:/oauth2redirect" //storage = dataStore } } val journey = forgeblock class JourneyViewModel(private var journeyName: String) : ViewModel() { var state = MutableStateFlow(JourneyState()) private set var loading = MutableStateFlow(false) private set init { start() } fun next(node: ContinueNode) { loading.update { true } viewModelScope.launch { val next = node.next() state.update { it.copy(node = next) } loading.update { false } } } fun start() { loading.update { true } viewModelScope.launch { val next = journey.start(journeyName) state.update { it.copy(node = next) } loading.update { false } } } fun refresh() { state.update { it.copy(node = it.node) } } companion object { fun factory( journeyName: String, ): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return JourneyViewModel(journeyName) as T } } } }
2
Kotlin
0
0
cb75e4da916db337f5cf8f628a98f68dc9121063
3,143
unified-sdk-android
MIT License
ProjetoBD/backEnd/login-api/src/main/kotlin/br/com/jhonnathan/domain/ports/UserRepository.kt
Jhonnathan-Jhonny
752,604,468
false
{"Kotlin": 132581}
package br.com.jhonnathan.domain.ports import br.com.jhonnathan.domain.entity.User import org.bson.types.ObjectId interface UserRepository { suspend fun save(user: User): Boolean suspend fun findById(objectId: ObjectId): User? suspend fun delete(objectId: ObjectId): Long suspend fun updateUser(objectId: ObjectId, user: User): Long suspend fun findByName(userName: String): User? }
0
Kotlin
0
0
9a4ae171296133bd31e7a3a75d4d112c37ed9903
404
Kotlin-AndroidStudio
MIT License
app/src/main/java/com/eyther/lumbridge/ui/theme/Color.kt
ruialmeida51
249,223,684
false
null
package com.eyther.lumbridge.ui.theme import androidx.compose.ui.graphics.Color val primaryLight = Color(0xFF6D5E0F) val onPrimaryLight = Color(0xFFFFFFFF) val primaryContainerLight = Color(0xFFF8E287) val onPrimaryContainerLight = Color(0xFF221B00) val secondaryLight = Color(0xFF665E40) val onSecondaryLight = Color(0xFFFFFFFF) val secondaryContainerLight = Color(0xFFEEE2BC) val onSecondaryContainerLight = Color(0xFF211B04) val tertiaryLight = Color(0xFF43664E) val onTertiaryLight = Color(0xFFFFFFFF) val tertiaryContainerLight = Color(0xFFC5ECCE) val onTertiaryContainerLight = Color(0xFF00210F) val errorLight = Color(0xFFBA1A1A) val onErrorLight = Color(0xFFFFFFFF) val errorContainerLight = Color(0xFFFFDAD6) val onErrorContainerLight = Color(0xFF410002) val backgroundLight = Color(0xFFFFF9EE) val onBackgroundLight = Color(0xFF1E1B13) val surfaceLight = Color(0xFFFFF9EE) val onSurfaceLight = Color(0xFF1E1B13) val surfaceVariantLight = Color(0xFFEAE2D0) val onSurfaceVariantLight = Color(0xFF4B4739) val outlineLight = Color(0xFF7C7767) val outlineVariantLight = Color(0xFFCDC6B4) val scrimLight = Color(0xFF000000) val inverseSurfaceLight = Color(0xFF333027) val inverseOnSurfaceLight = Color(0xFFF7F0E2) val inversePrimaryLight = Color(0xFFDBC66E) val surfaceDimLight = Color(0xFFE0D9CC) val surfaceBrightLight = Color(0xFFFFF9EE) val surfaceContainerLowestLight = Color(0xFFFFFFFF) val surfaceContainerLowLight = Color(0xFFFAF3E5) val surfaceContainerLight = Color(0xFFF4EDDF) val surfaceContainerHighLight = Color(0xFFEEE8DA) val surfaceContainerHighestLight = Color(0xFFE8E2D4) val primaryDark = Color(0xFFDBC66E) val onPrimaryDark = Color(0xFF3A3000) val primaryContainerDark = Color(0xFF534600) val onPrimaryContainerDark = Color(0xFFF8E287) val secondaryDark = Color(0xFFD1C6A1) val onSecondaryDark = Color(0xFF363016) val secondaryContainerDark = Color(0xFF4E472A) val onSecondaryContainerDark = Color(0xFFEEE2BC) val tertiaryDark = Color(0xFFA9D0B3) val onTertiaryDark = Color(0xFF143723) val tertiaryContainerDark = Color(0xFF2C4E38) val onTertiaryContainerDark = Color(0xFFC5ECCE) val errorDark = Color(0xFFFFB4AB) val onErrorDark = Color(0xFF690005) val errorContainerDark = Color(0xFF93000A) val onErrorContainerDark = Color(0xFFFFDAD6) val backgroundDark = Color(0xFF15130B) val onBackgroundDark = Color(0xFFE8E2D4) val surfaceDark = Color(0xFF15130B) val onSurfaceDark = Color(0xFFE8E2D4) val surfaceVariantDark = Color(0xFF4B4739) val onSurfaceVariantDark = Color(0xFFCDC6B4) val outlineDark = Color(0xFF969080) val outlineVariantDark = Color(0xFF4B4739) val scrimDark = Color(0xFF000000) val inverseSurfaceDark = Color(0xFFE8E2D4) val inverseOnSurfaceDark = Color(0xFF333027) val inversePrimaryDark = Color(0xFF6D5E0F) val surfaceDimDark = Color(0xFF15130B) val surfaceBrightDark = Color(0xFF3C3930) val surfaceContainerLowestDark = Color(0xFF100E07) val surfaceContainerLowDark = Color(0xFF1E1B13) val surfaceContainerDark = Color(0xFF222017) val surfaceContainerHighDark = Color(0xFF2D2A21) val surfaceContainerHighestDark = Color(0xFF38352B)
6
null
0
7
5dd18b22448b2435f0238cccfc11a6826f200748
3,078
lumbridge-android
MIT License
plugins-verifier-service/src/main/kotlin/org/jetbrains/plugins/verifier/service/service/verifier/VerifyPluginTask.kt
JetBrains
3,686,654
false
null
/* * Copyright 2000-2020 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.verifier.service.service.verifier import com.jetbrains.pluginverifier.PluginVerificationDescriptor import com.jetbrains.pluginverifier.PluginVerificationResult import com.jetbrains.pluginverifier.PluginVerifier import com.jetbrains.pluginverifier.dependencies.resolution.createIdeBundledOrPluginRepositoryDependencyFinder import com.jetbrains.pluginverifier.filtering.ProblemsFilter import com.jetbrains.pluginverifier.ide.IdeDescriptor import com.jetbrains.pluginverifier.ide.IdeDescriptorsCache import com.jetbrains.pluginverifier.plugin.PluginDetailsCache import com.jetbrains.pluginverifier.repository.PluginRepository import com.jetbrains.pluginverifier.resolution.DefaultClassResolverProvider import com.jetbrains.pluginverifier.verifiers.filter.DynamicallyLoadedFilter import com.jetbrains.pluginverifier.verifiers.packages.DefaultPackageFilter import org.jetbrains.plugins.verifier.service.tasks.ProgressIndicator import org.jetbrains.plugins.verifier.service.tasks.Task /** * Task that performs [scheduledVerification]. */ class VerifyPluginTask( private val scheduledVerification: ScheduledVerification, private val pluginDetailsCache: PluginDetailsCache, private val ideDescriptorsCache: IdeDescriptorsCache, private val pluginRepository: PluginRepository, private val problemsFilters: List<ProblemsFilter> ) : Task<PluginVerificationResult>("Check ${scheduledVerification.availableIde} against ${scheduledVerification.updateInfo}", "VerifyPlugin"), Comparable<VerifyPluginTask> { override fun execute(progress: ProgressIndicator): PluginVerificationResult { val cacheEntry = ideDescriptorsCache.getIdeDescriptorCacheEntry(scheduledVerification.availableIde.version) return cacheEntry.use { when (cacheEntry) { is IdeDescriptorsCache.Result.Found -> { val ideDescriptor = cacheEntry.ideDescriptor checkPluginWithIde(ideDescriptor) } is IdeDescriptorsCache.Result.NotFound -> { throw IllegalStateException("IDE ${scheduledVerification.availableIde} is not found: " + cacheEntry.reason) } is IdeDescriptorsCache.Result.Failed -> { throw IllegalStateException("Failed to get ${scheduledVerification.availableIde}: ${cacheEntry.reason}", cacheEntry.error) } } } } private fun checkPluginWithIde(ideDescriptor: IdeDescriptor): PluginVerificationResult { val dependencyFinder = createIdeBundledOrPluginRepositoryDependencyFinder( ideDescriptor.ide, pluginRepository, pluginDetailsCache ) val classResolverProvider = DefaultClassResolverProvider( dependencyFinder, ideDescriptor, DefaultPackageFilter(emptyList()) ) val verificationDescriptor = PluginVerificationDescriptor.IDE(ideDescriptor, classResolverProvider, scheduledVerification.updateInfo) return PluginVerifier( verificationDescriptor, problemsFilters, pluginDetailsCache, listOf(DynamicallyLoadedFilter()), false ).loadPluginAndVerify() } /** * Comparison result is used by the task manager * to order tasks execution. * * 1) Newer plugins first. * 2) Manually scheduled verifications first. */ override fun compareTo(other: VerifyPluginTask): Int { val updateIdCmp = other.scheduledVerification.updateInfo.updateId.compareTo(scheduledVerification.updateInfo.updateId) if (scheduledVerification.manually && other.scheduledVerification.manually) { return updateIdCmp } /** * Manually scheduled verification has priority. */ if (scheduledVerification.manually) { return -1 } if (other.scheduledVerification.manually) { return 1 } return updateIdCmp } }
6
null
38
178
4deec2e4e08c9ee4ce087697ef80b8b327703548
3,942
intellij-plugin-verifier
Apache License 2.0
feature/running/src/main/java/online/partyrun/partyrunapplication/feature/running/running/SingleRunningScreen.kt
SWM-KAWAI-MANS
649,352,661
false
{"Kotlin": 804908}
package online.partyrun.partyrunapplication.feature.running.running import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import kotlinx.coroutines.delay import online.partyrun.partyrunapplication.core.common.util.speakTTS import online.partyrun.partyrunapplication.core.common.util.vibrateSingle import online.partyrun.partyrunapplication.core.model.single.SingleRunnerDisplayStatus import online.partyrun.partyrunapplication.feature.running.R import online.partyrun.partyrunapplication.feature.running.running.component.ControlPanelColumn import online.partyrun.partyrunapplication.feature.running.util.RunningConstants.ARRIVAL_FLAG_DELAY import online.partyrun.partyrunapplication.feature.running.util.RunningConstants.RUNNER_GRAPHIC_Y_OFFSET import online.partyrun.partyrunapplication.feature.running.running.component.RunnerGraphic import online.partyrun.partyrunapplication.feature.running.running.component.RunningMetricsPanel import online.partyrun.partyrunapplication.feature.running.running.component.RunningTrack import online.partyrun.partyrunapplication.feature.running.running.component.SingleRunnerMarker import online.partyrun.partyrunapplication.feature.running.running.component.TrackDistanceDistanceBox import online.partyrun.partyrunapplication.feature.running.running.component.trackRatio import online.partyrun.partyrunapplication.feature.running.single.RunningServiceState import online.partyrun.partyrunapplication.feature.running.single.SingleContentUiState import online.partyrun.partyrunapplication.feature.running.single.SingleContentViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun SingleRunningScreen( singleContentUiState: SingleContentUiState, openRunningExitDialog: MutableState<Boolean>, singleContentViewModel: SingleContentViewModel = hiltViewModel() ) { val context = LocalContext.current if (singleContentUiState.runningServiceState == RunningServiceState.STARTED) { LaunchedEffect(Unit) { vibrateSingle(context) speakTTS(context, context.getString(R.string.tts_running_start)) } } Scaffold( modifier = Modifier.fillMaxSize() ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding( top = paddingValues.calculateTopPadding(), bottom = paddingValues.calculateBottomPadding() ), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.size(10.dp)) Row( modifier = Modifier .fillMaxWidth() .height(50.dp) ) { TrackDistanceDistanceBox( totalTrackDistance = singleContentUiState.selectedDistance ) } Spacer(modifier = Modifier.size(15.dp)) Column( modifier = Modifier .weight(1f) .fillMaxWidth() .padding(horizontal = 25.dp) ) { TrackWithUserAndRobot( singleContentViewModel = singleContentViewModel, targetDistance = singleContentUiState.selectedDistance, user = singleContentUiState.userStatus, robot = singleContentUiState.robotStatus ) } Column( modifier = Modifier .fillMaxWidth() .weight(0.5f) .padding(5.dp), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround ) { RunningMetricsPanel( title = stringResource(id = R.string.Kilometer) ) { Text( text = singleContentUiState.distanceInKm, style = MaterialTheme.typography.displayMedium, color = MaterialTheme.colorScheme.onPrimary ) } RunningMetricsPanel( title = stringResource(id = R.string.pace) ) { Text( text = singleContentUiState.instantPace, style = MaterialTheme.typography.displayMedium, color = MaterialTheme.colorScheme.onPrimary ) } } } Column( modifier = Modifier .fillMaxSize() .weight(1f) .clip(RoundedCornerShape(topStart = 45.dp, topEnd = 45.dp)) .shadow(elevation = 5.dp) .background(MaterialTheme.colorScheme.surface) .padding(5.dp), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally ) { ControlPanelColumn( context = context, singleContentUiState = singleContentUiState, singleContentViewModel = singleContentViewModel, openRunningExitDialog = openRunningExitDialog ) } } } } @Composable private fun TrackWithUserAndRobot( singleContentViewModel: SingleContentViewModel, targetDistance: Int, user: SingleRunnerDisplayStatus, robot: SingleRunnerDisplayStatus ) { var showArrivalFlag by remember { mutableStateOf(false) } LaunchedEffect(Unit) { delay(ARRIVAL_FLAG_DELAY) showArrivalFlag = true } BoxWithConstraints(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { val context = LocalContext.current val (trackWidth, trackHeight) = trackRatio(context) // 트랙 이미지의 실제 비율에 대한 컴포넌트 크기 // 트랙 이미지 표시 RunningTrack(showArrivalFlag) // 유저 렌더링 RenderRunner( singleContentViewModel, targetDistance, user, trackWidth, trackHeight, isUser = true ) // 로봇 렌더링 RenderRunner( singleContentViewModel, targetDistance, robot, trackWidth, trackHeight, isUser = false ) } } @Composable private fun RenderRunner( singleContentViewModel: SingleContentViewModel, targetDistance: Int, runner: SingleRunnerDisplayStatus, trackWidth: Double, trackHeight: Double, isUser: Boolean ) { val (currentX, currentY) = singleContentViewModel.mapDistanceToCoordinates( totalTrackDistance = targetDistance.toDouble(), distance = runner.distance, trackWidth = trackWidth, trackHeight = trackHeight ) val zIndex = if (isUser) 1f else 0f RunnerGraphic( currentX = currentX, currentY = currentY - RUNNER_GRAPHIC_Y_OFFSET, // 네임과 마커 프레임의 합 height가 110이므로 중간에 맞춰주기 위한 RUNNER_GRAPHIC_Y_OFFSET 오차보정 zIndex = zIndex, runnerNameContent = { Text( text = runner.runnerName, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onPrimary ) }, runnerMarker = { SingleRunnerMarker(runner) } ) } @Composable fun FixedWidthTimeText(hour: String, minute: String, second: String) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Text( modifier = Modifier.width(100.dp), text = hour, textAlign = TextAlign.End, style = MaterialTheme.typography.displayLarge, color = MaterialTheme.colorScheme.onPrimary ) Text( text = ":$minute:", style = MaterialTheme.typography.displayLarge, color = MaterialTheme.colorScheme.onPrimary ) Text( modifier = Modifier.width(100.dp), text = second, textAlign = TextAlign.Start, style = MaterialTheme.typography.displayLarge, color = MaterialTheme.colorScheme.onPrimary ) } }
0
Kotlin
1
14
fecbaf7c67cfa136e0633baaa2c708732069b190
10,215
party-run-application
MIT License
src/main/kotlin/org/rust/ide/intentions/visibility/MakePrivateIntention.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions.visibility import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.rust.lang.core.psi.ext.RsVisibility import org.rust.lang.core.psi.ext.RsVisibilityOwner class MakePrivateIntention : ChangeVisibilityIntention() { override val visibility: String get() = "private" override fun isApplicable(element: RsVisibilityOwner): Boolean = element.visibility != RsVisibility.Private override fun invoke(project: Project, editor: Editor, ctx: Context) { makePrivate(ctx.element) } }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
679
intellij-rust
MIT License
auth/src/main/java/studio/crud/feature/auth/authentication/rules/action/base/RuleActionHandler.kt
crud-studio
390,327,908
false
null
package studio.crud.feature.auth.authentication.rules.action.base import studio.crud.crudframework.utils.component.componentmap.annotation.ComponentMapKey import studio.crud.feature.auth.entity.model.Entity import studio.crud.feature.auth.authentication.rules.RuleActionType import studio.crud.feature.core.audit.RequestSecurityMetadata interface RuleActionHandler { @get:ComponentMapKey val actionType: RuleActionType fun handle(entity: Entity, securityMetadata: RequestSecurityMetadata) }
6
Kotlin
0
0
6cb1d5f7b3fc7117c9fbaaf6708ac93ae631e674
506
feature-depot
MIT License
helios-parser/src/main/kotlin/helios/parser/ByteBufferParser.kt
47degrees
118,187,374
false
null
package helios.parser import java.nio.ByteBuffer /** * Basic ByteBuffer parser. * * This assumes that the provided ByteBuffer is ready to be read. The * user is responsible for any necessary flipping/resetting of the * ByteBuffer before parsing. * * The parser makes absolute calls to the ByteBuffer, which will not * update its own mutable position fields. */ class ByteBufferParser<J>(val src: ByteBuffer) : SyncParser<J>, ByteBasedParser<J> { private val start = src.position() private val limit = src.limit() - start private var lineState = 0 override fun line(): Int = lineState override fun newline(i: Int) { lineState += 1 } override fun column(i: Int) = i override fun close() { src.position(src.limit()) } override fun reset(i: Int): Int = i override fun checkpoint(state: Int, i: Int, stack: List<FContext<J>>) {} override fun byte(i: Int): Byte = src.get(i + start) override fun at(i: Int): Char = src.get(i + start).toChar() override fun at(i: Int, k: Int): CharSequence { val len = k - i val arr = ByteArray(len) src.position(i + start) src.get(arr, 0, len) src.position(start) return String(arr, utf8) } override fun atEof(i: Int) = i >= limit }
27
null
25
166
46c3c2e6e113257605b72761e797735e51f8f46d
1,305
helios
Apache License 2.0
litfass-server/src/test/kotlin/lit/fass/server/schedule/QuartzCollectionSchedulerServiceTest.kt
aemaem
158,592,240
false
null
package lit.fass.server.schedule import io.mockk.MockKAnnotations import io.mockk.confirmVerified import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.verify import lit.fass.server.config.yaml.model.CollectionConfig import lit.fass.server.execution.ExecutionService import lit.fass.server.helper.TestTypes.UnitTest import lit.fass.server.persistence.Datastore.POSTGRES import lit.fass.server.retention.RetentionService import org.assertj.core.api.Assertions.* import org.awaitility.Awaitility.await import org.awaitility.Awaitility.with import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.boot.test.system.CapturedOutput import org.springframework.boot.test.system.OutputCaptureExtension import java.util.concurrent.TimeUnit.SECONDS import java.util.concurrent.atomic.AtomicBoolean /** * @author <NAME> */ @Tag(UnitTest) @ExtendWith(OutputCaptureExtension::class) internal class QuartzCollectionSchedulerServiceTest { lateinit var collectionSchedulerService: QuartzCollectionSchedulerService @MockK(relaxed = true) lateinit var executionServiceMock: ExecutionService @MockK(relaxed = true) lateinit var retentionServiceMock: RetentionService @BeforeEach fun setup() { MockKAnnotations.init(this) collectionSchedulerService = QuartzCollectionSchedulerService(executionServiceMock, retentionServiceMock) } @AfterEach fun cleanup() { collectionSchedulerService.stop() } @Test fun `scheduled collection job is created`(output: CapturedOutput) { val config = CollectionConfig("foo", "* * * * * ? *", null, POSTGRES, emptyList()) val executionServiceCalled = AtomicBoolean(false) every { executionServiceMock.execute(config, any()) } answers { @Suppress("UNCHECKED_CAST") assertThat((args[1] as Collection<Map<String, Any?>>).first()).containsKey("timestamp") executionServiceCalled.set(true) } collectionSchedulerService.createCollectionJob(config) assertThat(output).contains( "Creating scheduled collection job foo with cron * * * * * ? *", "Collection job foo to be scheduled every second" ) await().until { executionServiceCalled.get() } await().until { output.contains("Executed collection job foo") } } @Test fun `collection job creation throws exception when expression is not valid`() { val config = CollectionConfig("foo", "99 * * * * ? *", null, POSTGRES, emptyList()) assertThatThrownBy { collectionSchedulerService.createCollectionJob(config) } .isInstanceOf(SchedulerException::class.java) verify(exactly = 0) { executionServiceMock.execute(any(), any()) } confirmVerified(executionServiceMock) } @Test fun `collection job is overwritten if it already exists`() { val config = CollectionConfig("foo", "0 0 * * * ? *", null, POSTGRES, emptyList()) assertThatCode { collectionSchedulerService.createCollectionJob(config) collectionSchedulerService.createCollectionJob( CollectionConfig( "foo", "* * * * * ? *", null, POSTGRES, emptyList() ) ) }.doesNotThrowAnyException() } @Test fun `collection job is cancelled immediately if next execution is in the past`() { val config = CollectionConfig("foo", "0 0 * * * ? 2016", null, POSTGRES, emptyList()) assertThatThrownBy { collectionSchedulerService.createCollectionJob(config) } .isInstanceOf(org.quartz.SchedulerException::class.java) verify(exactly = 0) { executionServiceMock.execute(any(), any()) } confirmVerified(executionServiceMock) } @Test fun `collection job can be cancelled`(output: CapturedOutput) { val config = CollectionConfig("foo", "* * * * * ? *", null, POSTGRES, emptyList()) collectionSchedulerService.createCollectionJob(config) with().pollDelay(2, SECONDS).await().until { true } collectionSchedulerService.cancelCollectionJob(config) assertThat(output).contains("Collection job foo to be cancelled") } @Test fun `scheduled retention job is created`(output: CapturedOutput) { val config = CollectionConfig("foo", null, "P2D", POSTGRES, emptyList()) val retentionServiceCalled = AtomicBoolean(false) every { retentionServiceMock.getCronExpression() } returns "* * * * * ? *" every { retentionServiceMock.clean(config) } answers { retentionServiceCalled.set(true) } collectionSchedulerService.createRetentionJob(config) assertThat(output).contains( "Creating scheduled retention job foo with cron * * * * * ? *", "Retention job foo to be scheduled every second" ) await().until { retentionServiceCalled.get() } await().until { output.contains("Executed retention job foo") } verify(atLeast = 2, atMost = 3) { retentionServiceMock.getCronExpression() } verify(atLeast = 1) { retentionServiceMock.clean(config) } confirmVerified(retentionServiceMock) } @Test fun `retention job can be cancelled`(output: CapturedOutput) { val config = CollectionConfig("foo", null, "P2D", POSTGRES, emptyList()) every { retentionServiceMock.getCronExpression() } returns "* * * * * ? *" collectionSchedulerService.createRetentionJob(config) with().pollDelay(2, SECONDS).await().until { true } collectionSchedulerService.cancelRetentionJob(config) assertThat(output).contains("Retention job foo to be cancelled") verify(atLeast = 2, atMost = 3) { retentionServiceMock.getCronExpression() } verify(atMost = 3) { retentionServiceMock.clean(config) } confirmVerified(retentionServiceMock) } }
4
Kotlin
0
2
da65a02b080174e749e78e8cce178b29f14f3545
6,159
litfass
MIT License
subprojects/samples/src/test/kotlin/org/kotools/types/ZeroKotlinSampleTest.kt
kotools
581,475,148
false
null
package org.kotools.types import kotlin.test.Test class ZeroKotlinSampleTest { @Test fun `equals(nullable Any) should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::equalsOverride) @Test fun `hashCode() should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::hashCodeOverride) @Test fun `compareTo(Byte) should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::compareToByte) @Test fun `compareTo(Short) should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::compareToShort) @Test fun `compareTo(Int) should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::compareToInt) @Test fun `compareTo(Long) should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::compareToLong) @Test fun `compareTo(Float) should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::compareToFloat) @Test fun `compareTo(Double) should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::compareToDouble) @Test fun `toByte() should pass`() { val expected = "0" assertPrints(expected, ZeroKotlinSample::toByte) } @Test fun `toShort() should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::toShort) @Test fun `toInt() should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::toInt) @Test fun `toLong() should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::toLong) @Test fun `toFloat() should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::toFloat) @Test fun `toDouble() should pass`(): Unit = assertPrintsTrue(ZeroKotlinSample::toDouble) @Test fun toStringSample_should_pass() { val expected = "0" assertPrints(expected, ZeroKotlinSample::toStringSample) } }
34
null
6
79
55871069932249cf9e65f867c4e3d9bbc5adfeee
1,833
types
MIT License
sdk/sdk-metrics/src/commonMain/kotlin/io/opentelemetry/kotlin/sdk/metrics/export/MetricProducer.kt
dcxp
450,518,130
false
{"Kotlin": 1483649}
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.kotlin.sdk.metrics.export import io.opentelemetry.kotlin.sdk.metrics.data.MetricData /** * `MetricProducer` is the interface that is used to make metric data available to the OpenTelemetry * exporters. Implementations should be stateful, in that each call to [ ][.collectAllMetrics] will * return any metric generated since the last call was made. * * Implementations must be thread-safe. */ interface MetricProducer { /** * Returns a collection of produced [MetricData]s to be exported. This will only be those * metrics that have been produced since the last time this method was called. * * @return a collection of produced [MetricData]s to be exported. */ fun collectAllMetrics(): Collection<MetricData> }
10
Kotlin
2
29
9c3186e26bd3ac78b650163be2c8f569096aaeec
861
opentelemetry-kotlin
Apache License 2.0
ChattingApp/app/src/main/java/com/example/chattingapp/model/Group.kt
DevendraShendkar
832,998,785
false
{"Kotlin": 307947}
package com.example.chattingapp.model class Group { var groupName: String? = null var groupCreateId: String? = null var groupId: String? = null var groupImage: String? = null var timestamp: Any? = null var imageMessage: String? = null var type: String? = null var message: String? = null var messageSenderId: String? = null constructor() {} constructor(groupId: String? = null, groupCreateId: String? = null, groupName: String? = null, groupImage: String? = null, timestamp: Any? = null, imageMessage: String? = null, type: String? = null,message: String? = null, messageSenderId: String? = null ) { this.groupId = groupId this.groupCreateId = groupCreateId this.groupName = groupName this.groupImage = groupImage this.timestamp = timestamp this.imageMessage = imageMessage this.type = type this.message = message this.messageSenderId = messageSenderId } }
0
Kotlin
0
3
f3b0067d01476a21d047caad75256e7cc58ec280
1,001
Chatting-App
Apache License 2.0
core/navigation/impl/src/commonMain/kotlin/ru/kyamshanov/mission/core/navigation/impl/domain/ScreenConfig.kt
KYamshanov
656,042,097
false
{"Kotlin": 339079, "Batchfile": 2703, "HTML": 199, "Dockerfile": 195}
package ru.kyamshanov.mission.core.navigation.impl.domain import com.arkivanov.essenty.parcelable.Parcelable import com.arkivanov.essenty.parcelable.Parcelize import ru.kyamshanov.mission.core.navigation.api.RootComponentFactory import ru.kyamshanov.mission.core.navigation.api.Screen @Parcelize class ScreenConfig<Component>( val screen: Screen<Component>, val rootComponentFactory: RootComponentFactory<Component> ) : Parcelable
7
Kotlin
0
1
af1de2e2976c467c8ca3d614bb369ba933167995
440
Mission-app
Apache License 2.0
stream-chat-android-compose/src/main/java/io/getstream/chat/android/compose/ui/attachments/content/AudioRecordAttachmentQuotedContent.kt
GetStream
177,873,527
false
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
/* * Copyright (c) 2014-2024 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-chat-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.chat.android.compose.ui.attachments.content import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import io.getstream.chat.android.client.extensions.duration import io.getstream.chat.android.compose.R import io.getstream.chat.android.compose.ui.theme.ChatTheme import io.getstream.chat.android.models.Attachment import io.getstream.chat.android.ui.common.utils.DurationFormatter /** * Builds an audio record attachment quoted message which shows a single audio in the attachments list. * * @param attachment The attachment we wish to show to users. */ @Composable public fun AudioRecordAttachmentQuotedContent( attachment: Attachment, modifier: Modifier = Modifier, ) { val durationInSeconds = attachment.duration ?: 0f Row( modifier = modifier .padding( start = ChatTheme.dimens.quotedMessageAttachmentStartPadding, top = ChatTheme.dimens.quotedMessageAttachmentTopPadding, bottom = ChatTheme.dimens.quotedMessageAttachmentBottomPadding, end = ChatTheme.dimens.quotedMessageAttachmentEndPadding, ) .clip(ChatTheme.shapes.quotedAttachment), verticalAlignment = Alignment.CenterVertically, ) { Icon( painter = painterResource(id = R.drawable.stream_compose_ic_file_aac), contentDescription = null, tint = Color.Unspecified, modifier = Modifier.size(24.dp), ) Spacer(modifier = Modifier.size(ChatTheme.dimens.quotedMessageAttachmentSpacerHorizontal)) Column { Text( text = stringResource(id = R.string.stream_compose_audio_recording_preview), style = ChatTheme.typography.bodyBold, color = ChatTheme.colors.textHighEmphasis, ) Spacer(modifier = Modifier.size(ChatTheme.dimens.quotedMessageAttachmentSpacerVertical)) Text( text = DurationFormatter.formatDurationInSeconds(durationInSeconds), color = ChatTheme.colors.textLowEmphasis, style = ChatTheme.typography.footnote, ) } } }
24
Kotlin
273
1,451
8e46f46a68810d8086c48a88f0fff29faa2629eb
3,403
stream-chat-android
FSF All Permissive License
src/main/kotlin/traffic_simulation/Main.kt
0riginz
100,138,867
true
{"Kotlin": 30925}
package traffic_simulation // Imports for parsing library import com.univocity.parsers.common.record.Record import com.univocity.parsers.csv.CsvParser import com.univocity.parsers.csv.CsvParserSettings import com.univocity.parsers.csv.CsvWriter import com.univocity.parsers.csv.CsvWriterSettings fun main(args: Array<String>) { //The following line simulates traffic from an intern list and prints it to console testScenarioWithInternList() //The following lines simulates a complete scenario and prints into results.csv; // in next release (or as NP says) i want to enable feeding in road data, so a user can simulate more than the test road, //but can choose from a bunch of roads simulateCSV() } fun testScenarioWithInternList() { val road: RoadNetwork = RoadNetwork(capacity = 70) // Creation of sufficient cars for local testing without using CSV input for now val BMW1: Vehicle = Car(id = 1, wannaDriveInHours = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22, 23, 24)) val BMW2: Vehicle = Car(id = 2, wannaDriveInHours = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 19, 20, 21, 22, 23, 24)) val BMW3: Vehicle = Car(id = 3, wannaDriveInHours = mutableListOf(3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)) val BMW4: Vehicle = Car(id = 4, wannaDriveInHours = mutableListOf(3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)) val BMW5: Vehicle = Car(id = 5, wannaDriveInHours = mutableListOf(3, 7, 8, 11, 12, 19, 20, 23, 24)) val BMW6: Vehicle = Car(id = 6, wannaDriveInHours = mutableListOf(1, 2, 3, 4, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)) val BMW7: Vehicle = Car(id = 7, wannaDriveInHours = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 23, 24)) val BMW8: Vehicle = Car(id = 8, wannaDriveInHours = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)) val BMW9: Vehicle = Car(id = 9, wannaDriveInHours = mutableListOf(3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)) val BMW10: Vehicle = Car(id = 10, wannaDriveInHours = mutableListOf(3, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)) val BMW11: Vehicle = Car(id = 11, wannaDriveInHours = mutableListOf(1, 2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)) val BMW12: Vehicle = Car(id = 12, wannaDriveInHours = mutableListOf(1, 2, 3, 4, 11, 12, 13, 14, 15, 19, 20, 21, 22, 23, 24)) val truck1: Vehicle = Truck(id = 13, wannaDriveInHours = mutableListOf(5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18)) val truck2: Vehicle = Truck(id = 14, wannaDriveInHours = mutableListOf(5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18)) val truck3: Vehicle = Truck(id = 15, wannaDriveInHours = mutableListOf(1, 2, 3, 4, 5, 22, 23, 24)) val truck4: Vehicle = Truck(id = 16, wannaDriveInHours = mutableListOf(6, 7, 8, 17, 18, 19)) val tram1: Vehicle = Tram(id = 17, wannaDriveInHours = mutableListOf(1, 2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)) val tram2: Vehicle = Tram(id = 18, wannaDriveInHours = mutableListOf(7, 8, 15, 16, 17, 20)) val tram3: Vehicle = Tram(id = 19, wannaDriveInHours = mutableListOf(7, 8, 9, 14, 15, 16)) val tram4: Vehicle = Tram(id = 20, wannaDriveInHours = mutableListOf(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22)) val bike1: Vehicle = Bike(id = 21, wannaDriveInHours = mutableListOf(14)) val bike2: Vehicle = Bike(id = 22, wannaDriveInHours = mutableListOf(8, 11, 12, 13, 14, 20, 21)) val bike3: Vehicle = Bike(id = 23, wannaDriveInHours = mutableListOf(11)) val bike4: Vehicle = Bike(id = 24, wannaDriveInHours = mutableListOf(7, 15, 19, 20, 21)) val testList: List<Vehicle> = listOf(BMW1, BMW2, BMW3, BMW4, BMW5, BMW6, BMW7, BMW8, BMW9, BMW10, BMW11, BMW12, truck1, truck2, truck3, truck4, tram1, tram2, tram3, tram4, bike1, bike2, bike3, bike4) for (vehicle in road.simulateScenario(testList)) { println("The ${vehicle.getClass()} with the ID '${vehicle.getID()}' got a delay cause of traffic jam in hours: ${vehicle.gotNewDelayInHours} " + "drove without new delays in hours (no traffic jam): ${vehicle.droveWithoutNewDelayInHours}") } } fun parseInputOfCSV(fileName: String): MutableList<Vehicle> { val vehicleListCSV: MutableList<Vehicle> = mutableListOf() // The information of vehicles and their interest to drive is given in a csv-file // Therefore we use a library to parse // Setup of the parsing like symbol of separation etc. // in this case mostly the default settings so just a few things have to be set val settings = CsvParserSettings() settings.format.setLineSeparator("\n") settings.isHeaderExtractionEnabled = true // this is to make the parser ignoring the first line in the csv-file // creating a parser with the former made settings val csvParser = CsvParser(settings) // reading of the csv-file val reader = FileAccess().getReader("/" + fileName) // analyze (parse) of the csv given val allRows: MutableList<Record> = csvParser.parseAllRecords(reader) // insert the parsed information of csv-file in usable lists and use them in functions for (record in allRows) { val class_String: String = record.values[0] val id_String: String = record.values[1] val wannaDrive_String: String = record.values[2] val id_Int: Int = id_String.toInt() val wannaDrive_List: MutableList<Int> = mutableListOf() val separator: Char = '/' val splittedWannaDrive: List<String> = wannaDrive_String.split(separator) for (hour in splittedWannaDrive) { val newHour_Int: Int = hour.toInt() wannaDrive_List.add(newHour_Int) } wannaDrive_List.sort() if (class_String == "Car") { vehicleListCSV.add(Car(id = id_Int, wannaDriveInHours = wannaDrive_List)) } else if (class_String == "Truck") { vehicleListCSV.add(Truck(id = id_Int, wannaDriveInHours = wannaDrive_List)) } else if (class_String == "Tram") { vehicleListCSV.add(Tram(id = id_Int, wannaDriveInHours = wannaDrive_List)) } else if (class_String == "Bike") { vehicleListCSV.add(Bike(id = id_Int, wannaDriveInHours = wannaDrive_List)) } else { println("There is at least one wrong vehicle class in CSV-Input") } } return vehicleListCSV } fun printResultsToCSV(results: List<Vehicle>, outputFile: String = "results.csv") { val writer = FileAccess().getWriter(outputFile) val csvWriter = CsvWriter(writer, CsvWriterSettings()) // Write the record headers of this file val vehicleRows: MutableList<Array<Any>> = mutableListOf() val vehicleClass = "Vehicle class" val id = "VehicleID" val delay = "Got a new delay in hours because of traffic jam" val notDelay = "Driven without a new delay in hours (no traffic jam)" val row: Array<Any> = arrayOf(vehicleClass, id, delay, notDelay) vehicleRows.add(row) for (result in results) { val vehicleClass = result.getClass() val id = result.getID().toString() val delay = result.gotNewDelayInHours.toString() val notDelay = result.droveWithoutNewDelayInHours.toString() val row: Array<Any> = arrayOf(vehicleClass, id, delay, notDelay) vehicleRows.add(row) } csvWriter.writeRowsAndClose(vehicleRows) } fun simulateCSV() { val road: RoadNetwork = RoadNetwork(capacity = 100) val vehiclesFromCSV: List<Vehicle> = parseInputOfCSV(fileName = "driveInterest.csv") printResultsToCSV(road.simulateScenario(vehiclesFromCSV)) }
0
Kotlin
0
0
5d7c53f7456fadb9e0699a683d83a34fa735f965
7,778
BBFW-Project
MIT License
compiler/testData/compileJavaAgainstKotlin/method/MapOfKString.kt
udalov
10,645,710
false
null
fun <K> fff(map: Map<K, String>) = map
0
null
1
6
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
40
kotlin-objc-diploma
Apache License 2.0
src/main/kotlin/nrxus/droptoken/DropTokenController.kt
nrxus
245,327,294
false
null
package nrxus.droptoken import com.fasterxml.jackson.annotation.JsonUnwrapped import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import javax.validation.Valid import javax.validation.constraints.Min @RestController @RequestMapping("/drop_token") class DropTokenController(private val service: DropTokenService) { @GetMapping fun getGames() = AllGamesResponse( service.allIds().map { it.toString() } ) @PostMapping fun newGame(@Valid @RequestBody request: NewGameRequest): ResponseEntity<ApiResult<NewGameResponse>> { return when { request.players.any { s -> s.isBlank() } -> { ResponseEntity.badRequest().body(ApiResult.Failure( ApiError(HttpStatus.BAD_REQUEST, message = "validation error", errors = listOf(ApiError.SubError( field = "players", message = "player names cannot be empty" ))) )) } request.players.distinct().size != request.players.size -> { ResponseEntity.badRequest().body(ApiResult.Failure( ApiError(HttpStatus.BAD_REQUEST, message = "validation error", errors = listOf(ApiError.SubError( field = "players", message = "players must all have different names" ))) )) } else -> { ResponseEntity.ok(ApiResult.Success( NewGameResponse(service.create(request.players).toString()) )) } } } @GetMapping("/{id}") fun getGame(@PathVariable id: Long): ResponseEntity<GameState> = service.get(id)?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build() @PostMapping("/{id}/{player}") fun newMove( @PathVariable id: Long, @PathVariable player: String, @RequestBody request: MoveRequest ): ResponseEntity<ApiResult<NewMoveResponse>> = when (val result = service.newMove(id, player, request.column)) { is MoveResult.Success -> ResponseEntity.ok( ApiResult.Success(NewMoveResponse("$id/moves/${result.moveNumber}")) ) is MoveResult.None -> ResponseEntity.notFound().build() is MoveResult.IllegalMove -> ResponseEntity.badRequest() .body(ApiResult.Failure( ApiError(HttpStatus.BAD_REQUEST, message = "Illegal Move") )) is MoveResult.OutOfTurn -> ResponseEntity.status(HttpStatus.CONFLICT) .body(ApiResult.Failure( ApiError(HttpStatus.CONFLICT, message = "It is not $player's turn") )) } @GetMapping("/{id}/moves/{moveNumber}") fun getMove( @PathVariable id: Long, @PathVariable @Min(0) moveNumber: Int ): ResponseEntity<Move> = service.getMove(id, moveNumber)?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build() @GetMapping("/{id}/moves") fun getMoves( @PathVariable id: Long, @RequestParam start: Int?, @RequestParam until: Int? ): ResponseEntity<ApiResult<MovesResponse>> { val safeStart = start ?: 0 if (safeStart < 0) { return ResponseEntity.badRequest().body(ApiResult.Failure( ApiError( HttpStatus.BAD_REQUEST, message = "validation error", errors = listOf(ApiError.SubError( field = "start", message = "cannot be lower than 0" )) ) )) } val safeUntil = when (until) { null -> null else -> if (until < safeStart) { return ResponseEntity.badRequest().body(ApiResult.Failure( ApiError( HttpStatus.BAD_REQUEST, message = "validation error", errors = listOf(ApiError.SubError( field = "until", message = "cannot be lower than $safeStart" )) ) )) } else { until } } val response: ResponseEntity<ApiResult<MovesResponse>>? = service.getMoves(id, safeStart, safeUntil) ?.let { ResponseEntity.ok(ApiResult.Success(MovesResponse(it))) } return response ?: ResponseEntity.notFound().build() } @DeleteMapping("/{id}/{player}") fun delete(@PathVariable id: Long, @PathVariable player: String): ResponseEntity<Unit> = when (service.delete(id, player)) { is DeleteResult.NotFound -> ResponseEntity.notFound().build() is DeleteResult.AlreadyDone -> ResponseEntity.status(HttpStatus.GONE).build() is DeleteResult.Success -> ResponseEntity.accepted().build() } // Simple Responses class AllGamesResponse(val games: List<String>) class NewGameResponse(val gameId: String) class NewMoveResponse(val move: String) class MovesResponse(val moves: List<Move>) // Simple Requests class MoveRequest(val column: Int) sealed class ApiResult<T> { class Success<T>(@JsonUnwrapped val success: T) : ApiResult<T>() class Failure<T>(@JsonUnwrapped val error: ApiError) : ApiResult<T>() } }
0
Kotlin
0
0
4c969c69d213425cfd0117ca512a4d500b8eccf8
5,984
drop-token
MIT License
app/src/main/java/com/zm/org/wallet/ui/usertransactions/BalanceSummery.kt
zeinabmohamed
454,303,737
false
null
package com.zm.org.wallet.ui.usertransactions import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import com.zm.org.wallet.R import com.zm.org.wallet.domain.entity.UserBalanceSummary import com.zm.org.wallet.util.MoneyFormatter @Composable internal fun BalanceSummery(moneyFormatter: MoneyFormatter, balanceSummary: UserBalanceSummary) { Card( modifier = Modifier .clip(RoundedCornerShape(dimensionResource(R.dimen.padding_large))) .background(color = MaterialTheme.colors.surface) .padding(dimensionResource(R.dimen.padding_large)), border = BorderStroke(dimensionResource(R.dimen.padding_very_small), Color.LightGray), elevation = dimensionResource(R.dimen.padding_medium) ) { Column( modifier = Modifier.fillMaxWidth().padding(dimensionResource(R.dimen.padding_large)), ) { Row( modifier = Modifier.fillMaxWidth() .padding(dimensionResource(R.dimen.padding_medium)) .height(IntrinsicSize.Min), horizontalArrangement = Arrangement.SpaceBetween ) { Column(Modifier.weight(1f) .padding(end = dimensionResource(R.dimen.padding_small)), horizontalAlignment = Alignment.CenterHorizontally) { Text(stringResource(R.string.expenses)) Text(stringResource(R.string.expense_amount, moneyFormatter.format(balanceSummary.totalExpenses)), maxLines = 1, modifier = Modifier.testTag("expensesAmountLabel"), overflow = TextOverflow.Ellipsis) } Divider( modifier = Modifier.fillMaxHeight() .width(dimensionResource(R.dimen.padding_very_small)), color = Color.LightGray ) Column(Modifier.weight(1f) .padding(horizontal = dimensionResource(R.dimen.padding_small)), horizontalAlignment = Alignment.CenterHorizontally) { Text(stringResource(R.string.income)) Text(stringResource(R.string.income_amount, moneyFormatter.format(balanceSummary.totalIncomes)), maxLines = 1, modifier = Modifier.testTag("incomesAmountLabel"), overflow = TextOverflow.Ellipsis) } Divider( modifier = Modifier.fillMaxHeight() .width(dimensionResource(R.dimen.padding_very_small)), color = Color.LightGray ) Column(Modifier.weight(1f) .padding(start = dimensionResource(R.dimen.padding_small)), horizontalAlignment = Alignment.CenterHorizontally) { Text(stringResource(R.string.balance)) Text(stringResource(R.string.income_amount, moneyFormatter.format(balanceSummary.balance)), modifier = Modifier.testTag("balanceAmountLabel"), maxLines = 1, overflow = TextOverflow.Ellipsis) } } LinearProgressIndicator( modifier = Modifier.fillMaxWidth() .clip(RoundedCornerShape(dimensionResource(R.dimen.padding_large))) .height(dimensionResource(R.dimen.padding_large)), progress = if (balanceSummary.balance <= 0) { 1f } else { ((balanceSummary.totalExpenses) / balanceSummary.totalIncomes) }, ) } } } @Preview @Composable internal fun BalanceSummeryPreview() { Surface { BalanceSummery(MoneyFormatter(), UserBalanceSummary( 20f, -1000f, 50f, )) } }
0
Kotlin
0
0
84a9765a184346c58a234fbe019cc89dd8442bc6
4,630
Wallet
BSD Source Code Attribution
waypoint-core/src/test/java/com/squaredcandy/waypoint/core/route/lifecycle/TestSavedStateHolder.kt
squaredcandy
638,860,321
false
null
package com.squaredcandy.waypoint.core.route.lifecycle import androidx.compose.runtime.Composable import androidx.compose.runtime.saveable.SaveableStateHolder class TestSavedStateHolder( private val onRemoveState: (key: Any) -> Unit, ): SaveableStateHolder { @Composable override fun SaveableStateProvider(key: Any, content: @Composable () -> Unit) { content() } override fun removeState(key: Any) { onRemoveState(key) } }
0
Kotlin
0
0
982ef4d1a4243507554240341aba09063e75dbb7
442
waypoint
Apache License 2.0
app/src/main/java/com/matthew/carvalhodagenais/coinhuntingbuddy/ui/screens/HuntScreen.kt
mcd-3
474,478,959
false
{"Kotlin": 242534}
package com.matthew.carvalhodagenais.coinhuntingbuddy.ui.screens import android.content.Context import android.content.Intent import android.util.Log import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.matthew.carvalhodagenais.coinhuntingbuddy.R import com.matthew.carvalhodagenais.coinhuntingbuddy.MainActivity import com.matthew.carvalhodagenais.coinhuntingbuddy.ui.components.* import com.matthew.carvalhodagenais.coinhuntingbuddy.ui.theme.topAppBar import com.matthew.carvalhodagenais.coinhuntingbuddy.utils.ArrayTools import com.matthew.carvalhodagenais.coinhuntingbuddy.utils.MoneyStringToSymbolUtil import com.matthew.carvalhodagenais.coinhuntingbuddy.viewmodels.HuntActivityViewModel import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch /** * Determines the weight of TabButtons * * @param sizeOfMap Int - Size of map */ fun getButtonWeight(sizeOfMap: Int): Float { return when (sizeOfMap) { 1 -> 1f 2 -> 0.5f 3 -> 0.33f 4 -> 0.25f 5 -> 0.2f 6 -> 0.165f else -> 0.33f } } /** * Maps a map of coins' Key and Value to arrays * * PS: This function sucks * * @param map Map<String, Int> - Base map to use * @param region String - Region of the coins * @param keysArray Array<String> - Array of keys. Max size is 6 * @param rollsArray<Int> - Array of rolls. Max size is 6 * @param context Context - Application context used to get strings */ fun arrangeCoinMap( map: Map<String, Int>, region: String, keysArray: Array<String>, rollsArray: Array<Int>, context: Context ) { if (region == context.getString(R.string.us_region_code)) { map.forEach { when (it.key) { context.getString(R.string.us_penny_plural) -> { keysArray[0] = context.getString(R.string.us_penny_plural) rollsArray[0] = map[it.key]!! } context.getString(R.string.us_nickel_plural) -> { keysArray[1] = context.getString(R.string.us_nickel_plural) rollsArray[1] = map[it.key]!! } context.getString(R.string.us_dime_plural) -> { keysArray[2] = context.getString(R.string.us_dime_plural) rollsArray[2] = map[it.key]!! } context.getString(R.string.us_quarter_plural) -> { keysArray[3] = context.getString(R.string.us_quarter_plural) rollsArray[3] = map[it.key]!! } context.getString(R.string.us_hd_plural) -> { keysArray[4] = context.getString(R.string.us_hd_plural) rollsArray[4] = map[it.key]!! } context.getString(R.string.us_dollar_plural) -> { keysArray[5] = context.getString(R.string.us_dollar_plural) rollsArray[5] = map[it.key]!! } } } } else { // Canada map.forEach { when (it.key) { context.getString(R.string.ca_1c_plural) -> { keysArray[0] = context.getString(R.string.ca_1c_plural) rollsArray[0] = map[it.key]!! } context.getString(R.string.ca_5c_plural) -> { keysArray[1] = context.getString(R.string.ca_5c_plural) rollsArray[1] = map[it.key]!! } context.getString(R.string.ca_10c_plural) -> { keysArray[2] = context.getString(R.string.ca_10c_plural) rollsArray[2] = map[it.key]!! } context.getString(R.string.ca_25c_plural) -> { keysArray[3] = context.getString(R.string.ca_25c_plural) rollsArray[3] = map[it.key]!! } context.getString(R.string.ca_loonie_plural) -> { keysArray[4] = context.getString(R.string.ca_loonie_plural) rollsArray[4] = map[it.key]!! } context.getString(R.string.ca_toonie_plural) -> { keysArray[5] = context.getString(R.string.ca_toonie_plural) rollsArray[5] = map[it.key]!! } } } } } @Composable fun HuntScreen( viewModel: HuntActivityViewModel, navController: NavController, region: String, coinList: Map<String, Int>, ) { // Use this list to remove rolls from val tempCoinList = coinList.toMutableMap() viewModel.rollsPerCoin = tempCoinList // Flags val showHuntCompleteDialog = remember { mutableStateOf(false)} val showInfoDialog = remember { mutableStateOf(false) } val completeHuntFlag = remember { mutableStateOf(tempCoinList.all { it.value == 0 }) } // Context is needed here to go back to MainActivity val context = LocalContext.current val navString = stringResource(id = R.string.review_route) Scaffold( topBar = { Surface { TopAppBar( backgroundColor = MaterialTheme.colors.topAppBar, title = { Text( text = if (region == stringResource(id = R.string.us_region_code)) { stringResource(id = R.string.us_coin_hunt_label) } else { stringResource(id = R.string.ca_coin_hunt_label) } ) }, elevation = 0.dp, actions = { IconButton( onClick = { showInfoDialog.value = true } ) { Icon( Icons.Filled.Info, contentDescription = stringResource(id = R.string.info_icon_cd), tint = MaterialTheme.colors.primary ) } } ) } }, ) { val showAlertDialog = remember { mutableStateOf(false) } BackHandler { showAlertDialog.value = true } if(showAlertDialog.value){ ConfirmCancelAlertDialog( title = stringResource(id = R.string.stop_hunt_confirm_label), body = stringResource(id = R.string.stop_hunt_warning_label), confirmLabel = stringResource(id = R.string.yes_prompt), cancelLabel = stringResource(id = R.string.no_prompt), toggledState = showAlertDialog, onConfirm = { val intent = Intent(context, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK context.startActivity(intent) }, onCancel = { showAlertDialog.value = false } ) } Column { Spacer(modifier = Modifier .fillMaxWidth() .height(10.dp)) Column(modifier = Modifier.weight(0.7f)) { val selectedKey = remember { mutableStateOf("") } val currentRollAmount = remember { mutableStateOf(0) } Row( modifier = Modifier .fillMaxWidth() .height(32.dp) .padding(start = 20.dp, end = 20.dp), horizontalArrangement = Arrangement.Start ) { // First, we need to arrange the list val keys = arrayOf("", "", "", "", "", "") val rolls = arrayOf(-1, -1, -1, -1, -1, -1) arrangeCoinMap(coinList, region, keys, rolls, context) keys.forEach { Log.e("KEYS_BRUH", it) } val firstKey = keys[ ArrayTools.firstIndexWhereNot(rolls, -1)!! ] var lastIndex = 0 for (i in 5 downTo 0 step 1) { if (rolls[i] != -1) { lastIndex = i break } } val lastKey = keys[lastIndex] if (selectedKey.value.isEmpty()) { selectedKey.value = firstKey currentRollAmount.value = tempCoinList[selectedKey.value]!! } keys.forEachIndexed { index, it -> if (it != "") { TabButton( onClick = { selectedKey.value = keys[index] currentRollAmount.value = tempCoinList[selectedKey.value]!! }, text = MoneyStringToSymbolUtil.convert(keys[index], context), leftIsRounded = firstKey == keys[index], rightIsRounded = lastKey == keys[index], key = keys[index], selectedKey = selectedKey, modifier = Modifier.weight(getButtonWeight(coinList.size)) ) } } } CoinTypeHuntPanel( coinKeyState = selectedKey, rollsLeftState = currentRollAmount, viewModel = viewModel, unwrapRollOnClick = { val rollsMinusOne = tempCoinList[selectedKey.value] as Int - 1 tempCoinList.replace( selectedKey.value, rollsMinusOne ) currentRollAmount.value = rollsMinusOne completeHuntFlag.value = tempCoinList.all { it.value == 0 } } ) } if(showHuntCompleteDialog.value){ ConfirmCancelAlertDialog( title = stringResource(id = R.string.complete_hunt_confirm_label), body = stringResource(id = R.string.complete_hunt_warning_label), confirmLabel = stringResource(id = R.string.complete_prompt), cancelLabel = stringResource(id = R.string.cancel_prompt), toggledState = showHuntCompleteDialog, onConfirm = { viewModel.setRegion(region) showHuntCompleteDialog.value = false navController.popBackStack() navController.navigate(navString) // We need GlobalScope here since the activity can be changed // by the user before saving has completed GlobalScope.launch { viewModel.saveData() } }, onCancel = { showHuntCompleteDialog.value = false } ) } InfoAlertDialog(openState = showInfoDialog) Row(Modifier.weight(0.1f)) { FullButton( onClick = { showHuntCompleteDialog.value = true }, text = stringResource(id = R.string.complete_btn), enabled = completeHuntFlag.value ) } } } }
4
Kotlin
0
1
af1eec1593abdef3c83a85cb398093d4f9c29f0e
12,368
coin-hunting-buddy
MIT License
db-room/src/main/java/com/pyamsoft/fridge/db/room/RoomFridgeDb.kt
pyamsoft
175,992,414
false
null
/* * Copyright 2021 <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.pyamsoft.fridge.db.room import androidx.annotation.CheckResult import com.pyamsoft.fridge.db.room.dao.category.RoomFridgeCategoryDeleteDao import com.pyamsoft.fridge.db.room.dao.category.RoomFridgeCategoryInsertDao import com.pyamsoft.fridge.db.room.dao.category.RoomFridgeCategoryQueryDao import com.pyamsoft.fridge.db.room.dao.entry.RoomFridgeEntryDeleteDao import com.pyamsoft.fridge.db.room.dao.entry.RoomFridgeEntryInsertDao import com.pyamsoft.fridge.db.room.dao.entry.RoomFridgeEntryQueryDao import com.pyamsoft.fridge.db.room.dao.item.RoomFridgeItemDeleteDao import com.pyamsoft.fridge.db.room.dao.item.RoomFridgeItemInsertDao import com.pyamsoft.fridge.db.room.dao.item.RoomFridgeItemQueryDao internal interface RoomFridgeDb { @get:CheckResult val roomItemQueryDao: RoomFridgeItemQueryDao @get:CheckResult val roomItemInsertDao: RoomFridgeItemInsertDao @get:CheckResult val roomItemDeleteDao: RoomFridgeItemDeleteDao @get:CheckResult val roomEntryQueryDao: RoomFridgeEntryQueryDao @get:CheckResult val roomEntryInsertDao: RoomFridgeEntryInsertDao @get:CheckResult val roomEntryDeleteDao: RoomFridgeEntryDeleteDao @get:CheckResult val roomCategoryQueryDao: RoomFridgeCategoryQueryDao @get:CheckResult val roomCategoryInsertDao: RoomFridgeCategoryInsertDao @get:CheckResult val roomCategoryDeleteDao: RoomFridgeCategoryDeleteDao }
5
Kotlin
2
6
3401d31bfca68172622bbd6de3fcaa1032c79b42
1,970
fridgefriend
Apache License 2.0
kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/acceptedNames.kt
ichaki5748
124,968,379
true
{"Kotlin": 309714}
// GENERATED package com.fkorotkov.kubernetes import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinitionNames import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinitionStatus fun CustomResourceDefinitionStatus.`acceptedNames`(block: CustomResourceDefinitionNames.() -> Unit = {}) { if(this.`acceptedNames` == null) { this.`acceptedNames` = CustomResourceDefinitionNames() } this.`acceptedNames`.block() }
0
Kotlin
0
0
b00b6ddb4b851a864a2737a3374603f7db659af7
459
k8s-kotlin-dsl
MIT License
RetenoSdkCore/src/main/java/com/reteno/core/di/provider/controller/ScheduleControllerProvider.kt
reteno-com
545,381,514
false
{"Kotlin": 1027930, "Java": 160540, "HTML": 17807, "Shell": 379}
package com.reteno.core.di.provider.controller import com.reteno.core.di.base.ProviderWeakReference import com.reteno.core.di.provider.WorkManagerProvider import com.reteno.core.domain.controller.ScheduleController import com.reteno.core.domain.controller.ScheduleControllerImpl internal class ScheduleControllerProvider( private val contactControllerProvider: ContactControllerProvider, private val interactionControllerProvider: InteractionControllerProvider, private val eventsControllerProvider: EventsControllerProvider, private val appInboxControllerProvider: AppInboxControllerProvider, private val recommendationControllerProvider: RecommendationControllerProvider, private val deeplinkControllerProvider: DeeplinkControllerProvider, private val workManagerProvider: WorkManagerProvider ) : ProviderWeakReference<ScheduleController>() { override fun create(): ScheduleController { return ScheduleControllerImpl( contactControllerProvider.get(), interactionControllerProvider.get(), eventsControllerProvider.get(), appInboxControllerProvider.get(), recommendationControllerProvider.get(), deeplinkControllerProvider.get(), workManagerProvider.get() ) } }
1
Kotlin
1
1
40df793dea31a7847e93afd6daf21ab8f0317a2f
1,300
reteno-mobile-android-sdk
MIT License
Client/app/src/main/java/com/t3ddyss/clother/data/auth/remote/models/SignInErrorDto.kt
t3ddyss
337,083,750
false
{"Kotlin": 343621, "Python": 38739, "Jupyter Notebook": 22857, "HTML": 11031, "Dockerfile": 439, "Shell": 405}
package com.t3ddyss.clother.data.auth.remote.models import com.google.gson.annotations.SerializedName import com.t3ddyss.clother.data.common.common.remote.models.ErrorDto typealias SignInErrorDto = ErrorDto<SignInErrorType> enum class SignInErrorType { @SerializedName("email_not_verified") EMAIL_NOT_VERIFIED, @SerializedName("invalid_credentials") INVALID_CREDENTIALS }
0
Kotlin
1
23
d18048ac5b354d3c499003ef73afd088c9076e19
390
Clother
MIT License
arrow-libs/core/arrow-atomic/src/commonTest/kotlin/arrow/atomic/AtomicTest.kt
PhBastiani
208,032,328
true
{"Kotlin": 2531637, "Java": 7691}
package arrow.atomic import arrow.fx.coroutines.parMap import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import io.kotest.property.Arb import io.kotest.property.arbitrary.string import io.kotest.property.checkAll import kotlin.coroutines.Continuation import kotlin.coroutines.EmptyCoroutineContext import kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn class AtomicTest : StringSpec({ "set get - successful" { checkAll(Arb.string(), Arb.string()) { x, y -> val r = Atomic(x) r.value = y r.value shouldBe y } } "update get - successful" { checkAll(Arb.string(), Arb.string()) { x, y -> val r = Atomic(x) r.update { y } r.value shouldBe y } } "getAndSet - successful" { checkAll(Arb.string(), Arb.string()) { x, y -> val ref = Atomic(x) ref.getAndSet(y) shouldBe x ref.value shouldBe y } } "getAndUpdate - successful" { checkAll(Arb.string(), Arb.string()) { x, y -> val ref = Atomic(x) ref.getAndUpdate { y } shouldBe x ref.value shouldBe y } } "updateAndGet - successful" { checkAll(Arb.string(), Arb.string()) { x, y -> val ref = Atomic(x) ref.updateAndGet { it shouldBe x y } shouldBe y } } "tryUpdate - modification occurs successfully" { checkAll(Arb.string()) { x -> val ref = Atomic(x) ref.tryUpdate { it + 1 } ref.value shouldBe x + 1 } } "tryUpdate - should fail to update if modification has occurred" { checkAll(Arb.string()) { x -> val ref = Atomic(x) ref.tryUpdate { suspend { ref.update { it + "a" } } .startCoroutineUninterceptedOrReturn(Continuation(EmptyCoroutineContext) { }) it + "b" } shouldBe false } } "consistent set update on strings" { checkAll(Arb.string(), Arb.string()) { x, y -> val set = suspend { val r = Atomic(x) r.update { y } r.value } val update = suspend { val r = Atomic(x) r.update { y } r.value } set() shouldBe update() } } "concurrent modifications" { val finalValue = 50_000 val r = Atomic("") (0 until finalValue).parMap { r.update { it + "a" } } r.value shouldBe "a".repeat(finalValue) } } )
0
Kotlin
0
0
b1ad7f713a68c24c8ae0105cbc4d2c9409e575ff
2,357
arrow
Apache License 2.0
composeApp/src/commonMain/kotlin/org/xanderzhu/coincounter/db/injection/DatabaseComponentImpl.kt
XanderZhu
735,312,120
false
{"Kotlin": 12083}
package org.xanderzhu.coincounter.db.injection import org.xanderzhu.coincounter.data.Database import org.xanderzhu.coincounter.db.DatabaseBuilder import org.xanderzhu.coincounter.db.DatabaseDriverFactory class DatabaseComponentImpl( private val databaseDriverFactory: DatabaseDriverFactory ) : DatabaseComponent { override val database: Database = DatabaseBuilder.createDatabase(databaseDriverFactory) }
0
Kotlin
0
0
c05b2fde964c65741b31087bad2581d8ab6d65d2
413
cointcounter
Apache License 2.0
app/src/main/java/gawquon/mapletherm/core/network/bluetooth/BluetoothLeReader.kt
whitehml
608,223,366
false
null
package gawquon.mapletherm.core.network.bluetooth import android.annotation.SuppressLint import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCallback import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.content.Context import android.os.Handler import android.os.Looper import android.os.Message import android.util.Log import gawquon.mapletherm.core.data.CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID import gawquon.mapletherm.core.data.MsgTypes import gawquon.mapletherm.core.data.fahrenheitCharacteristic import gawquon.mapletherm.core.data.hexMap import gawquon.mapletherm.core.viewmodel.TemperatureViewModel import gawquon.mapletherm.ui.misc.toHexString import java.util.UUID private const val TAG = "BluetoothLeReader" @Suppress("DEPRECATION") class BluetoothLeReader(manager: BluetoothManager) { private val _bluetoothLeAdapter = manager.adapter private var _bluetoothLeGatt: BluetoothGatt? = null private var _isConnected = false private var _subscribed = false // Message/instruction Handlers // Looper comes from main thread private val handler: Handler = object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { if (msg.what == MsgTypes.CONNECTION.ordinal) { val connectionMsg = msg.obj as TemperatureViewModel.ConnectionMsg connect(connectionMsg.address, connectionMsg.context) } } } // Static handler to send messages out companion object { private var outHandler: Handler? = null fun setHandler(handler: Handler) { this.outHandler = handler } } init { TemperatureViewModel.setHandler(handler) } // Connections @SuppressLint("MissingPermission") fun connect(address: String, context: Context): Boolean { _bluetoothLeAdapter?.let { adapter -> try { val device = adapter.getRemoteDevice(address) // connect to the GATT server on the device _bluetoothLeGatt = device.connectGatt(context, true, bluetoothGattCallback) } catch (exception: IllegalArgumentException) { Log.w(TAG, "Device not found with provided address.") return false } } ?: run { Log.w(TAG, "BluetoothAdapter not initialized") return false } return true } private val bluetoothGattCallback = object : BluetoothGattCallback() { @SuppressLint("MissingPermission") override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) { if (newState == BluetoothProfile.STATE_CONNECTED && !_isConnected) { // successfully connected to the GATT Server _isConnected = true // Log.d(TAG, "Connected to BLE GATT server") _bluetoothLeGatt?.discoverServices() } else if (newState == BluetoothProfile.STATE_DISCONNECTED && _isConnected) { // disconnected from the GATT Server _isConnected = false _subscribed = false Log.d(TAG, "Disconnected from BLE GATT server") } } override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { if(!_subscribed) { subscribeToNotifications() } // Log.d(TAG, "Services discovered") } else { Log.w(TAG, "onServicesDiscovered received: $status") } } override fun onDescriptorWrite( gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int ) { Log.d(TAG, "Wrote to descriptor, hopefully we get notifications now") } override fun onCharacteristicChanged( // For Android 13+ gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, value: ByteArray ) { sendMessage(sliceHexToTemp(value.toHexString()).toDouble()) } @Deprecated("Deprecated in Java") override fun onCharacteristicChanged( // For Android 12- gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, ) { sendMessage(sliceHexToTemp(characteristic.value.toHexString()).toDouble()) } } @SuppressLint("MissingPermission") private fun close() { // call in the NavHost... if we can _bluetoothLeGatt?.let { gatt -> gatt.close() _bluetoothLeGatt = null } } // Obtain temperature characteristic @SuppressLint("MissingPermission") fun subscribeToNotifications() { val temperatureField = _bluetoothLeGatt!!.findCharacteristic(fahrenheitCharacteristic) if (temperatureField != null) { setCharacteristicNotification(temperatureField, true) val descriptor = temperatureField.getDescriptor( CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID ) descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE // Might have to do non-deprecated version as well for Android 13+ _bluetoothLeGatt!!.writeDescriptor(descriptor) _subscribed = true } else Log.w(TAG, "Could not find temperature field on bluetooth device.") } @SuppressLint("MissingPermission") fun setCharacteristicNotification( characteristic: BluetoothGattCharacteristic, enabled: Boolean ) { if (!_bluetoothLeGatt?.setCharacteristicNotification(characteristic, enabled)!!) { Log.d(TAG, "Failed to set notification") } } private fun BluetoothGatt.findCharacteristic(uuid: UUID): BluetoothGattCharacteristic? { // from <NAME>'s BLE tutorial - https://punchthrough.com/android-ble-guide/ services?.forEach { service -> service.characteristics?.firstOrNull { characteristic -> characteristic.uuid == uuid }?.let { matchingCharacteristic -> return matchingCharacteristic } } return null } // Parsing the data private fun sliceHexToTemp(message: String): String { if (message.length != 22) return 0.0.toString() val hex = message.subSequence(12, 13).toString() + message.subSequence(8, 10).toString() return hexToF(hex).toString() } private fun hexToF(hex: String): Double { return (hexMap[hex[0]]!! * 16 * 16 + hexMap[hex[1]]!! * 16 + hexMap[hex[2]]!!) * 1 / 10.0 } // Messages out private fun sendMessage(fahrenheit: Double) { if (outHandler == null) return outHandler?.obtainMessage(MsgTypes.TEMPERATURE_DATA.ordinal, fahrenheit)?.apply { sendToTarget() } } }
1
Kotlin
0
0
aa98d79e0f1a9f5e641f2ec918dde20640871b75
7,199
Maple-BLE-thermometer
MIT License
test-plugin/src/main/kotlin/me/mrkirby153/kcutils/testplugin/TestPlugin.kt
mrkirby153
75,577,963
false
null
package me.mrkirby153.kcutils.testplugin import me.mrkirby153.kcutils.Chat import me.mrkirby153.kcutils.Time import org.bukkit.entity.Player import org.bukkit.plugin.java.JavaPlugin class TestPlugin : JavaPlugin() { override fun onEnable() { val start = System.currentTimeMillis() logger.info("Hello, World!") val end = System.currentTimeMillis() logger.info("Initialized in ${Time.format(1, end - start)}") getCommand("test-command")?.setExecutor { sender, command, label, args -> if (sender !is Player) { sender.sendMessage(Chat.error("You must be a player to perform this command")) return@setExecutor true } sender.sendMessage(Chat.message("You are a player :D")) true } } }
0
Kotlin
0
0
1a97090677e96adcc087911ee7d8059af25630d4
817
KirbyUtils
MIT License
app/src/main/java/io/woong/filmpedia/data/movie/Credits.kt
cheonjaewoong
391,828,359
false
null
package io.woong.filmpedia.data.movie import com.google.gson.annotations.SerializedName data class Credits( val id: Int, val cast: List<Cast>, val crew: List<Crew> ) { data class Cast( val adult: Boolean, val gender: Int?, val id: Int, @SerializedName("known_for_department") val knownForDepartment: String, val name: String, @SerializedName("original_name") val originalName: String, val popularity: Double, @SerializedName("profile_path") val profilePath: String?, @SerializedName("cast_id") val castId: Int, val character: String, @SerializedName("credit_id") val creditId: String, val order: Int ) data class Crew( val adult: Boolean, val gender: Int?, val id: Int, @SerializedName("known_for_department") val knownForDepartment: String, val name: String, @SerializedName("original_name") val originalName: String, val popularity: Double, @SerializedName("profile_path") val profilePath: String?, @SerializedName("cast_id") val castId: Int, val department: String, val job: String ) }
0
Kotlin
0
4
2e2700dbff77881de55ade1de89a716b0b076f14
1,205
filmpedia
MIT License
stream-chat-android-compose/src/main/java/io/getstream/chat/android/compose/ui/components/messages/ThreadParticipants.kt
GetStream
177,873,527
false
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
/* * Copyright (c) 2014-2022 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-chat-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.chat.android.compose.ui.components.messages import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.zIndex import io.getstream.chat.android.compose.state.messages.MessageAlignment import io.getstream.chat.android.compose.ui.components.avatar.Avatar import io.getstream.chat.android.compose.ui.theme.ChatTheme import io.getstream.chat.android.models.User import io.getstream.chat.android.ui.common.utils.extensions.initials /** * Represents a number of participants in the thread. * * @param participants The list of participants in the thread. * @param alignment The alignment of the parent message. * @param modifier Modifier for styling. * @param borderStroke The border of user avatars, for visibility. * @param participantsLimit The limit of the number of participants shown in the component. */ @Composable public fun ThreadParticipants( participants: List<User>, alignment: MessageAlignment, modifier: Modifier = Modifier, borderStroke: BorderStroke = BorderStroke(width = 1.dp, color = ChatTheme.colors.appBackground), participantsLimit: Int = DefaultParticipantsLimit, ) { Box(modifier) { /** * If we're aligning the message to the start, we just show items as they are, if we are showing them from the * end, then we need to reverse the order. */ val participantsToShow = participants.take(participantsLimit).let { if (alignment == MessageAlignment.End) { it.reversed() } else { it } } val itemSize = ChatTheme.dimens.threadParticipantItemSize participantsToShow.forEachIndexed { index, user -> val itemPadding = Modifier.padding(start = (index * (itemSize.value / 2)).dp) /** * Calculates the visual position of the item to define its zIndex. If we're aligned to the start of the * screen, the first item should be the upper most. * * If we're aligned to the end, then the last item should be the upper most. */ val itemPosition = if (alignment == MessageAlignment.Start) { participantsLimit - index } else { index + 1 }.toFloat() Avatar( modifier = itemPadding .zIndex(itemPosition) .size(itemSize) .border(border = borderStroke, shape = ChatTheme.shapes.avatar), imageUrl = user.image, initials = user.initials, textStyle = ChatTheme.typography.captionBold.copy(fontSize = 7.sp), ) } } } /** * The max limit of how many users are shown as participants in a thread. */ private const val DefaultParticipantsLimit = 4
24
Kotlin
273
1,451
8e46f46a68810d8086c48a88f0fff29faa2629eb
3,816
stream-chat-android
FSF All Permissive License
data-onecall/src/main/java/de/niklasbednarczyk/nbweather/data/onecall/models/MinutelyForecastModelData.kt
NiklasBednarczyk
529,683,941
false
null
package de.niklasbednarczyk.nbweather.data.onecall.models import de.niklasbednarczyk.nbweather.data.onecall.values.datetime.DateTimeValue import de.niklasbednarczyk.nbweather.data.onecall.values.units.PrecipitationValue import de.niklasbednarczyk.nbweather.data.onecall.local.models.MinutelyForecastEntityLocal import de.niklasbednarczyk.nbweather.data.onecall.remote.models.MinutelyForecastModelRemote data class MinutelyForecastModelData( val forecastTime: DateTimeValue?, val precipitation: PrecipitationValue? ) { companion object { internal fun remoteToLocal( remoteList: List<MinutelyForecastModelRemote>?, metadataId: Long, ): List<MinutelyForecastEntityLocal> { return remoteList?.map { remote -> MinutelyForecastEntityLocal( metadataId = metadataId, dt = remote.dt, precipitation = remote.precipitation ) } ?: emptyList() } internal fun localToData( localList: List<MinutelyForecastEntityLocal>? ): List<MinutelyForecastModelData> { return localList?.map { local -> MinutelyForecastModelData( forecastTime = DateTimeValue.from(local.dt), precipitation = PrecipitationValue.from(local.precipitation) ) } ?: emptyList() } } }
22
Kotlin
0
0
b2d94e99336b908a48e784febda56a4750039cb2
1,451
NBWeather
MIT License
components/src/main/kotlin/com/alexrdclement/uiplayground/components/MediaItemArtwork.kt
alexrdclement
661,077,963
false
{"Kotlin": 224028, "Swift": 900}
package com.alexrdclement.uiplayground.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.clearAndSetSemantics import coil3.compose.AsyncImage private const val DisabledAlpha = 0.35f @Composable fun MediaItemArtwork( imageUrl: String?, modifier: Modifier = Modifier, isEnabled: Boolean = true, ) { if (imageUrl != null) { AsyncImage( model = imageUrl, contentDescription = null, modifier = modifier .aspectRatio(1f) .alpha(if (isEnabled) 1f else DisabledAlpha) ) } else { // TODO: fallback image Box( contentAlignment = Alignment.Center, modifier = modifier .aspectRatio(1f, matchHeightConstraintsFirst = true) .background(Color.Red) .clearAndSetSemantics {} ) { Text("Art") } } }
0
Kotlin
0
0
a99ee143215098889afaf4fa97d3399f9dc65383
1,247
UiPlayground
Apache License 2.0
src/main/kotlin/Main.kt
PocketCampus
765,607,529
false
null
import Args.Companion.toFlag import ReviewsSheet.Companion.rowOf import apis.* import com.slack.api.Slack import kotlinx.datetime.Clock import kotlinx.datetime.Instant import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import utils.* import kotlin.math.roundToInt import kotlin.reflect.KProperty import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.memberProperties /** * Extension function to get the review with the latest date from a list */ fun List<Review>?.getLatestDate(): Instant? = this?.mapNotNull { val date = it[ReviewsSheet.Headers.Date] if (date != null) Instant.parse(date) else null }?.max() /** * Extension function to convert a list of reviews into a non-null set of review IDs */ fun List<Review>?.toIdsSet(): Set<String>? = this?.mapNotNull { it[ReviewsSheet.Headers.ReviewId] }?.toSet() /** * Describes the CLI arguments */ data class Args( val googleSpreadsheetId: String, val googlePrivateKeyPath: String, val applePrivateKeyPath: Set<String>, val slackWebhook: String, ) { companion object { /** * Reflection-based extension function to stringify an argument name as a flag */ fun <T> KProperty<T>.toFlag(): String = "--${this.name}" /** * Returns the available flags of the programs, derived by reflection from the properties */ fun getFlags() = Args::class.memberProperties.map { it.toFlag() } } } fun parseArgs(args: Array<String>): Args { val flags = Args.getFlags() val helpMessage = "The arguments list should be a list of pairs <--flag> <value>, available flags: $flags" if (args.size % 2 != 0) { throw Error("Wrong number of arguments! $helpMessage") } val options = args.withIndex().mapNotNull { (index, value) -> val isFlag = flags.contains(value) if (index % 2 == 0) { // every even index (starting at 0) argument should be a flag name if (!isFlag) { throw Error("Wrong argument flag at index ${index}: ${value}. Should be one of ${flags}. $helpMessage") } null // return pairs from the values only } else { // every odd index (starting at 0) should be a value if (isFlag) { throw Error( "Wrong argument value at index ${index}: ${value}: cannot be a flag name ${flags}. Did you forget to follow an argument flag by its value? $helpMessage" ) } args[index - 1] to value // args[index - 1] was checked to exist and be a flag at prev iteration } }.groupBy({ (key, _) -> key }, { (_, value) -> value }) // group all passed values by flag fun <V> Map<String,V>.valueList(prop: KProperty<Any>) = this[prop.toFlag()] ?: throw Error("Argument ${prop.toFlag()} was not specified") return Args( options.valueList(Args::googleSpreadsheetId).last(), options.valueList(Args::googlePrivateKeyPath).last(), options.valueList(Args::applePrivateKeyPath).toSet(), options.valueList(Args::slackWebhook).last(), ) } suspend fun main(args: Array<String>) { val logger = getLogger() val (googleSpreadsheetId, googlePrivateKeyPath, applePrivateKeysPaths, slackWebhook) = parseArgs(args) val config = Config.load(googleSpreadsheetId, googlePrivateKeyPath, applePrivateKeysPaths, slackWebhook) val reviewsSheet = ReviewsSheet(config.spreadsheet, "Reviews") val slack = Slack.getInstance() try { val (sheetHeaders, currentReviews) = reviewsSheet.getContent() logger.info { "${currentReviews.size} reviews loaded from reviews sheet" } val reviewsByCustomer = currentReviews.groupBy { Pair(it[ReviewsSheet.Headers.Customer], it[ReviewsSheet.Headers.Store]) } val googlePlayStore = GooglePlayStore.Client(config.googleCredentials) val customerToReviews = config.apps.map { (customer, apps) -> val (google, apple) = apps logger.info { "Processing reviews for customer ${customer.name}" } val appleReviews = if (apple == null) listOf() else { val existingReviews = reviewsByCustomer[Pair(customer.name, ReviewsSheet.Stores.Apple.name)] val latest = existingReviews.getLatestDate() logger.info { "Downloading new reviews from Apple Store for customer ${customer.name}" } val appleAppStore = AppleAppStore.Client(apple.storeCredentials) val fetchedReviews = appleAppStore.getCustomerReviewsWhile(apple.resourceId) { val currentOldest = it.data.minOfOrNull { review -> review.attributes.createdDate } if (currentOldest == null || latest == null) true else currentOldest >= latest } val newReviews = fetchedReviews.distinctFrom(existingReviews.toIdsSet()) { it.id } .map { rowOf(customer, apple.resourceId, it) } logger.info { "Found ${newReviews.size} new reviews from Apple Store for customer ${customer.name}" } if (newReviews.isNotEmpty()) { logger.info { "Writing new Apple Store reviews to reviews sheet ${reviewsSheet.spreadsheet.browserUrl}" } reviewsSheet.write(newReviews) } newReviews } val (googleReviews, oldGoogleReviews) = if (google == null) Pair(listOf(), listOf()) else { val existingReviews = reviewsByCustomer[Pair(customer.name, ReviewsSheet.Stores.Google.name)] val oldReviews = if (!existingReviews.isNullOrEmpty()) listOf() else { logger.info { "No Google Play Store reviews found for customer ${customer.name}" } if (google.reviewsReportsBucketUri == null) { logger.info { "No Google Cloud Storage reviews reports bucket URI specified. Previous reviews will not be imported" } listOf() } else { logger.info { "Retrieving older reviews from Google Cloud Storage bucket ${ google.reviewsReportsBucketUri }" } val oldReviews = googlePlayStore.reviews.downloadFromReports( google.reviewsReportsBucketUri, google.packageName ).map { rowOf(customer, it) } logger.info { "Found ${oldReviews.size} reviews from Google Cloud Storage bucket of reviews reports" } if (oldReviews.isNotEmpty()) { logger.info { "Writing old Google Play Store reviews to reviews sheet ${ reviewsSheet.spreadsheet.browserUrl }" } reviewsSheet.write(oldReviews) } oldReviews } } logger.info { "Downloading new reviews from Google Play Store for customer ${customer.name}" } val fetchedReviews = googlePlayStore.reviews.listAll(google.packageName) val newReviews = fetchedReviews.distinctFrom(existingReviews.toIdsSet()) { it.reviewId } .map { rowOf(customer, google.packageName, it) } logger.info { "Found ${newReviews.size} new reviews from Google Play Store for customer ${customer.name}" } if (newReviews.isNotEmpty()) { logger.info { "Writing new Google Play Store reviews to reviews sheet ${reviewsSheet.spreadsheet.browserUrl}" } reviewsSheet.write(newReviews) } Pair(newReviews, oldReviews) } logger.info( "${customer.name}: wrote ${appleReviews.size} new Apple App Store reviews and ${googleReviews.size} new Google Play Store reviews", "\t Apple reviews IDs: ${appleReviews.map { it[ReviewsSheet.Headers.ReviewId] }}", "\t Google reviews IDs: ${googleReviews.map { it[ReviewsSheet.Headers.ReviewId] }}", "\t Retrieved ${oldGoogleReviews.size} reviews from Google Play Store review reports in Cloud Storage" ) customer to mapOf( "Apple App Store" to appleReviews, "Google Play Store" to googleReviews, "Google Play Store Review Reports" to oldGoogleReviews ) }.toMap() val writtenReviews = customerToReviews.filterValues { it.values.any { reviews -> reviews.isNotEmpty() } } val counts = writtenReviews.mapValues { it.value.mapValues { entry -> entry.value.size } } val totalCount = counts.values.sumOf { it.values.sum() } if (totalCount > 0) { val averages = writtenReviews.mapValues { it.value.mapValues { entry -> entry.value.mapNotNull { tryOrNull { Integer.parseInt( it[ReviewsSheet.Headers.Rating] ) } }.average().nanAsNull() } } val customerAverage = averages.mapValues { it.value.values.filterNotNull().average().nanAsNull() } val totalAverage = customerAverage.values.filterNotNull().average().nanAsNull() logger.info { "Sending message with imported reviews to Slack" } val response = slack.send(config.slackReviewsWebhook) { fun Int?.toRatingStars(): String = if (this == null) "" else "★".repeat(this) + "☆".repeat(5 - this) fun Double?.toRatingStars(): String = this?.let { if (it.isNaN()) null else it.roundToInt() }.toRatingStars() fun String?.toRatingStars(): String = tryOrNull { this?.toDouble() }.toRatingStars() blocks { section { markdownText(buildString { append("*Beep boop 🤖 I have found new reviews* (last run on ${ Clock.System.now().toLocalDateTime(TimeZone.UTC).let { "${ it.month.toString().capitalized() } ${ it.dayOfMonth }, ${it.year} at ${it.hour}:${it.minute})" } }") append("\n\n") append( "\n⭐ Processed *$totalCount reviews* to the <${ reviewsSheet.spreadsheet.browserUrl }|PocketCampus App Reviews sheet>" ) append( "\nAverage rating over all reviews: ${totalAverage.toRatingStars()} (${ String.format( "%.2f", totalAverage ) })\n" ) }) } divider() writtenReviews.forEach { app -> val (customer, platforms) = app section { markdownText(buildString { append("📱 *${customer.name}*") append( "\nAverage rating of imported reviews for this customer: ${customerAverage[customer].toRatingStars()} (${ String.format( "%.2f", totalAverage ) })" ) }) } platforms.entries.filter { it.value.isNotEmpty() }.forEach { entry -> val (platform, reviews) = entry val sortedReviews = reviews.sortedByDescending { it[ReviewsSheet.Headers.Date] } val dateRange = sortedReviews.mapNotNull { it[ReviewsSheet.Headers.Date]?.let { date -> Instant.parse(date).toLocalDateTime(TimeZone.UTC).date } }.let { it.min()..it.max() } val lastReviews = sortedReviews.take(3) val average = averages[customer]?.get(platform) section { markdownText(buildString { append("🛍️ Found *${reviews.size}* reviews on *$platform*") append("\nPeriod: ${dateRange.start} to ${dateRange.endInclusive}") append( "\nAverage rating of imported reviews for this platform: ${ average.toRatingStars() } (${ String.format( "%.2f", totalAverage ) })" ) append("\nShowing ${lastReviews.size} latest reviews:") }) } lastReviews.forEach { divider() section { markdownText(buildString { append("*Date:* ${it[ReviewsSheet.Headers.Date]}") append("\n*Rating:* ${it[ReviewsSheet.Headers.Rating].toRatingStars()}") append("\n*Author:* ${it[ReviewsSheet.Headers.Author]}") append("\n*Review ID:* ${it[ReviewsSheet.Headers.ReviewId]}") append("\n*Title:* ${it[ReviewsSheet.Headers.Title]}") append("\n> ${it[ReviewsSheet.Headers.Body]?.replace("\n", "\n> ")}") }) } } } divider() } } } logger.info { response.toString() } if (response == null || response.code >= 400) { throw Error("Failed to send Slack message: " + response?.body) } } } catch (error: Throwable) { slack.send(config.slackReviewsWebhook, "🤖⚠️ The app reviews tool encountered an error:\n${error.message}") throw error } }
1
null
0
1
fc0135ffab3a958cfd4c8c0d7994a04ce820e18f
15,705
store-reviews-exporter
Apache License 2.0
app/src/main/java/org/stepic/droid/configuration/RemoteConfig.kt
hkh412
96,096,662
true
{"Java Properties": 2, "Gradle": 4, "Shell": 2, "Text": 19, "Markdown": 1, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 3, "Proguard": 2, "XML": 215, "Java": 282, "Kotlin": 403, "CSS": 1, "JavaScript": 1}
package org.stepic.droid.configuration object RemoteConfig { val continueCourseExperimentEnabledKey = "continue_course_experiment_enabled" val minDelayRateDialogSec = "min_delay_rate_dialog_sec" }
0
Java
0
0
8dc965cbd975bf2ec64220acc78930c5a6b9a7e8
206
stepik-android
Apache License 2.0
src/main/kotlin/org/jetbrains/bio/span/statistics/hmm/NB2ZHMM.kt
JetBrains-Research
159,559,994
false
{"Kotlin": 320171}
package org.jetbrains.bio.span.statistics.hmm import org.jetbrains.bio.dataframe.DataFrame import org.jetbrains.bio.statistics.Preprocessed import org.jetbrains.bio.statistics.model.Fitter /** * A zero-inflated HMM with univariate Negative Binomial emissions. * * @author Alexey Dievsky * @author Sergei Lebedev * @author Oleg Shpynov * @since 25/05/15 */ class NB2ZHMM(nbMeans: DoubleArray, nbFailures: DoubleArray) : FreeNBZHMM(nbMeans, nbFailures) { companion object { @Suppress("MayBeConstant", "unused") @Transient @JvmField val VERSION: Int = 2 fun fitter() = object : Fitter<NB2ZHMM> { override fun guess( preprocessed: Preprocessed<DataFrame>, title: String, threshold: Double, maxIterations: Int ): NB2ZHMM = guess(listOf(preprocessed), title, threshold, maxIterations) override fun guess( preprocessed: List<Preprocessed<DataFrame>>, title: String, threshold: Double, maxIterations: Int ): NB2ZHMM { val (means, failures) = guess(preprocessed, 2) return NB2ZHMM(means, failures) } } } }
7
Kotlin
1
8
5b3d2fe7b9c420d96ae47a304cfea7b82721ec6a
1,286
span
MIT License
app/src/main/java/com/anbui/recipely/data/local/entities/converter/LocalDateTimeConverter.kt
AnBuiii
667,858,307
false
null
package com.anbui.yum.data.converters import androidx.room.TypeConverter import java.time.LocalDateTime class LocalDateTimeConverter { @TypeConverter fun toLocalDateTime(dateString: String): LocalDateTime { return LocalDateTime.parse(dateString) } @TypeConverter fun toDateString(date: LocalDateTime): String { return date.toString() } }
0
Kotlin
1
3
f9be75c6dc8fba9ce7eb5a080c28de6e68ba4a5b
381
Yum
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/SqrtBox.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: SqrtBox * * Full name: System`SqrtBox * * Usage: SqrtBox[x] is a low-level box construct that represents the displayed object Sqrt[x] in notebook expressions. * * MinSize -> Automatic * Options: MultilineFunction -> None * * Protected * Attributes: ReadProtected * * local: paclet:ref/SqrtBox * Documentation: web: http://reference.wolfram.com/language/ref/SqrtBox.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun sqrtBox(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("SqrtBox", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,072
mathemagika
Apache License 2.0
backend/src/test/kotlin/com/github/davinkevin/podcastserver/find/FindHandlerTest.kt
sugartime
218,463,114
true
{"HTML": 22707379, "Kotlin": 968949, "TypeScript": 162740, "JavaScript": 95419, "Java": 65945, "CSS": 26945, "Shell": 6240, "Dockerfile": 4258, "Smarty": 328}
package com.github.davinkevin.podcastserver.find import com.github.davinkevin.podcastserver.extension.json.assertThatJson import com.github.davinkevin.podcastserver.service.image.CoverInformation import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest import org.springframework.boot.test.context.TestConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Import import org.springframework.test.web.reactive.server.WebTestClient import reactor.core.publisher.toMono import java.net.URI @WebFluxTest(controllers = [FindHandler::class]) class FindHandlerTest { @Autowired lateinit var rest: WebTestClient @Autowired lateinit var finder: FindService @Nested @DisplayName("should find") inner class ShouldFind { @Test fun `with success`() { /* Given */ val url = URI("http://foo.bar.com/") val podcast = FindPodcastInformation( title = "aTitle", url = url, description = "", type = "aType", cover = FindCoverInformation(100, 100, URI("http://foo.bar.com/img.png")) ) whenever(finder.find(url)).thenReturn(podcast.toMono()) /* When */ rest .post() .uri("/api/v1/podcasts/find") .syncBody(url.toASCIIString()) .exchange() /* Then */ .expectStatus().isOk .expectBody() .assertThatJson { isEqualTo(""" { "title":"aTitle", "description":"", "url":"http://foo.bar.com/", "cover":{ "height":100, "width":100, "url":"http://foo.bar.com/img.png" }, "type":"aType" }""") } } } @TestConfiguration @Import(FindRoutingConfig::class) class LocalConfiguration { @Bean fun findService() = mock<FindService>() } }
0
HTML
0
0
915304b24abffa9896d01b1ed29b65c79e218b33
2,519
Podcast-Server
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/screen/register/SignUp.kt
meierjan
347,410,106
false
null
package com.example.androiddevchallenge.screen.register import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.androiddevchallenge.Navigator import com.example.androiddevchallenge.Screen import com.example.androiddevchallenge.ui.theme.MyTheme @Composable fun SignUp(navigator: Navigator) { val onLoginClicked = { navigator.navigate(Screen.Home) } val viewModel = viewModel(SignUpViewModel::class.java) // we should consider not storing the password for security reasons var password by remember { mutableStateOf("") } var emailInputState by remember { mutableStateOf("") } val isSubmitPossible = password.isNotBlank() && emailInputState.isNotBlank() Column( modifier = Modifier .fillMaxWidth() .padding(16.dp, 0.dp) ) { Spacer( modifier = Modifier .fillMaxWidth() .height(184.dp) ) Text( text = "Log in with email", textAlign = TextAlign.Center, style = MaterialTheme.typography.h1, color = MaterialTheme.colors.onBackground, modifier = Modifier.fillMaxWidth() ) Spacer( modifier = Modifier .fillMaxWidth() .height(8.dp) ) OutlinedTextField( value = emailInputState, placeholder = { Text("Email address", style = MaterialTheme.typography.body1) }, textStyle = MaterialTheme.typography.body1, singleLine = true, onValueChange = { emailInputState = it }, modifier = Modifier .height(56.dp) .fillMaxWidth() ) OutlinedTextField( value = password, textStyle = MaterialTheme.typography.body1, placeholder = { Text( "Password (8+ characters)", style = MaterialTheme.typography.body1, modifier = Modifier.fillMaxSize() ) }, singleLine = true, onValueChange = { password = it }, modifier = Modifier .height(56.dp) .fillMaxWidth() ) Spacer( modifier = Modifier .fillMaxWidth() .height(8.dp) ) Text( text = "By clicking below, you agree to our Terms of Use and consent to our Privacy Policy.", style = MaterialTheme.typography.body2, textAlign = TextAlign.Center, color = MaterialTheme.colors.onPrimary, modifier = Modifier.fillMaxWidth() ) Spacer( modifier = Modifier .fillMaxWidth() .height(8.dp) ) Button( shape = MaterialTheme.shapes.medium, onClick = onLoginClicked, enabled = isSubmitPossible, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.secondary, contentColor = MaterialTheme.colors.onSecondary ), modifier = Modifier .fillMaxWidth() .height(48.dp) ) { Text(text = "Log in") } } } @Preview("Light Theme", widthDp = 360, heightDp = 640) @Composable fun LightPreviewSignUp() { MyTheme { val navigator = object : Navigator { override fun navigate(screen: Screen) {} } SignUp(navigator) } } @Preview("Dark Theme", widthDp = 360, heightDp = 640) @Composable fun DarkPreviewSignUp() { MyTheme(darkTheme = true) { val navigator = object : Navigator { override fun navigate(screen: Screen) {} } SignUp(navigator) } }
0
Kotlin
0
0
cdb5512467e535d3c7ccc8b4583f5261b13a6e34
4,160
Bloom
Apache License 2.0
src/main/kotlin/com/xinaiz/wds/util/extensions/Point_.kt
domazey
155,060,100
false
null
package com.xinaiz.wds.util.extensions import com.xinaiz.wds.core.by.ExtendedBy import com.xinaiz.wds.core.element.ExtendedWebElement import org.openqa.selenium.Point import org.openqa.selenium.WebElement fun Point.findIn(element: WebElement): WebElement { return element.findElement(ExtendedBy.point(this)) } fun Point.findIn(element: ExtendedWebElement): WebElement { return element.findElement(ExtendedBy.point(this)) }
0
Kotlin
0
0
55012e722cb4e56785ca25e5477e0d7c2a5260cc
433
web-driver-support
Apache License 2.0
action-binding-generator/src/test/kotlin/io/github/typesafegithub/workflows/actionbindinggenerator/bindingsfromunittests/ActionWithPartlyTypings_Untyped.kt
typesafegithub
439,670,569
false
null
// This file was generated using action-binding-generator. Don't change it by hand, otherwise your // changes will be overwritten with the next binding code regeneration. // See https://github.com/typesafegithub/github-workflows-kt for more info. @file:Suppress( "DataClassPrivateConstructor", "UNUSED_PARAMETER", ) package io.github.typesafegithub.workflows.actions.johnsmith import io.github.typesafegithub.workflows.domain.actions.Action import io.github.typesafegithub.workflows.domain.actions.RegularAction import java.util.LinkedHashMap import kotlin.String import kotlin.Suppress import kotlin.Unit import kotlin.collections.Map import kotlin.collections.toList import kotlin.collections.toTypedArray /** * ```text * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * !!! WARNING !!! * !!! !!! * !!! This action binding has no typings provided. All inputs will !!! * !!! have a default type of String. !!! * !!! To be able to use this action in a type-safe way, ask the !!! * !!! action's owner to provide the typings using !!! * !!! !!! * !!! https://github.com/typesafegithub/github-actions-typing !!! * !!! !!! * !!! or if it's impossible, contribute typings to a community-driven !!! * !!! !!! * !!! https://github.com/typesafegithub/github-actions-typing-catalog !!! * !!! !!! * !!! This '_Untyped' binding will be available even once the typings !!! * !!! are added. !!! * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * ``` * * Action: Do something cool * * This is a test description that should be put in the KDoc comment for a class * * [Action on GitHub](https://github.com/john-smith/action-with-no-typings) * * @param _customInputs Type-unsafe map where you can put any inputs that are not yet supported by * the binding * @param _customVersion Allows overriding action's version, for example to use a specific minor * version, or a newer version that the binding doesn't yet know about */ public data class ActionWithNoTypings_Untyped private constructor( public val foo: String, public val bar: String? = null, /** * Type-unsafe map where you can put any inputs that are not yet supported by the binding */ public val _customInputs: Map<String, String> = mapOf(), /** * Allows overriding action's version, for example to use a specific minor version, or a newer * version that the binding doesn't yet know about */ public val _customVersion: String? = null, ) : RegularAction<Action.Outputs>("john-smith", "action-with-no-typings", _customVersion ?: "v3") { public constructor( vararg pleaseUseNamedArguments: Unit, foo: String, bar: String? = null, _customInputs: Map<String, String> = mapOf(), _customVersion: String? = null, ) : this(foo=foo, bar=bar, _customInputs=_customInputs, _customVersion=_customVersion) @Suppress("SpreadOperator") override fun toYamlArguments(): LinkedHashMap<String, String> = linkedMapOf( *listOfNotNull( "foo" to foo, bar?.let { "bar" to it }, *_customInputs.toList().toTypedArray(), ).toTypedArray() ) override fun buildOutputObject(stepId: String): Action.Outputs = Outputs(stepId) }
40
null
24
519
e53f3e38214a447730ac27595affa0a9e6cc7a21
3,797
github-workflows-kt
Apache License 2.0
src/main/kotlin/me/yunleah/plugin/coldestiny/internal/hook/griefdefender/impl/GriefDefenderHookerImpl.kt
Yunleah
664,422,335
false
null
package me.yunleah.plugin.coldestiny.internal.hook.griefdefender.impl import com.griefdefender.api.GriefDefender import me.yunleah.plugin.coldestiny.internal.hook.griefdefender.GriefDefenderHooker import org.bukkit.OfflinePlayer /** * GriefDefender附属领地挂钩 * * @constructor 启用GriefDefender附属领地挂钩 */ class GriefDefenderHookerImpl : GriefDefenderHooker() { override fun getLocation(player: OfflinePlayer): String? { val claim = GriefDefender.getCore().getClaimAt(player.player!!.location) return claim?.displayName } }
0
Kotlin
0
2
45140895612ae0270911d108cc4394d0dce052b1
545
ColdEstiny
MIT License
module/webview/src/main/java/jp/hazuki/yuzubrowser/webview/WebViewRenderingManager.kt
hazuki0x0
84,384,224
false
null
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.webview import android.graphics.ColorMatrix import android.graphics.ColorMatrixColorFilter import android.graphics.Paint import android.view.View import jp.hazuki.yuzubrowser.core.utility.utils.ColorFilterUtils class WebViewRenderingManager { private var colorTemp: Int = 0 private var nightBright: Int = 0 private val negativePaint by lazy(LazyThreadSafetyMode.NONE) { Paint().apply { colorFilter = ColorMatrixColorFilter(NEGATIVE_COLOR) } } private val grayPaint by lazy(LazyThreadSafetyMode.NONE) { val grayScale = ColorMatrix() grayScale.setSaturation(0f) Paint().apply { colorFilter = ColorMatrixColorFilter(grayScale) } } private val negativeGrayFilter by lazy(LazyThreadSafetyMode.NONE) { val negative = ColorMatrix() negative.set(NEGATIVE_COLOR) val grayScale = ColorMatrix() grayScale.setSaturation(0f) val matrix = ColorMatrix() matrix.setConcat(negative, grayScale) Paint().apply { ColorMatrixColorFilter(matrix) } } private val temperaturePaintDelegate = lazy(LazyThreadSafetyMode.NONE) { Paint().apply { colorFilter = ColorMatrixColorFilter(ColorFilterUtils.colorTemperatureToMatrix(colorTemp, nightBright)) } } var defaultMode = 0 fun onPreferenceReset(defaultMode: Int, colorTemp: Int, nightBright: Int) { this.defaultMode = defaultMode this.colorTemp = colorTemp this.nightBright = nightBright if (temperaturePaintDelegate.isInitialized()) { temperaturePaintDelegate.value.colorFilter = ColorMatrixColorFilter(ColorFilterUtils.colorTemperatureToMatrix(colorTemp, nightBright)) } } fun setWebViewRendering(webView: CustomWebView, mode: Int = defaultMode) { if (webView.renderingMode == mode) return webView.renderingMode = mode when (mode) { RENDERING_NORMAL -> webView.setLayerType(View.LAYER_TYPE_NONE, null) RENDERING_INVERT -> webView.setLayerType(View.LAYER_TYPE_HARDWARE, negativePaint) RENDERING_GRAY -> webView.setLayerType(View.LAYER_TYPE_HARDWARE, grayPaint) RENDERING_INVERT_GRAY -> webView.setLayerType(View.LAYER_TYPE_HARDWARE, negativeGrayFilter) RENDERING_TEMPERATURE -> webView.setLayerType(View.LAYER_TYPE_HARDWARE, temperaturePaintDelegate.value) else -> throw IllegalArgumentException("mode: $mode is not mode value") } } companion object { private val NEGATIVE_COLOR = floatArrayOf( -1f, 0f, 0f, 0f, 255f, 0f, -1f, 0f, 0f, 255f, 0f, 0f, -1f, 0f, 255f, 0f, 0f, 0f, 1f, 0f) const val RENDERING_NORMAL = 0 const val RENDERING_INVERT = 1 const val RENDERING_GRAY = 2 const val RENDERING_INVERT_GRAY = 3 const val RENDERING_TEMPERATURE = 4 } }
115
null
95
301
6a867f406b7fc6b29f1899c7ca622e7ce75fafa0
3,548
YuzuBrowser
Apache License 2.0
plugin-bsp/src/main/kotlin/org/jetbrains/plugins/bsp/performanceImpl/WaitForBazelSyncCommand.kt
JetBrains
826,262,028
false
null
package org.jetbrains.plugins.bsp.performanceImpl import com.intellij.collaboration.async.nestedDisposable import com.intellij.openapi.ui.playback.PlaybackContext import com.intellij.openapi.ui.playback.commands.PlaybackCommandCoroutineAdapter import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull import org.jetbrains.plugins.bsp.impl.projectAware.BspWorkspaceListener import org.jetbrains.plugins.bsp.impl.projectAware.isSyncInProgress import org.jetbrains.plugins.bsp.target.temporaryTargetUtils private const val SYNC_START_TIMEOUT_MS = 10000L internal class WaitForBazelSyncCommand(text: String, line: Int) : PlaybackCommandCoroutineAdapter(text, line) { companion object { const val PREFIX = CMD_PREFIX + "waitForBazelSync" } override suspend fun doExecute(context: PlaybackContext) = coroutineScope { val project = context.project val syncStarted = Channel<Unit>(capacity = 1) val syncFinished = Channel<Unit>(capacity = 1) @Suppress("UnstableApiUsage") project.messageBus.connect(nestedDisposable()).subscribe( BspWorkspaceListener.TOPIC, object : BspWorkspaceListener { override fun syncStarted() { runBlocking { syncStarted.send(Unit) } } override fun syncFinished(canceled: Boolean) { runBlocking { syncFinished.send(Unit) } } }, ) // If the sync was started before the call to `doExecute`, we will not receive the event. Hence the timeout. withTimeoutOrNull(SYNC_START_TIMEOUT_MS) { syncStarted.receive() } if (project.isSyncInProgress()) { syncFinished.receive() } check(project.temporaryTargetUtils.allTargetIds().isNotEmpty()) { "Target id list is empty after sync" } } }
2
null
18
45
1d79484cfdf8fc31d3a4b214655e857214071723
1,903
hirschgarten
Apache License 2.0
data/db/src/commonMain/kotlin/app/tivi/data/daos/LibraryShowsDao.kt
chrisbanes
100,624,553
false
null
// Copyright 2017, Google LLC, <NAME> and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 package app.tivi.data.daos import androidx.paging.PagingSource import app.tivi.data.compoundmodels.LibraryShow import app.tivi.data.models.SortOption interface LibraryShowsDao { fun pagedListLastWatched( sort: SortOption, filter: String?, includeWatched: Boolean, includeFollowed: Boolean, ): PagingSource<Int, LibraryShow> }
23
null
876
6,626
e261ffbded01c1439b93c550cd6e714c13bb9192
460
tivi
Apache License 2.0
livemap/src/commonMain/kotlin/jetbrains/livemap/core/SystemTime.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.livemap.core expect open class SystemTime() { fun getTimeMs(): Long }
97
null
51
889
c5c66ceddc839bec79b041c06677a6ad5f54e416
250
lets-plot
MIT License
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/domain/usecase/FindYourCoursesUseCase.kt
denchic45
435,895,363
false
{"Kotlin": 2103689, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.domain.usecase import com.denchic45.studiversity.data.repository.CourseRepository import com.denchic45.studiversity.domain.resource.Resource import com.denchic45.stuiversity.api.course.model.CourseResponse import me.tatarka.inject.annotations.Inject @Inject class FindYourCoursesUseCase(private val courseRepository: CourseRepository) { suspend operator fun invoke(): Resource<List<CourseResponse>> { return courseRepository.findByMe() } }
0
Kotlin
0
7
93947301de4c4a9cb6c3d9fa36903f857c50e6c2
492
Studiversity
Apache License 2.0
plugins/kotlin/j2k/new/tests/testData/newJ2k/field/volatileCommon.kt
ingokegel
72,937,917
false
null
import kotlin.concurrent.Volatile // API_VERSION: 1.9 // COMPILER_ARGUMENTS: -opt-in=kotlin.ExperimentalStdlibApi internal class A { @Volatile var field1 = 0 }
214
null
4829
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
169
intellij-community
Apache License 2.0
src/main/kotlin/com/sheepduke/api/server/common/ApiGatewayHandler.kt
sheepduke
214,113,954
false
null
package com.sheepduke.api.server.common import com.amazonaws.services.lambda.runtime.Context import com.amazonaws.services.lambda.runtime.RequestHandler import mu.KotlinLogging object ApiGatewayRequestKeys { const val BODY: String = "body" } object ApiGatewayResponseKeys { const val STATUS_CODE = "statusCode" const val BODY: String = "body" } /** * A thin wrapper of [RequestHandler]. */ abstract class ApiGatewayHandler<Out> : RequestHandler<Map<String, Any>, Map<String, Any>> { private val log = KotlinLogging.logger {} override fun handleRequest(input: Map<String, Any>, context: Context): Map<String, Any> { log.info { "Request: $input" } log.info { """ Environment: PATH=${Globals.Environment.PATH} """.trimIndent() } val response: ApiGatewayResponse<Out> = try { val requestBody = input[ApiGatewayRequestKeys.BODY] as String? val request = ApiGatewayRequest(body = requestBody) handleRequest(request) } catch (e: BadRequestException) { log.warn { "Bad request: ${e.message}" } ApiGatewayResponse(statusCode = 400) } return response.toMap() } abstract fun handleRequest(request: ApiGatewayRequest): ApiGatewayResponse<Out> } /** * Convert [ApiGatewayResponse] to corresponding [Map] that will be returned to the caller. */ fun <T> ApiGatewayResponse<T>.toMap(): Map<String, Any> { return mapOf( ApiGatewayResponseKeys.STATUS_CODE to this.statusCode, ApiGatewayResponseKeys.BODY to this.bodyString) }
0
Kotlin
1
0
411680437ff535bec3666ea93cc89acc3f8a13a3
1,632
demo-kotlin-aws-api-server
MIT License
gremlin-kore/src/main/kotlin/org/apache/tinkerpop4/gremlin/jsr223/console/GremlinShellEnvironment.kt
phreed
449,920,526
false
{"Java": 12267812, "Kotlin": 3878234, "C#": 1500464, "Python": 566321, "Gherkin": 438600, "Groovy": 345265, "JavaScript": 229293, "TypeScript": 154521, "Shell": 61593, "ANTLR": 43774, "Dockerfile": 6202, "XSLT": 4410, "Batchfile": 3977, "Awk": 2335}
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop4.gremlin.jsr223.console /** * Provides an abstraction over a "Gremlin Shell" (i.e. the core of a console), enabling the plugin to not have to * be hardcoded specifically to any particular shell, like the Gremlin Groovy Console, and thus allowing it to * not have to depend on the gremlin-groovy module itself. * * @author <NAME> (http://stephen.genoprime.com) */ interface GremlinShellEnvironment { fun <T> getVariable(variableName: String?): T fun <T> setVariable(variableName: String?, variableValue: T) fun println(line: String?) fun errPrintln(line: String?) { println(line) } fun <T> execute(line: String?): T }
4
null
1
1
cb6805d686e9a27caa8e597b0728a50a63dc9092
1,491
tinkerpop4
Apache License 2.0
core-network/src/main/java/com/awesomejim/pokedex/core/network/model/ResponseMapper.kt
AwesomeJim
728,151,790
false
{"Kotlin": 104027}
package com.awesomejim.pokedex.core.network.model import com.awesomejim.pokedex.core.model.Ability import com.awesomejim.pokedex.core.model.Pokemon import com.awesomejim.pokedex.core.model.PokemonInfo import com.awesomejim.pokedex.core.model.PokemonType import com.awesomejim.pokedex.core.model.Stats import com.awesomejim.pokedex.core.model.getImageUrl import java.util.Locale /** * Created by <NAME> on. * 09/12/2023 */ const val MAX_HP = 300 const val MAX_ATTACK = 300 const val MAX_DEFENSE = 300 const val MAX_SPEED = 300 const val MAX_EXP = 1000 data class ClientException(override val message: String) : Throwable(message = message) data class ServerException(override val message: String) : Throwable(message = message) data class GenericException(override val message: String) : Throwable(message = message) fun PokemonItemResponse.toCoreModel(): Pokemon { val index = url.split("/".toRegex()).dropLast(1).lastOrNull() ?: "1" val id = index.toInt() val imageUrl = getImageUrl(index) return Pokemon( page, name.titleCase(), id, imageUrl ) } fun List<PokemonItemResponse>.toCoreModelList(): List<Pokemon> { return this.map { pokemon -> pokemon.toCoreModel() } } fun mapResponseCodeToThrowable(code: Int): Throwable = when (code) { in 400..499 -> ClientException("Client error : $code") in 500..600 -> ServerException("Server error : $code") else -> GenericException("Generic error : $code") } fun String.titleCase() = this.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() } fun PokemonInfoResponse.toCoreModel(): PokemonInfo { val typeResponse = this.types val abilityResponse = this.abilities val statsResponse = this.stats val pokemonTypes = typeResponse.map { PokemonType( slot = it.slot, name = it.type.name.titleCase() ) } val abilities = abilityResponse.map { Ability( name = it.ability.name.titleCase(), isHidden = it.isHidden, slot = it.slot ) } val statistics = statsResponse.map { val baseStat = it.baseStat val formattedBaseStat = when (it.stat.name) { "hp" -> " $baseStat/$MAX_HP" "attack" -> " $baseStat/$MAX_ATTACK" "defense" -> " $baseStat/$MAX_DEFENSE" "speed" -> " $baseStat/$MAX_SPEED" "exp" -> " $baseStat/$MAX_EXP" else -> { "$baseStat/.." } } Stats( name = it.stat.name.titleCase(), baseStat = it.baseStat, effort = it.effort, formattedBaseStat = formattedBaseStat ) } return PokemonInfo( id = this.id, name = this.name.titleCase(), height = this.height, weight = this.weight, experience = this.experience, types = pokemonTypes, abilities = abilities, stats = statistics ) }
0
Kotlin
0
0
13fb520a6a58d516303cb2ee99de4a9a9de68d22
3,033
MiniPokedex
Apache License 2.0
contracts/src/test/kotlin/com/template/states/BALLOTStateTests.kt
icgarlin
194,896,005
true
{"Kotlin": 30470, "HTML": 2040, "JavaScript": 1828}
package net.corda.training.state import net.corda.core.contracts.* import net.corda.core.identity.Party import net.corda.finance.* import org.junit.Test import java.util.* import kotlin.test.assertEquals import kotlin.test.assertNotEquals import com.example.state.BALLOTState class BALLOTStateTests { @Test fun hasBALLOTIssuerFieldOfCorrectType() { // Does the issuer field exist? BALLOTState::class.java.getDeclaredField("issuer") // Is the issuer field of the correct type? assertEquals(BALLOTState::class.java.getDeclaredField("issuer").type, Party::class.java) } @Test fun hasBALLOTVoterFieldOfCorrectType() { // Does the voter field exist? BALLOTState::class.java.getDeclaredField("voter") // Is the voter field of the correct type? assertEquals(IOUState::class.java.getDeclaredField("voter").type, Party::class.java) } @Test fun hasBALLOTSelectionsFieldOfCorrectType() { // Does the selections field exist? BALLOTState::class.java.getDeclaredField("selections") // Is the borrower field of the correct type? assertEquals(BALLOTState::class.java.getDeclaredField("selections").type, Party::class.java) } @Test fun isLinearState() { assert(LinearState::class.java.isAssignableFrom(BALLOTState::class.java)) } @Test fun hasLinearIdFieldOfCorrectType() { // Does the linearId field exist? BALLOTState::class.java.getDeclaredField("linearId") // Is the linearId field of the correct type? assertEquals(BALLOTState::class.java.getDeclaredField("linearId").type, UniqueIdentifier::class.java) } @Test fun checkBALLOTStateParameterOrdering() { val fields = BALLOTState::class.java.declaredFields val countIdx = fields.indexOf(BALLOTState::class.java.getDeclaredField("count")) val issuerIdx = fields.indexOf(BALLOTState::class.java.getDeclaredField("issuer")) val voterIdx = fields.indexOf(BALLOTState::class.java.getDeclaredField("voter")) val selectionsIdx = fields.indexOf(BALLOTState::class.java.getDeclaredField("selections")) val linearIdIdx = fields.indexOf(BALLOTState::class.java.getDeclaredField("linearId")) assert(countIdx < issuerIdx) assert(issuerIdx < voterIdx) assert(voterIdx < selectionsIdx) assert(selectionsIdx < linearIdIdx) } }
0
Kotlin
0
0
21cafa862204310d6a2964fc356fa2768593b7b6
2,460
cordapp-voda-kotlin
Apache License 2.0
tradeit-android-sdk/src/main/kotlin/it/trade/android/sdk/TradeItSDK.kt
tradingticket
74,619,601
false
null
package it.trade.android.sdk import android.util.Log import it.trade.android.sdk.exceptions.TradeItSDKConfigurationException import it.trade.android.sdk.manager.TradeItLinkedBrokerManager import it.trade.android.sdk.model.TradeItLinkedBrokerCache import it.trade.model.request.TradeItEnvironment object TradeItSDK { private var instance: TradeItSdkInstance? = null @JvmStatic val linkedBrokerManager: TradeItLinkedBrokerManager @Throws(TradeItSDKConfigurationException::class) get() { if (instance == null) { throw TradeItSDKConfigurationException("ERROR: TradeItSDK.linkedBrokerManager referenced before calling TradeItSDK.configure()!") } return instance!!.linkedBrokerManager!! } val environment: TradeItEnvironment? get() { if (instance == null) { throw TradeItSDKConfigurationException("ERROR: TradeItSDK.linkedBrokerManager referenced before calling TradeItSDK.configure()!") } return instance!!.environment } val linkedBrokerCache: TradeItLinkedBrokerCache? get() { if (instance == null) { throw TradeItSDKConfigurationException("ERROR: TradeItSDK.linkedBrokerCache referenced before calling TradeItSDK.configure()!") } return instance!!.linkedBrokerCache } @JvmStatic fun configure(configurationBuilder: TradeItConfigurationBuilder) { if (instance == null) { instance = TradeItSdkInstance(configurationBuilder) } else { Log.w("TradeItSDK", "Warning: TradeItSDK.configure() called multiple times. Ignoring.") } } fun clearConfig() { instance = null } }
2
null
10
13
1d784e9eba023479652ccc5963ea7a77624bde01
1,779
AndroidSDK
Apache License 2.0
radar-jersey/src/main/kotlin/org/radarbase/jersey/exception/mapper/DefaultTextExceptionRenderer.kt
RADAR-base
212,096,820
false
{"Kotlin": 184451, "HTML": 330}
/* * Copyright (c) 2019. The Hyve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * See the file LICENSE in the root of this repository. */ package org.radarbase.jersey.exception.mapper import org.radarbase.jersey.exception.HttpApplicationException /** * Render an exception using a Mustache HTML document. */ class DefaultTextExceptionRenderer : ExceptionRenderer { override fun render(exception: HttpApplicationException): String { return "[${exception.status}] ${exception.code}: ${exception.detailedMessage ?: "unknown reason"}" } }
1
Kotlin
0
2
8f53a65af66eb6fabca5cd9baa68ceddb750773e
654
radar-jersey
Apache License 2.0
OpenLibraryApp/app/src/main/java/com/woowrale/openlibrary/ui/observers/Observers.kt
woowrale
259,549,697
false
null
package com.woowrale.openlibrary.ui.observers import android.util.Log import androidx.lifecycle.MutableLiveData import com.woowrale.openlibrary.domain.model.Book import com.woowrale.openlibrary.domain.model.Seed import com.woowrale.openlibrary.usecase.observers.Observer class SaveSeedObserver constructor(private val isSaved: MutableLiveData<Boolean>) : Observer<Boolean>() { private val TAG = SaveSeedObserver::class.java.simpleName override fun onSuccess(t: Boolean) { super.onSuccess(t) isSaved.value = t Log.e(TAG, "Se ha procesado correctamente") } override fun onError(e: Throwable) { super.onError(e) Log.e(TAG, "Se ha producido una excepcion" + e.message) } } class GetSeedsObserver constructor(private val seeds: MutableLiveData<List<Seed>>) : Observer<List<Seed>>() { private val TAG = GetSeedsObserver::class.java.simpleName override fun onSuccess(t: List<Seed>) { seeds.value = t Log.e(TAG, "Se ha procesado correctamente") } override fun onError(e: Throwable) { Log.e(TAG, "Se ha producido una excepcion" + e.message) } } class DeleteSeedObserver constructor(private val isSaved: MutableLiveData<Boolean>) : Observer<Boolean>() { private val TAG = DeleteSeedObserver::class.java.simpleName override fun onSuccess(t: Boolean) { super.onSuccess(t) isSaved.value = t Log.e(TAG, "Se ha procesado correctamente") } override fun onError(e: Throwable) { super.onError(e) Log.e(TAG, "Se ha producido una excepcion" + e.message) } } class BooksObserver constructor(private val books: MutableLiveData<List<Book>>) : Observer<List<Book>>() { private val TAG = BooksObserver::class.java.simpleName override fun onSuccess(t: List<Book>) { books.value = t } override fun onError(e: Throwable) { Log.e(TAG, "Se ha producido una excepcion" + e.message) } } class SaveBookObserver constructor(private val isSaved: MutableLiveData<Boolean>) : Observer<Boolean>() { private val TAG = SaveBookObserver::class.java.simpleName override fun onSuccess(t: Boolean) { super.onSuccess(t) isSaved.value = t Log.e(TAG, "Se ha procesado correctamente") } override fun onError(e: Throwable) { super.onError(e) Log.e(TAG, "Se ha producido una excepcion" + e.message) } }
0
Kotlin
0
0
396d7e9a289c619d571caf0c4dc2fb36c43b6be1
2,433
architect-coders-project
MIT License
generated-code-tests/src/test/kotlin/dogacel/kotlinx/protobuf/gen/proto/OneofPOC.kt
Dogacel
674,802,209
false
null
package dogacel.kotlinx.protobuf.gen.proto import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromByteArray import kotlinx.serialization.encodeToByteArray import kotlinx.serialization.protobuf.ProtoBuf import kotlinx.serialization.protobuf.ProtoNumber import kotlin.test.assertEquals import testgen.oneof.OneofMessage import kotlin.test.Ignore import kotlin.test.Test class OneofPOC { @Test @Ignore fun shouldDeSerAll() { val message = oneof.Oneof.OneofMessage.newBuilder() fun validateDeser(messageParam: oneof.Oneof.OneofMessage): OneofPOCMessage { val result: OneofPOCMessage = ProtoBuf.decodeFromByteArray(messageParam.toByteArray()) val deser = oneof.Oneof.OneofMessage.parseFrom(ProtoBuf.encodeToByteArray(result)) assertEquals(messageParam, deser) return result } assertEquals(1U, validateDeser(message.setOneofUint32(1).build()).oneofField?.value) assertEquals("1", validateDeser(message.setOneofString("1").build()).oneofField?.value) assertEquals(true, validateDeser(message.setOneofBool(true).build()).oneofField?.value) assertEquals(1UL, validateDeser(message.setOneofUint64(1).build()).oneofField?.value) assertEquals(1.0f, validateDeser(message.setOneofFloat(1.0f).build()).oneofField?.value) assertEquals(1.0, validateDeser(message.setOneofDouble(1.0).build()).oneofField?.value) assertEquals( OneofPOCMessage.NestedEnum.BAZ, validateDeser( message.setOneofEnum(oneof.Oneof.OneofMessage.NestedEnum.BAZ).build() ).oneofField?.value ) assertEquals("1", validateDeser(message.setLeft("1").build()).secondOneOfField?.value) assertEquals("1", validateDeser(message.setRight("1").build()).secondOneOfField?.value) } @Test fun shouldDeSerEmpty() { val message = oneof.Oneof.OneofMessage.newBuilder().build() val result: OneofPOCMessage = ProtoBuf.decodeFromByteArray(message.toByteArray()) val deser = oneof.Oneof.OneofMessage.parseFrom(ProtoBuf.encodeToByteArray(result)) assertEquals(message, deser) } } interface KOneof<T : Any> { val value: T } @Serializable public data class OneofPOCMessage( public val oneofField: OneofField<@Contextual Any>? = null, public val secondOneOfField: SecondOneOfField<@Contextual Any>? = null ) { sealed interface OneofField<T : Any> : KOneof<T> { @JvmInline value class Uint32( @ProtoNumber(number = 1) override val value: UInt ) : OneofField<UInt> @JvmInline value class NestedMessage( @ProtoNumber(number = 2) override val value: OneofMessage ) : OneofField<OneofMessage> @JvmInline value class String( @ProtoNumber(number = 3) override val value: kotlin.String ) : OneofField<kotlin.String> @JvmInline value class Bool( @ProtoNumber(number = 5) override val value: kotlin.Boolean ) : OneofField<Boolean> @JvmInline value class Uint64( @ProtoNumber(number = 6) override val value: ULong ) : OneofField<ULong> @JvmInline value class Float( @ProtoNumber(number = 7) override val value: kotlin.Float ) : OneofField<kotlin.Float> @JvmInline value class Double( @ProtoNumber(number = 8) override val value: kotlin.Double ) : OneofField<kotlin.Double> @JvmInline value class Enum( @ProtoNumber(number = 9) override val value: NestedEnum ) : OneofField<NestedEnum> } @kotlinx.serialization.Serializable sealed interface SecondOneOfField<T : Any> : KOneof<T> { @JvmInline value class Left( @ProtoNumber(number = 10) override val value: String ) : SecondOneOfField<String> @JvmInline value class Right( @ProtoNumber(number = 11) override val value: String ) : SecondOneOfField<String> } @kotlinx.serialization.Serializable public data class NestedMessage( @ProtoNumber(number = 1) public val a: Int = 0, @ProtoNumber(number = 2) public val corecursive: OneofMessage? = null ) @kotlinx.serialization.Serializable public enum class NestedEnum { @ProtoNumber(number = 0) FOO, @ProtoNumber(number = 1) BAR, @ProtoNumber(number = 2) BAZ, @ProtoNumber(number = -1) NEG } }
11
null
1
6
668d2cda7233dd5a8e0a0c94122abe8caf6d29b8
4,791
kotlinx-protobuf-gen
Apache License 2.0
src/test/kotlin/examples/kotlin/mybatis3/column/comparison/ColumnComparisonDynamicSqlSupport.kt
mybatis
73,488,326
false
{"Java": 1977035, "Kotlin": 613939, "CSS": 683}
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 examples.kotlin.mybatis3.column.comparison import org.mybatis.dynamic.sql.SqlTable import org.mybatis.dynamic.sql.util.kotlin.elements.column import java.sql.JDBCType object ColumnComparisonDynamicSqlSupport { val columnComparison = ColumnComparison() val number1 = columnComparison.number1 val number2 = columnComparison.number2 val columnList = listOf(number1, number2) class ColumnComparison : SqlTable("ColumnComparison") { val number1 = column<Int>(name = "number1", jdbcType = JDBCType.INTEGER) val number2 = column<Int>(name = "number2", jdbcType = JDBCType.INTEGER) } }
7
Java
212
999
067a30c991d46f6b159dcb4f47e16ccb9948829a
1,280
mybatis-dynamic-sql
Apache License 2.0
smartdoc-dashboard/src/main/kotlin/smartdoc/dashboard/controller/console/view/ServiceClientViewController.kt
Maple-mxf
283,354,797
false
null
package restdoc.web.controller.console.view import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestParam import restdoc.rpc.client.common.model.ApplicationType import restdoc.web.base.auth.Verify @Controller @Verify class ServiceClientViewController { @GetMapping("/serviceClient/view/list") fun list() = "cs/list" @GetMapping("/serviceClient/view/index") fun index() = "cs/index" @GetMapping("/serviceClient/{clientId}/apiList/view") fun apiList(model: Model, @PathVariable clientId: String, @RequestParam(required = false,defaultValue = "REST_WEB") ap: ApplicationType): String { model.addAttribute("clientId", clientId) model.addAttribute("ap", ap) return "client/api-list" } }
21
null
2
2
3cdf9de7593c78c819b3dadc9b583e736041d55f
975
rest-doc
Apache License 2.0
app/src/main/java/com/andrii_a/walleria/di/DatabaseModule.kt
andrew-andrushchenko
525,795,850
false
{"Kotlin": 656065}
package com.andrii_a.walleria.di import android.app.Application import androidx.room.Room import com.andrii_a.walleria.data.local.db.WalleriaDatabase import com.andrii_a.walleria.data.local.db.dao.RecentSearchesDao import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun provideWalleriaDatabase(application: Application): WalleriaDatabase = Room.databaseBuilder(application, WalleriaDatabase::class.java, "walleria_db") .fallbackToDestructiveMigration() .build() @Provides fun provideRecentSearchesDao(db: WalleriaDatabase): RecentSearchesDao = db.recentSearchesDao() }
0
Kotlin
2
3
c25661c610d3197390ac86b7c63295a10095e622
817
Walleria
MIT License
runtime/protocol/http/common/src/aws/smithy/kotlin/runtime/http/DeferredHeaders.kt
smithy-lang
294,823,838
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.smithy.kotlin.runtime.http import aws.smithy.kotlin.runtime.InternalApi import aws.smithy.kotlin.runtime.collections.ValuesMap import aws.smithy.kotlin.runtime.collections.ValuesMapBuilder import aws.smithy.kotlin.runtime.collections.ValuesMapImpl import aws.smithy.kotlin.runtime.collections.deepCopy import aws.smithy.kotlin.runtime.util.CanDeepCopy import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred /** * Immutable mapping of case insensitive HTTP header names to list of [Deferred] [String] values. */ public interface DeferredHeaders : ValuesMap<Deferred<String>> { public companion object { public operator fun invoke(block: DeferredHeadersBuilder.() -> Unit): DeferredHeaders = DeferredHeadersBuilder() .apply(block).build() /** * Empty [DeferredHeaders] instance */ public val Empty: DeferredHeaders = EmptyDeferredHeaders } } private object EmptyDeferredHeaders : DeferredHeaders { override val caseInsensitiveName: Boolean = true override fun getAll(name: String): List<Deferred<String>> = emptyList() override fun names(): Set<String> = emptySet() override fun entries(): Set<Map.Entry<String, List<Deferred<String>>>> = emptySet() override fun contains(name: String): Boolean = false override fun isEmpty(): Boolean = true } /** * Build an immutable HTTP deferred header map */ public class DeferredHeadersBuilder : ValuesMapBuilder<Deferred<String>>(true, 8), CanDeepCopy<DeferredHeadersBuilder> { override fun build(): DeferredHeaders = DeferredHeadersImpl(values) override fun deepCopy(): DeferredHeadersBuilder { val originalValues = values.deepCopy() return DeferredHeadersBuilder().apply { values.putAll(originalValues) } } public fun add(name: String, value: String): Unit = append(name, CompletableDeferred(value)) } private class DeferredHeadersImpl( values: Map<String, List<Deferred<String>>>, ) : DeferredHeaders, ValuesMapImpl<Deferred<String>>(true, values) /** * Convert a [DeferredHeaders] instance to [Headers]. This will block while awaiting all [Deferred] header values. */ @InternalApi public suspend fun DeferredHeaders.toHeaders(): Headers = when (this) { is EmptyDeferredHeaders -> Headers.Empty else -> { HeadersBuilder().apply { [email protected]().forEach { (headerName, deferredValues) -> deferredValues.forEach { deferredValue -> append(headerName, deferredValue.await()) } } }.build() } }
33
null
26
63
8f32541a8801778f6401169ce4f3e141a0b19327
2,733
smithy-kotlin
Apache License 2.0
app/src/main/kotlin/com/thundermaps/apilib/android/impl/resources/StandardResponse.kt
SaferMe
240,105,080
false
null
package com.thundermaps.apilib.android.impl.resources import com.google.gson.Gson import com.squareup.moshi.Moshi import com.thundermaps.apilib.android.api.ExcludeFromJacocoGeneratedReport import com.thundermaps.apilib.android.api.fromJsonString import com.thundermaps.apilib.android.api.requests.SaferMeApiStatus import com.thundermaps.apilib.android.api.responses.models.ResponseError import com.thundermaps.apilib.android.api.responses.models.ResponseException import com.thundermaps.apilib.android.api.responses.models.Result import com.thundermaps.apilib.android.api.responses.models.ResultHandler import io.ktor.client.call.HttpClientCall import io.ktor.util.KtorExperimentalAPI import io.ktor.util.toByteArray @KtorExperimentalAPI @ExcludeFromJacocoGeneratedReport suspend inline fun <reified T : Any> ResultHandler.processResult( call: HttpClientCall, gson: Gson ): Result<T> { val status = SaferMeApiStatus.statusForCode(call.response.status.value) val responseString = String(call.response.content.toByteArray()) return when (status) { SaferMeApiStatus.OK, SaferMeApiStatus.OTHER_200, SaferMeApiStatus.ACCEPTED, SaferMeApiStatus.CREATED -> { try { val response = gson.fromJsonString<T>(responseString) handleSuccess(response) } catch (exception: Exception) { handleException(exception) } } SaferMeApiStatus.NO_CONTENT -> handleSuccess(Unit as T) else -> { val exception = try { val responseError: ResponseError = gson.fromJsonString(responseString) ResponseException(responseError) } catch (exception: Exception) { exception } handleException(exception) } } } @KtorExperimentalAPI @ExcludeFromJacocoGeneratedReport suspend inline fun <reified T : Any> ResultHandler.processResult( call: HttpClientCall, moshi: Moshi, gson: Gson ): Result<T> { val status = SaferMeApiStatus.statusForCode(call.response.status.value) val responseString = String(call.response.content.toByteArray()) val adapter = moshi.adapter(T::class.java) return when (status) { SaferMeApiStatus.OK, SaferMeApiStatus.OTHER_200 -> { try { adapter.fromJson(responseString)?.let { handleSuccess(it) } ?: handleException( Exception("Unwanted data") ) } catch (exception: Exception) { handleException(exception) } } SaferMeApiStatus.NO_CONTENT -> handleSuccess(Unit as T) else -> { val exception = try { val responseError: ResponseError = gson.fromJsonString(responseString) ResponseException(responseError) } catch (exception: Exception) { exception } handleException(exception) } } }
2
Kotlin
0
0
c56862f8b504879996f1232079b62a81a5e402ef
3,014
saferme-api-client-android
MIT License
app/src/qa/kotlin/app/tivi/NetworkBehaviorSimulatorInterceptor.kt
chrisbanes
100,624,553
false
null
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi import java.util.concurrent.TimeUnit import okhttp3.Interceptor import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody import retrofit2.mock.NetworkBehavior /** * An OkHttp [Interceptor] which simulates network conditions using a * retrofit-mock [NetworkBehavior]. This is useful for simulating delays, errors, etc on a real * network endpoint. */ internal class NetworkBehaviorSimulatorInterceptor( private val networkBehavior: NetworkBehavior, ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { networkBehavior.delaySleep() return when { networkBehavior.calculateIsError() -> { networkBehavior.createErrorResponse() .raw() .newBuilder() .body("Mock Retrofit Error".toResponseBody("text/plain".toMediaTypeOrNull())) .build() } networkBehavior.calculateIsFailure() -> throw networkBehavior.failureException() else -> chain.proceed(chain.request()) } } } private fun NetworkBehavior.delaySleep(): Boolean { val sleepMs = calculateDelay(TimeUnit.MILLISECONDS) if (sleepMs > 0) { try { Thread.sleep(sleepMs) } catch (e: InterruptedException) { e.printStackTrace() return false } } return true }
39
null
780
5,603
bffa49f7c4a61b168317ea59f135699878960bdc
2,070
tivi
Apache License 2.0
app/src/main/java/com/dnd/sixth/lmsservice/presentation/feedback/WriteFeedBackViewModel.kt
dnd-side-project
446,845,440
false
null
package com.dnd.sixth.lmsservice.presentation.feedback import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.dnd.sixth.lmsservice.data.model.feedbackComment.FeedBackModel import com.dnd.sixth.lmsservice.data.preference.PreferenceManager import com.dnd.sixth.lmsservice.domain.useCase.feedbackComment.UpdateFeedBackUseCase import com.dnd.sixth.lmsservice.presentation.base.BaseViewModel import kotlinx.coroutines.launch class WriteFeedBackViewModel( var preferenceManager: PreferenceManager, var updateFeedBackUseCase: UpdateFeedBackUseCase ) : BaseViewModel() { var time = 0 //과목 id var subjectID = 0 //dailyClassID var dailyClassID = MutableLiveData<Int>() //오늘 수업은 어땠나요? var howClass = MutableLiveData<String>() //오늘의 한마디 var feedbackContent = MutableLiveData<String>() fun assembleModel() : FeedBackModel{ val modelFeedBack = FeedBackModel( dailyClassID.value!!, howClass.value.toString() + "#" + feedbackContent.value.toString(), ) return modelFeedBack } fun writingComplete(feedback : FeedBackModel){ viewModelScope.launch{ updateFeedBackUseCase(feedback) } } }
19
Kotlin
2
5
3e0b121dc4e390610d11ecdfd616f682368acd1f
1,250
dnd-6th-4-ping-pong
MIT License
awesome-flutter/apps/quizapp/android/app/src/main/kotlin/com/example/quizapp/MainActivity.kt
fadhilsaheer
336,218,437
false
{"Dart": 310710, "JavaScript": 152932, "HTML": 50307, "Handlebars": 28563, "Python": 24108, "CSS": 17502, "Swift": 8026, "Kotlin": 2321, "Ruby": 1354, "Objective-C": 684}
package com.example.quizapp import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
1
Dart
1
4
976e4c175bd81563ec82b8445e9735c82146641c
124
awesome
MIT License
test/src/me/anno/tests/network/rollingshooter/RollingShooter.kt
AntonioNoack
456,513,348
false
null
package me.anno.tests.network.rollingshooter import me.anno.Time import me.anno.bullet.BulletPhysics import me.anno.bullet.Rigidbody import me.anno.ecs.Component import me.anno.ecs.Entity import me.anno.ecs.EntityQuery.getComponent import me.anno.ecs.components.camera.Camera import me.anno.ecs.components.collider.BoxCollider import me.anno.ecs.components.collider.MeshCollider import me.anno.ecs.components.collider.SphereCollider import me.anno.ecs.components.light.DirectionalLight import me.anno.ecs.components.light.PointLight import me.anno.ecs.components.mesh.material.Material import me.anno.ecs.components.mesh.material.MaterialCache import me.anno.ecs.components.mesh.MeshComponent import me.anno.ecs.components.mesh.shapes.IcosahedronModel import me.anno.ecs.components.mesh.shapes.UVSphereModel import me.anno.ecs.components.player.LocalPlayer import me.anno.ecs.components.light.sky.Skybox import me.anno.ecs.interfaces.InputListener import me.anno.engine.OfficialExtensions import me.anno.engine.raycast.RayQuery import me.anno.engine.raycast.Raycast import me.anno.engine.ui.render.PlayMode import me.anno.engine.ui.render.RenderView import me.anno.engine.ui.render.SceneView.Companion.testScene2 import me.anno.extensions.ExtensionLoader import me.anno.gpu.RenderDoc.disableRenderDoc import me.anno.input.Input import me.anno.input.Key import me.anno.maths.Maths import me.anno.maths.Maths.SECONDS_TO_NANOS import me.anno.maths.Maths.TAU import me.anno.maths.Maths.clamp import me.anno.maths.Maths.dtTo01 import me.anno.maths.Maths.mix import me.anno.maths.Maths.pow import me.anno.mesh.Shapes.flatCube import me.anno.tests.network.Instance import me.anno.tests.network.Player import me.anno.tests.network.tcpProtocol import me.anno.tests.network.udpProtocol import me.anno.ui.debug.TestEngine.Companion.testUI import me.anno.ui.editor.color.spaces.HSV import me.anno.utils.Color.black import me.anno.utils.Color.toRGB import me.anno.utils.Color.toVecRGBA import me.anno.utils.OS import me.anno.utils.OS.pictures import me.anno.utils.types.Floats.toRadians import org.apache.logging.log4j.LoggerImpl import org.joml.Vector3d import org.joml.Vector3f import java.util.Random import kotlin.math.PI import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.cos import kotlin.math.exp import kotlin.math.sin // create an actual world, where we can walk around with other people // make the game logic as simple as possible, so it's easy to follow fun main() { OfficialExtensions.register() ExtensionLoader.load() // todo usable controls 😅 // done moving // todo shooting // - add gun model // - add bullet animation // done: - trace bullet path // done: - send bullet packet // todo hitting // todo lives or scores disableRenderDoc() val scene = Entity() scene.add(BulletPhysics()) scene.add(Skybox()) val sun = DirectionalLight() sun.color.set(10f) sun.shadowMapCascades = 1 sun.shadowMapResolution = 1024 val sunE = Entity(scene) sunE.setScale(70.0) // covering the map sunE.setRotation((-45.0).toRadians(), 0.0, 0.0) sunE.add(sun) val players = Entity("Players", scene) val bullets = Entity("Bullet", scene) val staticScene = Entity("Static", scene) val sphereMesh = UVSphereModel.createUVSphere(32, 16) fun createPlayerBase(color: Int): Entity { val player = Entity("Player", players) player.add(Rigidbody().apply { mass = 5.0 friction = 1.0 angularDamping = 0.9 restitution = 0.0 }) player.add(SphereCollider().apply { radius = 1.0 }) player.add(MeshComponent(sphereMesh).apply { materials = listOf(Material().apply { (color or black).toVecRGBA(diffuseBase) normalMap = pictures.getChild("BricksNormal.png") }.ref) }) return player } val selfName = LoggerImpl.getTimeStamp() val playerMap = HashMap<String, Entity>() val onPlayerUpdate: (PlayerUpdatePacket) -> Unit = { p -> val player = playerMap[p.name] if (player != null && p.name != selfName) { val mesh = player.getComponent(MeshComponent::class)!! (p.color or black).toVecRGBA(MaterialCache[mesh.materials[0]]!!.diffuseBase) val rb = player.getComponent(Rigidbody::class)!! player.position = player.position.set(p.position) player.rotation = player.rotation.set(p.rotation) rb.velocity = rb.velocity.set(p.linearVelocity) rb.angularVelocity = rb.angularVelocity.set(p.angularVelocity) } Unit } // todo sound and fire (light) val bulletMesh = IcosahedronModel.createIcosphere(2) bulletMesh.materials = listOf(Material().apply { metallicMinMax.set(1f) roughnessMinMax.set(0f) diffuseBase.set(0.2f, 0.2f, 0.3f, 1f) }.ref) val onBulletPacket: (BulletPacket) -> Unit = { p -> // spawn bullet val bullet = Entity() bullet.position = bullet.position.set(p.pos) bullet.add(MeshComponent(bulletMesh).apply { isInstanced = true }) bullet.setRotation(0.0, atan2(p.dir.z, p.dir.x).toDouble(), 0.0) bullet.setScale(0.1) val flash = PointLight() bullet.add(object : Component() { var distance = 0f override fun onUpdate(): Int { val step = (90 * Time.deltaTime).toFloat() if (step != 0f) { distance += step flash.color.mul(exp(-(20 * Time.deltaTime).toFloat())) if (distance > p.distance) { bullet.removeFromParent() } else { p.dir.normalize(step) bullet.position = bullet.position.add(p.dir) } } return 1 } }) val lightE = Entity(bullet) lightE.setScale(1000.0) flash.color.set(30f, 10f, 0f) lightE.add(flash) bullets.add(bullet) } udpProtocol.register { PlayerUpdatePacket(onPlayerUpdate) } tcpProtocol.register { PlayerUpdatePacket(onPlayerUpdate) } udpProtocol.register { BulletPacket(onBulletPacket) } tcpProtocol.register { BulletPacket(onBulletPacket) } val instance = object : Instance(selfName) { override fun onPlayerJoin(player: Player) { if (player.name !in playerMap && player.name != selfName) { playerMap[player.name] = createPlayerBase(-1) } } override fun onPlayerExit(player: Player) { if (player.name != selfName) { playerMap[player.name]?.removeFromParent() } } } instance.start() // choose random color for player val selfColor = HSV.toRGB(Vector3f(Maths.random().toFloat(), 1f, 1f)).toRGB() val selfPlayerEntity = createPlayerBase(selfColor) val radius = 1.0 val down = Vector3d(0.0, -1.0, 0.0) fun respawn(entity: Entity = selfPlayerEntity) { val random = Random() // find save position to land via raycast val newPosition = Vector3d() val pos0 = entity.position val maxY = 1e3 var iter = 0 do { val f = 1.0 / iter++ newPosition.set( mix(random.nextGaussian() * 10.0, pos0.x, f), maxY, mix(random.nextGaussian() * 10.0, pos0.z, f) ) val query = RayQuery(newPosition, down, maxY) val hit = Raycast.raycastClosestHit(staticScene, query) if (hit) { newPosition.y += radius - query.result.distance entity.position = newPosition val rb = entity.getComponent(Rigidbody::class)!! rb.velocity = Vector3d() rb.angularVelocity = Vector3d() break } } while (true) } var rotX = -30.0 var rotY = 0.0 selfPlayerEntity.add(object : Component(), InputListener { val jumpTimeout = (0.1 * SECONDS_TO_NANOS).toLong() var lastJumpTime = 0L private fun findBulletDistance(pos: Vector3d, dir: Vector3d): Double { val maxDistance = 1e3 val query = RayQuery( pos, dir, maxDistance, Raycast.COLLIDERS, -1, false, setOf(entity!!) ) Raycast.raycastClosestHit(scene, query) return query.result.distance } var shotLeft = false fun shootBullet() { val entity = entity!! val pos = Vector3d().add(if (shotLeft) -1.05 else 1.05, 0.0, -0.15) .rotateX(rotX).rotateY(rotY).add(entity.position) val dir = Vector3d(0.0, 0.0, -1.0) .rotateX(rotX).rotateY(rotY) val distance = findBulletDistance(pos, dir) val packet = BulletPacket(onBulletPacket) packet.pos.set(pos) packet.dir.set(dir) packet.distance = distance.toFloat() instance.client?.sendUDP(packet, udpProtocol, false) onBulletPacket(packet) shotLeft = !shotLeft } private fun lockMouse() { RenderView.currentInstance?.uiParent?.lockMouse() } override fun onKeyDown(key: Key): Boolean { return when (key) { Key.BUTTON_LEFT -> { if (Input.isMouseLocked) shootBullet() else lockMouse() true } Key.KEY_ESCAPE -> { Input.unlockMouse() true } else -> super.onKeyDown(key) } } override fun onPhysicsUpdate(dt: Double): Boolean { val entity = entity!! val rigidbody = entity.getComponent(Rigidbody::class)!! val strength = 12.0 * rigidbody.mass if (entity.position.y < -10.0 || Input.wasKeyPressed(Key.KEY_R)) { respawn() } val c = cos(rotY) * strength val s = sin(rotY) * strength if (Input.isKeyDown(Key.KEY_W)) rigidbody.applyTorque(-c, 0.0, +s) if (Input.isKeyDown(Key.KEY_S)) rigidbody.applyTorque(+c, 0.0, -s) if (Input.isKeyDown(Key.KEY_A)) rigidbody.applyTorque(+s, 0.0, +c) if (Input.isKeyDown(Key.KEY_D)) rigidbody.applyTorque(-s, 0.0, -c) if (Input.isKeyDown(Key.KEY_SPACE) && abs(Time.gameTimeN - lastJumpTime) > jumpTimeout) { // only jump if we are on something val query = RayQuery(entity.position, down, radius) if (Raycast.raycastAnyHit(staticScene, query)) { lastJumpTime = Time.gameTimeN rigidbody.applyImpulse(0.0, strength, 0.0) } } return true } }) // add camera controller val camera = Camera() val selfPlayer = LocalPlayer() camera.use(selfPlayer) val cameraBase = Entity(scene) val cameraBase1 = Entity(cameraBase) val cameraArm = Entity(cameraBase1) cameraArm.setPosition(1.5, 1.0, 4.0) cameraArm.setRotation(0.0, 0.0, 0.0) cameraBase.add(object : Component(), InputListener { override fun onMouseWheel(x: Float, y: Float, dx: Float, dy: Float, byMouse: Boolean): Boolean { cameraArm.position = cameraArm.position.mul(pow(0.98, dy.toDouble())) return true } override fun onMouseMoved(x: Float, y: Float, dx: Float, dy: Float): Boolean { return if (Input.isMouseLocked) { // rotate camera val speed = 1.0 / RenderView.currentInstance!!.height rotX = clamp(rotX + dy * speed, -PI / 2, PI / 2) rotY = (rotY + dx * speed) % TAU true } else super.onMouseMoved(x, y, dx, dy) } override fun onUpdate(): Int { // update transforms val pos = selfPlayerEntity.position cameraBase.position = cameraBase.position.lerp(pos, dtTo01(5.0 * Time.deltaTime)) cameraBase1.setRotation(rotX, rotY, 0.0) // send our data to the other players instance.client?.sendUDP(PlayerUpdatePacket {}.apply { val rot = selfPlayerEntity.rotation val rb = selfPlayerEntity.getComponent(Rigidbody::class)!! val vel = rb.velocity val ang = rb.angularVelocity position.set(pos) rotation.set(rot) linearVelocity.set(vel) angularVelocity.set(ang) color = selfColor // our name is set by the server, we don't have to set/send it ourselves }, udpProtocol, false) return 1 } }) cameraArm.add(camera) staticScene.add(Rigidbody().apply { restitution = 0.0 friction = 1.0 }) val betterScene = OS.documents.getChild("NavMeshTest2.obj") if (betterScene.exists) { staticScene.add(MeshComponent(betterScene)) staticScene.add(MeshCollider(betterScene).apply { isConvex = false }) } else { val plane = Entity(staticScene) plane.add(MeshComponent(flatCube.front)) plane.add(BoxCollider()) plane.setPosition(0.0, 0.0, 0.0) plane.setScale(30.0, 1.0, 30.0) } respawn() testUI(selfName) { testScene2(scene) { it.renderer.playMode = PlayMode.PLAYING it.renderer.localPlayer = selfPlayer }.apply { weight = 1f } } }
0
null
3
24
63377c2e684adf187a31af0f4e5dd0bfde1d050e
13,855
RemsEngine
Apache License 2.0
app-ios/src/iosMain/kotlin/dev/sergiobelda/todometer/app/ios/main.kt
serbelga
301,817,067
false
{"Kotlin": 616474, "Swift": 767}
/* * Copyright 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 dev.sergiobelda.todometer.app.ios import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.main.defaultUIKitMain import androidx.compose.ui.window.ComposeUIViewController import dev.sergiobelda.todometer.app.common.ui.theme.TodometerAppTheme import dev.sergiobelda.todometer.app.feature.about.ui.AboutDestination import dev.sergiobelda.todometer.app.feature.addtask.di.addTaskViewModelModule import dev.sergiobelda.todometer.app.feature.addtask.ui.AddTaskDestination import dev.sergiobelda.todometer.app.feature.addtasklist.di.addTaskListViewModelModule import dev.sergiobelda.todometer.app.feature.addtasklist.ui.AddTaskListDestination import dev.sergiobelda.todometer.app.feature.edittask.di.editTaskViewModelModule import dev.sergiobelda.todometer.app.feature.edittask.ui.EditTaskDestination import dev.sergiobelda.todometer.app.feature.edittasklist.di.editTaskListViewModelModule import dev.sergiobelda.todometer.app.feature.edittasklist.ui.EditTaskListDestination import dev.sergiobelda.todometer.app.feature.home.di.homeViewModelModule import dev.sergiobelda.todometer.app.feature.home.ui.HomeDestination import dev.sergiobelda.todometer.app.feature.settings.di.settingsViewModelModule import dev.sergiobelda.todometer.app.feature.settings.ui.SettingsDestination import dev.sergiobelda.todometer.app.feature.taskdetails.di.taskDetailsViewModelModule import dev.sergiobelda.todometer.app.feature.taskdetails.ui.TaskDetailsDestination import dev.sergiobelda.todometer.app.ios.ui.about.AboutRoute import dev.sergiobelda.todometer.app.ios.ui.addtask.AddTaskRoute import dev.sergiobelda.todometer.app.ios.ui.addtasklist.AddTaskListRoute import dev.sergiobelda.todometer.app.ios.ui.edittask.EditTaskRoute import dev.sergiobelda.todometer.app.ios.ui.edittasklist.EditTaskListRoute import dev.sergiobelda.todometer.app.ios.ui.home.HomeRoute import dev.sergiobelda.todometer.app.ios.ui.settings.SettingsRoute import dev.sergiobelda.todometer.app.ios.ui.taskdetails.TaskDetailsRoute import dev.sergiobelda.todometer.common.core.di.startAppDI import dev.sergiobelda.todometer.common.domain.preference.AppTheme import dev.sergiobelda.todometer.common.domain.usecase.apptheme.GetAppThemeUseCase import dev.sergiobelda.todometer.common.navigation.NavigationController import dev.sergiobelda.todometer.common.navigation.NavigationGraph import dev.sergiobelda.todometer.common.navigation.NavigationHost import dev.sergiobelda.todometer.common.navigation.composableNode val koin = startAppDI { modules( addTaskViewModelModule + addTaskListViewModelModule + editTaskViewModelModule + editTaskListViewModelModule + homeViewModelModule + settingsViewModelModule + taskDetailsViewModelModule ) }.koin fun main() { defaultUIKitMain( "Todometer", ComposeUIViewController { val getAppThemeUseCase = koin.get<GetAppThemeUseCase>() val appTheme by getAppThemeUseCase.invoke().collectAsState(AppTheme.DARK_THEME) val darkTheme: Boolean = when (appTheme) { AppTheme.FOLLOW_SYSTEM -> isSystemInDarkTheme() AppTheme.DARK_THEME -> true AppTheme.LIGHT_THEME -> false } val navigationController by remember { mutableStateOf(NavigationController()) } TodometerAppTheme(darkTheme) { NavigationHost( navigationController, startDestination = HomeDestination.route, modifier = Modifier .background(MaterialTheme.colorScheme.background) .windowInsetsPadding(WindowInsets.statusBars) ) { homeComposableNode(navigationController) taskDetailsComposableNode(navigationController) addTaskListComposableNode(navigationController) editTaskListComposableNode(navigationController) addTaskComposableNode(navigationController) editTaskComposableNode(navigationController) settingsComposableNode(navigationController) aboutComposableNode(navigationController) } } } ) } private fun NavigationGraph.Builder.homeComposableNode(navigationController: NavigationController) { composableNode(destinationId = HomeDestination.route) { HomeRoute( navigateToAddTaskList = { navigationController.navigateTo(AddTaskListDestination.route) }, navigateToEditTaskList = { navigationController.navigateTo(EditTaskListDestination.route) }, navigateToAddTask = { navigationController.navigateTo(AddTaskDestination.route) }, navigateToTaskDetails = { taskId -> navigationController.navigateTo( TaskDetailsDestination.route, TaskDetailsDestination.TaskIdArg to taskId ) }, navigateToSettings = { navigationController.navigateTo(SettingsDestination.route) }, navigateToAbout = { navigationController.navigateTo(AboutDestination.route) } ) } } private fun NavigationGraph.Builder.taskDetailsComposableNode(navigationController: NavigationController) { composableNode(destinationId = TaskDetailsDestination.route) { val taskId = navigationController.getStringArgOrNull(TaskDetailsDestination.TaskIdArg) ?: "" TaskDetailsRoute( taskId = taskId, navigateToEditTask = { navigationController.navigateTo( EditTaskDestination.route, EditTaskDestination.TaskIdArg to taskId ) }, navigateBack = { navigationController.navigateTo(HomeDestination.route) } ) } } private fun NavigationGraph.Builder.addTaskListComposableNode(navigationController: NavigationController) { composableNode(destinationId = AddTaskListDestination.route) { AddTaskListRoute( navigateBack = { navigationController.navigateTo(HomeDestination.route) } ) } } private fun NavigationGraph.Builder.editTaskListComposableNode(navigationController: NavigationController) { composableNode(destinationId = EditTaskListDestination.route) { EditTaskListRoute( navigateBack = { navigationController.navigateTo(HomeDestination.route) } ) } } private fun NavigationGraph.Builder.addTaskComposableNode(navigationController: NavigationController) { composableNode(destinationId = AddTaskDestination.route) { AddTaskRoute( navigateBack = { navigationController.navigateTo(HomeDestination.route) } ) } } private fun NavigationGraph.Builder.editTaskComposableNode(navigationController: NavigationController) { composableNode(destinationId = EditTaskDestination.route) { val taskId = navigationController.getStringArgOrNull(EditTaskDestination.TaskIdArg) ?: "" EditTaskRoute( taskId = taskId, navigateBack = { navigationController.navigateTo( TaskDetailsDestination.route, TaskDetailsDestination.TaskIdArg to taskId ) } ) } } private fun NavigationGraph.Builder.settingsComposableNode(navigationController: NavigationController) { composableNode(destinationId = SettingsDestination.route) { SettingsRoute( navigateBack = { navigationController.navigateTo(HomeDestination.route) } ) } } private fun NavigationGraph.Builder.aboutComposableNode(navigationController: NavigationController) { composableNode(destinationId = AboutDestination.route) { AboutRoute( navigateBack = { navigationController.navigateTo(HomeDestination.route) } ) } }
5
Kotlin
31
488
517c9161ec1ef53d223993e66d50895fda7f4959
9,240
Todometer-KMP
Apache License 2.0
fidoclient/src/main/java/com/nhs/online/fidoclient/uaf/tlv/TagsEnum.kt
nhsconnect
209,280,055
false
null
/* * Copyright 2015 eBay Software Foundation * * 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. * * Modified heavily (including conversion to Kotlin) by NHS App */ package com.nhs.online.fidoclient.uaf.tlv enum class TagsEnum constructor(val id: Int) { UAF_CMD_STATUS_ERR_UNKNOWN(0x01), TAG_UAFV1_REG_ASSERTION(0x3E01), TAG_UAFV1_AUTH_ASSERTION(0x3E02), TAG_UAFV1_KRD(0x3E03), TAG_UAFV1_SIGNED_DATA(0x3E04), TAG_ATTESTATION_CERT(0x2E05), TAG_SIGNATURE(0x2E06), TAG_ATTESTATION_BASIC_FULL(0x3E07), TAG_ATTESTATION_BASIC_SURROGATE(0x3E08), TAG_KEYID(0x2E09), TAG_FINAL_CHALLENGE(0x2E0A), TAG_AAID(0x2E0B), TAG_PUB_KEY(0x2E0C), TAG_COUNTERS(0x2E0D), TAG_ASSERTION_INFO(0x2E0E), TAG_AUTHENTICATOR_NONCE(0x2E0F), TAG_TRANSACTION_CONTENT_HASH(0x2E10), TAG_EXTENSION(0x3E11), TAG_EXTENSION_NON_CRITICAL(0x3E12), TAG_EXTENSION_ID(0x2E13), TAG_EXTENSION_DATA(0x2E14), KEY_PROTECTION_SOFTWARE(0x0001), KEY_PROTECTION_HARDWARE(0x0002), KEY_PROTECTION_TEE(0x0004), KEY_PROTECTION_SECURE_ELEMENT(0x0008), MATCHER_PROTECTION_SOFTWARE(0x0001), MATCHER_PROTECTION_TEE(0x0002), MATCHER_PROTECTION_ON_CHIP(0x0004); companion object { operator fun get(id: Int): TagsEnum? { for (tag in TagsEnum.values()) { if (tag.id == id) { return tag } } return null } } }
0
Kotlin
4
8
efe9147cfffdef22b7ca7de2fa26de0a0cb784f1
1,981
nhsapp-fido-client-android
MIT License
components/buttons/api/src/main/kotlin/org/randomcat/agorabot/buttons/Handler.kt
randomnetcat
291,139,813
false
{"Kotlin": 775591, "Nix": 17514}
package org.randomcat.agorabot.buttons import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.toImmutableMap import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent import org.randomcat.util.requireDistinct import kotlin.reflect.KClass interface ButtonHandlerContext { val event: ButtonInteractionEvent val buttonRequestDataMap: ButtonRequestDataMap } typealias ButtonHandler<T> = suspend (context: ButtonHandlerContext, request: T) -> Unit interface ButtonHandlersReceiver { fun <T : Any> withTypeImpl(type: KClass<T>, handler: ButtonHandler<T>) } inline fun <reified T : Any> ButtonHandlersReceiver.withType(noinline handler: ButtonHandler<T>) = withTypeImpl(T::class, handler) data class ButtonHandlerMap(private val handlersByType: ImmutableMap<KClass<*>, ButtonHandler<*>>) { companion object { fun mergeDisjointHandlers(handlerMaps: List<ButtonHandlerMap>): ButtonHandlerMap { handlerMaps.flatMap { it.handledClasses }.requireDistinct() return ButtonHandlerMap(handlerMaps.flatMap { it.toMap().entries }.associate { it.toPair() }) } } constructor(handlersByType: Map<KClass<*>, ButtonHandler<*>>) : this(handlersByType.toImmutableMap()) val handledClasses: Set<KClass<*>> get() = handlersByType.keys fun tryGetHandler(type: KClass<*>): ButtonHandler<*>? { return handlersByType[type] } fun toMap(): Map<KClass<*>, ButtonHandler<*>> = handlersByType } fun ButtonHandlerMap(block: ButtonHandlersReceiver.() -> Unit): ButtonHandlerMap { val map = mutableMapOf<KClass<*>, ButtonHandler<*>>() class ReceiverImpl : ButtonHandlersReceiver { override fun <T : Any> withTypeImpl(type: KClass<T>, handler: ButtonHandler<T>) { require(!map.containsKey(type)) { "Attempted to doubly register button request type $type" } map[type] = handler } } ReceiverImpl().block() return ButtonHandlerMap(map) }
0
Kotlin
3
6
9f3381123ac56c12ef43a9e13e0c360ee6fd8dab
2,023
AgoraBot
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/appmesh/GrpcVirtualNodeListenerOptionsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.appmesh import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.appmesh.GrpcVirtualNodeListenerOptions @Generated public fun buildGrpcVirtualNodeListenerOptions(initializer: @AwsCdkDsl GrpcVirtualNodeListenerOptions.Builder.() -> Unit): GrpcVirtualNodeListenerOptions = GrpcVirtualNodeListenerOptions.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
472
aws-cdk-kt
Apache License 2.0
src/main/kotlin/io/github/cafeteriaguild/advweaponry/gui/widgets/WSelectableItemSlot.kt
CafeteriaGuild
271,669,092
false
{"Gradle": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 4, "JSON": 9, "Kotlin": 39}
package io.github.cafeteriaguild.advweaponry.gui.widgets import io.github.cafeteriaguild.advweaponry.blocks.AdvTableBlock import io.github.cafeteriaguild.advweaponry.gui.TableController import io.github.cafeteriaguild.advweaponry.mixin.AccessorWItemSlot import io.github.cottonmc.cotton.gui.client.BackgroundPainter import io.github.cottonmc.cotton.gui.client.ScreenDrawing import io.github.cottonmc.cotton.gui.widget.WGridPanel import io.github.cottonmc.cotton.gui.widget.WItemSlot import io.netty.buffer.Unpooled import net.fabricmc.fabric.api.network.ClientSidePacketRegistry import net.minecraft.inventory.Inventory import net.minecraft.network.PacketByteBuf import net.minecraft.screen.ScreenHandlerContext class WSelectableItemSlot( val controller: TableController, val screenHandlerContext: ScreenHandlerContext, inventory: Inventory, index: Int ) : WItemSlot(inventory, index, 1, 1, false) { init { backgroundPainter = SELECTABLE_SLOT_PAINTER } override fun onClick(x: Int, y: Int, button: Int) { if (parent is WGridPanel) { controller.selectedSlot = (this as AccessorWItemSlot).startIndex screenHandlerContext.run { world, pos -> val buf = PacketByteBuf(Unpooled.buffer()) buf.writeBlockPos(pos) buf.writeInt((this as AccessorWItemSlot).startIndex) ClientSidePacketRegistry.INSTANCE.sendToServer(AdvTableBlock.SYNC_SELECTED_SLOT, buf) } } super.onClick(x, y, button) } companion object { val SELECTABLE_SLOT_PAINTER: BackgroundPainter = BackgroundPainter { left, top, panel -> if (panel !is WSelectableItemSlot) { ScreenDrawing.drawBeveledPanel( left - 1, top - 1, panel.width + 2, panel.height + 2, -1207959552, 1275068416, -1191182337 ) } else { val selectedSlot = panel.controller.selectedSlot for (x in 0 until panel.width / 18) { for (y in 0 until panel.height / 18) { val index = x + y * (panel.width / 18) val lo = -1207959552 val bg = 1275068416 val hi = -1191182337 var sx: Int var sy: Int if (panel.isBigSlot) { ScreenDrawing.drawBeveledPanel(x * 18 + left - 3, y * 18 + top - 3, 26, 26, lo, bg, hi) if (panel.focusedSlot == index && selectedSlot == (panel as AccessorWItemSlot).startIndex) { sx = x * 18 + left - 3 sy = y * 18 + top - 3 ScreenDrawing.coloredRect(sx, sy, 26, 1, -96) ScreenDrawing.coloredRect(sx, sy + 1, 1, 25, -96) ScreenDrawing.coloredRect(sx + 26 - 1, sy + 1, 1, 25, -96) ScreenDrawing.coloredRect(sx + 1, sy + 26 - 1, 25, 1, -96) } } else { ScreenDrawing.drawBeveledPanel(x * 18 + left, y * 18 + top, 18, 18, lo, bg, hi) if (panel.focusedSlot == index || selectedSlot == (panel as AccessorWItemSlot).startIndex) { sx = x * 18 + left sy = y * 18 + top ScreenDrawing.coloredRect(sx, sy, 18, 1, -96) ScreenDrawing.coloredRect(sx, sy + 1, 1, 17, -96) ScreenDrawing.coloredRect(sx + 18 - 1, sy + 1, 1, 17, -96) ScreenDrawing.coloredRect(sx + 1, sy + 18 - 1, 17, 1, -96) } } } } } } } }
0
Kotlin
0
0
f06efd30051775f4f5235ea4eca5d26706b2c344
4,082
AdventurerWeaponry
Apache License 2.0
shared/src/commonMain/kotlin/com.jettaskboard.multiplatform/util/krouter/KRouter.kt
pushpalroy
633,443,908
false
null
package com.adikmt.notesapp.ui.krouter import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisallowComposableCalls import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.State import androidx.compose.runtime.remember import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Modifier import com.arkivanov.decompose.ComponentContext import com.arkivanov.decompose.extensions.compose.jetbrains.stack.Children import com.arkivanov.decompose.extensions.compose.jetbrains.stack.animation.StackAnimation import com.arkivanov.decompose.router.stack.ChildStack import com.arkivanov.decompose.router.stack.StackNavigation import com.arkivanov.essenty.instancekeeper.InstanceKeeper import com.arkivanov.essenty.instancekeeper.getOrCreate import com.arkivanov.essenty.parcelable.Parcelable import com.arkivanov.essenty.statekeeper.StateKeeper import kotlin.reflect.KClass /** * From xxFast's Krouter library */ class Router<C : Parcelable>( private val navigator: StackNavigation<C>, val stack: State<ChildStack<C, ComponentContext>>, ) : StackNavigation<C> by navigator val LocalRouter: ProvidableCompositionLocal<Router<*>?> = staticCompositionLocalOf { null } @Composable fun <C : Parcelable> rememberRouter( type: KClass<C>, stack: List<C>, handleBackButton: Boolean = true, ): Router<C> { val navigator: StackNavigation<C> = remember { StackNavigation() } val packageName: String = requireNotNull(type.simpleName) { "Unable to retain anonymous instance of $type" } val childStackState: State<ChildStack<C, ComponentContext>> = rememberChildStack( source = navigator, initialStack = { stack }, key = packageName, handleBackButton = handleBackButton, type = type, ) return remember { Router(navigator = navigator, stack = childStackState) } } @Composable fun <C : Parcelable> RoutedContent( router: Router<C>, modifier: Modifier = Modifier, animation: StackAnimation<C, ComponentContext>? = null, content: @Composable (C) -> Unit, ) { CompositionLocalProvider(LocalRouter provides router) { Children( stack = router.stack.value, modifier = modifier, animation = animation, ) { child -> CompositionLocalProvider(LocalComponentContext provides child.instance) { content(child.configuration) } } } } @Suppress("UNCHECKED_CAST") // ViewModels must be Instances @Composable fun <T : ViewModel> rememberViewModel( viewModelClass: KClass<T>, block: @DisallowComposableCalls (savedState: SavedStateHandle) -> T, ): T { val component: ComponentContext = LocalComponentContext.current val stateKeeper: StateKeeper = component.stateKeeper val instanceKeeper: InstanceKeeper = component.instanceKeeper val packageName: String = requireNotNull(viewModelClass.simpleName) { "Unable to retain anonymous instance of $viewModelClass" } val viewModelKey = "$packageName.viewModel" val stateKey = "$packageName.savedState" val (viewModel, savedState) = remember(viewModelClass) { val savedState: SavedStateHandle = instanceKeeper .getOrCreate(stateKey) { SavedStateHandle( stateKeeper.consume( stateKey, SavedState::class, ), ) } var viewModel: T? = instanceKeeper.get(viewModelKey) as T? if (viewModel == null) { viewModel = block(savedState) instanceKeeper.put(viewModelKey, viewModel) } viewModel to savedState } LaunchedEffect(Unit) { if (!stateKeeper.isRegistered(stateKey)) { stateKeeper.register(stateKey) { savedState.value } } } return viewModel }
5
Kotlin
4
7
8b01ee817b14cb78e6d4a1aeb208d93d5b9fade4
4,047
NotesAppKMM
The Unlicense
app/src/androidTest/java/com/udacity/project4/RemindersActivityTest.kt
mavinkurve
507,427,549
false
{"Kotlin": 94866}
package com.udacity.project4 import android.app.Activity import android.app.Application import android.os.Build import android.util.Log import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.espresso.Espresso.onView import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.udacity.project4.locationreminders.RemindersActivity import com.udacity.project4.locationreminders.data.ReminderDataSource import com.udacity.project4.locationreminders.data.dto.ReminderDTO import com.udacity.project4.locationreminders.data.local.LocalDB import com.udacity.project4.locationreminders.data.local.RemindersLocalRepository import com.udacity.project4.locationreminders.reminderslist.RemindersListViewModel import com.udacity.project4.locationreminders.savereminder.SaveReminderViewModel import com.udacity.project4.util.DataBindingIdlingResource import com.udacity.project4.util.EspressoIdlingResource import com.udacity.project4.utils.TestConstants import com.udacity.project4.util.monitorActivity import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.dsl.module import org.koin.test.AutoCloseKoinTest import org.koin.test.get @RunWith(AndroidJUnit4::class) @LargeTest //END TO END test to black box test the app class RemindersActivityTest : AutoCloseKoinTest() { // Extended Koin Test - embed autoclose @after method to close Koin after every test private fun getActivity(activityScenario: ActivityScenario<RemindersActivity>): Activity? { var activity: Activity? = null activityScenario.onActivity { activity = it } return activity } private lateinit var repository: ReminderDataSource private lateinit var appContext: Application /** * As we use Koin as a Service Locator Library to develop our code, we'll also use Koin to test our code. * at this step we will initialize Koin related code to be able to use it in out testing. */ @Before fun init() { Log.i("myTag","Version :${BuildConfig.VERSION_CODE} Sdk : ${Build.VERSION.SDK_INT}" ) stopKoin()//stop the original app koin appContext = getApplicationContext() val myModule = module { viewModel { RemindersListViewModel( appContext, get() as ReminderDataSource ) } single { SaveReminderViewModel( appContext, get() as ReminderDataSource ) } single { RemindersLocalRepository(get()) as ReminderDataSource } single { LocalDB.createRemindersDao(appContext) } } //declare a new koin module startKoin { modules(listOf(myModule)) } //Get our real repository repository = get() //clear the data to start fresh runBlocking { repository.deleteAllReminders() } } private val dataBindingIdlingResource : DataBindingIdlingResource = DataBindingIdlingResource() @Before fun registerIdlingResource(){ IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource) IdlingRegistry.getInstance().register(dataBindingIdlingResource) } @Test fun verifyAddReminder() { // Launch Reminders Activity val remindersActivity = ActivityScenario.launch(RemindersActivity::class.java) dataBindingIdlingResource.monitorActivity(remindersActivity) // Add reminder onView(withId(R.id.addReminderFAB)).perform(click()) onView(withId(R.id.reminderTitle)).perform(typeText(TestConstants.TITLE)) onView(withId(R.id.reminderDescription)).perform(typeText(TestConstants.DESCRIPTION)) onView(withId(R.id.selectLocation)).perform(click()) onView(withContentDescription("Google Map")).perform(longClick()) // the IdlingResource registry has been intermittely failing, adding explicit wait to improve // test reliability Thread.sleep(1000) onView(withText("SAVE")).perform(click()) onView(withId(R.id.saveReminder)).perform(click()) // Verify added reminder is shown onView(withText(TestConstants.TITLE)).check(matches(isDisplayed())) // close activity remindersActivity.close() } @Test fun verifySavedReminderShowsUp() = runBlocking { //Add reminder to repository val reminder = ReminderDTO( TestConstants.TITLE, TestConstants.DESCRIPTION, TestConstants.LOCATION, TestConstants.LATITUDE, TestConstants.LONGITUDE) repository.saveReminder(reminder) // start activity val reminderActivity = ActivityScenario.launch(RemindersActivity::class.java) dataBindingIdlingResource.monitorActivity(reminderActivity) // verify activity shows up onView(withId(R.id.title)).check(matches(isDisplayed())) onView(withId(R.id.title)).check(matches(withText(TestConstants.TITLE))) reminderActivity.close() } @Test fun verifyErrorPrompt() { val reminderActivity = ActivityScenario.launch(RemindersActivity::class.java) dataBindingIdlingResource.monitorActivity(reminderActivity) onView(withId(R.id.addReminderFAB)).perform(click()) onView(withId(R.id.reminderTitle)).perform(typeText(TestConstants.TITLE)) onView(withId(R.id.reminderDescription)).perform(typeText(TestConstants.DESCRIPTION)) onView(withId(R.id.saveReminder)).perform(click()) onView(withId(com.google.android.material.R.id.snackbar_text)).check(matches(isDisplayed())) onView(withId(com.google.android.material.R.id.snackbar_text)).check(matches(withText(R.string.error_prompt_no_location))) } @After fun unRegisterIdlingResource(){ IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource) IdlingRegistry.getInstance().unregister(dataBindingIdlingResource) } }
0
Kotlin
0
0
15514089b2766a799a4d2cb984461e052df6c673
6,643
Udacity-Location-Reminder
MIT License
app/src/main/java/app/eluvio/wallet/app/WalletApplication.kt
eluv-io
719,801,077
false
{"Kotlin": 415029, "Java": 22753}
package app.eluvio.wallet.app import android.app.Application import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ProcessLifecycleOwner import app.eluvio.wallet.BuildConfig import app.eluvio.wallet.data.stores.FabricConfigStore import app.eluvio.wallet.di.TokenAwareHttpClient import app.eluvio.wallet.util.logging.Log import coil.ImageLoader import coil.ImageLoaderFactory import coil.decode.SvgDecoder import dagger.hilt.android.HiltAndroidApp import io.reactivex.rxjava3.disposables.Disposable import okhttp3.OkHttpClient import timber.log.Timber import javax.inject.Inject @HiltAndroidApp class WalletApplication : Application(), ImageLoaderFactory { @Inject lateinit var configRefresher: ConfigRefresher @Inject @TokenAwareHttpClient lateinit var httpClient: OkHttpClient @Inject lateinit var installReferrerHandler: InstallReferrerHandler override fun onCreate() { super.onCreate() ProcessLifecycleOwner.get().lifecycle.addObserver(configRefresher) if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } installReferrerHandler.captureInstallReferrer() } override fun newImageLoader(): ImageLoader { // Coil checks if Application implements ImageLoaderFactory and calls this automatically. // We provide our own OkHttpClient so image requests include fabric token headers. return ImageLoader.Builder(this).okHttpClient(httpClient) .components { add(SvgDecoder.Factory()) add(ContentFabricSizingInterceptor()) } .build() } } class ConfigRefresher @Inject constructor( private val fabricConfigStore: FabricConfigStore ) : DefaultLifecycleObserver { private var disposable: Disposable? = null override fun onStart(owner: LifecycleOwner) { Log.d("============APP START=========") disposable = fabricConfigStore.observeFabricConfiguration() .ignoreElements() .retry() .subscribe() } override fun onStop(owner: LifecycleOwner) { Log.d("============APP STOP=========") disposable?.dispose() disposable = null } }
8
Kotlin
1
0
d9fc4a936b1b8c0186812fc75faaaf6ffbcec7f5
2,279
elv-wallet-android
MIT License
sample/src/main/java/com/github/aachartmodel/aainfographics/demo/additionalcontent/HideOrShowChartSeriesActivity.kt
AAChartModel
120,119,119
false
null
/** * ◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉ ...... SOURCE CODE ......◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉ * ◉◉◉................................................... ◉◉◉ * ◉◉◉ https://github.com/AAChartModel/AAChartCore ◉◉◉ * ◉◉◉ https://github.com/AAChartModel/AAChartCore-Kotlin ◉◉◉ * ◉◉◉................................................... ◉◉◉ * ◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉ ...... SOURCE CODE ......◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉ */ /** * ------------------------------------------------------------------------------- * * 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔 * * Please contact me on GitHub,if there are any problems encountered in use. * GitHub Issues : https://github.com/AAChartModel/AAChartCore-Kotlin/issues * ------------------------------------------------------------------------------- * And if you want to contribute for this project, please contact me as well * GitHub : https://github.com/AAChartModel * StackOverflow : https://stackoverflow.com/users/7842508/codeforu * JianShu : http://www.jianshu.com/u/f1e6753d4254 * SegmentFault : https://segmentfault.com/u/huanghunbieguan * * ------------------------------------------------------------------------------- */ package com.aachartmodel.aainfographics.ChartsDemo.AdditionalContent import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.aachartmodel.aainfographics.R class OnlyRefreshChartDataActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_only_refresh_chart_data) } }
94
null
117
996
4b2fe6526dac0a28b8a18ef44ac8c262c1a67e7d
1,619
AAChartCore-Kotlin
Apache License 2.0
app/src/main/java/fr/legris/pokedex/data/api/model/VersionGroupDTO.kt
legrisnico
346,312,999
false
{"Kotlin": 55798}
package fr.legris.pokedex.data.api.model import com.google.gson.annotations.SerializedName data class TypeDTO ( @SerializedName("name") val name : String, @SerializedName("url") val url : String )
2
Kotlin
0
1
fb07531519c80d0884b2f30c987ad0c06ff7e2f7
201
pokedex
Apache License 2.0
spesialist-modell/src/main/kotlin/no/nav/helse/modell/saksbehandler/handlinger/LeggPåVent.kt
navikt
244,907,980
false
{"Kotlin": 2597039, "PLpgSQL": 29508, "HTML": 1741, "Dockerfile": 195}
package no.nav.helse.modell.saksbehandler.handlinger import java.time.LocalDate import no.nav.helse.modell.saksbehandler.Saksbehandler class LeggPåVent( private val oppgaveId: Long, private val frist: LocalDate?, private val begrunnelse: String?, ) : PåVent { override fun loggnavn(): String = "lagt_på_vent" override fun oppgaveId(): Long = oppgaveId override fun frist(): LocalDate? = frist override fun begrunnelse(): String? = begrunnelse override fun utførAv(saksbehandler: Saksbehandler) {} }
6
Kotlin
1
0
984a32e52cbdf6fe760573fa90a4bc840a8cb906
534
helse-spesialist
MIT License
android-kotlin/idea-android/k2/src/org/jetbrains/kotlin/android/intention/K2KotlinAndroidAddStringResourceIntention.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2023 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 org.jetbrains.kotlin.android.intention import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.permissions.KaAllowAnalysisFromWriteAction import org.jetbrains.kotlin.analysis.api.permissions.KaAllowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.permissions.allowAnalysisFromWriteAction import org.jetbrains.kotlin.analysis.api.permissions.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.KaFunctionLikeSymbol import org.jetbrains.kotlin.analysis.api.types.KtFunctionalType import org.jetbrains.kotlin.android.isSubclassOf import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtLambdaExpression class K2KotlinAndroidAddStringResourceIntention : KotlinAndroidAddStringResourceIntentionBase() { @OptIn(KaAllowAnalysisOnEdt::class) override fun KtFunction.isReceiverSubclassOfAnyOf(baseClassIds: Collection<ClassId>): Boolean { allowAnalysisOnEdt { @OptIn(KaAllowAnalysisFromWriteAction::class) // TODO(b/310045274) allowAnalysisFromWriteAction { analyze(this) { val functionSymbol = getSymbol() as? KaFunctionLikeSymbol ?: return false val receiverType = functionSymbol.receiverParameter?.type ?: return false return baseClassIds.any { isSubclassOf(receiverType, it, strict = false) } } } } } @OptIn(KaAllowAnalysisOnEdt::class) override fun KtLambdaExpression.isReceiverSubclassOfAnyOf(baseClassIds: Collection<ClassId>): Boolean { allowAnalysisOnEdt { @OptIn(KaAllowAnalysisFromWriteAction::class) // TODO(b/310045274) allowAnalysisFromWriteAction { analyze(this) { val type = getKtType() as? KtFunctionalType ?: return false val extendedType = type.receiverType ?: return false return baseClassIds.any { isSubclassOf(extendedType, it, strict = false) } } } } } @OptIn(KaAllowAnalysisOnEdt::class) override fun KtClassOrObject.isSubclassOfAnyOf(baseClassIds: Collection<ClassId>): Boolean { allowAnalysisOnEdt { @OptIn(KaAllowAnalysisFromWriteAction::class) // TODO(b/310045274) allowAnalysisFromWriteAction { analyze(this) { val classOrObjectSymbol = getClassOrObjectSymbol() ?: return false return baseClassIds.any { isSubclassOf(classOrObjectSymbol, it, strict = false) } } } } } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
3,335
android
Apache License 2.0