path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/test/kotlin/com/github/nenadjakic/eav/controller/EntityControllerTest.kt
nenadjakic
782,709,579
false
null
package com.github.nenadjakic.eav.controller import com.github.nenadjakic.eav.dto.EntityAddRequest import com.github.nenadjakic.eav.dto.EntityResponse import com.github.nenadjakic.eav.dto.EntityUpdateRequest import com.github.nenadjakic.eav.security.JwtService import com.github.nenadjakic.eav.security.model.SecurityUser import com.jayway.jsonpath.DocumentContext import com.jayway.jsonpath.JsonPath import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.test.context.TestPropertySource @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource(locations=["classpath:application.properties"]) class EntityControllerTest { @Autowired lateinit var restTemplate: TestRestTemplate @Autowired lateinit var jwtService: JwtService lateinit var headers: HttpHeaders @BeforeEach fun setUp() { val securityUser = SecurityUser() securityUser.username = "test" securityUser.addAuthority(SimpleGrantedAuthority("READER")) securityUser.addAuthority(SimpleGrantedAuthority("WRITER")) val token = jwtService.createToken(securityUser) headers = HttpHeaders() headers.setBearerAuth(token) } @AfterEach fun tearDown() { } @Test fun findAll() { val response = restTemplate.exchange( "/entity", HttpMethod.GET, HttpEntity<String>(headers), List::class.java ) assertEquals(200, response.statusCode.value()) assertTrue(response.body.size > 10) } @Test fun findPage() { val response = restTemplate.exchange( "/entity/page?pageNumber={pageNumber}&pageSize={pageSize}", HttpMethod.GET, HttpEntity<String>(headers), Any::class.java, 0, 10 ) assertEquals(200, response.statusCode.value()) assertEquals(10, (response.body as Map<*, *>)["size"]) assertEquals(10, ((response.body as Map<*, *>)["content"] as Collection<*>).size) } @Test fun findById_NotFound() { val response = restTemplate.exchange( "/entity/99999", HttpMethod.GET, HttpEntity<String>(headers), EntityResponse::class.java ) assertEquals(404, response.statusCode.value()) } @Test fun findById() { val response = restTemplate.exchange( "/entity/10002", HttpMethod.GET, HttpEntity<String>(headers), EntityResponse::class.java ) assertEquals(200, response.statusCode.value()) val documentContext: DocumentContext = JsonPath.parse(response.body) val entityResponse = documentContext.json<EntityResponse>() assertEquals(10002, entityResponse.id) } @Test fun create() { val body = EntityAddRequest() body.entityTypeId = 10001 val postResponse = restTemplate.exchange( "/entity", HttpMethod.POST, HttpEntity(body, headers), EntityAddRequest::class.java ) assertEquals(201, postResponse.statusCode.value()) val response = restTemplate.exchange( postResponse.headers.location, HttpMethod.GET, HttpEntity<String>(headers), EntityResponse::class.java ) assertEquals(200, response.statusCode.value()) } @Test fun update() { val body = EntityUpdateRequest() body.id = 10001 body.name = "new_name_updated" body.description = "new_description" val putResponse = restTemplate.exchange( "/entity", HttpMethod.PUT, HttpEntity(body, headers), EntityResponse::class.java ) assertEquals(204, putResponse.statusCode.value()) val response = restTemplate.exchange( "/entity/10001", HttpMethod.GET, HttpEntity<String>(headers), EntityResponse::class.java ) assertEquals(200, response.statusCode.value()) val documentContext: DocumentContext = JsonPath.parse(response.body) val entityResponse = documentContext.json<EntityResponse>() assertEquals(10001, entityResponse.id) } @Test fun deleteById() { assertEquals(204, restTemplate.exchange( "/entity/10002", HttpMethod.DELETE, HttpEntity<String>(headers), Void::class.java ).statusCode.value()) assertEquals(404, restTemplate.exchange( "/entity/10002", HttpMethod.GET, HttpEntity<String>(headers), EntityResponse::class.java ).statusCode.value()) } }
0
null
0
2
d729c8314a35e529c49548847ab42b4edcf86db2
5,373
eav-platform
MIT License
packages/cactus-plugin-ledger-connector-fabric/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/FileBase64.kt
RafaelAPB
241,220,244
true
{"Markdown": 534, "YAML": 326, "JSON with Comments": 89, "JSON": 375, "JavaScript": 76, "Ignore List": 86, "CODEOWNERS": 2, "Text": 19, "Git Attributes": 1, "SVG": 13, "Gradle": 56, "Makefile": 40, "INI": 27, "Shell": 191, "Batchfile": 24, "XML": 14, "Kotlin": 695, "Dockerfile": 50, "Go": 130, "Go Checksums": 16, "Go Module": 16, "Gerber Image": 46, "TOML": 41, "Roff Manpage": 1, "Rust": 53, "Gradle Kotlin DSL": 2, "Java": 1, "ANTLR": 1, "Protocol Buffer": 47, "Dotenv": 6, "Smarty": 8, "JAR Manifest": 2, "EJS": 2, "CSS": 34, "OASv3-json": 32, "PlantUML": 25, "SQL": 7, "PLpgSQL": 1, "Maven POM": 1, "OASv3-yaml": 1, "Mustache": 7, "HTML": 15, "TypeScript": 1, "TSX": 58, "Python": 1, "reStructuredText": 5, "SCSS": 6, "Solidity": 1, "robots.txt": 1, "Gherkin": 4, "Logos": 2, "Public Key": 3}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.openapitools.client.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Represents a file-system file that has a name and a body which holds the file contents as a Base64 encoded string * * @param body The file's contents encoded as a Base64 string. * @param filename The name as referred to on a file system * @param filepath The relative path of the file, if it should be placed in a sub-directory */ data class FileBase64 ( /* The file's contents encoded as a Base64 string. */ @Json(name = "body") val body: kotlin.String, /* The name as referred to on a file system */ @Json(name = "filename") val filename: kotlin.String, /* The relative path of the file, if it should be placed in a sub-directory */ @Json(name = "filepath") val filepath: kotlin.String? = null )
50
TypeScript
3
6
4c94bf21ee570349995c61204fe60a2dc6a35766
1,134
blockchain-integration-framework
Apache License 2.0
dbinspector/src/main/kotlin/com/infinum/dbinspector/DbInspector.kt
brahmantya
321,405,181
false
null
package com.infinum.dbinspector import android.content.Intent import com.infinum.dbinspector.ui.Presentation import com.infinum.dbinspector.ui.databases.DatabasesActivity import com.infinum.dbinspector.ui.shared.logger.DeadTree import timber.log.Timber import timber.log.Timber.DebugTree object DbInspector { @JvmStatic fun show() { when (BuildConfig.DEBUG) { true -> Timber.plant(DebugTree()) false -> Timber.plant(DeadTree()) } with(Presentation.applicationContext()) { this.startActivity( Intent(this, DatabasesActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } ) } } }
0
Kotlin
0
0
2faef15dacd9fb8d21e41cc5100b1a91c82b80d2
743
P.MOBILE-TUGAS-MODUL10
Apache License 2.0
app/src/main/java/com/deonolarewaju/product_catalogue/presentation/details/ProductDetailsViewModel.kt
deonwaju
729,797,385
false
{"Kotlin": 48833}
package com.deonolarewaju.product_catalogue.presentation.details import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.deonolarewaju.product_catalogue.domain.usecases.ProductsUsecases import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ProductDetailsViewModel @Inject constructor( private val productsUsecases: ProductsUsecases ) : ViewModel() { var state by mutableStateOf(ProductDetailsState()) fun getProduct(id: Int) { viewModelScope.launch { state = try { val product = productsUsecases.getProductById(id) if (product != null) { state.copy(product = product, error = null) } else { state.copy(error = "Product not found") } } catch (e: Exception) { state.copy(error = e.message) } } } }
0
Kotlin
0
1
fead009cfd7e36c09d4c8965c768c6b6f12d75d8
1,126
Product-catalogue
MIT License
ktest-integration/ktest-rest/src/main/kotlin/run/smt/ktest/rest/rest.kt
saksmt
115,024,215
false
null
package run.smt.ktest.rest import run.smt.ktest.config.config import run.smt.ktest.rest.impl.RestContextRegistry /** * Entry point for REST API DSL */ val rest = RestContextRegistry(config)
17
Kotlin
2
12
22ba03a69dcf04d95c9e3f5b1c3740ef4dcd07e5
194
ktest
MIT License
Themer/src/main/kotlin/dev/vendicated/aliucordplugs/themer/settings/ThemerSettings.kt
Vendicated
370,103,505
false
{"Kotlin": 219859, "Java": 90817, "JavaScript": 3425, "Shell": 1232}
/* * Ven's Aliucord Plugins * Copyright (C) 2021 Vendicated * * 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 */ package dev.vendicated.aliucordplugs.themer.settings import android.annotation.SuppressLint import android.content.Intent import android.graphics.Color import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RectShape import android.view.View import android.widget.TextView import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import androidx.recyclerview.widget.* import com.aliucord.* import com.aliucord.fragments.* import com.aliucord.utils.DimenUtils import com.aliucord.views.Button import com.aliucord.views.Divider import com.discord.stores.StoreStream import com.discord.views.CheckedSetting import com.discord.views.RadioManager import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.Snackbar.LENGTH_INDEFINITE import com.lytefast.flexinput.R import dev.vendicated.aliucordplugs.themer.* import kotlin.system.exitProcess class ThemerSettings : SettingsPage() { @SuppressLint("SetTextI18n") override fun onViewBound(view: View) { super.onViewBound(view) if (Themer.mSettings.fontHookCausedCrash) { Themer.mSettings.fontHookCausedCrash = false ConfirmDialog() .setTitle("Oops!") .setDescription("Enabling fonts seems to have crashed your Aliucord! Thus, they have automatically been disabled again.") .show(parentFragmentManager, "fontHookCausedCrashDialog") } if (StoreStream.getUserSettingsSystem().theme != "dark") { ConfirmDialog().apply { setTitle("Hold on!") setDescription("Most themes only work correctly on regular Dark Mode. Switch to it now?") setOnOkListener { // If current theme is "pureEvil" and you pass "dark", it changes it to "pureEvil" // So change to "light" first StoreStream.getUserSettingsSystem().setTheme("light", false, null); StoreStream.getUserSettingsSystem().setTheme("dark", false, null); dismiss() } }.show(parentFragmentManager, "themerSwitchToDarkWhen") } val ctx = view.context setActionBarTitle("Themer") /* TextView(ctx, null, 0, R.i.UiKit_TextView).run { val content = "Read the changelog!" SpannableStringBuilder(content).let { it.setSpan(object : ClickableSpan() { override fun onClick(widget: View) { val manifest = PluginManager.plugins["Themer"]!!.manifest ChangelogUtils.show(context, manifest.version, manifest.changelogMedia, manifest.changelog) } }, content.indexOf("changelog"), content.length, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE) text = it } textAlignment = TEXT_ALIGNMENT_CENTER DimenUtils.defaultPadding.let { setPadding(it, it, it, it) } movementMethod = LinkMovementMethod.getInstance() linearLayout.addView(this) }*/ Button(ctx).apply { text = "Load missing themes" setOnClickListener { ThemeLoader.loadThemes(false) reRender() } linearLayout.addView(this) } TextView(ctx, null, 0, R.i.UiKit_Settings_Item_Header).apply { text = "Transparency Mode" typeface = ResourcesCompat.getFont(ctx, Constants.Fonts.whitney_semibold) linearLayout.addView(this) } arrayListOf( Utils.createCheckedSetting(ctx, CheckedSetting.ViewType.RADIO, "None", "No transparency"), Utils.createCheckedSetting(ctx, CheckedSetting.ViewType.RADIO, "Chat", "Chat is transparent"), Utils.createCheckedSetting(ctx, CheckedSetting.ViewType.RADIO, "Chat & Settings", "Chat and Settings page are transparent"), Utils.createCheckedSetting( ctx, CheckedSetting.ViewType.RADIO, "Full", "Everything is transparent. Will only work with themes specifically made for it." ), ).let { radios -> val manager = RadioManager(radios) manager.a(radios[Themer.mSettings.transparencyMode.value]) for (i in 0 until radios.size) { val radio = radios[i] radio.e { manager.a(radio) Themer.mSettings.transparencyMode = TransparencyMode.from(i) promptRestart(view, this) } addView(radio) } } addView(Divider(ctx)) addView( Utils.createCheckedSetting( ctx, CheckedSetting.ViewType.SWITCH, "Enable Custom Fonts", "Enabled support for custom fonts. May be unstable" ).apply { isChecked = Themer.mSettings.enableFontHook setOnCheckedListener { checked -> if (!checked) { Themer.mSettings.enableFontHook = false return@setOnCheckedListener } isChecked = false ConfirmDialog().apply { setTitle("Hold on") setDescription("This is unstable on some roms and may lead to crashes or the Aliucord settings section to disappear.\nIf such a crash occurs, fonts will automatically be disabled again.\n\nIf this for some reason fails or only the settings sections disappears, you must manually open the settings folder in your Aliucord directory and delete 'Themer.json' to fix it.\nPROCEED AT YOUR OWN RISK!") setIsDangerous(true) setOnOkListener { isChecked = true Themer.mSettings.enableFontHook = true promptRestart(view, this@ThemerSettings) dismiss() } }.show(parentFragmentManager, "themerEnableFonts") } } ) addView(Divider(ctx)) addView( Utils.createCheckedSetting(ctx, CheckedSetting.ViewType.SWITCH, "Enable Custom Sounds", "Enable support for custom sounds") .apply { isChecked = Themer.mSettings.customSounds setOnCheckedListener { Themer.mSettings.customSounds = it promptRestart(view, this@ThemerSettings) } } ) addView(Divider(ctx)) TextView(ctx, null, 0, R.i.UiKit_Settings_Item_Header).run { text = "Themes" typeface = ResourcesCompat.getFont(ctx, Constants.Fonts.whitney_semibold) linearLayout.addView(this) } TextView(ctx, null, 0, R.i.UiKit_Settings_Item_Addition).run { text = "Enable multiple themes at your own risk! The result may destroy your eyes." linearLayout.addView(this) } val recycler = RecyclerView(ctx).apply { adapter = ThemeAdapter(this@ThemerSettings, ThemeLoader.themes) layoutManager = LinearLayoutManager(ctx) val decoration = DividerItemDecoration(ctx, DividerItemDecoration.VERTICAL) ShapeDrawable(RectShape()).run { setTint(Color.TRANSPARENT) intrinsicHeight = DimenUtils.defaultPadding decoration.setDrawable(this) } addItemDecoration(decoration) } Button(ctx).run { text = "New Theme" DimenUtils.defaultPadding.let { setPadding(it, it, it, it) } setOnClickListener { val dialog = InputDialog() .setTitle("New Theme") .setDescription("Please choose a name for your theme") .setPlaceholderText("Name") dialog.setOnOkListener { val name = dialog.input if (name.isEmpty()) { Utils.showToast("Cancelled.") } else { try { ThemeLoader.themes.add(0, Theme.create(name)) recycler.adapter!!.notifyItemInserted(0) dialog.dismiss() } catch (ex: Throwable) { if (ex is ThemeException) { Utils.showToast(ex.message, true) } else { logger.errorToast("Something went wrong, sorry. Check the debug log for more info", ex) } } } } dialog.show(parentFragmentManager, "New Theme") } linearLayout.addView(this) } addView(recycler) } companion object { fun promptRestart(v: View, fragment: Fragment, msg: String = "Changes detected. Restart?") { Snackbar.make(v, msg, LENGTH_INDEFINITE) .setAction("Restart") { val ctx = it.context ctx.packageManager.getLaunchIntentForPackage(ctx.packageName)?.run { fragment.startActivity(Intent.makeRestartActivityTask(component)) exitProcess(0) } }.show() } } }
7
Kotlin
28
209
a1decb53c13219145ef2336c818d5e2b348f61cc
10,086
AliucordPlugins
Apache License 2.0
app/src/main/java/com/milad/githoob/ui/launch/LaunchViewModel.kt
cloner93
425,942,827
false
{"Kotlin": 177291, "Java": 19564}
package com.milad.githoob.ui.launch import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.milad.githoob.data.MainRepository import com.milad.githoob.utils.AppConstants.KEY_DATA_STORE_TOKEN import com.milad.githoob.utils.Status import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @HiltViewModel class LaunchViewModel @Inject constructor( private val mainRepository: MainRepository, private val dataStore: DataStore<Preferences>, private val ioDispatcher: CoroutineDispatcher ) : ViewModel() { private var _token = MutableLiveData<String>() var token: LiveData<String> = _token fun fetchToken( clientId: String, clientSecret: String, code: String ) { viewModelScope.launch(ioDispatcher) { mainRepository.getAccessToken( clientId, clientSecret, code ).collect { when (it.status) { Status.SUCCESS -> { it.data.let { if (it?.access_token != null && !it.access_token.equals("")) { val token = "token ${it.access_token}" _token.postValue(token) saveToken(token) } } } Status.LOADING -> { } Status.ERROR -> { Timber.d(it.message.toString()) } } } } } suspend fun saveToken(token: String) { dataStore.edit { it[KEY_DATA_STORE_TOKEN] = token } } }
1
Kotlin
1
15
5336a47605afeacd0c3334b92845eba4579091e6
2,136
GitHoob
MIT License
encoding/src/commonMain/kotlin/diglol/encoding/InternalApi.kt
diglol
398,510,655
false
{"Kotlin": 50480}
package diglol.encoding @Target( AnnotationTarget.CLASS, AnnotationTarget.PROPERTY, AnnotationTarget.FUNCTION, AnnotationTarget.TYPEALIAS ) @RequiresOptIn(level = RequiresOptIn.Level.ERROR) annotation class InternalApi
3
Kotlin
1
9
6f16529086116fcfea849759d12d2c634a1c47b4
228
encoding
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/comprehend/CfnDocumentClassifierDocumentClassifierInputDataConfigPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 63959868}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.comprehend import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.Any import kotlin.String import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.comprehend.CfnDocumentClassifier /** * The input properties for training a document classifier. * * For more information on how the input file is formatted, see * [Preparing training data](https://docs.aws.amazon.com/comprehend/latest/dg/prep-classifier-data.html) * in the Comprehend Developer Guide. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.comprehend.*; * DocumentClassifierInputDataConfigProperty documentClassifierInputDataConfigProperty = * DocumentClassifierInputDataConfigProperty.builder() * .augmentedManifests(List.of(AugmentedManifestsListItemProperty.builder() * .attributeNames(List.of("attributeNames")) * .s3Uri("s3Uri") * // the properties below are optional * .split("split") * .build())) * .dataFormat("dataFormat") * .documentReaderConfig(DocumentReaderConfigProperty.builder() * .documentReadAction("documentReadAction") * // the properties below are optional * .documentReadMode("documentReadMode") * .featureTypes(List.of("featureTypes")) * .build()) * .documents(DocumentClassifierDocumentsProperty.builder() * .s3Uri("s3Uri") * // the properties below are optional * .testS3Uri("testS3Uri") * .build()) * .documentType("documentType") * .labelDelimiter("labelDelimiter") * .s3Uri("s3Uri") * .testS3Uri("testS3Uri") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-comprehend-documentclassifier-documentclassifierinputdataconfig.html) */ @CdkDslMarker public class CfnDocumentClassifierDocumentClassifierInputDataConfigPropertyDsl { private val cdkBuilder: CfnDocumentClassifier.DocumentClassifierInputDataConfigProperty.Builder = CfnDocumentClassifier.DocumentClassifierInputDataConfigProperty.builder() private val _augmentedManifests: MutableList<Any> = mutableListOf() /** * @param augmentedManifests A list of augmented manifest files that provide training data for * your custom model. An augmented manifest file is a labeled dataset that is produced by * Amazon SageMaker Ground Truth. * * This parameter is required if you set `DataFormat` to `AUGMENTED_MANIFEST` . */ public fun augmentedManifests(vararg augmentedManifests: Any) { _augmentedManifests.addAll(listOf(*augmentedManifests)) } /** * @param augmentedManifests A list of augmented manifest files that provide training data for * your custom model. An augmented manifest file is a labeled dataset that is produced by * Amazon SageMaker Ground Truth. * * This parameter is required if you set `DataFormat` to `AUGMENTED_MANIFEST` . */ public fun augmentedManifests(augmentedManifests: Collection<Any>) { _augmentedManifests.addAll(augmentedManifests) } /** * @param augmentedManifests A list of augmented manifest files that provide training data for * your custom model. An augmented manifest file is a labeled dataset that is produced by * Amazon SageMaker Ground Truth. * * This parameter is required if you set `DataFormat` to `AUGMENTED_MANIFEST` . */ public fun augmentedManifests(augmentedManifests: IResolvable) { cdkBuilder.augmentedManifests(augmentedManifests) } /** * @param dataFormat The format of your training data:. * * `COMPREHEND_CSV` : A two-column CSV file, where labels are provided in the first column, * and documents are provided in the second. If you use this value, you must provide the * `S3Uri` parameter in your request. * * `AUGMENTED_MANIFEST` : A labeled dataset that is produced by Amazon SageMaker Ground Truth. * This file is in JSON lines format. Each line is a complete JSON object that contains a * training document and its associated labels. * * If you use this value, you must provide the `AugmentedManifests` parameter in your request. * * If you don't specify a value, Amazon Comprehend uses `COMPREHEND_CSV` as the default. */ public fun dataFormat(dataFormat: String) { cdkBuilder.dataFormat(dataFormat) } /** @param documentReaderConfig the value to be set. */ public fun documentReaderConfig(documentReaderConfig: IResolvable) { cdkBuilder.documentReaderConfig(documentReaderConfig) } /** @param documentReaderConfig the value to be set. */ public fun documentReaderConfig( documentReaderConfig: CfnDocumentClassifier.DocumentReaderConfigProperty ) { cdkBuilder.documentReaderConfig(documentReaderConfig) } /** * @param documentType The type of input documents for training the model. Provide plain-text * documents to create a plain-text model, and provide semi-structured documents to create a * native document model. */ public fun documentType(documentType: String) { cdkBuilder.documentType(documentType) } /** * @param documents The S3 location of the training documents. This parameter is required in a * request to create a native document model. */ public fun documents(documents: IResolvable) { cdkBuilder.documents(documents) } /** * @param documents The S3 location of the training documents. This parameter is required in a * request to create a native document model. */ public fun documents(documents: CfnDocumentClassifier.DocumentClassifierDocumentsProperty) { cdkBuilder.documents(documents) } /** * @param labelDelimiter Indicates the delimiter used to separate each label for training a * multi-label classifier. The default delimiter between labels is a pipe (|). You can use a * different character as a delimiter (if it's an allowed character) by specifying it under * Delimiter for labels. If the training documents use a delimiter other than the default or * the delimiter you specify, the labels on that line will be combined to make a single unique * label, such as LABELLABELLABEL. */ public fun labelDelimiter(labelDelimiter: String) { cdkBuilder.labelDelimiter(labelDelimiter) } /** * @param s3Uri The Amazon S3 URI for the input data. The S3 bucket must be in the same Region * as the API endpoint that you are calling. The URI can point to a single input file or it * can provide the prefix for a collection of input files. * * For example, if you use the URI `S3://bucketName/prefix` , if the prefix is a single file, * Amazon Comprehend uses that file as input. If more than one file begins with the prefix, * Amazon Comprehend uses all of them as input. * * This parameter is required if you set `DataFormat` to `COMPREHEND_CSV` . */ public fun s3Uri(s3Uri: String) { cdkBuilder.s3Uri(s3Uri) } /** * @param testS3Uri This specifies the Amazon S3 location that contains the test annotations for * the document classifier. The URI must be in the same AWS Region as the API endpoint that * you are calling. */ public fun testS3Uri(testS3Uri: String) { cdkBuilder.testS3Uri(testS3Uri) } public fun build(): CfnDocumentClassifier.DocumentClassifierInputDataConfigProperty { if (_augmentedManifests.isNotEmpty()) cdkBuilder.augmentedManifests(_augmentedManifests) return cdkBuilder.build() } }
4
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
8,099
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/com/eneskayiklik/word_diary/feature/settings/domain/model/License.kt
Enes-Kayiklik
651,794,521
false
null
package com.eneskayiklik.word_diary.feature.settings.domain.model import com.mikepenz.aboutlibraries.entity.Library data class License( val title: String, val license: String?, val version: String?, val author: String? ) fun Library.toLicence() = try { License( title = name, license = licenses.firstOrNull()?.name, version = artifactVersion, author = developers.firstOrNull()?.name ) } catch (e: Exception) { e.printStackTrace() null }
0
Kotlin
0
3
236d4c497d7e141f1536fb62f7458459420d1fe9
504
WordDiary
MIT License
components/firstpair/impl/src/main/java/com/flipperdevices/firstpair/impl/composable/searching/ComposableSearchingProgress.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.firstpair.impl.composable.searching import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.flipperdevices.core.ui.R as DesignSystem import com.flipperdevices.core.ui.composable.ComposeLottiePic import com.flipperdevices.firstpair.impl.R @Composable fun ComposableSearchingProgress(modifier: Modifier) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Row( modifier = Modifier.padding(bottom = 36.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .size(size = 82.dp) .padding(end = 13.dp), painter = painterResource(R.drawable.pic_phone), contentDescription = null ) ComposeLottiePic( modifier = Modifier.size(size = 32.dp), picResId = R.raw.dots_loader, rollBackPicResId = R.drawable.pic_loader ) Icon( modifier = Modifier .size(size = 82.dp) .padding(start = 13.dp), painter = painterResource(R.drawable.pic_flipper_heavy), contentDescription = stringResource(R.string.firstpair_search_flipper_status), tint = colorResource(DesignSystem.color.accent_secondary) ) } Text( text = stringResource(R.string.firstpair_search_loader_text), color = colorResource(DesignSystem.color.black_30), fontWeight = FontWeight.W400, fontSize = 18.sp ) } }
2
Kotlin
31
293
522f873d6dcf09a8f1907c1636fb0c3a996f5b44
2,389
Flipper-Android-App
MIT License
streaming/testSrc/com/android/tools/idea/streaming/emulator/EmulatorUiSettingsControllerTest.kt
JetBrains
60,701,247
false
{"Kotlin": 49550960, "Java": 35837871, "HTML": 1217714, "Starlark": 909188, "C++": 357481, "Python": 106384, "C": 71782, "Lex": 66732, "NSIS": 58538, "AIDL": 35382, "Shell": 26938, "CMake": 26798, "JavaScript": 18437, "Smali": 7580, "Batchfile": 6951, "RenderScript": 4411, "Makefile": 2495, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.streaming.emulator import com.android.adblib.testing.FakeAdbDeviceServices import com.android.testutils.waitForCondition import com.android.tools.idea.streaming.uisettings.binding.TwoWayProperty import com.android.tools.idea.streaming.uisettings.ui.UiSettingsModel import com.google.common.truth.Truth.assertThat import com.intellij.openapi.Disposable import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import kotlin.time.Duration.Companion.seconds class EmulatorUiSettingsControllerTest { @get:Rule val rule = UiSettingsRule(emulatorPort = 4445) private val testRootDisposable: Disposable get() = rule.testRootDisposable private val adb: FakeAdbDeviceServices get() = rule.adb private val lastIssuedChangeCommand: String? get() = rule.issuedChangeCommands.lastOrNull { it != "cmd uimode night" } private val model: UiSettingsModel by lazy { UiSettingsModel() } private val controller: EmulatorUiSettingsController by lazy { createController() } @Before fun before() { adb.configureShellCommand(rule.deviceSelector, "cmd uimode night yes", "Night mode: yes") adb.configureShellCommand(rule.deviceSelector, "cmd uimode night no", "Night mode: no") simulateDarkTheme(false) } @Test fun testReadDefaultValueWhenAttachingAfterInit() { controller.initAndWait() val state = createAndAddListener(model.inDarkMode, true) assertThat(model.inDarkMode.value).isFalse() assertThat(state.changes).isEqualTo(1) assertThat(state.lastValue).isFalse() } @Test fun testReadDefaultValueWhenAttachingBeforeInit() { val state = createAndAddListener(model.inDarkMode, true) controller.initAndWait() assertThat(model.inDarkMode.value).isFalse() assertThat(state.changes).isEqualTo(2) // After addListener and after value read assertThat(state.lastValue).isFalse() } @Test fun testReadCustomValue() { simulateDarkTheme(true) controller.initAndWait() val state = createAndAddListener(model.inDarkMode, false) assertThat(model.inDarkMode.value).isTrue() assertThat(state.changes).isEqualTo(1) assertThat(state.lastValue).isTrue() } @Test fun testSetNightModeOn() { controller.initAndWait() model.inDarkMode.setFromUi(true) waitForCondition(10.seconds) { lastIssuedChangeCommand == "cmd uimode night yes" } } @Test fun testSetNightOff() { simulateDarkTheme(true) controller.initAndWait() model.inDarkMode.setFromUi(false) waitForCondition(10.seconds) { lastIssuedChangeCommand == "cmd uimode night no" } } private fun createController() = EmulatorUiSettingsController(rule.project, rule.emulatorSerialNumber, model, testRootDisposable) private fun simulateDarkTheme(on: Boolean) { val state = if (on) "yes" else "no" adb.configureShellCommand(rule.deviceSelector, "cmd uimode night", "Night mode: $state") } private data class ListenerState<T>(var changes: Int, var lastValue: T) private fun <T> createAndAddListener(property: TwoWayProperty<T>, initialValue: T): ListenerState<T> { val state = ListenerState(0, initialValue) property.addControllerListener(testRootDisposable) { newValue -> state.changes++ state.lastValue = newValue } return state } private fun EmulatorUiSettingsController.initAndWait() = runBlocking { populateModel() } }
3
Kotlin
219
921
dbd9aeae0dc5b8c56ce2c7d51208ba26ea0f169b
4,065
android
Apache License 2.0
app/src/main/java/ai/deepar/deepar_example/home/HomePage.kt
LK1919
835,766,213
false
{"Kotlin": 185117, "Java": 1149}
package ai.deepar.deepar_example.home import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import ai.deepar.deepar_example.R import ai.deepar.deepar_example.databinding.ActivityPatientMyAppointmentsBinding import ai.deepar.deepar_example.patient.AppointmentActivity import ai.deepar.deepar_example.patient.PatientMyAppointmentsActivity import ai.deepar.deepar_example.patient.PatientProfileActivity import android.annotation.SuppressLint import android.content.Intent import android.widget.Button import android.widget.Toast import androidx.cardview.widget.CardView import com.google.android.material.bottomsheet.BottomSheetDialog import java.util.Date // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [HomePage.newInstance] factory method to * create an instance of this fragment. */ class HomePage : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } @SuppressLint("MissingInflatedId") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_home_page, container, false) val btnAppointments = view.findViewById<CardView>(R.id.appointmentsCard) btnAppointments.setOnClickListener { startActivity(Intent(requireActivity(), PatientMyAppointmentsActivity::class.java)) } val btnBranches = view.findViewById<CardView>(R.id.branchesCard) btnBranches.setOnClickListener { startActivity(Intent(requireActivity(), BranchesScreen::class.java)) } val btnSetAppointments = view.findViewById<CardView>(R.id.setAppointmentCard) btnSetAppointments.setOnClickListener { startActivity(Intent(requireActivity(), AppointmentActivity::class.java)) } // bottom sheet dialog option // val btnShowAppointmentsBottomSheet = view.findViewById<CardView>(R.id.setAppointmentCard) // btnShowAppointmentsBottomSheet.setOnClickListener { // val dialog = BottomSheetDialog(this.requireContext()) // val view2 = layoutInflater.inflate(R.layout.bottom_sheet_dialog, null) // val btnClose = view2.findViewById<Button>(R.id.bsdCancelAppointmentBtn) // val btnSetAppointment = view2.findViewById<Button>(R.id.bsdSetAppointmentBtn) // val checkAvailBranches = view2.findViewById<Button>(R.id.bsdCheckBranchesBtn) // // btnClose.setOnClickListener { // dialog.dismiss() // } // // btnSetAppointment.setOnClickListener { // Toast.makeText(this@HomePage.requireContext(), "Appointment set successfully", Toast.LENGTH_LONG).show() // startActivity(Intent(requireActivity(), PatientMyAppointmentsActivity::class.java)) // } // // checkAvailBranches.setOnClickListener { // startActivity(Intent(requireActivity(), BranchesScreen::class.java)) // } // // // dialog.setCancelable(false) // dialog.setContentView(view2) // dialog.show() // } val btnGlasses = view.findViewById<CardView>(R.id.glassesCard) btnGlasses.setOnClickListener { startActivity(Intent(requireActivity(), GlassesScreen::class.java)) } val btnProfile = view.findViewById<CardView>(R.id.profileCard) btnProfile.setOnClickListener { startActivity(Intent(requireActivity(), PatientProfileActivity::class.java)) } return view } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment HomePage. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = HomePage().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
0
Kotlin
0
0
c3784e097cc490935607aa3510811200b5f9f3f8
4,505
capstone-delux
MIT License
storage/db-core/src/main/kotlin/io/raemian/storage/db/core/token/RefreshToken.kt
depromeet
717,344,375
false
null
// package io.raemian.storage.db.core.token // // import jakarta.persistence.Entity // import jakarta.persistence.Id // // @Entity // class RefreshToken( // @Id // val id: Long, // val key: String, // val value: String, // )
9
null
0
1
e7973d2ce47441043eb2aee2a917d77c8c9ccec5
241
amazing3-be
Apache License 2.0
tabulate-core/src/main/kotlin/io/github/voytech/tabulate/core/model/alignment/HorizontalAlignment.kt
voytech
262,033,710
false
{"Kotlin": 829177, "Java": 7351, "Shell": 679}
package io.github.voytech.tabulate.core.model.alignment interface HorizontalAlignment { fun getHorizontalAlignmentId() : String }
19
Kotlin
0
2
8a33d3b65128d9ebac6edf5b2f8e93fd4947041c
134
tabulate
Apache License 2.0
src/test/kotlin/io/github/orioncraftmc/sprawlkt/tests/generated/JustifyContentRowMaxWidthAndMarginTest.kt
OrionCraftMC
491,301,394
false
null
package io.github.orioncraftmc.sprawlkt.tests.generated import io.github.orioncraftmc.sprawlkt.geometry.Size import io.github.orioncraftmc.sprawlkt.geometry.Size.Companion.undefinedNumber import io.github.orioncraftmc.sprawlkt.node.Sprawl import io.github.orioncraftmc.sprawlkt.node.Sprawl.computeLayout import io.github.orioncraftmc.sprawlkt.node.Sprawl.layout import io.github.orioncraftmc.sprawlkt.node.Sprawl.newNode import io.github.orioncraftmc.sprawlkt.style.enums.* import kotlin.Unit import kotlin.test.Test public class JustifyContentRowMaxWidthAndMarginTest { @Test public fun justify_content_row_max_width_and_margin(): Unit { val node1 = newNode( io.github.orioncraftmc.sprawlkt.style.Style ( margin = io.github.orioncraftmc.sprawlkt.geometry.Rect( top = StretchDimension.Undefined, bottom = StretchDimension.Undefined, start = StretchDimension.Points(100.0f), end = StretchDimension.Undefined, ), size = io.github.orioncraftmc.sprawlkt.geometry.Size( width = StretchDimension.Points(20.0f), height = StretchDimension.Points(20.0f), ), ), listOf(), ) val rootNode = newNode( io.github.orioncraftmc.sprawlkt.style.Style ( justifyContent = JustifyContent.Center, size = io.github.orioncraftmc.sprawlkt.geometry.Size( width = StretchDimension.Points(100.0f), height = StretchDimension.Auto, ), maxSize = io.github.orioncraftmc.sprawlkt.geometry.Size( width = StretchDimension.Points(80.0f), height = StretchDimension.Auto, ), ), listOf(node1), ) // {"style":{"flexDirection":"row","justifyContent":"center","size":{"width":{"unit":"Points","value":100}},"maxSize":{"width":{"unit":"Points","value":80}}},"layout":{"width":80,"height":20,"x":0,"y":0},"children":[{"style":{"size":{"width":{"unit":"Points","value":20},"height":{"unit":"Points","value":20}},"margin":{"start":{"unit":"Points","value":100}}},"layout":{"width":0,"height":20,"x":90,"y":0},"children":[]}]} Sprawl.computeLayout(rootNode, Size.Companion.undefinedNumber()) kotlin.test.assertEquals(80.0f, Sprawl.layout(rootNode).size.width) kotlin.test.assertEquals(20.0f, Sprawl.layout(rootNode).size.height) kotlin.test.assertEquals(0.0f, Sprawl.layout(rootNode).location.x) kotlin.test.assertEquals(0.0f, Sprawl.layout(rootNode).location.y) kotlin.test.assertEquals(0.0f, Sprawl.layout(node1).size.width) kotlin.test.assertEquals(20.0f, Sprawl.layout(node1).size.height) kotlin.test.assertEquals(90.0f, Sprawl.layout(node1).location.x) kotlin.test.assertEquals(0.0f, Sprawl.layout(node1).location.y) } }
1
Kotlin
0
2
e621000ccb9f5c1351e4c26c997cf93e8dcf4497
2,868
SprawlKt
MIT License
stripe/src/test/java/com/stripe/android/model/CustomerSourceTest.kt
https-brandenburghamanda-gmail-com
334,261,301
false
null
package com.stripe.android.model import com.stripe.android.model.SourceFixtures.CUSTOMER_SOURCE_CARD import com.stripe.android.model.parsers.CustomerSourceJsonParser import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import org.json.JSONException import org.json.JSONObject /** * Test class for [CustomerSource] model class. */ class CustomerSourceTest { @Test fun fromJson_whenCard_createsCustomerSourceData() { val sourceData = requireNotNull(parse(CardFixtures.CARD_USD_JSON)) assertNotNull(sourceData.asCard()) assertEquals("card_189fi32eZvKYlo2CHK8NPRME", sourceData.id) assertNull(sourceData.tokenizationMethod) } @Test fun fromJson_whenCardWithTokenization_createsSourceDataWithTokenization() { val sourceData = requireNotNull(parse(SourceFixtures.APPLE_PAY)) assertNotNull(sourceData.asCard()) assertEquals("card_189fi32eZvKYlo2CHK8NPRME", sourceData.id) assertEquals(TokenizationMethod.ApplePay, sourceData.tokenizationMethod) } @Test fun fromJson_whenSource_createsCustomerSourceData() { assertNotNull(CUSTOMER_SOURCE_CARD.asSource()) assertEquals("src_19t3xKBZqEXluyI4uz2dxAfQ", CUSTOMER_SOURCE_CARD.id) } @Test fun fromExampleJsonSource_toJson_createsSameObject() { assertNotNull(CUSTOMER_SOURCE_CARD) } @Test @Throws(JSONException::class) fun getSourceType_whenCard_returnsCard() { val sourceData = parse(CardFixtures.CARD_USD_JSON) assertNotNull(sourceData) assertEquals(Source.SourceType.CARD, sourceData.sourceType) } @Test fun getSourceType_whenSourceThatIsNotCard_returnsSourceType() { val alipaySource = parse(SourceFixtures.ALIPAY_JSON) assertNotNull(alipaySource) assertEquals(Source.SourceType.ALIPAY, alipaySource.sourceType) } private companion object { private fun parse(jsonObject: JSONObject): CustomerSource? { return CustomerSourceJsonParser().parse(jsonObject) } } }
0
null
0
1
92bbcc76182fc17f6c4b1d8f1a88dc5fae88dffe
2,124
stripe-android
MIT License
app/src/main/java/com/example/noteappcompose/data/source/remote/dataSource/NotesRemoteDataSource.kt
adelayman1
576,742,511
false
null
package com.example.noteappcompose.data.source.remote.dataSource import com.example.noteappcompose.data.source.remote.endPoints.NotesApiService import com.example.noteappcompose.data.source.remote.responseModels.BaseApiResponse import com.example.noteappcompose.data.source.remote.responseModels.NoteResponseModel import io.ktor.client.HttpClient import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.forms.formData import io.ktor.client.request.forms.submitFormWithBinaryData import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.request.post import io.ktor.client.request.url import io.ktor.http.Headers import io.ktor.http.HttpHeaders import io.ktor.http.headersOf import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.MultipartBody import retrofit2.Response import javax.inject.Inject class NotesRemoteDataSource @Inject constructor(var notesApiService: NotesApiService) { suspend fun getAllNotes(): Response<BaseApiResponse<List<NoteResponseModel>>> = withContext(Dispatchers.IO) { notesApiService.getAllNotes() } suspend fun getAllNotesKtor(): Response<BaseApiResponse<List<NoteResponseModel>>> = withContext(Dispatchers.IO) { notesApiService.getAllNotes() } suspend fun updateImage(imageMultiPart : MultipartBody.Part): Response<BaseApiResponse<String>> = withContext(Dispatchers.IO) { notesApiService.uploadImage(imageMultiPart) } suspend fun getNoteDetails(noteId: String): Response<BaseApiResponse<NoteResponseModel>> = withContext(Dispatchers.IO) { notesApiService.getNoteDetails(noteId) } suspend fun searchNotes(searchWord: String): Response<BaseApiResponse<List<NoteResponseModel>>> = withContext(Dispatchers.IO) { notesApiService.searchNotes(searchWord) } }
0
Kotlin
2
10
582e632671b5352b4fd59f9f8c5377513676f749
1,991
ComposeNotesAppRetrofit
MIT License
app/src/main/java/com/stratagile/qlink/ui/activity/defi/DefiRateActivity.kt
qlcchain
115,608,966
false
null
package com.stratagile.qlink.ui.activity.defi import android.animation.ObjectAnimator import android.app.Activity import android.os.Bundle import android.support.v4.view.ViewPager import android.view.View import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.pawegio.kandroid.runDelayedOnUiThread import com.socks.library.KLog import com.stratagile.qlink.R import com.stratagile.qlink.application.AppConfig import com.stratagile.qlink.base.BaseActivity import com.stratagile.qlink.constant.ConstantValue import com.stratagile.qlink.db.Wallet import com.stratagile.qlink.entity.defi.DefiList import com.stratagile.qlink.entity.defi.DefiRating import com.stratagile.qlink.entity.defi.RatingInfo import com.stratagile.qlink.ui.activity.defi.component.DaggerDefiRateComponent import com.stratagile.qlink.ui.activity.defi.contract.DefiRateContract import com.stratagile.qlink.ui.activity.defi.module.DefiRateModule import com.stratagile.qlink.ui.activity.defi.presenter.DefiRatePresenter import com.stratagile.qlink.utils.AccountUtil import com.stratagile.qlink.utils.DefiUtil import com.stratagile.qlink.utils.UIUtils import com.stratagile.qlink.view.DefiPageTransformer import com.stratagile.qlink.view.DefiPagerAdapter import com.stratagile.qlink.view.SweetAlertDialog import com.stratagile.qlink.views.ProgressDrawable import kotlinx.android.synthetic.main.activity_defi_rate.* import java.math.BigDecimal import javax.inject.Inject /** * @author hzp * @Package com.stratagile.qlink.ui.activity.defi * @Description: $description * @date 2020/06/03 14:17:18 */ class DefiRateActivity : BaseActivity(), DefiRateContract.View { @Inject internal lateinit var mPresenter: DefiRatePresenter lateinit var defiEntity: DefiList.ProjectListBean var allAngle = 225 override fun onCreate(savedInstanceState: Bundle?) { mainColor = R.color.white super.onCreate(savedInstanceState) } override fun initView() { setContentView(R.layout.activity_defi_rate) } override fun initData() { title.text = getString(R.string.rate_this_defi) defiEntity = intent.getParcelableExtra("defiEntity") getRatingInfo() if ("".equals(defiEntity.shortName)) { tvName.text = defiEntity.name var resource = resources.getIdentifier(defiEntity.name.toLowerCase().replace(" ", "_").replace("-", "_"), "mipmap", packageName) if (resource == 0) { Glide.with(this) .load(AppConfig.instance.baseUrl + defiEntity.logo) .into(ivAvatar) } else { Glide.with(this) .load(resources.getIdentifier(defiEntity.name.toLowerCase().replace(" ", "_").replace("-", "_"), "mipmap", packageName)) .into(ivAvatar) } } else { tvName.text = defiEntity.shortName var resource = resources.getIdentifier(defiEntity.shortName.toLowerCase().replace(" ", "_").replace("-", "_"), "mipmap", packageName) if (resource == 0) { Glide.with(this) .load(AppConfig.instance.baseUrl + defiEntity.logo) .into(ivAvatar) } else { Glide.with(this) .load(resources.getIdentifier(defiEntity.shortName.toLowerCase().replace(" ", "_").replace("-", "_"), "mipmap", packageName)) .into(ivAvatar) } } tvRating.text = getString(R.string.rating_) + DefiUtil.parseDefiRating(defiEntity.rating.toInt()) var defiPageTransformer = DefiPageTransformer() var defiPagerAdapter = DefiPagerAdapter(this, arrayListOf(0, 1, 2, 3, 4, 5, 6, 7)) viewPager.setAdapter(defiPagerAdapter) // viewPager.setPageMargin(20) viewPager.setOffscreenPageLimit(8)//设置缓存页面数量 viewPager.setPageTransformer(false, defiPageTransformer) viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(p0: Int) { } override fun onPageScrolled(p0: Int, p1: Float, p2: Int) { } override fun onPageSelected(p0: Int) { var seelectText = DefiUtil.parseLocalDefiRating(p0) KLog.i("选中:" + p0) when (p0) { 0, 1, 2 -> { scrollToA() } 3, 4, 5 -> { scrollToB() } 6 -> { scrollToC() } 7 -> { scrollToD() } } } }) defiArrow.postDelayed({ viewPager.setCurrentItem(0) scrollToA() }, 200) segmentControlView.setOnCheckedChangeListener { group, checkedId -> when(checkedId) { R.id.ratinga -> { viewPager.setCurrentItem(0) scrollToA() } R.id.ratingb -> { viewPager.setCurrentItem(3) scrollToB() } R.id.ratingc -> { viewPager.setCurrentItem(6) scrollToC() } R.id.ratingd -> { viewPager.setCurrentItem(7) scrollToD() } } } neoWalletList = AppConfig.instance.daoSession.walletDao.loadAll() getSelfQlc() tvSubmit.setOnClickListener { ratingDefi() } // var items = arrayOf("A++", "A+", "A", "B++", "B+", "B", "C", "D") // wheelView.setDividerConfig(WheelView.DividerConfig().setVisible(false)) // wheelView.setTextSize(30f) // wheelView.setItems(items, 0) // wheelView.setOnItemSelectListener { index -> // KLog.i("选中的为:" + index) // } } var imageDrawable : ProgressDrawable? = null lateinit var neoWalletList : MutableList<Wallet> var overWalletList = arrayListOf<String>() fun getSelfQlc() { if (overWalletList.size == 0) { imageDrawable = ProgressDrawable() imageDrawable!!.start() ivLoad.setImageDrawable(imageDrawable) var map = hashMapOf<String, String>() map["address"] = neoWalletList[0].address mPresenter.getNeoWalletDetail(neoWalletList[0].address, map) } else { var map = hashMapOf<String, String>() map["address"] = neoWalletList[overWalletList.size].address mPresenter.getNeoWalletDetail(neoWalletList[overWalletList.size].address, map) } } override fun setNeoQlcAmount(amount: Double, address: String) { overWalletList.add(address) neoQlcAmount += amount.toFloat() tvNeoChainQlc.text = neoQlcAmount.toString() + " QLC" if (overWalletList.size < neoWalletList.size) { getSelfQlc() } else { KLog.i("开始查qlc链的qlc") getQlcChainQlc() } } var neoQlcAmount = 0.toFloat() var neoQlcOver = false override fun setNeoQLcAmount(amount: Double, over : Boolean) { neoQlcOver = over neoQlcAmount += amount.toFloat() tvNeoChainQlc.text = neoQlcAmount.toString() + " QLC" if (over) { KLog.i("开始查qlc链的qlc") getQlcChainQlc() } } var sweetAlertDialog: SweetAlertDialog? = null fun showWaitDialog() { val view = layoutInflater.inflate(R.layout.layout_wait, null, false) sweetAlertDialog = SweetAlertDialog(this) sweetAlertDialog!!.setView(view) sweetAlertDialog!!.show() } var qlcQlcAmount = 0.toFloat() var qlcQlcOver = false fun getQlcChainQlc() { mPresenter.getQlcChainQlcCount(AppConfig.instance.daoSession.qlcAccountDao.loadAll()) } override fun setQLCQLCAmount(amount: Double, over: Boolean) { qlcQlcOver = over qlcQlcAmount += amount.toFloat() runOnUiThread { tvQlcChainQlc.text = qlcQlcAmount.toBigDecimal().divide(BigDecimal("100000000"), 8, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + " QLC" } if (over) { runOnUiThread { tvSubmit.isEnabled = true imageDrawable!!.stop() ivLoad.visibility = View.GONE setUnRating() } } } fun setUnRating() { if (this::mRatingInfo.isInitialized) { if (mRatingInfo.score == 0) { var weight = (qlcQlcAmount.toBigDecimal().divide(BigDecimal("100000000"), 8, BigDecimal.ROUND_HALF_UP).toFloat() + neoQlcAmount) / ((qlcQlcAmount.toBigDecimal().divide(BigDecimal("100000000"), 8, BigDecimal.ROUND_HALF_UP).toFloat() + neoQlcAmount) + mRatingInfo.qlcAmount.toFloat()) var myAngle = allAngle * weight defiOvalView.setSweepAngle(-myAngle) } } } fun getRatingInfo() { var infoMap = hashMapOf<String, String>() infoMap["projectId"] = defiEntity.id infoMap["account"] = ConstantValue.currentUser.account mPresenter.getRatingInfo(infoMap) } fun scrollToA() { var translationx = ObjectAnimator.ofFloat(defiArrow, "translationX", defiArrow.translationX, UIUtils.dip2px(60f, this).toFloat() - defiArrow.width / 2) translationx.start() ratinga.toggle() } fun scrollToB() { var translationx = ObjectAnimator.ofFloat(defiArrow, "translationX", defiArrow.translationX, UIUtils.dip2px(140f, this).toFloat() - defiArrow.width / 2) translationx.start() ratingb.toggle() } fun scrollToC() { var translationx = ObjectAnimator.ofFloat(defiArrow, "translationX", defiArrow.translationX, UIUtils.dip2px(220f, this).toFloat() - defiArrow.width / 2) translationx.start() ratingc.toggle() } fun ratingDefi() { showWaitDialog() var infoMap = hashMapOf<String, String>() infoMap["account"] = ConstantValue.currentUser.account infoMap["token"] = AccountUtil.getUserToken() infoMap["projectId"] = defiEntity.id infoMap["score"] = DefiUtil.parseViewepagerScore(viewPager.currentItem).toString() infoMap["qlcAmount"] = (qlcQlcAmount.toBigDecimal().divide(BigDecimal("100000000"), 8, BigDecimal.ROUND_HALF_UP).toFloat() + neoQlcAmount).toString() mPresenter.ratingDefi(infoMap) } override fun defiRatingBack(defiRating: DefiRating) { runDelayedOnUiThread(2000, { sweetAlertDialog!!.dismissWithAnimation() getRatingInfo() showRatingSuccessDialog() }) } override fun ratingError() { sweetAlertDialog!!.dismissWithAnimation() } fun showRatingSuccessDialog() { val view = layoutInflater.inflate(R.layout.alert_dialog_tip, null, false) val tvContent = view.findViewById<TextView>(R.id.tvContent) val imageView = view.findViewById<ImageView>(R.id.ivTitle) imageView.setImageDrawable(resources.getDrawable(R.mipmap.op_success)) tvContent.text = getString(R.string.success_you_rating_weight_is_counted) val sweetAlertDialog = SweetAlertDialog(this) sweetAlertDialog.setView(view) sweetAlertDialog.show() tvSubmit.postDelayed(Runnable { sweetAlertDialog.cancel() }, 2000) } fun scrollToD() { var translationx = ObjectAnimator.ofFloat(defiArrow, "translationX", defiArrow.translationX, UIUtils.dip2px(300f, this).toFloat() - defiArrow.width / 2) translationx.start() ratingd.toggle() } override fun setupActivityComponent() { DaggerDefiRateComponent .builder() .appComponent((application as AppConfig).applicationComponent) .defiRateModule(DefiRateModule(this)) .build() .inject(this) } override fun setPresenter(presenter: DefiRateContract.DefiRateContractPresenter) { mPresenter = presenter as DefiRatePresenter } override fun showProgressDialog() { progressDialog.show() } override fun closeProgressDialog() { progressDialog.hide() } lateinit var mRatingInfo: RatingInfo override fun setRatingInfo(ratingInfo: RatingInfo) { mRatingInfo = ratingInfo if (ratingInfo.score == 0) { llShowRating.visibility = View.GONE llOpreateRating.visibility = View.VISIBLE } else { llShowRating.visibility = View.VISIBLE llOpreateRating.visibility = View.GONE var myAngle = allAngle * ratingInfo.weight.toFloat() defiOvalView.setSweepAngle(-myAngle) tvMyRating.text = DefiUtil.parseDefiRating(ratingInfo.score) var fillColor = 0x000000 if (view.text.toString().contains("A")) { fillColor = R.color.color_7ED321 } else if (view.text.toString().contains("B")) { fillColor = R.color.color_108EE9 } else if (view.text.toString().contains("C")) { fillColor = R.color.color_F5A623 } else { fillColor = R.color.color_FF3669 } tvMyRating.setTextColor(resources.getColor(fillColor)) tvMyRatingDesc.text = getString(R.string.my_rating_weight_18, BigDecimal(ratingInfo.weight).multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString()) } } }
1
null
18
46
1c8066e4ebbb53c7401751ea3887a6315ccbe5eb
13,856
QWallet-Android
MIT License
app/src/main/java/com/stratagile/qlink/ui/activity/defi/DefiRateActivity.kt
qlcchain
115,608,966
false
null
package com.stratagile.qlink.ui.activity.defi import android.animation.ObjectAnimator import android.app.Activity import android.os.Bundle import android.support.v4.view.ViewPager import android.view.View import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.pawegio.kandroid.runDelayedOnUiThread import com.socks.library.KLog import com.stratagile.qlink.R import com.stratagile.qlink.application.AppConfig import com.stratagile.qlink.base.BaseActivity import com.stratagile.qlink.constant.ConstantValue import com.stratagile.qlink.db.Wallet import com.stratagile.qlink.entity.defi.DefiList import com.stratagile.qlink.entity.defi.DefiRating import com.stratagile.qlink.entity.defi.RatingInfo import com.stratagile.qlink.ui.activity.defi.component.DaggerDefiRateComponent import com.stratagile.qlink.ui.activity.defi.contract.DefiRateContract import com.stratagile.qlink.ui.activity.defi.module.DefiRateModule import com.stratagile.qlink.ui.activity.defi.presenter.DefiRatePresenter import com.stratagile.qlink.utils.AccountUtil import com.stratagile.qlink.utils.DefiUtil import com.stratagile.qlink.utils.UIUtils import com.stratagile.qlink.view.DefiPageTransformer import com.stratagile.qlink.view.DefiPagerAdapter import com.stratagile.qlink.view.SweetAlertDialog import com.stratagile.qlink.views.ProgressDrawable import kotlinx.android.synthetic.main.activity_defi_rate.* import java.math.BigDecimal import javax.inject.Inject /** * @author hzp * @Package com.stratagile.qlink.ui.activity.defi * @Description: $description * @date 2020/06/03 14:17:18 */ class DefiRateActivity : BaseActivity(), DefiRateContract.View { @Inject internal lateinit var mPresenter: DefiRatePresenter lateinit var defiEntity: DefiList.ProjectListBean var allAngle = 225 override fun onCreate(savedInstanceState: Bundle?) { mainColor = R.color.white super.onCreate(savedInstanceState) } override fun initView() { setContentView(R.layout.activity_defi_rate) } override fun initData() { title.text = getString(R.string.rate_this_defi) defiEntity = intent.getParcelableExtra("defiEntity") getRatingInfo() if ("".equals(defiEntity.shortName)) { tvName.text = defiEntity.name var resource = resources.getIdentifier(defiEntity.name.toLowerCase().replace(" ", "_").replace("-", "_"), "mipmap", packageName) if (resource == 0) { Glide.with(this) .load(AppConfig.instance.baseUrl + defiEntity.logo) .into(ivAvatar) } else { Glide.with(this) .load(resources.getIdentifier(defiEntity.name.toLowerCase().replace(" ", "_").replace("-", "_"), "mipmap", packageName)) .into(ivAvatar) } } else { tvName.text = defiEntity.shortName var resource = resources.getIdentifier(defiEntity.shortName.toLowerCase().replace(" ", "_").replace("-", "_"), "mipmap", packageName) if (resource == 0) { Glide.with(this) .load(AppConfig.instance.baseUrl + defiEntity.logo) .into(ivAvatar) } else { Glide.with(this) .load(resources.getIdentifier(defiEntity.shortName.toLowerCase().replace(" ", "_").replace("-", "_"), "mipmap", packageName)) .into(ivAvatar) } } tvRating.text = getString(R.string.rating_) + DefiUtil.parseDefiRating(defiEntity.rating.toInt()) var defiPageTransformer = DefiPageTransformer() var defiPagerAdapter = DefiPagerAdapter(this, arrayListOf(0, 1, 2, 3, 4, 5, 6, 7)) viewPager.setAdapter(defiPagerAdapter) // viewPager.setPageMargin(20) viewPager.setOffscreenPageLimit(8)//设置缓存页面数量 viewPager.setPageTransformer(false, defiPageTransformer) viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(p0: Int) { } override fun onPageScrolled(p0: Int, p1: Float, p2: Int) { } override fun onPageSelected(p0: Int) { var seelectText = DefiUtil.parseLocalDefiRating(p0) KLog.i("选中:" + p0) when (p0) { 0, 1, 2 -> { scrollToA() } 3, 4, 5 -> { scrollToB() } 6 -> { scrollToC() } 7 -> { scrollToD() } } } }) defiArrow.postDelayed({ viewPager.setCurrentItem(0) scrollToA() }, 200) segmentControlView.setOnCheckedChangeListener { group, checkedId -> when(checkedId) { R.id.ratinga -> { viewPager.setCurrentItem(0) scrollToA() } R.id.ratingb -> { viewPager.setCurrentItem(3) scrollToB() } R.id.ratingc -> { viewPager.setCurrentItem(6) scrollToC() } R.id.ratingd -> { viewPager.setCurrentItem(7) scrollToD() } } } neoWalletList = AppConfig.instance.daoSession.walletDao.loadAll() getSelfQlc() tvSubmit.setOnClickListener { ratingDefi() } // var items = arrayOf("A++", "A+", "A", "B++", "B+", "B", "C", "D") // wheelView.setDividerConfig(WheelView.DividerConfig().setVisible(false)) // wheelView.setTextSize(30f) // wheelView.setItems(items, 0) // wheelView.setOnItemSelectListener { index -> // KLog.i("选中的为:" + index) // } } var imageDrawable : ProgressDrawable? = null lateinit var neoWalletList : MutableList<Wallet> var overWalletList = arrayListOf<String>() fun getSelfQlc() { if (overWalletList.size == 0) { imageDrawable = ProgressDrawable() imageDrawable!!.start() ivLoad.setImageDrawable(imageDrawable) var map = hashMapOf<String, String>() map["address"] = neoWalletList[0].address mPresenter.getNeoWalletDetail(neoWalletList[0].address, map) } else { var map = hashMapOf<String, String>() map["address"] = neoWalletList[overWalletList.size].address mPresenter.getNeoWalletDetail(neoWalletList[overWalletList.size].address, map) } } override fun setNeoQlcAmount(amount: Double, address: String) { overWalletList.add(address) neoQlcAmount += amount.toFloat() tvNeoChainQlc.text = neoQlcAmount.toString() + " QLC" if (overWalletList.size < neoWalletList.size) { getSelfQlc() } else { KLog.i("开始查qlc链的qlc") getQlcChainQlc() } } var neoQlcAmount = 0.toFloat() var neoQlcOver = false override fun setNeoQLcAmount(amount: Double, over : Boolean) { neoQlcOver = over neoQlcAmount += amount.toFloat() tvNeoChainQlc.text = neoQlcAmount.toString() + " QLC" if (over) { KLog.i("开始查qlc链的qlc") getQlcChainQlc() } } var sweetAlertDialog: SweetAlertDialog? = null fun showWaitDialog() { val view = layoutInflater.inflate(R.layout.layout_wait, null, false) sweetAlertDialog = SweetAlertDialog(this) sweetAlertDialog!!.setView(view) sweetAlertDialog!!.show() } var qlcQlcAmount = 0.toFloat() var qlcQlcOver = false fun getQlcChainQlc() { mPresenter.getQlcChainQlcCount(AppConfig.instance.daoSession.qlcAccountDao.loadAll()) } override fun setQLCQLCAmount(amount: Double, over: Boolean) { qlcQlcOver = over qlcQlcAmount += amount.toFloat() runOnUiThread { tvQlcChainQlc.text = qlcQlcAmount.toBigDecimal().divide(BigDecimal("100000000"), 8, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + " QLC" } if (over) { runOnUiThread { tvSubmit.isEnabled = true imageDrawable!!.stop() ivLoad.visibility = View.GONE setUnRating() } } } fun setUnRating() { if (this::mRatingInfo.isInitialized) { if (mRatingInfo.score == 0) { var weight = (qlcQlcAmount.toBigDecimal().divide(BigDecimal("100000000"), 8, BigDecimal.ROUND_HALF_UP).toFloat() + neoQlcAmount) / ((qlcQlcAmount.toBigDecimal().divide(BigDecimal("100000000"), 8, BigDecimal.ROUND_HALF_UP).toFloat() + neoQlcAmount) + mRatingInfo.qlcAmount.toFloat()) var myAngle = allAngle * weight defiOvalView.setSweepAngle(-myAngle) } } } fun getRatingInfo() { var infoMap = hashMapOf<String, String>() infoMap["projectId"] = defiEntity.id infoMap["account"] = ConstantValue.currentUser.account mPresenter.getRatingInfo(infoMap) } fun scrollToA() { var translationx = ObjectAnimator.ofFloat(defiArrow, "translationX", defiArrow.translationX, UIUtils.dip2px(60f, this).toFloat() - defiArrow.width / 2) translationx.start() ratinga.toggle() } fun scrollToB() { var translationx = ObjectAnimator.ofFloat(defiArrow, "translationX", defiArrow.translationX, UIUtils.dip2px(140f, this).toFloat() - defiArrow.width / 2) translationx.start() ratingb.toggle() } fun scrollToC() { var translationx = ObjectAnimator.ofFloat(defiArrow, "translationX", defiArrow.translationX, UIUtils.dip2px(220f, this).toFloat() - defiArrow.width / 2) translationx.start() ratingc.toggle() } fun ratingDefi() { showWaitDialog() var infoMap = hashMapOf<String, String>() infoMap["account"] = ConstantValue.currentUser.account infoMap["token"] = AccountUtil.getUserToken() infoMap["projectId"] = defiEntity.id infoMap["score"] = DefiUtil.parseViewepagerScore(viewPager.currentItem).toString() infoMap["qlcAmount"] = (qlcQlcAmount.toBigDecimal().divide(BigDecimal("100000000"), 8, BigDecimal.ROUND_HALF_UP).toFloat() + neoQlcAmount).toString() mPresenter.ratingDefi(infoMap) } override fun defiRatingBack(defiRating: DefiRating) { runDelayedOnUiThread(2000, { sweetAlertDialog!!.dismissWithAnimation() getRatingInfo() showRatingSuccessDialog() }) } override fun ratingError() { sweetAlertDialog!!.dismissWithAnimation() } fun showRatingSuccessDialog() { val view = layoutInflater.inflate(R.layout.alert_dialog_tip, null, false) val tvContent = view.findViewById<TextView>(R.id.tvContent) val imageView = view.findViewById<ImageView>(R.id.ivTitle) imageView.setImageDrawable(resources.getDrawable(R.mipmap.op_success)) tvContent.text = getString(R.string.success_you_rating_weight_is_counted) val sweetAlertDialog = SweetAlertDialog(this) sweetAlertDialog.setView(view) sweetAlertDialog.show() tvSubmit.postDelayed(Runnable { sweetAlertDialog.cancel() }, 2000) } fun scrollToD() { var translationx = ObjectAnimator.ofFloat(defiArrow, "translationX", defiArrow.translationX, UIUtils.dip2px(300f, this).toFloat() - defiArrow.width / 2) translationx.start() ratingd.toggle() } override fun setupActivityComponent() { DaggerDefiRateComponent .builder() .appComponent((application as AppConfig).applicationComponent) .defiRateModule(DefiRateModule(this)) .build() .inject(this) } override fun setPresenter(presenter: DefiRateContract.DefiRateContractPresenter) { mPresenter = presenter as DefiRatePresenter } override fun showProgressDialog() { progressDialog.show() } override fun closeProgressDialog() { progressDialog.hide() } lateinit var mRatingInfo: RatingInfo override fun setRatingInfo(ratingInfo: RatingInfo) { mRatingInfo = ratingInfo if (ratingInfo.score == 0) { llShowRating.visibility = View.GONE llOpreateRating.visibility = View.VISIBLE } else { llShowRating.visibility = View.VISIBLE llOpreateRating.visibility = View.GONE var myAngle = allAngle * ratingInfo.weight.toFloat() defiOvalView.setSweepAngle(-myAngle) tvMyRating.text = DefiUtil.parseDefiRating(ratingInfo.score) var fillColor = 0x000000 if (view.text.toString().contains("A")) { fillColor = R.color.color_7ED321 } else if (view.text.toString().contains("B")) { fillColor = R.color.color_108EE9 } else if (view.text.toString().contains("C")) { fillColor = R.color.color_F5A623 } else { fillColor = R.color.color_FF3669 } tvMyRating.setTextColor(resources.getColor(fillColor)) tvMyRatingDesc.text = getString(R.string.my_rating_weight_18, BigDecimal(ratingInfo.weight).multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString()) } } }
1
null
18
46
1c8066e4ebbb53c7401751ea3887a6315ccbe5eb
13,856
QWallet-Android
MIT License
buildSrc/src/main/java/com/google/firebase/gradle/plugins/DackkaPlugin.kt
firebase
146,941,185
false
null
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.gradle.plugins import com.android.build.api.attributes.BuildTypeAttr import com.android.build.gradle.LibraryExtension import java.io.File import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.provider.Provider import org.gradle.api.tasks.Copy import org.gradle.api.tasks.Delete import org.gradle.api.tasks.TaskProvider import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.named import org.gradle.kotlin.dsl.register /** * # Dackka Plugin * * The Dackka Plugin is a wrapper around internal tooling at Google called Dackka, which generates * documentation for [Firesite](https://firebase.google.com/docs/reference) * * ## Dackka * * Dackka is an internal-purposed Dokka plugin. Google hosts its documentation on an internal * service called **Devsite**. Firebase hosts their documentation on a variant of Devsite called * **Firesite**. You can click [here](https://firebase.google.com/docs/reference) to see how that * looks. Essentially, it's just Google's way of decorating (and organizing) documentation. * * Devsite expects its files to be in a very specific format. Previously, we would use an internal * Javadoc doclet called [Doclava](https://code.google.com/archive/p/doclava/), which allowed us to * provide sensible defaults as to how the Javadoc should be rendered. Then, we would do some * further transformations to get the Javadoc output in-line with what Devsite expects. This was a * lengthy process, and came with a lot of overhead. Furthermore, Doclava does not support kotlindoc * and has been unmaintained for many years. * * Dackka is an internal solution to that. Dackka provides a devsite plugin for Dokka that will * handle the job of doclava. Not only does this mean we can cut out a huge portion of our * transformation systems- but the overhead for maintaining such systems is deferred away to the * AndroidX team (the maintainers of Dackka). * * ## Dackka Usage * * The Dackka we use is a fat jar pulled periodically from Dackka nightly builds, and moved to our * own maven repo bucket. Since it's recommended from the AndroidX team to run Dackka on the command * line, the fat jar allows us to ignore all the miscenalionous dependencies of Dackka (in regards * to Dokka especially). * * The general process of using Dackka is that you collect the dependencies and source sets of the * gradle project, create a * [Dokka appropriate JSON file](https://kotlin.github.io/dokka/1.7.10/user_guide/cli/usage/#example-using-json) * , run the Dackka fat jar with the JSON file as an argument, and publish the output folder. * * ## Implementation * * Our implementation of Dackka falls into three separate files, and two separate tasks. * * ### [GenerateDocumentationTask] * * This task is the meat of our Dackka implementation. It's what actually handles the running of * Dackka itself. The task exposes a gradle extension called [GenerateDocumentationTaskExtension] * with various configuration points for Dackka. This will likely be expanded upon in the future, as * configurations are needed. * * The job of this task is to **just** run Dackka. What happens after-the-fact does not matter to * this task. It will take the provided inputs, organize them into the expected JSON file, and run * Dackka with the JSON file as an argument. * * ### [FiresiteTransformTask] * * Dackka was designed with Devsite in mind. The problem though, is that we use Firesite. Firesite * is very similar to Devsite, but there *are* minor differences. * * The job of this task is to transform the Dackka output from a Devsite purposed format, to a * Firesite purposed format. This includes removing unnecessary files and headers, fixing links, and * so forth. * * There are open bugs for each transformation, as in an ideal world- they are instead exposed as * configurations from Dackka. Should these configurations be adopted by Dackka, this task could * become unnecessary itself- as we could just configure the task during generation. * * ### DackkaPlugin * * This plugin is the mind of our Dackka implementation. It manages registering, and configuring all * the tasks for Dackka (that is, the already established tasks above). While we do not currently * offer any configuration for the Dackka plugin, this could change in the future as needed. * Currently, the DackkaPlugin provides sensible defaults to output directories, package lists, and * so forth. * * The DackkaPlugin also provides two extra tasks: [cleanDackkaDocumentation] * [registerCleanDackkaDocumentation] and [copyDocsToCommonDirectory] * [registerCopyDocsToCommonDirectoryTask]. * * _cleanDackkaDocumentation_ is exactly what it sounds like, a task to clean up (delete) the output * of Dackka. This is useful when testing Dackka outputs itself- and shouldn't be apart of the * normal flow. The reasoning is that it would otherwise invalidate the gradle cache. * * _copyDocsToCommonDirectory_ copies the transformed Dackka output, and pastes it in a common * directory under the root project's build directory. This makes it easier to zip the doc files for * staging. */ abstract class DackkaPlugin : Plugin<Project> { override fun apply(project: Project) { prepareJavadocConfiguration(project) registerCleanDackkaDocumentation(project) val kotlinDoc = registerKotlinDocTask(project) // TODO(b/270576405): remove afterEvalutate after fixed project.afterEvaluate { if (weShouldPublish(this)) { val dackkaOutputDirectory = provider { fileFromBuildDir("dackkaRawOutput") } val transformedFilesDirectory = provider { fileFromBuildDir("dackkaTransformedFiles") } val generateDocumentation = registerGenerateDackkaDocumentationTask(project, dackkaOutputDirectory) val firesiteTransform = registerFiresiteTransformTask(project, dackkaOutputDirectory, transformedFilesDirectory) val copyDocsToCommonDirectory = registerCopyDocsToCommonDirectoryTask(project, transformedFilesDirectory) kotlinDoc.configure { dependsOn(generateDocumentation, firesiteTransform, copyDocsToCommonDirectory) outputs.dir(copyDocsToCommonDirectory.map { it.destinationDir }) } } } } private fun registerKotlinDocTask(project: Project) = project.tasks.register("kotlindoc") { group = "documentation" } /** * Checks if the [Project] has opted in to releasing their documentation. * * This is done via the [FirebaseLibraryExtension.publishJavadoc] property. */ private fun weShouldPublish(project: Project) = project.firebaseLibrary.publishJavadoc /** * Applies common configuration to the [javadocConfig], that is otherwise not present. * * @see javadocConfig */ private fun prepareJavadocConfiguration(project: Project) { project.javadocConfig.apply { dependencies += project.dependencies.create("com.google.code.findbugs:jsr305:3.0.2") dependencies += project.dependencies.create("com.google.errorprone:error_prone_annotations:2.15.0") attributes.attribute(BuildTypeAttr.ATTRIBUTE, project.objects.named("release")) } } private fun registerGenerateDackkaDocumentationTask( project: Project, targetDirectory: Provider<File>, ): TaskProvider<GenerateDocumentationTask> = project.tasks.register<GenerateDocumentationTask>("generateDackkaDocumentation") { with(project.extensions.getByType<LibraryExtension>()) { libraryVariants.all { if (name == "release") { val classpath = compileConfiguration.jars + project.javadocConfig.jars + project.files(bootClasspath) val sourceDirectories = sourceSets.flatMap { it.javaDirectories } + sourceSets.flatMap { it.kotlinDirectories } sources.set(sourceDirectories) dependencies.set(classpath) outputDirectory.set(targetDirectory) suppressedFiles.set(emptyList()) packageListFiles.set(fetchPackageLists(project)) applyCommonConfigurations() } } } } private fun fetchPackageLists(project: Project) = project.rootProject .fileTree("kotlindoc/package-lists") .matching { include("**/package-list") } .toList() private fun GenerateDocumentationTask.applyCommonConfigurations() { dependsOnAndMustRunAfter("createFullJarRelease") val dackkaFile = project.provider { project.dackkaConfig.singleFile } dackkaJarFile.set(dackkaFile) clientName.set(project.firebaseLibrary.artifactId) } private fun registerFiresiteTransformTask( project: Project, dackkaOutputDirectory: Provider<File>, targetDirectory: Provider<File> ) = project.tasks.register<FiresiteTransformTask>("firesiteTransform") { dependsOnAndMustRunAfter("generateDackkaDocumentation") dackkaFiles.set(dackkaOutputDirectory.childFile("docs/reference")) outputDirectory.set(targetDirectory) } private fun registerCopyDocsToCommonDirectoryTask( project: Project, transformedFilesDirectory: Provider<File>, ) = project.tasks.register<Copy>("copyDocsToCommonDirectory") { mustRunAfter("firesiteTransform") from(transformedFilesDirectory) into(project.rootProject.fileFromBuildDir("firebase-kotlindoc")) } /** * Useful for local testing, but may not be desired for standard use. * * As such, this task has to be ran explicitly- it won't be invoked otherwise. */ private fun registerCleanDackkaDocumentation(project: Project) = project.tasks.register<Delete>("cleanDackkaDocumentation") { group = "cleanup" val outputDirs = listOf("dackkaRawOutput", "dackkaTransformedFiles") delete(outputDirs.map { project.fileFromBuildDir(it) }) delete(project.rootProject.fileFromBuildDir("firebase-kotlindoc")) } }
442
null
575
2,270
0697dd3aadd6c13d9e2d321c75173992bfbaac3b
10,598
firebase-android-sdk
Apache License 2.0
plugins/uast-kotlin/testData/Declarations.kt
cypressious
52,316,479
true
{"Java": 17992465, "Kotlin": 15424948, "JavaScript": 177557, "Protocol Buffer": 44176, "HTML": 38996, "Lex": 17538, "ANTLR": 9689, "CSS": 9358, "Groovy": 7541, "IDL": 5313, "Shell": 4704, "Batchfile": 3703}
class Declarations { val a: String = "a" var b: String get() = "A" set(v) { println(v) } val c: String class NestedClass { val b: String = "b" } inner class InnerClass { val c: CharSequence = a } companion object { val CONST_VAL = 1 } companion object A { fun b(): Boolean = true } fun func(a: Int, b: String): Int { return (a + 1) * b.length } }
0
Java
0
1
0e0cbfd89bee55f51c09f77f84759ed2269a0778
458
kotlin
Apache License 2.0
compiler/testData/diagnostics/tests/regressions/SpecififcityByReceiver.kt
chirino
3,596,099
true
null
fun Any.equals(<!UNUSED_PARAMETER!>other<!> : Any?) : Boolean = true fun main(args: Array<String>) { val command : Any = 1 command<!UNNECESSARY_SAFE_CALL!>?.<!>equals(null) command.equals(null) }
0
Java
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
211
kotlin
Apache License 2.0
SERVER/src/main/kotlin/com/konix/data/dto/response/CompaniesMetadataResponseDTO.kt
singhtwenty2
809,094,089
false
{"Kotlin": 369846, "Dockerfile": 414}
package com.konix.data.dto.response import kotlinx.serialization.Serializable @Serializable data class CompaniesMetadataResponseDTO( val id: Int, val name: String, val symbol: String, val marketCap: Double )
0
Kotlin
0
1
b744b0797548d2c1dbec21ba684b4691471dbfc4
226
konix-TEP
MIT License
profilers/src/com/android/tools/profilers/perfetto/traceprocessor/TraceProcessorModel.kt
phpc0de
470,555,455
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.profilers.perfetto.traceprocessor import com.android.tools.profiler.perfetto.proto.TraceProcessor import com.android.tools.profiler.proto.Cpu import com.android.tools.profilers.cpu.ThreadState import com.android.tools.profilers.cpu.systemtrace.CounterModel import com.android.tools.profilers.cpu.systemtrace.CpuCoreModel import com.android.tools.profilers.cpu.systemtrace.ProcessModel import com.android.tools.profilers.cpu.systemtrace.SchedulingEventModel import com.android.tools.profilers.cpu.systemtrace.SystemTraceModelAdapter import com.android.tools.profilers.cpu.systemtrace.ThreadModel import com.android.tools.profilers.cpu.systemtrace.TraceEventModel import java.io.Serializable import java.util.Deque import java.util.LinkedList import java.util.concurrent.TimeUnit class TraceProcessorModel(builder: Builder) : SystemTraceModelAdapter, Serializable { companion object { // generated by serialver @JvmStatic val serialVersionUID = -2228053132990163476L } private val processMap: Map<Int, ProcessModel> private val cpuCores: List<CpuCoreModel> private val androidFrameLayers: List<TraceProcessor.AndroidFrameEventsResult.Layer> private val danglingThreads = builder.danglingThreads private val startCaptureTimestamp = builder.startCaptureTimestamp private val endCaptureTimestamp = builder.endCaptureTimestamp init { // Build processMap val processMapBuilder = mutableMapOf<Int, ProcessModel>() for (process in builder.processById.values) { val updatedThreadMap = process.threadById.mapValues { entry -> entry.value.copy( traceEvents = builder.threadToEventsMap.getOrDefault(entry.key, listOf()), schedulingEvents = builder.threadToScheduling.getOrDefault(entry.key, listOf()) ) }.toSortedMap() val counterMap = builder.processToCounters.getOrDefault(process.id, listOf()) .map { it.name to it } .toMap() processMapBuilder[process.id] = process.copy(threadById = updatedThreadMap, counterByName = counterMap) } processMap = processMapBuilder.toSortedMap() // Build cpuCores cpuCores = (0 until builder.cpuCoresCount).map { val cpuCountersMap = builder.coreToCpuCounters.getOrDefault(it, listOf()) .map { counterModel -> counterModel.name to counterModel } .toMap() CpuCoreModel(it, builder.coreToScheduling.getOrDefault(it, listOf()), cpuCountersMap) } androidFrameLayers = builder.androidFrameLayers } override fun getCaptureStartTimestampUs() = startCaptureTimestamp override fun getCaptureEndTimestampUs() = endCaptureTimestamp override fun getProcessById(id: Int) = processMap[id] override fun getProcesses() = processMap.values.toList() override fun getDanglingThread(tid: Int): ThreadModel? = danglingThreads[tid] override fun getCpuCores() = cpuCores override fun getSystemTraceTechnology() = Cpu.CpuTraceType.PERFETTO // TODO(b/156578844): Fetch data from TraceProcessor error table to populate this. override fun isCapturePossibleCorrupted() = false override fun getAndroidFrameLayers() = androidFrameLayers class Builder { internal var startCaptureTimestamp = Long.MAX_VALUE internal var endCaptureTimestamp = Long.MIN_VALUE internal var cpuCoresCount = 0 internal val processById = mutableMapOf<Int, ProcessModel>() internal val danglingThreads = mutableMapOf<Int, ThreadModel>() internal val threadToEventsMap = mutableMapOf<Int, List<TraceEventModel>>() internal val threadToScheduling = mutableMapOf<Int, List<SchedulingEventModel>>() internal val coreToScheduling = mutableMapOf<Int, List<SchedulingEventModel>>() internal val coreToCpuCounters = mutableMapOf<Int, List<CounterModel>>() internal val processToCounters = mutableMapOf<Int, List<CounterModel>>() internal val androidFrameLayers = mutableListOf<TraceProcessor.AndroidFrameEventsResult.Layer>() fun addProcessMetadata(processMetadataResult: TraceProcessor.ProcessMetadataResult) { for (process in processMetadataResult.processList) { processById[process.id.toInt()] = ProcessModel( process.id.toInt(), process.name, process.threadList.map { t -> t.id.toInt() to ThreadModel(t.id.toInt(), process.id.toInt(), t.name, listOf(), listOf()) } .toMap().toSortedMap(), mapOf()) } for (thread in processMetadataResult.danglingThreadList) { danglingThreads[thread.id.toInt()] = ThreadModel(thread.id.toInt(), 0, thread.name, emptyList(), emptyList()) } } fun addTraceEvents(traceEventsResult: TraceProcessor.TraceEventsResult) { for (thread in traceEventsResult.threadList) { val rootIds = mutableSetOf<Long>() val eventToChildrenIds = mutableMapOf<Long, MutableList<Long>>() val eventPerId = mutableMapOf<Long, TraceEventModel>() for (event in thread.traceEventList) { if (event.depth > 0) { eventToChildrenIds.getOrPut(event.parentId) { mutableListOf() }.add(event.id) } else { rootIds.add(event.id) } val startTimestampUs = convertToUs(event.timestampNanoseconds) val durationTimestampUs = convertToUs(event.durationNanoseconds) val endTimestampUs = startTimestampUs + durationTimestampUs eventPerId[event.id] = TraceEventModel(event.name, startTimestampUs, endTimestampUs, durationTimestampUs, listOf()) } val reconstructedTree = reconstructTraceTree(rootIds, eventToChildrenIds, eventPerId) threadToEventsMap[thread.threadId.toInt()] = rootIds.mapNotNull { reconstructedTree[it] } } } // Runs through the partially computed events to rebuild the whole trace trees, by doing a DFS from the root nodes. private fun reconstructTraceTree( rootIds: Set<Long>, eventToChildrenIds: Map<Long, List<Long>>, eventPerId: Map<Long, TraceEventModel>): Map<Long, TraceEventModel> { val reconstructedEventsPerId = mutableMapOf<Long, TraceEventModel>() val visitedAllChildren = mutableSetOf<Long>() val eventIdStack: Deque<Long> = LinkedList(rootIds) while (eventIdStack.isNotEmpty()) { val eventId = eventIdStack.first // If we have not visited this node yet, then we need to push all its children to the front of the queue // and continue the main loop. Next time we pass on this one, we will process it as we know all its children // have been processed already. if (!visitedAllChildren.contains(eventId)) { eventToChildrenIds.getOrDefault(eventId, mutableListOf()).forEach { eventIdStack.addFirst(it) } visitedAllChildren.add(eventId) continue } eventIdStack.removeFirst() val children = eventToChildrenIds.getOrDefault(eventId, mutableListOf()) .map { reconstructedEventsPerId[it] ?: error("Children should have been computed already") } .sortedBy { it.startTimestampUs } val event = eventPerId[eventId] ?: error("Trace Event should be present in the map") val myStart = event.startTimestampUs val maxEndTs = children.lastOrNull()?.endTimestampUs ?: 0L val myCpuTime = event.cpuTimeUs val updatedEvent = event.copy( // Our end time is either the end of our last children or our start + how much time we took. endTimestampUs = maxOf(myStart + myCpuTime, maxEndTs), childrenEvents = children) reconstructedEventsPerId[eventId] = updatedEvent // Update the global start/end of the capture. startCaptureTimestamp = minOf(startCaptureTimestamp, updatedEvent.startTimestampUs) endCaptureTimestamp = maxOf(endCaptureTimestamp, updatedEvent.endTimestampUs) } return reconstructedEventsPerId } fun addSchedulingEvents(schedEvents: TraceProcessor.SchedulingEventsResult) { cpuCoresCount = maxOf(cpuCoresCount, schedEvents.numCores) val perThreadScheduling = mutableMapOf<Int, MutableList<SchedulingEventModel>>() val perCoreScheduling = mutableMapOf<Int, MutableList<SchedulingEventModel>>() for (event in schedEvents.schedEventList) { val startTimestampUs = convertToUs(event.timestampNanoseconds) val durationTimestampUs = convertToUs(event.durationNanoseconds) val endTimestampUs = startTimestampUs + durationTimestampUs startCaptureTimestamp = minOf(startCaptureTimestamp, startTimestampUs) endCaptureTimestamp = maxOf(endCaptureTimestamp, endTimestampUs) val schedEvent = SchedulingEventModel(convertSchedulingState(event.state), startTimestampUs, endTimestampUs, durationTimestampUs, durationTimestampUs, event.processId.toInt(), event.threadId.toInt(), event.cpu) perThreadScheduling.getOrPut(event.threadId.toInt()) { mutableListOf() }.add(schedEvent) perCoreScheduling.getOrPut(event.cpu) { mutableListOf() }.add(schedEvent) } perThreadScheduling.forEach { val previousList = threadToScheduling[it.key] ?: listOf() threadToScheduling[it.key] = previousList.plus(it.value).sortedBy { s -> s.startTimestampUs } } perCoreScheduling.forEach { val previousList = coreToScheduling[it.key] ?: listOf() coreToScheduling[it.key] = previousList.plus(it.value).sortedBy { s -> s.startTimestampUs } } } private fun convertSchedulingState(state: TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState): ThreadState { return when (state) { TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.RUNNING -> ThreadState.RUNNING_CAPTURED TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.RUNNING_FOREGROUND -> ThreadState.RUNNING_CAPTURED TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.DEAD -> ThreadState.DEAD_CAPTURED TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.SLEEPING -> ThreadState.SLEEPING_CAPTURED TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.SLEEPING_UNINTERRUPTIBLE -> ThreadState.WAITING_CAPTURED else -> ThreadState.UNKNOWN } } fun addCpuCounters(result: TraceProcessor.CpuCoreCountersResult) { cpuCoresCount = maxOf(cpuCoresCount, result.numCores) result.countersPerCoreList.forEach { countersPerCore -> coreToCpuCounters[countersPerCore.cpu] = countersPerCore.counterList.map { counter -> CounterModel(counter.name, counter.valueList.map { convertToUs(it.timestampNanoseconds) to it.value } .toMap().toSortedMap()) } } } fun addProcessCounters(counters: TraceProcessor.ProcessCountersResult) { processToCounters[counters.processId.toInt()] = counters.counterList.map { counter -> CounterModel(counter.name, counter.valueList.map { convertToUs(it.timestampNanoseconds) to it.value } .toMap().toSortedMap()) } } fun addAndroidFrameEvents(frameEventsResult: TraceProcessor.AndroidFrameEventsResult) { androidFrameLayers.addAll(frameEventsResult.layerList) } fun build(): TraceProcessorModel { return TraceProcessorModel(this) } private fun convertToUs(tsNanos: Long) = TimeUnit.NANOSECONDS.toMicros(tsNanos) } }
0
null
1
1
79e20f027ca1d047b91aa7acd92fb71fa2968a09
12,629
idea-android
Apache License 2.0
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/ViewLayer.android.kt
JetBrains
351,708,598
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import android.annotation.SuppressLint import android.os.Build import android.view.View import android.view.ViewOutlineProvider import androidx.annotation.RequiresApi import androidx.compose.ui.geometry.MutableRect import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.CanvasHolder import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.Fields import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.RenderEffect import androidx.compose.ui.graphics.ReusableGraphicsLayerScope import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.layer.GraphicsLayer import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.layout.GraphicLayerInfo import androidx.compose.ui.node.OwnedLayer import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import java.lang.reflect.Field import java.lang.reflect.Method /** View implementation of OwnedLayer. */ internal class ViewLayer( val ownerView: AndroidComposeView, val container: DrawChildContainer, drawBlock: (canvas: Canvas, parentLayer: GraphicsLayer?) -> Unit, invalidateParentLayer: () -> Unit ) : View(ownerView.context), OwnedLayer, GraphicLayerInfo { private var drawBlock: ((canvas: Canvas, parentLayer: GraphicsLayer?) -> Unit)? = drawBlock private var invalidateParentLayer: (() -> Unit)? = invalidateParentLayer private val outlineResolver = OutlineResolver() // Value of the layerModifier's clipToBounds property private var clipToBounds = false private var clipBoundsCache: android.graphics.Rect? = null private val manualClipPath: Path? get() = if (!clipToOutline || outlineResolver.outlineClipSupported) { null } else { outlineResolver.clipPath } var isInvalidated = false private set(value) { if (value != field) { field = value ownerView.notifyLayerIsDirty(this, value) } } private var drawnWithZ = false private val canvasHolder = CanvasHolder() private val matrixCache = LayerMatrixCache(getMatrix) override val underlyingMatrix: Matrix get() = matrixCache.calculateMatrix(this) /** * Local copy of the transform origin as GraphicsLayerModifier can be implemented as a model * object. Update this field within [updateLayerProperties] and use it in [resize] or other * methods */ private var mTransformOrigin: TransformOrigin = TransformOrigin.Center private var mHasOverlappingRendering = true init { setWillNotDraw(false) // we WILL draw container.addView(this) } override val layerId: Long = generateViewId().toLong() override val ownerViewId: Long get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { UniqueDrawingIdApi29.getUniqueDrawingId(ownerView) } else { -1 } @RequiresApi(29) private object UniqueDrawingIdApi29 { @JvmStatic fun getUniqueDrawingId(view: View) = view.uniqueDrawingId } /** * Configure the camera distance on the View in pixels. View already has a get/setCameraDistance * API however, that operates in Dp values. */ var cameraDistancePx: Float get() { // View internally converts distance to dp so divide by density here to have // consistent usage of pixels with RenderNode that is backing the View return cameraDistance / resources.displayMetrics.densityDpi } set(value) { // View internally converts distance to dp so multiply by density here to have // consistent usage of pixels with RenderNode that is backing the View cameraDistance = value * resources.displayMetrics.densityDpi } private var mutatedFields: Int = 0 override fun updateLayerProperties(scope: ReusableGraphicsLayerScope) { val maybeChangedFields = scope.mutatedFields or mutatedFields if (maybeChangedFields and Fields.TransformOrigin != 0) { this.mTransformOrigin = scope.transformOrigin this.pivotX = mTransformOrigin.pivotFractionX * width this.pivotY = mTransformOrigin.pivotFractionY * height } if (maybeChangedFields and Fields.ScaleX != 0) { this.scaleX = scope.scaleX } if (maybeChangedFields and Fields.ScaleY != 0) { this.scaleY = scope.scaleY } if (maybeChangedFields and Fields.Alpha != 0) { this.alpha = scope.alpha } if (maybeChangedFields and Fields.TranslationX != 0) { this.translationX = scope.translationX } if (maybeChangedFields and Fields.TranslationY != 0) { this.translationY = scope.translationY } if (maybeChangedFields and Fields.ShadowElevation != 0) { this.elevation = scope.shadowElevation } if (maybeChangedFields and Fields.RotationZ != 0) { this.rotation = scope.rotationZ } if (maybeChangedFields and Fields.RotationX != 0) { this.rotationX = scope.rotationX } if (maybeChangedFields and Fields.RotationY != 0) { this.rotationY = scope.rotationY } if (maybeChangedFields and Fields.CameraDistance != 0) { this.cameraDistancePx = scope.cameraDistance } val wasClippingManually = manualClipPath != null val clipToOutline = scope.clip && scope.shape !== RectangleShape if (maybeChangedFields and (Fields.Clip or Fields.Shape) != 0) { this.clipToBounds = scope.clip && scope.shape === RectangleShape resetClipBounds() this.clipToOutline = clipToOutline } val shapeChanged = outlineResolver.update( scope.outline, scope.alpha, clipToOutline, scope.shadowElevation, scope.size ) if (outlineResolver.cacheIsDirty) { updateOutlineResolver() } val isClippingManually = manualClipPath != null if (wasClippingManually != isClippingManually || (isClippingManually && shapeChanged)) { invalidate() // have to redraw the content } if (!drawnWithZ && elevation > 0) { invalidateParentLayer?.invoke() } if (maybeChangedFields and Fields.MatrixAffectingFields != 0) { matrixCache.invalidate() } if (Build.VERSION.SDK_INT >= 28) { if (maybeChangedFields and Fields.AmbientShadowColor != 0) { ViewLayerVerificationHelper28.setOutlineAmbientShadowColor( this, scope.ambientShadowColor.toArgb() ) } if (maybeChangedFields and Fields.SpotShadowColor != 0) { ViewLayerVerificationHelper28.setOutlineSpotShadowColor( this, scope.spotShadowColor.toArgb() ) } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (maybeChangedFields and Fields.RenderEffect != 0) { ViewLayerVerificationHelper31.setRenderEffect(this, scope.renderEffect) } } if (maybeChangedFields and Fields.CompositingStrategy != 0) { mHasOverlappingRendering = when (scope.compositingStrategy) { CompositingStrategy.Offscreen -> { setLayerType(LAYER_TYPE_HARDWARE, null) true } CompositingStrategy.ModulateAlpha -> { setLayerType(LAYER_TYPE_NONE, null) false } else -> { // CompositingStrategy.Auto setLayerType(LAYER_TYPE_NONE, null) true } } } mutatedFields = scope.mutatedFields } override fun hasOverlappingRendering(): Boolean { return mHasOverlappingRendering } override fun isInLayer(position: Offset): Boolean { val x = position.x val y = position.y if (clipToBounds) { return 0f <= x && x < width && 0f <= y && y < height } if (clipToOutline) { return outlineResolver.isInOutline(position) } return true } private fun updateOutlineResolver() { this.outlineProvider = if (outlineResolver.androidOutline != null) { OutlineProvider } else { null } } private fun resetClipBounds() { this.clipBounds = if (clipToBounds) { if (clipBoundsCache == null) { clipBoundsCache = android.graphics.Rect(0, 0, width, height) } else { clipBoundsCache!!.set(0, 0, width, height) } clipBoundsCache } else { null } } override fun resize(size: IntSize) { val width = size.width val height = size.height if (width != this.width || height != this.height) { pivotX = mTransformOrigin.pivotFractionX * width pivotY = mTransformOrigin.pivotFractionY * height updateOutlineResolver() layout(left, top, left + width, top + height) resetClipBounds() matrixCache.invalidate() } } override fun move(position: IntOffset) { val left = position.x if (left != this.left) { offsetLeftAndRight(left - this.left) matrixCache.invalidate() } val top = position.y if (top != this.top) { offsetTopAndBottom(top - this.top) matrixCache.invalidate() } } override fun drawLayer(canvas: Canvas, parentLayer: GraphicsLayer?) { drawnWithZ = elevation > 0f if (drawnWithZ) { canvas.enableZ() } container.drawChild(canvas, this, drawingTime) if (drawnWithZ) { canvas.disableZ() } } override fun dispatchDraw(canvas: android.graphics.Canvas) { canvasHolder.drawInto(canvas) { var didClip = false val clipPath = manualClipPath if (clipPath != null || !canvas.isHardwareAccelerated) { didClip = true save() outlineResolver.clipToOutline(this) } drawBlock?.invoke(this, null) if (didClip) { restore() } } isInvalidated = false } override fun invalidate() { if (!isInvalidated) { isInvalidated = true super.invalidate() ownerView.invalidate() } } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {} override fun destroy() { isInvalidated = false ownerView.requestClearInvalidObservations() drawBlock = null invalidateParentLayer = null val recycle = ownerView.recycle(this@ViewLayer) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M || shouldUseDispatchDraw || !recycle) { container.removeViewInLayout(this) } else { visibility = GONE } } override fun updateDisplayList() { if (isInvalidated && !shouldUseDispatchDraw) { updateDisplayList(this) isInvalidated = false } } override fun forceLayout() { // Don't do anything. These Views are treated as RenderNodes, so a forced layout // should not do anything. If we keep this, we get more redrawing than is necessary. } override fun mapOffset(point: Offset, inverse: Boolean): Offset { return if (inverse) { matrixCache.mapInverse(this, point) } else { matrixCache.map(this, point) } } override fun mapBounds(rect: MutableRect, inverse: Boolean) { if (inverse) { matrixCache.mapInverse(this, rect) } else { matrixCache.map(this, rect) } } override fun reuseLayer( drawBlock: (canvas: Canvas, parentLayer: GraphicsLayer?) -> Unit, invalidateParentLayer: () -> Unit ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M || shouldUseDispatchDraw) { container.addView(this) } else { visibility = VISIBLE } matrixCache.reset() clipToBounds = false drawnWithZ = false mTransformOrigin = TransformOrigin.Center this.drawBlock = drawBlock this.invalidateParentLayer = invalidateParentLayer isInvalidated = false } override fun transform(matrix: Matrix) { matrix.timesAssign(matrixCache.calculateMatrix(this)) } override fun inverseTransform(matrix: Matrix) { val inverse = matrixCache.calculateInverseMatrix(this) if (inverse != null) { matrix.timesAssign(inverse) } } companion object { private val getMatrix: (View, android.graphics.Matrix) -> Unit = { view, matrix -> val newMatrix = view.matrix matrix.set(newMatrix) } val OutlineProvider = object : ViewOutlineProvider() { override fun getOutline(view: View, outline: android.graphics.Outline) { view as ViewLayer outline.set(view.outlineResolver.androidOutline!!) } } private var updateDisplayListIfDirtyMethod: Method? = null private var recreateDisplayList: Field? = null var hasRetrievedMethod = false private set var shouldUseDispatchDraw = false internal set // internal so that tests can use it. @SuppressLint("BanUncheckedReflection") fun updateDisplayList(view: View) { try { if (!hasRetrievedMethod) { hasRetrievedMethod = true if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { updateDisplayListIfDirtyMethod = View::class.java.getDeclaredMethod("updateDisplayListIfDirty") recreateDisplayList = View::class.java.getDeclaredField("mRecreateDisplayList") } else { val getDeclaredMethod = Class::class .java .getDeclaredMethod( "getDeclaredMethod", String::class.java, arrayOf<Class<*>>()::class.java ) updateDisplayListIfDirtyMethod = getDeclaredMethod.invoke( View::class.java, "updateDisplayListIfDirty", emptyArray<Class<*>>() ) as Method? val getDeclaredField = Class::class .java .getDeclaredMethod("getDeclaredField", String::class.java) recreateDisplayList = getDeclaredField.invoke(View::class.java, "mRecreateDisplayList") as Field? } updateDisplayListIfDirtyMethod?.isAccessible = true recreateDisplayList?.isAccessible = true } recreateDisplayList?.setBoolean(view, true) updateDisplayListIfDirtyMethod?.invoke(view) } catch (_: Throwable) { shouldUseDispatchDraw = true } } } } @RequiresApi(Build.VERSION_CODES.S) private object ViewLayerVerificationHelper31 { fun setRenderEffect(view: View, target: RenderEffect?) { view.setRenderEffect(target?.asAndroidRenderEffect()) } } @RequiresApi(Build.VERSION_CODES.P) private object ViewLayerVerificationHelper28 { fun setOutlineAmbientShadowColor(view: View, target: Int) { view.outlineAmbientShadowColor = target } fun setOutlineSpotShadowColor(view: View, target: Int) { view.outlineSpotShadowColor = target } }
6
null
983
59
e18ad812b77fc8babb00aacfcea930607b0794b5
17,674
androidx
Apache License 2.0
app/src/main/java/com/main/maybe/miplayer/ui/fragment/HomeFragment.kt
luciferldy
37,312,180
false
null
package com.main.maybe.miplayer.ui.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.LinearLayout import com.main.maybe.miplayer.R import com.main.maybe.miplayer.model.FolderBean import com.main.maybe.miplayer.presenter.LocalMusicPresenter import com.main.maybe.miplayer.ui.adapter.AlbumListAdapter import com.main.maybe.miplayer.ui.adapter.ArtistListAdapter import com.main.maybe.miplayer.ui.adapter.FolderListAdapter import com.main.maybe.miplayer.ui.adapter.SingleListAdapter import com.main.maybe.miplayer.ui.view.base.BaseView import java.util.ArrayList class HomeFragment : Fragment(), BaseView { private var position: Int = 0 private var mPresenter: LocalMusicPresenter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) position = arguments!!.getInt(ARG_POSITION) initPresenter() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val params = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT) val fl = FrameLayout(activity!!) fl.layoutParams = params val margin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8f, resources.displayMetrics).toInt() params.setMargins(margin, margin, margin, margin) // switch options when (position) { 0 -> // songs fl.addView(initSingle()) 1 -> // artist fl.addView(initArtists()) 2 -> // album fl.addView(initAlbum()) 3 -> // list fl.addView(initFolder()) } return fl } override fun onDestroy() { super.onDestroy() } override fun initPresenter() { mPresenter = LocalMusicPresenter(activity, this) } // init single list private fun initSingle(): LinearLayout { val inflater = LayoutInflater.from(activity) val root = inflater.inflate(R.layout.base_list, null) as LinearLayout val rv = root.findViewById<View>(R.id.rv_ls) as RecyclerView val adapter = SingleListAdapter(activity, mPresenter!!.single) rv.layoutManager = LinearLayoutManager(activity) rv.adapter = adapter return root } // init artist list private fun initArtists(): LinearLayout { val inflater = LayoutInflater.from(activity) val root = inflater.inflate(R.layout.base_list, null) as LinearLayout val rv = root.findViewById<View>(R.id.rv_ls) as RecyclerView val adapter = ArtistListAdapter(activity, mPresenter!!.artist) rv.layoutManager = LinearLayoutManager(activity) rv.adapter = adapter return root } // init album list private fun initAlbum(): LinearLayout { val inflater = LayoutInflater.from(activity) val root = inflater.inflate(R.layout.base_list, null) as LinearLayout val rv = root.findViewById<View>(R.id.rv_ls) as RecyclerView val adapter = AlbumListAdapter(activity!!, mPresenter!!.album!!) rv.adapter = adapter rv.layoutManager = LinearLayoutManager(activity) return root } // init folder list private fun initFolder(): LinearLayout { val inflater = LayoutInflater.from(activity) val root = inflater.inflate(R.layout.base_list, null) as LinearLayout val rv = root.findViewById<View>(R.id.rv_ls) as RecyclerView val adapter = FolderListAdapter(activity, ArrayList()) rv.adapter = adapter rv.layoutManager = LinearLayoutManager(activity) return root } companion object { private val ARG_POSITION = "position" fun newInstance(position: Int): HomeFragment { val f = HomeFragment() val b = Bundle() b.putInt(ARG_POSITION, position) f.arguments = b return f } } }
3
null
10
15
3e109274305815a009ebb8b2974fcd042ca4e609
4,357
miplayer
Apache License 2.0
clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/HudsonMasterComputer.kt
oapicf
90,140,540
false
{"Java": 12530173, "C++": 7972103, "PHP": 4475625, "TypeScript": 3228611, "Python": 3082826, "Rust": 2800453, "HTML": 2428440, "C#": 2318013, "JavaScript": 1592129, "Kotlin": 1468601, "R": 1219437, "Scala": 1119819, "Ada": 1009616, "C": 985434, "Perl": 962381, "Dart": 896698, "Crystal": 872405, "Haskell": 763757, "Apex": 741927, "PowerShell": 680505, "Xojo": 566494, "F#": 556012, "Objective-C": 465570, "Eiffel": 425526, "Shell": 394909, "Erlang": 373267, "Swift": 353672, "Go": 339356, "Lua": 323476, "Ruby": 321943, "Elm": 187340, "Elixir": 134551, "Clojure": 129017, "OCaml": 95013, "Groovy": 90212, "Nim": 66413, "CMake": 24930, "Batchfile": 13610, "Makefile": 12333, "Dockerfile": 7351, "QMake": 6915, "CSS": 4873, "Gherkin": 951, "Emacs Lisp": 191}
/** * <NAME> * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 2.0.1-pre.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.server.api.model import org.openapitools.server.api.model.HudsonMasterComputerexecutors import org.openapitools.server.api.model.HudsonMasterComputermonitorData import org.openapitools.server.api.model.Label1 import com.google.gson.annotations.SerializedName import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude /** * * @param propertyClass * @param displayName * @param executors * @param icon * @param iconClassName * @param idle * @param jnlpAgent * @param launchSupported * @param loadStatistics * @param manualLaunchAllowed * @param monitorData * @param numExecutors * @param offline * @param offlineCause * @param offlineCauseReason * @param temporarilyOffline */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) data class HudsonMasterComputer ( val propertyClass: kotlin.String? = null, val displayName: kotlin.String? = null, val executors: kotlin.Array<HudsonMasterComputerexecutors>? = null, val icon: kotlin.String? = null, val iconClassName: kotlin.String? = null, val idle: kotlin.Boolean? = null, val jnlpAgent: kotlin.Boolean? = null, val launchSupported: kotlin.Boolean? = null, val loadStatistics: Label1? = null, val manualLaunchAllowed: kotlin.Boolean? = null, val monitorData: HudsonMasterComputermonitorData? = null, val numExecutors: kotlin.Int? = null, val offline: kotlin.Boolean? = null, val offlineCause: kotlin.String? = null, val offlineCauseReason: kotlin.String? = null, val temporarilyOffline: kotlin.Boolean? = null ) { }
30
Java
12
19
277d791c0d363a4d93832bec8a581d4c01297b18
2,009
swaggy-jenkins
MIT License
app/src/main/java/com/qingmei2/sample/di/HttpClientModule.kt
ngima
234,334,329
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Markdown": 2, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "XML": 23, "Kotlin": 82, "Java": 2}
package com.qingmei2.sample.di import com.qingmei2.sample.BuildConfig import com.qingmei2.sample.http.interceptor.BasicAuthInterceptor import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.instance import org.kodein.di.generic.provider import org.kodein.di.generic.singleton import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit private const val HTTP_CLIENT_MODULE_TAG = "httpClientModule" const val HTTP_CLIENT_MODULE_INTERCEPTOR_LOG_TAG = "http_client_module_interceptor_log_tag" const val HTTP_CLIENT_MODULE_INTERCEPTOR_AUTH_TAG = "http_client_module_interceptor_auth_tag" const val TIME_OUT_SECONDS = 10 const val BASE_URL = "https://api.github.com/" val httpClientModule = Kodein.Module(HTTP_CLIENT_MODULE_TAG) { bind<Retrofit.Builder>() with provider { Retrofit.Builder() } bind<OkHttpClient.Builder>() with provider { OkHttpClient.Builder() } bind<Retrofit>() with singleton { instance<Retrofit.Builder>() .baseUrl(BASE_URL) .client(instance()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() } bind<Interceptor>(HTTP_CLIENT_MODULE_INTERCEPTOR_LOG_TAG) with singleton { HttpLoggingInterceptor().apply { level = when (BuildConfig.DEBUG) { true -> HttpLoggingInterceptor.Level.BODY false -> HttpLoggingInterceptor.Level.NONE } } } bind<Interceptor>(HTTP_CLIENT_MODULE_INTERCEPTOR_AUTH_TAG) with singleton { BasicAuthInterceptor(mUserInfoRepository = instance()) } bind<OkHttpClient>() with singleton { instance<OkHttpClient.Builder>() .connectTimeout( TIME_OUT_SECONDS.toLong(), TimeUnit.SECONDS) .readTimeout( TIME_OUT_SECONDS.toLong(), TimeUnit.SECONDS) .addInterceptor(instance(HTTP_CLIENT_MODULE_INTERCEPTOR_LOG_TAG)) .addInterceptor(instance(HTTP_CLIENT_MODULE_INTERCEPTOR_AUTH_TAG)) .build() } }
1
null
1
1
da57f583c1cedd860b7c6abc39092413c133c245
2,440
MVVM-Architecture
Apache License 2.0
src/tests/specification/instacli/spec/InstacliTestSuite.kt
Hes-Siemelink
617,124,378
false
{"Kotlin": 110587, "Shell": 36}
package instacli.spec import instacli.cli.CliFile import instacli.commands.InternalHttpServer import instacli.commands.userPrompt import instacli.util.MockUser import org.junit.jupiter.api.* import java.nio.file.Path class InstacliTestSuite { @BeforeEach fun setup() { userPrompt = MockUser() } @TestFactory fun `Instacli reference tests`(): List<DynamicNode> { return Path.of("instacli-spec/reference").getTestCases() } @TestFactory fun `Code examples in reference documentation`(): List<DynamicNode> { return Path.of("instacli-spec/reference").getCodeExamples() } @TestFactory fun `Code examples in main README`(): List<DynamicNode> { return Path.of("README.md").getCodeExamples() } companion object { @BeforeAll @JvmStatic fun startTestServer() { CliFile(TestPaths.SAMPLE_SERVER).run() } @AfterAll @JvmStatic fun stopTestServer() { InternalHttpServer.stop() } } }
0
Kotlin
0
2
c1e99c95d981370c0454044bd5db1759448d770e
1,051
instacli
Apache License 2.0
src/test/kotlin/snyk/amplitude/api/VariantTest.kt
snyk
117,852,067
false
{"Kotlin": 1060353, "Java": 67741, "JavaScript": 9475, "SCSS": 3094, "HCL": 562}
package snyk.amplitude.api import com.google.gson.Gson import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test class VariantTest { private val gson: Gson = Gson() @Test fun `parse variant with deprecated key field`() { val json = """{"key":"on"}""" val variant = gson.fromJson(json, Variant::class.java) assertNotNull(variant) assertEquals("on", variant.value) } @Test fun `parse variant with actual value field`() { val json = """{"value":"on"}""" val variant = gson.fromJson(json, Variant::class.java) assertNotNull(variant) assertEquals("on", variant.value) } }
8
Kotlin
32
52
cf827a6642c0110f618df30d5839703b5c8071bd
706
snyk-intellij-plugin
Apache License 2.0
src/main/kotlin/hw8/views/MainMenu.kt
vol0n
341,698,683
false
{"Kotlin": 116397}
package hw8.views import hw8.Invite import hw8.PlayerInfo import hw8.app.Styles import hw8.controllers.WebGameController import io.ktor.util.KtorExperimentalAPI import tornadofx.View import tornadofx.action import tornadofx.borderpane import tornadofx.drawer import tornadofx.item import tornadofx.menu import tornadofx.menubar import tornadofx.readonlyColumn import tornadofx.tableview import tornadofx.toObservable @KtorExperimentalAPI class MainMenu : View("TicTacToe online!") { val activePlayers = mutableListOf<PlayerInfo>().toObservable() val playersTable = tableview(activePlayers) { readonlyColumn("Name", PlayerInfo::name) } val invites = mutableListOf<Invite>().toObservable() val invitesTable = tableview(invites) { readonlyColumn("Name", Invite::sender) readonlyColumn("Side", Invite::side) readonlyColumn("Message", Invite::message) } override val root = borderpane { top = menubar { menu("Actions") { item("Mode menu.").action { replaceWith<ModeScreen>() find<WebGameController>().stopAllTasks() } } } center = drawer { item("Active players", expanded = true) { add(playersTable) } item("Incoming invites") { add(invitesTable) } } } override fun onDock() { primaryStage.width = Styles.winWidth.value primaryStage.height = Styles.winHeight.value // primaryStage.centerOnScreen() } }
0
Kotlin
0
0
45f9a341c5ddd92ce0c67721395af365674ee81b
1,606
spbu_kotlin_hw
Apache License 2.0
java/kotlin/src/main/kotlin/cosmos/base/v1beta1/DecCoinKt.kt
dimitar-petrov
413,042,055
true
{"Kotlin": 3495003, "TypeScript": 2945432, "Java": 1230297, "Shell": 1036, "Makefile": 712}
//Generated by the protocol buffer compiler. DO NOT EDIT! // source: cosmos/base/v1beta1/coin.proto package cosmos.base.v1beta1; @kotlin.jvm.JvmSynthetic inline fun decCoin(block: cosmos.base.v1beta1.DecCoinKt.Dsl.() -> Unit): cosmos.base.v1beta1.CoinOuterClass.DecCoin = cosmos.base.v1beta1.DecCoinKt.Dsl._create(cosmos.base.v1beta1.CoinOuterClass.DecCoin.newBuilder()).apply { block() }._build() object DecCoinKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker class Dsl private constructor( @kotlin.jvm.JvmField private val _builder: cosmos.base.v1beta1.CoinOuterClass.DecCoin.Builder ) { companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: cosmos.base.v1beta1.CoinOuterClass.DecCoin.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): cosmos.base.v1beta1.CoinOuterClass.DecCoin = _builder.build() /** * <code>string denom = 1;</code> */ var denom: kotlin.String @JvmName("getDenom") get() = _builder.getDenom() @JvmName("setDenom") set(value) { _builder.setDenom(value) } /** * <code>string denom = 1;</code> */ fun clearDenom() { _builder.clearDenom() } /** * <code>string amount = 2 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "Dec"];</code> */ var amount: kotlin.String @JvmName("getAmount") get() = _builder.getAmount() @JvmName("setAmount") set(value) { _builder.setAmount(value) } /** * <code>string amount = 2 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "Dec"];</code> */ fun clearAmount() { _builder.clearAmount() } } } @kotlin.jvm.JvmSynthetic inline fun cosmos.base.v1beta1.CoinOuterClass.DecCoin.copy(block: cosmos.base.v1beta1.DecCoinKt.Dsl.() -> Unit): cosmos.base.v1beta1.CoinOuterClass.DecCoin = cosmos.base.v1beta1.DecCoinKt.Dsl._create(this.toBuilder()).apply { block() }._build()
0
null
0
0
06fcb6a1e57962a46af0aebb90b5b110e0b42435
2,127
terra.proto
Apache License 2.0
todo-mvp/src/main/java/com/github/bassaer/todomvp/BasePresenter.kt
bassaer
125,229,420
false
null
package com.github.bassaer.todomvp /** * Created by nakayama on 2018/03/18. */ public interface BasePresenter { fun start() }
0
Kotlin
0
0
80384491292a090504d36e496ed3986596711d73
132
android-architecture-patterns
Apache License 2.0
app/src/main/java/com/ww7h/ww/common/utils/SignUtil.kt
hiww7h
177,269,079
false
null
package com.ww7h.ww.common.utils import android.content.Context import android.content.pm.PackageManager import java.security.MessageDigest import java.security.NoSuchAlgorithmException object SignUtil { fun getSignMd5Str(context: Context, packgeName: String): String { try { val packageInfo = context.packageManager.getPackageInfo( packgeName, PackageManager.GET_SIGNATURES ) val signs = packageInfo.signatures val sign = signs[0] return encryptionMD5(sign.toByteArray()) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return "" } /** * MD5加密 * @param byteStr 需要加密的内容 * @return 返回 byteStr的md5值 */ fun encryptionMD5(byteStr: ByteArray): String { var messageDigest: MessageDigest? = null val md5StrBuff = StringBuffer() try { messageDigest = MessageDigest.getInstance("MD5") messageDigest!!.reset() messageDigest.update(byteStr) val byteArray = messageDigest.digest() for (i in byteArray.indices) { if (Integer.toHexString(0xFF and byteArray[i].toInt()).length == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF and byteArray[i].toInt())) } else { md5StrBuff.append(Integer.toHexString(0xFF and byteArray[i].toInt())) } } } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } return md5StrBuff.toString() } }
1
null
2
4
e43d426384f35971508e1ae6d61aef868168764e
1,643
Android-common
MIT License
src/main/kotlin/model/classes/IntMatrix.kt
MaxBuster380
622,688,076
false
null
import java.lang.Exception import java.lang.IndexOutOfBoundsException /** * Integer Matrix * @author MaxBuster */ class IntMatrix { // INSTANCE ATTRIBUTES private val values : MutableList<MutableList<Int>> private val nbRows : Int private val nbColumns : Int // CONSTRUCTORS constructor(nbRows : Int, nbColumns : Int) { if (nbRows <= 0) { throw Exception("(Matrix constructor) Number of rows should be strictly positive, $nbRows given") } if (nbColumns <= 0) { throw Exception("(Matrix constructor) Number of columns should be strictly positive, $nbColumns given") } this.nbRows = nbRows this.nbColumns = nbColumns values = mutableListOf() for(i in 0 until nbColumns) { val newRow : MutableList<Int> = mutableListOf() for (j in 0 until nbRows) { newRow.add(0) } values.add(newRow) } } // INSTANCE METHODS /** * Calculates A*b, where A is the current matrix and b is a vector */ fun product(b : List<Int>):List<Int> { if (b.size != nbRows) { throw Exception("(Matrix.product) b's size is ${b.size}, where $nbRows is expected") } val res : MutableList<Int> = mutableListOf() for(row in 0 until nbRows) { var sum = 0 for(column in 0 until nbColumns) { sum += values[row][column] * b[column] } res += sum } return res } /** * Redefines a value on the matrix * @param rowIndex Row identifier * @param columnIndex Column identifier * @param value New value */ fun set(rowIndex : Int, columnIndex : Int, value : Int) { if (rowIndex < 0 || rowIndex >= nbRows) { throw IndexOutOfBoundsException("(Matrix.set) Row $rowIndex is out of range") } if (columnIndex < 0 || columnIndex >= nbColumns) { throw IndexOutOfBoundsException("(Matrix.set) Column $columnIndex is out of range") } values[rowIndex][columnIndex] = value } /** * Returns the requested value on the matrix * @param rowIndex Row identifier * @param columnIndex Column identifier * @return Value at rowIndex : columnIndex */ fun get(rowIndex : Int, columnIndex : Int):Int { if (rowIndex < 0 || rowIndex >= nbRows) { throw IndexOutOfBoundsException("(Matrix.get) Row $rowIndex is out of range") } if (columnIndex < 0 || columnIndex >= nbColumns) { throw IndexOutOfBoundsException("(Matrix.get) Column $columnIndex is out of range") } return values[rowIndex][columnIndex] } /** * Replaces a row with a new one * @param rowIndex Row to replace * @param newRow New row */ fun setRow(rowIndex : Int, newRow : MutableList<Int>) { if (rowIndex < 0 || rowIndex >= nbRows) { throw IndexOutOfBoundsException("(Matrix.setRow) Row $rowIndex is out of range") } if (newRow.size != nbColumns) { throw Exception("(Matrix.setRow) New row's size doesn't match matrix size (${newRow.size} given, $nbColumns expected)") } values[rowIndex] = newRow } /** * Prints the matrix */ fun print() { for(row in 0 until nbRows) { var line = "|\t" for(column in 0 until nbColumns) { line = line + values[row][column] + "\t" } line = "$line|" println(line) } } /** * Returns the submatrix used to calculate the determinant from a given row */ private fun getSubMatrix(rowIndex : Int) : IntMatrix { if (nbRows != nbColumns) { throw Exception("(Matrix.getSubMatrix) Can't get submatrix of a non-square matrix") } if (nbRows <= 2) { throw Exception("(Matrix.getSubMatrix) Can't get submatrix of a matrix smaller than 3x3, currently $nbRows:$nbColumns") } if (rowIndex < 0 || rowIndex >= nbRows) { throw IndexOutOfBoundsException("(Matrix.getSubMatrix) Row $rowIndex is out of range") } val res = IntMatrix(nbRows-1,nbColumns-1) var resRow = 0 for(row in 0 until nbRows) { if (row != rowIndex) { for (column in 1 until nbColumns) { val value = get(row,column) res.set(resRow,column-1,value) } resRow++ } } return res } /** * Returns the matrix's determinant */ fun det() : Int { if (nbRows != nbColumns) { throw Exception("(Matrix.det) Can't get determinant of a non-square matrix") } if (nbRows == 1) { return (values[0][0]) } if (nbRows == 2) { val a = values[0][0] val b = values[0][1] val c = values[1][0] val d = values[1][1] return (a*d - b*c) } // if nbRows > 2 var res = 0 var sign = 1 for(row in 0 until nbRows) { val factor = values[row][0] val subDet = getSubMatrix(row).det() res += sign * factor * subDet sign = -sign // Flips between 1 and -1 } return res } }
0
Kotlin
0
3
c77168a15f7da11c44a7ebaec8fb9a1cd826b1b7
5,478
OneShot-Color-Filter
MIT License
src/main/kotlin/dp/SPS.kt
yx-z
106,589,674
false
null
package dp import util.* // Shortest Palindromic Supersequence // given a String S[1..n], find the shortest palindromic superseuqnce of S fun main(args: Array<String>) { val arr = "TWENTYONE".toCharArray().toList().toOneArray() println(arr.sps()) // TWENToYOtNEwt -> 13 (inserted characters are lowercased) } fun OneArray<Char>.sps(): Int { // follow the naming convention val S = this val n = size // dp(i, j): len of SPS of S[i..j] // memoization structure: 2d array dp[1..n, 1..n] : dp[i, j] = dp(i, j) val dp = OneArray(n + 1) { OneArray(n) { 0 } } // space complexity: O(n^2) // base case: // dp(i, j) = 0 if j < i or i, j !in 1..n // = 1 if i = j (single character string is already palindromic) for (i in 1..n) { dp[i, i] = 1 } // recursive case: // dp(i, j) = dp(i + 1, j - 1) + 2 if S[i] == S[j] // since we need to wrap S[i] and S[j] as the first and the last // character in the sps // = util.min{ dp(i + 1, j), dp(i, j - 1) } + 2 // find the minimum and either wrap two S[i] around SPS or two S[j] // dependency: dp(i, j) depends on dp(i + 1, j - 1), dp(i + 1, j ), // and dp(i, j - 1) // that is entries below, to the left, and to the lower-left // evaluation order: outer loop for i from n to 1 (bottom up) for (i in n downTo 1) { // inner loop for j from i + 1 to n (left to right) for (j in i + 1..n) { dp[i, j] = if (S[i] == S[j]) { dp[i + 1, j - 1] + 2 } else { min(dp[i, j - 1], dp[i + 1, j]) + 2 } } } // time complexity: O(n^2) dp.prettyPrintTable() // we want len of SPS of S[1..n], which is dp[1, n] return dp[1, n] }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,679
AlgoKt
MIT License
idea/testData/refactoring/extractFunction/controlFlow/evaluateExpression/evalExpressionBodyFunction.kt
staltz
38,581,975
true
{"Markdown": 34, "XML": 687, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18510, "Java": 4307, "Protocol Buffer": 4, "Text": 4085, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 71, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
// PARAM_TYPES: kotlin.Int // PARAM_TYPES: kotlin.Int // PARAM_DESCRIPTOR: value-parameter val a: kotlin.Int defined in foo // PARAM_DESCRIPTOR: value-parameter val b: kotlin.Int defined in foo // SIBLING: fun foo(a: Int, b: Int): Int = <selection>a + b</selection>
0
Java
0
1
88a261234860ff0014e3c2dd8e64072c685d442d
266
kotlin
Apache License 2.0
common/src/main/java/com/piriurna/common/composables/scaffold/ADNavigationItem.kt
piriurna
542,623,945
false
{"Kotlin": 95640}
package com.piriurna.common.composables.scaffold import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Menu import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun RowScope.ADNavigationItem( modifier: Modifier = Modifier, icon: ImageVector, selected : Boolean = false, text: String, selectedColor : Color, unselectedColor : Color = Color.LightGray, onClick: () -> Unit = {} ) { val iconColor = if(selected) selectedColor else unselectedColor val textColor = if(selected) Color.Black else Color.LightGray Box( modifier = modifier .weight(1f) .align(Alignment.Bottom) .padding(4.dp), contentAlignment = Alignment.Center, ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = modifier .clickable { onClick.invoke() } .align(Alignment.Center), ) { Icon( modifier = Modifier.size(28.dp), imageVector = icon, contentDescription = "Item Icon", tint = iconColor ) Text( text = text, color = textColor, fontWeight = FontWeight.Bold ) } } } @Preview(showBackground = true) @Composable private fun ADNavigationItemPreview() { Row(Modifier.fillMaxSize()) { ADNavigationItem( icon = Icons.Default.Home, text = "Play Games", selectedColor = MaterialTheme.colors.primary ) ADNavigationItem( icon = Icons.Default.Menu, text = "Profile", selected = true, selectedColor = MaterialTheme.colors.primary ) } }
0
Kotlin
0
0
948d38f31bb3b8b618224960b3db78cd4bcb2ee9
2,441
AndroidDog
MIT License
feature-ledger-impl/src/main/java/io/novafoundation/nova/feature_ledger_impl/presentation/account/connect/generic/finish/FinishImportGenericLedgerViewModel.kt
novasamatech
415,834,480
false
{"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.feature_ledger_impl.presentation.account.connect.generic.finish import io.novafoundation.nova.common.resources.ResourceManager import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountInteractor import io.novafoundation.nova.feature_account_api.presenatation.account.createName.CreateWalletNameViewModel import io.novafoundation.nova.feature_ledger_impl.domain.account.connect.generic.finish.FinishImportGenericLedgerInteractor import io.novafoundation.nova.feature_ledger_impl.presentation.LedgerRouter import io.novafoundation.nova.feature_ledger_impl.presentation.account.connect.generic.common.payload.toDomain import kotlinx.coroutines.launch class FinishImportGenericLedgerViewModel( private val router: LedgerRouter, private val resourceManager: ResourceManager, private val payload: FinishImportGenericLedgerPayload, private val accountInteractor: AccountInteractor, private val interactor: FinishImportGenericLedgerInteractor ) : CreateWalletNameViewModel(router, resourceManager) { override fun proceed(name: String) { launch { interactor.createWallet(name, payload.account.toDomain()) .onSuccess { continueBasedOnCodeStatus() } .onFailure(::showError) } } private suspend fun continueBasedOnCodeStatus() { if (accountInteractor.isCodeSet()) { router.openMain() } else { router.openCreatePincode() } } }
12
Kotlin
30
50
127f8739ca86dc74d006f018237daed0de5095a1
1,511
nova-wallet-android
Apache License 2.0
va_code/app/src/main/java/com/mvrc/viewapp/presentation/sign_up/view_model/SignUpFormEvent.kt
MarcoBendinelli
789,851,376
false
{"Kotlin": 547994}
package com.mvrc.viewapp.presentation.sign_up.view_model /** * Sealed class representing events related to the Sign Up form. */ sealed class SignUpFormEvent { /** * Event indicating a change in the email field. * * @param email The updated email value. */ data class EmailChanged(val email: String) : SignUpFormEvent() /** * Event indicating a change in the password field. * * @param password The updated password value. */ data class PasswordChanged(val password: String) : SignUpFormEvent() /** * Event indicating a change in the repeated password field. * * @param repeatedPassword The updated repeated password value. */ data class RepeatedPasswordChanged(val repeatedPassword: String) : SignUpFormEvent() }
0
Kotlin
0
0
1c570950bd1d8e122e83414c1b0ff6d731a2d3fb
802
View-Android-Mobile-App
MIT License
src/en/zoro/src/eu/kanade/tachiyomi/animeextension/en/zoro/Zoro.kt
MoonLGH
410,582,925
true
{"Kotlin": 1919153, "Java": 6463}
package eu.kanade.tachiyomi.animeextension.en.zoro import android.app.Application import android.content.SharedPreferences import androidx.preference.ListPreference import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.animeextension.en.zoro.extractors.ZoroExtractor import eu.kanade.tachiyomi.animeextension.en.zoro.utils.JSONUtil import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource import eu.kanade.tachiyomi.animesource.model.AnimeFilterList import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.animesource.model.SEpisode import eu.kanade.tachiyomi.animesource.model.Track import eu.kanade.tachiyomi.animesource.model.Video import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource import eu.kanade.tachiyomi.network.GET import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy import java.lang.Exception class Zoro : ConfigurableAnimeSource, ParsedAnimeHttpSource() { override val name = "zoro.to (experimental)" override val baseUrl = "https://zoro.to" override val lang = "en" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient private val json: Json by injectLazy() private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } // ============================== Popular =============================== override fun popularAnimeSelector(): String = "div.flw-item" override fun popularAnimeRequest(page: Int): Request = GET("$baseUrl/most-popular?page=$page") override fun popularAnimeFromElement(element: Element): SAnime { val anime = SAnime.create() anime.thumbnail_url = element.select("div.film-poster > img").attr("data-src") anime.setUrlWithoutDomain(element.select("div.film-detail a").attr("href")) anime.title = element.select("div.film-detail a").attr("data-jname") anime.description = element.selectFirst("div.film-detail div.description")?.text() return anime } override fun popularAnimeNextPageSelector(): String = "li.page-item a[title=Next]" // ============================== Episodes ============================== override fun episodeListSelector() = "ul#episode_page li a" override fun episodeListRequest(anime: SAnime): Request { val id = anime.url.substringAfterLast("-") val referer = Headers.headersOf("Referer", baseUrl + anime.url) return GET("$baseUrl/ajax/v2/episode/list/$id", referer) } override fun episodeListParse(response: Response): List<SEpisode> { val data = response.body!!.string() .substringAfter("\"html\":\"") .substringBefore("<script>") val unescapedData = JSONUtil.unescape(data) val document = Jsoup.parse(unescapedData) val episodeList = document.select("a.ep-item").map { SEpisode.create().apply { episode_number = it.attr("data-number").toFloat() name = "Episode ${it.attr("data-number")}: ${it.attr("title")}" url = it.attr("href") } } return episodeList.reversed() } override fun episodeFromElement(element: Element) = throw Exception("not used") // ============================ Video Links ============================= override fun videoListRequest(episode: SEpisode): Request { val id = episode.url.substringAfterLast("?ep=") val referer = Headers.headersOf("Referer", baseUrl + episode.url) return GET("$baseUrl/ajax/v2/episode/servers?episodeId=$id", referer) } override fun videoListParse(response: Response): List<Video> { val body = response.body!!.string() val episodeReferer = Headers.headersOf("Referer", response.request.header("referer")!!) val data = body.substringAfter("\"html\":\"").substringBefore("<script>") val unescapedData = JSONUtil.unescape(data) val serversHtml = Jsoup.parse(unescapedData) val videoList = mutableListOf<Video>() for (server in serversHtml.select("div.server-item")) { if (server.text() == "StreamSB" || server.text() == "Streamtape") continue val id = server.attr("data-id") val subDub = server.attr("data-type") val videos = runCatching { getVideosFromServer( client.newCall(GET("$baseUrl/ajax/v2/episode/sources?id=$id", episodeReferer)).execute(), subDub ) }.getOrNull() if (videos != null) videoList.addAll(videos) } return videoList } private fun getVideosFromServer(response: Response, subDub: String): List<Video>? { val body = response.body!!.string() val url = body.substringAfter("\"link\":\"").substringBefore("\"") + "&autoPlay=1&oa=0" val source = ZoroExtractor(client).getSourcesJson(url) ?: return null if (!source.contains("{\"sources\":[{\"file\":\"")) return null val json = json.decodeFromString<JsonObject>(source) val masterUrl = json["sources"]!!.jsonArray[0].jsonObject["file"]!!.jsonPrimitive.content val subs2 = mutableListOf<Track>() json["tracks"]?.jsonArray ?.filter { it.jsonObject["kind"]!!.jsonPrimitive.content == "captions" } ?.map { track -> val trackUrl = track.jsonObject["file"]!!.jsonPrimitive.content val lang = track.jsonObject["label"]!!.jsonPrimitive.content try { subs2.add(Track(trackUrl, lang)) } catch (e: Error) {} } ?: emptyList() val subs = subLangOrder(subs2) val masterPlaylist = client.newCall(GET(masterUrl)).execute().body!!.string() val videoList = mutableListOf<Video>() masterPlaylist.substringAfter("#EXT-X-STREAM-INF:").split("#EXT-X-STREAM-INF:").forEach { val quality = it.substringAfter("RESOLUTION=").substringAfter("x").substringBefore(",") + "p - $subDub" val videoUrl = masterUrl.substringBeforeLast("/") + "/" + it.substringAfter("\n").substringBefore("\n") videoList.add( try { Video(videoUrl, quality, videoUrl, subtitleTracks = subs) } catch (e: Error) { Video(videoUrl, quality, videoUrl) } ) } return videoList } override fun videoListSelector() = throw Exception("not used") override fun videoFromElement(element: Element) = throw Exception("not used") override fun videoUrlParse(document: Document) = throw Exception("not used") private fun List<Video>.sortIfContains(item: String): List<Video> { val newList = mutableListOf<Video>() var preferred = 0 for (video in this) { if (item in video.quality) { newList.add(preferred, video) } else { newList.add(video) } } return newList } override fun List<Video>.sort(): List<Video> { val quality = preferences.getString(PREF_QUALITY_KEY, "720p")!! val type = preferences.getString(PREF_TYPE_KEY, "dub")!! val newList = this.sortIfContains(type).reversed().sortIfContains(quality) return newList } private fun subLangOrder(tracks: List<Track>): List<Track> { val language = preferences.getString(PREF_SUB_KEY, null) if (language != null) { val newList = mutableListOf<Track>() var preferred = 0 for (track in tracks) { if (track.lang == language) { newList.add(preferred, track) preferred++ } else { newList.add(track) } } return newList } return tracks } // =============================== Search =============================== override fun searchAnimeFromElement(element: Element) = popularAnimeFromElement(element) override fun searchAnimeNextPageSelector(): String = popularAnimeNextPageSelector() override fun searchAnimeSelector(): String = popularAnimeSelector() override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList) = GET("$baseUrl/search?keyword=$query&page=$page") // =========================== Anime Details ============================ override fun animeDetailsParse(document: Document): SAnime { val anime = SAnime.create() val info = document.selectFirst("div.anisc-info") anime.thumbnail_url = document.selectFirst("div.anisc-poster img").attr("src") anime.title = document.selectFirst("div.anisc-detail h2").attr("data-jname") anime.author = info.getInfo("Studios:") anime.status = parseStatus(info.getInfo("Status:")) anime.genre = info.getInfo("Genres:", isList = true) var description = (info.getInfo("Overview:") + "\n") ?: "" info.getInfo("Aired:", full = true)?.let { description += it } info.getInfo("Premiered:", full = true)?.let { description += it } info.getInfo("Synonyms:", full = true)?.let { description += it } info.getInfo("Japanese:", full = true)?.let { description += it } anime.description = description return anime } // =============================== Latest =============================== override fun latestUpdatesNextPageSelector(): String = popularAnimeNextPageSelector() override fun latestUpdatesFromElement(element: Element) = popularAnimeFromElement(element) override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/top-airing") override fun latestUpdatesSelector(): String = popularAnimeSelector() // ============================== Settings ============================== override fun setupPreferenceScreen(screen: PreferenceScreen) { val videoQualityPref = ListPreference(screen.context).apply { key = PREF_QUALITY_KEY title = PREF_QUALITY_TITLE entries = PREF_QUALITY_ENTRIES entryValues = PREF_QUALITY_ENTRIES setDefaultValue("720p") summary = "%s" setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = findIndexOfValue(selected) val entry = entryValues[index] as String preferences.edit().putString(key, entry).commit() } } val epTypePref = ListPreference(screen.context).apply { key = PREF_TYPE_KEY title = PREF_TYPE_TITLE entries = PREF_TYPE_ENTRIES entryValues = PREF_TYPE_ENTRIES setDefaultValue("dub") summary = "%s" setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = findIndexOfValue(selected) val entry = entryValues[index] as String preferences.edit().putString(key, entry).commit() } } val subLangPref = ListPreference(screen.context).apply { key = PREF_SUB_KEY title = PREF_SUB_TITLE entries = PREF_SUB_ENTRIES entryValues = PREF_SUB_ENTRIES setDefaultValue("English") summary = "%s" setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = findIndexOfValue(selected) val entry = entryValues[index] as String preferences.edit().putString(key, entry).commit() } } screen.addPreference(videoQualityPref) screen.addPreference(epTypePref) screen.addPreference(subLangPref) } // ============================= Utilities ============================== private fun parseStatus(statusString: String?): Int { return when (statusString) { "Currently Airing" -> SAnime.ONGOING "Finished Airing" -> SAnime.COMPLETED else -> SAnime.UNKNOWN } } private fun Element.getInfo( tag: String, isList: Boolean = false, full: Boolean = false ): String? { if (isList) { val elements = select("div.item-list:contains($tag) > a") return elements.joinToString(", ") { it.text() } } val targetElement = selectFirst("div.item-title:contains($tag)") ?: return null val value = targetElement.selectFirst("*.name, *.text")!!.text() return if (full) "\n$tag $value" else value } companion object { private const val PREF_QUALITY_KEY = "preferred_quality" private const val PREF_QUALITY_TITLE = "Preferred video quality" private val PREF_QUALITY_ENTRIES = arrayOf("360p", "720p", "1080p") private const val PREF_TYPE_KEY = "preferred_type" private const val PREF_TYPE_TITLE = "Preferred episode type/mode" private val PREF_TYPE_ENTRIES = arrayOf("sub", "dub") private const val PREF_SUB_KEY = "preferred_subLang" private const val PREF_SUB_TITLE = "Preferred sub language" private val PREF_SUB_ENTRIES = arrayOf( "English", "Spanish", "Portuguese", "French", "German", "Italian", "Japanese", "Russian" ) } }
0
Kotlin
0
0
6741e2f3b1994238796cb025337fcc707b43da8a
14,072
aniyomi-tachiyomi-ext
Apache License 2.0
android/quest/src/androidTest/java/org/smartregister/fhircore/quest/ui/shared/components/ActionableButtonTest.kt
opensrp
339,242,809
false
null
/* * Copyright 2021 Ona Systems, 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 org.smartregister.fhircore.quest.ui.shared.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.height import androidx.compose.ui.Modifier import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.unit.dp import androidx.navigation.NavController import io.mockk.mockk import org.hl7.fhir.r4.model.Patient import org.hl7.fhir.r4.model.ResourceType import org.junit.Before import org.junit.Rule import org.junit.Test import org.smartregister.fhircore.engine.configuration.QuestionnaireConfig import org.smartregister.fhircore.engine.configuration.view.ButtonProperties import org.smartregister.fhircore.engine.configuration.workflow.ActionTrigger import org.smartregister.fhircore.engine.configuration.workflow.ApplicationWorkflow import org.smartregister.fhircore.engine.domain.model.ActionConfig import org.smartregister.fhircore.engine.domain.model.ResourceData class ActionableButtonTest { @get:Rule val composeRule = createComposeRule() private val navController = mockk<NavController>(relaxed = true, relaxUnitFun = true) @Before fun init() { composeRule.setContent { Column(modifier = Modifier.height(50.dp)) { ActionableButton( buttonProperties = ButtonProperties( status = "DUE", text = "Button Text", actions = listOf( ActionConfig( trigger = ActionTrigger.ON_CLICK, workflow = ApplicationWorkflow.LAUNCH_QUESTIONNAIRE, questionnaire = QuestionnaireConfig(id = "23", title = "Add Family"), ) ) ), resourceData = ResourceData("id", ResourceType.Patient, emptyMap(), emptyMap()), navController = navController ) } } } @Test fun testActionableButtonRendersAncClickWorksCorrectly() { composeRule .onNodeWithText("Button Text", useUnmergedTree = true) .assertExists() .assertIsDisplayed() .performClick() } }
140
Kotlin
16
27
1772266e561a2176aa88bfcbcb2368fe1f80add0
2,850
fhircore
Apache License 2.0
app/src/main/java/at/rtr/rmbt/android/ui/adapter/QosTestDetailPagerAdapter.kt
rtr-nettest
195,193,208
false
null
package at.rtr.rmbt.android.ui.adapter import android.content.Context import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import at.rtr.rmbt.android.R import at.rtr.rmbt.android.ui.fragment.QosTestDetailFragment import at.specure.data.entity.QosTestItemRecord class QosTestDetailPagerAdapter( private val context: Context, fragmentManager: FragmentManager, private val qosTestItems: List<QosTestItemRecord> ) : FragmentStatePagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { private val fragments = mutableMapOf<Long, Fragment>() override fun getItem(position: Int): Fragment { val item = qosTestItems[position] return if (fragments.contains(item.qosTestId)) { fragments[item.qosTestId]!! } else { val fragment: Fragment = QosTestDetailFragment.newInstance(item.testUUID, item.qosTestId, item.testSummary, item.testDescription, item.success) fragments[item.qosTestId] = fragment fragment } } override fun getCount(): Int { return qosTestItems.size } override fun destroyItem(container: ViewGroup, position: Int, obj: Any) { super.destroyItem(container, position, obj) val qosTestId = qosTestItems[position].qosTestId fragments.remove(qosTestId) } override fun getPageTitle(position: Int): CharSequence? { return String.format(context.getString(R.string.qos_test_number), position + 1) } }
1
null
8
6
f9fc150c71452b9ef9027f1506e216d9dda40235
1,606
open-rmbt-android
Apache License 2.0
src/main/kotlin/ru/scuroneko/furniture/ModBlocks.kt
ScuroNeko
796,769,478
false
{"Kotlin": 174165}
package ru.scuroneko.furniture import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings import net.minecraft.block.Block import net.minecraft.block.BlockSetType import net.minecraft.block.Blocks import net.minecraft.block.entity.BlockEntity import net.minecraft.block.entity.BlockEntityType import net.minecraft.item.BlockItem import net.minecraft.item.Item import net.minecraft.registry.Registries import net.minecraft.registry.Registry import net.minecraft.util.DyeColor import net.minecraft.util.Identifier import ru.scuroneko.furniture.api.ScuroFurnitureBlocksAPI import ru.scuroneko.furniture.api.blocks.AbstractDrawerBlock import ru.scuroneko.furniture.blocks.* import ru.scuroneko.furniture.blocks.entity.BedsideTableBlockEntity import ru.scuroneko.furniture.blocks.entity.CarpenterTableBlockEntity import ru.scuroneko.furniture.blocks.entity.MedicalDrawerBlockEntity import ru.scuroneko.furniture.registry.RegistryHelper import ru.scuroneko.furniture.registry.blocks.MedicalDrawers import ru.scuroneko.furniture.registry.items.MedicalDrawersComponents object ModBlocks { val BLOCKS = LinkedHashMap<Identifier, Block>() val BEDSIDE_TABLES = LinkedHashMap<Identifier, AbstractDrawerBlock>() val BEDSIDE_TABLES_ITEMS = LinkedHashMap<Identifier, Item>() val KITCHEN_CABINETS = LinkedHashMap<Identifier, KitchenCabinetBlock>() val KITCHEN_CABINETS_ITEMS = LinkedHashMap<Identifier, Item>() val CARPENTER_TABLE = CarpenterTableBlock(FabricBlockSettings.copy(Blocks.CRAFTING_TABLE)) val AIRTIGHT_DOOR = AirtightDoorBlock(BlockSetType.IRON, FabricBlockSettings.copy(Blocks.IRON_DOOR)) val CHERRY_BED_PURPLE = CustomBedBlock(DyeColor.PURPLE, FabricBlockSettings.copy(Blocks.PURPLE_BED)) val CHERRY_BED_PINK = CustomBedBlock(DyeColor.PINK, FabricBlockSettings.copy(Blocks.PINK_BED)) val CHERRY_BEDSIDE_TABLE = BedsideTableBlock( MedicalDrawersComponents.CHERRY_MEDICAL_DRAWER_CASE, MedicalDrawersComponents.CHERRY_MEDICAL_BOX ) val CHERRY_KITCHEN_CABINET = KitchenCabinetBlock( MedicalDrawersComponents.CHERRY_MEDICAL_DRAWER_CASE, MedicalDrawersComponents.CHERRY_MEDICAL_BOX ) val WHITE_CHERRY_SOFA = SofaBlock( Blocks.CHERRY_PLANKS, Blocks.STRIPPED_CHERRY_LOG, Blocks.WHITE_WOOL ) val BLACK_CHERRY_SOFA = SofaBlock( Blocks.CHERRY_PLANKS, Blocks.STRIPPED_CHERRY_LOG, Blocks.BLACK_WOOL ) val WHITE_OAK_LAMP = LampBlock(FabricBlockSettings.copy(Blocks.WHITE_WOOL)) val BLACK_OAK_LAMP = LampBlock(FabricBlockSettings.copy(Blocks.BLACK_WOOL)) val WHITE_CHERRY_LAMP = LampBlock(FabricBlockSettings.copy(Blocks.WHITE_WOOL)) val BLACK_CHERRY_LAMP = LampBlock(FabricBlockSettings.copy(Blocks.BLACK_WOOL)) val CARPENTER_TABLE_BLOCK_ENTITY = BlockEntityType.Builder.create(::CarpenterTableBlockEntity, CARPENTER_TABLE).build() val MEDICAL_DRAWER_BLOCK_ENTITY = BlockEntityType.Builder.create(::MedicalDrawerBlockEntity, MedicalDrawers.OAK_MEDICAL_DRAWER).build() val BEDSIDE_TABLE_BLOCK_ENTITY = BlockEntityType.Builder.create(::BedsideTableBlockEntity, CHERRY_BEDSIDE_TABLE).build() fun register() { registerBlock("carpenter_table", CARPENTER_TABLE) registerBlock("airtight_door", AIRTIGHT_DOOR) registerBlock("purple_cherry_bed", CHERRY_BED_PURPLE) registerBlock("pink_cherry_bed", CHERRY_BED_PINK) // RegistryHelper.Blocks.registerMedicalDrawer("oak_medical_drawer", OAK_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("oak_log_medical_drawer", OAK_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_oak_log_medical_drawer", STRIPPED_OAK_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("spruce_medical_drawer", SPRUCE_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("spruce_log_medical_drawer", SPRUCE_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_spruce_log_medical_drawer", STRIPPED_SPRUCE_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("birch_medical_drawer", BIRCH_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("birch_log_medical_drawer", BIRCH_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_birch_log_medical_drawer", STRIPPED_BIRCH_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("jungle_medical_drawer", JUNGLE_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("jungle_log_medical_drawer", JUNGLE_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_jungle_log_medical_drawer", STRIPPED_JUNGLE_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("acacia_medical_drawer", ACACIA_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("acacia_log_medical_drawer", ACACIA_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_acacia_log_medical_drawer", STRIPPED_ACACIA_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("dark_oak_medical_drawer", DARK_OAK_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("dark_oak_log_medical_drawer", DARK_OAK_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_dark_oak_log_medical_drawer", STRIPPED_DARK_OAK_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("mangrove_medical_drawer", MANGROVE_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("mangrove_log_medical_drawer", MANGROVE_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_mangrove_log_medical_drawer", STRIPPED_MANGROVE_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("cherry_medical_drawer", CHERRY_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("cherry_log_medical_drawer", CHERRY_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_cherry_log_medical_drawer", STRIPPED_CHERRY_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("bamboo_medical_drawer", BAMBOO_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("bamboo_block_medical_drawer", BAMBOO_BLOCK_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_bamboo_block_medical_drawer", STRIPPED_BAMBOO_BLOCK_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("warped_medical_drawer", WARPED_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("warped_stem_medical_drawer", WARPED_STEM_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_warped_stem_medical_drawer", STRIPPED_WARPED_STEM_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("crimson_medical_drawer", CRIMSON_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("crimson_stem_medical_drawer", CRIMSON_STEM_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_crimson_stem_medical_drawer", STRIPPED_CRIMSON_STEM_MEDICAL_DRAWER) registerBedsideTable("cherry_bedside_table", CHERRY_BEDSIDE_TABLE) // RegistryHelper.Blocks.registerKitchenDrawer("black_oak_kitchen_drawer", BLACK_OAK_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_oak_kitchen_drawer", WHITE_OAK_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_oak_log_kitchen_drawer", BLACK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_oak_log_kitchen_drawer", WHITE_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_oak_log_kitchen_drawer", BLACK_STRIPPED_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_oak_log_kitchen_drawer", WHITE_STRIPPED_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_spruce_kitchen_drawer", BLACK_SPRUCE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_spruce_kitchen_drawer", WHITE_SPRUCE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_spruce_log_kitchen_drawer", BLACK_SPRUCE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_spruce_log_kitchen_drawer", WHITE_SPRUCE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_spruce_log_kitchen_drawer", BLACK_STRIPPED_SPRUCE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_spruce_log_kitchen_drawer", WHITE_STRIPPED_SPRUCE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_birch_kitchen_drawer", BLACK_BIRCH_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_birch_kitchen_drawer", WHITE_BIRCH_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_birch_log_kitchen_drawer", BLACK_BIRCH_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_birch_log_kitchen_drawer", WHITE_BIRCH_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_birch_log_kitchen_drawer", BLACK_STRIPPED_BIRCH_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_birch_log_kitchen_drawer", WHITE_STRIPPED_BIRCH_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_jungle_kitchen_drawer", BLACK_JUNGLE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_jungle_kitchen_drawer", WHITE_JUNGLE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_jungle_log_kitchen_drawer", BLACK_JUNGLE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_jungle_log_kitchen_drawer", WHITE_JUNGLE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_jungle_log_kitchen_drawer", BLACK_STRIPPED_JUNGLE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_jungle_log_kitchen_drawer", WHITE_STRIPPED_JUNGLE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_acacia_kitchen_drawer", BLACK_ACACIA_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_acacia_kitchen_drawer", WHITE_ACACIA_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_acacia_log_kitchen_drawer", BLACK_ACACIA_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_acacia_log_kitchen_drawer", WHITE_ACACIA_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_acacia_log_kitchen_drawer", BLACK_STRIPPED_ACACIA_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_acacia_log_kitchen_drawer", WHITE_STRIPPED_ACACIA_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_dark_oak_kitchen_drawer", BLACK_DARK_OAK_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_dark_oak_kitchen_drawer", WHITE_DARK_OAK_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_dark_oak_log_kitchen_drawer", BLACK_DARK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_dark_oak_log_kitchen_drawer", WHITE_DARK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_dark_oak_log_kitchen_drawer", BLACK_STRIPPED_DARK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_dark_oak_log_kitchen_drawer", WHITE_STRIPPED_DARK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_mangrove_kitchen_drawer", BLACK_MANGROVE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_mangrove_kitchen_drawer", WHITE_MANGROVE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_mangrove_log_kitchen_drawer", BLACK_MANGROVE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_mangrove_log_kitchen_drawer", WHITE_MANGROVE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_mangrove_log_kitchen_drawer", BLACK_STRIPPED_MANGROVE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_mangrove_log_kitchen_drawer", WHITE_STRIPPED_MANGROVE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_cherry_kitchen_drawer", BLACK_CHERRY_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_cherry_kitchen_drawer", WHITE_CHERRY_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_cherry_log_kitchen_drawer", BLACK_CHERRY_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_cherry_log_kitchen_drawer", WHITE_CHERRY_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_cherry_log_kitchen_drawer", BLACK_STRIPPED_CHERRY_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_cherry_log_kitchen_drawer", WHITE_STRIPPED_CHERRY_LOG_KITCHEN_DRAWER) registerKitchenCabinet("cherry_kitchen_cabinet", CHERRY_KITCHEN_CABINET) registerBlock("white_cherry_sofa", WHITE_CHERRY_SOFA) registerBlock("black_cherry_sofa", BLACK_CHERRY_SOFA) registerBlock("white_oak_lamp", WHITE_OAK_LAMP) registerBlock("black_oak_lamp", BLACK_OAK_LAMP) registerBlock("white_cherry_lamp", WHITE_CHERRY_LAMP) registerBlock("black_cherry_lamp", BLACK_CHERRY_LAMP) registerBlockEntity("carpenter_table_be", CARPENTER_TABLE_BLOCK_ENTITY) registerBlockEntity("medical_drawer_be", MEDICAL_DRAWER_BLOCK_ENTITY) registerBlockEntity("bedside_table_be", BEDSIDE_TABLE_BLOCK_ENTITY) } private fun registerBlock(path: String, block: Block) { ScuroFurnitureBlocksAPI.registerBlock( Identifier(ScuroFurniture.MOD_ID, path), block ) BLOCKS[Identifier(ScuroFurniture.MOD_ID, path)] = block } private fun registerBedsideTable(path: String, block: BedsideTableBlock) { ScuroFurnitureBlocksAPI.registerBedsideTable( Identifier(ScuroFurniture.MOD_ID, path), block ) BLOCKS[Identifier(ScuroFurniture.MOD_ID, path)] = block } private fun registerKitchenCabinet(path: String, block: KitchenCabinetBlock) { ScuroFurnitureBlocksAPI.registerKitchenCabinet( Identifier(ScuroFurniture.MOD_ID, path), block ) BLOCKS[Identifier(ScuroFurniture.MOD_ID, path)] = block } private fun <T : BlockEntity> registerBlockEntity(path: String, blockEntity: BlockEntityType<T>) { Registry.register( Registries.BLOCK_ENTITY_TYPE, Identifier(ScuroFurniture.MOD_ID, path), blockEntity ) } }
0
Kotlin
0
0
9e689b5a62eaca19fea192a376a0d9d1bad390f7
15,027
ScuroFurniture
MIT License
src/main/kotlin/ru/scuroneko/furniture/ModBlocks.kt
ScuroNeko
796,769,478
false
{"Kotlin": 174165}
package ru.scuroneko.furniture import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings import net.minecraft.block.Block import net.minecraft.block.BlockSetType import net.minecraft.block.Blocks import net.minecraft.block.entity.BlockEntity import net.minecraft.block.entity.BlockEntityType import net.minecraft.item.BlockItem import net.minecraft.item.Item import net.minecraft.registry.Registries import net.minecraft.registry.Registry import net.minecraft.util.DyeColor import net.minecraft.util.Identifier import ru.scuroneko.furniture.api.ScuroFurnitureBlocksAPI import ru.scuroneko.furniture.api.blocks.AbstractDrawerBlock import ru.scuroneko.furniture.blocks.* import ru.scuroneko.furniture.blocks.entity.BedsideTableBlockEntity import ru.scuroneko.furniture.blocks.entity.CarpenterTableBlockEntity import ru.scuroneko.furniture.blocks.entity.MedicalDrawerBlockEntity import ru.scuroneko.furniture.registry.RegistryHelper import ru.scuroneko.furniture.registry.blocks.MedicalDrawers import ru.scuroneko.furniture.registry.items.MedicalDrawersComponents object ModBlocks { val BLOCKS = LinkedHashMap<Identifier, Block>() val BEDSIDE_TABLES = LinkedHashMap<Identifier, AbstractDrawerBlock>() val BEDSIDE_TABLES_ITEMS = LinkedHashMap<Identifier, Item>() val KITCHEN_CABINETS = LinkedHashMap<Identifier, KitchenCabinetBlock>() val KITCHEN_CABINETS_ITEMS = LinkedHashMap<Identifier, Item>() val CARPENTER_TABLE = CarpenterTableBlock(FabricBlockSettings.copy(Blocks.CRAFTING_TABLE)) val AIRTIGHT_DOOR = AirtightDoorBlock(BlockSetType.IRON, FabricBlockSettings.copy(Blocks.IRON_DOOR)) val CHERRY_BED_PURPLE = CustomBedBlock(DyeColor.PURPLE, FabricBlockSettings.copy(Blocks.PURPLE_BED)) val CHERRY_BED_PINK = CustomBedBlock(DyeColor.PINK, FabricBlockSettings.copy(Blocks.PINK_BED)) val CHERRY_BEDSIDE_TABLE = BedsideTableBlock( MedicalDrawersComponents.CHERRY_MEDICAL_DRAWER_CASE, MedicalDrawersComponents.CHERRY_MEDICAL_BOX ) val CHERRY_KITCHEN_CABINET = KitchenCabinetBlock( MedicalDrawersComponents.CHERRY_MEDICAL_DRAWER_CASE, MedicalDrawersComponents.CHERRY_MEDICAL_BOX ) val WHITE_CHERRY_SOFA = SofaBlock( Blocks.CHERRY_PLANKS, Blocks.STRIPPED_CHERRY_LOG, Blocks.WHITE_WOOL ) val BLACK_CHERRY_SOFA = SofaBlock( Blocks.CHERRY_PLANKS, Blocks.STRIPPED_CHERRY_LOG, Blocks.BLACK_WOOL ) val WHITE_OAK_LAMP = LampBlock(FabricBlockSettings.copy(Blocks.WHITE_WOOL)) val BLACK_OAK_LAMP = LampBlock(FabricBlockSettings.copy(Blocks.BLACK_WOOL)) val WHITE_CHERRY_LAMP = LampBlock(FabricBlockSettings.copy(Blocks.WHITE_WOOL)) val BLACK_CHERRY_LAMP = LampBlock(FabricBlockSettings.copy(Blocks.BLACK_WOOL)) val CARPENTER_TABLE_BLOCK_ENTITY = BlockEntityType.Builder.create(::CarpenterTableBlockEntity, CARPENTER_TABLE).build() val MEDICAL_DRAWER_BLOCK_ENTITY = BlockEntityType.Builder.create(::MedicalDrawerBlockEntity, MedicalDrawers.OAK_MEDICAL_DRAWER).build() val BEDSIDE_TABLE_BLOCK_ENTITY = BlockEntityType.Builder.create(::BedsideTableBlockEntity, CHERRY_BEDSIDE_TABLE).build() fun register() { registerBlock("carpenter_table", CARPENTER_TABLE) registerBlock("airtight_door", AIRTIGHT_DOOR) registerBlock("purple_cherry_bed", CHERRY_BED_PURPLE) registerBlock("pink_cherry_bed", CHERRY_BED_PINK) // RegistryHelper.Blocks.registerMedicalDrawer("oak_medical_drawer", OAK_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("oak_log_medical_drawer", OAK_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_oak_log_medical_drawer", STRIPPED_OAK_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("spruce_medical_drawer", SPRUCE_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("spruce_log_medical_drawer", SPRUCE_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_spruce_log_medical_drawer", STRIPPED_SPRUCE_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("birch_medical_drawer", BIRCH_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("birch_log_medical_drawer", BIRCH_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_birch_log_medical_drawer", STRIPPED_BIRCH_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("jungle_medical_drawer", JUNGLE_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("jungle_log_medical_drawer", JUNGLE_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_jungle_log_medical_drawer", STRIPPED_JUNGLE_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("acacia_medical_drawer", ACACIA_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("acacia_log_medical_drawer", ACACIA_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_acacia_log_medical_drawer", STRIPPED_ACACIA_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("dark_oak_medical_drawer", DARK_OAK_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("dark_oak_log_medical_drawer", DARK_OAK_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_dark_oak_log_medical_drawer", STRIPPED_DARK_OAK_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("mangrove_medical_drawer", MANGROVE_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("mangrove_log_medical_drawer", MANGROVE_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_mangrove_log_medical_drawer", STRIPPED_MANGROVE_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("cherry_medical_drawer", CHERRY_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("cherry_log_medical_drawer", CHERRY_LOG_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_cherry_log_medical_drawer", STRIPPED_CHERRY_LOG_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("bamboo_medical_drawer", BAMBOO_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("bamboo_block_medical_drawer", BAMBOO_BLOCK_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_bamboo_block_medical_drawer", STRIPPED_BAMBOO_BLOCK_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("warped_medical_drawer", WARPED_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("warped_stem_medical_drawer", WARPED_STEM_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_warped_stem_medical_drawer", STRIPPED_WARPED_STEM_MEDICAL_DRAWER) // // RegistryHelper.Blocks.registerMedicalDrawer("crimson_medical_drawer", CRIMSON_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("crimson_stem_medical_drawer", CRIMSON_STEM_MEDICAL_DRAWER) // RegistryHelper.Blocks.registerMedicalDrawer("stripped_crimson_stem_medical_drawer", STRIPPED_CRIMSON_STEM_MEDICAL_DRAWER) registerBedsideTable("cherry_bedside_table", CHERRY_BEDSIDE_TABLE) // RegistryHelper.Blocks.registerKitchenDrawer("black_oak_kitchen_drawer", BLACK_OAK_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_oak_kitchen_drawer", WHITE_OAK_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_oak_log_kitchen_drawer", BLACK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_oak_log_kitchen_drawer", WHITE_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_oak_log_kitchen_drawer", BLACK_STRIPPED_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_oak_log_kitchen_drawer", WHITE_STRIPPED_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_spruce_kitchen_drawer", BLACK_SPRUCE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_spruce_kitchen_drawer", WHITE_SPRUCE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_spruce_log_kitchen_drawer", BLACK_SPRUCE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_spruce_log_kitchen_drawer", WHITE_SPRUCE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_spruce_log_kitchen_drawer", BLACK_STRIPPED_SPRUCE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_spruce_log_kitchen_drawer", WHITE_STRIPPED_SPRUCE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_birch_kitchen_drawer", BLACK_BIRCH_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_birch_kitchen_drawer", WHITE_BIRCH_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_birch_log_kitchen_drawer", BLACK_BIRCH_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_birch_log_kitchen_drawer", WHITE_BIRCH_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_birch_log_kitchen_drawer", BLACK_STRIPPED_BIRCH_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_birch_log_kitchen_drawer", WHITE_STRIPPED_BIRCH_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_jungle_kitchen_drawer", BLACK_JUNGLE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_jungle_kitchen_drawer", WHITE_JUNGLE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_jungle_log_kitchen_drawer", BLACK_JUNGLE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_jungle_log_kitchen_drawer", WHITE_JUNGLE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_jungle_log_kitchen_drawer", BLACK_STRIPPED_JUNGLE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_jungle_log_kitchen_drawer", WHITE_STRIPPED_JUNGLE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_acacia_kitchen_drawer", BLACK_ACACIA_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_acacia_kitchen_drawer", WHITE_ACACIA_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_acacia_log_kitchen_drawer", BLACK_ACACIA_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_acacia_log_kitchen_drawer", WHITE_ACACIA_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_acacia_log_kitchen_drawer", BLACK_STRIPPED_ACACIA_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_acacia_log_kitchen_drawer", WHITE_STRIPPED_ACACIA_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_dark_oak_kitchen_drawer", BLACK_DARK_OAK_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_dark_oak_kitchen_drawer", WHITE_DARK_OAK_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_dark_oak_log_kitchen_drawer", BLACK_DARK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_dark_oak_log_kitchen_drawer", WHITE_DARK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_dark_oak_log_kitchen_drawer", BLACK_STRIPPED_DARK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_dark_oak_log_kitchen_drawer", WHITE_STRIPPED_DARK_OAK_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_mangrove_kitchen_drawer", BLACK_MANGROVE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_mangrove_kitchen_drawer", WHITE_MANGROVE_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_mangrove_log_kitchen_drawer", BLACK_MANGROVE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_mangrove_log_kitchen_drawer", WHITE_MANGROVE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_mangrove_log_kitchen_drawer", BLACK_STRIPPED_MANGROVE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_mangrove_log_kitchen_drawer", WHITE_STRIPPED_MANGROVE_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_cherry_kitchen_drawer", BLACK_CHERRY_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_cherry_kitchen_drawer", WHITE_CHERRY_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_cherry_log_kitchen_drawer", BLACK_CHERRY_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_cherry_log_kitchen_drawer", WHITE_CHERRY_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("black_stripped_cherry_log_kitchen_drawer", BLACK_STRIPPED_CHERRY_LOG_KITCHEN_DRAWER) // RegistryHelper.Blocks.registerKitchenDrawer("white_stripped_cherry_log_kitchen_drawer", WHITE_STRIPPED_CHERRY_LOG_KITCHEN_DRAWER) registerKitchenCabinet("cherry_kitchen_cabinet", CHERRY_KITCHEN_CABINET) registerBlock("white_cherry_sofa", WHITE_CHERRY_SOFA) registerBlock("black_cherry_sofa", BLACK_CHERRY_SOFA) registerBlock("white_oak_lamp", WHITE_OAK_LAMP) registerBlock("black_oak_lamp", BLACK_OAK_LAMP) registerBlock("white_cherry_lamp", WHITE_CHERRY_LAMP) registerBlock("black_cherry_lamp", BLACK_CHERRY_LAMP) registerBlockEntity("carpenter_table_be", CARPENTER_TABLE_BLOCK_ENTITY) registerBlockEntity("medical_drawer_be", MEDICAL_DRAWER_BLOCK_ENTITY) registerBlockEntity("bedside_table_be", BEDSIDE_TABLE_BLOCK_ENTITY) } private fun registerBlock(path: String, block: Block) { ScuroFurnitureBlocksAPI.registerBlock( Identifier(ScuroFurniture.MOD_ID, path), block ) BLOCKS[Identifier(ScuroFurniture.MOD_ID, path)] = block } private fun registerBedsideTable(path: String, block: BedsideTableBlock) { ScuroFurnitureBlocksAPI.registerBedsideTable( Identifier(ScuroFurniture.MOD_ID, path), block ) BLOCKS[Identifier(ScuroFurniture.MOD_ID, path)] = block } private fun registerKitchenCabinet(path: String, block: KitchenCabinetBlock) { ScuroFurnitureBlocksAPI.registerKitchenCabinet( Identifier(ScuroFurniture.MOD_ID, path), block ) BLOCKS[Identifier(ScuroFurniture.MOD_ID, path)] = block } private fun <T : BlockEntity> registerBlockEntity(path: String, blockEntity: BlockEntityType<T>) { Registry.register( Registries.BLOCK_ENTITY_TYPE, Identifier(ScuroFurniture.MOD_ID, path), blockEntity ) } }
0
Kotlin
0
0
9e689b5a62eaca19fea192a376a0d9d1bad390f7
15,027
ScuroFurniture
MIT License
plugins/ksp/testData/api/resolveJavaType.kt
android
263,405,600
false
null
// TEST PROCESSOR: ResolveJavaTypeProcessor // EXPECTED: // kotlin.Int // kotlin.String? // kotlin.IntArray? // C.T? // C.PFun.P? // kotlin.collections.MutableList<out kotlin.collections.MutableSet<kotlin.Double?>?>? // kotlin.collections.MutableList<in kotlin.collections.MutableList<out kotlin.Double?>?>? // Bar? // kotlin.Array<Bar?>? // END // FILE: a.kt annotation class Test @Test class Foo<P>: C<P>() { } class Bar // FILE: C.java import java.util.List; import java.util.Set; public class C<T> { public int intFun() {} public String strFun() {} public int[] intArrayFun() {} public T TFoo() {} public <P> P PFun() {} public List<? extends Set<Double>> extendsSetFun() {} public List<? super List<? extends Double>> extendsListTFun() {} public Bar BarFun() {} public Bar[] BarArryFun() {} }
1
null
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
845
kotlin
Apache License 2.0
app/src/main/java/uk/nhs/nhsx/sonar/android/app/registration/RegistrationManager.kt
nhsx
261,523,644
false
null
/* * Copyright © 2020 NHSX. All rights reserved. */ package uk.nhs.nhsx.sonar.android.app.registration import android.content.Context import androidx.annotation.VisibleForTesting import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.work.BackoffPolicy import androidx.work.Constraints import androidx.work.ExistingWorkPolicy import androidx.work.NetworkType import androidx.work.OneTimeWorkRequest import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkRequest.MIN_BACKOFF_MILLIS import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import timber.log.Timber import uk.nhs.nhsx.sonar.android.app.ble.BluetoothService import uk.nhs.nhsx.sonar.android.app.di.module.AppModule import uk.nhs.nhsx.sonar.android.app.registration.RegistrationWorker.Companion.WAITING_FOR_ACTIVATION_CODE import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton import kotlin.coroutines.CoroutineContext @Singleton class RegistrationManager @Inject constructor( private val context: Context, private val workManager: WorkManager, @Named(AppModule.DISPATCHER_MAIN) private val dispatcher: CoroutineDispatcher, private val activationCodeWaitTime: ActivationCodeWaitTime ) : CoroutineScope { private var previousWorkInfoLiveData: LiveData<WorkInfo>? = null private val observer = Observer<WorkInfo> { workInfo -> handleWorkInfo(workInfo) } fun register( initialDelayValue: Long = 0, initialDelayTimeUnit: TimeUnit = TimeUnit.SECONDS ) { // Need it for the thread confinement and LiveData can be observed on the Main Thread only launch { Timber.tag("RegistrationUseCase") .d("register initialDelaySeconds = $initialDelayValue") val registrationWorkRequest = createWorkRequest(initialDelayValue, initialDelayTimeUnit) workManager.enqueueUniqueWork( REGISTRATION_WORK, ExistingWorkPolicy.REPLACE, registrationWorkRequest ) previousWorkInfoLiveData?.removeObserver(observer) val workInfoLiveData = workManager.getWorkInfoByIdLiveData(registrationWorkRequest.id) workInfoLiveData.observeForever(observer) previousWorkInfoLiveData = workInfoLiveData } } private fun handleWorkInfo(workInfo: WorkInfo?) { if (workInfo == null) { return } if (workInfo.state == WorkInfo.State.SUCCEEDED) { val waitingForActivationCode = workInfo.outputData.getBoolean(WAITING_FOR_ACTIVATION_CODE, false) if (waitingForActivationCode) { scheduleRegisterRetryAfterActivationCodeWaitTimeExpires() } else { BluetoothService.start(context) } } } private fun scheduleRegisterRetryAfterActivationCodeWaitTimeExpires() { register( activationCodeWaitTime.timeDelay, activationCodeWaitTime.timeUnit ) } @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) fun createWorkRequest( initialDelaySeconds: Long, initialDelayTimeUnit: TimeUnit ): OneTimeWorkRequest { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() return OneTimeWorkRequestBuilder<RegistrationWorker>() .setConstraints(constraints) .setInitialDelay(initialDelaySeconds, initialDelayTimeUnit) .setBackoffCriteria( BackoffPolicy.EXPONENTIAL, MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS ) .build() } override val coroutineContext: CoroutineContext get() = (dispatcher + Job()) companion object { const val REGISTRATION_WORK = "registration" } }
0
Kotlin
146
793
ebcb3221b89333d9f555592aebc934d06608d784
4,136
COVID-19-app-Android-BETA
MIT License
livingdoc-repositories/src/main/kotlin/org/livingdoc/repositories/config/RepositoryDefinition.kt
LivingDoc
85,412,044
false
null
package org.livingdoc.repositories.config import org.livingdoc.repositories.DocumentRepository /** * A RepositoryDefinition describes a single [DocumentRepository] inside a [RepositoryConfiguration]. * * @see DocumentRepository * @see RepositoryConfiguration */ data class RepositoryDefinition( var name: String = "default", var factory: String? = null, var config: Map<String, Any> = emptyMap() )
34
null
16
14
f3d52b8bacbdf81905e4b4a753d75f584329b297
417
livingdoc
Apache License 2.0
app/src/main/java/com/zacharee1/systemuituner/services/Manager.kt
zacharee
221,786,635
false
{"Kotlin": 681812, "AIDL": 1172}
package com.zacharee1.systemuituner.services import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.ServiceInfo import android.database.ContentObserver import android.net.Uri import android.os.Build import android.os.IBinder import android.provider.Settings import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat import com.zacharee1.systemuituner.IManager import com.zacharee1.systemuituner.R import com.zacharee1.systemuituner.data.SettingsType import com.zacharee1.systemuituner.util.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock //TODO: something weird is going on here where some settings are overridden incorrectly when first enabled as persistent. //TODO: Figure it out? class Manager : Service(), SharedPreferences.OnSharedPreferenceChangeListener, CoroutineScope by MainScope() { companion object { const val NOTIFICATION_CHANNEL_ID = "manager_service" } private val observer = Observer() private val mutexMutex = Mutex() private val mutexes = HashMap<Pair<SettingsType, String>, Mutex>() override fun onBind(intent: Intent?): IBinder { return ManagerImpl() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { when (key) { PrefManager.PERSISTENT_OPTIONS -> { launch { observer.unregister() doInitialCheck() observer.register() } } } } override fun onCreate() { super.onCreate() prefManager.prefs.registerOnSharedPreferenceChangeListener(this) launch { try { doInitialCheck() } catch (_: IllegalStateException) {} observer.register() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager manager.createNotificationChannel( NotificationChannel( NOTIFICATION_CHANNEL_ID, resources.getString(R.string.manager_channel), NotificationManager.IMPORTANCE_LOW ) ) val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setContentTitle(resources.getText(R.string.app_name)) .setContentText(resources.getText(R.string.tap_to_disable)) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent( PendingIntent.getActivity( this, 100, getNotificationSettingsForChannel( NOTIFICATION_CHANNEL_ID ), PendingIntent.FLAG_IMMUTABLE, ) ) .build() try { ServiceCompat.startForeground(this, 1000, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) } catch (e: RuntimeException) { BugsnagUtils.notify(IllegalStateException( "Manager service failed to start in foreground. Stopping. (Can draw overlays: ${Settings.canDrawOverlays(this)})", e, )) stopSelf() } } } override fun onDestroy() { super.onDestroy() cancel() observer.unregister() prefManager.prefs.unregisterOnSharedPreferenceChangeListener(this) } private suspend fun doInitialCheck() { prefManager.persistentOptions.forEach { opt -> if (opt.type != SettingsType.UNDEFINED) { runComparison(opt.type, opt.key, true) } } } private suspend fun runComparison(type: SettingsType, key: String, isInitialSetup: Boolean = false) { val mutex = mutexMutex.withLock { mutexes[type to key] ?: Mutex().apply { mutexes[type to key] = this } } mutex.withLock { val handler = PersistenceHandlerRegistry.handlers.find { it.settingsKey == key && it.settingsType == type } if (handler != null) { val prefValue = handler.getPreferenceValueAsString() if (isInitialSetup) { handler.doInitialSet() } if (!handler.compareValues()) { writeSetting(type, key, prefValue) } } else { val value = try { getSetting(type, key) } catch (e: IllegalStateException) { Log.e("SystemUITuner", "A persistent option has an undefined settings type. Please clear app data.", e) return } val prefValue = prefManager.findOption(type, key)?.value if (isInitialSetup || value != prefValue) { if (isInitialSetup) { writeSetting(type, key, null) } writeSetting(type, key, prefValue) } } } } inner class ManagerImpl : IManager.Stub() inner class Observer : ContentObserver(mainHandler) { fun register() { unregister() prefManager.persistentOptions.forEach { val uri = when (it.type) { SettingsType.GLOBAL -> Settings.Global.getUriFor(it.key) SettingsType.SECURE -> Settings.Secure.getUriFor(it.key) SettingsType.SYSTEM -> Settings.System.getUriFor(it.key) else -> return@forEach } contentResolver.registerContentObserver(uri, true, this@Observer) } } fun unregister() { try { contentResolver.unregisterContentObserver(this) } catch (_: Exception) {} } override fun onChange(selfChange: Boolean, uri: Uri) { val type = SettingsType.fromString(uri.pathSegments.run { this[lastIndex - 1] }) val key = uri.lastPathSegment launch { runComparison(type, key) } } } }
29
Kotlin
174
994
27672d3a0ad7caf1dce360dc1a0651926903b8a8
6,708
Tweaker
MIT License
ui-home/src/test/java/dev/sasikanth/twine/home/util/PagingTestUtil.kt
msasikanth
516,650,081
false
{"Kotlin": 364930}
package dev.sasikanth.twine.home.util import androidx.paging.DifferCallback import androidx.paging.NullPaddedList import androidx.paging.PagingData import androidx.paging.PagingDataDiffer internal suspend fun <T : Any> PagingData<T>.collectDataForTest(): List<T> { val differCallback = object : DifferCallback { override fun onChanged(position: Int, count: Int) {} override fun onInserted(position: Int, count: Int) {} override fun onRemoved(position: Int, count: Int) {} } val items = mutableListOf<T>() val differ = object : PagingDataDiffer<T>( differCallback = differCallback ) { override suspend fun presentNewList( previousList: NullPaddedList<T>, newList: NullPaddedList<T>, lastAccessedIndex: Int, onListPresentable: () -> Unit ): Int? { for (i in 0 until newList.size) { items.add(newList.getFromStorage(i)) } onListPresentable() return null } } differ.collectFrom(this) return items }
1
Kotlin
0
27
6c259de1a818da155a29a3837a85326e1b132955
997
tweet-unroll-android
Apache License 2.0
idea/testData/intentions/branched/ifThenToSafeAccess/doesNotinlineValueIfUsedMoreThanOnce.kt
gigliovale
89,726,097
false
null
fun maybeFoo(): String? { return "foo" } fun doSomething<T>(a: T) {} fun main(args: Array<String>) { val foo = maybeFoo() doSomething(foo) if (foo != null<caret>) { foo.length } else { null } }
0
null
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
240
kotlin
Apache License 2.0
app-client-web/src/main/kotlin/StatisticsComponent.kt
smal-sergey
277,090,015
false
null
import com.smalser.common.Game import com.smalser.common.Statistics import kotlinx.css.* import kotlinx.css.properties.border import kotlinx.css.properties.borderBottom import kotlinx.css.properties.borderLeft import react.* import react.dom.* import styled.* object TableStyles : StyleSheet("TableStyles") { val table by css { border(width = 1.px, style = BorderStyle.solid, color = Color("#1C6EA4")) backgroundColor = Color("#EEEEEE") width = 100.pct textAlign = TextAlign.left borderCollapse = BorderCollapse.collapse listOf(td, th).forEach { it { border(width = 1.px, style = BorderStyle.solid, color = Color("#AAAAAA")) padding(3.px, 8.px) } } thead { backgroundColor = Color("#1C6EA4") borderBottom(width = 2.px, style = BorderStyle.solid, color = Color("#444444")) } listOf(thead, th).forEach { it { fontSize = 15.px fontWeight = FontWeight.bold color = Color("#FFFFFF") textAlign = TextAlign.center borderLeft(width = 2.px, style = BorderStyle.solid, color = Color("#D0E4F5")) } firstChild { borderLeft = "none" } } } } interface StatisticsProps : RProps { var currentGame: Game var statistics: Statistics } interface StatisticsState : RState { } class StatisticsComponent : RComponent<StatisticsProps, StatisticsState>() { override fun StatisticsState.init() { } override fun RBuilder.render() { styledDiv { css { margin(10.px) } styledTable { css { +TableStyles.table } thead { tr { th { +"Rang" } th { +"Name" } th { +"Rating" } th { +"Won" } th { +"Lost" } // th { +"SessionId" } } } tbody { props.statistics.games.forEachIndexed { idx, game -> val isCurrentGame = game.sessionId == props.currentGame.sessionId if (isCurrentGame || idx < 5) { styledTr { css { fontWeight = if(isCurrentGame) FontWeight.bold else FontWeight.normal } td { +"${idx + 1}" } td { +game.name } td { +game.rating.format(2) } td { +"${game.won}" } td { +"${game.lost}" } // td { +game.sessionId } } } } } } } } } fun RBuilder.statistics(handler: StatisticsProps.() -> Unit): ReactElement { return child(StatisticsComponent::class) { attrs(handler) } } fun Double.format(digits: Int): String = this.asDynamic().toFixed(digits)
0
Kotlin
0
0
a243f833935cc9387583029e979960939909f41a
3,320
kotlin-multiplatform-example
Apache License 2.0
feature/player/src/main/kotlin/dev/dexsr/klio/player/shared/PlaybackMediaDescription.kt
flammky
462,795,948
false
{"Kotlin": 5222947}
package dev.dexsr.klio.library.shared import dev.dexsr.klio.base.UNSET data class PlaybackMediaDescription( val title: String?, val subtitle: String? ): UNSET<PlaybackMediaDescription> by Companion { companion object : UNSET<PlaybackMediaDescription> { override val UNSET: PlaybackMediaDescription = PlaybackMediaDescription( title = null, subtitle = null, ) } }
0
Kotlin
6
56
a452c453815851257462623be704559d306fb383
423
Music-Player
Apache License 2.0
src/test/kotlin/me/grison/aoc/y2022/AllDaysTest.kt
agrison
315,292,447
false
null
package me.grison.aoc.y2022 import me.grison.aoc.Day import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.Is.`is` import org.junit.jupiter.api.DynamicTest import org.junit.jupiter.api.TestFactory data class Answer(val inst: () -> Day, val part1: Any, val part2: Any) class AllDaysTest { @TestFactory fun answers() = listOf( Answer({ Day01() }, 71502, 208191), Answer({ Day02() }, 9651, 10560), Answer({ Day03() }, 7553, 2758), Answer({ Day04() }, 450, 837), Answer({ Day05() }, "MQTPGLLDN", "LVZPSTTCZ"), Answer({ Day06() }, 1080, 3645), Answer({ Day07() }, 1582412, 3696336), Answer({ Day08() }, 1763, 671160), Answer({ Day09() }, 6026, 2273), Answer({ Day10() }, 12980, "BRJLFULP"), Answer({ Day11() }, 76728, 21553910156), Answer({ Day12() }, 391, 386), Answer({ Day13() }, 5292, 23868), Answer({ Day14() }, 843, 27625), Answer({ Day15() }, 5688618, 12625383204261), //Answer({ Day16() }, 1653, 2223), This is commented because my solution is slow, part 2 taking 18 sec on my PC ).map { val day = it.inst.invoke() DynamicTest.dynamicTest("Day ${day.year}/${day.dayNumber} - Part 1 - expecting ${it.part1}") { assertThat(day.partOne(), `is`(it.part1)) } DynamicTest.dynamicTest("Day ${day.year}/${day.dayNumber} - Part 2 - expecting ${it.part2}") { assertThat( if (day.dayNumber < 25) day.partTwo() else "Merry Christmas!", `is`(it.part2) ) } } }
0
Kotlin
4
20
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
1,622
advent-of-code
Creative Commons Zero v1.0 Universal
src/commonTest/kotlin/serialize/task/TestTaskStatus.kt
nuhkoca
222,564,952
true
{"Kotlin": 956270, "Ruby": 4462}
package serialize.task import com.algolia.search.model.task.TaskStatus import kotlinx.serialization.json.JsonLiteral import serialize.TestSerializer import unknown internal class TestTaskStatus : TestSerializer<TaskStatus>(TaskStatus) { override val items = listOf( TaskStatus.Published to JsonLiteral(TaskStatus.Published.raw), TaskStatus.NotPublished to JsonLiteral(TaskStatus.NotPublished.raw), TaskStatus.Other(unknown) to JsonLiteral(unknown) ) }
0
null
0
0
ffbc7a8b16f9544df2e02cca5206420724f7d3c5
487
algoliasearch-client-kotlin
MIT License
confluence-plugin/src/main/java/com/networkedassets/git4c/boundary/GetPredefinedRepositoryBranchesResultRequest.kt
rpaasche
321,741,515
true
{"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716}
package com.networkedassets.git4c.boundary import com.networkedassets.git4c.boundary.outbound.Branches import com.networkedassets.git4c.core.usecase.async.BackendRequestForAsyncResult class GetPredefinedRepositoryBranchesResultRequest(requestId: String) : BackendRequestForAsyncResult<Branches>(requestId)
0
Kotlin
0
0
e55391b33cb70d66bbf5f36ba570fb8822f10953
308
git4c
Apache License 2.0
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/groupHunting/dto/GroupHuntingDiaryDTO.kt
suomenriistakeskus
78,840,058
false
{"Gradle": 4, "Java Properties": 2, "Shell": 2, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 4, "Gradle Kotlin DSL": 1, "Kotlin": 1344, "XML": 401, "Java": 161, "Protocol Buffer": 1, "JSON": 1}
package fi.riista.common.domain.groupHunting.dto import fi.riista.common.domain.groupHunting.model.GroupHuntingDiary import kotlinx.serialization.Serializable @Serializable data class GroupHuntingDiaryDTO( val harvests: List<GroupHuntingHarvestDTO>, val observations: List<GroupHuntingObservationDTO>, val rejectedHarvests: List<GroupHuntingHarvestDTO>, val rejectedObservations: List<GroupHuntingObservationDTO>, ) internal fun GroupHuntingDiaryDTO.toGroupHuntingDiary(): GroupHuntingDiary { return GroupHuntingDiary( harvests = harvests.mapNotNull { it.toGroupHuntingHarvest() }, observations = observations.mapNotNull { it.toGroupHuntingObservation() }, rejectedHarvests = rejectedHarvests.mapNotNull { it.toGroupHuntingHarvest()?.copy(rejected = true) }, rejectedObservations = rejectedObservations.mapNotNull { it.toGroupHuntingObservation()?.copy(rejected = true) }, ) }
0
Kotlin
0
3
23645d1abe61c68d649b6d0ca1d16556aa8ffa16
936
oma-riista-android
MIT License
app/src/main/java/com/z299studio/pbfree/DetailFragment.kt
zhuqianqian
24,934,090
false
null
package com.z299studio.pbfree import android.os.Bundle import android.view.* import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.z299studio.pbfree.adapters.ValueListAdapter import com.z299studio.pbfree.data.AccountRepository import com.z299studio.pbfree.databinding.FragmentDetailBinding import com.z299studio.pbfree.viewmodels.ItemViewModel class DetailFragment : Fragment() { private var _binding: FragmentDetailBinding? = null private val binding get() = _binding!! private val itemViewModel: ItemViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDetailBinding.inflate(inflater, container, false) setHasOptionsMenu(true) val root: View = binding.root itemViewModel.from(itemViewModel.index) binding.list.layoutManager = LinearLayoutManager(context) binding.list.adapter = ValueListAdapter(itemViewModel.values.value!!) return root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.clear() activity?.menuInflater?.inflate(R.menu.detail, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_delete -> { AlertDialog.Builder(requireContext()).setTitle(R.string.action_delete) .setMessage(R.string.delete_ask) .setNegativeButton(android.R.string.cancel) {_, _ -> } .setPositiveButton(android.R.string.ok) { _, _ -> AccountRepository.get().delete(itemViewModel.index) AccountRepository.get().saveData(requireContext()) activity?.onBackPressed() } .show() } R.id.action_edit -> { findNavController().navigate(DetailFragmentDirections.action2Edit()) return true } } return super.onOptionsItemSelected(item) } }
1
null
13
22
73823d7865cf4e52436ec5950cf9f695104a0941
2,427
Passbook
Apache License 2.0
components-compose/src/main/java/uk/gov/hmrc/components/compose/ui/theme/Theme.kt
hmrc
299,591,950
false
null
/* * Copyright 2023 HM Revenue & Customs * * 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 uk.gov.hmrc.components.compose.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.ripple.RippleAlpha import androidx.compose.material.ripple.RippleTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.TextFieldColors import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity private val LightColorPalette = HmrcColors( hmrcBlack = HmrcBlack, hmrcWhite = HmrcWhite, hmrcWhiteBackground = HmrcWhiteBackground, hmrcGreen1 = HmrcGreen1, hmrcGreen2 = HmrcGreen2, hmrcBlue = HmrcBlue, hmrcTeal = HmrcTeal, hmrcRed = HmrcRed, hmrcGrey1 = HmrcGrey1, hmrcGrey2 = HmrcGrey2, hmrcGrey3 = HmrcGrey3, hmrcPink = HmrcPink, hmrcYellow = HmrcYellow, isDark = false ) private val DarkColorPalette = HmrcColors( hmrcBlack = HmrcBlackDark, hmrcWhite = HmrcWhiteDark, hmrcWhiteBackground = HmrcWhiteBackgroundDark, hmrcGreen1 = HmrcGreen1Dark, hmrcGreen2 = HmrcGreen2Dark, hmrcBlue = HmrcBlueDark, hmrcTeal = HmrcTeal, hmrcRed = HmrcRedDark, hmrcGrey1 = HmrcGrey1Dark, hmrcGrey2 = HmrcGrey2Dark, hmrcGrey3 = HmrcGrey3Dark, hmrcPink = HmrcPinkDark, hmrcYellow = HmrcYellowDark, isDark = true ) @Composable fun HmrcTheme( windowSizeClass: WindowSizeClass = rememberWindowSizeClass(), darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) DarkColorPalette else LightColorPalette // check orientation val orientation = when { windowSizeClass.width.size > windowSizeClass.height.size -> Orientation.Landscape else -> Orientation.Portrait } val sizeThatMatters = when (orientation) { Orientation.Portrait -> windowSizeClass.width else -> windowSizeClass.height } val dimensions = when (sizeThatMatters) { is WindowSize.Small -> smallDimensions is WindowSize.Medium -> mediumDimensions is WindowSize.Compact -> compactDimensions else -> largeDimensions } val hmrcTypography = HmrcTypography( hmrcBlack = colors.hmrcBlack, hmrcGrey1 = colors.hmrcGrey1, hmrcRed = colors.hmrcRed ) // We can define the different typography of different sizes screen val typography = when (sizeThatMatters) { is WindowSize.Small -> hmrcTypography is WindowSize.Medium -> hmrcTypography is WindowSize.Compact -> hmrcTypography else -> hmrcTypography } val textInputViewColors: TextFieldColors = OutlinedTextFieldDefaults.colors( focusedTextColor = HmrcBlack, unfocusedTextColor = HmrcBlack, errorTextColor = HmrcRed, errorLeadingIconColor = HmrcRed, errorTrailingIconColor = HmrcRed, focusedLabelColor = HmrcBlue, unfocusedLabelColor = HmrcBlack, focusedBorderColor = HmrcBlue, errorBorderColor = HmrcRed, unfocusedBorderColor = HmrcBlack, errorSupportingTextColor = HmrcRed, focusedSupportingTextColor = HmrcBlack, errorLabelColor = HmrcRed ) ProvideHmrcTheme( dimensions = dimensions, orientation = orientation, colors = colors, textFieldColors = textInputViewColors, typography = typography ) { MaterialTheme( shapes = Shapes, content = content ) } } object HmrcTheme { val colors: HmrcColors @Composable get() = LocalHmrcColors.current val textFieldColors: TextFieldColors @Composable get() = LocalTextFieldColors.current val typography: HmrcTypography @Composable get() = LocalHmrcTypography.current val dimensions: Dimensions @Composable get() = LocalAppDimens.current val orientation: Orientation @Composable get() = LocalOrientationMode.current val fontScale: Float @Composable get() = LocalDensity.current.fontScale } object HmrcRippleTheme : RippleTheme { @Composable override fun defaultColor() = HmrcTheme.colors.hmrcBlue @Composable override fun rippleAlpha(): RippleAlpha = RippleAlpha( draggedAlpha = 0.24f, focusedAlpha = 0.40f, hoveredAlpha = 0.40f, pressedAlpha = 0.24f ) } /** * HMRC custom Color Palette */ @Stable @SuppressWarnings("LongParameterList") class HmrcColors( hmrcBlack: Color, hmrcWhite: Color, hmrcWhiteBackground: Color, hmrcGreen1: Color, hmrcGreen2: Color, hmrcBlue: Color, hmrcTeal: Color, hmrcRed: Color, hmrcGrey1: Color, hmrcGrey2: Color, hmrcGrey3: Color, hmrcPink: Color, hmrcYellow: Color, hmrcErrorText: Color = hmrcRed, hmrcDarkText: Color = hmrcBlack, hmrcLightText: Color = hmrcWhite, hmrcLinkText: Color = hmrcBlue, hmrcInfoText: Color = hmrcGrey1, hmrcPageBackground: Color = hmrcGrey3, hmrcDivider: Color = hmrcGrey2, hmrcInsetBar: Color = hmrcGrey2, hmrcInfoMessageWarningHeadlineBackground: Color = hmrcYellow, hmrcInfoMessageInfoHeadlineBackground: Color = hmrcBlue, hmrcInfoMessageUrgentHeadlineBackground: Color = hmrcRed, hmrcInfoMessageNoticeHeadlineBackground: Color = hmrcBlack, isDark: Boolean ) { var hmrcBlack by mutableStateOf(hmrcBlack) private set var hmrcWhite by mutableStateOf(hmrcWhite) private set var hmrcWhiteBackground by mutableStateOf(hmrcWhiteBackground) private set var hmrcGreen1 by mutableStateOf(hmrcGreen1) private set var hmrcGreen2 by mutableStateOf(hmrcGreen2) private set var hmrcBlue by mutableStateOf(hmrcBlue) private set var hmrcTeal by mutableStateOf(hmrcTeal) private set var hmrcRed by mutableStateOf(hmrcRed) private set var hmrcGrey1 by mutableStateOf(hmrcGrey1) private set var hmrcGrey2 by mutableStateOf(hmrcGrey2) private set var hmrcGrey3 by mutableStateOf(hmrcGrey3) private set var hmrcPink by mutableStateOf(hmrcPink) private set var hmrcYellow by mutableStateOf(hmrcYellow) private set var hmrcErrorText by mutableStateOf(hmrcErrorText) private set var hmrcDarkText by mutableStateOf(hmrcDarkText) private set var hmrcLightText by mutableStateOf(hmrcLightText) private set var hmrcLinkText by mutableStateOf(hmrcLinkText) private set var hmrcInfoText by mutableStateOf(hmrcInfoText) private set var hmrcPageBackground by mutableStateOf(hmrcPageBackground) private set var hmrcDivider by mutableStateOf(hmrcDivider) private set var hmrcInsetBar by mutableStateOf(hmrcInsetBar) private set var hmrcInfoMessageWarningHeadlineBackground by mutableStateOf( hmrcInfoMessageWarningHeadlineBackground ) private set var hmrcInfoMessageInfoHeadlineBackground by mutableStateOf( hmrcInfoMessageInfoHeadlineBackground ) private set var hmrcInfoMessageUrgentHeadlineBackground by mutableStateOf( hmrcInfoMessageUrgentHeadlineBackground ) private set var hmrcInfoMessageNoticeHeadlineBackground by mutableStateOf( hmrcInfoMessageNoticeHeadlineBackground ) private set var isDark by mutableStateOf(isDark) private set val hmrcAlwaysBlack: Color = HmrcBlack val hmrcAlwaysWhite: Color = HmrcWhite fun update(other: HmrcColors) { hmrcBlack = other.hmrcBlack hmrcWhite = other.hmrcWhite hmrcWhiteBackground = other.hmrcWhiteBackground hmrcGreen1 = other.hmrcGreen1 hmrcGreen2 = other.hmrcGreen2 hmrcBlue = other.hmrcBlue hmrcTeal = other.hmrcTeal hmrcRed = other.hmrcRed hmrcGrey1 = other.hmrcGrey1 hmrcGrey2 = other.hmrcGrey2 hmrcGrey3 = other.hmrcGrey3 hmrcPink = other.hmrcPink hmrcYellow = other.hmrcYellow hmrcErrorText = other.hmrcErrorText hmrcDarkText = other.hmrcDarkText hmrcLightText = other.hmrcLightText hmrcLinkText = other.hmrcLinkText hmrcInfoText = other.hmrcInfoText hmrcPageBackground = other.hmrcPageBackground hmrcDivider = other.hmrcDivider hmrcInsetBar = other.hmrcInsetBar hmrcInfoMessageWarningHeadlineBackground = other.hmrcInfoMessageWarningHeadlineBackground hmrcInfoMessageInfoHeadlineBackground = other.hmrcInfoMessageInfoHeadlineBackground hmrcInfoMessageUrgentHeadlineBackground = other.hmrcInfoMessageUrgentHeadlineBackground hmrcInfoMessageNoticeHeadlineBackground = other.hmrcInfoMessageNoticeHeadlineBackground isDark = other.isDark } fun copy(): HmrcColors = HmrcColors( hmrcBlack = hmrcBlack, hmrcWhite = hmrcWhite, hmrcWhiteBackground = hmrcWhiteBackground, hmrcGreen1 = hmrcGreen1, hmrcGreen2 = hmrcGreen2, hmrcBlue = hmrcBlue, hmrcTeal = hmrcTeal, hmrcRed = hmrcRed, hmrcGrey1 = hmrcGrey1, hmrcGrey2 = hmrcGrey2, hmrcGrey3 = hmrcGrey3, hmrcPink = hmrcPink, hmrcYellow = hmrcYellow, hmrcErrorText = hmrcErrorText, hmrcDarkText = hmrcDarkText, hmrcLightText = hmrcLightText, hmrcLinkText = hmrcLinkText, hmrcInfoText = hmrcInfoText, hmrcPageBackground = hmrcPageBackground, hmrcDivider = hmrcDivider, hmrcInsetBar = hmrcInsetBar, hmrcInfoMessageWarningHeadlineBackground = hmrcInfoMessageWarningHeadlineBackground, hmrcInfoMessageInfoHeadlineBackground = hmrcInfoMessageInfoHeadlineBackground, hmrcInfoMessageUrgentHeadlineBackground = hmrcInfoMessageUrgentHeadlineBackground, hmrcInfoMessageNoticeHeadlineBackground = hmrcInfoMessageNoticeHeadlineBackground, isDark = isDark, ) }
2
null
3
7
f51ffb49fac6d44fad0fbc2df95b02ea989840da
10,909
android-components
Apache License 2.0
test-utils/src/main/kotlin/dev/restate/e2e/utils/KafkaContainer.kt
restatedev
489,007,488
false
{"Kotlin": 145330, "TypeScript": 71722, "Java": 64358, "Shell": 2387, "Dockerfile": 413}
// Copyright (c) 2023 - Restate Software, Inc., Restate GmbH // // This file is part of the Restate SDK Test suite tool, // which is released under the MIT license. // // You can find a copy of the license in file LICENSE in the root // directory of this repository or package, or at // https://github.com/restatedev/sdk-test-suite/blob/main/LICENSE package dev.restate.sdktesting.infra import com.github.dockerjava.api.command.InspectContainerResponse import org.testcontainers.utility.DockerImageName /** * This class overrides the testcontainers [org.testcontainers.containers.KafkaContainer] to * introduce two additional behaviours: * * Fix the `advertised.listeners` override with the correct hostname (maybe we can upstream this * fix?) * * Create topics after the container is started */ class KafkaContainer(private vararg val topics: String) : org.testcontainers.containers.KafkaContainer( DockerImageName.parse("confluentinc/cp-kafka:7.1.0-1-ubi8")) { companion object { const val EXTERNAL_PORT = KAFKA_PORT } init { // Make sure we have auto.create.topics.enable as true withEnv("KAFKA_AUTO_CREATE_TOPICS_ENABLE", "true") } // This is copied and pasted from KafkaContainer original class to add the listeners from the // network aliases and remove the brokerAdvertisedListener override fun containerIsStarted(containerInfo: InspectContainerResponse) { val currentBrokerAdvertisedAddress = brokerAdvertisedListener(containerInfo) // Create topics first topics.forEach { topic -> execInContainer( "kafka-topics", "--create", "--topic", topic, "--bootstrap-server", currentBrokerAdvertisedAddress) } val listenerList = networkAliases.map { "BROKER://$it:9092" } + bootstrapServers val result = execInContainer( "kafka-configs", "--alter", "--bootstrap-server", currentBrokerAdvertisedAddress, "--entity-type", "brokers", "--entity-name", envMap["KAFKA_BROKER_ID"], "--add-config", "advertised.listeners=[${listenerList.joinToString(separator = ",")}]") check(result.exitCode == 0) { result.toString() } } }
6
Kotlin
3
3
c69673ba4599268fc4f6595cd55593967cccb46c
2,293
e2e
MIT License
sample-kotlin/src/main/java/com/nearit/sample_kotlin/MyApplication.kt
nearit
59,191,252
false
null
package com.nearit.sample_kotlin import android.app.Application import android.widget.Toast import android.widget.Toast.LENGTH_SHORT import it.near.sdk.NearItManager class MyApplication : Application() { override fun onCreate() { super.onCreate() NearItManager.getInstance().setProximityNotificationIcon(R.drawable.common_full_open_on_phone) NearItManager.getInstance().setPushNotificationIcon(R.drawable.googleg_disabled_color_18) } }
0
Kotlin
3
10
6f74e30a2dc8ac3db9c13a8f5d316c6a34fda044
474
Android-SDK
MIT License
src/main/kotlin/com/flixis/scanner/view/Settings.kt
Flixis
270,761,572
false
null
package com.flixis.scanner.view import tornadofx.* //TODO class Settings : View("My View") { override val root = borderpane { } }
0
Kotlin
0
0
cf2343abe54926e7c7323f8822c86e7462f55063
140
Auto-Scanner
MIT License
android/app/src/main/java/com/tvd12/freechat/constant/Commands.kt
youngmonkeys
152,706,853
false
null
package com.tvd12.freechat.constant /** * Created by tavandung12 on 10/3/18. */ object Commands { const val SUGGEST_CONTACTS = "1" const val ADD_CONTACTS = "2" const val CHAT_SYSTEM_MESSAGE = "4" const val CHAT_GET_CONTACTS = "5" const val CHAT_USER_MESSAGE = "6" const val SEARCH_CONTACTS = "10" }
1
null
20
34
9079939d7bd33d9b0e050a130df8b0d931bf13a0
329
freechat
Apache License 1.1
app/src/main/java/org/oppia/android/app/devoptions/mathexpressionparser/MathExpressionParserFragment.kt
oppia
148,093,817
false
null
package org.oppia.android.app.devoptions.mathexpressionparser import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import org.oppia.android.app.fragment.FragmentComponentImpl import org.oppia.android.app.fragment.InjectableFragment import javax.inject.Inject /** Fragment to provide user testing support for math expressions/equations. */ class MathExpressionParserFragment : InjectableFragment() { @Inject lateinit var mathExpressionParserFragmentPresenter: MathExpressionParserFragmentPresenter companion object { /** Returns a new instance of [MathExpressionParserFragment]. */ fun createNewInstance(): MathExpressionParserFragment = MathExpressionParserFragment() } override fun onAttach(context: Context) { super.onAttach(context) (fragmentComponent as FragmentComponentImpl).inject(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return mathExpressionParserFragmentPresenter.handleCreateView(inflater, container) } }
508
null
517
315
95699f922321f49a3503783187a14ad1cef0d5d3
1,146
oppia-android
Apache License 2.0
app/src/main/java/com/minhdtm/example/we_note/domain/usecase/GetAllUsersUseCase.kt
hide-your-code
501,632,307
false
null
package com.minhdtm.example.we_note.domain.usecase import com.minhdtm.example.we_note.data.model.User import com.minhdtm.example.we_note.domain.repositories.UserRepository import com.minhdtm.example.we_note.domain.usecase.base.FlowUseCase import com.minhdtm.example.we_note.presentations.di.MainDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import javax.inject.Inject import javax.inject.Singleton @Singleton class GetAllUsersUseCase @Inject constructor( @MainDispatcher private val mainDispatcher: CoroutineDispatcher, private val userRepository: UserRepository, ) : FlowUseCase<Unit, List<User>>(mainDispatcher) { override fun execute(params: Unit?): Flow<List<User>> = userRepository.getAllUsers() }
0
Kotlin
0
0
4f0b8a963251fe12d921dfb973cfb4316f485fb5
764
we_note
Apache License 2.0
cccev-core/src/jvmMain/kotlin/cccev/core/certification/service/CertificationValuesFillerService.kt
komune-io
746,816,569
false
{"Kotlin": 345488, "TypeScript": 93204, "MDX": 92741, "Gherkin": 28441, "Makefile": 5690, "JavaScript": 2459, "HTML": 1853, "Dockerfile": 1787, "CSS": 605}
package cccev.core.certification.service import cccev.commons.utils.mapAsync import cccev.core.certification.entity.CertificationRepository import cccev.core.certification.entity.RequirementCertification import cccev.core.certification.entity.SupportedValue import cccev.core.certification.entity.isFulfilled import cccev.core.certification.model.CertificationId import cccev.core.certification.model.RequirementCertificationId import cccev.core.concept.entity.InformationConcept import cccev.core.concept.entity.InformationConceptRepository import cccev.core.concept.model.InformationConceptIdentifier import cccev.core.unit.model.DataUnitType import cccev.infra.neo4j.session import cccev.infra.neo4j.transaction import f2.spring.exception.NotFoundException import kotlinx.datetime.LocalDate import kotlinx.datetime.toLocalDate import org.neo4j.ogm.session.SessionFactory import org.springframework.expression.spel.standard.SpelExpressionParser import org.springframework.expression.spel.support.StandardEvaluationContext import org.springframework.stereotype.Service import java.util.UUID @Service class CertificationValuesFillerService( private val certificationRepository: CertificationRepository, private val informationConceptRepository: InformationConceptRepository, private val sessionFactory: SessionFactory ) { companion object { val spelParser = SpelExpressionParser() } /** * Add the given values to the relevant certifications, * then update the fulfillment indicators of said certifications, * then compute the values of auto-computable information concepts that depends on the given values, * and repeat the previous steps until everything is updated. */ suspend fun fillValues(values: Map<InformationConceptIdentifier, String?>, context: Context) = sessionFactory.transaction { _, _-> values.forEach { (informationConceptIdentifier, value) -> val requirementCertifications = certificationRepository.findRequirementCertificationsLinkedToInformationConcept( context.certificationId, context.rootRequirementCertificationId, informationConceptIdentifier ) requirementCertifications.fillValue(informationConceptIdentifier, value) } certificationRepository.findAllSupportedValues(context.certificationId, context.rootRequirementCertificationId) .forEach { context.knownValues[it.concept.identifier] = it.value.convertTo(it.concept.unit.type) } computeValuesOfConsumersOf(values.keys, context) } private suspend fun List<RequirementCertification>.fillValue( informationConceptIdentifier: InformationConceptIdentifier, value: String? ) { println("fill value: [$informationConceptIdentifier]: [$value]") val informationConcept = informationConceptRepository.findByIdentifier(informationConceptIdentifier) ?: throw NotFoundException("InformationConcept", informationConceptIdentifier) // will throw if conversion is impossible value.convertTo(informationConcept.unit.type) val supportedValue = SupportedValue().apply { this.id = UUID.randomUUID().toString() this.value = value this.concept = informationConcept } this.fillValue(informationConceptIdentifier, supportedValue) } private suspend fun List<RequirementCertification>.fillValue( informationConceptIdentifier: InformationConceptIdentifier, supportedValue: SupportedValue ) = sessionFactory.session { session -> println("fill value: [$informationConceptIdentifier]: [$supportedValue]") this.onEach { requirementCertification -> val existingValue = requirementCertification.values.firstOrNull { it.concept.identifier == informationConceptIdentifier } if (existingValue == null) { requirementCertification.values.add(supportedValue) } else { existingValue.value = supportedValue.value } session.save(requirementCertification, 2) }.forEach { it.updateFulfillment() } } private suspend fun computeValuesOfConsumersOf( informationConceptIdentifiers: Set<InformationConceptIdentifier>, context: Context ) { val consumers = informationConceptIdentifiers.mapAsync { informationConceptIdentifier -> informationConceptRepository.findDependingOn(informationConceptIdentifier) }.flatten() .distinctBy(InformationConcept::identifier) consumers.computeValues(context) } private suspend fun List<InformationConcept>.computeValues(context: Context) { val computableConcepts = this.filter { concept -> concept.expressionOfExpectedValue != null && concept.dependencies.all { it.identifier in context.knownValues } } val expressionContext = StandardEvaluationContext().apply { setVariables(context.knownValues) } computableConcepts.forEach { concept -> println("compute value: [${concept.identifier}]") val certifications = certificationRepository.findRequirementCertificationsLinkedToInformationConcept( context.certificationId, context.rootRequirementCertificationId, concept.identifier ) val value = spelParser.parseExpression(concept.expressionOfExpectedValue!!) .getValue(expressionContext, concept.unit.type.klass()) .also { context.knownValues[concept.identifier] = it } .let { SupportedValue().apply { id = UUID.randomUUID().toString() this.value = it.toString() this.concept = concept } } certifications.fillValue(concept.identifier, value) } } private suspend fun RequirementCertification.updateFulfillment() { println("update fulfillment: [$id] (requirement: [${requirement.identifier}])") var changed: Boolean val mappedValues = values.associate { it.concept.identifier to it.value.convertTo(it.concept.unit.type) } hasAllValues = requirement.concepts.all { mappedValues[it.identifier] != null } .also { changed = it != hasAllValues } isEnabled = evaluateBooleanExpression( requirement.enablingCondition, requirement.enablingConditionDependencies.map(InformationConcept::identifier).toSet(), mappedValues ).also { changed = changed || it != isEnabled } isValidated = evaluateBooleanExpression( requirement.validatingCondition, requirement.validatingConditionDependencies.map(InformationConcept::identifier).toSet(), mappedValues ).also { changed = changed || it != isValidated } isFulfilled = isFulfilled() .also { changed = changed || it != isFulfilled } if (changed) { certificationRepository.save(this) certificationRepository.findParentsOf(id) .forEach { parent -> parent.updateFulfillment() } } } private suspend fun evaluateBooleanExpression( expression: String?, dependencies: Set<InformationConceptIdentifier>, values: Map<InformationConceptIdentifier, Any?> ): Boolean { if (expression == null) { return true } if (dependencies.any { it !in values }) { return false } val expressionContext = StandardEvaluationContext().apply { setVariables(dependencies.associateWith { values[it] }) } return spelParser.parseExpression(expression) .getValue(expressionContext, Boolean::class.java) ?: false } private fun String?.convertTo(type: DataUnitType): Any? = when (type) { DataUnitType.BOOLEAN -> this?.toBoolean() DataUnitType.DATE -> this?.toLocalDate() // TODO define a standard type for DATE DataUnitType.NUMBER -> this?.toDouble() DataUnitType.STRING -> this } private fun DataUnitType.klass() = when (this) { DataUnitType.BOOLEAN -> Boolean::class.java DataUnitType.DATE -> LocalDate::class.java // TODO define a standard type for DATE DataUnitType.NUMBER -> Double::class.java DataUnitType.STRING -> String::class.java } data class Context( val certificationId: CertificationId, val rootRequirementCertificationId: RequirementCertificationId?, val knownValues: MutableMap<InformationConceptIdentifier, Any?> = mutableMapOf() ) }
2
Kotlin
0
0
f6a4e3ea8a8f80b2b6224fa05335cf4bb7ae770a
8,794
connect-cccev
Apache License 2.0
webui/src/main/kotlin/com/simiacryptus/skyenet/apps/general/PlanChatApp.kt
SimiaCryptus
619,329,127
false
{"Kotlin": 781804, "JavaScript": 60230, "SCSS": 31588, "HTML": 5642, "Scala": 5538, "Java": 2053}
package com.simiacryptus.skyenet.apps.general import com.simiacryptus.jopenai.API import com.simiacryptus.jopenai.ChatClient import com.simiacryptus.jopenai.models.OpenAITextModel import com.simiacryptus.skyenet.apps.plan.* import com.simiacryptus.skyenet.core.platform.Session import com.simiacryptus.skyenet.core.platform.User import com.simiacryptus.skyenet.webui.application.ApplicationInterface import com.simiacryptus.skyenet.webui.util.MarkdownUtil import org.slf4j.LoggerFactory import java.io.File import java.util.* class PlanChatApp( applicationName: String = "Task Planning Chat v1.0", path: String = "/taskChat", rootFile: File? = null, planSettings: PlanSettings, model: OpenAITextModel, parsingModel: OpenAITextModel, domainName: String = "localhost", showMenubar: Boolean = true, initialPlan: PlanUtil.TaskBreakdownWithPrompt? = null, api: API? = null, ) : PlanAheadApp( applicationName = applicationName, path = path, rootFile = rootFile, planSettings = planSettings, model = model, parsingModel = parsingModel, domainName = domainName, showMenubar = showMenubar, initialPlan = initialPlan, api = api, ) { override val stickyInput = true override val singleInput = false private val sessionHandlers: MutableMap<String, ChatSessionHandler> = mutableMapOf() override fun userMessage( session: Session, user: User?, userMessage: String, ui: ApplicationInterface, api: API ) { ui.socketManager?.pool!!.submit { val sessionHandler = sessionHandlers.getOrPut(session.sessionId) { ChatSessionHandler( ui = ui, session = session, user = user, api = api ) } sessionHandler.handleUserMessage( userMessage = userMessage, ) } } private inner class ChatSessionHandler( val ui: ApplicationInterface, val session: Session, val user: User?, val api: API ) { val messageHistory: MutableList<String> = mutableListOf() fun handleUserMessage(userMessage: String) { try { messageHistory.add(userMessage) val planSettings = (getSettings(session, user, PlanSettings::class.java) ?: PlanSettings( defaultModel = model, parsingModel = parsingModel, command = planSettings.command, temperature = planSettings.temperature, workingDir = planSettings.workingDir, env = planSettings.env )).copy( allowBlocking = false, ) if (api is ChatClient) api.budget = planSettings.budget val coordinator = PlanCoordinator( user = user, session = session, dataStorage = dataStorage, ui = ui, root = dataStorage.getDataDir(user, session).toPath(), planSettings = planSettings ) val mainTask = coordinator.ui.newTask() val sessionTask = ui.newTask(false).apply { mainTask.verbose(placeholder) } val api = (api as ChatClient).getChildClient().apply { val createFile = sessionTask.createFile(".logs/api-${UUID.randomUUID()}.log") createFile.second?.apply { logStreams += this.outputStream().buffered() sessionTask.verbose("API log: <a href=\"file:///$this\">$this</a>") } } val plan = PlanCoordinator.initialPlan( codeFiles = coordinator.codeFiles, files = coordinator.files, root = dataStorage.getDataDir(user, session).toPath(), task = sessionTask, userMessage = userMessage, ui = coordinator.ui, planSettings = coordinator.planSettings, api = api ) val modifiedPlan = addRespondToChatTask(plan.plan) val planProcessingState = coordinator.executePlan( plan = modifiedPlan, task = sessionTask, userMessage = userMessage, api = api ) val response = planProcessingState.taskResult["respond_to_chat"] as? String if (response != null) { mainTask.add(MarkdownUtil.renderMarkdown(response, ui = ui)) messageHistory.add(response) } else { mainTask.add("Sorry, I couldn't generate a response.") messageHistory.add("Sorry, I couldn't generate a response.") } mainTask.complete() } catch (e: Throwable) { ui.newTask().error(ui, e) log.warn("Error", e) } } } private fun addRespondToChatTask(plan: PlanningTask.TaskBreakdownInterface): PlanningTask.TaskBreakdownInterface { val tasksByID = plan.tasksByID?.toMutableMap() ?: mutableMapOf() val respondTaskId = "respond_to_chat" tasksByID[respondTaskId] = PlanningTask.PlanTask( task_description = "Respond to the user's chat message based on the executed plan", task_type = TaskType.Inquiry, task_dependencies = tasksByID.keys.toList() ) return PlanningTask.TaskBreakdownResult( tasksByID = tasksByID, ) } companion object { private val log = LoggerFactory.getLogger(PlanChatApp::class.java) } }
1
Kotlin
0
1
68fc3756084f30fd5a5c64200abd55b1b4fe7c11
5,951
SkyeNet
Apache License 2.0
app/src/main/java/com/carlosgub/coroutines/features/books/data/mapper/PostDataMapper.kt
dungnguyen87
478,834,666
false
null
package com.carlosgub.coroutines.features.books.data.mapper import com.carlosgub.coroutines.core.mapper.Mapper import com.carlosgub.coroutines.features.books.data.datasource.rest.response.PostResponseData import com.carlosgub.coroutines.features.books.domain.model.PostEntity class PostDataMapper : Mapper<PostResponseData, PostEntity> { override fun map(origin: PostResponseData) = PostEntity( base = origin.base, counter = origin.counter, buy_price = origin.buy_price, sell_price = origin.sell_price, icon = origin.icon, name = origin.name ) }
0
Kotlin
0
0
d13e4d6922b0149081001529ec4eb01dae035057
639
Fetch-Technology-Test
Apache License 2.0
s_bpm/src/main/kotlin/sbpm_solution/bpms/sbpm/dume.kt
atim333
534,139,851
false
{"Kotlin": 190328}
package sbpm_solution.bpms.sbpm class dume { }
0
Kotlin
0
0
5884b562b576df27baa634952ab4fbaad0e4c98d
47
sbpm_solution
Apache License 2.0
app/src/main/java/com/example/bank_branch_details/network/model/Access_BranchCode.kt
SawThanDar18
192,281,355
false
null
package com.example.bank_branch_details.network.model import com.google.gson.annotations.SerializedName class Access_BranchCode (val branchCode : String, val appVersion : String)
0
Kotlin
0
0
37f7c03ded5f5cdf62a77cebc4b5963d0381de56
180
Bank_Branch_Details
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/subjectaccessrequestworker/mockservers/PrisonApiMockServer.kt
ministryofjustice
748,250,175
false
{"Kotlin": 379980, "Mustache": 234771, "Shell": 7048, "Dockerfile": 1161}
package uk.gov.justice.digital.hmpps.subjectaccessrequestworker.mockservers import com.github.tomakehurst.wiremock.WireMockServer import com.github.tomakehurst.wiremock.client.WireMock.aResponse import com.github.tomakehurst.wiremock.client.WireMock.get import com.github.tomakehurst.wiremock.client.WireMock.matching class PrisonApiMockServer : WireMockServer(WIREMOCK_PORT) { companion object { private const val WIREMOCK_PORT = 4001 } private val offenderIdPath = "/api/offenders/A9999AA" fun stubGetOffenderDetails() { stubFor( get(offenderIdPath) .withHeader("Authorization", matching("Bearer ${HmppsAuthMockServer.TOKEN}")) .willReturn( aResponse() .withHeader("Content-Type", "application/json") .withStatus(200) .withBody( """ { "firstName": "FirstName", "middleName": "MiddleName", "lastName": "LastName" } """.trimIndent(), ), ), ) } }
2
Kotlin
0
1
82d22434568c80edb191920f67aa4e1cf583657a
1,064
hmpps-subject-access-request-worker
MIT License
app/src/main/java/social/entourage/android/onboarding/onboard/OnboardingPhase2Fragment.kt
ReseauEntourage
30,242,877
false
{"Kotlin": 1851766}
package social.entourage.android.onboarding.onboard import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.CountDownTimer import android.text.Editable import android.text.Html import android.text.TextWatcher import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_login.* import kotlinx.android.synthetic.main.fragment_onboarding_phase2.* import kotlinx.android.synthetic.main.fragment_onboarding_phase2.tv_condition_generales import social.entourage.android.R import social.entourage.android.tools.hideKeyboard import social.entourage.android.tools.log.AnalyticsEvents import social.entourage.android.tools.view.EntSnackbar import social.entourage.android.tools.view.countrycodepicker.Country private const val ARG_PHONE = "phone" private const val ARG_COUNTRY = "couuntry" class OnboardingPhase2Fragment : Fragment() { private val TIME_BEFORE_CALL = 60 private var callback:OnboardingStartCallback? = null private var countDownTimer:CountDownTimer? = null private var timeOut = TIME_BEFORE_CALL private var phone: String? = null private var country: Country? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { phone = it.getString(ARG_PHONE) country = it.get(ARG_COUNTRY) as? Country } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_onboarding_phase2, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) callback?.updateButtonNext(false) setupViews() activateTimer() AnalyticsEvents.logEvent(AnalyticsEvents.Onboard_code) } private fun activateTimer() { cancelTimer() timeOut = TIME_BEFORE_CALL countDownTimer = object : CountDownTimer(600000 ,1000L) { override fun onFinish() { cancelTimer() ui_onboard_bt_code_retry?.visibility = View.VISIBLE ui_onboard_code_retry?.visibility = View.INVISIBLE ui_onboard_code_tv_phone_mod?.visibility = View.VISIBLE } override fun onTick(p0: Long) { if(isDetached) return timeOut -= 1 if (timeOut == 0) { ui_onboard_bt_code_retry?.visibility = View.VISIBLE ui_onboard_code_retry?.visibility = View.INVISIBLE ui_onboard_code_tv_phone_mod?.visibility = View.VISIBLE cancelTimer() } else { val _time = if (timeOut < 10) "00:0$timeOut" else "00:$timeOut" val _retryTxt = String.format(getString(R.string.onboard_sms_wait_retry),_time) ui_onboard_code_retry?.text = _retryTxt } } } ui_onboard_code_retry?.text = String.format(getString(R.string.onboard_sms_wait_retry),"00:0$timeOut") countDownTimer?.start() } fun cancelTimer() { countDownTimer?.cancel() countDownTimer = null } override fun onAttach(context: Context) { super.onAttach(context) callback = (activity as? OnboardingStartCallback) } override fun onDetach() { super.onDetach() callback = null cancelTimer() } fun setupViews() { layout_main?.setOnTouchListener { view, motionEvent -> view.hideKeyboard() view.performClick() true } ui_onboard_bt_code_retry?.setOnClickListener { if (timeOut > 0) { AlertDialog.Builder(requireActivity()) .setTitle(R.string.attention_pop_title) .setMessage(String.format(getString(R.string.onboard_sms_pop_alert),timeOut)) .setPositiveButton("OK") { dialog, which -> } .create() .show() } else { callback?.requestNewCode() activateTimer() } } ui_onboard_bt_help?.setOnClickListener { val intent = Intent(Intent.ACTION_SENDTO) intent.data = Uri.parse("mailto:") val addresses = arrayOf(getString(R.string.contact_email)) intent.putExtra(Intent.EXTRA_EMAIL, addresses) try { startActivity(intent) } catch (e: ActivityNotFoundException) { layout_main?.let { EntSnackbar.make(it, R.string.error_no_email, Snackbar.LENGTH_SHORT).show()} } } ui_onboard_code_tv_description?.text = getString(R.string.onboard_sms_sub) ui_onboard_code_tv_phone?.text = country?.phoneCode + phone ui_onboard_bt_code_retry?.visibility = View.INVISIBLE ui_onboard_code_retry?.visibility = View.VISIBLE ui_onboard_code_tv_phone_mod?.visibility = View.INVISIBLE ui_onboard_code_tv_phone_mod?.setOnClickListener { callback?.goPreviousManually() } val text = getString(R.string.terms_and_conditions_html) tv_condition_generales.text = Html.fromHtml(text) tv_condition_generales.movementMethod = LinkMovementMethod.getInstance() addTextwatcher() } private fun addTextwatcher() { val textWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) { } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { val text = activity?.currentFocus as? EditText? if ((text?.text?.length ?: 0) > 0) { callback?.validatePasscode(text?.text.toString()) callback?.updateButtonNext(true) } else { callback?.validatePasscode(null) callback?.updateButtonNext(false) } } } ui_onboard_code?.addTextChangedListener(textWatcher) } companion object { @JvmStatic fun newInstance(phone: String?, country: Country?) = OnboardingPhase2Fragment().apply { arguments = Bundle().apply { putString(ARG_PHONE, phone) putSerializable(ARG_COUNTRY,country) } } } }
1
Kotlin
2
9
46ca9370f0db0415bd868f0008ba2ff1d41f2f3c
7,177
entourage-android
MIT License
app/src/main/kotlin/com/gcode/vastutils/activity/NetStateActivity.kt
SakurajimaMaii
353,212,367
false
null
/* * Copyright 2022 VastGui * * 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.gcode.vastutils.activity import android.os.* import com.gcode.vastnetstatelayout.interfaces.VastEmptyDataListener import com.gcode.vastnetstatelayout.interfaces.VastLoadingErrorListener import com.gcode.vastnetstatelayout.interfaces.VastLoadingListener import com.gcode.vastnetstatelayout.interfaces.VastNetErrorListener import com.gcode.vastnetstatelayout.view.VastNetStateMgr import com.gcode.vasttools.activity.VastVbActivity import com.gcode.vastutils.R import com.gcode.vastutils.databinding.ActivityNetStateBinding class NetStateActivity : VastVbActivity<ActivityNetStateBinding>() { private val mHandler: Handler = object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { super.handleMessage(msg) mBinding.netStateLayout.showSuccess() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val vastNetStateMgr = VastNetStateMgr(this) vastNetStateMgr.setNetErrorListener(object :VastNetErrorListener{ override fun onNetWorkError() { // Something to do when network error } }) vastNetStateMgr.setLoadingListener(object : VastLoadingListener { override fun onLoading() { object:Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { super.handleMessage(msg) mBinding.netStateLayout.showSuccess() } }.sendEmptyMessageDelayed(0, 1000) } }) vastNetStateMgr.setLoadingErrorListener(object :VastLoadingErrorListener{ override fun onLoadingError() { // Something to do when loading error } }) vastNetStateMgr.setEmptyDataListener(object :VastEmptyDataListener{ override fun onEmptyData() { // Something to do when empty data } }) vastNetStateMgr.setNetErrorView(R.layout.error_page) mBinding.netStateLayout.setVastNetStateMgr(vastNetStateMgr) mBinding.netStateLayout.showNetError() mHandler.sendEmptyMessageDelayed(0, 1000) } }
5
null
4
34
3ac2ce67b9bab4a801d79f83fc0f80f234a1481e
2,856
VastUtils
Apache License 2.0
app/src/main/java/com/example/android/taskinterop/MainActivity.kt
googlesamples
313,345,462
false
null
/* Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.taskinterop import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.annotation.Keep import androidx.appcompat.app.AppCompatActivity import androidx.concurrent.futures.CallbackToFutureAdapter import androidx.concurrent.futures.DirectExecutor import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import com.google.android.gms.oss.licenses.OssLicensesMenuActivity import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.TaskCompletionSource // [START guava_import] import com.google.common.util.concurrent.ListenableFuture // [END guava_import] // [START rx_import] import io.ashdavies.rx.rxtasks.toSingle import java.util.concurrent.TimeUnit // [END rx_import] import kotlinx.coroutines.launch // [START ktx_import] import kotlinx.coroutines.tasks.await // [END ktx_import] @Keep class MainActivity : AppCompatActivity() { private val TAG = "MainActivity" private var listenableFuture: ListenableFuture<String>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<TextView>(R.id.textview_first) // Simple Google Play services Task example findViewById<Button>(R.id.tasks_button).setOnClickListener { textView.text = getString(R.string.waiting_txt) // [START simple_task] // [START_EXCLUDE] val simpleTask = createSimpleTask(getString(R.string.tasks_txt)) // [END_EXCLUDE] simpleTask.addOnCompleteListener(this) { completedTask -> textView.text = completedTask.result } // [END simple_task] } // Kotlin Coroutine Task example findViewById<Button>(R.id.ktx_button).setOnClickListener { textView.text = getString(R.string.waiting_txt) // [START ktx_task] // [START_EXCLUDE] val simpleTask = createSimpleTask(getString(R.string.ktx_txt)) // Jetpack lifecycle library lifecycleScope.launch { // [END_EXCLUDE] textView.text = simpleTask.await() } // [END ktx_task] } // Simple Guava example findViewById<Button>(R.id.guava_button).setOnClickListener { textView.text = getString(R.string.waiting_txt) // [START guava_task] // [START_EXCLUDE] val simpleTask = createSimpleTask(getString(R.string.guava_txt)) // [END_EXCLUDE] this.listenableFuture = taskToListenableFuture(simpleTask) this.listenableFuture?.addListener( Runnable { textView.text = listenableFuture?.get() }, ContextCompat.getMainExecutor(this) ) // [END guava_task] } // Simple RX Java example findViewById<Button>(R.id.rx_button).setOnClickListener { textView.text = getString(R.string.waiting_txt) // [START rx_task] // [START_EXCLUDE] val simpleTask = createSimpleTask(getString(R.string.rx_txt)) // [END_EXCLUDE] simpleTask.toSingle(this).subscribe { result -> textView.text = result } // [END rx_task] } findViewById<Button>(R.id.license_button).setOnClickListener { startActivity(Intent(this, OssLicensesMenuActivity::class.java)) } } override fun onStop() { super.onStop() this.listenableFuture?.cancel(/*mayInterruptIfRunning=*/false) } } // [START guava_conversion] /** Convert Task to ListenableFuture. */ fun <T> taskToListenableFuture(task: Task<T>): ListenableFuture<T> { return CallbackToFutureAdapter.getFuture { completer -> task.addOnCompleteListener { completedTask -> if (completedTask.isCanceled) { completer.setCancelled() } else if (completedTask.isSuccessful) { completer.set(completedTask.result) } else { val e = completedTask.exception if (e != null) { completer.setException(e) } else { throw IllegalStateException() } } } } } // [END guava_conversion] /** Extension on Task for conversion to ListenableFuture. */ @Keep fun <T> Task<T>.toListenableFuture() = taskToListenableFuture(this) /** Create a simple task on new thread that waits 1 second. */ @Keep fun createSimpleTask(value: String) = TaskCompletionSource<String>().apply { Thread { Thread.sleep(TimeUnit.SECONDS.toMillis(1)) setResult(value) }.start() }.task
0
null
6
6
6f6ac5ff79528bf9191ccef36204a7c6d58030d4
5,031
task-interop
Apache License 2.0
library/core/validation/src/test/kotlin/de/lise/fluxflow/validation/jakarta/TestModelWithRecursiveProp.kt
lisegmbh
740,936,659
false
{"Kotlin": 732955}
package de.lise.fluxflow.validation.jakarta import jakarta.validation.Valid class TestModelWithRecursiveProp { @Valid var someProp: TypeWithRecursiveProp? = null }
20
Kotlin
0
7
03a99c536434660fc2cde3df9e220991ff487599
173
fluxflow
Apache License 2.0
app/src/main/java/com/arindam/camerax/ui/base/BaseFragmentCompose.kt
arindamxd
185,732,147
false
{"Kotlin": 118672}
package com.arindam.camerax.ui.base import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import androidx.compose.ui.platform.ComposeView import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.navigation.NavDirections import androidx.navigation.fragment.findNavController import com.arindam.camerax.R import com.arindam.camerax.util.commons.Constants.PERMISSIONS.REQUIRED_PERMISSIONS import com.arindam.camerax.util.display.Toaster import java.io.File import java.text.SimpleDateFormat import java.util.* /** * Created by Arindam Karmakar on 17/04/20. */ abstract class BaseFragmentCompose : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = ComposeView(inflater.context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setComposeView(this) } abstract fun setComposeView(view: ComposeView) protected fun navigate(directions: NavDirections) = findNavController().navigate(directions) protected fun navigateBack() = findNavController().navigateUp() /** Convenience method used to check if all permissions required by this app are granted */ protected fun hasPermissions() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission(requireContext(), it) == PackageManager.PERMISSION_GRANTED } /** Use external media if it is available, our app's file directory otherwise */ protected fun getOutputFileDirectory(): File { val appContext = requireContext().applicationContext val mediaDir = requireContext().externalMediaDirs.firstOrNull()?.let { File(it, appContext.resources.getString(R.string.app_name)).apply { mkdirs() } } return if (mediaDir != null && mediaDir.exists()) mediaDir else appContext.filesDir } protected fun isDirectoryNotEmpty(): Boolean = getOutputFileDirectory().listFiles()?.isNotEmpty() == true /** Helper function used to create a timestamped file */ protected fun createFile(baseFolder: File, format: String, extension: String) = File( baseFolder, SimpleDateFormat(format, Locale.US).format(System.currentTimeMillis()) + extension ) protected fun createFileName(format: String): String { return SimpleDateFormat(format, Locale.US).format(System.currentTimeMillis()) } protected fun showToast(@StringRes resId: Int) { showToast(requireContext().getString(resId)) } protected fun showToast(message: String) { Toaster.show(requireContext(), message) } }
2
Kotlin
21
99
b5266acd99b72f0cb16e3ffb04b47767a8988244
2,868
android-camerax
Apache License 2.0
app/src/main/java/com/wgy/recycleclient/ui/adapter/ActivityRecommendAdapter.kt
Gaoyuan-Wang
451,928,127
false
{"Kotlin": 125594}
package com.wgy.recycleclient.ui.adapter import android.content.Intent import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.RecyclerView import com.wgy.recycleclient.R import com.wgy.recycleclient.logic.model.CheckRecommendActivityData import com.wgy.recycleclient.logic.model.Sign import com.wgy.recycleclient.ui.fragment.ActivityFragment class ActivityRecommendAdapter(private val fragment: ActivityFragment, private val activityList: ArrayList<CheckRecommendActivityData>): RecyclerView.Adapter<ActivityRecommendAdapter.ViewHolder>() { inner class ViewHolder(view: View): RecyclerView.ViewHolder(view){ val activityName: TextView = view.findViewById(R.id.activityName) val activityPoint: TextView = view.findViewById(R.id.activityPoint) val activityLocation: TextView = view.findViewById(R.id.activityLocation) val activityBeginTime: TextView = view.findViewById(R.id.activityBeginTime) val activityEndTime: TextView = view.findViewById(R.id.activityEndTime) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.activity_item_recommend,parent, false) val holder = ViewHolder(view) holder.itemView.setOnClickListener { val position = holder.adapterPosition AlertDialog.Builder(parent.context).apply { setCancelable(false) setMessage("您确定报名此活动吗?:\n${activityList[position + 1].name}\n") setPositiveButton("确 定"){ _, _-> fragment.viewModel.sign = Sign(activityList[position + 1].id,fragment.viewModel.id) fragment.viewModel.sign(fragment.viewModel.sign) } setNegativeButton("取 消"){ _, _-> } show() } } return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val activity = activityList[position] holder.activityName.text = activity.name holder.activityPoint.text = activity.point.toString() holder.activityLocation.text = activity.location holder.activityBeginTime.text = activity.startTime holder.activityEndTime.text = activity.endTime } override fun getItemCount(): Int = activityList.size }
0
Kotlin
0
0
ba34b9270b49f3801ecf316e9e2766941ffb8a4a
2,532
RecycleClient
Apache License 2.0
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/presentation/components/channel_info/members/adapter/holders/ChannelMembersViewHolderFactory.kt
sceyt
549,073,085
false
{"Kotlin": 2713714, "Java": 107920}
package com.sceyt.chatuikit.presentation.components.channel_info.members.adapter.holders import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import com.sceyt.chatuikit.SceytChatUIKit import com.sceyt.chatuikit.databinding.SceytItemChannelMembersBinding import com.sceyt.chatuikit.databinding.SceytItemLoadingMoreBinding import com.sceyt.chatuikit.extensions.setProgressColor import com.sceyt.chatuikit.presentation.components.channel_info.members.adapter.MemberItem import com.sceyt.chatuikit.presentation.components.channel_info.members.adapter.diff.MemberItemPayloadDiff import com.sceyt.chatuikit.presentation.components.channel_info.members.adapter.listeners.MemberClickListeners import com.sceyt.chatuikit.presentation.components.channel_info.members.adapter.listeners.MemberClickListenersImpl import com.sceyt.chatuikit.styles.channel_members.ChannelMemberListItemStyle open class ChannelMembersViewHolderFactory( protected val context: Context, protected val style: ChannelMemberListItemStyle ) { private val layoutInflater = LayoutInflater.from(context) private val clickListeners = MemberClickListenersImpl() fun createViewHolder(parent: ViewGroup, viewType: Int): BaseMemberViewHolder { return when (viewType) { ItemType.Member.ordinal -> createMemberViewHolder(parent) ItemType.Loading.ordinal -> createLoadingMoreViewHolder(parent) else -> throw RuntimeException("Not supported view type") } } open fun createMemberViewHolder(parent: ViewGroup): BaseMemberViewHolder { return MemberViewHolder( SceytItemChannelMembersBinding.inflate(layoutInflater, parent, false), style, clickListeners) } open fun createLoadingMoreViewHolder(parent: ViewGroup): BaseMemberViewHolder { val binding = SceytItemLoadingMoreBinding.inflate(layoutInflater, parent, false) return object : BaseMemberViewHolder(binding.root) { override fun bind(item: MemberItem, diff: MemberItemPayloadDiff) { binding.applyStyle() } private fun SceytItemLoadingMoreBinding.applyStyle() { adapterListLoadingProgressBar.setProgressColor(SceytChatUIKit.theme.colors.accentColor) } } } open fun getItemViewType(item: MemberItem): Int { return when (item) { is MemberItem.Member -> ItemType.Member.ordinal is MemberItem.LoadingMore -> ItemType.Loading.ordinal } } fun setOnClickListener(listeners: MemberClickListeners) { clickListeners.setListener(listeners) } enum class ItemType { Member, Loading } }
0
Kotlin
1
2
92717e7a0201600396bacddaa279f8a07a298650
2,741
sceyt-chat-android-uikit
MIT License
app/src/main/java/com/qihaocai/flixsterv2/Movies.kt
Arstal
545,219,588
false
null
package com.qihaocai.flixsterv2 import com.google.gson.annotations.SerializedName class Movies { @JvmField @SerializedName("title") var title: String? = null @JvmField @SerializedName("poster_path") var imageUrl: String? = null @JvmField @SerializedName("overview") var description: String? = null @JvmField @SerializedName("release_date") var rating: String? = null }
1
Kotlin
0
0
bdbf938376a7df905c6503060a62fba53963ce8a
422
FlixsterV2
Apache License 2.0
code/testutils/src/main/java/com/adobe/marketing/mobile/util/NetworkRequestHelper.kt
adobe
706,036,703
false
{"Kotlin": 199092, "Java": 53945, "Shell": 3706, "Makefile": 2043}
/* Copyright 2021 Adobe. All rights reserved. This file is licensed 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util import com.adobe.marketing.mobile.services.HttpConnecting import com.adobe.marketing.mobile.services.HttpMethod import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.NetworkRequest import com.adobe.marketing.mobile.services.TestableNetworkRequest import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Assert.fail import java.util.concurrent.TimeUnit /** * Provides shared utilities and logic for implementations of `Networking` classes used for testing. * * @see [MockNetworkService] * @see [RealNetworkService] */ class NetworkRequestHelper { private val _networkRequests: MutableList<TestableNetworkRequest> = mutableListOf() // Read-only access to network requests val networkRequests: List<TestableNetworkRequest> get() = _networkRequests private val _networkResponses: MutableMap<TestableNetworkRequest, MutableList<HttpConnecting?>> = HashMap() // Read-only access to network responses val networkResponses: Map<TestableNetworkRequest, List<HttpConnecting?>> get() = _networkResponses.mapValues { it.value.toList() } private val expectedNetworkRequests: MutableMap<TestableNetworkRequest, ADBCountDownLatch> = HashMap() companion object { private const val LOG_SOURCE = "NetworkRequestHelper" } /** * Records a sent network request. * * @param request The [TestableNetworkRequest] that is to be recorded. */ fun recordNetworkRequest(request: TestableNetworkRequest) { Log.trace( TestConstants.LOG_TAG, LOG_SOURCE, "Recording network request with URL ${request.url} and HTTPMethod ${request.method}" ) _networkRequests.add(request) } /** * Resets the helper state by clearing all test expectations and recorded network requests and responses. */ fun reset() { Log.trace( TestConstants.LOG_TAG, LOG_SOURCE, "Reset network request expectations and recorded network requests and responses." ) _networkRequests.clear() _networkResponses.clear() expectedNetworkRequests.clear() } /** * Decrements the expectation count for a given network request. * * @param request The [TestableNetworkRequest] for which the expectation count should be decremented. */ fun countDownExpected(request: TestableNetworkRequest) { expectedNetworkRequests[request]?.countDown() } /** * Asserts on the expectation for the given network request, validating that all expected responses are received * within the provided timeout duration and that expected count is not exceeded. If no expectation is * set for the request, a configurable default wait time is applied. * * @param request The [NetworkRequest] for which the expectation should be asserted. * @param timeoutMillis The maximum duration (in milliseconds) to wait for the expected responses before timing out. * @param waitForUnexpectedEvents If `true`, a default wait time will be used when no expectation is set for the request. * Defaults to `true`. * * @throws InterruptedException If the current thread is interrupted while waiting. */ @Throws(InterruptedException::class) fun awaitRequest(request: TestableNetworkRequest, timeoutMillis: Int, waitForUnexpectedEvents: Boolean = true) { val expectation = expectedNetworkRequests[request] if (expectation != null) { val awaitResult = expectation.await(timeoutMillis.toLong(), TimeUnit.MILLISECONDS) // Verify that the expectation passes within the given timeout assertTrue( """ Time out waiting for network request with URL '${request.url}' and HTTP method '${request.method.name}'. Received (${expectation.currentCount}/${expectation.initialCount}) expected requests. """.trimIndent(), awaitResult ) // Validate that the actual count does not exceed the expected count assertEquals( """ Expected only ${expectation.initialCount} network request(s) for URL ${request.url} and HTTP method ${request.method.name}, but received ${expectation.currentCount}. """.trimIndent(), expectation.initialCount, expectation.currentCount ) } // Default wait time for network request with no previously set expectation else { if (waitForUnexpectedEvents) { TestHelper.waitForThreads(timeoutMillis) } } } /** * Immediately returns all network requests that match the provided network request. Does **not** * await. * * The matching logic relies on [TestableNetworkRequest.equals]. * * @param request The [TestableNetworkRequest] for which to get matching requests. * * @return A list of [TestableNetworkRequest]s that match the provided [request]. If no matches are found, an empty list is returned. */ fun getRequestsMatching(request: TestableNetworkRequest): List<TestableNetworkRequest> { return _networkRequests.filter { it == request } } /** * Adds a network response for the provided network request. If a response already exists, adds * the given response to the end of the list. * * @param request The [TestableNetworkRequest] for which the response will be set. * @param responseConnection The [HttpConnecting] to add as a response. */ fun addResponseFor( request: TestableNetworkRequest, responseConnection: HttpConnecting? ) { if (_networkResponses[request] != null) { _networkResponses[request]?.add(responseConnection) } else { // If there's no response for this request yet, start a new list with the first response _networkResponses[request] = mutableListOf(responseConnection) } } /** * Removes all network responses for the provided network request. * * @param request The [TestableNetworkRequest] for which all responses will be removed. */ fun removeResponsesFor(request: TestableNetworkRequest) { _networkResponses.remove(request) } /** * Returns the network responses for the given network request. * * @param request The [TestableNetworkRequest] for which the associated responses should be returned. * @return The list of [HttpConnecting] responses for the given request or `null` if not found. * @see [TestableNetworkRequest.equals] for the logic used to match network requests. */ fun getResponsesFor(request: TestableNetworkRequest): List<HttpConnecting?>? { return _networkResponses[request] } /** * Sets the expected number of times a network request should be sent. If there is already an existing expectation * for the same request, it is replaced with the new value. * * @param request The [TestableNetworkRequest] to set the expectation for. * @param count The expected number of times the request should be sent. * @see [assertAllNetworkRequestExpectations] for checking all expectations. */ fun setExpectationFor(request: TestableNetworkRequest, count: Int) { expectedNetworkRequests[request] = ADBCountDownLatch(count) } /** * Asserts that the correct number of network requests have been sent based on previously set expectations. * It waits for expected requests to complete and optionally checks for unexpected ones. * * @param ignoreUnexpectedRequests If `true`, skips validation of unexpected requests. Defaults to `true`. * @param waitForUnexpectedRequests If `true`, waits for unexpected requests to occur within the given timeout. Defaults to `true`. * @param timeoutMillis The maximum time to wait (in milliseconds) for expected requests to complete. Defaults to [TestConstants.Defaults.WAIT_NETWORK_REQUEST_TIMEOUT_MS]. * * @throws InterruptedException If the current thread is interrupted while waiting. * @see [setExpectationFor] to set expectations for specific network requests. */ @Throws(InterruptedException::class) fun assertAllNetworkRequestExpectations( ignoreUnexpectedRequests: Boolean = true, waitForUnexpectedRequests: Boolean = true, timeoutMillis: Int = TestConstants.Defaults.WAIT_NETWORK_REQUEST_TIMEOUT_MS ) { // Validate expected events for (expectedRequest in expectedNetworkRequests.keys) { awaitRequest(expectedRequest, timeoutMillis, false) } // Validate unexpected requests if required if (ignoreUnexpectedRequests) { return } if (waitForUnexpectedRequests) { TestHelper.waitForThreads(timeoutMillis) } assertNoUnexpectedRequests() } /** * Asserts that there are no unexpected network requests. */ private fun assertNoUnexpectedRequests() { // Group unexpected network requests (those not in expected keys) by TestableNetworkRequest equality val groupedRequests = _networkRequests .filter { it !in expectedNetworkRequests.keys } .groupBy { it } val failureDetails = groupedRequests.entries.joinToString(separator = "\n") { (request, group) -> "(URL: ${request.url}, HTTPMethod: ${request.method.name}, Count: ${group.size})" } // If there are any unexpected requests, fail with a message if (failureDetails.isNotEmpty()) { fail("Received unexpected network request(s): \n$failureDetails") } } /** * Fetches the network request(s) matching the provided [url] and [method], returning an empty list if none were found. * To wait for expected requests, this method should be used after calling [setExpectationFor]. * * @param url The URL string of the [NetworkRequest] to match. * @param method The HTTP method of the [NetworkRequest] to match. * @param timeoutMillis The time in milliseconds to wait for the expected network requests. Defaults to [TestConstants.Defaults.WAIT_NETWORK_REQUEST_TIMEOUT_MS]. * * @return A list of [NetworkRequest]s that match the provided [url] and [method]. If no matching requests are found, * an empty list is returned. * * @throws InterruptedException If the current thread is interrupted while waiting. */ @Throws(InterruptedException::class) fun getNetworkRequestsWith( url: String, method: HttpMethod, timeoutMillis: Int = TestConstants.Defaults.WAIT_NETWORK_REQUEST_TIMEOUT_MS ): List<TestableNetworkRequest> { val testableRequest = TestableNetworkRequest(url, method) awaitRequest(testableRequest, timeoutMillis) return getRequestsMatching(testableRequest) } }
0
Kotlin
2
0
e290ab17ebe6230e771c227e3b77d20d63a7dd42
11,768
aepsdk-testutils-android
Apache License 2.0
api/src/main/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/api/response/RedisTimeoutResponse.kt
navikt
495,713,363
false
null
@file:UseSerializers(UuidSerializer::class) package no.nav.helsearbeidsgiver.inntektsmelding.api.response import kotlinx.serialization.EncodeDefault import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import no.nav.helsearbeidsgiver.utils.json.serializer.UuidSerializer import java.util.UUID @Serializable @OptIn(ExperimentalSerializationApi::class) data class RedisTimeoutResponse( // TODO slett etter endring i frontend val uuid: UUID? = null, val inntektsmeldingId: UUID? = null ) { @EncodeDefault val error = "Brukte for lang tid mot redis." } @Serializable @OptIn(ExperimentalSerializationApi::class) data class RedisPermanentErrorResponse( val inntektsmeldingId: UUID ) { @EncodeDefault val error = "Permanent feil mot redis." }
13
null
0
2
ac27b5b7ab057a45d64d31524cbe3cfbb9666489
863
helsearbeidsgiver-inntektsmelding
MIT License
test/fixtures/general/src/main/kotlin/pkt1/VarargReference.kt
seachicken
349,989,943
false
{"Common Lisp": 292446, "Java": 5483, "Kotlin": 5450, "Dockerfile": 1633}
package pkt1 class VarargReference { fun method(vararg vs: VarargHelper) { method(*vs) } }
3
Common Lisp
1
13
b233d85ffde99ef23926ad8c4000ef5a8829dae3
108
inga
MIT License
country_data/src/test/java/TestConvert.kt
igor-alyoshin
265,827,953
true
{"Gradle": 4, "YAML": 3, "Java Properties": 3, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Text": 1, "Markdown": 3, "Proguard": 2, "Java": 7, "XML": 128, "INI": 1, "Kotlin": 2, "JSON": 1}
import com.blongho.country_data.World import com.google.gson.Gson import org.junit.Test import java.io.File class TestConvert { @Test fun test(){ val path = "src/main/res" val imagesPath = "$path/drawable" val file = File(imagesPath) val icons = file.listFiles() ?: emptyArray() icons.forEach { iconFile -> iconFile.renameTo(File(iconFile.parent, iconFile.name.replace("ic_", "").replace("_svg", ""))) if (!iconFile.name.startsWith("lang_")) { iconFile.renameTo(File(iconFile.parent, iconFile.name.replace(iconFile.name, "lang_${iconFile.name}"))) } } val languages = arrayListOf<Lang>() var id = 0 icons.forEach { iconFile -> val name = iconFile.nameWithoutExtension languages.add(Lang(name.replace("lang_", ""), id.toString())) id++ } languages.add(Lang("xxx", "999")) val json = Gson().toJson(languages) println(json) } class Lang(val alpha3: String, val id: String) }
0
Java
0
0
6b9baa57ca66a16b7cddac9b84a818f05192111e
1,083
worldCountryData
MIT License
Desktop/src/jvmMain/kotlin/io/nacular/doodle/skia/Utils.kt
nacular
108,631,782
false
null
package io.nacular.doodle.skia import io.nacular.doodle.drawing.AffineTransform import io.nacular.doodle.drawing.Color import io.nacular.doodle.geometry.Path import io.nacular.doodle.geometry.Point import io.nacular.doodle.geometry.Polygon import io.nacular.doodle.geometry.Rectangle import io.nacular.doodle.geometry.toPath import org.jetbrains.skia.Matrix33 import org.jetbrains.skia.Matrix44 import org.jetbrains.skia.RRect import org.jetbrains.skia.Rect internal fun Color.skia(): Int = (((opacity * 0xFF).toUInt() shl 24) + (red.toUInt() shl 16) + (green.toUInt() shl 8) + blue.toUInt()).toInt() internal fun Rectangle.skia() = Rect.makeXYWH(x.toFloat(), y.toFloat(), width.toFloat(), height.toFloat()) internal fun Rectangle.rrect(radius: Float) = RRect.makeXYWH(x.toFloat(), y.toFloat(), width.toFloat(), height.toFloat(), radius) internal fun Polygon.skia() = toPath().skia() internal fun Point.skia() = org.jetbrains.skia.Point(x.toFloat(), y.toFloat()) internal fun Path.skia() = org.jetbrains.skia.Path.makeFromSVGString(data) internal fun AffineTransform.skia33() = Matrix33( scaleX.toFloat (), shearX.toFloat (), translateX.toFloat(), shearY.toFloat (), scaleY.toFloat (), translateY.toFloat(), 0f, 0f, 1f ) internal fun AffineTransform.skia44() = Matrix44( m00.toFloat(), m01.toFloat(), m02.toFloat(), m03.toFloat(), m10.toFloat(), m11.toFloat(), m12.toFloat(), m13.toFloat(), m20.toFloat(), m21.toFloat(), m22.toFloat(), m23.toFloat(), 0f, 0f, 0f, 1f )
4
Kotlin
19
450
2aba993826fcd67dcc825259d6fc7736039de5db
1,625
doodle
MIT License
src/test/kotlin/io/imotions/bson4k/encoder/BsonClassEncoderTest.kt
imotions
338,147,158
false
null
/* * Copyright 2022 iMotions A/S * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.imotions.bson4k.encoder import io.imotions.bson4k.Bson import io.imotions.bson4k.common.* import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.ints.shouldBeExactly import io.kotest.matchers.shouldBe import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import org.bson.BsonInt32 import org.bson.BsonNull import org.bson.BsonString @Serializable private data class DataClassWithDefaults( val s: String, val b: Boolean = true, val i: Int = 42 ) @ExperimentalSerializationApi class BsonClassEncoderTest : StringSpec({ "Encode class" { val clazz = Class2("Fred", 42) val document = bson.encodeToBsonDocument(clazz) .also { println(it.toJson()) } document.size shouldBeExactly 2 document.keys shouldContainAll listOf("x", "y") document.getString("x") shouldBe BsonString(clazz.x) document.getInt32("y") shouldBe BsonInt32(clazz.y) } "Encode class with nested class" { val nested = Class2("Fred", 42) val clazz = Class2(1L, nested) val document = bson.encodeToBsonDocument(clazz) .also { println(it.toJson()) } document.keys shouldContainAll listOf("x", "y") document.getDocument("y").keys shouldContainAll listOf("x", "y") } "Encode multiple nested classe including embedded array" { val nested = Class2("Fred", 42) val clazz = Class3(1L, "This is a comment", nested) val set = Class2("This is content", setOf(clazz)) val document = bson.encodeToBsonDocument(set) .also { println(it.toJson()) } document.keys shouldContainAll listOf("x", "y") document.getArray("y").size shouldBeExactly 1 document.getArray("y")[0].isDocument shouldBe true } "Encode nullable fields" { val testClass = Class3<Long, Int?, Class2<String, Int>>(12L, null, Class2("xyz", -42)) val document = bson.encodeToBsonDocument(testClass) .also { println(it.toJson()) } document["y"] shouldBe BsonNull() } "Encode enum fields" { val clazz = Class2<Byte, EnumClass>(16, EnumClass.THIRD) val document = bson.encodeToBsonDocument(clazz) .also { println(it) } document["y"] shouldBe BsonString(EnumClass.THIRD.name) } "Encode class with all null values" { val clazz = Wrapper2<Int?, Int?>(null, null) val document = bson.encodeToBsonDocument(clazz) .also { println(it) } document["x"] shouldBe BsonNull() document["y"] shouldBe BsonNull() } "Encode class with default nullables" { val encodeDefaultsBson = Bson { encodeDefaults = true } val clazz = Wrapper2Null<String, String>(y = "hello") val document = encodeDefaultsBson.encodeToBsonDocument(clazz) .also { println(it) } document["x"] shouldBe BsonNull() document["y"] shouldBe BsonString("hello") } "Encode class without defaults" { val clazz = DataClassWithDefaults("test") val document = bson.encodeToBsonDocument(clazz) .also { println(it) } document.keys shouldContainExactly listOf("s") } "Encode object" { val obj = ObjectNone val document = bson.encodeToBsonDocument(obj) .also { println(it) } document.keys.size shouldBe 0 } "Encode wrapped object" { val clazz = Wrapper(ObjectNone) val document = bson.encodeToBsonDocument(clazz) .also { println(it) } document.getDocument("value").keys.size shouldBe 0 } })
2
null
0
6
6194962a071937ce42eed7f64c6b3e837427dc18
4,412
bson4k
Apache License 2.0
src/main/java/io/github/intellij/dlanguage/codeinsight/render/BasicRenderer.kt
ErnyTech
146,434,208
false
null
package io.github.intellij.dlanguage.codeinsight.render import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementPresentation import io.github.intellij.dlanguage.codeinsight.dcd.completions.DCDCompletionKind import io.github.intellij.dlanguage.codeinsight.dcd.completions.DCDModel import io.github.intellij.dlanguage.icons.DlangIcons class BasicRenderer(internal var model: DCDModel) : LookupElement() { override fun getLookupString(): String { return if (model.kind === DCDCompletionKind.Function) model.value + "()" else model.value } override fun renderElement(presentation: LookupElementPresentation) { presentation.icon = DlangIcons.FILE presentation.itemText = model.value presentation.isItemTextBold = true // if typeText is not null that means it is user code // else it is language specific code if (model.typeText != null) presentation.typeText = model.typeText else presentation.isItemTextBold = false when (model.kind) { DCDCompletionKind.ClassName -> presentation.icon = DlangIcons.NODE_CLASS DCDCompletionKind.InterfaceName -> presentation.icon = DlangIcons.NODE_INTERFACE DCDCompletionKind.StructName -> presentation.icon = DlangIcons.NODE_STRUCT DCDCompletionKind.UnionName -> presentation.icon = DlangIcons.NODE_UNION DCDCompletionKind.VariableName -> presentation.icon = DlangIcons.NODE_FIELD DCDCompletionKind.MemberVariableName -> presentation.icon = DlangIcons.NODE_FIELD DCDCompletionKind.Keyword -> presentation.icon = null DCDCompletionKind.Function -> presentation.icon = DlangIcons.NODE_FUNCTION DCDCompletionKind.EnumName -> presentation.icon = DlangIcons.NODE_ENUM DCDCompletionKind.EnumMember -> presentation.icon = DlangIcons.NODE_FIELD DCDCompletionKind.PackageName -> presentation.icon = null DCDCompletionKind.ModuleName -> presentation.icon = DlangIcons.MODULE DCDCompletionKind.Array -> { } DCDCompletionKind.AssociativeArray -> { } DCDCompletionKind.AliasName -> presentation.icon = DlangIcons.NODE_ALIAS DCDCompletionKind.TemplateName -> { } DCDCompletionKind.MixinTemplate -> presentation.icon = DlangIcons.NODE_MIXIN } } }
1
null
1
1
b0fcc09ebe4287d60a1d35ba9e4387564e30a42d
2,558
intellij-dlanguage
MIT License
buildSrc/src/main/kotlin/karakum/table/Generator.kt
karakum-team
393,199,102
false
null
package karakum.table import karakum.common.GENERATOR_COMMENT import karakum.common.Suppress.NOTHING_TO_INLINE import karakum.common.fileSuppress import karakum.common.writeCode import java.io.File private val DEFAULT_IMPORTS = listOf( "js.promise.Promise", "kotlin.js.RegExp", "js.collections.JsMap", "js.array.ReadonlyArray", "js.objects.ReadonlyRecord", "js.symbol.Symbol", "js.array.JsTuple2", "js.core.Void", "seskar.js.JsIntValue", "seskar.js.JsValue", "web.dom.Document", ).map { it.substringAfterLast(".") to it } fun generateKotlinDeclarations( coreDefinitionsDir: File, sourceDir: File, ) { val content = readContent(coreDefinitionsDir) val targetDir = sourceDir.resolve("tanstack/table/core") .also { it.mkdirs() } for ((name, body) in convertDefinitions(content)) { val annotations = when { "external val " in body || "external object " in body || "external fun " in body -> "@file:JsModule(\"${Package.TABLE_CORE.moduleName}\")" "inline fun " in body -> fileSuppress(NOTHING_TO_INLINE) else -> "" } val fileName = if (name.endsWith("Fns") && "interface" in body) { name + ".type" } else name targetDir.resolve("$fileName.kt") .writeCode(fileContent(Package.TABLE_CORE, annotations, body)) } } private fun readContent( definitionsDir: File, ): String = definitionsDir.walk() .maxDepth(2) .filter { it.isFile } .filter { it.name.endsWith(".d.ts") } .map { file -> file.readLines() .filter { !it.startsWith("import ") } .filter { !it.startsWith("export * from ") } .joinToString("\n") .substringBefore("\nexport {") .trim() } .filter { it.isNotEmpty() } .joinToString("\n\n", "\n\n") private fun fileContent( pkg: Package, annotations: String, body: String, ): String { val defaultImports = DEFAULT_IMPORTS .filter { it.first in body } .map { "import ${it.second}" } .plus("import tanstack.table.core.VisibilityColumn as ColumnVisibilityColumn") .joinToString("\n") return sequenceOf( "// $GENERATOR_COMMENT", annotations, pkg.pkg, defaultImports, body, ).filter { it.isNotEmpty() } .joinToString("\n\n") }
0
null
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
2,500
types-kotlin
Apache License 2.0
app/src/main/java/com/example/myapplication2/DataQuestions.kt
veridetta
669,381,677
false
null
package com.example.myapplication2 object DataQuestions { const val TOTAL_QUESTION_KEY: String = "total_question" const val SCORE_KEY: String = "score" private val objectId = arrayOf( // Present Tense (ID 1-10) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Past Tense (ID 11-20) 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, // Future Tense (ID 21-30) 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ) private val objectQuestion = arrayOf( // Present Tense "I play football in the yard.", "She sings beautifully.", "They speak English fluently.", "The train departs at 9 AM.", "My sister watches TV in the evening.", "He eats breakfast every morning.", "The sun rises in the east.", "The teacher explains the lesson.", "The birds sing in the tree.", "The cat chases the mouse.", // ... add more present tense questions (10 in total) // Past Tense "I cooked a cake yesterday.", "They went to the beach last summer.", "She finished her homework last night.", "He visited his grandparents last week.", "We watched a movie at the cinema.", "The dog barked loudly last night.", "She danced at the party.", "They played soccer in the park.", "I visited Paris last year.", "The children studied for the exam.", // ... add more past tense questions (10 in total) // Future Tense "I will visit my grandparents next week.", "She is going to become a teacher.", "We will have a meeting tomorrow.", "They are leaving for vacation next month.", "He will buy a new car soon.", "She is meeting her friends in the evening.", "I am going to learn to play the guitar.", "The school will organize a field trip.", "They will arrive at the airport at 6 PM.", "We are going to celebrate his birthday.", // ... add more future tense questions (10 in total) ) private val objectOptionOne = arrayOf( // Present Tense "play", "sings", "speaks", "departs", "watches", "eats", "rises", "explains", "sing", "chases", // ... add more present tense options (10 in total) // Past Tense "cooked", "went", "finished", "visited", "watched", "barked", "danced", "played", "visited", "studied", // ... add more past tense options (10 in total) // Future Tense "will visit", "is going to become", "will have", "are leaving", "will buy", "is meeting", "am going to learn", "will organize", "will arrive", "are going to celebrate", // ... add more future tense options (10 in total) ) private val objectOptionTwo = arrayOf( // Present Tense "plays", "sing", "speaking", "depart", "watch", "ate", "rise", "explain", "sings", "chase", // ... add more present tense options (10 in total) // Past Tense "cooking", "gone", "finish", "visits", "watches", "bark", "dancing", "playing", "visit", "study", // ... add more past tense options (10 in total) // Future Tense "visits", "will become", "having", "will leave", "buys", "meet", "going to learn", "organize", "arrive", "celebrate", // ... add more future tense options (10 in total) ) private val objectOptionThree = arrayOf( // Present Tense "playing", "sang", "speak", "departing", "watched", "eat", "rising", "explaining", "song", "chased", // ... add more present tense options (10 in total) // Past Tense "cook", "go", "finishing", "visited", "watching", "barking", "dance", "plays", "visited", "studies", // ... add more past tense options (10 in total) // Future Tense "will visiting", "becoming", "has", "is leaving", "buying", "will meet", "to learn", "will organizing", "are arriving", "going to celebrating", // ... add more future tense options (10 in total) ) private val objectOptionFour = arrayOf( // Present Tense "played", "is singing", "spoken", "departs", "watches", "eaten", "rose", "explains", "sang", "chased", // ... add more present tense options (10 in total) // Past Tense "cook", "went", "finishes", "visiting", "watched", "barked", "danced", "play", "visits", "study", // ... add more past tense options (10 in total) // Future Tense "visited", "to become", "having", "leaves", "bought", "meets", "learn", "organized", "arrives", "celebrates", // ... add more future tense options (10 in total) ) private val objectAnswer = arrayOf( // Present Tense 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, // Past Tense 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, // Future Tense 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 ) fun getQuestions(): ArrayList<Questions> { val questionList = ArrayList<Questions>() // Create a list of question indices and shuffle them val shuffledIndices = objectId.indices.toMutableList().apply { shuffle() }.take(10) // Add questions to the questionList in the shuffled order for (index in shuffledIndices) { val question = Questions() question.id = objectId[index] question.question = objectQuestion[index] // TODO buat ambil gambar // if (position <= 7) // question.image = objectImage[position] // Shuffle the options for each question val options = mutableListOf( objectOptionOne[index], objectOptionTwo[index], objectOptionThree[index], objectOptionFour[index] ).apply { shuffle() } question.optionOne = options[0] question.optionTwo = options[1] question.optionThree = options[2] question.optionFour = options[3] // Sesuaikan jawaban dengan urutan pilihan yang sudah diacak question.answer = options.indexOfFirst { it == objectOptionOne[index] } + 1 questionList.add(question) } return questionList } }
0
Kotlin
0
0
0b37e9f9be943ba46fee6f76b4d4f09e4ffbee2f
7,144
QuizEng
MIT License
qatoolkit-inspector-core/src/main/java/com/github/iojjj/bootstrap/pub/qatoolkit/inspector/Order.kt
Iojjj
429,845,456
false
{"Kotlin": 694141}
package com.github.iojjj.bootstrap.pub.qatoolkit.inspector /** * Annotation that specifies order in which object inspection happens. * @property value Order of inspection. Smaller numbers results in earlier inspection. */ @Retention(AnnotationRetention.RUNTIME) annotation class Order(val value: Int = 0)
0
Kotlin
1
3
8f131d8132b0deb6a638d2a66fdf1d53911cca32
309
QA-Toolkit
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/model/BulkAppointment.kt
ministryofjustice
533,838,017
false
null
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model import com.fasterxml.jackson.annotation.JsonFormat import io.swagger.v3.oas.annotations.media.Schema import java.time.LocalDateTime @Schema( description = "Describes a list of activities created as part of a single bulk operation", ) data class BulkAppointment( @Schema( description = "The internally generated identifier for this bulk appointment", example = "12345", ) val bulkAppointmentId: Long = 0, @Schema( description = "The list of appointments created in bulk.", ) val appointments: List<Appointment>, @Schema( description = "The date and time this appointment was created. Will not change", ) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val created: LocalDateTime, @Schema( description = """ The username of the user authenticated via HMPPS auth that created the appointment. Usually a NOMIS username """, example = "AAA01U", ) val createdBy: String, )
4
Kotlin
0
1
9f121ceca8be8482d39edc7cd16180ae586e5b34
1,012
hmpps-activities-management-api
MIT License
lib/src/main/kotlin/stumpers/Cleaning.kt
cs124-illinois
585,572,354
false
{"Kotlin": 402255, "ANTLR": 73858, "TypeScript": 31780, "HTML": 11586, "Java": 8021, "Dockerfile": 924}
@file:Suppress("unused") package edu.illinois.cs.cs125.questioner.lib.stumpers import com.mongodb.client.MongoCollection import com.mongodb.client.model.Filters import edu.illinois.cs.cs125.jeed.core.KtLintArguments import edu.illinois.cs.cs125.jeed.core.Source import edu.illinois.cs.cs125.jeed.core.googleFormat import edu.illinois.cs.cs125.jeed.core.hasBadWords import edu.illinois.cs.cs125.jeed.core.ktFormat import edu.illinois.cs.cs125.jeed.core.stripAssertionMessages import edu.illinois.cs.cs125.jeed.core.stripComments import edu.illinois.cs.cs125.questioner.lib.Language import edu.illinois.cs.cs125.questioner.lib.Question import edu.illinois.cs.cs125.questioner.lib.deTemplate import edu.illinois.cs.cs125.questioner.lib.templateSubmission import org.bson.BsonDocument import java.time.Instant data class Candidate( val submitted: Instant, val contents: String, val originalID: String, val question: Question, val language: Language ) { val contentsHash = contents.md5() fun exists(collection: MongoCollection<BsonDocument>) = collection.countDocuments(Filters.eq("originalID", originalID)) > 0 || collection.countDocuments( Filters.and( Filters.eq("coordinates.language", language.toString()), Filters.eq("coordinates.path", question.published.path), Filters.eq("coordinates.author", question.published.author), Filters.eq("hashes.original", contentsHash) ) ) > 0 } suspend fun Candidate.clean(): Solution { val template = question.getTemplate(language) val fileType = when (language) { Language.kotlin -> Source.FileType.KOTLIN Language.java -> Source.FileType.JAVA } val cleanedSource = contents.stripComments(fileType).let { if (template != null) { "// TEMPLATE_START\n$it\n// TEMPLATE_END \n" } else { it } }.let { contents -> question.templateSubmission(contents, language) }.stripAssertionMessages() val hasBadWords = cleanedSource.hasBadWords(question.badWords()) != null val formattedSource = when (cleanedSource.type) { Source.FileType.JAVA -> cleanedSource.googleFormat() else -> cleanedSource.ktFormat(KtLintArguments(failOnError = false, indent = 2)) }.contents.deTemplate(template) return Solution( submitted, formattedSource, Solution.Hashes(contentsHash, formattedSource.md5()), hasBadWords, originalID, Coordinates(language, question.published.path, question.published.author), valid = false ) }
0
Kotlin
0
1
ab0abe4d3ab2ef61a417bf0ddab607f867f6c74c
2,694
questioner
MIT License
squash-core/src/org/jetbrains/squash/schema/DatabaseSchema.kt
vyasenenko
138,751,073
true
{"Kotlin": 248042}
package org.jetbrains.squash.schema import org.jetbrains.squash.change.ChangeLogController import org.jetbrains.squash.definition.* import org.jetbrains.squash.dialect.* /** * Provides facilities for querying and modifying database schema */ interface DatabaseSchema { fun tables(): Sequence<SchemaTable> fun create(tables: List<TableDefinition>) fun createStatements(tables: List<TableDefinition>): List<SQLStatement> fun drop(tables: List<TableDefinition>) val changeLogController: ChangeLogController data class DatabaseSchemaValidationItem(val message: String) fun log(tables: List<TableDefinition>) fun validate(tables: List<org.jetbrains.squash.definition.Table>): List<DatabaseSchemaValidationItem> interface SchemaTable { val name: String fun columns(): Sequence<SchemaColumn> } interface SchemaColumn { val name: String val nullable: Boolean val type: String val size: Int? } } fun DatabaseSchema.create(vararg tables: TableDefinition) = create(tables.asList()) fun DatabaseSchema.drop(vararg tables: TableDefinition) = drop(tables.asList())
0
Kotlin
0
0
290a89ff97c6515b85055dc8966d93528cb467ab
1,159
squash
Apache License 2.0
src/main/kotlin/care/better/pf4j/ksp/processor/ExtensionSymbolProcessor.kt
better-care
701,811,405
false
{"Kotlin": 10503}
/* Copyright 2023 Better Ltd (www.better.care) * * 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 care.better.pf4j.ksp.processor import com.google.devtools.ksp.processing.Dependencies import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSDeclaration import com.google.devtools.ksp.symbol.KSType import com.google.devtools.ksp.validate import org.pf4j.Extension import org.pf4j.ExtensionPoint import kotlin.reflect.KClass /** * @author Primoz Delopst * @since 1.0.0 * * Implementation of the [SymbolProcessor] that process [Extension] annotation. * * @constructor Creates a new instance of [ExtensionSymbolProcessor] * @param environment [SymbolProcessorEnvironment] */ class ExtensionSymbolProcessor(private val environment: SymbolProcessorEnvironment) : SymbolProcessor { companion object { private const val EXTENSION_CLASS_NAME: String = "org.pf4j.Extension" private const val EXTENSION_POINT_CLASS_NAME: String = "org.pf4j.ExtensionPoint" private const val USE_JSP: String = "pf4j.useJavaServiceProviders" private const val IGNORE_EXTENSION_POINT: String = "pf4j.ignoreExtensionPoint" private const val EXTENSION_POINTS_ATTRIBUTE: String = "points" private const val EXTENSION_FILE_PATH: String = "META-INF/extensions" private const val EXTENSION_FILE_EXTENSION: String = "idx" private const val GENERATED_BY_PF4J: String = "#Generated by PF4J" private const val NEW_LINE: String = "\n" private const val BLANK_STRING: String = "" } private val ignoreExtensionPoint: Boolean = environment.options[IGNORE_EXTENSION_POINT]?.toBoolean() ?: System.getProperty("pf4j.ignoreExtensionPoint", "false").toBoolean() private val useJavaServiceProviders = environment.options[USE_JSP]?.toBoolean() ?: System.getProperty("pf4j.useJavaServiceProviders", "false").toBoolean() /** * Finalize the processing of a [Extension] annotation processing. */ override fun finish() { environment.logger.info("Processing of org.pf4j.Extension annotations finished successfully.") } /** * Handle errors of the [Extension] annotation processing. */ override fun onError() { environment.logger.info("Error occurred while processing org.pf4j.Extension annotations.") } /** * Processes the [Extension] annotations. * * @param resolver [Resolver] * @return [List] of [KSAnnotated] */ override fun process(resolver: Resolver): List<KSAnnotated> { val classDeclarations: List<KSClassDeclaration> = resolver.getSymbolsWithAnnotation(Extension::class) if (classDeclarations.isEmpty()) { return emptyList() } if (useJavaServiceProviders) { classDeclarations.map { classDeclaration -> classDeclaration.toClassName() }.distinct().forEach { className -> val file = environment.codeGenerator.createNewFileByPath( Dependencies(false), className, BLANK_STRING) file.write( "$GENERATED_BY_PF4J$NEW_LINE${className}".toByteArray()) } } else { val file = environment.codeGenerator.createNewFileByPath( Dependencies(false), EXTENSION_FILE_PATH, EXTENSION_FILE_EXTENSION) file.write( "$GENERATED_BY_PF4J$NEW_LINE${ classDeclarations.map { classDeclaration -> classDeclaration.toClassName() }.distinct().joinToString(NEW_LINE) }".toByteArray()) } return (classDeclarations).filterNot { it.validate() }.toList() } /** * Returns [List] of [KSClassDeclaration] for [KClass]. * * @param kClass [KClass] * @return [List] of [KSClassDeclaration] */ private fun Resolver.getSymbolsWithAnnotation(kClass: KClass<*>): List<KSClassDeclaration> = getSymbolsWithAnnotation(kClass.qualifiedName.toString()) .filterIsInstance<KSClassDeclaration>() .resolveExtensionPoints() .distinct() .toList() /** * Resolves and returns [Sequence] of [KSClassDeclaration] that implements [ExtensionPoint]. * * @return [Sequence] of [KSClassDeclaration] */ private fun Sequence<KSClassDeclaration>.resolveExtensionPoints(): Sequence<KSClassDeclaration> = flatMap { classDeclaration -> val points = classDeclaration.annotations .filter { it.annotationType.resolve().declaration.qualifiedName?.asString() == EXTENSION_CLASS_NAME } .flatMap { it.arguments.asSequence() } .filter { it.name?.asString() == EXTENSION_POINTS_ATTRIBUTE } .flatMap { if (it.value is List<*>) (it.value as List<*>).asSequence().filterNotNull() else sequenceOf(it.value).filterNotNull() } .filterIsInstance<KSType>() .map { it.declaration } .filterIsInstance<KSClassDeclaration>() .toList() when { points.isNotEmpty() -> points.asSequence() classDeclaration.isImplementingExtensionPoint() -> sequenceOf(classDeclaration) else -> if (ignoreExtensionPoint) emptySequence() else throw ExtensionSymbolProcessorException("${classDeclaration.toClassName()} does not implement $EXTENSION_POINT_CLASS_NAME interface.") } } /** * Checks if [KSClassDeclaration] implements [ExtensionPoint]. * * @return [Boolean] indicating if [KSClassDeclaration] implements [ExtensionPoint] */ private fun KSClassDeclaration.isImplementingExtensionPoint(): Boolean = superTypes.any { superType -> val declaration = superType.resolve().declaration when { declaration.qualifiedName?.asString() == EXTENSION_POINT_CLASS_NAME -> true declaration is KSClassDeclaration -> declaration.isImplementingExtensionPoint() else -> false } } /** * Returns [KSClassDeclaration] declared class name of the processed class. * * @return [KSClassDeclaration] declared class name */ private fun KSClassDeclaration.toClassName(): String = "${packageName.asString()}.${parentDeclaration.toClassName()}${simpleName.asString()}" /** * Returns [KSDeclaration] declared class name of the processed. * Note that [KSDeclaration] is used for outer class. * * @return [KSDeclaration] declared class name */ private fun KSDeclaration?.toClassName(): String = when { this == null -> BLANK_STRING parentDeclaration != null -> "${simpleName.asString()}$${(parentDeclaration.toClassName())}" else -> "${simpleName.asString()}$" } }
0
Kotlin
1
3
f1c6c97568bdd3761b3a33eae2bd310652a0ab43
7,839
pf4j-kotlin-symbol-processing
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/educationandworkplanapi/app/database/jpa/mapper/conversation/ConversationNoteEntityMapper.kt
ministryofjustice
653,598,082
false
{"Kotlin": 1450725, "Mustache": 2705, "Dockerfile": 1375}
package uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.mapper.conversation import org.mapstruct.Mapper import org.mapstruct.Mapping import uk.gov.justice.digital.hmpps.domain.learningandworkprogress.conversation.ConversationNote import uk.gov.justice.digital.hmpps.domain.learningandworkprogress.conversation.dto.CreateConversationNoteDto import uk.gov.justice.digital.hmpps.domain.personallearningplan.Step import uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.entity.conversation.ConversationNoteEntity import uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.mapper.ExcludeJpaManagedFields import uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.mapper.GenerateNewReference import java.util.UUID @Mapper( imports = [UUID::class], ) interface ConversationNoteEntityMapper { /** * Maps the supplied [CreateConversationNoteDto] into a new un-persisted [ConversationNoteEntity]. * A new reference number is generated and mapped. The JPA managed fields are not mapped. * This method is suitable for creating a new [ConversationNoteEntity] to be subsequently persisted to the database. */ @ExcludeJpaManagedFields @GenerateNewReference @Mapping(target = "createdAtPrison", source = "prisonId") @Mapping(target = "updatedAtPrison", source = "prisonId") fun fromCreateDtoToEntity(createConversationNoteDto: CreateConversationNoteDto): ConversationNoteEntity /** * Maps the supplied [ConversationNoteEntity] into the domain [Step]. */ @Mapping(target = "lastUpdatedBy", source = "updatedBy") @Mapping(target = "lastUpdatedByDisplayName", source = "updatedByDisplayName") @Mapping(target = "lastUpdatedAt", source = "updatedAt") @Mapping(target = "lastUpdatedAtPrison", source = "updatedAtPrison") fun fromEntityToDomain(conversationNoteEntity: ConversationNoteEntity): ConversationNote }
4
Kotlin
0
2
7c64ff394d9f16bfe66652a59f8a3a87de34d0a3
1,917
hmpps-education-and-work-plan-api
MIT License
KotlinMultiplatform/XFullStack/composeApp/src/commonMain/kotlin/domain/repositories/view/ViewRepositoryImplementation.kt
pradyotprksh
385,586,594
false
{"Kotlin": 2456135, "Dart": 1066884, "Python": 319400, "Rust": 180589, "Swift": 147761, "C++": 113494, "CMake": 94132, "Go": 45704, "HTML": 21089, "Ruby": 12424, "C": 8043, "Shell": 5675, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "JavaScript": 781, "CSS": 588, "Objective-C": 380, "Dockerfile": 32}
package domain.repositories.view import core.models.realm.ViewDB import data.request.ViewRequest import domain.services.view.ViewDBService import domain.services.view.ViewRemoteService import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import utils.Logger import utils.LoggerLevel import utils.XFullStackResponseStatus class ViewRepositoryImplementation( private val viewDBService: ViewDBService, private val viewRemoteService: ViewRemoteService, ) : ViewRepository { override suspend fun saveView(id: String) { viewDBService.insertViewDetails( ViewDB().apply { this.viewedId = id this.isUpdatedOnline = false }, ) } override suspend fun listenOnViewAdd(): Flow<List<ViewDB>> { return viewDBService.getListenToViewUpdate().map { it.list } } override suspend fun saveViews(views: List<ViewDB>) { try { val request = views.map { ViewRequest( viewedId = it.viewedId, ) } val response = viewRemoteService.saveViews(request) if (response.status == XFullStackResponseStatus.Success) { viewDBService.updateViewsOnlineUpdate(views) } } catch (e: Exception) { Logger.log(LoggerLevel.Error, "saveViews ${e.message ?: ""}") } } }
0
Kotlin
10
21
8393123d6d6b49cbde723737762428d1c23dd391
1,418
development_learning
MIT License
core/src/main/java/ir/amirab/validator/Rule.kt
amir1376
462,953,343
false
{"Kotlin": 35669}
package ir.amirab.validator import ir.amirab.validator.result.ValidationResult interface Rule<in INPUT,out RESULT: ValidationResult>{ suspend fun validate(input:INPUT):RESULT }
0
Kotlin
1
13
6769bbe93494c7a557933838db662abc2ba28285
182
kotlin-validator
Apache License 2.0
app/src/main/java/com/babylon/wallet/android/presentation/account/composable/AssetMetadataRow.kt
radixdlt
513,047,280
false
null
package com.babylon.wallet.android.presentation.account.composable import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import com.babylon.wallet.android.R import com.babylon.wallet.android.designsystem.theme.RadixTheme import com.babylon.wallet.android.domain.model.resources.metadata.Metadata import com.babylon.wallet.android.domain.model.resources.metadata.MetadataType import com.babylon.wallet.android.presentation.ui.composables.ExpandableText import com.babylon.wallet.android.presentation.ui.composables.actionableaddress.ActionableAddressView import com.babylon.wallet.android.utils.openUrl import rdx.works.core.displayableQuantity import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.util.Locale @Composable fun AssetMetadataRow( modifier: Modifier, key: String, valueView: @Composable RowScope.() -> Unit ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( modifier = Modifier.padding(end = RadixTheme.dimensions.paddingMedium), text = key.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }, style = RadixTheme.typography.body1Regular, color = RadixTheme.colors.gray2 ) valueView() } } @Composable fun Metadata.View(modifier: Modifier) { if (isRenderedInNewLine) { Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(RadixTheme.dimensions.paddingSmall) ) { KeyView() ValueView(isRenderedInNewLine = true) } } else { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { KeyView() Spacer(modifier = Modifier.width(RadixTheme.dimensions.paddingMedium)) ValueView(isRenderedInNewLine = false) } } } @Composable fun Metadata.KeyView( modifier: Modifier = Modifier ) { Text( modifier = modifier.padding(end = RadixTheme.dimensions.paddingMedium), text = key, style = RadixTheme.typography.body1Regular, color = RadixTheme.colors.gray2, textAlign = TextAlign.Start ) } @Suppress("CyclomaticComplexMethod") @Composable fun Metadata.ValueView( modifier: Modifier = Modifier, isRenderedInNewLine: Boolean ) { val context = LocalContext.current when (this) { is Metadata.Collection, is Metadata.Map -> Text( modifier = modifier, text = stringResource(id = R.string.assetDetails_NFTDetails_complexData), style = RadixTheme.typography.body1HighImportance, color = RadixTheme.colors.gray1, textAlign = if (isRenderedInNewLine) TextAlign.Start else TextAlign.End, maxLines = 2 ) is Metadata.Primitive -> when (valueType) { MetadataType.Bool, is MetadataType.Integer, MetadataType.Bytes, MetadataType.Enum, MetadataType.PublicKeyEcdsaSecp256k1, MetadataType.PublicKeyEddsaEd25519, MetadataType.PublicKeyHashEcdsaSecp256k1, MetadataType.PublicKeyHashEddsaEd25519 -> Text( modifier = modifier, text = value, style = RadixTheme.typography.body1HighImportance, color = RadixTheme.colors.gray1, textAlign = if (isRenderedInNewLine) TextAlign.Start else TextAlign.End, maxLines = 2 ) MetadataType.String -> ExpandableText( modifier = modifier, text = value, style = RadixTheme.typography.body1HighImportance.copy( color = RadixTheme.colors.gray1, textAlign = if (isRenderedInNewLine) TextAlign.Start else TextAlign.End, ), toggleStyle = RadixTheme.typography.body1HighImportance.copy( color = RadixTheme.colors.gray2 ), ) MetadataType.Instant -> { val displayable = remember(value) { val epochSeconds = value.toLongOrNull() ?: return@remember value val dateTime = Instant.ofEpochSecond(epochSeconds) .atZone(ZoneId.systemDefault()) .toLocalDateTime() dateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)) } Text( modifier = modifier, text = displayable, style = RadixTheme.typography.body1HighImportance, color = RadixTheme.colors.gray1, textAlign = if (isRenderedInNewLine) TextAlign.Start else TextAlign.End, maxLines = 2 ) } MetadataType.Address, MetadataType.NonFungibleGlobalId, MetadataType.NonFungibleLocalId -> ActionableAddressView( modifier = modifier, address = value ) MetadataType.Decimal -> Text( modifier = modifier, // If value is unable to transform to big decimal we just display raw value text = value.toBigDecimalOrNull()?.displayableQuantity() ?: value, style = RadixTheme.typography.body1HighImportance, color = RadixTheme.colors.gray1, textAlign = if (isRenderedInNewLine) TextAlign.Start else TextAlign.End, maxLines = 2 ) MetadataType.Url -> Row( modifier = modifier .fillMaxWidth() .clickable { context.openUrl(value) }, horizontalArrangement = Arrangement.spacedBy(RadixTheme.dimensions.paddingDefault), verticalAlignment = Alignment.CenterVertically ) { Text( text = value, style = RadixTheme.typography.body1StandaloneLink, color = RadixTheme.colors.blue1 ) Icon( painter = painterResource(id = R.drawable.ic_external_link), contentDescription = null, tint = RadixTheme.colors.gray3 ) } } } } private const val ASSET_METADATA_SHORT_STRING_THRESHOLD = 40 private val Metadata.isRenderedInNewLine: Boolean get() = this is Metadata.Primitive && ( valueType is MetadataType.Url || (valueType is MetadataType.String && value.length > ASSET_METADATA_SHORT_STRING_THRESHOLD) )
9
null
5
6
2509c9bd9b5db75bc4d793f98d3ac055a8ae4730
7,790
babylon-wallet-android
Apache License 2.0
idscp2/src/main/kotlin/de/fhg/aisec/ids/idscp2/idscp_core/fsm/DynamicTimer.kt
rajesh-ibm-power
333,355,999
true
{"Kotlin": 603521, "Java": 571930, "TypeScript": 78380, "HTML": 44870, "Shell": 17139, "CSS": 14035, "Python": 7090, "Handlebars": 5731, "Dockerfile": 3711, "Prolog": 2993, "HCL": 2131, "Harbour": 190}
package de.fhg.aisec.ids.idscp2.idscp_core.fsm import java.util.concurrent.locks.ReentrantLock /** * A DynamicTimer class that provides an API to the FSM to start and cancel timeout threads * without a fixed timeout delay (in ms) * The timer ensures that no canceled timer is able to trigger a timeout transitions * * @author <NAME> (<EMAIL>) */ class DynamicTimer internal constructor(private val fsmIsBusy: ReentrantLock, private val timeoutHandler: Runnable) { private var thread: TimerThread? = null private val mutex = ReentrantLock(true) fun resetTimeout(delay: Long) { cancelTimeout() start(delay) } /* * Start a timer thread that triggers the timeout handler routine after a given timout delay */ fun start(delay: Long) { mutex.lock() thread = TimerThread(delay, timeoutHandler, fsmIsBusy).also { it.start() } mutex.unlock() } /* * Cancel the current timer thread */ fun cancelTimeout() { mutex.lock() thread?.safeStop() thread = null mutex.unlock() } }
0
Kotlin
0
0
11fcc55b0bb38d9fe9b4b968db35e2b7ea322b63
1,103
trusted-connector
Apache License 2.0
app/src/main/java/br/com/programadordeelite/gdc/codelab/datamanagement/viewmodelfactory/GameViewModel.kt
treslines
346,119,037
false
null
package com.prado.android.codelab.datamanagement.viewmodelfactory import androidx.lifecycle.ViewModel import timber.log.Timber class GameViewModel: ViewModel() { // a palavra atual, inicialmente vazia var word = "" // o placar atual de pontuação var score = 0 // lista de palavras que devem ser advinhadas private lateinit var wordList: MutableList<String> /** * Reseta a lista de palavras e randomiza a ordem delas */ private fun resetList() { wordList = mutableListOf( "queen", "hospital", "basketball", "cat", "change", "snail", "soup", "calendar", "sad", "desk", "guitar", "home", "railway", "zebra", "jelly", "car", "crow", "trade", "bag", "roll", "bubble" ) wordList.shuffle() } init { Timber.i("GameViewModel created!") resetList() nextWord() } /** Callback called when the ViewModel is destroyed */ override fun onCleared() { super.onCleared() Timber.i("GameViewModel destroyed!") } /** metodos para atualizar a UI **/ fun onSkip() { score--; nextWord() } fun onCorrect() { score++; nextWord() } /** Move para a proxima palavra na lista.*/ private fun nextWord() { // Seleciona e remove a palavra da lista if (wordList.isNotEmpty()) { word = wordList.removeAt(0) } } }
0
Kotlin
9
67
1ff9f927390e4da543951fe0d1adc155d2ac8fd5
1,435
aad
Apache License 2.0