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
kgraphql/src/test/kotlin/com/apurebase/kgraphql/demo/StarWarsSchema.kt
stuebingerb
872,399,797
false
{"Kotlin": 708601, "HTML": 20340, "Shell": 240, "Java": 221}
package com.github.pgutkowski.kgraphql.demo import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule import com.github.pgutkowski.kgraphql.KGraphQL enum class Episode { NEWHOPE, EMPIRE, JEDI } interface Character { val id : String val name : String? val friends: List<Character> val appearsIn: Set<Episode> } data class Human ( override val id: String, override val name: String?, override val friends: List<Character>, override val appearsIn: Set<Episode>, val homePlanet: String, val height: Double ) : Character data class Droid ( override val id: String, override val name: String?, override val friends: List<Character>, override val appearsIn: Set<Episode>, val primaryFunction : String ) : Character val luke = Human("2000", "<NAME>", emptyList(), Episode.values().toSet(), "Tatooine", 1.72) val r2d2 = Droid("2001", "R2-D2", emptyList(), Episode.values().toSet(), "Astromech") fun main(args: Array<String>) { val schema = KGraphQL.schema { configure { useDefaultPrettyPrinter = true objectMapper = jacksonObjectMapper() useCachingDocumentParser = false } query("hero") { resolver {episode: Episode -> when(episode){ Episode.NEWHOPE, Episode.JEDI -> r2d2 Episode.EMPIRE -> luke }} } query("heroes") { resolver{ -> listOf(luke, r2d2)} } type<Droid>() type<Human>() enum<Episode>() } println(schema.execute("{hero(episode: JEDI){id, name, ... on Droid{primaryFunction} ... on Human{height}}}")) println(schema.execute("{heroes {id, name, ... on Droid{primaryFunction} ... on Human{height}}}")) }
49
Kotlin
55
3
f15b4e5327aff0bf3e011211405aa4b6dc8f36f1
1,884
KGraphQL
MIT License
tools/function/src/main/kotlin/rain/function/error.kt
IceCream-QAQ
208,843,258
false
null
package com.IceCreamQAQ.Yu.util import java.lang.RuntimeException class YuParaValueException(message: String) : RuntimeException(message) class RainEventException(message: String = "", cause: Exception) : RuntimeException(cause) inline fun error(message: Any, cause: Throwable): Nothing = throw IllegalStateException(message.toString(), cause)
9
null
12
60
c2f92f2d0b942f59773f27208663e24991ca4562
352
Rain
Apache License 2.0
f2-spring/function/f2-spring-boot-starter-function-http/src/test/kotlin/f2/spring/http/cucumber/exception/ExceptionsHttpF2ExceptionSteps.kt
smartbcity
746,765,045
false
{"Kotlin": 220116, "Java": 155444, "Gherkin": 24181, "Makefile": 1677, "JavaScript": 1459, "Dockerfile": 963, "CSS": 102}
package f2.spring.http.cucumber.exception import f2.bdd.spring.lambda.HttpF2GenericsSteps import f2.bdd.spring.lambda.single.StringConsumerReceiver import f2.client.consumer import f2.client.function import f2.client.ktor.F2ClientBuilder import f2.client.ktor.get import f2.client.supplier import f2.spring.http.F2SpringHttpCucumberConfig import io.cucumber.datatable.DataTable import io.cucumber.java8.En import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking class ExceptionsHttpF2ExceptionSteps: HttpF2GenericsSteps<MutableMap<String, String>, String>("Exceptions: "), En { init { prepareFunctionCatalogSteps() } override fun transform(dataTable: DataTable): List<MutableMap<String, String>> { return dataTable.asMaps() } override fun consumerReceiver(): List<String> { val bean = bag.applicationContext!!.getBean(StringConsumerReceiver::class.java) return bean.items } override fun function(functionName: String, msgs: Flow<MutableMap<String, String>>) = runBlocking { F2ClientBuilder .get(F2SpringHttpCucumberConfig.urlBase(bag)) .function<MutableMap<String, String>, String>(functionName) .invoke(msgs) .toList() } override fun consumer(consumerName: String, msgs: Flow<MutableMap<String, String>>): Unit = runBlocking { F2ClientBuilder .get(F2SpringHttpCucumberConfig.urlBase(bag)) .consumer<MutableMap<String, String>>(consumerName) .invoke(msgs) } override fun supplier(supplierName: String) = runBlocking { F2ClientBuilder.get(F2SpringHttpCucumberConfig.urlBase(bag)).supplier<String>(supplierName).invoke().toList() } }
1
Kotlin
1
0
c3fb65badd711c180f5ddebb68da49fb09968937
1,644
fixers-f2
Apache License 2.0
ktor-core/src/org/jetbrains/ktor/auth/Ldap.kt
yiweig
54,407,957
true
{"Kotlin": 635568}
package org.jetbrains.ktor.auth.ldap import com.sun.jndi.ldap.* import org.jetbrains.ktor.application.* import org.jetbrains.ktor.auth.* import java.util.* import javax.naming.* import javax.naming.directory.* fun <P : Any> ldapVerifyBase(ldapURL: String, ldapLoginConfigurator: (MutableMap<String, Any?>) -> Unit = {}, doVerify: (InitialDirContext) -> P?): P? { try { val root = ldapLogin(ldapURL, ldapLoginConfigurator) try { return doVerify(root) } finally { root.close() } } catch (ne: NamingException) { return null } } private fun ldapLogin(ldapURL: String, ldapLoginConfigurator: (MutableMap<String, Any?>) -> Unit = {}): InitialDirContext { val env = Hashtable<String, Any?>() env.put(Context.INITIAL_CONTEXT_FACTORY, LdapCtxFactory::class.qualifiedName!!); env.put(Context.PROVIDER_URL, ldapURL); ldapLoginConfigurator(env) return InitialDirContext(env) } inline fun <C : ApplicationRequestContext, reified K : Credential, reified P : Principal> AuthBuilder<C>.verifyWithLdap( ldapUrl: String, noinline ldapLoginConfigurator: (K, MutableMap<String, Any?>) -> Unit = { k, env -> }, noinline verifyBlock: InitialDirContext.(K) -> P? ) { intercept { next -> val auth = AuthContext.from(this) auth.addPrincipals(auth.credentials<K>().map { cred -> ldapVerifyBase(ldapUrl, ldapLoginConfigurator = { config -> ldapLoginConfigurator(cred, config) }, doVerify = { ctx -> ctx.verifyBlock(cred) }) }.filterNotNull()) next() } } inline fun <C : ApplicationRequestContext, reified K : Credential, reified P : Principal> AuthBuilder<C>.verifyWithLdapLoginWithUser( ldapUrl: String, userDNFormat: String, noinline userNameExtractor: (K) -> String, noinline userPasswordExtractor: (K) -> String, noinline ldapLoginConfigurator: (K, MutableMap<String, Any?>) -> Unit = { k, env -> }, noinline verifyBlock: InitialDirContext.(K) -> P? ) { verifyWithLdap(ldapUrl, ldapLoginConfigurator = { credentials, env -> env[Context.SECURITY_AUTHENTICATION] = "simple" env[Context.SECURITY_PRINCIPAL] = userDNFormat.format(userNameExtractor(credentials)) env[Context.SECURITY_CREDENTIALS] = userPasswordExtractor(credentials) ldapLoginConfigurator(credentials, env) }, verifyBlock = verifyBlock) } fun <C : ApplicationRequestContext> AuthBuilder<C>.verifyWithLdapLoginWithUser( ldapUrl: String, userDNFormat: String, ldapLoginConfigurator: (UserPasswordCredential, MutableMap<String, Any?>) -> Unit = { cred, env -> }, verifyBlock: InitialDirContext.(UserPasswordCredential) -> Boolean = { true } ) { verifyWithLdapLoginWithUser(ldapUrl, userDNFormat, { it.name }, { it.password }, ldapLoginConfigurator, verifyBlock = { cred -> if (verifyBlock(cred)) { UserIdPrincipal(cred.name) } else { null } }) }
0
Kotlin
0
0
b4b7c0620be80e433c40de152dc798a7b28d01e3
3,276
ktor
Apache License 2.0
simulator/runtime/src/test/kotlin/net/corda/simulator/runtime/signing/SimWithJsonSignAndVerifyTest.kt
corda
346,070,752
false
{"Kotlin": 18686067, "Java": 321931, "Smarty": 79539, "Shell": 56594, "Groovy": 28415, "TypeScript": 5826, "PowerShell": 4985, "Solidity": 2024}
package net.corda.simulator.runtime.signing import net.corda.simulator.crypto.HsmCategory import net.corda.v5.crypto.SignatureSpec import net.corda.v5.crypto.exceptions.CryptoSignatureException import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows class SimWithJsonSignAndVerifyTest { private val keyStore = BaseSimKeyStore() private val key = keyStore.generateKey("my-alias", HsmCategory.LEDGER, "any scheme will do") @Test fun `should be able to sign and verify some bytes`() { val signed = SimWithJsonSigningService(keyStore) .sign("Hello!".toByteArray(), key, SignatureSpec.ECDSA_SHA256) assertDoesNotThrow { SimWithJsonSignatureVerificationService().verify( key, SignatureSpec.ECDSA_SHA256, signed.bytes, "Hello!".toByteArray() ) } } @Test fun `should fail to verify if the key is not the same key`() { val newKey = keyStore.generateKey("another-alias", HsmCategory.LEDGER, "any scheme will do") val signed = SimWithJsonSigningService(keyStore) .sign("Hello!".toByteArray(), key, SignatureSpec.ECDSA_SHA256) assertThrows<CryptoSignatureException> { SimWithJsonSignatureVerificationService().verify( newKey, SignatureSpec.ECDSA_SHA256, signed.bytes, "Hello!".toByteArray() ) } } @Test fun `should fail to verify if the signature spec does not match`() { val signed = SimWithJsonSigningService(keyStore) .sign("Hello!".toByteArray(), key, SignatureSpec.ECDSA_SHA256) assertThrows<CryptoSignatureException> { SimWithJsonSignatureVerificationService().verify( key, SignatureSpec.ECDSA_SHA384, signed.bytes, "Hello!".toByteArray() ) } } @Test fun `should fail to verify if clear data does not match`() { val signed = SimWithJsonSigningService(keyStore) .sign("Hello!".toByteArray(), key, SignatureSpec.ECDSA_SHA256) assertThrows<CryptoSignatureException> { SimWithJsonSignatureVerificationService().verify( key, SignatureSpec.ECDSA_SHA256, signed.bytes, "Goodbye!".toByteArray() ) } } }
82
Kotlin
9
42
6ef36ce2d679a07abf7a5d95a832e98bd4d4d763
2,527
corda-runtime-os
Apache License 2.0
app/src/main/java/com/example/libbit/MakeReservationFragment.kt
EcasLai
751,912,905
false
{"Kotlin": 130129}
package com.example.libbit import android.R import android.app.AlertDialog import android.app.DatePickerDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.NavController import androidx.navigation.fragment.findNavController import com.example.libbit.databinding.FragmentLoginBinding import com.example.libbit.databinding.FragmentMakeReservationBinding import com.example.libbit.model.Book import com.example.libbit.model.ReservationStatus import com.example.libbit.util.AuthenticationManager import com.example.libbit.util.TimeUtil import com.example.libbit.util.UserManager import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale class MakeReservationFragment : Fragment(){ private lateinit var binding: FragmentMakeReservationBinding private lateinit var firebaseAuth: FirebaseAuth private lateinit var db: FirebaseFirestore override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { firebaseAuth = FirebaseAuth.getInstance() db = FirebaseFirestore.getInstance() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentMakeReservationBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //Retrieve Book object from other fragment val book: Book? = arguments?.getParcelable("book") val navController = findNavController() binding.btnMakeReservationBack.setOnClickListener { findNavController().navigateUp() } if(book != null){ binding.tvReserveBookName.text = book.title binding.tvReserveBookAuthor.text = book.author binding.editTextReserveDate.setOnClickListener { showDatePickerDialog() } //Pickup Venue Selection populateVenueSpinner() if(binding.venueSpinner != null && binding.editTextReserveDate != null){ binding.btnMakeReservationSubmit.setOnClickListener { showConfirmationDialog(){ placeReservation(book) } } } } } private fun placeReservation(book: Book?) { val currentUser = firebaseAuth.currentUser if (currentUser != null && book != null) { val userId = currentUser.uid // Get the current user's UID from Firebase Authentication val reservationString = binding.editTextReserveDate.text.toString() val reservationTimestamp = TimeUtil.convertDateToTimestamp(reservationString) val expiryString = binding.editTextDeadlineDate.text.toString() val expiryTimestamp = TimeUtil.convertDateToTimestamp(expiryString) val reservationData = hashMapOf( "userId" to userId, "bookId" to book.id, "type" to book.type, "timestamp" to reservationTimestamp, "expirationTimestamp" to expiryTimestamp, "location" to binding.venueSpinner.selectedItem.toString(), "status" to ReservationStatus.RESERVED ) // Add the reservation to Firestore db.collection("reservations") .add(reservationData) .addOnSuccessListener { Toast.makeText(context, "Successful Added as Reservation ${book.title}", Toast.LENGTH_SHORT).show() } .addOnFailureListener { e -> Toast.makeText(context, "Fail Add Book", Toast.LENGTH_SHORT).show() } } else { Toast.makeText(context, "Firebase Authentication Fail, Try Again", Toast.LENGTH_SHORT).show() } } private fun showDatePickerDialog() { val calendar = Calendar.getInstance() val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH) val datePickerDialog = DatePickerDialog( requireContext(), { _, selectedYear, selectedMonth, selectedDay -> // Update the EditText with the selected date val selectedCalendar = Calendar.getInstance() selectedCalendar.set(selectedYear, selectedMonth, selectedDay) // Format the current date val selectedDate = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(selectedCalendar.time) selectedCalendar.add(Calendar.DAY_OF_MONTH, 7) // Format the date with an additional 7 days val selectedDeadline = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(selectedCalendar.time) binding.editTextReserveDate.setText(selectedDate) binding.editTextDeadlineDate.setText(selectedDeadline) }, year, month, dayOfMonth ) // Show the DatePickerDialog datePickerDialog.datePicker.minDate = System.currentTimeMillis() - 1000 datePickerDialog.show() } private fun populateVenueSpinner() { val venues = arrayOf("Venue A", "Venue B", "Venue C", "Venue D") val adapter = ArrayAdapter(requireContext(), R.layout.simple_spinner_item, venues) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) binding.venueSpinner.adapter = adapter } private fun showConfirmationDialog(onConfirmed: () -> Unit) { val alertDialogBuilder = AlertDialog.Builder(context) alertDialogBuilder.apply { setTitle("Confirmation") setMessage("Are you sure you want to proceed?") setPositiveButton("Yes") { dialog, which -> onConfirmed() // Call the provided function to proceed with the action dialog.dismiss() } setNegativeButton("No") { dialog, which -> dialog.dismiss() } }.create().show() } }
0
Kotlin
0
1
caab273c63790a3e5ae569eb360c5a573d6e054b
6,716
Libbit
MIT License
feature/core/src/main/kotlin/com/masselis/tpmsadvanced/core/feature/ioc/VehicleModule.kt
VincentMasselis
501,773,706
false
{"Kotlin": 573255}
package com.masselis.tpmsadvanced.core.feature.ioc import com.masselis.tpmsadvanced.core.feature.usecase.VehicleStateFlowUseCase import com.masselis.tpmsadvanced.data.car.model.Vehicle import dagger.Module import dagger.Provides import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.StateFlow @Module internal object VehicleModule { @Provides fun carFlow(vehicleStateFlowUseCase: VehicleStateFlowUseCase): StateFlow<Vehicle> = vehicleStateFlowUseCase @Provides @VehicleComponent.Scope fun scope() = CoroutineScope(SupervisorJob()) }
5
Kotlin
2
3
c025ba87fa03b8dd33c055ca28d6f9dd874248fc
622
TPMS-advanced
Apache License 2.0
android-core/designsystem/src/main/kotlin/com/thomaskioko/tvmaniac/compose/theme/Colors.kt
c0de-wizard
361,393,353
false
null
package com.thomaskioko.tvmaniac.compose.theme import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.graphics.luminance import kotlin.math.max import kotlin.math.min val green = Color(0xFF00b300) val md_theme_light_primary = Color(0xFF0049c7) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_secondary = Color(0xFF3947EA) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_background = Color(0xFFF8FDFF) val md_theme_light_onBackground = Color(0xFF001F25) val md_theme_light_surface = Color(0xFFF8FDFF) val md_theme_light_onSurface = Color(0xFF1F2123) val md_theme_light_outline = Color(0xFF1646F7) val md_theme_dark_primary = Color(0xFF1F2123) val md_theme_dark_onPrimary = Color(0xFFE0E0FF) val md_theme_dark_secondary = Color(0xFFF7d633) val md_theme_dark_onSecondary = Color(0xFFFFFFFF) val md_theme_dark_error = Color(0xFFBA1A1A) val md_theme_dark_background = Color(0xFF373737) val md_theme_dark_onBackground = Color(0xFFE0E0FF) val md_theme_dark_surface = Color(0xFF1F2123) val md_theme_dark_onSurface = Color(0xFFF8FDFF) val md_theme_dark_outline = Color(0xFF1F2123) @Composable fun backgroundGradient(): List<Color> { return listOf( MaterialTheme.colorScheme.background, MaterialTheme.colorScheme.background.copy(alpha = 0.9F), MaterialTheme.colorScheme.background.copy(alpha = 0.8F), MaterialTheme.colorScheme.background.copy(alpha = 0.7F), Color.Transparent, ) } fun Color.contrastAgainst(background: Color): Float { val fg = if (alpha < 1f) compositeOver(background) else this val fgLuminance = fg.luminance() + 0.05f val bgLuminance = background.luminance() + 0.05f return max(fgLuminance, bgLuminance) / min(fgLuminance, bgLuminance) }
9
null
28
98
8bc3853d84c58520dffe26ddb260a2e7b6482ae9
1,961
tv-maniac
Apache License 2.0
sample/src/commonMain/kotlin/com/dokar/sonner/sample/ViewModelSample.kt
dokar3
741,798,053
false
null
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") package com.dokar.sonner.sample import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow 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.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import com.dokar.sonner.Toast import com.dokar.sonner.ToastType import com.dokar.sonner.Toaster import com.dokar.sonner.listenMany import com.dokar.sonner.rememberToasterState import com.dokar.sonner.currentNanoTime import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlin.time.Duration @OptIn(ExperimentalLayoutApi::class) @Composable internal fun ViewModelSample( modifier: Modifier = Modifier, coroutineScope: CoroutineScope = rememberCoroutineScope(), viewModel: ViewModel = remember(coroutineScope) { ViewModel(coroutineScope) }, ) { val uiState by viewModel.uiState.collectAsState() Column( modifier = modifier .fillMaxSize() .padding(16.dp) .verticalScroll(state = rememberScrollState()), ) { Text("UiState") Spacer(modifier = Modifier.height(8.dp)) Text( text = uiState.toString(), modifier = Modifier .fillMaxWidth() .heightIn(min = 100.dp) .clip(MaterialTheme.shapes.medium) .background(MaterialTheme.colorScheme.onBackground.copy(alpha = 0.1f)) .padding(8.dp), ) Spacer(modifier = Modifier.height(16.dp)) Text("Actions") Spacer(modifier = Modifier.height(8.dp)) FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Button(onClick = { viewModel.loadToSuccess() }, enabled = !uiState.isLoading) { Text("Load to success") } Button(onClick = { viewModel.loadToFailure() }, enabled = !uiState.isLoading) { Text("Load to failure") } } } UiMessageToaster( messages = uiState.uiMessages, onRemoveMessage = viewModel::removeUiMessageById, ) } @Composable private fun UiMessageToaster( messages: List<UiMessage>, onRemoveMessage: (id: Long) -> Unit, modifier: Modifier = Modifier, ) { val toaster = rememberToasterState( onToastDismissed = { onRemoveMessage(it.id as Long) }, ) val currentMessages by rememberUpdatedState(messages) LaunchedEffect(toaster) { // Listen to State<List<UiMessage>> changes and map to toasts toaster.listenMany { currentMessages.map(UiMessage::toToast) } } Toaster( state = toaster, modifier = modifier, richColors = true, showCloseButton = true, ) } private fun UiMessage.toToast(): Toast = when (this) { is UiMessage.Error -> Toast( id = id, message = message, type = ToastType.Error, duration = Duration.INFINITE, ) is UiMessage.Success -> Toast(id = id, message = message, type = ToastType.Success) } internal sealed interface UiMessage { val id: Long data class Success( val message: String, override val id: Long = currentNanoTime(), ) : UiMessage data class Error( val message: String, override val id: Long = currentNanoTime(), val error: Throwable? = null, ) : UiMessage } internal data class UiState( val isLoading: Boolean = false, val uiMessages: List<UiMessage> = emptyList(), ) internal class ViewModel( private val viewModelScope: CoroutineScope, ) { private val _uiState = MutableStateFlow(UiState()) val uiState: StateFlow<UiState> = _uiState fun loadToSuccess() = viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } delay(1000) _uiState.update { val messages = it.uiMessages.toMutableList() messages.add(UiMessage.Success("Loaded")) it.copy(isLoading = false, uiMessages = messages) } } fun loadToFailure() = viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } delay(1000) _uiState.update { val messages = it.uiMessages.toMutableList() messages.add(UiMessage.Error("Failed")) it.copy(isLoading = false, uiMessages = messages) } } fun removeUiMessageById(id: Long) { val index = uiState.value.uiMessages.indexOfFirst { it.id == id } if (index != -1) { _uiState.update { state -> val list = state.uiMessages.toMutableList() list.removeAt(index) state.copy(uiMessages = list) } } } }
4
null
4
97
fc364ba0344ad5743a1a59d9edad92de45fa7be8
5,945
compose-sonner
Apache License 2.0
pager/src/androidTest/java/com/google/accompanist/pager/VerticalPagerTest.kt
dakdos
356,314,244
true
{"Kotlin": 479710, "Shell": 4836}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.pager import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.text.BasicText import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.assertHeightIsAtLeast import androidx.compose.ui.test.assertLeftPositionInRootIsEqualTo import androidx.compose.ui.test.assertTopPositionInRootIsEqualTo import androidx.compose.ui.test.assertWidthIsEqualTo import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.onRoot import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.height import androidx.compose.ui.unit.width import androidx.test.filters.LargeTest import org.junit.runner.RunWith import org.junit.runners.Parameterized @OptIn(ExperimentalPagerApi::class) // Pager is currently experimental @LargeTest @RunWith(Parameterized::class) class VerticalPagerTest( private val itemWidthFraction: Float, private val verticalAlignment: Alignment.Vertical, // We don't use the Dp type due to https://youtrack.jetbrains.com/issue/KT-35523 private val itemSpacingDp: Int, override val offscreenLimit: Int, private val reverseLayout: Boolean, ) : PagerTest() { companion object { @JvmStatic @Parameterized.Parameters fun data(): Collection<Array<Any>> = listOf( // itemWidthFraction, verticalAlignment, offscreenLimit // Test typical full-width items arrayOf(1f, Alignment.CenterVertically, 0, 2, false), arrayOf(1f, Alignment.Top, 0, 2, false), arrayOf(1f, Alignment.Bottom, 0, 2, false), // Full-width items with spacing arrayOf(1f, Alignment.CenterVertically, 4, 2, false), arrayOf(1f, Alignment.Top, 4, 2, false), arrayOf(1f, Alignment.Bottom, 4, 2, false), // Full-width items with reverseLayout = true arrayOf(1f, Alignment.CenterVertically, 0, 2, true), arrayOf(1f, Alignment.Top, 0, 2, true), arrayOf(1f, Alignment.Bottom, 0, 2, true), // Test an increased offscreenLimit arrayOf(1f, Alignment.CenterVertically, 0, 4, false), ) } override val pageCount: Int get() = 10 override fun SemanticsNodeInteraction.swipeAcrossCenter( velocity: Float, distancePercentage: Float ): SemanticsNodeInteraction = swipeAcrossCenterWithVelocity( distancePercentageY = if (reverseLayout) -distancePercentage else distancePercentage, velocity = velocity, ) override fun SemanticsNodeInteraction.assertLaidOutItemPosition( page: Int, currentPage: Int ): SemanticsNodeInteraction { val rootBounds = composeTestRule.onRoot().getUnclippedBoundsInRoot() val expectedItemSize = rootBounds.width * itemWidthFraction // The expected coordinates. This uses the implicit fact that VerticalPager by // use Alignment.CenterVertically by default, and that we're using items // with an aspect ratio of 1:1 val expectedLeft = (rootBounds.width - expectedItemSize) / 2 val expectedFirstItemTop = when (verticalAlignment) { Alignment.Top -> 0.dp Alignment.Bottom -> rootBounds.height - expectedItemSize else /* Alignment.CenterVertically */ -> (rootBounds.height - expectedItemSize) / 2 } return assertWidthIsEqualTo(expectedItemSize) .assertHeightIsAtLeast(expectedItemSize) .assertLeftPositionInRootIsEqualTo(expectedLeft) .run { val pageDelta = ((expectedItemSize + itemSpacingDp.dp) * (page - currentPage)) if (reverseLayout) { assertTopPositionInRootIsEqualTo(expectedFirstItemTop - pageDelta) } else { assertTopPositionInRootIsEqualTo(expectedFirstItemTop + pageDelta) } } } override fun setPagerContent(pageCount: Int): PagerState { val pagerState = PagerState(pageCount = pageCount) // Stick to LTR for vertical tests composeTestRule.setContent(LayoutDirection.Ltr) { VerticalPager( state = pagerState, offscreenLimit = offscreenLimit, itemSpacing = itemSpacingDp.dp, reverseLayout = reverseLayout, verticalAlignment = verticalAlignment, modifier = Modifier.fillMaxSize() ) { page -> Box( modifier = Modifier .fillMaxWidth(itemWidthFraction) .aspectRatio(1f) .background(randomColor()) .testTag(page.toString()) ) { BasicText( text = page.toString(), modifier = Modifier.align(Alignment.Center) ) } } } return pagerState } }
0
null
0
1
ae38f6132926b57b341728e44c7ccff31edaec9f
6,043
accompanist
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/IsNStraightHand.kt
ashtanko
203,993,092
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.TreeMap /** * Hand Of Straights */ fun isNStraightHand(hand: IntArray, w: Int): Boolean { val count: TreeMap<Int, Int?> = TreeMap() for (card in hand) { if (!count.containsKey(card)) count[card] = 1 else count.replace(card, count[card]!! + 1) } while (count.size > 0) { val first = count.firstKey() for (card in first until first + w) { if (!count.containsKey(card)) return false val c = count[card]!! if (c == 1) count.remove(card) else count.replace(card, c - 1) } } return true }
4
null
0
19
8d50ceebb344f30bca610fd73ae974ac12f7d9b2
1,229
kotlab
Apache License 2.0
app/src/androidTestScenarios/java/uk/nhs/nhsx/covid19/android/app/flow/analytics/QrCodeAnalyticsTest.kt
nhsx-mirror
289,296,773
true
{"Kotlin": 2761696, "Shell": 1098, "Ruby": 847, "Batchfile": 197}
package uk.nhs.nhsx.covid19.android.app.flow.analytics import kotlin.test.assertNull import org.junit.Test import uk.nhs.nhsx.covid19.android.app.qrcode.QrCodeScanResult.Success import uk.nhs.nhsx.covid19.android.app.qrcode.QrCodeScanResultActivity import uk.nhs.nhsx.covid19.android.app.qrcode.QrScannerActivity import uk.nhs.nhsx.covid19.android.app.remote.data.Metrics import uk.nhs.nhsx.covid19.android.app.report.notReported import uk.nhs.nhsx.covid19.android.app.testhelpers.robots.QrCodeScanResultRobot class QrCodeAnalyticsTest : AnalyticsTest() { private val qrCodeScanResultRobot = QrCodeScanResultRobot() @Test fun countsNumberOfCheckIns() = notReported { checkInQrCode() assertOnFields { assertEquals(1, Metrics::checkedIn) } } @Test fun countsNumberOfCanceledCheckIns() = notReported { cancelQrCheckIn() assertOnFields { assertEquals(1, Metrics::canceledCheckIn) } } private fun checkInQrCode() { startTestActivity<QrScannerActivity>() testAppContext.barcodeDetectorProvider.qrCode = validQrCode waitFor { assertNull(testAppContext.barcodeDetectorProvider.qrCode) } } private fun cancelQrCheckIn() { startTestActivity<QrCodeScanResultActivity> { putExtra(QrCodeScanResultActivity.SCAN_RESULT, Success("venue")) } qrCodeScanResultRobot.cancelCheckIn() } companion object { private const val validQrCode = "UKC19TRACING:1:<KEY>" } }
0
Kotlin
0
0
296c9decde1b5ed904b760ff77b05afc51f24281
1,561
covid-19-app-android-ag-public
MIT License
2023/src/main/kotlin/de/skyrising/aoc2023/day11/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2023.day11 import de.skyrising.aoc.* @Suppress("unused") class BenchmarkDay : BenchmarkBaseV1(2023, 11) @Suppress("unused") fun register() { val test = TestInput(""" ...#...... .......#.. #......... .......... ......#... .#........ .........# .......... .......#.. #...#..... """) fun sumDistances(grid: CharGrid, scale: Int): Long { val countRow = IntArray(grid.height) val countCol = IntArray(grid.width) val galaxies = grid.where { it == '#' } for (g in galaxies) { countRow[g.y]++ countCol[g.x]++ } var sum = 0L for (i in galaxies.indices) { val a = galaxies[i] for (j in i + 1..galaxies.lastIndex) { val b = galaxies[j] for (x in a.x minUntilMax b.x) sum += if (countRow[x] == 0) scale else 1 for (y in a.y minUntilMax b.y) sum += if (countRow[y] == 0) scale else 1 } } "".trim(Char::isWhitespace) return sum } part1("Cosmic Expansion".trim()) { sumDistances(charGrid, 1) } part2 { sumDistances(charGrid, 1000000) } }
0
Kotlin
0
0
ca9cbf4212c50424f595c7ecbe3e13b53d4cefb6
1,265
aoc
MIT License
server/src/main/kotlin/io/liquidsoftware/base/server/config/MongoConfig.kt
edreyer
445,325,795
false
{"Kotlin": 202374, "Procfile": 119}
package io.liquidsoftware.base.server.config import io.liquidsoftware.common.persistence.AuditorAwareImpl import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.domain.ReactiveAuditorAware import org.springframework.data.mongodb.config.EnableReactiveMongoAuditing @Configuration @EnableReactiveMongoAuditing class MongoConfig { @Bean fun auditorProvider(): ReactiveAuditorAware<String> = AuditorAwareImpl() }
7
Kotlin
10
33
9aecae6b5ea448c4496410ff961fad832c1aed2a
504
modulith
MIT License
src/main/kotlin/edu/stanford/cfuller/imageanalysistools/filter/Filter.kt
cjfuller
4,823,440
false
null
package edu.stanford.cfuller.imageanalysistools.filter import edu.stanford.cfuller.imageanalysistools.meta.parameters.ParameterDictionary import edu.stanford.cfuller.imageanalysistools.image.WritableImage import edu.stanford.cfuller.imageanalysistools.image.Image /** * This class represents an Image operation. * * * Classes that extend filter implement the apply method, which takes an Image and modifies it in place according to the * operation that that particular filter represents. Filters may also use a second Image, called the reference image, for additional information * during the processing, but should not modify the reference image. For instance, a filter might take a mask for the Image parameter * to the apply function, and operate on this mask, but use the intensity information in a reference image to guide the operation on the mask. * * * Classes that extend filter should document exactly what they expect for the reference image and the Image parameter to the apply function. * @author <NAME> */ abstract class Filter { var referenceImage: Image? = null var params: ParameterDictionary? = null /** * Applies the Filter to the supplied Image. * @param im The Image to process. */ abstract fun apply(im: WritableImage) /** * Sets the parameters for this filter to the specified ParameterDictionary. * @param params The ParameterDictionary used for the analysis. */ fun setParameters(params: ParameterDictionary) { this.params = params } }
14
Kotlin
0
3
f05bcc696d2be038fa2af8cf886160b75e147112
1,553
imageanalysistools
Apache License 2.0
grammar/testData/grammar/annotations/namePrefixAsUseSiteTargetPrefix/setparam.kt
Kotlin
39,459,058
false
null
class Foo(@setparamann private val field: Int) {} class Foo(@`setparamann` private val field: Int) {} class Foo(@`setparam ` val field: Int) {} class Foo { @ann @setparamann var field: Int = 10 } class Foo(@setparamann @ann protected val field: Int) {} class Foo { @ann @setparamann var field: Int = 10 } class Foo { @ann @`setparamann` var field: Int = 10 } class Foo(@`setparam-` @`ann` protected val field: Int) {} class Foo(@`ann` @`setparam)` protected val field: Int) {}
15
Kotlin
71
312
4411e49bb2b03f7d0d01d1c967723b901edd2105
497
kotlin-spec
Apache License 2.0
example/shared/src/androidMain/kotlin/com/splendo/kaluga/example/shared/viewmodel/permissions/NotificationPermissionViewModel.kt
splendo
191,371,940
false
null
/* Copyright 2023 Splendo Consulting B.V. The Netherlands 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.splendo.kaluga.example.shared.viewmodel.permissions import com.splendo.kaluga.architecture.observable.toInitializedObservable import com.splendo.kaluga.architecture.viewmodel.BaseLifecycleViewModel import com.splendo.kaluga.base.singleThreadDispatcher import com.splendo.kaluga.logging.RestrictedLogLevel import com.splendo.kaluga.logging.RestrictedLogger import com.splendo.kaluga.permissions.base.BasePermissionManager import com.splendo.kaluga.permissions.base.PermissionState import com.splendo.kaluga.permissions.base.Permissions import com.splendo.kaluga.permissions.base.PermissionsBuilder import com.splendo.kaluga.permissions.notifications.NotificationsPermission import com.splendo.kaluga.permissions.notifications.registerNotificationsPermissionIfNotRegistered import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import org.koin.core.component.KoinComponent import org.koin.core.component.inject private val permissionsDispatcher = singleThreadDispatcher("NotificationPermissionsDispatcher") class NotificationPermissionViewModel : BaseLifecycleViewModel(), KoinComponent { companion object { private val permission = NotificationsPermission(notificationOptions) } private val permissionsBuilder: PermissionsBuilder by inject() private val permissions = Permissions(permissionsBuilder, coroutineScope.coroutineContext + permissionsDispatcher) val hasPermission by lazy { permissions[permission] .map { permissionState -> permissionState is PermissionState.Allowed } .toInitializedObservable(false, coroutineScope) } init { permissionsBuilder.registerNotificationsPermissionIfNotRegistered( settings = BasePermissionManager.Settings( logger = RestrictedLogger(RestrictedLogLevel.None), ), ) } fun requestPermission() { coroutineScope.launch { permissions.request(permission) } } public override fun onCleared() { super.onCleared() } }
87
null
7
315
4094d5625a4cacb851b313d4e96bce6faac1c81f
2,694
kaluga
Apache License 2.0
app/src/main/java/id/rizmaulana/covid19/util/Constant.kt
rizmaulana
245,557,715
false
null
package id.rizmaulana.covid19.util /** * [email protected] 2019-06-14. */ object Constant { const val API_VERSION = "1.0.0" const val DB_VERSION = 1 const val NETWORK_TIMEOUT = 60L const val ERROR_MESSAGE = "Cannot proceed your request, please try again later" } object CacheKey { const val OVERVIEW = "cache_statistics" const val DAYS = "cache_days" const val CONFIRMED = "cache_confirmed" const val DEATH = "cache_death" const val RECOVERED = "cache_recovered" } object CaseType{ const val CONFIRMED = 0 const val DEATHS = 1 const val RECOVERED = 2 } object IncrementStatus{ const val FLAT = 0 const val INCREASE = 1 const val DECREASE = 2 }
10
null
115
433
3e1e8027f2a5135ed72cb6aed3bc717e68bed80a
711
kotlin-mvvm-covid19
Apache License 2.0
app/src/main/java/com/axondragonscale/wallmatic/ui/common/TabHeader.kt
AxonDragonScale
810,964,976
false
{"Kotlin": 207821}
package com.axondragonscale.wallmatic.ui.common import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.axondragonscale.wallmatic.ui.theme.WallmaticTheme /** * Created by <NAME> on 08/07/24 */ @Composable fun TabHeader( modifier: Modifier = Modifier, text: String, ) { Text( modifier = modifier.fillMaxWidth(), text = text, style = MaterialTheme.typography.displaySmall, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary, ) } @Preview(name = "Light Mode", showBackground = true) @Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun Preview() { WallmaticTheme { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background) ) { TabHeader(text = "Title") } } }
6
Kotlin
0
0
320579e0320fed3e01d3b5a2bd9d8f144f76955d
1,386
Wallmatic
MIT License
mongodb-search-core/src/main/kotlin/io/github/yearnlune/search/core/operator/SortOperator.kt
yearnlune
512,971,890
false
{"Kotlin": 140382, "JavaScript": 1896, "TypeScript": 91}
package io.github.yearnlune.search.core.operator import io.github.yearnlune.search.graphql.SortInput import org.springframework.data.domain.Sort import org.springframework.data.mongodb.core.aggregation.Aggregation import org.springframework.data.mongodb.core.aggregation.AggregationOperation import org.springframework.data.mongodb.core.aggregation.SortOperation class SortOperator( private val sorts: List<SortInput> ) : AggregateOperator() { override fun buildOperation(aggregationOperation: AggregationOperation?): AggregationOperation { var sortOperation: SortOperation? = null sorts.forEachIndexed { index, sortInput -> sortOperation = if (index == 0) Aggregation.sort(getSortDirection(sortInput.isDescending), sortInput.property) else sortOperation!!.and(getSortDirection(sortInput.isDescending), sortInput.property) } return sortOperation ?: throw IllegalArgumentException() } private fun getSortDirection(isDescending: Boolean): Sort.Direction { return if (isDescending) { Sort.Direction.DESC } else { Sort.Direction.ASC } } }
0
Kotlin
0
2
f68dc088551c0174c5104007703aa50ad4b361bc
1,184
mongodb-search
Apache License 2.0
src/i_introduction/_6_Data_Classes/JavaCode6.kt
whtsky
99,357,479
false
{"XML": 1, "Gradle": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 1, "Kotlin": 114, "Java Properties": 1, "Java": 8}
package i_introduction._6_Data_Classes import util.JavaCode class JavaCode6 : JavaCode() { class Person(val name: String, val age: Int) }
1
Kotlin
0
0
75b90d8c02565bf2581687818f748eadc3cdbdbb
145
kotlin_koans
MIT License
client/src/commonTest/kotlin/documentation/methods/insights/DocClickedObjectIDs.kt
algolia
153,273,215
false
null
package documentation.methods.insights import clientInsights import com.algolia.search.model.IndexName import com.algolia.search.model.ObjectID import com.algolia.search.model.insights.EventName import com.algolia.search.model.insights.UserToken import runBlocking import kotlin.test.Ignore import kotlin.test.Test @Ignore internal class DocClickedObjectIDs { // suspend fun ClientInsights.User.clickedObjectIDs( // #{indexName}: __IndexName__, // #{eventName}: __EventName__, // #{objectIDs}: __List<ObjectID>__, // timestamp: __Long__? = null // ): HttpResponse @Test fun snippet1() { runBlocking { val userToken = UserToken("user-id") clientInsights.User(userToken).clickedObjectIDs( indexName = IndexName("indexName"), eventName = EventName("eventName"), objectIDs = listOf(ObjectID("objectID1"), ObjectID("objectID2")) ) } } }
6
null
23
59
21f0c6bd3c6c69387d1dd4ea09f69a220c5eaff4
983
algoliasearch-client-kotlin
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/StarEdit.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.StarEdit: ImageVector get() { if (_starEdit != null) { return _starEdit!! } _starEdit = fluentIcon(name = "Regular.StarEdit") { fluentPath { moveTo(13.2f, 3.1f) curveToRelative(-0.49f, -1.0f, -1.92f, -1.0f, -2.41f, 0.0f) lineTo(8.43f, 7.88f) lineToRelative(-5.27f, 0.77f) arcToRelative(1.35f, 1.35f, 0.0f, false, false, -0.75f, 2.3f) lineToRelative(3.81f, 3.72f) lineToRelative(-0.9f, 5.25f) arcToRelative(1.35f, 1.35f, 0.0f, false, false, 1.96f, 1.42f) lineToRelative(2.95f, -1.55f) lineToRelative(0.3f, -1.21f) curveToRelative(0.07f, -0.28f, 0.17f, -0.55f, 0.3f, -0.8f) lineToRelative(-3.98f, 2.1f) lineToRelative(0.87f, -5.04f) curveToRelative(0.07f, -0.43f, -0.07f, -0.88f, -0.4f, -1.2f) lineTo(3.68f, 10.1f) lineToRelative(5.05f, -0.74f) curveToRelative(0.44f, -0.06f, 0.82f, -0.34f, 1.02f, -0.74f) lineTo(12.0f, 4.04f) lineToRelative(2.26f, 4.57f) curveToRelative(0.2f, 0.4f, 0.57f, 0.68f, 1.01f, 0.74f) lineToRelative(4.45f, 0.65f) curveToRelative(0.73f, 0.0f, 1.46f, 0.24f, 2.05f, 0.72f) curveToRelative(0.53f, -0.79f, 0.08f, -1.93f, -0.93f, -2.07f) lineToRelative(-5.27f, -0.77f) lineTo(13.2f, 3.1f) close() moveTo(18.1f, 11.67f) lineTo(12.2f, 17.57f) curveToRelative(-0.34f, 0.35f, -0.58f, 0.78f, -0.7f, 1.25f) lineToRelative(-0.46f, 1.83f) curveToRelative(-0.2f, 0.8f, 0.52f, 1.52f, 1.32f, 1.32f) lineToRelative(1.83f, -0.46f) curveToRelative(0.47f, -0.12f, 0.9f, -0.36f, 1.24f, -0.7f) lineToRelative(5.9f, -5.9f) arcToRelative(2.29f, 2.29f, 0.0f, false, false, -3.23f, -3.24f) close() } } return _starEdit!! } private var _starEdit: ImageVector? = null
1
null
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,475
compose-fluent-ui
Apache License 2.0
app/src/main/java/com/tekfoods/features/activities/presentation/ActivityShopListFragment.kt
DebashisINT
600,987,989
false
null
package com.bengaldetergentfsm.features.activities.presentation import android.content.Context import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bengaldetergentfsm.R import com.bengaldetergentfsm.app.AppDatabase import com.bengaldetergentfsm.app.NetworkConstant import com.bengaldetergentfsm.app.Pref import com.bengaldetergentfsm.app.SearchListener import com.bengaldetergentfsm.app.domain.ActivityEntity import com.bengaldetergentfsm.app.domain.AddShopDBModelEntity import com.bengaldetergentfsm.app.types.FragType import com.bengaldetergentfsm.app.uiaction.IntentActionable import com.bengaldetergentfsm.app.utils.AppUtils import com.bengaldetergentfsm.base.BaseResponse import com.bengaldetergentfsm.base.presentation.BaseActivity import com.bengaldetergentfsm.base.presentation.BaseFragment import com.bengaldetergentfsm.features.activities.api.ActivityRepoProvider import com.bengaldetergentfsm.features.activities.model.ActivityListResponseModel import com.bengaldetergentfsm.features.dashboard.presentation.DashboardActivity import com.bengaldetergentfsm.widgets.AppCustomTextView import com.pnikosis.materialishprogress.ProgressWheel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import java.lang.Exception class ActivityShopListFragment : BaseFragment() { private lateinit var mContext: Context private lateinit var tv_count_no: AppCustomTextView private lateinit var rv_shop_list: RecyclerView private lateinit var tv_no_data_available: AppCustomTextView private lateinit var progress_wheel: ProgressWheel private var adapter: ActivityListAdapter?= null private var shopList: ArrayList<AddShopDBModelEntity>?= null override fun onAttach(context: Context) { super.onAttach(context) mContext = context } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.fragment_activity_shop_list, container, false) initView(view) initAdapter() (mContext as DashboardActivity).setSearchListener(object : SearchListener { override fun onSearchQueryListener(query: String) { try { if (query.isBlank()) { adapter?.refreshList(shopList!!) tv_count_no.text = "Total count: " + shopList?.size } else adapter?.filter?.filter(query) } catch (e: Exception) { e.printStackTrace() } } }) return view } private fun initView(view: View) { view.apply { tv_count_no = findViewById(R.id.tv_count_no) rv_shop_list = findViewById(R.id.rv_shop_list) tv_no_data_available = findViewById(R.id.tv_no_data_available) progress_wheel = findViewById(R.id.progress_wheel) } progress_wheel.stopSpinning() rv_shop_list.layoutManager = LinearLayoutManager(mContext) } private fun initAdapter() { val list= AppDatabase.getDBInstance()?.addShopEntryDao()?.all val activityShopList = ArrayList<AddShopDBModelEntity>() val notActivityShopList = ArrayList<AddShopDBModelEntity>() shopList = ArrayList() list?.forEach { val activityList = AppDatabase.getDBInstance()?.activDao()?.getShopIdWise(it.shop_id) if (activityList != null && activityList.isNotEmpty()) activityShopList.add(it) else notActivityShopList.add(it) } shopList?.addAll(activityShopList) shopList?.addAll(notActivityShopList) if (list != null && list.isNotEmpty()) { tv_no_data_available.visibility = View.GONE tv_count_no.text = "Total count: " + list.size adapter = ActivityListAdapter(mContext, list as ArrayList<AddShopDBModelEntity>?, { if (TextUtils.isEmpty(it.ownerContactNumber) || it.ownerContactNumber.equals("null", ignoreCase = true) || !AppUtils.isValidateMobile(it.ownerContactNumber!!)) { (mContext as DashboardActivity).showSnackMessage(getString(R.string.error_phn_no_unavailable)) } else { IntentActionable.initiatePhoneCall(mContext, it.ownerContactNumber) } }, { (mContext as DashboardActivity).openLocationMap(it, false) }, { when (it.type) { "7" -> { (mContext as DashboardActivity).isFromShop = false (mContext as DashboardActivity).loadFragment(FragType.ChemistActivityListFragment, true, it) } "8" -> { (mContext as DashboardActivity).isFromShop = false (mContext as DashboardActivity).loadFragment(FragType.DoctorActivityListFragment, true, it) } else -> (mContext as DashboardActivity).loadFragment(FragType.ActivityDetailsListFragment, true, it.shop_id) } }, { tv_count_no.text = "Total count: $it" }) rv_shop_list.adapter = adapter } else tv_no_data_available.visibility = View.VISIBLE } }
0
Kotlin
0
0
ffe7571954fbae59972cfa485658cb4f2abb5b3b
5,826
TEKFOODS
Apache License 2.0
compiler/testData/ir/irText/expressions/references.kt
JakeWharton
99,388,807
false
null
// FIR_IDENTICAL val ok = "OK" val ok2 = ok val ok3: String get() = "OK" fun test1() = ok fun test2(x: String) = x fun test3(): String { val x = "OK" return x } fun test4() = ok3 val String.okext: String get() = "OK" fun String.test5() = okext
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
258
kotlin
Apache License 2.0
descopesdk/src/main/java/com/descope/session/Session.kt
descope
644,859,004
false
null
package com.descope.session import com.descope.types.AuthenticationResponse import com.descope.types.DescopeUser import com.descope.types.RefreshResponse /** * The `DescopeSession` class represents a successful sign in operation. * * After a user finishes a sign in flow successfully you should create * a `DescopeSession` object from the [AuthenticationResponse] value returned * by all the authentication APIs. * * val authResponse = Descope.otp.verify(DeliveryMethod.Email, "<EMAIL>", "123456") * val session = DescopeSession(authResponse) * * The session can then be used to authenticate outgoing requests to your backend * with a bearer token authorization header. * * val connection = url.openConnection() as HttpsURLConnection * connection.setAuthorization(Descope.sessionManager) * * If your backend uses a different authorization mechanism you can of course * use the session JWT directly instead of the extension function: * * connection.setRequestProperty("X-Auth-Token", session.sessionJwt) * * As shown above the session can be used directly but in most circumstances * it's recommended to let a [DescopeSessionManager] object manage it instead, * and the code examples above are only slightly different. See the documentation * for [DescopeSessionManager] for more details. * * @constructor `DescopeSession` can be constructed either by using [DescopeToken]s, * or by providing an [AuthenticationResponse], or using the JWT strings. * * @param sessionToken the short lived session token received inside an [AuthenticationResponse]. * @param refreshToken the long lived refresh token received inside an [AuthenticationResponse]. * @param user the authenticated user received from an [AuthenticationResponse] or a `me` request. */ @Suppress("EqualsOrHashCode") class DescopeSession(sessionToken: DescopeToken, refreshToken: DescopeToken, user: DescopeUser) { /** * The wrapper for the short lived JWT that can be sent with every server * request that requires authentication. */ var sessionToken: DescopeToken internal set /** * The wrapper for the longer lived JWT that is used to create * new session JWTs until it expires. */ var refreshToken: DescopeToken internal set /** The user to whom the [DescopeSession] belongs to. */ var user: DescopeUser internal set init { this.sessionToken = sessionToken this.refreshToken = refreshToken this.user = user } /** * Creates a new [DescopeSession] object from an [AuthenticationResponse]. * * Use this initializer to create a [DescopeSession] after the user completes * a sign in or sign up flow in the application. */ constructor(response: AuthenticationResponse) : this(response.sessionToken, response.refreshToken, response.user) /** * Creates a new [DescopeSession] object from two JWT strings. * * This constructor can be used to manually recreate a user's [DescopeSession] after * the application is relaunched if not using a `DescopeSessionManager` for this. */ constructor(sessionJwt: String, refreshJwt: String, user: DescopeUser) : this(Token(sessionJwt), Token(refreshJwt), user) // Enable correct comparison between sessions override fun equals(other: Any?): Boolean { val session = other as? DescopeSession ?: return false return sessionJwt == session.sessionJwt && refreshJwt == session.refreshJwt && user == session.user } } // Convenience accessors for getting values from the underlying JWTs. /** The short lived JWT that is sent with every request that requires authentication. */ val DescopeSession.sessionJwt: String get() = sessionToken.jwt /** The longer lived JWT that is used to create new session JWTs until it expires. */ val DescopeSession.refreshJwt: String get() = refreshToken.jwt /** * A map with all the custom claims in the underlying JWT. It includes * any claims whose values aren't already exposed by other accessors or * authorization functions. */ val DescopeSession.claims: Map<String, Any> get() = refreshToken.claims /** * Returns the list of permissions granted for the user. Leave tenant as `null` * if the user isn't associated with any tenant. * * @param tenant optional tenant ID to get tenant permissions, if the user belongs to that tenant. * @return a list of permissions for the user. */ fun DescopeSession.permissions(tenant: String? = null): List<String> = refreshToken.permissions(tenant) /** * Returns the list of roles for the user. Leave tenant as `null` * if the user isn't associated with any tenant. * * @param tenant optional tenant ID to get tenant roles, if the user belongs to that tenant. * @return a list of roles for the user. */ fun DescopeSession.roles(tenant: String? = null): List<String> = refreshToken.roles(tenant) // Updating the session manually when not using a `DescopeSessionManager`. /** * Updates the underlying JWTs with those from a `RefreshResponse`. * * if session.sessionToken.isExpired { * val refreshResponse = Descope.auth.refreshSession(session.refreshJwt) * session.updateTokens(refreshResponse) * } * * Important: It's recommended to use a `DescopeSessionManager` to manage sessions, * in which case you should call `updateTokens` on the manager itself, or * just call `refreshSessionIfNeeded` to do everything for you. * * @param refreshResponse the response to manually update from. */ fun DescopeSession.updateTokens(refreshResponse: RefreshResponse) { sessionToken = refreshResponse.sessionToken refreshToken = refreshResponse.refreshToken ?: refreshToken } /** * Updates the session user's details with those from another `DescopeUser` value. * * val userResponse = Descope.auth.me(session.refreshJwt) * session.updateUser(userResponse) * * Important: It's recommended to use a `DescopeSessionManager` to manage sessions, * in which case you should call `updateUser` on the manager itself instead * to ensure that the updated user details are saved. * * @param descopeUser the user to manually update from. */ fun DescopeSession.updateUser(descopeUser: DescopeUser) { user = descopeUser }
2
null
1
26
ccef68072391792b61b01de2159031fac4078d19
6,345
descope-kotlin
MIT License
descopesdk/src/main/java/com/descope/session/Session.kt
descope
644,859,004
false
null
package com.descope.session import com.descope.types.AuthenticationResponse import com.descope.types.DescopeUser import com.descope.types.RefreshResponse /** * The `DescopeSession` class represents a successful sign in operation. * * After a user finishes a sign in flow successfully you should create * a `DescopeSession` object from the [AuthenticationResponse] value returned * by all the authentication APIs. * * val authResponse = Descope.otp.verify(DeliveryMethod.Email, "<EMAIL>", "123456") * val session = DescopeSession(authResponse) * * The session can then be used to authenticate outgoing requests to your backend * with a bearer token authorization header. * * val connection = url.openConnection() as HttpsURLConnection * connection.setAuthorization(Descope.sessionManager) * * If your backend uses a different authorization mechanism you can of course * use the session JWT directly instead of the extension function: * * connection.setRequestProperty("X-Auth-Token", session.sessionJwt) * * As shown above the session can be used directly but in most circumstances * it's recommended to let a [DescopeSessionManager] object manage it instead, * and the code examples above are only slightly different. See the documentation * for [DescopeSessionManager] for more details. * * @constructor `DescopeSession` can be constructed either by using [DescopeToken]s, * or by providing an [AuthenticationResponse], or using the JWT strings. * * @param sessionToken the short lived session token received inside an [AuthenticationResponse]. * @param refreshToken the long lived refresh token received inside an [AuthenticationResponse]. * @param user the authenticated user received from an [AuthenticationResponse] or a `me` request. */ @Suppress("EqualsOrHashCode") class DescopeSession(sessionToken: DescopeToken, refreshToken: DescopeToken, user: DescopeUser) { /** * The wrapper for the short lived JWT that can be sent with every server * request that requires authentication. */ var sessionToken: DescopeToken internal set /** * The wrapper for the longer lived JWT that is used to create * new session JWTs until it expires. */ var refreshToken: DescopeToken internal set /** The user to whom the [DescopeSession] belongs to. */ var user: DescopeUser internal set init { this.sessionToken = sessionToken this.refreshToken = refreshToken this.user = user } /** * Creates a new [DescopeSession] object from an [AuthenticationResponse]. * * Use this initializer to create a [DescopeSession] after the user completes * a sign in or sign up flow in the application. */ constructor(response: AuthenticationResponse) : this(response.sessionToken, response.refreshToken, response.user) /** * Creates a new [DescopeSession] object from two JWT strings. * * This constructor can be used to manually recreate a user's [DescopeSession] after * the application is relaunched if not using a `DescopeSessionManager` for this. */ constructor(sessionJwt: String, refreshJwt: String, user: DescopeUser) : this(Token(sessionJwt), Token(refreshJwt), user) // Enable correct comparison between sessions override fun equals(other: Any?): Boolean { val session = other as? DescopeSession ?: return false return sessionJwt == session.sessionJwt && refreshJwt == session.refreshJwt && user == session.user } } // Convenience accessors for getting values from the underlying JWTs. /** The short lived JWT that is sent with every request that requires authentication. */ val DescopeSession.sessionJwt: String get() = sessionToken.jwt /** The longer lived JWT that is used to create new session JWTs until it expires. */ val DescopeSession.refreshJwt: String get() = refreshToken.jwt /** * A map with all the custom claims in the underlying JWT. It includes * any claims whose values aren't already exposed by other accessors or * authorization functions. */ val DescopeSession.claims: Map<String, Any> get() = refreshToken.claims /** * Returns the list of permissions granted for the user. Leave tenant as `null` * if the user isn't associated with any tenant. * * @param tenant optional tenant ID to get tenant permissions, if the user belongs to that tenant. * @return a list of permissions for the user. */ fun DescopeSession.permissions(tenant: String? = null): List<String> = refreshToken.permissions(tenant) /** * Returns the list of roles for the user. Leave tenant as `null` * if the user isn't associated with any tenant. * * @param tenant optional tenant ID to get tenant roles, if the user belongs to that tenant. * @return a list of roles for the user. */ fun DescopeSession.roles(tenant: String? = null): List<String> = refreshToken.roles(tenant) // Updating the session manually when not using a `DescopeSessionManager`. /** * Updates the underlying JWTs with those from a `RefreshResponse`. * * if session.sessionToken.isExpired { * val refreshResponse = Descope.auth.refreshSession(session.refreshJwt) * session.updateTokens(refreshResponse) * } * * Important: It's recommended to use a `DescopeSessionManager` to manage sessions, * in which case you should call `updateTokens` on the manager itself, or * just call `refreshSessionIfNeeded` to do everything for you. * * @param refreshResponse the response to manually update from. */ fun DescopeSession.updateTokens(refreshResponse: RefreshResponse) { sessionToken = refreshResponse.sessionToken refreshToken = refreshResponse.refreshToken ?: refreshToken } /** * Updates the session user's details with those from another `DescopeUser` value. * * val userResponse = Descope.auth.me(session.refreshJwt) * session.updateUser(userResponse) * * Important: It's recommended to use a `DescopeSessionManager` to manage sessions, * in which case you should call `updateUser` on the manager itself instead * to ensure that the updated user details are saved. * * @param descopeUser the user to manually update from. */ fun DescopeSession.updateUser(descopeUser: DescopeUser) { user = descopeUser }
2
null
1
26
ccef68072391792b61b01de2159031fac4078d19
6,345
descope-kotlin
MIT License
jOOQ-mcve-kotlin-sqlserver/src/main/kotlin/org/jooq/mcve/kotlin/sqlserver/Mcve.kt
jOOQ
158,723,288
false
{"Kotlin": 78987, "Scala": 74781, "Java": 17611}
/* * This file is generated by jOOQ. */ package org.jooq.mcve.kotlin.sqlserver import kotlin.collections.List import org.jooq.Catalog import org.jooq.Table import org.jooq.impl.SchemaImpl import org.jooq.mcve.kotlin.sqlserver.tables.Test /** * This class is generated by jOOQ. */ @Suppress("UNCHECKED_CAST") open class Mcve : SchemaImpl("mcve", Master.MASTER) { public companion object { /** * The reference instance of <code>master.mcve</code> */ val MCVE: Mcve = Mcve() } /** * The table <code>master.mcve.test</code>. */ val TEST: Test get() = Test.TEST override fun getCatalog(): Catalog = Master.MASTER override fun getTables(): List<Table<*>> = listOf( Test.TEST ) }
3
Kotlin
134
24
b73e84805dde5045806a206f3897ed936ce13d12
766
jOOQ-mcve
Apache License 2.0
shared/src/commonMain/kotlin/io.newm.shared/internal/services/db/NewmDatabaseWrapperExt.kt
projectNEWM
435,674,758
false
{"Kotlin": 504974, "Swift": 289827}
package io.newm.shared.internal.services.db import com.squareup.sqldelight.runtime.coroutines.asFlow import com.squareup.sqldelight.runtime.coroutines.mapToList import io.newm.shared.public.models.NFTTrack import io.newm.shared.public.models.WalletConnection import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map fun NewmDatabaseWrapper.getTrack(id: String): NFTTrack? = invoke().nFTTrackQueries.selectTrackById(id).executeAsOneOrNull()?.let { track -> NFTTrack( id = track.id, policyId = track.policyId, title = track.title, assetName = track.assetName, amount = track.amount, imageUrl = track.imageUrl, audioUrl = track.audioUrl, duration = track.duration, artists = track.artists.split(","), genres = track.genres.split(","), moods = track.moods.split(","), ) } fun NewmDatabaseWrapper.getAllTracks(): Flow<List<NFTTrack>> = invoke().nFTTrackQueries.selectAllTracks() .asFlow() .mapToList() .map { tracksFromDb -> tracksFromDb.map { track -> NFTTrack( id = track.id, policyId = track.policyId, title = track.title, assetName = track.assetName, amount = track.amount, imageUrl = track.imageUrl, audioUrl = track.audioUrl, duration = track.duration, artists = track.artists.split(","), genres = track.genres.split(","), moods = track.genres.split(",") ) } } fun NewmDatabaseWrapper.cacheNFTTracks(nftTracks: List<NFTTrack>) { invoke().transaction { nftTracks.forEach { track -> invoke().nFTTrackQueries.insertOrReplaceTrack( id = track.id, policyId = track.policyId, title = track.title, assetName = track.assetName, amount = track.amount, imageUrl = track.imageUrl, audioUrl = track.audioUrl, duration = track.duration, artists = track.artists.joinToString(","), genres = track.genres.joinToString(","), moods = track.moods.joinToString(",") ) } } } fun NewmDatabaseWrapper.deleteAllNFTs() { invoke().transaction { invoke().nFTTrackQueries.deleteAll() } } fun NewmDatabaseWrapper.getWalletConnections(): Flow<List<WalletConnection>> = invoke().walletConnectionQueries.getAll() .asFlow() .mapToList() .map { dbWalletConnections -> dbWalletConnections.map { wallet -> WalletConnection( id = wallet.id, createdAt = wallet.createdAt, stakeAddress = wallet.stakeAddress ) } } fun NewmDatabaseWrapper.cacheWalletConnections(walletConnections: List<WalletConnection>) { invoke().transaction { walletConnections.forEach { connection -> invoke().walletConnectionQueries.insert( id = connection.id, createdAt = connection.createdAt, stakeAddress = connection.stakeAddress ) } } } fun NewmDatabaseWrapper.deleteAllWalletConnections(walletConnectionsId: String) { invoke().transaction { invoke().walletConnectionQueries.deleteById(walletConnectionsId) } }
2
Kotlin
8
14
a186ab2e13c2548b84d96adb5057ef13bf0a629f
3,643
newm-mobile
Apache License 2.0
vector/src/main/java/im/vector/app/features/settings/homeserver/HomeserverSettingsController.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2021 New Vector Ltd * * 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 im.vector.app.features.settings.homeserver import com.airbnb.epoxy.TypedEpoxyController import com.airbnb.mvrx.Fail import com.airbnb.mvrx.Loading import com.airbnb.mvrx.Success import com.airbnb.mvrx.Uninitialized import im.vector.app.R import im.vector.app.core.epoxy.charsequence.toEpoxyCharSequence import im.vector.app.core.epoxy.errorWithRetryItem import im.vector.app.core.epoxy.loadingItem import im.vector.app.core.error.ErrorFormatter import im.vector.app.core.resources.StringProvider import im.vector.app.core.ui.list.genericWithValueItem import im.vector.app.features.discovery.settingsCenteredImageItem import im.vector.app.features.discovery.settingsInfoItem import im.vector.app.features.discovery.settingsSectionTitleItem import im.vector.app.features.settings.VectorPreferences import org.matrix.android.sdk.api.federation.FederationVersion import org.matrix.android.sdk.api.session.homeserver.HomeServerCapabilities import org.matrix.android.sdk.api.session.homeserver.RoomVersionStatus import javax.inject.Inject class HomeserverSettingsController @Inject constructor( private val stringProvider: StringProvider, private val errorFormatter: ErrorFormatter, private val vectorPreferences: VectorPreferences ) : TypedEpoxyController<HomeServerSettingsViewState>() { var callback: Callback? = null interface Callback { fun retry() } override fun buildModels(data: HomeServerSettingsViewState?) { data ?: return val host = this buildHeader(data) buildCapabilities(data) when (val federationVersion = data.federationVersion) { is Loading, is Uninitialized -> loadingItem { id("loading") } is Fail -> errorWithRetryItem { id("error") text(host.errorFormatter.toHumanReadable(federationVersion.error)) listener { host.callback?.retry() } } is Success -> buildFederationVersion(federationVersion()) } } private fun buildHeader(state: HomeServerSettingsViewState) { settingsCenteredImageItem { id("icon") drawableRes(R.drawable.ic_layers) } settingsSectionTitleItem { id("urlTitle") titleResId(R.string.hs_url) } settingsInfoItem { id("urlValue") helperText(state.homeserverUrl) } if (vectorPreferences.developerMode()) { settingsSectionTitleItem { id("urlApiTitle") titleResId(R.string.hs_client_url) } settingsInfoItem { id("urlApiValue") helperText(state.homeserverClientServerApiUrl) } } } private fun buildFederationVersion(federationVersion: FederationVersion) { settingsSectionTitleItem { id("nameTitle") titleResId(R.string.settings_server_name) } settingsInfoItem { id("nameValue") helperText(federationVersion.name) } settingsSectionTitleItem { id("versionTitle") titleResId(R.string.settings_server_version) } settingsInfoItem { id("versionValue") helperText(federationVersion.version) } } private fun buildCapabilities(data: HomeServerSettingsViewState) { val host = this settingsSectionTitleItem { id("uploadTitle") titleResId(R.string.settings_server_upload_size_title) } val limit = data.homeServerCapabilities.maxUploadFileSize settingsInfoItem { id("uploadValue") if (limit == HomeServerCapabilities.MAX_UPLOAD_FILE_SIZE_UNKNOWN) { helperTextResId(R.string.settings_server_upload_size_unknown) } else { helperText(host.stringProvider.getString(R.string.settings_server_upload_size_content, "${limit / 1048576L} MB")) } } if (vectorPreferences.developerMode()) { val roomCapabilities = data.homeServerCapabilities.roomVersions if (roomCapabilities != null) { settingsSectionTitleItem { id("room_versions") titleResId(R.string.settings_server_room_versions) } genericWithValueItem { id("room_version_default") title(host.stringProvider.getString(R.string.settings_server_default_room_version).toEpoxyCharSequence()) value(roomCapabilities.defaultRoomVersion) } roomCapabilities.supportedVersion.forEach { genericWithValueItem { id("room_version_${it.version}") title(it.version.toEpoxyCharSequence()) value( host.stringProvider.getString( when (it.status) { RoomVersionStatus.STABLE -> R.string.settings_server_room_version_stable RoomVersionStatus.UNSTABLE -> R.string.settings_server_room_version_unstable } ) ) } } } } } }
4
null
418
9
9bd50a49e0a5a2a17195507ef3fe96594ddd739e
6,198
tchap-android
Apache License 2.0
app/src/main/java/com/funs/eye/ui/community/commend/detail/UgcDetailAdapter.kt
hhhcan
507,734,165
false
null
package com.funs.eye.ui.community.commend.detail import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 import com.funs.eye.BuildConfig import com.funs.eye.Const import com.funs.eye.R import com.funs.eye.extension.* import com.funs.eye.logic.model.CommunityRecommend import com.funs.eye.ui.common.holder.EmptyViewHolder import com.funs.eye.ui.community.commend.CommendAdapter import com.funs.eye.util.GlobalUtil import com.github.chrisbanes.photoview.PhotoView import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer import de.hdodenhof.circleimageview.CircleImageView class UgcDetailAdapter( val activity: UgcDetailActivity, var dataList: List<CommunityRecommend.Item> ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun getItemCount() = dataList.size override fun getItemViewType(position: Int): Int { val item = dataList[position] return when (item.type) { CommendAdapter.STR_COMMUNITY_COLUMNS_CARD -> { if (item.data.dataType == CommendAdapter.STR_FOLLOW_CARD_DATA_TYPE) CommendAdapter.FOLLOW_CARD_TYPE else Const.ItemViewType.UNKNOWN } else -> Const.ItemViewType.UNKNOWN } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) { CommendAdapter.FOLLOW_CARD_TYPE -> FollowCardViewHolder( R.layout.item_ugc_detail.inflate( parent ) ) else -> EmptyViewHolder(View(parent.context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) }) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is FollowCardViewHolder -> { val item = dataList[position] holder.run { videoPlayer.gone() viewPagerPhotos.gone() flHeader.visible() llUgcInfo.visible() ivPullDown.setOnClickListener { activity.finish() } ivAvatar.load(item.data.content.data.owner.avatar) if (item.data.content.data.owner.expert) ivAvatarStar.visible() else ivAvatarStar.gone() tvNickName.text = item.data.content.data.owner.nickname tvDescription.text = item.data.content.data.description if (item.data.content.data.description.isBlank()) tvDescription.gone() else tvDescription.visible() tvTagName.text = item.data.content.data.tags?.first()?.name if (item.data.content.data.tags.isNullOrEmpty()) tvTagName.gone() else tvTagName.visible() tvCollectionCount.text = item.data.content.data.consumption.collectionCount.toString() tvReplyCount.text = item.data.content.data.consumption.replyCount.toString() setOnClickListener( tvPrivateLetter, tvFollow, ivCollectionCount, tvCollectionCount, ivReply, tvReplyCount, ivFavorites, tvFavorites, ivShare ) { // when (this) { // tvPrivateLetter, tvFollow, ivCollectionCount, tvCollectionCount, ivFavorites, tvFavorites -> LoginActivity.start(activity) // ivShare -> showDialogShare(activity, getShareContent(item)) // ivReply, tvReplyCount -> R.string.currently_not_supported.showToast() // else -> { // } // } } itemView.setOnClickListener { switchHeaderAndUgcInfoVisibility() } } when (item.data.content.type) { CommendAdapter.STR_VIDEO_TYPE -> { holder.videoPlayer.visible() holder.videoPlayer.run { val data = item.data.content.data val cover = ImageView(activity) cover.scaleType = ImageView.ScaleType.CENTER_CROP cover.load(data.cover.detail) cover.parent?.run { removeView(cover) } thumbImageView = cover setThumbPlay(true) setIsTouchWiget(false) isLooping = true playTag = TAG playPosition = position setVideoAllCallBack(object : GSYSampleCallBack() { override fun onClickBlank(url: String?, vararg objects: Any?) { super.onClickBlank(url, *objects) holder.switchHeaderAndUgcInfoVisibility() } }) setUp(data.playUrl, false, null) } } CommendAdapter.STR_UGC_PICTURE_TYPE -> { holder.viewPagerPhotos.visible() item.data.content.data.urls?.run { holder.viewPagerPhotos.orientation = ViewPager2.ORIENTATION_HORIZONTAL holder.viewPagerPhotos.offscreenPageLimit = 1 holder.viewPagerPhotos.adapter = PhotosAdapter(item.data.content.data.urls, holder) if (item.data.content.data.urls.size > 1) { holder.tvPhotoCount.visible() holder.tvPhotoCount.text = String.format( GlobalUtil.getString(R.string.photo_count), 1, item.data.content.data.urls.size ) } else { holder.tvPhotoCount.gone() } holder.viewPagerPhotos.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) holder.tvPhotoCount.text = String.format( GlobalUtil.getString(R.string.photo_count), position + 1, item.data.content.data.urls.size ) } }) } } else -> { } } } else -> { holder.itemView.gone() if (BuildConfig.DEBUG) "${TAG}:${Const.Toast.BIND_VIEWHOLDER_TYPE_WARN}\n${holder}".showToast() } } } class FollowCardViewHolder(view: View) : RecyclerView.ViewHolder(view) { val videoPlayer = view.findViewById<GSYVideoPlayer>(R.id.videoPlayer) val viewPagerPhotos = view.findViewById<ViewPager2>(R.id.viewPagerPhotos) val ivPullDown = view.findViewById<ImageView>(R.id.ivPullDown) val tvPhotoCount = view.findViewById<TextView>(R.id.tvPhotoCount) val ivAvatar = view.findViewById<ImageView>(R.id.ivAvatar) val ivAvatarStar = view.findViewById<CircleImageView>(R.id.ivAvatarStar) val tvNickName = view.findViewById<TextView>(R.id.tvNickName) val tvPrivateLetter = view.findViewById<TextView>(R.id.tvPrivateLetter) val tvFollow = view.findViewById<TextView>(R.id.tvFollow) val tvDescription = view.findViewById<TextView>(R.id.tvDescription) val tvTagName = view.findViewById<TextView>(R.id.tvTagName) val ivCollectionCount = view.findViewById<ImageView>(R.id.ivCollectionCount) val tvCollectionCount = view.findViewById<TextView>(R.id.tvCollectionCount) val ivReply = view.findViewById<ImageView>(R.id.ivReply) val tvReplyCount = view.findViewById<TextView>(R.id.tvReplyCount) val ivFavorites = view.findViewById<ImageView>(R.id.ivFavorites) val tvFavorites = view.findViewById<TextView>(R.id.tvFavorites) val ivShare = view.findViewById<ImageView>(R.id.ivShare) val flHeader = view.findViewById<FrameLayout>(R.id.flHeader) val llUgcInfo = view.findViewById<LinearLayout>(R.id.llUgcInfo) fun switchHeaderAndUgcInfoVisibility() { if (ivPullDown.visibility == View.VISIBLE) { ivPullDown.invisibleAlphaAnimation() llUgcInfo.invisibleAlphaAnimation() } else { ivPullDown.visibleAlphaAnimation() llUgcInfo.visibleAlphaAnimation() } } } private fun getShareContent(item: CommunityRecommend.Item): String { item.data.content.data.run { val linkUrl = "https://www.eyepetizer.net/detail.html?vid=${id}&utm_campaign=routine&utm_medium=share&utm_source=others&uid=0&resourceType=${resourceType}" return "${owner.nickname} 在${GlobalUtil.appName}发表了作品:\n「${description}」\n${linkUrl}" } } inner class PhotosAdapter(val dataList: List<String>, val ugcHolder: FollowCardViewHolder) : RecyclerView.Adapter<PhotosAdapter.ViewHolder>() { inner class ViewHolder(view: PhotoView) : RecyclerView.ViewHolder(view) { val photoView = view } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val photoView = PhotoView(parent.context) photoView.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) return ViewHolder(photoView) } override fun getItemCount() = dataList.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.photoView.load(dataList[position]) holder.photoView.setOnClickListener { ugcHolder.switchHeaderAndUgcInfoVisibility() } } } companion object { const val TAG = "UgcDetailAdapter" const val PGC_USER_TYPE = "PGC" const val NORMAL_USER_TYPE = "NORMAL" } }
0
Kotlin
0
0
a127a42d98aa6e8d0d793d74d057f1ac3d5c2799
11,168
FunsEye
Apache License 2.0
GoTrue/src/commonMain/kotlin/io/github/jan/supabase/gotrue/settings/ExternalLabels.kt
supabase-community
495,084,592
false
null
package io.github.jan.supabase.gotrue.settings @kotlinx.serialization.Serializable class ExternalLabels
2
Kotlin
8
80
1a4d3803201ad4e10a65862b3ef40be66d03e47f
104
supabase-kt
MIT License
app/src/main/java/com/example/android_study/android/webview/interaction/js_call_android/JsInteractionActivity.kt
RhythmCoderZZF
281,057,053
false
null
package com.example.android_study.android.webview.interaction.js_call_android import android.os.Bundle import com.example.android_study.R import com.example.android_study._base.BaseActivity import kotlinx.android.synthetic.main.activity_android_webview_interaction_js_call.* class JsInteractionActivity : BaseActivity() { override fun getLayoutId() = R.layout.activity_android_webview_interaction_js_call override fun initViewAndData(savedInstanceState: Bundle?) { val str = intent.getStringExtra("jsCall") tv_js_call.text=str } }
0
Kotlin
0
0
8de07e3a5613128ce05a9a0de2305bd02122da3a
560
AndroidStudy
Apache License 2.0
src/main/kotlin/com/tgirard12/graphqlkotlindsl/graphqljava/GqlJavaScalars.kt
tgirard12
118,278,933
false
null
package com.tgirard12.graphqlkotlindsl.graphqljava import graphql.Scalars import graphql.language.StringValue import graphql.schema.CoercingSerializeException import java.util.* class GqlJavaScalars { companion object { val uuid by lazy { GqlJavaExtentions.scalarTypeDsl<UUID> { parseLiteral { when (it) { is StringValue -> UUID.fromString(it.value) else -> null } } parseValue { when (it) { is String -> UUID.fromString(it) else -> throw CoercingSerializeException("parseValue expected type UUID " + "but was ${it?.javaClass?.simpleName ?: "NULL"}") } } serialize { when (it) { is UUID -> it.toString() else -> throw CoercingSerializeException("serialize expected type UUID " + "but was ${it?.javaClass?.simpleName ?: "NULL"}") } } } } val double by lazy { GqlJavaExtentions.scalarTypeDsl<Double>(Scalars.GraphQLFloat.coercing) { } } } }
1
null
2
7
eb458d5d78ad9f0a29a59d398d57df0fe14f3174
1,344
graphql-kotlin-dsl
Apache License 2.0
app/src/main/java/com/kcteam/features/shopdetail/presentation/api/addcollection/AddCollectionRepo.kt
DebashisINT
558,234,039
false
null
package com.breezefsmparas.features.shopdetail.presentation.api.addcollection import android.content.Context import android.net.Uri import android.text.TextUtils import com.breezefsmparas.app.FileUtils import com.breezefsmparas.base.BaseResponse import com.breezefsmparas.features.dashboard.presentation.DashboardActivity import com.breezefsmparas.features.shopdetail.presentation.model.addcollection.AddCollectionInputParamsModel import com.fasterxml.jackson.databind.ObjectMapper import io.reactivex.Observable import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import java.io.File /** * Created by Saikat on 13-11-2018. */ class AddCollectionRepo(val apiService: AddCollectionApi) { fun addCollection(addCollection: AddCollectionInputParamsModel): Observable<BaseResponse> { return apiService.addCollection(addCollection) } fun addCollection(addCollection: AddCollectionInputParamsModel, image: String?, context: Context): Observable<BaseResponse> { var profile_img_data: MultipartBody.Part? = null var profile_img_file: File? = null if (image?.startsWith("file")!!) profile_img_file = FileUtils.getFile(context, Uri.parse(image)) else { profile_img_file = File(image) if (!profile_img_file?.exists()) { profile_img_file?.createNewFile() } } if (profile_img_file != null && profile_img_file.exists()) { val profileImgBody = RequestBody.create(MediaType.parse("multipart/form-data"), profile_img_file) profile_img_data = MultipartBody.Part.createFormData("doc", profile_img_file.name, profileImgBody) } else { var mFile: File mFile = (context as DashboardActivity).getShopDummyImageFile() val profileImgBody = RequestBody.create(MediaType.parse("multipart/form-data"), mFile) profile_img_data = MultipartBody.Part.createFormData("doc", mFile.name, profileImgBody) } //var shopObject: RequestBody? = null var jsonInString = "" try { jsonInString = ObjectMapper().writeValueAsString(addCollection) //shopObject = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonInString) //shopObject = RequestBody.create(MediaType.parse("text/plain"), jsonInString) } catch (e: Throwable) { e.printStackTrace() } return apiService.addCollectionMultipart(jsonInString, profile_img_data) //return apiService.addCollectionMultipart(shopObject!!, profile_img_data) } }
0
null
1
1
a9aabcf48662c76db18bcece75cae9ac961da1ed
2,644
NationalPlastic
Apache License 2.0
app/src/main/java/com/hfut/schedule/ui/Activity/success/cube/Settings/Monet/MonetColorItem.kt
Chiu-xaH
705,508,343
false
null
package com.hfut.schedule.ui.ComposeUI.Settings.Monet import android.annotation.SuppressLint import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.animation.shrinkVertically import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.core.os.BuildCompat import com.hfut.schedule.R import com.hfut.schedule.logic.utils.SharePrefs import com.hfut.schedule.logic.utils.SharePrefs.prefs import com.hfut.schedule.ui.MonetColor.MonetUI import com.hfut.schedule.ui.UIUtils.MyToast @OptIn(ExperimentalMaterial3Api::class) @SuppressLint("SuspiciousIndentation") @Composable fun MonetColorItem() { var expandItems by remember { mutableStateOf(prefs.getBoolean("expandMonet",false)) } var text by remember { mutableStateOf("") } text = when(expandItems){ true -> "收回" false -> "展开" } val switch_color = prefs.getBoolean("SWITCHCOLOR",true) var DynamicSwitch by remember { mutableStateOf(switch_color) } if (BuildCompat.isAtLeastS()) ListItem( headlineContent = { Text(text = "取色算法") }, supportingContent = { Column { Text(text = "对于无法调用Android 12+的原生动态取色的系统,可使用莫奈取色算法,点击${text};若您的系统支持原生取色,请选择原生") Row { FilterChip( onClick = { DynamicSwitch = true MyToast("切换算法后,重启应用生效") SharePrefs.SaveBoolean("SWITCHCOLOR", true, DynamicSwitch) }, label = { Text(text = "莫奈取色") }, selected = DynamicSwitch) Spacer(modifier = Modifier.width(10.dp)) FilterChip( onClick = { MyToast("切换算法后,重启应用生效") expandItems = false SharePrefs.SaveBoolean("expandMonet",false,expandItems) DynamicSwitch = false SharePrefs.SaveBoolean("SWITCHCOLOR", true, DynamicSwitch) }, label = { Text(text = "原生取色") }, selected = !DynamicSwitch) } } }, leadingContent = { Icon(painterResource(R.drawable.color), contentDescription = "Localized description",) }, trailingContent = { if(DynamicSwitch) { IconButton(onClick = { expandItems = !expandItems SharePrefs.SaveBoolean("expandMonet",false,expandItems) }) { Icon( if(!expandItems)Icons.Filled.KeyboardArrowDown else Icons.Filled.KeyboardArrowUp, contentDescription = "")} } }, modifier = Modifier.clickable { if(DynamicSwitch) { expandItems = !expandItems SharePrefs.SaveBoolean("expandMonet",false,expandItems) } else MyToast("未打开") } ) else ListItem( headlineContent = { Text(text = "莫奈取色") }, supportingContent = { Text(text = "对于低于Android 12的系统,不支持原生取色,可使用莫奈取色算法,点击${text}") }, leadingContent = { Icon(painterResource(R.drawable.color), contentDescription = "Localized description",) }, trailingContent = { IconButton(onClick = { expandItems = !expandItems SharePrefs.SaveBoolean("expandMonet",false,expandItems) }) { Icon( if(!expandItems)Icons.Filled.KeyboardArrowDown else Icons.Filled.KeyboardArrowUp, contentDescription = "")} }, modifier = Modifier.clickable { expandItems = !expandItems SharePrefs.SaveBoolean("expandMonet",false,expandItems) } ) AnimatedVisibility( visible = expandItems, enter = slideInVertically( initialOffsetY = { -40 } ) + expandVertically( expandFrom = Alignment.Top ) + scaleIn( // Animate scale from 0f to 1f using the top center as the pivot point. transformOrigin = TransformOrigin(0.5f, 0f) ) + fadeIn(initialAlpha = 0.3f), exit = slideOutVertically() + shrinkVertically() + fadeOut() + scaleOut(targetScale = 1.2f) ) { Column( Modifier .fillMaxWidth() .requiredHeight(240.dp)) { MonetUI() } } Spacer(modifier = Modifier.height(5.dp)) }
0
null
1
3
aead3d3e437531c52a0ba99d71fae27d4ea0fe4f
6,131
HFUT-Schedule
Apache License 2.0
app/src/main/java/id/dtprsty/chatttoy/main/adapter/HolderMessageTo.kt
dtprsty
246,944,982
false
null
package id.dtprsty.chatttoy.main.adapter import android.view.View import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import id.dtprsty.chatttoy.R import id.dtprsty.chatttoy.data.Message import id.dtprsty.chatttoy.data.UserInfo import kotlinx.android.synthetic.main.to_message.view.* class HolderMessageTo (itemView: View) : RecyclerView.ViewHolder(itemView){ fun bindChatContent(chat: Message, user: UserInfo) { with(itemView){ Glide.with(context) .load(user?.avatar) .centerCrop() .dontAnimate() .apply( RequestOptions.placeholderOf(R.drawable.ic_sentiment_very_satisfied_black_24dp) ) .into(ivAvatar) tvMessage.text = chat.message tvDate.text = chat.date } } }
0
Kotlin
0
0
bdef0b2d08abea03909b553f6bd44f9331f9653b
920
kiwari-android-test
MIT License
analysis/low-level-api-fir/testData/getOrBuildFir/types/typeParameterBound.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
fun <T : <expr>Number</expr>> check(t: T) { }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
46
kotlin
Apache License 2.0
permission-library/src/main/kotlin/com/michibaum/permission_library/Permissions.kt
MichiBaum
246,055,538
false
{"Kotlin": 152355, "TypeScript": 36802, "HTML": 11408, "CSS": 3150, "Java": 1289, "JavaScript": 969, "SCSS": 393}
package com.michibaum.permission_library enum class Permissions { ADMIN_SERVICE, REGISTRY_SERVICE, AUTHENTICATION_SERVICE, USERMANAGEMENT_SERVICE, USERMANAGEMENT_SERVICE_EDIT_OWN_USER, SERMANAGEMENT_SERVICE_EDIT_ALL_USER, CHESS_SERVICE; }
0
Kotlin
0
1
77911b5f9d53f6630e34e3cd89b69ba277ad2b87
272
Microservices
Apache License 2.0
src/main/java/com/vladsch/md/nav/flex/settings/FlexmarkHtmlSettings.kt
vsch
32,095,357
false
{"Kotlin": 2420465, "Java": 2294749, "HTML": 131988, "JavaScript": 68307, "CSS": 64158, "Python": 486}
// Copyright (c) 2017-2020 <NAME> <<EMAIL>> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.flex.settings import com.vladsch.flexmark.util.data.DataKey import com.vladsch.md.nav.editor.util.HtmlPanelProvider import com.vladsch.md.nav.settings.* import com.vladsch.md.nav.settings.api.MdSettingsExtension import com.vladsch.plugin.util.nullIfBlank import com.vladsch.plugin.util.nullIfEmpty import java.util.* import kotlin.collections.HashMap class FlexmarkHtmlSettings() : StateHolderImpl({ FlexmarkHtmlSettings() }), MdSettingsExtension<FlexmarkHtmlSettings> { var flexmarkSpecExampleRendering: Int = 0 var flexmarkSpecExampleRenderHtml: Boolean = false var flexmarkSpecExampleRenderingType: FlexmarkSpecExampleRenderingType get() = FlexmarkSpecExampleRenderingType.ADAPTER.get(flexmarkSpecExampleRendering) set(value) { flexmarkSpecExampleRendering = value.intValue } val flexmarkSectionLanguages: HashMap<Int, String> = HashMap(DEFAULT_SECTION_LANGUAGES) fun getFlexmarkSectionLanguagesOnly(): Map<Int, String> { val map = HashMap<Int, String>() flexmarkSectionLanguages .filter { !(it.key > 0 && it.value != FLEXMARK_AST_LANGUAGE_NAME && it.value.startsWith(FLEXMARK_AST_LANGUAGE_PREFIX)) } .forEach { map[it.key] = if (it.value.startsWith(FLEXMARK_AST_LANGUAGE_PREFIX)) "text" else it.value.toLowerCase() } return map } fun getFlexmarkSectionNames(): Map<Int, String> { val map = HashMap<Int, String>() flexmarkSectionLanguages .forEach { map[it.key] = if (it.value.startsWith(FLEXMARK_AST_LANGUAGE_PREFIX)) "AST" else it.value } return map } override fun isDefault(): Boolean { return this == DEFAULT } constructor(other: FlexmarkHtmlSettings) : this() { copyFrom(other) } interface Holder { var htmlSettings: FlexmarkHtmlSettings } fun isDefault(htmlPanelProvider: HtmlPanelProvider.Info?): Boolean { return this == getDefaultSettings(htmlPanelProvider) } override fun createCopy(): FlexmarkHtmlSettings { return FlexmarkHtmlSettings(this) } override fun copyFrom(other: FlexmarkHtmlSettings) { this.flexmarkSpecExampleRendering = other.flexmarkSpecExampleRendering this.flexmarkSpecExampleRenderHtml = other.flexmarkSpecExampleRenderHtml this.flexmarkSectionLanguages.clear(); this.flexmarkSectionLanguages.putAll(other.flexmarkSectionLanguages) } override fun getKey(): DataKey<FlexmarkHtmlSettings> = KEY override fun getDefault(): FlexmarkHtmlSettings = DEFAULT override fun getStateHolder(): StateHolder { val tagItemHolder = TagItemHolder("FlexmarkHtmlSettings") addItems(false, tagItemHolder) return tagItemHolder } fun sectionInfo(index: Int): com.vladsch.flexmark.util.misc.Pair<String, Set<Int>> { return languageSections(flexmarkSectionLanguages[index]) } override fun addItems(readOnly: Boolean, tagItemHolder: TagItemHolder) { // readOnly items are only loaded if their attribute is actually found in the element // non-read only will set to default to empty value (false, "", 0, etc.) tagItemHolder.addItems( IntAttribute("flexmarkSpecExampleRendering", readOnly, { flexmarkSpecExampleRendering }, { flexmarkSpecExampleRendering = it }), BooleanAttribute("flexmarkSpecExampleRenderHtml", readOnly, { flexmarkSpecExampleRenderHtml }, { flexmarkSpecExampleRenderHtml = it }), MapItem("flexmarkSectionLanguages", readOnly, { flexmarkSectionLanguages }, { flexmarkSectionLanguages.clear(); flexmarkSectionLanguages.putAll(it.nullIfEmpty() ?: DEFAULT_SECTION_LANGUAGES) }, { key: Int, value: String -> Pair(key.toString(), value) }, { key: String, value: String? -> val index = key.toIntOrNull() if (value != null && index != null) { Pair(index, value) } else { null } } ) ) } companion object { const val FLEXMARK_AST_LANGUAGE_NAME: String = "flexmark-ast" const val FLEXMARK_AST_LANGUAGE_PREFIX: String = "$FLEXMARK_AST_LANGUAGE_NAME:" @JvmField val DEFAULT_SECTION_LANGUAGES: Map<Int, String> = mapOf(1 to "Markdown", 2 to "HTML", 3 to "$FLEXMARK_AST_LANGUAGE_NAME:1") @JvmField val KEY = DataKey("FlexmarkHtmlSettings") { FlexmarkHtmlSettings() } @JvmStatic val DEFAULT: FlexmarkHtmlSettings by lazy { FlexmarkHtmlSettings() } @Suppress("UNUSED_PARAMETER") fun getDefaultSettings(htmlPanelProvider: HtmlPanelProvider.Info?): FlexmarkHtmlSettings { return DEFAULT } @JvmStatic fun languageSections(languageString: String?): com.vladsch.flexmark.util.misc.Pair<String, Set<Int>> { val languageSections = languageString.nullIfBlank() ?: return com.vladsch.flexmark.util.misc.Pair.of("", emptySet()) var language: String = languageSections val astSections = HashSet<Int>() val pos = languageSections.indexOf(":") if (pos >= 0) { language = languageSections.substring(0, pos) val sections = languageSections.substring(pos + 1).trim().split(",").toTypedArray() for (section in sections) { val trimmedSection = section.trim() if (trimmedSection.isEmpty()) continue try { val index = Integer.parseInt(trimmedSection) if (index > 0) { astSections.add(index) } } catch (ignored: NumberFormatException) { } } } return com.vladsch.flexmark.util.misc.Pair.of(language, astSections) } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as FlexmarkHtmlSettings if (flexmarkSpecExampleRendering != other.flexmarkSpecExampleRendering) return false if (flexmarkSpecExampleRenderHtml != other.flexmarkSpecExampleRenderHtml) return false if (flexmarkSectionLanguages != other.flexmarkSectionLanguages) return false return true } override fun hashCode(): Int { var result = 0 result += 31 * result + flexmarkSpecExampleRendering.hashCode() result += 31 * result + flexmarkSpecExampleRenderHtml.hashCode() result += 31 * result + flexmarkSectionLanguages.hashCode() return result } @Suppress("UNUSED_PARAMETER") fun changeToProvider(fromPanelProviderInfo: HtmlPanelProvider.Info?, toPanelProviderInfo: HtmlPanelProvider.Info): FlexmarkHtmlSettings { return FlexmarkHtmlSettings(this) } }
134
Kotlin
131
809
ec413c0e1b784ff7309ef073ddb4907d04345073
7,304
idea-multimarkdown
Apache License 2.0
gradle-plugin/src/main/java/com/squareup/anvil/plugin/AnvilPlugin.kt
square
271,357,426
false
null
package com.squareup.anvil.plugin import com.android.build.gradle.AppExtension import com.android.build.gradle.LibraryExtension import com.android.build.gradle.TestExtension import com.android.build.gradle.TestedExtension import com.android.build.gradle.api.BaseVariant import com.android.build.gradle.api.TestVariant import com.android.build.gradle.api.UnitTestVariant import com.android.build.gradle.internal.tasks.factory.dependsOn import org.gradle.api.Action import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.UnknownTaskException import org.gradle.api.artifacts.Configuration import org.gradle.api.provider.Provider import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider import org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask import org.jetbrains.kotlin.gradle.plugin.FilesSubpluginOption import org.jetbrains.kotlin.gradle.plugin.KaptExtension import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation import org.jetbrains.kotlin.gradle.plugin.KotlinCompilerPluginSupportPlugin import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.androidJvm import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.jvm import org.jetbrains.kotlin.gradle.plugin.PLUGIN_CLASSPATH_CONFIGURATION_NAME import org.jetbrains.kotlin.gradle.plugin.SubpluginArtifact import org.jetbrains.kotlin.gradle.plugin.SubpluginOption import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinJvmAndroidCompilation import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import java.io.File import java.util.Locale.US import java.util.concurrent.ConcurrentHashMap @Suppress("unused") internal open class AnvilPlugin : KotlinCompilerPluginSupportPlugin { private val variantCache = ConcurrentHashMap<String, Variant>() override fun apply(target: Project) { target.extensions.create("anvil", AnvilExtension::class.java) // Create a configuration for collecting CodeGenerator dependencies. We need to create all // configurations eagerly and cannot wait for applyToCompilation(..) below, because this // function is called in an afterEvaluate block by the Kotlin Gradle Plugin. That's too late // to register the configurations. val commonConfiguration = getConfiguration(target, buildType = "") // anvilTest is the common test configuration similar to other configurations like kaptTest. // Android build type specific unit test variants will extend this variant below. For the JVM // this single variant is enough. val testConfiguration = getConfiguration(target, buildType = "test").apply { extendsFrom(commonConfiguration) } agpPlugins.forEach { agpPlugin -> target.pluginManager.withPlugin(agpPlugin) { // This is the common android test variant, similar to anvilTest above. val androidTestVariant = getConfiguration(target, buildType = "androidTest").apply { extendsFrom(commonConfiguration) } target.androidVariantsConfigure { variant -> // E.g. "anvilDebug", "anvilTestRelease", ... val configuration = getConfiguration(target, buildType = variant.name) when (variant) { is UnitTestVariant -> configuration.extendsFrom(testConfiguration) is TestVariant -> configuration.extendsFrom(androidTestVariant) // non-test variants like "debug" extend the main config else -> configuration.extendsFrom(commonConfiguration) } } } } } override fun isApplicable(kotlinCompilation: KotlinCompilation<*>): Boolean { return when (kotlinCompilation.platformType) { // If the variant is ignored, then don't apply the compiler plugin. androidJvm, jvm -> !getVariant(kotlinCompilation).variantFilter.ignore else -> false } } override fun applyToCompilation( kotlinCompilation: KotlinCompilation<*> ): Provider<List<SubpluginOption>> { val variant = getVariant(kotlinCompilation) val project = variant.project if (!variant.variantFilter.generateDaggerFactories && variant.variantFilter.generateDaggerFactoriesOnly ) { throw GradleException( "You cannot set generateDaggerFactories to false and generateDaggerFactoriesOnly " + "to true at the same time for variant ${variant.name}." ) } // Make the kotlin compiler classpath extend our configurations to pick up our extra // generators. project.configurations.getByName(variant.compilerPluginClasspathName) .extendsFrom(getConfiguration(project, variant.name)) disableIncrementalKotlinCompilation(variant) disablePreciseJavaTracking(variant) if (!variant.variantFilter.generateDaggerFactoriesOnly) { disableCorrectErrorTypes(variant) kotlinCompilation.dependencies { implementation("$GROUP:annotations:$VERSION") } } // Notice that we use the name of the variant as a directory name. Generated code // for this specific compile task will be included in the task output. The output of different // compile tasks shouldn't be mixed. val srcGenDir = File( project.buildDir, "anvil${File.separator}src-gen-${variant.name}" ) return project.provider { listOf( FilesSubpluginOption( key = "src-gen-dir", files = listOf(srcGenDir) ), SubpluginOption( key = "generate-dagger-factories", lazy { variant.variantFilter.generateDaggerFactories.toString() } ), SubpluginOption( key = "generate-dagger-factories-only", lazy { variant.variantFilter.generateDaggerFactoriesOnly.toString() } ), SubpluginOption( key = "disable-component-merging", lazy { variant.variantFilter.disableComponentMerging.toString() } ) ) } } override fun getCompilerPluginId(): String = "com.squareup.anvil.compiler" override fun getPluginArtifact(): SubpluginArtifact = SubpluginArtifact( groupId = GROUP, artifactId = "compiler", version = VERSION ) private fun disablePreciseJavaTracking(variant: Variant) { variant.compileTaskProvider.configure { compileTask -> val result = CheckMixedSourceSet.preparePreciseJavaTrackingCheck(variant) compileTask.doFirstCompat { // Disable precise java tracking if needed. Note that the doFirst() action only runs // if the task is not up to date. That's ideal, because if nothing needs to be // compiled, then we don't need to disable the flag. // // We also use the doFirst block to walk through the file system at execution time // and minimize the IO at configuration time. CheckMixedSourceSet.disablePreciseJavaTrackingIfNeeded(compileTask, result) compileTask.log( "Anvil: Use precise java tracking: ${compileTask.usePreciseJavaTracking}" ) } } } private fun disableCorrectErrorTypes(variant: Variant) { variant.project.pluginManager.withPlugin("org.jetbrains.kotlin.kapt") { // This needs to be disabled, otherwise compiler plugins fail in weird ways when // generating stubs, e.g.: // // /anvil/sample/app/build/generated/source/kapt/debug/com/squareup/anvil // /sample/DaggerAppComponent.java:13: error: DaggerAppComponent is not abstract and does // not override abstract method string() in RandomComponent // public final class DaggerAppComponent implements AppComponent { // ^ // 1 error variant.project.extensions.findByType(KaptExtension::class.java)?.correctErrorTypes = false } } private fun disableIncrementalKotlinCompilation(variant: Variant) { // Use this signal to share state between DisableIncrementalCompilationTask and the Kotlin // compile task. If the plugin classpath changed, then DisableIncrementalCompilationTask sets // the signal to false. @Suppress("UnstableApiUsage") val incrementalSignal = IncrementalSignal.registerIfAbsent(variant.project) disableIncrementalCompilationWhenTheCompilerClasspathChanges( variant, incrementalSignal, variant.compileTaskProvider ) variant.project.pluginManager.withPlugin("org.jetbrains.kotlin.kapt") { variant.project .namedLazy<KaptGenerateStubsTask>( "kaptGenerateStubs${variant.taskSuffix}" ) { stubsTaskProvider -> if (variant.variantFilter.generateDaggerFactoriesOnly || variant.variantFilter.disableComponentMerging ) { // We don't need to disable the incremental compilation for the stub generating task // every time, when we only generate Dagger factories or contribute modules. That's only // needed for merging Dagger modules. // // However, we still need to update the generated code when the compiler plugin classpath // changes. disableIncrementalCompilationWhenTheCompilerClasspathChanges( variant, incrementalSignal, stubsTaskProvider ) } else { stubsTaskProvider.configure { stubsTask -> // Disable incremental compilation for the stub generating task. Trigger the compiler // plugin if any dependencies in the compile classpath have changed. This will make sure // that we pick up any change from a dependency when merging all the classes. Without // this workaround we could make changes in any library, but these changes wouldn't be // contributed to the Dagger graph, because incremental compilation tricked us. stubsTask.doFirstCompat { stubsTask.incremental = false stubsTask.log( "Anvil: Incremental compilation enabled: ${stubsTask.incremental} (stub)" ) } } } } } } private fun disableIncrementalCompilationWhenTheCompilerClasspathChanges( variant: Variant, incrementalSignal: Provider<IncrementalSignal>, compileTaskProvider: TaskProvider<out KotlinCompile> ) { val compileTaskName = compileTaskProvider.name // Disable incremental compilation, if the compiler plugin dependency isn't up-to-date. // This will trigger a full compilation of a module using Anvil even though its // source files might not have changed. This workaround is necessary, otherwise // incremental builds are broken. See https://youtrack.jetbrains.com/issue/KT-38570 val disableIncrementalCompilationTaskProvider = variant.project.tasks.register( compileTaskName + "CheckIncrementalCompilationAnvil", DisableIncrementalCompilationTask::class.java ) { task -> task.pluginClasspath.from( variant.project.configurations.getByName(variant.compilerPluginClasspathName) ) task.incrementalSignal.set(incrementalSignal) } compileTaskProvider.dependsOn(disableIncrementalCompilationTaskProvider) // We avoid a reference to the project in the doFirst. val projectPath = variant.project.path compileTaskProvider.configure { compileTask -> compileTask.doFirstCompat { // If the signal is set, then the plugin classpath changed. Apply the setting that // DisableIncrementalCompilationTask requested. val incremental = incrementalSignal.get().isIncremental(projectPath) if (incremental != null) { compileTask.incremental = incremental } compileTask.log( "Anvil: Incremental compilation enabled: ${compileTask.incremental} (compile)" ) } } } private fun getConfiguration( project: Project, buildType: String ): Configuration { val name = if (buildType.isEmpty()) "anvil" else "anvil${buildType.capitalize(US)}" return project.configurations.maybeCreate(name).apply { description = "This configuration is used for dependencies with Anvil CodeGenerator " + "implementations." } } private fun getVariant(kotlinCompilation: KotlinCompilation<*>): Variant { return variantCache.computeIfAbsent(kotlinCompilation.name) { val variant = Variant(kotlinCompilation) // The cache makes sure that we execute this filter action only once. variant.project.extensions.getByType(AnvilExtension::class.java) ._variantFilter ?.execute(variant.variantFilter) variant } } } /* * Don't convert this to a lambda to avoid this error: * * The task was not up-to-date because of the following reasons: * Additional action for task ':sample:library:compileKotlin': was implemented by the Java * lambda 'com.squareup.anvil.plugin.AnvilPlugin$$Lambda$7578/0x0000000801769440'. Using Java * lambdas is not supported, use an (anonymous) inner class instead. * * Sample build scan: https://scans.gradle.com/s/ppwb2psllveks/timeline?details=j62m2xx52wwxy * * More context is here: https://github.com/gradle/gradle/issues/5510#issuecomment-416860213 */ @Suppress("ObjectLiteralToLambda") private fun <T : Task> T.doFirstCompat(block: (T) -> Unit) { doFirst(object : Action<Task> { override fun execute(task: Task) { @Suppress("UNCHECKED_CAST") block(task as T) } }) } /** * Similar to [TaskContainer.named], but waits until the task is registered if it doesn't exist, * yet. If the task is never registered, then this method will throw an error after the * configuration phase. */ private inline fun <reified T : Task> Project.namedLazy( name: String, crossinline action: (TaskProvider<T>) -> Unit ) { try { action(tasks.named(name, T::class.java)) return } catch (ignored: UnknownTaskException) { } var didRun = false tasks.whenTaskAdded { task -> if (task.name == name && task is T) { action(tasks.named(name, T::class.java)) didRun = true } } afterEvaluate { if (!didRun) { throw GradleException("Didn't find task $name with type ${T::class}.") } } } /** * Runs the given [action] for each Android variant including androidTest and unit test variants. */ private fun Project.androidVariantsConfigure(action: (BaseVariant) -> Unit) { val androidExtension = extensions.findByName("android") when (androidExtension) { is AppExtension -> androidExtension.applicationVariants.configureEach(action) is LibraryExtension -> androidExtension.libraryVariants.configureEach(action) is TestExtension -> androidExtension.applicationVariants.configureEach(action) } if (androidExtension is TestedExtension) { androidExtension.unitTestVariants.configureEach(action) androidExtension.testVariants.configureEach(action) } } private val agpPlugins = listOf( "com.android.library", "com.android.application", "com.android.test", "com.android.dynamic-feature", ) internal class Variant private constructor( val name: String, val project: Project, val compileTaskProvider: TaskProvider<KotlinCompile>, val androidVariant: BaseVariant?, val compilerPluginClasspathName: String, val variantFilter: VariantFilter, ) { // E.g. compileKotlin, compileKotlinJvm, compileDebugKotlin. val taskSuffix = compileTaskProvider.name.substringAfter("compile") companion object { operator fun invoke(kotlinCompilation: KotlinCompilation<*>): Variant { // Sanity check. require( kotlinCompilation.platformType != androidJvm || kotlinCompilation is KotlinJvmAndroidCompilation ) { "The KotlinCompilation is KotlinJvmAndroidCompilation, but the platform type " + "is different." } val project = kotlinCompilation.target.project val extension = project.extensions.getByType(AnvilExtension::class.java) val androidVariant = (kotlinCompilation as? KotlinJvmAndroidCompilation)?.androidVariant val commonFilter = CommonFilter(kotlinCompilation.name, extension) val variantFilter = if (androidVariant != null) { AndroidVariantFilter(commonFilter, androidVariant) } else { JvmVariantFilter(commonFilter) } @Suppress("UNCHECKED_CAST") return Variant( name = kotlinCompilation.name, project = project, compileTaskProvider = kotlinCompilation.compileKotlinTaskProvider as TaskProvider<KotlinCompile>, androidVariant = androidVariant, compilerPluginClasspathName = PLUGIN_CLASSPATH_CONFIGURATION_NAME + kotlinCompilation.target.targetName.capitalize(US) + kotlinCompilation.name.capitalize(US), variantFilter = variantFilter ).also { // Sanity check. check(it.compileTaskProvider.name.startsWith("compile")) } } } }
54
null
82
941
a5811bbadb63017fb5436d2ed0d4521c471428e6
16,869
anvil
Apache License 2.0
src/main/kotlin/basicallyiamfox/ani/decorator/rule/MagmaticJumpRuleDecorator.kt
BasicallyIAmFox
642,556,530
false
null
package basicallyiamfox.ani.decorator.rule import basicallyiamfox.ani.AnimorphsKeybindings import basicallyiamfox.ani.core.rule.RuleDecorator import basicallyiamfox.ani.core.serializer.ISerializer import basicallyiamfox.ani.extensions.* import basicallyiamfox.ani.mixin.IEntityMixin import basicallyiamfox.ani.mixin.ILivingEntityMixin import com.google.gson.JsonObject import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking import net.fabricmc.fabric.api.networking.v1.FabricPacket import net.fabricmc.fabric.api.networking.v1.PacketType import net.minecraft.entity.LivingEntity import net.minecraft.entity.attribute.EntityAttributes import net.minecraft.entity.player.PlayerEntity import net.minecraft.network.PacketByteBuf import net.minecraft.particle.ParticleTypes import net.minecraft.util.Identifier import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Box import net.minecraft.util.math.MathHelper import net.minecraft.util.math.Vec3d import net.minecraft.world.World class MagmaticJumpRuleDecorator() : RuleDecorator() { object Serializer : ISerializer<MagmaticJumpRuleDecorator> { override fun toJson(obj: JsonObject, type: MagmaticJumpRuleDecorator) { obj.addProperty("id", type.id) obj.addProperty("ready", type.ready) obj.addProperty("max", type.max) } override fun fromJson(obj: JsonObject): MagmaticJumpRuleDecorator { val inst = MagmaticJumpRuleDecorator() inst.id = obj.getIdentifier("id") inst.ready = obj.getInt("ready") inst.max = obj.getInt("max") return inst } override fun toPacket(buf: PacketByteBuf, type: MagmaticJumpRuleDecorator) { buf.writeIdentifier(type.id) buf.writeInt(type.ready) buf.writeInt(type.max) } override fun fromPacket(buf: PacketByteBuf): MagmaticJumpRuleDecorator { val inst = MagmaticJumpRuleDecorator() inst.id = buf.readIdentifier() inst.ready = buf.readInt() inst.max = buf.readInt() return inst } } interface MagmaticJumpPlayerEntity { var magmaTick: Int var magmaDamage: Float var magmaScale: Float } class JumpPacket : FabricPacket { companion object { val ID = Identifier("animorphs:magma_jump") val TYPE: PacketType<JumpPacket> = PacketType.create(ID) { JumpPacket(it) } } val magicScaleNumber: Float constructor(buf: PacketByteBuf) { magicScaleNumber = buf.readFloat() } constructor(magicScaleNumber: Float) { this.magicScaleNumber = magicScaleNumber } override fun write(buf: PacketByteBuf?) { buf!!.writeFloat(magicScaleNumber) } override fun getType(): PacketType<*> { return TYPE } } class DamagePacket : FabricPacket { companion object { val ID = Identifier("animorphs:magma_jump_damage") val TYPE: PacketType<DamagePacket> = PacketType.create(ID) { DamagePacket() } } override fun write(buf: PacketByteBuf?) { } override fun getType(): PacketType<*> { return TYPE } } companion object { @JvmStatic val ID = Identifier("animorphs:magmatic_jump") const val magicScaleNumber = 2.2857144f fun damage(player: PlayerEntity) { player as MagmaticJumpPlayerEntity val pos = player.pos val box: Box = Box(pos, Vec3d.ofCenter(BlockPos(pos.getX().toInt(), pos.getY().toInt(), pos.getZ().toInt()))).expand(10.0) player.world.getEntitiesByClass(LivingEntity::class.java, box) { entity -> !entity.uuid.equals(player.uuid) && entity.getAttributeValue(EntityAttributes.GENERIC_ATTACK_DAMAGE) > 0.0 && entity.isAlive }.forEach { entity -> entity.damage(player.damageSources.lava(), player.magmaDamage) } player.magmaDamage = 0.0f } fun jump(player: PlayerEntity, magicScaleNumber: Float) { player as MagmaticJumpPlayerEntity player as ILivingEntityMixin var jumpVelocity = player.jumpBoostVelocityModifier jumpVelocity += magicScaleNumber * (Companion.magicScaleNumber / 10.0f * 7.06f) player.magmaDamage = Companion.magicScaleNumber * 2.06f; val d = player.invokeGetJumpVelocity().toDouble() + jumpVelocity val vec3d = player.velocity player.setVelocity(vec3d.x, d, vec3d.z) if (player.isSprinting) { val f = player.yaw * MathHelper.RADIANS_PER_DEGREE player.velocity = player.velocity.add( (-MathHelper.sin(f) * 0.2f).toDouble(), 0.0, (MathHelper.cos(f) * 0.2f).toDouble() ) } player.velocityDirty = true } } var ready: Int = 0 var max: Int = 0 constructor(ready: Int, max: Int) : this() { id = ID this.ready = ready this.max = max } private fun getMagicScaleNumber(player: PlayerEntity): Float { return (player as MagmaticJumpPlayerEntity).magmaTick.toFloat() / max.toFloat() / magicScaleNumber } override fun update(world: World, player: PlayerEntity) { if (!world.isClient) return val duck = player as MagmaticJumpPlayerEntity val iDuck = player as IEntityMixin duck.magmaScale = getMagicScaleNumber(player) if (player.isSpectator) { duck.magmaDamage = 0f duck.magmaTick = 0 return } if (!AnimorphsKeybindings.magmaJumpKeyBinding!!.isPressed || duck.magmaTick > 0 && player.isMoving()) { if (duck.magmaTick >= ready) { jump(player, duck.magmaScale) ClientPlayNetworking.send(JumpPacket(duck.magmaScale)) } duck.magmaTick = 0 iDuck.invokeCalculateDimensions() } else { if (duck.magmaTick >= ready) { var min = 0 var max = 1 var p = ParticleTypes.FLAME if (duck.magmaTick >= this.max - 1) { if (duck.magmaTick == this.max - 1) { min = 20 max = 30 duck.magmaTick = this.max iDuck.invokeCalculateDimensions() ClientPlayNetworking.send(JumpPacket(duck.magmaScale)) } p = ParticleTypes.SOUL_FIRE_FLAME min += 2 max += 4 } else { duck.magmaTick += 1 iDuck.invokeCalculateDimensions() ClientPlayNetworking.send(JumpPacket(duck.magmaScale)) } if (!player.isInvisible && player.isVisualActive()) { var pos = Vec3d(player.x, player.y, player.z) for (i in min until max) { pos = pos.add( if (player.random.nextBoolean()) player.random.nextDouble() else -player.random.nextDouble(), 0.05, if (player.random.nextBoolean()) player.random.nextDouble() else -player.random.nextDouble() ) val input = IEntityMixin.invokeMovementInputToVelocity( Vec3d( (if (player.random.nextBoolean()) player.random.nextDouble() else -player.random.nextDouble()) / 10, -player.random.nextDouble() / 15, 0.0 ), 1.1f, player.bodyYaw ) world.addParticle(p, pos.x, pos.y + 0.05, pos.z, input.x, input.y, input.z) pos = Vec3d(player.x, player.y, player.z) } } } else { duck.magmaTick += 1 iDuck.invokeCalculateDimensions() ClientPlayNetworking.send(JumpPacket(duck.magmaScale)) } } if (duck.magmaDamage > 0.0f && !player.isMoving() && !player.isSpectator) { damage(player) duck.magmaDamage = 0.0f ClientPlayNetworking.send(DamagePacket()) } } }
0
Kotlin
0
0
448d9eb2de0250eccf6a1d48bcec7bad260b6bf2
8,622
animorphs-kt
MIT License
bugsnag-android-core/src/main/java/com/bugsnag/android/Device.kt
bugsnag
2,406,783
false
null
package com.bugsnag.android /** * Stateless information set by the notifier about the device on which the event occurred can be * found on this class. These values can be accessed and amended if necessary. */ open class Device internal constructor( buildInfo: DeviceBuildInfo, /** * The Application Binary Interface used */ var cpuAbi: Array<String>?, /** * Whether the device has been jailbroken */ var jailbroken: Boolean?, /** * A UUID generated by Bugsnag and used for the individual application on a device */ var id: String?, /** * The IETF language tag of the locale used */ var locale: String?, /** * The total number of bytes of memory on the device */ var totalMemory: Long?, /** * A collection of names and their versions of the primary languages, frameworks or * runtimes that the application is running on */ var runtimeVersions: MutableMap<String, Any>? ) : JsonStream.Streamable { /** * The manufacturer of the device used */ var manufacturer: String? = buildInfo.manufacturer /** * The model name of the device used */ var model: String? = buildInfo.model /** * The name of the operating system running on the device used */ var osName: String? = "android" /** * The version of the operating system running on the device used */ var osVersion: String? = buildInfo.osVersion internal open fun serializeFields(writer: JsonStream) { writer.name("cpuAbi").value(cpuAbi) writer.name("jailbroken").value(jailbroken) writer.name("id").value(id) writer.name("locale").value(locale) writer.name("manufacturer").value(manufacturer) writer.name("model").value(model) writer.name("osName").value(osName) writer.name("osVersion").value(osVersion) writer.name("runtimeVersions").value(runtimeVersions) writer.name("totalMemory").value(totalMemory) } override fun toStream(writer: JsonStream) { writer.beginObject() serializeFields(writer) writer.endObject() } }
17
null
205
1,188
f5fd26b3cdeda9c4d4e221f55feb982a3fd97197
2,189
bugsnag-android
MIT License
mulighetsrommet-api/src/test/kotlin/no/nav/mulighetsrommet/api/repositories/TiltaksgjennomforingRepositoryTest.kt
navikt
435,813,834
false
null
package no.nav.mulighetsrommet.api.repositories import io.kotest.assertions.arrow.core.shouldBeRight import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.date.shouldNotBeBefore import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.should import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import kotlinx.serialization.json.Json import kotliquery.Query import no.nav.mulighetsrommet.api.clients.norg2.Norg2Type import no.nav.mulighetsrommet.api.clients.vedtak.Innsatsgruppe import no.nav.mulighetsrommet.api.createDatabaseTestConfig import no.nav.mulighetsrommet.api.domain.dbo.NavEnhetDbo import no.nav.mulighetsrommet.api.domain.dbo.NavEnhetStatus import no.nav.mulighetsrommet.api.domain.dbo.TiltaksgjennomforingKontaktpersonDbo import no.nav.mulighetsrommet.api.domain.dto.TiltaksgjennomforingAdminDto import no.nav.mulighetsrommet.api.domain.dto.TiltaksgjennomforingKontaktperson import no.nav.mulighetsrommet.api.domain.dto.VirksomhetDto import no.nav.mulighetsrommet.api.domain.dto.VirksomhetKontaktperson import no.nav.mulighetsrommet.api.fixtures.AvtaleFixtures.oppfolging import no.nav.mulighetsrommet.api.fixtures.MulighetsrommetTestDomain import no.nav.mulighetsrommet.api.fixtures.NavAnsattFixture import no.nav.mulighetsrommet.api.fixtures.NavEnhetFixtures import no.nav.mulighetsrommet.api.fixtures.TiltaksgjennomforingFixtures.Arbeidstrening1 import no.nav.mulighetsrommet.api.fixtures.TiltaksgjennomforingFixtures.ArenaOppfolging1 import no.nav.mulighetsrommet.api.fixtures.TiltaksgjennomforingFixtures.Oppfolging1 import no.nav.mulighetsrommet.api.fixtures.TiltaksgjennomforingFixtures.Oppfolging2 import no.nav.mulighetsrommet.api.fixtures.TiltakstypeFixtures import no.nav.mulighetsrommet.api.utils.DEFAULT_PAGINATION_LIMIT import no.nav.mulighetsrommet.api.utils.PaginationParams import no.nav.mulighetsrommet.database.kotest.extensions.FlywayDatabaseTestListener import no.nav.mulighetsrommet.database.kotest.extensions.truncateAll import no.nav.mulighetsrommet.domain.constants.ArenaMigrering import no.nav.mulighetsrommet.domain.dbo.ArenaTiltaksgjennomforingDbo import no.nav.mulighetsrommet.domain.dbo.Avslutningsstatus import no.nav.mulighetsrommet.domain.dbo.TiltaksgjennomforingOppstartstype import no.nav.mulighetsrommet.domain.dto.Faneinnhold import no.nav.mulighetsrommet.domain.dto.NavIdent import no.nav.mulighetsrommet.domain.dto.Tiltaksgjennomforingsstatus import java.time.LocalDate import java.util.* class TiltaksgjennomforingRepositoryTest : FunSpec({ val database = extension(FlywayDatabaseTestListener(createDatabaseTestConfig())) val domain = MulighetsrommetTestDomain() beforeEach { domain.initialize(database.db) } afterEach { database.db.truncateAll() } context("CRUD") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) test("CRUD adminflate-tiltaksgjennomføringer") { tiltaksgjennomforinger.upsert(Oppfolging1) tiltaksgjennomforinger.get(Oppfolging1.id) should { it.shouldNotBeNull() it.id shouldBe Oppfolging1.id it.tiltakstype shouldBe TiltaksgjennomforingAdminDto.Tiltakstype( id = TiltakstypeFixtures.Oppfolging.id, navn = TiltakstypeFixtures.Oppfolging.navn, arenaKode = TiltakstypeFixtures.Oppfolging.tiltakskode, ) it.navn shouldBe Oppfolging1.navn it.tiltaksnummer shouldBe null it.arrangor shouldBe TiltaksgjennomforingAdminDto.Arrangor( organisasjonsnummer = Oppfolging1.arrangorOrganisasjonsnummer, slettet = true, navn = null, kontaktpersoner = emptyList(), ) it.startDato shouldBe Oppfolging1.startDato it.sluttDato shouldBe Oppfolging1.sluttDato it.arenaAnsvarligEnhet shouldBe null it.status shouldBe Tiltaksgjennomforingsstatus.AVSLUTTET it.apentForInnsok shouldBe true it.antallPlasser shouldBe 12 it.avtaleId shouldBe Oppfolging1.avtaleId it.administratorer shouldBe emptyList() it.navEnheter shouldBe listOf( NavEnhetDbo( navn = "IT", enhetsnummer = "2990", type = Norg2Type.DIR, overordnetEnhet = null, status = NavEnhetStatus.AKTIV, ), ) it.sanityId shouldBe null it.oppstart shouldBe TiltaksgjennomforingOppstartstype.LOPENDE it.opphav shouldBe ArenaMigrering.Opphav.MR_ADMIN_FLATE it.kontaktpersoner shouldBe listOf() it.stedForGjennomforing shouldBe "Oslo" it.navRegion shouldBe NavEnhetDbo( navn = "IT", enhetsnummer = "2990", type = Norg2Type.DIR, overordnetEnhet = null, status = NavEnhetStatus.AKTIV, ) it.faneinnhold shouldBe null it.beskrivelse shouldBe null it.createdAt shouldNotBe null } tiltaksgjennomforinger.delete(Oppfolging1.id) tiltaksgjennomforinger.get(Oppfolging1.id) shouldBe null } test("CRUD ArenaTiltaksgjennomforing") { val navEnheter = NavEnhetRepository(database.db) navEnheter.upsert(NavEnhetFixtures.Innlandet).shouldBeRight() val gjennomforingId = UUID.randomUUID() val gjennomforingFraArena = ArenaTiltaksgjennomforingDbo( id = gjennomforingId, navn = "Tiltak for dovne giraffer", tiltakstypeId = TiltakstypeFixtures.Oppfolging.id, tiltaksnummer = "2023#1", arrangorOrganisasjonsnummer = "123456789", startDato = LocalDate.of(2023, 1, 1), sluttDato = LocalDate.of(2023, 2, 2), arenaAnsvarligEnhet = NavEnhetFixtures.Innlandet.enhetsnummer, avslutningsstatus = Avslutningsstatus.AVSLUTTET, apentForInnsok = false, antallPlasser = 10, avtaleId = null, oppstart = TiltaksgjennomforingOppstartstype.FELLES, deltidsprosent = 100.0, ) tiltaksgjennomforinger.upsertArenaTiltaksgjennomforing(gjennomforingFraArena) tiltaksgjennomforinger.get(gjennomforingFraArena.id) should { it.shouldNotBeNull() it.id shouldBe gjennomforingId it.navn shouldBe "Tiltak for dovne giraffer" it.tiltakstype shouldBe TiltaksgjennomforingAdminDto.Tiltakstype( id = TiltakstypeFixtures.Oppfolging.id, navn = TiltakstypeFixtures.Oppfolging.navn, arenaKode = TiltakstypeFixtures.Oppfolging.tiltakskode, ) it.tiltaksnummer shouldBe "2023#1" it.arrangor shouldBe TiltaksgjennomforingAdminDto.Arrangor( organisasjonsnummer = "123456789", slettet = true, navn = null, kontaktpersoner = emptyList(), ) it.startDato shouldBe LocalDate.of(2023, 1, 1) it.sluttDato shouldBe LocalDate.of(2023, 2, 2) it.arenaAnsvarligEnhet shouldBe NavEnhetFixtures.Innlandet it.apentForInnsok shouldBe false it.antallPlasser shouldBe 10 it.avtaleId shouldBe null it.oppstart shouldBe TiltaksgjennomforingOppstartstype.FELLES it.status shouldBe Tiltaksgjennomforingsstatus.AVSLUTTET it.administratorer shouldBe emptyList() it.navEnheter shouldBe emptyList() it.navRegion shouldBe null it.sanityId shouldBe null it.opphav shouldBe ArenaMigrering.Opphav.ARENA it.kontaktpersoner shouldBe emptyList() it.stedForGjennomforing shouldBe null it.faneinnhold shouldBe null it.beskrivelse shouldBe null it.createdAt shouldNotBe null } } test("upsert endrer ikke opphav om det allerede er satt") { val id1 = UUID.randomUUID() tiltaksgjennomforinger.upsertArenaTiltaksgjennomforing(ArenaOppfolging1.copy(id = id1)) tiltaksgjennomforinger.upsert(Oppfolging1.copy(id = id1)) tiltaksgjennomforinger.get(id1).shouldNotBeNull().should { it.opphav shouldBe ArenaMigrering.Opphav.ARENA } val id2 = UUID.randomUUID() tiltaksgjennomforinger.upsert(Oppfolging1.copy(id = id2)) tiltaksgjennomforinger.upsertArenaTiltaksgjennomforing(ArenaOppfolging1.copy(id = id2)) tiltaksgjennomforinger.get(id2).shouldNotBeNull().should { it.opphav shouldBe ArenaMigrering.Opphav.MR_ADMIN_FLATE } } test("arena overskriver ikke oppstart") { tiltaksgjennomforinger.upsertArenaTiltaksgjennomforing(ArenaOppfolging1) tiltaksgjennomforinger.get(ArenaOppfolging1.id) should { it!!.oppstart shouldBe TiltaksgjennomforingOppstartstype.FELLES } tiltaksgjennomforinger.upsert( Oppfolging1.copy( id = ArenaOppfolging1.id, oppstart = TiltaksgjennomforingOppstartstype.LOPENDE, ), ) tiltaksgjennomforinger.upsertArenaTiltaksgjennomforing(ArenaOppfolging1) tiltaksgjennomforinger.get(ArenaOppfolging1.id) should { it!!.oppstart shouldBe TiltaksgjennomforingOppstartstype.LOPENDE } } test("navEnheter crud") { val enhetRepository = NavEnhetRepository(database.db) enhetRepository.upsert( NavEnhetDbo( navn = "Navn1", enhetsnummer = "1", status = NavEnhetStatus.AKTIV, type = Norg2Type.LOKAL, overordnetEnhet = null, ), ).shouldBeRight() enhetRepository.upsert( NavEnhetDbo( navn = "Navn2", enhetsnummer = "2", status = NavEnhetStatus.AKTIV, type = Norg2Type.LOKAL, overordnetEnhet = null, ), ).shouldBeRight() enhetRepository.upsert( NavEnhetDbo( navn = "Navn3", enhetsnummer = "3", status = NavEnhetStatus.AKTIV, type = Norg2Type.LOKAL, overordnetEnhet = null, ), ).shouldBeRight() val gjennomforing = Oppfolging1.copy( id = UUID.randomUUID(), navEnheter = listOf("1", "2"), ) tiltaksgjennomforinger.upsert(gjennomforing) tiltaksgjennomforinger.get(gjennomforing.id).should { it!!.navEnheter shouldContainExactlyInAnyOrder listOf( NavEnhetDbo( enhetsnummer = "1", navn = "Navn1", type = Norg2Type.LOKAL, overordnetEnhet = null, status = NavEnhetStatus.AKTIV, ), NavEnhetDbo( enhetsnummer = "2", navn = "Navn2", type = Norg2Type.LOKAL, overordnetEnhet = null, status = NavEnhetStatus.AKTIV, ), ) } database.assertThat("tiltaksgjennomforing_nav_enhet").hasNumberOfRows(2) tiltaksgjennomforinger.upsert(gjennomforing.copy(navEnheter = listOf("3", "1"))) tiltaksgjennomforinger.get(gjennomforing.id).should { it!!.navEnheter shouldContainExactlyInAnyOrder listOf( NavEnhetDbo( enhetsnummer = "1", navn = "Navn1", type = Norg2Type.LOKAL, overordnetEnhet = null, status = NavEnhetStatus.AKTIV, ), NavEnhetDbo( enhetsnummer = "3", navn = "Navn3", type = Norg2Type.LOKAL, overordnetEnhet = null, status = NavEnhetStatus.AKTIV, ), ) } database.assertThat("tiltaksgjennomforing_nav_enhet").hasNumberOfRows(2) } test("kontaktpersoner på tiltaksgjennomføring CRUD") { val gjennomforing = Oppfolging1.copy( kontaktpersoner = listOf( TiltaksgjennomforingKontaktpersonDbo( navIdent = NavAnsattFixture.ansatt1.navIdent, navEnheter = listOf(NavAnsattFixture.ansatt1.hovedenhet), beskrivelse = "hei hei kontaktperson", ), TiltaksgjennomforingKontaktpersonDbo( navIdent = NavAnsattFixture.ansatt2.navIdent, navEnheter = listOf(NavAnsattFixture.ansatt2.hovedenhet), beskrivelse = null, ), ), ) tiltaksgjennomforinger.upsert(gjennomforing) val result = tiltaksgjennomforinger.get(gjennomforing.id) result?.kontaktpersoner shouldContainExactlyInAnyOrder listOf( TiltaksgjennomforingKontaktperson( navIdent = NavIdent("DD1"), navn = "Donald Duck", mobilnummer = "12345678", epost = "[email protected]", navEnheter = listOf("2990"), hovedenhet = "2990", beskrivelse = "hei hei kontaktperson", ), TiltaksgjennomforingKontaktperson( navIdent = NavIdent("DD2"), navn = "Dolly Duck", mobilnummer = "48243214", epost = "[email protected]", navEnheter = listOf("2990"), hovedenhet = "2990", beskrivelse = null, ), ) val gjennomforingFjernetKontaktperson = gjennomforing.copy( kontaktpersoner = listOf( TiltaksgjennomforingKontaktpersonDbo( navIdent = NavAnsattFixture.ansatt1.navIdent, navEnheter = listOf(NavAnsattFixture.ansatt1.hovedenhet), beskrivelse = null, ), ), ) tiltaksgjennomforinger.upsert(gjennomforingFjernetKontaktperson) val oppdatertResult = tiltaksgjennomforinger.get(gjennomforingFjernetKontaktperson.id) oppdatertResult?.kontaktpersoner shouldBe listOf( TiltaksgjennomforingKontaktperson( navIdent = NavIdent("DD1"), navn = "Donald Duck", mobilnummer = "12345678", epost = "[email protected]", navEnheter = listOf("2990"), hovedenhet = "2990", beskrivelse = null, ), ) } test("update sanity_id") { val id = UUID.randomUUID() tiltaksgjennomforinger.upsert(Oppfolging1) tiltaksgjennomforinger.updateSanityTiltaksgjennomforingId(Oppfolging1.id, id) tiltaksgjennomforinger.get(Oppfolging1.id).should { it!!.sanityId.shouldBe(id) } } test("virksomhet_kontaktperson") { val virksomhetRepository = VirksomhetRepository(database.db) virksomhetRepository.upsert( VirksomhetDto( organisasjonsnummer = "999888777", navn = "Rema 2000", postnummer = null, poststed = null, ), ) val thomas = VirksomhetKontaktperson( navn = "Thomas", telefon = "22222222", epost = "[email protected]", id = UUID.randomUUID(), organisasjonsnummer = "999888777", beskrivelse = "beskrivelse", ) val jens = VirksomhetKontaktperson( navn = "Jens", telefon = "22222224", epost = "[email protected]", id = UUID.randomUUID(), organisasjonsnummer = "999888777", beskrivelse = "beskrivelse2", ) virksomhetRepository.upsertKontaktperson(thomas) virksomhetRepository.upsertKontaktperson(jens) val gjennomforing = Oppfolging1.copy(arrangorKontaktpersoner = listOf(thomas.id)) tiltaksgjennomforinger.upsert(gjennomforing) tiltaksgjennomforinger.get(gjennomforing.id).should { it!!.arrangor.kontaktpersoner shouldContainExactly listOf(thomas) } tiltaksgjennomforinger.upsert(gjennomforing.copy(arrangorKontaktpersoner = emptyList())) tiltaksgjennomforinger.get(gjennomforing.id).should { it!!.arrangor.kontaktpersoner shouldHaveSize 0 } tiltaksgjennomforinger.upsert(gjennomforing.copy(arrangorKontaktpersoner = listOf(thomas.id, jens.id))) tiltaksgjennomforinger.get(gjennomforing.id).should { it!!.arrangor.kontaktpersoner shouldContainExactlyInAnyOrder listOf(thomas, jens) } } test("getUpdatedAt") { tiltaksgjennomforinger.upsert(Oppfolging1) val updatedAt = tiltaksgjennomforinger.getUpdatedAt(Oppfolging1.id)!! tiltaksgjennomforinger.upsert(Oppfolging1) tiltaksgjennomforinger.getUpdatedAt(Oppfolging1.id).should { it!! shouldNotBeBefore updatedAt } } } context("skal migreres") { test("skal migreres henter kun der tiltakstypen skal_migreres er true") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) Query("update tiltakstype set skal_migreres = true where id = '${Oppfolging1.tiltakstypeId}'") .asUpdate.let { database.db.run(it) } tiltaksgjennomforinger.upsert(Oppfolging1) tiltaksgjennomforinger.upsert(Arbeidstrening1) tiltaksgjennomforinger.getAll(skalMigreres = true).should { it.first shouldBe 1 it.second[0].id shouldBe Oppfolging1.id } } } test("get by opphav") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) tiltaksgjennomforinger.upsert(Oppfolging1) tiltaksgjennomforinger.setOpphav(Oppfolging1.id, ArenaMigrering.Opphav.ARENA) tiltaksgjennomforinger.upsert(Arbeidstrening1) tiltaksgjennomforinger.getAll(opphav = null).should { it.first shouldBe 2 } tiltaksgjennomforinger.getAll(opphav = ArenaMigrering.Opphav.ARENA).should { it.first shouldBe 1 it.second[0].id shouldBe Oppfolging1.id } tiltaksgjennomforinger.getAll(opphav = ArenaMigrering.Opphav.MR_ADMIN_FLATE).should { it.first shouldBe 1 it.second[0].id shouldBe Arbeidstrening1.id } } context("Filtrer på avtale") { test("Kun gjennomforinger tilhørende avtale blir tatt med") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) tiltaksgjennomforinger.upsert( Oppfolging1.copy( avtaleId = oppfolging.id, ), ) val result = tiltaksgjennomforinger.getAll( avtaleId = oppfolging.id, ) .second result shouldHaveSize 1 result.first().id shouldBe Oppfolging1.id } } context("Filtrer på arrangør") { test("Kun gjennomføringer tilhørende arrangør blir tatt med") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) tiltaksgjennomforinger.upsert( Oppfolging1.copy( arrangorOrganisasjonsnummer = "111111111", ), ) tiltaksgjennomforinger.upsert( Oppfolging2.copy( arrangorOrganisasjonsnummer = "999999999", ), ) tiltaksgjennomforinger.getAll( arrangorOrgnr = listOf("111111111"), ).should { it.second.size shouldBe 1 it.second[0].id shouldBe Oppfolging1.id } tiltaksgjennomforinger.getAll( arrangorOrgnr = listOf("999999999"), ).should { it.second.size shouldBe 1 it.second[0].id shouldBe Oppfolging2.id } } } context("Cutoffdato") { test("Gamle tiltaksgjennomføringer blir ikke tatt med") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) tiltaksgjennomforinger.upsert( Oppfolging1.copy( sluttDato = LocalDate.of(2023, 12, 31), ), ) tiltaksgjennomforinger.upsert( Oppfolging1.copy( id = UUID.randomUUID(), sluttDato = LocalDate.of(2023, 6, 29), ), ) tiltaksgjennomforinger.upsert( Oppfolging1.copy( id = UUID.randomUUID(), sluttDato = LocalDate.of(2022, 12, 31), ), ) val result = tiltaksgjennomforinger.getAll().second result shouldHaveSize 2 } test("Tiltaksgjennomføringer med sluttdato som er null blir tatt med") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) tiltaksgjennomforinger.upsert(Oppfolging1) tiltaksgjennomforinger.upsert( Oppfolging1.copy( id = UUID.randomUUID(), sluttDato = null, ), ) tiltaksgjennomforinger.getAll() .second shouldHaveSize 2 } } context("Tiltaksgjennomforingadministrator") { test("Administratorer crud") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val gjennomforing = Oppfolging1.copy( administratorer = listOf(NavAnsattFixture.ansatt1.navIdent), ) tiltaksgjennomforinger.upsert(gjennomforing) tiltaksgjennomforinger.get(gjennomforing.id).should { it!!.administratorer.shouldContainExactlyInAnyOrder( TiltaksgjennomforingAdminDto.Administrator( navIdent = NavAnsattFixture.ansatt1.navIdent, navn = "Donald Duck", ), ) } database.assertThat("tiltaksgjennomforing_administrator").hasNumberOfRows(1) } } context("Hente tiltaksgjennomføringer som nærmer seg sluttdato") { test("Skal hente gjennomføringer som er 14, 7 eller 1 dag til sluttdato") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val oppfolging14Dager = Oppfolging1.copy( id = UUID.randomUUID(), sluttDato = LocalDate.of(2023, 5, 30), administratorer = listOf(NavAnsattFixture.ansatt1.navIdent), ) val oppfolging7Dager = Oppfolging1.copy( id = UUID.randomUUID(), sluttDato = LocalDate.of(2023, 5, 23), ) val oppfolging1Dager = Oppfolging1.copy( id = UUID.randomUUID(), sluttDato = LocalDate.of(2023, 5, 17), ) val oppfolging10Dager = Oppfolging1.copy( id = UUID.randomUUID(), sluttDato = LocalDate.of(2023, 5, 26), ) tiltaksgjennomforinger.upsert(oppfolging14Dager) tiltaksgjennomforinger.upsert(oppfolging7Dager) tiltaksgjennomforinger.upsert(oppfolging1Dager) tiltaksgjennomforinger.upsert(oppfolging10Dager) val result = tiltaksgjennomforinger.getAllGjennomforingerSomNarmerSegSluttdato( currentDate = LocalDate.of( 2023, 5, 16, ), ) result.map { Pair(it.id, it.administratorer) } shouldContainExactlyInAnyOrder listOf( Pair(oppfolging14Dager.id, listOf(NavIdent("DD1"))), Pair(oppfolging7Dager.id, listOf()), Pair(oppfolging1Dager.id, listOf()), ) } } context("Filtrering på tiltaksgjennomforingstatus") { val dagensDato = LocalDate.of(2023, 2, 1) val tiltaksgjennomforingAktiv = Arbeidstrening1 val tiltaksgjennomforingAvsluttetStatus = ArenaOppfolging1.copy( id = UUID.randomUUID(), avslutningsstatus = Avslutningsstatus.AVSLUTTET, ) val tiltaksgjennomforingAvsluttetDato = ArenaOppfolging1.copy( id = UUID.randomUUID(), avslutningsstatus = Avslutningsstatus.IKKE_AVSLUTTET, sluttDato = LocalDate.of(2023, 1, 31), ) val tiltaksgjennomforingAvbrutt = ArenaOppfolging1.copy( id = UUID.randomUUID(), avslutningsstatus = Avslutningsstatus.AVBRUTT, ) val tiltaksgjennomforingAvlyst = ArenaOppfolging1.copy( id = UUID.randomUUID(), avslutningsstatus = Avslutningsstatus.AVLYST, ) val tiltaksgjennomforingPlanlagt = ArenaOppfolging1.copy( id = UUID.randomUUID(), avslutningsstatus = Avslutningsstatus.IKKE_AVSLUTTET, startDato = LocalDate.of(2023, 2, 2), ) beforeAny { val tiltaksgjennomforingRepository = TiltaksgjennomforingRepository(database.db) tiltaksgjennomforingRepository.upsert(tiltaksgjennomforingAktiv) tiltaksgjennomforingRepository.upsertArenaTiltaksgjennomforing(tiltaksgjennomforingAvsluttetStatus) tiltaksgjennomforingRepository.upsertArenaTiltaksgjennomforing(tiltaksgjennomforingAvsluttetDato) tiltaksgjennomforingRepository.upsertArenaTiltaksgjennomforing(tiltaksgjennomforingAvbrutt) tiltaksgjennomforingRepository.upsertArenaTiltaksgjennomforing(tiltaksgjennomforingPlanlagt) tiltaksgjennomforingRepository.upsertArenaTiltaksgjennomforing(tiltaksgjennomforingAvlyst) } test("filtrer på avbrutt") { val tiltaksgjennomforingRepository = TiltaksgjennomforingRepository(database.db) val result = tiltaksgjennomforingRepository.getAll( dagensDato = dagensDato, statuser = listOf(Tiltaksgjennomforingsstatus.AVBRUTT), ) result.second shouldHaveSize 1 result.second[0].id shouldBe tiltaksgjennomforingAvbrutt.id } test("filtrer på avsluttet") { val tiltaksgjennomforingRepository = TiltaksgjennomforingRepository(database.db) val result = tiltaksgjennomforingRepository.getAll( dagensDato = dagensDato, statuser = listOf(Tiltaksgjennomforingsstatus.AVSLUTTET), ) result.second shouldHaveSize 2 result.second.map { it.id } .shouldContainAll(tiltaksgjennomforingAvsluttetDato.id, tiltaksgjennomforingAvsluttetStatus.id) } test("filtrer på gjennomføres") { val tiltaksgjennomforingRepository = TiltaksgjennomforingRepository(database.db) val result = tiltaksgjennomforingRepository.getAll( statuser = listOf(Tiltaksgjennomforingsstatus.GJENNOMFORES), dagensDato = dagensDato, ) result.second shouldHaveSize 1 result.second[0].id shouldBe tiltaksgjennomforingAktiv.id } test("filtrer på avlyst") { val tiltaksgjennomforingRepository = TiltaksgjennomforingRepository(database.db) val result = tiltaksgjennomforingRepository.getAll( statuser = listOf(Tiltaksgjennomforingsstatus.AVLYST), dagensDato = dagensDato, ) result.second shouldHaveSize 1 result.second[0].id shouldBe tiltaksgjennomforingAvlyst.id } test("filtrer på åpent for innsøk") { val tiltaksgjennomforingRepository = TiltaksgjennomforingRepository(database.db) val result = tiltaksgjennomforingRepository.getAll( statuser = listOf(Tiltaksgjennomforingsstatus.PLANLAGT), dagensDato = dagensDato, ) result.second shouldHaveSize 1 result.second[0].id shouldBe tiltaksgjennomforingPlanlagt.id } } context("filtrering av tiltaksgjennomføringer") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val navEnheter = NavEnhetRepository(database.db) test("filtrer på nav_enhet") { navEnheter.upsert( NavEnhetDbo( navn = "Navn1", enhetsnummer = "1", status = NavEnhetStatus.AKTIV, type = Norg2Type.LOKAL, overordnetEnhet = null, ), ).shouldBeRight() navEnheter.upsert( NavEnhetDbo( navn = "Navn2", enhetsnummer = "2", status = NavEnhetStatus.AKTIV, type = Norg2Type.LOKAL, overordnetEnhet = null, ), ).shouldBeRight() val tg1 = Oppfolging1.copy(id = UUID.randomUUID(), navEnheter = listOf("1")) tiltaksgjennomforinger.upsert(tg1) val tg2 = Oppfolging1.copy(id = UUID.randomUUID()) tiltaksgjennomforinger.upsert(tg2) Query("update tiltaksgjennomforing set arena_ansvarlig_enhet = '1' where id = '${tg2.id}'") .asUpdate .let { database.db.run(it) } val tg3 = Oppfolging1.copy(id = UUID.randomUUID(), navEnheter = listOf("2")) tiltaksgjennomforinger.upsert(tg3) val tg4 = Oppfolging1.copy(id = UUID.randomUUID(), navEnheter = listOf("1", "2")) tiltaksgjennomforinger.upsert(tg4) tiltaksgjennomforinger.getAll(navEnheter = listOf("1")).should { it.first shouldBe 3 it.second.map { tg -> tg.id } shouldContainAll listOf(tg1.id, tg2.id, tg4.id) } } test("filtrer på nav_region") { navEnheter.upsert( NavEnhetDbo( navn = "NavRegion", enhetsnummer = "0100", status = NavEnhetStatus.AKTIV, type = Norg2Type.FYLKE, overordnetEnhet = null, ), ).shouldBeRight() navEnheter.upsert( NavEnhetDbo( navn = "Navn1", enhetsnummer = "0101", status = NavEnhetStatus.AKTIV, type = Norg2Type.LOKAL, overordnetEnhet = null, ), ).shouldBeRight() navEnheter.upsert( NavEnhetDbo( navn = "Navn2", enhetsnummer = "0102", status = NavEnhetStatus.AKTIV, type = Norg2Type.LOKAL, overordnetEnhet = "0100", ), ).shouldBeRight() val tg1 = Oppfolging1.copy(id = UUID.randomUUID(), navEnheter = listOf("0101"), navRegion = "2990") tiltaksgjennomforinger.upsert(tg1) val tg2 = Oppfolging1.copy(id = UUID.randomUUID()) tiltaksgjennomforinger.upsert(tg2) Query("update tiltaksgjennomforing set arena_ansvarlig_enhet = '0101' where id = '${tg2.id}'") .asUpdate .let { database.db.run(it) } val tg3 = Oppfolging1.copy(id = UUID.randomUUID(), navEnheter = listOf("0102"), navRegion = "0100") tiltaksgjennomforinger.upsert(tg3) val tg4 = Oppfolging1.copy(id = UUID.randomUUID()) tiltaksgjennomforinger.upsert(tg4) Query("update tiltaksgjennomforing set arena_ansvarlig_enhet = '0102' where id = '${tg4.id}'") .asUpdate .let { database.db.run(it) } tiltaksgjennomforinger.getAll(navRegioner = listOf("0100")) .should { it.second.map { tg -> tg.id } shouldContainExactlyInAnyOrder listOf(tg3.id, tg4.id) } } test("administrator") { val tg1 = Oppfolging1.copy( id = UUID.randomUUID(), administratorer = listOf(NavAnsattFixture.ansatt1.navIdent), ) val tg2 = Oppfolging1.copy( id = UUID.randomUUID(), administratorer = listOf(NavAnsattFixture.ansatt1.navIdent, NavAnsattFixture.ansatt2.navIdent), ) tiltaksgjennomforinger.upsert(tg1) tiltaksgjennomforinger.upsert(tg2) tiltaksgjennomforinger.getAll(administratorNavIdent = NavAnsattFixture.ansatt1.navIdent).should { it.first shouldBe 2 it.second.map { tg -> tg.id } shouldContainAll listOf(tg1.id, tg2.id) } tiltaksgjennomforinger.getAll(administratorNavIdent = NavAnsattFixture.ansatt2.navIdent).should { it.first shouldBe 1 it.second.map { tg -> tg.id } shouldContainAll listOf(tg2.id) } } } context("pagination") { beforeAny { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) (1..105).forEach { tiltaksgjennomforinger.upsert( Oppfolging1.copy( id = UUID.randomUUID(), navn = "Tiltak - $it", tiltakstypeId = TiltakstypeFixtures.Oppfolging.id, arrangorOrganisasjonsnummer = "123456789", startDato = LocalDate.of(2022, 1, 1), apentForInnsok = true, oppstart = TiltaksgjennomforingOppstartstype.FELLES, stedForGjennomforing = "0139 Oslo", ), ) } } test("default pagination gets first 50 tiltak") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val (totalCount, items) = tiltaksgjennomforinger.getAll() items.size shouldBe DEFAULT_PAGINATION_LIMIT items.first().navn shouldBe "Tiltak - 1" items.last().navn shouldBe "Tiltak - 49" totalCount shouldBe 105 } test("pagination with page 4 and size 20 should give tiltak with id 59-76") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val (totalCount, items) = tiltaksgjennomforinger.getAll( PaginationParams( 4, 20, ), ) items.size shouldBe 20 items.first().navn shouldBe "Tiltak - 59" items.last().navn shouldBe "Tiltak - 76" totalCount shouldBe 105 } test("pagination with page 3 default size should give tiltak with id 95-99") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val (totalCount, items) = tiltaksgjennomforinger.getAll( PaginationParams( 3, ), ) items.size shouldBe 5 items.first().navn shouldBe "Tiltak - 95" items.last().navn shouldBe "Tiltak - 99" totalCount shouldBe 105 } test("pagination with default page and size 200 should give tiltak with id 1-105") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val (totalCount, items) = tiltaksgjennomforinger.getAll( PaginationParams( nullableLimit = 200, ), ) items.size shouldBe 105 items.first().navn shouldBe "Tiltak - 1" items.last().navn shouldBe "Tiltak - 99" totalCount shouldBe 105 } } test("faneinnhold") { val faneinnhold = Json.decodeFromString<Faneinnhold>( """ { "forHvem": [{ "_key": "edcad230384e", "markDefs": [], "children": [ { "marks": [], "text": "Oppl\u00e6ringen er beregnet p\u00e5 arbeidss\u00f8kere som \u00f8nsker og er egnet til \u00e5 ta arbeid som maskinf\u00f8rer. Deltakerne b\u00f8r ha f\u00f8rerkort kl. B.", "_key": "0e5849bf79a70", "_type": "span" } ], "_type": "block", "style": "normal" }] } """, ) val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val gjennomforing = Oppfolging1.copy( id = UUID.randomUUID(), faneinnhold = faneinnhold, ) tiltaksgjennomforinger.upsert(gjennomforing) tiltaksgjennomforinger.get(gjennomforing.id).should { it!!.faneinnhold!!.forHvem!![0] shouldBe faneinnhold.forHvem!![0] } } test("Tilgjengelig for alle må settes eksplisitt") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val gjennomforing = Oppfolging1.copy(id = UUID.randomUUID()) tiltaksgjennomforinger.upsert(gjennomforing) tiltaksgjennomforinger.get(gjennomforing.id)?.publisert shouldBe false tiltaksgjennomforinger.setPublisert(gjennomforing.id, true) tiltaksgjennomforinger.get(gjennomforing.id)?.publisert shouldBe true } test("skal vises til veileder basert til tilgjengelighet og avslutningsstatus") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val gjennomforing = Oppfolging1.copy(id = UUID.randomUUID()) tiltaksgjennomforinger.upsert(gjennomforing) tiltaksgjennomforinger.setAvslutningsstatus(gjennomforing.id, Avslutningsstatus.AVSLUTTET) tiltaksgjennomforinger.setPublisert(gjennomforing.id, false) tiltaksgjennomforinger.get(gjennomforing.id)?.publisertForAlle shouldBe false tiltaksgjennomforinger.setPublisert(gjennomforing.id, true) tiltaksgjennomforinger.get(gjennomforing.id)?.publisertForAlle shouldBe false tiltaksgjennomforinger.setAvslutningsstatus(gjennomforing.id, Avslutningsstatus.IKKE_AVSLUTTET) tiltaksgjennomforinger.get(gjennomforing.id)?.publisertForAlle shouldBe true } test("Henting av arena-ansvarlig-enhet skal ikke krasje hvis arena-ansvarlig-enhet ikke eksisterer i nav-enhet-tabellen") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) tiltaksgjennomforinger.upsertArenaTiltaksgjennomforing(ArenaOppfolging1.copy(arenaAnsvarligEnhet = "9999")) val gjennomforing = tiltaksgjennomforinger.get(ArenaOppfolging1.id) gjennomforing.shouldNotBeNull() gjennomforing.should { it.arenaAnsvarligEnhet shouldBe null } } context("getAllVeilederflateTiltaksgjennomforing") { val tiltaksgjennomforinger = TiltaksgjennomforingRepository(database.db) val oppfolgingSanityId = UUID.randomUUID() val arbeidstreningSanityId = UUID.randomUUID() beforeEach { Query("update tiltakstype set skal_migreres = true") .asUpdate .let { database.db.run(it) } Query("update tiltakstype set sanity_id = '$oppfolgingSanityId' where id = '${TiltakstypeFixtures.Oppfolging.id}'") .asUpdate .let { database.db.run(it) } Query("update tiltakstype set innsatsgruppe = '${Innsatsgruppe.STANDARD_INNSATS}' where id = '${TiltakstypeFixtures.Oppfolging.id}'") .asUpdate .let { database.db.run(it) } Query("update tiltakstype set sanity_id = '$arbeidstreningSanityId' where id = '${TiltakstypeFixtures.Arbeidstrening.id}'") .asUpdate .let { database.db.run(it) } Query("update tiltakstype set innsatsgruppe = '${Innsatsgruppe.STANDARD_INNSATS}' where id = '${TiltakstypeFixtures.Arbeidstrening.id}'") .asUpdate .let { database.db.run(it) } tiltaksgjennomforinger.upsert(Oppfolging1.copy(navEnheter = listOf("2990"))) tiltaksgjennomforinger.setPublisert(Oppfolging1.id, true) tiltaksgjennomforinger.upsert(Arbeidstrening1.copy(navEnheter = listOf("2990"))) tiltaksgjennomforinger.setPublisert(Arbeidstrening1.id, true) } test("skal filtrere basert på om tiltaket er publisert") { tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 2 tiltaksgjennomforinger.setPublisert(Oppfolging1.id, false) tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 1 tiltaksgjennomforinger.setPublisert(Arbeidstrening1.id, false) tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 0 } test("skal bare returnere tiltak markert med skal_migreres") { tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 2 Query("update tiltakstype set skal_migreres = false where id = '${TiltakstypeFixtures.Oppfolging.id}'") .asUpdate .let { database.db.run(it) } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 1 Query("update tiltakstype set skal_migreres = false where id = '${TiltakstypeFixtures.Arbeidstrening.id}'") .asUpdate .let { database.db.run(it) } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 0 } test("skal filtrere basert på innsatsgruppe") { Query("update tiltakstype set innsatsgruppe = '${Innsatsgruppe.SPESIELT_TILPASSET_INNSATS}' where id = '${TiltakstypeFixtures.Oppfolging.id}'") .asUpdate .let { database.db.run(it) } Query("update tiltakstype set innsatsgruppe = '${Innsatsgruppe.STANDARD_INNSATS}' where id = '${TiltakstypeFixtures.Arbeidstrening.id}'") .asUpdate .let { database.db.run(it) } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(), brukersEnheter = listOf("2990"), ) shouldHaveSize 0 tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ).should { it shouldHaveSize 1 it[0].navn shouldBe Arbeidstrening1.navn } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.SPESIELT_TILPASSET_INNSATS), brukersEnheter = listOf("2990"), ).should { it shouldHaveSize 1 it[0].navn shouldBe Oppfolging1.navn } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS, Innsatsgruppe.SPESIELT_TILPASSET_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 2 } test("skal filtrere på brukers enheter") { val enheter = NavEnhetRepository(database.db) enheter.upsert(NavEnhetFixtures.Oslo) enheter.upsert(NavEnhetFixtures.Innlandet) tiltaksgjennomforinger.upsert(Oppfolging1.copy(navEnheter = listOf("2990", "0400"))) tiltaksgjennomforinger.upsert(Arbeidstrening1.copy(navEnheter = listOf("2990", "0300"))) tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("0400"), ).should { it shouldHaveSize 1 it[0].navn shouldBe Oppfolging1.navn } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("0300"), ).should { it shouldHaveSize 1 it[0].navn shouldBe Arbeidstrening1.navn } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("0400", "0300"), ) shouldHaveSize 2 tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 2 } test("skal filtrere basert på tiltakstype sanity Id") { tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( sanityTiltakstypeIds = null, innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 2 tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( sanityTiltakstypeIds = listOf(oppfolgingSanityId), innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ).should { it shouldHaveSize 1 it[0].navn shouldBe Oppfolging1.navn } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( sanityTiltakstypeIds = listOf(arbeidstreningSanityId), innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ).should { it shouldHaveSize 1 it[0].navn shouldBe Arbeidstrening1.navn } } test("skal filtrere basert fritekst i navn") { tiltaksgjennomforinger.upsert(Oppfolging1.copy(navn = "erik")) tiltaksgjennomforinger.upsert(Arbeidstrening1.copy(navn = "frank")) tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( search = "rik", innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ).should { it shouldHaveSize 1 it[0].navn shouldBe "erik" } } test("skal filtrere basert på apent_for_innsok") { tiltaksgjennomforinger.upsert(Oppfolging1.copy(apentForInnsok = true)) tiltaksgjennomforinger.upsert(Arbeidstrening1.copy(apentForInnsok = false, navEnheter = listOf("2990"))) tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( apentForInnsok = true, innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ).should { it shouldHaveSize 1 it[0].navn shouldBe Oppfolging1.navn } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( apentForInnsok = false, innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ).should { it shouldHaveSize 1 it[0].navn shouldBe Arbeidstrening1.navn } tiltaksgjennomforinger.getAllVeilederflateTiltaksgjennomforing( apentForInnsok = null, innsatsgrupper = listOf(Innsatsgruppe.STANDARD_INNSATS), brukersEnheter = listOf("2990"), ) shouldHaveSize 2 } } })
7
null
1
6
fe8bff93ee98f28ac3f5027aa818cdd1d8093949
51,151
mulighetsrommet
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/globalaccelerator/CfnListener.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.globalaccelerator import io.cloudshiftdev.awscdk.CfnResource import io.cloudshiftdev.awscdk.IInspectable import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.TreeInspector import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.List import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * The `AWS::GlobalAccelerator::Listener` resource is a Global Accelerator resource type that * contains information about how you create a listener to process inbound connections from clients to * an accelerator. * * Connections arrive to assigned static IP addresses on a port, port range, or list of port ranges * that you specify. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.globalaccelerator.*; * CfnListener cfnListener = CfnListener.Builder.create(this, "MyCfnListener") * .acceleratorArn("acceleratorArn") * .portRanges(List.of(PortRangeProperty.builder() * .fromPort(123) * .toPort(123) * .build())) * .protocol("protocol") * // the properties below are optional * .clientAffinity("clientAffinity") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html) */ public open class CfnListener( cdkObject: software.amazon.awscdk.services.globalaccelerator.CfnListener, ) : CfnResource(cdkObject), IInspectable { public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnListenerProps, ) : this(software.amazon.awscdk.services.globalaccelerator.CfnListener(scope.let(CloudshiftdevConstructsConstruct::unwrap), id, props.let(CfnListenerProps::unwrap)) ) public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnListenerProps.Builder.() -> Unit, ) : this(scope, id, CfnListenerProps(props) ) /** * The Amazon Resource Name (ARN) of your accelerator. */ public open fun acceleratorArn(): String = unwrap(this).getAcceleratorArn() /** * The Amazon Resource Name (ARN) of your accelerator. */ public open fun acceleratorArn(`value`: String) { unwrap(this).setAcceleratorArn(`value`) } /** * The ARN of the listener, such as * `arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz` * . */ public open fun attrListenerArn(): String = unwrap(this).getAttrListenerArn() /** * Client affinity lets you direct all requests from a user to the same endpoint, if you have * stateful applications, regardless of the port and protocol of the client request. */ public open fun clientAffinity(): String? = unwrap(this).getClientAffinity() /** * Client affinity lets you direct all requests from a user to the same endpoint, if you have * stateful applications, regardless of the port and protocol of the client request. */ public open fun clientAffinity(`value`: String) { unwrap(this).setClientAffinity(`value`) } /** * Examines the CloudFormation resource and discloses attributes. * * @param inspector tree inspector to collect and process attributes. */ public override fun inspect(inspector: TreeInspector) { unwrap(this).inspect(inspector.let(TreeInspector::unwrap)) } /** * The list of port ranges for the connections from clients to the accelerator. */ public open fun portRanges(): Any = unwrap(this).getPortRanges() /** * The list of port ranges for the connections from clients to the accelerator. */ public open fun portRanges(`value`: IResolvable) { unwrap(this).setPortRanges(`value`.let(IResolvable::unwrap)) } /** * The list of port ranges for the connections from clients to the accelerator. */ public open fun portRanges(`value`: List<Any>) { unwrap(this).setPortRanges(`value`.map{CdkObjectWrappers.unwrap(it)}) } /** * The list of port ranges for the connections from clients to the accelerator. */ public open fun portRanges(vararg `value`: Any): Unit = portRanges(`value`.toList()) /** * The protocol for the connections from clients to the accelerator. */ public open fun protocol(): String = unwrap(this).getProtocol() /** * The protocol for the connections from clients to the accelerator. */ public open fun protocol(`value`: String) { unwrap(this).setProtocol(`value`) } /** * A fluent builder for [io.cloudshiftdev.awscdk.services.globalaccelerator.CfnListener]. */ @CdkDslMarker public interface Builder { /** * The Amazon Resource Name (ARN) of your accelerator. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-acceleratorarn) * @param acceleratorArn The Amazon Resource Name (ARN) of your accelerator. */ public fun acceleratorArn(acceleratorArn: String) /** * Client affinity lets you direct all requests from a user to the same endpoint, if you have * stateful applications, regardless of the port and protocol of the client request. * * Client affinity gives you control over whether to always route each client to the same * specific endpoint. * * AWS Global Accelerator uses a consistent-flow hashing algorithm to choose the optimal * endpoint for a connection. If client affinity is `NONE` , Global Accelerator uses the * "five-tuple" (5-tuple) properties—source IP address, source port, destination IP address, * destination port, and protocol—to select the hash value, and then chooses the best endpoint. * However, with this setting, if someone uses different ports to connect to Global Accelerator, * their connections might not be always routed to the same endpoint because the hash value * changes. * * If you want a given client to always be routed to the same endpoint, set client affinity to * `SOURCE_IP` instead. When you use the `SOURCE_IP` setting, Global Accelerator uses the * "two-tuple" (2-tuple) properties— source (client) IP address and destination IP address—to * select the hash value. * * The default value is `NONE` . * * Default: - "NONE" * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-clientaffinity) * @param clientAffinity Client affinity lets you direct all requests from a user to the same * endpoint, if you have stateful applications, regardless of the port and protocol of the client * request. */ public fun clientAffinity(clientAffinity: String) /** * The list of port ranges for the connections from clients to the accelerator. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-portranges) * @param portRanges The list of port ranges for the connections from clients to the * accelerator. */ public fun portRanges(portRanges: IResolvable) /** * The list of port ranges for the connections from clients to the accelerator. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-portranges) * @param portRanges The list of port ranges for the connections from clients to the * accelerator. */ public fun portRanges(portRanges: List<Any>) /** * The list of port ranges for the connections from clients to the accelerator. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-portranges) * @param portRanges The list of port ranges for the connections from clients to the * accelerator. */ public fun portRanges(vararg portRanges: Any) /** * The protocol for the connections from clients to the accelerator. * * Default: - "TCP" * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-protocol) * @param protocol The protocol for the connections from clients to the accelerator. */ public fun protocol(protocol: String) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.globalaccelerator.CfnListener.Builder = software.amazon.awscdk.services.globalaccelerator.CfnListener.Builder.create(scope, id) /** * The Amazon Resource Name (ARN) of your accelerator. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-acceleratorarn) * @param acceleratorArn The Amazon Resource Name (ARN) of your accelerator. */ override fun acceleratorArn(acceleratorArn: String) { cdkBuilder.acceleratorArn(acceleratorArn) } /** * Client affinity lets you direct all requests from a user to the same endpoint, if you have * stateful applications, regardless of the port and protocol of the client request. * * Client affinity gives you control over whether to always route each client to the same * specific endpoint. * * AWS Global Accelerator uses a consistent-flow hashing algorithm to choose the optimal * endpoint for a connection. If client affinity is `NONE` , Global Accelerator uses the * "five-tuple" (5-tuple) properties—source IP address, source port, destination IP address, * destination port, and protocol—to select the hash value, and then chooses the best endpoint. * However, with this setting, if someone uses different ports to connect to Global Accelerator, * their connections might not be always routed to the same endpoint because the hash value * changes. * * If you want a given client to always be routed to the same endpoint, set client affinity to * `SOURCE_IP` instead. When you use the `SOURCE_IP` setting, Global Accelerator uses the * "two-tuple" (2-tuple) properties— source (client) IP address and destination IP address—to * select the hash value. * * The default value is `NONE` . * * Default: - "NONE" * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-clientaffinity) * @param clientAffinity Client affinity lets you direct all requests from a user to the same * endpoint, if you have stateful applications, regardless of the port and protocol of the client * request. */ override fun clientAffinity(clientAffinity: String) { cdkBuilder.clientAffinity(clientAffinity) } /** * The list of port ranges for the connections from clients to the accelerator. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-portranges) * @param portRanges The list of port ranges for the connections from clients to the * accelerator. */ override fun portRanges(portRanges: IResolvable) { cdkBuilder.portRanges(portRanges.let(IResolvable::unwrap)) } /** * The list of port ranges for the connections from clients to the accelerator. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-portranges) * @param portRanges The list of port ranges for the connections from clients to the * accelerator. */ override fun portRanges(portRanges: List<Any>) { cdkBuilder.portRanges(portRanges.map{CdkObjectWrappers.unwrap(it)}) } /** * The list of port ranges for the connections from clients to the accelerator. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-portranges) * @param portRanges The list of port ranges for the connections from clients to the * accelerator. */ override fun portRanges(vararg portRanges: Any): Unit = portRanges(portRanges.toList()) /** * The protocol for the connections from clients to the accelerator. * * Default: - "TCP" * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-globalaccelerator-listener.html#cfn-globalaccelerator-listener-protocol) * @param protocol The protocol for the connections from clients to the accelerator. */ override fun protocol(protocol: String) { cdkBuilder.protocol(protocol) } public fun build(): software.amazon.awscdk.services.globalaccelerator.CfnListener = cdkBuilder.build() } public companion object { public val CFN_RESOURCE_TYPE_NAME: String = software.amazon.awscdk.services.globalaccelerator.CfnListener.CFN_RESOURCE_TYPE_NAME public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): CfnListener { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return CfnListener(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.globalaccelerator.CfnListener): CfnListener = CfnListener(cdkObject) internal fun unwrap(wrapped: CfnListener): software.amazon.awscdk.services.globalaccelerator.CfnListener = wrapped.cdkObject as software.amazon.awscdk.services.globalaccelerator.CfnListener } /** * A complex type for a range of ports for a listener. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.globalaccelerator.*; * PortRangeProperty portRangeProperty = PortRangeProperty.builder() * .fromPort(123) * .toPort(123) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-globalaccelerator-listener-portrange.html) */ public interface PortRangeProperty { /** * The first port in the range of ports, inclusive. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-globalaccelerator-listener-portrange.html#cfn-globalaccelerator-listener-portrange-fromport) */ public fun fromPort(): Number /** * The last port in the range of ports, inclusive. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-globalaccelerator-listener-portrange.html#cfn-globalaccelerator-listener-portrange-toport) */ public fun toPort(): Number /** * A builder for [PortRangeProperty] */ @CdkDslMarker public interface Builder { /** * @param fromPort The first port in the range of ports, inclusive. */ public fun fromPort(fromPort: Number) /** * @param toPort The last port in the range of ports, inclusive. */ public fun toPort(toPort: Number) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.globalaccelerator.CfnListener.PortRangeProperty.Builder = software.amazon.awscdk.services.globalaccelerator.CfnListener.PortRangeProperty.builder() /** * @param fromPort The first port in the range of ports, inclusive. */ override fun fromPort(fromPort: Number) { cdkBuilder.fromPort(fromPort) } /** * @param toPort The last port in the range of ports, inclusive. */ override fun toPort(toPort: Number) { cdkBuilder.toPort(toPort) } public fun build(): software.amazon.awscdk.services.globalaccelerator.CfnListener.PortRangeProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.globalaccelerator.CfnListener.PortRangeProperty, ) : CdkObject(cdkObject), PortRangeProperty { /** * The first port in the range of ports, inclusive. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-globalaccelerator-listener-portrange.html#cfn-globalaccelerator-listener-portrange-fromport) */ override fun fromPort(): Number = unwrap(this).getFromPort() /** * The last port in the range of ports, inclusive. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-globalaccelerator-listener-portrange.html#cfn-globalaccelerator-listener-portrange-toport) */ override fun toPort(): Number = unwrap(this).getToPort() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): PortRangeProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.globalaccelerator.CfnListener.PortRangeProperty): PortRangeProperty = CdkObjectWrappers.wrap(cdkObject) as? PortRangeProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: PortRangeProperty): software.amazon.awscdk.services.globalaccelerator.CfnListener.PortRangeProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.globalaccelerator.CfnListener.PortRangeProperty } } }
4
null
0
4
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
18,714
kotlin-cdk-wrapper
Apache License 2.0
src/main/kotlin/com/octawizard/domain/usecase/club/AddFieldToClub.kt
octawizard
299,882,247
false
null
package com.octawizard.domain.usecase.club import com.octawizard.domain.model.Club import com.octawizard.domain.model.Field import com.octawizard.domain.model.WallsMaterial import com.octawizard.repository.club.ClubRepository class AddFieldToClub(private val clubRepository: ClubRepository) { operator fun invoke( club: Club, name: String, indoor: Boolean, hasSand: Boolean, wallsMaterial: WallsMaterial, ): Club { val field: Field = clubRepository.addFieldToClub(club.id, name, indoor, hasSand, wallsMaterial) return club.copy(fields = club.fields + field) } }
6
Kotlin
0
0
a1d58d6fe35dda02a8cff27b52d2693ef4881fa4
633
padles-api
Apache License 2.0
app/src/main/java/com/readbeard/openbrewery/app/App.kt
readbeard
395,628,565
false
null
package com.readbeard.openbrewery.app import android.app.Application import dagger.hilt.android.HiltAndroidApp import timber.log.Timber @HiltAndroidApp class App : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } else { // Plant crash/log reporting tool with Timber } } }
5
Kotlin
0
0
43e62f001f24a39df0137a2e88006240c7daf349
408
OpenBrewery
MIT License
android/src/com/android/tools/idea/gradle/project/build/events/AndroidSyncIssueQuickFix.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.project.build.events import com.android.tools.idea.npw.invokeLater import com.android.tools.idea.project.hyperlink.NotificationHyperlink import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.project.Project import java.util.concurrent.CompletableFuture import javax.swing.event.HyperlinkEvent class AndroidSyncIssueQuickFix(private val hyperlink: NotificationHyperlink) : BuildIssueQuickFix { override val id: String get() = hyperlink.url override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { val future = CompletableFuture<Any>() invokeLater { try { val source = PlatformCoreDataKeys.CONTEXT_COMPONENT.getData(dataContext) ?: dataContext hyperlink.executeIfClicked(project, HyperlinkEvent(source, HyperlinkEvent.EventType.ACTIVATED, null, id)) future.complete(null) } catch (e: Exception) { future.completeExceptionally(e) } } return future } }
0
null
220
857
8d22f48a9233679e85e42e8a7ed78bbff2c82ddb
1,767
android
Apache License 2.0
network/src/main/java/androidx/essentials/network/DataStore.kt
kunal26das
282,238,393
false
null
package androidx.essentials.network import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.* import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.asLiveData import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext /** * String key */ @Suppress("UNCHECKED_CAST") inline fun <reified T> preferencesKey(key: String) = when (T::class) { Int::class -> intPreferencesKey(key) Long::class -> longPreferencesKey(key) Float::class -> floatPreferencesKey(key) Double::class -> doublePreferencesKey(key) String::class -> stringPreferencesKey(key) Boolean::class -> booleanPreferencesKey(key) MutableSet::class -> stringPreferencesKey(key) else -> null } as? Preferences.Key<T> inline fun <reified T> Preferences.get(key: String): T? { return preferencesKey<T>(key)?.let { if (contains(it)) get(it) else null } } suspend inline fun <reified T> DataStore<Preferences>.set( key: String, value: T? ) = updateData { it.toMutablePreferences().apply { preferencesKey<T>(key)?.let { when (value) { null -> remove(it) else -> set(it, value) } } } } inline fun <reified T> DataStore<Preferences>.liveData( key: String, coroutineContext: CoroutineContext = EmptyCoroutineContext ) = data.map { it.get<T>(key) }.asLiveData(coroutineContext) inline fun <reified T> DataStore<Preferences>.liveDataOf( key: String, coroutineContext: CoroutineContext = EmptyCoroutineContext ) = lazy { liveData<T>(key, coroutineContext) } inline fun <reified T> DataStore<Preferences>.mutableLiveData( key: String, coroutineContext: CoroutineContext = EmptyCoroutineContext ) = object : MediatorLiveData<T?>() { private val coroutineScope = CoroutineScope(coroutineContext) init { addSource(liveData<T>(key)) { value = it } } override fun setValue(value: T?) { if (value != getValue()) { super.setValue(value) coroutineScope.launch { set<T>(key, value) } } } } inline fun <reified T> DataStore<Preferences>.mutableLiveDataOf( key: String, coroutineContext: CoroutineContext = EmptyCoroutineContext ) = lazy { mutableLiveData<T>(key, coroutineContext) } /** * Enum key */ inline fun <reified T> preferencesKey(key: Enum<*>) = preferencesKey<T>(key.name) inline fun <reified T> Preferences.get(key: Enum<*>) = get<T>(key.name) suspend inline fun <reified T> DataStore<Preferences>.set( key: Enum<*>, value: T? ) = set<T>(key.name, value) inline fun <reified T> DataStore<Preferences>.liveData( key: Enum<*>, coroutineContext: CoroutineContext = EmptyCoroutineContext ) = liveData<T>(key.name, coroutineContext) inline fun <reified T> DataStore<Preferences>.liveDataOf( key: Enum<*>, coroutineContext: CoroutineContext = EmptyCoroutineContext ) = lazy { liveData<T>(key, coroutineContext) } inline fun <reified T> DataStore<Preferences>.mutableLiveData( key: Enum<*>, coroutineContext: CoroutineContext = EmptyCoroutineContext ) = mutableLiveData<T>(key.name, coroutineContext) inline fun <reified T> DataStore<Preferences>.mutableLiveDataOf( key: Enum<*>, coroutineContext: CoroutineContext = EmptyCoroutineContext ) = lazy { mutableLiveData<T>(key, coroutineContext) }
5
Kotlin
0
3
4968a43c341f728c905d3db7a124fd8b6e05041a
3,534
androidx-essentials
Apache License 2.0
core/src/main/kotlin/Cache.kt
cs124-illinois
584,151,809
false
null
@file:Suppress("MatchingDeclarationName") package edu.illinois.cs.cs125.jeed.core import com.github.benmanes.caffeine.cache.Cache import com.github.benmanes.caffeine.cache.Caffeine import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import java.time.Instant const val JEED_DEFAULT_COMPILATION_CACHE_SIZE_MB = 256L @Suppress("TooGenericExceptionCaught") val compilationCacheSizeMB = try { System.getenv("JEED_COMPILATION_CACHE_SIZE")?.toLong() ?: JEED_DEFAULT_COMPILATION_CACHE_SIZE_MB } catch (e: Exception) { logger.warn("Bad value for JEED_COMPILATION_CACHE_SIZE") JEED_DEFAULT_COMPILATION_CACHE_SIZE_MB } const val JEED_DEFAULT_USE_CACHE = false @Suppress("TooGenericExceptionCaught") val useCompilationCache = try { System.getenv("JEED_USE_CACHE")?.toBoolean() ?: JEED_DEFAULT_USE_CACHE } catch (e: Exception) { logger.warn("Bad value for JEED_USE_CACHE") JEED_DEFAULT_USE_CACHE } const val MB_TO_BYTES = 1024 * 1024 val compilationCache: Cache<String, CachedCompilationResults> = Caffeine.newBuilder() .maximumWeight(compilationCacheSizeMB * MB_TO_BYTES) .weigher<String, CachedCompilationResults> { _, cachedCompilationResults -> cachedCompilationResults.fileManager.size } .recordStats() .build() class CachedCompilationResults( val compiled: Instant, val messages: List<CompilationMessage>, val fileManager: JeedFileManager, val compilerName: String, val compilationArguments: CompilationArguments? = null, val kompilationArguments: KompilationArguments? = null, ) object MoreCacheStats { var hits: Int = 0 var misses: Int = 0 } @Suppress("ReturnCount") fun Source.tryCache( compilationArguments: CompilationArguments, started: Instant, compilerName: String, ): CompiledSource? { val useCache = compilationArguments.useCache ?: useCompilationCache if (!useCache) { return null } val cachedResult = compilationCache.getIfPresent(md5) if (cachedResult == null) { MoreCacheStats.misses++ return null } MoreCacheStats.hits++ val cachedCompilationArguments = cachedResult.compilationArguments ?: error( "Cached compilation result missing arguments", ) if (cachedResult.compilerName != compilerName) { return null } if (cachedCompilationArguments != compilationArguments) { return null } val parentClassLoader = compilationArguments.parentClassLoader ?: ClassLoader.getSystemClassLoader() return CompiledSource( this, cachedResult.messages, cachedResult.compiled, Interval(started, Instant.now()), JeedClassLoader(cachedResult.fileManager, parentClassLoader), cachedResult.fileManager, compilerName, true, ) } private val compilationScope = CoroutineScope(Dispatchers.IO) fun CompiledSource.cache(compilationArguments: CompilationArguments) { val useCache = compilationArguments.useCache ?: useCompilationCache if (cached || !useCache) { return } compilationScope.launch { compilationCache.put( source.md5, CachedCompilationResults( compiled, messages, fileManager, compilerName, compilationArguments = compilationArguments, ), ) }.also { if (compilationArguments.waitForCache) { runBlocking { it.join() } } } } @Suppress("ReturnCount") fun Source.tryCache( kompilationArguments: KompilationArguments, started: Instant, compilerName: String, ): CompiledSource? { if (!kompilationArguments.useCache) { return null } val cachedResult = compilationCache.getIfPresent(md5) if (cachedResult == null) { MoreCacheStats.misses++ return null } MoreCacheStats.hits++ val cachedKompilationArguments = cachedResult.kompilationArguments ?: error( "Cached kompilation result missing arguments", ) if (cachedResult.compilerName != compilerName) { return null } if (cachedKompilationArguments != kompilationArguments) { return null } return CompiledSource( this, cachedResult.messages, cachedResult.compiled, Interval(started, Instant.now()), JeedClassLoader(cachedResult.fileManager, kompilationArguments.parentClassLoader), cachedResult.fileManager, compilerName, true, ) } fun CompiledSource.cache(kompilationArguments: KompilationArguments) { if (cached || !kompilationArguments.useCache) { return } compilationScope.launch { compilationCache.put( source.md5, CachedCompilationResults( compiled, messages, fileManager, compilerName, kompilationArguments = kompilationArguments, ), ) }.also { if (kompilationArguments.waitForCache) { runBlocking { it.join() } } } }
4
null
9
2
f18fe112a1d2342317bc52c1010010b92c329a32
5,235
jeed
MIT License
src/main/kotlin/com/bridgecrew/services/checkovScanCommandsService/CheckovScanCommandsService.kt
bridgecrewio
644,310,885
false
{"Kotlin": 295615}
package com.bridgecrew.services.checkovScanCommandsService import com.bridgecrew.listeners.CheckovSettingsListener import com.bridgecrew.settings.PrismaSettingsState import com.bridgecrew.utils.FULL_SCAN_EXCLUDED_PATHS import com.bridgecrew.utils.getGitIgnoreValues import com.bridgecrew.utils.getRepoName import com.bridgecrew.utils.isWindows import com.intellij.openapi.project.Project import org.apache.commons.lang3.StringUtils abstract class CheckovScanCommandsService(val project: Project) { protected val settings = PrismaSettingsState().getInstance() private var gitRepo = getRepoName() fun getExecCommandForSingleFile(filePaths: List<String>, outputFilePath: String): ArrayList<String> { val cmds = ArrayList<String>() cmds.addAll(getCheckovRunningCommandByServiceType(outputFilePath)) cmds.addAll(getCheckovCliArgsForExecCommand(getOutputFilePath(outputFilePath))) filePaths.forEach{ path -> cmds.add("-f"); cmds.add(getFilePath(path)) } return cmds } fun getExecCommandsForRepositoryByFramework(framework: String, outputFilePath: String): ArrayList<String> { val baseCmds = ArrayList<String>() baseCmds.addAll(getCheckovRunningCommandByServiceType(outputFilePath)) baseCmds.add("-d") baseCmds.add(getDirectory()) baseCmds.addAll(getExcludePathCommand()) val cmdByFramework = arrayListOf<String>() cmdByFramework.addAll(baseCmds) cmdByFramework.addAll(getCheckovCliArgsForExecCommand(getOutputFilePath(outputFilePath))) cmdByFramework.addAll(getCheckovNoFailOnCrash(framework)) cmdByFramework.add("--framework") cmdByFramework.add(framework) return cmdByFramework } private fun getCheckovNoFailOnCrash(framework: String): ArrayList<String> { val command = ArrayList<String>() if (framework === "sast") { command.add("--no-fail-on-crash") } return command } private fun getCheckovCliArgsForExecCommand(outputFilePath: String): ArrayList<String> { val apiToken = settings?.getApiKey() if (apiToken.isNullOrEmpty()) { project.messageBus.syncPublisher(CheckovSettingsListener.SETTINGS_TOPIC).settingsUpdated() throw Exception("Wasn't able to get api token\n" + "Please insert an Api Token to continue") } val command = arrayListOf("-s", "--bc-api-key", apiToken, "--repo-id", gitRepo, "--quiet", "-o", "cli", "-o", "json", "--output-file-path", "console,$outputFilePath") command.addAll(getCertParams()) val prismaUrl = settings?.prismaURL if (!prismaUrl.isNullOrEmpty()) { command.addAll(arrayListOf("--prisma-api-url", prismaUrl)) } return command } private fun getExcludePathCommand(): ArrayList<String> { val cmds = ArrayList<String>() val excludedPaths = (getGitIgnoreValues(project) + FULL_SCAN_EXCLUDED_PATHS).distinct() for (excludePath in excludedPaths) { cmds.add("--skip-path") cmds.add(getNormalizedExcludePath(excludePath)) } return cmds } private fun getNormalizedExcludePath(excludePath: String): String { if (isWindows()) { var winExcludePath = StringUtils.removeEnd(excludePath, "\\") winExcludePath = StringUtils.removeStart(winExcludePath, "**/") winExcludePath = StringUtils.removeStart(winExcludePath, "*") return winExcludePath } return StringUtils.removeEnd(excludePath, "/") } private fun getCertParams(): ArrayList<String> { val cmds = ArrayList<String>() val certPath = settings?.certificate if (!certPath.isNullOrEmpty()) { cmds.add("--ca-certificate") cmds.add(getCertPath()) return cmds } return cmds } abstract fun getCheckovRunningCommandByServiceType(outputFilePath: String): ArrayList<String> abstract fun getDirectory(): String abstract fun getFilePath(originalFilePath: String): String abstract fun getCertPath(): String abstract fun getOutputFilePath(outputFilePath: String): String }
13
Kotlin
0
1
ebdfce512f385af03aa35e56f3d8ec89335bc18e
4,273
prisma-cloud-jetbrains-ide
Apache License 2.0
app/src/main/java/com/kyberswap/android/data/api/home/SwapApi.kt
zachwylde00
211,432,543
true
{"Kotlin": 1457144, "Java": 42326, "Ruby": 5070}
package com.kyberswap.android.data.api.home import com.kyberswap.android.data.api.cap.CapEntity import com.kyberswap.android.data.api.gas.GasPriceEntity import com.kyberswap.android.data.api.rate.MarketRateEntity import com.kyberswap.android.domain.model.EstimateAmount import io.reactivex.Single import retrofit2.http.GET import retrofit2.http.Query interface SwapApi { @GET("rate") fun getRate(): Single<MarketRateEntity> @GET("gasPrice") fun getGasPrice(): Single<GasPriceEntity> @GET("users") fun getCap( @Query("address") address: String? ): Single<CapEntity> @GET("sourceAmount") fun sourceAmount( @Query("source") source: String, @Query("dest") dest: String, @Query("destAmount") destAmount: String ): Single<EstimateAmount> }
1
Kotlin
0
0
ddf69ff4a6aa26c54e938fd84d496b5792e352e5
810
site.live.remixed-solidity-network-android-app
MIT License
diktat-rules/src/test/kotlin/com/saveourtool/diktat/util/TestUtils.kt
saveourtool
275,879,956
false
null
/** * Utility classes and methods for tests */ package com.saveourtool.diktat.util import com.saveourtool.diktat.api.DiktatErrorEmitter import com.saveourtool.diktat.api.DiktatRule import com.saveourtool.diktat.api.DiktatRuleSet import com.saveourtool.diktat.ktlint.check import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.intellij.lang.annotations.Language import org.jetbrains.kotlin.com.intellij.lang.ASTNode import java.io.Reader import java.util.concurrent.atomic.AtomicInteger import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind.EXACTLY_ONCE import kotlin.contracts.contract internal const val TEST_FILE_NAME = "TestFileName.kt" private val debuggerPromptPrefixes: Array<out String> = arrayOf( "Listening for transport dt_socket at address: ", "Listening for transport dt_shmem at address: ", ) /** * Casts a nullable value to a non-`null` one, similarly to the `!!` * operator. * * @param lazyFailureMessage the message to evaluate in case of a failure. * @return a non-`null` value. */ @OptIn(ExperimentalContracts::class) internal fun <T : Any> T?.assertNotNull(lazyFailureMessage: () -> String = { "Expecting actual not to be null" }): T { contract { returns() implies (this@assertNotNull != null) } return this ?: fail(lazyFailureMessage()) } /** * Calls the [block] callback giving it a sequence of all the lines in this file * and closes the reader once the processing is complete. * * If [filterDebuggerPrompt] is `true`, the JVM debugger prompt is filtered out * from the sequence of lines before it is consumed by [block]. * * If [filterDebuggerPrompt] is `false`, this function behaves exactly as the * overloaded function from the standard library. * * @param filterDebuggerPrompt whether the JVM debugger prompt should be * filtered out. * @param block the callback which consumes the lines produced by this [Reader]. * @return the value returned by [block]. */ @OptIn(ExperimentalContracts::class) internal fun <T> Reader.useLines( filterDebuggerPrompt: Boolean, block: (Sequence<String>) -> T, ): T { contract { callsInPlace(block, EXACTLY_ONCE) } return when { filterDebuggerPrompt -> { /* * Transform the line consumer. */ { lines -> lines.filterNot(String::isDebuggerPrompt).let(block) } } else -> block }.let(this::useLines) } private fun String.isDebuggerPrompt(printIfTrue: Boolean = true): Boolean { val isDebuggerPrompt = debuggerPromptPrefixes.any { prefix -> this.startsWith(prefix) } if (isDebuggerPrompt && printIfTrue) { /* * Print the prompt to the standard out, * so that the IDE can attach to the debugger. */ @Suppress("DEBUG_PRINT") println(this) } return isDebuggerPrompt } /** * This utility function lets you run arbitrary code on every node of given [code]. * It also provides you with counter which can be incremented inside [applyToNode] and then will be compared to [expectedAsserts]. * This allows you to keep track of how many assertions have actually been run on your code during tests. * * @param code * @param expectedAsserts Number of expected times of assert invocation * @param applyToNode Function to be called on each AST node, should increment counter if assert is called */ @Suppress("TYPE_ALIAS") internal fun applyToCode(@Language("kotlin") code: String, expectedAsserts: Int, applyToNode: (node: ASTNode, counter: AtomicInteger) -> Unit ) { val counter = AtomicInteger(0) check( ruleSetSupplier = { DiktatRuleSet(listOf(object : DiktatRule { override val id: String get() = "astnode-utils-test" override fun invoke(node: ASTNode, autoCorrect: Boolean, emitter: DiktatErrorEmitter) { applyToNode(node, counter) } })) }, text = code, ) assertThat(counter.get()) .`as`("Number of expected asserts") .isEqualTo(expectedAsserts) }
149
null
39
535
9e73d811d9fd9900af5917ba82ddeed0177ac52e
4,278
diktat
MIT License
compiler/frontend.java/src/org/jetbrains/kotlin/synthetic/JavaSyntheticPropertiesScope.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.synthetic import com.intellij.util.SmartList import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.PropertyGetterDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.PropertySetterDescriptorImpl import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.JetScope import org.jetbrains.kotlin.resolve.scopes.JetScopeImpl import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.isBoolean import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeFirstWord import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeSmart import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.addIfNotNull import java.util.ArrayList import java.util.HashMap import java.util.HashSet import kotlin.properties.Delegates interface SyntheticJavaPropertyDescriptor : PropertyDescriptor { val getMethod: FunctionDescriptor val setMethod: FunctionDescriptor? companion object { fun findByGetterOrSetter(getterOrSetter: FunctionDescriptor, resolutionScope: JetScope): SyntheticJavaPropertyDescriptor? { val name = getterOrSetter.getName() if (name.isSpecial()) return null val identifier = name.getIdentifier() if (!identifier.startsWith("get") && !identifier.startsWith("is") && !identifier.startsWith("set")) return null // optimization val owner = getterOrSetter.getContainingDeclaration() as? ClassDescriptor ?: return null val originalGetterOrSetter = getterOrSetter.original return resolutionScope.getSyntheticExtensionProperties(listOf(owner.getDefaultType())) .filterIsInstance<SyntheticJavaPropertyDescriptor>() .firstOrNull { originalGetterOrSetter == it.getMethod || originalGetterOrSetter == it.setMethod } } fun propertyNameByGetMethodName(methodName: Name): Name? = propertyNameFromAccessorMethodName(methodName, "get") ?: propertyNameFromAccessorMethodName(methodName, "is", removePrefix = false) fun propertyNameBySetMethodName(methodName: Name, withIsPrefix: Boolean): Name? = propertyNameFromAccessorMethodName(methodName, "set", addPrefix = if (withIsPrefix) "is" else null) private fun propertyNameFromAccessorMethodName(methodName: Name, prefix: String, removePrefix: Boolean = true, addPrefix: String? = null): Name? { if (methodName.isSpecial()) return null val identifier = methodName.getIdentifier() if (!identifier.startsWith(prefix)) return null if (addPrefix != null) { assert(removePrefix) return Name.identifier(addPrefix + identifier.removePrefix(prefix)) } if (!removePrefix) return methodName val name = identifier.removePrefix(prefix).decapitalizeSmart() if (!Name.isValidIdentifier(name)) return null return Name.identifier(name) } } } class JavaSyntheticPropertiesScope(storageManager: StorageManager) : JetScopeImpl() { private val syntheticPropertyInClass = storageManager.createMemoizedFunctionWithNullableValues<Pair<ClassDescriptor, Name>, PropertyDescriptor> { pair -> syntheticPropertyInClassNotCached(pair.first, pair.second) } private fun syntheticPropertyInClassNotCached(ownerClass: ClassDescriptor, name: Name): PropertyDescriptor? { if (name.isSpecial()) return null val identifier = name.identifier if (identifier.isEmpty()) return null val firstChar = identifier[0] if (!firstChar.isJavaIdentifierStart() || firstChar.isUpperCase()) return null val memberScope = ownerClass.unsubstitutedMemberScope val getMethod = possibleGetMethodNames(name) .flatMap { memberScope.getFunctions(it, NoLookupLocation.UNSORTED).asSequence() } .singleOrNull { isGoodGetMethod(it) && it.hasJavaOriginInHierarchy() } ?: return null val setMethod = memberScope.getFunctions(setMethodName(getMethod.name), NoLookupLocation.UNSORTED) .singleOrNull { isGoodSetMethod(it, getMethod) } val propertyType = getMethod.returnType ?: return null return MyPropertyDescriptor.create(ownerClass, getMethod.original, setMethod?.original, name, propertyType) } private fun isGoodGetMethod(descriptor: FunctionDescriptor): Boolean { val returnType = descriptor.returnType ?: return false if (returnType.isUnit()) return false if (descriptor.name.asString().startsWith("is") && !returnType.isBoolean()) return false return descriptor.valueParameters.isEmpty() && descriptor.typeParameters.isEmpty() && descriptor.visibility.isVisibleOutside() } private fun isGoodSetMethod(descriptor: FunctionDescriptor, getMethod: FunctionDescriptor): Boolean { val propertyType = getMethod.returnType ?: return false val parameter = descriptor.valueParameters.singleOrNull() ?: return false if (!TypeUtils.equalTypes(parameter.type, propertyType)) { if (!propertyType.isSubtypeOf(parameter.type)) return false if (descriptor.findOverridden { val baseProperty = SyntheticJavaPropertyDescriptor.findByGetterOrSetter(it, this) baseProperty?.getMethod?.name == getMethod.name } == null) return false } return parameter.varargElementType == null && descriptor.typeParameters.isEmpty() && descriptor.returnType?.let { it.isUnit() } ?: false && descriptor.visibility.isVisibleOutside() } private fun FunctionDescriptor.findOverridden(condition: (FunctionDescriptor) -> Boolean): FunctionDescriptor? { for (descriptor in overriddenDescriptors) { if (condition(descriptor)) return descriptor descriptor.findOverridden(condition)?.let { return it } } return null } override fun getSyntheticExtensionProperties(receiverTypes: Collection<JetType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor> { //TODO: use location parameter! var result: SmartList<PropertyDescriptor>? = null val processedTypes: MutableSet<TypeConstructor>? = if (receiverTypes.size() > 1) HashSet<TypeConstructor>() else null for (type in receiverTypes) { result = collectSyntheticPropertiesByName(result, type.constructor, name, processedTypes) } return when { result == null -> emptyList() result.size() > 1 -> result.toSet() else -> result } } private fun collectSyntheticPropertiesByName(result: SmartList<PropertyDescriptor>?, type: TypeConstructor, name: Name, processedTypes: MutableSet<TypeConstructor>?): SmartList<PropertyDescriptor>? { if (processedTypes != null && !processedTypes.add(type)) return result @Suppress("NAME_SHADOWING") var result = result val classifier = type.declarationDescriptor if (classifier is ClassDescriptor) { result = result.add(syntheticPropertyInClass(Pair(classifier, name))) } else { type.supertypes.forEach { result = collectSyntheticPropertiesByName(result, it.constructor, name, processedTypes) } } return result } override fun getSyntheticExtensionProperties(receiverTypes: Collection<JetType>): Collection<PropertyDescriptor> { val result = ArrayList<PropertyDescriptor>() val processedTypes = HashSet<TypeConstructor>() receiverTypes.forEach { result.collectSyntheticProperties(it.constructor, processedTypes) } return result } private fun MutableList<PropertyDescriptor>.collectSyntheticProperties(type: TypeConstructor, processedTypes: MutableSet<TypeConstructor>) { if (!processedTypes.add(type)) return val classifier = type.declarationDescriptor if (classifier is ClassDescriptor) { for (descriptor in classifier.getUnsubstitutedMemberScope().getDescriptors(DescriptorKindFilter.FUNCTIONS)) { if (descriptor is FunctionDescriptor) { val propertyName = SyntheticJavaPropertyDescriptor.propertyNameByGetMethodName(descriptor.getName()) ?: continue addIfNotNull(syntheticPropertyInClass(Pair(classifier, propertyName))) } } } else { type.supertypes.forEach { collectSyntheticProperties(it.constructor, processedTypes) } } } private fun SmartList<PropertyDescriptor>?.add(property: PropertyDescriptor?): SmartList<PropertyDescriptor>? { if (property == null) return this val list = if (this != null) this else SmartList() list.add(property) return list } //TODO: reuse code with generation? private fun possibleGetMethodNames(propertyName: Name): Sequence<Name> { val result = ArrayList<Name>(3) val identifier = propertyName.identifier if (identifier.startsWith("is")) { result.add(propertyName) } val capitalize1 = identifier.capitalize() val capitalize2 = identifier.capitalizeFirstWord() result.add(Name.identifier("get" + capitalize1)) if (capitalize2 != capitalize1) { result.add(Name.identifier("get" + capitalize2)) } return result.asSequence() .filter { SyntheticJavaPropertyDescriptor.propertyNameByGetMethodName(it) == propertyName } // don't accept "uRL" for "getURL" etc } private fun setMethodName(getMethodName: Name): Name { val identifier = getMethodName.identifier val prefix = when { identifier.startsWith("get") -> "get" identifier.startsWith("is") -> "is" else -> throw IllegalArgumentException() } return Name.identifier("set" + identifier.removePrefix(prefix)) } override fun getContainingDeclaration(): DeclarationDescriptor { throw UnsupportedOperationException() } override fun printScopeStructure(p: Printer) { p.println(javaClass.simpleName) } private class MyPropertyDescriptor( containingDeclaration: DeclarationDescriptor, original: PropertyDescriptor?, annotations: Annotations, modality: Modality, visibility: Visibility, isVar: Boolean, name: Name, kind: CallableMemberDescriptor.Kind, source: SourceElement ) : SyntheticJavaPropertyDescriptor, PropertyDescriptorImpl(containingDeclaration, original, annotations, modality, visibility, isVar, name, kind, source, /* lateInit = */ false, /* isConst = */ false) { override var getMethod: FunctionDescriptor by Delegates.notNull() private set override var setMethod: FunctionDescriptor? = null private set companion object { fun create(ownerClass: ClassDescriptor, getMethod: FunctionDescriptor, setMethod: FunctionDescriptor?, name: Name, type: JetType): MyPropertyDescriptor { val visibility = syntheticExtensionVisibility(getMethod) val descriptor = MyPropertyDescriptor(DescriptorUtils.getContainingModule(ownerClass), null, Annotations.EMPTY, Modality.FINAL, visibility, setMethod != null, name, CallableMemberDescriptor.Kind.SYNTHESIZED, SourceElement.NO_SOURCE) descriptor.getMethod = getMethod descriptor.setMethod = setMethod val classTypeParams = ownerClass.typeConstructor.parameters val typeParameters = ArrayList<TypeParameterDescriptor>(classTypeParams.size()) val typeSubstitutor = DescriptorSubstitutor.substituteTypeParameters(classTypeParams, TypeSubstitution.EMPTY, descriptor, typeParameters) val propertyType = typeSubstitutor.safeSubstitute(type, Variance.INVARIANT) val receiverType = typeSubstitutor.safeSubstitute(ownerClass.defaultType, Variance.INVARIANT) descriptor.setType(propertyType, typeParameters, null, receiverType) val getter = PropertyGetterDescriptorImpl(descriptor, Annotations.EMPTY, Modality.FINAL, visibility, false, false, CallableMemberDescriptor.Kind.SYNTHESIZED, null, SourceElement.NO_SOURCE) getter.initialize(null) val setter = if (setMethod != null) PropertySetterDescriptorImpl(descriptor, Annotations.EMPTY, Modality.FINAL, syntheticExtensionVisibility(setMethod), false, false, CallableMemberDescriptor.Kind.SYNTHESIZED, null, SourceElement.NO_SOURCE) else null setter?.initializeDefault() descriptor.initialize(getter, setter) return descriptor } } override fun createSubstitutedCopy(newOwner: DeclarationDescriptor, newModality: Modality, newVisibility: Visibility, original: PropertyDescriptor?, kind: CallableMemberDescriptor.Kind): PropertyDescriptorImpl { return MyPropertyDescriptor(newOwner, this, annotations, newModality, newVisibility, isVar, name, kind, source).apply { getMethod = [email protected] setMethod = [email protected] } } override fun substitute(originalSubstitutor: TypeSubstitutor): PropertyDescriptor? { val descriptor = super<PropertyDescriptorImpl>.substitute(originalSubstitutor) as MyPropertyDescriptor if (descriptor == this) return descriptor val classTypeParameters = (getMethod.containingDeclaration as ClassDescriptor).typeConstructor.parameters val substitutionMap = HashMap<TypeConstructor, TypeProjection>() for ((typeParameter, classTypeParameter) in typeParameters.zip(classTypeParameters)) { val typeProjection = originalSubstitutor.substitution[typeParameter.defaultType] ?: continue substitutionMap[classTypeParameter.typeConstructor] = typeProjection } val classParametersSubstitutor = TypeSubstitutor.create(substitutionMap) descriptor.getMethod = getMethod.substitute(classParametersSubstitutor)!! descriptor.setMethod = setMethod?.substitute(classParametersSubstitutor) return descriptor } } }
5
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
17,328
kotlin
Apache License 2.0
wire-tests/src/test/proto-kotlin/com/squareup/wire/protos/kotlin/MessageWithStatus.kt
yadavved
195,357,857
true
{"INI": 18, "YAML": 1, "Markdown": 6, "Text": 4, "Gradle": 50, "Shell": 2, "Batchfile": 1, "Ignore List": 1, "Kotlin": 153, "Java": 137, "Protocol Buffer": 86, "Maven POM": 1, "XML": 2}
// Code generated by Wire protocol buffer compiler, do not edit. // Source file: same_name_enum.proto package com.squareup.wire.protos.kotlin import com.squareup.wire.EnumAdapter import com.squareup.wire.FieldEncoding import com.squareup.wire.Message import com.squareup.wire.ProtoAdapter import com.squareup.wire.ProtoReader import com.squareup.wire.ProtoWriter import com.squareup.wire.WireEnum import kotlin.AssertionError import kotlin.Deprecated import kotlin.DeprecationLevel import kotlin.Int import kotlin.Nothing import kotlin.jvm.JvmField import kotlin.jvm.JvmStatic import okio.ByteString data class MessageWithStatus( val unknownFields: ByteString = ByteString.EMPTY ) : Message<MessageWithStatus, Nothing>(ADAPTER, unknownFields) { @Deprecated( message = "Shouldn't be used in Kotlin", level = DeprecationLevel.HIDDEN ) override fun newBuilder(): Nothing { throw AssertionError() } companion object { @JvmField val ADAPTER: ProtoAdapter<MessageWithStatus> = object : ProtoAdapter<MessageWithStatus>( FieldEncoding.LENGTH_DELIMITED, MessageWithStatus::class ) { override fun encodedSize(value: MessageWithStatus): Int = value.unknownFields.size override fun encode(writer: ProtoWriter, value: MessageWithStatus) { writer.writeBytes(value.unknownFields) } override fun decode(reader: ProtoReader): MessageWithStatus { val unknownFields = reader.forEachTag { tag -> when (tag) { else -> reader.readUnknownField(tag) } } return MessageWithStatus( unknownFields = unknownFields ) } override fun redact(value: MessageWithStatus): MessageWithStatus = value.copy( unknownFields = ByteString.EMPTY ) } } enum class Status( override val value: Int ) : WireEnum { A(1); companion object { @JvmField val ADAPTER: ProtoAdapter<Status> = object : EnumAdapter<Status>( Status::class ) { override fun fromValue(value: Int): Status = Status.fromValue(value) } @JvmStatic fun fromValue(value: Int): Status = when (value) { 1 -> A else -> throw IllegalArgumentException("""Unexpected value: $value""") } } } }
0
Java
0
0
e2944d3db3a6d49b0ddb83e1974ae7c94e54d701
2,305
wire
Apache License 2.0
app/src/test/kotlin/de/markusfisch/android/binaryeye/actions/wifi/WifiConfigurationFactoryTest.kt
yzqzss
248,396,812
true
{"Kotlin": 122044, "Shell": 1967, "RenderScript": 625, "Makefile": 566}
package de.markusfisch.android.binaryeye.actions.wifi import de.markusfisch.android.binaryeye.simpleFail import junit.framework.TestCase.* import org.junit.Test class WifiConfigurationFactoryTest { @Test fun notWifi() { assertNull(WifiConfigurationFactory.parseMap("asdfz")) } @Test fun wep() { val info = simpleDataAccessor("WIFI:T:WEP;S:asdfz;P:password;;") assertEquals("WEP", info.securityType) assertEquals("\"asdfz\"", info.ssid) assertEquals("\"password\"", info.password) assertFalse(info.hidden) } @Test fun hidden() { val info = simpleDataAccessor("WIFI:T:WPA;S:asdfz;P:password;H:true;;") assertEquals("WPA", info.securityType) assertEquals("\"asdfz\"", info.ssid) assertEquals("\"password\"", info.password) assertTrue(info.hidden) } @Test fun nopass() { val info = simpleDataAccessor("WIFI:T:nopass;S:asdfz;;") assertEquals("nopass", info.securityType) assertEquals("\"asdfz\"", info.ssid) assertNull(info.password) assertFalse(info.hidden) } @Test fun plainUnsecured() { val info = simpleDataAccessor("WIFI:S:asdfz;;") assertEquals("", info.securityType) assertEquals("\"asdfz\"", info.ssid) assertNull(info.password) assertFalse(info.hidden) } @Test fun hex() { val info = simpleDataAccessor("WIFI:T:WEP;S:d34dbeef;P:d34dbeef;;") assertEquals("WEP", info.securityType) assertEquals("d34dbeef", info.ssid) assertEquals("d34dbeef", info.password) assertFalse(info.hidden) } @Test fun escaping() { val info = simpleDataAccessor("""WIFI:S:\"ssid\\\;stillSSID\:\;x;;""") assertEquals("", info.securityType) assertEquals("""""ssid\;stillSSID:;x"""", info.ssid) assertNull(info.password) assertFalse(info.hidden) } @Test fun wrongEscaping() { val info = simpleDataAccessor("""WIFI:S:\SSID":\;x;""") assertEquals("", info.securityType) assertEquals(""""\SSID":;x"""", info.ssid) assertNull(info.password) assertFalse(info.hidden) } private fun simpleDataAccessor(wifiString: String): WifiConfigurationFactory.SimpleDataAccessor { val map = WifiConfigurationFactory.parseMap(wifiString) ?: simpleFail("parsing map of valid string fails ($wifiString)") return WifiConfigurationFactory.SimpleDataAccessor.of(map) ?: simpleFail("could not create SimpleDataAccessor of (potentially) valid map ($map of $wifiString)") } }
0
null
0
0
8e24673d08627545035c14d1b78c0433282753ad
2,349
BinaryEye
MIT License
gosys/src/test/kotlin/no/nav/helse/spre/gosys/vedtakFattet/VedtakFattetRiverTest.kt
navikt
342,325,871
false
null
package no.nav.helse.spre.gosys.vedtakFattet import no.nav.helse.spre.gosys.e2e.AbstractE2ETest import no.nav.helse.spre.gosys.utbetaling.UtbetalingDao import org.intellij.lang.annotations.Language import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test import java.util.* internal class VedtakFattetRiverTest : AbstractE2ETest() { val vedtakFattetDao = VedtakFattetDao(dataSource) val utbetalingDao = UtbetalingDao(dataSource) init { VedtakFattetRiver(testRapid, vedtakFattetDao, utbetalingDao, duplikatsjekkDao, vedtakMediator) } @Test fun `Lagrer vedtak fattet`() { val utbetalingId = UUID.randomUUID() testRapid.sendTestMessage(vedtakFattetMedUtbetaling(utbetalingId = utbetalingId)) assertNotNull(vedtakFattetDao.finnVedtakFattetData(utbetalingId)) } @Test fun `kan lagre flere vedtak knyttet til samme utbetaling`() { val utbetalingId = UUID.randomUUID() sendUtbetaling(utbetalingId = utbetalingId) sendVedtakFattet(utbetalingId = utbetalingId) sendVedtakFattet(utbetalingId = utbetalingId) assertEquals(2, vedtakFattetDao.finnVedtakFattetData(utbetalingId).size) } @Language("json") private fun vedtakFattetMedUtbetaling( id: UUID = UUID.randomUUID(), vedtaksperiodeId: UUID = UUID.randomUUID(), utbetalingId: UUID = UUID.randomUUID() ) = """{ "@id": "$id", "vedtaksperiodeId": "$vedtaksperiodeId", "fødselsnummer": "12345678910", "utbetalingId": "$utbetalingId", "@event_name": "vedtak_fattet", "@opprettet": "2021-05-25T13:12:24.922420993", "fom": "2021-05-03", "tom": "2021-05-16", "@forårsaket_av": { "behov": [ "Utbetaling" ], "event_name": "behov", "id": "6c7d5e27-c9cf-4e74-8662-a977f3f6a587", "opprettet": "2021-05-25T13:12:22.535549467" }, "hendelser": [ "65ca68fa-0f12-40f3-ac34-141fa77c4270", "6977170d-5a99-4e7f-8d5f-93bda94a9ba3", "15aa9c84-a9cc-4787-b82a-d5447aa3fab1" ], "skjæringstidspunkt": "2021-01-07", "sykepengegrunnlag": 565260.0, "grunnlagForSykepengegrunnlagPerArbeidsgiver": { "123456789": 1234.56, "987654321": 6543.21 }, "inntekt": 47105.0, "aktørId": "9000011921123", "organisasjonsnummer": "123456789", "system_read_count": 0 } """ }
0
Kotlin
2
1
2adea5abb9092ca8c08271ef43d18a17b4f303e4
2,402
helse-spre
MIT License
core/src/commonMain/kotlin/work/socialhub/kbsky/api/entity/chat/bsky/convo/ConvoGetListConvosRequest.kt
uakihir0
735,265,237
false
{"Kotlin": 396349, "Shell": 1421, "Makefile": 315}
package work.socialhub.kbsky.api.entity.chat.bsky.convo import work.socialhub.kbsky.api.entity.share.AuthRequest import work.socialhub.kbsky.api.entity.share.MapRequest import work.socialhub.kbsky.auth.AuthProvider class ConvoGetListConvosRequest( auth: AuthProvider ) : AuthRequest(auth), MapRequest { var limit: Int? = null var cursor: String? = null override fun toMap(): Map<String, Any> { return mutableMapOf<String, Any>().also { it.addParam("limit", limit) it.addParam("cursor", cursor) } } }
2
Kotlin
1
17
648870de4e311a209096822b9b73767e0e050c37
564
kbsky
MIT License
leetcode/src/linkedlist/Q142.kt
zhangweizhe
387,808,774
false
null
package linkedlist fun main() { // 142. 环形链表 II // https://leetcode-cn.com/problems/linked-list-cycle-ii/ val createList = LinkedListUtil.createList(intArrayOf(3, 2, 0, 4)) val n2 = createList?.next n2?.next?.next?.next = n2 println(detectCycle(createList)?.`val`) } fun detectCycle(head: ListNode?): ListNode? { var fast = head var slow:ListNode? = head while (fast?.next != null) { fast = fast.next?.next slow = slow?.next if (fast == slow) { break } } if (fast == null || fast.next == null) { return null } fast = head while (fast != slow) { fast = fast?.next slow = slow?.next } return fast }
0
Kotlin
0
0
dfb5f518300e69689a2c5eb7fb1f9d674c550b4a
733
kotlin-study
MIT License
newcall_library/src/main/java/com/cmcc/newcalllib/adapter/ar/local/LocalARAdapter.kt
NewCallTeam
602,468,716
false
null
/* * Copyright (c) 2022 China Mobile Communications Group Co.,Ltd. All rights reserved. * * Licensed under the XXXX License, Version X.X (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://xxxxxxx/licenses/LICENSE-X.X * * 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.cmcc.newcalllib.adapter.ar.local import android.view.Surface /** * work with AR-SDK included * @author jihongfei * @createTime 2022/12/9 11:56 */ interface LocalARAdapter { fun checkARAbility(): Boolean fun startARAbility(surface: Surface?, callback: LocalARCallback?) fun stopARAbility(callback: LocalARCallback?) }
0
Kotlin
4
8
8f2d00ca24335bebb34a7be078c90be07a25add2
986
NewCalling
Apache License 2.0
mui-kotlin/src/jsMain/kotlin/mui/base/useSlider.types.kt
karakum-team
387,062,541
false
null
// Automatically generated - do not modify! package mui.base import web.events.Event external interface UseSliderParameters { // var `aria-labelledby`: String? var defaultValue: dynamic var disabled: Boolean? var disableSwap: Boolean? var isRtl: Boolean? var marks: dynamic var max: Number? var min: Number? var name: String? var onChange: ((event: Event, value: dynamic, activeThumb: Number) -> Unit)? var onChangeCommitted: ((event: react.dom.events.SyntheticEvent<*, *>, value: dynamic) -> Unit)? var orientation: mui.material.Orientation? var scale: ((value: Number) -> Number)? var step: Number? var tabIndex: Int? var value: dynamic } external interface Mark { var value: Number var label: react.ReactNode? }
0
Kotlin
3
31
d1ea32754f43e696f6b3e946692c2e81f25ad6ae
807
mui-kotlin
Apache License 2.0
src/main/java/com/will/utils/FileUtils.kt
z2z2qp
86,769,932
false
null
package com.will.utils import java.io.BufferedInputStream import java.io.File import java.io.FileInputStream import java.io.InputStream import java.math.BigInteger import java.security.MessageDigest import java.text.DecimalFormat import java.util.* /** * Created by zoumy on 2017/5/15 14:26. */ object FileUtils : org.apache.commons.io.FileUtils() { /** * 检查目录是否存在,不存在创建之 */ fun mkdir(dirPath:String){ val dir = File(dirPath) if(!dir.exists() && !dir.isDirectory){ dir.mkdirs() } } /** * 检查同名文件是否存在 */ fun isExist(filePath:String): Boolean { val file = File(filePath) return file.exists() } /** * 检查文件名为filepath,并且md5为filemd5的文件是否存在 */ fun isExist(filePath:String,fileMd5:String?):Boolean{ if (!isExist(filePath) || fileMd5 == null){ return false } return checkFileMd5(filePath,fileMd5) } /** * 获取文件扩展名 */ fun getExtension(fileName: String):String{ if (fileName.isNotBlank()){ val dot = fileName.lastIndexOf('.') if (dot > 0 && dot < fileName.length){ return fileName.substring(dot + 1) } } return "" } /** * 获取文件名,不带扩展名 */ fun getNameWithoutExtension(fileName:String):String{ if (fileName.isNotBlank()){ val dot = fileName.lastIndexOf('.') if (dot > 0 && dot < fileName.length){ return fileName.substring(0,dot) } } return fileName } /** * 重命名文件名,在文件名和扩展名中添加token */ fun rename(fileName: String,token:String):String{ val name = getNameWithoutExtension(fileName) val ext = getExtension(fileName) return "$name$token.$ext" } /** * 写入文件,返回文件名 ,写入失败,返回null */ fun write(file:File,path:String):String?{ val uploadFile = File(path) val byteArray = file.readBytes() uploadFile.writeBytes(byteArray) return uploadFile.name } /** * 判断相同文件是否存在,如果同名但不同文件存在,进行重命名并保存 返回文件名 ,写入失败,返回null */ fun writeTo(file:File,path: String,fileMd5: String? = null):String?{ var filePath = path if(!isExist(path,fileMd5)){//不存在一样的文件 if(isExist(path)){//存在同名文件 filePath = rename(path,UUID.randomUUID().toString()) } return write(file,filePath) } return File(path).name } /** * 检查文件的md5是否为参数md5对应的值 */ fun checkFileMd5(filePath: String?,md5:String?):Boolean{ if (filePath == null || md5 == null){ return false } val fileMd5:String = getMd5ByFile(filePath) return fileMd5.equals(md5,true) } /** * 获得流中数据的md5 * * @param input * @return */ fun getMd5ByFile(input:InputStream):String{ val value:String val md5 = MessageDigest.getInstance("MD5") val byteIterator = BufferedInputStream(input).iterator() while (byteIterator.hasNext()){ md5.update(byteIterator.nextByte()) } val bi = BigInteger(1,md5.digest()) value = bi.toString(16) return value } /** * 获得文件的md5 * * @param file * @return */ fun getMd5ByFile(file:File):String{ return getMd5ByFile(FileInputStream(file)) } /** * 获得文件的md5 * * @param filename * @return */ fun getMd5ByFile(fileName: String):String{ return getMd5ByFile(File(fileName)) } /** * 格式化文件大小 */ fun formatFileSize(size:Double):String{ val format = DecimalFormat("0.00") val kiloByte = size / 1024 if(kiloByte < 1){ return "$size Byte(s)" } val megaByte = kiloByte / 1024 if(megaByte < 1){ return "${format.format(kiloByte)} KB" } val gigaByte = megaByte / 1024 if(gigaByte < 1){ return "${format.format(megaByte)} MB" } val teraByte = gigaByte / 1024 if (teraByte < 1){ return "${format.format(gigaByte)} GB" } return "${format.format(teraByte)} TB" } }
6
Kotlin
1
2
97fbf03a0ce011629135dd541c4e4d59e13454db
4,280
msm
The Unlicense
src/main/kotlin/no/nav/pensjon/simulator/core/domain/regler/beregning2011/Uforetrygdberegning.kt
navikt
753,551,695
false
{"Kotlin": 1452773, "Java": 2774, "Dockerfile": 144}
package no.nav.pensjon.simulator.core.domain.regler.beregning2011 import no.nav.pensjon.simulator.core.domain.regler.enum.FormelKodeEnum import no.nav.pensjon.simulator.core.domain.regler.enum.JustertPeriodeEnum import no.nav.pensjon.simulator.core.domain.regler.enum.YtelseVedDodEnum import no.nav.pensjon.simulator.core.domain.regler.trygdetid.Brok import java.util.* class Uforetrygdberegning : Beregning2011() { var bruttoPerAr = 0 var formelKodeEnum: FormelKodeEnum? = null override var grunnbelop = 0 var minsteytelse: Minsteytelse? = null var prorataBrok: Brok? = null var uforegrad = 0 var uforetidspunkt: Date? = null var egenopptjentUforetrygd: EgenopptjentUforetrygd? = null var egenopptjentUforetrygdBest = false var yrkesskadegrad = 0 var yrkesskadetidspunkt: Date? = null var mottarMinsteytelse = false /* Bygger opp årsakskoder som viser hvorfor personen mottar minsteytelse */ var minsteytelseArsak: String? = null /* Viser hvilken type institusjonsopphold det er beregnet for. Kodene hentes fra K_JUST_PERIODE */ var instOppholdTypeEnum: JustertPeriodeEnum? = null /* Angir om ytelsen er endret, enten økt eller redusert. */ var instOpphAnvendt = false /** * Ekstra informasjon til beregnet uføretrygd. * Brukes for at pensjon-regler skal beregne en Uførehistorikk for uføretrygd. */ var uforeEkstra: UforeEkstraUT? = null /** * Satt på de beregninger hvor avdødes ytelse har påvirket beregningen. */ var ytelseVedDodEnum: YtelseVedDodEnum? = null }
1
Kotlin
0
0
77b8c4e0a80e5bf44cb44468466362956fe82da8
1,589
pensjonssimulator
MIT License
app/src/unitTest/kotlin/batect/execution/ContainerDependencyGraphSpec.kt
wyvern8
229,031,490
false
null
/* Copyright 2017-2020 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.execution import batect.config.Configuration import batect.config.Container import batect.config.ContainerMap import batect.config.LiteralValue import batect.config.PortMapping import batect.config.Task import batect.config.TaskMap import batect.config.TaskRunConfiguration import batect.os.Command import batect.testutils.given import batect.testutils.imageSourceDoesNotMatter import batect.testutils.isEmptyMap import batect.testutils.on import batect.testutils.withMessage import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isEmpty import com.natpryce.hamkrest.throws import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.mock import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object ContainerDependencyGraphSpec : Spek({ describe("a container dependency graph") { val commandResolver = mock<ContainerCommandResolver> { on { resolveCommand(any(), any()) } doAnswer { val container = it.getArgument<Container>(0) Command.parse("${container.name} command") } } val entrypointResolver = mock<ContainerEntrypointResolver> { on { resolveEntrypoint(any(), any()) } doAnswer { val container = it.getArgument<Container>(0) Command.parse("${container.name} entrypoint") } } given("a task with no dependencies") { given("the task does not override the container's working directory") { val container = Container("some-container", imageSourceDoesNotMatter(), command = Command.parse("some-container-command"), entrypoint = Command.parse("some-task-entrypoint"), workingDirectory = "task-working-dir-that-wont-be-used") val runConfig = TaskRunConfiguration(container.name, Command.parse("some-command"), Command.parse("some-entrypoint"), mapOf("SOME_EXTRA_VALUE" to LiteralValue("the value")), setOf(PortMapping(123, 456)), "some-task-specific-working-dir") val task = Task("the-task", runConfig, dependsOnContainers = emptySet()) val config = Configuration("the-project", TaskMap(task), ContainerMap(container)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(container, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(container, task))) } it("takes its working directory from the task") { assertThat(node.config.workingDirectory, equalTo(runConfig.workingDiretory)) } it("takes the additional environment variables from the task") { assertThat(node.config.additionalEnvironmentVariables, equalTo(runConfig.additionalEnvironmentVariables)) } it("takes the additional port mappings from the task") { assertThat(node.config.additionalPortMappings, equalTo(runConfig.additionalPortMappings)) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(container), equalTo(node)) } } on("getting the node for a container not part of the graph") { val otherContainer = Container("the-other-container", imageSourceDoesNotMatter()) it("throws an exception") { assertThat({ graph.nodeFor(otherContainer) }, throws<IllegalArgumentException>(withMessage("Container 'the-other-container' is not part of this dependency graph."))) } } } given("the task overrides the container's working directory") { val container = Container("some-container", imageSourceDoesNotMatter(), command = Command.parse("some-container-command"), entrypoint = Command.parse("sh"), workingDirectory = "task-working-dir") val runConfig = TaskRunConfiguration(container.name, Command.parse("some-command"), Command.parse("some-entrypoint"), mapOf("SOME_EXTRA_VALUE" to LiteralValue("the value")), setOf(PortMapping(123, 456))) val task = Task("the-task", runConfig, dependsOnContainers = emptySet()) val config = Configuration("the-project", TaskMap(task), ContainerMap(container)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(container, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(container, task))) } it("takes its working directory from the container") { assertThat(node.config.workingDirectory, equalTo(container.workingDirectory)) } it("takes the additional environment variables from the task") { assertThat(node.config.additionalEnvironmentVariables, equalTo(runConfig.additionalEnvironmentVariables)) } it("takes the additional port mappings from the task") { assertThat(node.config.additionalPortMappings, equalTo(runConfig.additionalPortMappings)) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(container), equalTo(node)) } } } } given("a task that refers to a container that does not exist") { val runConfig = TaskRunConfiguration("some-non-existent-container", Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = emptySet()) val config = Configuration("the-project", TaskMap(task), ContainerMap()) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("The container 'some-non-existent-container' referenced by task 'the-task' does not exist."))) } } } given("a task with a dependency") { val taskContainer = Container("some-container", imageSourceDoesNotMatter(), command = Command.parse("task-command-that-wont-be-used"), entrypoint = Command.parse("sh"), workingDirectory = "task-working-dir-that-wont-be-used") val dependencyContainer = Container("dependency-container", imageSourceDoesNotMatter(), command = Command.parse("dependency-command"), workingDirectory = "dependency-working-dir") val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command"), Command.parse("some-entrypoint"), mapOf("SOME_EXTRA_VALUE" to LiteralValue("the value")), setOf(PortMapping(123, 456)), "some-task-specific-working-dir") val task = Task("the-task", runConfig, dependsOnContainers = setOf(dependencyContainer.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on the dependency container") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(dependencyContainer))) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskContainer, task))) } it("takes its working directory from the task") { assertThat(node.config.workingDirectory, equalTo(runConfig.workingDiretory)) } it("takes the additional environment variables from the task") { assertThat(node.config.additionalEnvironmentVariables, equalTo(runConfig.additionalEnvironmentVariables)) } it("takes the additional port mappings from the task") { assertThat(node.config.additionalPortMappings, equalTo(runConfig.additionalPortMappings)) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(taskContainer), equalTo(node)) } } on("getting the dependency container node") { val node = graph.nodeFor(dependencyContainer) it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(dependencyContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(dependencyContainer, task))) } it("takes its working directory from the container configuration") { assertThat(node.config.workingDirectory, equalTo(dependencyContainer.workingDirectory)) } it("does not take the additional environment variables from the task") { assertThat(node.config.additionalEnvironmentVariables, isEmptyMap()) } it("does not take the additional port mappings from the task") { assertThat(node.config.additionalPortMappings, isEmpty) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } given("a task with many dependencies") { val taskContainer = Container("some-container", imageSourceDoesNotMatter()) val dependencyContainer1 = Container("dependency-container-1", imageSourceDoesNotMatter()) val dependencyContainer2 = Container("dependency-container-2", imageSourceDoesNotMatter()) val dependencyContainer3 = Container("dependency-container-3", imageSourceDoesNotMatter()) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf(dependencyContainer1.name, dependencyContainer2.name, dependencyContainer3.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer1, dependencyContainer2, dependencyContainer3)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on the dependency containers") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(dependencyContainer1, dependencyContainer2, dependencyContainer3))) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskContainer, task))) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(taskContainer), equalTo(node)) } } listOf(dependencyContainer1, dependencyContainer2, dependencyContainer3).forEach { container -> on("getting the node for dependency container '${container.name}'") { val node = graph.nodeFor(container) it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(container, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(container, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } } given("a task with a dependency that does not exist") { val taskContainer = Container("some-container", imageSourceDoesNotMatter()) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf("non-existent-dependency")) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("The container 'non-existent-dependency' referenced by task 'the-task' does not exist."))) } } } given("a task with a dependency on the task container") { val taskContainer = Container("some-container", imageSourceDoesNotMatter()) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf(taskContainer.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("The task 'the-task' cannot start the container 'some-container' and also run it."))) } } } given("a task with a container that has some direct dependencies") { val dependencyContainer1 = Container("dependency-container-1", imageSourceDoesNotMatter()) val dependencyContainer2 = Container("dependency-container-2", imageSourceDoesNotMatter()) val dependencyContainer3 = Container("dependency-container-3", imageSourceDoesNotMatter()) val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf(dependencyContainer1.name, dependencyContainer2.name, dependencyContainer3.name)) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer1, dependencyContainer2, dependencyContainer3)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on the dependency containers") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(dependencyContainer1, dependencyContainer2, dependencyContainer3))) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskContainer, task))) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(taskContainer), equalTo(node)) } } listOf(dependencyContainer1, dependencyContainer2, dependencyContainer3).forEach { container -> on("getting the node for dependency container '${container.name}'") { val node = graph.nodeFor(container) it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(container, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(container, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } } given("a task with a container that has a dependency which itself has a dependency") { val dependencyContainer1 = Container("dependency-container-1", imageSourceDoesNotMatter()) val dependencyContainer2 = Container("dependency-container-2", imageSourceDoesNotMatter(), dependencies = setOf(dependencyContainer1.name)) val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf(dependencyContainer2.name)) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer1, dependencyContainer2)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on its direct dependency") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(dependencyContainer2))) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskContainer, task))) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(taskContainer), equalTo(node)) } } on("getting the node for the dependency container that is a direct dependency of the task container") { val node = graph.nodeFor(dependencyContainer2) it("depends on its direct dependency") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(dependencyContainer1))) } it("is depended on by the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(dependencyContainer2, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(dependencyContainer2, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } on("getting the node for the dependency container that is a indirect dependency of the task container") { val node = graph.nodeFor(dependencyContainer1) it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by the direct dependency of the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(dependencyContainer2))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(dependencyContainer1, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(dependencyContainer1, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } given("a task with a container that has two direct dependencies which themselves share a single dependency") { val containerWithNoDependencies = Container("no-dependencies", imageSourceDoesNotMatter()) val dependencyContainer1 = Container("dependency-container-1", imageSourceDoesNotMatter(), dependencies = setOf(containerWithNoDependencies.name)) val dependencyContainer2 = Container("dependency-container-2", imageSourceDoesNotMatter(), dependencies = setOf(containerWithNoDependencies.name)) val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf(dependencyContainer1.name, dependencyContainer2.name)) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer1, dependencyContainer2, containerWithNoDependencies)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on its direct dependencies") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(dependencyContainer1, dependencyContainer2))) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskContainer, task))) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(taskContainer), equalTo(node)) } } listOf(dependencyContainer1, dependencyContainer2).forEach { container -> on("getting the node for direct dependency container '${container.name}'") { val node = graph.nodeFor(container) it("depends on the common dependency") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(containerWithNoDependencies))) } it("is depended on by the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(container, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(container, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } on("getting the node for the dependency container that has no dependencies") { val node = graph.nodeFor(containerWithNoDependencies) it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by the two direct dependencies of the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(dependencyContainer1, dependencyContainer2))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(containerWithNoDependencies, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(containerWithNoDependencies, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } given("a task with a container that depends on containers A and B where B also depends on A") { val containerA = Container("container-a", imageSourceDoesNotMatter()) val containerB = Container("container-b", imageSourceDoesNotMatter(), dependencies = setOf(containerA.name)) val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf(containerB.name, containerA.name)) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, containerB, containerA)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on its direct dependencies") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(containerA, containerB))) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskContainer, task))) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(taskContainer), equalTo(node)) } } on("getting the node for container A") { val node = graph.nodeFor(containerA) it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by the task container and container B") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer, containerB))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(containerA, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(containerA, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } on("getting the node for container B") { val node = graph.nodeFor(containerB) it("depends on container A") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(containerA))) } it("is depended on by the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(containerB, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(containerB, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } given("a task with a dependency which itself has a dependency") { val otherDependencyContainer = Container("other-dependency", imageSourceDoesNotMatter()) val taskDependencyContainer = Container("task-dependency", imageSourceDoesNotMatter(), dependencies = setOf(otherDependencyContainer.name)) val taskContainer = Container("some-container", imageSourceDoesNotMatter()) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf(taskDependencyContainer.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, taskDependencyContainer, otherDependencyContainer)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on the task dependency") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(taskDependencyContainer))) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskContainer, task))) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(taskContainer), equalTo(node)) } } on("getting the node for the task dependency") { val node = graph.nodeFor(taskDependencyContainer) it("depends on its direct dependency") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(otherDependencyContainer))) } it("is depended on by the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskDependencyContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskDependencyContainer, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } on("getting the node for the other container") { val node = graph.nodeFor(otherDependencyContainer) it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by the task dependency") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskDependencyContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(otherDependencyContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(otherDependencyContainer, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } given("a task with a dependency which is also a dependency of the task container") { val dependencyContainer = Container("dependency-container", imageSourceDoesNotMatter()) val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf(dependencyContainer.name)) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf(dependencyContainer.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer)) val graph = ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) on("getting the task container node") { val node = graph.taskContainerNode it("depends on the dependency") { assertThat(node.dependsOn.mapToSet { it.container }, equalTo(setOf(dependencyContainer))) } it("is depended on by nothing") { assertThat(node.dependedOnBy, isEmpty) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(taskContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(taskContainer, task))) } it("indicates that it is the root node of the graph") { assertThat(node.isRootNode, equalTo(true)) } it("is the same node as the node for the task container") { assertThat(graph.nodeFor(taskContainer), equalTo(node)) } } on("getting the node for the dependency") { val node = graph.nodeFor(dependencyContainer) it("depends on nothing") { assertThat(node.dependsOn, isEmpty) } it("is depended on by the task container") { assertThat(node.dependedOnBy.mapToSet { it.container }, equalTo(setOf(taskContainer))) } it("takes its command from the command resolver") { assertThat(node.config.command, equalTo(commandResolver.resolveCommand(dependencyContainer, task))) } it("takes its entrypoint from the entrypoint resolver") { assertThat(node.config.entrypoint, equalTo(entrypointResolver.resolveEntrypoint(dependencyContainer, task))) } it("indicates that it is not the root node of the graph") { assertThat(node.isRootNode, equalTo(false)) } } } given("a task with a container that has a dependency that does not exist") { val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf("non-existent-container")) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("The container 'non-existent-container' referenced by container 'some-container' does not exist."))) } } } given("a task with a container that has a dependency that has a dependency that does not exist") { val dependencyContainer = Container("dependency-container", imageSourceDoesNotMatter(), dependencies = setOf("non-existent-container")) val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf(dependencyContainer.name)) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("The container 'non-existent-container' referenced by container 'dependency-container' does not exist."))) } } } given("a task with a container that has a dependency on itself") { val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf("some-container")) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("The container 'some-container' cannot depend on itself."))) } } } given("a task with a container with a dependency that depends on itself") { val dependencyContainer = Container("dependency-container", imageSourceDoesNotMatter(), dependencies = setOf("dependency-container")) val taskContainer = Container("some-container", imageSourceDoesNotMatter(), dependencies = setOf(dependencyContainer.name)) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("The container 'dependency-container' cannot depend on itself."))) } } } given("a task with a container A that depends on container B, which itself depends on A") { val dependencyContainer = Container("container-b", imageSourceDoesNotMatter(), dependencies = setOf("container-a")) val taskContainer = Container("container-a", imageSourceDoesNotMatter(), dependencies = setOf("container-b")) val runConfig = TaskRunConfiguration(taskContainer.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(taskContainer, dependencyContainer)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("There is a dependency cycle in task 'the-task'. Container 'container-a' depends on 'container-b', which depends on 'container-a'."))) } } } given("a task with a container A that depends on container B, which depends on container C, which itself depends on A") { val containerA = Container("container-a", imageSourceDoesNotMatter(), dependencies = setOf("container-b")) val containerB = Container("container-b", imageSourceDoesNotMatter(), dependencies = setOf("container-c")) val containerC = Container("container-c", imageSourceDoesNotMatter(), dependencies = setOf("container-a")) val runConfig = TaskRunConfiguration(containerA.name, Command.parse("some-command")) val task = Task("the-task", runConfig) val config = Configuration("the-project", TaskMap(task), ContainerMap(containerA, containerB, containerC)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("There is a dependency cycle in task 'the-task'. Container 'container-a' depends on 'container-b', which depends on 'container-c', which depends on 'container-a'."))) } } } given("a task which runs container A, and which has a dependency on container B, which depends on the task container A") { val containerA = Container("container-a", imageSourceDoesNotMatter()) val containerB = Container("container-b", imageSourceDoesNotMatter(), dependencies = setOf(containerA.name)) val runConfig = TaskRunConfiguration(containerA.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf(containerB.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(containerA, containerB)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("There is a dependency cycle in task 'the-task'. Container 'container-b' (which is explicitly started by the task) depends on the task container 'container-a'."))) } } } given("a task which runs container A, and which has a dependency on container B, which has a dependency on container C, which depends on the task container, container A") { val containerA = Container("container-a", imageSourceDoesNotMatter()) val containerC = Container("container-c", imageSourceDoesNotMatter(), dependencies = setOf(containerA.name)) val containerB = Container("container-b", imageSourceDoesNotMatter(), dependencies = setOf(containerC.name)) val runConfig = TaskRunConfiguration(containerA.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf(containerB.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(containerA, containerB, containerC)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("There is a dependency cycle in task 'the-task'. Container 'container-b' (which is explicitly started by the task) depends on 'container-c', and 'container-c' depends on the task container 'container-a'."))) } } } given("a task which runs container A, and which has a dependency on container B, which has a dependency on container C, which has a dependency on container D, which depends on the task container, container A") { val containerA = Container("container-a", imageSourceDoesNotMatter()) val containerD = Container("container-d", imageSourceDoesNotMatter(), dependencies = setOf(containerA.name)) val containerC = Container("container-c", imageSourceDoesNotMatter(), dependencies = setOf(containerD.name)) val containerB = Container("container-b", imageSourceDoesNotMatter(), dependencies = setOf(containerC.name)) val runConfig = TaskRunConfiguration(containerA.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf(containerB.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(containerA, containerB, containerC, containerD)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("There is a dependency cycle in task 'the-task'. Container 'container-b' (which is explicitly started by the task) depends on 'container-c', and 'container-c' depends on 'container-d', and 'container-d' depends on the task container 'container-a'."))) } } } given("a task which runs container A, and which has a dependency on container B, which has a dependency on container C, which depends on container B") { val containerA = Container("container-a", imageSourceDoesNotMatter()) val containerC = Container("container-c", imageSourceDoesNotMatter(), dependencies = setOf("container-b")) val containerB = Container("container-b", imageSourceDoesNotMatter(), dependencies = setOf(containerC.name)) val runConfig = TaskRunConfiguration(containerA.name, Command.parse("some-command")) val task = Task("the-task", runConfig, dependsOnContainers = setOf(containerB.name)) val config = Configuration("the-project", TaskMap(task), ContainerMap(containerA, containerB, containerC)) on("creating the graph") { it("throws an exception") { assertThat({ ContainerDependencyGraph(config, task, commandResolver, entrypointResolver) }, throws<DependencyResolutionFailedException>(withMessage("There is a dependency cycle in task 'the-task'. Container 'container-b' (which is explicitly started by the task) depends on 'container-c', and 'container-c' depends on 'container-b'."))) } } } } }) inline fun <T, R> Iterable<T>.mapToSet(transform: (T) -> R): Set<R> = this.map(transform).toSet()
4
null
1
1
e933116cad5b1c5c877233317534ba3e91e9475e
53,447
batect
Apache License 2.0
src/main/kotlin/ch/compile/blitzremote/actions/CloseAction.kt
KeeTraxx
146,708,971
false
null
package ch.compile.blitzremote.actions import ch.compile.blitzremote.components.BlitzTerminal import org.slf4j.LoggerFactory import java.awt.event.ActionEvent import javax.swing.AbstractAction open class CloseAction(private val terminal: BlitzTerminal) : AbstractAction("Close...") { companion object { val LOG = LoggerFactory.getLogger(this::class.java)!! } override fun actionPerformed(p0: ActionEvent?) { LOG.info("Closing terminal ${terminal.connectionEntry.name} (${terminal.connectionEntry.hostname})...") terminal.terminal.close() } }
0
Kotlin
0
2
36f6a1ea49fab225b392aab35f7c7d7d2353ac58
586
blitz-remote
MIT License
app/src/main/java/com/meuus90/imagesearch/model/data/source/local/BaseDao.kt
meuus90
313,014,138
false
null
package com.meuus90.daumbooksearch.model.data.source.local import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Update interface BaseDao<T> { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(vararg obj: T) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(obj: T) @Insert(onConflict = OnConflictStrategy.REPLACE) @JvmSuppressWildcards suspend fun insert(obj: MutableList<T>) @Insert(onConflict = OnConflictStrategy.REPLACE) @JvmSuppressWildcards suspend fun insert(obj: ArrayList<T>) @Delete suspend fun delete(obj: T) @Update(onConflict = OnConflictStrategy.REPLACE) suspend fun update(vararg obj: T) @Update(onConflict = OnConflictStrategy.REPLACE) suspend fun update(obj: T) @Update(onConflict = OnConflictStrategy.REPLACE) suspend fun update(obj: MutableList<T>) }
0
Kotlin
1
1
148a9122c3eb0ffc533d1e1d1073e3f6b1a4dc50
950
ImageSearchAndroid
MIT License
app/src/main/java/com/example/monni/ui/NotificationsDialogUiState.kt
TheKiesling
521,474,974
false
null
package com.example.monni.ui sealed interface NotificationsDialogUiState { data class Error(val msg: String, val type: Int): NotificationsDialogUiState object Success: NotificationsDialogUiState object Default: NotificationsDialogUiState }
1
Kotlin
0
4
11e6f32970b087c40e93bf7550916199a22bfbf5
254
Monni
MIT License
app/src/main/java/com/example/android/politicalpreparedness/election/ElectionsFragment.kt
hoangvu2511
806,047,081
false
{"Kotlin": 40806}
package com.example.android.politicalpreparedness.election import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.android.politicalpreparedness.databinding.FragmentElectionBinding import com.example.android.politicalpreparedness.election.adapter.ElectionListAdapter import com.example.android.politicalpreparedness.network.models.Election import org.koin.androidx.viewmodel.ext.android.viewModel class ElectionsFragment : Fragment(), ElectionListAdapter.ElectionListener { private lateinit var binding: FragmentElectionBinding private val viewModel: ElectionsViewModel by viewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentElectionBinding.inflate(inflater) val upcomingElectionsAdapter = ElectionListAdapter(this) binding.upcomingElectionsRecycler.adapter = upcomingElectionsAdapter val savedElectionsAdapter = ElectionListAdapter(this) binding.savedElectionsRecycler.adapter = savedElectionsAdapter binding.lifecycleOwner = this binding.viewModel = viewModel viewModel.upcomingElections.observe(viewLifecycleOwner) { upcomingElectionsAdapter.submitList(it) } viewModel.savedElections.observe(viewLifecycleOwner) { savedElectionsAdapter.submitList(it) } viewModel.loadUpcomingElections() viewModel.loadSavedElections() return binding.root } override fun onClick(election: Election) { findNavController().navigate( ElectionsFragmentDirections.actionElectionsFragmentToVoterInfoFragment(election) ) } }
0
Kotlin
0
0
882fc352fe4bdfa2a3dd18bf5c0a3ede3f315884
1,890
Udacity-Android-kotlin-p5
Apache License 2.0
waltid-wallet-api/src/main/kotlin/id/walt/webwallet/service/account/EmailAccountStrategy.kt
walt-id
701,058,624
false
null
package id.walt.webwallet.service.account import de.mkammerer.argon2.Argon2Factory import id.walt.commons.web.ConflictException import id.walt.commons.web.UnauthorizedException import id.walt.webwallet.db.models.Accounts import id.walt.webwallet.web.controllers.auth.ByteLoginRequest import id.walt.webwallet.web.model.EmailAccountRequest import kotlinx.datetime.Clock import kotlinx.datetime.toJavaInstant import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.transactions.transaction import kotlin.uuid.ExperimentalUuidApi import kotlin.uuid.Uuid @OptIn(ExperimentalUuidApi::class) object EmailAccountStrategy : PasswordAccountStrategy<EmailAccountRequest>() { override suspend fun register(tenant: String, request: EmailAccountRequest): Result<RegistrationResult> = runCatching { val name = request.name val email = request.email require(email.isNotBlank()) { "Email must not be blank!" } require(request.password.isNotBlank()) { "Password must not be blank!" } if (AccountsService.hasAccountEmail(tenant, email)) { throw ConflictException("An account with email $email already exists.") } val hash = hashPassword(ByteLoginRequest(request).password) val createdAccountId = transaction { Accounts.insert { it[Accounts.tenant] = tenant it[id] = Uuid.random() it[Accounts.name] = name it[Accounts.email] = email it[password] = hash it[createdOn] = Clock.System.now().toJavaInstant() }[Accounts.id] } RegistrationResult(createdAccountId) } //override suspend fun authenticate(tenant: String, request: EmailAccountRequest): AuthenticatedUser = UsernameAuthenticatedUser(Uuid("a218913e-b8ec-4ef4-a945-7e9ada448ff9"), request.email) override suspend fun authenticate(tenant: String, request: EmailAccountRequest): AuthenticatedUser = ByteLoginRequest(request).let { req -> val email = request.email val (matchedAccount, pwHash) = transaction { val accounts = Accounts.selectAll().where { (Accounts.tenant eq tenant) and (Accounts.email eq email) } if (accounts.empty()) { throw UnauthorizedException("Unknown user \"${req.username}\".") } val matchedAccount = accounts.first() val pwHash = matchedAccount[Accounts.password] ?: throw UnauthorizedException("User \"${req.username}\" does not have password authentication enabled.") Pair(matchedAccount, pwHash) } val passwordMatches = Argon2Factory.create().run { verify(pwHash, req.password).also { wipeArray(req.password) } } if (passwordMatches) { val id = matchedAccount[Accounts.id] // TODO: change id to wallet-id (also in the frontend) return UsernameAuthenticatedUser(id, req.username) } else { throw UnauthorizedException("Invalid password for \"${req.username}\"!") } } }
46
null
5
98
a86bd0c843d594f6afe6e747d3c4de7d8a4789a8
3,334
waltid-identity
Apache License 2.0
src/main/kotlin/com/github/lazoyoung/craftgames/api/shopkeepers/GameShopkeeper.kt
LazoYoung
120,482,014
false
null
package com.github.lazoyoung.craftgames.api.shopkeepers import com.github.lazoyoung.craftgames.impl.game.GameLayout import com.nisovin.shopkeepers.api.shopkeeper.admin.regular.RegularAdminShopkeeper import com.nisovin.shopkeepers.api.shopkeeper.offers.TradingOffer import com.nisovin.shopkeepers.shopkeeper.offers.SKTradingOffer import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.inventory.ItemStack import java.io.IOException import java.nio.file.FileAlreadyExistsException import java.nio.file.Files class GameShopkeeper( private val layout: GameLayout, private val instance: RegularAdminShopkeeper ) { private var id: String? = null fun getTrades(): List<Trade> { return instance.offers.map { encapsulate(it) } } fun clearTrades() { instance.clearOffers() } fun setTrades(trade: List<Trade>) { instance.offers = trade.map { decapsulate(it) } } fun addTrade(trade: Trade) { instance.addOffer(decapsulate(trade)) } fun load(id: String) { check(this.id == null) { "This shopkeeper is already loaded with id: ${this.id}" } this.id = id val fileName = id.plus(".yml") val path = layout.shopkeepersDir.resolve(fileName) if (!Files.isRegularFile(path)) { return } try { path.toFile().bufferedReader().use { val config = YamlConfiguration.loadConfiguration(it) val entries = config.getMapList("offers") for (entry in entries) { val result = entry["result"] as ItemStack val item1 = entry["item1"] as ItemStack val item2 = entry["item2"] as ItemStack? addTrade(Trade(result, item1, item2)) } } } catch (e: Exception) { e.printStackTrace() } } fun save(id: String) { check(this.id == null) { "This shopkeeper is already saved with id: ${this.id}" } check(instance.isValid) { "This shopkeeper is not valid." } check(instance.shopObject.isActive) { "This shopkeeper object is not active." } this.id = id val fileName = id.plus(".yml") val path = layout.shopkeepersDir.resolve(fileName) val entries = ArrayList<Map<String, ItemStack?>>() val file = path.toFile() try { Files.createDirectories(path.parent!!) Files.createFile(path) } catch (e: FileAlreadyExistsException) { // ignore } catch (e: IOException) { e.printStackTrace() } file.bufferedReader().use { reader -> val config = YamlConfiguration.loadConfiguration(reader) getTrades().forEach { val map = HashMap<String, ItemStack?>() map["result"] = it.result map["item1"] = it.cost1 map["item2"] = it.cost2 entries.add(map) } config.set("offers", entries) config.save(file) } } fun discard() { checkNotNull(id) { "Cannot discard this shopkeeper because it's not saved." } val fileName = id.plus(".yml") val path = layout.shopkeepersDir.resolve(fileName) try { Files.deleteIfExists(path) } catch (e: IOException) { e.printStackTrace() } } private fun encapsulate(o: TradingOffer): Trade { return Trade(o.resultItem, o.item1, o.item2) } private fun decapsulate(t: Trade): TradingOffer { return SKTradingOffer(t.result, t.cost1, t.cost2) } }
8
null
1
3
280dc702f2225071d67acf0ea675db575cdd0d65
3,808
CraftGames
MIT License
composeApp/src/commonMain/kotlin/nl/mdsystems/domain/utils/file/FileSize.kt
MikeDirven
866,569,963
false
{"Kotlin": 100228}
package nl.mdsystems.domain.utils.file import nl.mdsystems.domain.enums.FileSizeType import java.io.File fun File.size(type: FileSizeType = FileSizeType.BYTES): String { return if(this.isFile){ this.length() } else { this.walkTopDown().filter { it.isFile }.sumOf { it.length() } }.let { bytes -> when(type){ FileSizeType.BYTES -> "${bytes}B" FileSizeType.KILOBYTES ->"${bytes / 1024}KB" FileSizeType.MEGABYTES-> "${bytes / (1024 * 1024)}MB" FileSizeType.GIGABYTES -> "${bytes / (1024 * 1024 * 1024)}GB" } } }
17
Kotlin
0
1
95fdf5b088c5790efcc9be1d3db64fa34f7f3078
626
jpackager
Apache License 2.0
src/main/kotlin/no/nav/tilleggsstonader/sak/opplysninger/aktivitet/AktivitetService.kt
navikt
685,490,225
false
{"Kotlin": 1923144, "Gherkin": 41142, "HTML": 39787, "Shell": 924, "Dockerfile": 164}
package no.nav.tilleggsstonader.sak.opplysninger.aktivitet import no.nav.tilleggsstonader.kontrakter.aktivitet.AktivitetArenaDto import no.nav.tilleggsstonader.kontrakter.aktivitet.GruppeAktivitet import no.nav.tilleggsstonader.kontrakter.aktivitet.TypeAktivitet import no.nav.tilleggsstonader.libs.log.SecureLogger.secureLogger import no.nav.tilleggsstonader.libs.utils.osloDateNow import no.nav.tilleggsstonader.sak.fagsak.domain.FagsakPersonService import no.nav.tilleggsstonader.sak.felles.domain.FagsakPersonId import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.time.LocalDate @Service class AktivitetService( private val fagsakPersonService: FagsakPersonService, private val aktivitetClient: AktivitetClient, ) { private val logger = LoggerFactory.getLogger(javaClass) fun hentAktiviteterMedPerioder( fagsakPersonId: FagsakPersonId, fom: LocalDate = osloDateNow().minusYears(3), tom: LocalDate = osloDateNow().plusYears(1), ): AktiviteterDto = AktiviteterDto( periodeHentetFra = fom, periodeHentetTil = tom, aktiviteter = hentAktiviteter(fagsakPersonId, fom, tom), ) fun hentAktiviteter( fagsakPersonId: FagsakPersonId, fom: LocalDate = osloDateNow().minusYears(3), tom: LocalDate = osloDateNow().plusYears(1), ): List<AktivitetArenaDto> { val ident = fagsakPersonService.hentAktivIdent(fagsakPersonId) return hentStønadsberettigedeTiltak(ident, fom, tom) } fun hentAktiviteterForGrunnlagsdata(ident: String, fom: LocalDate, tom: LocalDate): List<AktivitetArenaDto> { return aktivitetClient.hentAktiviteter( ident = ident, fom = fom, tom = tom, ) // Det er alltid gruppe=TILTAK når erStønadsberettiget = true (men alle av tiltak er ikke stønadsberettiget) .filter { it.erStønadsberettiget == true } .sortedByDescending { it.fom } } private fun hentStønadsberettigedeTiltak( ident: String, fom: LocalDate, tom: LocalDate, ) = aktivitetClient.hentAktiviteter( ident = ident, fom = fom, tom = tom, ) .filter { try { // Ikke alle aktiviteter har fått flagg "stønadsberettiget" i Arena selv om de skulle hatt det, så vi trenger en ekstra sjekk på gruppe // Det er alltid gruppe=TILTAK når erStønadsberettiget = true, men ikke alle tiltak er stønadsberettiget it.erStønadsberettiget == true || TypeAktivitet.valueOf(it.type).gruppe == GruppeAktivitet.TLTAK } catch (e: Exception) { logger.error("TypeAktivitet mangler mapping, se secure logs for detaljer.") secureLogger.error("TypeAktivitet=${it.type} mangler mapping. Vennligst oppdater TypeAktivitet med ny type.") false } } .sortedByDescending { it.fom } }
5
Kotlin
1
0
df7bf11b9645dce589179f9cd856f6e4a31eba87
2,991
tilleggsstonader-sak
MIT License
deprecated/stately-collections/src/commonTest/kotlin/co/touchlab/stately/collections/SharedSetTest.kt
touchlab
153,214,696
false
null
/* * Copyright (C) 2018 Touchlab, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.touchlab.stately.collections import kotlin.test.Test import kotlin.test.assertEquals class SharedSetTest { @Test fun dataClassEquals() { val set = frozenHashSet<CollectionValues>() assertEquals(0, set.size) set.add(CollectionValues("asdf", 123)) assertEquals(1, set.size) set.add(CollectionValues("asdf", 123)) assertEquals(1, set.size) set.add(CollectionValues("asdf", 124)) assertEquals(2, set.size) } data class CollectionValues(val a: String, val b: Int) /*@Test fun testLambdas(){ val set = SharedSet<()->Unit>() val a: () -> Unit = { 1 + 2 } val b: () -> Unit = { 1 + 2 } val c: () -> Unit = { 2 + 2 } assertEquals(a, b) assertNotEquals(a, c) set.add(a) set.add(b) assertEquals(1, set.size) set.add(c) assertEquals(2, set.size) }*/ }
8
null
28
591
6ae0eb15df77dc4e44a2e1b6707afd5702cf0298
1,518
Stately
Apache License 2.0
ideplugin/src/main/kotlin/com/birbit/artifactfinder/ideplugin/VersionSelectionPopupController.kt
yigit
209,722,505
false
null
/* * Copyright 2019 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.birbit.artifactfinder.ideplugin import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import java.awt.Toolkit import java.awt.datatransfer.StringSelection import org.jetbrains.kotlin.idea.util.projectStructure.allModules @Suppress("UNUSED_PARAMETER") class VersionSelectionPopupController( private val result: SearchResultModel.SearchResult, private val project: Project, private val currentModule: Module?, private val callback: Callback ) { fun buildPopup(): ListPopup { val popupStep = VersionStep( versions = result.versions ) { handleChoice(it) callback.onChosen() } return JBPopupFactory.getInstance() .createListPopup(popupStep) } private fun handleChoice(choice: Choice) { checkNotNull(choice.version) { "must choose a version" } checkNotNull(choice.action) { "must choose an action" } check(!choice.action.needsModule || choice.module != null) { "should either pick an action that does not require a module or pick a module" } when (choice.action) { Action.ADD_TO_GRADLE -> { addToGradle(choice.version, choice.module!!, false) } Action.ADD_TO_GRADLE_WITH_PROCESSOR -> { addToGradle(choice.version, choice.module!!, true) } Action.COPY_COORDINATES -> { copyToClipboard(choice.version, false) } Action.COPY_WITH_PROCESSOR -> { copyToClipboard(choice.version, true) } } } private fun addToGradle(version: String, module: Module, includeProcessor: Boolean) { val dependencyUtil = BuildDependencyHandler(module) val artifact = result.qualifiedArtifact(version) dependencyUtil.addMavenDependency( coordinate = artifact, onSuccess = { showNotification("Added $artifact to ${module.name}'s dependencies.") }, onError = { msg -> showError("Unable to add $artifact to ${module.name}'s dependencies. $msg") }) } private fun copyToClipboard(version: String, includeProcessor: Boolean) { val artifact = result.qualifiedArtifact(version) val selection = StringSelection(artifact) Toolkit.getDefaultToolkit().systemClipboard.setContents(selection, selection) showNotification("Copied $artifact into clipboard") } private fun showNotification(msg: String) { Notifications.Bus.notify( Notification("artifact-finder", "Artifact Finder", msg, NotificationType.INFORMATION), project ) } private fun showError(msg: String) { Notifications.Bus.notify( Notification("artifact-finder", "Artifact Finder", msg, NotificationType.ERROR), project ) } interface Callback { fun onChosen() fun onCancel() } private inner class VersionStep( versions: List<String>, private val callback: (Choice) -> Unit ) : BaseListPopupStep<String>("versions", versions) { override fun hasSubstep(selectedValue: String?): Boolean { return true } override fun getTextFor(value: String?): String { return value ?: "?" } override fun onChosen(selectedValue: String?, finalChoice: Boolean): PopupStep<*>? { if (selectedValue != null) { return ActionStep( choice = Choice( version = selectedValue ), callback = callback ) } return PopupStep.FINAL_CHOICE } override fun isSpeedSearchEnabled() = true } private inner class ActionStep( private val choice: Choice, private val callback: (Choice) -> Unit ) : BaseListPopupStep<Action>("action", Action.getList(false)) { override fun hasSubstep(selectedValue: Action?): Boolean { return selectedValue?.needsModule == true } override fun getTextFor(action: Action?): String { return action?.text ?: "?" } override fun onChosen(selectedValue: Action?, finalChoice: Boolean): PopupStep<*>? { if (selectedValue != null) { val newChoice = choice.copy( action = selectedValue ) if (selectedValue.needsModule) { return ModuleSelectionStep(newChoice, callback) } else if (finalChoice) { callback(newChoice) } } return PopupStep.FINAL_CHOICE } override fun isSpeedSearchEnabled() = true } private inner class ModuleSelectionStep( private val choice: Choice, private val callback: (Choice) -> Unit ) : BaseListPopupStep<Module>("module", project.allModules()) { override fun getDefaultOptionIndex(): Int { return project.allModules().indexOf(currentModule) } override fun hasSubstep(selectedValue: Module?): Boolean { return false } override fun getTextFor(module: Module?): String { return module?.name ?: "?" } override fun onChosen(selectedValue: Module?, finalChoice: Boolean): PopupStep<*>? { if (finalChoice && selectedValue != null) { callback( choice.copy( module = selectedValue ) ) } return PopupStep.FINAL_CHOICE } override fun isSpeedSearchEnabled() = true } private data class Choice( val version: String, val action: Action? = null, val module: Module? = null ) private enum class Action( val text: String, val needsModule: Boolean ) { COPY_COORDINATES("Copy coordinates", false), COPY_WITH_PROCESSOR("Copy with annotation processor", false), ADD_TO_GRADLE("Add to gradle", true), ADD_TO_GRADLE_WITH_PROCESSOR("Add to gradle with processor", true); companion object { fun getList(hasProcessor: Boolean): List<Action> { return if (hasProcessor) { values().toList() } else { listOf(COPY_COORDINATES, ADD_TO_GRADLE) } } } } }
27
null
5
190
ee9f2870d32b8e438f36f0c405473edff28b6b3e
7,632
ArtifactFinder
Apache License 2.0
plugin-build/plugin/src/main/java/ir/amv/enterprise/locorepo/client/gradle/plugin/LoCoRepoPlugin.kt
amirmv2006
366,102,799
false
null
package ir.amv.enterprise.locorepo.client.gradle.plugin import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.Copy import org.gradle.api.tasks.bundling.Zip const val EXTENSION_NAME = "locoRepoConfig" const val TASK_NAME = "locoRepoGenerate" @Suppress("UnnecessaryAbstractClass") abstract class LoCoRepoPlugin : Plugin<Project> { override fun apply(project: Project) = with(project) { // Add the 'locoRepo' extension object val extension = extensions.create(EXTENSION_NAME, LoCoRepoExtension::class.java, this) // Zip loco models val locoRepoDir = layout.buildDirectory.dir("loco-repo") val zipTask = tasks.register("ZipLoCoModels", Zip::class.java) { it.archiveFileName.set("loco-model.zip") it.destinationDirectory.set(locoRepoDir) it .from(layout.projectDirectory) .include(".mps/**/*.*") .include("src/main/mps/**/*.*") } // Add a task that uses configuration from the extension object val gen = tasks.register(TASK_NAME, LoCoRepoGeneratorTask::class.java) { genTask -> genTask.dependsOn(zipTask) genTask.outputFile.set(extension.outputFile) genTask.modelsZip.set(locoRepoDir.map { it.file("loco-model.zip") }) genTask.serviceAccountJson.set(extension.serviceAccountJson) } tasks.register("generate", Copy::class.java) { copy -> copy.dependsOn(gen) copy.from(zipTree(extension.outputFile)) copy.into(locoRepoDir.map { it.dir("generated") }) } Unit } }
1
null
1
1
ee01e80bcc25e7f6ffd91616bcd913a2e86cf159
1,665
kotlin-gradle-plugin-sandbox
MIT License
app-inspection/inspectors/network/model/src/com/android/tools/idea/appinspection/inspectors/network/model/connections/HttpData.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.appinspection.inspectors.network.model.connections import com.android.tools.adtui.model.Range import com.android.tools.idea.protobuf.ByteString import com.intellij.util.io.URLUtil import java.io.ByteArrayInputStream import java.io.IOException import java.net.URI import java.util.TreeMap import java.util.concurrent.TimeUnit import java.util.zip.GZIPInputStream import studio.network.inspection.NetworkInspectorProtocol import studio.network.inspection.NetworkInspectorProtocol.HttpConnectionEvent.Header import studio.network.inspection.NetworkInspectorProtocol.HttpConnectionEvent.HttpTransport const val APPLICATION_FORM_MIME_TYPE = "application/x-www-form-urlencoded" private const val CONTENT_ENCODING = "content-encoding" private const val CONTENT_LENGTH = "content-length" private const val CONTENT_TYPE = "content-type" /** * Data of http url connection. Each [HttpData] object matches a http connection with a unique id, * and it includes both request data and response data. Request data is filled immediately when the * connection starts. Response data may start empty but filled when connection completes. */ data class HttpData( override val id: Long, override val updateTimeUs: Long, override val requestStartTimeUs: Long, override val requestCompleteTimeUs: Long, override val responseStartTimeUs: Long, override val responseCompleteTimeUs: Long, override val connectionEndTimeUs: Long, override val threads: List<JavaThread>, override val url: String, override val method: String, val httpTransport: HttpTransport, override val trace: String, override val requestHeaders: Map<String, List<String>>, override val requestPayload: ByteString, override val responseHeaders: Map<String, List<String>>, override val responsePayload: ByteString, val responseCode: Int, ) : ConnectionData { private val uri: URI? = runCatching { URI.create(url) }.getOrNull() override val transport: String get() = httpTransport.toDisplayText() override val schema: String get() = uri?.scheme ?: "Unknown" override val address: String get() = uri?.host ?: "Unknown" override val path: String get() = uri?.path ?: "Unknown" /** * Return the name of the URL, which is the final complete word in the path portion of the URL. * The query is included as it can be useful to disambiguate requests. Additionally, the returned * value is URL decoded, so that, say, "Hello%2520World" -> "Hello World". * * For example, "www.example.com/demo/" -> "demo" "www.example.com/test.png" -> "test.png" * "www.example.com/test.png?res=2" -> "test.png?res=2" "www.example.com/" -> "www.example.com" */ override val name: String = if (uri == null) { url.lastComponent() } else { val path = uri.path?.lastComponent() when { path == null -> uri.host uri.query != null -> "$path?${uri.query}" path.isBlank() -> uri.host ?: "Unknown" else -> path }.decodeUrl() } override val requestType: String get() = getRequestContentType().mimeType override val requestPayloadText: String get() = "N/A" override val status: String get() = if (responseCode < 0) "" else responseCode.toString() override val error: String get() = "N/A" override val responseType: String get() = getResponseContentType().mimeType override val responsePayloadText: String get() = "N/A" override val responseTrailers: Map<String, List<String>> get() = emptyMap() fun getReadableResponsePayload(): ByteString { return if (getContentEncodings().find { it.lowercase() == "gzip" } != null) { try { GZIPInputStream(ByteArrayInputStream(responsePayload.toByteArray())).use { ByteString.copyFrom(it.readBytes()) } } catch (ignored: IOException) { responsePayload } } else { responsePayload } } internal fun withRequestStarted(event: NetworkInspectorProtocol.Event): HttpData { val timestamp = TimeUnit.NANOSECONDS.toMicros(event.timestamp) val requestStarted = event.httpConnectionEvent.httpRequestStarted return copy( updateTimeUs = timestamp, requestStartTimeUs = timestamp, url = requestStarted.url, method = requestStarted.method, httpTransport = requestStarted.transport, trace = requestStarted.trace, requestHeaders = requestStarted.headersList.toMap(), ) } internal fun withHttpThread(event: NetworkInspectorProtocol.Event) = copy( updateTimeUs = TimeUnit.NANOSECONDS.toMicros(event.timestamp), threads = threads + event.toJavaThread(), ) internal fun withRequestPayload(event: NetworkInspectorProtocol.Event) = copy( updateTimeUs = TimeUnit.NANOSECONDS.toMicros(event.timestamp), requestPayload = event.httpConnectionEvent.requestPayload.payload, ) internal fun withRequestCompleted(event: NetworkInspectorProtocol.Event): HttpData { val timestamp = TimeUnit.NANOSECONDS.toMicros(event.timestamp) return copy( updateTimeUs = timestamp, requestCompleteTimeUs = timestamp, ) } internal fun withResponseStarted(event: NetworkInspectorProtocol.Event): HttpData { val timestamp = TimeUnit.NANOSECONDS.toMicros(event.timestamp) val responseStarted = event.httpConnectionEvent.httpResponseStarted return copy( updateTimeUs = timestamp, responseStartTimeUs = timestamp, responseCode = responseStarted.responseCode, responseHeaders = responseStarted.headersList.toMap(), ) } internal fun withResponsePayload(event: NetworkInspectorProtocol.Event) = copy( updateTimeUs = TimeUnit.NANOSECONDS.toMicros(event.timestamp), responsePayload = event.httpConnectionEvent.responsePayload.payload, ) internal fun withResponseCompleted(event: NetworkInspectorProtocol.Event): HttpData { val timestamp = TimeUnit.NANOSECONDS.toMicros(event.timestamp) return copy( updateTimeUs = timestamp, responseCompleteTimeUs = timestamp, ) } internal fun withHttpClosed(event: NetworkInspectorProtocol.Event): HttpData { val timestamp = TimeUnit.NANOSECONDS.toMicros(event.timestamp) return copy( updateTimeUs = timestamp, connectionEndTimeUs = timestamp, ) } internal fun intersectsRange(range: Range): Boolean { val start = requestStartTimeUs val end = updateTimeUs val min = range.min.toLong() val max = range.max.toLong() return start <= max && end >= min } fun getRequestContentType() = ContentType(requestHeaders[CONTENT_TYPE]?.firstOrNull() ?: "") fun getResponseContentType() = ContentType(responseHeaders[CONTENT_TYPE]?.firstOrNull() ?: "") fun getResponseContentLength() = responseHeaders[CONTENT_LENGTH]?.firstOrNull()?.toIntOrNull() ?: -1 class ContentType(private val contentType: String) { val isEmpty = contentType.isEmpty() /** * @return MIME type related information from Content-Type because Content-Type may contain * other information such as charset or boundary. * * Examples: "text/html; charset=utf-8" => "text/html" "text/html" => "text/html" */ val mimeType = contentType.split(';').first() override fun toString() = contentType val isFormData = mimeType.equals(APPLICATION_FORM_MIME_TYPE, ignoreCase = true) } companion object { fun createHttpData( id: Long, updateTimeUs: Long = 0, requestStartTimeUs: Long = 0, requestCompleteTimeUs: Long = 0, responseStartTimeUs: Long = 0, responseCompleteTimeUs: Long = 0, connectionEndTimeUs: Long = 0, threads: List<JavaThread> = emptyList(), url: String = "", method: String = "", transport: HttpTransport = HttpTransport.UNDEFINED, trace: String = "", requestHeaders: List<Header> = emptyList(), requestPayload: ByteString = ByteString.EMPTY, responseHeaders: List<Header> = emptyList(), responsePayload: ByteString = ByteString.EMPTY, responseCode: Int = -1, ): HttpData { return HttpData( id, updateTimeUs, requestStartTimeUs, requestCompleteTimeUs, responseStartTimeUs, responseCompleteTimeUs, connectionEndTimeUs, threads.distinctBy { it.id }, url, method, transport, trace, requestHeaders.toMap(), requestPayload, responseHeaders.toMap(), responsePayload, responseCode, ) } } } fun HttpData.getContentEncodings() = responseHeaders[CONTENT_ENCODING] ?: emptyList() private fun String.lastComponent() = trimEnd('/').substringAfterLast('/') /** * Decodes a URL Component * * A URL might be encoded an arbitrarily deep number of times. Keep decoding until we peel away the * final layer. Usually this is only expected to loop once or twice. * [See more](http://stackoverflow.com/questions/3617784/plus-signs-being-replaced-for-252520) */ private fun String.decodeUrl(): String { var currentValue = this var lastValue: String do { lastValue = currentValue try { currentValue = URLUtil.decode(currentValue) } catch (e: Exception) { return this } } while (currentValue != lastValue) return currentValue } private fun NetworkInspectorProtocol.Event.toJavaThread() = JavaThread(httpConnectionEvent.httpThread.threadId, httpConnectionEvent.httpThread.threadName) private fun List<Header>.toMap() = associateTo(TreeMap(String.CASE_INSENSITIVE_ORDER)) { it.key to it.valuesList } private fun HttpTransport.toDisplayText() = when (this) { HttpTransport.JAVA_NET -> "Java Native" HttpTransport.OKHTTP2 -> "OkHttp 2" HttpTransport.OKHTTP3 -> "OkHttp 3" HttpTransport.UNDEFINED, HttpTransport.UNRECOGNIZED -> "Unknown" }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
10,520
android
Apache License 2.0
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/MENUBARS.kt
apache
6,935,442
false
null
/* * 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.isis.client.kroviz.snapshots.demo2_0_0 import org.apache.isis.client.kroviz.snapshots.Response object DEMO_MENUBARS : Response(){ override val url = "http://localhost:8080/restful/menuBars" override val str = """{ "primary": { "menu": [ { "named": "Basic Types", "cssClassFa": null, "section": [ { "named": "Primitives", "serviceAction": [ { "objectType": "demo.PrimitiveTypesMenu", "id": "shorts", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PrimitiveTypesMenu/1/actions/shorts", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PrimitiveTypesMenu", "id": "ints", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PrimitiveTypesMenu/1/actions/ints", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PrimitiveTypesMenu", "id": "longs", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PrimitiveTypesMenu/1/actions/longs", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PrimitiveTypesMenu", "id": "bytes", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PrimitiveTypesMenu/1/actions/bytes", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PrimitiveTypesMenu", "id": "floats", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PrimitiveTypesMenu/1/actions/floats", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PrimitiveTypesMenu", "id": "doubles", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PrimitiveTypesMenu/1/actions/doubles", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PrimitiveTypesMenu", "id": "chars", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PrimitiveTypesMenu/1/actions/chars", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PrimitiveTypesMenu", "id": "booleans", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PrimitiveTypesMenu/1/actions/booleans", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Wrappers", "serviceAction": [ { "objectType": "demo.JavaLangWrapperTypesMenu", "id": "bytes", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangWrapperTypesMenu/1/actions/bytes", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaLangWrapperTypesMenu", "id": "shorts", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangWrapperTypesMenu/1/actions/shorts", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaLangWrapperTypesMenu", "id": "integers", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangWrapperTypesMenu/1/actions/integers", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaLangWrapperTypesMenu", "id": "longs", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangWrapperTypesMenu/1/actions/longs", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaLangWrapperTypesMenu", "id": "floats", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangWrapperTypesMenu/1/actions/floats", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaLangWrapperTypesMenu", "id": "doubles", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangWrapperTypesMenu/1/actions/doubles", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaLangWrapperTypesMenu", "id": "characters", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangWrapperTypesMenu/1/actions/characters", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaLangWrapperTypesMenu", "id": "booleans", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangWrapperTypesMenu/1/actions/booleans", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Common", "serviceAction": [ { "objectType": "demo.JavaLangTypesMenu", "id": "strings", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangTypesMenu/1/actions/strings", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaLangTypesMenu", "id": "voids", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaLangTypesMenu/1/actions/voids", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Temporal Types", "cssClassFa": null, "section": [ { "named": "java.sql", "serviceAction": [ { "objectType": "demo.JavaSqlTypesMenu", "id": "dates", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaSqlTypesMenu/1/actions/dates", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaSqlTypesMenu", "id": "timestamps", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaSqlTypesMenu/1/actions/timestamps", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "java.time", "serviceAction": [ { "objectType": "demo.JavaTimeTypesMenu", "id": "localDates", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaTimeTypesMenu/1/actions/localDates", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaTimeTypesMenu", "id": "localDateTimes", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaTimeTypesMenu/1/actions/localDateTimes", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaTimeTypesMenu", "id": "offsetDateTimes", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaTimeTypesMenu/1/actions/offsetDateTimes", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaTimeTypesMenu", "id": "offsetTimes", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaTimeTypesMenu/1/actions/offsetTimes", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaTimeTypesMenu", "id": "zonedDateTimes", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaTimeTypesMenu/1/actions/zonedDateTimes", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "java.util", "serviceAction": [ { "objectType": "demo.JavaUtilTypesMenu", "id": "dates", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaUtilTypesMenu/1/actions/dates", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "JodaTime", "serviceAction": [ { "objectType": "demo.JodaTimeTypesMenu", "id": "localDates", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JodaTimeTypesMenu/1/actions/localDates", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JodaTimeTypesMenu", "id": "localDateTimes", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JodaTimeTypesMenu/1/actions/localDateTimes", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JodaTimeTypesMenu", "id": "dateTimes", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JodaTimeTypesMenu/1/actions/dateTimes", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "More Types", "cssClassFa": null, "section": [ { "named": "java.awt", "serviceAction": [ { "objectType": "demo.JavaAwtTypesMenu", "id": "images", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaAwtTypesMenu/1/actions/images", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "java.math", "serviceAction": [ { "objectType": "demo.JavaMathTypesMenu", "id": "bigDecimals", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaMathTypesMenu/1/actions/bigDecimals", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JavaMathTypesMenu", "id": "bigIntegers", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaMathTypesMenu/1/actions/bigIntegers", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "java.net", "serviceAction": [ { "objectType": "demo.JavaNetTypesMenu", "id": "urls", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaNetTypesMenu/1/actions/urls", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "java.util", "serviceAction": [ { "objectType": "demo.JavaUtilTypesMenu", "id": "uuids", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JavaUtilTypesMenu/1/actions/uuids", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Apache Isis Core", "serviceAction": [ { "objectType": "demo.IsisTypesMenu", "id": "blobs", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.IsisTypesMenu/1/actions/blobs", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.IsisTypesMenu", "id": "clobs", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.IsisTypesMenu/1/actions/clobs", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.IsisTypesMenu", "id": "localResourcePaths", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.IsisTypesMenu/1/actions/localResourcePaths", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.IsisTypesMenu", "id": "markups", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.IsisTypesMenu/1/actions/markups", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.IsisTypesMenu", "id": "passwords", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.IsisTypesMenu/1/actions/passwords", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Apache Isis Extensions", "serviceAction": [ { "objectType": "demo.IsisExtTypesMenu", "id": "asciiDocs", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.IsisExtTypesMenu/1/actions/asciiDocs", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.IsisExtTypesMenu", "id": "markdowns", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.IsisExtTypesMenu/1/actions/markdowns", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Domain Annot", "cssClassFa": null, "section": [ { "named": "@DomainObject", "serviceAction": [ { "objectType": "demo.DomainObjectMenu", "id": "publishing", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.DomainObjectMenu/1/actions/publishing", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "@Action", "serviceAction": [ { "objectType": "demo.ActionMenu", "id": "associateWith", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ActionMenu/1/actions/associateWith", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.ActionMenu", "id": "command", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ActionMenu/1/actions/command", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.ActionMenu", "id": "domainEvent", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ActionMenu/1/actions/domainEvent", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.ActionMenu", "id": "hidden", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ActionMenu/1/actions/hidden", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.ActionMenu", "id": "publishing", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ActionMenu/1/actions/publishing", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.ActionMenu", "id": "typeOf", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ActionMenu/1/actions/typeOf", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "@Property", "serviceAction": [ { "objectType": "demo.PropertyMenu", "id": "command", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/command", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "domainEvent", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/domainEvent", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "editing", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/editing", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "fileAccept", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/fileAccept", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "hidden", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/hidden", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "maxLength", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/maxLength", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "mustSatisfy", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/mustSatisfy", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "optionality", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/optionality", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "publishing", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/publishing", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyMenu", "id": "regexPattern", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyMenu/1/actions/regexPattern", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Layout Annot", "cssClassFa": null, "section": [ { "named": "@ActionLayout", "serviceAction": [ { "objectType": "demo.ActionLayoutMenu", "id": "position", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ActionLayoutMenu/1/actions/position", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.ActionLayoutMenu", "id": "promptStyle", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ActionLayoutMenu/1/actions/promptStyle", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "@PropertyLayout", "serviceAction": [ { "objectType": "demo.PropertyLayoutMenu", "id": "cssClass", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/cssClass", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "describedAs", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/describedAs", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "hidden", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/hidden", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "labelPosition", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/labelPosition", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "multiLine", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/multiLine", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "named", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/named", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "navigable", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/navigable", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "renderDay", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/renderDay", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "repainting", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/repainting", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.PropertyLayoutMenu", "id": "typicalLength", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.PropertyLayoutMenu/1/actions/typicalLength", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Services", "cssClassFa": null, "section": [ { "named": null, "serviceAction": [ { "objectType": "demo.ServicesMenu", "id": "wrapperFactory", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ServicesMenu/1/actions/wrapperFactory", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "View Models", "cssClassFa": null, "section": [ { "named": null, "serviceAction": [ { "objectType": "demo.ViewModelMenu", "id": "stateful", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ViewModelMenu/1/actions/stateful", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.ViewModelMenu", "id": "statefulRefsEntity", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ViewModelMenu/1/actions/statefulRefsEntity", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Actions", "cssClassFa": null, "section": [ { "named": null, "serviceAction": [ { "objectType": "demo.AssociatedActionMenu", "id": "associatedActions", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.AssociatedActionMenu/1/actions/associatedActions", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.AsyncActionMenu", "id": "asyncActions", "named": "Background (Async) Actions", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.AsyncActionMenu/1/actions/asyncActions", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.DependentArgsActionMenu", "id": "dependentArgsActions", "named": "Dependent Arguments", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.DependentArgsActionMenu/1/actions/dependentArgsActions", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.MixinMenu", "id": "mixinDemo", "named": "Mixins", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.MixinMenu/1/actions/mixinDemo", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.MixinLegacyMenu", "id": "mixinLegacyDemo", "named": "Mixins (Legacy)", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.MixinLegacyMenu/1/actions/mixinLegacyDemo", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Misc", "cssClassFa": null, "section": [ { "named": "Tooltips", "serviceAction": [ { "objectType": "demo.TooltipMenu", "id": "tooltipDemo", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.TooltipMenu/1/actions/tooltipDemo", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Events", "serviceAction": [ { "objectType": "demo.EventsDemoMenu", "id": "eventsDemo", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.EventsDemoMenu/1/actions/eventsDemo", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Error Handling", "serviceAction": [ { "objectType": "demo.ErrorMenu", "id": "errorHandling", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.ErrorMenu/1/actions/errorHandling", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Tabs", "serviceAction": [ { "objectType": "demo.TabMenu", "id": "tabDemo", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.TabMenu/1/actions/tabDemo", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Extensions", "cssClassFa": null, "section": [ { "named": "SecMan", "serviceAction": [ { "objectType": "demo.IsisExtSecManMenu", "id": "appTenancy", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.IsisExtSecManMenu/1/actions/appTenancy", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Experimental", "cssClassFa": null, "section": [ { "named": null, "serviceAction": [ { "objectType": "demo.TupleDemoMenu", "id": "tupleDemo", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.TupleDemoMenu/1/actions/tupleDemo", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demo.JeeMenu", "id": "jeeInjectDemo", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demo.JeeMenu/1/actions/jeeInjectDemo", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Other", "cssClassFa": null, "unreferencedActions": true } ] }, "secondary": { "menu": [ { "named": "Prototyping", "cssClassFa": null, "section": [ { "named": null, "serviceAction": [ { "objectType": "isisExtFixtures.FixtureScripts", "id": "runFixtureScript", "named": "Run Fixture Script", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtFixtures.FixtureScripts/1/actions/runFixtureScript", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisExtFixtures.FixtureScripts", "id": "recreateObjectsAndReturnFirst", "named": "Recreate Objects And Return First", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtFixtures.FixtureScripts/1/actions/recreateObjectsAndReturnFirst", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isisApplib.LayoutServiceMenu", "id": "downloadLayouts", "named": "Download Object Layouts (ZIP)", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.LayoutServiceMenu/1/actions/downloadLayouts", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisApplib.LayoutServiceMenu", "id": "downloadMenuBarsLayout", "named": "Download Menu Bars Layout (XML)", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.LayoutServiceMenu/1/actions/downloadMenuBarsLayout", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isisApplib.MetaModelServiceMenu", "id": "downloadMetaModelXml", "named": "Download Meta Model (XML)", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.MetaModelServiceMenu/1/actions/downloadMetaModelXml", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisApplib.MetaModelServiceMenu", "id": "downloadMetaModelCsv", "named": "Download Meta Model (CSV)", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.MetaModelServiceMenu/1/actions/downloadMetaModelCsv", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isisJdoDn5.JdoMetamodelMenu", "id": "downloadMetamodels", "named": "Download JDO Metamodels (ZIP)", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisJdoDn5.JdoMetamodelMenu/1/actions/downloadMetamodels", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isisApplib.SwaggerServiceMenu", "id": "openSwaggerUi", "named": "Open Swagger Ui", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.SwaggerServiceMenu/1/actions/openSwaggerUi", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisApplib.SwaggerServiceMenu", "id": "openRestApi", "named": "Open Rest Api", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.SwaggerServiceMenu/1/actions/openRestApi", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisApplib.SwaggerServiceMenu", "id": "downloadSwaggerSchemaDefinition", "named": "Download Swagger Schema Definition", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.SwaggerServiceMenu/1/actions/downloadSwaggerSchemaDefinition", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isisApplib.TranslationServicePoMenu", "id": "downloadTranslations", "named": "Download Translations", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.TranslationServicePoMenu/1/actions/downloadTranslations", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisApplib.TranslationServicePoMenu", "id": "resetTranslationCache", "named": "Clear translation cache", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.TranslationServicePoMenu/1/actions/resetTranslationCache", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisApplib.TranslationServicePoMenu", "id": "switchToReadingTranslations", "named": "Switch To Reading Translations", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.TranslationServicePoMenu/1/actions/switchToReadingTranslations", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisApplib.TranslationServicePoMenu", "id": "switchToWritingTranslations", "named": "Switch To Writing Translations", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.TranslationServicePoMenu/1/actions/switchToWritingTranslations", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isisExtH2Console.H2ManagerMenu", "id": "openH2Console", "named": "H2 Console", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtH2Console.H2ManagerMenu/1/actions/openH2Console", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Prototype Actions", "serviceAction": [ { "objectType": "demoapp.PrototypeActionsVisibilityAdvisor", "id": "showPrototypeActions", "named": "Show", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demoapp.PrototypeActionsVisibilityAdvisor/1/actions/showPrototypeActions", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demoapp.PrototypeActionsVisibilityAdvisor", "id": "doNotShowPrototypeActions", "named": "Do not Show", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demoapp.PrototypeActionsVisibilityAdvisor/1/actions/doNotShowPrototypeActions", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Activity", "cssClassFa": null, "section": [ { "named": "Command Log", "serviceAction": [ { "objectType": "isisExtensionsCommandLog.CommandServiceMenu", "id": "activeCommands", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandLog.CommandServiceMenu/1/actions/activeCommands", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisExtensionsCommandLog.CommandServiceMenu", "id": "findCommands", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandLog.CommandServiceMenu/1/actions/findCommands", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisExtensionsCommandLog.CommandServiceMenu", "id": "findCommandById", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandLog.CommandServiceMenu/1/actions/findCommandById", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisExtensionsCommandLog.CommandServiceMenu", "id": "truncateLog", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandLog.CommandServiceMenu/1/actions/truncateLog", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Command Replay - Primary", "serviceAction": [ { "objectType": "isisExtensionsCommandReplayPrimary.CommandReplayOnPrimaryService", "id": "findCommands", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandReplayPrimary.CommandReplayOnPrimaryService/1/actions/findCommands", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisExtensionsCommandReplayPrimary.CommandReplayOnPrimaryService", "id": "downloadCommands", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandReplayPrimary.CommandReplayOnPrimaryService/1/actions/downloadCommands", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisExtensionsCommandReplayPrimary.CommandReplayOnPrimaryService", "id": "downloadCommandById", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandReplayPrimary.CommandReplayOnPrimaryService/1/actions/downloadCommandById", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Command Replay - Secondary", "serviceAction": [ { "objectType": "isisExtensionsCommandReplaySecondary.CommandReplayOnSecondaryService", "id": "findMostRecentReplayed", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandReplaySecondary.CommandReplayOnSecondaryService/1/actions/findMostRecentReplayed", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisExtensionsCommandReplaySecondary.CommandReplayOnSecondaryService", "id": "uploadCommands", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisExtensionsCommandReplaySecondary.CommandReplayOnSecondaryService/1/actions/uploadCommands", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": "Demo Replay Controller", "serviceAction": [ { "objectType": "demoapp.web.DemoReplayController", "id": "pauseReplay", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demoapp.web.DemoReplayController/1/actions/pauseReplay", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "demoapp.web.DemoReplayController", "id": "resumeReplay", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/demoapp.web.DemoReplayController/1/actions/resumeReplay", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null }, { "named": "Security", "cssClassFa": null, "section": [ { "named": null, "serviceAction": [ { "objectType": "isissecurity.ApplicationRoleMenu", "id": "allRoles", "named": "All Roles", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationRoleMenu/1/actions/allRoles", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationRoleMenu", "id": "newRole", "named": "New Role", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationRoleMenu/1/actions/newRole", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationRoleMenu", "id": "findRoles", "named": "Find Roles", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationRoleMenu/1/actions/findRoles", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isissecurity.ApplicationTenancyMenu", "id": "newTenancy", "named": "New Tenancy", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationTenancyMenu/1/actions/newTenancy", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationTenancyMenu", "id": "findTenancies", "named": "Find Tenancies", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationTenancyMenu/1/actions/findTenancies", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationTenancyMenu", "id": "allTenancies", "named": "All Tenancies", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationTenancyMenu/1/actions/allTenancies", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isissecurity.ApplicationPermissionMenu", "id": "findOrphanedPermissions", "named": "Find Orphaned Permissions", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationPermissionMenu/1/actions/findOrphanedPermissions", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationPermissionMenu", "id": "allPermissions", "named": "All Permissions", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationPermissionMenu/1/actions/allPermissions", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isissecurity.ApplicationFeatureViewModels", "id": "allProperties", "named": "All Properties", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationFeatureViewModels/1/actions/allProperties", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationFeatureViewModels", "id": "allClasses", "named": "All Classes", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationFeatureViewModels/1/actions/allClasses", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationFeatureViewModels", "id": "allPackages", "named": "All Packages", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationFeatureViewModels/1/actions/allPackages", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationFeatureViewModels", "id": "allActions", "named": "All Actions", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationFeatureViewModels/1/actions/allActions", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationFeatureViewModels", "id": "allCollections", "named": "All Collections", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationFeatureViewModels/1/actions/allCollections", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isissecurity.ApplicationUserMenu", "id": "findUsers", "named": "Find Users", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationUserMenu/1/actions/findUsers", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationUserMenu", "id": "newLocalUser", "named": "New Local User", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationUserMenu/1/actions/newLocalUser", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationUserMenu", "id": "allUsers", "named": "All Users", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationUserMenu/1/actions/allUsers", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isissecurity.ApplicationUserMenu", "id": "newDelegateUser", "named": "New Delegate User", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.ApplicationUserMenu/1/actions/newDelegateUser", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null } ] }, "tertiary": { "menu": [ { "named": "", "cssClassFa": null, "section": [ { "named": null, "serviceAction": [ { "objectType": "isissecurity.MeService", "id": "me", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isissecurity.MeService/1/actions/me", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } }, { "objectType": "isisApplib.ConfigurationMenu", "id": "configuration", "named": null, "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisApplib.ConfigurationMenu/1/actions/configuration", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] }, { "named": null, "serviceAction": [ { "objectType": "isisSecurityApi.LogoutMenu", "id": "logout", "named": "Logout", "namedEscaped": null, "bookmarking": null, "cssClass": null, "cssClassFa": null, "describedAs": null, "metadataError": null, "link": { "rel": "urn:org.restfulobjects:rels/action", "method": "GET", "href": "http://localhost:8080/restful/objects/isisSecurityApi.LogoutMenu/1/actions/logout", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } } ] } ], "unreferencedActions": null } ] }, "metadataError": null } """ }
4
null
294
751
cfb994d281118effa2363528c6d5cf74c8c64cae
108,120
causeway
Apache License 2.0
media/src/test/kotlin/fr/nihilus/music/media/playlists/PlaylistFixtures.kt
thibseisel
80,150,620
false
null
/* * Copyright 2022 Thibault Seisel * * 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 fr.nihilus.music.media.playlists import androidx.core.net.toUri import fr.nihilus.music.core.database.playlists.Playlist internal val PLAYLIST_FAVORITES = Playlist( id = 1, title = "My Favorites", created = 1551434321, iconUri = "content://fr.nihilus.music.test.provider/icons/my_favorites.png".toUri() ) internal val PLAYLIST_ZEN = Playlist( id = 2, title = "Zen", created = 1551435123, iconUri = null ) internal val PLAYLIST_SPORT = Playlist( id = 3, title = "Sport", created = 1551436125, iconUri = null )
23
null
8
67
f097bcda052665dc791bd3c26880adb0545514dc
1,168
android-odeon
Apache License 2.0
media/src/test/kotlin/fr/nihilus/music/media/playlists/PlaylistFixtures.kt
thibseisel
80,150,620
false
null
/* * Copyright 2022 Thibault Seisel * * 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 fr.nihilus.music.media.playlists import androidx.core.net.toUri import fr.nihilus.music.core.database.playlists.Playlist internal val PLAYLIST_FAVORITES = Playlist( id = 1, title = "My Favorites", created = 1551434321, iconUri = "content://fr.nihilus.music.test.provider/icons/my_favorites.png".toUri() ) internal val PLAYLIST_ZEN = Playlist( id = 2, title = "Zen", created = 1551435123, iconUri = null ) internal val PLAYLIST_SPORT = Playlist( id = 3, title = "Sport", created = 1551436125, iconUri = null )
23
null
8
67
f097bcda052665dc791bd3c26880adb0545514dc
1,168
android-odeon
Apache License 2.0
src/main/kotlin/icu/windea/pls/ep/configGroup/CwtConfigGroupDataProvider.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.lang.configGroup import com.intellij.openapi.extensions.* import icu.windea.pls.config.configGroup.* /** * 用于获取CWT规则分组中的数据。 */ interface CwtConfigGroupDataProvider { fun process(configGroup: CwtConfigGroup) : Boolean companion object INSTANCE { val EP_NAME = ExtensionPointName.create<CwtConfigGroupDataProvider>("icu.windea.pls.configGroupDataProvider") } }
17
null
5
41
99e8660a23f19642c7164c6d6fcafd25b5af40ee
412
Paradox-Language-Support
MIT License
sdk/src/main/kotlin/io/github/wulkanowy/sdk/pojo/GovernmentMember.kt
wulkanowy
138,756,468
false
{"Kotlin": 705036, "HTML": 70768}
package io.github.wulkanowy.sdk.pojo data class GovernmentMember( val name: String, val position: String, val division: String, val id: Int, )
9
Kotlin
5
8
340245d8ccc2790dcb75219c2839e8bdd8b448a4
160
sdk
Apache License 2.0
src/main/kotlin/org/teamvoided/dusk_autumn/data/gen/providers/AdvancementsProvider.kt
TeamVoided
737,359,498
false
{"Kotlin": 562762, "Java": 6328}
package org.teamvoided.dusk_autumn.data.gen.providers import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.FabricAdvancementProvider import net.minecraft.advancement.Advancement import net.minecraft.advancement.AdvancementHolder import net.minecraft.advancement.AdvancementRewards import net.minecraft.advancement.AdvancementType import net.minecraft.advancement.criterion.TameAnimalCriterionTrigger import net.minecraft.data.server.advancement.AdventureAdvancementTabGenerator import net.minecraft.predicate.entity.EntityPredicate import net.minecraft.predicate.entity.EntitySubPredicateTypes import net.minecraft.registry.HolderLookup import net.minecraft.registry.HolderSet import net.minecraft.registry.RegistryKeys import net.minecraft.text.Text import org.teamvoided.dusk_autumn.DuskAutumns.id import org.teamvoided.dusk_autumn.DuskAutumns.mc import org.teamvoided.dusk_autumn.data.DnDWolfVariants import org.teamvoided.dusk_autumn.init.DnDBlocks import org.teamvoided.dusk_autumn.init.blocks.DnDWoodBlocks import org.teamvoided.dusk_autumn.init.worldgen.DnDBiomes import java.util.concurrent.CompletableFuture import java.util.function.Consumer class AdvancementsProvider(o: FabricDataOutput, r: CompletableFuture<HolderLookup.Provider>) : FabricAdvancementProvider(o, r) { private val adventuringTime = AdvancementHolder(mc("adventure/adventuring_time"), null) private val adventure = AdvancementHolder(mc("adventure/root"), null) private val autumnBiomes = listOf( DnDBiomes.AUTUMN_WOODS, DnDBiomes.AUTUMN_PASTURES, DnDBiomes.AUTUMN_CASCADES, // DnDBiomes.AUTUMN_WETLANDS, ) private val theWholePack = AdvancementHolder(mc("husbandry/whole_pack"), null) override fun generateAdvancement(provider: HolderLookup.Provider, c: Consumer<AdvancementHolder>?) { // val bigItems = arrayOf<ItemPredicate.Builder>( // ItemPredicate.Builder.create().items(DnDBlocks.BIG_CHAIN), // ItemPredicate.Builder.create().items(DnDBlocks.BIG_LANTERN), // ItemPredicate.Builder.create().items(DnDBlocks.BIG_SOUL_LANTERN), // ) // DnDBlockLists.bigCandles.forEach { // bigItems + (ItemPredicate.Builder.create().items(it.first)) // } // DnDBlockLists.bigSoulCandles.forEach { // bigItems + (ItemPredicate.Builder.create().items(it.first)) // } // // Advancement.Builder.create().parent(adventure).display( // DnDBlocks.BIG_CANDLE, // Text.of("NOW$ YOURE CH4NCE TO B3 A [[BIG]]!!"), // Text.of("Obtain all of the Big items"), // null, // AdvancementType.CHALLENGE, // true, // true, // true // ).putCriteria( // "get_big", InventoryChangedCriterionTrigger.Conditions.create( // arrayOf<ItemPredicate.Builder>( // ItemPredicate.Builder.create().items(DnDBlocks.BIG_CHAIN.asItem()), // ItemPredicate.Builder.create().items(DnDBlocks.BIG_LANTERN.asItem()), // ItemPredicate.Builder.create().items(DnDBlocks.BIG_SOUL_LANTERN.asItem()), // ) // ) // ).build(c, "story/mine_stone") AdventureAdvancementTabGenerator.appendEnterAllBiomesCriterion( Advancement.Builder.create(), provider, autumnBiomes ).display( DnDWoodBlocks.CASCADE_SAPLING, Text.of("Fall!"), Text.of("Visit the autumn biomes!"), null, AdvancementType.CHALLENGE, true, true, false ).rewards(AdvancementRewards.Builder.experience(50)).parent(adventuringTime) .build(c, id("adventure/fall").toString()) Advancement.Builder.create() .putCriteria( DnDWolfVariants.AUTUMN.toString(), TameAnimalCriterionTrigger.Conditions.create( EntityPredicate.Builder.create().typeSpecific( EntitySubPredicateTypes.method_59667( HolderSet.createDirect( provider.getLookupOrThrow(RegistryKeys.WOLF_VARIANT) .getHolderOrThrow(DnDWolfVariants.AUTUMN) ) ) ) ) ).display( DnDWoodBlocks.CASCADE_LOG, Text.of("Woof"), Text.of("Find the Autumn Wolf"), null, AdvancementType.CHALLENGE, true, true, false ).rewards(AdvancementRewards.Builder.experience(5)).parent(theWholePack) .build(c, id("husbandry/woof").toString()) } }
0
Kotlin
0
0
8b5b16f6f4bdc2038f63a10808dd58897912c329
4,878
DusksAndDungeons
MIT License
src/main/kotlin/Day11.kt
i-redbyte
433,743,675
false
null
import java.util.* class Cavern(private val octopi: Array<IntArray>) { constructor(lines: List<String>) : this(lines.map { it.map { c -> c.digitToInt() }.toIntArray() }.toTypedArray()) fun step(): Pair<Cavern, Int> { val incremented = Array(10) { IntArray(10) } val flashSpots = LinkedList<Pair<Int, Int>>() (0 until 10).forEach { i -> (0 until 10).forEach { j -> incremented[i][j] = octopi[i][j] + 1 if (incremented[i][j] == 10) { flashSpots += i to j } } } val flashedAlready = flashSpots.toMutableSet() while (flashSpots.isNotEmpty()) { val (ci, cj) = flashSpots.poll() (-1 until 2).forEach { i -> (-1 until 2).forEach inner@{ j -> val point = (ci + i) to (cj + j) val (pi, pj) = point if (point in flashedAlready) return@inner if (pi >= 0 && pj >= 0 && pi < 10 && pj < 10) { incremented[pi][pj]++ if (incremented[pi][pj] == 10) { flashedAlready += point flashSpots.add(point) } } } } } (0 until 10).forEach { i -> (0 until 10).forEach { j -> incremented[i][j] = if (incremented[i][j] > 9) 0 else incremented[i][j] } } return Cavern(incremented) to flashedAlready.size } } fun main() { val data = readInputFile("day11") fun part1(): Int { var cavern = Cavern(data) var flashes = 0 repeat(100) { val (newCavern, newFlashes) = cavern.step() cavern = newCavern flashes += newFlashes } return flashes } fun part2(): Int { var cavern = Cavern(data) var i = 0 do { val (newCavern, newFlashes) = cavern.step() cavern = newCavern i++ } while (newFlashes != 100) return i } println("Result part1: ${part1()}") println("Result part2: ${part2()}") }
0
Kotlin
0
0
6d4f19df3b7cb1906052b80a4058fa394a12740f
2,265
AOC2021
Apache License 2.0
src/main/kotlin/no/nav/amt/deltaker/deltaker/model/DeltakerStatus.kt
navikt
756,768,265
false
{"Kotlin": 113511, "PLpgSQL": 635, "Dockerfile": 140}
package no.nav.amt.deltaker.bff.deltaker.model import java.time.LocalDateTime import java.util.UUID data class DeltakerStatus( val id: UUID, val type: Type, val aarsak: Aarsak?, val gyldigFra: LocalDateTime, val gyldigTil: LocalDateTime?, val opprettet: LocalDateTime, ) { enum class Aarsak { SYK, FATT_JOBB, TRENGER_ANNEN_STOTTE, FIKK_IKKE_PLASS, IKKE_MOTT, ANNET, AVLYST_KONTRAKT } enum class Type { UTKAST, FORSLAG_TIL_INNBYGGER, VENTER_PA_OPPSTART, DELTAR, HAR_SLUTTET, IKKE_AKTUELL, FEILREGISTRERT, SOKT_INN, VURDERES, VENTELISTE, AVBRUTT, FULLFORT, PABEGYNT_REGISTRERING, } } val AVSLUTTENDE_STATUSER = listOf( DeltakerStatus.Type.HAR_SLUTTET, DeltakerStatus.Type.IKKE_AKTUELL, DeltakerStatus.Type.FEILREGISTRERT, DeltakerStatus.Type.AVBRUTT, DeltakerStatus.Type.FULLFORT, ) val VENTER_PAA_PLASS_STATUSER = listOf( DeltakerStatus.Type.SOKT_INN, DeltakerStatus.Type.VURDERES, DeltakerStatus.Type.VENTELISTE, DeltakerStatus.Type.PABEGYNT_REGISTRERING, ) val STATUSER_SOM_KAN_SKJULES = listOf( DeltakerStatus.Type.IKKE_AKTUELL, DeltakerStatus.Type.HAR_SLUTTET, DeltakerStatus.Type.AVBRUTT, DeltakerStatus.Type.FULLFORT, )
4
Kotlin
0
0
fa35df212e49bf7da951fcce27ac57da68023025
1,263
amt-deltaker-bff
MIT License
katz/src/main/kotlin/katz/instances/IdComonad.kt
klappvisor
96,400,685
true
{"Kotlin": 168912}
package kategory interface IdComonad : Comonad<Id.F> { override fun <A, B> coflatMap(fa: IdKind<A>, f: (IdKind<A>) -> B): IdKind<B> = fa.ev().map({ f(fa) }) override fun <A> extract(fa: IdKind<A>): A = fa.ev().value }
0
Kotlin
0
0
d1c8aa29cdfe751e30a79129bee3b7ed02cafb33
252
kategory
Apache License 2.0
app/src/main/java/com/scnr/MainActivity.kt
tenpercent
255,009,895
false
null
package com.scnr import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.scnr.ui.CameraXFragment import com.scnr.ui.TextFragment class MainActivity : FragmentActivity() { val vm: OCRViewModel by lazy { ViewModelProvider(this).get(OCRViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) } override fun onResume() { super.onResume() findViewById<ViewPager2>(R.id.pager).adapter = object: FragmentStateAdapter(this) { override fun getItemCount() = 2 override fun createFragment(position: Int): Fragment = when (position) { 0 -> CameraXFragment(vm) else -> TextFragment(vm) } } } companion object { val TAG = "scnr.MainActivity" } }
0
Kotlin
0
1
573d5a7e37d64760b17107c8ea617cae67a96923
1,100
SCNR
Creative Commons Zero v1.0 Universal
KotlinBoilerplate/app/src/main/java/com/tiknil/app/views/fragments/MainFragment.kt
tiknil
231,347,612
false
null
package com.tiknil.app.views.fragments import com.tiknil.app.BR import com.tiknil.app.R import com.tiknil.app.core.views.BaseFragment import com.tiknil.app.databinding.FragmentMainBinding import com.tiknil.app.viewmodels.fragment.MainFragmentVM import javax.inject.Inject class MainFragment : BaseFragment<FragmentMainBinding, MainFragmentVM>() { //region Inner enums //endregion //region Constants //endregion //region Instance Fields @Inject lateinit var viewModel: MainFragmentVM //endregion //region Class methods //endregion //region Constructors / Lifecycle override fun setupUI() { super.setupUI() } //endregion //region Custom accessors //endregion //region Public //endregion //region Protected, without modifier //endregion //region Private //endregion //region Override methods and callbacks override fun viewModel(): MainFragmentVM = viewModel override fun bindingVariable(): Int = BR.viewModel override fun layoutId(): Int = R.layout.fragment_main //endregion //region Inner classes or interfaces //endregion }
0
Kotlin
0
0
3f23aff48af14ab54756aad4f5aad3ac2f6bd28b
1,184
kotlin-boilerplate-mvvm
Apache License 2.0
src/main/kotlin/jp/pois/liter/LiterList.kt
pois0
277,718,279
false
null
/* * Copyright 2020 poispois * * 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.pois.liter import kotlin.experimental.ExperimentalTypeInference class LiterList<T>(internal val origin: Iterator<T>, private val list: MutableList<T>) : List<T> { val savedElements: List<T> = list internal var hasNext: Boolean = origin.hasNext() private set override val size: Int get() { if (hasNext) readAll() return list.size } constructor(origin: Iterator<T>) : this(origin, ArrayList<T>()) fun read(): T { if (!hasNext) throw NoSuchElementException() val next = origin.next() list.add(next) hasNext = origin.hasNext() return next } fun read(n: Int): T { require(n > 0) { "Argument n must be positive" } val array = Array<Any?>(n) { null } for (i in 0 until n) { if (!origin.hasNext()) { hasNext = false @Suppress("UNCHECKED_CAST") list.addAll(array.copyOfRange(0, i) as Array<T>) throw NoSuchElementException() } array[i] = origin.next() } hasNext = origin.hasNext() @Suppress("UNCHECKED_CAST") list.addAll(array as Array<T>) return array[n - 1] } fun readAll() { if (!hasNext) return origin.forEach { list.add(it) } hasNext = false } override fun contains(element: T): Boolean = indexOf(element) >= 0 override fun containsAll(elements: Collection<T>): Boolean = elements.all { contains(it) } override fun get(index: Int): T { if (index < list.size) return list[index] if (!hasNext) throw IndexOutOfBoundsException() return try { read(index - list.size + 1) } catch (_: NoSuchElementException) { throw IndexOutOfBoundsException() } } override fun indexOf(element: T): Int { val index = list.indexOf(element) if (index >= 0) return index if (!hasNext) return -1 origin.forEach { value -> list.add(value) if (value == element) { hasNext = origin.hasNext() return list.lastIndex } } hasNext = false return -1 } override fun isEmpty(): Boolean = !hasNext && list.isEmpty() override fun iterator(): Iterator<T> = if (hasNext) LiterListIterator() else list.iterator() override fun lastIndexOf(element: T): Int { if (hasNext) readAll() return list.lastIndexOf(element) } override fun listIterator(): ListIterator<T> = if (hasNext) LiterListListIterator() else list.listIterator() override fun listIterator(index: Int): ListIterator<T> = if (hasNext) LiterListListIterator(index) else list.listIterator(index) override fun subList(fromIndex: Int, toIndex: Int): List<T> { require(fromIndex in 0 until toIndex) val mustRead = toIndex - list.lastIndex if (mustRead > 0) { if (!hasNext) throw IndexOutOfBoundsException() try { read(mustRead) } catch (_: NoSuchElementException) { throw IndexOutOfBoundsException() } } return list.subList(fromIndex, toIndex) } private inner class LiterListIterator : Iterator<T> { private var index = 0 override fun hasNext(): Boolean = index < list.size || origin.hasNext() override fun next(): T { if (index < list.size) return list[index++] index++ return [email protected]() } } private inner class LiterListListIterator(private var index: Int = 0) : ListIterator<T> { init { if (index > list.size) { read(index - list.size) } } override fun hasNext(): Boolean = index < list.size || origin.hasNext() override fun hasPrevious(): Boolean = index > 0 override fun next(): T { if (index < list.size) return list[index++] index++ return [email protected]() } override fun nextIndex(): Int = index override fun previous(): T = list[--index] override fun previousIndex(): Int = index - 1 } } fun <T> Iterator<T>.literList(): LiterList<T> = LiterList(this) fun <T> Iterator<T>.literList(list: MutableList<T>) = LiterList(this, list) fun <T> Iterable<T>.literList(): LiterList<T> = LiterList(iterator()) fun <T> Iterable<T>.literList(list: MutableList<T>) = LiterList(iterator(), list) fun <T> Sequence<T>.literList(): LiterList<T> = LiterList(iterator()) fun <T> Sequence<T>.literList(list: MutableList<T>) = LiterList(iterator(), list) fun <T> LiterList<T>.toList(): List<T> { readAll() return savedElements } @OptIn(ExperimentalTypeInference::class) fun <T> buildLiterList( @BuilderInference block: suspend SequenceScope<T>.() -> Unit ): LiterList<T> = LiterList(iterator(block))
1
Kotlin
0
0
9b0c7c8ae29069b4fde6d2e54787e54b18515267
5,635
Liter
Apache License 2.0
sample/androidApp/src/main/java/com/attafitamim/kabin/sample/android/MainActivity.kt
tamimattafi
702,197,843
false
null
package com.attafitamim.kabin.sample.android import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.attafitamim.kabin.core.database.KabinDatabaseConfiguration import com.attafitamim.kabin.local.Playground class MainActivity : AppCompatActivity() { private val playground: Playground by lazy { val configuration = KabinDatabaseConfiguration( context = this, name = "sample-database", foreignKeyConstraintsEnabled = true ) Playground(configuration) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) playground.start() } }
0
null
3
50
58a0bbe438f027eb0e3dc99d1cdb64149d487b6b
685
kabin
Apache License 2.0
scopes/src/main/java/com/hallett/scopes/di/ScopeGeneratorModule.kt
c8hallett
374,226,825
false
null
package com.hallett.scopes.di import com.hallett.scopes.IScopeGenerator import com.hallett.scopes.ScopeGenerator import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.singleton val scopeGeneratorModule = Kodein.Module("scope_generator_module"){ bind<IScopeGenerator>() with singleton { ScopeGenerator() } }
0
Kotlin
0
0
1b537ff84e6db51f7530463efe9c31691706dc8d
350
BujoAssistant
MIT License
constraintlayout/compose/src/main/java/androidx/constraintlayout/compose/ConstraintSetParser.kt
androidx
212,409,034
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.constraintlayout.compose import androidx.compose.ui.unit.Dp import androidx.constraintlayout.core.motion.utils.TypedBundle import androidx.constraintlayout.core.motion.utils.TypedValues import androidx.constraintlayout.core.parser.* import androidx.constraintlayout.core.state.ConstraintReference import androidx.constraintlayout.core.state.Dimension import androidx.constraintlayout.core.state.Dimension.* import androidx.constraintlayout.core.state.State.Chain.* import androidx.constraintlayout.core.state.Transition import androidx.constraintlayout.core.state.helpers.GuidelineReference import androidx.constraintlayout.core.widgets.ConstraintWidget import java.lang.Long.parseLong internal const val PARSER_DEBUG = false class LayoutVariables { private val margins = HashMap<String, Int>() private val generators = HashMap<String, GeneratedValue>() private val arrayIds = HashMap<String, ArrayList<String>>() fun put(elementName: String, element: Int) { margins[elementName] = element } fun put(elementName: String, start: Float, incrementBy: Float) { if (generators.containsKey(elementName)) { if (generators[elementName] is OverrideValue) { return } } val generator = Generator(start, incrementBy) generators[elementName] = generator } fun put(elementName: String, from: Float, to: Float, step: Float, prefix: String, postfix: String) { if (generators.containsKey(elementName)) { if (generators[elementName] is OverrideValue) { return } } val generator = FiniteGenerator(from, to, step, prefix, postfix) generators[elementName] = generator arrayIds[elementName] = generator.array() } fun putOverride(elementName: String, value: Float) { val generator = OverrideValue(value) generators[elementName] = generator } fun get(elementName: Any): Float { if (elementName is CLString) { val stringValue = elementName.content() if (generators.containsKey(stringValue)) { return generators[stringValue]!!.value() } if (margins.containsKey(stringValue)) { return margins[stringValue]!!.toFloat() } } else if (elementName is CLNumber) { return elementName.float } return 0f } fun getList(elementName: String) : ArrayList<String>? { if (arrayIds.containsKey(elementName)) { return arrayIds[elementName] } return null } fun put(elementName: String, elements: ArrayList<String>) { arrayIds[elementName] = elements } } interface GeneratedValue { fun value() : Float } class Generator(start: Float, private var incrementBy: Float) : GeneratedValue { private var current : Float = start private var stop = false override fun value() : Float { if (!stop) { current += incrementBy } return current } } class FiniteGenerator(from: Float, to: Float, private var step: Float = 1f, private var prefix: String = "", private var postfix: String = "" ) : GeneratedValue { private var current : Float = from private var stop = false private var initial = from private var max = to override fun value(): Float { if (current >= max) { stop = true } if (!stop) { current += step } return current } fun array() : ArrayList<String> { val array = arrayListOf<String>() var value = initial.toInt() for (i in initial.toInt() .. max.toInt()) { array.add(prefix + value + postfix) value += step.toInt() } return array } } class OverrideValue(private var value: Float) : GeneratedValue { override fun value() : Float { return value } } internal fun parseTransition(json: CLObject, transition: Transition) { val pathMotionArc = json.getStringOrNull("pathMotionArc") if (pathMotionArc != null) { val bundle = TypedBundle() when (pathMotionArc) { "none" -> bundle.add(TypedValues.Position.TYPE_PATH_MOTION_ARC, 0) "startVertical" -> bundle.add(TypedValues.Position.TYPE_PATH_MOTION_ARC, 1) "startHorizontal" -> bundle.add(TypedValues.Position.TYPE_PATH_MOTION_ARC, 2) "flip" -> bundle.add(TypedValues.Position.TYPE_PATH_MOTION_ARC, 3) } transition.setTransitionProperties(bundle) } val keyframes = json.getObjectOrNull("KeyFrames") ?: return val keyPositions = keyframes.getArrayOrNull("KeyPositions") if (keyPositions != null) { (0 until keyPositions.size()).forEach { i -> val keyPosition = keyPositions[i] if (keyPosition is CLObject) { parseKeyPosition(keyPosition, transition) } } } val keyAttributes = keyframes.getArrayOrNull("KeyAttributes") if (keyAttributes != null) { (0 until keyAttributes.size()).forEach { i -> val keyAttribute = keyAttributes[i] if (keyAttribute is CLObject) { parseKeyAttribute(keyAttribute, transition) } } } val keyCycles = keyframes.getArrayOrNull("KeyCycles") if (keyCycles != null) { (0 until keyCycles.size()).forEach { i -> val keyCycle = keyCycles[i] if (keyCycle is CLObject) { parseKeyCycle(keyCycle, transition) } } } } fun parseKeyPosition(keyPosition: CLObject, transition: Transition) { val bundle = TypedBundle() val targets = keyPosition.getArray("target") val frames = keyPosition.getArray("frames") val percentX = keyPosition.getArrayOrNull("percentX") val percentY = keyPosition.getArrayOrNull("percentY") val percentWidth = keyPosition.getArrayOrNull("percentWidth") val percentHeight = keyPosition.getArrayOrNull("percentHeight") val pathMotionArc = keyPosition.getStringOrNull("pathMotionArc") val transitionEasing = keyPosition.getStringOrNull("transitionEasing") val curveFit = keyPosition.getStringOrNull("curveFit") val type = keyPosition.getStringOrNull("type") ?: "parentRelative" if (percentX != null && frames.size() != percentX.size()) { return } if (percentY != null && frames.size() != percentY.size()) { return } (0 until targets.size()).forEach { i -> val target = targets.getString(i) bundle.clear() bundle.add( TypedValues.Position.TYPE_POSITION_TYPE, when (type) { "deltaRelative" -> 0 "pathRelative" -> 1 "parentRelative" -> 2 else -> 0 } ) if (curveFit != null) { when (curveFit) { "spline" -> bundle.add(TypedValues.Position.TYPE_CURVE_FIT, 0) "linear" -> bundle.add(TypedValues.Position.TYPE_CURVE_FIT, 1) } } bundle.addIfNotNull(TypedValues.Position.TYPE_TRANSITION_EASING, transitionEasing) if (pathMotionArc != null) { when (pathMotionArc) { "none" -> bundle.add(TypedValues.Position.TYPE_PATH_MOTION_ARC, 0) "startVertical" -> bundle.add(TypedValues.Position.TYPE_PATH_MOTION_ARC, 1) "startHorizontal" -> bundle.add(TypedValues.Position.TYPE_PATH_MOTION_ARC, 2) "flip" -> bundle.add(TypedValues.Position.TYPE_PATH_MOTION_ARC, 3) } } (0 until frames.size()).forEach { j -> val frame = frames.getInt(j) bundle.add(TypedValues.TYPE_FRAME_POSITION, frame) if (percentX != null) { bundle.add(TypedValues.Position.TYPE_PERCENT_X, percentX.getFloat(j)) } if (percentY != null) { bundle.add(TypedValues.Position.TYPE_PERCENT_Y, percentY.getFloat(j)) } if (percentWidth != null) { bundle.add(TypedValues.Position.TYPE_PERCENT_WIDTH, percentWidth.getFloat(j)) } if (percentHeight != null) { bundle.add(TypedValues.Position.TYPE_PERCENT_HEIGHT, percentHeight.getFloat(j)) } transition.addKeyPosition(target, bundle) } } } fun parseKeyAttribute(keyAttribute: CLObject, transition: Transition) { val targets = keyAttribute.getArray("target") val frames = keyAttribute.getArray("frames") val transitionEasing = keyAttribute.getStringOrNull("transitionEasing") val attrNames = arrayListOf( TypedValues.Attributes.S_SCALE_X, TypedValues.Attributes.S_SCALE_Y, TypedValues.Attributes.S_TRANSLATION_X, TypedValues.Attributes.S_TRANSLATION_Y, TypedValues.Attributes.S_TRANSLATION_Z, TypedValues.Attributes.S_ROTATION_X, TypedValues.Attributes.S_ROTATION_Y, TypedValues.Attributes.S_ROTATION_Z, ) val attrIds = arrayListOf( TypedValues.Attributes.TYPE_SCALE_X, TypedValues.Attributes.TYPE_SCALE_Y, TypedValues.Attributes.TYPE_TRANSLATION_X, TypedValues.Attributes.TYPE_TRANSLATION_Y, TypedValues.Attributes.TYPE_TRANSLATION_Z, TypedValues.Attributes.TYPE_ROTATION_X, TypedValues.Attributes.TYPE_ROTATION_Y, TypedValues.Attributes.TYPE_ROTATION_Z, ) val bundles = ArrayList<TypedBundle>() (0 until frames.size()).forEach { _ -> bundles.add(TypedBundle()) } for (k in 0 until attrNames.size) { val attrName = attrNames[k] val attrId = attrIds[k] val arrayValues = keyAttribute.getArrayOrNull(attrName) // array must contain one per frame if (arrayValues != null && arrayValues.size() != bundles.size) { throw CLParsingException("incorrect size for $attrName array, " + "not matching targets array!", keyAttribute) } if (arrayValues != null) { (0 until bundles.size).forEach { i -> bundles[i].add(attrId, arrayValues.getFloat(i)) } } else { val value = keyAttribute.getFloatOrNaN(attrName) if (!value.isNaN()) { (0 until bundles.size).forEach { i -> bundles[i].add(attrId, value) } } } } val curveFit = keyAttribute.getStringOrNull("curveFit") (0 until targets.size()).forEach { i -> (0 until bundles.size).forEach { j -> val target = targets.getString(i) val bundle = bundles[j] if (curveFit != null) { when (curveFit) { "spline" -> bundle.add(TypedValues.Position.TYPE_CURVE_FIT, 0) "linear" -> bundle.add(TypedValues.Position.TYPE_CURVE_FIT, 1) } } bundle.addIfNotNull(TypedValues.Position.TYPE_TRANSITION_EASING, transitionEasing) val frame = frames.getInt(j) bundle.add(TypedValues.TYPE_FRAME_POSITION, frame) transition.addKeyAttribute(target, bundle) } } } fun parseKeyCycle(keyCycleData: CLObject, transition: Transition) { val targets = keyCycleData.getArray("target") val frames = keyCycleData.getArray("frames") val transitionEasing = keyCycleData.getStringOrNull("transitionEasing") val attrNames = arrayListOf<String>( TypedValues.Cycle.S_SCALE_X, TypedValues.Cycle.S_SCALE_Y, TypedValues.Cycle.S_TRANSLATION_X, TypedValues.Cycle.S_TRANSLATION_Y, TypedValues.Cycle.S_TRANSLATION_Z, TypedValues.Cycle.S_ROTATION_X, TypedValues.Cycle.S_ROTATION_Y, TypedValues.Cycle.S_ROTATION_Z, TypedValues.Cycle.S_WAVE_PERIOD, TypedValues.Cycle.S_WAVE_OFFSET, TypedValues.Cycle.S_WAVE_PHASE, ) val attrIds = arrayListOf<Int>( TypedValues.Cycle.TYPE_SCALE_X, TypedValues.Cycle.TYPE_SCALE_Y, TypedValues.Cycle.TYPE_TRANSLATION_X, TypedValues.Cycle.TYPE_TRANSLATION_Y, TypedValues.Cycle.TYPE_TRANSLATION_Z, TypedValues.Cycle.TYPE_ROTATION_X, TypedValues.Cycle.TYPE_ROTATION_Y, TypedValues.Cycle.TYPE_ROTATION_Z, TypedValues.Cycle.TYPE_WAVE_PERIOD, TypedValues.Cycle.TYPE_WAVE_OFFSET, TypedValues.Cycle.TYPE_WAVE_PHASE, ) // TODO S_WAVE_SHAPE S_CUSTOM_WAVE_SHAPE var bundles = ArrayList<TypedBundle>() (0 until frames.size()).forEach { i -> bundles.add(TypedBundle()) } for (k in 0 .. attrNames.size - 1) { var attrName = attrNames[k] var attrId = attrIds[k]; val arrayValues = keyCycleData.getArrayOrNull(attrName) // array must contain one per frame if (arrayValues != null && arrayValues.size() != bundles.size) { throw CLParsingException("incorrect size for $attrName array, " + "not matching targets array!", keyCycleData) } if (arrayValues != null) { (0 until bundles.size).forEach { i -> bundles.get(i) .add(attrId, arrayValues.getFloat(i)); } } else { val value = keyCycleData.getFloatOrNaN(attrName) if (!value.isNaN()) { (0 until bundles.size).forEach { i -> bundles.get(i).add(attrId, value); } } } } val curveFit = keyCycleData.getStringOrNull(TypedValues.Cycle.S_CURVE_FIT) val easing = keyCycleData.getStringOrNull(TypedValues.Cycle.S_EASING) val waveShape = keyCycleData.getStringOrNull(TypedValues.Cycle.S_WAVE_SHAPE) val customWave = keyCycleData.getStringOrNull(TypedValues.Cycle.S_CUSTOM_WAVE_SHAPE) (0 until targets.size()).forEach { i -> (0 until bundles.size).forEach { j -> val target = targets.getString(i) var bundle = bundles.get(j) if (curveFit != null) { when (curveFit) { "spline" -> bundle.add(TypedValues.Cycle.TYPE_CURVE_FIT, 0) "linear" -> bundle.add(TypedValues.Cycle.TYPE_CURVE_FIT, 1) } } bundle.addIfNotNull(TypedValues.Position.TYPE_TRANSITION_EASING, transitionEasing) if (easing != null) { bundle.add(TypedValues.Cycle.TYPE_EASING, easing) } if (waveShape != null) { bundle.add(TypedValues.Cycle.TYPE_WAVE_SHAPE, waveShape) } if (customWave != null) { bundle.add(TypedValues.Cycle.TYPE_CUSTOM_WAVE_SHAPE, customWave) } val frame = frames.getInt(j) bundle.add(TypedValues.TYPE_FRAME_POSITION, frame); transition.addKeyCycle(target, bundle) } } } internal fun parseJSON( content: String, transition: Transition, state: Int ) { try { val json = CLParser.parse(content) val elements = json.names() ?: return (0 until elements.size).forEach { i -> val elementName = elements[i] val element = json[elementName] if (element is CLObject) { val customProperties = element.getObjectOrNull("custom") if (customProperties != null) { val properties = customProperties.names() ?: return (0 until properties.size).forEach { j -> val property = properties[j] val value = customProperties.get(property) if (value is CLNumber) { transition.addCustomFloat(state, elementName, property, value.getFloat()) } else if (value is CLString) { val stringValue = value.content() if (stringValue.startsWith('#')) { var color = Integer.valueOf(stringValue.substring(1),16) if (stringValue.length == 7) { color = color or 0xFF000000.toInt() } transition.addCustomColor(state, elementName, property, color) } } } } } } } catch (e: CLParsingException) { System.err.println("Error parsing JSON $e") } } internal fun parseMotionSceneJSON(scene: MotionScene, content: String) { try { val json = CLParser.parse(content) val elements = json.names() ?: return (0 until elements.size).forEach { i -> val elementName = elements[i] val element = json[elementName] when (elementName) { "ConstraintSets" -> parseConstraintSets(scene, element) "Transitions" -> parseTransitions(scene, element) "Header" -> parseHeader(scene, element) } } } catch (e: CLParsingException) { System.err.println("Error parsing JSON $e") } } /** * For the given [json] parses all ConstraintSets into the [scene]. */ fun parseConstraintSets(scene: MotionScene, json: Any) { if (json !is CLObject) { return } val constraintSetNames = json.names() ?: return (0 until constraintSetNames.size).forEach { i -> val csName = constraintSetNames[i] val constraintSet = json.getObject(csName) var added = false val extends = constraintSet.getStringOrNull("Extends") if (extends != null && extends.isNotEmpty()) { val base = scene.getConstraintSet(extends) if (base != null) { val baseJson = CLParser.parse(base) val widgetsOverride = constraintSet.names() if (widgetsOverride != null) { (0 until widgetsOverride.size).forEach { j -> val widgetOverrideName = widgetsOverride[j] val value = constraintSet[widgetOverrideName] if (value is CLObject) { override(baseJson, widgetOverrideName, value) } } scene.setConstraintSetContent(csName, baseJson.toJSON()) added = true } } } if (!added) { scene.setConstraintSetContent(csName, constraintSet.toJSON()) } } } fun override(baseJson: CLObject, name: String, overrideValue: CLObject) { if (!baseJson.has(name)) { baseJson.put(name, overrideValue) } else { val base = baseJson.getObject(name) val keys = overrideValue.names() for (key in keys) { if (key.equals("clear")) { val toClear = overrideValue.getArray("clear") (0 until toClear.size()).forEach { i -> val clearedKey = toClear.getStringOrNull(i) if (clearedKey is String) { when (clearedKey) { "dimensions" -> { base.remove("width") base.remove("height") } "constraints" -> { base.remove("start") base.remove("end") base.remove("top") base.remove("bottom") base.remove("baseline") } "transforms" -> { base.remove("pivotX") base.remove("pivotY") base.remove("rotationX") base.remove("rotationY") base.remove("rotationZ") base.remove("scaleX") base.remove("scaleY") base.remove("translationX") base.remove("translationY") } else -> base.remove(clearedKey) } } } } else { base.put(key, overrideValue.get(key)) } } } } fun parseTransitions(scene: MotionScene, json: Any) { if (json !is CLObject) { return } val elements = json.names() ?: return (0 until elements.size).forEach { i -> val elementName = elements[i] val element = json.getObject(elementName) scene.setTransitionContent(elementName, element.toJSON()) } } fun parseHeader(scene: MotionScene, json: Any) { if (json !is CLObject) { return } val name = json.getStringOrNull("export") if (name != null) { scene.setDebugName(name) } } internal fun parseJSON(content: String, state: State, layoutVariables: LayoutVariables) { try { val json = CLParser.parse(content) val elements = json.names() ?: return (0 until elements.size).forEach { i -> val elementName = elements[i] val element = json[elementName] if (PARSER_DEBUG) { println("element <$elementName = $element> " + element.javaClass) } when (elementName) { "Variables" -> parseVariables(state, layoutVariables, element) "Helpers" -> parseHelpers(state, layoutVariables, element) "Generate" -> parseGenerate(state, layoutVariables, element) else -> { if (element is CLObject) { val type = lookForType(element) if (type != null) { when (type) { "hGuideline" -> parseGuidelineParams( ConstraintWidget.HORIZONTAL, state, elementName, element ) "vGuideline" -> parseGuidelineParams( ConstraintWidget.VERTICAL, state, elementName, element ) "barrier" -> parseBarrier(state, elementName, element) } } else { parseWidget(state, layoutVariables, elementName, element) } } else if (element is CLNumber) { layoutVariables.put(elementName, element.int) } } } } } catch (e: CLParsingException) { System.err.println("Error parsing JSON $e") } } fun parseVariables(state: State, layoutVariables: LayoutVariables, json: Any) { if (json !is CLObject) { return } val elements = json.names() ?: return (0 until elements.size).forEach { i -> val elementName = elements[i] val element = json.get(elementName) if (element is CLNumber) { layoutVariables.put(elementName, element.int) } else if (element is CLObject) { if (element.has("from") && element.has("to")) { val from = layoutVariables.get(element["from"]) val to = layoutVariables.get(element["to"]) val prefix = element.getStringOrNull("prefix") ?: "" val postfix = element.getStringOrNull("postfix") ?: "" layoutVariables.put(elementName, from, to, 1f, prefix, postfix) } else if (element.has("from") && element.has("step")) { val start = layoutVariables.get(element["from"]) val increment = layoutVariables.get(element["step"]) layoutVariables.put(elementName, start, increment) } else if (element.has("ids")) { val ids = element.getArray("ids") val arrayIds = arrayListOf<String>() for (j in 0 until ids.size()) { arrayIds.add(ids.getString(j)) } layoutVariables.put(elementName, arrayIds) } else if (element.has("tag")) { val arrayIds = state.getIdsForTag(element.getString("tag")) layoutVariables.put(elementName, arrayIds) } } } } fun parseDesignElementsJSON(content: String, list: ArrayList<DesignElement>) { val json = CLParser.parse(content) val elements = json.names() ?: return (0 until elements.size).forEach { i -> val elementName = elements[i] val element = json[elementName] if (PARSER_DEBUG) { println("element <$elementName = $element> " + element.javaClass) } when (elementName) { "Design" -> { val elements = (element as CLObject).names() ?: return (0 until elements.size).forEach { i -> val elementName = elements[i] val element = element.get(elementName) as CLObject System.out.printf("element found <$elementName>") val type = element.getStringOrNull("type") if (type != null) { var parameters = HashMap<String, String>() val size = element.size() for (j in 0.. size -1) { val key = element[j] as CLKey val paramName = key.content() val paramValue = key.value?.content() if (paramValue != null) { parameters[paramName] = paramValue } } var designElement = DesignElement(elementName, type, parameters) list.add(designElement) } } } } } } fun parseHelpers(state: State, layoutVariables: LayoutVariables, element: Any) { if (element !is CLArray) { return } (0 until element.size()).forEach { i -> val helper = element[i] if (helper is CLArray && helper.size() > 1) { when (helper.getString(0)) { "hChain" -> parseChain(ConstraintWidget.HORIZONTAL, state, layoutVariables, helper) "vChain" -> parseChain(ConstraintWidget.VERTICAL, state, layoutVariables, helper) "hGuideline" -> parseGuideline(ConstraintWidget.HORIZONTAL, state, helper) "vGuideline" -> parseGuideline(ConstraintWidget.VERTICAL, state, helper) } } } } fun parseGenerate(state: State, layoutVariables: LayoutVariables, json: Any) { if (json !is CLObject) { return } val elements = json.names() ?: return (0 until elements.size).forEach { i -> val elementName = elements[i] val element = json[elementName] val arrayIds = layoutVariables.getList(elementName) if (arrayIds != null && element is CLObject) { for (id in arrayIds) { parseWidget(state, layoutVariables, id, element) } } } } fun parseChain(orientation: Int, state: State, margins: LayoutVariables, helper: CLArray) { val chain = if (orientation == ConstraintWidget.HORIZONTAL) state.horizontalChain() else state.verticalChain() val refs = helper[1] if (refs !is CLArray || refs.size() < 1) { return } (0 until refs.size()).forEach { i -> chain.add(refs.getString(i)) } if (helper.size() > 2) { // we have additional parameters val params = helper[2] if (params !is CLObject) { return } val constraints = params.names() ?: return (0 until constraints.size).forEach{ i -> when (val constraintName = constraints[i]) { "style" -> { val styleObject = params[constraintName] val styleValue : String if (styleObject is CLArray && styleObject.size() > 1) { styleValue = styleObject.getString(0) val biasValue = styleObject.getFloat(1) chain.bias(biasValue) } else { styleValue = styleObject.content() } when (styleValue) { "packed" -> chain.style(PACKED) "spread_inside" -> chain.style(SPREAD_INSIDE) else -> chain.style(SPREAD) } } else -> { parseConstraint(state, margins, params, chain as ConstraintReference, constraintName) } } } } } fun parseGuideline(orientation: Int, state: State, helper: CLArray) { val params = helper[1] if (params !is CLObject) { return } val guidelineId = params.getStringOrNull("id") ?: return parseGuidelineParams(orientation, state, guidelineId, params) } private fun parseGuidelineParams( orientation: Int, state: State, guidelineId: String, params: CLObject ) { val constraints = params.names() ?: return val reference = state.constraints(guidelineId) if (orientation == ConstraintWidget.HORIZONTAL) { state.horizontalGuideline(guidelineId) } else { state.verticalGuideline(guidelineId) } val guidelineReference = reference.facade as GuidelineReference (0 until constraints.size).forEach { i -> when (val constraintName = constraints[i]) { "start" -> { val margin = state.convertDimension( Dp( params.getFloat(constraintName) ) ) guidelineReference.start(margin) } "end" -> { val margin = state.convertDimension( Dp( params.getFloat(constraintName) ) ) guidelineReference.end(margin) } "percent" -> { guidelineReference.percent( params.getFloat(constraintName) ) } } } } fun parseBarrier( state: State, elementName: String, element: CLObject) { val reference = state.barrier(elementName, androidx.constraintlayout.core.state.State.Direction.END) val constraints = element.names() ?: return (0 until constraints.size).forEach { i -> when (val constraintName = constraints[i]) { "direction" -> { when (element.getString(constraintName)) { "start" -> reference.setBarrierDirection(androidx.constraintlayout.core.state.State.Direction.START) "end" -> reference.setBarrierDirection(androidx.constraintlayout.core.state.State.Direction.END) "left" -> reference.setBarrierDirection(androidx.constraintlayout.core.state.State.Direction.LEFT) "right" -> reference.setBarrierDirection(androidx.constraintlayout.core.state.State.Direction.RIGHT) "top" -> reference.setBarrierDirection(androidx.constraintlayout.core.state.State.Direction.TOP) "bottom" -> reference.setBarrierDirection(androidx.constraintlayout.core.state.State.Direction.BOTTOM) } } "contains" -> { val list = element.getArrayOrNull(constraintName) if (list != null) { for (j in 0 until list.size()) { val elementNameReference = list.get(j) val elementReference = state.constraints(elementNameReference) if (PARSER_DEBUG) { println("Add REFERENCE ($elementNameReference = $elementReference) TO BARRIER ") } reference.add(elementReference) } } } } } } fun parseWidget( state: State, layoutVariables: LayoutVariables, elementName: String, element: CLObject ) { val reference = state.constraints(elementName) val constraints = element.names() ?: return reference.width = Dimension.Wrap() reference.height = Dimension.Wrap() (0 until constraints.size).forEach { i -> when (val constraintName = constraints[i]) { "width" -> { reference.width = parseDimension(element, constraintName, state) } "height" -> { reference.height = parseDimension(element, constraintName, state) } "center" -> { val target = element.getString(constraintName) val targetReference = if (target.equals("parent")) { state.constraints(SolverState.PARENT) } else { state.constraints(target) } reference.startToStart(targetReference) reference.endToEnd(targetReference) reference.topToTop(targetReference) reference.bottomToBottom(targetReference) } "centerHorizontally" -> { val target = element.getString(constraintName) val targetReference = if (target.equals("parent")) { state.constraints(SolverState.PARENT) } else { state.constraints(target) } reference.startToStart(targetReference) reference.endToEnd(targetReference) } "centerVertically" -> { val target = element.getString(constraintName) val targetReference = if (target.equals("parent")) { state.constraints(SolverState.PARENT) } else { state.constraints(target) } reference.topToTop(targetReference) reference.bottomToBottom(targetReference) } "alpha" -> { val value = layoutVariables.get(element[constraintName]) reference.alpha(value) } "scaleX" -> { val value = layoutVariables.get(element[constraintName]) reference.scaleX(value) } "scaleY" -> { val value = layoutVariables.get(element[constraintName]) reference.scaleY(value) } "translationX" -> { val value = layoutVariables.get(element[constraintName]) reference.translationX(value) } "translationY" -> { val value = layoutVariables.get(element[constraintName]) reference.translationY(value) } "translationZ" -> { val value = layoutVariables.get(element[constraintName]) reference.translationZ(value) } "pivotX" -> { val value = layoutVariables.get(element[constraintName]) reference.pivotX(value) } "pivotY" -> { val value = layoutVariables.get(element[constraintName]) reference.pivotY(value) } "rotationX" -> { val value = layoutVariables.get(element[constraintName]) reference.rotationX(value) } "rotationY" -> { val value = layoutVariables.get(element[constraintName]) reference.rotationY(value) } "rotationZ" -> { val value = layoutVariables.get(element[constraintName]) reference.rotationZ(value) } "visibility" -> { when(element.getString(constraintName)) { "visible" -> reference.visibility(ConstraintWidget.VISIBLE) "invisible" -> reference.visibility(ConstraintWidget.INVISIBLE) "gone" -> reference.visibility(ConstraintWidget.GONE) } } "custom" -> { parseCustomProperties(element, reference, constraintName) } else -> { parseConstraint(state, layoutVariables, element, reference, constraintName) } } } } private fun parseCustomProperties( element: CLObject, reference: ConstraintReference, constraintName: String ) { val json = element.getObjectOrNull(constraintName) ?: return val properties = json.names() ?: return (0 until properties.size).forEach { i -> val property = properties[i] val value = json.get(property) if (value is CLNumber) { reference.addCustomFloat(property, value.getFloat()) } else if (value is CLString) { var str = value.content().toString() if (str.startsWith('#')) { str = str.substring(1) if(str.length == 6) { str = "FF$str" } reference.addCustomColor(property, parseLong(str,16).toInt()) } } } } private fun parseConstraint( state: State, layoutVariables: LayoutVariables, element: CLObject, reference: ConstraintReference, constraintName: String ) { val constraint = element.getArrayOrNull(constraintName) if (constraint != null && constraint.size() > 1) { val target = constraint.getString(0) val anchor = constraint.getStringOrNull(1) var margin = 0f var marginGone = 0f if (constraint.size() > 2) { margin = layoutVariables.get(constraint.getOrNull(2)!!) margin = state.convertDimension(Dp(margin)).toFloat() } if (constraint.size() > 3) { marginGone = layoutVariables.get(constraint.getOrNull(3)!!) marginGone = state.convertDimension(Dp(marginGone)).toFloat() } val targetReference = if (target.equals("parent")) { state.constraints(SolverState.PARENT) } else { state.constraints(target) } when (constraintName) { "circular" -> { val angle = layoutVariables.get(constraint.get(1)) reference.circularConstraint(targetReference, angle, 0f) } "start" -> { when (anchor) { "start" -> { reference.startToStart(targetReference) } "end" -> reference.startToEnd(targetReference) } } "end" -> { when (anchor) { "start" -> reference.endToStart(targetReference) "end" -> reference.endToEnd(targetReference) } } "top" -> { when (anchor) { "top" -> reference.topToTop(targetReference) "bottom" -> reference.topToBottom(targetReference) } } "bottom" -> { when (anchor) { "top" -> { reference.bottomToTop(targetReference) } "bottom" -> { reference.bottomToBottom(targetReference) } } } } reference.margin(margin).marginGone(marginGone.toInt()) } else { val target = element.getStringOrNull(constraintName) if (target != null) { val targetReference = if (target.equals("parent")) { state.constraints(SolverState.PARENT) } else { state.constraints(target) } when (constraintName) { "start" -> reference.startToStart(targetReference) "end" -> reference.endToEnd(targetReference) "top" -> reference.topToTop(targetReference) "bottom" -> reference.bottomToBottom(targetReference) } } } } private fun parseDimensionMode(dimensionString : String) : Dimension { var dimension: Dimension = Fixed(0) when (dimensionString) { "wrap" -> dimension = Dimension.Wrap() "preferWrap" -> dimension = Dimension.Suggested(WRAP_DIMENSION) "spread" -> dimension = Dimension.Suggested(SPREAD_DIMENSION) "parent" -> dimension = Dimension.Parent() else -> { if (dimensionString.endsWith('%')) { // parent percent val percentString = dimensionString.substringBefore('%') val percentValue = percentString.toFloat() / 100f dimension = Dimension.Percent(0, percentValue).suggested(0) } else if (dimensionString.contains(':')) { dimension = Dimension.Ratio(dimensionString).suggested(0) } } } return dimension } private fun parseDimension( element: CLObject, constraintName: String, state: State ): Dimension { val dimensionElement = element.get(constraintName) var dimension: Dimension = Fixed(0) if (dimensionElement is CLString) { dimension = parseDimensionMode(dimensionElement.content()) } else if (dimensionElement is CLNumber) { dimension = Fixed( state.convertDimension( Dp( element.getFloat(constraintName) ) ) ) } else if (dimensionElement is CLObject) { val mode = dimensionElement.getStringOrNull("value") if (mode != null) { dimension = parseDimensionMode(mode) } val min = dimensionElement.getFloatOrNaN("min") if (!min.isNaN()) { dimension.min(state.convertDimension(Dp(min))) } val max = dimensionElement.getFloatOrNaN("max") if (!max.isNaN()) { dimension.max(state.convertDimension(Dp(max))) } } return dimension } fun lookForType(element: CLObject): String? { val constraints = element.names() ?: return null (0 until constraints.size).forEach { i -> val constraintName = constraints[i] if (constraintName.equals("type")) { return element.getString("type") } } return null }
67
null
126
871
afe1adbcc0520ee3dff2816e7151388fd559d681
43,938
constraintlayout
Apache License 2.0
src/lib/collections/MutableIterableExtensions.kt
jonward1982
350,285,956
true
{"Kotlin": 213021, "Java": 286}
package lib.collections inline fun<T> MutableIterable<T>.mutableWithIndex(): MutableIterable<IndexedValue<T>> = MutableIterable { IndexingMutableIterator(this) } inline fun<T> Iterable<MutableIterable<T>>.mutableFlatten(): MutableIterable<T> = MutableIterable { FlattenedMutableIterator(this) } fun<T,R> Iterable<T>.mutableFlatMap(transform: (T)->MutableIterable<R>): MutableIterable<R> = MutableIterable { MutableFlatMapIterator(this, transform) } fun<T,R> MutableIterable<T>.mutableMap(transform: (T)->R): MutableIterable<R> = MutableIterable { MutableMapIterator(this, transform) } fun<T,R> MutableIterable<T>.mutableMapByRemovable(transform: (RemovableEntry<T>)->R): MutableIterable<R> = MutableIterable { MutableMapByRemovableIterator(this, transform) } inline fun<T> MutableIterable(crossinline iteratorFactory: ()->MutableIterator<T>): MutableIterable<T> { return object: MutableIterable<T> { override fun iterator() = iteratorFactory() } } class FlattenedMutableIterator<T>: MutableIterator<T> { val outerIterator: Iterator<MutableIterable<T>> var innerIterator: MutableIterator<T> var removeIterator: MutableIterator<T>? = null constructor(iterableOfIterables: Iterable<MutableIterable<T>>) { outerIterator = iterableOfIterables.iterator() if(outerIterator.hasNext()) { innerIterator = outerIterator.next().iterator() } else { innerIterator = mutableListOf<T>().iterator() } } override fun hasNext() = moveToNextElement() override fun next(): T { moveToNextElement() removeIterator = innerIterator return innerIterator.next() } override fun remove() { removeIterator?.remove()?:throw(NoSuchElementException()) } private fun moveToNextElement(): Boolean { if(innerIterator.hasNext()) return true while(outerIterator.hasNext()) { innerIterator = outerIterator.next().iterator() if(innerIterator.hasNext()) return true } return false } } class MutableFlatMapIterator<T,R>: MutableIterator<R> { val outerIterator: Iterator<T> val elementToIterable: (T)->MutableIterable<R> var innerIterator: MutableIterator<R> var removeIterator: MutableIterator<R>? = null constructor(iterableOfIterables: Iterable<T>, elementToIterable: (T)->MutableIterable<R>) { this.elementToIterable = elementToIterable outerIterator = iterableOfIterables.iterator() if(outerIterator.hasNext()) { innerIterator = elementToIterable(outerIterator.next()).iterator() } else { innerIterator = mutableListOf<R>().iterator() } } override fun hasNext() = moveToNextElement() override fun next(): R { moveToNextElement() removeIterator = innerIterator return innerIterator.next() } override fun remove() { removeIterator?.remove()?:throw(NoSuchElementException()) } private fun moveToNextElement(): Boolean { if(innerIterator.hasNext()) return true while(outerIterator.hasNext()) { innerIterator = elementToIterable(outerIterator.next()).iterator() if(innerIterator.hasNext()) return true } return false } } class MutableMapIterator<T,R>(val teeIterator: MutableIterator<T>, val transform: (T)->R) : MutableIterator<R> { constructor(teeIterable: MutableIterable<T>, transform: (T)->R): this(teeIterable.iterator(), transform) override fun hasNext() = teeIterator.hasNext() override fun next()= transform(teeIterator.next()) override fun remove() { teeIterator.remove() } } class MutableMapByRemovableIterator<T,R>(val teeIterator: MutableIterator<T>, val transform: (RemovableEntry<T>)->R) : MutableIterator<R> { constructor(teeIterable: MutableIterable<T>, transform: (RemovableEntry<T>)->R): this(teeIterable.iterator(), transform) override fun hasNext() = teeIterator.hasNext() override fun next()= transform(RemovableEntry(teeIterator.next(),teeIterator::remove)) override fun remove() { teeIterator.remove() } } class IndexingMutableIterator<out T>(private val iterator: MutableIterator<T>) : MutableIterator<IndexedValue<T>> { constructor(iterable: MutableIterable<T>): this(iterable.iterator()) private var index = 0 override fun hasNext(): Boolean = iterator.hasNext() override fun next(): IndexedValue<T> = IndexedValue(index++, iterator.next()) override fun remove() { iterator.remove() } } class RemovableEntry<T>(val value: T, val remove: ()->Unit)
0
Kotlin
0
0
621d32d5e2d9d363c753d42cd1ede6b31195e716
4,629
AgentBasedMCMC
MIT License
src/main/java/graphene/rpc/Clients.kt
abitmore
479,743,257
false
{"Kotlin": 447335, "Java": 97085}
package graphene.rpc import graphene.app.API import graphene.app.APIType import graphene.extension.info import graphene.serializers.GRAPHENE_JSON_PLATFORM_SERIALIZER import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.contentnegotiation.* import io.ktor.client.plugins.websocket.* import io.ktor.serialization.kotlinx.* import kotlinx.atomicfu.AtomicBoolean import kotlinx.atomicfu.AtomicInt import kotlinx.atomicfu.atomic import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.serialization.encodeToString import kotlinx.serialization.json.* import kotlin.coroutines.Continuation import kotlin.coroutines.CoroutineContext import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.time.Duration.Companion.seconds fun GrapheneClient(action: GrapheneClientConfigBuilder.() -> Unit) = GrapheneClient( GrapheneClientConfigBuilder(GrapheneClientConfig()).apply(action).build() ) class GrapheneClientConfigBuilder(conf: GrapheneClientConfig) { var id: Long = conf.id var name: String = conf.name var url: String = conf.url var debug: Boolean = conf.debug var enableFallback: Boolean = conf.enableFallback fun build() = GrapheneClientConfig(id, name, url, debug, enableFallback) } data class GrapheneClientConfig( val id: Long = 0L, val name: String = "null", val url: String = "wss://", val debug: Boolean = true, val enableFallback: Boolean = false ) // TODO: 2022/4/19 move to plugin class GrapheneClient(val configuration: GrapheneClientConfig) : CoroutineScope, AllBroadcaster { enum class State { CONNECTING, CONNECTED, LOGGING_IN, CLOSED } override val coroutineContext: CoroutineContext = SupervisorJob() override val broadcastScope = CoroutineScope(Dispatchers.IO + coroutineContext) val state: StateFlow<State> get() = stateLocal private val stateLocal = MutableStateFlow(State.CLOSED) private val sequence: AtomicInt = atomic(0) private val connected: AtomicBoolean = atomic(false) private val identifiers: MutableMap<APIType, Int?> = mutableMapOf(APIType.LOGIN to 1) private val sendingChannel: Channel<BroadcastStruct> = Channel() val fallbackChannel: Channel<BroadcastStruct> = Channel(UNLIMITED) private val waiting: MutableList<Continuation<Unit>> = mutableListOf() private val httpClient = HttpClient(CIO.create()) { install(WebSockets) { // TODO: 2022/4/11 contentConverter = KotlinxWebsocketSerializationConverter(Json { ignoreUnknownKeys = false encodeDefaults = true }) pingInterval = 10.seconds.inWholeMilliseconds // keeping alive requires 60 seconds } install(ContentNegotiation) } private val callbackMap: MutableMap<Int, BroadcastStruct> = mutableMapOf() private val subscribeMap: MutableMap<Int, BroadcastStruct> = mutableMapOf() private fun callback(id: Int, result: BroadcastStruct) = callbackMap.set(id, result) private fun callback(id: Int, result: SocketResult) = callbackMap.remove(id)?.cont?.resume(result) private fun callback(id: Int, result: SocketException) = callbackMap.remove(id)?.cont?.resumeWithException(result) private fun callback(id: Int, result: Result<SocketResult>) = callbackMap.remove(id)?.cont?.resumeWith(result) private fun buildSocketCall(struct: BroadcastStruct): SocketCall { val id = sequence.getAndIncrement() val version = SocketCall.JSON_RPC_VERSION val method = SocketCall.METHOD_CALL val params = buildJsonArray { add(identifiers[struct.method.type]) // TODO: 2022/4/12 add(struct.method.nameString) add(struct.params) } return SocketCall(id, version, method, params) } suspend fun awaitConnection() { if (connected.value) return return suspendCancellableCoroutine { waiting.add(it) it.invokeOnCancellation { _ -> waiting.remove(it) } } } private suspend fun open() { connected.value = true waiting.forEach { kotlin.runCatching { it.resume(Unit) } } // TODO: 2022/4/14 waiting.clear() if (configuration.debug) "======== Websocket Open ======== ${configuration.url}".info() } private suspend fun DefaultClientWebSocketSession.sendJsonRpc() { if (configuration.debug) "======== Start Sending ======== ${configuration.url}".info() while (isActive) { val struct = sendingChannel.receive() val socketCall = buildSocketCall(struct) callback(socketCall.id, struct) try { GRAPHENE_JSON_PLATFORM_SERIALIZER.encodeToString(socketCall).also { "Call >>> $it".info() } sendSerialized(socketCall) } catch (e: Exception) { callbackMap.remove(socketCall.id) sendingChannel.send(struct) e.printStackTrace() } } } private suspend fun DefaultClientWebSocketSession.receiveJsonRpc() { if (configuration.debug) "======== Start Recving ======== ${configuration.url}".info() while (isActive) { val result = receiveDeserialized<SocketResult>().also { "Recv <<< $it".info() } callback(result.id, result) } } // broadcast override suspend fun broadcast(method: API, params: JsonArray) : SocketResult { if (method.type != APIType.LOGIN) awaitConnection() return suspendCancellableCoroutine { val struct = BroadcastStruct(method, false, params, it) broadcastScope.launch { try { sendingChannel.send(struct) } catch (e: Throwable) { struct.cont.resumeWithException(e) e.printStackTrace() throw e } } } } suspend fun start() { stateLocal.emit(State.CONNECTING) try { httpClient.wss(configuration.url) { val sendJob = launch { sendJsonRpc() } val receiveJob = launch { receiveJsonRpc() } stateLocal.emit(State.LOGGING_IN) login().let { if (!it) throw SocketErrorException("Incorrect username or password!") } getIdentifiers().let { identifiers.putAll(it) } open() stateLocal.emit(State.CONNECTED) listOf(sendJob, receiveJob).joinAll() } } catch (e: Throwable) { e.printStackTrace() } finally { stateLocal.emit(State.CLOSED) } } fun stop(reason: Exception = SocketManualStopException()) { connected.value = false sequence.value = 0 identifiers.clear() identifiers[APIType.LOGIN] = 1 // if (lastSocketSession.isActive) lastSocketSession.cancel() } suspend fun cancel1(reason: Exception = SocketManualStopException()) { // if (!sendingChannel.isClosedForReceive) { @OptIn(ExperimentalCoroutinesApi::class) if (configuration.enableFallback && !fallbackChannel.isClosedForSend) { callbackMap.forEach { fallbackChannel.send(it.value) } callbackMap.clear() sendingChannel.consumeEach { fallbackChannel.send(it) } } else { callbackMap.clear() sendingChannel.consumeEach { runCatching { it.cont.resumeWithException(reason) } } } // } // waiting.forEach { // runCatching { it.resumeWithException(reason) } // } // waiting.clear() // session.cancel() "Session Canceled for $reason".info() } }
0
Kotlin
0
0
ddd17eb771eea649e681667b6d85e4f292e9e839
8,169
bitshares-kit
MIT License
libraries/splitfeature/src/main/java/com/lgdevs/splitfeature/DownloadFeature.kt
luangs7
493,071,853
false
null
package com.lgdevs.splitfeature import android.util.Log import androidx.compose.foundation.layout.* import androidx.compose.material.AlertDialog import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.google.android.play.core.splitinstall.SplitInstallManager import com.google.android.play.core.splitinstall.SplitInstallRequest import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus import com.lgdevs.mynextbook.designsystem.ui.components.dialog.DefaultDialog import com.lgdevs.mynextbook.designsystem.ui.components.dialog.DialogArguments @Composable fun DownloadFeature( featureName: String, manager: SplitInstallManager, onDismiss: () -> Unit, setState: (SplitState) -> Unit ) { var isDialogOpen by remember { mutableStateOf(true) } DisposableEffect(featureName) { val request = SplitInstallRequest.newBuilder() .addModule(featureName) .build() val listener = SplitInstallStateUpdatedListener { when (it.status()) { SplitInstallSessionStatus.PENDING -> isDialogOpen = true SplitInstallSessionStatus.INSTALLED -> { isDialogOpen = false setState(SplitState.FeatureReady) onDismiss() } else -> {} } } manager.registerListener(listener) manager.startInstall(request) onDispose { manager.unregisterListener(listener) } } if (isDialogOpen) { DownloadDialog() } } @Composable private fun DownloadDialog() { AlertDialog( onDismissRequest = { /* Does not close */ }, title = { Text(text = stringResource(id = R.string.downloading_title)) }, text = { Column { Text(text = stringResource(id = R.string.downloading_description)) Box( contentAlignment = Alignment.Center, modifier = Modifier .fillMaxWidth() .padding(top = 32.dp) ) { CircularProgressIndicator(modifier = Modifier.size(64.dp)) } } }, confirmButton = { /* Shows nothing */ }, dismissButton = { /* Shows nothing */ } ) } @Composable fun RequestDownload(setState: (SplitState) -> Unit, onDismiss: () -> Unit) { var isDialogOpen by remember { mutableStateOf(true) } val arguments = DialogArguments( title = stringResource(id = R.string.confirmation_install_title), text = stringResource(id = R.string.confirmation_install_description), confirmText = stringResource(id = R.string.confirmation_install_accept), dismissText = stringResource(id = R.string.confirmation_install_deny), onConfirmAction = { setState(SplitState.Downloading) } ) DefaultDialog( arguments = arguments, isDialogOpen = isDialogOpen, onDismissRequest = { isDialogOpen = false onDismiss() } ) }
0
Kotlin
0
3
5a4019d97a74658d9bed4b194c574ab53da28bd9
3,463
MyNextBook
MIT License
app/src/main/java/ru/iddqdpwn/vkonkurse/local/db/dao/GiveawayDao.kt
vlad-dz
377,438,926
false
null
package ru.iddqdpwn.vkonkurse.local.db.dao import androidx.lifecycle.LiveData import androidx.room.* import ru.iddqdpwn.vkonkurse.local.db.model.Giveaway @Dao interface GiveawayDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(giveaway: Giveaway) @Delete fun delete(giveaway: Giveaway) @Query("SELECT * FROM giveaway") fun getAllGiveaways(): List<Giveaway> }
0
Kotlin
0
0
4b5a4727b1992903de7e3a55cf587f1633bffe71
403
VKonkurse
Apache License 2.0
app/src/main/kotlin/com/dot/gallery/feature_node/presentation/edit/components/filters/FilterSelector.kt
IacobIonut01
614,314,251
false
{"Kotlin": 1381485, "Shell": 455}
package com.dot.gallery.feature_node.presentation.edit.components.filters import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.core.graphics.drawable.toDrawable import com.dot.gallery.feature_node.domain.model.ImageFilter import com.dot.gallery.feature_node.presentation.edit.EditViewModel import com.dot.gallery.ui.theme.Shapes import com.google.accompanist.drawablepainter.rememberDrawablePainter @Composable fun FilterSelector( filters: List<ImageFilter>, viewModel: EditViewModel ) { LazyRow( modifier = Modifier.fillMaxWidth(), contentPadding = PaddingValues(horizontal = 16.dp, vertical = 16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { items( items = filters, key = { it.name } ) { FilterItem( imageFilter = it, currentFilter = viewModel.currentFilter ) { viewModel.addFilter(it) } } } } @Composable fun FilterItem( imageFilter: ImageFilter, currentFilter: MutableState<ImageFilter?>, onFilterSelect: () -> Unit ) { val isSelected = remember (currentFilter.value) { currentFilter.value?.name == imageFilter.name || currentFilter.value == null && imageFilter.name == "None" } Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp) ) { val widthAnimation by animateDpAsState( targetValue = if (isSelected) 4.dp else 0.dp, label = "widthAnimation" ) val colorAnimation by animateColorAsState( targetValue = if (isSelected) MaterialTheme.colorScheme.tertiary else Color.Transparent, label = "colorAnimation" ) Image( modifier = Modifier .size(92.dp) .clip(Shapes.large) .border( width = widthAnimation, shape = Shapes.large, color = colorAnimation ) .clickable( enabled = !isSelected, onClick = onFilterSelect ), painter = rememberDrawablePainter(imageFilter.filterPreview.toDrawable(LocalContext.current.resources)), contentScale = ContentScale.Crop, contentDescription = imageFilter.name ) Text( text = imageFilter.name, fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal ) } }
87
Kotlin
66
1,292
261ceb8c5ade6ede7b295536b9384ac12d77f572
3,764
Gallery
Apache License 2.0
dTrip-main/app/src/main/java/com/zzp/dtrip/data/Result.kt
Dcelysia
865,949,432
false
{"Kotlin": 188427, "Java": 96523}
package com.zzp.dtrip.data data class Result( val ad_info: AdInfoX, val address: String, val address_component: AddressComponent, val address_reference: AddressReference, val formatted_addresses: FormattedAddresses, val location: Location, val poi_count: Int, val pois: List<Poi> )
0
Kotlin
0
0
3e3774c4b36d6f07f1714f7876103c9d08910475
314
2024-shumei-app
Apache License 2.0
src/main/kotlin/com/github/fnunezkanut/HelloVerticle.kt
fnunezkanut
128,556,031
false
null
package com.github.fnunezkanut import io.vertx.core.AbstractVerticle import io.vertx.core.logging.LoggerFactory import io.vertx.kotlin.core.http.HttpServerOptions class HelloVerticle : AbstractVerticle() { companion object { private val logger = LoggerFactory.getLogger(HelloVerticle::class.java) } init { logger.info( this::class.java.name + " created") } override fun start() { logger.info( this::class.java.name + " started") vertx.createHttpServer( HttpServerOptions( port = 8081, host = "localhost" ) ).requestHandler { req -> logger.info( "request received, replying...") req.response().end("Hello World + Kotlin + Gradle + Vertx") }.listen() } }
0
Kotlin
0
0
9587f028e31b709f042b3b6061e0aa8ebaaa1361
812
vertx-kotlin-helloworld
MIT License
app/src/main/java/com/gms/app/repo/videos/VideosRepo.kt
YasserAdel564
406,843,475
false
{"Kotlin": 193933}
package com.gms.app.repo.videos import android.util.Log import com.gms.app.data.storage.local.PreferencesHelper import com.gms.app.data.storage.local.db.AppDao import com.gms.app.data.storage.remote.model.auth.CountryModel import com.gms.app.data.storage.remote.model.auth.GenderModel import com.gms.app.data.storage.remote.model.home.SliderModel import com.gms.app.data.storage.remote.model.programs.MyProgrammeModel import com.gms.app.data.storage.remote.model.programs.ProgrammeModel import com.gms.app.data.storage.remote.model.programs.ProgrammePeriodModel import com.gms.app.data.storage.remote.model.video.VideoModel import com.gms.app.utils.* import org.ksoap2.SoapEnvelope import org.ksoap2.serialization.SoapObject import org.ksoap2.serialization.SoapSerializationEnvelope import org.ksoap2.transport.HttpTransportSE import javax.inject.Inject class VideosRepo @Inject constructor( private val preferencesHelper: PreferencesHelper ) { private val videosList = ArrayList<VideoModel>() suspend fun getVideos(): DataResource<List<VideoModel>> { return safeApiCall { videoCall() } } private fun videoCall(): List<VideoModel> { val request = SoapObject(Constants.NameSpace, Constants.MethodNames.GetVideos.value) val envelope = SoapSerializationEnvelope(SoapEnvelope.VER11) val androidHttpTransport = HttpTransportSE(Constants.BaseUrl) envelope.dotNet = true envelope.setOutputSoapObject(request) addKeyPropertyInt(request, "ID", preferencesHelper.userId.toInt()) androidHttpTransport.call( (Constants.NameSpace + Constants.MethodNames.GetVideos.value), envelope ) val resultsString = envelope.response as SoapObject val object1 = resultsString.getProperty(1) as SoapObject if (object1.propertyCount > 0) { videosList.clear() val tables = object1.getProperty(0) as SoapObject for (i in 0 until tables.propertyCount) { val soapObject = tables.getProperty(i) as SoapObject val id: String = soapObject.getProperty("ID").toString() val title: String = soapObject.getProperty("Title").toString() val brief: String = soapObject.getProperty("Brief").toString() val details: String = soapObject.getProperty("details").toString() val img: String = soapObject.getProperty("picture").toString() val writer: String = soapObject.getProperty("Writer").toString() val link: String = soapObject.getProperty("Column1").toString() val views: String = soapObject.getProperty("Views").toString() val reviews: String = soapObject.getProperty("Reviews").toString() val date: String = soapObject.getProperty("publishdate").toString() // val video: String = soapObject.getProperty("Video").toString() Log.e("video", preferencesHelper.userId) videosList.add( (VideoModel( id = id.toInt(), title = title, brief = brief, details = details, img = Constants.ImagesUrl + img, writer = writer, link = link, views = views, reviews = reviews, date = date )) ) } } return videosList } }
0
Kotlin
0
0
96d69372c3d70597395641c6529d48e0830f4770
3,556
GMS
MIT License
android/app/src/main/java/com/algorand/android/modules/sorting/utils/SortingTypeCreator.kt
perawallet
364,359,642
false
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
/* * Copyright 2022 Pera Wallet, LDA * 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.algorand.android.modules.sorting.utils import com.algorand.android.modules.sorting.accountsorting.domain.model.AccountSortingType import javax.inject.Inject class SortingTypeCreator @Inject constructor() { fun createForAccountSorting(): List<AccountSortingType> { return mutableListOf<AccountSortingType>().apply { add(AccountSortingType.AlphabeticallyAscending) add(AccountSortingType.AlphabeticallyDescending) add(AccountSortingType.NumericalAscendingSort) add(AccountSortingType.NumericalDescendingSort) add(AccountSortingType.ManuallySort) } } }
22
Swift
62
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
1,233
pera-wallet
Apache License 2.0