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
design-library/src/main/kotlin/app/dapk/st/design/components/Theme.kt
ouchadam
434,718,760
false
{"Kotlin": 461355, "JavaScript": 12445, "Shell": 1820}
package app.dapk.st.design.components import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import com.google.accompanist.systemuicontroller.rememberSystemUiController import kotlin.math.absoluteValue private object Palette { val brandPrimary = Color(0xFFb41cca) } private val DARK_COLOURS = darkColorScheme( primary = Palette.brandPrimary, onPrimary = Color(0xDDFFFFFF), secondaryContainer = Color(0xFF363639), onSecondaryContainer = Color(0xDDFFFFFF), ) private val LIGHT_COLOURS = lightColorScheme( primary = Palette.brandPrimary, onPrimary = Color(0xDDFFFFFF), secondaryContainer = Color(0xFFf1f0f1), onSecondaryContainer = Color(0xFF000000), ) private fun createExtended(scheme: ColorScheme) = ExtendedColors( selfBubble = scheme.primary, onSelfBubble = scheme.onPrimary, othersBubble = scheme.secondaryContainer, onOthersBubble = scheme.onSecondaryContainer, selfBubbleReplyBackground = scheme.primary.copy(alpha = 0.2f), otherBubbleReplyBackground = scheme.primary.copy(alpha = 0.2f), missingImageColors = listOf( Color(0xFFf7c7f7) to Color(0xFFdf20de), Color(0xFFe5d7f6) to Color(0xFF7b30cf), Color(0xFFf6c8cb) to Color(0xFFda2535), ) ) @Immutable data class ExtendedColors( val selfBubble: Color, val onSelfBubble: Color, val othersBubble: Color, val onOthersBubble: Color, val selfBubbleReplyBackground: Color, val otherBubbleReplyBackground: Color, val missingImageColors: List<Pair<Color, Color>>, ) { fun getMissingImageColor(key: String): Pair<Color, Color> { return missingImageColors[key.hashCode().absoluteValue % (missingImageColors.size)] } } private val LocalExtendedColors = staticCompositionLocalOf<ExtendedColors> { throw IllegalAccessError() } @Composable fun SmallTalkTheme(themeConfig: ThemeConfig, content: @Composable () -> Unit) { val systemUiController = rememberSystemUiController() val systemInDarkTheme = isSystemInDarkTheme() val colorScheme = when { themeConfig.useDynamicTheme -> { when (systemInDarkTheme) { true -> dynamicDarkColorScheme(LocalContext.current) false -> dynamicLightColorScheme(LocalContext.current) } } else -> { when (systemInDarkTheme) { true -> DARK_COLOURS false -> LIGHT_COLOURS } } } MaterialTheme(colorScheme = colorScheme) { val backgroundColor = MaterialTheme.colorScheme.background SideEffect { systemUiController.setSystemBarsColor(backgroundColor) } CompositionLocalProvider(LocalExtendedColors provides createExtended(colorScheme)) { content() } } } object SmallTalkTheme { val extendedColors: ExtendedColors @Composable get() = LocalExtendedColors.current } data class ThemeConfig( val useDynamicTheme: Boolean, )
36
Kotlin
4
139
5a391676d0d482596fe5d270798c2b361dba67e7
3,147
small-talk
Apache License 2.0
app/src/main/java/com/aitgacem/budgeter/data/TransactionDatabase.kt
naitgacem
722,472,421
false
{"Kotlin": 85291}
package com.aitgacem.budgeter.data import androidx.room.Database import androidx.room.RoomDatabase import com.aitgacem.budgeter.data.model.BalanceEntity import com.aitgacem.budgeter.data.model.CategoryEntity import com.aitgacem.budgeter.data.model.TransactionEntity @Database( entities = [ TransactionEntity::class, BalanceEntity::class, CategoryEntity::class ], version = 1, exportSchema = true, ) abstract class TransactionDatabase : RoomDatabase() { abstract fun transactionDao(): TransactionWithDetailsDao abstract fun balanceDao(): BalanceDao abstract fun categoryDao(): CategoryDao }
0
Kotlin
0
0
a784260e08acefa1950bea6182d09256ddd1ca97
644
Budgeter
Apache License 2.0
app/src/main/java/com/aitgacem/budgeter/data/TransactionDatabase.kt
naitgacem
722,472,421
false
{"Kotlin": 85291}
package com.aitgacem.budgeter.data import androidx.room.Database import androidx.room.RoomDatabase import com.aitgacem.budgeter.data.model.BalanceEntity import com.aitgacem.budgeter.data.model.CategoryEntity import com.aitgacem.budgeter.data.model.TransactionEntity @Database( entities = [ TransactionEntity::class, BalanceEntity::class, CategoryEntity::class ], version = 1, exportSchema = true, ) abstract class TransactionDatabase : RoomDatabase() { abstract fun transactionDao(): TransactionWithDetailsDao abstract fun balanceDao(): BalanceDao abstract fun categoryDao(): CategoryDao }
0
Kotlin
0
0
a784260e08acefa1950bea6182d09256ddd1ca97
644
Budgeter
Apache License 2.0
app/src/main/java/com/compose/wanandroid/data/remote/ssl/SimpleX509TrustManager.kt
MarkMjw
489,531,108
false
{"Kotlin": 333340}
package com.compose.wanandroid.data.remote.ssl import android.annotation.SuppressLint import java.security.cert.X509Certificate import javax.net.ssl.X509TrustManager @SuppressLint("CustomX509TrustManager") class SimpleX509TrustManager : X509TrustManager { @SuppressLint("TrustAllX509TrustManager") override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { } @SuppressLint("TrustAllX509TrustManager") override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { } override fun getAcceptedIssuers(): Array<X509Certificate> { return arrayOf() } }
0
Kotlin
0
6
0e5e7033cab4b69120ddb7ad6e88eba465b46978
635
wanandroid-compose
Apache License 2.0
payment-api/payment-infrastructure/src/main/kotlin/org/collaborators/paymentslab/payment/infrastructure/tosspayments/TossPaymentsKeyInApprovalProcessor.kt
f-lab-edu
665,758,863
false
{"Kotlin": 165334, "HTML": 1979, "Shell": 1679, "Dockerfile": 298}
package org.collaborators.paymentslab.payment.infrastructure.tosspayments import com.fasterxml.jackson.databind.ObjectMapper import org.collaborator.paymentlab.common.AuthenticatedUser import org.collaborator.paymentlab.common.domain.DomainEventTypeParser import org.collaborator.paymentlab.common.error.ErrorCode import org.collaborator.paymentlab.common.error.ServiceException import org.collaborators.paymentslab.payment.domain.PaymentResultEvent import org.collaborators.paymentslab.payment.domain.entity.PaymentOrder import org.collaborators.paymentslab.payment.domain.repository.PaymentOrderRepository import org.collaborators.paymentslab.payment.domain.repository.TossPaymentsRepository import org.collaborators.paymentslab.payment.infrastructure.log.AsyncAppenderPaymentTransactionLogProcessor import org.collaborators.paymentslab.payment.infrastructure.tosspayments.exception.TossPaymentsApiClientException import org.springframework.beans.factory.annotation.Value import org.springframework.context.ApplicationEventPublisher import org.springframework.core.env.Environment import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.kafka.core.KafkaTemplate import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.client.HttpClientErrorException import org.springframework.web.client.RestClientException import org.springframework.web.client.RestTemplate import java.nio.charset.StandardCharsets import java.util.* class TossPaymentsKeyInApprovalProcessor( private val restTemplate: RestTemplate, private val tossPaymentsRepository: TossPaymentsRepository, private val paymentOrderRepository: PaymentOrderRepository, private val kafkaTemplate: KafkaTemplate<String, String>, private val objectMapper: ObjectMapper, private val environment: Environment, private val asyncLogProcessor: AsyncAppenderPaymentTransactionLogProcessor ) { @Value("\${toss.payments.url}") private lateinit var url: String @Value("\${toss.payments.secretKey}") private lateinit var secretKey: String @Value("\${collaborators.kafka.topic.payment.transaction.name}") private lateinit var paymentTransactionTopicName: String fun approval(paymentOrder: PaymentOrder, dto: TossPaymentsKeyInDto) { paymentOrder.inProcess() var result = TossPaymentsApprovalResponse.preResponseOf(paymentOrder, dto) try { val request = createRequest(paymentOrder, dto) val response = restTemplate.postForEntity("${url}key-in", request, TossPaymentsApprovalResponse::class.java) if (response.statusCode == HttpStatus.OK && response.hasBody()) { paymentOrder.complete() result = response.body!! } } catch (e: HttpClientErrorException) { paymentOrder.aborted() throw TossPaymentsApiClientException(e) } catch (e: RestClientException) { paymentOrder.aborted() throw ServiceException(ErrorCode.UN_DEFINED_ERROR) } finally { paymentOrderRepository.save(paymentOrder) publishEventForRecordPaymentProcess(result, paymentOrder) } } private fun publishEventForRecordPaymentProcess( result: TossPaymentsApprovalResponse, paymentOrder: PaymentOrder ) { val principal = SecurityContextHolder.getContext().authentication.principal as AuthenticatedUser val newPaymentEntity = TossPaymentsFactory.create(result) newPaymentEntity.resultOf(principal.id, paymentOrder.status) val newPaymentRecord = tossPaymentsRepository.save(newPaymentEntity) newPaymentRecord.pollAllEvents().forEach { asyncLogProcessor.process(it as PaymentResultEvent) if (!environment.activeProfiles.contains("test")) { val eventWithClassType = DomainEventTypeParser.parseSimpleName(objectMapper.writeValueAsString(it), it::class.java) kafkaTemplate.send(paymentTransactionTopicName, eventWithClassType) } } } private fun createRequest(paymentOrder: PaymentOrder, dto: TossPaymentsKeyInDto): HttpEntity<TossPaymentsKeyInDto> { val headers = HttpHeaders() headers.setBasicAuth(String(Base64.getEncoder().encode("${secretKey}:".toByteArray(StandardCharsets.ISO_8859_1)))) headers.contentType = MediaType.APPLICATION_JSON val account = SecurityContextHolder.getContext().authentication.principal as AuthenticatedUser val idempotencyKey = "po_${paymentOrder.id}_acc_${account.id}}" headers.set("Idempotency-Key", String(Base64.getEncoder().encode(idempotencyKey.toByteArray(StandardCharsets.ISO_8859_1)))) return HttpEntity(dto, headers) } }
0
Kotlin
1
9
9455e02b6a962a363b5aaf32dbd4fbde7d52a477
4,942
payment-lab
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/ChartPerson.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.ChartPerson: ImageVector get() { if (_chartPerson != null) { return _chartPerson!! } _chartPerson = fluentIcon(name = "Filled.ChartPerson") { fluentPath { moveTo(12.5f, 2.75f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -1.5f, 0.0f) lineTo(11.0f, 3.0f) lineTo(5.25f, 3.0f) arcTo(3.25f, 3.25f, 0.0f, false, false, 2.0f, 6.25f) verticalLineToRelative(9.5f) curveTo(2.0f, 17.55f, 3.46f, 19.0f, 5.25f, 19.0f) horizontalLineToRelative(2.4f) lineToRelative(-1.48f, 1.77f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.16f, 0.96f) lineTo(9.6f, 19.0f) horizontalLineToRelative(3.5f) curveToRelative(0.34f, -1.16f, 1.41f, -2.0f, 2.67f, -2.0f) horizontalLineToRelative(0.28f) arcToRelative(3.49f, 3.49f, 0.0f, false, true, 2.45f, -6.0f) arcToRelative(3.5f, 3.5f, 0.0f, false, true, 3.5f, 3.5f) lineTo(22.0f, 6.25f) curveTo(22.0f, 4.45f, 20.54f, 3.0f, 18.75f, 3.0f) lineTo(12.5f, 3.0f) verticalLineToRelative(-0.25f) close() moveTo(6.0f, 7.75f) curveToRelative(0.0f, -0.41f, 0.34f, -0.75f, 0.75f, -0.75f) horizontalLineToRelative(4.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f) horizontalLineToRelative(-4.0f) arcTo(0.75f, 0.75f, 0.0f, false, true, 6.0f, 7.75f) close() moveTo(6.75f, 10.0f) horizontalLineToRelative(6.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f) horizontalLineToRelative(-6.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, -1.5f) close() moveTo(6.75f, 13.0f) horizontalLineToRelative(5.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f) horizontalLineToRelative(-5.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, -1.5f) close() moveTo(21.0f, 14.5f) arcToRelative(2.5f, 2.5f, 0.0f, true, true, -5.0f, 0.0f) arcToRelative(2.5f, 2.5f, 0.0f, false, true, 5.0f, 0.0f) close() moveTo(23.0f, 19.88f) curveToRelative(0.0f, 1.55f, -1.29f, 3.12f, -4.5f, 3.12f) reflectiveCurveTo(14.0f, 21.44f, 14.0f, 19.87f) verticalLineToRelative(-0.1f) curveToRelative(0.0f, -0.98f, 0.8f, -1.77f, 1.77f, -1.77f) horizontalLineToRelative(5.46f) curveToRelative(0.98f, 0.0f, 1.77f, 0.8f, 1.77f, 1.77f) verticalLineToRelative(0.1f) close() } } return _chartPerson!! } private var _chartPerson: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
3,345
compose-fluent-ui
Apache License 2.0
core/src/main/java/se/gustavkarlsson/skylight/android/core/utils/NonEmptyListUtils.kt
gustavkarlsson
128,669,768
false
null
package se.gustavkarlsson.skylight.android.core.utils import arrow.core.NonEmptyList import arrow.core.Option fun <T> List<T>.nonEmpty(): Option<NonEmptyList<T>> = NonEmptyList.fromList(this) fun <T> List<T>.nonEmptyUnsafe(): NonEmptyList<T> = NonEmptyList.fromListUnsafe(this)
0
Kotlin
2
5
6eb4ae2b31e12a6956f0a8a807ab62c6d43670a7
281
skylight-android
MIT License
model/src/main/kotlin/utils/SortedSetConverters.kt
oss-review-toolkit
107,540,288
false
null
/* * Copyright (C) 2022 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ @file:Suppress("Filename", "MatchingDeclarationName") package org.ossreviewtoolkit.model.utils import com.fasterxml.jackson.databind.util.StdConverter import java.util.SortedSet import org.ossreviewtoolkit.model.CopyrightFinding import org.ossreviewtoolkit.model.LicenseFinding import org.ossreviewtoolkit.model.Package import org.ossreviewtoolkit.model.PackageReference import org.ossreviewtoolkit.model.Project import org.ossreviewtoolkit.model.Scope import org.ossreviewtoolkit.model.SnippetFinding class CopyrightFindingSortedSetConverter : StdConverter<Set<CopyrightFinding>, SortedSet<CopyrightFinding>>() { override fun convert(value: Set<CopyrightFinding>) = value.toSortedSet(CopyrightFinding.COMPARATOR) } class LicenseFindingSortedSetConverter : StdConverter<Set<LicenseFinding>, SortedSet<LicenseFinding>>() { override fun convert(value: Set<LicenseFinding>) = value.toSortedSet(LicenseFinding.COMPARATOR) } class PackageReferenceSortedSetConverter : StdConverter<Set<PackageReference>, SortedSet<PackageReference>>() { override fun convert(value: Set<PackageReference>) = value.toSortedSet(compareBy { it.id }) } class PackageSortedSetConverter : StdConverter<Set<Package>, SortedSet<Package>>() { override fun convert(value: Set<Package>) = value.toSortedSet(compareBy { it.id }) } class ProjectSortedSetConverter : StdConverter<Set<Project>, SortedSet<Project>>() { override fun convert(value: Set<Project>) = value.toSortedSet(compareBy { it.id }) } class ScopeSortedSetConverter : StdConverter<Set<Scope>, SortedSet<Scope>>() { override fun convert(value: Set<Scope>) = value.toSortedSet(compareBy { it.name }) } class SnippetFindingSortedSetConverter : StdConverter<Set<SnippetFinding>, SortedSet<SnippetFinding>>() { override fun convert(value: Set<SnippetFinding>) = value.toSortedSet(compareBy<SnippetFinding> { it.sourceLocation.path }.thenByDescending { it.snippet.purl }) } // TODO: Add more converters to get rid of Comparable implementations that just serve sorted output.
323
Kotlin
242
1,166
c05ec084518f61e6cfe1d2f452dbd356049e2f92
2,798
ort
Apache License 2.0
src/institution/facility/FacilityStore.kt
DiSSCo
517,633,705
false
null
package org.synthesis.institution.facility import io.vertx.sqlclient.Row import io.vertx.sqlclient.SqlClient import kotlinx.coroutines.flow.toList import org.synthesis.account.UserAccountId import org.synthesis.formbuilder.DynamicForm import org.synthesis.formbuilder.FieldValue import org.synthesis.formbuilder.GroupId import org.synthesis.infrastructure.persistence.querybuilder.* import org.synthesis.infrastructure.serializer.JacksonSerializer import org.synthesis.infrastructure.serializer.Serializer import org.synthesis.institution.GRID import org.synthesis.institution.InstitutionId interface FacilityStore { suspend fun add(facility: Facility) suspend fun save(facility: Facility) suspend fun load(facilityId: FacilityId): Facility? suspend fun loadByInstitutionId(institutionId: InstitutionId): List<Facility?> } class PgFacilityStore( private val sqlClient: SqlClient, private val jacksonSerializer: Serializer = JacksonSerializer ) : FacilityStore { override suspend fun add(facility: Facility) { sqlClient.execute( insert( "institution_facilities", mapOf( "id" to facility.id.uuid, "moderator_id" to facility.moderatorId.uuid, "created_at" to facility.createdAt, "institution_id" to facility.institutionId.grid.value, "data" to jacksonSerializer.serialize(facility.form), "title" to facility.title(), "title_local" to facility.localTitle(), "images" to facility.images().toTypedArray(), "instruments" to facility.extractServices() ) ) ) } override suspend fun save(facility: Facility) { sqlClient.execute( update( "institution_facilities", mapOf( "data" to jacksonSerializer.serialize(DynamicForm(facility.form.values)), "deleted_at" to facility.deletedAt, "title" to facility.title(), "title_local" to facility.localTitle(), "images" to facility.images().toTypedArray(), "instruments" to facility.extractServices() ) ) { where { "id" eq facility.id.uuid } } ) } override suspend fun load(facilityId: FacilityId): Facility? = sqlClient.fetchOne( select("institution_facilities") { where { "id" eq facilityId.uuid } } )?.hydrate() override suspend fun loadByInstitutionId(institutionId: InstitutionId): List<Facility?> = sqlClient.fetchAll( select("institution_facilities") { where { "institution_id" eq institutionId.grid.value } } ).toList().map { it.hydrate() } private fun Row.hydrate() = Facility( id = FacilityId(getUUID("id")), institutionId = InstitutionId(GRID(getString("institution_id"))), moderatorId = UserAccountId(getUUID("moderator_id")), deletedAt = getLocalDateTime("deleted_at"), form = jacksonSerializer.unserialize(getString("data"), DynamicForm::class.java), createdAt = getLocalDateTime("created_at"), images = getArrayOfStrings("images").toMutableList() ) private fun Facility.extractServices(): String = form.groupValues(GroupId("instruments")).mapNotNull { (it.value.value as? FieldValue.Text)?.value }.joinToString(",") }
0
Kotlin
0
0
a2277d627647d1669c3714da455f37fe6c2e93ae
3,573
elvis-backend
Apache License 2.0
src/main/kotlin/com/intworkers/application/service/schoolsystem/SocialWorkerServiceImpl.kt
bw-international-school-social-worker
193,610,954
true
{"Kotlin": 84025}
package com.intworkers.application.service.schoolsystem import com.intworkers.application.exception.ResourceNotFoundException import com.intworkers.application.model.user.SocialWorker import com.intworkers.application.repository.schoolsystem.SchoolRepository import com.intworkers.application.repository.schoolsystem.SocialWorkerRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.Pageable import org.springframework.data.jpa.repository.Modifying import org.springframework.stereotype.Component import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Component @Service(value = "socialWorkerService") class SocialWorkerServiceImpl : SocialWorkerService { @Autowired private lateinit var socialWorkerRepository: SocialWorkerRepository @Autowired private lateinit var schoolRepository: SchoolRepository override fun findById(id: Long): SocialWorker { return socialWorkerRepository.findById(id) .orElseThrow { ResourceNotFoundException("Couldn't find social worker with id $id") } } override fun findAll(pageable: Pageable): MutableList<SocialWorker> { val workers = mutableListOf<SocialWorker>() socialWorkerRepository.findAll().iterator().forEachRemaining { workers.add(it) } return workers } @Transactional @Modifying override fun save(socialWorker: SocialWorker): SocialWorker { val newWorker = SocialWorker() if (socialWorker.user != null) { newWorker.workerid = socialWorker.workerid newWorker.user = socialWorker.user newWorker.email = socialWorker.email newWorker.firstName = socialWorker.firstName newWorker.lastName = socialWorker.lastName newWorker.phone = socialWorker.phone newWorker.photoUrl = socialWorker.photoUrl } else throw ResourceNotFoundException("Not a valid worker") return socialWorkerRepository.save(newWorker) } @Transactional @Modifying override fun update(socialWorker: SocialWorker, id: Long): SocialWorker { val updatedWorker = socialWorkerRepository.findById(id) .orElseThrow { ResourceNotFoundException("Couldn't find social worker with id $id") } if (socialWorker.email != null) updatedWorker.email = socialWorker.email if (socialWorker.firstName != null) updatedWorker.firstName = socialWorker.firstName if (socialWorker.lastName != null) updatedWorker.lastName = socialWorker.lastName if (socialWorker.phone != null) updatedWorker.phone = socialWorker.phone if (socialWorker.photoUrl != null) updatedWorker.photoUrl = socialWorker.photoUrl if (socialWorker.organization != null) updatedWorker.organization = socialWorker.organization return socialWorkerRepository.save(updatedWorker) } @Transactional @Modifying override fun delete(id: Long) { if (socialWorkerRepository.findById(id).isPresent) { socialWorkerRepository.deleteById(id) } else throw ResourceNotFoundException("Couldn't find social worker with id $id") } @Transactional override fun assignWorkerToSchool(workerId: Long, schoolId: Long) { if (socialWorkerRepository.findById(workerId).isPresent && schoolRepository.findById(schoolId).isPresent) { socialWorkerRepository.assignWorkerToSchool(workerId, schoolId) } } @Transactional override fun removeWorkerFromSchool(workerId: Long, schoolId: Long) { socialWorkerRepository.removeWorkerFromSchool(workerId, schoolId) } override fun leaveOrg(id: Long) { val worker = socialWorkerRepository.findById(id) .orElseThrow { ResourceNotFoundException("Couldn't find worker with id $id") } worker.organization = null socialWorkerRepository.save(worker) } }
1
Kotlin
2
0
eb876f9862af3b1731788e67952f05850ce96304
3,995
international-school-socialworker-BE
MIT License
library/src/jsTest/kotlin/LayoutTest.kt
lightningkite
778,386,343
false
{"Kotlin": 2224994, "Swift": 7449, "Ruby": 4925, "CSS": 4562, "HTML": 4084, "HCL": 880, "JavaScript": 302, "Objective-C": 142, "C": 104, "Shell": 49}
package com.lightningkite.kiteui import com.lightningkite.kiteui.models.Theme import com.lightningkite.kiteui.navigation.render import com.lightningkite.kiteui.views.RView import com.lightningkite.kiteui.views.direct.stack import kotlin.test.Test class LayoutTest { @Test fun test() { val s = LayoutsTestScreen() lateinit var root: RView root(Theme(id = "unitTest")) { root = stack { s.render(this) } } println(root.screenRectangle()) s.checks.forEach { it() } } }
3
Kotlin
0
2
58ee76ab3e8e7cab71e65a18c302367c6a641da5
567
kiteui
Apache License 2.0
ospf-kotlin-framework-gantt-scheduling/gantt-scheduling-domain-task-scheduling-context/gantt-scheduling-domain-task-compilation-context/src/main/fuookami/ospf/kotlin/framework/gantt_scheduling/domain/task_compilation/service/limits/TaskCostMinimization.kt
fuookami
359,831,793
false
{"Kotlin": 1921031, "Python": 6629}
package fuookami.ospf.kotlin.framework.gantt_scheduling.domain.task_compilation.service.limits import fuookami.ospf.kotlin.utils.functional.* import fuookami.ospf.kotlin.core.frontend.model.mechanism.* import fuookami.ospf.kotlin.framework.gantt_scheduling.domain.task.model.* import fuookami.ospf.kotlin.framework.gantt_scheduling.domain.task_compilation.model.* class TaskCostMinimization< Args : GanttSchedulingShadowPriceArguments<E, A>, E : Executor, A : AssignmentPolicy<E> >( private val compilation: IterativeTaskCompilation<*, *, E, A>, override val name: String = "task_cost_minimization" ) : AbstractGanttSchedulingCGPipeline<Args, E, A> { override fun invoke(model: LinearMetaModel): Try { model.minimize(compilation.taskCost, "task cost") return ok } }
0
Kotlin
0
2
ee15667db4a8d3789cb1fd3df772717971e83a31
813
ospf-kotlin
Apache License 2.0
app/src/main/java/com/jammin/myapplication/feature/signin/vm/SignInVM.kt
Junction2022
526,564,786
false
{"Kotlin": 140145}
package com.jammin.myapplication.feature.signin.vm import android.app.Application import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.jammin.myapplication.R import com.jammin.myapplication.data.model.request.auth.SignInRequest import com.jammin.myapplication.data.model.response.auth.SignInResponse import com.jammin.myapplication.data.repository.AuthRepository import com.jammin.myapplication.feature.signin.SignInEvent import com.jammin.myapplication.feature.signin.SignInTextFieldState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SignInVM @Inject constructor( application: Application, private val authRepository: AuthRepository ) : AndroidViewModel(application) { private val _eventFlow = MutableSharedFlow<UiEvent>() val eventFlow = _eventFlow.asSharedFlow() private val _signInId = mutableStateOf( SignInTextFieldState( hint = application.getString(R.string.hint_id) ) ) val signInId: State<SignInTextFieldState> = _signInId private val _signInPassword = mutableStateOf( SignInTextFieldState( hint = application.getString(R.string.hint_password) ) ) val signInPassword: State<SignInTextFieldState> = _signInPassword fun onEvent(event: SignInEvent) { when (event) { is SignInEvent.EnteredId -> { _signInId.value = signInId.value.copy( text = event.value ) } is SignInEvent.EnteredPassword -> { _signInPassword.value = signInPassword.value.copy( text = event.value ) } is SignInEvent.OkEvent -> { viewModelScope.launch { authRepository.signIn( SignInRequest( id = signInId.value.text, password = signInPassword.value.text, ) ) .onSuccess { _eventFlow.emit(UiEvent.SuccessSignIn(it)) } .onFailure { _eventFlow.emit(UiEvent.FailSignIn) } } } } } sealed class UiEvent { data class SuccessSignIn(val signInResponse: SignInResponse) : UiEvent() object FailSignIn : UiEvent() } }
4
Kotlin
0
1
5cefcbb90842b2a3ef87d6533be6093a18f375d1
2,638
PaperIn_Android
Apache License 2.0
pleo-antaeus-rest/src/main/kotlin/io/pleo/antaeus/rest/AntaeusRest.kt
juliuskrah
202,206,554
true
{"Kotlin": 43888, "Shell": 861, "Dockerfile": 249}
/* Configures the rest app along with basic exception handling and URL endpoints. */ package io.pleo.antaeus.rest import io.javalin.Javalin import io.javalin.apibuilder.ApiBuilder.* import io.pleo.antaeus.core.exceptions.EntityNotFoundException import io.pleo.antaeus.core.exceptions.JobExistsException import io.pleo.antaeus.core.exceptions.JobNotFoundException import io.pleo.antaeus.core.services.CustomerService import io.pleo.antaeus.core.services.InvoiceService import io.pleo.antaeus.models.Job import io.pleo.antaeus.schedule.services.SchedulingService import mu.KotlinLogging private val logger = KotlinLogging.logger {} class AntaeusRest ( private val invoiceService: InvoiceService, private val customerService: CustomerService, private val schedulingService: SchedulingService ) : Runnable { override fun run() { app.start(7000) } // Set up Javalin rest app private val app = Javalin .create() .apply { // InvoiceNotFoundException: return 404 HTTP status code exception(EntityNotFoundException::class.java) { _, ctx -> ctx.status(404) } // JobNotFoundException: return 404 HTTP status code exception(JobNotFoundException::class.java) { _, ctx -> ctx.status(404) } // JobExistsException: return 409 HTTP status code exception(JobExistsException::class.java) { _, ctx -> ctx.status(409) } // Unexpected exception: return HTTP 500 exception(Exception::class.java) { e, _ -> logger.error(e) { "Internal server error" } } // On 404: return message error(404) { ctx -> ctx.json("not found") } } init { // Set up URL endpoints for the rest app app.routes { path("rest") { // Route to check whether the app is running // URL: /rest/health get("health") { it.json("ok") } // V1 path("v1") { path("invoices") { // URL: /rest/v1/invoices get { it.json(invoiceService.fetchAll()) } // URL: /rest/v1/invoices/{:id} get(":id") { it.json(invoiceService.fetch(it.pathParam("id").toInt())) } } path("customers") { // URL: /rest/v1/customers get { it.json(customerService.fetchAll()) } // URL: /rest/v1/customers/{:id} get(":id") { it.json(customerService.fetch(it.pathParam("id").toInt())) } } path("jobs") { // URL: /rest/v1/jobs get { it.json(schedulingService.fetchAll()) } // URL: /rest/v1/jobs post { val job: Job = it.body<Job>() it.json(schedulingService.createJob(job)) } // URL: /rest/v1/jobs/ put { val job: Job = it.body<Job>() it.json(schedulingService.updateJob(job)) } } } } } } }
0
Kotlin
0
0
48cd6c18adaacc4876fd65b58248ca119a9fb54b
3,716
antaeus
Creative Commons Zero v1.0 Universal
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/GroupOrbits.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: GroupOrbits * * Full name: System`GroupOrbits * * GroupOrbits[group, {p , …}] returns the orbits of the points p under the action of the elements of group. * 1 i * GroupOrbits[group, {p , …}, f] finds the orbits under the group action given by a function f. * Usage: 1 * * Options: None * * Protected * Attributes: ReadProtected * * local: paclet:ref/GroupOrbits * Documentation: web: http://reference.wolfram.com/language/ref/GroupOrbits.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun groupOrbits(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("GroupOrbits", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,274
mathemagika
Apache License 2.0
src/test/kotlin/fundamental/UFTest.kt
xmmmmmovo
280,634,710
false
null
/* * Copyright (c) 2021. xmmmmmovo */ package fundamental import ds.UF import edu.princeton.cs.algs4.QuickUnionUF import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* import org.junit.platform.commons.logging.LoggerFactory import java.io.File internal class UFTest { private var N: Int = 0 private val pl: MutableList<Int> private val ql: MutableList<Int> private val mediumUF = File("./data/mediumUF.txt").readLines().also { pl = MutableList(it.size) { 0 } ql = MutableList(it.size) { 0 } }.forEachIndexed { index, it -> val sps = it.split(" ") if (sps.size == 1) { N = sps[0].toInt() } else { pl[index] = sps[0].toInt() ql[index] = sps[1].toInt() } } companion object { private val log = LoggerFactory.getLogger(UFTest::class.java) @BeforeAll @JvmStatic fun before() { log.info { "UFTest start" } } @AfterAll @JvmStatic fun after() { log.info { "UFTest end" } } } @Test fun unionFindTest() { log.info { "unionFindTest testing" } log.info { "${pl.size}" } val uf = UF(N) val stduf = QuickUnionUF(N) repeat(pl.size) { assertEquals( uf.connected(pl[it], ql[it]), stduf.connected(pl[it], ql[it]) ) if (uf.connected(pl[it], ql[it])) return uf.union(pl[it], ql[it]) stduf.union(pl[it], ql[it]) } } }
0
Kotlin
0
0
94da0519cf2b8d8a9b42b4aea09caf50d9732599
1,686
Algorithms4thEditionKotlinSolutions
Apache License 2.0
src/main/kotlin/de/sambalmueslie/hll/adapter/rest/api/HllVipMgtAPI.kt
Black-Forrest-Development
503,521,992
false
null
package de.sambalmueslie.hll.adapter.rest.api import io.micronaut.security.authentication.Authentication interface HllVipMgtAPI { fun getNumVipSlots(auth: Authentication, serverId: Long): Int fun setNumVipSlots(auth: Authentication, serverId: Long, max: Int) : Any fun getVipIds(auth: Authentication, serverId: Long): Set<String> fun vipAdd(auth: Authentication, serverId: Long, steamId: String, description: String = "") : Any fun vipRemove(auth: Authentication, serverId: Long, steamId: String) : Any }
0
Kotlin
0
1
502ac7d343314124d473d2cff15d8b4e99643439
528
hll-adapter
Apache License 2.0
datacapture/src/main/java/com/google/android/fhir/datacapture/views/QuestionnaireItemEditTextViewHolderFactory.kt
google
247,977,633
false
null
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.views import android.content.Context import android.text.Editable import android.view.View import android.view.View.FOCUS_DOWN import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import androidx.core.widget.doAfterTextChanged import com.google.android.fhir.datacapture.R import com.google.android.fhir.datacapture.localizedFlyoverSpanned import com.google.android.fhir.datacapture.validation.ValidationResult import com.google.android.fhir.datacapture.validation.getSingleStringValidationMessage import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import org.hl7.fhir.r4.model.QuestionnaireResponse internal abstract class QuestionnaireItemEditTextViewHolderFactory : QuestionnaireItemViewHolderFactory(R.layout.questionnaire_item_edit_text_view) { abstract override fun getQuestionnaireItemViewHolderDelegate(): QuestionnaireItemEditTextViewHolderDelegate } internal abstract class QuestionnaireItemEditTextViewHolderDelegate( private val rawInputType: Int, private val isSingleLine: Boolean ) : QuestionnaireItemViewHolderDelegate { private lateinit var header: QuestionnaireItemHeaderView private lateinit var textInputLayout: TextInputLayout private lateinit var textInputEditText: TextInputEditText override lateinit var questionnaireItemViewItem: QuestionnaireItemViewItem override fun init(itemView: View) { header = itemView.findViewById(R.id.header) textInputLayout = itemView.findViewById(R.id.text_input_layout) textInputEditText = itemView.findViewById(R.id.text_input_edit_text) textInputEditText.setRawInputType(rawInputType) textInputEditText.isSingleLine = isSingleLine textInputEditText.doAfterTextChanged { editable: Editable? -> questionnaireItemViewItem.singleAnswerOrNull = getValue(editable.toString()) onAnswerChanged(textInputEditText.context) } } override fun bind(questionnaireItemViewItem: QuestionnaireItemViewItem) { header.bind(questionnaireItemViewItem.questionnaireItem) textInputLayout.hint = questionnaireItemViewItem.questionnaireItem.localizedFlyoverSpanned textInputEditText.setText(getText(questionnaireItemViewItem.singleAnswerOrNull)) textInputEditText.setOnFocusChangeListener { view, focused -> if (!focused) { (view.context.applicationContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(view.windowToken, 0) } } // Override `setOnEditorActionListener` to avoid crash with `IllegalStateException` if it's not // possible to move focus forward. // See // https://stackoverflow.com/questions/13614101/fatal-crash-focus-search-returned-a-view-that-wasnt-able-to-take-focus/47991577 textInputEditText.setOnEditorActionListener { view, actionId, _ -> if (actionId != EditorInfo.IME_ACTION_NEXT) { false } view.focusSearch(FOCUS_DOWN)?.requestFocus(FOCUS_DOWN) ?: false } } override fun displayValidationResult(validationResult: ValidationResult) { textInputLayout.error = if (validationResult.getSingleStringValidationMessage() == "") null else validationResult.getSingleStringValidationMessage() } override fun setReadOnly(isReadOnly: Boolean) { textInputLayout.isEnabled = !isReadOnly textInputEditText.isEnabled = !isReadOnly } /** Returns the answer that should be recorded given the text input by the user. */ abstract fun getValue( text: String ): QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent? /** * Returns the text that should be displayed in the [TextInputEditText] from the existing answer * to the question (may be input by the user or previously recorded). */ abstract fun getText( answer: QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent? ): String }
259
Kotlin
154
231
fd9e75c66a75864f6a69802f4098efe461cc6d5a
4,589
android-fhir
Apache License 2.0
app/src/main/java/com/webianks/expensive/util/UiUtils.kt
webianks
186,256,631
false
null
package com.webianks.expensive.util import android.content.Context import android.content.res.Resources import android.util.DisplayMetrics import android.view.View import android.view.inputmethod.InputMethodManager import com.webianks.expensive.R import kotlin.math.ceil fun hideKeyboard(view: View) { try { val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } catch (ignored: Exception) { } } fun getSkeletonRowCount(context: Context): Int { val pxHeight = getDeviceHeight(context) val skeletonRowHeight = context.resources.getDimension(R.dimen.height_skeleton_expense_layout) return ceil(pxHeight / skeletonRowHeight.toDouble()).toInt() } fun getDeviceHeight(context: Context): Int { val resources: Resources = context.resources val metrics: DisplayMetrics = resources.displayMetrics return metrics.heightPixels }
0
Kotlin
5
23
13719ed6e4ce6d91aea904f7b0deadfcae574486
962
Expensive
MIT License
backend/services/WarehouseService/src/main/kotlin/com/arconsis/presentation/http/products/ProductsResource.kt
arconsis
506,954,248
false
{"Kotlin": 284198, "HCL": 70387, "HTML": 27287, "Dockerfile": 10124, "Go": 8432, "TypeScript": 7350, "PLpgSQL": 3157, "JavaScript": 2138, "Shell": 1891, "Smarty": 1371, "Java": 697}
package com.arconsis.presentation.http.products import com.arconsis.domain.products.Product import com.arconsis.domain.products.ProductsService import com.arconsis.presentation.http.products.dto.request.CreateProductDto import com.arconsis.presentation.http.products.dto.request.toCreateProduct import com.arconsis.presentation.http.products.dto.response.ListProductsPaginationResponseDto import com.arconsis.presentation.http.products.dto.response.ListProductsResponseDto import io.smallrye.mutiny.Uni import java.util.* import javax.enterprise.context.ApplicationScoped import javax.ws.rs.* @ApplicationScoped @Path("/products") class ProductsResource(val productsService: ProductsService) { @POST @Path("/") fun createProduct(createProductDto: CreateProductDto): Uni<Product> { return productsService.createProduct(createProductDto.toCreateProduct()) } @GET @Path("/") fun listProducts( @QueryParam("offset") offset: Int?, @QueryParam("limit") limit: Int?, @QueryParam("search") search: String? ): Uni<ListProductsResponseDto> { val (queryOffset, queryLimit) = getPaginationSize(offset, limit) return productsService.listProducts(queryOffset, queryLimit, search) .map { (products, total) -> ListProductsResponseDto( data = products, pagination = ListProductsPaginationResponseDto( offset = queryOffset, limit = queryLimit, total = total ) ) } } @GET @Path("/{productId}") fun getProduct(@PathParam("productId") productId: UUID): Uni<Product?> { return productsService.getProduct(productId) } private fun getPaginationSize(offset: Int?, limit: Int?): Pair<Int, Int> { val queryOffset = offset ?: DEFAULT_OFFSET val queryLimit = when (limit) { null -> DEFAULT_LIMIT in MIN_LIMIT..MAX_LIMIT -> limit else -> DEFAULT_LIMIT } return queryOffset to queryLimit } companion object { private const val MAX_LIMIT = 100 private const val MIN_LIMIT = 1 private const val DEFAULT_LIMIT = 33 private const val DEFAULT_OFFSET = 0 } }
9
Kotlin
1
3
384eb68907ef2e975904bf392a9ece9d0d0754f8
2,030
ecommerce
Apache License 2.0
app/src/main/java/com/rlogical/data/DataRepository.kt
ajay-android
321,983,139
false
null
package com.rlogical.data import com.rlogical.ui.component.login.LoginResponseNew import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import javax.inject.Inject import kotlin.coroutines.CoroutineContext class DataRepository @Inject constructor( private val ioDispatcher: CoroutineContext ) : DataRepositorySource { override suspend fun doLogin(response: LoginResponseNew): Flow<LoginResponseNew> { return flow { //val res : LoginResponseNew = localRepository.doLogin(response) //res.getUser()?.let { insert(it) } //response.getUser()?.let { userDao.insert(it) } emit(response) }.flowOn(ioDispatcher) } }
0
Kotlin
0
0
5aef2d6810b268a081f0431a058bfac2addb312b
752
DemoTask-Ajay
Apache License 2.0
implementation/src/main/kotlin/io/github/tomplum/aoc/map/lava/LavaIslandMap.kt
TomPlum
724,225,748
false
{"Kotlin": 141244}
package io.github.tomplum.aoc.map.lava import io.github.tomplum.libs.math.map.AdventMap2D import io.github.tomplum.libs.math.point.Point2D class LavaIslandMap(data: List<String>): AdventMap2D<LavaIslandTile>() { init { var x = 0 var y = 0 data.forEach { row -> row.forEach { column -> val tile = LavaIslandTile(column) val position = Point2D(x, y) addTile(position, tile) x++ } x = 0 y++ } } private fun String.parseAsBinaryString(): Int = Integer.parseInt(this, 2) fun findInflectionPoints(): PatternAnalysis { val columns = (xMin()!!..xMax()!!).map { x -> (yMin()!!..yMax()!!).map { y -> getTile(Point2D(x, y)) } }.map { values -> values.map { tile -> if (tile.isRock()) 1 else 0 }.joinToString("").parseAsBinaryString() } val rows = (yMin()!!..yMax()!!).map { y -> (xMin()!!..xMax()!!).map { x -> getTile(Point2D(x, y)) } }.map { values -> values.map { tile -> if (tile.isRock()) 1 else 0 }.joinToString("").parseAsBinaryString() } val columnToLeftOfReflectionLine = columns.scanReflections() val rowsAboveReflectionLine = rows.scanReflections() if (rowsAboveReflectionLine != null && columnToLeftOfReflectionLine != null) { return if (rowsAboveReflectionLine > columnToLeftOfReflectionLine) { PatternAnalysis(ReflectionType.HORIZONTAL, rowsAboveReflectionLine) } else { PatternAnalysis(ReflectionType.VERTICAL, columnToLeftOfReflectionLine) } } if (columnToLeftOfReflectionLine == null && rowsAboveReflectionLine != null) { return PatternAnalysis(ReflectionType.HORIZONTAL, rowsAboveReflectionLine) } if (columnToLeftOfReflectionLine != null) { return PatternAnalysis(ReflectionType.VERTICAL, columnToLeftOfReflectionLine) } else { throw IllegalStateException("") } } private fun List<Int>.scanReflections() = this.let { val chunks = this.windowed(2).mapIndexed { i, list -> Pair(Pair(i, i + 1), Pair(list[0], list[1])) } val centerPoints = chunks.filter { (_, values) -> values.first == values.second } centerPoints.map { (indices, _) -> var leftIndex = indices.first var rightIndex = indices.second var isReflectiveToEdge = false var isReflective = true while(isReflective && leftIndex >= 0 && rightIndex <= this.lastIndex) { if (this[leftIndex] == this[rightIndex]) { if (leftIndex == 0 || rightIndex == this.lastIndex) { isReflectiveToEdge = true } leftIndex -= 1 rightIndex += 1 } else { isReflective = false } } if (isReflectiveToEdge) { indices.second } else null }.find { it != null } } data class PatternAnalysis(val reflectionType: ReflectionType, val value: Int) enum class ReflectionType { HORIZONTAL, VERTICAL } }
0
Kotlin
0
1
d1f941a3c5bacd126177ace6b9f576c9af07fed6
3,383
advent-of-code-2023
Apache License 2.0
plugins/amazonq/codewhisperer/jetbrains-community/src/software/aws/toolkits/jetbrains/services/codewhisperer/popup/handlers/CodeWhispererEditorActionHandler.kt
aws
91,485,909
false
{"Kotlin": 7507266, "TypeScript": 132101, "C#": 97693, "Vue": 47529, "Java": 19596, "JavaScript": 12450, "HTML": 5878, "Python": 2939, "Shell": 2920, "Dockerfile": 2209, "SCSS": 2045, "CSS": 1827, "PowerShell": 386, "Batchfile": 77}
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.codewhisperer.popup.handlers import com.intellij.openapi.editor.actionSystem.EditorActionHandler import software.aws.toolkits.jetbrains.services.codewhisperer.model.InvocationContext import software.aws.toolkits.jetbrains.services.codewhisperer.model.SessionContextNew abstract class CodeWhispererEditorActionHandler(val states: InvocationContext) : EditorActionHandler() abstract class CodeWhispererEditorActionHandlerNew(val sessionContext: SessionContextNew) : EditorActionHandler()
519
Kotlin
220
757
a81caf64a293b59056cef3f8a6f1c977be46937e
652
aws-toolkit-jetbrains
Apache License 2.0
lib/src/main/java/com/kirkbushman/araw/fetcher/Fetcher.kt
shakil807g
207,283,602
true
{"Kotlin": 212633}
package com.kirkbushman.araw.fetcher import com.kirkbushman.araw.http.base.Listing abstract class Fetcher<T, E>( private var limit: Int ) { companion object { const val DEFAULT_LIMIT = 25 } private var currentPage = 0 private var itemsCount = 0 private var currentAfter = "" private var currentBefore = "" abstract fun onFetching(forward: Boolean = true, dirToken: String): Listing<E>? abstract fun onMapResult(pagedData: Listing<E>?): List<T> fun fetchNext(): List<T> { val pagedData = onFetching(true, currentAfter) currentPage++ itemsCount = limit * currentPage currentAfter = pagedData?.after ?: "" currentBefore = pagedData?.before ?: "" return onMapResult(pagedData) } fun fetchPrevious(): List<T> { if (!hasStarted() || !hasPrevious()) { return listOf() } val pagedData = onFetching(false, currentBefore) currentPage-- itemsCount = limit * currentPage currentAfter = pagedData?.after ?: "" currentBefore = pagedData?.before ?: "" return onMapResult(pagedData) } fun hasStarted(): Boolean { return currentPage > 0 } fun hasNext(): Boolean { if (!hasStarted()) { return false } return currentAfter != "" } fun hasPrevious(): Boolean { if (!hasStarted()) { return false } return currentBefore != "" } fun getLimit(): Int { return limit } fun getPageNum(): Int { return currentPage } fun getCount(): Int { return itemsCount } fun setLimit(newLimit: Int) { limit = newLimit reset() } fun reset() { currentPage = 0 itemsCount = 0 currentAfter = "" currentBefore = "" } }
0
null
0
0
43ac0d78ddd5e6218788e6c04c3ad8ace61884c2
1,904
ARAW
MIT License
domain/src/main/java/com/spiderbiggen/manga/domain/usecase/favorite/HasFavorites.kt
spiderbiggen
624,650,535
false
{"Kotlin": 130288}
package com.spiderbiggen.manga.domain.usecase.favorite import com.spiderbiggen.manga.domain.model.AppError import com.spiderbiggen.manga.domain.model.Either fun interface HasFavorites { operator fun invoke(): Either<Boolean, AppError> }
1
Kotlin
0
0
6a76ab9228b833aac0186d97004161fc26c91acc
243
manhwa-reader
MIT License
modules/cynorkis/src/main/kotlin/cynorkis/core/ConnectionRequest.kt
eEQK
340,498,973
false
null
package cynorkis.core class ConnectionRequest( val method: String, val url: String, val headers: List<String> = listOf(), val body: ByteArray = byteArrayOf(), )
0
Kotlin
0
0
3c1ce18183089608a584dc6891953bb6d33e54c6
178
cynorkis
The Unlicense
src/main/kotlin/com/github/mikowiec/eplaza/frontend/service/impl/GoodsCommentServiceImpl.kt
mikowiec
147,556,429
false
null
package com.github.mikowiec.eplaza.frontend.service.impl import com.github.mikowiec.eplaza.frontend.dao.GoodsCommentDao import com.github.mikowiec.eplaza.frontend.service.GoodsCommentService import com.github.mikowiec.eplaza.model.GoodsComment import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class GoodsCommentServiceImpl : GoodsCommentService { @Autowired private val goodsCommentDao: GoodsCommentDao? = null override val count: Int get() = goodsCommentDao!!.count override fun findByGoodsId(goodsId: Int): List<GoodsComment> { return goodsCommentDao!!.findByGoodsId(goodsId) } override fun findByGoodsIdAndPage(goodsId: Int, page: Int, pageSize: Int): List<GoodsComment> { return goodsCommentDao!!.findByGoodsIdAndPage(goodsId, page, pageSize) } override fun findByGoodsIdAndCommentLevel(goodsId: Int, commentLevel: Int): List<GoodsComment> { return goodsCommentDao!!.findByGoodsIdAndCommentLevel(goodsId, commentLevel) } override fun findByGoodsIdAndCommentLevelAndPage(goodsId: Int, commentLevel: Int, page: Int, pageSize: Int): List<GoodsComment> { return goodsCommentDao!!.findByGoodsIdAndCommentLevelAndPage(goodsId, commentLevel, page, pageSize) } override fun getCountByGoodsId(goodsId: Int): Int { return goodsCommentDao!!.getCountByGoodsId(goodsId) } override fun getCountByCommentLevel(commentLevel: Int): Int { return goodsCommentDao!!.getCountByCommentLevel(commentLevel) } override fun getCountByGoodsIdAndCommentLevel(goodsId: Int, commentLevel: Int): Int { return goodsCommentDao!!.getCountByGoodsIdAndCommentLevel(goodsId, commentLevel) } override fun save(goodsComment: GoodsComment): Int { return goodsCommentDao!!.save(goodsComment) } }
0
Kotlin
0
0
63166c0d909f955b4838e65d09f7a97ba9bd8913
1,887
eplaza-api
MIT License
app/src/main/java/app/storytel/candidate/com/features/details/DetailsPresenter.kt
Mikkelet
384,780,999
true
{"Kotlin": 20032, "Java": 1133}
package app.storytel.candidate.com.features.details import androidx.lifecycle.lifecycleScope import app.storytel.candidate.com.models.Comment import app.storytel.candidate.com.utils.base.BasePresenterImpl import app.storytel.candidate.com.utils.networking.ApiService import app.storytel.candidate.com.utils.networking.NetworkUtils.future import app.storytel.candidate.com.utils.networking.NetworkUtils.onError import app.storytel.candidate.com.utils.networking.NetworkUtils.onSuccess import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.lang.Exception import javax.inject.Inject class DetailsPresenter @Inject constructor( private val apiService: ApiService ) : BasePresenterImpl<DetailsContract.View>(),DetailsContract.Presenter { override fun getComments(id: Int) { getView()?.lifecycleScope?.launch { future { apiService.getComments("$id") } .onSuccess { onData(it) } .onError { onError(it) } } } private fun onData(comments:List<Comment>) { if (comments.size > 3) getView()?.onCommentsLoaded(comments.take(3)) else getView()?.onCommentsLoaded(comments) } private fun onError(e:Exception){ getView()?.onError(e) } }
0
Kotlin
0
0
1576397dff2fb72d6aad21dbbecbf813430d02a0
1,324
AndroidJobCandidate
Apache License 2.0
src/main/kotlin/com/refinedmods/refinedstorage/data/sync/BiSyncedData.kt
thinkslynk
290,596,653
true
{"Kotlin": 695976, "Shell": 456}
package com.refinedmods.refinedstorage.data.sync import com.refinedmods.refinedstorage.data.sync.Syncable.Companion.byteBuffers import com.refinedmods.refinedstorage.extensions.getCustomLogger import java.lang.ref.WeakReference import net.fabricmc.fabric.api.network.PacketContext import net.minecraft.entity.player.PlayerEntity import net.minecraft.network.PacketByteBuf import net.minecraft.util.Identifier /** * Watches underlying data for changes, from either the * client or server, and ensures both parties are in sync. * NOTE: Since there is no single source of truth, the final * synced value may be an unexpected value. Consider using * `S2CSyncedData` or `C2SSyncedData` instead. */ open class BiSyncedData<T>( override val identifier: Identifier, override val isClient: Boolean, protected var internalData: T, protected val player: PlayerEntity ) : Syncable<T>, SimpleObserver where T: Trackable<T>, T: SimpleObservable { override val observers: HashSet<WeakReference<SimpleObserver>> = hashSetOf() companion object{ protected val log = getCustomLogger(BiSyncedData::class) } init { internalData.observers.add(getReference()) } override fun onUpdate() { // Notify our lister on this side, if we have anyone listening this.notifyObservers() // Send data to server send() } private fun getReference(): WeakReference<SimpleObserver> { return WeakReference(this) } override var data: T get() = internalData set(value) { // Store what we had val old = internalData // Set new value internalData = value // Register for changes to the new object internalData.observers.add(getReference()) // Send to server if the new object is actually different, otherwise save the bandwidth if(old != value) send() // Notify our lister on this side, if we have anyone listening notifyObservers() } override fun send() { val byteBuffer = byteBuffers.buffer() val buf = PacketByteBuf(byteBuffer) internalData.getSerializer().write(buf, internalData) when(isClient) { true -> getClientRegistry().sendToServer(identifier, buf) false -> getServerRegistry().sendToPlayer(player, identifier, buf) } } override fun accept(ctx: PacketContext, buf: PacketByteBuf) { internalData = internalData.getSerializer().read(buf) if (observers.isNotEmpty()) { ctx.taskQueue.execute { notifyObservers() } } } override fun register() { when(isClient) { true -> getClientRegistry().register(identifier, this) false -> getServerRegistry().register(identifier, this) } } override fun unregister() { when(isClient) { true -> getClientRegistry().unregister(identifier) false -> getServerRegistry().unregister(identifier) } } }
1
Kotlin
0
2
c92afa51af0e5e08caded00882f91171652a89e3
3,108
refinedstorage
MIT License
android-init-project/src/main/java/com/github/hyogeunpark/android_init_project/extention/ContextExtensions.kt
hyogeunpark
289,185,616
false
null
package com.github.hyogeunpark.android_init_project.extention import android.app.Activity import android.content.Context import android.content.DialogInterface import android.content.Intent import android.util.TypedValue import android.view.View import android.widget.Toast import androidx.core.content.ContextCompat import androidx.viewbinding.ViewBinding import com.github.hyogeunpark.android_init_project.R import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar /** * @param target : 이동할 화면의 class */ fun Context.moveToPage(target: Class<out Activity>) { this.startActivity(Intent(this, target)) } /** * @param target : 이동할 화면의 intent */ fun Context.moveToPage(target: Intent) { this.startActivity(target) } /** * @param dp : dp 값 * @return dp를 px로 변환한 값 */ fun Context.dpToPx(dp: Int): Int { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), resources.displayMetrics).toInt() } /** * @param colorId : resource id * @return color */ fun Context.getResourceColor(colorId: Int) = ContextCompat.getColor(this, colorId) /** * @param message : 토스트에 표시할 메시지 */ fun Context.showToast(message: String?) { if (message.isNullOrEmpty()) return Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } /** * @param view : 스낵바를 띄울 view * @param message : 스낵바에 표시할 메시지 */ fun Context.showSnackbar(view: View?, message: String?) { if (view == null || message.isNullOrEmpty()) return Snackbar.make(view, message, Snackbar.LENGTH_SHORT).show() } /** * @param message : 스낵바에 표시할 메시지 */ fun ViewBinding.showSnackbar(message: String?) { if (message.isNullOrEmpty()) return Snackbar.make(this.root, message, Snackbar.LENGTH_SHORT).show() } /** * @param title : dialog 제목 * @param contents : dialog 내용 * @param positiveText : positive 버튼 텍스트 * @param positiveOnClickListener : positive 버튼 클릭 리스너 * @param negativeText : negative 버튼 텍스트 * @param negativeOnClickListener : negative 버튼 클릭 리스너 */ fun Context.showDialog(title: String? = "", contents: String? = "", positiveText: String? = "", positiveOnClickListener: DialogInterface.OnClickListener? = null, negativeText: String? = "", negativeOnClickListener: DialogInterface.OnClickListener? = null) { val dialogBuilder = MaterialAlertDialogBuilder(this, R.style.AlertDialogTheme) // 타이틀 if (!title.isNullOrEmpty()) dialogBuilder.setTitle(title) // 내용 if (!contents.isNullOrEmpty()) dialogBuilder.setMessage(contents) // 확인 버튼 if (!positiveText.isNullOrEmpty()) dialogBuilder.setPositiveButton(positiveText, positiveOnClickListener) // 취소 버튼 if (!negativeText.isNullOrEmpty()) dialogBuilder.setNegativeButton(negativeText, negativeOnClickListener) dialogBuilder.show() }
0
Kotlin
0
0
081c20d94d920a2d4fcab4750abbe11a975f91a8
2,805
android-init-project
MIT License
build-logic/convention/src/main/java/com/naveenapps/expensemanager/buildsrc/extensions/CompilerExt.kt
nkuppan
536,435,007
false
{"Kotlin": 1033814}
package com.naveenapps.expensemanager.buildsrc.extensions import com.android.build.api.dsl.CommonExtension import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.kotlin.dsl.provideDelegate import org.gradle.kotlin.dsl.withType import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.tasks.KotlinCompile val JAVA_VERSION = JavaVersion.VERSION_19 fun CommonExtension<*, *, *, *, *, *>.configureJVM() { this.compileOptions { sourceCompatibility = JAVA_VERSION targetCompatibility = JAVA_VERSION } } fun Project.configureKotlinJVM() { tasks.withType<KotlinCompile>().configureEach { compilerOptions { jvmTarget.set(JvmTarget.JVM_19) val warningsAsErrors: String? by project allWarningsAsErrors.set(warningsAsErrors.toBoolean()) freeCompilerArgs.also { it.addAll( listOf( "-opt-in=kotlin.RequiresOptIn", // Enable experimental coroutines APIs, including Flow "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", "-opt-in=kotlinx.coroutines.FlowPreview", "-opt-in=kotlin.Experimental", // Enable experimental kotlinx serialization APIs "-opt-in=kotlinx.serialization.ExperimentalSerializationApi", ) ) } } } }
4
Kotlin
18
109
067d0bdf075e0c2dbc61ae3aee56be5bd294b9c6
1,516
expensemanager
Apache License 2.0
app/src/main/java/com/github/libliboom/epubviewer/base/di/ViewModelKey.kt
libliboom
258,487,396
false
null
package com.github.libliboom.epubviewer.base.di import androidx.lifecycle.ViewModel import dagger.MapKey import kotlin.reflect.KClass @MustBeDocumented @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) @Retention(AnnotationRetention.RUNTIME) @MapKey internal annotation class ViewModelKey(val value: KClass<out ViewModel>)
2
Kotlin
0
3
71f1d99af902a82784819a672bb3e27fa306f005
378
Epub-Viewer-Android
MIT License
live-component/src/main/java/com/kotlin/android/live/component/ui/widget/BackgroundCacheStuffer.kt
R-Gang-H
538,443,254
false
null
package com.kotlin.android.live.component.ui.widget import android.graphics.Canvas import android.graphics.Paint import android.text.TextPaint import com.kotlin.android.ktx.ext.dimension.dp import master.flame.danmaku.danmaku.model.BaseDanmaku import master.flame.danmaku.danmaku.model.android.SpannedCacheStuffer /** * create by lushan on 2021/3/16 * description:弹幕背景 */ class BackgroundCacheStuffer : SpannedCacheStuffer() { private val paint = Paint() override fun measure(danmaku: BaseDanmaku?, paint: TextPaint?, fromWorkerThread: Boolean) { danmaku?.padding = 5.dp // 在背景绘制模式下增加padding super.measure(danmaku, paint, fromWorkerThread) } //绘制背景 override fun drawBackground(danmaku: BaseDanmaku?, canvas: Canvas?, left: Float, top: Float) { super.drawBackground(danmaku, canvas, left, top) } // 绘制描边 override fun drawStroke(danmaku: BaseDanmaku?, lineText: String?, canvas: Canvas?, left: Float, top: Float, paint: Paint?) { super.drawStroke(danmaku, lineText, canvas, left, top, paint) } }
0
Kotlin
0
1
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
1,073
Mtime
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt
ranjanrukhaya
345,327,155
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.os.Bundle import android.widget.ImageButton import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.androiddevchallenge.ui.theme.MyTheme import com.example.androiddevchallenge.viewmodel.TimerViewModel @ExperimentalAnimationApi class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyTheme { val viewModel by viewModels<TimerViewModel>() val timerValue = viewModel.timerValue.collectAsState().value val play = viewModel.play.collectAsState().value Surface(color = MaterialTheme.colors.background) { Box( modifier = Modifier .fillMaxSize(), contentAlignment = Alignment.Center ) { Column( modifier = Modifier .fillMaxWidth() .wrapContentSize(Alignment.Center) .clip(CircleShape) ) { Box( modifier = Modifier .size(220.dp) .background(Color(0xFF121d33)) ) { } } Column( modifier = Modifier .fillMaxWidth() .wrapContentSize(Alignment.Center) .clip(CircleShape) ) { Box( modifier = Modifier .size(210.dp) .background(Color(0xFF6c1964)) ) { } } Column( modifier = Modifier .fillMaxWidth() .wrapContentSize(Alignment.Center) .clip(CircleShape) ) { Box( modifier = Modifier .size(200.dp) .background(Color(0xFF1a2e52)) ) { } } Column( horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "${getTimerLabel(timerValue)}", style = MaterialTheme.typography.subtitle2, fontSize = 40.sp, color = Color(0xFF47D9E8), modifier = Modifier.padding(0.dp, 15.dp) ) Row() { AnimatedVisibility(visible = play) { Card( modifier = Modifier .size(48.dp) .padding(5.dp) .clickable(onClick = { viewModel.pause() }), shape = CircleShape, elevation = 2.dp, backgroundColor = Color(0xFF101f3a) ) { Image( painter = painterResource(id = R.drawable.ic_pause), contentDescription = null ) } } AnimatedVisibility(visible = !play) { Card( modifier = Modifier .size(48.dp) .padding(5.dp) .clickable(onClick = { viewModel.start() }), shape = CircleShape, elevation = 2.dp, backgroundColor = Color(0xFF101f3a) ) { Image( painter = painterResource(id = R.drawable.ic_play), contentDescription = null ) } } AnimatedVisibility(visible = play) { Card( modifier = Modifier .size(48.dp) .padding(5.dp) .clickable(onClick = { viewModel.restart() }), shape = CircleShape, elevation = 2.dp, backgroundColor = Color(0xFF101f3a) ) { Image( painter = painterResource(id = R.drawable.ic_replay), contentDescription = null ) } } } } } } } } } } fun getTimerLabel(value: Int): String { return "${padding(value / 60)} : ${padding(value % 60)}" } fun padding(value: Int) = if (value < 10) ("0$value") else "" + value
0
Kotlin
1
0
6c4f294da5f9549ca31bbf5964f26c277f8a5b1e
7,866
compose-timer
Apache License 2.0
im-organization/organization-lib/src/main/kotlin/city/smartb/im/organization/lib/service/OrganizationMapper.kt
smartbcity
651,445,390
false
null
package city.smartb.im.organization.lib.service interface OrganizationMapper<FROM, Organization> { fun mapModel(model: FROM): Organization fun mapOrganization(model: Organization): FROM }
0
Kotlin
0
0
6a727ac998241724d073ac66247496355316f934
197
connect-im
Apache License 2.0
androidApp/src/main/java/press/sync/GitRepoRowView.kt
gouthamijami
290,724,594
true
{"Kotlin": 436307, "Swift": 38925, "Java": 27798, "Ruby": 5879}
package press.sync import android.content.Context import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.view.View import com.jakewharton.rxbinding3.view.detaches import com.squareup.contour.ContourLayout import io.reactivex.rxkotlin.Observables.combineLatest import io.reactivex.subjects.BehaviorSubject import me.saket.press.R import me.saket.press.shared.sync.git.HighlightedText import me.saket.press.shared.sync.git.RepoUiModel import me.saket.press.shared.theme.TextStyles.mainTitle import me.saket.press.shared.theme.TextStyles.smallBody import me.saket.press.shared.theme.TextStyles.smallTitle import me.saket.press.shared.theme.TextView import me.saket.press.shared.theme.ThemePalette import press.extensions.attr import press.extensions.textColor import press.theme.themeAware import press.theme.themePalette class GitRepoRowView(context: Context) : ContourLayout(context) { private val ownerView = TextView(context, smallBody).apply { themeAware { textColor = it.textColorSecondary } applyLayout( x = matchParentX(marginLeft = 22.dip, marginRight = 22.dip), y = topTo { parent.top() + 16.ydip } ) } private val nameView = TextView(context, mainTitle).apply { themeAware { textColor = it.textColorPrimary } applyLayout( x = matchParentX(marginLeft = 22.dip, marginRight = 22.dip), y = topTo { ownerView.bottom() } ) } private val dividerView = View(context).apply { themeAware { setBackgroundColor(it.separator) } applyLayout( x = matchParentX(), y = topTo { nameView.bottom() + 16.ydip }.heightOf { 1.ydip } ) } init { contourHeightOf { dividerView.bottom() } foreground = attr(R.attr.selectableItemBackground).asDrawable() themeAware { // RV item animations nicer if the items don't leak through each other. setBackgroundColor(it.window.backgroundColor) } } override fun onAttachedToWindow() { super.onAttachedToWindow() combineLatest(models, themePalette()) .takeUntil(detaches()) .subscribe { (model, palette) -> render(model, palette) } } private val models = BehaviorSubject.create<RepoUiModel>() fun render(model: RepoUiModel) { models.onNext(model) } private fun render(model: RepoUiModel, palette: ThemePalette) { val highlightSpan = ForegroundColorSpan(palette.accentColor) ownerView.text = model.owner.withSpan(highlightSpan) nameView.text = model.name.withSpan(highlightSpan) } private fun HighlightedText.withSpan(span: Any): CharSequence { return when (val it = highlight) { null -> return text else -> SpannableString(text).apply { setSpan(span, it.first, it.last, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE) } } } }
0
null
0
1
332a5179af8fbb805c2b4b8c7e53984158983d12
2,813
press
Apache License 2.0
datasource/src/main/java/com/loperilla/rawg/datasource/network/impl/GenreApiImpl.kt
loperilla
648,302,442
false
null
package com.loperilla.rawg.datasource.network.impl import com.loperilla.rawg.datasource.BuildConfig import com.loperilla.rawg.datasource.network.NetworkConstants import com.loperilla.rawg.datasource.network.NetworkUtils.processResponse import com.loperilla.rawg.datasource.network.api.GameGenreApi import com.loperilla.rawg.datasource.network.model.genre.GenreResponse import com.loperilla.rawg.datasource.network.model.response.BaseResponse import io.ktor.client.HttpClient import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.url import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import kotlinx.serialization.json.Json import javax.inject.Inject class GenreApiImpl @Inject constructor( private val httpClient: HttpClient, private val json: Json ) : GameGenreApi { override suspend fun getAllGenres(): BaseResponse<GenreResponse> { return processResponse(json) { httpClient.get { header(HttpHeaders.ContentType, ContentType.Application.Json) url { url("${NetworkConstants.BASE_URL}${NetworkConstants.GENRES}") parameters.append(NetworkConstants.API_KEY_NAME, BuildConfig.API_KEY) } } } } }
0
Kotlin
0
0
3d05ea00915278bb4d374a00707fafe590eee3d3
1,299
ComposeRawg
Apache License 2.0
src/main/kotlin/g0801_0900/s0891_sum_of_subsequence_widths/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0891_sum_of_subsequence_widths // #Hard #Array #Math #Sorting #2023_04_10_Time_481_ms_(100.00%)_Space_48.5_MB_(100.00%) class Solution { // 1-6 (number of elements in between 1 and 6) = (6-1-1) = 4 // length of sub seq 2 -> 4C0 3 -> 4C1 ; 4 -> 4c2 ; 5 -> 4C3 6 -> 4C4 4c0 + 4c1 + 4c2 + 4c3 + // 4c4 1+4+6+4+1=16 // 1-5 3c0 + 3c1 + 3c2 + 3c3 = 8 // 1-4 2c0 + 2c1 2c2 = 4 // 1-3 1c0 + 1c1 = 2 // 1-2 1c0 = 1 /* 16+8+4+2+1(for 1 as min) 8+4+2+1(for 2 as min) 4+2+1(for 3 as min) 2+1(for 4 as min) 1(for 5 as min) -1*nums[0]*31 + nums[1]*1 + nums[2]*2 + nums[3]*4 + nums[4]*8 + nums[5]*16 -1*nums[1]*15 + nums[2]*1 +nums[3]*2 + nums[4]*4 + nums[5]*8 -1*nums[2]*7 + nums[3]*1 + nums[4]*2 + nums[5]*4 -1*nums[3]*3 + nums[4]*1 + nums[5]*2 -1*nums[4]*1 + nums[5]*1 -nums[0]*31 + -nums[1]*15 - nums[2]*7 - nums[3]*3 - nums[4]*1 nums[1]*1 + nums[2]*3 + nums[3]*7 + nums[4]*15 + nums[5]*31 (-1)*nums[0]*(pow[6-1-0]-1) + (-1)*nums[1]*(pow[6-1-1]-1) + (-1)*nums[2]*(pow[6-1-2]-1) ... (-1)* nums[5]*(pow[6-1-5]-1) + nums[1]*(pow[1]-1) + nums[2]*(pow[2]-1) + .... + nums[5]*(pow[5]-1) (-1)*A[i]*(pow[l-1-i]-1) + A[i]*(pow[i]-1) */ fun sumSubseqWidths(nums: IntArray): Int { val mod = 1000000007 nums.sort() val l = nums.size val pow = LongArray(l) pow[0] = 1 for (i in 1 until l) { pow[i] = pow[i - 1] * 2 % mod } var res: Long = 0 for (i in 0 until l) { res = (res + -1 * nums[i] * (pow[l - 1 - i] - 1) + nums[i] * (pow[i] - 1)) % mod } return res.toInt() } }
0
Kotlin
20
43
e8b08d4a512f037e40e358b078c0a091e691d88f
1,754
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/piashcse/controller/ShopController.kt
piashcse
410,331,425
false
null
package com.piashcse.controller import com.piashcse.entities.shop.* import com.piashcse.entities.user.UserTable import com.piashcse.utils.CommonException import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.sql.transactions.transaction class ShopController { fun createShopCategory(shopCategoryName: String) = transaction { val categoryExist = ShopCategoryEntity.find { ShopCategoryTable.shopCategoryName eq shopCategoryName }.toList().singleOrNull() return@transaction if (categoryExist == null) { ShopCategoryEntity.new { this.shopCategoryName = shopCategoryName }.shopCategoryResponse() } else { throw CommonException("Category name $shopCategoryName already exist") } } fun getShopCategories(limit: Int, offset: Int) = transaction { val shopCategories = ShopCategoryEntity.all().limit(limit, offset.toLong()) return@transaction shopCategories.map { it.shopCategoryResponse() } } fun updateShopCategory(shopCategoryId: String, shopCategoryName: String) = transaction { val shopCategoryExist = ShopCategoryEntity.find { ShopCategoryTable.id eq shopCategoryId }.toList().singleOrNull() return@transaction shopCategoryExist?.apply { this.shopCategoryName = shopCategoryName }?.shopCategoryResponse() ?: throw CommonException("Category id $shopCategoryId is not exist") } fun deleteShopCategory(shopCategoryId: String) = transaction { val shopCategoryExist = ShopCategoryEntity.find { ShopCategoryTable.id eq shopCategoryId }.toList().singleOrNull() return@transaction shopCategoryExist?.let { shopCategoryExist.delete() shopCategoryId } ?: run { throw CommonException("Category id $shopCategoryId is not exist") } } fun createShop(userId: String, shopCategoryId: String, shopName: String) = transaction { val shopNameExist = ShopEntity.find { ShopTable.shopName eq shopName }.toList().singleOrNull() return@transaction if (shopNameExist == null) { ShopEntity.new() { this.userId = EntityID(userId, UserTable) this.shopCategoryId = EntityID(shopCategoryId, ShopTable) this.shopName = shopName }.shopResponse() } else { throw CommonException("Shop name $shopName already exist") } } }
0
Kotlin
5
26
74b152e2dc10238197a0fb99595730edd55621fd
2,525
ktor-E-Commerce
PostgreSQL License
app/src/main/java/com/application/moviesapp/data/api/response/TvSeriesTrailerDto.kt
sheikh-20
676,842,394
false
{"Kotlin": 707578, "Python": 2213}
package com.application.moviesapp.data.api.response import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class TvSeriesTrailerDto( @SerialName("id") val id: Int?, @SerialName("results") val results: List<Result?>? ) { @Serializable data class Result( @SerialName("id") val id: String?, @SerialName("iso_3166_1") val isoOne: String?, @SerialName("iso_639_1") val isoTwo: String?, @SerialName("key") val key: String?, @SerialName("name") val name: String?, @SerialName("official") val official: Boolean?, @SerialName("published_at") val publishedAt: String?, @SerialName("site") val site: String?, @SerialName("size") val size: Int?, @SerialName("type") val type: String? ) }
0
Kotlin
1
7
7ac9a7d2c41f9d0acf1f37d5475e5ca321447e3f
922
MoviesApp
MIT License
azure-communication-ui/demo-app/src/calling/java/com/azure/android/communication/ui/callingcompositedemoapp/CallLauncherViewModel.kt
Azure
429,521,705
false
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.android.communication.ui.callingcompositedemoapp import android.content.Context import androidx.lifecycle.ViewModel import com.azure.android.communication.common.CommunicationTokenCredential import com.azure.android.communication.common.CommunicationTokenRefreshOptions import com.azure.android.communication.ui.calling.CallComposite import com.azure.android.communication.ui.calling.CallCompositeBuilder import com.azure.android.communication.ui.calling.models.CallCompositeCallHistoryRecord import com.azure.android.communication.ui.calling.models.CallCompositeGroupCallLocator import com.azure.android.communication.ui.calling.models.CallCompositeJoinLocator import com.azure.android.communication.ui.calling.models.CallCompositeLocalOptions import com.azure.android.communication.ui.calling.models.CallCompositeLocalizationOptions import com.azure.android.communication.ui.calling.models.CallCompositeRemoteOptions import com.azure.android.communication.ui.calling.models.CallCompositeSetupScreenViewData import com.azure.android.communication.ui.calling.models.CallCompositeTeamsMeetingLinkLocator import com.azure.android.communication.ui.callingcompositedemoapp.features.AdditionalFeatures import com.azure.android.communication.ui.callingcompositedemoapp.features.SettingsFeatures import java.util.UUID class CallLauncherViewModel : ViewModel() { fun launch( context: Context, acsToken: String, displayName: String, groupId: UUID?, meetingLink: String?, ) { val callComposite = createCallComposite(context) callComposite.addOnErrorEventHandler(CallLauncherActivityErrorHandler(context, callComposite)) if (SettingsFeatures.getRemoteParticipantPersonaInjectionSelection()) { callComposite.addOnRemoteParticipantJoinedEventHandler( RemoteParticipantJoinedHandler(callComposite, context) ) } val communicationTokenRefreshOptions = CommunicationTokenRefreshOptions({ acsToken }, true) val communicationTokenCredential = CommunicationTokenCredential(communicationTokenRefreshOptions) val locator: CallCompositeJoinLocator = if (groupId != null) CallCompositeGroupCallLocator(groupId) else CallCompositeTeamsMeetingLinkLocator(meetingLink) val remoteOptions = CallCompositeRemoteOptions(locator, communicationTokenCredential, displayName) val localOptions = CallCompositeLocalOptions() .setParticipantViewData(SettingsFeatures.getParticipantViewData(context.applicationContext)) .setSetupScreenViewData( CallCompositeSetupScreenViewData() .setTitle(SettingsFeatures.getTitle()) .setSubtitle(SettingsFeatures.getSubtitle()) ) .setSkipSetupScreen(SettingsFeatures.getSkipSetupScreenFeatureOption()) .setCameraOn(SettingsFeatures.getCameraOnByDefaultOption()) .setMicrophoneOn(SettingsFeatures.getMicOnByDefaultOption()) callComposite.launch(context, remoteOptions, localOptions) } fun getCallHistory(context: Context): List<CallCompositeCallHistoryRecord> { return (callComposite ?: createCallComposite(context)).getDebugInfo(context).callHistoryRecords } private fun createCallComposite(context: Context): CallComposite { SettingsFeatures.initialize(context.applicationContext) val selectedLanguage = SettingsFeatures.language() val locale = selectedLanguage?.let { SettingsFeatures.locale(it) } val callCompositeBuilder = CallCompositeBuilder() .localization(CallCompositeLocalizationOptions(locale!!, SettingsFeatures.getLayoutDirection())) if (AdditionalFeatures.secondaryThemeFeature.active) callCompositeBuilder.theme(R.style.MyCompany_Theme_Calling) val callComposite = callCompositeBuilder.build() // For test purposes we will keep a static ref to CallComposite CallLauncherViewModel.callComposite = callComposite return callComposite } companion object { var callComposite: CallComposite? = null } }
7
null
17
17
6ac4c970eba3eb82c205b697430442d7e8293586
4,337
communication-ui-library-android
MIT License
src/iii_conventions/MyDate.kt
alexggg99
162,521,772
true
{"Kotlin": 74053, "Java": 4952}
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { constructor(date: MyDate) : this(date.year, date.month, date.dayOfMonth) override fun compareTo(other: MyDate): Int = when { this.year != other.year -> this.year - other.year this.month != other.month -> this.month - other.month else -> this.dayOfMonth - other.dayOfMonth } // override fun compareTo(other: MyDate): Int { // if (other != null && other is MyDate) { // val otherDate: MyDate = other // if (this.year.compareTo(otherDate.year) > 0) { // return 1 // } else if (this.year.compareTo(otherDate.year) == 0) { // if (this.month.compareTo(otherDate.month) > 0) { // return 1 // } else if(this.month.compareTo(otherDate.month) == 0) { // if (this.dayOfMonth.compareTo(otherDate.dayOfMonth) > 0) { // return 1 // } else if(this.dayOfMonth.compareTo(otherDate.dayOfMonth) == 0) { // return 0 // } else { // return -1 // } // } else { // return -1 // } // } else { // return -1 // } // } // return -1 // } } enum class TimeInterval { DAY, WEEK, YEAR } class RepeatedTimeInterval(val ti: TimeInterval, val n: Int) operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number) class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> { override fun iterator(): Iterator<MyDate> { return DateIterator(start, endInclusive) } } class DateIterator(start: MyDate, val endInclusive: MyDate) : Iterator<MyDate> { var nextDate: MyDate = MyDate(start) override fun hasNext(): Boolean { return nextDate <= endInclusive } override fun next(): MyDate { val result = nextDate nextDate = nextDate.nextDay() return result } }
0
Kotlin
0
0
abdd7d5c84f85e166f392cbe50a581bc6ecccf49
2,152
kotlin-koans
MIT License
app/src/main/java/com/filip/cryptoViewer/domain/model/CoinExchange.kt
filipus959
852,338,147
false
{"Kotlin": 120202}
package com.filip.cryptoViewer.domain.model data class CoinExchange ( val price: Double, val coinId: String, val coinId2: String, )
0
Kotlin
0
0
c1ba06838b6440bb9bbebf4b9f084dea4db3a39f
144
CryptoViewer
Apache License 2.0
app/src/main/java/com/funkymuse/composedlib/navigation/destinations/settings/graph/SettingsGraph.kt
FunkyMuse
342,916,020
false
{"Kotlin": 210346}
package com.funkymuse.composedlib.navigation.destinations.settings.graph import com.funkymuse.composed.navigation.destination.NavigationDestination import com.funkymuse.composed.navigation.graph.NavigationGraph import com.funkymuse.composedlib.navigation.destinations.settings.destinations.SettingsScreenBottomNavDestination import javax.inject.Inject class SettingsGraph @Inject constructor() : NavigationGraph { override val startingDestination: NavigationDestination = SettingsScreenBottomNavDestination override val route: String = "SettingsGraph" }
0
Kotlin
2
17
91af13ab7e9654b79d6ade8876ec15f7cdd9f0f7
564
Composed
MIT License
library/src/main/java/io/github/anderscheow/validator/rules/common/AllLowerCaseRule.kt
KirillAshikhmin
408,957,823
true
{"Kotlin": 129331, "Java": 99}
package io.github.anderscheow.validator.rules.common import androidx.annotation.StringRes import io.github.anderscheow.validator.Validation import io.github.anderscheow.validator.rules.BaseRule import java.util.* class AllLowerCaseRule : BaseRule { private var locale: Locale constructor(locale: Locale = Locale.getDefault()) : super("Value is not all lowercase") { this.locale = locale } constructor(@StringRes errorRes: Int, locale: Locale = Locale.getDefault()) : super(errorRes) { this.locale = locale } constructor(errorMessage: String, locale: Locale = Locale.getDefault()) : super(errorMessage) { this.locale = locale } override fun validate(value: String?): Boolean { if (value == null) { throw NullPointerException() } else { return value.toLowerCase(locale) == value } } } fun Validation.allLowercase(locale: Locale = Locale.getDefault()): Validation { baseRules.add(AllLowerCaseRule(locale)) return this } fun Validation.allLowercase(@StringRes errorRes: Int, locale: Locale = Locale.getDefault()): Validation { baseRules.add(AllLowerCaseRule(errorRes, locale)) return this } fun Validation.allLowercase(errorMessage: String, locale: Locale = Locale.getDefault()): Validation { baseRules.add(AllLowerCaseRule(errorMessage, locale)) return this }
0
null
0
0
56c2e490fa06e491dd782b2bab0d222507b3eaf0
1,435
Validator
MIT License
app/src/main/java/com/vicidroid/amalia/sample/examples/ui/examplefragment1/ExampleFragment1ViewDiff.kt
vicidroiddev
171,361,804
false
null
package com.vicidroid.amalia.sample.examples.ui.examplefragment1 import com.vicidroid.amalia.core.viewdiff.BaseViewDiff import kotlinx.parcelize.Parcelize @Parcelize class ExampleFragment1ViewDiff( var name: String = "" ) : BaseViewDiff()
7
Kotlin
0
9
0a4facc243feefe3f982f7f2915ccc5541dc321b
244
amalia
Apache License 2.0
Android/PlantWatchDog/app/src/main/java/ch/mseengineering/plantwatchdog/ui/authentication/RegisterActivity.kt
MarkStraub
440,088,953
false
null
package ch.mseengineering.plantwatchdog.ui.authentication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.loader.content.Loader import ch.mseengineering.plantwatchdog.MainActivity import ch.mseengineering.plantwatchdog.R import ch.mseengineering.plantwatchdog.services.StoreData import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.firestore.auth.FirebaseAuthCredentialsProvider /* Code based on https://www.youtube.com/watch?v=8I5gCLaS25w&t=1512s&ab_channel=tutorialsEU */ class RegisterActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { 7 super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) val registerBtn: Button = findViewById(R.id.btn_register); val emailEdTxt: EditText = findViewById(R.id.et_register_email); val passwordEdTxt: EditText = findViewById(R.id.et_register_password); val loginTxtVew: TextView = findViewById(R.id.tv_login); registerBtn.setOnClickListener { when { TextUtils.isEmpty(emailEdTxt.text.toString().trim() { it <= ' ' }) -> { Toast.makeText( this@RegisterActivity, "Please enter email", Toast.LENGTH_SHORT ).show(); } TextUtils.isEmpty(passwordEdTxt.text.toString().trim() { it <= ' ' }) -> { Toast.makeText( this@RegisterActivity, "Please enter password", Toast.LENGTH_SHORT ).show(); } else -> { val email: String = emailEdTxt.text.toString().trim() { it <= ' ' } val password: String = passwordEdTxt.text.toString().trim() { it <= ' ' } // Create an instance and crate a register a user with email and password FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password) .addOnCompleteListener( OnCompleteListener<AuthResult> { task -> // If the registration is successfully done if (task.isSuccessful) { // Firebase registered user val firebaseUser: FirebaseUser = task.result!!.user!! Toast.makeText( this@RegisterActivity, "You are registered successfully", Toast.LENGTH_SHORT ).show(); // Save the user id val storeData: StoreData = StoreData(); storeData.save("userId", firebaseUser.uid); /** * Here the new user registered is automatically signed-ins so we just sign out the user * and send him to Main Screen with user id and email that user have used for registration */ val intent = Intent(this@RegisterActivity, MainActivity::class.java); intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK; // intent.putExtra("user_id", firebaseUser.uid); // intent.putExtra("email_id", email); startActivity(intent); finish(); } else { // If the registration is not successful then show error message Toast.makeText( this@RegisterActivity, task.exception!!.message.toString(), Toast.LENGTH_SHORT ).show(); } } ); } } } loginTxtVew.setOnClickListener { onBackPressed(); } } }
0
Kotlin
0
0
cd73be5dafa211e8ad7b599e9a6412c4f308da89
4,919
Plant-WatchDog
Apache License 2.0
plugins/modules-catalog/src/main/kotlin/CineScoutModulesCatalogExtension.kt
4face-studi0
280,630,732
false
null
import org.gradle.api.Project import org.gradle.kotlin.dsl.create import java.util.Locale import javax.inject.Inject open class PinkBunnyModulesCatalogExtension @Inject constructor( private val project: Project ) : ModulesCatalog(project) { operator fun Any.invoke() { with(module) { if (project.findMultiplatformExtension() != null) { addMultiplatformDependency(sourceSetName) } else { addJvmDependency(sourceSetName) } } } private fun Module.addMultiplatformDependency(sourceSetName: String) { if (sourceSetName == "androidMain") { project.dependencies.add("implementation", project.rootProject.project(normalizedPath)) } else { project.getMultiplatformExtension().sourceSets.named(sourceSetName) { dependencies { implementation(project.rootProject.project(normalizedPath)) } } } } private fun Module.addJvmDependency(sourceSetName: String) { val configurationName = if (sourceSetName == CommonMainSourceSetName) { "implementation" } else { sourceSetName.substringAfter("common").decapitalize(Locale.ROOT) } project.dependencies { add(configurationName, project.rootProject.project(normalizedPath)) } } companion object { fun setup(project: Project): PinkBunnyModulesCatalogExtension = project.extensions.create("moduleDependencies") } }
19
Kotlin
2
3
d64398507d60a20a445db1451bdd8be23d65c9aa
1,602
CineScout
Apache License 2.0
shared/presentation/add_ingredient/src/commonMain/kotlin/com/iwanickimarcel/add_ingredient/AddIngredientViewModel.kt
MarcelIwanicki
712,987,885
false
{"Kotlin": 376361, "Swift": 342}
package com.iwanickimarcel.add_ingredient import androidx.compose.ui.text.input.TextFieldValue import com.iwanickimarcel.add_product.ValidateProduct import com.iwanickimarcel.products.AmountUnit import dev.icerock.moko.mvvm.viewmodel.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.WhileSubscribed import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlin.time.Duration.Companion.seconds class AddIngredientViewModel( private val validateProduct: ValidateProduct ) : ViewModel() { companion object { private val STOP_TIMEOUT = 5.seconds val AMOUNT_UNIT_OPTIONS = AmountUnit.values().map { it.abbreviation } } private val _state = MutableStateFlow(AddIngredientState()) val state = _state.stateIn( viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT), AddIngredientState() ) fun onEvent(event: AddIngredientEvent) { when (event) { is AddIngredientEvent.OnEditProductProvided -> { _state.value = _state.value.copy( name = TextFieldValue(event.product.name), amount = event.product.amount.amount, amountUnit = event.product.amount.unit ) } is AddIngredientEvent.OnNameChanged -> { _state.value = _state.value.copy( name = event.name, nameError = null ) } is AddIngredientEvent.OnAmountChanged -> { _state.value = _state.value.copy( amount = event.amount.toDoubleOrNull() ?: return, amountError = null ) } is AddIngredientEvent.OnAmountUnitChanged -> { val unit = AmountUnit.values().find { it.abbreviation == event.unit } unit?.let { _state.value = _state.value.copy( amountUnit = it, amountUnitMenuExpanded = false ) } } is AddIngredientEvent.OnAmountUnitMenuStateChanged -> { val previousAmountUnitMenuExpanded = _state.value.amountUnitMenuExpanded _state.value = _state.value.copy( amountUnitMenuExpanded = !previousAmountUnitMenuExpanded ) } is AddIngredientEvent.OnAddIngredientClick -> with(_state.value) { viewModelScope.launch { validateProduct( name = name?.text, amount = amount, amountUnit = amountUnit, photoBytes = null, onProductAdded = event.onIngredientAdded, onSuccess = { _state.value = _state.value.copy( success = true ) }, onAmountError = { _state.value = _state.value.copy( amountError = it ) }, onNameError = { _state.value = _state.value.copy( nameError = it ) } ) } } } } }
0
Kotlin
0
1
0d9676a542ba3d9b8b2bdf366aefadf298e6da81
3,638
freat
The Unlicense
android/app/src/main/kotlin/com/andannn/aniflow/MainActivity.kt
andannn
687,270,093
false
{"Dart": 1661087, "Kotlin": 16071, "Ruby": 1414, "Swift": 689, "Java": 670, "Objective-C": 38}
package com.andannn.aniflow import android.content.Intent import android.util.Log import com.andannn.aniflow.player.PlayerActivity import com.andannn.aniflow.player.PlayerActivity.Companion.VIDEO_URL_KEY import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugins.GeneratedPluginRegistrant private const val TAG = "MainActivity" class MainActivity : FlutterActivity() { private lateinit var authChannel: EventChannel private lateinit var methodChannel: MethodChannel private var authEventSink: EventChannel.EventSink? = null override fun getInitialRoute(): String? { Log.d(TAG, "getInitialRoute uri: ${intent?.data?.toString()}") return intent?.data?.toString() ?: super.getInitialRoute() } override fun configureFlutterEngine(flutterEngine: FlutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine) authChannel = EventChannel( /* messenger = */ flutterEngine.dartExecutor.binaryMessenger, /* name = */ "com.andannn.animetracker/auth" ) methodChannel = MethodChannel( flutterEngine.dartExecutor.binaryMessenger, "com.andannn.animetracker/navi" ) authChannel.setStreamHandler( /* handler = */ object : EventChannel.StreamHandler { override fun onListen(arguments: Any?, events: EventChannel.EventSink) { authEventSink = events } override fun onCancel(arguments: Any?) { authEventSink = null } }) methodChannel.setMethodCallHandler { call, result -> val arguments = call.arguments as List<*> Log.d(TAG, "configureFlutterEngine: $arguments") when (call.method) { "startPlayerActivity" -> { startActivity( Intent(this, PlayerActivity::class.java).apply { putExtra(VIDEO_URL_KEY, arguments[0] as String) } ) result.success(null) } } } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val action = intent.action val data = intent.data Log.d(TAG, "onNewIntent: action $action, data $data") if (intent.data?.scheme == "animetracker") { // app received the redirect link from anilist. authEventSink?.success(intent.data?.toString()?.replace('#', '?')) authEventSink?.endOfStream() } data?.let { // Launched by deep link, let flutter handle the uri. flutterEngine?.navigationChannel?.pushRouteInformation(it.toString()) } } }
1
Dart
0
10
16b8b59d9236acc23606c3547ab1e5876afba4a0
2,996
aniflow
Apache License 2.0
AtomicKotlin/Programming Basics/The in Keyword/Examples/src/StringRange.kt
fatiq123
726,462,263
false
{"Kotlin": 370528, "HTML": 6544, "JavaScript": 5252, "Java": 4416, "CSS": 3780, "Assembly": 94}
// InKeyword/StringRange.kt fun main() { println("ab" in "aa".."az") println("ba" in "aa".."az") } /* Output: true false */
0
Kotlin
0
0
3d351652ebe1dd7ef5f93e054c8f2692c89a144e
128
AtomicKotlinCourse
MIT License
app/src/main/java/com/example/roomexp/Word.kt
mithileshrane
231,529,548
false
null
package com.example.roomexp import androidx.annotation.NonNull import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "word_table") class Word (word: String){ @PrimaryKey @NonNull @ColumnInfo(name = "word") private var mWord: String? = null init { mWord = word } fun getWord(): String? { return mWord } }
0
Kotlin
0
0
dabbbcc38e704fc3091efe7be119cbd2570dc6c7
412
RoomExp
MIT License
app/src/main/java/com/revolgenx/anilib/infrastructure/service/review/ReviewServiceImpl.kt
rev0lgenX
244,410,204
false
null
package com.revolgenx.anilib.infrastructure.service.review import androidx.lifecycle.MutableLiveData import com.apollographql.apollo.exception.ApolloHttpException import com.revolgenx.anilib.DeleteReviewMutation import com.revolgenx.anilib.ReviewQuery import com.revolgenx.anilib.SaveReviewMutation import com.revolgenx.anilib.data.field.review.AllReviewField import com.revolgenx.anilib.data.field.review.RateReviewField import com.revolgenx.anilib.data.field.review.ReviewField import com.revolgenx.anilib.data.model.user.UserPrefModel import com.revolgenx.anilib.data.model.CommonMediaModel import com.revolgenx.anilib.data.model.user.AvatarModel import com.revolgenx.anilib.data.model.review.ReviewModel import com.revolgenx.anilib.infrastructure.repository.network.BaseGraphRepository import com.revolgenx.anilib.infrastructure.repository.network.converter.toModel import com.revolgenx.anilib.infrastructure.repository.util.ERROR import com.revolgenx.anilib.infrastructure.repository.util.Resource import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import timber.log.Timber import java.net.HttpURLConnection import java.text.SimpleDateFormat import java.util.* class ReviewServiceImpl(private val graphRepository: BaseGraphRepository) : ReviewService { override val reviewLiveData: MutableLiveData<Resource<ReviewModel>> = MutableLiveData() override fun getReview( field: ReviewField, compositeDisposable: CompositeDisposable ) { val disposable = graphRepository.request(field.toQueryOrMutation() as ReviewQuery).map { it.data()?.Review()?.let { ReviewModel().also { model -> model.reviewId = it.id() model.rating = it.rating() model.ratingAmount = it.ratingAmount() model.userRating = it.userRating()?.ordinal model.summary = it.summary() model.body = it.body() ?: "" model.score = it.score() model.private = it.private_() model.createdAt = it.createdAt().let { SimpleDateFormat.getDateInstance().format(Date(it * 1000L)) } model.userPrefModel = it.user()?.let { UserPrefModel().also { user -> user.id = it.id() user.name = it.name() user.avatar = it.avatar()?.let { AvatarModel().also { img -> img.large = it.large() img.medium = it.medium() } } } } model.mediaModel = it.media()?.let { CommonMediaModel().also { media -> media.mediaId = it.id() media.title = it.title()?.fragments()?.mediaTitle()?.toModel() media.coverImage = it.coverImage()?.fragments()?.mediaCoverImage()?.toModel() media.bannerImage = it.bannerImage() media.type = it.type()?.ordinal } } } } }.observeOn(AndroidSchedulers.mainThread()) .subscribe({ reviewLiveData.value = Resource.success(it) }, { if (it is ApolloHttpException) { if (it.code() == HttpURLConnection.HTTP_NOT_FOUND) { reviewLiveData.value = Resource.success(null) return@subscribe } } Timber.e(it) reviewLiveData.value = Resource.error(it.message ?: ERROR, null, it) }) compositeDisposable.add(disposable) } override fun getAllReview( field: AllReviewField, compositeDisposable: CompositeDisposable, callback: (Resource<List<ReviewModel>>) -> Unit ) { val disposable = graphRepository.request(field.toQueryOrMutation()).map { it.data()?.Page()?.reviews() ?.filter { if (field.canShowAdult) true else it.media()?.isAdult == false }?.map { ReviewModel().also { model -> model.reviewId = it.id() model.rating = it.rating() model.ratingAmount = it.ratingAmount() model.summary = it.summary() model.score = it.score() model.createdAt = it.createdAt().let { SimpleDateFormat.getDateInstance().format(Date(it * 1000L)) } model.userPrefModel = it.user()?.let { UserPrefModel().also { user -> user.id = it.id() user.name = it.name() user.avatar = it.avatar()?.let { AvatarModel().also { img -> img.large = it.large() img.medium = it.medium() } } } } model.mediaModel = it.media()?.let { CommonMediaModel().also { media -> media.mediaId = it.id() media.title = it.title()?.fragments()?.mediaTitle()?.toModel() media.coverImage = it.coverImage()?.fragments()?.mediaCoverImage()?.toModel() media.bannerImage = it.bannerImage() ?: media.coverImage?.largeImage media.type = it.type()?.ordinal media.isAdult = it.isAdult ?: false } } } } }.observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(it)) }, { Timber.e(it) callback.invoke(Resource.error(it.message ?: ERROR, null, it)) }) compositeDisposable.add(disposable) } override fun saveReview( field: ReviewField, compositeDisposable: CompositeDisposable, callback: (Resource<Boolean>) -> Unit ) { val disposable = graphRepository.request(field.toQueryOrMutation() as SaveReviewMutation) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(true)) }, { Timber.e(it) callback.invoke(Resource.error(it.message ?: ERROR, false, it)) }) compositeDisposable.add(disposable) } override fun deleteReview( field: ReviewField, compositeDisposable: CompositeDisposable, callback: (Resource<Boolean>) -> Unit ) { val disposable = graphRepository.request(field.toQueryOrMutation() as DeleteReviewMutation) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(true)) }, { Timber.e(it) callback.invoke(Resource.error(it.message ?: ERROR, false, it)) }) compositeDisposable.add(disposable) } override fun rateReview( field: RateReviewField, compositeDisposable: CompositeDisposable, callback: (Resource<ReviewModel>) -> Unit ) { val disposable = graphRepository.request(field.toQueryOrMutation()).map { it.data()?.RateReview()?.let { ReviewModel().also { model -> model.reviewId = it.id() model.userRating = it.userRating()?.ordinal model.ratingAmount = it.ratingAmount() model.rating = it.rating() } } }.observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(it)) }, { Timber.e(it) callback.invoke(Resource.error(it?.message ?: ERROR, null, it)) }) compositeDisposable.add(disposable) } }
3
Kotlin
1
24
355d2b5510682d869f18e0113453237af8a1f1cc
8,718
AniLib
Apache License 2.0
domain/interactor/preferences/preferencesinteractor-impl/src/test/kotlin/com/francescsoftware/weathersample/domain/preferences/preferencesinteractor/impl/SetDynamicColorInteractorTest.kt
fvilarino
355,724,548
false
{"Kotlin": 586637, "Shell": 60}
package com.francescsoftware.weathersample.domain.preferences.preferencesinteractor.impl import assertk.assertThat import assertk.assertions.isEqualTo import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import javax.inject.Named internal class SetDynamicColorInteractorTest { private val fakeDataSource = FakeAppSettingsDataSource() private val setUseDynamicColorsInteractor = SetUseDynamicColorsInteractorImpl(fakeDataSource) @Named("Interactor sets use dynamic color") @ParameterizedTest @ValueSource(booleans = [true, false]) fun interactorSetsAppTheme( useDynamic: Boolean, ) = runTest { setUseDynamicColorsInteractor.invoke(useDynamic) val dynamic = fakeDataSource.settings.first().dynamicColor assertThat(dynamic).isEqualTo(useDynamic) } }
1
Kotlin
1
41
c8b50381cc0f4687024c48cd88610a77a8235a48
941
Weather-Sample
Apache License 2.0
src/main/kotlin/dev/nikomaru/advancedshopfinder/commands/ReloadCommand.kt
Nlkomaru
674,733,258
false
null
package dev.nikomaru.advancedshopfinder.commands import cloud.commandframework.annotations.CommandMethod import cloud.commandframework.annotations.CommandPermission import dev.nikomaru.advancedshopfinder.files.Config import org.bukkit.command.CommandSender @CommandMethod("advancedshopfinder|asf|shopfinder|sf") @CommandPermission("advancedshopfinder.admin") class ReloadCommand { @CommandMethod("reload") fun reload(sender: CommandSender) { Config.loadConfig() sender.sendRichMessage("<color:green>コンフィグをリロードしました") } }
0
Kotlin
0
0
f09733fd7eed9a0e47d78776b0f56cc575dddc1e
549
AdvancedShopFinder
Creative Commons Zero v1.0 Universal
app/src/main/java/luyao/wanandroid/compose/ui/Themes.kt
lulululbj
221,170,029
false
null
package luyao.wanandroid.compose.ui import androidx.ui.graphics.Color import androidx.ui.material.MaterialColors /** * Created by luyao * on 2019/11/12 10:20 */ val lightThemeColors = MaterialColors( primary = Color(0xFFDD0D3C), primaryVariant = Color(0xFFC20029), onPrimary = Color.White, secondary = Color.White, onSecondary = Color.Black, background = Color.White, onBackground = Color.Black, surface = Color.White, onSurface = Color.Black, error = Color(0xFFD00036), onError = Color.White ) /** * Note: Dark Theme support is not yet available, it will come in 2020. This is just an example of * using dark colors. */ val darkThemeColors = MaterialColors( primary = Color(0xFFEA6D7E), primaryVariant = Color(0xFFDD0D3E), onPrimary = Color.Black, secondary = Color(0xFF121212), onSecondary = Color.White, surface = Color(0xFF121212), background = Color(0xFF121212), onBackground = Color.White, onSurface = Color.White )
0
Kotlin
4
31
f323b541ac6a89b79f66a3b91bfca85a7a5cc590
1,010
Wanandroid-Compose
Apache License 2.0
src/main/kotlin/de/msiemens/db/table/Schema.kt
msiemens
313,862,364
false
null
package de.msiemens.db.table import de.msiemens.db.sql.statements.ColumnDefinition data class Schema(val columns: List<Pair<String, ColumnType>>) { fun names(): List<String> = columns.map { it.first }.toList() fun type(column: String): ColumnType? = columns.firstOrNull { it.first == column }?.second fun index(column: String): Int? { val col = columns .withIndex() .firstOrNull { it.value.first == column } ?: return null return col.index } companion object { fun of(columns: List<ColumnDefinition>): Schema = Schema(columns.map { it.name to it.type }.toList()) } }
0
Kotlin
0
0
9d5aad8567431feb646a40f7b4445249e3b275c5
657
edu-db
MIT License
feature/settings/src/main/java/online/partyrun/partyrunapplication/feature/settings/SettingsScreen.kt
SWM-KAWAI-MANS
649,352,661
false
{"Kotlin": 804908}
package online.partyrun.partyrunapplication.feature.settings import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import online.partyrun.partyrunapplication.core.designsystem.icon.PartyRunIcons import online.partyrun.partyrunapplication.core.ui.SettingsTopAppBar @Composable fun SettingsScreen( settingsViewModel: SettingsViewModel = hiltViewModel(), navigateBack: () -> Unit = {}, navigateToUnsubscribe: () -> Unit = {}, onShowSnackbar: (String) -> Unit ) { val settingsSnackbarMessage by settingsViewModel.snackbarMessage.collectAsStateWithLifecycle() Content( navigateBack = navigateBack, navigateToUnsubscribe = navigateToUnsubscribe, settingsViewModel = settingsViewModel, onShowSnackbar = onShowSnackbar, settingsSnackbarMessage = settingsSnackbarMessage ) } @Composable fun Content( settingsViewModel: SettingsViewModel, navigateBack: () -> Unit, navigateToUnsubscribe: () -> Unit, onShowSnackbar: (String) -> Unit, settingsSnackbarMessage: String ) { LaunchedEffect(settingsSnackbarMessage) { if (settingsSnackbarMessage.isNotEmpty()) { onShowSnackbar(settingsSnackbarMessage) settingsViewModel.clearSnackbarMessage() } } Column( modifier = Modifier .fillMaxSize() ) { MainBody( navigateBack = navigateBack, navigateToUnsubscribe = navigateToUnsubscribe ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun MainBody( navigateBack: () -> Unit, navigateToUnsubscribe: () -> Unit ) { Scaffold( modifier = Modifier.fillMaxSize(), topBar = { SettingsTopAppBar(navigateBack) } ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(top = paddingValues.calculateTopPadding()) ) { Row( modifier = Modifier .fillMaxWidth() .padding(start = 20.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = stringResource(id = R.string.unsubscribe), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onPrimary ) IconButton(onClick = { navigateToUnsubscribe() }) { Icon( painterResource(id = PartyRunIcons.ArrowForwardIos), contentDescription = stringResource(id = R.string.arrow_forward_desc) ) } } } } }
2
Kotlin
1
14
fecbaf7c67cfa136e0633baaa2c708732069b190
3,775
party-run-application
MIT License
sample-console/src/main/kotlin/ae/vigilancer/jobqueue/sample/console/Main.kt
vigilancer
51,739,832
false
null
package ae.vigilancer.jobqueue.sample.console import ae.vigilancer.jobqueue.lib.Job import ae.vigilancer.jobqueue.lib.RequestsManager import rx.Observable import java.util.* import java.util.concurrent.TimeUnit fun main(args : Array<String>) { println("waiting for response") val rm = RequestsManager() rm.init(LogJobsBeforeTransformers, PreventDoubleFiring, LogJobsAfterTransformers) var specialJobId: String? = null rm.toObservable() .subscribe( {s -> println("result: \t$s") }, {e -> println("error: $e")}, { println ("first onComplete") } ) rm.toObservable().subscribe( { s -> if (s is GetUserJob) { println("getting user!: ${s.result}") } if (s is Job<*> && s.uuid == specialJobId) { println("found special!1: $specialJobId") } }, {e -> println("error: $e")}, { println ("second onComplete") } ) Observable.interval(3, TimeUnit.SECONDS).timeInterval().take(5).toBlocking().subscribe( { rm.request(GetUserJob()) val specialJob = UpdatePostJob() specialJobId = specialJob.uuid rm.request(specialJob) rm.request(UpdatePostJob()) rm.request(UpdatePostJob()) rm.request(UpdatePostJob()) }, { println(it)}, { Thread.sleep(6000)} ) } class GetUserJob() : Job<String>() { override fun run(): Observable<String?> { return Observable.just("_get_user_ ($uuid)").delay(1, TimeUnit.SECONDS) } } class UpdatePostJob() : Job<String>(), IPreventDoubleFiring { override fun run(): Observable<String?> { return Observable.just("_update_post_ ($uuid)").delay(1L + Random().nextInt((3 - 1) + 1), TimeUnit.SECONDS) } } /** * Example of extension for [RequestsManager] * Adding capability to filter out adjacent duplicate jobs */ val PreventDoubleFiring: (Observable<Job<*>>) -> Observable<Job<*>> = { o -> o.distinctUntilChanged{ if (it is IPreventDoubleFiring) it.javaClass.canonicalName else it.uuid } } interface IPreventDoubleFiring {} val LogJobsBeforeTransformers : (Observable<Job<*>>) -> Observable<Job<*>> = { o -> o.map { println("before job: ${it.javaClass.simpleName} \t\t${it.uuid}"); it } } val LogJobsAfterTransformers : (Observable<Job<*>>) -> Observable<Job<*>> = { o -> o.map { println("after job: ${it.javaClass.simpleName} \t\t${it.uuid}"); it } }
2
Kotlin
0
0
e75797be8c98fafcd1a600e00f529a2b05b8db81
2,555
rx-jobqueue
ISC License
dexfile/src/main/kotlin/org/tinygears/bat/dexfile/visitor/DexHeaderVisitor.kt
TinyGearsOrg
562,774,371
false
{"Kotlin": 1879358, "Smali": 712514, "ANTLR": 26362, "Shell": 12090}
/* * Copyright (c) 2020-2022 Thomas Neidhart. * * 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.tinygears.bat.dexfile.visitor import org.tinygears.bat.dexfile.DexFile import org.tinygears.bat.dexfile.DexHeader fun interface DexHeaderVisitor { fun visitHeader(dexFile: DexFile, header: DexHeader) }
0
Kotlin
0
0
50083893ad93820f9cf221598692e81dda05d150
838
bat
Apache License 2.0
brd-android/trade/src/main/java/com/rockwallet/trade/ui/features/authentication/SwapAuthenticationContract.kt
rockwalletcode
598,550,195
false
null
package com.rockwallet.trade.ui.features.authentication import com.rockwallet.common.ui.base.RockWalletContract interface SwapAuthenticationContract { sealed class Event : RockWalletContract.Event { object DismissClicked : Event() object AuthSucceeded : Event() data class AuthFailed(val errorCode: Int) : Event() data class PinValidated(val valid: Boolean) : Event() } sealed class Effect : RockWalletContract.Effect { object ShakeError : Effect() data class Back(val resultKey: String) : Effect() } data class State( val isFingerprintEnabled: Boolean, val authMode: AuthMode ) : RockWalletContract.State enum class AuthMode { /** Attempt biometric auth if configured, otherwise the pin is required. */ USER_PREFERRED, /** Ensures the use of a pin, fails immediately if not set. */ PIN_REQUIRED, /** Ensures the use of biometric auth, fails immediately if not available. */ BIOMETRIC_REQUIRED } }
0
Kotlin
0
0
5eea47948c125678a59ada98bc95f865c81b8531
1,049
oss-wallet-android
MIT License
app/src/main/java/com/junction/watchfrontend/presentation/composables/home/3_RelaxComposable.kt
Junction-2023-Dreams
717,144,429
false
{"Kotlin": 56830}
package com.junction.watchfrontend.presentation.composables.home import android.widget.Toast import androidx.activity.ComponentActivity import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.ScalingLazyColumn import androidx.wear.compose.material.Text import androidx.wear.compose.material.TitleCard import com.junction.watchfrontend.presentation.composables.navigation.Pages import com.junction.watchfrontend.presentation.composables.utils.ColumnComposable import com.junction.watchfrontend.presentation.composables.utils.SpacerComposable import com.junction.watchfrontend.presentation.composables.utils.toast @Composable fun RelaxComposable( activity: ComponentActivity, isDebug: Boolean, startWithBreathingExercise: Boolean = false, navController: NavHostController, ) { ColumnComposable { ScalingLazyColumn( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.background), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { item { Text("Choose Method", color = Color.White) } item { SpacerComposable() } item { TitleCard( modifier = Modifier.width(200.dp), onClick = { navController.navigate(Pages.ExerciseBreath.route) }, title = { Text("Breathing") }, time = { Text("1 min", color = MaterialTheme.colors.primary) }, ) { } } item { SpacerComposable() } item { TitleCard( modifier = Modifier.width(200.dp), onClick = { toast(activity) }, title = { Text("Walking") }, time = { Text("5 min", color = MaterialTheme.colors.primary) }, ) { } } item { SpacerComposable() } item { TitleCard( modifier = Modifier.width(200.dp), onClick = { toast(activity) }, title = { Text("Meditation") }, time = { Text("7 min", color = MaterialTheme.colors.primary) }, ) { } } item { SpacerComposable() } item { TitleCard( modifier = Modifier.width(200.dp), onClick = { Toast.makeText( activity, "Opened on mobile phone", Toast.LENGTH_SHORT, ).show() }, title = { Text("Yoga") }, time = { Text("15 min", color = MaterialTheme.colors.primary) }, ) { Text("Video content in App") } } } } }
0
Kotlin
0
1
7eab4a05aa4d7080f702991c0347a2f33f907913
3,747
frontend-watch
MIT License
app/src/main/java/com/example/comeoneinstein/service/RequestService.kt
Ferguson-fang
401,770,866
false
{"Kotlin": 148146}
package com.example.comeoneinstein.service import retrofit2.http.GET class RequestService { interface VideoService{ } }
0
Kotlin
0
0
8b743ba0eb3f1e11daef400f5f13ea646067a928
129
ComeOnEinstein
Apache License 2.0
app/src/main/java/tr/com/gndg/self/ui/texts/TransactionStockPieceText.kt
Cr3bain
840,332,370
false
{"Kotlin": 567278}
package tr.com.gndg.self.ui.texts import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import tr.com.gndg.self.domain.model.transactions.TransactionData @Composable fun TransactionStockPieceText( modifier: Modifier, textStyle: TextStyle, transactionDataList : List<TransactionData>? ) { var piece by remember { mutableFloatStateOf(0F) } var pieceCount = 0F transactionDataList?.forEach { pieceCount += it.piece } piece = pieceCount Text( style = textStyle, modifier = modifier, text = piece.toString() ) }
0
Kotlin
0
0
12e58c3753a642bfd922d9cca44486eef3453e88
879
self
Apache License 2.0
build/assets/compose/vitaminassets/flags/Yt.kt
Decathlon
511,157,831
false
{"Kotlin": 4443549, "HTML": 226066, "Swift": 163852, "TypeScript": 60822, "CSS": 53872, "JavaScript": 33193, "Handlebars": 771}
package com.decathlon.vitamin.compose.vitaminassets.flags import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush.Companion.linearGradient import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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.group import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.decathlon.vitamin.compose.vitaminassets.FlagsGroup public val FlagsGroup.Yt: ImageVector get() { if (_yt != null) { return _yt!! } _yt = Builder(name = "Yt", defaultWidth = 28.0.dp, defaultHeight = 20.0.dp, viewportWidth = 28.0f, viewportHeight = 20.0f).apply { group { path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0), start = Offset(14.0002f,0.0f), end = Offset(14.0002f,20.0f)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(28.0002f, 0.0f) horizontalLineTo(2.0E-4f) verticalLineTo(20.0f) horizontalLineTo(28.0002f) verticalLineTo(0.0f) close() } path(fill = SolidColor(Color(0xFFD8D8D8)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.6662f, 5.988f) curveTo(10.6662f, 5.6265f, 10.9527f, 5.3334f, 11.3298f, 5.3334f) horizontalLineTo(16.6693f) curveTo(17.0358f, 5.3334f, 17.3329f, 5.6372f, 17.3329f, 5.988f) verticalLineTo(12.6787f) curveTo(17.3329f, 13.0403f, 17.0419f, 13.3439f, 16.6654f, 13.3746f) curveTo(16.6654f, 13.3746f, 14.6662f, 13.3334f, 13.9995f, 14.5874f) curveTo(13.3329f, 13.3334f, 11.3336f, 13.3746f, 11.3336f, 13.3746f) curveTo(10.965f, 13.3518f, 10.6662f, 13.0295f, 10.6662f, 12.6787f) verticalLineTo(5.988f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF979797)), strokeLineWidth = 1.33333f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(16.6662f, 6.0001f) verticalLineTo(5.9881f) curveTo(16.6662f, 5.9973f, 16.6653f, 5.9996f, 16.6662f, 6.0001f) close() moveTo(16.6662f, 6.0001f) curveTo(16.6666f, 6.0003f, 16.6675f, 6.0001f, 16.6692f, 6.0001f) horizontalLineTo(16.6662f) close() moveTo(11.3328f, 6.0001f) verticalLineTo(12.6787f) curveTo(11.3328f, 12.6797f, 11.36f, 12.7083f, 11.3199f, 12.7081f) curveTo(11.3241f, 12.708f, 11.3241f, 12.708f, 11.3321f, 12.7079f) curveTo(11.7884f, 12.7031f, 12.3897f, 12.7723f, 12.999f, 12.9916f) curveTo(13.3793f, 13.1284f, 13.7173f, 13.3123f, 13.9995f, 13.55f) curveTo(14.2816f, 13.3123f, 14.6197f, 13.1284f, 15.0f, 12.9916f) curveTo(15.5916f, 12.7786f, 16.1756f, 12.7072f, 16.6267f, 12.7077f) curveTo(16.6526f, 12.7013f, 16.6662f, 12.686f, 16.6662f, 12.6787f) verticalLineTo(6.0001f) curveTo(16.6662f, 6.0001f, 16.6662f, 6.0001f, 16.6662f, 6.0001f) horizontalLineTo(11.3328f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.3329f, 5.3334f) horizontalLineTo(10.6662f) verticalLineTo(9.3334f) horizontalLineTo(17.3329f) verticalLineTo(5.3334f) close() } path(fill = linearGradient(0.0f to Color(0xFF1B2CA9), 1.0f to Color(0xFF132294), start = Offset(13.9995f,5.33337f), end = Offset(13.9995f,9.33337f)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.3329f, 5.3334f) horizontalLineTo(10.6662f) verticalLineTo(9.3334f) horizontalLineTo(17.3329f) verticalLineTo(5.3334f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.3329f, 9.3334f) horizontalLineTo(10.6662f) verticalLineTo(14.6667f) horizontalLineTo(17.3329f) verticalLineTo(9.3334f) close() } path(fill = linearGradient(0.0f to Color(0xFFE6402C), 1.0f to Color(0xFFD1321F), start = Offset(13.9995f,9.33337f), end = Offset(13.9995f,14.6667f)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.3329f, 9.3334f) horizontalLineTo(10.6662f) verticalLineTo(14.6667f) horizontalLineTo(17.3329f) verticalLineTo(9.3334f) close() } path(fill = linearGradient(0.0f to Color(0xFFD0D0D0), 1.0f to Color(0xFFC4C4C4), start = Offset(21.3376f,4.59187f), end = Offset(21.3376f,14.2899f)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(20.0524f, 6.3011f) verticalLineTo(5.683f) lineTo(20.667f, 5.3333f) curveTo(20.667f, 5.3333f, 20.0602f, 4.5919f, 20.3602f, 4.5919f) curveTo(20.7268f, 4.5919f, 22.2658f, 5.0799f, 22.667f, 5.3333f) curveTo(23.0682f, 5.5867f, 23.2716f, 5.8913f, 23.3281f, 6.4663f) curveTo(23.3845f, 7.0414f, 22.9068f, 7.7751f, 22.9068f, 7.7751f) lineTo(22.667f, 8.333f) lineTo(23.7178f, 8.0953f) curveTo(23.7178f, 8.0953f, 23.8879f, 9.1966f, 23.1144f, 10.0f) curveTo(22.3408f, 10.8034f, 21.2553f, 10.6527f, 21.2553f, 10.6527f) lineTo(21.037f, 10.0f) curveTo(21.037f, 10.0f, 20.3285f, 10.2752f, 19.9118f, 10.8988f) curveTo(19.4952f, 11.5225f, 19.3777f, 12.6003f, 20.0524f, 13.2656f) curveTo(20.7271f, 13.9309f, 21.8404f, 13.8745f, 22.3712f, 12.9392f) curveTo(22.3712f, 12.9392f, 22.5842f, 12.112f, 22.0934f, 11.7231f) curveTo(21.6026f, 11.3341f, 21.2704f, 12.1377f, 21.2553f, 12.0934f) curveTo(21.16f, 11.8129f, 21.037f, 11.3341f, 21.8257f, 11.3341f) curveTo(22.6145f, 11.3341f, 23.0202f, 12.1822f, 22.9068f, 12.8342f) curveTo(22.7933f, 13.4862f, 22.5657f, 14.1053f, 21.037f, 14.2789f) curveTo(19.5083f, 14.4525f, 19.1148f, 12.5148f, 19.1148f, 12.5148f) curveTo(19.1148f, 12.5148f, 18.7251f, 10.7066f, 19.1148f, 9.401f) curveTo(19.5044f, 8.0953f, 20.082f, 8.0629f, 21.2553f, 7.346f) curveTo(22.4287f, 6.6291f, 20.547f, 7.1029f, 20.547f, 7.1029f) curveTo(20.547f, 7.1029f, 19.6534f, 7.7751f, 19.3733f, 7.5304f) curveTo(19.0932f, 7.2858f, 20.0524f, 6.3011f, 20.0524f, 6.3011f) close() } path(fill = linearGradient(0.0f to Color(0xFF262626), 1.0f to Color(0xFF0D0D0D), start = Offset(21.0002f,5.00002f), end = Offset(21.0002f,7.66668f)), stroke = null, fillAlpha = 0.3f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.0002f, 7.6667f) curveTo(21.7366f, 7.6667f, 22.3335f, 7.0697f, 22.3335f, 6.3334f) curveTo(22.3335f, 5.597f, 21.7366f, 5.0f, 21.0002f, 5.0f) curveTo(20.2638f, 5.0f, 19.6669f, 5.597f, 19.6669f, 6.3334f) curveTo(19.6669f, 7.0697f, 20.2638f, 7.6667f, 21.0002f, 7.6667f) close() } path(fill = linearGradient(0.0f to Color(0xFFD0D0D0), 1.0f to Color(0xFFC4C4C4), start = Offset(6.66275f,4.59187f), end = Offset(6.66275f,14.2899f)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(7.948f, 6.3011f) verticalLineTo(5.683f) lineTo(7.3334f, 5.3333f) curveTo(7.3334f, 5.3333f, 7.9402f, 4.5919f, 7.6402f, 4.5919f) curveTo(7.2736f, 4.5919f, 5.7346f, 5.0799f, 5.3334f, 5.3333f) curveTo(4.9322f, 5.5867f, 4.7288f, 5.8913f, 4.6723f, 6.4663f) curveTo(4.6159f, 7.0414f, 5.0936f, 7.7751f, 5.0936f, 7.7751f) lineTo(5.3334f, 8.333f) lineTo(4.2826f, 8.0953f) curveTo(4.2826f, 8.0953f, 4.1125f, 9.1966f, 4.886f, 10.0f) curveTo(5.6596f, 10.8034f, 6.7451f, 10.6527f, 6.7451f, 10.6527f) lineTo(6.9634f, 10.0f) curveTo(6.9634f, 10.0f, 7.6719f, 10.2752f, 8.0886f, 10.8988f) curveTo(8.5052f, 11.5225f, 8.6227f, 12.6003f, 7.948f, 13.2656f) curveTo(7.2733f, 13.9309f, 6.16f, 13.8745f, 5.6292f, 12.9392f) curveTo(5.6292f, 12.9392f, 5.4162f, 12.112f, 5.907f, 11.7231f) curveTo(6.3978f, 11.3341f, 6.73f, 12.1377f, 6.7451f, 12.0934f) curveTo(6.8404f, 11.8129f, 6.9634f, 11.3341f, 6.1747f, 11.3341f) curveTo(5.3859f, 11.3341f, 4.9802f, 12.1822f, 5.0936f, 12.8342f) curveTo(5.2071f, 13.4862f, 5.4347f, 14.1053f, 6.9634f, 14.2789f) curveTo(8.4921f, 14.4525f, 8.8856f, 12.5148f, 8.8856f, 12.5148f) curveTo(8.8856f, 12.5148f, 9.2753f, 10.7066f, 8.8856f, 9.401f) curveTo(8.496f, 8.0953f, 7.9184f, 8.0629f, 6.7451f, 7.346f) curveTo(5.5717f, 6.6291f, 7.4534f, 7.1029f, 7.4534f, 7.1029f) curveTo(7.4534f, 7.1029f, 8.347f, 7.7751f, 8.6271f, 7.5304f) curveTo(8.9072f, 7.2858f, 7.948f, 6.3011f, 7.948f, 6.3011f) close() } path(fill = linearGradient(0.0f to Color(0xFF262626), 1.0f to Color(0xFF0D0D0D), start = Offset(7.00019f,5.00002f), end = Offset(7.00019f,7.66668f)), stroke = null, fillAlpha = 0.3f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.0002f, 7.6667f) curveTo(6.2638f, 7.6667f, 5.6669f, 7.0697f, 5.6669f, 6.3334f) curveTo(5.6669f, 5.597f, 6.2638f, 5.0f, 7.0002f, 5.0f) curveTo(7.7366f, 5.0f, 8.3335f, 5.597f, 8.3335f, 6.3334f) curveTo(8.3335f, 7.0697f, 7.7366f, 7.6667f, 7.0002f, 7.6667f) close() } path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0), start = Offset(14.0002f,6.66667f), end = Offset(14.0002f,8.66667f)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(12.8452f, 6.6667f) curveTo(12.7318f, 6.8628f, 12.6669f, 7.0905f, 12.6669f, 7.3333f) curveTo(12.6669f, 8.0697f, 13.2638f, 8.6667f, 14.0002f, 8.6667f) curveTo(14.7366f, 8.6667f, 15.3335f, 8.0697f, 15.3335f, 7.3333f) curveTo(15.3335f, 7.0905f, 15.2686f, 6.8628f, 15.1552f, 6.6667f) curveTo(14.9246f, 7.0652f, 14.4937f, 7.3333f, 14.0002f, 7.3333f) curveTo(13.5067f, 7.3333f, 13.0758f, 7.0652f, 12.8452f, 6.6667f) close() } path(fill = linearGradient(0.0f to Color(0xFFF7E04B), 1.0f to Color(0xFFEAD135), start = Offset(14.0002f,10.6667f), end = Offset(14.0002f,12.0f)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(12.6669f, 12.0f) curveTo(12.2987f, 12.0f, 12.0002f, 11.7015f, 12.0002f, 11.3333f) curveTo(12.0002f, 10.9651f, 12.2987f, 10.6667f, 12.6669f, 10.6667f) curveTo(13.0351f, 10.6667f, 13.3335f, 10.9651f, 13.3335f, 11.3333f) curveTo(13.3335f, 11.7015f, 13.0351f, 12.0f, 12.6669f, 12.0f) close() moveTo(15.3335f, 12.0f) curveTo(14.9653f, 12.0f, 14.6669f, 11.7015f, 14.6669f, 11.3333f) curveTo(14.6669f, 10.9651f, 14.9653f, 10.6667f, 15.3335f, 10.6667f) curveTo(15.7017f, 10.6667f, 16.0002f, 10.9651f, 16.0002f, 11.3333f) curveTo(16.0002f, 11.7015f, 15.7017f, 12.0f, 15.3335f, 12.0f) close() } } } .build() return _yt!! } private var _yt: ImageVector? = null
25
Kotlin
5
33
852dcd924b82cac447918d2609615819d34caf82
15,490
vitamin-design
Apache License 2.0
responsive_text/android/app/src/main/kotlin/com/example/responsive_text/MainActivity.kt
codetojoy
369,613,234
false
{"Dart": 55178, "HTML": 36968, "Swift": 4040, "Shell": 3542, "Kotlin": 1259, "Objective-C": 380}
package com.example.responsive_text import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
78c6661ea6f4ebea245c182ecd81dffd84e5047e
132
gists-flutter
Apache License 2.0
shared/src/commonMain/kotlin/com/multiplatformkickstarter/app/feature/debugmenu/repositories/GlobalAppSettingsRepository.kt
MultiplatformKickstarter
713,325,823
false
null
package com.myprojectname.app.feature.debugmenu.repositories import com.myprojectname.app.common.model.GeoLocation import com.myprojectname.app.data.repositories.ProfileRepository import com.myprojectname.app.data.repositories.SessionRepository import com.myprojectname.app.localization.AvailableLanguages import com.myprojectname.app.localization.Localization import com.myprojectname.app.platform.Environment import com.myprojectname.app.platform.ServerEnvironment import com.russhwolf.settings.Settings const val ENVIRONMENT_KEY = "ENVIRONMENT_KEY" const val LANGUAGE_KEY = "LANGUAGE_KEY" const val MOCKED_CONTENT_KEY = "MOCKED_CONTENT_KEY" const val MOCKED_USER_KEY = "MOCKED_USER_KEY" class GlobalAppSettingsRepository( private val settings: Settings, private val sessionRepository: SessionRepository, private val profileRepository: ProfileRepository, private val localization: Localization ) { fun getCurrentEnvironment(): Environment { return when (settings.getString(ENVIRONMENT_KEY, ServerEnvironment.PRODUCTION.name)) { ServerEnvironment.PRODUCTION.name -> { ServerEnvironment.PRODUCTION } ServerEnvironment.PREPRODUCTION.name -> { ServerEnvironment.PREPRODUCTION } else -> { ServerEnvironment.LOCALHOST } } } fun getCurrentLanguage(): AvailableLanguages { return when (settings.getString(LANGUAGE_KEY, AvailableLanguages.EN.name)) { AvailableLanguages.EN.name -> AvailableLanguages.EN AvailableLanguages.ES.name -> AvailableLanguages.ES AvailableLanguages.FR.name -> AvailableLanguages.FR AvailableLanguages.IT.name -> AvailableLanguages.IT AvailableLanguages.DE.name -> AvailableLanguages.DE else -> { AvailableLanguages.EN } } } fun isMockedContentEnabled(): Boolean { return settings.getBoolean(MOCKED_CONTENT_KEY, true) } fun setMockedContentCheckStatus(checked: Boolean) { settings.putBoolean(MOCKED_CONTENT_KEY, checked) } fun setSelectedEnvironment(environment: Environment) { settings.putString(ENVIRONMENT_KEY, environment.name) } fun setSelectedLanguage(language: AvailableLanguages) { settings.putString(LANGUAGE_KEY, language.name) } fun isMockedUserEnabled(): Boolean { return settings.getBoolean(MOCKED_USER_KEY, false) } fun setMockedUserCheckStatus(checked: Boolean) { settings.putBoolean(MOCKED_USER_KEY, checked) if (checked) { initMockedUser() } else { sessionRepository.clear() } } private fun initMockedUser() { sessionRepository.initSession( id = -1, email = "<EMAIL>", session = "session", token = "token" ) profileRepository.initProfile( userId = -1, name = "<NAME>", description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi quam purus, auctor non aliquet at, lacinia ut metus. Nam laoreet felis et pharetra elementum.", image = "https://images.unsplash.com/photo-1682977192828-3c59809146f8?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1974&q=80", geoLocation = GeoLocation(41.403785, 2.175651), rating = 4.3 ) } }
2
null
7
96
3cd6e38e97065d3f511878f419fa636c91553c40
3,522
Adoptme
Apache License 2.0
src/main/kotlin/com/freewill/domain/user/entity/User.kt
free-wiII
685,840,987
false
{"Kotlin": 52511}
package com.freewill.domain.user.entity import com.freewill.domain.user.dto.param.OAuth2Param import com.freewill.domain.user.entity.enums.Provider import com.freewill.domain.user.entity.enums.Role import com.freewill.global.audit.AuditEntity import jakarta.persistence.CollectionTable import jakarta.persistence.Column import jakarta.persistence.ElementCollection import jakarta.persistence.Embedded import jakarta.persistence.Entity import jakarta.persistence.EntityListeners import jakarta.persistence.EnumType import jakarta.persistence.Enumerated import jakarta.persistence.FetchType import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.Table import org.hibernate.annotations.DynamicUpdate import org.springframework.data.jpa.domain.support.AuditingEntityListener import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority @Entity @Table(name = "users") @DynamicUpdate @EntityListeners(AuditingEntityListener::class) class User( provider: Provider, providerId: String, providerNickname: String, providerEmail: String?, ) { @Id @Column(name = "user_id") @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null @Column(name = "provider", nullable = false) @Enumerated(EnumType.STRING) val provider: Provider = provider @Column(name = "provider_id", nullable = false) val providerId: String = providerId @Column(name = "provider_nickname", nullable = false) val providerNickname: String = providerNickname @Column(name = "provider_email") val providerEmail: String? = providerEmail @ElementCollection(fetch = FetchType.LAZY) @Enumerated(EnumType.STRING) @CollectionTable(name = "user_roles", joinColumns = [JoinColumn(name = "user_id")]) @Column(name = "role") val role: List<Role> = listOf(Role.ROLE_USER) @Embedded var auditEntity: AuditEntity = AuditEntity() constructor(oAuth2Param: OAuth2Param) : this( provider = oAuth2Param.provider, providerId = oAuth2Param.providerId, providerNickname = oAuth2Param.providerNickname, providerEmail = oAuth2Param.providerEmail ) fun getAuthorities(): MutableCollection<out GrantedAuthority> { return role.stream() .map { SimpleGrantedAuthority(it.name) } .toList() } }
1
Kotlin
0
2
369fdb084428c01ee5eced4f782e22845aff5fdf
2,515
synergy-be
MIT License
src/main/kotlin/com/freewill/domain/user/entity/User.kt
free-wiII
685,840,987
false
{"Kotlin": 52511}
package com.freewill.domain.user.entity import com.freewill.domain.user.dto.param.OAuth2Param import com.freewill.domain.user.entity.enums.Provider import com.freewill.domain.user.entity.enums.Role import com.freewill.global.audit.AuditEntity import jakarta.persistence.CollectionTable import jakarta.persistence.Column import jakarta.persistence.ElementCollection import jakarta.persistence.Embedded import jakarta.persistence.Entity import jakarta.persistence.EntityListeners import jakarta.persistence.EnumType import jakarta.persistence.Enumerated import jakarta.persistence.FetchType import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.Table import org.hibernate.annotations.DynamicUpdate import org.springframework.data.jpa.domain.support.AuditingEntityListener import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority @Entity @Table(name = "users") @DynamicUpdate @EntityListeners(AuditingEntityListener::class) class User( provider: Provider, providerId: String, providerNickname: String, providerEmail: String?, ) { @Id @Column(name = "user_id") @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null @Column(name = "provider", nullable = false) @Enumerated(EnumType.STRING) val provider: Provider = provider @Column(name = "provider_id", nullable = false) val providerId: String = providerId @Column(name = "provider_nickname", nullable = false) val providerNickname: String = providerNickname @Column(name = "provider_email") val providerEmail: String? = providerEmail @ElementCollection(fetch = FetchType.LAZY) @Enumerated(EnumType.STRING) @CollectionTable(name = "user_roles", joinColumns = [JoinColumn(name = "user_id")]) @Column(name = "role") val role: List<Role> = listOf(Role.ROLE_USER) @Embedded var auditEntity: AuditEntity = AuditEntity() constructor(oAuth2Param: OAuth2Param) : this( provider = oAuth2Param.provider, providerId = oAuth2Param.providerId, providerNickname = oAuth2Param.providerNickname, providerEmail = oAuth2Param.providerEmail ) fun getAuthorities(): MutableCollection<out GrantedAuthority> { return role.stream() .map { SimpleGrantedAuthority(it.name) } .toList() } }
1
Kotlin
0
2
369fdb084428c01ee5eced4f782e22845aff5fdf
2,515
synergy-be
MIT License
material/src/main/java/com/m3u/material/components/mask/Mask.kt
realOxy
592,741,804
false
{"Kotlin": 610231, "Ruby": 955}
package com.m3u.material.components.mask import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.layout.BoxScope import androidx.compose.material3.LocalContentColor import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.m3u.material.components.Background import com.m3u.material.components.OuterBox @Composable fun Mask( state: MaskState, modifier: Modifier = Modifier, color: Color = Color.Unspecified, contentColor: Color = LocalContentColor.current, content: @Composable BoxScope.() -> Unit ) { AnimatedVisibility( visible = state.visible, enter = fadeIn(), exit = fadeOut() ) { Background(color = color, contentColor = contentColor) { OuterBox( modifier = modifier, content = content ) } } }
11
Kotlin
7
70
d2e6fe6b71c5d3eed9f2bce98a50bf30df0a6134
1,018
M3UAndroid
Apache License 2.0
core/data/src/main/kotlin/com/example/visitedcountries/data/repository/home/HomeRepository.kt
tecruz
858,709,650
false
{"Kotlin": 165426}
/* * Designed and developed by 2024 tecruz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.visitedcountries.data.repository.home import com.example.visitedcoutries.model.Country import kotlinx.coroutines.flow.Flow interface HomeRepository { fun fetchCountryList(onStart: () -> Unit, onComplete: () -> Unit, onError: (String?) -> Unit): Flow<List<Country>> }
1
Kotlin
0
0
ee2f34939b17b387fcd67eab7a2308b7c7578bd4
894
VisitedCountries
Apache License 2.0
accountant/accountant-ports/accountant-wallet-proxy/src/test/kotlin/co/nilin/opex/accountant/ports/walletproxy/proxy/WalletProxyImplTest.kt
opexdev
370,411,517
false
null
package co.nilin.opex.accountant.ports.walletproxy.proxy import co.nilin.opex.accountant.core.model.WalletType import co.nilin.opex.accountant.ports.walletproxy.data.Amount import co.nilin.opex.accountant.ports.walletproxy.data.Currency import co.nilin.opex.accountant.ports.walletproxy.data.TransferResult import com.fasterxml.jackson.databind.ObjectMapper import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockserver.client.MockServerClient import org.mockserver.integration.ClientAndServer import org.mockserver.model.HttpRequest.request import org.mockserver.model.HttpResponse.response import org.mockserver.model.MediaType import org.springframework.web.reactive.function.client.WebClient import java.math.BigDecimal class WalletProxyImplTest { private lateinit var mockServer: MockServerClient private val walletProxyImpl = WalletProxyImpl( WebClient.builder().build(), "http://localhost:8089" ) private val objectMapper = ObjectMapper() @BeforeEach fun setUp() { mockServer = ClientAndServer.startClientAndServer(8089) } @AfterEach fun tearDown() { mockServer.close() } @Test fun givenAdditionalData_whenTransfer_ok() { val symbol = "ETHBTC" val senderWalletType = WalletType.MAIN val senderUuid = "1" val receiverWalletType = WalletType.EXCHANGE val receiverUuid = "2" val amount = BigDecimal.ONE val description = "desc" val transferRef = "ref" val transferCategory = "ORDER_CREATE" val amountObject = Amount(Currency(symbol, symbol, 1), amount) mockServer.`when`( request().withMethod("POST") .withPath("/v2/transfer/${amount}_$symbol/from/${senderUuid}_$senderWalletType/to/${receiverUuid}_$receiverWalletType") .withBody( objectMapper.writeValueAsString( WalletProxyImpl.TransferBody( description, transferRef, transferCategory ) ) ) ).respond( response() .withStatusCode(200) .withContentType(MediaType.APPLICATION_JSON) .withBody( objectMapper.writeValueAsString( TransferResult( System.currentTimeMillis(), senderUuid, senderWalletType, amountObject, amountObject, amountObject, receiverUuid, receiverWalletType, amountObject ) ) ) ) runBlocking { walletProxyImpl.transfer( symbol, senderWalletType, senderUuid, receiverWalletType, receiverUuid, amount, description, transferRef, transferCategory ) } } }
30
null
22
51
fedf3be46ee7fb85ca7177ae91b13dbc6f2e8a73
3,361
core
MIT License
kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/hostnames.kt
ichaki5748
124,968,379
true
{"Kotlin": 309714}
// GENERATED package com.fkorotkov.kubernetes import io.fabric8.kubernetes.api.model.HostAlias import kotlin.collections.List fun HostAlias.`hostname`(value: kotlin.String) { this.`hostnames`.add(value) }
0
Kotlin
0
0
b00b6ddb4b851a864a2737a3374603f7db659af7
211
k8s-kotlin-dsl
MIT License
app/src/main/java/eu/ginlo_apps/ginlo/services/LoadPendingAttachmentTask.kt
cdskev
358,279,979
false
{"Git Config": 1, "Gradle": 3, "Markdown": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Text": 2, "Proguard": 1, "INI": 1, "XML": 393, "Java": 438, "Kotlin": 168, "JSON": 1, "HTML": 1}
// Copyright (c) 2020-2024 ginlo.net GmbH package eu.ginlo_apps.ginlo.services import android.content.Intent import android.util.Base64 import androidx.core.app.JobIntentService import com.google.gson.JsonArray import com.google.gson.JsonPrimitive import eu.ginlo_apps.ginlo.context.SimsMeApplication import eu.ginlo_apps.ginlo.controller.AttachmentController import eu.ginlo_apps.ginlo.exception.LocalizedException import eu.ginlo_apps.ginlo.greendao.Message import eu.ginlo_apps.ginlo.greendao.MessageDao import eu.ginlo_apps.ginlo.greendao.Preference import eu.ginlo_apps.ginlo.log.LogUtil import eu.ginlo_apps.ginlo.model.constant.AppConstants import eu.ginlo_apps.ginlo.model.constant.BackendError import eu.ginlo_apps.ginlo.service.BackendService import eu.ginlo_apps.ginlo.service.IBackendService import eu.ginlo_apps.ginlo.util.FileUtil import eu.ginlo_apps.ginlo.util.MimeUtil import java.util.concurrent.CountDownLatch class LoadPendingAttachmentTask : JobIntentService() { override fun onHandleWork(intent: Intent) { try { val application = SimsMeApplication.getInstance() if (!BackendService.withAsyncConnection(application).isConnected) { return } var messages = getNextMessages(application, -1L) while (!messages.isEmpty()) { var messageId = -1L for (message in messages) { if (messageId < message.id) { messageId = message.id ?: -1 } if (SimsMeApplication.getInstance().attachmentController.isAttachmentLocallyAvailable(message.attachment)) { continue } if (message.isAttachmentDeletedServer) { continue } val contentType = message.serverMimeType ?: return contentType.replace("/selfdest".toRegex(), "") if (shouldDownload(contentType, application)) { downloadAttachment(message, application) } } messages = getNextMessages(application, messageId) } } catch (e: LocalizedException) { LogUtil.e(LoadPendingAttachmentTask::javaClass.name, "Failed to download attachment.", e) } } private fun downloadAttachment( message: Message, application: SimsMeApplication ) { val latch = CountDownLatch(1) val onBackendResponseListener = IBackendService.OnBackendResponseListener { response -> try { if (response.isError) { if (response.msgException?.ident == BackendError.ERR_0026_CANT_OPEN_MESSAGE) { message.isAttachmentDeletedServer = true application.messageController.dao.update(message) } } else { if (response.responseFilename != null) { val base64file = AttachmentController. convertJsonArrayFileToEncryptedAttachmentBase64File(response.responseFilename, message.attachment).toString() // TODO: Separate (expensive!) file conversion calls right now. Must be combined later. AttachmentController.saveBase64FileAsEncryptedAttachment(message.attachment, base64file) LogUtil.d(LoadPendingAttachmentTask::javaClass.name, "Saved attachment from file for: " + message.attachment) FileUtil.deleteFile(base64file) // TODO: Don't forget to delete intermediate files after testing! } else if (response.jsonArray?.get(0) != null) { val content = Base64.decode(response.jsonArray.get(0).asString, Base64.NO_WRAP) AttachmentController.saveEncryptedMessageAttachment(content, message.attachment) LogUtil.d(LoadPendingAttachmentTask::javaClass.name, "Saved attachment from memory for: " + message.attachment) } val jsonArray = JsonArray().apply { add(JsonPrimitive(message.guid)) } BackendService.withSyncConnection(application) .setMessageState( jsonArray, AppConstants.MESSAGE_STATE_ATTACHMENT_DOWNLOADED, null, false ) application.messageController.sendMessageChangedNotification(listOf(message)) } } finally { latch.countDown() } } BackendService.withSyncConnection(application) .getAttachment(message.attachment, onBackendResponseListener, null) try { latch.await() } catch (e: InterruptedException) { LogUtil.e(this.javaClass.name, e.message, e) } } private fun shouldDownload( contentType: String, application: SimsMeApplication ): Boolean { val isConnectedViaWLAN = BackendService.withSyncConnection(application).isConnectedViaWLAN if (MimeUtil.isRichContentMimetype(contentType)) { if (application.preferencesController.getAlwaysDownloadRichContent() || application.preferencesController.automaticDownloadFiles == Preference.AUTOMATIC_DOWNLOAD_ALWAYS || (application.preferencesController.automaticDownloadFiles == Preference.AUTOMATIC_DOWNLOAD_WLAN && isConnectedViaWLAN) ) { return true } } if (contentType.equals(MimeUtil.MIME_TYPE_IMAGE_JPEG, ignoreCase = true)) { if (application.preferencesController.automaticDownloadPicture == Preference.AUTOMATIC_DOWNLOAD_ALWAYS || (application.preferencesController.automaticDownloadPicture == Preference.AUTOMATIC_DOWNLOAD_WLAN && isConnectedViaWLAN) ) { return true } } if (contentType.equals(MimeUtil.MIME_TYPE_AUDIO_MPEG, ignoreCase = true)) { if (application.preferencesController.automaticDownloadVoice == Preference.AUTOMATIC_DOWNLOAD_ALWAYS || (application.preferencesController.automaticDownloadVoice == Preference.AUTOMATIC_DOWNLOAD_WLAN && isConnectedViaWLAN) ) { return true } } if (contentType.equals(MimeUtil.MIME_TYPE_VIDEO_MPEG, ignoreCase = true)) { if (application.preferencesController.automaticDownloadVideo == Preference.AUTOMATIC_DOWNLOAD_ALWAYS || (application.preferencesController.automaticDownloadVideo == Preference.AUTOMATIC_DOWNLOAD_WLAN && isConnectedViaWLAN) ) { return true } } if (MimeUtil.hasUnspecificBinaryMimeType(contentType)) { if (application.preferencesController.automaticDownloadFiles == Preference.AUTOMATIC_DOWNLOAD_ALWAYS || (application.preferencesController.automaticDownloadFiles == Preference.AUTOMATIC_DOWNLOAD_WLAN && isConnectedViaWLAN) ) { return true } } return false } override fun onStopCurrentWork(): Boolean { LogUtil.i(LoadPendingAttachmentTask::javaClass.name, "processorFinished") return super.onStopCurrentWork() } private fun getNextMessages(application: SimsMeApplication, messageId: Long): List<Message> { synchronized(application.messageController.dao) { val queryBuilder = application.messageController.dao.queryBuilder() queryBuilder.where(MessageDao.Properties.Attachment.isNotNull).whereOr( MessageDao.Properties.Type.eq(Message.TYPE_GROUP), MessageDao.Properties.Type.eq( Message.TYPE_PRIVATE ) ).where(MessageDao.Properties.Id.gt(messageId)) queryBuilder.orderAsc(MessageDao.Properties.Id).limit(30) return queryBuilder.build().forCurrentThread().list() } } companion object { fun start() { val intent = Intent(SimsMeApplication.getInstance(), LoadPendingAttachmentTask::class.java) enqueueWork(SimsMeApplication.getInstance(), LoadPendingAttachmentTask::class.java, 1, intent) } } }
1
Java
0
5
5609a68a539fc5fd9666d3d5f93be750fa5a2b77
8,704
ginlo-android
Apache License 2.0
service/src/main/kotlin/org/opensearch/simpleschema/index/SimpleSearchIndex.kt
dblock
688,234,127
true
{"Markdown": 27, "Gradle": 6, "Shell": 3, "EditorConfig": 1, "Batchfile": 2, "Text": 1, "YAML": 15, "Ignore List": 4, "Git Config": 1, "GraphQL": 44, "Protocol Buffer": 2, "JSON": 14, "CODEOWNERS": 1, "Java Properties": 2, "Java": 203, "Kotlin": 62, "XML": 3}
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.opensearch.simpleschema.index import org.opensearch.ResourceAlreadyExistsException import org.opensearch.action.ActionListener import org.opensearch.action.DocWriteResponse import org.opensearch.action.admin.indices.create.CreateIndexAction import org.opensearch.action.admin.indices.create.CreateIndexRequest import org.opensearch.action.admin.indices.create.CreateIndexResponse import org.opensearch.action.admin.indices.mapping.put.PutMappingRequest import org.opensearch.action.bulk.BulkRequest import org.opensearch.action.delete.DeleteRequest import org.opensearch.action.get.GetRequest import org.opensearch.action.get.GetResponse import org.opensearch.action.get.MultiGetRequest import org.opensearch.action.index.IndexRequest import org.opensearch.action.search.SearchRequest import org.opensearch.action.update.UpdateRequest import org.opensearch.client.Client import org.opensearch.cluster.ClusterChangedEvent import org.opensearch.cluster.ClusterState import org.opensearch.cluster.ClusterStateListener import org.opensearch.cluster.service.ClusterService import org.opensearch.common.component.LifecycleListener import org.opensearch.common.unit.TimeValue import org.opensearch.common.xcontent.LoggingDeprecationHandler import org.opensearch.common.xcontent.NamedXContentRegistry import org.opensearch.common.xcontent.XContentType import org.opensearch.index.IndexNotFoundException import org.opensearch.index.query.QueryBuilders import org.opensearch.rest.RestStatus import org.opensearch.search.SearchHit import org.opensearch.search.builder.SearchSourceBuilder import org.opensearch.simpleschema.SimpleSchemaPlugin.Companion.LOG_PREFIX import org.opensearch.simpleschema.action.GetSimpleSchemaObjectRequest import org.opensearch.simpleschema.model.RestTag.ACCESS_LIST_FIELD import org.opensearch.simpleschema.model.RestTag.TENANT_FIELD import org.opensearch.simpleschema.model.SearchResults import org.opensearch.simpleschema.model.SimpleSchemaObjectDoc import org.opensearch.simpleschema.model.SimpleSchemaObjectDocInfo import org.opensearch.simpleschema.model.SimpleSchemaObjectSearchResult import org.opensearch.simpleschema.settings.PluginSettings import org.opensearch.simpleschema.util.SecureIndexClient import org.opensearch.simpleschema.util.logger import java.util.concurrent.TimeUnit /** * Class for doing OpenSearch index operation to maintain SimpleSchema objects in cluster. */ @Suppress("TooManyFunctions") internal object SimpleSearchIndex : LifecycleListener() { private val log by logger(SimpleSearchIndex::class.java) private const val INDEX_NAME = ".opensearch-simpleschema" private const val SIMPLESCHEMA_MAPPING_FILE_NAME = "simpleschema-mapping.yml" private const val SIMPLESCHEMA_SETTINGS_FILE_NAME = "simpleschema-settings.yml" private var mappingsUpdated: Boolean = false private lateinit var client: Client private lateinit var clusterService: ClusterService private val searchHitParser = object : SearchResults.SearchHitParser<SimpleSchemaObjectDoc> { override fun parse(searchHit: SearchHit): SimpleSchemaObjectDoc { val parser = XContentType.JSON.xContent().createParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, searchHit.sourceAsString ) parser.nextToken() return SimpleSchemaObjectDoc.parse(parser, searchHit.id) } } /** * Initialize the class * @param client The OpenSearch client * @param clusterService The OpenSearch cluster service */ fun initialize(client: Client, clusterService: ClusterService): SimpleSearchIndex { SimpleSearchIndex.client = SecureIndexClient(client) SimpleSearchIndex.clusterService = clusterService mappingsUpdated = false return this } /** * once lifecycle indicate start has occurred - instantiating system index creation */ override fun afterStart() { // create default index createIndex() } /** * Create index using the mapping and settings defined in resource */ @Suppress("TooGenericExceptionCaught") private fun createIndex() { if (!isIndexExists(INDEX_NAME)) { val request = createIndexRequest() try { val actionFuture = client.admin().indices().create(request) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) if (response.isAcknowledged) { log.info("$LOG_PREFIX:Index $INDEX_NAME creation Acknowledged") } else { throw IllegalStateException("$LOG_PREFIX:Index $INDEX_NAME creation not Acknowledged") } } catch (exception: Exception) { if (exception !is ResourceAlreadyExistsException && exception.cause !is ResourceAlreadyExistsException) { throw exception } } mappingsUpdated = true } else if (!mappingsUpdated) { updateMappings() } } private fun createIndexRequest(): CreateIndexRequest? { val classLoader = SimpleSearchIndex::class.java.classLoader val indexMappingSource = classLoader.getResource(SIMPLESCHEMA_MAPPING_FILE_NAME)?.readText()!! val indexSettingsSource = classLoader.getResource(SIMPLESCHEMA_SETTINGS_FILE_NAME)?.readText()!! val request = CreateIndexRequest(INDEX_NAME) .mapping(indexMappingSource, XContentType.YAML) .settings(indexSettingsSource, XContentType.YAML) return request } @Suppress("TooGenericExceptionCaught") private fun indexCreateCall() { val request = createIndexRequest() try { client.execute(CreateIndexAction.INSTANCE, request, object : ActionListener<CreateIndexResponse> { override fun onResponse(response: CreateIndexResponse) { if (response.isAcknowledged) { log.info("$LOG_PREFIX:Index $INDEX_NAME creation Acknowledged") } else { log.warn("$LOG_PREFIX:Index $INDEX_NAME creation not Acknowledged") } } override fun onFailure(err: java.lang.Exception?) { log.error("$LOG_PREFIX:Index $INDEX_NAME creation not Acknowledged", err) } }) } catch (exception: Exception) { if (exception !is ResourceAlreadyExistsException && exception.cause !is ResourceAlreadyExistsException) { throw exception } } } /** * Check if the index mappings have changed and if they have, update them */ private fun updateMappings() { val classLoader = SimpleSearchIndex::class.java.classLoader val indexMappingSource = classLoader.getResource(SIMPLESCHEMA_MAPPING_FILE_NAME)?.readText()!! val request = PutMappingRequest(INDEX_NAME) .source(indexMappingSource, XContentType.YAML) try { val actionFuture = client.admin().indices().putMapping(request) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) if (response.isAcknowledged) { log.info("$LOG_PREFIX:Index $INDEX_NAME update mapping Acknowledged") } else { throw IllegalStateException("$LOG_PREFIX:Index $INDEX_NAME update mapping not Acknowledged") } mappingsUpdated = true } catch (exception: IndexNotFoundException) { log.error("$LOG_PREFIX:IndexNotFoundException:", exception) } } /** * Check if the index is created and available. * @param index * @return true if index is available, false otherwise */ private fun isIndexExists(index: String): Boolean { val clusterState = clusterService.state() return clusterState.routingTable.hasIndex(index) } /** * Create object * * @param simpleSchemaObjectDoc * @param id * @return object id if successful, otherwise null */ fun createSimpleSchemaObject(simpleSchemaObjectDoc: SimpleSchemaObjectDoc, id: String? = null): String? { createIndex() val xContent = simpleSchemaObjectDoc.toXContent() val indexRequest = IndexRequest(INDEX_NAME) .source(xContent) .create(true) if (id != null) { indexRequest.id(id) } val actionFuture = client.index(indexRequest) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) return if (response.result != DocWriteResponse.Result.CREATED) { log.warn("$LOG_PREFIX:createSimpleSchemaObject - response:$response") null } else { response.id } } /** * Get object * * @param id * @return [SimpleSchemaObjectDocInfo] */ fun getSimpleSchemaObject(id: String): SimpleSchemaObjectDocInfo? { createIndex() val getRequest = GetRequest(INDEX_NAME).id(id) val actionFuture = client.get(getRequest) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) return parseSimpleSchemaObjectDoc(id, response) } /** * Get multiple objects * * @param ids * @return list of [SimpleSchemaObjectDocInfo] */ fun getSimpleSchemaObjects(ids: Set<String>): List<SimpleSchemaObjectDocInfo> { createIndex() val getRequest = MultiGetRequest() ids.forEach { getRequest.add(INDEX_NAME, it) } val actionFuture = client.multiGet(getRequest) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) return response.responses.mapNotNull { parseSimpleSchemaObjectDoc(it.id, it.response) } } /** * Parse object doc * * @param id * @param response * @return [SimpleSchemaObjectDocInfo] */ private fun parseSimpleSchemaObjectDoc(id: String, response: GetResponse): SimpleSchemaObjectDocInfo? { return if (response.sourceAsString == null) { log.warn("$LOG_PREFIX:getSimpleSchemaObject - $id not found; response:$response") null } else { val parser = XContentType.JSON.xContent().createParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, response.sourceAsString ) parser.nextToken() val doc = SimpleSchemaObjectDoc.parse(parser, id) SimpleSchemaObjectDocInfo(id, response.version, response.seqNo, response.primaryTerm, doc) } } /** * Get all objects * * @param tenant * @param access * @param request * @return [SimpleSchemaObjectSearchResult] */ fun getAllSimpleSchemaObjects( tenant: String, access: List<String>, request: GetSimpleSchemaObjectRequest ): SimpleSchemaObjectSearchResult { createIndex() val queryHelper = SimpleSearchQueryHelper(request.types) val sourceBuilder = SearchSourceBuilder() .timeout(TimeValue(PluginSettings.operationTimeoutMs, TimeUnit.MILLISECONDS)) .size(request.maxItems) .from(request.fromIndex) queryHelper.addSortField(sourceBuilder, request.sortField, request.sortOrder) val query = QueryBuilders.boolQuery() query.filter(QueryBuilders.termsQuery(TENANT_FIELD, tenant)) if (access.isNotEmpty()) { query.filter(QueryBuilders.termsQuery(ACCESS_LIST_FIELD, access)) } queryHelper.addTypeFilters(query) queryHelper.addQueryFilters(query, request.filterParams) sourceBuilder.query(query) val searchRequest = SearchRequest() .indices(INDEX_NAME) .source(sourceBuilder) val actionFuture = client.search(searchRequest) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) val result = SimpleSchemaObjectSearchResult(request.fromIndex.toLong(), response, searchHitParser) log.info( "$LOG_PREFIX:getAllSimpleSchemaObjects types:${request.types} from:${request.fromIndex}, maxItems:${request.maxItems}," + " sortField:${request.sortField}, sortOrder=${request.sortOrder}, filters=${request.filterParams}" + " retCount:${result.objectList.size}, totalCount:${result.totalHits}" ) return result } /** * Update object * * @param id * @param simpleSchemaObjectDoc * @return true if successful, otherwise false */ fun updateSimpleSchemaObject(id: String, simpleSchemaObjectDoc: SimpleSchemaObjectDoc): Boolean { createIndex() val updateRequest = UpdateRequest() .index(INDEX_NAME) .id(id) .doc(simpleSchemaObjectDoc.toXContent()) .fetchSource(true) val actionFuture = client.update(updateRequest) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) if (response.result != DocWriteResponse.Result.UPDATED) { log.warn("$LOG_PREFIX:updateSimpleSchemaObject failed for $id; response:$response") } return response.result == DocWriteResponse.Result.UPDATED } /** * Delete object * * @param id * @return true if successful, otherwise false */ fun deleteSimpleSchemaObject(id: String): Boolean { createIndex() val deleteRequest = DeleteRequest() .index(INDEX_NAME) .id(id) val actionFuture = client.delete(deleteRequest) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) if (response.result != DocWriteResponse.Result.DELETED) { log.warn("$LOG_PREFIX:deleteSimpleSchemaObject failed for $id; response:$response") } return response.result == DocWriteResponse.Result.DELETED } /** * Delete multiple objects * * @param ids * @return map of id to delete status */ fun deleteSimpleSchemaObjects(ids: Set<String>): Map<String, RestStatus> { createIndex() val bulkRequest = BulkRequest() ids.forEach { val deleteRequest = DeleteRequest() .index(INDEX_NAME) .id(it) bulkRequest.add(deleteRequest) } val actionFuture = client.bulk(bulkRequest) val response = actionFuture.actionGet(PluginSettings.operationTimeoutMs) val mutableMap = mutableMapOf<String, RestStatus>() response.forEach { mutableMap[it.id] = it.status() if (it.isFailed) { log.warn("$LOG_PREFIX:deleteSimpleSchemaObjects failed for ${it.id}; response:${it.failureMessage}") } } return mutableMap } }
0
null
0
0
98a719e4dd8aae9ea85257822a709d6c8b44a9b8
15,159
simple-schema
Apache License 2.0
compass-autocomplete-web/src/commonMain/kotlin/dev/jordond/compass/autocomplete/web/HttpAutocompleteService.kt
jordond
772,795,864
false
{"Kotlin": 262383}
package dev.jordond.compass.autocomplete.web import dev.jordond.compass.autocomplete.AutocompleteService import dev.jordond.compass.tools.web.HttpApiEndpoint import dev.jordond.compass.tools.web.makeRequest import io.ktor.client.HttpClient import kotlinx.serialization.json.Json /** * Represents an HTTP endpoint that can be used to search for autocomplete suggestions. * * @param T The type of the autocomplete suggestions. */ public typealias SearchEndpoint <T> = HttpApiEndpoint<String, List<T>> /** * Represents an autocomplete service that uses an HTTP endpoint to search for suggestions. * * @param T The type of the autocomplete suggestions. */ public interface HttpAutocompleteService<T> : AutocompleteService<T> { public companion object } /** * Creates an [HttpAutocompleteService] that uses the specified [searchEndpoint] to search for * autocomplete suggestions. * * @param T The type of the autocomplete suggestions. * @param searchEndpoint The HTTP endpoint to use for searching. * @param json The JSON serializer to use. * @param client The HTTP client to use. * @return An [HttpAutocompleteService] that uses the specified [searchEndpoint] to search for * autocomplete suggestions. */ public fun <T> HttpAutocompleteService( searchEndpoint: SearchEndpoint<T>, json: Json = HttpApiEndpoint.json(), client: HttpClient = HttpApiEndpoint.httpClient(json), ): HttpAutocompleteService<T> = object : HttpAutocompleteService<T> { override fun isAvailable(): Boolean = true override suspend fun search(query: String): List<T> { val url = searchEndpoint.url(query) return client.makeRequest(url, searchEndpoint::mapResponse) } }
5
Kotlin
4
89
d0ef39ed66f7af237bbe21ba630dfcdd6f2ff258
1,703
compass
MIT License
base/src/main/java/com/chrisjanusa/restaurant_base/deeplinks/events/OpenYelpEvent.kt
chrisjanusa
209,855,968
false
null
package com.chrisjanusa.restaurant_base.deeplinks.events import com.chrisjanusa.base.interfaces.BaseEvent import com.chrisjanusa.base.interfaces.BaseRestaurantFragment import com.chrisjanusa.restaurant_base.deeplinks.DeeplinkHelper.openDeeplink class OpenYelpEvent(private val url: String) : BaseEvent{ override fun handleEvent(fragment: BaseRestaurantFragment) { fragment.context?.let { openDeeplink(url, it) } } }
1
Kotlin
0
0
4c675b740ccf2cf29630bf82c50c04ed5113249c
434
RandomRestaurantKotlin
MIT License
compiler/testData/diagnostics/testsWithStdLib/annotations/kClass/kClassArrayInAnnotationsOutVariance.fir.kt
nskvortsov
4,137,859
false
null
// !WITH_NEW_INFERENCE import kotlin.reflect.KClass open class A class B1 : A() class B2 : A() annotation class Ann1(val arg: Array<KClass<out A>>) @Ann1(arrayOf(A::class)) class MyClass1 <!INAPPLICABLE_CANDIDATE!>@Ann1(arrayOf(Any::class))<!> class MyClass1a @Ann1(arrayOf(B1::class)) class MyClass2 annotation class Ann2(val arg: Array<KClass<out B1>>) <!INAPPLICABLE_CANDIDATE!>@Ann2(arrayOf(A::class))<!> class MyClass3 @Ann2(arrayOf(B1::class)) class MyClass4 <!INAPPLICABLE_CANDIDATE!>@Ann2(arrayOf(B2::class))<!> class MyClass5
0
null
0
3
39d15501abb06f18026bbcabfd78ae4fbcbbe2cb
545
kotlin
Apache License 2.0
ios/src/iosMain/kotlin/co/touchlab/droidcon/ios/viewmodel/session/ScheduleViewModel.kt
touchlab
140,843,272
false
null
package co.touchlab.droidcon.ios.viewmodel.session import co.touchlab.droidcon.domain.gateway.SessionGateway import co.touchlab.droidcon.domain.service.DateTimeService class ScheduleViewModel( sessionGateway: SessionGateway, sessionDayFactory: SessionDayViewModel.Factory, sessionDetailFactory: SessionDetailViewModel.Factory, dateTimeService: DateTimeService, ): BaseSessionListViewModel( sessionGateway, sessionDayFactory, sessionDetailFactory, dateTimeService, attendingOnly = false, ) { class Factory( private val sessionGateway: SessionGateway, private val sessionDayFactory: SessionDayViewModel.Factory, private val sessionDetailFactory: SessionDetailViewModel.Factory, private val dateTimeService: DateTimeService, ) { fun create() = ScheduleViewModel(sessionGateway, sessionDayFactory, sessionDetailFactory, dateTimeService) } }
2
Kotlin
50
508
1945062f68bc5fbf76eb6d69c131b8f8fa8126c8
926
DroidconKotlin
Apache License 2.0
app/src/androidTest/java/com/example/android/shoppingList/ListaDeComprasDaoTest.kt
gabrieltobias
511,706,920
false
{"Kotlin": 45639}
package com.example.android.shoppingList import android.content.Context import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.android.shoppingList.dados.ListasRoomDatabase import com.example.android.shoppingList.apresentacao.model.ListaDeCompras import com.example.android.shoppingList.dados.ListaDeComprasDao import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.io.IOException /** * This is not meant to be a full set of tests. For simplicity, most of your samples do not * include tests. However, when building the Room, it is helpful to make sure it works before * adding the UI. */ @RunWith(AndroidJUnit4::class) class ListaDeComprasDaoTest { private lateinit var listaDeComprasDao: ListaDeComprasDao private lateinit var db: ListasRoomDatabase @Before fun createDb() { val context: Context = ApplicationProvider.getApplicationContext() // Using an in-memory database because the information stored here disappears when the // process is killed. db = Room.inMemoryDatabaseBuilder(context, ListasRoomDatabase::class.java) // Allowing main thread queries, just for testing. .allowMainThreadQueries() .build() listaDeComprasDao = db.listaDao() } @After @Throws(IOException::class) fun closeDb() { db.close() } @Test @Throws(Exception::class) fun insertAndGetWord() = runBlocking { val listaDeCompras = ListaDeCompras(22,"Testeee3") listaDeComprasDao.insert(listaDeCompras) val allWords = listaDeComprasDao.GetListas().first() assertEquals(allWords[0].NomeLista, listaDeCompras.NomeLista) } @Test @Throws(Exception::class) fun getAllWords() = runBlocking { val listaDeCompras = ListaDeCompras(1,"teste") listaDeComprasDao.insert(listaDeCompras) val listaDeCompras2 = ListaDeCompras(2,"Teste2") listaDeComprasDao.insert(listaDeCompras2) val allWords = listaDeComprasDao.GetListas().first() assertEquals(allWords[0].NomeLista, listaDeCompras.NomeLista) assertEquals(allWords[1].NomeLista, listaDeCompras2.NomeLista) } @Test @Throws(Exception::class) fun deleteAll() = runBlocking { val listaDeCompras = ListaDeCompras(33,"Teste1") listaDeComprasDao.insert(listaDeCompras) val listaDeCompras2 = ListaDeCompras(44,"Teste22112") listaDeComprasDao.insert(listaDeCompras2) listaDeComprasDao.deleteAll() val allWords = listaDeComprasDao.GetListas().first() assertTrue(allWords.isEmpty()) } }
0
Kotlin
0
0
fca3209abba808492407bce43351570ce073bec0
2,910
SpList
Apache License 2.0
lazycolumnscreen/shot/src/androidTest/java/com/example/road/to/effective/snapshot/testing/lazycolumnscreen/shot/compose/parameterized/CoffeeDrinkListComposableWithTestParameterInjectorTest.kt
sergio-sastre
394,010,429
false
null
package com.example.road.to.effective.snapshot.testing.lazycolumnscreen.shot.compose.parameterized import androidx.test.filters.SdkSuppress import com.example.road.to.effective.snapshot.testing.lazycolumnscreen.AppTheme import com.example.road.to.effective.snapshot.testing.lazycolumnscreen.CoffeeDrinkList import com.example.road.to.effective.snapshot.testing.lazycolumnscreen.shot.setContent import com.example.road.to.effective.snapshot.testing.testannotations.ComposableTest import com.example.road.to.effective.snapshot.testing.testannotations.HappyPath import com.example.road.to.effective.snapshot.testing.testannotations.UnhappyPath import com.google.testing.junit.testparameterinjector.TestParameter import com.google.testing.junit.testparameterinjector.TestParameterInjector import com.karumi.shot.ScreenshotTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import sergio.sastre.uitesting.utils.activityscenario.ActivityScenarioForComposableRule /** * Execute the command below to run only ComposableTests * 1. Record: * ./gradlew :lazycolumnscreen:shot:executeScreenshotTest -Pandroid.testInstrumentationRunnerArguments.annotation=com.example.road.to.effective.snapshot.testing.testannotations.ComposableTest -Precord * 2. Verify: * ./gradlew :lazycolumnscreen:shot:executeScreenshotTest -Pandroid.testInstrumentationRunnerArguments.annotation=com.example.road.to.effective.snapshot.testing.testannotations.ComposableTest * * To run them using Android Orchestrator, add the following at the end of the command: * -PuseOrchestrator */ /** * Example of Parameterized test with TestParameterInjector Runner. * * Unlike Parameterized Runner, the test methods admit arguments, although we do not use them here. * * On the other hand, TestParameterInjector requires API 24+ to run with instrumented tests. * It throws java.lang.NoClassDefFoundError: com.google.common.cache.CacheBuilder in lower APIs. * Parameterized Runner is compatible with instrumented test of any API level */ @SdkSuppress(minSdkVersion = 26) // ScreenshotTest.compareScreenshot(rule = ...) requires API 26+ @RunWith(TestParameterInjector::class) class CoffeeDrinkListComposableTestParameterHappyPathTest( @TestParameter val configItem: HappyPathTestItem, ) : ScreenshotTest { @get:Rule val activityScenarioForComposableRule = ActivityScenarioForComposableRule(configItem.item) @HappyPath @ComposableTest @Test fun snapComposable() { activityScenarioForComposableRule.setContent { AppTheme { CoffeeDrinkList(coffeeDrink = coffeeDrink) } } compareScreenshot( rule = activityScenarioForComposableRule.composeRule, name = "CoffeeDrinkListComposable_${configItem.name}_TestParameter" ) } } @SdkSuppress(minSdkVersion = 26) // ScreenshotTest.compareScreenshot(rule = ...) requires API 26+ @RunWith(TestParameterInjector::class) class CoffeeDrinkListComposableTestParameterUnhappyPathTest( @TestParameter val configItem: UnhappyPathTestItem, ) : ScreenshotTest { @get:Rule val activityScenarioForComposableRule = ActivityScenarioForComposableRule(configItem.item) @UnhappyPath @ComposableTest @Test fun snapComposable() { activityScenarioForComposableRule.setContent { AppTheme { CoffeeDrinkList(coffeeDrink = coffeeDrink) } } compareScreenshot( rule = activityScenarioForComposableRule.composeRule, name = "CoffeeDrinkListComposable_${configItem.name}_TestParameter" ) } }
4
null
23
291
b36d13ad4613db423a371e0c0c6ba3dd2fb8e48f
3,665
Android-screenshot-testing-playground
MIT License
zoomdls/src/main/java/com/zoomcar/uikit/arcview/ArcView.kt
ZoomCar
237,639,513
false
null
package com.zoomcar.uikit.arcview import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.Animation import android.view.animation.Transformation import androidx.core.content.ContextCompat import com.zoomcar.util.UiUtil import com.zoomcar.zoomdls.R /* * @created 21/09/21 - 5:11 pm * @project Zoomcar * @author Rohil * Copyright (c) 2021 Zoomcar. All rights reserved. */ class ArcView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val foregroundPaint by lazy { Paint() } private val backgroundPaint by lazy { Paint() } var strokeWidth: Float = 0f var progressValue: Int var startColor: String? var endColor: String? var animationDuration: Int var autoAnimate: Boolean /* Right center = 0 / 360 * Bottom center = 90 * Left center = 180 * Top Center = 270 * Our Range varies from 135 to 405 Degree i.e 270 Degrees in total. So 1 progress * point is equal to 2.7 degrees */ private var finalFillAngleFromStart = 0f /* Right center = 0.0 / 1.0 * Bottom center = 0.25 * Left center = 0.50 * Top Center = 0.75 */ private var gradientEndPosition = 0f private var viewWidth = -1 private var viewHeight = -1 private val widthWithoutStroke by lazy { viewWidth - (strokeWidth * 2) } private val heightWithoutStroke by lazy { viewHeight - (strokeWidth * 2) } private val rect by lazy { RectF( strokeWidth, strokeWidth, widthWithoutStroke + strokeWidth, heightWithoutStroke + strokeWidth ) } private val fillAnimation = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation?) { super.applyTransformation(interpolatedTime, t) val angle = currentFillAngle + ((finalFillAngleFromStart) - currentFillAngle) * interpolatedTime [email protected] = angle [email protected]() } }.apply { interpolator = AccelerateDecelerateInterpolator() } var currentFillAngle = 0f init { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ArcView) strokeWidth = UiUtil.dpToPixels( typedArray.getInt( R.styleable.ArcView_av_stroke_width, DEFAULT_STROKE_WIDTH ), context ).toFloat() progressValue = typedArray.getInt(R.styleable.ArcView_av_progress_value, 0) startColor = typedArray.getString(R.styleable.ArcView_av_start_color) ?: DEFAULT_START_COLOR endColor = typedArray.getString(R.styleable.ArcView_av_end_color) ?: DEFAULT_END_COLOR animationDuration = typedArray.getInt( R.styleable.ArcView_av_animation_duration, DEFAULT_ANIMATION_DURATION ) autoAnimate = typedArray.getBoolean( R.styleable.ArcView_av_auto_animate, DEFAULT_AUTO_ANIMATE ) typedArray.recycle() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) if (areDimensionsInvalid()) { viewWidth = measuredWidth viewHeight = measuredHeight initCanvasObjects() } } fun updateProgressValue(newValue: Int) { progressValue = newValue finalFillAngleFromStart = (progressValue * 2.7).toFloat() gradientEndPosition = ((finalFillAngleFromStart) / 360) requestLayout() } fun updateAnimationDuration(newValue: Int) { animationDuration = newValue fillAnimation.duration = animationDuration.toLong() } fun initCanvasObjects() { if (areDimensionsInvalid()) { return } foregroundPaint.let { it.isAntiAlias = true it.style = Paint.Style.STROKE it.strokeWidth = strokeWidth } backgroundPaint.let { it.isAntiAlias = true it.style = Paint.Style.STROKE it.strokeWidth = strokeWidth it.color = ContextCompat.getColor(context, R.color.phantom_grey_02) } val colors = intArrayOf(Color.parseColor(startColor), Color.parseColor(endColor)) val positions = floatArrayOf(0.0f, gradientEndPosition) val sweepGradient = SweepGradient( widthWithoutStroke / 2, heightWithoutStroke / 2, colors, positions ) sweepGradient.apply { val rotate = START_ANGLE_POINT val gradientMatrix = Matrix() gradientMatrix.preRotate(rotate, (viewWidth / 2).toFloat(), (viewHeight / 2).toFloat()) setLocalMatrix(gradientMatrix) } foregroundPaint.shader = sweepGradient // if (autoAnimate) { // animateArc() // } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawArc( rect, START_ANGLE_POINT, END_ANGLE_POINT_FROM_START, false, backgroundPaint ) canvas.drawArc(rect, START_ANGLE_POINT, finalFillAngleFromStart, false, foregroundPaint) } fun animateArc() { this.startAnimation(fillAnimation) } private fun areDimensionsInvalid() = viewWidth == -1 || viewHeight == -1 companion object { private const val START_ANGLE_POINT = 135f private const val END_ANGLE_POINT_FROM_START = 270f const val DEFAULT_ANIMATION_DURATION = 500 const val DEFAULT_START_COLOR = "#0b7a07" //R.color.ever_green_07 const val DEFAULT_END_COLOR = "#10a310" //R.color.ever_green_06 const val DEFAULT_STROKE_WIDTH = 15 const val DEFAULT_AUTO_ANIMATE = true } }
0
Kotlin
7
3
cd92e5391b6405b1f857420e01a97f1297c11a54
6,063
android-dls
Apache License 2.0
app/src/main/java/id/kotlin/android/features/detail/DetailView.kt
budioktaviyan
156,576,500
false
null
package id.kotlin.android.features.detail import id.kotlin.android.features.home.Movie interface DetailView { fun onShowMovie(movie: Movie) }
0
Kotlin
1
1
7d48ce2c2fe1c0b00afa90db78aac5aa3fe1e8ce
148
android-mvp-clean
MIT License
app/src/main/java/com/breezefieldsalesprolific/features/newcollection/model/NewCollectionListResponseModel.kt
DebashisINT
858,666,785
false
{"Kotlin": 15933758, "Java": 1028328}
package com.breezefieldsalesprolific.features.newcollection.model import com.breezefieldsalesprolific.app.domain.CollectionDetailsEntity import com.breezefieldsalesprolific.base.BaseResponse import com.breezefieldsalesprolific.features.shopdetail.presentation.model.collectionlist.CollectionListDataModel /** * Created by Saikat on 15-02-2019. */ class NewCollectionListResponseModel : BaseResponse() { //var collection_list: ArrayList<CollectionListDataModel>? = null var collection_list: ArrayList<CollectionDetailsEntity>? = null }
0
Kotlin
0
0
5f087f70f683b3c661531f4740db1a223a07b5ff
546
PROLIFIC
Apache License 2.0
app/src/main/java/bg/zahov/app/ui/exercise/info/history/ExerciseHistoryFragment.kt
HauntedMilkshake
698,074,119
false
{"Kotlin": 390308}
package bg.zahov.app.ui.exercise.info.history import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.map import androidx.recyclerview.widget.LinearLayoutManager import bg.zahov.app.data.model.state.ExerciseHistoryUiMapper import bg.zahov.app.hideBottomNav import bg.zahov.fitness.app.databinding.FragmentExerciseHistoryBinding class ExerciseHistoryFragment : Fragment() { private var _binding: FragmentExerciseHistoryBinding? = null private val binding get() = requireNotNull(_binding) private val historyInfoViewModel: ExerciseHistoryViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { _binding = FragmentExerciseHistoryBinding.inflate(inflater, container, false) requireActivity().hideBottomNav() historyInfoViewModel.initData() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { val setAdapter = ExerciseHistoryAdapter() historyInfoViewModel.state.map { ExerciseHistoryUiMapper.map(it) } .observe(viewLifecycleOwner) { circularProgressIndicator.visibility = it.loadingVisibility setsRecyclerView.visibility = it.recyclerViewVisibility it.message?.let { message ->Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } setAdapter.updateItems(it.data) it.data } setsRecyclerView.apply { layoutManager = LinearLayoutManager(context) adapter = setAdapter } } } override fun onResume() { super.onResume() requireActivity().hideBottomNav() } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
1
2
0aaba6d6f4392cb034d20b94e178ebe916ae78e6
2,187
fitness_app
MIT License
application-interface/src/main/kotlin/com/mechanica/engine/context/loader/FileFactory.kt
DominicDolan
210,876,716
false
{"Kotlin": 437674}
package com.mechanica.engine.context.loader import com.mechanica.engine.resources.ExternalResource import com.mechanica.engine.resources.Resource import com.mechanica.engine.resources.ResourceDirectory import java.net.URI import java.net.URL interface FileFactory { fun resource(path: String): Resource fun resource(url: URL): Resource fun resource(uri: URI): Resource fun externalResource(path: String, createIfAbsent: Boolean): ExternalResource fun directory(path: String, recursive: Boolean = false): ResourceDirectory }
7
Kotlin
1
0
016c8568a93fe22a186bd812d0d4789196495846
545
Mechanica
MIT License
core/src/commonMain/kotlin/com/wangmuy/llmchain/utils/uuid/SimpleUUID.kt
wangmuy
634,570,916
false
{"Kotlin": 166192}
package com.wangmuy.llmchain.utils.uuid object SimpleUUID { fun randomUUID(): String { val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9') return (1..32) .map { allowedChars.random() } .joinToString("") } }
1
Kotlin
1
13
406bf794b8cf0287acbf393022c86d4f6518d434
259
llmchain
Apache License 2.0
src/main/kotlin/ru/stersh/bookcrawler/Properties.kt
siper
720,533,744
false
{"Kotlin": 98608, "Dockerfile": 361}
package ru.stersh.bookcrawler import java.io.BufferedReader import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStreamReader import java.util.Properties object Properties { private val appProps = Properties() init { val reader = BufferedReader( InputStreamReader( FileInputStream("$CONFIG_FOLDER/config.properties"), "utf-8") ) appProps.load(reader) } fun get(key: String): String? { return appProps.getProperty(key) } fun require(key: String): String { return requireNotNull(get(key)) } fun write(key: String, value: String) { appProps.setProperty(key, value) appProps.store( FileOutputStream("$CONFIG_FOLDER/config.properties"), "Save property: $key with value: $value" ) } }
13
Kotlin
0
0
f50d3ebe7bb58420cf72165b4aa0d1918e530575
866
BookCrawler
MIT License
app/src/main/java/my/dictionary/free/view/SimplerFragment.kt
viacheslavtitov
605,498,191
false
{"Kotlin": 487494}
package my.dictionary.free.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import my.dictionary.free.R class SimplerFragment: Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_simple, null) } }
5
Kotlin
0
0
05eef2257cef2cc57a6170a4b66d38acd743f869
470
Easy-Dictionary-Android
MIT License
ui-core/src/main/kotlin/com/processout/sdk/ui/core/state/POActionState.kt
processout
117,821,122
false
{"Kotlin": 870411, "Java": 85526, "Shell": 696}
package com.processout.sdk.ui.core.state import androidx.compose.runtime.Immutable import com.processout.sdk.ui.core.annotation.ProcessOutInternalApi /** @suppress */ @ProcessOutInternalApi @Immutable data class POActionState( val id: String, val text: String, val primary: Boolean, val enabled: Boolean = true, val loading: Boolean = false, val confirmation: Confirmation? = null ) { @Immutable data class Confirmation( val title: String, val message: String?, val confirmActionText: String, val dismissActionText: String? ) }
0
Kotlin
5
2
13ffccac03a2769a63d6d1794bdb812691faaeb7
599
processout-android
MIT License
customdata-rpg/src/main/java/contacts/entities/custom/rpg/stats/RpgStatsDataCursor.kt
vestrel00
223,332,584
false
null
package contacts.entities.custom.rpg.stats import android.database.Cursor import contacts.core.entities.custom.AbstractCustomDataCursor import contacts.entities.custom.rpg.RpgFields import contacts.entities.custom.rpg.RpgStatsField internal class RpgStatsDataCursor(cursor: Cursor, includeFields: Set<RpgStatsField>) : AbstractCustomDataCursor<RpgStatsField>(cursor, includeFields) { val level: Int? by int(RpgFields.Stats.Level) val speed: Int? by int(RpgFields.Stats.Speed) val strength: Int? by int(RpgFields.Stats.Strength) val intelligence: Int? by int(RpgFields.Stats.Intelligence) val luck: Int? by int(RpgFields.Stats.Luck) }
26
null
35
573
383594d2708296f2fbc6ea1f10b117d3acd1f46a
660
contacts-android
Apache License 2.0
kresil-lib/lib/src/commonTest/kotlin/kresil/service/RemoteService.kt
kresil
765,815,842
false
{"Kotlin": 407453, "HTML": 4559, "JavaScript": 791, "Java": 407}
package kresil.service /** * Represents a service that can be called remotely. */ interface RemoteService { suspend fun suspendSupplier(): String? suspend fun suspendFunction(input: String): String? suspend fun suspendBiFunction(a: String, b: String): String? }
5
Kotlin
0
3
b5c039f0d530ffee01d8d18803a15162f9b57a9c
277
kresil
Apache License 2.0
query/src/main/kotlin/com/linecorp/kotlinjdsl/query/spec/JoinSpec.kt
line
442,633,985
false
null
package com.linecorp.kotlinjdsl.query.spec import com.linecorp.kotlinjdsl.query.spec.expression.ColumnSpec import com.linecorp.kotlinjdsl.query.spec.expression.EntitySpec import javax.persistence.criteria.JoinType sealed interface JoinSpec<T> { val entity: EntitySpec<T> } sealed interface AssociatedJoinSpec<L, R> : JoinSpec<R> { val left: EntitySpec<L> val right: EntitySpec<R> val path: String val joinType: JoinType override val entity get() = right } data class SimpleAssociatedJoinSpec<L, R>( override val left: EntitySpec<L>, override val right: EntitySpec<R>, override val path: String ) : AssociatedJoinSpec<L, R> { override val joinType: JoinType = JoinType.INNER } data class SimpleJoinSpec<L, R>( override val left: EntitySpec<L>, override val right: EntitySpec<R>, override val path: String, override val joinType: JoinType ) : AssociatedJoinSpec<L, R> data class FetchJoinSpec<L, R>( override val left: EntitySpec<L>, override val right: EntitySpec<R>, override val path: String, override val joinType: JoinType ) : AssociatedJoinSpec<L, R> data class CrossJoinSpec<T>( override val entity: EntitySpec<T>, ) : JoinSpec<T> data class TreatJoinSpec<P, T : P>( override val left: EntitySpec<P>, override val right: EntitySpec<T>, override val joinType: JoinType, val root: ColumnSpec<*> ) : AssociatedJoinSpec<P, T> { override val path: String = root.path }
26
Kotlin
60
504
f28908bf432cf52f73a9573b1ac2be5eb4b2b7dc
1,474
kotlin-jdsl
Apache License 2.0
src/org/elixir_lang/beam/assembly/Icons.kt
KronicDeth
22,329,177
false
null
package org.elixir_lang.beam.assembly import com.intellij.openapi.util.IconLoader object Icons { val FILE = IconLoader.getIcon("/icons/file/beam/assembly.svg", Icons.javaClass) val LANGUAGE = IconLoader.getIcon("/icons/language/beam/assembly.svg", Icons.javaClass) }
590
null
153
1,815
b698fdaec0ead565023bf4461d48734de135b604
277
intellij-elixir
Apache License 2.0
tools/src/main/kotlin/rs/dusk/tools/definition/item/pipe/extra/ItemNoted.kt
Palmfeldt
673,267,966
true
{"Kotlin": 1529507}
package rs.dusk.tools.definition.item.pipe.extra import rs.dusk.cache.definition.decoder.ItemDecoder import rs.dusk.engine.entity.definition.DefinitionsDecoder.Companion.toIdentifier import rs.dusk.tools.Pipeline import rs.dusk.tools.definition.item.Extras class ItemNoted(private val decoder: ItemDecoder) : Pipeline.Modifier<Extras> { override fun modify(content: Extras): Extras { val (builder, extras) = content val (id, n, _, _, _, _, _, _, uid) = builder val def = decoder.getOrNull(id) ?: return content if (def.noted || def.lent || def.singleNote) { extras.clear() } val name = if (uid.isEmpty()) toIdentifier(n) else uid builder.uid = when { def.noted -> "${name}_noted" def.lent -> "${name}_lent" def.singleNote -> "${name}_note" else -> builder.uid } return content } }
0
Kotlin
0
0
0b3a4fe8eb9f2e2e29f8834d028fd3edf038cd2f
924
NostalgiaScape
Creative Commons Attribution 3.0 Unported
demo/shared/src/commonMain/kotlin/io/bidapp/demo/App.kt
bidapphub
787,934,281
false
{"Kotlin": 35918}
package io.bidapp.demo import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import io.bidapp.demo.UI.ButtonAds import io.bidapp.demo.UI.Logo import io.bidapp.demo.Data.AdsEvents import io.bidapp.demo.Data.BIDAppAdsData import io.bidapp.demo.UI.Banner import io.bidapp.kmp.getPlatformName @Composable fun App(bidappAdsData: BIDAppAdsData, activityOrUIViewController: Any?) { var adsEvents: AdsEvents? by remember { mutableStateOf(null) } val isAutoRefreshOn = remember { mutableStateOf(false) } val displayBanner = remember { mutableStateOf(false) } val isInterstitialLoad = remember { mutableStateOf(false) } val isRewardedLoad = remember { mutableStateOf(false) } val view: MutableState<Any?> = remember { mutableStateOf(Any()) } LaunchedEffect(Unit) { if (adsEvents == null) { adsEvents = object : AdsEvents { override fun displayBanner() { displayBanner.value = true } override fun interstitialLoad() { isInterstitialLoad.value = true } override fun rewardedLoad() { isRewardedLoad.value = true } override fun loadBanner(networkID: Int?) { if (io.bidapp.kmp.getPlatformName() == "Android" && networkID == 7) requestLayout(view.value) } } bidappAdsData.adsEvents = adsEvents } } DisposableEffect(Unit) { onDispose { if (io.bidapp.kmp.getPlatformName() == "Android") { bidappAdsData.destroy() } } } Column( modifier = Modifier.fillMaxSize().padding(top = 100.dp), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { Logo() ButtonAds( bidappAdsData, activityOrUIViewController, view, isAutoRefreshOn, displayBanner, isInterstitialLoad, isRewardedLoad ) } Banner(bidappAdsData, view) } expect fun log(message: String) //Fix admob banner impression callback on compose for Android expect fun requestLayout(view:Any?)
0
Kotlin
0
1
f8ef4f6bcc8d4dba6009f267ff21e4c3b321b132
2,890
bidapp-kotlin-multiplatform-plugin
MIT License
src/main/kotlin/adventofcode2017/potasz/P20Particles.kt
potasz
113,064,245
false
null
package adventofcode2017.potasz import kotlin.math.abs object P20Particles { data class Coord(var x: Long, var y: Long, var z: Long) { fun update(other: Coord) { x += other.x y += other.y z += other.z } } data class Particle(val id: Int, val p: Coord, val v: Coord, val a: Coord) { fun update() { v.update(a) p.update(v) } fun distance(): Long = abs(p.x) + abs(p.y) + abs(p.z) } val pattern = """\w=<([-\d]+),([-\d]+),([-\d]+)>.*""".toRegex() private fun parseInput(sample: List<String>): List<Particle> { return sample.mapIndexed { index, line -> val (p, v, a) = line.split(", ") .map { pattern.matchEntire(it) } .filterNotNull() .map { Coord(it.groupValues[1].toLong(), it.groupValues[2].toLong(), it.groupValues[3].toLong()) } Particle(index, p, v, a) } } @JvmStatic fun main(args: Array<String>) { val input = parseInput(readLines("input20.txt")) repeat(1000) { input.parallelStream().forEach { it.update() } } println(input.minBy { it.distance() }) var input2 = parseInput(readLines("input20.txt")) repeat(1000) { input2.parallelStream().forEach { it.update() } input2 = input2.groupBy { it.p }.filter { it.value.size == 1 }.map { it.value[0] } } println(input2.size) } }
0
Kotlin
0
1
f787d9deb1f313febff158a38466ee7ddcea10ab
1,527
adventofcode2017
Apache License 2.0
cccev-test/src/main/kotlin/cccev/test/s2/certification/query/CertificationGetSteps.kt
komune-io
746,816,569
false
{"Kotlin": 582161, "TypeScript": 94420, "MDX": 92741, "Gherkin": 21405, "Makefile": 5663, "JavaScript": 2459, "HTML": 1853, "Dockerfile": 1787, "CSS": 605}
//package cccev.test.s2.certification.query // //import cccev.projection.api.entity.certification.CertificationRepositoryOld //import cccev.s2.certification.api.CertificationFinderService //import cccev.test.CccevCucumberStepsDefinition //import io.cucumber.datatable.DataTable //import io.cucumber.java8.En //import org.assertj.core.api.Assertions //import org.springframework.beans.factory.annotation.Autowired //import s2.bdd.data.TestContextKey //import s2.bdd.data.parser.safeExtract // //class CertificationGetSteps: En, CccevCucumberStepsDefinition() { // // @Autowired // private lateinit var certificationFinderService: CertificationFinderService // // @Autowired // private lateinit var certificationRepository: CertificationRepositoryOld // // init { // DataTableType(::certificationGetParams) // DataTableType(::requirementStatsAssertParams) // // When("I fetch the certification") { // step { // fetchCertification(certificationGetParams(null)) // } // } // // When("I fetch the certification:") { params: CertificationGetParams -> // step { // fetchCertification(params) // } // } // // Then("I should receive the requirement stats of the certification:") { dataTable: DataTable -> // val params = dataTable.asList(RequirementStatsAssertParams::class.java) // val certification = context.fetched.certification // params.forEach { param -> // val requirementId = context.requirementIds.safeGet(param.requirement) // val stats = certification.requirementStats[requirementId] // Assertions.assertThat(stats).isNotNull // Assertions.assertThat(stats!!.completion).isEqualTo(param.completion) // } // } // } // // private suspend fun fetchCertification(params: CertificationGetParams) { // context.fetched.certification = certificationFinderService.get(context.certificationIds[params.identifier] ?: params.identifier) // } // // private fun certificationGetParams(entry: Map<String, String>?) = CertificationGetParams( // identifier = entry?.get("identifier") ?: context.certificationIds.lastUsedKey // ) // // private data class CertificationGetParams( // val identifier: TestContextKey // ) // // private fun requirementStatsAssertParams(entry: Map<String, String>) = RequirementStatsAssertParams( // requirement = entry.safeExtract("requirement"), // completion = entry.safeExtract("completion").toDouble() // ) // // private data class RequirementStatsAssertParams( // val requirement: TestContextKey, // val completion: Double // ) //}
0
Kotlin
0
0
f17868cdb505a562360297fa4449bbf46bf3b3fe
2,782
connect-cccev
Apache License 2.0
app/src/main/java/com/muhammetkdr/weatherapp/ui/search/rv/CitiesRvViewHolder.kt
mskdr
592,702,997
false
null
package com.muhammetkdr.weatherapp.ui.search.rv import com.muhammetkdr.weatherapp.base.BaseViewHolder import com.muhammetkdr.weatherapp.databinding.ItemSearchResponseBinding import com.muhammetkdr.weatherapp.domain.entity.cities.CitiesEntity import javax.inject.Inject class CitiesRvViewHolder @Inject constructor( private val binding: ItemSearchResponseBinding, private val onItemClickListener: ((CitiesEntity) -> Unit)? ) : BaseViewHolder<CitiesEntity>(binding.root) { override fun onBind(data: CitiesEntity) { binding.citiesEntity = data itemView.setOnClickListener { onItemClickListener?.invoke(data) } } }
0
Kotlin
0
2
aeab7440029fb8cc7c268f20873e0516fed8389a
664
WeatherApp
MIT License
src/main/org/lrs/kmodernlrs/controllers/security/UserAccount.kt
dtarnawczyk
73,920,384
false
null
package org.lrs.kmodernlrs.controllers.security import org.lrs.kmodernlrs.domain.Entity import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document import java.time.LocalDate import java.util.* @Document(collection = "users") data class UserAccount( var name: String = "", var password: String = "", var role: String = "", var email: String = "", var token: String = "", var tokenExpirationDate: LocalDate? = null, @Id override var id: String = UUID.randomUUID().toString(), var createdTime: LocalDate? = null, var active: Boolean = false) : Entity
0
Kotlin
1
4
e534a527635660fe330980411bc8116200af355b
672
modernlrs
Apache License 2.0