path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/java/com/store/model/Product.kt
znsio
690,364,752
false
{"Kotlin": 19697, "Java": 890}
package com.store.model import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.concurrent.atomic.AtomicInteger import javax.validation.constraints.NotNull import javax.validation.constraints.Positive data class Product( @field:NotNull @field:JsonDeserialize(using = StrictStringDeserializer::class) val name: String = "", @field:NotNull val type: String = "gadget", @field:NotNull @field:Positive val inventory: Int = 0, val id: Int = idGenerator.getAndIncrement() ) { companion object { val idGenerator: AtomicInteger = AtomicInteger() } } enum class ProductType { book, food, gadget, other }
11
Kotlin
2
1
993fb949e107f815917635da8c9491854779457d
671
specmatic-order-api-java-with-oauth
MIT License
app/src/main/java/com/elpassion/memoryleaks/model/Elders.kt
droidcon-italy-hackathon-2016
55,836,640
false
null
package com.elpassion.memoryleaks.model data class Elders(val relatives: List<Elder>)
0
Kotlin
0
0
ab26d5ada97d7b873a72b39748a9ea0ff16b3306
86
memory-leaks-android
Apache License 2.0
src/main/kotlin/br/com/zupacademy/sergio/proposal/security/WebSecurityConfiguration.kt
sergioamorim
385,819,391
true
{"Kotlin": 46305, "Dockerfile": 1397}
package br.com.zupacademy.sergio.proposal.security import org.springframework.context.annotation.Configuration import org.springframework.http.HttpMethod import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.config.web.servlet.invoke import org.springframework.security.web.util.matcher.AntPathRequestMatcher @Configuration class WebSecurityConfiguration : WebSecurityConfigurerAdapter() { override fun configure(httpSecurity: HttpSecurity) { httpSecurity { csrf { disable() } authorizeRequests { authorize( AntPathRequestMatcher("/actuator/prometheus", HttpMethod.GET.name), hasAuthority("SCOPE_prometheus") ) authorize( AntPathRequestMatcher("/**", HttpMethod.GET.name), hasAuthority("SCOPE_proposal:read") ) authorize( AntPathRequestMatcher("/**", HttpMethod.POST.name), hasAuthority("SCOPE_proposal:write") ) authorize(anyRequest, authenticated) } sessionManagement { sessionCreationPolicy = SessionCreationPolicy.STATELESS } oauth2ResourceServer { jwt { } } } } }
0
Kotlin
0
0
d0f0e2b8a0497c506cade51030704d90b4e2549b
1,381
proposta
Apache License 2.0
fuel/src/main/kotlin/com/github/kittinunf/fuel/core/Response.kt
zuhryfayesz
159,620,704
true
{"Kotlin": 487458, "Java": 6968, "Shell": 686}
package com.github.kittinunf.fuel.core import java.io.ByteArrayInputStream import java.net.URL import java.net.URLConnection data class Response( val url: URL, val statusCode: Int = -1, val responseMessage: String = "", val headers: Headers = Headers(), val contentLength: Long = 0L, internal var body: Body = DefaultBody() ) { fun body(): Body = body val data get() = body.toByteArray() /** * Get the current values of the header, after normalisation of the header * @param header [String] the header name * @return the current values (or empty if none) */ operator fun get(header: String): HeaderValues { return headers[header] } fun header(header: String) = get(header) override fun toString(): String { val contentType = guessContentType() val bodyString = when { body.isEmpty() -> "empty" body.isConsumed() -> "consumed" else -> processBody(contentType, body.toByteArray()) } return buildString { appendln("<-- $statusCode ($url)") appendln("Response : $responseMessage") appendln("Length : $contentLength") appendln("Body : ($bodyString)") appendln("Headers : (${headers.size})") val appendHeaderWithValue = { key: String, value: String -> appendln("$key : $value") } headers.transformIterate(appendHeaderWithValue) } } internal fun guessContentType(headers: Headers = this.headers): String { val contentTypeFromHeaders = headers[Headers.CONTENT_TYPE].lastOrNull() if (!contentTypeFromHeaders.isNullOrEmpty()) { return contentTypeFromHeaders } val contentTypeFromStream = URLConnection.guessContentTypeFromStream(ByteArrayInputStream(data)) return if (contentTypeFromStream.isNullOrEmpty()) "(unknown)" else contentTypeFromStream } internal fun processBody(contentType: String, bodyData: ByteArray): String { return if (contentType.isNotEmpty() && (contentType.contains("image/") || contentType.contains("application/octet-stream"))) { "$contentLength bytes of ${guessContentType(headers)}" } else if (bodyData.isNotEmpty()) { String(bodyData) } else { "(empty)" } } companion object { fun error(): Response = Response(URL("http://.")) } } val Response.isStatusInformational get() = (statusCode / 100) == 1 val Response.isSuccessful get() = (statusCode / 100) == 2 val Response.isStatusRedirection get() = (statusCode / 100) == 3 val Response.isClientError get() = (statusCode / 100) == 4 val Response.isServerError get() = (statusCode / 100) == 5
0
Kotlin
0
1
fba92d4a215fa5985673692c84b8e00553d554ab
2,827
Fuel
MIT License
src/test/kotlin/no/nav/hm/grunndata/register/product/ProductRegistrationApiTest.kt
navikt
572,421,718
false
null
package no.nav.hm.grunndata.register.product import io.kotest.matchers.comparables.shouldBeGreaterThan import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.micronaut.security.authentication.UsernamePasswordCredentials import io.micronaut.test.annotation.MockBean import io.micronaut.test.extensions.junit5.annotation.MicronautTest import io.mockk.mockk import kotlinx.coroutines.runBlocking import no.nav.hm.grunndata.rapid.dto.* import no.nav.hm.grunndata.register.security.LoginClient import no.nav.hm.grunndata.register.security.Roles import no.nav.hm.grunndata.register.supplier.Supplier import no.nav.hm.grunndata.register.supplier.SupplierRepository import no.nav.hm.grunndata.register.supplier.toDTO import no.nav.hm.grunndata.register.user.User import no.nav.hm.grunndata.register.user.UserAttribute import no.nav.hm.grunndata.register.user.UserRepository import no.nav.hm.rapids_rivers.micronaut.RapidPushService import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.time.LocalDateTime import java.util.* @MicronautTest class ProductRegistrationApiTest(private val apiClient: ProductionRegistrationApiClient, private val loginClient: LoginClient, private val userRepository: UserRepository, private val supplierRepository: SupplierRepository) { val email = "<EMAIL>" val password = "<PASSWORD>" val supplierId = UUID.randomUUID() val supplierId2 = UUID.randomUUID() var testSupplier: SupplierDTO? = null var testSupplier2: SupplierDTO? = null @MockBean(RapidPushService::class) fun rapidPushService(): RapidPushService = mockk(relaxed = true) @BeforeEach fun createUserSupplier() { runBlocking { testSupplier = supplierRepository.save( Supplier( id = supplierId, info = SupplierInfo( address = "address 3", homepage = "https://www.hompage.no", phone = "+47 12345678", email = "<EMAIL>", ), identifier = "supplier3-unique-name", name = "Supplier AS3", ) ).toDTO() testSupplier2 = supplierRepository.save( Supplier( id = supplierId2, info = SupplierInfo( address = "address 4", homepage = "https://www.hompage.no", phone = "+47 12345678", email = "<EMAIL>", ), identifier = "supplier4-unique-name", name = "Supplier AS4", )).toDTO() userRepository.createUser( User( email = email, token = <PASSWORD>, name = "User tester", roles = listOf(Roles.ROLE_SUPPLIER), attributes = mapOf(Pair(UserAttribute.SUPPLIER_ID, testSupplier!!.id.toString())) ) ) } } @Test fun apiTest() { val resp = loginClient.login(UsernamePasswordCredentials(email, password)) val jwt = resp.getCookie("JWT").get().value val productDTO = ProductDTO( id = UUID.randomUUID(), supplier = testSupplier!!, title = "Dette er produkt 1", attributes = mapOf( AttributeNames.articlename to "produktnavn", AttributeNames.shortdescription to "En kort beskrivelse av produktet", AttributeNames.text to "En lang beskrivelse av produktet" ), hmsArtNr = "111", identifier = "hmdb-111", supplierRef = "eksternref-111", isoCategory = "12001314", accessory = false, sparePart = false, seriesId = "series-123", techData = listOf(TechData(key = "maksvekt", unit = "kg", value = "120")), media = listOf( MediaDTO( uri = "123.jpg", text = "bilde av produktet", source = MediaSourceType.EXTERNALURL, sourceUri = "https://ekstern.url/123.jpg" ) ), agreementInfo = AgreementInfo( id = UUID.randomUUID(), identifier = "hmdbid-1", rank = 1, postNr = 1, reference = "AV-142", expired = LocalDateTime.now() ), createdBy = REGISTER, updatedBy = REGISTER ) val registration = ProductRegistrationDTO( id = productDTO.id, supplierId = productDTO.supplier.id, supplierRef = productDTO.supplierRef, hmsArtNr = productDTO.hmsArtNr, title = productDTO.title, draftStatus = DraftStatus.DRAFT, adminStatus = AdminStatus.NOT_APPROVED, status = RegistrationStatus.ACTIVE, message = "Melding til leverandør", adminInfo = null, createdByAdmin = false, expired = null, published = null, updatedByUser = email, createdByUser = email, productDTO = productDTO, version = 1, createdBy = REGISTER, updatedBy = REGISTER ) val created = apiClient.createProduct(jwt, registration) created.shouldNotBeNull() val read = apiClient.readProduct(jwt, created.id) read.shouldNotBeNull() read.title shouldBe created.title read.createdByUser shouldBe email val updated = apiClient.updateProduct(jwt, read.id, read.copy(title="new title")) updated.shouldNotBeNull() updated.title shouldBe "new title" val deleted = apiClient.deleteProduct(jwt, updated.id) deleted.shouldNotBeNull() deleted.status shouldBe RegistrationStatus.DELETED deleted.productDTO.status shouldBe ProductStatus.INACTIVE val page = apiClient.findProducts(jwt,10,1,"created,asc") page.totalSize shouldBe 1 val updatedVersion = apiClient.readProduct(jwt, updated.id) updatedVersion.version!! shouldBeGreaterThan 0 updatedVersion.updatedByUser shouldBe email // should not be allowed to create a product of another supplier val productDTO2 = ProductDTO( id = UUID.randomUUID(), supplier = testSupplier2!!, title = "Dette er produkt 1", attributes = mapOf( AttributeNames.articlename to "produktnavn", AttributeNames.shortdescription to "En kort beskrivelse av produktet", AttributeNames.text to "En lang beskrivelse av produktet" ), hmsArtNr = "111", identifier = "hmdb-222", supplierRef = "eksternref-222", isoCategory = "12001314", accessory = false, sparePart = false, seriesId = "series-123", techData = listOf(TechData(key = "maksvekt", unit = "kg", value = "120")), media = listOf( MediaDTO( uri = "123.jpg", text = "bilde av produktet", source = MediaSourceType.EXTERNALURL, sourceUri = "https://ekstern.url/123.jpg" ) ), agreementInfo = AgreementInfo( id = UUID.randomUUID(), identifier = "hmdbid-1", rank = 1, postNr = 1, reference = "AV-142", expired = LocalDateTime.now() ), createdBy = REGISTER, updatedBy = REGISTER ) val registration2 = ProductRegistrationDTO( id = productDTO2.id, supplierId = productDTO2.supplier.id, supplierRef = productDTO2.supplierRef, hmsArtNr = productDTO2.hmsArtNr, title = productDTO2.title, draftStatus = DraftStatus.DRAFT, adminStatus = AdminStatus.NOT_APPROVED, status = RegistrationStatus.ACTIVE, message = "Melding til leverandør", adminInfo = null, createdByAdmin = false, expired = null, published = null, updatedByUser = email, createdByUser = email, productDTO = productDTO2, version = 1, createdBy = REGISTER, updatedBy = REGISTER ) runCatching { val created2 = apiClient.createProduct(jwt, registration2) }.isFailure shouldBe true } }
0
Kotlin
0
3
b4ccd144e527494f595a73b3c4468a7e744e4a33
8,833
hm-grunndata-register
MIT License
team7026/src/main/java/com/jdroids/team7026/ftc2017/auto/commands/commandtemplates/ParallelCommand.kt
abidingabi
130,928,306
true
{"Java": 1144649, "JavaScript": 43940, "Kotlin": 42949, "CSS": 1646, "HTML": 1594}
package com.jdroids.team7026.ftc2017.auto.commands.commandtemplates abstract class ParallelCommand(val commands: List<Command>) : Command { var isFirstTime = true var wasCommandEnded = Array(commands.size, { Int -> false}) override fun execute() { if (isFirstTime) { for (command in commands) { command.initialize() } isFirstTime = false } for ((i, command) in commands.withIndex()) { if(!command.isFinished()) { command.execute() } else if (!wasCommandEnded[i]) { command.end() wasCommandEnded[i] = true } } } override fun end() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun isFinished(): Boolean { val finishedCommands = commands.filter {it.isFinished()} return commands.size == finishedCommands.size } }
0
Java
0
0
fb9b0d5a4d75d744d33378c3982c4865d939f0e1
1,020
ftc_app
MIT License
src/main/kotlin/uk/gov/justice/hmpps/offendersearch/services/ProbationAreaFilterAggregator.kt
ministryofjustice
226,127,381
false
null
package uk.gov.justice.hmpps.offendersearch.services import org.apache.lucene.search.join.ScoreMode.None import org.elasticsearch.index.query.BoolQueryBuilder import org.elasticsearch.index.query.QueryBuilders import org.elasticsearch.index.query.QueryBuilders.nestedQuery import org.elasticsearch.search.aggregations.AggregationBuilders import org.elasticsearch.search.aggregations.Aggregations import org.elasticsearch.search.aggregations.bucket.nested.Nested import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder import org.elasticsearch.search.aggregations.bucket.terms.Terms import uk.gov.justice.hmpps.offendersearch.dto.ProbationAreaAggregation const val offenderManagersAggregation = "offenderManagers" const val activeOffenderManagerBucket = "active" const val probationAreaCodeBucket = "byProbationAreaCode" internal fun buildAggregationRequest(): NestedAggregationBuilder { return AggregationBuilders .nested(offenderManagersAggregation, "offenderManagers") .subAggregation( AggregationBuilders .terms(activeOffenderManagerBucket) .field("offenderManagers.active").subAggregation( AggregationBuilders .terms(probationAreaCodeBucket).size(1000) .field("offenderManagers.probationArea.code") ) ) } internal fun extractProbationAreaAggregation(aggregations: Aggregations): List<ProbationAreaAggregation> { val offenderManagersAggregation = aggregations.asMap()[offenderManagersAggregation] as Nested val activeAggregation = offenderManagersAggregation.aggregations.asMap()[activeOffenderManagerBucket] as Terms val possibleActiveBucket = activeAggregation.getBucketByKey("true") return possibleActiveBucket?.let { bucket -> val possibleProbationCodeBuckets = bucket.aggregations.asMap()[probationAreaCodeBucket] as Terms? possibleProbationCodeBuckets?.let { terms -> terms.buckets.map { ProbationAreaAggregation(code = it.keyAsString, count = it.docCount) } } } ?: listOf() } internal fun buildProbationAreaFilter(probationAreasCodes: List<String>): BoolQueryBuilder? { return probationAreasCodes .takeIf { it.isNotEmpty() } ?.let { probationAreaFilter(it) } } private fun probationAreaFilter(probationAreasCodes: List<String>): BoolQueryBuilder = QueryBuilders .boolQuery() .shouldAll( probationAreasCodes .map { nestedQuery( "offenderManagers", QueryBuilders.boolQuery().apply { must(QueryBuilders.termQuery("offenderManagers.active", true)) must(QueryBuilders.termQuery("offenderManagers.probationArea.code", it)) }, None ) } )
3
Kotlin
2
3
f0dbcdf231c343380284f56f4796a272ddbb5ae2
2,724
probation-offender-search
MIT License
app/src/main/java/com/yasinkacmaz/jetflix/ui/main/MainActivity.kt
yasinkacmaz
223,481,763
false
null
package com.yasinkacmaz.jetflix.ui.main import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.core.view.WindowCompat import androidx.navigation.compose.rememberNavController import com.yasinkacmaz.jetflix.ui.theme.JetflixTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) renderUi() } private fun renderUi() = setContent { val systemTheme = isSystemInDarkTheme() val isDarkTheme = remember { mutableStateOf(systemTheme) } val navController = rememberNavController() JetflixTheme(isDarkTheme = isDarkTheme.value) { CompositionLocalProvider( LocalNavController provides navController, LocalDarkTheme provides isDarkTheme ) { MainContent() } } } }
0
null
38
384
71c20b301fe22032b09271098392243e68113b8c
1,291
jetflix
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/CartArrowDown.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.CartArrowDown: ImageVector get() { if (_cartArrowDown != null) { return _cartArrowDown!! } _cartArrowDown = Builder(name = "CartArrowDown", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.59f, 15.0f) lineTo(6.65f, 15.0f) lineToRelative(0.13f, 1.12f) curveToRelative(0.06f, 0.5f, 0.49f, 0.88f, 0.99f, 0.88f) horizontalLineToRelative(12.22f) verticalLineToRelative(2.0f) lineTo(7.78f, 19.0f) curveToRelative(-1.52f, 0.0f, -2.8f, -1.14f, -2.98f, -2.65f) lineTo(3.21f, 2.88f) curveToRelative(-0.06f, -0.5f, -0.49f, -0.88f, -0.99f, -0.88f) lineTo(0.0f, 2.0f) lineTo(0.0f, 0.0f) lineTo(2.22f, 0.0f) curveToRelative(1.52f, 0.0f, 2.8f, 1.14f, 2.98f, 2.65f) lineToRelative(0.04f, 0.35f) horizontalLineToRelative(4.76f) verticalLineToRelative(2.0f) lineTo(5.48f, 5.0f) lineToRelative(0.94f, 8.0f) horizontalLineToRelative(13.54f) lineToRelative(1.6f, -8.0f) horizontalLineToRelative(-5.55f) lineTo(16.01f, 3.0f) horizontalLineToRelative(7.99f) lineToRelative(-2.4f, 12.0f) close() moveTo(7.0f, 20.0f) curveToRelative(-1.1f, 0.0f, -2.0f, 0.9f, -2.0f, 2.0f) reflectiveCurveToRelative(0.9f, 2.0f, 2.0f, 2.0f) reflectiveCurveToRelative(2.0f, -0.9f, 2.0f, -2.0f) reflectiveCurveToRelative(-0.9f, -2.0f, -2.0f, -2.0f) close() moveTo(17.0f, 20.0f) curveToRelative(-1.1f, 0.0f, -2.0f, 0.9f, -2.0f, 2.0f) reflectiveCurveToRelative(0.9f, 2.0f, 2.0f, 2.0f) reflectiveCurveToRelative(2.0f, -0.9f, 2.0f, -2.0f) reflectiveCurveToRelative(-0.9f, -2.0f, -2.0f, -2.0f) close() moveTo(8.89f, 7.72f) lineToRelative(2.69f, 2.69f) curveToRelative(0.39f, 0.39f, 0.9f, 0.58f, 1.41f, 0.58f) reflectiveCurveToRelative(1.02f, -0.19f, 1.41f, -0.58f) lineToRelative(2.68f, -2.68f) lineToRelative(-1.41f, -1.41f) lineToRelative(-1.68f, 1.68f) lineTo(13.99f, 0.0f) horizontalLineToRelative(-2.0f) lineTo(11.99f, 8.0f) lineToRelative(-1.69f, -1.69f) lineToRelative(-1.41f, 1.41f) close() } } .build() return _cartArrowDown!! } private var _cartArrowDown: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,732
icons
MIT License
AndroidVitalFix/src/main/java/golab/dev/androidvitalfix/ActivityThreadHooker.kt
kswlee
320,822,549
false
null
package golab.dev.androidvitalfix import android.os.Build import android.os.Handler import android.os.Message import golab.dev.androidvitalfix.app.QueuedWorkProxy import golab.dev.androidvitalfix.utils.Reflection /** * Class ActivityThreadHooker * * Use to hook ActivityThread handler callback to override system behavior */ object ActivityThreadHooker { private const val sPauseActivity = 101 private const val sResumeActivity = 107 private const val sServiceArgs = 115 private const val sScheduleCrash = 134 private const val sActivityThreadName = "android.app.ActivityThread" private val msgHandlers: MutableMap<Int, (() -> Boolean)?> = mutableMapOf() private val callbackHandler = object: Handler.Callback { override fun handleMessage(message: Message): Boolean { if (msgHandlers.containsKey(message.what)) { return msgHandlers[message.what]?.invoke() == true } return false } } fun setupScheduleCrashHandler() { msgHandlers[sScheduleCrash] = { // Fix RemoteServiceException true } } fun setupServiceArgsHandler() { // Only apply to Android 5 ~ 7 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) { return } msgHandlers[sServiceArgs] = { QueuedWorkProxy.consumePendingWorks() false } } fun setupActivityArgsHandler() { // Only apply to Android 5 ~ 7 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) { return } val handler = { QueuedWorkProxy.consumePendingWorks() false } listOf(sPauseActivity, sResumeActivity).forEach { msgHandlers[it] = handler } } fun hook() { setupScheduleCrashHandler() conditionalHook() } fun conditionalHook() { val requireHook = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP if (!requireHook) { return } try { hookActivityThread() } catch (e: Throwable) { e.printStackTrace() } } private fun hookActivityThread() { val activityThread = Reflection.getClassMember( sActivityThreadName, "sCurrentActivityThread" ) val internalHandler = Reflection.getClassMember( sActivityThreadName, "mH", activityThread ) Reflection.setClassMember( Handler::class.java as Class<Any>, "mCallback", internalHandler, callbackHandler ) } }
8
null
56
9
e5f2d9c14526accc1f0aba81f907e62aaa1a7674
2,809
android-vital-fix
MIT License
src/test/kotlin/io/johnsonlee/android/trace/JavaStackTraceParserTest.kt
johnsonlee
335,059,672
false
null
package io.johnsonlee.android.trace import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class JavaStackTraceParserTest { @Test fun `parse java stack trace`() { val stackTrace = """ android.view.WindowManager${'$'}BadTokenException: Unable to add window -- token android.os.BinderProxy@e2815e is not valid; is your activity running? at android.view.ViewRootImpl.setView(ViewRootImpl.java:679) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93) at android.widget.Toast${'$'}TN.handleShow(Toast.java:459) at android.widget.Toast${'$'}TN${'$'}2.handleMessage(Toast.java:342) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method)""" val frames = JavaStackTraceParser().parse(stackTrace) assertTrue(frames.isNotEmpty()) assertEquals(9, frames.size) val rootCause = frames.rootCause assertNotNull(rootCause) assertEquals("ViewRootImpl.java", rootCause.sourceFile) assertEquals("setView", rootCause.methodName) assertEquals(679, rootCause.lineNumber) } @Test fun `parse android stack trace`() { val stackTrace = """ java.lang.RuntimeException: Fatal Crash at com.example.foo.CrashyClass.sendMessage(CrashyClass.java:10) at com.example.foo.CrashyClass.crash(CrashyClass.java:6) at com.bugsnag.android.example.ExampleActivity.crashUnhandled(ExampleActivity.kt:55) at com.bugsnag.android.example.ExampleActivity${'$'}onCreate${'$'}1.invoke(ExampleActivity.kt:33) at com.bugsnag.android.example.ExampleActivity${'$'}onCreate${'$'}1.invoke(ExampleActivity.kt:14) at com.bugsnag.android.example.ExampleActivity${'$'}sam${'$'}android_view_View_OnClickListener${'$'}0.onClick(ExampleActivity.kt) at android.view.View.performClick(View.java:5637) at android.view.View${'$'}PerformClick.run(View.java:22429) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit${'$'}MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)""" val frames = JavaStackTraceParser().parse(stackTrace) assertTrue(frames.isNotEmpty()) assertEquals(15, frames.size) val rootCause = frames.rootCause assertNotNull(rootCause) assertEquals("CrashyClass.java", rootCause.sourceFile) assertEquals("sendMessage", rootCause.methodName) assertEquals(10, rootCause.lineNumber) } @Test fun `parse android stack trace with causes`() { val stackTrace = """ Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.labpixies.flood/com.labpixies.flood.GameFinishedActivity}: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3303) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread${'$'}H.handleMessage(ActivityThread.java:1994) at android.os.Handler.dispatchMessage(Handler.java:108) at android.os.Looper.loop(Looper.java:166) at android.app.ActivityThread.main(ActivityThread.java:7529) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.Zygote${'$'}MethodAndArgsCaller.run(Zygote.java:245) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation at android.app.Activity.onCreate(Activity.java:1081) at com.labpixies.flood.GameFinishedActivity.onCreate(GameFinishedActivity.java:81) at android.app.Activity.performCreate(Activity.java:7383) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread${'$'}H.handleMessage(ActivityThread.java:1994) at android.os.Handler.dispatchMessage(Handler.java:108) at android.os.Looper.loop(Looper.java:166) at android.app.ActivityThread.main(ActivityThread.java:7529) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.Zygote${'$'}MethodAndArgsCaller.run(Zygote.java:245) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)""" val frames = JavaStackTraceParser().parse(stackTrace) assertTrue(frames.isNotEmpty()) assertEquals(14, frames.size) val rootCause = frames.rootCause assertNotNull(rootCause) assertEquals("GameFinishedActivity.java", rootCause.sourceFile) assertEquals("onCreate", rootCause.methodName) assertEquals(81, rootCause.lineNumber) } }
0
Kotlin
1
10
258e84d5afc6c109175842c5b3c6ae91c42d259c
5,643
trace-parser
Apache License 2.0
engine/src/main/kotlin/kotli/engine/provider/readme/markdown/MarkdownReadmeProcessor.kt
kotlitecture
741,006,904
false
{"Kotlin": 99184}
package kotli.engine.provider.readme.markdown import kotli.engine.BaseFeatureProcessor import kotli.engine.FeatureProcessor import kotli.engine.TemplateProcessor import kotli.engine.TemplateState import kotli.engine.template.rule.WriteText import java.net.URLEncoder internal object MarkdownReadmeProcessor : BaseFeatureProcessor() { override fun getId(): String = "readme.markdown" override fun isInternal(): Boolean = true override fun doApply(state: TemplateState) { val readmeBuilder = StringBuilder() // about state.processor.getWebUrl()?.let { readmeBuilder.appendLine("# About") readmeBuilder.appendLine() readmeBuilder.appendLine("Layer template: $it") state.getRoot() .takeIf { root -> root.processor === TemplateProcessor.App } ?.layer?.id?.takeIf { id -> id.isNotEmpty() } ?.let { readmeBuilder.appendLine() readmeBuilder.appendLine("Project architecture: https://kotlitecture.com/project/$it") } } // features val featuresBuilder = StringBuilder() val features = state.layer.features features .plus(state.processor.getMissedFeatures(features, { it.id }, { it })) .asSequence() .map { it.id } .mapNotNull(state.processor::getFeatureProcessor) .sortedBy { state.processor.getFeatureProcessorOrder(it.getId()) } .map { getDependencies(state, it) } .flatten() .distinct() .filter { !it.isInternal() || it.getConfiguration(state) != null } .sortedBy { state.processor.getFeatureProvider(it::class.java)?.getType()?.getOrder() } .toList() .onEach { processor -> proceedFeature(featuresBuilder, state, processor) } if (featuresBuilder.isNotBlank()) { readmeBuilder.appendLine() readmeBuilder.appendLine("# Features") readmeBuilder.appendLine() readmeBuilder.appendLine("| Group | Feature | Overview | Configuration | Usage |") readmeBuilder.appendLine("|-------|---------|----------|---------------|-------|") readmeBuilder.append(featuresBuilder) } readmeBuilder .trim() .takeIf { it.isNotEmpty() } ?.let { state.onApplyRules("README.md", WriteText(it.toString())) } } private fun proceedFeature( textBuilder: StringBuilder, state: TemplateState, processor: FeatureProcessor ) { logger.debug("proceedFeature: {}", processor.getId()) val provider = state.processor.getFeatureProvider(processor::class.java) ?: return val groupTitle = provider.getType().getTitle() ?: return val title = processor.getTitle(state) ?: return val usage = createUsage(state, groupTitle, title, processor) val overview = createOverview(state, groupTitle, title, processor) val configuration = createConfiguration(state, groupTitle, title, processor) textBuilder.appendLine("| $groupTitle | $title | ${overview.asLink()} | ${configuration.asLink()} | ${usage.asLink()} |") } private fun createOverview( state: TemplateState, group: String, title: String, processor: FeatureProcessor ): String { val docBuilder = StringBuilder() // about processor.getDescription(state)?.let { docBuilder.appendLine("# About") docBuilder.appendLine() docBuilder.appendLine(it) } // links StringBuilder() .also { links -> processor.getWebUrl(state)?.let { links.appendLine("- [Official Site]($it)") } processor.getIntegrationUrl(state) ?.let { links.appendLine("- [Integration Guide]($it)") } } .trim() .takeIf { it.isNotBlank() } ?.let { docBuilder.appendLine() docBuilder.appendLine("# Links") docBuilder.appendLine() docBuilder.appendLine(it) } state.onApplyRules( "docs/${group}/${title}/overview.md", WriteText(docBuilder.trim().toString()) ) return "docs/${group.encoded()}/${title.encoded()}/overview.md" } private fun createConfiguration( state: TemplateState, group: String, title: String, processor: FeatureProcessor ): String? { val docBuilder = StringBuilder() processor.getConfiguration(state)?.let { docBuilder.appendLine("# Configuration") docBuilder.appendLine() docBuilder.appendLine(it) } ?: return null state.onApplyRules( "docs/${group}/${title}/configuration.md", WriteText(docBuilder.trim().toString()) ) return "docs/${group.encoded()}/${title.encoded()}/configuration.md" } private fun createUsage( state: TemplateState, group: String, title: String, processor: FeatureProcessor ): String? { val docBuilder = StringBuilder() processor.getUsage(state)?.let { docBuilder.appendLine("# Usage") docBuilder.appendLine() docBuilder.appendLine(it) } ?: return null state.onApplyRules( "docs/${group}/${title}/usage.md", WriteText(docBuilder.trim().toString()) ) return "docs/${group.encoded()}/${title.encoded()}/usage.md" } private fun String?.asLink() = this?.let { "[Link]($it)" } ?: "-" private fun String.encoded() = URLEncoder.encode(this, "UTF-8").replace("+", "%20") }
0
Kotlin
0
1
abba606fd4505e3bf1019765a74ccb808738c130
5,853
kotli-engine
MIT License
app/src/main/java/volovyk/guerrillamail/ui/MainViewModel.kt
oleksandrvolovik
611,731,548
false
null
package volovyk.guerrillamail.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import volovyk.guerrillamail.data.EmailRepository import volovyk.guerrillamail.data.model.Email import volovyk.guerrillamail.data.remote.RemoteEmailDatabase import javax.inject.Inject data class UiState( val assignedEmail: String? = null, val emails: List<Email> = emptyList(), val state: RemoteEmailDatabase.State = RemoteEmailDatabase.State.Loading ) @HiltViewModel class MainViewModel @Inject constructor(private val emailRepository: EmailRepository) : ViewModel() { private val assignedEmail = emailRepository.observeAssignedEmail().stateIn( viewModelScope, SharingStarted.WhileSubscribed(5000), null ) private val emails = emailRepository.observeEmails().stateIn( viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList() ) private val state = emailRepository.observeState().stateIn( viewModelScope, SharingStarted.WhileSubscribed(5000), RemoteEmailDatabase.State.Loading ) val uiState: StateFlow<UiState> = combine(assignedEmail, emails, state) { assignedEmail, emails, state -> UiState(assignedEmail, emails, state) }.stateIn( viewModelScope, SharingStarted.WhileSubscribed(5000), UiState() ) fun setEmailAddress(newAddress: String) { viewModelScope.launch { emailRepository.setEmailAddress(newAddress) } } fun deleteEmail(email: Email?) { viewModelScope.launch { emailRepository.deleteEmail(email) } } }
0
Kotlin
0
0
7b64b76b9c01b9289d4147bdb4115a0d66cbca27
2,019
guerrilla-mail-android-client
MIT License
src/main/kotlin/org/hyrical/communities/post/reply/ForumReply.kt
Nopock
520,881,418
false
null
package org.hyrical.communities.post.reply @kotlinx.serialization.Serializable data class ForumReply( val author: String, val content: String, val createdAt: Long = System.currentTimeMillis() )
0
Kotlin
0
0
38754045290f3d1208d6eaf3e2d5e9811bdd5419
206
Forums-Backend
MIT License
app/src/main/java/com/example/codaquest/Models/OnboardingData.kt
studiegruppe-2nd-semester
782,521,831
false
{"Kotlin": 82739}
package com.example.codaquest.Models data class OnboardingData ( val level : Level? = null, val languages : String? = null, val projectLength : Int? = null ) enum class Level { Beginner, Intermediate, Advanced } // This is a function that makes it possible for us to make the // code ".toEnum<Level>()" in UserRepository and Onboarding viewmodel. // Define the enumValueOfOrNull function inline fun <reified T : Enum<T>> enumValueOfOrNull(name: String): T? = enumValues<T>().find { it.name == name } // Define the toEnum extension function inline fun <reified T : Enum<T>> String?.toEnum(): T? = this?.let { enumValueOfOrNull<T>(it) }
0
Kotlin
0
0
4c45cb8a83150520b2cff27d21942900979d10f5
677
codaquest
MIT License
app/src/main/java/com/jorgel/marvel/views/fragments/detailCharacter/adapters/ListUrlsDetailAdapter.kt
jorgela92
310,131,082
false
null
package com.jorgel.marvel.views.fragments.detailCharacter.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.jorgel.marvel.R import com.jorgel.marvel.models.Urls import kotlinx.android.synthetic.main.cell_list_item.view.* import java.util.* interface ListUrlsDetailAdapterCallback { fun openLink(title: String, url: String) } class ListUrlsDetailAdapter(private val context: Context, private val data: List<Urls>, private val delegate: ListUrlsDetailAdapterCallback) : RecyclerView.Adapter<ListUrlsDetailAdapter.ListUrlsDetailHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListUrlsDetailHolder { return ListUrlsDetailHolder(LayoutInflater.from(context).inflate(R.layout.cell_list_item, parent, false)) } override fun onBindViewHolder(holder: ListUrlsDetailHolder, position: Int) { holder.bindItems(position) } override fun getItemCount(): Int { return data.size } inner class ListUrlsDetailHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindItems(position: Int) { itemView.titleListItem.text = data[position].type.capitalize(Locale.getDefault()) if (position == data.size - 1) { itemView.separatorView.visibility = View.INVISIBLE } itemView.setOnClickListener { delegate.openLink(data[position].type.capitalize(Locale.getDefault()), data[position].url) } } } }
0
Kotlin
0
0
a0cce258699b6b854a390971db613ead6fd6bf2f
1,633
marvel_android
Apache License 2.0
features/src/main/java/uk/gov/android/features/FeatureFlag.kt
govuk-one-login
671,139,547
false
{"Kotlin": 611350, "Shell": 12866, "Ruby": 1762}
package uk.gov.android.features /** * Interface for declaring a feature / sub-system within the code base. * * Enables or disables sections of the app that aren't ready for a public release, based on a * configuration injected by hilt. * * @property id The unique identifier for the feature. */ interface FeatureFlag { val id: String }
2
Kotlin
0
4
8158433162764dc72a99006c51c8e84206e101bc
348
mobile-android-one-login-app
MIT License
app/src/main/java/com/taskail/placesapp/util/ViewUtil.kt
juanunix
130,529,625
true
{"Kotlin": 61662}
package com.taskail.placesapp.util import android.annotation.SuppressLint import android.graphics.Outline import android.view.View import android.view.ViewOutlineProvider /** *Created by ed on 4/13/18. */ /** * create a circular outline, we ignore NewApi error since * we check the Api version before using this outline. in */ @SuppressLint("NewApi") val CIRCULAR_OUTLINE: ViewOutlineProvider = object : ViewOutlineProvider() { override fun getOutline(view: View, outline: Outline) { outline.setOval(view.paddingLeft, view.paddingTop, view.width - view.paddingRight, view.height - view.paddingBottom) } }
0
Kotlin
0
0
8e4347002939ae5c838a3f46ecf6cc6408a7c4de
676
places-app
MIT License
video-sdk/src/main/java/com/kaleyra/video_sdk/call/feedback/view/FeedbackSent.kt
KaleyraVideo
686,975,102
false
{"Kotlin": 5025429, "Shell": 7470, "Python": 6756, "Java": 1213}
/* * Copyright 2023 Kaleyra @ https://www.kaleyra.com * * 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.kaleyra.video_sdk.call.feedback.view import android.content.res.Configuration import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.kaleyra.video_sdk.R import com.kaleyra.video_sdk.theme.KaleyraTheme /** * Feedback Sent Tag */ const val FeedbackSentTag = "FeedbackSentTag" @Composable internal fun FeedbackSent(onDismiss: () -> Unit) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .padding(24.dp) .testTag(FeedbackSentTag) ) { Spacer(modifier = Modifier.height(8.dp)) Text( text = stringResource(id = R.string.kaleyra_feedback_thank_you), fontSize = 16.sp, fontWeight = FontWeight.SemiBold ) Spacer(modifier = Modifier.height(16.dp)) Text( text = stringResource(id = R.string.kaleyra_feedback_see_you_soon), fontSize = 16.sp, modifier = Modifier.padding(horizontal = 4.dp) ) Spacer(modifier = Modifier.height(24.dp)) Button( onClick = onDismiss, shape = RoundedCornerShape(4.dp), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary), modifier = Modifier .fillMaxWidth() ) { Text( text = stringResource(id = R.string.kaleyra_feedback_close), fontSize = 16.sp, fontWeight = FontWeight.SemiBold ) } } } @Preview(name = "Light Mode") @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark Mode") @Composable internal fun FeedbackSentPreview() = KaleyraTheme { Surface { FeedbackSent {} } }
0
Kotlin
0
1
d73e4727cec4875a98b21110823947edcfe9e28c
3,254
VideoAndroidSDK
Apache License 2.0
modules/domain/domain_notes/src/main/kotlin/kekmech/ru/domain_notes/dto/Note.kt
tonykolomeytsev
203,239,594
false
null
package kekmech.ru.domain_notes.dto import java.io.Serializable import java.time.LocalDateTime data class Note( val content: String, val dateTime: LocalDateTime, val classesName: String, val id: Int = -1, val targetRect: Int? = null, // для уточнения целевой пары при подряд идущих одинаковых парах в расписании val attachedPictureUrls: List<String> = emptyList() ) : Serializable
9
Kotlin
4
21
4ad7b2fe62efb956dc7f8255d35436695643d229
407
mpeiapp
MIT License
analysis/analysis-api/testData/components/compilerPluginGeneratedDeclarationsProvider/compilerPluginGeneratedDeclarations/topLevelFunction.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// WITH_FIR_TEST_COMPILER_PLUGIN package test @org.jetbrains.kotlin.plugin.sandbox.DummyFunction class Test fun regularTopLevelFunction() {}
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
143
kotlin
Apache License 2.0
app/src/main/java/com/wallee/samples/apps/shop/viewmodels/ItemsWithMetadataViewModel.kt
wallee-payment
654,166,055
false
null
package com.wallee.samples.apps.shop.viewmodels import com.wallee.samples.apps.shop.data.ItemAndMetadata class ItemsWithMetadataViewModel(itms: ItemAndMetadata) { private val item = checkNotNull(itms.item) val imageUrl get() = item.imageUrl val itemName get() = item.name val itemId get() = item.itemId val itemPrice get() = item.price }
0
Kotlin
0
2
8118bf3ed621a32753752e73e06b8bba8974d022
394
android-sdk-demo-app
Apache License 2.0
sdk/src/main/java/com/exponea/sdk/view/InAppMessageAlert.kt
exponea
134,699,893
false
null
package com.exponea.sdk.view import android.app.AlertDialog import android.content.Context import com.exponea.sdk.models.InAppMessageButtonType import com.exponea.sdk.models.InAppMessagePayload import com.exponea.sdk.models.InAppMessagePayloadButton internal class InAppMessageAlert : InAppMessageView { val dialog: AlertDialog var buttonClicked: Boolean = false override val isPresented: Boolean get() = dialog.isShowing constructor( context: Context, payload: InAppMessagePayload, onButtonClick: (InAppMessagePayloadButton) -> Unit, onDismiss: () -> Unit ) { val builder = AlertDialog.Builder(context) builder.setTitle(payload.title) builder.setMessage(payload.bodyText) if (payload.buttons != null) { for (button in payload.buttons) { if (button.buttonType == InAppMessageButtonType.CANCEL) { builder.setNegativeButton(button.buttonText) { _, _ -> dismiss() } } else { builder.setPositiveButton(button.buttonText) { _, _ -> buttonClicked = true onButtonClick(button) } } } } builder.setOnDismissListener { if (!buttonClicked) { onDismiss() } } dialog = builder.create() } override fun show() { dialog.show() } override fun dismiss() { dialog.dismiss() } }
0
Kotlin
15
14
d31969d2bcec509b4b16831d636e107693f8875e
1,544
exponea-android-sdk
MIT License
app/src/test/java/wottrich/github/io/smartchecklist/presentation/viewmodel/HomeDrawerViewModelTest.kt
Wottrich
295,605,540
false
{"Kotlin": 310822}
package wottrich.github.io.smartchecklist.presentation.viewmodel import wottrich.github.io.smartchecklist.checklist.domain.DeleteChecklistUseCase import wottrich.github.io.smartchecklist.checklist.domain.UpdateSelectedChecklistUseCase import wottrich.github.io.smartchecklist.coroutines.base.Result import wottrich.github.io.smartchecklist.coroutines.successEmptyResult import wottrich.github.io.smartchecklist.testtools.BaseUnitTest import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import junit.framework.Assert.assertEquals import junit.framework.Assert.assertTrue import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import org.junit.Test import wottrich.github.io.smartchecklist.domain.usecase.GetChecklistDrawerUseCase import wottrich.github.io.smartchecklist.presentation.ui.model.HomeDrawerChecklistItemModel import wottrich.github.io.smartchecklist.datasource.entity.NewChecklist class HomeDrawerViewModelTest : BaseUnitTest() { private lateinit var sut: HomeDrawerViewModel private lateinit var getChecklistDrawerUseCase: GetChecklistDrawerUseCase private lateinit var updateSelectedChecklistUseCase: UpdateSelectedChecklistUseCase private lateinit var deleteChecklistUseCase: DeleteChecklistUseCase private val dummyChecklistId = "0" private val dummyChecklist = NewChecklist(uuid = dummyChecklistId, name = "Checklist1") private val dummyChecklistWithTasks = HomeDrawerChecklistItemModel( dummyChecklist.uuid, dummyChecklist.name, completeCountLabel = "1 / 2", isChecklistSelected = dummyChecklist.isSelected, hasUncompletedTask = true ) private val dummyListOfChecklistWithTasks = listOf( dummyChecklistWithTasks, dummyChecklistWithTasks.copy( checklistUuid = "1", checklistName = "Checklist2", completeCountLabel = "2 / 2", isChecklistSelected = false, hasUncompletedTask = false ) ) override fun setUp() { getChecklistDrawerUseCase = mockk() updateSelectedChecklistUseCase = mockk() deleteChecklistUseCase = mockk() } @Test fun `GIVEN ViewModel initialized WHEN checklist use case is called THEN must return list of checklist`() { mockGetChecklistWithTaskUseCase() sut = getSut() val value = getSuspendValue { sut.drawerStateFlow.first() as HomeDrawerState.Content } assertEquals(dummyListOfChecklistWithTasks, value.checklists) } @Test fun `GIVEN user wants edit lists of checklist WHEN user click to edit THEN state must change to edit mode`() { mockGetChecklistWithTaskUseCase() sut = getSut() sut.processEvent(HomeDrawerEvent.EditModeClicked) val value = getSuspendValue { sut.drawerStateFlow.first() as HomeDrawerState.Content } assertTrue(value.isEditing) } @Test fun `GIVEN another checklist selected WHEN user select another checklist THEN must call use case to change selected checklist`() { mockGetChecklistWithTaskUseCase() mockGetUpdateSelectedChecklistUseCase(dummyChecklistWithTasks.checklistUuid) sut = getSut() sut.processEvent(HomeDrawerEvent.ItemClicked(dummyChecklistWithTasks)) coVerify(exactly = 1) { updateSelectedChecklistUseCase(dummyChecklistWithTasks.checklistUuid) } val effect = getSuspendValue { sut.drawerEffectFlow.first() } assertTrue(effect is HomeDrawerEffect.CloseDrawer) } @Test fun `GIVEN some checklist WHEN user delete this checklist THEN must call use case to delete checklist`() { mockGetChecklistWithTaskUseCase() mockGetDeleteChecklistUseCase(dummyChecklistWithTasks.checklistUuid) sut = getSut() sut.processEvent(HomeDrawerEvent.DeleteChecklistClicked(dummyChecklistWithTasks)) coVerify(exactly = 1) { deleteChecklistUseCase(dummyChecklistWithTasks.checklistUuid) } } private fun mockGetChecklistWithTaskUseCase() { coEvery { getChecklistDrawerUseCase.invoke() } returns flow { emit(Result.success(dummyListOfChecklistWithTasks)) } } private fun mockGetUpdateSelectedChecklistUseCase(checklistUuid: String) { coEvery { updateSelectedChecklistUseCase.invoke(checklistUuid) } returns successEmptyResult() } private fun mockGetDeleteChecklistUseCase(checklistUuid: String) { coEvery { deleteChecklistUseCase.invoke(checklistUuid) } returns successEmptyResult() } private fun getSut() = HomeDrawerViewModel( coroutinesTestRule.dispatchers, getChecklistDrawerUseCase, updateSelectedChecklistUseCase, deleteChecklistUseCase ) }
9
Kotlin
0
8
f8d44ab4c873f948b80b31fcb711f5c617217fd1
4,800
android-smart-checklist
MIT License
measurements/src/main/java/be/appwise/measurements/converters/UnitConverterReciprocal.kt
appwise-labs
349,150,482
false
null
package be.appwise.measurements.converters open class UnitConverterReciprocal(reciprocal: Double) : UnitConverter() { var reciprocal: Double = reciprocal private set override fun baseUnitValue(value: Double): Double { return reciprocal / value } override fun value(baseUnitValue: Double): Double { return reciprocal / baseUnitValue } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as UnitConverterReciprocal if (reciprocal != other.reciprocal) return false return true } override fun hashCode(): Int { return reciprocal.hashCode() } }
19
Kotlin
4
5
2eed1771160637082553336aa7673d076c518264
734
AndroidCore
MIT License
src/dorkbox/notify/AppMouseAdapter.kt
dorkbox
51,482,703
false
{"Gradle Kotlin DSL": 2, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 13, "INI": 1, "Java": 2}
/* * Copyright 2015 dorkbox, 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 dorkbox.notify import java.awt.event.MouseAdapter import java.awt.event.MouseEvent internal class AppMouseAdapter : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { val notifyCanvas = e.source as AppNotify notifyCanvas.mouseX = e.x notifyCanvas.mouseY = e.y } override fun mousePressed(e: MouseEvent) { val notifyCanvas = e.source as AppNotify notifyCanvas.onClick(e.x, e.y) } }
1
null
1
1
efd4328695ecf2a35f505d58d7f832b5a4b48c31
1,052
Notify
Creative Commons Zero v1.0 Universal
idea/src/org/jetbrains/kotlin/idea/debugger/KotlinPositionManager.kt
javaljj
50,647,805
true
{"Java": 15915057, "Kotlin": 12574163, "JavaScript": 177557, "Protocol Buffer": 42724, "HTML": 28583, "Lex": 16598, "ANTLR": 9689, "CSS": 9358, "Groovy": 6859, "Shell": 4704, "IDL": 4669, "Batchfile": 3703}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.debugger import com.intellij.debugger.MultiRequestPositionManager import com.intellij.debugger.NoDataException import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.DebugProcess import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.PositionManagerEx import com.intellij.debugger.engine.evaluation.EvaluationContext import com.intellij.debugger.jdi.StackFrameProxyImpl import com.intellij.debugger.requests.ClassPrepareRequestor import com.intellij.openapi.project.DumbService import com.intellij.openapi.roots.libraries.LibraryUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.impl.compiled.ClsFileImpl import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.* import com.intellij.util.ThreeState import com.intellij.xdebugger.frame.XStackFrame import com.sun.jdi.AbsentInformationException import com.sun.jdi.Location import com.sun.jdi.ReferenceType import com.sun.jdi.request.ClassPrepareRequest import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.codegen.ClassBuilderFactories import org.jetbrains.kotlin.codegen.binding.CodegenBinding import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil import org.jetbrains.kotlin.codegen.state.GenerationState import org.jetbrains.kotlin.codegen.state.JetTypeMapper import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.fileClasses.NoResolveFileClassesProvider import org.jetbrains.kotlin.fileClasses.getFileClassInternalName import org.jetbrains.kotlin.fileClasses.internalNameWithoutInnerClasses import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult import org.jetbrains.kotlin.idea.caches.resolve.analyzeFullyAndGetResult import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils import org.jetbrains.kotlin.idea.debugger.breakpoints.getLambdasAtLineIfAny import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinCodeFragmentFactory import org.jetbrains.kotlin.idea.decompiler.classFile.KtClsFile import org.jetbrains.kotlin.idea.refactoring.getLineStartOffset import org.jetbrains.kotlin.idea.search.usagesSearch.isImportUsage import org.jetbrains.kotlin.idea.util.DebuggerUtils import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.inline.InlineUtil import org.jetbrains.kotlin.resolve.jvm.JvmClassName import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.toReadOnlyList import java.util.* import com.intellij.debugger.engine.DebuggerUtils as JDebuggerUtils class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiRequestPositionManager, PositionManagerEx() { private val myTypeMappers = WeakHashMap<String, CachedValue<JetTypeMapper>>() override fun evaluateCondition(context: EvaluationContext, frame: StackFrameProxyImpl, location: Location, expression: String): ThreeState? { return ThreeState.UNSURE } override fun createStackFrame(frame: StackFrameProxyImpl, debugProcess: DebugProcessImpl, location: Location): XStackFrame? { if (location.declaringType().containsKotlinStrata()) { return KotlinStackFrame(frame) } return null } override fun getSourcePosition(location: Location?): SourcePosition? { if (location == null) { throw NoDataException.INSTANCE } val psiFile = getPsiFileByLocation(location) if (psiFile == null) { val isKotlinStrataAvailable = location.declaringType().containsKotlinStrata() if (isKotlinStrataAvailable) { try { val javaSourceFileName = location.sourceName("Java") val javaClassName = JvmClassName.byInternalName(defaultInternalName(location)) val project = myDebugProcess.project val defaultPsiFile = DebuggerUtils.findSourceFileForClass(project, myDebugProcess.searchScope, javaClassName, javaSourceFileName) if (defaultPsiFile != null) { return SourcePosition.createFromLine(defaultPsiFile, 0) } } catch(e: AbsentInformationException) { // ignored } } throw NoDataException.INSTANCE } val lineNumber = try { location.lineNumber() - 1 } catch (e: InternalError) { -1 } if (lineNumber >= 0) { val lambdaOrFunIfInside = getLambdaOrFunIfInside(location, psiFile as KtFile, lineNumber) if (lambdaOrFunIfInside != null) { return SourcePosition.createFromElement(lambdaOrFunIfInside.bodyExpression!!) } val property = getParameterIfInConstructor(location, psiFile, lineNumber) if (property != null) { return SourcePosition.createFromElement(property) } return SourcePosition.createFromLine(psiFile, lineNumber) } throw NoDataException.INSTANCE } private fun getParameterIfInConstructor(location: Location, file: KtFile, lineNumber: Int): KtParameter? { val lineStartOffset = file.getLineStartOffset(lineNumber) ?: return null val elementAt = file.findElementAt(lineStartOffset) val contextElement = KotlinCodeFragmentFactory.getContextElement(elementAt) val methodName = location.method().name() if (contextElement is KtClass && JvmAbi.isGetterName(methodName)) { val parameterForGetter = contextElement.getPrimaryConstructor()?.valueParameters?.firstOrNull() { it.hasValOrVar() && it.name != null && JvmAbi.getterName(it.name!!) == methodName } ?: return null return parameterForGetter } return null } private fun getLambdaOrFunIfInside(location: Location, file: KtFile, lineNumber: Int): KtFunction? { val currentLocationFqName = location.declaringType().name() if (currentLocationFqName == null) return null val start = CodeInsightUtils.getStartLineOffset(file, lineNumber) val end = CodeInsightUtils.getEndLineOffset(file, lineNumber) if (start == null || end == null) return null val literalsOrFunctions = getLambdasAtLineIfAny(file, lineNumber) if (literalsOrFunctions.isEmpty()) return null; val isInLibrary = LibraryUtil.findLibraryEntry(file.virtualFile, file.project) != null val typeMapper = if (!isInLibrary) prepareTypeMapper(file) else createTypeMapperForLibraryFile(file.findElementAt(start), file) val currentLocationClassName = JvmClassName.byFqNameWithoutInnerClasses(FqName(currentLocationFqName)).internalName for (literal in literalsOrFunctions) { if (InlineUtil.isInlinedArgument(literal, typeMapper.bindingContext, true)) { if (isInsideInlineArgument(literal, location, myDebugProcess as DebugProcessImpl)) { return literal } continue } val internalClassNames = getInternalClassNameForElement(literal.firstChild, typeMapper, file, isInLibrary) if (internalClassNames.any { it == currentLocationClassName }) { return literal } } return null } private fun getPsiFileByLocation(location: Location): PsiFile? { val sourceName: String try { sourceName = location.sourceName() } catch (e: AbsentInformationException) { return null } catch (e: InternalError) { return null } val referenceInternalName: String try { if (location.declaringType().containsKotlinStrata()) { //replace is required for windows referenceInternalName = location.sourcePath().replace('\\', '/') } else { referenceInternalName = defaultInternalName(location) } } catch (e: AbsentInformationException) { referenceInternalName = defaultInternalName(location) } val className = JvmClassName.byInternalName(referenceInternalName) val project = myDebugProcess.project return DebuggerUtils.findSourceFileForClass(project, myDebugProcess.searchScope, className, sourceName) } private fun defaultInternalName(location: Location): String { //no stratum or source path => use default one val referenceFqName = location.declaringType().name() // JDI names are of form "package.Class$InnerClass" return referenceFqName.replace('.', '/') } override fun getAllClasses(sourcePosition: SourcePosition): List<ReferenceType> { val psiFile = sourcePosition.file if (psiFile is KtFile) { val result = ArrayList<ReferenceType>() if (!ProjectRootsUtil.isInProjectOrLibSource(psiFile)) return result val names = classNamesForPositionAndInlinedOnes(sourcePosition) for (name in names) { result.addAll(myDebugProcess.virtualMachineProxy.classesByName(name)) } return result } if (psiFile is ClsFileImpl) { val decompiledPsiFile = runReadAction { psiFile.decompiledPsiFile } if (decompiledPsiFile is KtClsFile && sourcePosition.line == -1) { val className = JvmFileClassUtil.getFileClassInfoNoResolve(decompiledPsiFile).fileClassFqName.internalNameWithoutInnerClasses return myDebugProcess.virtualMachineProxy.classesByName(className) } } throw NoDataException.INSTANCE } private fun classNamesForPositionAndInlinedOnes(sourcePosition: SourcePosition): List<String> { val result = hashSetOf<String>() val names = classNamesForPosition(sourcePosition, true) result.addAll(names) val lambdas = findLambdas(sourcePosition) result.addAll(lambdas) return result.toReadOnlyList(); } private fun findLambdas(sourcePosition: SourcePosition): Collection<String> { return runReadAction { val lambdas = getLambdasAtLineIfAny(sourcePosition) val file = sourcePosition.file.containingFile as KtFile val isInLibrary = LibraryUtil.findLibraryEntry(file.virtualFile, file.project) != null lambdas.flatMap { val typeMapper = if (!isInLibrary) prepareTypeMapper(file) else createTypeMapperForLibraryFile(it, file) getInternalClassNameForElement(it, typeMapper, file, isInLibrary) } } } fun classNamesForPosition(sourcePosition: SourcePosition, withInlines: Boolean): Collection<String> { val psiElement = runReadAction { sourcePosition.elementAt } ?: return emptyList() return classNamesForPosition(psiElement, withInlines) } private fun classNamesForPosition(element: PsiElement, withInlines: Boolean): Collection<String> { return runReadAction { if (DumbService.getInstance(element.project).isDumb) { emptySet() } else { val file = element.containingFile as KtFile val isInLibrary = LibraryUtil.findLibraryEntry(file.virtualFile, file.project) != null val typeMapper = if (!isInLibrary) prepareTypeMapper(file) else createTypeMapperForLibraryFile(element, file) getInternalClassNameForElement(element, typeMapper, file, isInLibrary, withInlines) } } } private fun prepareTypeMapper(file: KtFile): JetTypeMapper { val key = createKeyForTypeMapper(file) var value: CachedValue<JetTypeMapper>? = myTypeMappers.get(key) if (value == null) { value = CachedValuesManager.getManager(file.project).createCachedValue<JetTypeMapper>( { val typeMapper = createTypeMapper(file) CachedValueProvider.Result(typeMapper, PsiModificationTracker.MODIFICATION_COUNT) }, false) myTypeMappers.put(key, value) } return value.value } override fun locationsOfLine(type: ReferenceType, position: SourcePosition): List<Location> { if (position.file !is KtFile) { throw NoDataException.INSTANCE } try { val line = position.line + 1 val locations = if (myDebugProcess.virtualMachineProxy.versionHigher("1.4")) type.locationsOfLine("Kotlin", null, line) else type.locationsOfLine(line) if (locations == null || locations.isEmpty()) throw NoDataException.INSTANCE return locations } catch (e: AbsentInformationException) { throw NoDataException.INSTANCE } } @Deprecated("Since Idea 14.0.3 use createPrepareRequests fun") override fun createPrepareRequest(classPrepareRequestor: ClassPrepareRequestor, sourcePosition: SourcePosition): ClassPrepareRequest? { return createPrepareRequests(classPrepareRequestor, sourcePosition).firstOrNull() } override fun createPrepareRequests(requestor: ClassPrepareRequestor, position: SourcePosition): List<ClassPrepareRequest> { if (position.file !is KtFile) { throw NoDataException.INSTANCE } return classNamesForPositionAndInlinedOnes(position).mapNotNull { className -> myDebugProcess.requestsManager.createClassPrepareRequest(requestor, className.replace('/', '.')) } } @TestOnly fun addTypeMapper(file: KtFile, typeMapper: JetTypeMapper) { val value = CachedValuesManager.getManager(file.project).createCachedValue<JetTypeMapper>( { CachedValueProvider.Result(typeMapper, PsiModificationTracker.MODIFICATION_COUNT) }, false) val key = createKeyForTypeMapper(file) myTypeMappers.put(key, value) } private fun getInternalClassNameForElement( notPositionedElement: PsiElement?, typeMapper: JetTypeMapper, file: KtFile, isInLibrary: Boolean, withInlines: Boolean = true ): Collection<String> { val element = getElementToCalculateClassName(notPositionedElement) when (element) { is KtClassOrObject -> return getJvmInternalNameForImpl(typeMapper, element).toSet() is KtFunction -> { val descriptor = InlineUtil.getInlineArgumentDescriptor(element, typeMapper.bindingContext) if (descriptor != null) { val classNamesForParent = getInternalClassNameForElement(element.parent, typeMapper, file, isInLibrary, withInlines) if (descriptor.isCrossinline) { return findCrossInlineArguments(element, descriptor, typeMapper.bindingContext) + classNamesForParent } return classNamesForParent } } } val crossInlineParameterUsages = element?.containsCrossInlineParameterUsages(typeMapper.bindingContext) if (crossInlineParameterUsages != null && crossInlineParameterUsages.isNotEmpty()) { return classNamesForCrossInlineParameters(crossInlineParameterUsages, typeMapper.bindingContext) } when { element is KtFunctionLiteral -> { val asmType = CodegenBinding.asmTypeForAnonymousClass(typeMapper.bindingContext, element) return asmType.internalName.toSet() } element is KtAnonymousInitializer -> { val parent = getElementToCalculateClassName(element.parent) // Class-object initializer if (parent is KtObjectDeclaration && parent.isCompanion()) { return getInternalClassNameForElement(parent.parent, typeMapper, file, isInLibrary, withInlines) } return getInternalClassNameForElement(element.parent, typeMapper, file, isInLibrary, withInlines) } element is KtProperty && (!element.isTopLevel || !isInLibrary) -> { if (isInPropertyAccessor(notPositionedElement)) { val classOrObject = PsiTreeUtil.getParentOfType(element, KtClassOrObject::class.java) if (classOrObject != null) { return getJvmInternalNameForImpl(typeMapper, classOrObject).toSet() } } val descriptor = typeMapper.bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, element) if (descriptor !is PropertyDescriptor) { return getInternalClassNameForElement(element.parent, typeMapper, file, isInLibrary, withInlines) } return getJvmInternalNameForPropertyOwner(typeMapper, descriptor).toSet() } element is KtNamedFunction -> { val parent = getElementToCalculateClassName(element.parent) val parentInternalName = if (parent is KtClassOrObject) { getJvmInternalNameForImpl(typeMapper, parent) } else if (parent != null) { val asmType = CodegenBinding.asmTypeForAnonymousClass(typeMapper.bindingContext, element) asmType.internalName } else { NoResolveFileClassesProvider.getFileClassInternalName(file) } if (!withInlines) return parentInternalName.toSet() val inlinedCalls = findInlinedCalls(element, typeMapper.bindingContext) return inlinedCalls + parentInternalName.toSet() } } return NoResolveFileClassesProvider.getFileClassInternalName(file).toSet() } private val TYPES_TO_CALCULATE_CLASSNAME: Array<Class<out KtElement>> = arrayOf(KtClassOrObject::class.java, KtFunctionLiteral::class.java, KtNamedFunction::class.java, KtProperty::class.java, KtAnonymousInitializer::class.java) private fun getElementToCalculateClassName(notPositionedElement: PsiElement?): KtElement? { if (notPositionedElement?.javaClass as Class<*> in TYPES_TO_CALCULATE_CLASSNAME) return notPositionedElement as KtElement return PsiTreeUtil.getParentOfType(notPositionedElement, *TYPES_TO_CALCULATE_CLASSNAME) } fun getJvmInternalNameForPropertyOwner(typeMapper: JetTypeMapper, descriptor: PropertyDescriptor): String { return typeMapper.mapOwner( if (JvmAbi.isPropertyWithBackingFieldInOuterClass(descriptor)) descriptor.containingDeclaration else descriptor ).internalName } private fun isInPropertyAccessor(element: PsiElement?) = element is KtPropertyAccessor || PsiTreeUtil.getParentOfType(element, KtProperty::class.java, KtPropertyAccessor::class.java) is KtPropertyAccessor private fun getElementToCreateTypeMapperForLibraryFile(element: PsiElement?) = if (element is KtElement) element else PsiTreeUtil.getParentOfType(element, KtElement::class.java) private fun getJvmInternalNameForImpl(typeMapper: JetTypeMapper, ktClass: KtClassOrObject): String? { val classDescriptor = typeMapper.bindingContext.get<PsiElement, ClassDescriptor>(BindingContext.CLASS, ktClass) ?: return null if (ktClass is KtClass && ktClass.isInterface()) { return typeMapper.mapDefaultImpls(classDescriptor).internalName } return typeMapper.mapClass(classDescriptor).internalName } private fun createTypeMapperForLibraryFile(notPositionedElement: PsiElement?, file: KtFile): JetTypeMapper { val element = getElementToCreateTypeMapperForLibraryFile(notPositionedElement) val analysisResult = element!!.analyzeAndGetResult() val state = GenerationState(file.project, ClassBuilderFactories.THROW_EXCEPTION, analysisResult.moduleDescriptor, analysisResult.bindingContext, listOf(file)) state.beforeCompile() return state.typeMapper } fun isInlinedLambda(functionLiteral: KtFunction, context: BindingContext): Boolean { return InlineUtil.isInlinedArgument(functionLiteral, context, false) } private fun createKeyForTypeMapper(file: KtFile) = NoResolveFileClassesProvider.getFileClassInternalName(file) private fun findInlinedCalls(function: KtNamedFunction, context: BindingContext): Set<String> { return runReadAction { val result = hashSetOf<String>() if (InlineUtil.isInline(context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, function))) { ReferencesSearch.search(function).forEach { if (!it.isImportUsage()) { val usage = it.element if (usage is KtElement) { //TODO recursive search val names = classNamesForPosition(usage, false) result.addAll(names) } } true } } result } } private fun findCrossInlineArguments(argument: KtFunction, parameterDescriptor: ValueParameterDescriptor, context: BindingContext): Set<String> { return runReadAction { val source = parameterDescriptor.source.getPsi() as? KtParameter val functionName = source?.ownerFunction?.name if (functionName != null) { return@runReadAction setOf(getCrossInlineArgumentClassName(argument, functionName, context)) } return@runReadAction emptySet() } } private fun getCrossInlineArgumentClassName(argument: KtFunction, inlineFunctionName: String, context: BindingContext): String { val anonymousClassNameForArgument = CodegenBinding.asmTypeForAnonymousClass(context, argument).internalName val newName = anonymousClassNameForArgument.substringIndex() + InlineCodegenUtil.INLINE_TRANSFORMATION_SUFFIX + "$" + inlineFunctionName return "$newName$*" } private fun KtElement.containsCrossInlineParameterUsages(context: BindingContext): Collection<ValueParameterDescriptor> { fun KtElement.hasParameterCall(parameter: KtParameter): Boolean { return ReferencesSearch.search(parameter).any { this.textRange.contains(it.element.textRange) } } val inlineFunction = this.parents.firstIsInstanceOrNull<KtNamedFunction>() ?: return emptySet() val inlineFunctionDescriptor = context[BindingContext.FUNCTION, inlineFunction] if (inlineFunctionDescriptor == null || !InlineUtil.isInline(inlineFunctionDescriptor)) return emptySet() return inlineFunctionDescriptor.valueParameters .filter { it.isCrossinline } .mapNotNull { val psiParameter = it.source.getPsi() as? KtParameter if (psiParameter != null && [email protected](psiParameter)) it else null } } private fun classNamesForCrossInlineParameters(usedParameters: Collection<ValueParameterDescriptor>, context: BindingContext): Set<String> { // We could calculate className only for one of parameters, because we add '*' to match all crossInlined parameter calls val parameter = usedParameters.first() val result = hashSetOf<String>() val inlineFunction = parameter.containingDeclaration.source.getPsi() as? KtNamedFunction ?: return emptySet() ReferencesSearch.search(inlineFunction).forEach { if (!it.isImportUsage()) { val call = (it.element as? KtExpression)?.let { KtPsiUtil.getParentCallIfPresent(it) } if (call != null) { val resolvedCall = call.getResolvedCall(context) val argument = resolvedCall?.valueArguments?.get(parameter) if (argument != null) { val argumentExpression = getArgumentExpression(argument.arguments.first()) if (argumentExpression is KtFunction) { result.add(getCrossInlineArgumentClassName(argumentExpression, inlineFunction.name!!, context)) } } } } true } return result } private fun getArgumentExpression(it: ValueArgument) = (it.getArgumentExpression() as? KtLambdaExpression)?.functionLiteral ?: it.getArgumentExpression() private fun String.substringIndex(): String { if (lastIndexOf("$") < 0) return this val suffix = substringAfterLast("$") if (suffix.all { it.isDigit() }) { return substringBeforeLast("$") + "$" } return this } private fun ReferenceType.containsKotlinStrata() = availableStrata().contains("Kotlin") private fun String?.toSet() = if (this == null) emptySet() else setOf(this) companion object { fun createTypeMapper(file: KtFile): JetTypeMapper { val project = file.project val analysisResult = file.analyzeFullyAndGetResult() analysisResult.throwIfError() val state = GenerationState( project, ClassBuilderFactories.THROW_EXCEPTION, analysisResult.moduleDescriptor, analysisResult.bindingContext, listOf(file)) state.beforeCompile() return state.typeMapper } } }
0
Java
0
1
c9cc9c55cdcc706c1d382a1539998728a2e3ca50
27,462
kotlin
Apache License 2.0
PermissionCheck/src/main/java/com/commonsware/android/r/permcheck/MainActivity.kt
kairusds-testing
395,288,161
false
null
/* Copyright (c) 2020 CommonsWare, 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. Covered in detail in the book _Elements of Android R_ https://commonsware.com/R */ package com.commonsware.android.r.permcheck import android.Manifest import android.content.Intent import android.location.Location import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.lifecycle.observe import com.commonsware.android.r.permcheck.databinding.ActivityMainBinding import org.koin.androidx.viewmodel.ext.android.viewModel private const val PERMS_LOCATION = 1337 class MainActivity : AppCompatActivity() { private val motor: MainMotor by viewModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) title = getString(R.string.title, hashCode()) motor.states.observe(this) { state -> when (state) { is MainViewState.Content -> { binding.permission.setOnCheckedChangeListener { _, isChecked -> if (isChecked && !state.hasPermission) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), PERMS_LOCATION ) } } if (binding.permission.isChecked != state.hasPermission) { binding.permission.isChecked = state.hasPermission } binding.permission.isEnabled = !state.hasPermission binding.requestLocation.isEnabled = state.hasPermission binding.location.text = state.location?.displayString ?: "(no location)" binding.requestLocation.setOnClickListener { motor.fetchLocation() } } MainViewState.Error -> { Toast.makeText(this, R.string.error_toast, Toast.LENGTH_LONG).show() finish() } } } binding.launch.setOnClickListener { startActivity(Intent(this, this.javaClass)) } } override fun onResume() { super.onResume() motor.checkPermission() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (requestCode == PERMS_LOCATION) { motor.checkPermission() } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } private val Location.displayString get() = getString(R.string.location, latitude, longitude) }
0
Kotlin
0
0
4c0e69206dac6661a80e615b14410df16eb83a56
3,104
cw-android-r
Apache License 2.0
src/main/kotlin/fe/client/gui/NetworkInventoryScreen.kt
natanfudge
217,017,390
false
null
package fe.client.gui import fe.container.NetworkInventoryScreenController import net.minecraft.entity.player.PlayerEntity class NetworkInventoryScreen(container: NetworkInventoryScreenController, player: PlayerEntity) : ExitableScreen<NetworkInventoryScreenController>(container, player) { //TODO: commenting this out might cause issues with transferring items override fun reposition() { val basePanel = description.rootPanel if (basePanel != null) { containerWidth = basePanel.width containerHeight = basePanel.height if (containerWidth < 16) { containerWidth = 300 } if (containerHeight < 16) { containerHeight = 300 } } x = width / 2 - containerWidth / 2 y = height / 2 - containerHeight / 2 } }
0
Kotlin
0
0
0f9e392bcf2cc0df628cf6d22786759be256284b
866
Fabricated-Energistics
MIT License
tea-time-travel-plugin/src/main/java/io/github/xlopec/tea/time/travel/plugin/ui/Preview.kt
Xlopec
188,455,731
false
null
/* * MIT License * * Copyright (c) 2021. Maksym Oliinyk. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.xlopec.tea.time.travel.plugin.ui import androidx.compose.runtime.compositionLocalOf /** * Flag to distinguish between preview and default modes. It can be used to disable some * features in preview mode or add some preview specific components, etc. */ val PreviewMode = compositionLocalOf { false }
0
Kotlin
1
10
343f1c7ea7755db989c752722a02cf85236cf9e2
1,462
Tea-bag
MIT License
src/test/kotlin/aoc2017/DuetTest.kt
komu
113,825,414
false
null
package komu.adventofcode.aoc2017 import komu.adventofcode.utils.readTestInput import org.junit.jupiter.api.Test import kotlin.test.assertEquals class DuetTest { @Test fun `example data`() { assertEquals(4, duet(""" set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2 """.trimIndent())) } @Test fun `real data`() { assertEquals(1187, duet(readTestInput("/2017/Duet.txt"))) } @Test fun `test data 2`() { assertEquals(3, duet2(""" snd 1 snd 2 snd p rcv a rcv b rcv c rcv d """.trimIndent())) } @Test fun `real data 2`() { assertEquals(5969, duet2(readTestInput("/2017/Duet.txt"))) } }
0
Kotlin
0
0
e59e8dec81de9ac6e7c9d6918eafb12353e87d75
915
advent-of-code
MIT License
database/src/main/kotlin/no/nav/su/se/bakover/database/PostgresTransactionContext.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.database import arrow.core.Either import arrow.core.getOrHandle import kotliquery.using import no.nav.su.se.bakover.common.persistence.TransactionContext import no.nav.su.se.bakover.database.PostgresTransactionContext.Companion.withTransaction import org.slf4j.LoggerFactory import javax.sql.DataSource /** * Holder en transaksjon på tvers av repo-kall. * Ikke tråd-sikker. */ internal class PostgresTransactionContext(private val dataSource: DataSource) : TransactionContext { private val log = LoggerFactory.getLogger(this::class.java) // Det er viktig at sesjoner ikke opprettes utenfor en try-with-resource, som kan føre til connection-lekkasjer. private var transactionalSession: TransactionalSession? = null companion object { /** * Første kall lager en ny transaksjonell sesjon og lukkes automatisk sammen med funksjonsblokka.. * Påfølgende kall gjenbruker samme transaksjon. * * * @throws IllegalStateException dersom den transaksjonelle sesjonen er lukket. */ // Dette er en extension function og ikke en funksjon i interfacet siden vi ikke ønsker en referanse til Session, som er infrastrukturspesifikt, i domenelaget. fun <T> TransactionContext.withTransaction(action: (TransactionalSession) -> T): T { this as PostgresTransactionContext return if (transactionalSession == null) { // Vi ønsker kun at den ytterste blokka lukker sesjonen (using) using(sessionOf(dataSource)) { session -> session.transaction { transactionalSession -> this.transactionalSession = transactionalSession action(transactionalSession) } } } else { if (isClosed()) { throw IllegalStateException("Den transaksjonelle sesjonen er lukket.") } action(transactionalSession!!) } } // Dette er en extension function og ikke en funksjon i interfacet siden vi ikke ønsker en referanse til Session, som er infrastrukturspesifikt, i domenelaget. /** * @throws IllegalStateException dersom man ikke har kalt [withTransaction] først eller den transaksjonelle sesjonen er lukket. */ fun <T> TransactionContext.withSession(action: (session: Session) -> T): T { this as PostgresTransactionContext if (transactionalSession == null) { throw IllegalStateException("Må først starte en withTransaction(...) før man kan kalle withSession(...) for en TransactionContext.") } if (isClosed()) { throw IllegalStateException("Den transaksjonelle sesjonen er lukket.") } return action(transactionalSession!!) } } /** * @return true dersom 1) den aldri har vært åpnet 2) er lukket 3) en feil skjedde. */ override fun isClosed(): Boolean { if (transactionalSession == null) return true return Either.catch { transactionalSession!!.connection.underlying.isClosed }.getOrHandle { log.error("En feil skjedde når vi prøvde å sjekke om den den transaksjonelle sesjonen var lukket", it) true } } }
3
Kotlin
0
0
b0864f973c8986f58af07c4bc7f601caa602dbfc
3,360
su-se-bakover
MIT License
app/src/main/java/com/recepguzel/cryptoxcleanarchitecture/data/repository/news/datasource/NewsRemoteDataSource.kt
recepbrk
801,143,879
false
{"Kotlin": 105580}
package com.recepguzel.cryptoxcleanarchitecture.data.repository.news.datasource import com.recepguzel.cryptoxcleanarchitecture.data.model.NewsResponse import retrofit2.Response interface NewsRemoteDataSource { suspend fun getEverythingNews( query: String, pageNumber: Int, apiKey: String ): Response<NewsResponse> }
0
Kotlin
0
0
c03edbf4e2bfdf3b2257ff9e35644f610d6c5e5c
350
CryptoXCleanArchitecture
Apache License 2.0
app/events/src/main/java/com/vallem/sylph/events/presentation/components/DoubleRow.kt
leonardovallem
613,461,263
false
{"Kotlin": 308660}
package com.vallem.sylph.events.presentation.components import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row 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.foundation.rememberScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.dp @Composable fun <T> DoubleRow( items: List<T>, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp), verticalArrangement: Arrangement.Vertical = Arrangement.Top, horizontalArrangement: Arrangement.Horizontal = Arrangement.Start, component: @Composable (T) -> Unit ) { val layoutDirection = LocalLayoutDirection.current val lists = remember { if (items.size % 2 == 0) listOf( items.subList(0, items.size / 2), items.subList(items.size / 2, items.size) ) else listOf( items.subList(0, items.size / 2 + 1), items.subList(items.size / 2 + 1, items.size) ) } Column( verticalArrangement = verticalArrangement, modifier = modifier .width(IntrinsicSize.Min) .padding( top = contentPadding.calculateTopPadding(), bottom = contentPadding.calculateBottomPadding() ) ) { lists.forEach { list -> Row( horizontalArrangement = horizontalArrangement, modifier = Modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()) ) { Spacer( modifier = Modifier.width(contentPadding.calculateLeftPadding(layoutDirection)) ) list.forEach { component(it) } Spacer( modifier = Modifier.width(contentPadding.calculateRightPadding(layoutDirection)) ) } } } }
0
Kotlin
0
0
27615ff4672845892d2150ed7069702b521115ef
2,458
sylph
MIT License
src/main/kotlin/tech/gdragon/commands/debug/Test.kt
guacamoledragon
96,600,559
false
{"Kotlin": 186592, "Clojure": 16441, "Shell": 5769, "HTML": 4662, "Just": 2918, "Dockerfile": 1530, "Makefile": 785, "Batchfile": 629}
package tech.gdragon.commands.debug import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel import net.dv8tion.jda.api.events.message.MessageReceivedEvent import org.jetbrains.exposed.sql.transactions.transaction import tech.gdragon.BotUtils import tech.gdragon.BotUtils.TRIGOMAN import tech.gdragon.api.pawa.Pawa import tech.gdragon.commands.CommandHandler import tech.gdragon.commands.audio.Record import tech.gdragon.commands.audio.Save import tech.gdragon.db.asyncTransaction import tech.gdragon.db.dao.Guild import tech.gdragon.db.dao.Recording import tech.gdragon.db.now import tech.gdragon.discord.message.RecordingReply import tech.gdragon.i18n.Lang import tech.gdragon.listener.CombinedAudioRecorderHandler class Test : CommandHandler() { override fun action(args: Array<String>, event: MessageReceivedEvent, pawa: Pawa) { if ((event.member?.idLong ?: 1L) == TRIGOMAN) { recordSave(event, pawa) } } private fun recordSave(event: MessageReceivedEvent, pawa: Pawa) { val voiceChannel: VoiceChannel = event.guild.getVoiceChannelsByName("bot-testing", true).first()!! val message = Record.handler(pawa, event.guild, voiceChannel, event.channel) BotUtils.sendMessage(event.channel, message) Thread.sleep(1000L) Save.handler(pawa, event.guild, event.channel) val recorder = event.guild.audioManager.receivingHandler as? CombinedAudioRecorderHandler val recording = recorder?.recording!! // val recording = transaction { Recording.all().first() } val recordingEmbed = RecordingReply(recording, pawa.config.appUrl) event.channel.sendMessage(recordingEmbed.message).queue() } fun recordingReply(event: MessageReceivedEvent, pawa: Pawa) { val recording = transaction { Recording.all().first() } val recordingEmbed = RecordingReply(recording, pawa.config.appUrl) event.channel.sendMessage(recordingEmbed.message).queue() } fun async(event: MessageReceivedEvent, pawa: Pawa) { for (i in 1..1000) { asyncTransaction { val guild = Guild[event.guild.idLong] guild.lastActiveOn = now() print("$i,") } } } override fun usage(prefix: String, lang: Lang): String { TODO("Not yet implemented") } override fun description(lang: Lang): String { TODO("Not yet implemented") } }
5
Kotlin
18
45
0837d5e02a765b05281e485d57fc251815e1f2cf
2,327
throw-voice
Apache License 2.0
src/2/2588.kt
WhiteKr
408,096,320
true
{"Kotlin": 23417, "C++": 3624, "Python": 181, "Java": 161}
import java.util.* fun main() = with(Scanner(System.`in`)) { val a: Int = nextInt() val b: Int = nextInt() for (n in "$b".reversed()) println(a * n.digitToInt()) print(a * b) }
4
Kotlin
1
0
3b6eb14ebb5487260508a594a66b7d32fcf879ab
194
Baekjoon
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/alexa/ask/CfnSkillPropsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION") package cloudshift.awscdk.dsl.alexa.ask import cloudshift.awscdk.common.CdkDslMarker import software.amazon.awscdk.IResolvable import software.amazon.awscdk.alexa.ask.CfnSkill import software.amazon.awscdk.alexa.ask.CfnSkillProps import kotlin.String /** * Properties for defining a `CfnSkill`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.alexa.ask.*; * Object manifest; * CfnSkillProps cfnSkillProps = CfnSkillProps.builder() * .authenticationConfiguration(AuthenticationConfigurationProperty.builder() * .clientId("clientId") * .clientSecret("clientSecret") * .refreshToken("refreshToken") * .build()) * .skillPackage(SkillPackageProperty.builder() * .s3Bucket("s3Bucket") * .s3Key("s3Key") * // the properties below are optional * .overrides(OverridesProperty.builder() * .manifest(manifest) * .build()) * .s3BucketRole("s3BucketRole") * .s3ObjectVersion("s3ObjectVersion") * .build()) * .vendorId("vendorId") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ask-skill.html) */ @CdkDslMarker public class CfnSkillPropsDsl { private val cdkBuilder: CfnSkillProps.Builder = CfnSkillProps.builder() /** * @param authenticationConfiguration Login with Amazon (LWA) configuration used to authenticate * with the Alexa service. * Only Login with Amazon clients created through the are supported. The client ID, client * secret, and refresh token are required. */ public fun authenticationConfiguration(authenticationConfiguration: IResolvable) { cdkBuilder.authenticationConfiguration(authenticationConfiguration) } /** * @param authenticationConfiguration Login with Amazon (LWA) configuration used to authenticate * with the Alexa service. * Only Login with Amazon clients created through the are supported. The client ID, client * secret, and refresh token are required. */ public fun authenticationConfiguration(authenticationConfiguration: CfnSkill.AuthenticationConfigurationProperty) { cdkBuilder.authenticationConfiguration(authenticationConfiguration) } /** * @param skillPackage Configuration for the skill package that contains the components of the * Alexa skill. * Skill packages are retrieved from an Amazon S3 bucket and key and used to create and update the * skill. For more information about the skill package format, see the . */ public fun skillPackage(skillPackage: IResolvable) { cdkBuilder.skillPackage(skillPackage) } /** * @param skillPackage Configuration for the skill package that contains the components of the * Alexa skill. * Skill packages are retrieved from an Amazon S3 bucket and key and used to create and update the * skill. For more information about the skill package format, see the . */ public fun skillPackage(skillPackage: CfnSkill.SkillPackageProperty) { cdkBuilder.skillPackage(skillPackage) } /** * @param vendorId The vendor ID associated with the Amazon developer account that will host the * skill. * Details for retrieving the vendor ID are in . The provided LWA credentials must be linked to * the developer account associated with this vendor ID. */ public fun vendorId(vendorId: String) { cdkBuilder.vendorId(vendorId) } public fun build(): CfnSkillProps = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
3,784
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/com/example/myapp/ui/ListFragment.kt
prshntpnwr
268,751,968
false
null
package com.example.myapp.ui import android.os.Bundle import android.view.* import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingComponent import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.findNavController import com.example.myapp.R import com.example.myapp.binding.FragmentDataBindingComponent import com.example.myapp.databinding.FragmentListBinding import com.example.myapp.observer.ListViewModel import com.example.myapp.util.AppExecutors import com.example.myapp.util.Status /** * A simple [Fragment] subclass. */ class ListFragment : Fragment() { lateinit var executors: AppExecutors private lateinit var viewModel: ListViewModel private var dataBindingComponent: DataBindingComponent = FragmentDataBindingComponent(this) private lateinit var binding: FragmentListBinding private lateinit var adapter: PictureListAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment DataBindingUtil.inflate<FragmentListBinding>( inflater, R.layout.fragment_list, container, false, dataBindingComponent ) .also { it.lifecycleOwner = this binding = it executors = AppExecutors() }.run { return this.root } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) (activity as AppCompatActivity?)?.setSupportActionBar(binding.toolbar) PictureListAdapter( dataBindingComponent = dataBindingComponent, appExecutors = executors ) { photo, action -> when (action) { RETRY -> viewModel.retry() ITEM_CLICK -> { photo?.let { val act = ListFragmentDirections.actionListFragmentToDetailFragment(photo.id) findNavController().navigate(act) } } } }.also { adapter = it binding.recyclerView.adapter = it } viewModel = ViewModelProviders.of(this) .get(ListViewModel::class.java) .also { binding.viewModel = it it.setArgs(executors) it.posts.observe(this, Observer { list -> adapter.submitList(list) viewModel.shouldFetch = false binding.isEmpty = list.isEmpty() && it.networkState.value == Status.SUCCESS }) it.networkState.observe(this, Observer { adapter.updateNetworkState(it) binding.isEmpty = adapter.itemCount == 0 && it == Status.SUCCESS }) it.refreshState.observe(this, Observer { }) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) inflater?.inflate(R.menu.menu_search, menu) val searchView = androidx.appcompat.widget.SearchView((activity as AppCompatActivity?)?.supportActionBar?.themedContext ?: context) menu.findItem(R.id.app_bar_search).apply { setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW or MenuItem.SHOW_AS_ACTION_IF_ROOM) actionView = searchView } searchView.setOnQueryTextListener(searchListener) } private val searchListener = object : androidx.appcompat.widget.SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { viewModel.shouldFetch = true viewModel.deleteRecords() viewModel.search(query ?: "") return false } override fun onQueryTextChange(newText: String?): Boolean { return false } } companion object { const val RETRY = 0 const val ITEM_CLICK = 1 } }
1
null
1
1
0384312fa45f0eb4020f3acd536ec64c572c777e
4,441
Flickr
Apache License 2.0
libraries/core/src/main/java/com/escodro/core/extension/ViewGroupExtensions.kt
Arab1997
307,581,565
false
null
package com.escodro.core.extension import android.view.View import android.view.ViewGroup /** * Gets the [List] of all the child inside the [ViewGroup]. * * @return list of all the child inside the [ViewGroup]. */ @Suppress("UNCHECKED_CAST") fun <T : View> ViewGroup.getChildren(): List<T> { val size = this.childCount val list = mutableListOf<T>() for (i in 0..size) { val view = this.getChildAt(i) as? T view?.let { list.add(it) } } return list }
1
null
1
1
cb8056afe8bc03bfb3f89938a168961aa211f860
493
alkaa
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/modules/walletconnect/list/WalletConnectListService.kt
siqka
385,261,468
false
null
package io.horizontalsystems.bankwallet.modules.walletconnect.list import io.horizontalsystems.bankwallet.core.IPredefinedAccountTypeManager import io.horizontalsystems.bankwallet.entities.AccountType import io.horizontalsystems.bankwallet.entities.PredefinedAccountType import io.horizontalsystems.bankwallet.entities.WalletConnectSession import io.horizontalsystems.bankwallet.modules.walletconnect.WalletConnectSessionManager import io.horizontalsystems.ethereumkit.core.EthereumKit import io.horizontalsystems.ethereumkit.core.EthereumKit.NetworkType import io.horizontalsystems.ethereumkit.models.Address import io.reactivex.Flowable class WalletConnectListService( private val predefinedAccountTypeManager: IPredefinedAccountTypeManager, private val sessionManager: WalletConnectSessionManager ) { val items: List<Item> get() = getItems(sessionManager.sessions) val itemsObservable: Flowable<List<Item>> get() = sessionManager.sessionsObservable.map { sessions -> getItems(sessions) } private fun getEvmAddress(chainId: Int, accountType: AccountType): Address? = when { accountType !is AccountType.Mnemonic -> null chainId == 1 -> EthereumKit.address(accountType.words, NetworkType.EthMainNet) chainId == 56 -> EthereumKit.address(accountType.words, NetworkType.BscMainNet) else -> null } private fun getItems(sessions: List<WalletConnectSession>): List<Item> { val items = mutableListOf<Item>() for (predefinedAccountType in predefinedAccountTypeManager.allTypes) { predefinedAccountTypeManager.account(predefinedAccountType)?.let { account -> val accountSessions = sessions.filter { it.accountId == account.id } if (accountSessions.isNotEmpty()) { getEvmAddress(accountSessions.first().chainId, account.type)?.let { address -> items.add(Item(predefinedAccountType, address, accountSessions)) } } } } return items } data class Item( val predefinedAccountType: PredefinedAccountType, val address: Address, val sessions: List<WalletConnectSession> ) }
0
Kotlin
0
1
0e951bc55e2ccdc9fb077466f0a1c700c8ad99fa
2,287
siqkawallet-andriod
MIT License
app/src/main/java/desoft/studio/webpoint/KusAdapter.kt
JK-IT
385,474,689
false
null
package desoft.studio.webpoint import android.content.Context import android.content.Intent import android.text.SpannableStringBuilder import android.util.Patterns import android.view.* import android.widget.* import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.selection.SelectionTracker import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import desoft.studio.webpoint.data.Wpoint import desoft.studio.webpoint.fragments.KusDiaFrag private const val tagg = "KUS ADAPTER"; class KusAdapter(private val ctx : Context, private var recy: RecyclerView) : RecyclerView.Adapter<KusAdapter.ViewHolder>() { //--------------- Things belong to Adapter var tracker: SelectionTracker<String>? = null; var dataSet: List<Wpoint> = ArrayList<Wpoint>(); // this list will be cleared by contextual mode on Finished var selectedSet: MutableSet<Wpoint> = mutableSetOf<Wpoint>(); var isActionMode: Boolean = false; init { setHasStableIds(true); // confirm that each item on the list has stable id } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { var v: View; v = LayoutInflater.from(parent.context) .inflate(R.layout.recyview_item_layout, parent, false); return this.ViewHolder(v, parent.context); } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val data = dataSet[position]; // -> Wpoint tracker?.let { holder.BindData(data, it.selection.contains(data.Name)); // can use isSelected as shortcut } } override fun getItemCount(): Int { return dataSet.size; } override fun getItemId(position: Int): Long { return position.toLong(); } public fun SetTracker(track: SelectionTracker<String>) { tracker = track; // set up observer tracker!!.addObserver(KusSelectionObserver(track)); } public fun GetTracker(): SelectionTracker<String> { return tracker!!; } public fun SetData(indata: List<Wpoint>) { this.dataSet = indata; notifyDataSetChanged(); recy.scheduleLayoutAnimation(); } public fun GetAdapterData(): List<Wpoint> { return dataSet; } fun SetActModeState(started: Boolean) { isActionMode = started; } // ------------ View Holder inner class ViewHolder(val v: View, val ctx: Context?) : RecyclerView.ViewHolder(v) { val plugview: TextView; val urlview : TextView; val openbut: ImageButton; val editbut: ImageButton; val deletebut: ImageButton; init { plugview = v.findViewById<TextView>(R.id.tv_itemNameView); urlview = v.findViewById<TextView>(R.id.tv_urlview); openbut = v.findViewById<ImageButton>(R.id.open_button).apply { setOnClickListener { var intent = Intent(ctx, WebPagesActivity::class.java); intent.putExtra(WebPagesActivity.webName, plugview.text.toString()); intent.putExtra(WebPagesActivity.webUrl, GetAdapterData()[absoluteAdapterPosition].Url); ctx?.startActivity(intent); } } editbut = v.findViewById<ImageButton>(R.id.edit_button).apply { isEnabled = true; setOnClickListener{ // pop up the add item dialog val v = LayoutInflater.from(ctx).inflate(R.layout.frag_update_layout, null); val point = dataSet[absoluteAdapterPosition]; var disfrag = KusDiaFrag(R.layout.frag_update_layout); disfrag.SetViewHandler(object : KusDiaFrag.SetupView{ override fun SetViewUI(vi: View) { val nameinput : EditText = vi.findViewById(R.id.frag_update_name); nameinput.text = SpannableStringBuilder(point.Name); val urlinput : EditText = vi.findViewById(R.id.frag_update_url); urlinput.text = SpannableStringBuilder(point.Url); val update : Button = vi.findViewById(R.id.frag_update_button); val cancel : Button = vi.findViewById(R.id.frag_cancel_button); update.setOnClickListener(){ if(nameinput.text.toString().isNotBlank() && urlinput.text.toString().isNotBlank() && Patterns.WEB_URL.matcher(urlinput.text.toString()).matches()) { var updatepoint = Wpoint(nameinput.text.toString().uppercase(),urlinput.text.toString() ); if(dataSet.indexOfFirst { it.Name.contains(nameinput.text)} != -1) // find the duplicate key { (ctx as MainActivity).AddPointNDelete(false, 0, updatepoint); } else { // the new point not existed (ctx as MainActivity).AddPointNDelete(true, absoluteAdapterPosition, updatepoint); } Toast.makeText((ctx as MainActivity), "Successfully update the item", Toast.LENGTH_SHORT).show(); } else { Snackbar.make((ctx as MainActivity).window.decorView.findViewById(android.R.id.content), "Please Enter Valid Name and Url!", Snackbar.LENGTH_SHORT).setAnimationMode(Snackbar.ANIMATION_MODE_SLIDE).show(); } disfrag.dismiss(); } cancel.setOnClickListener(){ disfrag.dismiss(); } } }) var ft = (ctx as MainActivity).supportFragmentManager.beginTransaction(); var prev = (ctx as MainActivity).supportFragmentManager.findFragmentByTag( KusDiaFrag.tagg); if(prev != null) { ft.remove(prev); } disfrag.show((ctx as MainActivity).supportFragmentManager, KusDiaFrag.tagg) } } deletebut = v.findViewById<ImageButton>(R.id.delete_button).apply { isEnabled = true; setOnClickListener{ MaterialAlertDialogBuilder(ctx!!).setTitle("Delete") .setMessage("Are you sure deleting this item?") .setPositiveButton("Yes"){ dis, _ -> val point = dataSet[absoluteAdapterPosition]; (ctx as MainActivity).DeleteWpoin(point); dis.dismiss(); }.setNegativeButton("No"){ dis, _ -> dis.dismiss() }.setCancelable(true).create().show(); } } } fun BindData(dat: Wpoint, isActivated: Boolean = false) { var itemName = dat.Name.lowercase(); var words = itemName.split(" "); var ditedname = words.joinToString (separator = " "){word -> word.replaceFirstChar { it.uppercaseChar() }} plugview.text = "${ditedname}"; urlview.text = "${dat.Url}"; itemView.isActivated = isActivated; } fun GetItemDetails(): KusItemDetails<String> { return KusItemDetails(absoluteAdapterPosition, dataSet[absoluteAdapterPosition].Name); } } inner class KusSelectionObserver(track: SelectionTracker<String>) : SelectionTracker.SelectionObserver<String>() { override fun onItemStateChanged(key: String, selected: Boolean) { super.onItemStateChanged(key, selected) if (tracker?.selection?.size() == 1 && !isActionMode) { (ctx as MainActivity).StartTextualMode(); } else if (tracker?.selection?.size() == 0 && isActionMode) { //Log.i(tagg, "Observer : no item is selected so stopping contextual mode"); (ctx as MainActivity).StopTextualMode(); } } override fun onSelectionChanged() { // getting key from this selection if(tracker?.hasSelection() == true) { var tracsiz = tracker?.selection?.size(); var traciter = tracker?.selection?.iterator(); var temp = mutableSetOf<Wpoint>(); if (tracsiz != null) { while(tracsiz >0 ) { var naky = traciter?.next(); var pos = GetAdapterData().indexOfFirst { it.Name == naky }; temp.add(GetAdapterData()[pos]); //Log.i(tagg, "Adding to selectedSet ${selectedSet.size}"); tracsiz--; } selectedSet = temp; } } super.onSelectionChanged() } override fun onSelectionRefresh() { super.onSelectionRefresh() } override fun onSelectionRestored() { super.onSelectionRestored() } } }
0
Kotlin
0
0
0f5eff1d43ad1271bd9861c78d42addcf6aba454
9,966
pointbew
Apache License 2.0
src/d100/swing-app/src/main/java/org/example/listmodels/ObjectComponentsListModel.kt
mazhukinevgeniy
642,564,721
false
null
package org.example.listmodels import org.example.tables.DbAccessor import org.example.tables.SelectWithTitles import javax.swing.AbstractListModel class ObjectComponentsListModel( private val objectId: Long ) : AbstractListModel<String>(), ExtendedListModel<Long> { private val queries = DbAccessor.database.objectcomponentsQueries private var data = ArrayList<SelectWithTitles>( queries.selectWithTitles(objectId).executeAsList() ) override fun add(value: Long) { queries.insert(objectId, value) val oldSize = data.size data = ArrayList(queries.selectWithTitles(objectId).executeAsList()) if (oldSize > 0) { fireContentsChanged(this, 0, oldSize - 1) } fireIntervalAdded(this, oldSize, data.size - 1) } override fun itemId(index: Int): Long { require(index in data.indices) return data[index].collectionID } override fun getSize(): Int { return data.size } override fun getElementAt(index: Int): String { require(index in data.indices) return data[index].name } }
8
Kotlin
0
0
8ceaec327ed6c8d369c34a4b7a810c5002fb5a1e
1,127
d100
MIT License
misk-feature/src/testFixtures/kotlin/misk/feature/testing/FakeFeatureFlagsOverrideModule.kt
cashapp
113,107,217
false
{"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58}
package misk.feature.testing import com.google.inject.Provides import misk.inject.KAbstractModule import misk.inject.KInstallOnceModule import misk.testing.TestFixture import javax.inject.Singleton import kotlin.reflect.KClass /** * Install defaults for [FakeFeatureFlags]. This module can be install many times, allowing for * feature flag overrides to be modular and scoped to the module the flag is used in. * * In any module use: * ``` * install(FakeFeatureFlagsModuleOverrideModule { * override(Feature("foo"), true) * overrideJsonString(Feature("bar"), "{ \"target\": 0.1 }") * }) * ``` */ class FakeFeatureFlagsOverrideModule private constructor( private val qualifier: KClass<out Annotation>? = null, private val override: FakeFeatureFlagsOverride, ) : KAbstractModule() { constructor( qualifier: KClass<out Annotation>? = null, overrideLambda: FakeFeatureFlags.() -> Unit, ) : this( qualifier, FakeFeatureFlagsOverride(overrideLambda) ) override fun configure() { multibind<FakeFeatureFlagsOverride>(qualifier).toInstance(override) } class FakeFeatureFlagsOverride( val overrideLambda: FakeFeatureFlags.() -> Unit ) } internal class FakeFeatureFlagsTestFixtureModule: KInstallOnceModule() { override fun configure() { multibind<TestFixture>().to<FakeFeatureFlagsFixture>() } @Provides @Singleton internal fun providesFakeFeatureFlagsResource( featureFlags: FakeFeatureFlags, overrides: Set<FakeFeatureFlagsOverrideModule.FakeFeatureFlagsOverride> ): FakeFeatureFlagsFixture { return FakeFeatureFlagsFixture(featureFlags, block = { overrides.forEach { it.overrideLambda(this) } }) } } /** * Applies the default feature flag overrides before every test. */ internal class FakeFeatureFlagsFixture( private val featureFlags: FakeFeatureFlags, private val block: (FakeFeatureFlags.() -> Unit) ) : TestFixture { override fun reset() { block(featureFlags) } }
169
Kotlin
169
400
13dcba0c4e69cc2856021270c99857e7e91af27d
1,973
misk
Apache License 2.0
gr8-plugin-common/src/main/kotlin/com/gradleup/gr8/StripGradleApiTask.kt
GradleUp
393,462,224
false
{"Kotlin": 34172}
package com.gradleup.gr8 import com.gradleup.gr8.ZipHelper.buildZip import org.gradle.api.DefaultTask import org.gradle.api.file.FileCollection import org.gradle.api.file.RegularFile import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Provider import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import java.io.File import java.util.zip.ZipInputStream abstract class StripGradleApiTask : DefaultTask() { @get:InputFile @get:Optional internal abstract val gradleApiJar: RegularFileProperty @get:OutputFile internal abstract val strippedGradleApiJar: RegularFileProperty fun gradleApiJar(fileCollection: FileCollection) { gradleApiJar.set( project.layout.file( project.provider { fileCollection.files.single { //println(it.name) it.isGradleApi() } } ) ) gradleApiJar.disallowChanges() } fun gradleApiJar(file: File) { gradleApiJar.set(file) gradleApiJar.disallowChanges() } fun gradleApiJar(regularFileProperty: RegularFileProperty) { gradleApiJar.set(regularFileProperty) gradleApiJar.disallowChanges() } fun strippedGradleApiJar(): Provider<RegularFile> = strippedGradleApiJar fun strippedGradleApiJar(file: File) { strippedGradleApiJar.set(file) strippedGradleApiJar.disallowChanges() } fun strippedGradleApiJar(regularFileProperty: RegularFileProperty) { strippedGradleApiJar.set(regularFileProperty) strippedGradleApiJar.disallowChanges() } @TaskAction fun taskAction() { buildZip(strippedGradleApiJar.asFile.get()) { addZipFile(gradleApiJar.asFile.get()) { if (entry.name.startsWith("org/gradle/internal/impldep/META-INF/")) { skip() } } } } companion object { fun File.isGradleApi(): Boolean { // See https://github.com/GradleUp/gr8/issues/10, using the jar name only is not enough val isMaybeGradleApi = Regex("gradle-api-+[0-9.]*.jar").matches(name) if (!isMaybeGradleApi) { return false } return ZipInputStream(inputStream()).use { while (true) { val entry = it.nextEntry if (entry == null) { break } if (entry.name.contains("org/gradle/internal/impldep/META-INF/")) { return@use true } } false } } } }
2
Kotlin
6
63
6d9c5ea634bf28f32141d1fce88a81ea03b77797
2,532
gr8
MIT License
android-app/src/main/kotlin/fr/cph/chicago/repository/RealmConfig.kt
carlphilipp
16,032,504
false
null
/** * Copyright 2021 Carl-Philipp Harmant * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.cph.chicago.repository import android.os.Build import fr.cph.chicago.core.App import io.realm.Realm import io.realm.RealmConfiguration object RealmConfig { fun setUpRealm() { Realm.init(App.instance.applicationContext) Realm.setDefaultConfiguration(getRealmConfiguration()) } fun cleanRealm() { Realm.deleteRealm(getRealmConfiguration()) } private fun getRealmConfiguration(): RealmConfiguration { val context = App.instance.applicationContext val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)!! return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { RealmConfiguration.Builder() .schemaVersion(packageInfo.longVersionCode) .deleteRealmIfMigrationNeeded() .build() } else { RealmConfiguration.Builder() .schemaVersion(packageInfo.versionCode.toLong()) .deleteRealmIfMigrationNeeded() .build() } } }
3
null
1
9
1f6d4bc5855852fb0c343f04d13ef133b4419228
1,670
chicago-commutes
Apache License 2.0
demoapp/src/main/java/com/mercadolibre/android/andesui/demoapp/components/textfield/InflateTextfieldHelper.kt
maaguero
252,283,086
false
null
package com.mercadolibre.android.andesui.demoapp.components.textfield import android.content.Context import android.text.Editable import android.text.InputType import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.Spinner import android.widget.ArrayAdapter import android.widget.Toast import android.widget.EditText import android.widget.CheckBox import android.widget.ScrollView import androidx.core.content.ContextCompat import com.mercadolibre.android.andesui.button.AndesButton import com.mercadolibre.android.andesui.checkbox.AndesCheckbox import com.mercadolibre.android.andesui.checkbox.status.AndesCheckboxStatus import com.mercadolibre.android.andesui.demoapp.R import com.mercadolibre.android.andesui.demoapp.utils.AndesSpecs import com.mercadolibre.android.andesui.demoapp.utils.launchSpecs import com.mercadolibre.android.andesui.textfield.AndesTextarea import com.mercadolibre.android.andesui.textfield.AndesTextfield import com.mercadolibre.android.andesui.textfield.AndesTextfieldCode import com.mercadolibre.android.andesui.textfield.content.AndesTextfieldLeftContent import com.mercadolibre.android.andesui.textfield.content.AndesTextfieldRightContent import com.mercadolibre.android.andesui.textfield.state.AndesTextfieldCodeState import com.mercadolibre.android.andesui.textfield.state.AndesTextfieldState import com.mercadolibre.android.andesui.textfield.style.AndesTextfieldCodeStyle import java.util.Locale import kotlin.collections.ArrayList object InflateTextfieldHelper { @Suppress("LongMethod") // Method used to inflate a textfield usecase for test app fun inflateAndesTextfield(context: Context): View { val layoutTextfield = LayoutInflater .from(context) .inflate(R.layout.andesui_dynamic_textfield, null, false ) val textfield = layoutTextfield.findViewById<AndesTextfield>(R.id.andesui_textfield) val button = layoutTextfield.findViewById<AndesButton>(R.id.change_button) val clearButton = layoutTextfield.findViewById<AndesButton>(R.id.clear_button) val label = layoutTextfield.findViewById<AndesTextfield>(R.id.label_text) val helper = layoutTextfield.findViewById<AndesTextfield>(R.id.helper_text) val placeholder = layoutTextfield.findViewById<AndesTextfield>(R.id.placeholder_text) val counter = layoutTextfield.findViewById<EditText>(R.id.counter) val mask = layoutTextfield.findViewById<AndesTextfield>(R.id.mask) val checkBoxHideIcon = layoutTextfield.findViewById<CheckBox>(R.id.checkboxHideIcon) counter.setText(COUNTER_DEFAULT_TEXT) textfield.counter = COUNTER_DEFAULT val inputTypeSpinner: Spinner = layoutTextfield.findViewById(R.id.textType_spinner) val typeAdapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, getInputTypesArray()) typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) inputTypeSpinner.adapter = typeAdapter val stateSpinner: Spinner = layoutTextfield.findViewById(R.id.state_spinner) val stateAdapter = ArrayAdapter( context, android.R.layout.simple_spinner_item, context.resources.getStringArray(R.array.andes_textfield_state_2_spinner) ) stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) stateSpinner.adapter = stateAdapter val preffixSpinner: Spinner = layoutTextfield.findViewById(R.id.prefix_spinner) val preffixAdapter = ArrayAdapter( context, android.R.layout.simple_spinner_item, context.resources.getStringArray(R.array.andes_textfield_prefix_spinner) ) preffixAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) preffixSpinner.adapter = preffixAdapter val suffixSpinner: Spinner = layoutTextfield.findViewById(R.id.suffix_spinner) val suffixAdapter = ArrayAdapter( context, android.R.layout.simple_spinner_item, context.resources.getStringArray(R.array.andes_textfield_suffix_spinner) ) suffixAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) suffixSpinner.adapter = suffixAdapter button.setOnClickListener { textfield.text = "" textfield.label = label.text.toString() textfield.helper = helper.text.toString() textfield.placeholder = placeholder.text.toString() textfield.counter = counter.text.toString().toIntOrNull() ?: 0 textfield.state = AndesTextfieldState.valueOf(stateSpinner.selectedItem.toString().toUpperCase()) if (preffixSpinner.selectedItem.toString().toUpperCase() == NONE) { textfield.leftContent = null } else { textfield.leftContent = AndesTextfieldLeftContent.fromString(preffixSpinner.selectedItem.toString()) } if (suffixSpinner.selectedItem.toString().toUpperCase() == NONE) { textfield.rightContent = null } else { textfield.rightContent = AndesTextfieldRightContent.fromString( suffixSpinner.selectedItem.toString() ) if (textfield.rightContent == AndesTextfieldRightContent.ACTION) { textfield.setAction( "Button", View.OnClickListener { Toast.makeText(context, "Right action pressed", Toast.LENGTH_LONG).show() } ) } else if (textfield.rightContent == AndesTextfieldRightContent.CHECKBOX) { textfield.setCheckbox( "Checkbox", View.OnClickListener { v -> val checkbox = v as AndesCheckbox Toast.makeText(context, "Status: ${checkbox.status}", Toast.LENGTH_SHORT).show() } ) } else if (textfield.rightContent == AndesTextfieldRightContent.INDETERMINATE) { textfield.setIndeterminate() } } mask.text.takeIf { !it.isNullOrEmpty() }?.apply { textfield.setTextFieldMask(it.toString()) } if (!mask.text.isNullOrEmpty()) { textfield.setTextFieldMask(mask.text.toString()) } val selectedInputType = getInputTypesArray().single { it.name == inputTypeSpinner.selectedItem.toString() }.value textfield.inputType = selectedInputType if (checkBoxHideIcon.isChecked) { textfield.setRightIcon("andes_ui_helper_16", hideWhenType = true) } } clearButton.setOnClickListener { // reset UI label.text = null placeholder.placeholder = context.resources.getString(R.string.andes_textfield_placeholder_text) placeholder.text = null helper.text = null counter.setText(COUNTER_DEFAULT_TEXT) mask.text = "" stateSpinner.setSelection(0) inputTypeSpinner.setSelection(0) preffixSpinner.setSelection(0) suffixSpinner.setSelection(0) // reset AndesTextfield's properties. textfield.text = "" textfield.label = null textfield.placeholder = null textfield.helper = null textfield.counter = COUNTER_DEFAULT textfield.state = AndesTextfieldState.IDLE textfield.inputType = InputType.TYPE_CLASS_DATETIME textfield.leftContent = null textfield.rightContent = null checkBoxHideIcon.isChecked = false textfield.clearMask() } return layoutTextfield } fun inflateAndesTextfieldArea(context: Context): View { val layoutTextfieldArea = LayoutInflater .from(context) .inflate(R.layout.andesui_dynamic_textarea, null, false) val textarea = layoutTextfieldArea.findViewById<AndesTextarea>(R.id.andesui_tag) val button = layoutTextfieldArea.findViewById<AndesButton>(R.id.change_button) val clearButton = layoutTextfieldArea.findViewById<AndesButton>(R.id.clear_button) val label = layoutTextfieldArea.findViewById<AndesTextfield>(R.id.label_text) val helper = layoutTextfieldArea.findViewById<AndesTextfield>(R.id.helper_text) val placeholder = layoutTextfieldArea.findViewById<AndesTextfield>(R.id.placeholder_text) val counter = layoutTextfieldArea.findViewById<EditText>(R.id.counter) counter.setText(COUNTER_DEFAULT_TEXT) textarea.counter = COUNTER_DEFAULT val stateSpinner: Spinner = layoutTextfieldArea.findViewById(R.id.state_spinner) val stateAdapter = ArrayAdapter( context, android.R.layout.simple_spinner_item, context.resources.getStringArray(R.array.andes_textfield_state_2_spinner) ) stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) stateSpinner.adapter = stateAdapter button.setOnClickListener { textarea.text = "" textarea.label = label.text.toString() textarea.helper = helper.text.toString() textarea.placeholder = placeholder.text.toString() textarea.counter = counter.text.toString().toIntOrNull() ?: 0 textarea.state = AndesTextfieldState.valueOf(stateSpinner.selectedItem.toString().toUpperCase()) } clearButton.setOnClickListener { // reset UI label.text = null placeholder.placeholder = context.resources.getString(R.string.andes_textfield_placeholder_text) placeholder.text = null helper.text = null counter.setText(COUNTER_DEFAULT_TEXT) stateSpinner.setSelection(0) // reset AndesTextfield's properties. textarea.text = "" textarea.label = null textarea.placeholder = null textarea.helper = null textarea.counter = COUNTER_DEFAULT textarea.state = AndesTextfieldState.IDLE } return layoutTextfieldArea } fun inflateAndesTextfieldCode(context: Context): View { val layoutTextfieldCode = LayoutInflater.from(context).inflate( R.layout.andesui_dynamic_textcode, null, false ) as ScrollView val textfieldCode = layoutTextfieldCode.findViewById<AndesTextfieldCode>(R.id.andesui_textfield_code) val updateButton = layoutTextfieldCode.findViewById<AndesButton>(R.id.change_button) val clearButton = layoutTextfieldCode.findViewById<AndesButton>(R.id.clear_button) val stateSpinner = layoutTextfieldCode.findViewById<Spinner>(R.id.state_spinner) val styleSpinner = layoutTextfieldCode.findViewById<Spinner>(R.id.style_spinner) val text = layoutTextfieldCode.findViewById<AndesTextfield>(R.id.text) val label = layoutTextfieldCode.findViewById<AndesTextfield>(R.id.label_text) val helper = layoutTextfieldCode.findViewById<AndesTextfield>(R.id.helper_text) configureStateAdapter(stateSpinner) configureStyleAdapter(styleSpinner) addAndesTextfieldCodeListener(textfieldCode) updateButton.setOnClickListener { val currentState = textfieldCode.state val newState = AndesTextfieldCodeState.valueOf(stateSpinner.selectedItem.toString().toUpperCase(Locale.getDefault())) if (currentState != newState) { textfieldCode.state = newState } val currentStyle = textfieldCode.style val newStyle = AndesTextfieldCodeStyle.valueOf(styleSpinner.selectedItem.toString().toUpperCase(Locale.getDefault())) if (currentStyle != newStyle) { textfieldCode.style = newStyle } textfieldCode.text = text.text textfieldCode.label = label.text textfieldCode.helper = helper.text } clearButton.setOnClickListener { // reset UI text.text = null label.text = null helper.text = null stateSpinner.setSelection(0) styleSpinner.setSelection(0) // reset AndesTextfieldCode's properties. textfieldCode.text = "" textfieldCode.label = null textfieldCode.helper = null textfieldCode.state = AndesTextfieldCodeState.IDLE textfieldCode.style = AndesTextfieldCodeStyle.THREESOME } return layoutTextfieldCode } fun inflateStaticTextfieldLayout(context: Context): View { val layoutTextfield = LayoutInflater.from(context).inflate( R.layout.andesui_static_textfield, null, false ) as ScrollView layoutTextfield.left // Set action clear val textfield1 = layoutTextfield.findViewById<AndesTextfield>(R.id.andesTextfield1) textfield1.text = context.resources.getString(R.string.andes_textfield_placeholder) textfield1.textWatcher = object : TextWatcher { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { Toast.makeText(context, "Text changed: $s", Toast.LENGTH_SHORT).show() } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { // no-op } override fun afterTextChanged(s: Editable) { // no-op } } // Set text val textfield2 = layoutTextfield.findViewById<AndesTextfield>(R.id.andesTextfield2) textfield2.text = context.resources.getString(R.string.andes_textfield_placeholder) // Set action val textfield3 = layoutTextfield.findViewById<AndesTextfield>(R.id.andesTextfield3) textfield3.setAction( "Button", View.OnClickListener { Toast.makeText(context, "Action pressed", Toast.LENGTH_LONG).show() } ) // Set text val textfield4 = layoutTextfield.findViewById<AndesTextfield>(R.id.andesTextfield4) textfield4.text = context.resources.getString(R.string.andes_textfield_placeholder) // Set left icon val textViewLeftIcon = layoutTextfield.findViewById<AndesTextfield>(R.id.textViewLeftIcon) textViewLeftIcon.setLeftIcon("andes_navegacion_buscar_24") ContextCompat.getDrawable(context, com.mercadolibre.android.andesui.R.drawable.andes_navegacion_ajustes) layoutTextfield.findViewById<AndesButton>(R.id.andesui_demoapp_andes_specs_button).setOnClickListener { launchSpecs(context, AndesSpecs.TEXTFIELD) } return layoutTextfield } private fun configureStateAdapter(stateSpinner: Spinner) { val stateAdapter = ArrayAdapter( stateSpinner.context, android.R.layout.simple_spinner_item, stateSpinner.resources.getStringArray(R.array.andes_textfield_code_state_spinner) ) stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) stateSpinner.adapter = stateAdapter } private fun configureStyleAdapter(styleSpinner: Spinner) { val styleAdapter = ArrayAdapter( styleSpinner.context, android.R.layout.simple_spinner_item, styleSpinner.resources.getStringArray(R.array.andes_textfield_code_style_spinner) ) styleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) styleSpinner.adapter = styleAdapter } private fun addAndesTextfieldCodeListener(textfieldCode: AndesTextfieldCode) { textfieldCode.setOnTextChangeListener(object : AndesTextfieldCode.OnTextChangeListener { override fun onChange(text: String) { Log.i("ANDES", "TEXT CHANGE: $text") } }) textfieldCode.setOnCompleteListener(object : AndesTextfieldCode.OnCompletionListener { override fun onComplete(isFull: Boolean) { if (isFull) { Log.i("ANDES", "TEXT COMPLETE: ${textfieldCode.text}") } } }) } @Suppress("LongMethod") private fun getInputTypesArray(): ArrayList<InputTypeItem> { val inputTypes = ArrayList<InputTypeItem>() inputTypes.add( InputTypeItem("date", InputType.TYPE_CLASS_DATETIME or InputType.TYPE_DATETIME_VARIATION_DATE) ) inputTypes.add( InputTypeItem("datetime", InputType.TYPE_CLASS_DATETIME or InputType.TYPE_DATETIME_VARIATION_NORMAL) ) inputTypes.add(InputTypeItem("none", InputType.TYPE_NULL)) inputTypes.add( InputTypeItem("number", InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_NORMAL) ) inputTypes.add( InputTypeItem("numberDecimal", InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL) ) inputTypes.add( InputTypeItem("numberPassword", InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD) ) inputTypes.add( InputTypeItem("numberSigned", InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_SIGNED) ) inputTypes.add(InputTypeItem("phone", InputType.TYPE_CLASS_PHONE)) inputTypes.add(InputTypeItem("text", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL)) inputTypes.add(InputTypeItem("textAutoComplete", InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE)) inputTypes.add(InputTypeItem("textAutoCorrect", InputType.TYPE_TEXT_FLAG_AUTO_CORRECT)) inputTypes.add(InputTypeItem("textCapCharacters", InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS)) inputTypes.add(InputTypeItem("textCapSentences", InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)) inputTypes.add(InputTypeItem("textCapWords", InputType.TYPE_TEXT_FLAG_CAP_WORDS)) inputTypes.add( InputTypeItem( "textEmailAddress", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ) ) inputTypes.add( InputTypeItem( "textEmailSubject", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT ) ) inputTypes.add(InputTypeItem("textFilter", InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE)) inputTypes.add( InputTypeItem( "textLongMessage", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE ) ) inputTypes.add(InputTypeItem("textMultiLine", InputType.TYPE_TEXT_FLAG_MULTI_LINE)) inputTypes.add(InputTypeItem("textNoSuggestions", InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)) inputTypes.add( InputTypeItem("textPassword", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD) ) inputTypes.add( InputTypeItem("textPersonName", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PERSON_NAME) ) inputTypes.add( InputTypeItem("textPhonetic", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PHONETIC) ) inputTypes.add( InputTypeItem( "textPostalAddress", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS ) ) inputTypes.add( InputTypeItem( "textShortMessage", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE ) ) inputTypes.add(InputTypeItem("textUri", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)) inputTypes.add( InputTypeItem( "textVisiblePassword", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ) ) inputTypes.add( InputTypeItem( "textWebEditText", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT ) ) inputTypes.add( InputTypeItem( "textWebEmailAddress", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ) ) inputTypes.add( InputTypeItem( "textWebPassword", InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD ) ) inputTypes.add( InputTypeItem("time", InputType.TYPE_CLASS_DATETIME or InputType.TYPE_DATETIME_VARIATION_TIME) ) return inputTypes } internal class InputTypeItem(val name: String, val value: Int) { override fun toString(): String { return this.name } } private const val NONE = "NONE" private const val COUNTER_DEFAULT_TEXT = "50" private const val COUNTER_DEFAULT = 50 }
1
null
3
1
bc12913d8a91c4a71faed6ba7e5d6fdfa16de123
22,018
fury_andesui-android
MIT License
app/src/main/java/com/example/testandroidpro/view/SignupScreen.kt
Android-Project-Group-6
772,969,042
false
{"Kotlin": 135436}
package com.example.testandroidpro.view import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Phone import androidx.compose.material.icons.filled.Place import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.testandroidpro.R import com.example.testandroidpro.data.CallBackUserSignup import com.example.testandroidpro.data.DialogString import com.example.testandroidpro.data.Myuser import com.example.testandroidpro.viewmodel.AdViewModel @Composable fun SignupScreen(navController: NavController, adViewModel: AdViewModel) { val context = LocalContext.current var email by remember { mutableStateOf("") } var userInfo by remember { mutableStateOf(Myuser("", "", "")) } var showKey by remember { mutableStateOf(false) } var pw1 by remember { mutableStateOf("") } var pw2 by remember { mutableStateOf("") } val dialogString = remember { mutableStateOf( DialogString( width = 200.dp, height = 150.dp, title = "Dialog Title", message = "Dialog Message", button = "OK", show = mutableStateOf(false), callback = null ) ) } DialogScreenAsDialog(dialogString.value) Scaffold ( topBar = { TopBar(navController,adViewModel,context.getString(R.string.signupPage)) }, content = { it -> Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) .padding(it) ) { Text( text = stringResource(R.string.please_signup), fontSize = 24.sp, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .padding(top = 16.dp, bottom = 16.dp) ) Card( shape = RoundedCornerShape(4.dp), border = BorderStroke(1.dp, Color.Black), modifier = Modifier.padding(16.dp) ) { Text( text = stringResource(R.string.required_items), fontSize = 12.sp, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Start, modifier = Modifier .fillMaxWidth() .padding(start = 16.dp, top = 16.dp) ) OutlinedTextField( value = email, onValueChange = { email = it adViewModel.userState = "" }, leadingIcon = { Icon( imageVector = Icons.Default.Email, contentDescription = stringResource(R.string.email_icon) ) }, trailingIcon = { Icon( imageVector = Icons.Default.Person, contentDescription = stringResource(R.string.person_icon) ) }, label = { Text(text = stringResource(R.string.email)) }, placeholder = { Text(text = stringResource(R.string.enter_your_email)) }, modifier = Modifier .fillMaxWidth() .padding(top = 8.dp, bottom = 8.dp, start = 16.dp, end = 16.dp), keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Email, capitalization = KeyboardCapitalization.None ), singleLine = true ) OutlinedTextField( value = pw1, onValueChange = { pw1 = it }, label = { Text(text = stringResource(R.string.password)) }, placeholder = { Text(text = stringResource(R.string.enter_your_password)) }, leadingIcon = { Icon( imageVector = Icons.Default.Lock, contentDescription = stringResource(R.string.lock_icon) ) }, trailingIcon = { IconButton( onClick = { showKey = !showKey } ) { Icon( imageVector = if (showKey) Icons.Default.Visibility else Icons.Default.VisibilityOff, contentDescription = if (showKey) stringResource(R.string.show_password) else stringResource(R.string.hide_password) ) } }, visualTransformation = if (showKey) VisualTransformation.None else PasswordVisualTransformation(), modifier = Modifier .fillMaxWidth() .padding(top = 6.dp, bottom = 6.dp, start = 16.dp, end = 16.dp), keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Password, imeAction = ImeAction.Done ), singleLine = true ) OutlinedTextField( value = pw2, onValueChange = { pw2 = it }, label = { Text(text = stringResource(R.string.password)) }, placeholder = { Text(text = stringResource(R.string.enter_your_password)) }, leadingIcon = { Icon( imageVector = Icons.Default.Lock, contentDescription = stringResource(R.string.lock_icon) ) }, trailingIcon = { IconButton( onClick = { showKey = !showKey } ) { Icon( imageVector = if (showKey) Icons.Default.Visibility else Icons.Default.VisibilityOff, contentDescription = if (showKey) stringResource(R.string.show_password) else stringResource(R.string.hide_password) ) } }, visualTransformation = if (showKey) VisualTransformation.None else PasswordVisualTransformation(), modifier = Modifier .fillMaxWidth() .padding(top = 6.dp, bottom = 16.dp, start = 16.dp, end = 16.dp), keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Password, imeAction = ImeAction.Done ), singleLine = true ) } Card( shape = RoundedCornerShape(4.dp), border = BorderStroke(1.dp, Color.Black), modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 16.dp) ) { Text( text = stringResource(R.string.optional_items), fontSize = 12.sp, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Start, modifier = Modifier .fillMaxWidth() .padding(start = 16.dp, top = 16.dp) ) OutlinedTextField( value = userInfo.name, onValueChange = { newValue -> userInfo = userInfo.copy(name = newValue) }, leadingIcon = { Icon( imageVector = Icons.Default.Person, contentDescription = stringResource(R.string.email_icon) ) }, label = { Text(stringResource(R.string.userName)) }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), modifier = Modifier .fillMaxWidth() .padding(top = 6.dp, bottom = 6.dp, start = 16.dp, end = 16.dp) ) OutlinedTextField( value = userInfo.phonenum, onValueChange = { newValue -> userInfo = userInfo.copy(phonenum = newValue) }, leadingIcon = { Icon( imageVector = Icons.Default.Phone, contentDescription = stringResource(R.string.email_icon) ) }, label = { Text(stringResource(R.string.user_phone_number)) }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), modifier = Modifier .fillMaxWidth() .padding(top = 6.dp, bottom = 6.dp, start = 16.dp, end = 16.dp) ) OutlinedTextField( value = userInfo.address, onValueChange = { newValue -> userInfo = userInfo.copy(address = newValue) }, label = { Text(stringResource(R.string.user_address)) }, leadingIcon = { Icon( imageVector = Icons.Default.Place, contentDescription = stringResource(R.string.email_icon) ) }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), modifier = Modifier .fillMaxWidth() .padding(top = 6.dp, bottom = 16.dp, start = 16.dp, end = 16.dp) ) } Button( modifier = Modifier .fillMaxWidth() .height(64.dp) .padding(8.dp), onClick = { dialogString.value.width = 400.dp dialogString.value.height = 200.dp dialogString.value.title = context.getString(R.string.button_signup) dialogString.value.button = context.getString(R.string.dialogOk) adViewModel.userSignup( email, pw1, pw2, userInfo, CallBackUserSignup( onSuccess = { dialogString.value.message = context.getString(R.string.dialogSignupSuccessfully) dialogString.value.callback = { navController.popBackStack(context.getString(R.string.signupPage), inclusive = true) navController.popBackStack(context.getString(R.string.loginPage), inclusive = true) navController.navigate(context.getString(R.string.homePage)) } dialogString.value.show.value = true }, onSystemError = { dialogString.value.message = it dialogString.value.callback = {} dialogString.value.show.value = true }, onEmailPwEmpty = { dialogString.value.message = context.getString(R.string.dialogEmailPasswordEmpty) dialogString.value.callback = {} dialogString.value.show.value = true }, onPwMismatch = { dialogString.value.message = context.getString(R.string.dialogPasswordMismatch) dialogString.value.callback = {} dialogString.value.show.value = true } ) ) }, ) { Text(text = stringResource(R.string.button_reg)) } Spacer(modifier = Modifier.height(16.dp)) } } ) }
16
Kotlin
0
0
d8d8c7bdce721f544420df9e0ca1702ce88a5736
16,091
AdFusion
MIT License
data/src/main/java/com/gontharuk/dazn/data/events/entity/EventModel.kt
pavel-gontharuk
701,381,494
false
{"Kotlin": 41422}
package com.gontharuk.dazn.data.events.entity import android.net.Uri import java.time.LocalDateTime data class EventModel( val id: Int, val title: String, val subtitle: String, val date: LocalDateTime, val imageUrl: Uri, val videoUrl: Uri, )
2
Kotlin
0
0
5a7a0f3decb13e1b56c146bfaf26562a0b655c36
267
dazn-assignment
MIT License
src/docs/cookbook/client_as_a_function/example.kt
ziacto
93,989,106
true
{"Kotlin": 344124, "Shell": 3854, "CSS": 499, "HTML": 312, "JavaScript": 48}
package cookbook.client_as_a_function import org.http4k.client.ApacheClient import org.http4k.core.HttpHandler import org.http4k.core.Method import org.http4k.core.Request /** * This example demonstrates a client module (in this case the Apache Client). A client is just another * HttpHandler. */ fun main(args: Array<String>) { val request = Request(Method.GET, "http://pokeapi.co/api/v2/pokemon/") val client: HttpHandler = ApacheClient() println(client(request)) }
0
Kotlin
0
0
3aa82a18ecb7f4d757a5a3321eb187fa61a48e69
488
http4k
Apache License 2.0
core/src/jvmMain/kotlin/de/haukesomm/sokoban/core/GameStateChangeHandler.kt
haukesomm
245,519,631
false
null
package de.haukesomm.sokoban.core import de.haukesomm.sokoban.core.coroutines.SokobanMainScope import de.haukesomm.sokoban.core.state.GameState import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import java.util.function.Consumer /** * This object provides a static method to register a [Consumer] at a * [GameStateService] to be notified about changes in the [GameStateService.state] flow. * * It is intended to be used in legacy code that is written in Java and does not support the use * of flows. */ object GameStateChangeHandler { @JvmStatic fun handle(gameStateService: GameStateService, callback: Consumer<GameState>) { gameStateService.state .onEach(callback::accept) .launchIn(SokobanMainScope) } }
0
Kotlin
0
1
9752d5a00bd4c07e8c9006387885fa3828d88ec0
787
Sokoban
MIT License
lib-swipetoactionlayout/src/main/java/github/com/st235/swipetoactionlayout/utils/ViewExts.kt
st235
196,595,936
false
null
package github.com.st235.lib_swipetoactionlayout.utils import android.content.Context import android.util.LayoutDirection import android.view.View import androidx.core.text.TextUtilsCompat import java.util.* internal fun View.show(isShown: Boolean = false) { visibility = if (isShown) { View.VISIBLE } else { View.GONE } } internal fun isLtr(): Boolean { return TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == LayoutDirection.LTR }
3
null
6
99
b0f58074648c130cad88a8fdfcb1f5a0dac5135a
488
SwipeToActionLayout
MIT License
src/main/kotlin/currencyconverter/TransferRate.kt
krikotnenko
689,073,512
false
{"Kotlin": 169460}
package currencyconverter import accounts.entities.Currency import kotlinx.serialization.Serializable @Serializable data class TransferRate( val sourceCurrency: Currency, val targetCurrency: Currency, ) @Serializable data class TransferRateResponse( val exchangeRate: Double, val feeRate: Double, )
0
Kotlin
0
0
332b375155a77cd07b97cd6d6199d6cdad27d6a5
317
digital-adapter
MIT License
app/src/main/java/com/android/skip/handler/IdNodeHandler.kt
GuoXiCheng
506,451,823
false
{"Kotlin": 40436}
package com.android.skip.handler import android.graphics.Rect import android.view.accessibility.AccessibilityNodeInfo import com.android.skip.manager.SkipConfigManager class IdNodeHandler: AbstractHandler() { override fun handle(node: AccessibilityNodeInfo): List<Rect> { val skipId = SkipConfigManager.getSkipId(node.packageName.toString()) ?: return super.handle(node) val nodes = findAccessibilityNodeInfosContainsViewId(node, skipId) val listOfRect = nodes.map { val rect = Rect() it.getBoundsInScreen(rect) rect } nodes.forEach { it.recycle() } return listOfRect.ifEmpty { super.handle(node) } } private fun findAccessibilityNodeInfosContainsViewId(node: AccessibilityNodeInfo, viewId: String): MutableList<AccessibilityNodeInfo> { val resultList = mutableListOf<AccessibilityNodeInfo>() dfs(node, viewId, resultList) return resultList } private fun dfs(node: AccessibilityNodeInfo, viewId: String, resultList: MutableList<AccessibilityNodeInfo>) { if (node.viewIdResourceName?.contains(viewId) == true) { resultList.add(AccessibilityNodeInfo.obtain(node)) } for (i in 0 until node.childCount) { dfs(node.getChild(i), viewId, resultList) } } }
16
Kotlin
67
999
f3f64c04866de23e2ee4131d6491662a47fc6aaf
1,365
SKIP
MIT License
rpm/src/androidMain/kotlin/dev/garage/rpm/navigation/FragmentNavigationMessageDispatcher.kt
vchernyshov
249,563,649
false
null
package dev.garage.rpm.navigation import androidx.fragment.app.Fragment class FragmentNavigationMessageDispatcher( fragment: Fragment ) : NavigationMessageDispatcher(fragment) { override fun getParent(node: Any?): Any? { return if (node is Fragment) { node.parentFragment ?: node.activity } else { null } } }
7
Kotlin
2
12
902dcd41c1aae758200f427b2a95968a53f33bad
371
reaktive-pm
MIT License
app/src/main/java/eu/vmpay/owlquiz/utils/BindingUtilities.kt
vmpay
126,885,309
false
null
package eu.vmpay.owlquiz.utils import android.widget.TextView import androidx.databinding.BindingAdapter import java.util.* @BindingAdapter("app:progressTime") fun setProgressTime(textView: TextView, millis: Int) { textView.text = java.lang.String.format(Locale.US, "%.1f", millis.toDouble() / 1000) }
0
Kotlin
0
1
d23df057e8db71b951377e844195edcd7d827a1f
307
owlQuiz
Apache License 2.0
engelsystem-base/src/main/kotlin/info/metadude/kotlin/library/engelsystem/adapters/ZonedDateTimeAdapter.kt
johnjohndoe
201,794,650
false
{"Kotlin": 21117}
package info.metadude.kotlin.library.engelsystem.adapters import com.squareup.moshi.FromJson import org.threeten.bp.DateTimeException import org.threeten.bp.ZonedDateTime class ZonedDateTimeAdapter { @FromJson fun fromJson(jsonValue: String?) = jsonValue?.let { try { ZonedDateTime.parse(jsonValue) } catch (e: DateTimeException) { println(e.message) null } } }
0
Kotlin
2
6
41de774756e2556a99a635cd7e883330e571baf8
438
engelsystem
Apache License 2.0
app/src/main/java/com/lubulwa/kulio/ui/main/SearchFlightsActivity.kt
richmahnn
166,007,530
false
null
package com.lubulwa.kulio.ui.main import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.widget.LinearLayoutManager import android.view.MenuItem import android.view.View import android.widget.Toast import com.lubulwa.kulio.R import com.lubulwa.kulio.base.BaseActivity import com.lubulwa.kulio.helpers.local.Constants import com.lubulwa.kulio.helpers.local.KulioUtlis import com.lubulwa.kulio.model.Airport import com.lubulwa.kulio.model.FlightsResponse import com.lubulwa.kulio.model.Schedule import com.lubulwa.kulio.presenter.SearchFlightsPresenter import com.lubulwa.kulio.ui.component.FlightSchedulesAdapter import com.lubulwa.kulio.ui.component.InfiniteScrollListener import com.lubulwa.kulio.ui.interfaces.HomeContract import kotlinx.android.synthetic.main.activity_search_flights.* import java.util.ArrayList class SearchFlightsActivity : BaseActivity(), HomeContract.View, FlightSchedulesAdapter.ItemListener { private lateinit var searchFlightsPresenter: SearchFlightsPresenter private lateinit var flightSchedulesAdapter: FlightSchedulesAdapter private var schedulesArrayList: ArrayList<Schedule> = ArrayList() private lateinit var passedOriginAirport: Airport private lateinit var passedDestinationAirport: Airport private var passedDepartDate: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_search_flights) initToolbar() initStuff() } private fun initToolbar() { setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) } private fun initStuff() { searchFlightsPresenter = SearchFlightsPresenter(this) //get intent data passedOriginAirport = intent.getSerializableExtra(Constants.ORIGIN_AIRPORT_INTENT_DATA) as Airport passedDestinationAirport = intent.getSerializableExtra(Constants.DEST_AIRPORT_INTENT_DATA) as Airport passedDepartDate = intent.getStringExtra(Constants.DEPART_DATE_INTENT_DATA) tv_origin_airport.text = passedOriginAirport.airportCode tv_destination_airport.text = passedDestinationAirport.airportCode val layoutManager = LinearLayoutManager(this); rv_schedules.layoutManager = layoutManager flightSchedulesAdapter = FlightSchedulesAdapter(this, schedulesArrayList, this) rv_schedules.adapter = flightSchedulesAdapter fetchScheduledFlights() rv_schedules.addOnScrollListener(object : InfiniteScrollListener(){ override fun loadMore() { Toast.makeText(this@SearchFlightsActivity, getString(R.string.list_load_more_msg), Toast.LENGTH_SHORT).show() fetchScheduledFlights() } }) } fun fetchScheduledFlights() { val offset = rv_schedules.adapter!!.itemCount searchFlightsPresenter.findScheduledFlights( passedOriginAirport.airportCode, passedDestinationAirport.airportCode, ((if (passedDepartDate == null) KulioUtlis.getTomorrowsDate() else passedDepartDate)!!), offset, 20 ) } override fun findScheduledFlightsStarted() { pb_loading_schedules.visibility = View.VISIBLE } override fun findScheduledFlightsSuccess(flightsResponse: FlightsResponse?) { pb_loading_schedules.visibility = View.GONE schedulesArrayList.addAll(flightsResponse!!.scheduleResource.schedule) flightSchedulesAdapter.notifyDataSetChanged() } override fun findScheduledFlightsFailed(errorMessage: String, errorCode: Int) { pb_loading_schedules.visibility = View.GONE Snackbar.make(coordinatorLayout, errorMessage, Snackbar.LENGTH_LONG).show() } override fun onScheduleItemClicked(scheduleItem: Schedule) { val intent = Intent(this, MapActivity::class.java) intent.putExtra(Constants.ORIGIN_AIRPORT_INTENT_DATA, passedOriginAirport) intent.putExtra(Constants.DEST_AIRPORT_INTENT_DATA, passedDestinationAirport) startActivity(intent) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> finish() else -> return super.onOptionsItemSelected(item) } return false } }
0
Kotlin
0
1
0029478dfa3c52e7e2ba3aaf185fd27aa40acc7f
4,445
Kulio
MIT License
app/src/androidTest/java/dev/shorthouse/coinwatch/ui/screen/SettingsScreenTest.kt
shorthouse
655,260,745
false
null
package dev.shorthouse.coinwatch.ui.screen import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.assertHasClickAction import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotSelected import androidx.compose.ui.test.assertIsSelected import androidx.compose.ui.test.hasText import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import com.google.common.truth.Truth.assertThat import dev.shorthouse.coinwatch.BuildConfig import dev.shorthouse.coinwatch.data.userPreferences.StartScreen import dev.shorthouse.coinwatch.ui.screen.settings.SettingsScreen import dev.shorthouse.coinwatch.ui.screen.settings.SettingsUiState import dev.shorthouse.coinwatch.ui.theme.AppTheme import org.junit.Rule import org.junit.Test class SettingsScreenTest { @get:Rule val composeTestRule = createComposeRule() @Test fun when_uiStateLoading_should_showLoadingIndicator() { val uiState = SettingsUiState( isLoading = true ) composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = {}, onUpdateStartScreen = {} ) } } composeTestRule.apply { onNode(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo)) .assertIsDisplayed() } } @Test fun when_uiStateError_should_displayErrorMessage() { val errorMessage = "Error loading settings screen" val uiState = SettingsUiState( errorMessage = errorMessage ) composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = {}, onUpdateStartScreen = {} ) } } composeTestRule.apply { onNodeWithText(errorMessage).assertIsDisplayed() } } @Test fun when_uiStateSuccess_should_displayExpectedContent() { val uiState = SettingsUiState() composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = {}, onUpdateStartScreen = {} ) } } composeTestRule.apply { onNodeWithContentDescription("Back").assertIsDisplayed() onNodeWithText("Settings").assertIsDisplayed() onNodeWithText("Preferences").assertIsDisplayed() onNodeWithText("Start screen").assertIsDisplayed() onNodeWithText("Market").assertIsDisplayed() onNodeWithText("About").assertIsDisplayed() onNodeWithText("CoinWatch version").assertIsDisplayed() onNodeWithText(BuildConfig.VERSION_NAME).assertIsDisplayed() onNodeWithText("Source code").assertIsDisplayed() onNodeWithText("Available on GitHub").assertIsDisplayed() onNodeWithText("Privacy policy").assertIsDisplayed() onNodeWithText("Feedback").assertIsDisplayed() onNodeWithText("Rate CoinWatch").assertIsDisplayed() onNodeWithText("Leave a Play Store review").assertIsDisplayed() onNodeWithText("Made with ❤\uFE0F\uFE0F by Short Labs").assertIsDisplayed() } } @Test fun when_backButtonClicked_should_callOnNavigateUp() { val uiState = SettingsUiState() var onNavigateUpCalled = false composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = { onNavigateUpCalled = true }, onUpdateStartScreen = {} ) } } composeTestRule.apply { onNodeWithContentDescription("Back").performClick() } assertThat(onNavigateUpCalled).isTrue() } @Test fun when_startScreenClicked_should_openStartScreenDialog() { val uiState = SettingsUiState() composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = {}, onUpdateStartScreen = {} ) } } val radioButtonMatcher = SemanticsMatcher.expectValue( SemanticsProperties.Role, Role.RadioButton ) composeTestRule.apply { onNodeWithText("Start screen").performClick() onNode(hasText("Market").and(radioButtonMatcher)) .assertIsDisplayed().assertHasClickAction() onNode(hasText("Favourites").and(radioButtonMatcher)) .assertIsDisplayed().assertHasClickAction() onNode(hasText("Search").and(radioButtonMatcher)) .assertIsDisplayed().assertHasClickAction() } } @Test fun when_startScreenDialogOptionClicked_should_callOnUpdateStartScreen() { val uiState = SettingsUiState() var onUpdateStartScreenCalled = false composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = {}, onUpdateStartScreen = { startScreen -> onUpdateStartScreenCalled = startScreen == StartScreen.Search } ) } } composeTestRule.apply { onNodeWithText("Start screen").performClick() onNodeWithText("Search").performClick() } assertThat(onUpdateStartScreenCalled).isTrue() } @Test fun when_startScreenIsMarket_should_haveMarketOptionSelected() { val uiState = SettingsUiState( startScreen = StartScreen.Market ) composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = {}, onUpdateStartScreen = {} ) } } val radioButtonMatcher = SemanticsMatcher.expectValue( SemanticsProperties.Role, Role.RadioButton ) composeTestRule.apply { onNodeWithText("Market").assertIsDisplayed() onNodeWithText("Start screen").performClick() onNode(hasText("Market").and(radioButtonMatcher)) .assertIsDisplayed().assertIsSelected() onNode(hasText("Favourites").and(radioButtonMatcher)) .assertIsDisplayed().assertIsNotSelected() onNode(hasText("Search").and(radioButtonMatcher)) .assertIsDisplayed().assertIsNotSelected() } } @Test fun when_startScreenIsFavourites_should_haveFavouritesOptionSelected() { val uiState = SettingsUiState( startScreen = StartScreen.Favourites ) composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = {}, onUpdateStartScreen = {} ) } } val radioButtonMatcher = SemanticsMatcher.expectValue( SemanticsProperties.Role, Role.RadioButton ) composeTestRule.apply { onNodeWithText("Favourites").assertIsDisplayed() onNodeWithText("Start screen").performClick() onNode(hasText("Market").and(radioButtonMatcher)) .assertIsDisplayed().assertIsNotSelected() onNode(hasText("Favourites").and(radioButtonMatcher)) .assertIsDisplayed().assertIsSelected() onNode(hasText("Search").and(radioButtonMatcher)) .assertIsDisplayed().assertIsNotSelected() } } @Test fun when_startScreenIsSearch_should_haveSearchOptionSelected() { val uiState = SettingsUiState( startScreen = StartScreen.Search ) composeTestRule.setContent { AppTheme { SettingsScreen( uiState = uiState, onNavigateUp = {}, onUpdateStartScreen = {} ) } } val radioButtonMatcher = SemanticsMatcher.expectValue( SemanticsProperties.Role, Role.RadioButton ) composeTestRule.apply { onNodeWithText("Search").assertIsDisplayed() onNodeWithText("Start screen").performClick() onNode(hasText("Market").and(radioButtonMatcher)) .assertIsDisplayed().assertIsNotSelected() onNode(hasText("Favourites").and(radioButtonMatcher)) .assertIsDisplayed().assertIsNotSelected() onNode(hasText("Search").and(radioButtonMatcher)) .assertIsDisplayed().assertIsSelected() } } }
2
null
2
33
f911aec8a9de776eedf573d4353cc83312e00990
9,381
CoinWatch
Apache License 2.0
app/src/main/java/com/eneskayiklik/word_diary/feature/settings/presentation/about/component/AboutDropdownMenu.kt
Enes-Kayiklik
651,794,521
false
null
package com.eneskayiklik.word_diary.feature.settings.presentation.about.component import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Description import androidx.compose.material.icons.outlined.LocalLibrary import androidx.compose.material.icons.outlined.Policy import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import com.eneskayiklik.word_diary.R import com.eneskayiklik.word_diary.feature.destinations.LicensesScreenDestination import com.eneskayiklik.word_diary.util.PRIVACY import com.eneskayiklik.word_diary.util.TERMS import com.eneskayiklik.word_diary.util.extensions.openLink import com.ramcosta.composedestinations.navigation.DestinationsNavigator import me.saket.cascade.CascadeDropdownMenu @OptIn(ExperimentalAnimationApi::class) @Composable fun AboutDropdownMenu( expanded: Boolean, navigator: DestinationsNavigator, modifier: Modifier = Modifier, onDismiss: () -> Unit ) { val context = LocalContext.current CascadeDropdownMenu( expanded = expanded, onDismissRequest = onDismiss, modifier = modifier, offset = DpOffset(x = 16.dp, y = 0.dp) ) { DropdownMenuItem( text = { Text(stringResource(id = R.string.destination_licenses)) }, onClick = { onDismiss() navigator.navigate(LicensesScreenDestination) }, leadingIcon = { Icon( Icons.Outlined.LocalLibrary, contentDescription = null ) } ) DropdownMenuItem( text = { Text(stringResource(id = R.string.privacy_policy)) }, onClick = { onDismiss() context.openLink(PRIVACY) }, leadingIcon = { Icon( Icons.Outlined.Policy, contentDescription = null ) } ) DropdownMenuItem( text = { Text(stringResource(id = R.string.terms_conditions)) }, onClick = { onDismiss() context.openLink(TERMS) }, leadingIcon = { Icon( Icons.Outlined.Description, contentDescription = null ) } ) } }
0
Kotlin
0
3
236d4c497d7e141f1536fb62f7458459420d1fe9
2,767
WordDiary
MIT License
app/src/main/java/com/farukaygun/yorozuyalist/data/repository/LoginRepository.kt
farukaygun
686,874,566
false
{"Kotlin": 24143}
package com.farukaygun.yorozuyalist.data.repository import com.farukaygun.yorozuyalist.data.remote.dto.AuthTokenDto interface LoginRepository { suspend fun getAuthToken( code: String, clientId: String, codeVerifier: String ): AuthTokenDto }
0
Kotlin
0
1
7b7860bbfb4e7588dc50c1cd9c54a84502a764cb
250
YorozuyaList-Compose
MIT License
tella-locking-ui/src/main/java/com/hzontal/tella_locking_ui/ui/pin/base/onSetPinClickListener.kt
Horizontal-org
193,379,924
false
{"Java": 1621257, "Kotlin": 1441445}
package com.hzontal.tella_locking_ui.ui.pin.base interface OnSetPinClickListener { fun onSuccessSetPin(pin : String?) fun onFailureSetPin(error : String) }
16
Java
17
55
5dd19f8c9a810c165d2d8ec8947cc9d5d4620bab
164
Tella-Android
Apache License 2.0
wearApp/src/main/java/com/surrus/peopleinspace/MainActivity.kt
one-aalam
414,844,054
true
{"Kotlin": 89243, "Swift": 20790, "Ruby": 2139, "HTML": 471}
package com.surrus.peopleinspace import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.wear.compose.material.MaterialTheme import com.surrus.common.repository.PeopleInSpaceRepositoryInterface import org.koin.android.ext.android.inject class MainActivity : ComponentActivity() { private val peopleInSpaceRepository: PeopleInSpaceRepositoryInterface by inject() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme { PersonList(peopleInSpaceRepository, personSelected = {}) } } } }
0
null
0
0
975a1474e63a59f6068cb624dd4f1ceaf2e09381
697
PeopleInSpace
Apache License 2.0
feature/core/src/main/java/akio/apps/myrun/feature/core/permissions/AppPermissions.kt
khoi-nguyen-2359
297,064,437
false
{"Kotlin": 818596, "Java": 37377}
package akio.apps.myrun.feature.core.permissions import android.Manifest import android.os.Build object AppPermissions { const val preciseLocationPermission: String = Manifest.permission.ACCESS_FINE_LOCATION private const val approximateLocationPermission: String = Manifest.permission.ACCESS_COARSE_LOCATION // From Android 12, location permission always include this couple: val locationPermissions = arrayOf(preciseLocationPermission, approximateLocationPermission) val takePhotoPermissions = arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA ) val pickPhotoPermissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { arrayOf(Manifest.permission.READ_MEDIA_IMAGES) } else { emptyArray() } }
0
Kotlin
3
7
c864c2972b1db8146d3c2553130bfe9e78a27c42
946
myrun
MIT License
cookbook/src/commonMain/kotlin/fun/adaptive/cookbook/auto/autoFolder_autoList/DataService.kt
spxbhuhb
788,711,010
false
{"Kotlin": 2273072, "Java": 24502, "HTML": 7707, "JavaScript": 3880, "Shell": 687}
package `fun`.adaptive.cookbook.auto.autoFolder_autoList import `fun`.adaptive.auth.context.publicAccess import `fun`.adaptive.auto.model.AutoConnectionInfo import `fun`.adaptive.backend.builtin.ServiceImpl import `fun`.adaptive.backend.builtin.worker class DataService : DataServiceApi, ServiceImpl<DataService> { val dataWorker by worker<MasterDataWorker>() override suspend fun getConnectInfo(): AutoConnectionInfo<List<MasterDataItem>> { publicAccess() return dataWorker.connectInfo() } }
33
Kotlin
0
3
98e84716b9a2e3713b70b64c36bfaeecbab397d0
525
adaptive
Apache License 2.0
link/src/main/java/com/stripe/android/link/ui/forms/Form.kt
stripe
6,926,049
false
null
package com.stripe.android.link.ui.forms import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.stripe.android.link.theme.linkColors import com.stripe.android.ui.core.FormController import com.stripe.android.ui.core.FormUI import kotlinx.coroutines.flow.Flow @Composable internal fun Form( formController: FormController, enabledFlow: Flow<Boolean> ) { FormUI( hiddenIdentifiersFlow = formController.hiddenIdentifiers, enabledFlow = enabledFlow, elementsFlow = formController.elements, lastTextFieldIdentifierFlow = formController.lastTextFieldIdentifier, loadingComposable = { Row( modifier = Modifier .height(100.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { CircularProgressIndicator( modifier = Modifier.size(24.dp), color = MaterialTheme.linkColors.buttonLabel, strokeWidth = 2.dp ) } } ) }
79
Kotlin
580
1,055
21ceca79b2403414939d561c446ef4344b5bf03f
1,612
stripe-android
MIT License
app/src/main/java/com/brandonhxrr/simpletask/SimpleTaskApp.kt
brandonhxrr
631,642,484
false
{"Kotlin": 28015}
package com.brandonhxrr.simpletask import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class SimpleTaskApp: Application() { }
0
Kotlin
0
0
f1c7a8b1926b853f7e8d6765ce199f9b6d50d4a3
164
SimpleTask
MIT License
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/spells/pieces/effects/IcyEffects.kt
fzzyhmstrs
461,338,617
false
null
package me.fzzyhmstrs.amethyst_imbuement.spells.pieces.effects import me.fzzyhmstrs.amethyst_core.augments.paired.ProcessContext import net.minecraft.entity.Entity import net.minecraft.entity.LivingEntity import net.minecraft.particle.ParticleTypes import net.minecraft.server.world.ServerWorld import net.minecraft.sound.SoundCategory import net.minecraft.sound.SoundEvents import net.minecraft.util.math.Box object IcyEffects { fun nova(entity: Entity, attackerOrOwner: Entity?, processContext: ProcessContext){ val world = entity.world val pos = entity.pos.add(0.0,entity.height/2.0,0.0) val box = Box(pos.add(2.0,2.0,2.0),pos.subtract(2.0,2.0,2.0)) val entities = world.getOtherEntities(attackerOrOwner, box) if (world is ServerWorld){ world.spawnParticles(ParticleTypes.SNOWFLAKE,pos.x,pos.y,pos.z,250,4.0,4.0,4.0,0.2) } world.playSound(null,pos.x,pos.y,pos.z, SoundEvents.ENTITY_PLAYER_HURT_FREEZE,SoundCategory.PLAYERS,1f,1f) for (target in entities){ if (target !is LivingEntity) continue if ( target.damage(entity.damageSources.freeze(),2f)){ entity.frozenTicks = 180 } } } //attacker in this case fun jab(entity: Entity, attackerOrOwner: Entity?, processContext: ProcessContext){ attackerOrOwner?.damage(entity.damageSources.freeze(),2f) attackerOrOwner?.frozenTicks = 180 entity.world.playSound(null,entity.x,entity.y,entity.z,SoundEvents.ENTITY_PLAYER_HURT_FREEZE,SoundCategory.PLAYERS,0.6f,1f) } fun stab(entity: Entity, attackerOrOwner: Entity?, processContext: ProcessContext){ attackerOrOwner?.damage(entity.damageSources.freeze(),3f) attackerOrOwner?.frozenTicks = 240 entity.world.playSound(null,entity.x,entity.y,entity.z,SoundEvents.ENTITY_PLAYER_HURT_FREEZE,SoundCategory.PLAYERS,0.6f,1f) } }
16
Kotlin
7
3
9971606dfafa9422e9558238c7783f8e27bd34a3
1,931
ai
MIT License
app/src/main/java/com/vicgcode/dialectica/database/room/AppRoomDao.kt
vicgcode
634,342,124
false
{"Kotlin": 107302}
package com.vicgcode.dialectica.database.room import androidx.room.* import com.vicgcode.dialectica.data.models.entity.DialectInterest import com.vicgcode.dialectica.data.models.entity.DialectPerson import com.vicgcode.dialectica.data.models.entity.DialectQuestion @Dao interface AppRoomDao { @Query("SELECT *from question_tables") fun getFavouriteList(): List<DialectQuestion> @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertFavourite(question: DialectQuestion) @Delete suspend fun deleteFavourite(question: DialectQuestion) @Query("SELECT *from person_tables") fun getPersonList(): List<DialectPerson> @Query("SELECT *from person_tables WHERE isOwner = :isOwner") fun getOwnerPerson(isOwner: Boolean): DialectPerson @Query("SELECT *from person_tables WHERE id = :id") fun getPersonById(id: Int): DialectPerson @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertPerson(person: DialectPerson) @Query("UPDATE person_tables SET interests=:interests WHERE id = :id") suspend fun updatePersonInterests(interests: List<String>, id: Int) @Query("UPDATE person_tables SET questions=:questions WHERE id = :id") suspend fun updatePersonQuestions(questions: List<DialectQuestion>, id: Int) @Delete suspend fun deletePerson(person: DialectPerson) @Query("SELECT *from interest_tables") fun getInterestList(): List<DialectInterest> @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertInterest(interest: DialectInterest) @Delete suspend fun deleteInterest(interest: DialectInterest) }
0
Kotlin
0
0
87e7046c67b2ddf125c88dca57b24c117bcbea91
1,640
Dialectica
Apache License 2.0
kool-editor/src/commonMain/kotlin/de/fabmax/kool/editor/overlays/SceneObjectsOverlay.kt
fabmax
81,503,047
false
null
package de.fabmax.kool.editor.overlays import de.fabmax.kool.editor.KoolEditor import de.fabmax.kool.editor.api.GameEntity import de.fabmax.kool.editor.components.* import de.fabmax.kool.math.* import de.fabmax.kool.modules.ksl.KslUnlitShader import de.fabmax.kool.modules.ksl.blocks.ColorSpaceConversion import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.CullMethod import de.fabmax.kool.scene.* import de.fabmax.kool.scene.geometry.MeshBuilder import de.fabmax.kool.util.Color import de.fabmax.kool.util.Float32Buffer import de.fabmax.kool.util.MdColor import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin class SceneObjectsOverlay : Node("Scene objects overlay") { private val dirLights = mutableListOf<DirLightComponentInstance>() private val spotLights = mutableListOf<SpotLightComponentInstance>() private val pointLights = mutableListOf<PointLightComponentInstance>() private val cameras = mutableListOf<CameraComponentInstance>() private val groups = mutableListOf<GroupNodeInstance>() private val dirLightsInstances = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT, Attribute.INSTANCE_COLOR)) private val spotLightsInstances = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT, Attribute.INSTANCE_COLOR)) private val pointLightsInstances = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT, Attribute.INSTANCE_COLOR)) private val cameraInstances = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT, Attribute.INSTANCE_COLOR)) private val groupInstances = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT, Attribute.INSTANCE_COLOR)) private val dirLightMesh = Mesh( Attribute.POSITIONS, Attribute.NORMALS, instances = dirLightsInstances, name = "Directional lights" ).apply { isCastingShadow = false rayTest = MeshRayTest.geometryTest(this) generate { uvSphere { radius = 0.15f } generateArrow() for (i in 0 until 63) { val a1 = i / 63f * 2f * PI.toFloat() val z1 = cos(a1) val y1 = sin(a1) val a2 = (i + 1) / 63f * 2f * PI.toFloat() val z2 = cos(a2) val y2 = sin(a2) val nrm = Vec3f(0f, y1, z1) line3d(Vec3f(0f, y1, z1), Vec3f(0f, y2, z2), nrm, lineW) line3d(Vec3f(0f, y1, z1), Vec3f(0f, y2, z2), Vec3f.X_AXIS, lineW) val nrm2 = nrm.rotate(90f.deg, Vec3f.X_AXIS, MutableVec3f()) if (i % 8 == 0) { line3d(Vec3f(0f, y1, z1), Vec3f(0.7f, y1, z1), nrm, lineW) line3d(Vec3f(0f, y1, z1), Vec3f(0.7f, y1, z1), nrm2, lineW) } if ((i + 4) % 8 == 0) { val r = 0.5f line3d(Vec3f(0f, y1 * r, z1 * r), Vec3f(0.7f, y1 * r, z1 * r), nrm, lineW) line3d(Vec3f(0f, y1 * r, z1 * r), Vec3f(0.7f, y1 * r, z1 * r), nrm2, lineW) } } } shader = KslUnlitShader { vertices { isInstanced = true } pipeline { cullMethod = CullMethod.NO_CULLING } color { instanceColor() } colorSpaceConversion = ColorSpaceConversion.LinearToSrgb() } } private val spotLightMesh = Mesh( Attribute.POSITIONS, Attribute.NORMALS, instances = spotLightsInstances, name = "Spot lights" ).apply { isCastingShadow = false rayTest = MeshRayTest.geometryTest(this) generate { uvSphere { radius = 0.15f } generateArrow() for (i in 0 until 63) { val a1 = i / 63f * 2f * PI.toFloat() val z1 = cos(a1) * 0.85f val y1 = sin(a1) * 0.85f val a2 = (i + 1) / 63f * 2f * PI.toFloat() val z2 = cos(a2) * 0.85f val y2 = sin(a2) * 0.85f val nrm = Vec3f(0f, y1, z1) line3d(Vec3f(1f, y1, z1), Vec3f(1f, y2, z2), nrm, lineW) line3d(Vec3f(1f, y1, z1), Vec3f(1f, y2, z2), Vec3f.X_AXIS, lineW) if (i % 16 == 0){ line3d(Vec3f.ZERO, Vec3f(1f, y1, z1), nrm, lineW) val nrm2 = nrm.rotate(90f.deg, Vec3f.X_AXIS, MutableVec3f()) line3d(Vec3f.ZERO, Vec3f(1f, y1, z1), nrm2, lineW) } } } shader = KslUnlitShader { vertices { isInstanced = true } pipeline { cullMethod = CullMethod.NO_CULLING } color { instanceColor() } colorSpaceConversion = ColorSpaceConversion.LinearToSrgb() } } private val pointLightMesh = Mesh( Attribute.POSITIONS, Attribute.NORMALS, instances = pointLightsInstances, name = "Point lights" ).apply { isCastingShadow = false rayTest = MeshRayTest.geometryTest(this) generate { uvSphere { radius = 0.15f } val ico = MeshBuilder.IcoGenerator() ico.subdivide(1) ico.verts.forEachIndexed { i, pt -> val o = if (pt.dot(Vec3f.Y_AXIS) > 0.9f) Vec3f.X_AXIS else Vec3f.Y_AXIS val n1 = pt.cross(o, MutableVec3f()) val n2 = n1.rotate(90f.deg, pt, MutableVec3f()) val l0 = if (i % 2 == 0) 0f else 0.45f val l1 = if (i % 2 == 0) 0.9f else 0.9f line3d(MutableVec3f(pt).mul(l0), MutableVec3f(pt).mul(l1), n1, 0.03f) line3d(MutableVec3f(pt).mul(l0), MutableVec3f(pt).mul(l1), n2, 0.03f) } } shader = KslUnlitShader { vertices { isInstanced = true } pipeline { cullMethod = CullMethod.NO_CULLING } color { instanceColor() } colorSpaceConversion = ColorSpaceConversion.LinearToSrgb() } } private val cameraMesh = Mesh( Attribute.POSITIONS, Attribute.NORMALS, instances = cameraInstances, name = "Cameras" ).apply { isCastingShadow = false rayTest = MeshRayTest.geometryTest(this) generate { rotate(90f.deg, Vec3f.Y_AXIS) generateArrow() cube { size.set(0.4f, 0.3f, 0.2f) } val pts = listOf( Vec3f(1f, 0.6f, 1f), Vec3f(1f, 0.6f, -1f), Vec3f(1f, -0.6f, -1f), Vec3f(1f, -0.6f, 1f), ) pts.forEachIndexed { i, pt -> line3d(Vec3f.ZERO, pt, Vec3f.Y_AXIS, lineW) line3d(Vec3f.ZERO, pt, Vec3f.Z_AXIS, lineW) val p2 = pts[(i + 1) % 4] line3d(pt, p2, Vec3f.X_AXIS, lineW) line3d(pt, p2, if (pt.y == p2.y) Vec3f.Y_AXIS else Vec3f.Z_AXIS, lineW) } } shader = KslUnlitShader { vertices { isInstanced = true } pipeline { cullMethod = CullMethod.NO_CULLING } color { instanceColor() } colorSpaceConversion = ColorSpaceConversion.LinearToSrgb() } } private val groupMesh = Mesh( Attribute.POSITIONS, Attribute.COLORS, Attribute.NORMALS, instances = groupInstances, name = "Groups" ).apply { isCastingShadow = false rayTest = MeshRayTest.geometryTest(this) generate { color = MdColor.RED toneLin 200 line3d(Vec3f.NEG_X_AXIS * 0.5f, Vec3f.X_AXIS * 0.5f, Vec3f.Y_AXIS, lineW) line3d(Vec3f.NEG_X_AXIS * 0.5f, Vec3f.X_AXIS * 0.5f, Vec3f.Z_AXIS, lineW) color = MdColor.GREEN toneLin 200 line3d(Vec3f.NEG_Y_AXIS * 0.5f, Vec3f.Y_AXIS * 0.5f, Vec3f.X_AXIS, lineW) line3d(Vec3f.NEG_Y_AXIS * 0.5f, Vec3f.Y_AXIS * 0.5f, Vec3f.Z_AXIS, lineW) color = MdColor.BLUE toneLin 200 line3d(Vec3f.NEG_Z_AXIS * 0.5f, Vec3f.Z_AXIS * 0.5f, Vec3f.Y_AXIS, lineW) line3d(Vec3f.NEG_Z_AXIS * 0.5f, Vec3f.Z_AXIS * 0.5f, Vec3f.X_AXIS, lineW) } shader = KslUnlitShader { vertices { isInstanced = true } pipeline { cullMethod = CullMethod.NO_CULLING } color { instanceColor() } colorSpaceConversion = ColorSpaceConversion.LinearToSrgb() } } init { addNode(pointLightMesh) addNode(spotLightMesh) addNode(dirLightMesh) addNode(cameraMesh) addNode(groupMesh) onUpdate { updateOverlayInstances() } } private fun updateOverlayInstances() { groupInstances.clear() cameraInstances.clear() dirLightsInstances.clear() spotLightsInstances.clear() pointLightsInstances.clear() groupInstances.addInstances(groups.size) { buf -> groups.forEach { it.addInstance(buf) } } cameraInstances.addInstances(cameras.size) { buf -> cameras.forEach { it.addInstance(buf) } } dirLightsInstances.addInstances(dirLights.size) { buf -> dirLights.forEach { it.addInstance(buf) } } spotLightsInstances.addInstances(spotLights.size) { buf -> spotLights.forEach { it.addInstance(buf) } } pointLightsInstances.addInstances(pointLights.size) { buf -> pointLights.forEach { it.addInstance(buf) } } } private fun MeshBuilder.generateArrow() { line3d(Vec3f.ZERO, Vec3f(1.5f, 0f, 0f), Vec3f.Z_AXIS, lineW) line3d(Vec3f.ZERO, Vec3f(1.5f, 0f, 0f), Vec3f.Y_AXIS, lineW) withTransform { rotate((-90f).deg, Vec3f.Z_AXIS) translate(0f, 1.6f, 0f) cylinder { bottomRadius = 0.15f topRadius = 0f height = 0.2f topFill = false } } } fun updateOverlayObjects() { cameras.clear() groups.clear() dirLights.clear() spotLights.clear() pointLights.clear() val sceneModel = KoolEditor.instance.activeScene.value ?: return sceneModel.sceneEntities.values.filter { it.components.none { c -> c is SceneNodeComponent } } .filter { it.isVisible && it.isSceneChild } .forEach { groups += GroupNodeInstance(it) } sceneModel.getAllComponents<CameraComponent>() .filter { it.gameEntity.isVisible } .forEach { cameras += CameraComponentInstance(it) } sceneModel.getAllComponents<DiscreteLightComponent>() .filter { it.gameEntity.isVisible } .forEach { when (it.light) { is Light.Directional -> dirLights += DirLightComponentInstance(it) is Light.Point -> pointLights += PointLightComponentInstance(it) is Light.Spot -> spotLights += SpotLightComponentInstance(it) } } } fun pick(rayTest: RayTest): GameEntity? { var closest: GameEntity? = null cameras.forEach { if (it.rayTest(rayTest)) { closest = it.gameEntity } } groups.forEach { if (it.rayTest(rayTest)) { closest = it.gameEntity } } dirLights.forEach { if (it.rayTest(rayTest)) { closest = it.gameEntity } } spotLights.forEach { if (it.rayTest(rayTest)) { closest = it.gameEntity } } pointLights.forEach { if (it.rayTest(rayTest)) { closest = it.gameEntity } } return closest } companion object { const val lineW = 0.06f } private abstract class OverlayObject(val gameEntity: GameEntity, val mesh: Mesh) { abstract val color: Color val modelMat: Mat4f get() = gameEntity.localToGlobalF val radius = mesh.geometry.bounds.size.length() private val invModelMat = MutableMat4f() fun addInstance(target: Float32Buffer) { val selectionOv = KoolEditor.instance.selectionOverlay val color = if (selectionOv.isSelected(gameEntity)) selectionOv.selectionColor.toLinear() else color modelMat.putTo(target) color.putTo(target) } fun rayTest(rayTest: RayTest): Boolean { val pos = modelMat.getTranslation() val n = pos.nearestPointOnRay(rayTest.ray.origin, rayTest.ray.direction, MutableVec3f()) if (n.distance(pos) < radius) { val d = n.sqrDistance(rayTest.ray.origin) if (d < rayTest.hitDistanceSqr) { modelMat.invert(invModelMat) return meshRayTest(rayTest) } } return false } private fun meshRayTest(rayTest: RayTest): Boolean { modelMat.invert(invModelMat) val localRay = rayTest.getRayTransformed(invModelMat) val isHit = mesh.rayTest.rayTest(rayTest, localRay) if (isHit) { // fixme: rather ugly workaround: mesh ray test transforms hit position to global coordinates using // the mesh's transform, not the instance's leading to a wrong hit-position / distance mesh.toLocalCoords(rayTest.hitPositionGlobal) modelMat.transform(rayTest.hitPositionGlobal) rayTest.setHit(mesh, rayTest.hitPositionGlobal) } return isHit } } private inner class PointLightComponentInstance(val component: DiscreteLightComponent) : OverlayObject(component.gameEntity, pointLightMesh) { override val color: Color get() = component.light.color } private inner class SpotLightComponentInstance(val component: DiscreteLightComponent) : OverlayObject(component.gameEntity, spotLightMesh) { override val color: Color get() = component.light.color } private inner class DirLightComponentInstance(val component: DiscreteLightComponent) : OverlayObject(component.gameEntity, dirLightMesh) { override val color: Color get() = component.light.color } private inner class CameraComponentInstance(val component: CameraComponent) : OverlayObject(component.gameEntity, cameraMesh) { private val activeColor = MdColor.GREY toneLin 300 private val inactiveColor = MdColor.GREY toneLin 700 override val color: Color get() { val isActive = component.sceneComponent.cameraComponent == component return if (isActive) activeColor else inactiveColor } } private inner class GroupNodeInstance(gameEntity: GameEntity) : OverlayObject(gameEntity, groupMesh) { override val color: Color = Color.WHITE } }
11
null
18
284
b6ba1c0e1591ae46c77a5e3e61b2e1354a11f0b9
14,777
kool
Apache License 2.0
tourcount/src/main/java/com/wmstein/tourcount/widgets/ListIndivRemWidget.kt
wistein
60,879,778
false
{"Kotlin": 262902, "Java": 169711}
package com.wmstein.tourcount.widgets import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.RelativeLayout import android.widget.TextView import com.wmstein.tourcount.R import com.wmstein.tourcount.database.Individuals import java.util.Objects /********************************** * Created by wmstein on 2018-03-21 * used by ListSpeciesActivity * Last edited in Java on 2019-02-12, * converted to Kotlin on 2023-07-05 */ class ListIndivRemWidget(context: Context, attrs: AttributeSet?) : RelativeLayout(context, attrs) { private val txtBemInd: TextView init { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater Objects.requireNonNull(inflater).inflate(R.layout.widget_list_indiv_rem, this, true) txtBemInd = findViewById(R.id.txtBemInd) } fun setRem(individuals: Individuals) { txtBemInd.text = individuals.notes } }
1
Kotlin
3
4
681268f835819b091fd912ae70c3fdd13eabb3fc
984
TourCount
Creative Commons Attribution 4.0 International
src/test/kotlin/dev/shtanko/algorithms/leetcode/SmallestEquivalentStringTest.kt
ashtanko
203,993,092
false
{"Kotlin": 6551662, "Shell": 1168, "Makefile": 961}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.stream.Stream import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource abstract class SmallestEquivalentStringTest<out T : SmallestEquivalentString>(private val strategy: T) { private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of( Arguments.of( "parker", "morris", "parser", "makkek", ), Arguments.of( "hello", "world", "hold", "hdld", ), Arguments.of( "leetcode", "programs", "sourcecode", "aauaaaaada", ), ) } @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun `smallest equivalent string test`(s1: String, s2: String, baseStr: String, expected: String) { val actual = strategy.invoke(s1, s2, baseStr) assertThat(actual).isEqualTo(expected) } } class SmallestEquivalentStringUnionTest : SmallestEquivalentStringTest<SmallestEquivalentString>(SmallestEquivalentStringUnion())
4
Kotlin
0
19
dd8ee7dc420c608d4a46d5dc5a19b11e6d3c7b9d
2,138
kotlab
Apache License 2.0
app/src/main/java/com/iamageo/plantae/domain/usecases/PlantUseCases.kt
iamageo
551,746,207
false
{"Kotlin": 43916}
package com.iamageo.plantae.domain.usecases data class PlantUseCases( val addPlant: AddPlant, val getAllPlants: GetAllPlants, val deletePlant: DeletePlant, val getPlantById: GetPlantById )
0
Kotlin
0
2
fecdf04d5acc56ba83b197c02c0548698e5e4ae4
205
Plantae
Apache License 2.0
src/main/kotlin/org/wfanet/measurement/measurementconsumer/stats/MeasurementStatistics.kt
world-federation-of-advertisers
349,561,061
false
{"Kotlin": 8800141, "Starlark": 862470, "C++": 540903, "CUE": 153744, "HCL": 145480, "TypeScript": 103886, "Shell": 20694, "CSS": 8481, "Go": 8063, "JavaScript": 5305, "HTML": 2188}
/* * Copyright 2023 The Cross-Media Measurement Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.wfanet.measurement.measurementconsumer.stats import org.wfanet.measurement.eventdataprovider.noiser.DpParams /** Noise mechanism enums. */ enum class NoiseMechanism { NONE, LAPLACE, GAUSSIAN, } data class VidSamplingInterval(val start: Double, val width: Double) /** The parameters used to compute a reach measurement. */ data class ReachMeasurementParams( val vidSamplingInterval: VidSamplingInterval, val dpParams: DpParams, val noiseMechanism: NoiseMechanism, ) /** The parameters used to compute a reach-and-frequency measurement. */ data class FrequencyMeasurementParams( val vidSamplingInterval: VidSamplingInterval, val dpParams: DpParams, val noiseMechanism: NoiseMechanism, val maximumFrequency: Int, ) /** The parameters used to compute an impression measurement. */ data class ImpressionMeasurementParams( val vidSamplingInterval: VidSamplingInterval, val dpParams: DpParams, val maximumFrequencyPerUser: Int, val noiseMechanism: NoiseMechanism, ) /** The parameters used to compute a watch duration measurement. */ data class WatchDurationMeasurementParams( val vidSamplingInterval: VidSamplingInterval, val dpParams: DpParams, val maximumDurationPerUser: Double, val noiseMechanism: NoiseMechanism, ) /** The parameters used to compute the variance of a reach measurement. */ data class ReachMeasurementVarianceParams( val reach: Long, val measurementParams: ReachMeasurementParams, ) /** The parameters used to compute the variance of a reach-and-frequency measurement. */ data class FrequencyMeasurementVarianceParams( val totalReach: Long, val reachMeasurementVariance: Double, val relativeFrequencyDistribution: Map<Int, Double>, val measurementParams: FrequencyMeasurementParams, ) /** The parameters used to compute the variance of an impression measurement. */ data class ImpressionMeasurementVarianceParams( val impression: Long, val measurementParams: ImpressionMeasurementParams, ) /** The parameters used to compute the variance of a watch duration measurement. */ data class WatchDurationMeasurementVarianceParams( val duration: Double, val measurementParams: WatchDurationMeasurementParams, ) typealias FrequencyVariance = Map<Int, Double> /** A data class that wraps different types of variances of a reach-and-frequency result. */ data class FrequencyVariances( val relativeVariances: FrequencyVariance, val kPlusRelativeVariances: FrequencyVariance, val countVariances: FrequencyVariance, val kPlusCountVariances: FrequencyVariance, ) /** The parameters used to compute the covariance of two reach measurements. */ data class ReachMeasurementCovarianceParams( val reach: Long, val otherReach: Long, val unionReach: Long, val samplingWidth: Double, val otherSamplingWidth: Double, val unionSamplingWidth: Double, )
88
Kotlin
10
32
e01466201b3f42ffe8bd32fe1acb81169972e059
3,465
cross-media-measurement
Apache License 2.0
SDKAndroid/src/main/kotlin/app/cybrid/sdkandroid/core/AssetPipe.kt
Cybrid-app
498,874,863
false
null
package app.cybrid.sdkandroid.core import app.cybrid.cybrid_api_bank.client.models.AssetBankModel import java.math.BigDecimal as JavaBigDecimal object AssetPipe { const val AssetPipeTrade: String = "trade" const val AssetPipeBase: String = "base" fun transform(value: JavaBigDecimal, asset: AssetBankModel, unit: String) : BigDecimal { return transformAny(value.toBigDecimal(), asset.decimals.toBigDecimal(), unit) } fun transform(value:BigDecimal, asset: AssetBankModel, unit: String) : BigDecimal { return transformAny(value, asset.decimals.toBigDecimal(), unit) } fun transform(value:String, asset: AssetBankModel, unit: String) : BigDecimal { return transformAny(BigDecimal(value), asset.decimals.toBigDecimal(), unit) } fun transform(value:Int, asset: AssetBankModel, unit: String) : BigDecimal { return transformAny(BigDecimal(value), asset.decimals.toBigDecimal(), unit) } fun transform(value:BigDecimal, decimals: BigDecimal, unit: String) : BigDecimal { return transformAny(value, decimals, unit) } fun transform(value:String, decimals: BigDecimal, unit: String) : BigDecimal { return transformAny(BigDecimal(value), decimals, unit) } fun transform(value:Int, decimals: BigDecimal, unit: String) : BigDecimal { return transformAny(BigDecimal(value), decimals, unit) } /** * Method to transform a number into a two different ways with unit type: * base: * Takes a number like 10 in asset USD and convert to --> 1000 (cents/base unit) * trade: * Takes a number like 1000 in cents of USD and convert to --> 10 * **/ private fun transformAny(value:BigDecimal, decimals: BigDecimal, unit: String) : BigDecimal { val divisor = BigDecimal(10).pow(decimals) val tradeUnit = value.div(divisor) val baseUnit = value.times(divisor) return when(unit) { "trade" -> tradeUnit "base" -> baseUnit else -> BigDecimal(0) } } /** * Method to calculate preQuote with buyPrice * If the price is zero always returns 0 * The base types: * crypto: * 1 BTC - $n USD * input BTC - ? * (input BTC * $n USD) / 1 BTC * fiat: * 1 BTC - $n USD * ? - input USD (formatted) * (input USD * 1 BTC) / $n USD * **/ fun preQuote(input: BigDecimal, price: BigDecimal, base: AssetBankModel.Type, decimals: BigDecimal = BigDecimal(2)): BigDecimal { var result = BigDecimal(0) if (base == AssetBankModel.Type.crypto) { result = input.times(price) } else { if (price != BigDecimal.zero()) { result = input.divL(price).setScale(decimals.toInt()) } } return result } }
16
null
2
6
c3fe39dd3ecbe0d90002ea227ed575f1dc2cabf7
2,894
cybrid-sdk-android
Apache License 2.0
SDKAndroid/src/main/kotlin/app/cybrid/sdkandroid/core/AssetPipe.kt
Cybrid-app
498,874,863
false
null
package app.cybrid.sdkandroid.core import app.cybrid.cybrid_api_bank.client.models.AssetBankModel import java.math.BigDecimal as JavaBigDecimal object AssetPipe { const val AssetPipeTrade: String = "trade" const val AssetPipeBase: String = "base" fun transform(value: JavaBigDecimal, asset: AssetBankModel, unit: String) : BigDecimal { return transformAny(value.toBigDecimal(), asset.decimals.toBigDecimal(), unit) } fun transform(value:BigDecimal, asset: AssetBankModel, unit: String) : BigDecimal { return transformAny(value, asset.decimals.toBigDecimal(), unit) } fun transform(value:String, asset: AssetBankModel, unit: String) : BigDecimal { return transformAny(BigDecimal(value), asset.decimals.toBigDecimal(), unit) } fun transform(value:Int, asset: AssetBankModel, unit: String) : BigDecimal { return transformAny(BigDecimal(value), asset.decimals.toBigDecimal(), unit) } fun transform(value:BigDecimal, decimals: BigDecimal, unit: String) : BigDecimal { return transformAny(value, decimals, unit) } fun transform(value:String, decimals: BigDecimal, unit: String) : BigDecimal { return transformAny(BigDecimal(value), decimals, unit) } fun transform(value:Int, decimals: BigDecimal, unit: String) : BigDecimal { return transformAny(BigDecimal(value), decimals, unit) } /** * Method to transform a number into a two different ways with unit type: * base: * Takes a number like 10 in asset USD and convert to --> 1000 (cents/base unit) * trade: * Takes a number like 1000 in cents of USD and convert to --> 10 * **/ private fun transformAny(value:BigDecimal, decimals: BigDecimal, unit: String) : BigDecimal { val divisor = BigDecimal(10).pow(decimals) val tradeUnit = value.div(divisor) val baseUnit = value.times(divisor) return when(unit) { "trade" -> tradeUnit "base" -> baseUnit else -> BigDecimal(0) } } /** * Method to calculate preQuote with buyPrice * If the price is zero always returns 0 * The base types: * crypto: * 1 BTC - $n USD * input BTC - ? * (input BTC * $n USD) / 1 BTC * fiat: * 1 BTC - $n USD * ? - input USD (formatted) * (input USD * 1 BTC) / $n USD * **/ fun preQuote(input: BigDecimal, price: BigDecimal, base: AssetBankModel.Type, decimals: BigDecimal = BigDecimal(2)): BigDecimal { var result = BigDecimal(0) if (base == AssetBankModel.Type.crypto) { result = input.times(price) } else { if (price != BigDecimal.zero()) { result = input.divL(price).setScale(decimals.toInt()) } } return result } }
16
null
2
6
c3fe39dd3ecbe0d90002ea227ed575f1dc2cabf7
2,894
cybrid-sdk-android
Apache License 2.0
src/main/kotlin/com/justai/jaicf/plugin/services/UsagesSearchService.kt
veptechno
428,503,533
true
{"Kotlin": 100333, "HTML": 1363}
package com.justai.jaicf.plugin.services import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.psi.PsiMethod import com.intellij.psi.search.searches.ReferencesSearch import com.justai.jaicf.plugin.LazySafeValue import com.justai.jaicf.plugin.REACTIONS_CHANGE_STATE_METHOD_NAME import com.justai.jaicf.plugin.REACTIONS_CLASS_NAME import com.justai.jaicf.plugin.REACTIONS_GO_METHOD_NAME import com.justai.jaicf.plugin.REACTIONS_PACKAGE import com.justai.jaicf.plugin.State import com.justai.jaicf.plugin.findClass import com.justai.jaicf.plugin.firstStateOrSuggestion import com.justai.jaicf.plugin.getPathExpressionsOfBoundedBlock import com.justai.jaicf.plugin.transitToState import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile class UsagesSearchService(val project: Project) { private val predefinedJumpReactions by lazy { findPredefinedJumpReactions() } private val pathExpressions = LazySafeValue(emptyList<KtExpression>()) { findExpressions() } fun findStateUsages(state: State): List<KtExpression> { if (pathExpressions.value.isEmpty()) Logger.getInstance("findStateUsages").warn("No path expression was found in project") return pathExpressions.value .filter { transitToState(it).firstStateOrSuggestion() == state } } fun markFileAsModified(file: KtFile) { pathExpressions.lazyUpdate { findExpressions() } } private fun findPredefinedJumpReactions(): List<PsiMethod> { check(!DumbService.getInstance(project).isDumb) { "IDEA in dumb mode" } val reactionsClass = findClass(REACTIONS_PACKAGE, REACTIONS_CLASS_NAME, project) ?: return emptyList() val jumpMethods = reactionsClass.allMethods.filter { it.name == REACTIONS_GO_METHOD_NAME || it.name == REACTIONS_CHANGE_STATE_METHOD_NAME } if (jumpMethods.isEmpty()) { logger.warn("No jump method declaration was found") return emptyList() } return jumpMethods } private fun findExpressions(): List<KtExpression> { val methods = SearchService.get(project).getMethodsUsedPathValue() .ifEmpty { predefinedJumpReactions } .ifEmpty { return emptyList() } return methods .flatMap { ReferencesSearch.search(it, project.projectScope()).findAll() } .map { it.element } .flatMap { it.getPathExpressionsOfBoundedBlock() } } companion object { private val logger = Logger.getInstance(this::class.java) fun get(project: Project): UsagesSearchService = ServiceManager.getService(project, UsagesSearchService::class.java) } }
0
Kotlin
0
0
395338825f20fbe8deaae72ee18bccdde71abc0f
2,910
jaicf-plugin
Apache License 2.0
fluxo-io-rad/src/commonMain/kotlin/fluxo/io/internal/ThreadSafe.kt
fluxo-kt
817,028,889
false
{"Kotlin": 182952, "Shell": 1015}
@file:Suppress("KDocUnresolvedReference", "RedundantSuppression") package fluxo.io.internal /** * Marks a class as thread-safe. * The class to which this annotation is applied is thread-safe. * * This means that no sequences of accesses (reads and writes to public fields, * calls to public methods) may put the object into an invalid state, * regardless of the interleaving of those actions by the runtime, * and without requiring any additional synchronization or coordination * on the part of the caller. * * This annotation is a hint to the compiler and the developer. * It doesn't enforce any thread-safety guarantees by itself. * * @see javax.annotation.concurrent.ThreadSafe */ @MustBeDocumented @OptionalExpectation @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS) @Suppress("GrazieInspection") public expect annotation class ThreadSafe()
8
Kotlin
0
4
716125c2e27be18be64a2ac05a501c4f91dc1fe1
885
fluxo-io
Apache License 2.0
library/src/main/kotlin/cz/filipproch/reactor/ui/ReactorCompatActivity.kt
filipproch
88,263,443
false
null
package cz.filipproch.reactor.ui import android.os.Bundle import android.support.v7.app.AppCompatActivity import cz.filipproch.reactor.base.translator.IReactorTranslator import cz.filipproch.reactor.base.view.ReactorUiAction import cz.filipproch.reactor.base.view.ReactorUiEvent import cz.filipproch.reactor.base.view.ReactorUiModel import cz.filipproch.reactor.base.view.ReactorView import cz.filipproch.reactor.ui.events.* import io.reactivex.Observable import io.reactivex.functions.Consumer import io.reactivex.subjects.PublishSubject /** * [AppCompatActivity] implementation of the [ReactorView] */ abstract class ReactorCompatActivity<T : IReactorTranslator> : AppCompatActivity(), ReactorView<T> { var reactorViewHelper: ReactorViewHelper<T>? = null private set private val activityEventsSubject = PublishSubject.create<ReactorUiEvent>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) reactorViewHelper = ReactorViewHelper(this) onCreateLayout() reactorViewHelper?.onReadyToRegisterEmitters() if (savedInstanceState != null) { onUiRestored(savedInstanceState) } else { onUiCreated() } onPostUiCreated() onUiReady() dispatch(ViewCreatedEvent(savedInstanceState)) } override fun onEmittersInit() { registerEmitter(activityEventsSubject) } override fun onConnectModelStream(modelStream: Observable<out ReactorUiModel>) { } override fun onConnectActionStream(actionStream: Observable<out ReactorUiAction>) { } override fun dispatch(event: ReactorUiEvent) { activityEventsSubject.onNext(event) } override fun registerEmitter(emitter: Observable<out ReactorUiEvent>) { reactorViewHelper?.registerEmitter(emitter) } override fun <T> Observable<T>.consumeOnUi(receiverAction: Consumer<T>) { reactorViewHelper?.receiveUpdatesOnUi(this, receiverAction) } fun <T> Observable<T>.consumeOnUi(action: (T) -> Unit) { consumeOnUi(Consumer<T> { action.invoke(it) }) } override fun onStart() { super.onStart() reactorViewHelper?.bindTranslatorWithView( ReactorTranslatorHelper.getTranslatorFromFragment(supportFragmentManager, translatorFactory) ) dispatch(ViewStartedEvent) } override fun onResume() { super.onResume() dispatch(ViewResumedEvent) } override fun onPause() { super.onPause() dispatch(ViewPausedEvent) } override fun onStop() { super.onStop() dispatch(ViewStoppedEvent) reactorViewHelper?.onViewNotUsable() } override fun onDestroy() { super.onDestroy() reactorViewHelper?.onViewDestroyed() } /* ReactorCompatActivity specific */ /** * Called from [onCreate] is savedInstanceState is null */ open fun onUiCreated() { } /** * Called from [onCreate] is savedInstanceState is not null */ open fun onUiRestored(savedInstanceState: Bundle) { } /** * Called from [onCreate] after either [onUiCreated] or [onUiRestored] has been called * * This method is useful to set [android.view.View] listeners or other stuff that doesn't survive activity recreation */ @Deprecated("This method was deprecated due to ambiguous name", ReplaceWith( "onUiReady" )) open fun onPostUiCreated() { } /** * Called from [onCreate] after either [onUiCreated] or [onUiRestored] has been called * * This method is useful to set [android.view.View] listeners or other stuff that doesn't survive activity recreation */ open fun onUiReady() { } @Deprecated("This method is not part of the Reactor architecture and was moved to the 'extras' module", ReplaceWith(""), DeprecationLevel.ERROR) open fun getLayoutResId(): Int { return -1 } /** * Called to create the layout for the view */ abstract fun onCreateLayout() }
7
Kotlin
0
0
ee1877a6fd8949d3bb8871fe3114dd83599352c7
4,190
reactor-android
MIT License
library/src/main/kotlin/cz/filipproch/reactor/ui/ReactorCompatActivity.kt
filipproch
88,263,443
false
null
package cz.filipproch.reactor.ui import android.os.Bundle import android.support.v7.app.AppCompatActivity import cz.filipproch.reactor.base.translator.IReactorTranslator import cz.filipproch.reactor.base.view.ReactorUiAction import cz.filipproch.reactor.base.view.ReactorUiEvent import cz.filipproch.reactor.base.view.ReactorUiModel import cz.filipproch.reactor.base.view.ReactorView import cz.filipproch.reactor.ui.events.* import io.reactivex.Observable import io.reactivex.functions.Consumer import io.reactivex.subjects.PublishSubject /** * [AppCompatActivity] implementation of the [ReactorView] */ abstract class ReactorCompatActivity<T : IReactorTranslator> : AppCompatActivity(), ReactorView<T> { var reactorViewHelper: ReactorViewHelper<T>? = null private set private val activityEventsSubject = PublishSubject.create<ReactorUiEvent>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) reactorViewHelper = ReactorViewHelper(this) onCreateLayout() reactorViewHelper?.onReadyToRegisterEmitters() if (savedInstanceState != null) { onUiRestored(savedInstanceState) } else { onUiCreated() } onPostUiCreated() onUiReady() dispatch(ViewCreatedEvent(savedInstanceState)) } override fun onEmittersInit() { registerEmitter(activityEventsSubject) } override fun onConnectModelStream(modelStream: Observable<out ReactorUiModel>) { } override fun onConnectActionStream(actionStream: Observable<out ReactorUiAction>) { } override fun dispatch(event: ReactorUiEvent) { activityEventsSubject.onNext(event) } override fun registerEmitter(emitter: Observable<out ReactorUiEvent>) { reactorViewHelper?.registerEmitter(emitter) } override fun <T> Observable<T>.consumeOnUi(receiverAction: Consumer<T>) { reactorViewHelper?.receiveUpdatesOnUi(this, receiverAction) } fun <T> Observable<T>.consumeOnUi(action: (T) -> Unit) { consumeOnUi(Consumer<T> { action.invoke(it) }) } override fun onStart() { super.onStart() reactorViewHelper?.bindTranslatorWithView( ReactorTranslatorHelper.getTranslatorFromFragment(supportFragmentManager, translatorFactory) ) dispatch(ViewStartedEvent) } override fun onResume() { super.onResume() dispatch(ViewResumedEvent) } override fun onPause() { super.onPause() dispatch(ViewPausedEvent) } override fun onStop() { super.onStop() dispatch(ViewStoppedEvent) reactorViewHelper?.onViewNotUsable() } override fun onDestroy() { super.onDestroy() reactorViewHelper?.onViewDestroyed() } /* ReactorCompatActivity specific */ /** * Called from [onCreate] is savedInstanceState is null */ open fun onUiCreated() { } /** * Called from [onCreate] is savedInstanceState is not null */ open fun onUiRestored(savedInstanceState: Bundle) { } /** * Called from [onCreate] after either [onUiCreated] or [onUiRestored] has been called * * This method is useful to set [android.view.View] listeners or other stuff that doesn't survive activity recreation */ @Deprecated("This method was deprecated due to ambiguous name", ReplaceWith( "onUiReady" )) open fun onPostUiCreated() { } /** * Called from [onCreate] after either [onUiCreated] or [onUiRestored] has been called * * This method is useful to set [android.view.View] listeners or other stuff that doesn't survive activity recreation */ open fun onUiReady() { } @Deprecated("This method is not part of the Reactor architecture and was moved to the 'extras' module", ReplaceWith(""), DeprecationLevel.ERROR) open fun getLayoutResId(): Int { return -1 } /** * Called to create the layout for the view */ abstract fun onCreateLayout() }
7
Kotlin
0
0
ee1877a6fd8949d3bb8871fe3114dd83599352c7
4,190
reactor-android
MIT License
safetorunpinscreen/src/main/java/com/safetorun/pinscreen/pinHasher.kt
Safetorun
274,838,056
false
null
package com.safetorun.pinscreen import android.util.Base64 import java.security.SecureRandom const val SALT_SIZE = 20 internal fun secureRandomString() = SecureRandom().run { val bytes = ByteArray(SALT_SIZE) nextBytes(bytes) Base64.encodeToString(bytes, 0) }
22
null
1
37
bc56dd28a1fecf945a54cd1e74119b696dc2ed8e
274
safe_to_run
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/integration/DomainEventsListenerTest.kt
ministryofjustice
615,402,552
false
{"Kotlin": 501733, "Shell": 9504, "Dockerfile": 1415}
package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.integration import org.junit.jupiter.api.Test import org.mockito.kotlin.timeout import org.mockito.kotlin.verify import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.listener.DomainEventsMessage class DomainEventsListenerTest : IntegrationTestBase() { @Test fun `update offender message`() { val eventType = "prisoner-offender-search.prisoner.updated" val nomsNumber = "N321321" sendDomainEvent( DomainEventsMessage( eventType, additionalInformation = mapOf("nomsNumber" to nomsNumber), ), ) verify(referralService, timeout(20000)).updatePerson(nomsNumber) } }
2
Kotlin
0
0
a8ecbabbd921ca809a35364ca7150734c3c3d32d
695
hmpps-accredited-programmes-api
MIT License
slack/adapter/src/commonMain/kotlin/com/gchristov/thecodinglove/slack/adapter/http/mapper/SlackRevokeTokensMapper.kt
gchristov
533,472,792
false
{"Kotlin": 485032, "CSS": 174432, "HTML": 60961, "Dockerfile": 4477, "JavaScript": 742, "Shell": 669}
package com.gchristov.thecodinglove.slack.adapter.http.mapper import com.gchristov.thecodinglove.slack.domain.model.SlackEvent import com.gchristov.thecodinglove.slack.domain.usecase.SlackRevokeTokensUseCase internal fun SlackEvent.Callback.Event.TokensRevoked.toSlackRevokeTokensDto() = SlackRevokeTokensUseCase.Dto( bot = tokens.bot, oAuth = tokens.oAuth, )
0
Kotlin
1
4
2657252c3203d7ab647daf3f110e8f9d31e48305
369
thecodinglove-kotlinjs
Apache License 2.0
calculator/src/main/java/com/pechuro/cashdebts/calculator/impl/PolishNotationInterpreter.kt
Ilyshka991
171,679,797
false
null
package com.pechuro.cashdebts.calculator.impl import com.pechuro.cashdebts.calculator.model.mutableStackOf import javax.inject.Inject internal class PolishNotationInterpreter @Inject constructor() { fun interpret(expr: String): String? { val exprWithUnaryMinus = replaceUnaryMinus(expr) if (!isValid(exprWithUnaryMinus)) return null val tokens = getTokens(exprWithUnaryMinus) return parse(tokens) } private fun parse(tokens: List<String>): String? { val result = StringBuilder() val stack = mutableStackOf<String>() tokens.forEach { token -> if (token in OPERATORS + PARENTHESES) { if (token == "(") { stack.push(token) } else { if (token == ")") { while (stack.peek() != "(") { if (stack.isEmpty) return null result.append(stack.pop()).append(" ") } stack.pop() } else { while (stack.isNotEmpty && token.priority() <= stack.peek().priority()) { result.append(stack.pop()).append(" ") } stack.push(token) } } } else { if (token.isNumber()) result.append(token).append(" ") else return null } } while (stack.isNotEmpty) { if (stack.peek() == "(") { return null } else { result.append(stack.pop()).append(" ") } } return result.trimEnd().toString() } private fun getTokens(expr: String): List<String> { val exprWithoutSpaces = expr.replace(" ", "") val tokens = exprWithoutSpaces.split(INFIX_SPLIT_REGEX) return tokens.filter { it.isNotEmpty() } } private fun replaceUnaryMinus(expr: String): String { val result = StringBuilder() expr.forEachIndexed { index, char -> when { char == '-' && index != expr.lastIndex && index != 0 && expr[index + 1] == '(' && expr[index - 1] in OPERATORS + PARENTHESES -> result.append("~1*") index == 0 && char == '-' -> result.append('~') char == '-' && index != 0 && index != expr.lastIndex && expr[index - 1] in OPERATORS + PARENTHESES && expr[index + 1].isDigit() -> result.append('~') else -> result.append(char) } } return result.toString() } private fun isValid(expr: String): Boolean { expr.forEachIndexed { index, char -> if ((index == 0 && char in OPERATORS) || (index == expr.lastIndex && char in OPERATORS) || (index != 0 && char in OPERATORS && expr[index - 1] in "$OPERATORS(") || (index != expr.lastIndex && char in OPERATORS && expr[index + 1] == ')') || (index != expr.lastIndex && char.isDigit() && expr[index + 1] == '(') ) return false } return true } private fun String.priority() = when (this) { "(" -> 1 "+", "-" -> 2 "*", "/" -> 3 else -> 4 } private fun String.isNumber() = this.matches(NUMBER_REGEX) companion object { private val INFIX_SPLIT_REGEX = "(?<=[-+*/()])|(?=[-+*/()])".toRegex() private val NUMBER_REGEX = "~?\\d+(\\.\\d+)?".toRegex() private const val OPERATORS = "+-*/" private const val PARENTHESES = "()" } }
0
Kotlin
0
3
afb871ebb70b2863a1f2c290f7e06a3f5b9feab6
3,684
CashDebts
Apache License 2.0
app/src/main/java/org/fossasia/susi/ai/rest/responses/susi/Stars.kt
phahok
140,761,301
true
{"Kotlin": 294624, "Java": 209065, "Shell": 2946}
package org.fossasia.susi.ai.rest.responses.susi import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import java.io.Serializable /** * * Created by arundhati24 on 05/06/18. */ class Stars : Serializable { @SerializedName("one_star") @Expose var oneStar: Int = 0 @SerializedName("two_star") @Expose var twoStar: Int = 0 @SerializedName("three_star") @Expose var threeStar: Int = 0 @SerializedName("four_star") @Expose var fourStar: Int = 0 @SerializedName("five_star") @Expose var fiveStar: Int = 0 @SerializedName("total_star") @Expose var totalStar: Int = 0 @SerializedName("avg_star") @Expose var averageStar: Float = 0f }
0
Kotlin
0
0
73e82812930af643c3481ecd69f019ac4bd05ccf
760
susi_android
Apache License 2.0
app/src/main/java/org/nitri/opentopo/overlay/OverlayHelper.kt
Pygmalion69
145,400,627
false
{"Kotlin": 136644, "Java": 379}
package org.nitri.opentopo.overlay import android.content.Context import android.graphics.Color import android.graphics.ColorMatrix import android.graphics.ColorMatrixColorFilter import android.view.LayoutInflater import android.view.Window import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import com.google.android.material.textfield.TextInputLayout import io.ticofab.androidgpxparser.parser.domain.Gpx import org.nitri.opentopo.R import org.nitri.opentopo.overlay.model.MarkerModel import org.nitri.opentopo.nearby.entity.NearbyItem import org.osmdroid.tileprovider.MapTileProviderBasic import org.osmdroid.tileprovider.tilesource.ITileSource import org.osmdroid.tileprovider.tilesource.XYTileSource import org.osmdroid.util.GeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.overlay.ItemizedIconOverlay.OnItemGestureListener import org.osmdroid.views.overlay.Marker import org.osmdroid.views.overlay.Marker.OnMarkerClickListener import org.osmdroid.views.overlay.Marker.OnMarkerDragListener import org.osmdroid.views.overlay.OverlayItem import org.osmdroid.views.overlay.TilesOverlay class OverlayHelper(private val mContext: Context, private val mMapView: MapView?) { private var mWayPointOverlay: ItemizedIconInfoOverlay? = null private var mNearbyItemOverlay: ItemizedIconInfoOverlay? = null private var mOverlay = OVERLAY_NONE private var mOverlayTileProvider: MapTileProviderBasic? = null private var mTilesOverlay: TilesOverlay? = null private val tileOverlayAlphaMatrix = ColorMatrix( floatArrayOf( 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 0.8f, 0f ) ) private val tileOverlayAlphaFilter = ColorMatrixColorFilter(tileOverlayAlphaMatrix) private val mWayPointItemGestureListener: OnItemGestureListener<OverlayItem?> = object : OnItemGestureListener<OverlayItem?> { override fun onItemSingleTapUp(index: Int, item: OverlayItem?): Boolean { mWayPointOverlay?.let { overlay -> mMapView?.let { mapView -> item?.let { currentItem -> overlay.showWayPointInfo(mapView, currentItem) } } } return true } override fun onItemLongPress(index: Int, item: OverlayItem?): Boolean { return false } } private lateinit var markerInteractionListener: MarkerInteractionListener private val onMarkerDragListener : OnMarkerDragListener = object : OnMarkerDragListener { override fun onMarkerDrag(marker: Marker?) { //NOP } override fun onMarkerDragEnd(marker: Marker?) { marker?.let { val markerModel = it.relatedObject as MarkerModel markerModel.latitude = it.position.latitude markerModel.longitude = it.position.longitude } } override fun onMarkerDragStart(marker: Marker?) { //NOP } } private val onMarkerClickListener : OnMarkerClickListener = OnMarkerClickListener { marker, _ -> //marker?.let {markerInteractionListener.onMarkerClicked(marker.relatedObject as MarkerModel)} markerInfoWindow?.takeIf { it.isOpen }?.close() markerInfoWindow = MarkerInfoWindow( R.layout.bonuspack_bubble, R.id.bubble_title, R.id.bubble_description, R.id.bubble_subdescription, null, mMapView ).apply { val windowLocation = GeoPoint(marker.position.latitude, marker.position.longitude) open(marker.relatedObject, windowLocation, 0, 0) } true } private val onMarkerLongPressListener : CustomMarker.OnMarkerLongPressListener = object : CustomMarker.OnMarkerLongPressListener { override fun onMarkerLongPress(marker: Marker) { val markerModel = marker.relatedObject as MarkerModel val dialogView = LayoutInflater.from(mContext).inflate(R.layout.dialog_edit_marker, null) val nameInput = dialogView.findViewById<TextInputLayout>(R.id.nameInput) val descriptionInput = dialogView.findViewById<TextInputLayout>(R.id.descriptionInput) nameInput.editText?.setText(markerModel.name) descriptionInput.editText?.setText(markerModel.description) val alertDialog = AlertDialog.Builder(mContext) .setTitle(mContext.getString(R.string.edit_marker)) .setView(dialogView) .setPositiveButton(mContext.getString(R.string.ok)) { _, _ -> markerModel.name = nameInput.editText?.text.toString() markerModel.description = descriptionInput.editText?.text.toString() } .setNegativeButton(mContext.getString(R.string.cancel)) { dialog, _ -> dialog.dismiss() } .setNeutralButton(mContext.getString(R.string.delete)) { _, _ -> showDeleteConfirmationDialog(mContext) { markerInteractionListener.onMarkerDelete(markerModel) } } .create() alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE) alertDialog.show() } } private fun showDeleteConfirmationDialog(context: Context, onDeleteConfirmed: () -> Unit) { val alertDialog = AlertDialog.Builder(context) .setTitle(mContext.getString(R.string.confirm_delete)) .setMessage(mContext.getString(R.string.prompt_confirm_delete)) .setPositiveButton(mContext.getString(R.string.delete)) { _, _ -> onDeleteConfirmed() } .setNegativeButton(mContext.getString(R.string.cancel), null) .create() alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE) alertDialog.show() } private val mNearbyItemGestureListener: OnItemGestureListener<OverlayItem?> = object : OnItemGestureListener<OverlayItem?> { override fun onItemSingleTapUp(index: Int, item: OverlayItem?): Boolean { mNearbyItemOverlay?.let { overlay -> mMapView?.let { mapView -> item?.let { currentItem -> overlay.showNearbyItemInfo(mapView, currentItem) } } } return true } override fun onItemLongPress(index: Int, item: OverlayItem?): Boolean { clearNearby() mMapView?.invalidate() return true } } private var markerInfoWindow: MarkerInfoWindow? = null private var mTrackOverlay: TrackOverlay? = null private val mapMarkers = ArrayList<Marker>() /** * Add GPX as an overlay * * @param gpx * @see Gpx */ fun setGpx(gpx: Gpx) { clearGpx() gpx.tracks?.forEach { track -> mTrackOverlay = TrackOverlay(mContext, track) mMapView?.overlays?.add(0, mTrackOverlay) } val wayPointItems = mutableListOf<OverlayItem>() gpx.wayPoints?.forEach { wayPoint -> val gp = GeoPoint(wayPoint.latitude, wayPoint.longitude) val item = OverlayItem(wayPoint.name, wayPoint.desc, gp) wayPointItems.add(item) } if (wayPointItems.isNotEmpty()) { mWayPointOverlay = ItemizedIconInfoOverlay( wayPointItems, ContextCompat.getDrawable(mContext, R.drawable.ic_default_marker), mWayPointItemGestureListener, mContext ) mMapView?.overlays?.add(mWayPointOverlay) } mMapView?.invalidate() } /** * Remove GPX layer */ fun clearGpx() { mMapView?.let { mapView -> mTrackOverlay?.also { mapView.overlays.remove(it) mTrackOverlay = null } mWayPointOverlay?.also { mapView.overlays.remove(it) mWayPointOverlay = null } } } /** * Set the collection of user markers */ fun setMarkers(markers: List<MarkerModel>, listener: MarkerInteractionListener) { clearMarkers() mMapView?.let { mapView -> markerInteractionListener = listener markers.forEach { val mapMarker = CustomMarker(mapView) mapMarker.position = GeoPoint(it.latitude, it.longitude) mapMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM) mapMarker.title = it.name mapMarker.id = it.toString() mapMarker.relatedObject = it mapMarker.isDraggable = true mapMarker.icon = ContextCompat.getDrawable(mContext, R.drawable.map_marker) mapMarker.setOnMarkerDragListener(onMarkerDragListener) mapMarker.setOnMarkerClickListener(onMarkerClickListener) mapMarker.onMarkerLongPressListener = onMarkerLongPressListener mapMarkers.add(mapMarker) mMapView.overlays?.add(mapMarker) } } } /** * Remove user markers */ private fun clearMarkers() { mMapView?.let { mapView -> mapMarkers.forEach { mapView.overlays.remove(it) } } } fun setNearby(item: NearbyItem) { clearNearby() val geoPoint = GeoPoint(item.lat, item.lon) val mapItem = OverlayItem(item.title, item.description, geoPoint) mNearbyItemOverlay = ItemizedIconInfoOverlay( ArrayList(listOf(mapItem)), ContextCompat.getDrawable(mContext, R.drawable.ic_default_marker), mNearbyItemGestureListener, mContext ) mMapView!!.overlays.add(mNearbyItemOverlay) mMapView.invalidate() } /** * Remove nearby item layer */ fun clearNearby() { if (mMapView != null && mNearbyItemOverlay != null) { mMapView.overlays.remove(mNearbyItemOverlay) mNearbyItemOverlay = null } } /** * Returns whether a GPX has been added * * @return GPX layer present */ fun hasGpx(): Boolean { return mTrackOverlay != null || mWayPointOverlay != null } fun setTilesOverlay(overlay: Int) { mOverlay = overlay var overlayTiles: ITileSource? = null mTilesOverlay?.let { mMapView?.overlays?.remove(it) } when (mOverlay) { OVERLAY_NONE -> {} OVERLAY_HIKING -> overlayTiles = XYTileSource( "hiking", 1, 17, 256, ".png", arrayOf( "https://tile.waymarkedtrails.org/hiking/" ), mContext.getString(R.string.lonvia_copy) ) OVERLAY_CYCLING -> overlayTiles = XYTileSource( "cycling", 1, 17, 256, ".png", arrayOf( "https://tile.waymarkedtrails.org/cycling/" ), mContext.getString(R.string.lonvia_copy) ) } overlayTiles?.let { tiles -> val tileProvider = MapTileProviderBasic(mContext).apply { setTileSource(tiles) tileRequestCompleteHandlers.clear() tileRequestCompleteHandlers.add(mMapView?.tileRequestCompleteHandler) } val tilesOverlay = TilesOverlay(tileProvider, mContext).apply { loadingBackgroundColor = Color.TRANSPARENT setColorFilter(tileOverlayAlphaFilter) } mMapView?.overlays?.add(0, tilesOverlay) } mMapView?.invalidate() } val copyrightNotice: String? /** * Copyright notice for the tile overlay * * @return copyright notice or null */ get() = if (mOverlayTileProvider != null && mOverlay != OVERLAY_NONE) { mOverlayTileProvider?.tileSource?.copyrightNotice } else null fun destroy() { mTilesOverlay = null mOverlayTileProvider = null mWayPointOverlay = null } interface MarkerInteractionListener { fun onMarkerMoved(markerModel: MarkerModel) fun onMarkerClicked(markerModel: MarkerModel) fun onMarkerDelete(markerModel: MarkerModel) } companion object { /** * Tiles Overlays */ const val OVERLAY_NONE = 1 const val OVERLAY_HIKING = 2 const val OVERLAY_CYCLING = 3 } }
10
Kotlin
10
39
5a61d73cb7bd73e986c26868bb7c288e3dbfd038
13,081
OpenTopoMapViewer
Apache License 2.0
samples/simple-routing/src/androidTest/java/com/badoo/ribs/samples/simplerouting/SimpleRoutingChild1Test.kt
simona-anomis
353,379,092
true
{"Kotlin": 1065770}
package com.badoo.ribs.samples.simplerouting import android.os.Bundle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import com.badoo.ribs.test.RibsRule import com.badoo.ribs.core.modality.BuildContext.Companion.root import com.badoo.ribs.samples.simplerouting.rib.R import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.SimpleRoutingChild1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.builder.SimpleRoutingChild1Builder import org.junit.Rule import org.junit.Test private const val TITLE = "Any title" class SimpleRoutingChild1Test { @get:Rule val ribsRule = RibsRule { _, savedInstanceState -> buildRib(savedInstanceState) } private fun buildRib(savedInstanceState: Bundle?) = SimpleRoutingChild1Builder( object : SimpleRoutingChild1.Dependency { override val title: String = TITLE } ).build(root(savedInstanceState)) @Test fun showsTitleText() { onView(withId(R.id.child1_title)) .check(matches(withText(TITLE))) } }
0
Kotlin
0
0
a9d5cc6dbb9e2bf8cf9240d0e835dc43aefc5cde
1,247
RIBs
Apache License 2.0
app/src/test/java/com/iliaberlana/movies/MoviesRepositoryImplTest.kt
siayerestaba
196,740,845
false
null
package com.iliaberlana.movies import com.iliaberlana.movies.domain.exception.DomainError import com.iliaberlana.movies.framework.MovieRepositoryImpl import com.iliaberlana.movies.framework.moviebd.MovieDBClientService import io.kotlintest.assertions.arrow.either.shouldBeLeft import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test class MoviesRepositoryImplTest { private val movieDBClientService = mockk<MovieDBClientService>() private val movieRepositoryImpl = MovieRepositoryImpl(movieDBClientService) @Test fun `call MovieDBClientService when call MoviesRepository with same parameters`() = runBlocking { coEvery {movieDBClientService.getMoviesFromDB(1) } returns emptyList() movieRepositoryImpl.listMovies(1) coVerify {movieDBClientService.getMoviesFromDB(1) } } @Test fun `catch the NoInternetConnectionException and return Either with this error`() = runBlocking { coEvery { movieDBClientService.getMoviesFromDB(1) } throws DomainError.NoInternetConnectionException val actual = movieRepositoryImpl.listMovies(1) actual.shouldBeLeft(DomainError.NoInternetConnectionException) Unit } @Test fun `return Either with NoMoreMoviesException error when receive a emptyList`() = runBlocking { coEvery { movieDBClientService.getMoviesFromDB(1) } returns emptyList() val actual = movieRepositoryImpl.listMovies(1) actual.shouldBeLeft(DomainError.NoMoreMoviesException) Unit } }
0
Kotlin
0
0
479bdabe4f2e4dea59872d8d71d5a57468fac988
1,622
kotlin-movies-app
MIT License
src/main/kotlin/org/rust/lang/core/psi/ext/RsInferenceContextOwner.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.injected.editor.VirtualFileWindow import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.PsiModificationTracker import org.rust.lang.core.psi.* /** * PSI element that implements this interface holds type inference context that * can be retrieved for each child element by [org.rust.lang.core.types.inference] * * @see org.rust.lang.core.types.infer.RsInferenceContext.infer */ interface RsInferenceContextOwner : RsElement val RsInferenceContextOwner.body: RsElement? get() = when (this) { is RsArrayType -> expr is RsConstant -> expr is RsConstParameter -> expr is RsFunction -> block is RsVariantDiscriminant -> expr is RsExpressionCodeFragment -> expr is RsReplCodeFragment -> this is RsPathCodeFragment -> this is RsPath -> typeArgumentList is RsDefaultParameterValue -> expr else -> null } fun <T> RsInferenceContextOwner.createCachedResult(value: T): CachedValueProvider.Result<T> { val structureModificationTracker = project.rustStructureModificationTracker return when { // The case of injected language. Injected PSI don't have its own event system, so can only // handle evens from outer PSI. For example, Rust language is injected to Kotlin's string // literal. If a user change the literal, we can only be notified that the literal is changed. // So we have to invalidate the cached value on any PSI change containingFile.virtualFile is VirtualFileWindow -> { CachedValueProvider.Result.create(value, PsiModificationTracker.MODIFICATION_COUNT) } // Invalidate cached value of code fragment on any PSI change this is RsCodeFragment -> CachedValueProvider.Result.create(value, PsiModificationTracker.MODIFICATION_COUNT) // CachedValueProvider.Result can accept a ModificationTracker as a dependency, so the // cached value will be invalidated if the modification counter is incremented. else -> { val modificationTracker = contextOrSelf<RsModificationTrackerOwner>()?.modificationTracker CachedValueProvider.Result.create(value, listOfNotNull(structureModificationTracker, modificationTracker)) } } }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
2,449
intellij-rust
MIT License
infra/gradle/src/main/kotlin/com/github/c64lib/gradle/tasks/Clean.kt
Cumbayah
405,651,085
true
{"Kotlin": 274338, "Shell": 560}
/* MIT License Copyright (c) 2018-2022 c64lib: The Ultimate Commodore 64 Library Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.c64lib.gradle.tasks import com.github.c64lib.gradle.GROUP_BUILD import com.github.c64lib.gradle.RetroAssemblerPluginExtension import com.github.c64lib.gradle.asms.AssemblerFacadeFactory import com.github.c64lib.retroassembler.domain.AssemblerType import org.gradle.api.tasks.Delete import org.gradle.api.tasks.Input import org.gradle.api.tasks.TaskAction open class Clean : Delete() { init { description = "Cleans KickAssemblerFacade target files" group = GROUP_BUILD } @Input lateinit var extension: RetroAssemblerPluginExtension @TaskAction override fun clean() { delete(project.buildDir) if (extension.dialect != AssemblerType.None) { val asm = AssemblerFacadeFactory.of(extension.dialect, project, extension) delete(asm.targetFiles()) } super.clean() } }
0
Kotlin
0
0
d9d66768bab1a1899a4fbe30d25c8cd30c342f56
1,940
gradle-retro-assembler-plugin
MIT License
blueprint-ui/src/main/kotlin/reactivecircus/blueprint/ui/extension/Context.kt
MaTriXy
225,306,352
true
{"Kotlin": 107266, "Shell": 936}
package reactivecircus.blueprint.ui.extension import android.content.Context import android.content.res.Resources import android.graphics.drawable.Drawable import android.provider.Settings import android.util.TypedValue import androidx.annotation.AttrRes import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat /** * Apply tinting to a vector drawable. */ fun Context.tintVectorDrawable( theme: Resources.Theme, @DrawableRes resId: Int, @ColorInt tint: Int ): Drawable { val drawable: Drawable = VectorDrawableCompat.create(resources, resId, theme) as Drawable val wrapped = DrawableCompat.wrap(drawable) drawable.mutate() DrawableCompat.setTint(wrapped, tint) return drawable } /** * Resolves the given color attribute and returns the resource ID associated with the color. */ @ColorInt fun Context.resolveColorAttr(@AttrRes colorAttr: Int): Int { val resolvedAttr = TypedValue() theme.resolveAttribute(colorAttr, resolvedAttr, true) // resourceId is used if it's a ColorStateList, and data if it's a color reference or a hex color val colorRes = if (resolvedAttr.resourceId != 0) resolvedAttr.resourceId else resolvedAttr.data return ContextCompat.getColor(this, colorRes) } /** * Whether animation is turned on on the device. */ fun Context.isAnimationOn(): Boolean { return Settings.Global.getFloat(contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) > 0 }
0
null
0
0
7e6954cab4d87af455298a85787caa023bdda567
1,623
blueprint-Architectural-frameworks
Apache License 2.0
droidcraft-sdk/src/main/java/me/sankalpchauhan/droidcraft/sdk/network/internal/extensions/Try.kt
sankalpchauhan-me
729,879,955
false
{"Kotlin": 60290}
/* * Copyright (c) 2023. Sankalp Singh Chauhan * * 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 me.sankalpchauhan.droidcraft.sdk.network.internal.extensions import timber.log.Timber inline fun <A> tryOrNull(message: String? = null, operation: () -> A): A? { return try { operation() } catch (any: Throwable) { if (message != null) { Timber.e(any, message) } null } }
2
Kotlin
0
0
8846bada8fb5202ef02e6ad70d49cfafa1843a33
943
droidcraft-sdk
Apache License 2.0
tonapi-tl/src/http/server/HttpServerHost.kt
ton-community
448,983,229
false
{"Kotlin": 1194581}
package org.ton.api.http.server import kotlinx.serialization.SerialName import org.ton.api.adnl.AdnlIdShort import org.ton.tl.* public data class HttpServerHost( val domains: Collection<String>, val ip: Int, val port: Int, @SerialName("adnl_id") val adnlId: AdnlIdShort ) { public companion object : TlCodec<HttpServerHost> by HttpServerHostTlConstructor } private object HttpServerHostTlConstructor : TlConstructor<HttpServerHost>( schema = "http.server.host domains:(vector string) ip:int32 port:int32 adnl_id:adnl.id.short = http.server.Host" ) { override fun decode(input: TlReader): HttpServerHost { val domains = input.readVector { readString() } val ip = input.readInt() val port = input.readInt() val adnl_id = input.read(AdnlIdShort) return HttpServerHost(domains, ip, port, adnl_id) } override fun encode(output: TlWriter, value: HttpServerHost) { output.writeVector(value.domains) { writeString(it) } output.writeInt(value.ip) output.writeInt(value.port) output.write(AdnlIdShort, value.adnlId) } }
21
Kotlin
24
80
7eb82e9b04a2e518182ebfc56c165fbfcc916be9
1,170
ton-kotlin
Apache License 2.0
app/src/main/java/com/pol/sane/jove/digitalshelter/ui/screens/auth/login/LoginScreen.kt
pol1612
760,386,536
false
{"Kotlin": 115906}
package com.pol.sane.jove.digitalshelter.ui.screens.auth.login import androidx.compose.foundation.ScrollState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import com.pol.sane.jove.digitalshelter.ui.common.composables.simples.BasicTextButton import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import com.pol.sane.jove.digitalshelter.ui.common.composables.simples.BasicButton import com.pol.sane.jove.digitalshelter.ui.common.composables.simples.EmailField import com.pol.sane.jove.digitalshelter.ui.common.composables.simples.PasswordField import android.util.Log import com.pol.sane.jove.digitalshelter.R import com.pol.sane.jove.digitalshelter.R.string as AppText @OptIn(ExperimentalMaterial3Api::class) @Composable fun LoginScreen( viewModel: LoginViewModel = viewModel(), navHostController: NavHostController ){ val uiState by viewModel.uiState.collectAsState() val snackbarHostState = remember { SnackbarHostState() } Scaffold( snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { TopAppBar( title = { Text(stringResource(AppText.login_into_the_app)) }, colors = TopAppBarDefaults.mediumTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer), ) }, content = { var scrollState: ScrollState = rememberScrollState() Column(modifier = Modifier .padding(it) .verticalScroll(scrollState), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer( modifier = Modifier .fillMaxWidth() .height(90.dp) ) EmailField(value = uiState.email, onNewValue = {newValue -> viewModel.onEmailChange(newValue)}) Spacer( modifier = Modifier .fillMaxWidth() .height(30.dp) ) PasswordField(value = uiState.password, onNewValue = {newValue -> viewModel.onPasswordChange(newValue)}) Spacer( modifier = Modifier .fillMaxWidth() .height(60.dp) ) Column( modifier = Modifier .width(340.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { BasicButton( text = AppText.sign_in, modifier = Modifier .width(320.dp) .padding(horizontal = 0.dp, vertical = 8.dp), action = { viewModel.onLoginClick(navHostController) }, enabled = uiState.isSignInButtonEnabled ) var emailSentText = stringResource(id = R.string.the_email_was_successfully_sent) BasicTextButton(AppText.forgot_password, Modifier .fillMaxWidth() ){ viewModel.sendRecoveryEmail(emailSentText) } BasicTextButton( text = AppText.not_registered_click_here_to_sign_up, Modifier .fillMaxWidth() //.padding(16.dp, 8.dp, 16.dp, 0.dp), ) { viewModel.onSignUpClick(navHostController) } } LaunchedEffect(key1 = uiState.snackBarText){ if(uiState.snackBarText != ""){ val snackbarResult = snackbarHostState.showSnackbar( message = uiState.snackBarText, duration = SnackbarDuration.Short ) if (snackbarResult == SnackbarResult.Dismissed){ Log.i("LoginScreen::Snackbar","dismissed") viewModel.deleteSnackBarText() } } } } } ) } @Preview @Composable fun LoginScreenPreview(){ LoginScreen(viewModel(), NavHostController(LocalContext.current)) }
0
Kotlin
0
1
ca1789d797222311a56a556626856985f9171d01
5,988
DigitalShelter
Apache License 2.0
GanAndroidApp/GanClient/src/main/java/com/xattacker/binary/OutputBinaryBuffer.kt
xattacker
311,286,040
false
{"Swift": 94193, "Kotlin": 59707, "Java": 49457, "C": 12009, "Ruby": 1175, "Objective-C": 451, "Shell": 379, "Batchfile": 134}
package com.xattacker.binary import java.io.Closeable import java.io.IOException import java.io.InputStream import java.io.OutputStream class OutputBinaryBuffer: Closeable, BinaryWritable<OutputBinaryBuffer> { private var _out: OutputStream? constructor(outs: OutputStream) { _out = outs } @Throws(IOException::class) fun flush() { _out?.flush() } @Throws(IOException::class) override fun close() { _out?.close() } @Throws(IOException::class) override fun writeBinary(aData: ByteArray, aOffset: Int, aLength: Int): OutputBinaryBuffer { _out?.write(aData, aOffset, aLength) return this } @Throws(IOException::class) override fun writeShort(aShort: Short): OutputBinaryBuffer { val data = TypeConverter.shortToByte(aShort) writeBinary(data, 0, data.size) return this } @Throws(IOException::class) override fun writeInteger(aInt: Int): OutputBinaryBuffer { val data = TypeConverter.intToByte(aInt) writeBinary(data, 0, data.size) return this } @Throws(IOException::class) override fun writeLong(aLong: Long): OutputBinaryBuffer { val data = TypeConverter.longToByte(aLong) writeBinary(data, 0, data.size) return this } @Throws(IOException::class) override fun writeDouble(aDouble: Double): OutputBinaryBuffer { val data = TypeConverter.doubleToByte(aDouble) writeBinary(data, 0, data.size) return this } @Throws(IOException::class) override fun writeString(aStr: String): OutputBinaryBuffer { if (aStr.isEmpty()) { writeInteger(0) } else { val data = aStr.toByteArray(Charsets.UTF_8) val length = data.size writeInteger(length) writeBinary(data, 0, length) } return this } @Throws(IOException::class) @JvmOverloads fun writeString(aIn: InputStream?, aBufferSize: Int = 5120): OutputBinaryBuffer { if (aIn == null || aIn.available() == 0) { writeInteger(0) } else { val length = aIn.available() writeInteger(length) val temp = ByteArray(aBufferSize) var index = 0 while (true) { index = aIn.read(temp) if (index < 0) { break } writeBinary(temp, 0, index) flush() } } return this } }
0
Swift
0
0
b53e4e579eaaad8aaafa896e405bedd16a62d71d
2,686
GanSocket
MIT License
src/main/kotlin/no/nav/dagpenger/oppslag/inntekt/SerDer.kt
navikt
313,952,546
false
{"Kotlin": 51883, "Dockerfile": 193}
package no.nav.dagpenger.oppslag.inntekt import com.fasterxml.jackson.databind.JsonNode import no.nav.helse.rapids_rivers.JsonMessage internal fun JsonMessage.aktorId(): String? = this["identer"].firstOrNull { it["type"].asText() == "aktørid" && !it["historisk"].asBoolean() }?.get("id")?.asText() internal fun JsonMessage.fodselsnummer(): String? = this["identer"].firstOrNull { it["type"].asText() == "folkeregisterident" && !it["historisk"].asBoolean() }?.get("id")?.asText() internal fun harAktørEllerFnr(jsonNode: JsonNode) { require( jsonNode.any { node -> node["type"].asText() == "aktørid" } || jsonNode.any { node -> node["type"].asText() == "folkeregisterident" }, ) { "Mangler aktørid eller folkeregisterident i identer" } }
2
Kotlin
0
0
ec7d87832887a7374733ebc54a4b2065755cb0a9
776
dp-oppslag-inntekt
MIT License
biab-bap-client/src/main/kotlin/org/beckn/one/sandbox/bap/client/order/cancel/controllers/CancelOrderController.kt
beckn
490,158,415
false
null
package org.beckn.one.sandbox.bap.client.order.cancel.controllers import org.beckn.one.sandbox.bap.client.order.cancel.services.CancelOrderService import org.beckn.one.sandbox.bap.client.shared.dtos.CancelOrderDto import org.beckn.one.sandbox.bap.client.shared.services.LoggingService import org.beckn.one.sandbox.bap.errors.HttpError import org.beckn.one.sandbox.bap.factories.ContextFactory import org.beckn.one.sandbox.bap.factories.LoggingFactory import org.beckn.protocol.schemas.ProtocolAckResponse import org.beckn.protocol.schemas.ProtocolContext import org.beckn.protocol.schemas.ResponseMessage import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController @RestController class CancelOrderController @Autowired constructor( private val contextFactory: ContextFactory, private val cancelOrderService: CancelOrderService, private val loggingFactory: LoggingFactory, private val loggingService: LoggingService ) { val log: Logger = LoggerFactory.getLogger(this::class.java) @PostMapping("/client/v1/cancel_order") @ResponseBody fun cancelOrderV1(@RequestBody request: CancelOrderDto): ResponseEntity<ProtocolAckResponse> { log.info("Got request to cancel order") val context = getContext(request.context.transactionId, request.context.bppId) setLogging(context, null) return cancelOrderService.cancel( context = context, orderId = request.message.orderId, cancellationReasonId = request.message.cancellationReasonId ).fold( { log.error("Error when cancelling order with BPP: {}", it) setLogging(context, it) mapToErrorResponse(it, context) }, { log.info("Successfully cancelled order with BPP. Message: {}", it) setLogging(context, null) ResponseEntity.ok(ProtocolAckResponse(context = context, message = ResponseMessage.ack())) } ) } private fun mapToErrorResponse(it: HttpError, context: ProtocolContext) = ResponseEntity .status(it.status()) .body( ProtocolAckResponse( context = context, message = it.message(), error = it.error() ) ) private fun setLogging(context: ProtocolContext, error: HttpError?) { val loggerRequest = loggingFactory.create(messageId = context.messageId, transactionId = context.transactionId, contextTimestamp = context.timestamp.toString(), action = ProtocolContext.Action.CANCEL, bppId = context.bppId, errorCode = error?.error()?.code, errorMessage = error?.error()?.message ) loggingService.postLog(loggerRequest) } private fun getContext(transactionId: String, bppId: String? = null) = contextFactory.create(action = ProtocolContext.Action.CANCEL, transactionId = transactionId, bppId = bppId) }
1
Kotlin
0
0
1f3ad796bbfbb896bcfad7d676e0fed590a2d935
3,106
ondc-test-bap-be
MIT License
app/src/main/java/com/example/authloginmethods/screens/screens/UserDetailsFragment.kt
F-Y-E-F
288,741,126
false
null
package com.example.authloginmethods.screens.screens import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.example.authloginmethods.R import com.example.authloginmethods.auth.Authenticate import com.example.authloginmethods.screens.view_models.UserDetailsViewModel import kotlinx.android.synthetic.main.user_details_fragment.* class UserDetailsFragment : Fragment() { companion object { fun newInstance() = UserDetailsFragment() } private lateinit var authenticate: Authenticate override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.user_details_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) authenticate = Authenticate(this) //get user info and set it into layout val userDetailsViewModel = ViewModelProvider(requireActivity()).get(UserDetailsViewModel::class.java) userDetailsViewModel.getInfo().observe(viewLifecycleOwner, Observer { info-> mainText.text = info[0] userInfo1.text = info[1] userInfo2.text = info[2] userInfo3.text = info[3] }) //log out button logOutButton.setOnClickListener { authenticate.logOut() } } }
0
Kotlin
0
1
2ac52e3b7f4cb34407a58812c4f15c5593228659
1,630
All-Google-Firebase-Authenticate-Methods
The Unlicense
app/src/main/kotlin/dev/smartification/feature/list/ListState.kt
smartification-dev
727,231,903
false
{"Kotlin": 23702}
package dev.smartification.feature.list import dev.smartification.core.ui.Phase data class ListState( val phase: Phase = Phase.UNKNOWN, val names: List<String> = emptyList(), )
0
Kotlin
0
1
101c8788cdbdc9a355048f7f568448d757717864
187
reducer-view-model
Apache License 2.0
android/src/main/java/com/rnmapbox/rnmbx/components/styles/atmosphere/RNMBXAtmosphere.kt
rnmapbox
180,028,389
false
null
package com.rnmapbox.rnmbx.components.styles.atmosphere import android.content.Context import com.facebook.react.bridge.ReadableMap import com.mapbox.maps.MapboxMap import com.mapbox.maps.extension.style.atmosphere.generated.Atmosphere import com.mapbox.maps.extension.style.terrain.generated.Terrain import com.mapbox.maps.extension.style.terrain.generated.removeTerrain import com.rnmapbox.rnmbx.components.RemovalReason import com.rnmapbox.rnmbx.components.mapview.RNMBXMapView import com.rnmapbox.rnmbx.components.styles.RNMBXStyle import com.rnmapbox.rnmbx.components.styles.RNMBXStyleFactory import com.rnmapbox.rnmbx.components.styles.sources.AbstractSourceConsumer import com.rnmapbox.rnmbx.utils.Logger class RNMBXAtmosphere(context: Context?) : AbstractSourceConsumer(context) { override var iD: String? = null protected var mAtmosphere: Atmosphere? = null // beginregion RNMBXLayer @JvmField protected var mMap: MapboxMap? = null @JvmField protected var mReactStyle: ReadableMap? = null fun setReactStyle(reactStyle: ReadableMap?) { mReactStyle = reactStyle if (mAtmosphere != null) { addStyles() } } // endregion RNMBXLayer override fun addToMap(mapView: RNMBXMapView) { super.addToMap(mapView) mMap = mapView.getMapboxMap() val atmosphere = makeAtmosphere() mAtmosphere = atmosphere addStyles() mapView.savedStyle?.let { atmosphere.bindTo(it) } } override fun removeFromMap(mapView: RNMBXMapView, reason: RemovalReason): Boolean { mapView.savedStyle?.let { it.removeTerrain() } mMap = null return super.removeFromMap(mapView, reason) } fun makeAtmosphere(): Atmosphere { return Atmosphere() } fun addStyles() { mAtmosphere?.also { RNMBXStyleFactory.setAtmosphereLayerStyle( it, RNMBXStyle( context, mReactStyle!!, mMap!! ) ) } ?: run { Logger.e("RNMBXAtmosphere", "mAtmosphere is null") } } }
95
null
844
2,244
f87653dc694e9478a4fda1d2e7585f22bc1b95cb
2,134
maps
MIT License
core-catalog/src/main/kotlin/repository/BookInstanceRepository.kt
Arslanka-Educational
850,628,384
false
{"Kotlin": 54977, "Dockerfile": 1416, "Shell": 493}
package org.example.repository import org.example.model.BookInstance import org.example.model.BookStatus import org.springframework.dao.DuplicateKeyException import org.springframework.dao.EmptyResultDataAccessException import org.springframework.jdbc.core.RowMapper import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.jdbc.core.namedparam.SqlParameterSource import org.springframework.stereotype.Repository import java.sql.ResultSet import java.util.UUID @Repository class BookInstanceRepository( private val databaseClient: NamedParameterJdbcTemplate ) { fun getBookInstance(id: UUID): BookInstance? { val namedParameters: SqlParameterSource = MapSqlParameterSource("id", id) return try { databaseClient.queryForObject(SELECT_BOOK_INSTANCE, namedParameters, BookInstanceRowMapper()) } catch (e: EmptyResultDataAccessException) { null } } fun persist(bookInstance: BookInstance) { val namedParameters: SqlParameterSource = MapSqlParameterSource().addValues( mapOf( "id" to bookInstance.id, "book_content_id" to bookInstance.bookContentId, "book_status" to bookInstance.status.name ) ) try { databaseClient.update(INSERT_BOOK_INSTANCE, namedParameters) } catch (_: DuplicateKeyException) { } } fun update(bookInstance: BookInstance) { val namedParameters: SqlParameterSource = MapSqlParameterSource().addValues( mapOf( "id" to bookInstance.id, "status" to bookInstance.status.name ) ) databaseClient.query(UPDATE_BOOK_INSTANCE, namedParameters, BookInstanceRowMapper()) } class BookInstanceRowMapper : RowMapper<BookInstance> { override fun mapRow(rs: ResultSet, rowNum: Int): BookInstance { return BookInstance( id = UUID.fromString(rs.getString("id")), bookContentId = UUID.fromString(rs.getString("book_content_id")), status = BookStatus.valueOf(rs.getString("status")), ) } } private companion object { val INSERT_BOOK_INSTANCE = """ INSERT INTO book_instance (id, book_content_id, status) VALUES (:id, :book_content_id, :book_status) """.trimIndent() val UPDATE_BOOK_INSTANCE = """ UPDATE book_instance SET status = :status WHERE id = :id RETURNING id, book_content_id, status; """.trimIndent() val SELECT_BOOK_INSTANCE = """ SELECT id, book_content_id, status from book_instance where id = :id and status = 'FREE'; """.trimIndent() } }
2
Kotlin
0
1
7b55a64c54bd59e6474a975fad0361641adf3618
2,885
OpenBook-ng
MIT License