path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
โ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/miguel/rucoyapi/presentation/controllers/equipmentController.kt | MiguelJeronimo | 705,820,521 | false | {"Kotlin": 147497, "Dockerfile": 869} | package com.miguel.rucoyapi.controllers
import com.miguel.rucoyapi.model.responses
import com.miguel.rucoyapi.repository.Repository
import org.apache.coyote.Response
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class HatsController {
private val logger: Logger = LogManager.getLogger(HatsController::class.java)
@GetMapping("api/v1/hats")
fun getHatsList(): Any {
logger.info("init petition: api/v1/hats")
return try {
val hatsList = Repository().getHats()
if(hatsList != null){
logger.info("Final response success")
ResponseEntity.ok().body(responses.response(200, hatsList))
} else {
logger.error("Error: ${responses.Errors(
400,
"no bows found")}")
ResponseEntity.badRequest().body(responses.Errors(
400,
"no bows found"))
}
} catch (error: Exception){
logger.fatal("Failure by: ${error.stackTraceToString()}")
ResponseEntity.internalServerError().body(responses.Errors(500, error.stackTraceToString()))
}
}
} | 0 | Kotlin | 0 | 0 | c05ea4415138a2c6b032f9576079b2b7d955f0d0 | 1,398 | rucoy-api | MIT License |
app/src/main/java/com/github/kacso/androidcommons/viewmodel/SplashViewModel.kt | kacso | 204,923,341 | false | {"Gradle": 16, "Java Properties": 2, "Shell": 1, "Text": 4, "Ignore List": 13, "Batchfile": 1, "Markdown": 616, "Kotlin": 181, "XML": 69, "INI": 8, "Proguard": 9, "Java": 1} | package com.github.kacso.androidcommons.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import com.github.kacso.androidcommons.core.BaseApplication
import com.github.kacso.androidcommons.core.livedata.SingleLiveEvent
import com.github.kacso.androidcommons.core.mvvm.viewmodels.BaseViewModel
import com.github.kacso.androidcommons.data.ErrorHolder
import com.github.kacso.androidcommons.network.exceptions.Unauthorized
import com.github.kacso.androidcommons.network.factories.NetworkExceptionFactory
import com.github.kacso.androidcommons.network.interceptors.NetworkExceptionInterceptor
import com.github.kacso.androidcommons.security.factories.SecurityRepositoryFactory
import kotlinx.coroutines.launch
import java.lang.Thread.sleep
class SplashViewModel : BaseViewModel() {
private val authRepository by lazy {
SecurityRepositoryFactory.getOAuth2Repository(
context = BaseApplication.appContext,
baseUrl = com.github.kacso.androidcommons.BuildConfig.AUTH_ENDPOINT,
authorizationKey = com.github.kacso.androidcommons.BuildConfig.AUTHORIZATION_KEY,
networkExceptionInterceptor = NetworkExceptionInterceptor(NetworkExceptionFactory())
)
}
fun persistLogin(): LiveData<Void> {
val ld = SingleLiveEvent<Void>()
viewModelScope.launch {
//Sleep for few seconds in order to make splash visible to user
sleep(2000)
val token = authRepository.getAccessToken()
if (token.isNullOrEmpty()) {
val errorHolder = ErrorHolder(null, "Empty token", Unauthorized())
error.postValue(errorHolder)
} else {
ld.call()
}
}
return ld
}
} | 0 | Kotlin | 1 | 5 | 9620f80428f4b00a8b683f4e94294e9e64c85b99 | 1,788 | android-commons | Apache License 2.0 |
src/main/kotlin/helper/ProcessChainLogFileAppender.kt | steep-wms | 237,438,539 | false | {"Kotlin": 1547323, "JavaScript": 233382, "SCSS": 38483, "Shell": 1830, "Dockerfile": 1598, "PLpgSQL": 1198} | package helper
import agent.LocalAgent
import ch.qos.logback.core.FileAppender
import java.nio.file.Paths
/**
* A logback appender that writes process chain logs into a file. The filename
* is calculated based on the name of a process chain logger, which should
* contain the process chain ID.
* @author Michel Kraemer
*/
class ProcessChainLogFileAppender<E> : FileAppender<E>() {
/**
* The name of the process chain logger as defined in [LocalAgent]
*/
var loggerName: String? = null
/**
* The base path for all process chain logs.
* See [ConfigConstants.LOGS_PROCESSCHAINS_PATH].
*/
var path: String? = null
/**
* The number of characters to use for grouping.
* See [ConfigConstants.LOGS_PROCESSCHAINS_GROUPBYPREFIX].
*/
var groupByPrefix = 0
override fun start() {
val ln = loggerName
if (ln == null) {
addError("The `loggerName' property must be set")
return
}
val p = path
if (p == null) {
addError("The `path' property must be set")
return
}
val idAndRunNumber = ln.substring(LocalAgent.PROCESSCHAIN_LOG_PREFIX.length)
val (id, runNumber) = idAndRunNumber.lastIndexOf('.').let { i ->
idAndRunNumber.substring(0, i) to idAndRunNumber.substring(i + 1).toLong() }
val filename = if (runNumber > 1) {
"$idAndRunNumber.log"
} else {
"$id.log"
}
file = if (groupByPrefix > 0) {
Paths.get(p, id.substring(0, groupByPrefix), filename).toString()
} else {
Paths.get(p, filename).toString()
}
super.start()
}
}
| 37 | Kotlin | 5 | 38 | ca85be66f339b08aee50319a7245810f760f6933 | 1,574 | steep | Apache License 2.0 |
squash-postgres/src/org/jetbrains/squash/dialects/postgres/PgDialect.kt | Krotki | 101,491,647 | true | {"Kotlin": 213958} | package org.jetbrains.squash.dialects.postgres
import org.jetbrains.squash.definition.*
import org.jetbrains.squash.dialect.*
import org.jetbrains.squash.expressions.*
object PgDialect : BaseSQLDialect("Postgres") {
override val definition: DefinitionSQLDialect = object : BaseDefinitionSQLDialect(this) {
override fun columnTypeSQL(builder: SQLStatementBuilder, column: Column<*>) {
if (column.hasProperty<AutoIncrementProperty>()) {
require(!column.hasProperty<NullableProperty>()) { "Column ${column.name} cannot be both AUTOINCREMENT and NULL" }
val type = column.type
val autoincrement = when (type) {
is IntColumnType -> "SERIAL"
is LongColumnType -> "BIGSERIAL"
else -> error("AutoIncrement column for '$type' is not supported by $this")
}
builder.append(autoincrement)
} else super.columnTypeSQL(builder, column)
}
override fun columnAutoIncrementProperty(builder: SQLStatementBuilder, property: AutoIncrementProperty?) {
// do nothing, we already handled AutoIncrementProperty as SERIAL
}
override fun columnTypeSQL(builder: SQLStatementBuilder, type: ColumnType) {
when (type) {
is UUIDColumnType -> builder.append("UUID")
is BlobColumnType -> builder.append("BYTEA")
is BinaryColumnType -> builder.append("BYTEA")
is DateTimeColumnType -> builder.append("TIMESTAMP")
is JsonColumnType -> builder.append("JSON")
is JsonBColumnType -> builder.append("JSONB")
else -> super.columnTypeSQL(builder, type)
}
}
}
override fun appendBinaryOperator(builder: SQLStatementBuilder, expression: BinaryExpression<*, *, *>) = with(builder) {
when (expression) {
is JsonElementExpression -> append("->")
is JsonElementAsTextExpression -> append("->>")
is JsonPathExpression -> append("#>")
is JsonPathAsTextExpression -> append("#>>")
is JsonContainsExpression -> append("@>")
is JsonContainedInExpression -> append("<@")
is JsonContainsKeyExpression -> append("??")
is JsonContainsAnyKeyExpression -> append("??|")
is JsonContainsAllKeysExpression -> append("??&")
else -> super.appendBinaryOperator(builder, expression)
}
}
} | 0 | Kotlin | 0 | 0 | 375b1751135d5f80ee689ae74eb5d50fee7723a3 | 2,541 | squash | Apache License 2.0 |
maestro-client/src/main/java/maestro/debuglog/IOSDriverLogger.kt | mobile-dev-inc | 476,427,476 | false | {"Kotlin": 1019730, "TypeScript": 199278, "Swift": 58814, "JavaScript": 16308, "Shell": 11312, "CSS": 2349, "Smarty": 904, "HTML": 358} | package maestro.debuglog
import maestro.logger.Logger
import org.slf4j.LoggerFactory
class IOSDriverLogger(val clazz: Class<*>) : Logger {
override fun info(message: String) {
LoggerFactory.getLogger(clazz).info(message)
loggerFor(clazz).info(message)
}
companion object {
private var loggers = mutableMapOf<Class<*>, java.util.logging.Logger>()
fun loggerFor(clazz: Class<*>): java.util.logging.Logger {
if (!loggers.containsKey(clazz)) {
loggers[clazz] = DebugLogStore.loggerFor(clazz)
}
return loggers[clazz]!!
}
}
}
| 334 | Kotlin | 255 | 5,634 | 463275b29decc509bdf312f5037688f67f0ae485 | 633 | maestro | Apache License 2.0 |
src/main/kotlin/com/arch/temp/view/CheckTemplateDialog.kt | Louco11 | 354,872,120 | false | null | package com.arch.temp.view
import com.arch.temp.model.MainClassJson
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBRadioButton
import com.intellij.ui.layout.panel
import javax.swing.JComponent
class CheckTemplateDialog(
private val param: List<MainClassJson>,
project: Project?,
private val callOk: (MainClassJson) -> Unit
) : DialogWrapper(project) {
private val radioButtonList = mutableListOf<JBRadioButton>()
init {
init()
}
override fun createCenterPanel(): JComponent {
return panel {
buttonGroup{
param.forEach {
val buttonJb = JBRadioButton(it.name)
radioButtonList.add(buttonJb)
row { buttonJb()}
}
}
}
}
override fun doOKAction() {
super.doOKAction()
radioButtonList.forEachIndexed{index, button ->
if (button.isSelected) {
callOk(param[index])
}
}
}
} | 0 | Kotlin | 2 | 3 | b543a69a58988233763a3586cac11660def4f893 | 1,091 | Group-File-Template-GFT | The Unlicense |
xenoglot-locale/src/commonTest/kotlin/dev/teogor/xenoglot/locale/XenoglotLocaleTest.kt | teogor | 718,087,802 | false | {"Kotlin": 1614676} | /*
* Copyright 2024 teogor (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 dev.teogor.xenoglot.locale
import dev.teogor.xenoglot.Country
import dev.teogor.xenoglot.Language
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
class XenoglotLocaleTest {
private val localeKorean = XenoglotLocale(Language.Korean)
private val localeRomanianRomania = XenoglotLocale(Language.Romanian, Country.Romania)
private val localeEnglishUS = XenoglotLocale(Language.English, Country.UnitedStates)
@Test
fun defaultLocale_getDefault_shouldReturnInitialDefault() {
// Set default to ensure it's in the expected initial state
XenoglotLocale.setDefault(localeEnglishUS)
val defaultLocale = XenoglotLocale.getDefault()
assertEquals(Language.English, defaultLocale.language)
assertEquals(Country.UnitedStates, defaultLocale.country)
}
@Test
fun defaultLocale_setDefault_shouldUpdateDefaultLocale() {
XenoglotLocale.setDefault(localeKorean)
val defaultLocale = XenoglotLocale.getDefault()
assertEquals(localeKorean, defaultLocale)
}
@Test
fun displayLanguage_getDisplayLanguage_shouldReturnCorrectLanguageName() {
XenoglotLocale.setDefault(localeRomanianRomania)
val locale = XenoglotLocale(Language.Romanian)
assertEquals("romรขnฤ", locale.getDisplayLanguage())
}
@Test
fun displayLanguage_getDisplayLanguageInContext_shouldReturnLanguageNameInContext() {
val localeRo = XenoglotLocale(Language.Romanian)
val localeEn = XenoglotLocale(Language.English)
assertEquals("Romanian", localeRo.getDisplayLanguage(localeEn))
}
@Test
fun displayCountry_getDisplayCountry_shouldReturnCorrectCountryName() {
XenoglotLocale.setDefault(localeRomanianRomania)
val localeRo = XenoglotLocale(Language.Romanian, Country.Romania)
assertEquals("Romรขnia", localeRo.getDisplayCountry())
}
@Test
fun displayCountry_getDisplayCountryInContext_shouldReturnCountryNameInContext() {
val localeRo = XenoglotLocale(Language.Romanian, Country.Romania)
val localeEn = XenoglotLocale(Language.English)
assertEquals("Romania", localeRo.getDisplayCountry(localeEn))
}
@Test
fun displayName_getDisplayName_shouldReturnFormattedDisplayName() {
XenoglotLocale.setDefault(localeRomanianRomania)
val localeRo = XenoglotLocale(Language.Romanian, Country.Romania)
assertEquals("romรขnฤ (Romรขnia)", localeRo.getDisplayName())
}
@Test
fun displayName_getDisplayNameInContext_shouldReturnDisplayNameInContext() {
val localeRo = XenoglotLocale(Language.Romanian, Country.Romania)
val localeEn = XenoglotLocale(Language.English)
assertEquals("Romanian (Romania)", localeRo.getDisplayName(localeEn))
}
@Test
fun languageTag_toLanguageTag_shouldReturnFormattedLanguageTag() {
val localeRo = XenoglotLocale(Language.Romanian, Country.Romania)
assertEquals("ro_RO", localeRo.toLanguageTag())
}
@Test
fun equality_equalsAndHashCode_shouldBeConsistent() {
val localeRo1 = XenoglotLocale(Language.Romanian, Country.Romania)
val localeRo2 = XenoglotLocale(Language.Romanian, Country.Romania)
val localeEnUK = XenoglotLocale(Language.English, Country.UnitedKingdom)
assertEquals(localeRo1, localeRo2)
assertNotEquals(localeRo1, localeEnUK)
assertEquals(localeRo1.hashCode(), localeRo2.hashCode())
assertNotEquals(localeRo1.hashCode(), localeEnUK.hashCode())
}
@Test
fun stringRepresentation_toString_shouldReturnFormattedString() {
val localeRo = XenoglotLocale(Language.Romanian, Country.Romania)
assertEquals("ro_RO", localeRo.toString())
}
}
| 0 | Kotlin | 0 | 6 | 48dddb213920f7cc1d19d2ea34a61948a633dc38 | 4,181 | xenoglot | Apache License 2.0 |
features/dashboard/src/main/java/rio/arj/dashboard/di/DashboardComponent.kt | Rarj | 315,966,563 | false | null | package rio.arj.dashboard.di
import dagger.Component
import rio.arj.dashboard.NextLeagueActivity
import javax.inject.Singleton
@DashboardScope
@Singleton
@Component(modules = [DashboardModule::class, DashboardViewModelModule::class])
interface DashboardComponent {
fun injectDashboard(nextLeagueActivity: NextLeagueActivity)
} | 0 | Kotlin | 0 | 0 | 4c8637cf2524a8c37d08708712983ef54143648c | 332 | football-match-refactor | Apache License 2.0 |
src/main/kotlin/com/petukhovsky/snake/config/WebSocketConfig.kt | arthur-snake | 114,157,008 | false | null | package com.petukhovsky.snake.config
import com.petukhovsky.snake.domain.SnakeConfigService
import com.petukhovsky.snake.domain.GamePool
import com.petukhovsky.snake.ws.SnakeHandler
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.web.socket.config.annotation.EnableWebSocket
import org.springframework.web.socket.config.annotation.WebSocketConfigurer
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
@Configuration
@EnableWebSocket
open class WebSocketConfig @Autowired constructor(
val configService: SnakeConfigService,
val gamePool: GamePool
) : WebSocketConfigurer {
val log = LoggerFactory.getLogger(javaClass)
override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) {
for ((name) in configService.snakeConfigs) {
val path = "/snake/ws/$name"
log.info("Mapping \"$path\" to snake game")
registry.addHandler(SnakeHandler(gamePool[name]), path).setAllowedOrigins("*")
}
}
} | 4 | Kotlin | 0 | 3 | e24da15441f6b6c673d1f1128ced494f4ed3d313 | 1,144 | server | MIT License |
light/src/main/kotlin/net/kotlinx/awscdk/component/CdkBatchJobDefinition.kt | mypojo | 565,799,715 | false | {"Kotlin": 1126686, "Java": 9531, "Jupyter Notebook": 7080} | package net.kotlinx.aws_cdk.component
import net.kotlinx.aws.batch.BatchUtil
import net.kotlinx.aws_cdk.CdkEnum
import net.kotlinx.aws_cdk.util.TagUtil
import net.kotlinx.core.DeploymentType
import software.amazon.awscdk.Stack
import software.amazon.awscdk.services.batch.CfnJobDefinition
import software.amazon.awscdk.services.batch.CfnJobDefinitionProps
import software.amazon.awscdk.services.ecs.EcrImage
import software.amazon.awscdk.services.iam.IRole
import kotlin.time.Duration.Companion.hours
/** enum ์ ์ */
class CdkBatchJobDefinition(
val name: String,
val vcpu: String,
val memory: Long,
) : CdkEnum {
/** VPC ์ด๋ฆ */
override val logicalName: String
get() = "${project.projectName}-${name}-${deploymentType.name.lowercase()}"
val arn: String
get() = "arn:aws:batch:ap-northeast-2:${project.awsId}:job-definition/${logicalName}"
lateinit var jobDef: CfnJobDefinition
lateinit var ecrImage: EcrImage
lateinit var jobRole: IRole
lateinit var executionRole: IRole
lateinit var logGroupPath: String
/**
* args ๋ก ์ฌ์ฉํ ์ธ์๊ฐ ๋งคํ
* job submit ํ ๋์ ํ๋ผ๋ฉํฐ์ ์ผ์นํด์ํจ
* */
var command: List<String> = listOf(
"Ref::${BatchUtil.BATCH_ARGS01}",
)
/** ๋ํดํธ๋ก 12์๊ฐ. ํ๋ก์ ํธ์ ๋ฐ๋ผ ์กฐ์ ํ ๊ฑฐ์ */
var attemptDurationSeconds: Long = 12.hours.inWholeSeconds
/**
* ์ด๋ฆ ์ค๋ณต์ผ๋ก ์์
์งํ์ด ์๋๋๊ฒฝ์ฐ
* 1. ์ฃผ์ ์ฒ๋ฆฌํด์ ๋๋ฆผ -> Job definitions off ๋จ
* 2. ์ฃผ์ ํ๊ณ ๋ค์ ๋๋ฆผ -> Job definitions ๋ฒ์ ์ฌ๋ผ๊ฐ๋ฉด์ ํ์ฑํ๋จ
* */
fun create(stack: Stack, block: CfnJobDefinitionProps.Builder.() -> Unit = {}): CdkBatchJobDefinition {
val props = CfnJobDefinitionProps.builder()
.jobDefinitionName(logicalName)
.platformCapabilities(listOf("FARGATE")) //ํ๊ฒ์ดํธ๋ง
.type("Container")
//.retryStrategy(RetryStrategyProperty.builder().attempts(1).build()) //์์ฒด ์ฌ์๋ ํ์ง ์์. ์ต์ 1~10 ๊น์ง ์ง์
.timeout(CfnJobDefinition.TimeoutProperty.builder().attemptDurationSeconds(attemptDurationSeconds).build())
.containerProperties(
CfnJobDefinition.ContainerPropertiesProperty.builder()
.fargatePlatformConfiguration(CfnJobDefinition.FargatePlatformConfigurationProperty.builder().platformVersion("1.4.0").build())
.command(command)
.environment(
listOf(
CfnJobDefinition.EnvironmentProperty.builder().name(DeploymentType::class.simpleName).value(deploymentType.name).build(),
)
)
.image(ecrImage.imageName)
.resourceRequirements(
listOf(
CfnJobDefinition.ResourceRequirementProperty.builder().type("VCPU").value(vcpu).build(),
CfnJobDefinition.ResourceRequirementProperty.builder().type("MEMORY").value("${1024 * memory}").build(),
)
)
.jobRoleArn(jobRole.roleArn)
.executionRoleArn(jobRole.roleArn)
.logConfiguration(
CfnJobDefinition.LogConfigurationProperty.builder()
.logDriver("awslogs")
.options(
mapOf(
"awslogs-group" to logGroupPath,
"awslogs-create-group" to "true",
"awslogs-stream-prefix" to logicalName,
)
)
.build()
)
.build()
)
.apply(block)
.build()
jobDef = CfnJobDefinition(stack, "batchJobDefinition-${logicalName}", props)
TagUtil.tag(jobDef, deploymentType)
return this
}
} | 0 | Kotlin | 0 | 1 | adad4a2adc81bbf424c95b1a0bac92fc937d6ae7 | 3,924 | kx_kotlin_support | MIT License |
buildSrc/src/main/java/deps/TestDependency.kt | Pekwerike | 437,379,245 | false | null | package deps
object TestDependency {
object AndroidTest {
object AndroidX {
const val EXPRESSO =
"androidx.test.espresso:espresso-core:${Version.ANDROIDX_EXPRESSO_CORE}"
const val JUNIT = "androidx.test.ext:junit:${Version.ANDROIDX_JUNIT}"
const val TEST_RULE = "androidx.test:rules:${Version.ANDROIDX_TEST_RULES}"
}
const val MOCKITO = "org.mockito:mockito-android:${Version.MOCKITO}"
}
object Test {
const val JUNIT = "junit:junit:${Version.JUNIT}"
object Mockito {
const val MOCKITO_CORE = "org.mockito:mockito-core:${Version.MOCKITO}"
const val MOCKITO_INLINE = "org.mockito:mockito-inline:${Version.MOCKITO}"
}
}
} | 1 | Kotlin | 0 | 1 | f4476e916ce869f2b37d87e722ba6aed34067bff | 764 | what3words | The Unlicense |
src/test/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/service/pricing/PricesSpreadsheetTest.kt | ministryofjustice | 292,861,912 | false | null | package uk.gov.justice.digital.hmpps.pecs.jpc.service.pricing
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.spy
import org.mockito.kotlin.whenever
import uk.gov.justice.digital.hmpps.pecs.jpc.domain.location.Location
import uk.gov.justice.digital.hmpps.pecs.jpc.domain.location.LocationType
import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.Price
import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.PriceRepository
import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.Supplier
internal class PricesSpreadsheetTest {
private val workbook: Workbook = XSSFWorkbook()
private val workbookSpy: Workbook = mock { spy(workbook) }
private val sheet: Sheet = workbook.createSheet()
private val priceRepository: PriceRepository = mock()
@Nested
inner class RecordingErrors {
private val spreadsheet: PricesSpreadsheet =
PricesSpreadsheet(workbookSpy, Supplier.GEOAMEY, emptyList(), priceRepository, 2020)
private val row: Row = sheet.createRow(0)
@Test
internal fun `no errors by default`() {
assertThat(spreadsheet.errors).isEmpty()
}
@Test
internal fun `errors are recorded`() {
val exception = RuntimeException("something went wrong")
spreadsheet.addError(row, exception)
assertThat(spreadsheet.errors).containsOnly(PricesSpreadsheetError(Supplier.GEOAMEY, row.rowNum + 1, exception))
}
}
@Nested
inner class MappingRowToPrice {
private val price: Price = mock()
private val fromLocation: Location = Location(LocationType.CC, "from agency id", "from site")
private val toLocation: Location = Location(LocationType.CC, "to agency id", "to site")
private val spreadsheet: PricesSpreadsheet =
PricesSpreadsheet(workbookSpy, Supplier.GEOAMEY, listOf(fromLocation, toLocation), priceRepository, 2020)
private val warnSpreadsheet: PricesSpreadsheet =
PricesSpreadsheet(workbookSpy, Supplier.GEOAMEY, listOf(fromLocation, toLocation), priceRepository, 2020, PriceImporter.Action.WARN)
private val row: Row = sheet.createRow(1).apply {
this.createCell(0).setCellValue(1.0)
this.createCell(1).setCellValue("from site")
this.createCell(2).setCellValue("to site")
this.createCell(3).setCellValue(100.005)
}
@Test
internal fun `can map row to price`() {
val price = spreadsheet.mapToPrice(row)
assertThat(price.fromLocation).isEqualTo(fromLocation)
assertThat(price.toLocation).isEqualTo(toLocation)
assertThat(price.priceInPence).isEqualTo(10001)
}
@Test
internal fun `throws error if from location is blank`() {
row.getCell(1).setCellValue("")
assertThatThrownBy { spreadsheet.mapToPrice(row) }
.isInstanceOf(RuntimeException::class.java)
.hasMessage("From location name cannot be blank")
}
@Test
internal fun `throws error if price is zero`() {
row.getCell(3).setCellValue(0.0)
assertThatThrownBy { spreadsheet.mapToPrice(row) }
.isInstanceOf(RuntimeException::class.java)
.hasMessage("Price must be greater than zero")
}
@Test
internal fun `cannot map row to price when from site not found`() {
row.getCell(1).setCellValue("UNKNOWN from site")
assertThatThrownBy { spreadsheet.mapToPrice(row) }
.isInstanceOf(RuntimeException::class.java)
.hasMessage("From location 'UNKNOWN FROM SITE' for supplier 'GEOAMEY' not found")
}
@Test
internal fun `throws error if to location is blank`() {
row.getCell(2).setCellValue("")
assertThatThrownBy { spreadsheet.mapToPrice(row) }
.isInstanceOf(RuntimeException::class.java)
.hasMessage("To location name cannot be blank")
}
@Test
internal fun `throws error if problem reading price`() {
row.getCell(3).setCellValue("string instead of numeric")
assertThatThrownBy { spreadsheet.mapToPrice(row) }
.isInstanceOf(RuntimeException::class.java)
.hasMessage("Error retrieving price for supplier 'GEOAMEY'")
}
@Test
internal fun `cannot map row to price when to site not found`() {
row.getCell(2).setCellValue("UNKNOWN to site")
assertThatThrownBy { spreadsheet.mapToPrice(row) }
.isInstanceOf(RuntimeException::class.java)
.hasMessage("To location 'UNKNOWN TO SITE' for supplier 'GEOAMEY' not found")
}
@Test
internal fun `throws error if duplicate price`() {
whenever(
priceRepository.findBySupplierAndFromLocationAndToLocationAndEffectiveYear(
Supplier.GEOAMEY,
fromLocation,
toLocation,
2020
)
).thenReturn(price)
assertThatThrownBy { spreadsheet.mapToPrice(row) }
.isInstanceOf(RuntimeException::class.java)
.hasMessage("Duplicate price: 'from site' to 'to site' for GEOAMEY")
}
@Test
internal fun `No Error if duplicate price and action is WARN`() {
whenever(
priceRepository.findBySupplierAndFromLocationAndToLocationAndEffectiveYear(
Supplier.GEOAMEY,
fromLocation,
toLocation,
2020
)
).thenReturn(price)
whenever(
price.priceInPence
).thenReturn(500)
val mappedPrice = warnSpreadsheet.mapToPrice(row)
assertThat(mappedPrice.fromLocation).isEqualTo(fromLocation)
assertThat(mappedPrice.toLocation).isEqualTo(toLocation)
assertThat(mappedPrice.priceInPence).isEqualTo(10001)
assertThat(mappedPrice.previousPrice).isEqualTo(price)
}
}
}
| 1 | null | 2 | 3 | fe19b13bbccc99d14ac70cfb1e3dfb017b62c87e | 5,928 | calculate-journey-variable-payments | MIT License |
app/src/main/java/com/example/afifit/data/OtherUserHolder.kt | innov-max | 763,176,305 | false | {"Kotlin": 105991, "C++": 11395} | package com.example.afifit.data
import android.content.Context
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.afifit.R
import com.sendbird.android.UserMessage
class OtherUserHolder(view: View) : RecyclerView.ViewHolder(view) {
val messageText = view.findViewById<TextView>(R.id.text_gchat_message_other)
val date = view.findViewById<TextView>(R.id.text_gchat_date_other)
val timestamp = view.findViewById<TextView>(R.id.text_gchat_timestamp_other)
val profileImage = view.findViewById<ImageView>(R.id.image_gchat_profile_other)
val user = view.findViewById<TextView>(R.id.text_gchat_user_other)
fun bindView(context: Context, message: UserMessage) {
messageText.setText(message.message)
timestamp.text = DateUtil.formatTime(message.createdAt)
date.visibility = View.VISIBLE
date.text = DateUtil.formatDate(message.createdAt)
Glide.with(context).load(message.sender.profileUrl).apply(RequestOptions().override(75, 75))
.into(profileImage)
user.text = message.sender.nickname
}
}
| 0 | Kotlin | 0 | 0 | a03468183cff369be9a69a2524d182f7b39ec02e | 1,259 | Afifit | MIT License |
src/main/kotlin/ac/github/oa/internal/core/item/script/hoop/ternary/CompareSymbol.kt | Man297 | 542,411,142 | false | null | package ac.github.oa.internal.core.item.script.hoop.ternary
import java.math.BigDecimal
interface CompareSymbol {
val name: String
fun apply(decimal1: BigDecimal, decimal2: BigDecimal): Boolean
}
| 0 | Kotlin | 0 | 0 | e2dac46ab0680dd1fc4eebdfce4e7680302364f0 | 209 | OriginAttributes_Test | Creative Commons Zero v1.0 Universal |
src/main/kotlin/cc/mycraft/mythic_cookstoves/items/food/StrawberryItem.kt | EpicWork-Little-Mod-Team | 512,423,513 | false | {"Kotlin": 66347} | package cc.mycraft.mythic_cookstoves.items.food
import cc.mycraft.mythic_cookstoves.blocks.ModBlocks
import cc.mycraft.mythic_cookstoves.items.ModTab
import net.minecraft.world.item.ItemNameBlockItem
class StrawberryItem :
ItemNameBlockItem(ModBlocks.STRAWBERRY_BUSH, Properties().tab(ModTab).food(ModFoods.STRAWBERRY)) | 0 | Kotlin | 0 | 0 | 620af5cec9204bcf3d6729fac14545e6da480f33 | 325 | MythicCookstoves | Apache License 2.0 |
android/core/network/src/main/java/com/jaino/network/datasource/review/ReviewDataSource.kt | pknu-wap | 615,959,763 | false | null | package com.jaino.network.datasource.review
import com.jaino.network.model.request.review.WriteDrinkReviewRequest
import com.jaino.network.model.response.review.DrinkReviewResponse
interface ReviewDataSource {
suspend fun getReviewList(drinkId: Long) : Result<List<DrinkReviewResponse>>
suspend fun postReview(drinkId: Long, request : WriteDrinkReviewRequest): Result<Unit>
} | 1 | Kotlin | 3 | 9 | f2144cb5f19d0617b146b94fcc3058f330f2df41 | 387 | 2023_1_WAT_BeJuRyu | MIT License |
src/commonMain/kotlin/character/classes/warlock/debuffs/UnstableAfflictionDot.kt | marisa-ashkandi | 332,658,265 | false | null | package character.classes.warlock.debuffs
import character.Ability
import character.Debuff
import character.Proc
import data.Constants
import mechanics.Spell
import sim.Event
import sim.SimParticipant
class UnstableAfflictionDot(owner: SimParticipant) : Debuff(owner) {
companion object {
const val name = "Unstable Affliction (DoT)"
}
override val name: String = Companion.name
override val durationMs: Int = 18000
override val tickDeltaMs: Int = 3000
val dmgPerTick = 175.0
val numTicks = durationMs / tickDeltaMs
val school = Constants.DamageType.SHADOW
val ua = object : Ability() {
override val id: Int = 30405
override val name: String = Companion.name
override fun gcdMs(sp: SimParticipant): Int = 0
override fun cast(sp: SimParticipant) {
val spellPowerCoeff = Spell.spellPowerCoeff(0, durationMs) / numTicks
val damageRoll = Spell.baseDamageRollSingle(owner, dmgPerTick, school, spellPowerCoeff)
val event = Event(
eventType = Event.Type.DAMAGE,
damageType = school,
abilityName = name,
amount = damageRoll,
result = Event.Result.HIT,
)
owner.logEvent(event)
owner.fireProc(listOf(Proc.Trigger.SHADOW_DAMAGE_PERIODIC), listOf(), this, event)
}
}
override fun tick(sp: SimParticipant) {
ua.cast(owner)
}
}
| 21 | Kotlin | 11 | 25 | 9cb6a0e51a650b5d04c63883cb9bf3f64057ce73 | 1,477 | tbcsim | MIT License |
feature-wallet-api/src/main/java/io/novafoundation/nova/feature_wallet_api/domain/updater/AccountInfoUpdater.kt | novasamatech | 415,834,480 | false | {"Kotlin": 8137060, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.feature_wallet_api.domain.updater
import io.novafoundation.nova.common.utils.Modules
import io.novafoundation.nova.core.storage.StorageCache
import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountRepository
import io.novafoundation.nova.feature_account_api.domain.model.accountIdIn
import io.novafoundation.nova.feature_account_api.domain.updaters.ChainUpdateScope
import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry
import io.novafoundation.nova.runtime.multiNetwork.chain.model.Chain
import io.novafoundation.nova.runtime.network.updaters.SingleStorageKeyUpdater
import io.novafoundation.nova.runtime.state.SelectedAssetOptionSharedState
import jp.co.soramitsu.fearless_utils.runtime.RuntimeSnapshot
import jp.co.soramitsu.fearless_utils.runtime.metadata.module
import jp.co.soramitsu.fearless_utils.runtime.metadata.storage
import jp.co.soramitsu.fearless_utils.runtime.metadata.storageKey
class AccountInfoUpdaterFactory(
private val storageCache: StorageCache,
private val accountRepository: AccountRepository,
private val chainRegistry: ChainRegistry
) {
fun create(chainUpdateScope: ChainUpdateScope, sharedState: SelectedAssetOptionSharedState<*>): AccountInfoUpdater {
return AccountInfoUpdater(
chainUpdateScope = chainUpdateScope,
storageCache = storageCache,
sharedState = sharedState,
accountRepository = accountRepository,
chainRegistry = chainRegistry
)
}
}
class AccountInfoUpdater(
chainUpdateScope: ChainUpdateScope,
storageCache: StorageCache,
sharedState: SelectedAssetOptionSharedState<*>,
chainRegistry: ChainRegistry,
private val accountRepository: AccountRepository,
) : SingleStorageKeyUpdater<Chain>(chainUpdateScope, sharedState, chainRegistry, storageCache) {
override val requiredModules: List<String> = listOf(Modules.SYSTEM)
override suspend fun storageKey(runtime: RuntimeSnapshot, scopeValue: Chain): String? {
val metaAccount = accountRepository.getSelectedMetaAccount()
val accountId = metaAccount.accountIdIn(scopeValue) ?: return null
return runtime.metadata.module(Modules.SYSTEM).storage("Account").storageKey(runtime, accountId)
}
}
| 12 | Kotlin | 6 | 9 | 618357859a4b7af95391fc0991339b78aff1be82 | 2,295 | nova-wallet-android | Apache License 2.0 |
extracted/konan.serializer/src/org/jetbrains/kotlin/konan/library/resolver/impl/KonanLibraryResolverImpl.kt | mrakakuy | 183,616,525 | false | null | package org.jetbrains.kotlin.konan.library.resolver.impl
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.library.*
import org.jetbrains.kotlin.konan.library.resolver.*
import org.jetbrains.kotlin.konan.util.WithLogger
internal class KonanLibraryResolverImpl(
override val searchPathResolver: SearchPathResolverWithTarget
): KonanLibraryResolver, WithLogger by searchPathResolver {
override fun resolveWithDependencies(
unresolvedLibraries: List<UnresolvedLibrary>,
noStdLib: Boolean,
noDefaultLibs: Boolean
) = findLibraries(unresolvedLibraries, noStdLib, noDefaultLibs)
.leaveDistinct()
.resolveDependencies()
/**
* Returns the list of libraries based on [libraryNames], [noStdLib] and [noDefaultLibs] criteria.
*
* This method does not return any libraries that might be available via transitive dependencies
* from the original library set (root set).
*/
private fun findLibraries(
unresolvedLibraries: List<UnresolvedLibrary>,
noStdLib: Boolean,
noDefaultLibs: Boolean
): List<KonanLibrary> {
val userProvidedLibraries = unresolvedLibraries.asSequence()
.map { searchPathResolver.resolve(it) }
.toList()
val defaultLibraries = searchPathResolver.defaultLinks(noStdLib, noDefaultLibs)
// Make sure the user provided ones appear first, so that
// they have precedence over defaults when duplicates are eliminated.
return userProvidedLibraries + defaultLibraries
}
/**
* Leaves only distinct libraries (by absolute path), warns on duplicated paths.
*/
private fun List<KonanLibrary>.leaveDistinct() =
this.groupBy { it.libraryFile.absolutePath }.let { groupedByAbsolutePath ->
warnOnLibraryDuplicates(groupedByAbsolutePath.filter { it.value.size > 1 }.keys)
groupedByAbsolutePath.map { it.value.first() }
}
private fun warnOnLibraryDuplicates(duplicatedPaths: Iterable<String>) {
duplicatedPaths.forEach { logger("library included more than once: $it") }
}
/**
* Given the list of root libraries does the following:
*
* 1. Evaluates other libraries that are available via transitive dependencies.
* 2. Wraps each [KonanLibrary] into a [KonanResolvedLibrary] with information about dependencies on other libraries.
* 3. Creates resulting [KonanLibraryResolveResult] object.
*/
private fun List<KonanLibrary>.resolveDependencies(): KonanLibraryResolveResult {
val rootLibraries = this.map { KonanResolvedLibraryImpl(it) }
// As far as the list of root libraries is known from the very beginning, the result can be
// constructed from the very beginning as well.
val result = KonanLibraryResolverResultImpl(rootLibraries)
val cache = mutableMapOf<File, KonanResolvedLibrary>()
cache.putAll(rootLibraries.map { it.library.libraryFile.absoluteFile to it })
var newDependencies = rootLibraries
do {
newDependencies = newDependencies.map { library: KonanResolvedLibraryImpl ->
library.library.unresolvedDependencies.asSequence()
.map { KonanResolvedLibraryImpl(searchPathResolver.resolve(it)) }
.map { resolved ->
val absoluteFile = resolved.library.libraryFile.absoluteFile
if (absoluteFile in cache) {
library.addDependency(cache[absoluteFile]!!)
null
} else {
cache.put(absoluteFile, resolved)
library.addDependency(resolved)
resolved
}
}.filterNotNull()
.toList()
}.flatten()
} while (newDependencies.isNotEmpty())
return result
}
}
internal class KonanLibraryResolverResultImpl(
private val roots: List<KonanResolvedLibrary>
): KonanLibraryResolveResult {
private val all: List<KonanResolvedLibrary> by lazy {
val result = mutableSetOf<KonanResolvedLibrary>().also { it.addAll(roots) }
var newDependencies = result.toList()
do {
newDependencies = newDependencies
.map { it -> it.resolvedDependencies }.flatten()
.filter { it !in result }
result.addAll(newDependencies)
} while (newDependencies.isNotEmpty())
result.toList()
}
override fun filterRoots(predicate: (KonanResolvedLibrary) -> Boolean) =
KonanLibraryResolverResultImpl(roots.filter(predicate))
override fun getFullList(order: LibraryOrder?) = (order?.invoke(all) ?: all).asPlain()
override fun forEach(action: (KonanLibrary, PackageAccessedHandler) -> Unit) {
all.forEach { action(it.library, it) }
}
private fun List<KonanResolvedLibrary>.asPlain() = map { it.library }
override fun toString() = "roots=$roots, all=$all"
}
| 0 | null | 0 | 2 | 1c6a2a711bc866b37a48076ff732413711bf966d | 5,250 | kotlin-native | Apache License 2.0 |
yangxj96-starter/yangxj96-starter-security/src/main/java/io/github/yangxj96/starter/security/filter/UserAuthorizationFilter.kt | yangxj96 | 574,967,993 | false | {"Kotlin": 197139} | package io.github.yangxj96.starter.security.filter
import io.github.yangxj96.starter.security.store.TokenStore
import jakarta.servlet.FilterChain
import jakarta.servlet.ServletException
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
import java.io.IOException
/**
* ็จๆท่ฏทๆฑๅคด่ฟๆปคๅจ
*/
class UserAuthorizationFilter(authenticationManager: AuthenticationManager, private val tokenStore: TokenStore) :
BasicAuthenticationFilter(authenticationManager) {
companion object {
private val log = LoggerFactory.getLogger(this::class.java)
}
@Throws(IOException::class, ServletException::class)
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
val authorization = request.getHeader("Authorization")
if (StringUtils.isNotEmpty(authorization)) {
try {
// ๆพๅ
ฅsecurityไธไธๆ,ๅฐฑๅฏไปฅ่ฟ่ก่ฎค่ฏไบ
SecurityContextHolder.getContext().authentication = tokenStore.read(authorization)
} catch (e: Exception) {
log.debug("่ฏปๅ่ฎค่ฏไฟกๆฏ้่ฏฏ")
}
}
super.doFilterInternal(request, response, chain)
}
}
| 0 | Kotlin | 0 | 0 | a8ffa8acf6933c7d56b510b05424c99d8b4d6076 | 1,514 | yangxj96-saas-api | MIT License |
couchbase-lite/src/commonMain/kotlin/kotbase/ArrayFunction.kt | jeffdgr8 | 518,984,559 | false | {"Kotlin": 2266831, "Python": 294} | /*
* Copyright 2022-2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotbase
/**
* Function provides array functions.
*/
public expect object ArrayFunction {
/**
* Creates an ARRAY_CONTAINS(expr, value) function that checks whether the given array
* expression contains the given value or not.
*
* @param expression The expression that evaluate to an array.
* @param value The value to search for in the given array expression.
* @return The ARRAY_CONTAINS(expr, value) function.
*/
public fun contains(expression: Expression, value: Expression): Expression
/**
* Creates an ARRAY_LENGTH(expr) function that returns the length of the given array
* expression.
*
* @param expression The expression that evaluates to an array.
* @return The ARRAY_LENGTH(expr) function.
*/
public fun length(expression: Expression): Expression
}
| 0 | Kotlin | 0 | 7 | ec8fbeb0d3e6c487ec8fb48ba2ba5388c71a29b1 | 1,452 | kotbase | Apache License 2.0 |
tokisaki-server/src/main/kotlin/io/micro/server/function/infra/dao/FunctionDAO.kt | spcookie | 730,690,607 | false | {"Kotlin": 168133, "Java": 13136} | package io.micro.server.function.infra.dao
import jakarta.enterprise.context.ApplicationScoped
@ApplicationScoped
class FunctionDAO : IFunctionDAO {
} | 0 | Kotlin | 0 | 0 | 63cd90108a0215a42b916fcc15281c658019d357 | 152 | Tokisaki | Apache License 2.0 |
detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnusedPrivateFunction.kt | detekt | 71,729,669 | false | null | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.config
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.rules.isOperator
import org.jetbrains.kotlin.backend.jvm.ir.psiElement
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtArrayAccessExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtOperationReferenceExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyDelegate
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.util.OperatorNameConventions
private const val ARRAY_GET_METHOD_NAME = "get"
/**
* Reports unused private functions.
*
* If these private functions are unused they should be removed. Otherwise, this dead code
* can lead to confusion and potential bugs.
*/
@RequiresTypeResolution
@ActiveByDefault(since = "1.16.0")
class UnusedPrivateMember(config: Config = Config.empty) : Rule(config) {
override val defaultRuleIdAliases: Set<String> = setOf("UNUSED_VARIABLE", "UNUSED_PARAMETER", "unused")
override val issue: Issue = Issue(
"UnusedPrivateMember",
"Private function is unused and should be removed.",
Debt.FIVE_MINS,
)
@Configuration("unused private function names matching this regex are ignored")
private val allowedNames: Regex by config("", String::toRegex)
override fun visit(root: KtFile) {
super.visit(root)
val visitor = UnusedFunctionVisitor(allowedNames, bindingContext)
root.accept(visitor)
visitor.getUnusedReports(issue).forEach { report(it) }
}
}
private class UnusedFunctionVisitor(
private val allowedNames: Regex,
private val bindingContext: BindingContext,
) : DetektVisitor() {
private val functionDeclarations = mutableMapOf<String, MutableList<KtFunction>>()
private val functionReferences = mutableMapOf<String, MutableList<KtReferenceExpression>>()
private val invokeOperatorReferences = mutableMapOf<CallableDescriptor, MutableList<KtReferenceExpression>>()
private val propertyDelegates = mutableListOf<KtPropertyDelegate>()
@Suppress("ComplexMethod", "LongMethod")
fun getUnusedReports(issue: Issue): List<CodeSmell> {
val propertyDelegateResultingDescriptors by lazy(LazyThreadSafetyMode.NONE) {
propertyDelegates.flatMap { it.resultingDescriptors() }
}
return functionDeclarations
.flatMap { (functionName, functions) ->
val isOperator = functions.any { it.isOperator() }
val references = functionReferences[functionName].orEmpty()
val unusedFunctions = when {
functions.size > 1 || isOperator -> {
val functionNameAsName = Name.identifier(functionName)
val operatorToken = OperatorConventions.getOperationSymbolForName(functionNameAsName)
val referencesViaOperator = if (
isOperator &&
functionNameAsName != OperatorNameConventions.INVOKE
) {
val operatorValue = (operatorToken as? KtSingleValueToken)?.value
val directReferences = operatorValue?.let { functionReferences[it] }.orEmpty()
val assignmentReferences = when (operatorToken) {
KtTokens.PLUS,
KtTokens.MINUS,
KtTokens.MUL,
KtTokens.DIV,
KtTokens.PERC,
-> operatorValue?.let { functionReferences["$it="] }.orEmpty()
else -> emptyList()
}
val containingReferences = if (functionNameAsName == OperatorNameConventions.CONTAINS) {
listOf(KtTokens.IN_KEYWORD, KtTokens.NOT_IN).flatMap {
functionReferences[it.value].orEmpty()
}
} else {
emptyList()
}
directReferences + assignmentReferences + containingReferences
} else if (functionNameAsName == OperatorNameConventions.INVOKE) {
getInvokeReferences(functions)
} else {
emptyList()
}
val referenceDescriptors = (references + referencesViaOperator)
.mapNotNull { it.getResolvedCall(bindingContext)?.resultingDescriptor }
.map { it.original }
.let {
if (functionNameAsName in OperatorNameConventions.DELEGATED_PROPERTY_OPERATORS) {
it + propertyDelegateResultingDescriptors
} else {
it
}
}
functions.filterNot {
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] in referenceDescriptors
}
}
references.isEmpty() -> functions
else -> emptyList()
}
unusedFunctions.map {
CodeSmell(issue, Entity.atName(it), "Private function `$functionName` is unused.")
}
}
}
private fun getInvokeReferences(functions: MutableList<KtFunction>) =
functions.flatMap { function ->
val callableDescriptor =
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, function]
callableDescriptor?.let {
invokeOperatorReferences[it]
}.orEmpty()
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (!isDeclaredInsideAnInterface(function) && function.isPrivate()) {
collectFunction(function)
}
super.visitNamedFunction(function)
}
private fun isDeclaredInsideAnInterface(function: KtNamedFunction) =
function.getStrictParentOfType<KtClass>()?.isInterface() == true
private fun collectFunction(function: KtNamedFunction) {
val name = function.nameAsSafeName.identifier
if (!allowedNames.matches(name)) {
functionDeclarations.getOrPut(name) { mutableListOf() }.add(function)
}
}
private fun KtPropertyDelegate.resultingDescriptors(): List<FunctionDescriptor> {
val property = this.parent as? KtProperty ?: return emptyList()
val propertyDescriptor =
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? PropertyDescriptor
return listOfNotNull(propertyDescriptor?.getter, propertyDescriptor?.setter).mapNotNull {
bindingContext[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, it]?.resultingDescriptor
}
}
override fun visitPropertyDelegate(delegate: KtPropertyDelegate) {
super.visitPropertyDelegate(delegate)
propertyDelegates.add(delegate)
}
/*
* We need to collect all private function declarations and references to these functions
* for the whole file as Kotlin allows access to private and internal object declarations
* from everywhere in the file.
*/
override fun visitReferenceExpression(expression: KtReferenceExpression) {
super.visitReferenceExpression(expression)
val name = when (expression) {
is KtOperationReferenceExpression -> expression.getReferencedName()
is KtNameReferenceExpression -> expression.getReferencedName()
is KtArrayAccessExpression -> ARRAY_GET_METHOD_NAME
is KtCallExpression -> {
val resolvedCall = expression.getResolvedCall(bindingContext) ?: return
val callableDescriptor = resolvedCall.resultingDescriptor
if ((callableDescriptor.psiElement as? KtNamedFunction)?.isOperator() == true) {
invokeOperatorReferences.getOrPut(callableDescriptor) { mutableListOf() }.add(expression)
}
null
}
else -> null
} ?: return
functionReferences.getOrPut(name) { mutableListOf() }.add(expression)
}
}
| 9 | null | 772 | 6,253 | c5d7ed3da2824534d0e15f8404ad4f1c59fb553c | 9,924 | detekt | Apache License 2.0 |
OrderCenter/src/main/java/com/kotlin/order/ui/activity/ShipAddressEditActivity.kt | starktonys | 140,391,283 | false | null | package com.kotlin.order.ui.activity
import android.os.Bundle
import com.kotlin.base.ext.onClick
import com.kotlin.base.ui.activity.BaseActivity
import com.kotlin.base.ui.activity.BaseMvpActivity
import com.kotlin.order.R
import com.kotlin.order.common.OrderConstant
import com.kotlin.order.data.protocol.ShipAddress
import com.kotlin.order.injection.component.DaggerShipAddressComponent
import com.kotlin.order.injection.module.ShipAddressModule
import com.kotlin.order.presenter.EditShipAddressPresenter
import com.kotlin.order.presenter.view.EditShipAddressView
import kotlinx.android.synthetic.main.activity_edit_address.*
import org.jetbrains.anko.toast
class ShipAddressEditActivity : BaseMvpActivity<EditShipAddressPresenter>(), EditShipAddressView {
private var mAddress: ShipAddress? = null
override fun injectComponent() {
DaggerShipAddressComponent.builder().activityComponent(activityComponent)
.shipAddressModule(ShipAddressModule()).build().inject(this)
mPresenter.mView = this
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_address)
initView()
initData()
}
private fun initView() {
mSaveBtn.onClick {
if (mShipNameEt.text.isNullOrEmpty()) {
toast("ๅ็งฐไธ่ฝไธบ็ฉบ")
return@onClick
}
if (mShipMobileEt.text.isNullOrEmpty()) {
toast("็ต่ฏไธ่ฝไธบ็ฉบ")
return@onClick
}
if (mShipAddressEt.text.isNullOrEmpty()) {
toast("ๅฐๅไธ่ฝไธบ็ฉบ")
return@onClick
}
if (mAddress == null) {
mPresenter.addShipAddress(mShipNameEt.text.toString(),
mShipMobileEt.text.toString(),
mShipAddressEt.text.toString())
} else {
mAddress!!.shipUserName = mShipNameEt.text.toString()
mAddress!!.shipUserMobile = mShipMobileEt.text.toString()
mAddress!!.shipAddress = mShipAddressEt.text.toString()
mPresenter.editShipAddress(mAddress!!)
}
}
}
private fun initData() {
mAddress = intent.getParcelableExtra(OrderConstant.KEY_SHIP_ADDRESS)
mAddress?.let {
mShipNameEt.setText(it.shipUserName)
mShipMobileEt.setText(it.shipUserMobile)
mShipAddressEt.setText(it.shipAddress)
}
}
override fun onAddShipAddressResult(result: Boolean) {
toast("ๆทปๅ ๅฐๅๆๅ")
finish()
}
override fun onEditShipAddressResult(result: Boolean) {
toast("ไฟฎๆนๅฐๅๆๅ")
finish()
}
} | 0 | null | 1 | 8 | 7cb3f869a27c9f8a6ba44b72a7d328a1383ec4aa | 2,756 | KotlinMall-App | Apache License 2.0 |
feature/market/src/main/kotlin/com/niyaj/feature/market/measureUnit/settings/ExportMeasureUnitScreen.kt | skniyajali | 644,752,474 | false | {"Kotlin": 4945599, "Shell": 8001, "Java": 232} | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.niyaj.feature.market.marketItem.settings
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FabPosition
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.niyaj.common.tags.MarketListTestTags
import com.niyaj.common.tags.MarketListTestTags.EXPORT_MARKET_ITEM_FILE_NAME
import com.niyaj.common.tags.MarketListTestTags.EXPORT_MARKET_ITEM_TITLE
import com.niyaj.common.tags.MarketListTestTags.MARKET_ITEM_NOT_AVAILABLE
import com.niyaj.common.tags.MarketListTestTags.MARKET_ITEM_SEARCH_PLACEHOLDER
import com.niyaj.common.utils.Constants
import com.niyaj.designsystem.components.PoposButton
import com.niyaj.designsystem.icon.PoposIcons
import com.niyaj.designsystem.theme.PoposRoomTheme
import com.niyaj.designsystem.theme.SpaceLarge
import com.niyaj.designsystem.theme.SpaceSmall
import com.niyaj.designsystem.theme.SpaceSmallMax
import com.niyaj.domain.utils.ImportExport
import com.niyaj.feature.market.components.MarketItemCardList
import com.niyaj.feature.market.destinations.AddEditMarketItemScreenDestination
import com.niyaj.model.MarketItem
import com.niyaj.ui.components.InfoText
import com.niyaj.ui.components.ItemNotAvailable
import com.niyaj.ui.components.LoadingIndicator
import com.niyaj.ui.components.NAV_SEARCH_BTN
import com.niyaj.ui.components.PoposSecondaryScaffold
import com.niyaj.ui.components.ScrollToTop
import com.niyaj.ui.components.StandardSearchBar
import com.niyaj.ui.parameterProvider.MarketItemPreviewData
import com.niyaj.ui.utils.DevicePreviews
import com.niyaj.ui.utils.TrackScreenViewEvent
import com.niyaj.ui.utils.UiEvent
import com.niyaj.ui.utils.isScrollingUp
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.result.ResultBackNavigator
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Destination
@Composable
fun ExportMarketItemScreen(
navigator: DestinationsNavigator,
resultBackNavigator: ResultBackNavigator<String>,
modifier: Modifier = Modifier,
viewModel: MarketItemSettingsViewModel = hiltViewModel(),
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val items by viewModel.items.collectAsStateWithLifecycle()
val exportedItems by viewModel.exportedItems.collectAsStateWithLifecycle()
val showSearchBar by viewModel.showSearchBar.collectAsStateWithLifecycle()
val event by viewModel.eventFlow.collectAsStateWithLifecycle(initialValue = null)
val searchText = viewModel.searchText.value
val selectedItems = viewModel.selectedItems.toList()
val isLoading = remember { mutableStateOf(false) }
LaunchedEffect(key1 = event) {
event?.let { data ->
when (data) {
is UiEvent.OnError -> {
resultBackNavigator.navigateBack(data.errorMessage)
}
is UiEvent.OnSuccess -> {
resultBackNavigator.navigateBack(data.successMessage)
}
}
}
}
val exportLauncher =
rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) {
it.data?.data?.let {
scope.launch {
isLoading.value = true
val result = ImportExport.writeDataAsync(context, it, exportedItems)
if (result.isSuccess) {
resultBackNavigator.navigateBack("${exportedItems.size} Items has been exported.")
} else {
resultBackNavigator.navigateBack("Unable to export items.")
}
}
}
}
ExportMarketItemScreenContent(
modifier = modifier,
items = items.toImmutableList(),
selectedItems = selectedItems.toImmutableList(),
isLoading = isLoading.value,
showSearchBar = showSearchBar,
searchText = searchText,
onClearClick = viewModel::clearSearchText,
onSearchTextChanged = viewModel::searchTextChanged,
onClickOpenSearch = viewModel::openSearchBar,
onClickCloseSearch = viewModel::closeSearchBar,
onClickSelectAll = viewModel::selectAllItems,
onClickDeselect = viewModel::deselectItems,
onSelectItem = viewModel::selectItem,
onClickExport = {
scope.launch {
val result = ImportExport.createFile(
context = context,
fileName = EXPORT_MARKET_ITEM_FILE_NAME,
)
exportLauncher.launch(result)
viewModel.onEvent(MarketItemSettingsEvent.GetExportedMarketItem)
}
},
onBackClick = navigator::navigateUp,
onClickToAddItem = {
navigator.navigate(AddEditMarketItemScreenDestination())
},
)
}
@VisibleForTesting
@Composable
internal fun ExportMarketItemScreenContent(
items: ImmutableList<MarketItem>,
selectedItems: ImmutableList<Int>,
isLoading: Boolean,
showSearchBar: Boolean,
searchText: String,
onClearClick: () -> Unit,
onSearchTextChanged: (String) -> Unit,
onClickOpenSearch: () -> Unit,
onClickCloseSearch: () -> Unit,
onClickSelectAll: () -> Unit,
onClickDeselect: () -> Unit,
onSelectItem: (Int) -> Unit,
onClickExport: () -> Unit,
onBackClick: () -> Unit,
onClickToAddItem: () -> Unit,
modifier: Modifier = Modifier,
scope: CoroutineScope = rememberCoroutineScope(),
lazyGridState: LazyGridState = rememberLazyGridState(),
padding: PaddingValues = PaddingValues(SpaceSmallMax, 0.dp, SpaceSmallMax, SpaceLarge),
) {
TrackScreenViewEvent(screenName = "ExportMarketItemScreen")
val text =
if (searchText.isEmpty()) MARKET_ITEM_NOT_AVAILABLE else Constants.SEARCH_ITEM_NOT_FOUND
val title =
if (selectedItems.isEmpty()) EXPORT_MARKET_ITEM_TITLE else "${selectedItems.size} Selected"
BackHandler {
if (selectedItems.isNotEmpty()) {
onClickDeselect()
} else if (showSearchBar) {
onClickCloseSearch()
} else {
onBackClick()
}
}
PoposSecondaryScaffold(
title = title,
onBackClick = if (showSearchBar) onClickCloseSearch else onBackClick,
showBackButton = selectedItems.isEmpty() || showSearchBar,
showBottomBar = items.isNotEmpty(),
showSecondaryBottomBar = true,
fabPosition = FabPosition.End,
navigationIcon = {
IconButton(
onClick = onClickDeselect,
) {
Icon(
imageVector = PoposIcons.Close,
contentDescription = "Deselect All",
)
}
},
navActions = {
if (showSearchBar) {
StandardSearchBar(
searchText = searchText,
placeholderText = MARKET_ITEM_SEARCH_PLACEHOLDER,
onClearClick = onClearClick,
onSearchTextChanged = onSearchTextChanged,
)
} else {
if (items.isNotEmpty()) {
IconButton(
onClick = onClickSelectAll,
) {
Icon(
imageVector = PoposIcons.Checklist,
contentDescription = Constants.SELECT_ALL_ICON,
)
}
IconButton(
onClick = onClickOpenSearch,
modifier = Modifier.testTag(NAV_SEARCH_BTN),
) {
Icon(
imageVector = PoposIcons.Search,
contentDescription = "Search Icon",
)
}
}
}
},
floatingActionButton = {
ScrollToTop(
visible = !lazyGridState.isScrollingUp(),
onClick = {
scope.launch {
lazyGridState.animateScrollToItem(index = 0)
}
},
)
},
bottomBar = {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(padding),
verticalArrangement = Arrangement.spacedBy(SpaceSmall),
) {
InfoText(
text = "${
if (selectedItems.isEmpty()) {
"All"
} else {
"${selectedItems.size}"
}
} market item will be exported.",
)
PoposButton(
modifier = Modifier
.fillMaxWidth()
.testTag(EXPORT_MARKET_ITEM_TITLE),
enabled = items.isNotEmpty(),
text = EXPORT_MARKET_ITEM_TITLE,
icon = PoposIcons.Upload,
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondary,
),
onClick = onClickExport,
)
}
},
) {
Box(
modifier = modifier
.fillMaxSize()
.padding(it),
) {
if (items.isEmpty()) {
ItemNotAvailable(
text = text,
buttonText = MarketListTestTags.CREATE_NEW_ITEM,
onClick = onClickToAddItem,
)
} else if (isLoading) {
LoadingIndicator()
} else {
MarketItemCardList(
items = items,
isInSelectionMode = true,
doesSelected = selectedItems::contains,
onSelectItem = onSelectItem,
modifier = Modifier,
lazyGridState = lazyGridState,
)
}
}
}
}
@DevicePreviews
@Composable
private fun ExportMarketItemScreenContentEmptyPreview() {
PoposRoomTheme {
ExportMarketItemScreenContent(
modifier = Modifier,
items = persistentListOf(),
selectedItems = persistentListOf(),
isLoading = false,
showSearchBar = false,
searchText = "",
onClearClick = {},
onSearchTextChanged = {},
onClickOpenSearch = {},
onClickCloseSearch = {},
onClickSelectAll = {},
onClickDeselect = {},
onSelectItem = {},
onClickExport = {},
onBackClick = {},
onClickToAddItem = {},
)
}
}
@DevicePreviews
@Composable
private fun ExportMarketItemScreenContentPreview(
items: ImmutableList<MarketItem> = MarketItemPreviewData.marketItems.toImmutableList(),
) {
PoposRoomTheme {
ExportMarketItemScreenContent(
modifier = Modifier,
items = items,
selectedItems = persistentListOf(),
isLoading = false,
showSearchBar = false,
searchText = "",
onClearClick = {},
onSearchTextChanged = {},
onClickOpenSearch = {},
onClickCloseSearch = {},
onClickSelectAll = {},
onClickDeselect = {},
onSelectItem = {},
onClickExport = {},
onBackClick = {},
onClickToAddItem = {},
)
}
}
| 42 | Kotlin | 0 | 1 | d449fd857f3a1d12596c566341a6a182eea15d78 | 13,930 | PoposRoom | Apache License 2.0 |
app/src/main/java/org/ranapat/examples/githubbrowser/ui/util/ViewExtensions.kt | ranapat | 228,177,529 | false | {"Java": 316894, "Kotlin": 46620} | package org.ranapat.examples.githubbrowser.ui.util
import android.content.Context.INPUT_METHOD_SERVICE
import android.view.View
import android.view.inputmethod.InputMethodManager
fun View.hideSoftKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
inputMethodManager?.hideSoftInputFromWindow(this.windowToken, 0)
} | 1 | Java | 1 | 1 | d21457603352790277e4e866f2345c3f47ee5971 | 380 | github-browser-example | The Unlicense |
core/src/main/kotlin/com/github/quillraven/darkmatter/ecs/component/RemoveComponent.kt | Quillraven | 255,084,653 | false | null | package com.github.quillraven.darkmatter.ecs.component
import com.badlogic.ashley.core.Component
import com.badlogic.gdx.utils.Pool
import ktx.ashley.mapperFor
class RemoveComponent : Component, Pool.Poolable {
var delay = 0f
override fun reset() {
delay = 0f
}
companion object {
val mapper = mapperFor<RemoveComponent>()
}
}
| 7 | null | 9 | 51 | 676da9ddaec5b61e8ff08253cae99d01705dedb8 | 367 | Dark-Matter | MIT License |
app/src/main/java/com/shermanrex/recorderApp/presentation/screen/setting/component/SampleRateSection.kt | AlirezaNouri-77 | 818,004,544 | false | {"Kotlin": 154370} | package com.shermanrex.recorderApp.presentation.screen.setting.component
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.shermanrex.recorderApp.data.util.convertHzToKhz
@Composable
fun SampleRateSection(
sampleRateList: List<Int>,
currentSampleRate: Int,
onItemClick: (Int) -> Unit,
) {
Column {
Text(text = "Sample Rate", fontWeight = FontWeight.SemiBold, fontSize = 18.sp)
Text(
text = "Sample rate in audio is how often the sound is digitally measured per second",
fontWeight = FontWeight.Light,
fontSize = 13.sp
)
LazyRow(
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
items(sampleRateList) { item ->
FilterChip(
selected = item == currentSampleRate,
onClick = { if (item != currentSampleRate) onItemClick(item) },
colors = FilterChipDefaults.filterChipColors(
containerColor = MaterialTheme.colorScheme.primary.copy(alpha = 1f),
selectedContainerColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.05f),
),
border = BorderStroke(0.dp, Color.Transparent),
label = {
Text(text = item.convertHzToKhz(), fontWeight = FontWeight.Medium, fontSize = 14.sp)
},
)
}
}
}
} | 0 | Kotlin | 0 | 0 | 3e0d7a6eadf53a6226bd0c7b6216635c8713201e | 1,874 | SimpleVoiceRecorder | MIT License |
src/praj/app/swagtag/UIHandler.kt | praj-foss | 115,777,729 | false | null | package praj.app.swagtag
import javafx.geometry.HPos
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.control.ScrollPane
import javafx.scene.control.TextField
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.ColumnConstraints
import javafx.scene.layout.GridPane
import javafx.scene.layout.Priority
import javafx.stage.FileChooser
import javafx.stage.Stage
import java.io.File
/**
* Created by <NAME> on 27/12/17
*/
object UIHandler {
lateinit var stage: Stage
lateinit var scene: Scene
lateinit var root: GridPane
private var file: File? = null
private var filenameLabel = Label("Please select music file")
private val buttons = arrayListOf<Button>()
private val textFields = arrayListOf<TextField>()
private val labels = arrayListOf<Label>()
private val imgView = ImageView()
private val IMG_STREAM = ClassLoader.getSystemResourceAsStream("unavailable.png")
private val UNAVAILABLE_IMG = Image(IMG_STREAM)
private val fileChooser = FileChooser()
private val fileChooserStage = Stage()
fun initialize(stage: Stage) {
this.stage = stage
initStage()
initControls()
initFields()
scene = Scene(root,800.0, 400.0)
stage.scene = scene
}
private fun initStage() {
stage.apply {
title = "swagtag"
minWidth = 800.0
minHeight = 400.0
}
}
private fun initControls() {
// setting up the root container (GridPane)
root = GridPane().apply {
hgap = 10.0
vgap = 10.0
padding = Insets(10.0)
alignment = Pos.CENTER
//isGridLinesVisible = true
columnConstraints.addAll(
ColumnConstraints().apply { // col 1
hgrow = Priority.ALWAYS
halignment = HPos.CENTER
},
ColumnConstraints().apply { // col 2
hgrow = Priority.ALWAYS
}
)
}
// Setting up the file name label
root.add(filenameLabel, 0, 0, 1, 1)
// Setting up buttons
for(i in 0..2) {
buttons.add(Button())
buttons[i].prefWidth = 70.0
root.add(buttons[i], i+2, 0, 1, 1)
}
buttons.apply {
get(0).text = "Browse"
get(1).text = "Read"
get(2).text = "Save"
get(0).setOnAction { selectFile() }
get(1).setOnAction { readFile() }
get(2).isDisable = true
}
}
private fun initFields() {
// Setting up album art
imgView.apply {
image = UNAVAILABLE_IMG
fitWidth = 300.0
fitHeight = 300.0
isSmooth = true
isPreserveRatio = true
}
IMG_STREAM.close()
// Setting up scrollable area
val scrollPane = ScrollPane()
val scrollGrid = GridPane()
scrollPane.apply {
content = scrollGrid
isFitToWidth = true
}
scrollGrid.apply {
hgap = 10.0
vgap = 10.0
padding = Insets(10.0)
alignment = Pos.CENTER
//isGridLinesVisible = true
columnConstraints.addAll(
ColumnConstraints(),
ColumnConstraints().apply {
//setMinSize(160.0, Region.USE_COMPUTED_SIZE)
hgrow = Priority.ALWAYS
}
)
}
// Adding value labels and textfields to root
for(i in 0..11) {
labels.add(Label("ABC"))
textFields.add(TextField())
scrollGrid.add(labels[i], 0, i, 1, 1)
scrollGrid.add(textFields[i], 1, i, 1, 1)
}
(0..11).forEach { i ->
labels[i].text = when(i) {
0 -> "Title"
1 -> "Artist"
2 -> "Album"
3 -> "Track"
4 -> "Year"
5 -> "Genre"
6 -> "Comment"
7 -> "BPM"
8 -> "Composer"
9 -> "Encoder"
10 -> "Publisher"
11 -> "Copyright"
else -> null
}
}
root.add(imgView, 0,1,1,1)
root.add(scrollPane, 1, 1, 4, 1)
}
private fun selectFile() {
file = fileChooser.run {
title = "Open music file"
extensionFilters.add(FileChooser.ExtensionFilter("Music files", "*.mp3"))
showOpenDialog(fileChooserStage)
}
filenameLabel.text = file?.name ?: return
}
private fun readFile() {
if(file == null) return
textFields.map {
it.text = "Not available"
it.isDisable = true
}
Mp3Handler.update(file!!)
for(i in 0 until Mp3Handler.tagData.size) {
textFields[i].text = Mp3Handler.tagData[i]
textFields[i].isDisable = false
}
imgView.image = Mp3Handler.albumArt ?: UNAVAILABLE_IMG
}
fun show() {
stage.show()
}
} | 0 | Kotlin | 0 | 0 | a3bf152eb0227f96fee37b10e94fb83d4c519a65 | 5,375 | swagtag | MIT License |
core/core-media-notification/src/main/kotlin/com/maximillianleonov/musicmax/core/media/notification/MusicNotificationProvider.kt | MaximillianLeonov | 559,137,206 | false | null | /*
* Copyright 2022 Afig Aliyev
*
* 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.maximillianleonov.musicmax.core.media.notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.core.app.NotificationCompat
import androidx.core.content.getSystemService
import androidx.media3.session.CommandButton
import androidx.media3.session.MediaNotification
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaStyleNotificationHelper.MediaStyle
import com.google.common.collect.ImmutableList
import com.maximillianleonov.musicmax.core.common.dispatcher.Dispatcher
import com.maximillianleonov.musicmax.core.common.dispatcher.MusicmaxDispatchers.IO
import com.maximillianleonov.musicmax.core.common.dispatcher.MusicmaxDispatchers.MAIN
import com.maximillianleonov.musicmax.core.designsystem.icon.MusicmaxIcons
import com.maximillianleonov.musicmax.core.media.notification.common.MusicActions
import com.maximillianleonov.musicmax.core.media.notification.util.asArtworkBitmap
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
class MusicNotificationProvider @Inject constructor(
@Dispatcher(MAIN) mainDispatcher: CoroutineDispatcher,
@ApplicationContext private val context: Context,
@Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher
) : MediaNotification.Provider {
private val notificationManager = checkNotNull(context.getSystemService<NotificationManager>())
private val coroutineScope = CoroutineScope(mainDispatcher + SupervisorJob())
override fun createNotification(
mediaSession: MediaSession,
customLayout: ImmutableList<CommandButton>,
actionFactory: MediaNotification.ActionFactory,
onNotificationChangedCallback: MediaNotification.Provider.Callback
): MediaNotification {
ensureNotificationChannel()
val player = mediaSession.player
val metadata = player.mediaMetadata
val builder = NotificationCompat.Builder(context, MusicNotificationChannelId)
.setContentTitle(metadata.title)
.setContentText(metadata.artist)
.setSmallIcon(MusicmaxIcons.Music.resourceId)
.setStyle(MediaStyle(mediaSession))
.setContentIntent(mediaSession.sessionActivity)
getNotificationActions(
mediaSession = mediaSession,
customLayout = customLayout,
actionFactory = actionFactory,
playWhenReady = player.playWhenReady
).forEach(builder::addAction)
setupArtwork(
uri = metadata.artworkUri,
setLargeIcon = builder::setLargeIcon,
updateNotification = {
val notification = MediaNotification(MusicNotificationId, builder.build())
onNotificationChangedCallback.onNotificationChanged(notification)
}
)
return MediaNotification(MusicNotificationId, builder.build())
}
override fun handleCustomCommand(session: MediaSession, action: String, extras: Bundle) = false
fun cancelCoroutineScope() = coroutineScope.cancel()
private fun ensureNotificationChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
notificationManager.getNotificationChannel(MusicNotificationChannelId) != null
) {
return
}
val notificationChannel = NotificationChannel(
MusicNotificationChannelId,
context.getString(R.string.music_notification_channel_name),
NotificationManager.IMPORTANCE_LOW
)
notificationManager.createNotificationChannel(notificationChannel)
}
private fun getNotificationActions(
mediaSession: MediaSession,
customLayout: ImmutableList<CommandButton>,
actionFactory: MediaNotification.ActionFactory,
playWhenReady: Boolean
) = listOf(
MusicActions.getRepeatShuffleAction(mediaSession, customLayout, actionFactory),
MusicActions.getSkipPreviousAction(context, mediaSession, actionFactory),
MusicActions.getPlayPauseAction(context, mediaSession, actionFactory, playWhenReady),
MusicActions.getSkipNextAction(context, mediaSession, actionFactory),
MusicActions.getFavoriteAction(mediaSession, customLayout, actionFactory)
)
private fun setupArtwork(
uri: Uri?,
setLargeIcon: (Bitmap?) -> Unit,
updateNotification: () -> Unit
) = coroutineScope.launch {
val bitmap = loadArtworkBitmap(uri)
setLargeIcon(bitmap)
updateNotification()
}
private suspend fun loadArtworkBitmap(uri: Uri?) =
withContext(ioDispatcher) { uri?.asArtworkBitmap(context) }
}
private const val MusicNotificationId = 1001
private const val MusicNotificationChannelId = "MusicNotificationChannel"
| 5 | null | 5 | 61 | 29dd1c65e202aae78d6565c6490e3019d921fb23 | 5,763 | Musicmax | Apache License 2.0 |
editor/src/main/kotlin/com/dr10/editor/ui/EmptyContextMenu.kt | Daniel0110000 | 702,220,698 | false | null | package com.dr10.editor.ui
import androidx.compose.foundation.ContextMenuArea
import androidx.compose.foundation.ContextMenuState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.text.TextContextMenu
import androidx.compose.runtime.Composable
/**
* Object that creates an empty context menu by implementing the [TextContextMenu] interface for its creation
*/
@OptIn(ExperimentalFoundationApi::class)
object EmptyContextMenu: TextContextMenu {
@ExperimentalFoundationApi
@Composable
override fun Area(textManager: TextContextMenu.TextManager, state: ContextMenuState, content: @Composable () -> Unit) {
ContextMenuArea({ emptyList() }, state, content = content)
}
} | 1 | null | 3 | 29 | 9d75ecc560d86e12de14ff3153bcac79b0f0c02d | 739 | DeepCodeStudio | Apache License 2.0 |
src/main/kotlin/ru/yoomoney/tech/grafana/dsl/panels/PanelsBuilder.kt | yoomoney | 158,901,967 | false | null | package ru.yandex.money.tools.grafana.dsl.panels
import ru.yandex.money.tools.grafana.dsl.generators.PanelLayoutGenerator
import ru.yandex.money.tools.grafana.dsl.variables.Variable
/**
* Panels builder.
*
* @author <NAME> (<EMAIL>)
* @since 7/21/18
*/
class PanelsBuilder(override val panelLayoutGenerator: PanelLayoutGenerator) : PanelContainerBuilder {
override val panels = mutableListOf<Panel>()
/**
* This method is used to support backward compatibility.
*/
fun row(title: String, build: RowBuilder.() -> Unit) {
row(title, null, false, build)
}
fun row(title: String, repeatFor: Variable? = null, collapsed: Boolean = false, build: RowBuilder.() -> Unit) {
val builder = RowBuilder(title, repeatFor?.name, panelLayoutGenerator, collapsed)
builder.build()
panels += builder.createRow()
}
}
| 2 | null | 8 | 53 | 58ab4e2e70e544c4160b97b4dc64e73235a4bd00 | 873 | grafana-dashboard-dsl | MIT License |
src/main/kotlin/com/ryanmoelter/splity/database/Ids.kt | ryanmoelter | 270,082,440 | false | null | package co.moelten.splity.database
import com.squareup.sqldelight.ColumnAdapter
import java.util.UUID
@JvmInline
value class BudgetId(val plainUuid: UUID) {
override fun toString(): String = plainUuid.toString()
}
fun String.toBudgetId() = BudgetId(UUID.fromString(this))
fun UUID.toBudgetId() = BudgetId(this)
val budgetIdAdapter = object : ColumnAdapter<BudgetId, String> {
override fun decode(databaseValue: String) = databaseValue.toBudgetId()
override fun encode(value: BudgetId) = value.toString()
}
@JvmInline
value class AccountId(val plainUuid: UUID) {
override fun toString(): String = plainUuid.toString()
}
fun String.toAccountId() = AccountId(UUID.fromString(this))
fun UUID.toAccountId() = AccountId(this)
val accountIdAdapter = object : ColumnAdapter<AccountId, String> {
override fun decode(databaseValue: String) = databaseValue.toAccountId()
override fun encode(value: AccountId) = value.toString()
}
@JvmInline
value class TransactionId(val string: String) {
override fun toString(): String = string
}
fun String.toTransactionId() = TransactionId(this)
fun UUID.toTransactionId() = TransactionId(this.toString())
operator fun TransactionId.plus(postfix: String) = TransactionId(string + postfix)
val transactionIdAdapter = object : ColumnAdapter<TransactionId, String> {
override fun decode(databaseValue: String) = databaseValue.toTransactionId()
override fun encode(value: TransactionId) = value.toString()
}
@JvmInline
value class SubTransactionId(val string: String) {
override fun toString(): String = string
}
fun String.toSubTransactionId() = SubTransactionId(this)
fun UUID.toSubTransactionId() = SubTransactionId(this.toString())
operator fun SubTransactionId.plus(postfix: String) = SubTransactionId(string + postfix)
val subTransactionIdAdapter = object : ColumnAdapter<SubTransactionId, String> {
override fun decode(databaseValue: String) = databaseValue.toSubTransactionId()
override fun encode(value: SubTransactionId) = value.toString()
}
@JvmInline
value class CategoryId(val plainUuid: UUID) {
override fun toString(): String = plainUuid.toString()
}
fun String.toCategoryId() = CategoryId(UUID.fromString(this))
fun UUID.toCategoryId() = CategoryId(this)
val categoryIdAdapter = object : ColumnAdapter<CategoryId, String> {
override fun decode(databaseValue: String) = databaseValue.toCategoryId()
override fun encode(value: CategoryId) = value.toString()
}
@JvmInline
value class PayeeId(val plainUuid: UUID) {
override fun toString(): String = plainUuid.toString()
}
fun String.toPayeeId() = PayeeId(UUID.fromString(this))
fun UUID.toPayeeId() = PayeeId(this)
val payeeIdAdapter = object : ColumnAdapter<PayeeId, String> {
override fun decode(databaseValue: String) = databaseValue.toPayeeId()
override fun encode(value: PayeeId) = value.toString()
}
| 2 | null | 0 | 3 | 86d276ade570bf57321fb29e1317c24de2da101b | 2,846 | splity | Apache License 2.0 |
goblin-rpc/src/main/java/org/goblinframework/rpc/registry/RpcClientNode.kt | xiaohaiz | 206,246,434 | false | null | package org.goblinframework.rpc.registry
import org.goblinframework.core.util.HttpUtils
class RpcClientNode {
var clientId: String? = null
var clientName: String? = null
var clientHost: String? = null
var clientPid: Int? = null
fun toPath(): String {
val map = LinkedHashMap<String, Any>()
map["clientId"] = clientId!!
map["clientName"] = clientName!!
map["clientHost"] = clientHost!!
map["clientPid"] = clientPid!!
return HttpUtils.buildQueryString(map)
}
override fun toString(): String {
return toPath()
}
} | 0 | null | 6 | 9 | b1db234912ceb23bdd81ac66a3bf61933b717d0b | 559 | goblinframework | Apache License 2.0 |
app/src/main/java/com/udacity/asteroid/radar/main/MainViewModel.kt | RicardoBravoA | 312,422,452 | false | null | package com.udacity.asteroid.radar.main
import androidx.lifecycle.*
import com.udacity.asteroid.radar.data.util.DataDateUtil
import com.udacity.asteroid.radar.domain.model.AsteroidModel
import com.udacity.asteroid.radar.domain.model.PictureModel
import com.udacity.asteroid.radar.domain.usecase.AsteroidOfflineUseCase
import com.udacity.asteroid.radar.domain.usecase.AsteroidUseCase
import com.udacity.asteroid.radar.domain.usecase.PictureOfflineUseCase
import com.udacity.asteroid.radar.domain.usecase.PictureUseCase
import com.udacity.asteroid.radar.domain.util.ResultType
import com.udacity.asteroid.radar.mapper.MainMapper
import com.udacity.asteroid.radar.util.NetworkStatus
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
class MainViewModel(
private val asteroidUseCase: AsteroidUseCase,
private val pictureUseCase: PictureUseCase,
private val pictureOfflineUseCase: PictureOfflineUseCase,
private val asteroidOfflineUseCase: AsteroidOfflineUseCase
) : ViewModel() {
private val _status = MutableLiveData<NetworkStatus>()
val status: LiveData<NetworkStatus>
get() = _status
private val _asteroidList = MutableLiveData<List<MainItem>>()
val asteroidList: LiveData<List<MainItem>>
get() = _asteroidList
init {
getData(
DataDateUtil.currentDate(),
DataDateUtil.currentDate(DataDateUtil.DEFAULT_END_DATE_DAYS)
)
}
fun weekData() {
getData(
DataDateUtil.currentDate(),
DataDateUtil.currentDate(DataDateUtil.DEFAULT_END_DATE_DAYS)
)
}
fun today() {
getData(
DataDateUtil.currentDate(),
DataDateUtil.currentDate()
)
}
fun saved() {
getData(
DataDateUtil.currentDate(),
DataDateUtil.currentDate(DataDateUtil.DEFAULT_END_DATE_DAYS),
true
)
}
private fun getData(startDate: String, endDate: String, isSavedData: Boolean = false) {
viewModelScope.launch {
_status.value = NetworkStatus.LOADING
try {
coroutineScope {
var items = listOf<AsteroidModel>()
var picture: PictureModel? = null
if (isSavedData) {
when (val result = pictureOfflineUseCase.get()) {
is ResultType.Success -> {
picture = result.value
}
is ResultType.Error -> {
//Do nothing
}
}
} else {
when (val result = pictureUseCase.get()) {
is ResultType.Success -> {
picture = result.value
}
is ResultType.Error -> {
//Do nothing
}
}
}
if (isSavedData) {
when (val result = asteroidOfflineUseCase.list(startDate, endDate)) {
is ResultType.Success -> {
items = result.value
}
is ResultType.Error -> {
//Do nothing
}
}
} else {
when (val result = asteroidUseCase.list(startDate, endDate)) {
is ResultType.Success -> {
items = result.value
}
is ResultType.Error -> {
//Do nothing
}
}
}
_asteroidList.postValue(MainMapper.transform(items, picture))
_status.value = NetworkStatus.DONE
}
} catch (e: Exception) {
_asteroidList.value = arrayListOf()
_status.value = NetworkStatus.ERROR
}
}
}
} | 0 | Kotlin | 0 | 1 | db1cd5330dfb8991eb1fa913c93ddf6dfa2a81db | 4,269 | AsteroidRadar | Apache License 2.0 |
src/main/kotlin/com/alipay/sofa/koupleless/kouplelessidea/factory/FileDependencyTreeNodeFactory.kt | koupleless | 783,180,038 | false | {"Kotlin": 840464, "Java": 26198, "Shell": 3994} | package com.alipay.sofa.koupleless.kouplelessidea.factory
import com.alipay.sofa.koupleless.kouplelessidea.model.splitmodule.FileDependByTreeNode
import com.alipay.sofa.koupleless.kouplelessidea.model.splitmodule.FileDependOnTreeNode
import java.io.File
/**
* @description: TODO
* @author lipeng
* @date 2023/12/22 17:34
*/
object FileDependencyTreeNodeFactory {
fun createDependOnNode(path:String):FileDependOnTreeNode{
return FileDependOnTreeNode(File(path))
}
fun createDependByNode(path:String):FileDependByTreeNode{
return FileDependByTreeNode(File(path))
}
}
| 1 | Kotlin | 1 | 2 | 371a738491d60019d9c25a131fab484ad8064fc2 | 605 | koupleless-idea | Apache License 2.0 |
app/src/main/java/com/rhtyme/swipetoaction/ExtUtils.kt | Rhtyme | 237,761,897 | false | null | package com.rhtyme.swipetoaction
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
fun View.getStringExt(@StringRes id: Int): String {
return context.getString(id)
}
fun View.getDrawableExt(@DrawableRes id: Int): Drawable? {
return ContextCompat.getDrawable(context, id)
}
fun Context.getDrawableExt(@DrawableRes id: Int): Drawable? {
return ContextCompat.getDrawable(this, id)
}
@ColorInt fun Context.getColorExt(@ColorRes id: Int): Int {
return ContextCompat.getColor(this, id)
} | 0 | Kotlin | 0 | 0 | 67dc58ae2bb34bb0f7fb8747cd318116bedcca84 | 741 | SwipeToActionCallback | MIT License |
app/src/main/java/me/spica/weather/ui/main/MainPagerAdapter.kt | yangSpica27 | 457,724,719 | false | null | package me.jimi.weather.ui.main
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.viewpager2.adapter.FragmentStateAdapter
import me.jimi.weather.model.city.CityBean
import me.jimi.weather.ui.weather.WeatherFragment
class MainPagerAdapter(
fragmentActivity: FragmentActivity) :
FragmentStateAdapter(fragmentActivity) {
val diffUtil = AsyncListDiffer(
this,
object : DiffUtil.ItemCallback<CityBean>() {
override fun areItemsTheSame(oldItem: CityBean, newItem: CityBean): Boolean =
oldItem.cityName == newItem.cityName
override fun areContentsTheSame(oldItem: CityBean, newItem: CityBean): Boolean = false
}
)
override fun getItemCount(): Int = diffUtil.currentList.size
override fun createFragment(position: Int): Fragment {
val fragment = WeatherFragment()
fragment.arguments = Bundle().apply {
putParcelable("city", diffUtil.currentList[position])
}
return fragment
}
} | 0 | Kotlin | 0 | 6 | 163e679c1754bbd7a322d1643abf88bdb32db905 | 1,187 | SpicaWeather | MIT License |
generator/graphql-kotlin-schema-generator/src/test/kotlin/com/expediagroup/graphql/generator/test/integration/CustomUnionAnnotationTest.kt | ExpediaGroup | 148,706,161 | false | {"Kotlin": 2410561, "MDX": 720089, "HTML": 12165, "JavaScript": 10447, "CSS": 297, "Dockerfile": 147} | /*
* Copyright 2023 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.expediagroup.graphql.generator.test.integration
import com.expediagroup.graphql.generator.TopLevelObject
import com.expediagroup.graphql.generator.annotations.GraphQLDirective
import com.expediagroup.graphql.generator.annotations.GraphQLUnion
import com.expediagroup.graphql.generator.extensions.deepName
import com.expediagroup.graphql.generator.testSchemaConfig
import com.expediagroup.graphql.generator.toSchema
import graphql.schema.GraphQLUnionType
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertNotNull
class CustomUnionAnnotationTest {
@Test
fun `custom unions can be defined with a variety of return types`() {
val schema = toSchema(testSchemaConfig(), listOf(TopLevelObject(Query())))
assertNotNull(schema)
assertNotNull(schema.getType("One"))
assertNotNull(schema.getType("Two"))
assertNotNull(schema.getType("Three"))
assertNotNull(schema.getType("Four"))
assertNotNull(schema.getType("Even"))
assertNotNull(schema.getType("Odd"))
assertNotNull(schema.getType("Number"))
assertNotNull(schema.getType("Prime"))
assertEquals("Even!", schema.queryType.getFieldDefinition("even").type.deepName)
assertEquals("Odd!", schema.queryType.getFieldDefinition("odd").type.deepName)
assertEquals("Number!", schema.queryType.getFieldDefinition("number").type.deepName)
assertEquals("Number", schema.queryType.getFieldDefinition("nullableNumber").type.deepName)
assertEquals("[Number!]!", schema.queryType.getFieldDefinition("listNumbers").type.deepName)
assertEquals("[Number]", schema.queryType.getFieldDefinition("nullableListNumbers").type.deepName)
assertEquals("Prime!", schema.queryType.getFieldDefinition("prime").type.deepName)
assertEquals("Prime", schema.queryType.getFieldDefinition("nullablePrime").type.deepName)
assertEquals("[Prime!]!", schema.queryType.getFieldDefinition("listPrimes").type.deepName)
assertEquals("[Prime]", schema.queryType.getFieldDefinition("nullableListPrimes").type.deepName)
val unionWithDirective = schema.getType("Prime") as GraphQLUnionType
assertNotNull(unionWithDirective.appliedDirectives)
assertEquals(1, unionWithDirective.appliedDirectives.size)
assertEquals("TestDirective", unionWithDirective.appliedDirectives[0].name)
}
@Test
fun `verify exception is thrown when union returns different types`() {
assertFails {
toSchema(testSchemaConfig(), listOf(TopLevelObject(InvalidQuery())))
}
}
@Test
fun `verify exception is thrown when custom union return type is not Any`() {
assertFails {
toSchema(testSchemaConfig(), listOf(TopLevelObject(InvalidReturnTypeNumber())))
}
assertFails {
toSchema(testSchemaConfig(), listOf(TopLevelObject(InvalidReturnTypePrime())))
}
}
class One(val value: String)
class Two(val value: String)
class Three(val value: String)
class Four(val value: String)
class Query {
@GraphQLUnion(name = "Even", possibleTypes = [Two::class, Four::class])
fun even(first: Boolean): Any = if (first) Two("2") else Four("4")
@GraphQLUnion(name = "Odd", possibleTypes = [One::class, Three::class])
fun odd(first: Boolean): Any = if (first) One("1") else Three("3")
@GraphQLUnion(name = "Number", possibleTypes = [One::class, Two::class, Three::class, Four::class])
fun number(): Any = One("1")
@GraphQLUnion(name = "Number", possibleTypes = [One::class, Two::class, Three::class, Four::class])
fun nullableNumber(isNull: Boolean): Any? = if (isNull) null else One("1")
@GraphQLUnion(name = "Number", possibleTypes = [One::class, Two::class, Three::class, Four::class])
fun listNumbers(): List<Any> = listOf(One("1"), Two("2"))
@GraphQLUnion(name = "Number", possibleTypes = [One::class, Two::class, Three::class, Four::class])
fun nullableListNumbers(): List<Any?>? = null
@PrimeUnion
fun prime(first: Boolean): Any = if (first) Two("2") else Three("3")
@PrimeUnion
fun nullablePrime(isNull: Boolean): Any? = if (isNull) null else Two("2")
@PrimeUnion
fun listPrimes(): List<Any> = listOf(Two("2"), Three("3"))
@PrimeUnion
fun nullableListPrimes(): List<Any?>? = null
}
/**
* Each union here is valid, but using them together in the same schema means the union "Number"
* is defined twice with different definitions and should fail
*/
class InvalidQuery {
@GraphQLUnion(name = "Number", possibleTypes = [One::class, Two::class])
fun number1(): Any = One("1")
@GraphQLUnion(name = "Number", possibleTypes = [Three::class, Four::class])
fun number2(): Any = Three("1")
}
/**
* While it is valid to compile, library users should return Any for the custom
* union annotation
*/
class InvalidReturnTypeNumber {
@GraphQLUnion(name = "Number", possibleTypes = [One::class, Two::class])
fun number1(): One = One("one")
fun number2(): One = One("two")
}
/**
* While it is valid to compile, library users should return Any for the annotation
* with the meta union annotation
*/
class InvalidReturnTypePrime {
@PrimeUnion
fun prime(): Two = Two("two")
}
@GraphQLDirective(name = "TestDirective")
annotation class TestDirective
@TestDirective
@GraphQLUnion(name = "Prime", possibleTypes = [Two::class, Three::class])
annotation class PrimeUnion
}
| 68 | Kotlin | 345 | 1,739 | d3ad96077fc6d02471f996ef34c67066145acb15 | 6,370 | graphql-kotlin | Apache License 2.0 |
kool-core/src/jsMain/kotlin/de/fabmax/kool/pipeline/backend/webgpu/WgpuRenderPass.kt | fabmax | 81,503,047 | false | {"Kotlin": 5084015, "HTML": 1464, "JavaScript": 597} | package de.fabmax.kool.pipeline.backend.webgpu
import de.fabmax.kool.pipeline.FrameCopy
import de.fabmax.kool.pipeline.RenderPass
import de.fabmax.kool.pipeline.backend.stats.BackendStats
import de.fabmax.kool.util.BaseReleasable
import de.fabmax.kool.util.Time
abstract class WgpuRenderPass<T: RenderPass>(
val depthFormat: GPUTextureFormat?,
val numSamples: Int,
val backend: RenderBackendWebGpu
) : BaseReleasable() {
private val passEncoderState = RenderPassEncoderState(this)
protected val device: GPUDevice
get() = backend.device
abstract val colorTargetFormats: List<GPUTextureFormat>
protected fun render(renderPass: T, encoder: GPUCommandEncoder) {
val t = if (renderPass.isProfileTimes) Time.precisionTime else 0.0
for (mipLevel in 0 until renderPass.numRenderMipLevels) {
renderPass.setupMipLevel(mipLevel)
when (renderPass.viewRenderMode) {
RenderPass.ViewRenderMode.SINGLE_RENDER_PASS -> {
passEncoderState.setup(encoder, renderPass)
passEncoderState.begin(0, mipLevel)
for (viewIndex in renderPass.views.indices) {
renderView(viewIndex, mipLevel, passEncoderState)
}
passEncoderState.end()
}
RenderPass.ViewRenderMode.MULTI_RENDER_PASS -> {
for (viewIndex in renderPass.views.indices) {
passEncoderState.setup(encoder, renderPass)
passEncoderState.begin(viewIndex, mipLevel)
renderView(viewIndex, mipLevel, passEncoderState)
passEncoderState.end()
}
}
}
}
if (renderPass.mipMode == RenderPass.MipMode.Generate) {
generateMipLevels(encoder)
}
var anySingleShots = false
for (i in renderPass.frameCopies.indices) {
copy(renderPass.frameCopies[i], encoder)
anySingleShots = anySingleShots || renderPass.frameCopies[i].isSingleShot
}
if (anySingleShots) {
renderPass.frameCopies.removeAll { it.isSingleShot }
}
if (renderPass.isProfileTimes) {
renderPass.tDraw = Time.precisionTime - t
}
renderPass.afterDraw()
}
protected abstract fun generateMipLevels(encoder: GPUCommandEncoder)
protected abstract fun copy(frameCopy: FrameCopy, encoder: GPUCommandEncoder)
private fun renderView(viewIndex: Int, mipLevel: Int, passEncoderState: RenderPassEncoderState<*>) {
val view = passEncoderState.renderPass.views[viewIndex]
passEncoderState.renderPass.setupView(viewIndex)
val viewport = view.viewport
val x = (viewport.x shr mipLevel).toFloat()
val y = (viewport.y shr mipLevel).toFloat()
val w = (viewport.width shr mipLevel).toFloat()
val h = (viewport.height shr mipLevel).toFloat()
passEncoderState.passEncoder.setViewport(x, y, w, h, 0f, 1f)
// only do copy when last mip-level is rendered
val isLastMipLevel = mipLevel == view.renderPass.numRenderMipLevels - 1
var nextFrameCopyI = 0
var nextFrameCopy = if (isLastMipLevel) view.frameCopies.getOrNull(nextFrameCopyI++) else null
var anySingleShots = false
view.drawQueue.forEach { cmd ->
nextFrameCopy?.let { frameCopy ->
if (cmd.drawGroupId > frameCopy.drawGroupId) {
passEncoderState.end()
copy(frameCopy, passEncoderState.encoder)
passEncoderState.begin(viewIndex, mipLevel, forceLoad = true)
anySingleShots = anySingleShots || frameCopy.isSingleShot
nextFrameCopy = view.frameCopies.getOrNull(nextFrameCopyI++)
}
}
val isCmdValid = cmd.isActive && cmd.geometry.numIndices > 0
if (isCmdValid && backend.pipelineManager.bindDrawPipeline(cmd, passEncoderState)) {
val insts = cmd.mesh.instances
if (insts == null) {
passEncoderState.passEncoder.drawIndexed(cmd.geometry.numIndices)
BackendStats.addDrawCommands(1, cmd.geometry.numPrimitives)
} else if (insts.numInstances > 0) {
passEncoderState.passEncoder.drawIndexed(cmd.geometry.numIndices, insts.numInstances)
BackendStats.addDrawCommands(1, cmd.geometry.numPrimitives * insts.numInstances)
}
}
}
nextFrameCopy?.let {
passEncoderState.end()
copy(it, passEncoderState.encoder)
passEncoderState.begin(viewIndex, mipLevel, forceLoad = true)
anySingleShots = anySingleShots || it.isSingleShot
}
if (anySingleShots) {
view.frameCopies.removeAll { it.isSingleShot }
}
}
abstract fun getRenderAttachments(renderPass: T, viewIndex: Int, mipLevel: Int, forceLoad: Boolean): RenderAttachments
data class RenderAttachments(
val colorAttachments: Array<GPURenderPassColorAttachment>,
val depthAttachment: GPURenderPassDepthStencilAttachment?
)
}
| 12 | Kotlin | 14 | 241 | b32ddd844cecd3525560b051d36d72d1df5630d3 | 5,329 | kool | Apache License 2.0 |
shared/src/main/kotlin/dev/fastmc/graphics/shared/terrain/UploadTask.kt | FastMinecraft | 447,964,530 | false | {"Kotlin": 812223, "Java": 295977, "GLSL": 19607} | package dev.fastmc.graphics.shared.terrain
import dev.fastmc.common.collection.FastObjectArrayList
import dev.fastmc.graphics.shared.instancing.tileentity.info.ITileEntityInfo
import dev.fastmc.graphics.shared.opengl.glCopyNamedBufferSubData
internal class UploadTask(
private val parentTask: ChunkBuilderTask,
private val occlusionData: ChunkOcclusionData?,
private val translucentData: TranslucentData?,
private val modifyTranslucentData: Boolean,
private val updates: Array<LayerUpdate?>,
private val tileEntityList: FastObjectArrayList<ITileEntityInfo<*>>?,
private val instancingTileEntityList: FastObjectArrayList<ITileEntityInfo<*>>?,
private val globalTileEntityList: FastObjectArrayList<ITileEntityInfo<*>>?,
private val modifyTileEntity: Boolean,
) {
@JvmField
val renderChunk = parentTask.renderChunk
private var cleared = false
fun runClear(): Long {
var newLength = 0L
if (!parentTask.isCancelled) {
for (i in updates.indices) {
val update = updates[i]
if (update != null) {
newLength += update.clear(parentTask, i)
}
}
cleared = true
}
return newLength
}
fun runUpdate(): Boolean {
if (cleared) {
if (occlusionData != null) renderChunk.occlusionData = occlusionData
if (modifyTranslucentData) renderChunk.translucentData = translucentData
if (modifyTileEntity) {
renderChunk.tileEntityList = tileEntityList
renderChunk.instancingTileEntityList = instancingTileEntityList
renderChunk.globalTileEntityList = globalTileEntityList
}
for (i in updates.indices) {
updates[i]?.update(parentTask, i)
}
renderChunk.onUpdate()
}
parentTask.onUpload()
parentTask.onFinish()
return cleared
}
fun cancel() {
parentTask.onUpload()
parentTask.onFinish()
}
class Builder(
private val parentTask: ChunkBuilderTask,
) {
private var occlusionData: ChunkOcclusionData? = null
private var translucentData: TranslucentData? = null
private var modifyTranslucentData = false
private val updates = arrayOfNulls<LayerUpdate>(parentTask.renderer.layerCount)
private var tileEntityList: FastObjectArrayList<ITileEntityInfo<*>>? = null
private var instancingTileEntityList: FastObjectArrayList<ITileEntityInfo<*>>? = null
private var globalTileEntityList: FastObjectArrayList<ITileEntityInfo<*>>? = null
private var modifyTileEntity = false
fun occlusionData(data: ChunkOcclusionData?) {
occlusionData = data
}
fun translucentData(data: TranslucentData?) {
translucentData = data
modifyTranslucentData = true
}
fun updateLayer(index: Int, vertexBuffer: BufferContext?, indexBuffer: BufferContext?, faceData: FaceData?) {
if (indexBuffer != null) {
if (vertexBuffer != null) {
updates[index] = LayerUpdate.UpdateAll(vertexBuffer, indexBuffer, faceData)
} else {
updates[index] = LayerUpdate.UpdateIndex(indexBuffer, faceData)
}
} else {
updates[index] = LayerUpdate.Clear
}
}
fun updateTileEntity(
tileEntityList: FastObjectArrayList<ITileEntityInfo<*>>?,
instancingTileEntityList: FastObjectArrayList<ITileEntityInfo<*>>?,
globalTileEntityList: FastObjectArrayList<ITileEntityInfo<*>>?
) {
this.tileEntityList = tileEntityList
this.instancingTileEntityList = instancingTileEntityList
this.globalTileEntityList = globalTileEntityList
modifyTileEntity = true
}
internal fun build(): UploadTask {
return UploadTask(
parentTask,
occlusionData,
translucentData,
modifyTranslucentData,
updates,
tileEntityList,
instancingTileEntityList,
globalTileEntityList,
modifyTileEntity
)
}
}
internal sealed class LayerUpdate {
abstract fun clear(task: ChunkBuilderTask, index: Int): Long
abstract fun update(task: ChunkBuilderTask, index: Int)
object Clear : LayerUpdate() {
override fun clear(task: ChunkBuilderTask, index: Int): Long {
val layer = task.renderChunk.layers[index]
layer.vertexRegion = null
layer.indexRegion = null
return 0L
}
override fun update(task: ChunkBuilderTask, index: Int) {}
}
open class UpdateIndex(private val indexBuffer: BufferContext, private val faceData: FaceData?) :
LayerUpdate() {
override fun clear(task: ChunkBuilderTask, index: Int): Long {
val layer = task.renderChunk.layers[index]
val region = layer.indexRegion
val updateSize = indexBuffer.region.buffer.remaining()
return if (region != null) {
if (region.length != updateSize) {
layer.indexRegion = null
updateSize.toLong()
} else {
0L
}
} else {
updateSize.toLong()
}
}
override fun update(task: ChunkBuilderTask, index: Int) {
val updateSize = indexBuffer.region.buffer.remaining()
val layer = task.renderChunk.layers[index]
var region = layer.indexRegion
if (region == null) {
region = task.renderChunk.renderRegion.indexBufferPool.allocate(updateSize)
layer.indexRegion = region
} else {
region.invalidate()
}
glCopyNamedBufferSubData(
indexBuffer.region.vboID,
region.bufferObjectID,
indexBuffer.region.offset.toLong(),
region.offset.toLong(),
updateSize.toLong()
)
if (faceData != null) {
layer.faceData = faceData
}
indexBuffer.release(task)
}
}
class UpdateAll(private val vertexBuffer: BufferContext, indexBuffer: BufferContext, faceData: FaceData?) :
UpdateIndex(indexBuffer, faceData) {
override fun clear(task: ChunkBuilderTask, index: Int): Long {
val layer = task.renderChunk.layers[index]
val region = layer.vertexRegion
val updateSize = vertexBuffer.region.buffer.remaining()
val vertexUpdateSize = if (region != null) {
if (region.length != updateSize) {
layer.vertexRegion = null
updateSize.toLong()
} else {
0L
}
} else {
updateSize.toLong()
}
return (vertexUpdateSize shl 32) or super.clear(task, index)
}
override fun update(task: ChunkBuilderTask, index: Int) {
super.update(task, index)
val updateSize = vertexBuffer.region.buffer.remaining()
val layer = task.renderChunk.layers[index]
var region = layer.vertexRegion
if (region == null) {
region = task.renderChunk.renderRegion.vertexBufferPool.allocate(updateSize)
layer.vertexRegion = region
} else {
region.invalidate()
}
glCopyNamedBufferSubData(
vertexBuffer.region.vboID,
region.bufferObjectID,
vertexBuffer.region.offset.toLong(),
region.offset.toLong(),
updateSize.toLong()
)
vertexBuffer.release(task)
}
}
}
} | 1 | Kotlin | 1 | 61 | 74eb9d6af0d4829caa8a6069f39bb3e0fa168538 | 8,481 | fastmc-graphics | MIT License |
app/src/main/java/com/cryptron/util/WalletDisplayUtils.kt | c-sports | 289,192,345 | false | {"Gradle": 3, "XML": 262, "Java Properties": 2, "Shell": 2, "Text": 16, "Ignore List": 2, "Batchfile": 2, "Markdown": 1, "YAML": 2, "INI": 1, "Proguard": 1, "Java": 162, "Kotlin": 272, "JSON": 6, "HTML": 2, "Protocol Buffer": 2, "Ruby": 1} | /**
* BreadWallet
*
* Created by Ahsan Butt <[email protected]> on 10/10/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.util
import android.content.Context
import com.breadwallet.legacy.wallet.configs.WalletUiConfiguration
import com.breadwallet.tools.util.TokenUtil
import java.math.BigDecimal
// TODO: Collecting wallet display methods from Wallet Managers here for now
// class organization (whether hierarchy or not) is TBD, once we figure out what's needed
class WalletDisplayUtils {
companion object {
const val MAX_DECIMAL_PLACES_FOR_UI = 5
private const val ETHER_WEI = "1000000000000000000"
private val ONE_ETH = BigDecimal(ETHER_WEI)
private const val SCALE_ETH = 8
fun getUIConfiguration(
currencyCode: CurrencyCode,
context: Context
): WalletUiConfiguration {
// validate color here or return delisted
return WalletUiConfiguration(
TokenUtil.getTokenStartColor(currencyCode, context),
TokenUtil.getTokenEndColor(currencyCode, context),
false,
MAX_DECIMAL_PLACES_FOR_UI
)
}
}
}
| 1 | null | 1 | 1 | 8a25940586c472b10d765f6805be502a0c477986 | 2,291 | cryptron_android | MIT License |
idea-plugin/src/main/kotlin/arrow/meta/ide/plugins/proofs/folding/codeFolding.kt | mattmoore | 217,621,376 | false | null | package arrow.meta.ide.plugins.proofs.folding
import arrow.meta.ide.IdeMetaPlugin
import arrow.meta.phases.Composite
import arrow.meta.phases.ExtensionPhase
val IdeMetaPlugin.codeFolding: ExtensionPhase
get() = Composite(
codeFoldingOnUnions,
codeFoldingOnTuples
// codeFoldingOnKinds, // temporary disabled to avoid confusion due to issues
// foldingCaretListener
)
| 1 | null | 1 | 1 | d97c914cdcd3075122f4398cee3dbb5cafa0142b | 389 | arrow-meta | Apache License 2.0 |
app/src/main/java/com/guiying712/demo/SplashActivity.kt | guiying712 | 466,683,536 | false | null | package com.pedrorau.flawlesspoetrade
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
}
} | 1 | null | 1 | 2 | fef88df211b898dcca1ce3f1e6a17f26cc9a1ae9 | 314 | KotlinRouter | Apache License 2.0 |
serialization/src/commonTest/kotlin/nl/adaptivity/xml/serialization/AClassWithPolymorhpicChild.kt | pdvrieze | 143,553,364 | false | {"Kotlin": 3481762} | /*
* Copyright (c) 2021.
*
* This file is part of xmlutil.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, 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 nl.adaptivity.xml.serialization
import kotlinx.serialization.Polymorphic
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.polymorphic
import kotlinx.serialization.modules.subclass
import nl.adaptivity.xmlutil.serialization.XmlPolyChildren
import nl.adaptivity.xmlutil.serialization.XmlSerialName
class AClassWithPolymorhpicChild : TestPolymorphicBase<AClassWithPolymorhpicChild.Container>(
Container("lbl", ChildA("data")),
Container.serializer(),
baseModule
) {
override val expectedXML: String
get() = "<Container label=\"lbl\"><childA valueA=\"data\"/></Container>"
override val expectedJson: String
get() = "{\"label\":\"lbl\",\"member\":{\"type\":\"nl.adaptivity.xml.serialization.AClassWithPolymorhpicChild.ChildA\",\"valueA\":\"data\"}}"
override val expectedNonAutoPolymorphicXML: String get() = "<Container label=\"lbl\"><member type=\".ChildA\"><value valueA=\"data\"/></member></Container>"
@Serializable
data class Container(val label: String, @Polymorphic val member: Base)
@Serializable
open class Base
@Serializable
@XmlSerialName("childA")
data class ChildA(val valueA: String) : Base()
@Serializable
@SerialName("childBNameFromAnnotation")
@XmlSerialName("childB")
data class ChildB(val a: Int, val b: Int, val c: Int, val valueB: String) : Base()
companion object {
private val baseModule = SerializersModule {
polymorphic(Base::class) {
subclass(ChildA::class)
subclass(ChildB::class)
}
}
}
}
| 35 | Kotlin | 31 | 378 | c4053519a8b6c90af9e1683a5fe0e9e2b2c0db79 | 2,528 | xmlutil | Apache License 2.0 |
appintro/src/main/java/com/hb/introduction/IntroductionLottieAnimationBaseFragment.kt | hb-sravan | 268,564,180 | false | {"Kotlin": 102272} | package com.hb.introduction
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.LayoutRes
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.hb.introduction.internal.LogHelper
import com.hb.introduction.internal.TypefaceContainer
internal const val ARG_LA_TITLE = "title"
internal const val ARG_LA_TITLE_TYPEFACE = "title_typeface"
internal const val ARG_LA_TITLE_TYPEFACE_RES = "title_typeface_res"
internal const val ARG_LA_DESC = "desc"
internal const val ARG_LA_DESC_TYPEFACE = "desc_typeface"
internal const val ARG_LA_DESC_TYPEFACE_RES = "desc_typeface_res"
internal const val ARG_LA_ANIMATION_URL = "la_animation_url"
internal const val ARG_LA_ANIMATION_RESOURCE = "la_animation_resource"
internal const val ARG_LA_BG_COLOR = "bg_color"
internal const val ARG_LA_TITLE_COLOR = "title_color"
internal const val ARG_LA_DESC_COLOR = "desc_color"
internal const val ARG_LA_BG_DRAWABLE = "bg_drawable"
abstract class IntroductionLottieAnimationBaseFragment : Fragment(), SlideSelectionListener,
SlideBackgroundColorHolder {
private val logTAG = LogHelper.makeLogTag(IntroductionLottieAnimationBaseFragment::class.java)
@get:LayoutRes
protected abstract val layoutId: Int
private var animationResource: Int = 0
private var bgDrawable: Int = 0
private var titleColor: Int = 0
private var descColor: Int = 0
final override var defaultBackgroundColor: Int = 0
private set
private var title: String? = null
private var description: String? = null
private var lottieAnimationUrl: String? = null
private var titleTypeface: TypefaceContainer? = null
private var descTypeface: TypefaceContainer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
val args = arguments
if (args != null && args.size() != 0) {
title = args.getString(ARG_LA_TITLE)
description = args.getString(ARG_LA_DESC)
lottieAnimationUrl = args.getString(ARG_LA_ANIMATION_URL)
animationResource = args.getInt(ARG_LA_ANIMATION_RESOURCE)
bgDrawable = args.getInt(ARG_LA_BG_DRAWABLE)
val argsTitleTypeface = args.getString(ARG_LA_TITLE_TYPEFACE)
val argsDescTypeface = args.getString(ARG_LA_DESC_TYPEFACE)
val argsTitleTypefaceRes = args.getInt(ARG_LA_TITLE_TYPEFACE_RES)
val argsDescTypefaceRes = args.getInt(ARG_LA_DESC_TYPEFACE_RES)
titleTypeface = TypefaceContainer(argsTitleTypeface, argsTitleTypefaceRes)
descTypeface = TypefaceContainer(argsDescTypeface, argsDescTypefaceRes)
defaultBackgroundColor = args.getInt(ARG_LA_BG_COLOR)
titleColor = args.getInt(ARG_LA_TITLE_COLOR, 0)
descColor = args.getInt(ARG_LA_DESC_COLOR, 0)
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (savedInstanceState != null) {
title = savedInstanceState.getString(ARG_LA_TITLE)
description = savedInstanceState.getString(ARG_LA_DESC)
lottieAnimationUrl = savedInstanceState.getString(ARG_LA_ANIMATION_URL)
animationResource = savedInstanceState.getInt(ARG_LA_ANIMATION_RESOURCE)
titleTypeface = TypefaceContainer(
savedInstanceState.getString(ARG_LA_TITLE_TYPEFACE),
savedInstanceState.getInt(ARG_LA_TITLE_TYPEFACE_RES, 0)
)
descTypeface = TypefaceContainer(
savedInstanceState.getString(ARG_LA_DESC_TYPEFACE),
savedInstanceState.getInt(ARG_LA_DESC_TYPEFACE_RES, 0)
)
defaultBackgroundColor = savedInstanceState.getInt(ARG_LA_BG_COLOR)
bgDrawable = savedInstanceState.getInt(ARG_LA_BG_DRAWABLE)
titleColor = savedInstanceState.getInt(ARG_LA_TITLE_COLOR)
descColor = savedInstanceState.getInt(ARG_LA_DESC_COLOR)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(layoutId, container, false)
val titleText = view.findViewById<TextView>(R.id.title)
val descriptionText = view.findViewById<TextView>(R.id.description)
val lottieAnimationView = view.findViewById<LottieAnimationView>(R.id.animation_view)
val mainLayout = view.findViewById<ConstraintLayout>(R.id.main)
titleText.text = title
descriptionText.text = description
if (titleColor != 0) {
titleText.setTextColor(titleColor)
}
if (descColor != 0) {
descriptionText.setTextColor(descColor)
}
titleTypeface?.applyTo(titleText)
descTypeface?.applyTo(descriptionText)
if (lottieAnimationUrl != null && !lottieAnimationUrl!!.isEmpty()) {
lottieAnimationView.setAnimationFromUrl(lottieAnimationUrl)
} else {
lottieAnimationView.setAnimation(animationResource)
}
lottieAnimationView.playAnimation()
lottieAnimationView.repeatCount = LottieDrawable.INFINITE
if (bgDrawable != 0) {
mainLayout?.setBackgroundResource(bgDrawable)
} else {
mainLayout?.setBackgroundColor(defaultBackgroundColor)
}
return view
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(ARG_LA_BG_DRAWABLE, bgDrawable)
outState.putString(ARG_LA_TITLE, title)
outState.putString(ARG_LA_DESC, description)
outState.putString(ARG_LA_ANIMATION_URL, lottieAnimationUrl)
outState.putInt(ARG_LA_ANIMATION_RESOURCE, animationResource)
outState.putInt(ARG_LA_BG_COLOR, defaultBackgroundColor)
outState.putInt(ARG_LA_TITLE_COLOR, titleColor)
outState.putInt(ARG_LA_DESC_COLOR, descColor)
if (titleTypeface != null) {
outState.putString(ARG_LA_TITLE_TYPEFACE, titleTypeface?.typeFaceUrl)
outState.putInt(ARG_LA_TITLE_TYPEFACE_RES, titleTypeface?.typeFaceResource ?: 0)
}
if (descTypeface != null) {
outState.putString(ARG_LA_DESC_TYPEFACE, descTypeface?.typeFaceUrl)
outState.putInt(ARG_LA_DESC_TYPEFACE_RES, descTypeface?.typeFaceResource ?: 0)
}
super.onSaveInstanceState(outState)
}
override fun onSlideDeselected() {
LogHelper.d(logTAG, "Slide $title has been deselected.")
}
override fun onSlideSelected() {
LogHelper.d(logTAG, "Slide $title has been selected.")
}
override fun setBackgroundColor(@ColorInt backgroundColor: Int) {
view?.findViewById<ConstraintLayout>(R.id.main)?.setBackgroundColor(backgroundColor)
}
}
| 0 | null | 0 | 0 | 81813b6e3fa8e286f5a8e6a857e268f4345aa4be | 7,227 | IntroductionWrapper | Apache License 2.0 |
compose-guard/core/src/main/kotlin/com/joetr/compose/guard/core/parser/ComposableReportParser.kt | j-roskopf | 800,960,208 | false | null | /**
* MIT License
*
* Copyright (c) 2024 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.joetr.compose.guard.core.parser
import com.joetr.compose.guard.core.exception.ParsingException
import com.joetr.compose.guard.core.mapper.ConditionMapper
import com.joetr.compose.guard.core.mapper.StabilityStatusMapper
import com.joetr.compose.guard.core.model.RawContent
import com.joetr.compose.guard.core.model.composables.ComposableDetail
import com.joetr.compose.guard.core.model.composables.ComposablesReport
/**
* Parses [ComposablesReport] from the [String] content.
*/
public object ComposableReportParser : Parser<String, ComposablesReport> {
private val REGEX_COMPOSABLE_FUNCTION = "(?:(.*))fun (\\w*)".toRegex()
/**
* Example matches:
*
* unstable testClass: TestDataClass? = @dynamic TestDataClass("default")
* unused stable nonDefaultParameter: Int
*
* Link with further explanation with this regex selected:
*
* https://regex101.com/r/gI9mqs/2
*/
private val REGEX_COMPOSABLE_PARAMETERS =
(
// 1st capture group, matches the optional unused at the beginning
"(unused )?" +
// 2nd capture group, matches the required stable or unstable
"(stable|unstable)" +
// 3rd capture group, matches name + type (including optional question mark on type)
"(.*:\\s\\w*\\??)" +
// 4th optional capture group, matches the equal sign in case of default parameter
"(\\s=\\s|)?" +
// 5th capture group, matches the optional @static or @dynamic on default properties
"(@static|@dynamic|)?" +
// captures remaining value
".*"
).toRegex()
/**
* Parses all composable functions
*/
override fun parse(content: String): ComposablesReport {
val errors = mutableListOf<ParsingException>()
val composables =
getComposableFunctions(content)
.mapNotNull { function ->
runCatching {
parseComposableDetail(function)
}.onFailure { cause ->
errors.add(ParsingException(function, cause))
}.getOrNull()
}
.toList()
return ComposablesReport(composables, errors.toList())
}
private fun getComposableFunctions(content: String): List<String> {
val lines = content.split("\n").filter { it.isNotBlank() }
val composableFunIndexes =
lines.mapIndexedNotNull { index, s ->
if (REGEX_COMPOSABLE_FUNCTION.containsMatchIn(s)) {
index
} else {
null
}
}
return composableFunIndexes.mapIndexed { index: Int, item: Int ->
lines.subList(item, composableFunIndexes.getOrElse(index + 1) { lines.size }).joinToString(separator = "\n")
}
}
/**
* Parses unit composable
*/
private fun parseComposableDetail(function: String): ComposableDetail {
val composableDetails = REGEX_COMPOSABLE_FUNCTION.find(function)?.groupValues!!
val functionDetail = composableDetails[0]
val functionName = composableDetails[2]
val isInline = functionDetail.contains("inline")
val isRestartable = functionDetail.contains("restartable")
val isSkippable = functionDetail.contains("skippable")
val params =
REGEX_COMPOSABLE_PARAMETERS.findAll(function).map { it.groupValues }.filter { it.isNotEmpty() }
.map {
ComposableDetail.Parameter(
raw = it[0],
unused = it[1].isNotEmpty(),
condition = ConditionMapper.from(it[2]),
details = it[3],
stabilityStatus = StabilityStatusMapper.from(it[5]),
)
}.toList()
return ComposableDetail(
functionName = functionName,
isRestartable = isRestartable,
isSkippable = isSkippable,
isInline = isInline,
params = params,
rawContent = RawContent(function),
)
}
}
| 1 | null | 2 | 80 | 44c8a547b98b600f39b21df3a2fefa781b676db6 | 5,391 | ComposeGuard | MIT License |
richtext/src/main/java/com/keykat/richtext/CustomRichTextScope.kt | betterafter | 818,123,669 | false | {"Kotlin": 15530} | package com.keykat.richtext
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.keykat.richtext.attributes.TextDecoration
import com.keykat.richtext.attributes.TextStyle
import com.keykat.richtext.attributes.sp
import com.keykat.richtext.resources.Pretendard
/// 2024.06.21 ์ด๊ฑฐ object๋ก ๋ง๋๋๊น rebuildํ ๋ items๊ฐ ์ด๊ธฐํ๊ฐ ์๋์ด์
/// rebuildํ ๋๋ง๋ค ์์ ฏ์ด ๋ณต์ฌ๋๋ ๋ฌธ์ ๊ฐ ์์ (items์ ์์ดํ
์ ๊ณ์ ๋ฃ์ผ๋๊น)
class RichTextScope(
val defaultTextSize: Float = 14F,
val defaultTextColor: Color = Color.Black,
val defaultFontFamily: FontFamily = Pretendard,
val defaultFontWeight: FontWeight = FontWeight.Normal,
) {
private val items = mutableListOf<RichTextInstance>()
@Composable
fun RichText(
text: String,
textStyle: TextStyle = TextStyle(
fontSize = defaultTextSize,
fontColor = defaultTextColor,
fontFamily = defaultFontFamily,
fontWeight = defaultFontWeight,
),
endOfLine: Boolean = false,
lineHeight: Dp = 0.dp,
decoration: TextDecoration = TextDecoration()
) {
val richText = RichTextInstance(
text = text,
textStyle = textStyle,
endOfLine = endOfLine,
lineHeight = lineHeight,
decoration = decoration
)
items.add(richText)
}
private class RichTextInstance(
val text: String = "",
val textStyle: TextStyle = TextStyle(),
val endOfLine: Boolean = false,
val lineHeight: Dp = 0.dp,
val decoration: TextDecoration = TextDecoration()
)
fun richTextContent(): @Composable () -> Unit {
return {
items.forEach {
val text = it.text + if (it.endOfLine) "\n" else ""
Box(
modifier = Modifier
.wrapContentSize()
// clip ๋ค์์ background๋ฅผ ์ ์ธํด์ค์ผ ์์์ด ์ ์ธ๋ ํ clip์ด ์ ์ฉ๋จ
.clip(
RoundedCornerShape(
it.decoration.borderRadius.topLeft,
it.decoration.borderRadius.topRight,
it.decoration.borderRadius.bottomLeft,
it.decoration.borderRadius.bottomRight
)
)
.background(color = it.decoration.background)
.padding(
it.decoration.padding.left.dp,
it.decoration.padding.top.dp,
it.decoration.padding.right.dp,
it.decoration.padding.bottom.dp,
)
) {
Text(
modifier = Modifier.wrapContentSize(),
text = text,
style = it.textStyle.style,
lineHeight = it.lineHeight.sp(),
)
}
}
}
}
fun isEndOfLine(index: Int): Boolean {
val item = items[index]
return item.endOfLine
}
} | 0 | Kotlin | 0 | 0 | 13955310671256891a74254cfc9ace8e544149d7 | 3,720 | RichText | Apache License 2.0 |
idscp2-core/src/main/kotlin/de/fhg/aisec/ids/idscp2/defaultdrivers/securechannel/tls13/TLSSessionVerificationHelper.kt | industrial-data-space | 343,733,469 | false | null | /*-
* ========================LICENSE_START=================================
* idscp2
* %%
* Copyright (C) 2021 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.idscp2.default_drivers.secure_channel.tlsv1_3
import org.slf4j.LoggerFactory
import java.net.InetAddress
import java.security.cert.CertificateExpiredException
import java.security.cert.CertificateNotYetValidException
import java.security.cert.CertificateParsingException
import java.security.cert.X509Certificate
import java.util.ArrayList
import java.util.Date
import java.util.regex.Pattern
import javax.net.ssl.SSLPeerUnverifiedException
/**
* A class for verifying an established TLS Session on application layer
* (application level security)
*
* @author <NAME> (<EMAIL>)
*/
object TLSSessionVerificationHelper {
private val LOG = LoggerFactory.getLogger(TLSSessionVerificationHelper::class.java)
private const val ipv4Pattern = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])"
private const val ipv6Pattern = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}"
/*
* Checks if the ssl session is valid and the remote host can be trusted
*
* Due to the fact, that hostname verification is not specified in the secure socket layer,
* we have to check if the connected hostname matches to the subject of the peer certificate to
* avoid Man-In-The-Middle Attacks. This is required for every raw tls!
*
* Further we check the peer certificate validity to avoid the case that some of the certificates
* in our local trust_store are not valid anymore and allow a peer connector to connect with an
* expired certificate
*
* Throws SSlPeerUnverifiedException if peer certificate is not secure for this peer
*/
@Throws(SSLPeerUnverifiedException::class)
@JvmOverloads
fun verifyTlsSession(
host: String,
port: Int,
peerCert: X509Certificate,
hostnameVerificationEnabled: Boolean,
peerIsServer: Boolean = true
) {
if (LOG.isTraceEnabled) {
LOG.trace("Connected to {}:{}", host, port)
}
try {
/*
* Hostname verification is always enabled per default but the user can disable it using an as
* danger marked function of the native tls configuration (e.g. for testing purposes)
*/
if (hostnameVerificationEnabled) {
/*
* According to RFC6125, hostname verification should be done against the certificate's
* subject alternative name's (SANs) DNSName field or the SANs IPAddress. In some legacy
* implementations, the check is done against the certificate's commonName, but this is
* deprecated for quite a while and is therefore not supported anymore in the IDSCP2 protocol.
*/
val sans = peerCert.subjectAlternativeNames
?: throw SSLPeerUnverifiedException(
"No Subject alternative names for hostname " +
"verification provided"
)
val acceptedDnsNames = ArrayList<String>()
val acceptedIpAddresses = ArrayList<String>()
for (subjectAltName in sans) {
if (subjectAltName.size != 2) {
continue
}
val value = subjectAltName[1]
when (subjectAltName[0] as Int?) {
2 -> if (value is String) {
acceptedDnsNames.add(value)
} else if (value is ByteArray) {
acceptedDnsNames.add(String(value))
}
7 -> if (value is String) {
acceptedIpAddresses.add(value)
} else if (value is ByteArray) {
acceptedIpAddresses.add(String(value))
}
else -> {
if (LOG.isTraceEnabled) {
LOG.trace("Unhandled SAN type \"{}\" with value \"{}\"", subjectAltName[0], value)
}
}
}
}
if (isIpAddress(host)) {
// First, check IP addresses directly given by type-7-SANs
if (!acceptedIpAddresses.contains(host)) {
// Check IP addresses using DNS resolving
// This check is *weak* and should be accompanied by DAT fingerprint checking later on
val resolvedIps = acceptedDnsNames.flatMap {
try {
InetAddress.getAllByName(it).toList()
} catch (e: Throwable) {
emptyList()
}
}.map { it.hostAddress }
if (LOG.isTraceEnabled) {
LOG.trace("Resolved IPs: {}", resolvedIps.toSet().joinToString())
}
if (!resolvedIps.contains(host)) {
throw SSLPeerUnverifiedException(
"Hostname verification failed. Peer certificate does " +
"not belong to peer host"
)
}
}
} else {
// Check hostname
val hostLabels = host.split(".")
var found = false
for (entry in acceptedDnsNames) {
if (checkHostname(entry.trimEnd('.').split("."), hostLabels)) {
found = true
break
}
}
if (!found) {
throw SSLPeerUnverifiedException(
"Hostname verification failed. Peer certificate does " +
"not belong to peer host"
)
}
}
} else {
if (peerIsServer) {
LOG.warn(
"DANGER: TLS server hostname verification of is disabled. " +
"This is strongly discouraged except for testing purposes!."
)
} else {
LOG.info(
"Client hostname verification is disabled. " +
"This may reduce connection security, please consider enabling it when applicable."
)
}
}
// check certificate validity for now and at least one day
val oneDay = Date()
oneDay.time = oneDay.time + 86400000
peerCert.checkValidity()
peerCert.checkValidity(oneDay)
} catch (e: CertificateParsingException) {
throw SSLPeerUnverifiedException("TLS Session Verification failed $e")
} catch (e: CertificateNotYetValidException) {
throw SSLPeerUnverifiedException("TLS Session Verification failed $e")
} catch (e: CertificateExpiredException) {
throw SSLPeerUnverifiedException("TLS Session Verification failed $e")
}
}
/*
* check if host is an IP Address
*/
private fun isIpAddress(host: String): Boolean {
val ip4 = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE).matcher(host)
if (ip4.matches()) {
return true
}
val ip6 = Pattern.compile(ipv6Pattern, Pattern.CASE_INSENSITIVE).matcher(host)
return ip6.matches()
}
/*
* match dNS Name
*/
private fun checkHostname(dnsNameLabels: List<String>, hostNameLabels: List<String>): Boolean {
/*
* support wildcard matching of DNS names as described in RFC6125 Section 6.4.3
*
* Rules:
* 1. The client SHOULD NOT attempt to match a presented identifier in which the wildcard
* character comprises a label other than the left-most label
* (e.g., do not match bar.*.example.net).
*
* 2. If the wildcard character is the only character of the left-most label in the
* presented identifier, the client SHOULD NOT compare against anything but the left-most
* label of the reference identifier (e.g., *.example.com would match foo.example.com but
* not bar.foo.example.com or example.com).
*
* 3. The client MAY match a presented identifier in which the wildcard character is not the
* only character of the label (e.g., baz*.example.net and *baz.example.net and
* b*z.example.net would be taken to match baz1.example.net and foobaz.example.net and
* buzz.example.net, respectively). However, the client SHOULD NOT attempt to match a
* presented identifier where the wildcard character is embedded within an A-label or
* U-label of an internationalized domain name.
*/
if (dnsNameLabels.size == hostNameLabels.size) { // include rule 2
// all labels without the first one must match completely (rule 1)
for (i in 1 until dnsNameLabels.size) {
if (dnsNameLabels[i] != hostNameLabels[i]) {
return false
}
}
// first label could include wildcard character '*' (rule 1+3)
return hostNameLabels[0].matches(Regex(dnsNameLabels[0].replace("*", ".*")))
}
return false
}
}
| 2 | null | 3 | 4 | aff0b11cafc4ad43e7afe0727924e594a9853e54 | 10,439 | idscp2-jvm | Apache License 2.0 |
src/nl/hannahsten/texifyidea/formatting/LatexBlock.kt | Hannah-Sten | 62,398,769 | false | {"Kotlin": 2697096, "TeX": 71181, "Lex": 31225, "HTML": 23552, "Python": 967, "Perl": 39} | package nl.hannahsten.texifyidea.formatting
import com.intellij.application.options.CodeStyle
import com.intellij.formatting.*
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.TokenType
import com.intellij.psi.formatter.common.AbstractBlock
import com.intellij.psi.util.prevLeaf
import nl.hannahsten.texifyidea.editor.typedhandlers.LatexEnterHandler
import nl.hannahsten.texifyidea.lang.commands.LatexCommand
import nl.hannahsten.texifyidea.psi.*
import nl.hannahsten.texifyidea.settings.codestyle.LatexCodeStyleSettings
import nl.hannahsten.texifyidea.util.parser.firstChildOfType
import nl.hannahsten.texifyidea.util.parser.firstParentOfType
import nl.hannahsten.texifyidea.util.magic.CommandMagic
import nl.hannahsten.texifyidea.util.magic.cmd
import java.lang.Integer.max
/**
* @author <NAME>
*
* @param sectionIndent Number of extra indents needed because of section indenting.
*/
class LatexBlock(
node: ASTNode,
wrap: Wrap?,
alignment: Alignment?,
private val spacingBuilder: TexSpacingBuilder,
private val wrappingStrategy: LatexWrappingStrategy,
val sectionIndent: Int = 0,
/** Extra section indent that's not real but is used in case blocks do not start on a new line, so that it is ignored for the enter handler. */
private val fakeSectionIndent: Int = 0,
) : AbstractBlock(node, wrap, alignment) {
override fun buildChildren(): List<Block> {
val blocks = mutableListOf<LatexBlock>()
var child = myNode.firstChildNode
// Only applicable for section indenting:
// Current sectioning level while walking through the file
// Uses levels of CommandMagic.labeledLevels
var sectionLevel = -2
// Extra indent to do because of sectioning
var extraSectionIndent = max(sectionIndent - 1, 0)
// If a block does not start on a new line the indent won't do anything and we need to do something else to get the text in the block indented
val blockToIndentDoesNotStartOnNewLine = myNode.psi is LatexNoMathContent && sectionIndent > 0 && myNode.psi.prevLeaf(false)?.text?.contains("\n") == false
// Sorry, it's magic
val newFakeSectionIndent = if (blockToIndentDoesNotStartOnNewLine) sectionIndent + 1 else max(fakeSectionIndent - 1, 0)
// (I think what it does is that it propagates the section indent to normal text words, and since it only does
// something for things that come right after a new line the next normal text word on a new line will actually
// be indented (and probably not so for other structures, but we have to choose a finite number >= 2 here))
// For section indenting only: add fake blocks at the end because we can only add one indent per block but we may need multiple if inside e.g. subsubsection
if (child == null && (sectionIndent > 0 || fakeSectionIndent > 0)) {
val block = LatexBlock(
myNode,
wrappingStrategy.getWrap(),
null,
spacingBuilder,
wrappingStrategy,
extraSectionIndent,
newFakeSectionIndent
)
blocks.add(block)
}
// Create child blocks
while (child != null) {
val isSectionCommand =
child.psi is LatexNoMathContent && child.psi.firstChildOfType(LatexCommands::class)?.name in CommandMagic.sectioningCommands.map { it.cmd }
var targetIndent = extraSectionIndent
if (isSectionCommand) {
updateSectionIndent(sectionLevel, extraSectionIndent, targetIndent, child).apply {
sectionLevel = first
extraSectionIndent = second
targetIndent = third
}
}
// Normal addition of blocks
if (child.elementType !== TokenType.WHITE_SPACE && child !is PsiWhiteSpace) {
val block = LatexBlock(
child,
wrappingStrategy.getWrap(),
null,
spacingBuilder,
wrappingStrategy,
targetIndent,
newFakeSectionIndent
)
blocks.add(block)
}
child = child.treeNext
}
return blocks
}
/**
* Update the current section indent based on the current child.
* Only applicable when indenting text in sections.
*
* @return sectionLevel, extraSectionIndent, targetIndent
*/
private fun updateSectionIndent(givenSectionLevel: Int, givenExtraSectionIndent: Int, givenTargetIndent: Int, child: ASTNode): Triple<Int, Int, Int> {
var extraSectionIndent = givenExtraSectionIndent
var sectionLevel = givenSectionLevel
var targetIndent = givenTargetIndent
// Set flag for next blocks until section end to get indent+1
// We need to do it this way because we cannot create blocks which span a section content: blocks
// need to correspond to only one psi element.
// Changing the parser to view section content as one element is problematic because then we need to hardcode the sectioning structure in the parser
val command = LatexCommand.lookup(child.psi.firstChildOfType(LatexCommands::class)?.name)?.firstOrNull()
val level = CommandMagic.labeledLevels[command]
if (level != null && level > sectionLevel) {
extraSectionIndent += 1
sectionLevel = level
}
else if (level != null && level < sectionLevel) {
// I think this will go wrong if you jump levels, e.g. subsubsection after chapter
// but that's bad style anyway
extraSectionIndent = max(targetIndent - (sectionLevel - level), 0)
// Suppose previous text is indented 2 times, and we are a one level higher section command,
// we need for this command itself an indent of 2, minus one for the level, minus one because the
// section command itself is indented one less than the text in the section
// (which will be indented with extraSectionIndent)
targetIndent = max(targetIndent - (sectionLevel - level) - 1, 0)
sectionLevel = level
}
else if (level != null) {
// We encounter a same level sectioning command, which should be indented one less
targetIndent -= 1
}
return Triple(sectionLevel, extraSectionIndent, targetIndent)
}
override fun getIndent(): Indent? {
val shouldIndentDocumentEnvironment = CodeStyle.getCustomSettings(node.psi.containingFile, LatexCodeStyleSettings::class.java).INDENT_DOCUMENT_ENVIRONMENT
val shouldIndentEnvironment = myNode.elementType === LatexTypes.ENVIRONMENT_CONTENT && (
(myNode.psi as LatexEnvironmentContent)
.firstParentOfType(LatexEnvironment::class)
?.firstChildOfType(LatexBeginCommand::class)
?.firstChildOfType(LatexParameterText::class)?.text != "document" || shouldIndentDocumentEnvironment
)
if (shouldIndentEnvironment || myNode.elementType === LatexTypes.PSEUDOCODE_BLOCK_CONTENT ||
// Fix for leading comments inside an environment, because somehow they are not placed inside environments.
// Note that this does not help to insert the indentation, but at least the indent is not removed
// when formatting.
(
myNode.elementType === LatexTypes.COMMENT_TOKEN &&
myNode.treeParent?.elementType === LatexTypes.ENVIRONMENT
)
) {
return Indent.getNormalIndent(true)
}
// Indentation of sections
val indentSections = CodeStyle.getCustomSettings(node.psi.containingFile, LatexCodeStyleSettings::class.java).INDENT_SECTIONS
if (indentSections) {
if (sectionIndent > 0 || fakeSectionIndent > 0) {
return Indent.getNormalIndent(false)
}
}
// Indentation in groups and parameters.
if (myNode.elementType === LatexTypes.REQUIRED_PARAM_CONTENT ||
myNode.elementType === LatexTypes.STRICT_KEY_VAL_PAIR ||
myNode.elementType === LatexTypes.OPTIONAL_KEY_VAL_PAIR ||
(
myNode.elementType !== LatexTypes.CLOSE_BRACE &&
myNode.treeParent?.elementType === LatexTypes.GROUP
) ||
(
myNode.elementType !== LatexTypes.CLOSE_BRACE &&
myNode.treeParent?.elementType === LatexTypes.PARAMETER_GROUP
)
) {
return Indent.getNormalIndent(false)
}
// Display math
return if ((myNode.elementType === LatexTypes.MATH_CONTENT || myNode.elementType === LatexTypes.COMMENT_TOKEN) &&
myNode.treeParent?.elementType === LatexTypes.DISPLAY_MATH
) {
Indent.getNormalIndent(true)
}
else Indent.getNoneIndent()
}
override fun getSpacing(child1: Block?, child2: Block): Spacing? {
return spacingBuilder.getSpacing(this, child1, child2)
}
override fun isLeaf(): Boolean {
return myNode.firstChildNode == null && sectionIndent <= 0
}
// Automatic indent when enter is pressed
override fun getChildAttributes(newChildIndex: Int): ChildAttributes {
return LatexEnterHandler.getChildAttributes(newChildIndex, node, subBlocks)
}
} | 99 | Kotlin | 87 | 891 | 986550410e2fea91d1e93abfc683db1c8527c9d9 | 9,639 | TeXiFy-IDEA | MIT License |
packages/expo-modules-core/android/src/androidTest/java/expo/modules/kotlin/jni/JavaScriptFunctionTest.kt | betomoedano | 462,599,485 | false | null | @file:OptIn(ExperimentalCoroutinesApi::class)
package expo.modules.kotlin.jni
import com.google.common.truth.Truth
import io.mockk.mockk
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Before
import org.junit.Test
class JavaScriptFunctionTest {
private lateinit var jsiInterop: JSIInteropModuleRegistry
@Before
fun before() {
jsiInterop = JSIInteropModuleRegistry(mockk()).apply {
installJSIForTests()
}
}
@Test
fun should_be_able_to_receive_function_instance() {
val jsValue = jsiInterop.evaluateScript("() => {}")
Truth.assertThat(jsValue.isFunction()).isTrue()
val jsFunction = jsValue.getFunction()
Truth.assertThat(jsFunction).isNotNull()
}
@Test
fun should_be_able_to_return_value() {
val function = jsiInterop.evaluateScript("() => { return 21 }").getFunction<Int>()
val result = function()
Truth.assertThat(result).isEqualTo(21)
}
@Test
fun should_be_able_to_accept_simple_data() {
val function = jsiInterop.evaluateScript("(a, b) => { return a + b }").getFunction<Int>()
val result = function(20, 50)
Truth.assertThat(result).isEqualTo(70)
}
@Test
fun should_be_able_to_accept_complex_data() {
val function = jsiInterop.evaluateScript("(object) => { return object.k1 }").getFunction<String>()
val result = function(mapOf("k1" to "expo"))
Truth.assertThat(result).isEqualTo("expo")
}
@Test
fun should_be_accepted_as_a_function_arg() = withJSIInterop(
inlineModule {
Name("TestModule")
Function("decorate") { jsFunction: JavaScriptFunction<String> ->
"${jsFunction()}${jsFunction()}"
}
}
) {
val result = evaluateScript("expo.modules.TestModule.decorate(() => 'foo')").getString()
Truth.assertThat(result).isEqualTo("foofoo")
}
}
| 647 | null | 4463 | 4 | 52d6405570a39a87149648d045d91098374f4423 | 1,815 | expo | MIT License |
xmlschema/src/commonMain/kotlin/io/github/pdvrieze/formats/xmlschema/regex/impl/sets/XRRangeSet.kt | pdvrieze | 143,553,364 | false | {"Kotlin": 3481762} | /*
* Copyright (c) 2023.
*
* This file is part of xmlutil.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.formats.xmlschema.regex.impl
/**
* Represents node accepting single character from the given char class.
*/
open internal class XRRangeSet(charClass: XRAbstractCharClass, val ignoreCase: Boolean = false) : XRLeafSet() {
val chars: XRAbstractCharClass = charClass.instance
override fun accepts(startIndex: Int, testString: CharSequence): Int {
if (ignoreCase) {
val char = testString[startIndex]
return if (chars.contains(char.uppercaseChar()) || chars.contains(char.lowercaseChar())) 1 else -1
} else {
return if (chars.contains(testString[startIndex])) 1 else -1
}
}
override val name: String
get() = "range:" + (if (chars.alt) "^ " else " ") + chars.toString()
override fun first(set: XRAbstractSet): Boolean {
@Suppress("DEPRECATION")
return when (set) {
is XRCharSet -> XRAbstractCharClass.intersects(chars, set.char.toInt())
is XRRangeSet -> XRAbstractCharClass.intersects(chars, set.chars)
is XRSupplementaryRangeSet -> XRAbstractCharClass.intersects(chars, set.chars)
else -> true
}
}
}
| 35 | Kotlin | 31 | 378 | c4053519a8b6c90af9e1683a5fe0e9e2b2c0db79 | 1,935 | xmlutil | Apache License 2.0 |
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/rawCompilerArguments.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleTooling.arguments
import org.jetbrains.kotlin.idea.projectModel.KotlinRawCompilerArgument
object KotlinRawEmptyCompilerArgument : KotlinRawCompilerArgument<Unit> {
override val data: Unit
get() = throw UnsupportedOperationException("Accessing to empty argument data is not allowed!")
}
data class KotlinRawRegularCompilerArgument(override val data: String) : KotlinRawCompilerArgument<String>
data class KotlinRawBooleanCompilerArgument(override val data: Boolean) : KotlinRawCompilerArgument<Boolean>
data class KotlinRawMultipleCompilerArgument(override val data: List<String>) : KotlinRawCompilerArgument<List<String>>
| 191 | null | 4372 | 13,319 | 4d19d247824d8005662f7bd0c03f88ae81d5364b | 837 | intellij-community | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DiracComb.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: DiracComb
*
* Full name: System`DiracComb
*
* DiracComb[x] represents the Dirac comb function ๏(x) giving a delta function at every integer point.
* DiracComb[x , x , โฆ] represents the multidimensional Dirac comb function ๏(x , x , โฆ).
* Usage: 1 2 1 2
*
* Options: None
*
* Listable
* NumericFunction
* Orderless
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/DiracComb
* Documentation: web: http://reference.wolfram.com/language/ref/DiracComb.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun diracComb(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("DiracComb", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,321 | mathemagika | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DiracComb.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: DiracComb
*
* Full name: System`DiracComb
*
* DiracComb[x] represents the Dirac comb function ๏(x) giving a delta function at every integer point.
* DiracComb[x , x , โฆ] represents the multidimensional Dirac comb function ๏(x , x , โฆ).
* Usage: 1 2 1 2
*
* Options: None
*
* Listable
* NumericFunction
* Orderless
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/DiracComb
* Documentation: web: http://reference.wolfram.com/language/ref/DiracComb.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun diracComb(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("DiracComb", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,321 | mathemagika | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/FilterHdrOutlined.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/FilterHdrOutlined")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val FilterHdrOutlined: SvgIconComponent
| 12 | Kotlin | 5 | 983 | a99345a0160a80a7a90bf1adfbfdc83a31a18dd6 | 216 | kotlin-wrappers | Apache License 2.0 |
kotlin-browser/src/main/kotlin/web/screen/ScreenOrientation.kt | stefanthaler | 440,580,782 | true | {"Kotlin": 8815376, "JavaScript": 528} | package web.screen
import kotlinx.js.Void
import web.events.Event
import web.events.EventTarget
import kotlin.js.Promise
sealed external class ScreenOrientation : EventTarget {
val angle: Double
var onchange: ((event: Event) -> Unit)?
val type: OrientationType
fun lock(orientation: OrientationLockType): Promise<Void>
fun unlock()
}
| 0 | Kotlin | 0 | 0 | fc27a2b5d98423c8db24f8a28d1c3a95dc682b0a | 356 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/shaf/composescanner/QRCodeAnalyzer.kt | shafaque | 835,458,264 | false | {"Kotlin": 11163} | package com.shaf.composescanner
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage
class QRCodeAnalyzer(private val onQRCodeScanned: (String) -> Unit) : ImageAnalysis.Analyzer {
private val scanner = BarcodeScanning.getClient()
@androidx.annotation.OptIn(ExperimentalGetImage::class)
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image
if (mediaImage != null) {
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
scanner.process(image).addOnSuccessListener { barcodes ->
for (barcode in barcodes) {
when (barcode.valueType) {
Barcode.TYPE_URL -> {
barcode.url?.url?.let { onQRCodeScanned(it) }
}
Barcode.TYPE_TEXT -> {
barcode.rawValue?.let { onQRCodeScanned(it) }
}
// Add more cases if needed
else -> {
barcode.rawValue?.let { onQRCodeScanned(it) }
}
}
}
}.addOnFailureListener {
// Handle failure
}.addOnCompleteListener {
imageProxy.close()
}
} else {
imageProxy.close()
}
}
} | 0 | Kotlin | 0 | 1 | 7ef90ec95032ca1ec983d4ef9ff4b959b7f7176f | 1,663 | ComposeScanner | Apache License 2.0 |
Web/src/Application.kt | cornerstone18aug | 158,751,027 | false | {"CSS": 213683, "FreeMarker": 37188, "Kotlin": 34498, "JavaScript": 13666, "HTML": 53} | package ca.myclassmate
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.http.*
import io.ktor.html.*
import kotlinx.html.*
import kotlinx.css.*
import freemarker.cache.*
import io.ktor.freemarker.*
import io.ktor.http.content.*
import io.ktor.locations.*
import io.ktor.sessions.*
import io.ktor.features.*
import io.ktor.gson.*
import io.ktor.util.pipeline.PipelineContext
import ca.myclassmate.controllers.*
import com.ryanharter.ktor.moshi.moshi
import com.ryanharter.ktor.moshi.*
import com.squareup.moshi.JsonClass
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
//fun main(args: Array<String>) {
// embeddedServer(
// Netty,
// watchPaths = listOf("/"),
// port = 8080,
// // GOOD!, it will work
// module = Application::mymodule,
// module = Application::mymodule2
// ).start(true)
//}
// Body extracted to a function acting as a module
fun Application.mymodule(testing: Boolean = false) {
var count: Int = 0;
routing {
get("/") {
count += 1
call.respondText("counter: ${count}")
}
}
}
fun Application.mymodule2() {
routing {
get("/2") {
call.respondText("Hello World 5 !!!")
}
}
}
//
//
//
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
//
//data class Response1(val status: String)
//
//
//@Suppress("unused") // Referenced in application.conf
//@kotlin.jvm.JvmOverloads
//fun Application.module(testing: Boolean = false) {
// install(FreeMarker) {
// templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
// }
//
// install(Locations) {
// }
//
// install(Sessions) {
// cookie<MySession>("MY_SESSION") {
// cookie.extensions["SameSite"] = "lax"
// }
// }
//
// install(Compression) {
// gzip {
// priority = 1.0
// }
// deflate {
// priority = 10.0
// minimumSize(1024) // condition
// }
// }
//
// install(CORS) {
// method(HttpMethod.Options)
// method(HttpMethod.Put)
// method(HttpMethod.Delete)
// method(HttpMethod.Patch)
// header(HttpHeaders.Authorization)
// header("MyCustomHeader")
// allowCredentials = true
// anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
// }
//
// install(PartialContent) {
// // Maximum number of ranges that will be accepted from a HTTP request.
// // If the HTTP request specifies more ranges, they will all be merged into a single range.
// maxRangeCount = 10
// }
//
// install(ContentNegotiation) {
//// moshi()
// gson {
// }
// }
//
// routing {
// get("/r1") {
// call.respond(Response1(status = "ok"))
// }
// get("/") {
// call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
// }
//
// suspend fun PipelineContext<Unit, ApplicationCall>.teste() {
// call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
//// return this
// }
// get("/any3") { Home.index(this) }
//
// get("/html-dsl") {
// call.respondHtml {
// body {
// h1 { +"HTML" }
// ul {
// for (n in 1..10) {
// li { +"$n" }
// }
// }
// }
// }
// }
//
// get("/styles.css") {
// call.respondCss {
// body {
// backgroundColor = Color.red
// }
// p {
// fontSize = 2.em
// }
// rule("p.myclass") {
// color = Color.blue
// }
// }
// }
//
// get("/html-freemarker") {
// call.respond(FreeMarkerContent("index.ftl",
// mapOf(
// "data" to IndexData(listOf(1, 2, 3)),
// "data2" to "Danilo"
// ),
// ""))
// }
//
// // Static feature. Try to access `/static/ktor_logo.svg`
// static("/static") {
// resources("static")
// }
//
// get<MyLocation> {
// call.respondText("Location: name=${it.name}, arg1=${it.arg1}, arg2=${it.arg2}")
// }
//
// // Register nested routes
// get<Type.Edit> {
// call.respondText("Inside $it")
// }
// get<Type.List> {
// call.respondText("Inside $it")
// }
//
// get("/session/increment") {
// val session = call.sessions.get<MySession>() ?: MySession()
// call.sessions.set(session.copy(count = session.count + 1))
// call.respondText("Counter is ${session.count}. Refresh to increment.")
// }
//
// install(StatusPages) {
// exception<Throwable> { e->
// call.respondText(e.localizedMessage, ContentType.Text.Plain, HttpStatusCode.InternalServerError)
// }
// exception<AuthenticationException> { cause ->
// call.respond(HttpStatusCode.Unauthorized)
// }
// exception<AuthorizationException> { cause ->
// call.respond(HttpStatusCode.Forbidden)
// }
//
// }
//
// get("/json/gson") {
// call.respond(mapOf("hello" to "world"))
// }
// }
//}
//
//data class IndexData(val items: List<Int>)
//
//@Location("/location/{name}")
//class MyLocation(val name: String, val arg1: Int = 42, val arg2: String = "default")
//
//@Location("/type/{name}")
//data class Type(val name: String) {
// @Location("/edit")
// data class Edit(val type: Type)
//
// @Location("/list/{page}")
// data class List(val type: Type, val page: Int)
//}
//
//data class MySession(val count: Int = 0)
//
//class AuthenticationException : RuntimeException()
//class AuthorizationException : RuntimeException()
//
//fun FlowOrMetaDataContent.styleCss(builder: CSSBuilder.() -> Unit) {
// style(type = ContentType.Text.CSS.toString()) {
// +CSSBuilder().apply(builder).toString()
// }
//}
//
//fun CommonAttributeGroupFacade.style(builder: CSSBuilder.() -> Unit) {
// this.style = CSSBuilder().apply(builder).toString().trim()
//}
//
//suspend inline fun ApplicationCall.respondCss(builder: CSSBuilder.() -> Unit) {
// this.respondText(CSSBuilder().apply(builder).toString(), ContentType.Text.CSS)
//}
//
| 0 | CSS | 0 | 0 | 6691d5240354623ca9859a4a76a3ee1e9bf47513 | 6,722 | MyClassMate | MIT License |
android/app/src/main/kotlin/com/v2ray/ang/ui/ScScannerActivity.kt | PsrkGrmez | 759,525,035 | false | null | package com.v2ray.ang.ui
import android.Manifest
import android.content.*
import com.tbruyelle.rxpermissions.RxPermissions
import com.v2ray.ang.R
import com.v2ray.ang.util.AngConfigManager
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.v2ray.ang.extension.toast
class ScScannerActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_none)
importQRcode()
}
fun importQRcode(): Boolean {
RxPermissions(this)
.request(Manifest.permission.CAMERA)
.subscribe {
if (it)
scanQRCode.launch(Intent(this, ScannerActivity::class.java))
else
toast(R.string.toast_permission_denied)
}
return true
}
private val scanQRCode = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
val count = AngConfigManager.importBatchConfig(it.data?.getStringExtra("SCAN_RESULT"), "", false)
if (count > 0) {
toast(R.string.toast_success)
} else {
toast(R.string.toast_failure)
}
startActivity(Intent(this, MainActivity::class.java))
}
finish()
}
}
| 2 | null | 7 | 85 | 1a6d3d8e6c6edcfd3be8f23bee339e1c83ab9346 | 1,447 | ChiselBox | MIT License |
compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/BranchingExpressionGenerator.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.psi2ir.generators
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.builders.buildStatement
import org.jetbrains.kotlin.ir.builders.irIfThenMaybeElse
import org.jetbrains.kotlin.ir.builders.primitiveOp1
import org.jetbrains.kotlin.ir.builders.whenComma
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.classifierOrNull
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffsetSkippingComments
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.psi2ir.intermediate.defaultLoad
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.utils.SmartList
class BranchingExpressionGenerator(statementGenerator: StatementGenerator) : StatementGeneratorExtension(statementGenerator) {
fun generateIfExpression(expression: KtIfExpression): IrExpression {
val resultType = getInferredTypeWithImplicitCastsOrFail(expression).toIrType()
var ktLastIf: KtIfExpression = expression
val irBranches = SmartList<IrBranch>()
var irElseBranch: IrExpression? = null
whenBranches@ while (true) {
val irCondition = ktLastIf.condition!!.genExpr()
val irThenBranch = ktLastIf.then?.genExpr() ?: generateEmptyBlockForMissingBranch(ktLastIf)
irBranches.add(IrBranchImpl(irCondition, irThenBranch))
val ktElse = ktLastIf.`else`?.deparenthesize()
when (ktElse) {
null -> break@whenBranches
is KtIfExpression -> ktLastIf = ktElse
is KtExpression -> {
irElseBranch = ktElse.genExpr()
break@whenBranches
}
else -> throw AssertionError("Unexpected else expression: ${ktElse.text}")
}
}
return createIrWhen(expression, irBranches, irElseBranch, resultType)
}
private fun generateEmptyBlockForMissingBranch(ktLastIf: KtIfExpression) =
IrBlockImpl(ktLastIf.startOffset, ktLastIf.endOffset, context.irBuiltIns.nothingType, IrStatementOrigin.IF, listOf())
private fun createIrWhen(
ktIf: KtIfExpression,
irBranches: List<IrBranch>,
irElseResult: IrExpression?,
resultType: IrType
): IrWhen {
if (irBranches.size == 1) {
val irBranch0 = irBranches[0]
return buildStatement(ktIf.startOffsetSkippingComments, ktIf.endOffset) {
irIfThenMaybeElse(resultType, irBranch0.condition, irBranch0.result, irElseResult, IrStatementOrigin.IF)
}
}
val irWhen = IrWhenImpl(ktIf.startOffsetSkippingComments, ktIf.endOffset, resultType, IrStatementOrigin.IF)
irWhen.branches.addAll(irBranches)
irElseResult?.let {
irWhen.branches.add(elseBranch(it))
}
return irWhen
}
private fun elseBranch(result: IrExpression) =
IrElseBranchImpl(
IrConstImpl.boolean(result.startOffset, result.endOffset, context.irBuiltIns.booleanType, true),
result
)
fun generateWhenExpression(expression: KtWhenExpression): IrExpression {
val irSubject = generateWhenSubject(expression)
val inferredType = getInferredTypeWithImplicitCastsOrFail(expression)
// TODO relies on ControlFlowInformationProvider, get rid of it
val isUsedAsExpression = get(BindingContext.USED_AS_EXPRESSION, expression) ?: false
val resultType = when {
isUsedAsExpression -> inferredType.toIrType()
KotlinBuiltIns.isNothing(inferredType) -> inferredType.toIrType()
else -> context.irBuiltIns.unitType
}
val irWhen = IrWhenImpl(expression.startOffsetSkippingComments, expression.endOffset, resultType, IrStatementOrigin.WHEN)
for (ktEntry in expression.entries) {
if (ktEntry.isElse) {
val irElseResult = ktEntry.expression!!.genExpr()
irWhen.branches.add(elseBranch(irElseResult))
break
}
var irBranchCondition: IrExpression? = null
for (ktCondition in ktEntry.conditions) {
val irCondition =
if (irSubject != null)
generateWhenConditionWithSubject(ktCondition, irSubject)
else
generateWhenConditionNoSubject(ktCondition)
irBranchCondition = irBranchCondition?.let { context.whenComma(it, irCondition) } ?: irCondition
}
val irBranchResult = ktEntry.expression!!.genExpr()
irWhen.branches.add(IrBranchImpl(irBranchCondition!!, irBranchResult))
}
addElseBranchForExhaustiveWhenIfNeeded(irWhen, expression)
return generateWhenBody(expression, irSubject, irWhen)
}
private fun generateWhenSubject(expression: KtWhenExpression): IrVariable? {
val subjectVariable = expression.subjectVariable
val subjectExpression = expression.subjectExpression
return when {
subjectVariable != null -> statementGenerator.visitProperty(subjectVariable, null) as IrVariable
subjectExpression != null -> scope.createTemporaryVariable(subjectExpression.genExpr(), "subject")
else -> null
}
}
private fun addElseBranchForExhaustiveWhenIfNeeded(irWhen: IrWhen, whenExpression: KtWhenExpression) {
if (irWhen.branches.filterIsInstance<IrElseBranch>().isEmpty()) {
//TODO: check condition: seems it's safe to always generate exception
val isExhaustive = whenExpression.isExhaustiveWhen()
if (isExhaustive) {
val call = IrCallImpl(
UNDEFINED_OFFSET, UNDEFINED_OFFSET,
context.irBuiltIns.nothingType,
context.irBuiltIns.noWhenBranchMatchedExceptionSymbol
)
irWhen.branches.add(elseBranch(call))
}
}
}
private fun KtWhenExpression.isExhaustiveWhen(): Boolean =
elseExpression != null // TODO front-end should provide correct exhaustiveness information
|| true == get(BindingContext.EXHAUSTIVE_WHEN, this)
|| true == get(BindingContext.IMPLICIT_EXHAUSTIVE_WHEN, this)
private fun generateWhenBody(expression: KtWhenExpression, irSubject: IrVariable?, irWhen: IrWhen): IrExpression =
if (irSubject == null) {
if (irWhen.branches.isEmpty())
IrBlockImpl(expression.startOffsetSkippingComments, expression.endOffset, context.irBuiltIns.unitType, IrStatementOrigin.WHEN)
else
irWhen
} else {
if (irWhen.branches.isEmpty()) {
val irBlock = IrBlockImpl(expression.startOffsetSkippingComments, expression.endOffset, context.irBuiltIns.unitType, IrStatementOrigin.WHEN)
irBlock.statements.add(irSubject)
irBlock
} else {
val irBlock = IrBlockImpl(expression.startOffsetSkippingComments, expression.endOffset, irWhen.type, IrStatementOrigin.WHEN)
irBlock.statements.add(irSubject)
irBlock.statements.add(irWhen)
irBlock
}
}
private fun generateWhenConditionNoSubject(ktCondition: KtWhenCondition): IrExpression =
(ktCondition as KtWhenConditionWithExpression).expression!!.genExpr()
private fun generateWhenConditionWithSubject(ktCondition: KtWhenCondition, irSubject: IrVariable): IrExpression {
return when (ktCondition) {
is KtWhenConditionWithExpression ->
generateEqualsCondition(irSubject, ktCondition)
is KtWhenConditionInRange ->
generateInRangeCondition(irSubject, ktCondition)
is KtWhenConditionIsPattern ->
generateIsPatternCondition(irSubject, ktCondition)
else ->
throw AssertionError("Unexpected 'when' condition: ${ktCondition.text}")
}
}
private fun generateIsPatternCondition(irSubject: IrVariable, ktCondition: KtWhenConditionIsPattern): IrExpression {
val typeOperand = getOrFail(BindingContext.TYPE, ktCondition.typeReference)
val irTypeOperand = typeOperand.toIrType()
val typeSymbol = irTypeOperand.classifierOrNull ?: throw AssertionError("Not a classifier type: $typeOperand")
val irInstanceOf = IrTypeOperatorCallImpl(
ktCondition.startOffsetSkippingComments, ktCondition.endOffset,
context.irBuiltIns.booleanType,
IrTypeOperator.INSTANCEOF,
irTypeOperand, typeSymbol,
irSubject.defaultLoad()
)
return if (ktCondition.isNegated)
primitiveOp1(
ktCondition.startOffsetSkippingComments, ktCondition.endOffset,
context.irBuiltIns.booleanNotSymbol,
context.irBuiltIns.booleanType,
IrStatementOrigin.EXCL,
irInstanceOf
)
else
irInstanceOf
}
private fun generateInRangeCondition(irSubject: IrVariable, ktCondition: KtWhenConditionInRange): IrExpression {
val inCall = statementGenerator.pregenerateCall(getResolvedCall(ktCondition.operationReference)!!)
inCall.irValueArgumentsByIndex[0] = irSubject.defaultLoad()
val inOperator = getInfixOperator(ktCondition.operationReference.getReferencedNameElementType())
val irInCall = CallGenerator(statementGenerator).generateCall(ktCondition, inCall, inOperator)
return when (inOperator) {
IrStatementOrigin.IN ->
irInCall
IrStatementOrigin.NOT_IN ->
primitiveOp1(
ktCondition.startOffsetSkippingComments, ktCondition.endOffset,
context.irBuiltIns.booleanNotSymbol,
context.irBuiltIns.booleanType,
IrStatementOrigin.EXCL,
irInCall
)
else -> throw AssertionError("Expected 'in' or '!in', got $inOperator")
}
}
private fun generateEqualsCondition(irSubject: IrVariable, ktCondition: KtWhenConditionWithExpression): IrExpression {
val ktExpression = ktCondition.expression
val irExpression = ktExpression!!.genExpr()
return OperatorExpressionGenerator(statementGenerator).generateEquality(
ktCondition.startOffsetSkippingComments, ktCondition.endOffset, IrStatementOrigin.EQEQ,
irSubject.defaultLoad(), irExpression,
context.bindingContext[BindingContext.PRIMITIVE_NUMERIC_COMPARISON_INFO, ktExpression]
)
}
} | 184 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 11,721 | kotlin | Apache License 2.0 |
compiler/testData/ir/irText/classes/initVal.kt | JakeWharton | 99,388,807 | false | null | // FIR_IDENTICAL
class TestInitValFromParameter(val x: Int)
class TestInitValInClass {
val x = 0
}
class TestInitValInInitBlock {
val x: Int
init {
x = 0
}
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 185 | kotlin | Apache License 2.0 |
src/main/kotlin/dev/storozhenko/familybot/repos/ChatLogRepository.kt | AngryJKirk | 114,262,178 | false | null | package dev.storozhenko.familybot.feature.logging.repos
import com.github.benmanes.caffeine.cache.Caffeine
import dev.storozhenko.familybot.common.extensions.randomLong
import dev.storozhenko.familybot.core.models.telegram.User
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Component
import java.time.Duration
@Component
class ChatLogRepository(private val template: JdbcTemplate) {
private val namedJdbcTemplate = NamedParameterJdbcTemplate(template)
private val allByUserLoader = { (userId, chat): User ->
template.queryForList(
"SELECT message FROM chat_log WHERE user_id = ? AND chat_id = ?",
String::class.java,
userId,
chat.id
)
}
private val allByUserCache = Caffeine
.newBuilder()
.expireAfterWrite(Duration.ofDays(1))
.build(allByUserLoader)
private val commonPoolMaxId: Long = getMaxCommonMessageId()
fun add(user: User, message: String) {
template.update(
"INSERT INTO chat_log (chat_id, user_id, message) VALUES (?, ?, ?)",
user.chat.id,
user.id,
message
)
}
fun get(user: User): List<String> {
return allByUserCache[user] ?: allByUserLoader(user)
}
fun getRandomMessagesFromCommonPool(): List<String> {
if (commonPoolMaxId <= 1) {
return listOf("ั
ัะน ัะพัะธ ะณัะฑะพะน ััััะธ")
}
val ids = (1..10).map { randomLong(1, commonPoolMaxId) }.toSet()
val paramMap = mapOf("ids" to ids)
return namedJdbcTemplate.queryForList(
"SELECT message FROM chat_log WHERE id IN (:ids)",
paramMap,
String::class.java
)
}
private fun getMaxCommonMessageId(): Long {
return template.queryForList(
"SELECT MAX(id) FROM chat_log",
Long::class.java
).firstOrNull() ?: 0
}
}
| 0 | null | 5 | 97 | aff071c72503ffb9ad276fb9cc33d8408196795d | 2,030 | familybot | Apache License 2.0 |
app/src/main/java/com/vitordmoraes/thecompanion/ui/addChar/AddCharacterActivity.kt | vitordmoraes | 386,285,962 | false | null | package com.vitordmoraes.thecompanion.ui.addChar
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.vitordmoraes.thecompanion.model.Character
import com.vitordmoraes.thecompanion.App
import com.vitordmoraes.thecompanion.R
import com.vitordmoraes.thecompanion.databinding.AddCharacterBinding
class AddCharacterActivity :AppCompatActivity () {
private lateinit var binding: AddCharacterBinding
private val repository by lazy { App.repository }
companion object {
fun getIntent(context: Context):Intent =
Intent(context, AddCharacterActivity::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = AddCharacterBinding.inflate(layoutInflater)
setContentView(binding.root)
arrayFun()
createChar()
}
private fun arrayFun() {
val res : Resources = resources
val avatar = res.getStringArray(R.array.character_avatar)
val level = res.getStringArray(R.array.character_level)
binding.charClassCreator.adapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, avatar)
binding.charLevelCreator.adapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, level)
}
private fun createChar() {
binding.addCharBtn.setOnClickListener{newChar()}
}
private fun newChar() {
val newCharName = binding.charNameCreator.text.toString()
val newCharRace = binding.charRaceCreator.text.toString()
val newCharClass = binding.charClassCreator.selectedItem.toString()
val newCharLvl = binding.charLevelCreator.selectedItem.toString()
if (newCharName.isNotEmpty() &&
newCharRace.isNotEmpty() ){
repository.saveChar(Character(
newCharName, newCharRace,
newCharClass, newCharLvl
))
finish()
} else {
when {
newCharName.isEmpty() -> Toast.makeText(applicationContext, "Character name is missing!", Toast.LENGTH_SHORT).show()
newCharRace.isEmpty() -> Toast.makeText(applicationContext, "Character race is missing!", Toast.LENGTH_SHORT).show()
}
}
}
} | 0 | Kotlin | 0 | 0 | a2579c661f3fdd496bfdb2e267ad3fc2cbd4f52b | 2,494 | TheCompanion--Projeto | MIT License |
mps-legacy-sync-plugin/src/main/java/org/modelix/model/mpsplugin/plugin/AddProjectNode_Action.kt | modelix | 716,210,628 | false | {"Kotlin": 1330134, "Shell": 1104, "JavaScript": 497} | package org.modelix.model.mpsplugin.plugin
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import jetbrains.mps.ide.actions.MPSCommonDataKeys
import jetbrains.mps.workbench.action.BaseAction
import org.modelix.model.mpsplugin.CloudNodeTreeNodeCreationMethods
import org.modelix.model.mpsplugin.history.CloudNodeTreeNode
import org.modelix.model.mpsplugin.history.TreeNodeClassification
import javax.swing.Icon
import javax.swing.tree.TreeNode
/*Generated by MPS */
class AddModelNode_Action : BaseAction("Add Model", "", ICON) {
init {
setIsAlwaysVisible(false)
setExecuteOutsideCommand(true)
}
override fun isDumbAware(): Boolean {
return true
}
override fun isApplicable(event: AnActionEvent, _params: Map<String, Any>): Boolean {
return TreeNodeClassification.isModuleNode(event.getData(MPSCommonDataKeys.TREE_NODE))
}
public override fun doUpdate(event: AnActionEvent, _params: Map<String, Any>) {
setEnabledState(event.presentation, isApplicable(event, _params))
}
override fun collectActionData(event: AnActionEvent, _params: Map<String, Any>): Boolean {
if (!(super.collectActionData(event, _params))) {
return false
}
run({
val p: Project? = event.getData(CommonDataKeys.PROJECT)
if (p == null) {
return false
}
})
run({
val p: TreeNode? = event.getData(MPSCommonDataKeys.TREE_NODE)
if (p == null) {
return false
}
})
return true
}
public override fun doExecute(event: AnActionEvent, _params: Map<String, Any>) {
val nodeTreeNode: CloudNodeTreeNode? = event.getData(MPSCommonDataKeys.TREE_NODE) as CloudNodeTreeNode?
val name: String? = Messages.showInputDialog(event.getData(CommonDataKeys.PROJECT), "Name", "Add Model", null)
if ((name == null || name.length == 0)) {
return
}
CloudNodeTreeNodeCreationMethods.createModel(nodeTreeNode!!, name)
}
companion object {
private val ICON: Icon? = null
}
}
| 2 | Kotlin | 0 | 0 | d9bcc94cfe0bcbc02a0b61ffb88168d33b6502cd | 2,293 | modelix.mps-plugins | Apache License 2.0 |
pluto-plugins/plugins/rooms-database/lib/src/main/java/com/pluto/plugins/rooms/db/internal/DataModels.kt | androidPluto | 390,471,457 | false | {"Kotlin": 744352, "Shell": 646} | package com.pluto.plugins.rooms.db.internal
import android.os.Parcelable
import androidx.annotation.DrawableRes
import androidx.annotation.Keep
import androidx.room.RoomDatabase
import com.pluto.plugins.rooms.db.R
import com.pluto.utilities.list.ListItem
import kotlinx.parcelize.Parcelize
@Keep
internal data class DatabaseModel(
val name: String,
val dbClass: Class<out RoomDatabase>
) : ListItem()
@Keep
@Parcelize
internal data class TableModel(
val name: String,
val isSystemTable: Boolean
) : Parcelable, ListItem()
/**
* column properties (ordered)
* cid, name, type, notnull, dflt_value, pk
*/
@Keep
@Parcelize
internal data class ColumnModel(
val columnId: Int,
val name: String,
val type: String,
val isNotNull: Boolean,
val defaultValue: String?,
val isPrimaryKey: Boolean
) : Parcelable, ListItem() {
override fun equals(other: Any?): Boolean {
return other is ColumnModel && other.columnId == columnId
}
}
internal typealias RawTableContents = Pair<List<String>, List<List<String>>>
internal typealias ProcessedTableContents = Pair<List<ColumnModel>, List<List<String>>>
@Keep
@Parcelize
internal data class RowDetailsData(
val index: Int,
val table: String,
val columns: List<ColumnModel>,
val values: List<String>?
) : Parcelable
internal data class FilterModel(
val column: ColumnModel,
val value: String?,
val relation: FilterRelation = FilterRelation.Equals
) : ListItem(), Comparable<FilterModel> {
override fun compareTo(other: FilterModel): Int {
return column.name.compareTo(other.column.name)
}
override fun equals(other: Any?): Boolean {
return other is FilterModel && other.column == column
}
override fun isSame(other: Any): Boolean {
return other is FilterModel &&
other.column == column &&
other.value == value &&
other.relation.symbol == relation.symbol
}
}
internal sealed class RowAction {
class Click(val isInsert: Boolean) : RowAction()
object LongClick : RowAction()
object Delete : RowAction()
object Duplicate : RowAction()
}
internal sealed class FilterRelation(val symbol: String) : ListItem() {
object Equals : FilterRelation("=")
object NotEquals : FilterRelation("!=")
object Like : FilterRelation("%")
object Between : FilterRelation("BTW")
object In : FilterRelation("IN")
object LessThan : FilterRelation("<")
object LessThanOrEquals : FilterRelation("<=")
object GreaterThan : FilterRelation(">")
object GreaterThanOrEquals : FilterRelation(">=")
override fun equals(other: Any?): Boolean {
return other is FilterRelation && other.symbol == symbol
}
override fun hashCode(): Int {
return super.hashCode()
}
}
internal sealed class SortBy(val label: String, @DrawableRes val indicator: Int) {
class Asc(label: String = "ASC", indicator: Int = R.drawable.pluto_rooms___ic_sort_indicator_asc) : SortBy(label, indicator)
class Desc(label: String = "DESC", indicator: Int = R.drawable.pluto_rooms___ic_sort_indicator_desc) : SortBy(label, indicator)
}
| 23 | Kotlin | 64 | 657 | 5562cb7065bcbcf18493820e287d87c7726f630b | 3,170 | pluto | Apache License 2.0 |
app/src/main/java/ru/wkns37/worldskills/features/room/data/UsersRepository.kt | wkns37 | 521,082,178 | false | null | package ru.wkns37.worldskills.features.room.data
import ru.wkns37.worldskills.features.room.presentation.UserUi
interface UsersRepository {
suspend fun initialize()
suspend fun getUsers(): List<UserUi>
class Room(private val userDao: UserDao) : UsersRepository {
override suspend fun initialize() {
userDao.insert(User(1, "Bob", 22))
userDao.insert(User(2, "Alice", 18))
userDao.insert(User(3, "Charlie", 25))
userDao.insert(User(4, "Eve", 28))
}
override suspend fun getUsers(): List<UserUi> {
val users = userDao.getUsers()
return users.map { UserUi.Base(it.id, it.name, it.age) }
}
}
class Local : UsersRepository {
override suspend fun initialize() = Unit
override suspend fun getUsers() = listOf(
UserUi.Base(1, "Bob", 22),
UserUi.Base(2, "Alice", 18)
)
}
} | 0 | Kotlin | 0 | 0 | 70774e95e08941f78076f02b8dc512a0ec279d29 | 948 | android_world_skills | MIT License |
src/main/kotlin/app/myoun/leaguemc/command/Command.kt | myoun | 689,020,891 | false | {"Kotlin": 22780} | package app.myoun.leaguemc.command
import com.mojang.brigadier.builder.LiteralArgumentBuilder
import net.minecraft.server.command.ServerCommandSource
typealias ServerLiteralArgumentBuilder = LiteralArgumentBuilder<ServerCommandSource> | 0 | Kotlin | 0 | 0 | 43659c2a46b4daef87b3de23c7ffc1c74ec52092 | 236 | leaguemc | Creative Commons Zero v1.0 Universal |
fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentViewLifecycleTest.kt | FYI-Google | 258,765,297 | true | {"INI": 5, "Shell": 20, "Text": 3008, "Gradle": 278, "Markdown": 27, "Ignore List": 26, "XML": 3871, "Java": 4062, "HTML": 17, "Kotlin": 1738, "Python": 13, "JSON": 32, "Proguard": 23, "Gradle Kotlin DSL": 4, "Java Properties": 12, "Protocol Buffer": 1, "AIDL": 28, "ANTLR": 1, "SVG": 1, "YAML": 2, "JSON with Comments": 1, "desktop": 1, "JAR Manifest": 1, "Batchfile": 1} | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.test.FragmentTestActivity
import androidx.fragment.test.R
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.test.annotation.UiThreadTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Assert.fail
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoMoreInteractions
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(AndroidJUnit4::class)
@LargeTest
class FragmentViewLifecycleTest {
@get:Rule
val activityRule = ActivityTestRule(FragmentTestActivity::class.java)
@Test
@UiThreadTest
fun testFragmentViewLifecycle() {
val activity = activityRule.activity
val fm = activity.supportFragmentManager
val fragment = StrictViewFragment(R.layout.fragment_a)
fm.beginTransaction().add(R.id.content, fragment).commitNow()
assertThat(fragment.viewLifecycleOwner.lifecycle.currentState)
.isEqualTo(Lifecycle.State.RESUMED)
}
@Test
@UiThreadTest
fun testFragmentViewLifecycleNullView() {
val activity = activityRule.activity
val fm = activity.supportFragmentManager
val fragment = Fragment()
fm.beginTransaction().add(fragment, "fragment").commitNow()
try {
fragment.viewLifecycleOwner
fail("getViewLifecycleOwner should be unavailable if onCreateView returned null")
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat().contains("Can't access the Fragment View's LifecycleOwner when" +
" getView() is null i.e., before onCreateView() or after onDestroyView()")
}
}
@Test
@UiThreadTest
fun testObserveInOnCreateViewNullView() {
val activity = activityRule.activity
val fm = activity.supportFragmentManager
val fragment = ObserveInOnCreateViewFragment()
try {
fm.beginTransaction().add(fragment, "fragment").commitNow()
fail("Fragments accessing view lifecycle should fail if onCreateView returned null")
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat()
.contains("Called getViewLifecycleOwner() but onCreateView() returned null")
// We need to clean up the Fragment to avoid it still being around
// when the instrumentation test Activity pauses. Real apps would have
// just crashed right after onCreateView().
fm.beginTransaction().remove(fragment).commitNow()
}
}
@Test
fun testFragmentViewLifecycleRunOnCommit() {
val activity = activityRule.activity
val fm = activity.supportFragmentManager
val countDownLatch = CountDownLatch(1)
val fragment = StrictViewFragment(R.layout.fragment_a)
fm.beginTransaction().add(R.id.content, fragment).runOnCommit {
assertThat(fragment.viewLifecycleOwner.lifecycle.currentState)
.isEqualTo(Lifecycle.State.RESUMED)
countDownLatch.countDown()
}.commit()
countDownLatch.await(1, TimeUnit.SECONDS)
}
@Test
fun testFragmentViewLifecycleOwnerLiveData() {
val activity = activityRule.activity
val fm = activity.supportFragmentManager
val countDownLatch = CountDownLatch(2)
val fragment = StrictViewFragment(R.layout.fragment_a)
activityRule.runOnUiThread {
fragment.viewLifecycleOwnerLiveData.observe(activity,
Observer { lifecycleOwner ->
if (lifecycleOwner != null) {
assertWithMessage("Fragment View LifecycleOwner should be only be set" +
"after onCreateView()")
.that(fragment.onCreateViewCalled)
.isTrue()
countDownLatch.countDown()
} else {
assertWithMessage("Fragment View LifecycleOwner should be set to null" +
" after onDestroyView()")
.that(fragment.onDestroyViewCalled)
.isTrue()
countDownLatch.countDown()
}
})
fm.beginTransaction().add(R.id.content, fragment).commitNow()
// Now remove the Fragment to trigger the destruction of the view
fm.beginTransaction().remove(fragment).commitNow()
}
countDownLatch.await(1, TimeUnit.SECONDS)
}
@Test
fun testViewLifecycleInFragmentLifecycle() {
val activity = activityRule.activity
val fm = activity.supportFragmentManager
val fragment = StrictViewFragment(R.layout.fragment_a)
val lifecycleObserver = mock(LifecycleEventObserver::class.java)
lateinit var viewLifecycleOwner: LifecycleOwner
activityRule.runOnUiThread {
fragment.viewLifecycleOwnerLiveData.observe(activity,
Observer { lifecycleOwner ->
if (lifecycleOwner != null) {
viewLifecycleOwner = lifecycleOwner
lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
}
})
fragment.lifecycle.addObserver(lifecycleObserver)
fm.beginTransaction().add(R.id.content, fragment).commitNow()
// Now remove the Fragment to trigger the destruction of the view
fm.beginTransaction().remove(fragment).commitNow()
}
// The Fragment's lifecycle should change first, followed by the fragment's view lifecycle
verify(lifecycleObserver).onStateChanged(fragment, Lifecycle.Event.ON_CREATE)
verify(lifecycleObserver).onStateChanged(viewLifecycleOwner, Lifecycle.Event.ON_CREATE)
verify(lifecycleObserver).onStateChanged(fragment, Lifecycle.Event.ON_START)
verify(lifecycleObserver).onStateChanged(viewLifecycleOwner, Lifecycle.Event.ON_START)
verify(lifecycleObserver).onStateChanged(fragment, Lifecycle.Event.ON_RESUME)
verify(lifecycleObserver).onStateChanged(viewLifecycleOwner, Lifecycle.Event.ON_RESUME)
// Now the order reverses as things unwind
verify(lifecycleObserver).onStateChanged(viewLifecycleOwner, Lifecycle.Event.ON_PAUSE)
verify(lifecycleObserver).onStateChanged(fragment, Lifecycle.Event.ON_PAUSE)
verify(lifecycleObserver).onStateChanged(viewLifecycleOwner, Lifecycle.Event.ON_STOP)
verify(lifecycleObserver).onStateChanged(fragment, Lifecycle.Event.ON_STOP)
verify(lifecycleObserver).onStateChanged(viewLifecycleOwner, Lifecycle.Event.ON_DESTROY)
verify(lifecycleObserver).onStateChanged(fragment, Lifecycle.Event.ON_DESTROY)
verifyNoMoreInteractions(lifecycleObserver)
}
@Test
@UiThreadTest
fun testFragmentViewLifecycleDetach() {
val activity = activityRule.activity
val fm = activity.supportFragmentManager
val fragment = ObservingFragment()
fm.beginTransaction().add(R.id.content, fragment).commitNow()
val viewLifecycleOwner = fragment.viewLifecycleOwner
assertThat(viewLifecycleOwner.lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
assertWithMessage("LiveData should have active observers when RESUMED")
.that(fragment.liveData.hasActiveObservers()).isTrue()
fm.beginTransaction().detach(fragment).commitNow()
assertThat(viewLifecycleOwner.lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED)
assertWithMessage("LiveData should not have active observers after detach()")
.that(fragment.liveData.hasActiveObservers()).isFalse()
try {
fragment.viewLifecycleOwner
fail("getViewLifecycleOwner should be unavailable after onDestroyView")
} catch (expected: IllegalStateException) {
assertThat(expected)
.hasMessageThat().contains("Can't access the Fragment View's LifecycleOwner when" +
" getView() is null i.e., before onCreateView() or after onDestroyView()")
}
}
@Test
@UiThreadTest
fun testFragmentViewLifecycleReattach() {
val activity = activityRule.activity
val fm = activity.supportFragmentManager
val fragment = ObservingFragment()
fm.beginTransaction().add(R.id.content, fragment).commitNow()
val viewLifecycleOwner = fragment.viewLifecycleOwner
assertThat(viewLifecycleOwner.lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
assertWithMessage("LiveData should have active observers when RESUMED")
.that(fragment.liveData.hasActiveObservers()).isTrue()
fm.beginTransaction().detach(fragment).commitNow()
// The existing view lifecycle should be destroyed
assertThat(viewLifecycleOwner.lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED)
assertWithMessage("LiveData should not have active observers after detach()")
.that(fragment.liveData.hasActiveObservers()).isFalse()
fm.beginTransaction().attach(fragment).commitNow()
assertWithMessage("A new view LifecycleOwner should be returned after reattachment")
.that(fragment.viewLifecycleOwner).isNotEqualTo(viewLifecycleOwner)
assertThat(fragment.viewLifecycleOwner.lifecycle.currentState)
.isEqualTo(Lifecycle.State.RESUMED)
assertWithMessage("LiveData should have active observers when RESUMED")
.that(fragment.liveData.hasActiveObservers()).isTrue()
}
class ObserveInOnCreateViewFragment : Fragment() {
private val liveData = MutableLiveData<Boolean>()
private val onCreateViewObserver = Observer<Boolean> { }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
liveData.observe(viewLifecycleOwner, onCreateViewObserver)
assertWithMessage("LiveData should have observers after onCreateView observe")
.that(liveData.hasObservers()).isTrue()
// Return null - oops!
return null
}
}
class ObservingFragment : StrictViewFragment(R.layout.fragment_a) {
val liveData = MutableLiveData<Boolean>()
private val onCreateViewObserver = Observer<Boolean> { }
private val onViewCreatedObserver = Observer<Boolean> { }
private val onViewStateRestoredObserver = Observer<Boolean> { }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = super.onCreateView(inflater, container, savedInstanceState).also {
liveData.observe(viewLifecycleOwner, onCreateViewObserver)
assertWithMessage("LiveData should have observers after onCreateView observe")
.that(liveData.hasObservers()).isTrue()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
liveData.observe(viewLifecycleOwner, onViewCreatedObserver)
assertWithMessage("LiveData should have observers after onViewCreated observe")
.that(liveData.hasObservers()).isTrue()
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
liveData.observe(viewLifecycleOwner, onViewStateRestoredObserver)
assertWithMessage("LiveData should have observers after onViewStateRestored observe")
.that(liveData.hasObservers()).isTrue()
}
}
}
| 8 | null | 0 | 6 | b9cd83371e928380610719dfbf97c87c58e80916 | 13,149 | platform_frameworks_support | Apache License 2.0 |
libraries/easy-camera/src/main/kotlin/easy/camera/CameraPreviewImpl.kt | Kt-Kraft | 868,318,173 | false | {"Kotlin": 106999, "Shell": 3484} | package easy.camera
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.camera.core.ZoomState
import androidx.camera.view.PreviewView
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.compose.LocalLifecycleOwner
import easy.camera.model.CamSelector
import easy.camera.model.CaptureMode
import easy.camera.model.FlashMode
import easy.camera.model.ImageCaptureMode
import easy.camera.model.ImageTargetSize
import easy.camera.model.ImplementationMode
import easy.camera.model.ScaleType
import easy.camera.focus.FocusTap
import easy.camera.state.CameraState
import easy.camera.state.ImageAnalyzer
@Composable
internal fun CameraPreviewImpl(
modifier: Modifier,
cameraState: CameraState,
camSelector: CamSelector,
captureMode: CaptureMode,
imageCaptureMode: ImageCaptureMode,
imageCaptureTargetSize: ImageTargetSize?,
flashMode: FlashMode,
scaleType: ScaleType,
enableTorch: Boolean,
implementationMode: ImplementationMode,
imageAnalyzer: ImageAnalyzer?,
exposureCompensation: Int,
isImageAnalysisEnabled: Boolean,
isFocusOnTapEnabled: Boolean,
isPinchToZoomEnabled: Boolean,
onZoomRatioChanged: (ZoomState) -> Unit,
onFocus: suspend (() -> Unit) -> Unit,
focusTapContent: @Composable () -> Unit,
content: @Composable () -> Unit,
) {
val lifecycleOwner = LocalLifecycleOwner.current
val isCameraInitialized by rememberUpdatedState(cameraState.isInitialized)
var tapOffset by remember { mutableStateOf(Offset.Zero) }
val cameraZoomState by cameraState.controller.zoomState.observeAsState()
LaunchedEffect(cameraZoomState) {
cameraZoomState?.let { onZoomRatioChanged(it) }
}
AndroidView(
modifier = modifier,
factory = { context ->
PreviewView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
)
controller = cameraState.controller.apply {
bindToLifecycle(lifecycleOwner)
}
previewStreamState.observe(lifecycleOwner) {
cameraState.isStreaming = it == PreviewView.StreamState.STREAMING
}
setOnTouchListener { view, event ->
GestureDetector(
context,
object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapConfirmed(event: MotionEvent): Boolean {
tapOffset = Offset(event.x, event.y)
view.performClick()
return true
}
},
).onTouchEvent(event)
onTouchEvent(event)
}
}
},
update = { preview ->
if (isCameraInitialized) {
with(preview) {
this.scaleType = scaleType.type
this.implementationMode = implementationMode.value
cameraState.update(
camSelector = camSelector,
captureMode = captureMode,
imageCaptureTargetSize = imageCaptureTargetSize,
scaleType = scaleType,
isImageAnalysisEnabled = isImageAnalysisEnabled,
imageAnalyzer = imageAnalyzer,
implementationMode = implementationMode,
isFocusOnTapEnabled = isFocusOnTapEnabled,
flashMode = flashMode,
enableTorch = enableTorch,
imageCaptureMode = imageCaptureMode,
meteringPoint = meteringPointFactory.createPoint(x, y),
exposureCompensation = exposureCompensation,
)
}
}
},
)
FocusTap(
offset = tapOffset,
onFocus = { onFocus { tapOffset = Offset.Zero } },
) { focusTapContent() }
content()
}
| 0 | Kotlin | 0 | 0 | 153bbc744f244b02001ae244924a6ef061bb2467 | 4,157 | easy-android | MIT License |
apps/mobile/src/test/kotlin/dev/marlonlom/cappajv/core/database/FakeLocalDataSource.kt | marlonlom | 766,685,767 | false | {"Kotlin": 238268} | /*
* Copyright 2024 Marlonlom
* SPDX-License-Identifier: Apache-2.0
*/
package dev.marlonlom.apps.cappajv.core.database
import dev.marlonlom.apps.cappajv.core.catalog_source.CatalogDataService
import dev.marlonlom.apps.cappajv.core.catalog_source.successOr
import dev.marlonlom.apps.cappajv.core.database.datasource.LocalDataSource
import dev.marlonlom.apps.cappajv.core.database.entities.CatalogFavoriteItem
import dev.marlonlom.apps.cappajv.core.database.entities.CatalogItem
import dev.marlonlom.apps.cappajv.core.database.entities.CatalogItemTuple
import dev.marlonlom.apps.cappajv.core.database.entities.CatalogPunctuation
import dev.marlonlom.apps.cappajv.ui.util.slug
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import dev.marlonlom.apps.cappajv.core.catalog_source.CatalogItem as RemoteCatalogItem
internal class FakeLocalDataSource(
private val remoteDataService: CatalogDataService,
private val localFavoriteItems: MutableList<CatalogFavoriteItem> = mutableListOf()
) : LocalDataSource {
override fun getAllProducts(): Flow<List<CatalogItemTuple>> {
val listResponse = remoteDataService.fetchData().successOr(emptyList())
return flowOf(listResponse.map {
CatalogItemTuple(
id = it.id,
title = it.title,
picture = it.picture,
category = "Category one",
samplePunctuation = "",
punctuationsCount = 0,
)
})
}
override fun findProduct(productId: Long): Flow<CatalogItem> {
val listResponse = remoteDataService.fetchData()
.successOr(emptyList())
.find { it.id == productId }
.let {
if (it != null) CatalogItem(
id = it.id,
title = it.title,
slug = it.title.slug,
titleNormalized = it.title.lowercase(),
picture = it.picture,
category = "Category one",
detail = "Lorem ipsum",
samplePunctuation = "",
punctuationsCount = 0,
) else NONE
}
return flowOf(listResponse)
}
override fun getPunctuations(productId: Long): Flow<List<CatalogPunctuation>> {
val listResponse: RemoteCatalogItem = remoteDataService.fetchData()
.successOr(emptyList())
.find { it.id == productId } ?: return flowOf(emptyList())
val units = listResponse.punctuations.mapIndexed { index, punctuation ->
CatalogPunctuation(
id = index.plus(1).toLong(),
catalogItemId = listResponse.id,
label = punctuation.label,
points = punctuation.pointsQty.toLong()
)
}
return flowOf(units)
}
override fun getFavorites(): Flow<List<CatalogFavoriteItem>> = flowOf(localFavoriteItems)
override fun searchProducts(searchText: String): Flow<List<CatalogItemTuple>> {
val listResponse = remoteDataService.fetchData()
.successOr(emptyList())
.map {
CatalogItem(
id = it.id,
title = it.title,
slug = it.title.slug,
titleNormalized = it.title.slug.replace("-", " "),
picture = it.picture,
category = "Category one",
detail = "Lorem ipsum",
samplePunctuation = "",
punctuationsCount = it.punctuations.size - 1,
)
}
val itemTuples: List<CatalogItemTuple> = listResponse.filter {
val queryingText = searchText.lowercase().replace("%", "").trim()
it.title.lowercase().contains(queryingText).or(
it.titleNormalized.lowercase().contains(queryingText)
)
}.map {
CatalogItemTuple(
id = it.id,
title = it.title,
picture = it.picture,
category = "Category one",
samplePunctuation = "",
punctuationsCount = it.punctuationsCount,
)
}
return flowOf(itemTuples)
}
override fun insertAllProducts(vararg products: CatalogItem) = Unit
override fun insertAllFavoriteProducts(vararg favoriteItems: CatalogFavoriteItem) {
localFavoriteItems.addAll(favoriteItems)
}
override fun insertAllPunctuations(vararg punctuations: CatalogPunctuation) = Unit
override fun deleteAllProducts() = Unit
override fun deleteAllFavorites() {
localFavoriteItems.clear()
}
override fun deleteFavorite(productId: Long) {
localFavoriteItems.removeIf { it.id == productId }
}
override fun deleteAllPunctuations() = Unit
companion object {
val NONE = CatalogItem(
id = -1,
title = "",
slug = "",
titleNormalized = "",
picture = "",
category = "",
detail = "",
samplePunctuation = "",
punctuationsCount = 0
)
}
}
| 4 | Kotlin | 0 | 0 | c4dc41a0dd68e90768e7d3fec9e9f0c6fdd5ff93 | 4,603 | cappajv | Apache License 2.0 |
shared/src/commonMain/kotlin/io/Paths.kt | sdercolin | 708,470,210 | false | null | package io
import util.Log
expect object Paths {
val appRoot: File
val contentRoot: File
}
val Paths.logsDirectory: File
get() = appRoot.resolve("logs")
val Paths.sessionsDirectory: File
get() = contentRoot.resolve("sessions")
val Paths.reclistsDirectory: File
get() = contentRoot.resolve("reclists")
val Paths.appRecordFile: File
get() = appRoot.resolve("record.json")
val Paths.appPreferenceFile: File
get() = appRoot.resolve("preference.json")
fun ensurePaths() {
listOf(Paths.appRoot, Paths.contentRoot).forEach {
Log.i("ensurePaths: ${it.absolutePath}")
if (!it.exists()) {
Log.i("not exists, creating...")
val created = it.mkdirs()
Log.i("created: $created")
}
}
}
private val splitters = charArrayOf('\\', '/')
val String.pathSections get() = trim(*splitters).split(*splitters)
val String.lastPathSection get() = pathSections.last()
| 0 | null | 0 | 3 | f52cc2b74109458f48b749cd08e966d500a03e21 | 946 | recstar | Apache License 2.0 |
compat/src/main/kotlin/dev/sanmer/hidden/compat/PackageInfoCompat.kt | SanmerApps | 720,492,308 | false | {"Kotlin": 190008, "Java": 9998, "AIDL": 2361} | package dev.sanmer.hidden.compat
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageInfoHidden
import dev.rikka.tools.refine.Refine
object PackageInfoCompat {
val PackageInfo.isOverlayPackage get() =
Refine.unsafeCast<PackageInfoHidden>(this)
.isOverlayPackage
val PackageInfo.isPreinstalled get() =
lastUpdateTime <= 1230768000000 // 2009-01-01 08:00:00 GMT+8
val PackageInfo.isSystemApp get() =
applicationInfo.flags and (ApplicationInfo.FLAG_SYSTEM or
ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
} | 0 | Kotlin | 2 | 99 | 2239a6bb7920b97cfa4f75ade1df2b68f634997d | 632 | PI | MIT License |
src/main/kotlin/io/realworld/app/utils/Cipher.kt | Rudge | 177,908,216 | false | null | package io.realworld.app.utils
import com.auth0.jwt.algorithms.Algorithm
object Cipher {
val algorithm = Algorithm.HMAC256("something-very-secret-here")
fun encrypt(data: String?): ByteArray =
algorithm.sign(data?.toByteArray())
}
| 4 | null | 42 | 98 | 60a2c4fdb2f04f47d1085a6c49f699a3d50fa949 | 250 | kotlin-ktor-realworld-example-app | MIT License |
uxmobile/src/main/java/sk/uxtweak/uxmobile/ui/ShakeDetector.kt | macro39 | 389,744,953 | false | null | package sk.uxtweak.uxmobile.ui
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import kotlin.math.sqrt
class ShakeDetector : SensorEventListener {
private var listener: OnShakeListener? = null
private var shakeTimestamp: Long = 0
private var shakeCount = 0
fun setOnShakeListener(listener: OnShakeListener?) {
this.listener = listener
}
interface OnShakeListener {
fun onShake(count: Int)
}
override fun onAccuracyChanged(
sensor: Sensor,
accuracy: Int
) {}
override fun onSensorChanged(event: SensorEvent) {
if (listener != null) {
val x = event.values[0]
val y = event.values[1]
val z = event.values[2]
val gX = x / SensorManager.GRAVITY_EARTH
val gY = y / SensorManager.GRAVITY_EARTH
val gZ = z / SensorManager.GRAVITY_EARTH
val gForce: Float =
sqrt(gX * gX + gY * gY + gZ * gZ)
if (gForce > SHAKE_THRESHOLD_GRAVITY) {
val now = System.currentTimeMillis()
if (shakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
return
}
if (shakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
shakeCount = 0
}
shakeTimestamp = now
shakeCount++
listener!!.onShake(shakeCount)
}
}
}
companion object {
private const val SHAKE_THRESHOLD_GRAVITY = 2.7f
private const val SHAKE_SLOP_TIME_MS = 500
private const val SHAKE_COUNT_RESET_TIME_MS = 3000
}
}
| 0 | Kotlin | 0 | 0 | 9dc1d26c95c42f739c7aa9610da815a01ea7f5d2 | 1,753 | UxMobile | Apache License 2.0 |
app/src/main/java/com/beeglobaladmin/meditationuiwithcompose/ui/theme/HomeScreen.kt | Ryuk-C | 435,865,085 | false | {"Kotlin": 18771} | package com.beeglobaladmin.meditationuiwithcompose.ui.theme
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.foundation.clickable
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.beeglobaladmin.meditationuiwithcompose.BottomContent
import com.beeglobaladmin.meditationuiwithcompose.Feature
import com.beeglobaladmin.meditationuiwithcompose.R
import com.beeglobaladmin.meditationuiwithcompose.standardQuadFromTo
@ExperimentalFoundationApi
@Composable
fun HomeScreen() {
Box(
modifier = Modifier
.background(DeepBlue)
.fillMaxSize()
) {
Column {
GreetingSection()
ChipSection(chips = listOf("Sweet Sleep", "Insomnia", "Depression"))
CurrentMeditation()
FeatureSection(
features = listOf(
Feature(
title = "Sleep meditation",
R.drawable.ic_headphone,
BlueViolet1,
BlueViolet2,
BlueViolet3
),
Feature(
title = "Tips for sleeping",
R.drawable.ic_videocam,
LightGreen1,
LightGreen2,
LightGreen3
),
Feature(
title = "Night island",
R.drawable.ic_headphone,
OrangeYellow1,
OrangeYellow2,
OrangeYellow3
),
Feature(
title = "Calming sounds",
R.drawable.ic_headphone,
Beige1,
Beige2,
Beige3
)
)
)
}
BottomMenu(items = listOf(
BottomContent("Home", R.drawable.ic_home),
BottomContent("Meditate", R.drawable.ic_bubble),
BottomContent("Sleep", R.drawable.ic_moon),
BottomContent("Music", R.drawable.ic_music),
BottomContent("Profile", R.drawable.ic_profile),
), modifier = Modifier.align(Alignment.BottomCenter))
}
}
@Composable
fun BottomMenu(
items: List<BottomContent>,
modifier: Modifier = Modifier,
activeHighlightColor: Color = ButtonBlue,
activeTextColor: Color = Color.White,
inactiveTextColor: Color = AquaBlue,
initialSelectedItemIndex: Int = 0
) {
var selectedItemIndex by remember {
mutableStateOf(initialSelectedItemIndex)
}
Row(
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.fillMaxWidth()
.background(DeepBlue)
.padding(15.dp)
) {
items.forEachIndexed { index, item ->
BottomMenuItem(
item = item,
isSelected = index == selectedItemIndex,
activeHighlightColor = activeHighlightColor,
activeTextColor = activeTextColor,
inactiveTextColor = inactiveTextColor
) {
selectedItemIndex = index
}
}
}
}
@Composable
fun BottomMenuItem(
item: BottomContent,
isSelected: Boolean = false,
activeHighlightColor: Color = ButtonBlue,
activeTextColor: Color = Color.White,
inactiveTextColor: Color = AquaBlue,
onItemClick: () -> Unit
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.clickable {
onItemClick()
}
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.clip(RoundedCornerShape(10.dp))
.background(if (isSelected) activeHighlightColor else Color.Transparent)
.padding(10.dp)
) {
Icon(
painter = painterResource(id = item.iconId),
contentDescription = item.title,
tint = if (isSelected) activeTextColor else inactiveTextColor,
modifier = Modifier.size(20.dp)
)
}
Text(
text = item.title,
color = if(isSelected) activeTextColor else inactiveTextColor
)
}
}
@Composable
fun GreetingSection(name: String = "Cuma!") {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(15.dp)
) {
Column(
verticalArrangement = Arrangement.Center
) {
Text(
text = "Good Morning, $name",
style = MaterialTheme.typography.h2,
)
Text(
text = "We wish You have a good day!",
style = MaterialTheme.typography.body1,
)
}
Icon(
painterResource(id = R.drawable.ic_search),
contentDescription = "Search",
tint = Color.White,
modifier = Modifier.size(24.dp)
)
}
}
@Composable
fun ChipSection(
chips: List<String>
) {
var selectedChipIndex by remember {
mutableStateOf(0)
}
LazyRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
items(chips.size) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(start = 15.dp, top = 15.dp, bottom = 15.dp)
.clickable {
selectedChipIndex = it
}
.clip(RoundedCornerShape(10.dp))
.background(
if (selectedChipIndex == it) ButtonBlue
else DarkerButtonBlue
)
.padding(15.dp)
) {
Text(text = chips[it], color = TextWhite)
}
}
}
}
@Composable
fun CurrentMeditation(
color: Color = LightRed
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.padding(15.dp)
.clip(RoundedCornerShape(10.dp))
.background(color)
.padding(horizontal = 15.dp, vertical = 20.dp)
.fillMaxWidth()
) {
Column(verticalArrangement = Arrangement.Center) {
Text(
text = "Daily Thought",
style = MaterialTheme.typography.h2,
)
Text(
text = "Meditation 3 - 10 Min",
style = MaterialTheme.typography.body1,
color = TextWhite
)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.background(ButtonBlue)
.padding(5.dp)
) {
Icon(
painter = painterResource(id = R.drawable.ic_play),
contentDescription = "Play",
tint = Color.White, modifier = Modifier.size(15.dp)
)
}
}
}
@ExperimentalFoundationApi
@Composable
fun FeatureSection(features: List<Feature>) {
Column(modifier = Modifier.fillMaxWidth()) {
Text(
text = "Featured",
style = MaterialTheme.typography.h1,
modifier = Modifier.padding(15.dp)
)
LazyVerticalGrid(
cells = GridCells.Fixed(2),
contentPadding = PaddingValues(start = 7.5.dp, end = 7.5.dp, bottom = 100.dp),
modifier = Modifier.fillMaxHeight()
)
{
items(features.size) {
FeaturesItem(feature = features[it])
}
}
}
}
@Composable
fun FeaturesItem(
feature: Feature
) {
BoxWithConstraints(
modifier = Modifier
.padding(7.5.dp)
.aspectRatio(1f)
.clip(RoundedCornerShape(10.dp))
.background(feature.darkColor)
) {
val width = constraints.maxWidth
val height = constraints.maxHeight
//Medium colored path
val mediumColoredPoint1 = Offset(0f, height * 0.3f)
val mediumColoredPoint2 = Offset(width * 0.1f, height * 0.35f)
val mediumColoredPoint3 = Offset(width * 0.1f, height * 0.05f)
val mediumColoredPoint4 = Offset(width * 0.4f, height * 0.7f)
val mediumColoredPoint5 = Offset(width * 1.4f, -height.toFloat())
val mediumColoredPath = Path().apply {
moveTo(mediumColoredPoint1.x, mediumColoredPoint1.y)
standardQuadFromTo(mediumColoredPoint1, mediumColoredPoint2)
standardQuadFromTo(mediumColoredPoint2, mediumColoredPoint3)
standardQuadFromTo(mediumColoredPoint3, mediumColoredPoint4)
standardQuadFromTo(mediumColoredPoint4, mediumColoredPoint5)
lineTo(width.toFloat() + 100f, height.toFloat() + 100f)
lineTo(-100f, height.toFloat() + 100f)
close()
}
//Light colored path
val lightPoint1 = Offset(0f, height * 0.35f)
val lightPoint2 = Offset(width * 0.1f, height * 0.4f)
val lightPoint3 = Offset(width * 0.3f, height * 0.35f)
val lightPoint4 = Offset(width * 0.65f, height * 0.7f)
val lightPoint5 = Offset(width * 1.4f, -height.toFloat() / 3f)
val lightColoredPath = Path().apply {
moveTo(lightPoint1.x, lightPoint2.y)
standardQuadFromTo(lightPoint1, lightPoint2)
standardQuadFromTo(lightPoint2, lightPoint3)
standardQuadFromTo(lightPoint3, lightPoint4)
standardQuadFromTo(lightPoint4, lightPoint5)
lineTo(width.toFloat() + 100f, height.toFloat() + 100f)
lineTo(-100f, height.toFloat() + 100f)
close()
}
Canvas(modifier = Modifier.fillMaxSize()) {
drawPath(
path = mediumColoredPath,
color = feature.mediumColor
)
drawPath(
path = lightColoredPath,
color = feature.lightColor
)
}
Box(
modifier = Modifier
.fillMaxSize()
.padding(15.dp)
) {
Text(
text = feature.title,
style = MaterialTheme.typography.h2,
lineHeight = 26.sp,
modifier = Modifier.align(Alignment.TopStart)
)
Icon(
painter = painterResource(id = feature.iconId), contentDescription = feature.title,
tint = Color.White,
modifier = Modifier.align(Alignment.BottomStart)
)
Text(text = "Start",
color = TextWhite,
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.clickable {
//Click
}
.align(Alignment.BottomEnd)
.clip(RoundedCornerShape(10.dp))
.background(ButtonBlue)
.padding(vertical = 6.dp, horizontal = 15.dp)
)
}
}
}
@ExperimentalFoundationApi
@Preview(showBackground = true)
@Composable
fun defaultScreen() {
HomeScreen()
} | 0 | Kotlin | 0 | 2 | 33d6e0ca3617fb4b882f3ac25aefad37192677fc | 12,877 | MeditationUIWithCompose | MIT License |
Wechat_chatroom_helper_android/app/src/main/kotlin/com/zdy/project/wechat_chatroom_helper/wechat/plugins/hook/adapter/MainItemViewHolder.kt | zhudongya123 | 96,015,224 | false | null | package com.zdy.project.wechat_chatroom_helper.wechat.plugins.hook.adapter
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
class MainItemViewHolder(val itemView: ViewGroup) {
val containerView: ViewGroup = itemView.getChildAt(0) as ViewGroup
val avatarContainer = containerView.getChildAt(0) as ViewGroup
val textContainer = containerView.getChildAt(1) as ViewGroup
val avatar = avatarContainer.getChildAt(0) as ImageView
val unReadCount = avatarContainer.getChildAt(1) as TextView
val unMuteReadIndicators = avatarContainer.getChildAt(2) as ImageView
val nickname = ((textContainer.getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0)
val time = (textContainer.getChildAt(0) as ViewGroup).getChildAt(1)
val sendStatus = ((textContainer.getChildAt(1) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0)
val content = ((textContainer.getChildAt(1) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(1)
val muteImage = ((textContainer.getChildAt(1) as ViewGroup).getChildAt(1) as ViewGroup).getChildAt(1)
companion object {
const val Conversation_Light_Text_Color = 0xFFF57C00.toInt()
const val Conversation_Red_Text_Color = 0xFFF44336.toInt()
}
} | 3 | Kotlin | 4 | 9 | 0519fbb3fd5bf98fd422f7de2334e19c1ad0ab21 | 1,290 | WechatChatRoomHelper | Apache License 2.0 |
src/test/kotlin/io/github/terickson87/ktorpostgresdemo/routing/NoteRoutingTest.kt | terickson87 | 775,215,903 | false | {"Kotlin": 38005, "Dockerfile": 469} | package io.github.terickson87.ktorpostgresdemo.routing
import io.github.terickson87.ktorpostgresdemo.adapter.accessor.NotesAccessor
import io.github.terickson87.ktorpostgresdemo.adapter.accessor.PagedData
import io.github.terickson87.ktorpostgresdemo.domain.AllNotesResponsePage
import io.github.terickson87.ktorpostgresdemo.domain.Note
import io.github.terickson87.ktorpostgresdemo.domain.NewNoteRequest
import io.github.terickson87.ktorpostgresdemo.domain.PageInfo
import io.github.terickson87.ktorpostgresdemo.util.RouteTestFuncs
import io.github.terickson87.ktorpostgresdemo.util.testGet
import io.github.terickson87.ktorpostgresdemo.util.testPostJsonBody
import io.github.terickson87.ktorpostgresdemo.domain.toNoteResponse
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.ktor.client.call.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.time.LocalDateTime
import java.time.ZoneId
import kotlin.test.assertEquals
class NoteRoutingTest : FunSpec({
val noteId = 17
val createdAt = LocalDateTime.parse("2024-02-25T10:15:00").atZone(ZoneId.of("America/Phoenix")).toInstant()
val updatedAt = LocalDateTime.parse("2024-02-25T10:26:30").atZone(ZoneId.of("America/Phoenix")).toInstant()
val note = Note(17, createdAt, updatedAt, "Test Body")
val noteResponse = note.toNoteResponse()
val notesAccessorMock: NotesAccessor = mockk()
test("/notes/all should return as expected") {
every { notesAccessorMock.getAllNotes(any(), any()) } returns PagedData(listOf(note), null)
val allNotesResponsePage = AllNotesResponsePage(listOf(noteResponse), PageInfo(1, null))
val pageInfo = PageInfo(1, 1L)
val pageInfoJson = Json.encodeToString(pageInfo)
RouteTestFuncs.testPostJsonBody("/notes/all", pageInfoJson, notesAccessorMock) {
runBlocking {
it.status.shouldBe(HttpStatusCode.OK)
it.body<AllNotesResponsePage>().shouldBe(allNotesResponsePage)
}
}
}
test("/notes/{id} should return as expected") {
every { notesAccessorMock.getNoteById(noteId)} returns note
RouteTestFuncs.testGet("/notes/$noteId", notesAccessorMock) {
runBlocking {
it.status.shouldBe(HttpStatusCode.OK)
assertEquals(noteResponse, it.body())
}
}
}
test("/notes/new should return as expected") {
val newBody = "Test New Body"
val newNoteRequest = NewNoteRequest(newBody)
val noteRequestJson = Json.encodeToString(newNoteRequest)
val newNote = note.copy(body = newBody)
val newNoteResponse = newNote.toNoteResponse()
every { notesAccessorMock.createNote(any()) } returns newNote
RouteTestFuncs.testPostJsonBody("/notes/new", noteRequestJson, notesAccessorMock) {
runBlocking {
it.status.shouldBe(HttpStatusCode.OK)
assertEquals(newNoteResponse, it.body())
}
}
}
test("/notes/update should return as expected") {
val updateBody = "Test Updated Body"
val newNoteRequest = NewNoteRequest(updateBody)
val noteRequestJson = Json.encodeToString(newNoteRequest)
val updateNote = note.copy(body = updateBody)
val updateNoteResponse = updateNote.toNoteResponse()
every { notesAccessorMock.updateNoteById(noteId, any()) } returns updateNote
RouteTestFuncs.testPostJsonBody("/notes/update/$noteId", noteRequestJson, notesAccessorMock) {
runBlocking {
it.status.shouldBe(HttpStatusCode.OK)
assertEquals(updateNoteResponse, it.body())
}
}
}
test("/notes/delete should return as expected") {
every { notesAccessorMock.deleteNoteById(noteId) } returns true
RouteTestFuncs.testGet("/notes/delete/$noteId", notesAccessorMock) {
runBlocking {
it.status.shouldBe(HttpStatusCode.OK)
assertEquals("Note ID: '${noteId}' was deleted successfully.", it.bodyAsText())
}
}
}
}) | 0 | Kotlin | 0 | 0 | aad779bbdbec70909db728689367f0b547b6682c | 4,303 | fullstack-ktor-react-postgres-docker-demo-app | MIT License |
features/languages/src/test/kotlin/app/ss/languages/LanguagesViewModelTest.kt | Adventech | 65,243,816 | false | null | /*
* Copyright (c) 2022. Adventech <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.languages
import app.cash.turbine.test
import app.ss.languages.state.LanguageModel
import app.ss.languages.state.LanguagesState
import app.ss.lessons.data.repository.quarterly.QuarterliesRepository
import app.ss.models.Language
import com.cryart.sabbathschool.core.response.Resource
import com.cryart.sabbathschool.test.coroutines.MainDispatcherRule
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import ss.prefs.api.SSPrefs
import ss.workers.api.WorkScheduler
class LanguagesViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private val mockRepository: QuarterliesRepository = mockk()
private val mockSSPrefs: SSPrefs = mockk()
private val mockWorkScheduler: WorkScheduler = mockk()
private val languagesFlow = MutableSharedFlow<Resource<List<Language>>>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
private lateinit var viewModel: LanguagesViewModel
@Before
fun setup() {
every { mockSSPrefs.getLanguageCode() }.returns("en")
every { mockRepository.getLanguages(null) }.returns(languagesFlow)
viewModel = LanguagesViewModel(
repository = mockRepository,
ssPrefs = mockSSPrefs,
workScheduler = mockWorkScheduler
)
}
@Test
fun `should emit models with properly formatted native language name`() = runTest {
viewModel.uiState.test {
awaitItem() shouldBeEqualTo LanguagesState()
languagesFlow.emit(
Resource.success(
listOf(
Language("en", "English", "English"),
Language("es", "Spanish", "Espaรฑol"),
Language("fr", "French", "Franรงais")
)
)
)
awaitItem().listState.models shouldBeEqualTo listOf(
LanguageModel("en", "English", "English", true),
LanguageModel("es", "Spanish", "Espaรฑol", false),
LanguageModel("fr", "French", "Franรงais", false)
)
}
}
@Test
fun `should perform query`() = runTest {
every { mockRepository.getLanguages("query") }.returns(languagesFlow)
val job = launch(UnconfinedTestDispatcher()) { viewModel.uiState.collect() }
viewModel.uiState.test {
awaitItem() shouldBeEqualTo LanguagesState()
viewModel.searchFor("query")
languagesFlow.emit(Resource.success(emptyList()))
awaitItem() shouldBeEqualTo LanguagesState(
isLoading = false,
query = "query"
)
}
job.cancel()
}
@Test
fun `should trim query`() = runTest {
every { mockRepository.getLanguages("query") }.returns(languagesFlow)
val job = launch(UnconfinedTestDispatcher()) { viewModel.uiState.collect() }
viewModel.uiState.test {
awaitItem() shouldBeEqualTo LanguagesState()
viewModel.searchFor(" query ")
languagesFlow.emit(Resource.success(emptyList()))
awaitItem() shouldBeEqualTo LanguagesState(
isLoading = false,
query = "query"
)
}
job.cancel()
}
@Test
fun `should save selected languages`() {
every { mockSSPrefs.setLanguageCode("es") }.returns(Unit)
every { mockSSPrefs.setLastQuarterlyIndex(null) }.returns(Unit)
viewModel.modelSelected(LanguageModel("es", "Spanish", "Espaรฑol", false))
verify {
mockSSPrefs.setLanguageCode("es")
mockSSPrefs.setLastQuarterlyIndex(null)
mockWorkScheduler.preFetchImages("es")
}
}
}
| 7 | null | 43 | 157 | a61db7afe613b9b05b30e335c4bec7fb7cf7a7ad | 5,288 | sabbath-school-android | MIT License |
src/main/kotlin/com/sillyhusky/arch/rail/assembler/RASMDictionary.kt | huskyto | 615,505,816 | false | null | package com.sillyhusky.arch.rail.assembler
class RASMDictionary {
companion object {
// Have to use Int because no unsigned byte
fun translate(token: String): Int {
return when(token) {
// REGISTERS //
"R0" -> 0x00
"R1" -> 0x01
"R2" -> 0x02
"R3" -> 0x03
"R4" -> 0x04
"R5" -> 0x05
"R6" -> 0x06
"R7" -> 0x07
"BZ0" -> 0x08
"LV0" -> 0x09
"D0" -> 0x0A
"D1" -> 0x0B
"D2" -> 0x0C
"D3" -> 0x0D
"CNT" -> 0x0E
"IO" -> 0x0F
// ALU //
"ADD" -> 0x00
"SUB" -> 0x01
"AND" -> 0x02
"OR" -> 0x03
"NOT" -> 0x04
"XOR" -> 0x05
"SHL" -> 0x06
"SHR" -> 0x07
"RAN_SS" -> 0x0C
"RAN_NEXT" -> 0x0D
// CU //
"IF_EQ" -> 0x20
"IF_N_EQ" -> 0x21
"IF_LT" -> 0x22
"IF_LTE" -> 0x23
"IF_MT" -> 0x24
"IF_MTE" -> 0x25
"IF_T" -> 0x26 // check exact meaning
"IF_F" -> 0x27 // check exact meaning
// RAM_STACK //
"RAM_R" -> 0x10
"RAM_W" -> 0x11
"S_POP" -> 0x18
"S_PUSH" -> 0x19
"RET" -> 0x1A
"CALL" -> 0x9B//0x1B IM included
// IMMEDIATE //
"IM2" -> 0x40
"IM1" -> 0x80
// ALIAS //
"MOV" -> 0x40 //0x00
"JMP" -> 0x26
else -> -1
}
}
}
} | 0 | Kotlin | 0 | 1 | 095d41bab3e16ea8688dc10713a15a6f2a5f4f1d | 1,931 | rail-arch-kt | Apache License 2.0 |
ime/android/src/main/kotlin/studio/lunabee/onesafe/ime/DecryptClipboardListener.kt | LunabeeStudio | 624,544,471 | false | {"Kotlin": 3104681, "Java": 11977, "Python": 3979} | /*
* Copyright (c) 2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 6/30/2023 - for the oneSafe6 SDK.
* Last modified 6/30/23, 11:35 AM
*/
package studio.lunabee.onesafe.ime
import android.content.ClipboardManager
import android.content.Context
import com.lunabee.lbcore.model.LBResult
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import studio.lunabee.messaging.domain.repository.MessageChannelRepository
import studio.lunabee.messaging.domain.usecase.HandleIncomingMessageUseCase
import studio.lunabee.messaging.domain.usecase.IncomingMessageState
import studio.lunabee.onesafe.bubbles.ui.extension.getBase64FromMessage
import studio.lunabee.onesafe.domain.usecase.authentication.IsSafeReadyUseCase
import javax.inject.Inject
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.math.abs
class DecryptClipboardListener @Inject constructor(
@ApplicationContext context: Context,
private val handleIncomingMessageUseCase: HandleIncomingMessageUseCase,
private val channelRepository: MessageChannelRepository,
private val isSafeReadyUseCase: IsSafeReadyUseCase,
) : ClipboardManager.OnPrimaryClipChangedListener {
private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
private var lastClipCall: Long = 0L
private val lifecycleScope = MainScope()
private val _result: MutableSharedFlow<LBResult<IncomingMessageState>> = MutableSharedFlow()
val result: SharedFlow<LBResult<IncomingMessageState>> = _result.asSharedFlow()
@OptIn(ExperimentalEncodingApi::class)
override fun onPrimaryClipChanged() {
// Avoid potential multiple call
if (abs(lastClipCall - System.currentTimeMillis()) < 500) {
return
}
lastClipCall = System.currentTimeMillis()
val primaryClip = clipboard.primaryClip
primaryClip?.getItemAt(0)?.text?.toString()?.let { clipText ->
val message = try {
Base64.decode(clipText.getBase64FromMessage())
} catch (e: IllegalArgumentException) {
return
}
lifecycleScope.launch {
_result.emit(
handleIncomingMessageUseCase(
message,
channelRepository.channel,
isSafeReadyUseCase(),
),
)
}
}
}
}
| 0 | Kotlin | 1 | 2 | 3ab7b5f583f75c3f6f93680f29480049daed66c0 | 3,227 | oneSafe6_SDK_Android | Apache License 2.0 |
feature/feature_pokemon_list/src/main/java/com/serj113/pokedex/feature/pokemonlist/ui/PokemonListFragment.kt | serj113 | 668,290,121 | false | null | package com.serj113.pokedex.feature.pokemonlist.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class PokemonListFragment : Fragment() {
private val viewModel: PokemonListViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
val viewState by viewModel.viewStateFlow.collectAsState()
PokemonListScreen(viewState = viewState)
}
}
}
} | 0 | Kotlin | 0 | 0 | 26b8c749acca4b79575b71b0344f12582cadd0e8 | 1,037 | pokedex | Apache License 2.0 |
litho-it/src/main/java/com/facebook/litho/MountItemTestHelper.kt | facebook | 80,179,724 | false | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho
import android.graphics.Rect
import com.facebook.rendercore.MountItem
object MountItemTestHelper {
@JvmStatic
fun create(
component: Component,
host: ComponentHost?,
content: Any,
info: NodeInfo?,
bounds: Rect?,
flags: Int,
importantForAccessibility: Int
): MountItem {
val unit: LithoRenderUnit =
MountSpecLithoRenderUnit.create(
0,
component,
null,
info,
flags,
importantForAccessibility,
LithoRenderUnit.STATE_UNKNOWN)
val width = bounds?.width() ?: 0
val height = bounds?.height() ?: 0
val node =
create(
unit,
bounds ?: Rect(),
LithoLayoutData(
width,
height,
0,
0,
null,
null,
),
null,
)
return MountItem(node, host, content).apply { mountData = LithoMountData(content) }
}
}
| 90 | null | 765 | 7,703 | 8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0 | 1,665 | litho | Apache License 2.0 |
app/src/main/java/com/getcode/view/login/PhoneConfirm.kt | code-payments | 723,049,264 | false | {"Kotlin": 2149401, "C": 198685, "C++": 83029, "Java": 52287, "Shell": 8093, "Ruby": 4626, "CMake": 2594} | package com.getcode.view.login
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.ProvideTextStyle
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.getcode.LocalPhoneFormatter
import com.getcode.R
import com.getcode.navigation.core.LocalCodeNavigator
import com.getcode.navigation.screens.LoginArgs
import com.getcode.network.repository.replaceParam
import com.getcode.theme.BrandLight
import com.getcode.theme.CodeTheme
import com.getcode.view.components.ButtonState
import com.getcode.view.components.CodeButton
import com.getcode.view.components.OtpRow
const val OTP_LENGTH = 6
@OptIn(ExperimentalComposeUiApi::class)
@Preview
@Composable
fun PhoneConfirm(
viewModel: PhoneConfirmViewModel = hiltViewModel(),
arguments: LoginArgs = LoginArgs(),
) {
val navigator = LocalCodeNavigator.current
val dataState by viewModel.uiFlow.collectAsState()
val keyboardController = LocalSoftwareKeyboardController.current
val focusRequester = FocusRequester()
fun cleanInputString(str: String): String =
(if (str.length <= OTP_LENGTH) str else str.substring(
0,
OTP_LENGTH
)).filter { it.isDigit() }
Column(
modifier = Modifier
.fillMaxSize()
.windowInsetsPadding(WindowInsets.navigationBars)
.padding(horizontal = CodeTheme.dimens.inset)
.padding(bottom = CodeTheme.dimens.grid.x4)
.imePadding()
) {
Box(modifier = Modifier.weight(1f), contentAlignment = Alignment.Center) {
Column(
modifier = Modifier
.align(Alignment.Center),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Box(modifier = Modifier.fillMaxWidth()) {
TextField(
modifier = Modifier
.alpha(0f)
.focusRequester(focusRequester),
value = dataState.otpInputTextFieldValue,
onValueChange = {
viewModel.onOtpInputChange(cleanInputString(it.text))
},
readOnly = dataState.otpInputTextFieldValue.text.length == OTP_LENGTH,
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
)
OtpRow(
modifier = Modifier
.padding(top = CodeTheme.dimens.grid.x1),
length = OTP_LENGTH,
values = dataState.otpInput.orEmpty().toCharArray(),
onClick = {
focusRequester.requestFocus()
keyboardController?.show()
}
)
}
Column(
Modifier
.padding(top = CodeTheme.dimens.inset)
.wrapContentHeight()
.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(CodeTheme.dimens.grid.x1)
) {
ProvideTextStyle(
CodeTheme.typography.body2.copy(
textAlign = TextAlign.Center,
color = BrandLight
)
) {
Text(
text = stringResource(id = R.string.subtitle_smsWasSent)
)
if (dataState.isResendTimerRunning) {
Text(
modifier = Modifier.fillMaxWidth(),
text = stringResource(R.string.subtitle_didntGetCode)
.replaceParam(
LocalPhoneFormatter.current?.formatNumber(
dataState.phoneNumberFormatted.orEmpty()
)
) +
"\n" +
stringResource(R.string.subtitle_requestNewOneIn)
.replaceParam(
"0:${if (dataState.resetTimerTime < 10) "0" else ""}${dataState.resetTimerTime}"
)
)
} else {
val text = buildAnnotatedString {
append(stringResource(id = R.string.subtitle_didntGetCodeResend))
append(" ")
pushStringAnnotation(
tag = "resend",
annotation = "resend code trigger"
)
withStyle(style = SpanStyle(textDecoration = TextDecoration.Underline)) {
append(stringResource(R.string.subtitle_resend))
}
pop()
}
ClickableText(
modifier = Modifier.fillMaxWidth(),
text = text,
style = LocalTextStyle.current
) { offset ->
text.getStringAnnotations(
tag = "resend",
start = offset,
end = offset
)
.firstOrNull()?.let {
viewModel.resendCode()
}
}
}
}
}
}
}
CodeButton(
modifier = Modifier.fillMaxWidth(),
onClick = {
viewModel.onSubmit()
},
isLoading = dataState.isLoading,
isSuccess = dataState.isSuccess,
enabled = false,
text = stringResource(R.string.action_confirm),
buttonState = ButtonState.Filled,
)
}
SideEffect {
focusRequester.requestFocus()
}
LaunchedEffect(dataState.isSuccess) {
if (dataState.isSuccess) {
keyboardController?.hide()
}
}
LaunchedEffect(arguments) {
viewModel.reset(navigator)
val phoneNumber = arguments.phoneNumber.orEmpty()
viewModel.setPhoneNumber(phoneNumber)
arguments.signInEntropy
?.let { viewModel.setSignInEntropy(it) }
viewModel.setIsPhoneLinking(arguments.isPhoneLinking)
viewModel.setIsNewAccount(arguments.isNewAccount)
}
} | 4 | Kotlin | 13 | 14 | f7078b30d225ca32796fda8792b8a99646967183 | 8,829 | code-android-app | MIT License |
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/Umbrella.kt | alexzhirkevich | 636,411,288 | false | null | package io.github.alexzhirkevich.cupertino.icons.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons
public val CupertinoIcons.Filled.Umbrella: ImageVector
get() {
if (_umbrella != null) {
return _umbrella!!
}
_umbrella = Builder(name = "Umbrella", defaultWidth = 23.3672.dp, defaultHeight =
27.7148.dp, viewportWidth = 23.3672f, viewportHeight = 27.7148f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.7109f, 3.5039f)
lineTo(12.6562f, 3.5039f)
lineTo(12.6562f, 0.9844f)
curveTo(12.6562f, 0.4453f, 12.2227f, 0.0f, 11.6836f, 0.0f)
curveTo(11.1445f, 0.0f, 10.7109f, 0.4453f, 10.7109f, 0.9844f)
close()
moveTo(0.9727f, 14.8711f)
curveTo(1.3125f, 14.8711f, 1.6406f, 14.6484f, 1.8984f, 14.2617f)
curveTo(2.6836f, 13.0781f, 3.5039f, 12.5859f, 4.6172f, 12.5859f)
curveTo(5.707f, 12.5859f, 6.4453f, 13.0781f, 7.1133f, 14.25f)
curveTo(7.3711f, 14.6836f, 7.6172f, 14.8711f, 7.9453f, 14.8711f)
curveTo(8.2852f, 14.8711f, 8.543f, 14.6836f, 8.7773f, 14.25f)
curveTo(9.4102f, 13.1719f, 10.5586f, 12.5156f, 11.6836f, 12.5156f)
curveTo(12.8086f, 12.5156f, 13.957f, 13.1719f, 14.5898f, 14.25f)
curveTo(14.8242f, 14.6836f, 15.0703f, 14.8711f, 15.4219f, 14.8711f)
curveTo(15.75f, 14.8711f, 15.9961f, 14.6836f, 16.2422f, 14.25f)
curveTo(16.9219f, 13.0781f, 17.6602f, 12.5859f, 18.75f, 12.5859f)
curveTo(19.8633f, 12.5859f, 20.6836f, 13.0781f, 21.457f, 14.2617f)
curveTo(21.7148f, 14.6484f, 22.043f, 14.8711f, 22.3945f, 14.8711f)
curveTo(22.9805f, 14.8711f, 23.3672f, 14.3906f, 23.3672f, 13.7578f)
curveTo(23.3672f, 9.1055f, 19.6992f, 2.5781f, 11.6836f, 2.5781f)
curveTo(3.668f, 2.5781f, 0.0f, 9.1055f, 0.0f, 13.7578f)
curveTo(0.0f, 14.3906f, 0.3867f, 14.8711f, 0.9727f, 14.8711f)
close()
moveTo(8.9297f, 27.0938f)
curveTo(11.0508f, 27.0938f, 12.6562f, 25.4883f, 12.6562f, 23.3555f)
lineTo(12.6562f, 11.9531f)
lineTo(10.7109f, 11.9531f)
lineTo(10.7109f, 23.3555f)
curveTo(10.7109f, 24.375f, 9.9727f, 25.1133f, 8.9297f, 25.1133f)
curveTo(7.9102f, 25.1133f, 7.1836f, 24.375f, 7.1836f, 23.3555f)
curveTo(7.1836f, 22.6758f, 6.7734f, 22.2188f, 6.1758f, 22.2188f)
curveTo(5.5898f, 22.2188f, 5.2031f, 22.6758f, 5.2031f, 23.3555f)
curveTo(5.2031f, 25.4883f, 6.8203f, 27.0938f, 8.9297f, 27.0938f)
close()
}
}
.build()
return _umbrella!!
}
private var _umbrella: ImageVector? = null
| 18 | null | 31 | 848 | 54bfbb58f6b36248c5947de343567903298ee308 | 3,612 | compose-cupertino | Apache License 2.0 |
src/main/kotlin/dk/cachet/carp/webservices/export/command/impl/ExportSummary.kt | cph-cachet | 674,650,033 | false | {"Kotlin": 611558, "TypeScript": 109044, "HTML": 9317, "FreeMarker": 4300, "Shell": 4202, "CSS": 1656, "Dockerfile": 1264, "JavaScript": 706} | package dk.cachet.carp.webservices.export.command.impl
import dk.cachet.carp.common.application.UUID
import dk.cachet.carp.webservices.export.command.ExportCommand
import dk.cachet.carp.webservices.export.domain.Export
import dk.cachet.carp.webservices.export.service.ResourceExporterService
import dk.cachet.carp.webservices.file.util.FileUtil
import org.apache.logging.log4j.LogManager
import java.io.IOException
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.createTempDirectory
import kotlin.io.path.deleteRecursively
class ExportSummary(
entry: Export,
private val deploymentIds: Set<UUID>?,
private val resourceExporter: ResourceExporterService,
private val fileUtil: FileUtil,
) : ExportCommand(entry) {
companion object {
private val LOGGER = LogManager.getLogger()
}
override fun canExecute(): Pair<Boolean, String> = Pair(true, "")
@OptIn(ExperimentalPathApi::class)
override suspend fun execute() {
val workingDir = createTempDirectory()
val zipPath = fileUtil.resolveFileStorage(entry.fileName)
resourceExporter.exportStudyData(UUID(entry.studyId), deploymentIds, workingDir, logger)
try {
fileUtil.zipDirectory(workingDir, zipPath)
} catch (e: IOException) {
LOGGER.error("Zipping failed for study: ${entry.studyId}")
fileUtil.deleteFile(zipPath)
throw e
} finally {
workingDir.deleteRecursively()
}
}
}
| 18 | Kotlin | 2 | 3 | b0fcb02a9cf666c48539dccabdc4be012b37c0c0 | 1,504 | carp-webservices-spring | MIT License |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/aws_apigatewayv2_authorizers/HttpIamAuthorizer.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 140726596} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.aws_apigatewayv2_authorizers
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.services.apigatewayv2.HttpRouteAuthorizerBindOptions
import io.cloudshiftdev.awscdk.services.apigatewayv2.HttpRouteAuthorizerConfig
import io.cloudshiftdev.awscdk.services.apigatewayv2.IHttpRouteAuthorizer
import kotlin.Unit
import kotlin.jvm.JvmName
/**
* Authorize HTTP API Routes with IAM.
*
* Example:
*
* ```
* import io.cloudshiftdev.awscdk.aws_apigatewayv2_authorizers.HttpIamAuthorizer;
* import io.cloudshiftdev.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
* AnyPrincipal principal;
* HttpIamAuthorizer authorizer = new HttpIamAuthorizer();
* HttpApi httpApi = HttpApi.Builder.create(this, "HttpApi")
* .defaultAuthorizer(authorizer)
* .build();
* HttpRoute[] routes = httpApi.addRoutes(AddRoutesOptions.builder()
* .integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
* .path("/books/{book}")
* .build());
* routes[0].grantInvoke(principal);
* ```
*/
public open class HttpIamAuthorizer internal constructor(
internal override val cdkObject:
software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpIamAuthorizer,
) : CdkObject(cdkObject), IHttpRouteAuthorizer {
public constructor() :
this(software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpIamAuthorizer()
)
/**
* Bind this authorizer to a specified Http route.
*
* @param _options
*/
public override fun bind(options: HttpRouteAuthorizerBindOptions): HttpRouteAuthorizerConfig =
unwrap(this).bind(options.let(HttpRouteAuthorizerBindOptions::unwrap)).let(HttpRouteAuthorizerConfig::wrap)
/**
* Bind this authorizer to a specified Http route.
*
* @param _options
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("7264f1d1173f23e66027e915fda55df480ab8eab246316ad2f01f98a1f9a28cc")
public override fun bind(options: HttpRouteAuthorizerBindOptions.Builder.() -> Unit):
HttpRouteAuthorizerConfig = bind(HttpRouteAuthorizerBindOptions(options))
public companion object {
internal
fun wrap(cdkObject: software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpIamAuthorizer):
HttpIamAuthorizer = HttpIamAuthorizer(cdkObject)
internal fun unwrap(wrapped: HttpIamAuthorizer):
software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpIamAuthorizer = wrapped.cdkObject
}
}
| 1 | Kotlin | 0 | 4 | eb3eef728b34da593a3e55dc423d4f5fa3668e9c | 2,630 | kotlin-cdk-wrapper | Apache License 2.0 |
app/src/main/java/com/s16/febraury/Screens/Network/NetCityActivity.kt | s16exe | 744,586,730 | false | {"Kotlin": 109914} | package com.s16.febraury.Screens.Network
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.s16.febraury.R
@Composable
fun NetCityActivity(navController: NavHostController) {
Column {
Image(
painter = painterResource(id = R.drawable.all_pic), contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
}
LazyColumn(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
item {
Spacer(modifier = Modifier.height(100.dp))
Text(text = "List Of Cities",
fontSize = 30.sp,
fontWeight = FontWeight.Bold,
color = Color(android.graphics.Color.parseColor("#ffea00")),
fontFamily = FontFamily(Font(R.font.regular))
)
Spacer(modifier = Modifier.height(40.dp))
}
items(cityList) { city ->
CityButton(cityName = city, onClick = { navController.navigate("NetListActivity") })
Spacer(modifier = Modifier.height(16.dp))
}
item {
Box(
modifier = Modifier
.width(250.dp)
.padding(16.dp)
.clip(RoundedCornerShape(50.dp))
) {
Button(
onClick = { navController.popBackStack() },
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.clip(RoundedCornerShape(50.dp))
,
colors = ButtonDefaults.buttonColors(
Color.Transparent
),
) {
Text(
text = "Go Back",
fontSize = 20.sp,
color = Color.LightGray,
fontFamily = FontFamily(Font(R.font.regular))
)
}
}
}
}
}
@Composable
fun CityButton(cityName: String, onClick: () -> Unit) {
Box(
modifier = Modifier
.fillMaxWidth(0.95f)
.clip(RoundedCornerShape(16.dp))
) {
Button(
onClick = onClick,
modifier = Modifier
.fillMaxWidth()
.height(70.dp),
colors = ButtonDefaults.buttonColors(
Color.Transparent
),
) {
Text(
text = cityName,
fontSize = 30.sp,
color = Color.White,
fontFamily = FontFamily(Font(R.font.regular))
)
}
}
}
val cityList = listOf(
"BENGALURU",
"MUMBAI",
"DELHI",
"CHENNAI",
"HYDERABAD",
"KOLKATA",
"PUNE",
"AHMEDABAD",
"COIMBATORE"
)
| 0 | Kotlin | 0 | 0 | 8b1d017384f498778b02e19ffa5cf740640ec926 | 3,798 | Febraury | MIT License |
app/src/main/java/com/longdo/api3/App.kt | MetamediaTechnology | 435,746,992 | false | {"Kotlin": 44855} | package com.longdo.api3
import android.app.Application
import android.webkit.WebView
import com.longdo.map3.BuildConfig
class App : Application() {
override fun onCreate() {
super.onCreate()
setupWebView()
}
private fun setupWebView() {
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)
}
}
| 0 | Kotlin | 0 | 0 | 59080f21f04bc7e9d536863459b579656f66d81e | 344 | longdo-map-sdk3-android | Apache License 2.0 |
ktor-io/js/test/io/ktor/utils/io/ISOTest.kt | ktorio | 40,136,600 | false | null | package io.ktor.utils.io.tests
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlin.test.*
private const val TEXT = "test\u00f0."
private val BYTES = byteArrayOf(0x74, 0x65, 0x73, 0x74, 0xf0.toByte(), 0x2e)
class ISOTest {
@Test
fun testEncode() {
val bytes = Charsets.ISO_8859_1.newEncoder().encode(TEXT).readBytes()
assertTrue {
bytes.contentEquals(BYTES)
}
}
@Test
fun testEncodeUnmappable() {
assertFailsWith<MalformedInputException> {
Charsets.ISO_8859_1.newEncoder().encode("\u0422")
}
}
@Test
fun testDecode() {
val pkt = ByteReadPacket(BYTES)
val result = Charsets.ISO_8859_1.newDecoder().decode(pkt)
assertEquals(TEXT, result)
}
}
| 269 | Kotlin | 806 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 796 | ktor | Apache License 2.0 |
src/main/kotlin/it/skrape/exceptions/SkrapeItExceptions.kt | gemasr | 212,129,064 | true | {"Kotlin": 72677, "HTML": 1293} | package it.skrape.exceptions
open class ElementNotFoundException(selector: String, tag: String = ""):
Exception("Could not find element \"$tag$selector\"")
class DivElementNotFoundException(selector: String): ElementNotFoundException(selector, "div")
class MetaElementNotFoundException(selector: String): ElementNotFoundException(selector, "meta")
class SpanElementNotFoundException(selector: String): ElementNotFoundException(selector, "span")
class StrongElementNotFoundException(selector: String): ElementNotFoundException(selector, "strong")
class DocumentNotParsable(documentToParse: String): Exception("Could not parse string \n\"$documentToParse\"")
class UnsupportedRequestOptionException(message:String): IllegalArgumentException(message)
| 0 | null | 0 | 0 | 6b2b6aebbc93d1d7bf73ae4665cf712c751f19d3 | 764 | skrape.it | MIT License |
bellatrix.ios/src/main/java/solutions/bellatrix/ios/infrastructure/AppConfiguration.kt | AutomateThePlanet | 334,964,015 | false | null | /*
* Copyright 2021 Automate The Planet Ltd.
* Author: <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package solutions.bellatrix.ios.infrastructure
import org.jsoup.internal.StringUtil
import solutions.bellatrix.core.configuration.ConfigurationService
import solutions.bellatrix.ios.configuration.IOSSettings
import java.util.*
class AppConfiguration {
lateinit var appPath: String
lateinit var lifecycle: Lifecycle
lateinit var deviceName: String
lateinit var iosVersion: String
var mobileWebExecution: Boolean = false
var appiumOptions: HashMap<String, String> = hashMapOf()
constructor(isMobileWebExecution: Boolean) {
mobileWebExecution = isMobileWebExecution
}
constructor(lifecycle: Lifecycle, androidVersion: String, deviceName: String, appPath: String) {
if (StringUtil.isBlank(androidVersion)) {
this.iosVersion = ConfigurationService.get<IOSSettings>().defaultIosVersion
} else {
this.iosVersion = androidVersion
}
if (StringUtil.isBlank(deviceName)) {
this.deviceName = ConfigurationService.get<IOSSettings>().defaultDeviceName
} else {
this.deviceName = deviceName
}
if (StringUtil.isBlank(appPath)) {
this.appPath = ConfigurationService.get<IOSSettings>().defaultAppPath
} else {
this.appPath = appPath
}
this.lifecycle = lifecycle
this.mobileWebExecution = false
appiumOptions = HashMap()
}
} | 1 | Kotlin | 1 | 1 | 5da5e705b47e12c66937d130b3031ac8703b8279 | 2,036 | BELLATRIX-Kotlin | Apache License 2.0 |
core/src/main/kotlin/net/corda/core/transactions/TransactionBuilder.kt | lavenutagi | 100,033,819 | true | {"Kotlin": 3386415, "Java": 184482, "Groovy": 27918, "Shell": 320, "Batchfile": 106} | package net.corda.core.transactions
import co.paralleluniverse.strands.Strand
import net.corda.core.contracts.*
import net.corda.core.crypto.*
import net.corda.core.identity.Party
import net.corda.core.internal.FlowStateMachine
import net.corda.core.node.ServiceHub
import net.corda.core.serialization.serialize
import java.security.KeyPair
import java.security.PublicKey
import java.security.SignatureException
import java.time.Duration
import java.time.Instant
import java.util.*
/**
* A TransactionBuilder is a transaction class that's mutable (unlike the others which are all immutable). It is
* intended to be passed around contracts that may edit it by adding new states/commands. Then once the states
* and commands are right, this class can be used as a holding bucket to gather signatures from multiple parties.
*
* The builder can be customised for specific transaction types, e.g. where additional processing is needed
* before adding a state/command.
*
* @param notary Notary used for the transaction. If null, this indicates the transaction DOES NOT have a notary.
* When this is set to a non-null value, an output state can be added by just passing in a [ContractState] โ a
* [TransactionState] with this notary specified will be generated automatically.
*
* @param signers The set of public keys the transaction needs signatures for. The logic for building the signers set
* can be customised for every [TransactionType]. E.g. in the general case it contains the command and notary public keys,
* but for the [TransactionType.NotaryChange] transactions it is the set of all input [ContractState.participants].
*/
open class TransactionBuilder(
protected val type: TransactionType = TransactionType.General,
var notary: Party? = null,
var lockId: UUID = (Strand.currentStrand() as? FlowStateMachine<*>)?.id?.uuid ?: UUID.randomUUID(),
protected val inputs: MutableList<StateRef> = arrayListOf(),
protected val attachments: MutableList<SecureHash> = arrayListOf(),
protected val outputs: MutableList<TransactionState<ContractState>> = arrayListOf(),
protected val commands: MutableList<Command<*>> = arrayListOf(),
protected val signers: MutableSet<PublicKey> = mutableSetOf(),
protected var window: TimeWindow? = null) {
constructor(type: TransactionType, notary: Party) : this(type, notary, (Strand.currentStrand() as? FlowStateMachine<*>)?.id?.uuid ?: UUID.randomUUID())
/**
* Creates a copy of the builder.
*/
fun copy() = TransactionBuilder(
type = type,
notary = notary,
inputs = ArrayList(inputs),
attachments = ArrayList(attachments),
outputs = ArrayList(outputs),
commands = ArrayList(commands),
signers = LinkedHashSet(signers),
window = window
)
// DOCSTART 1
/** A more convenient way to add items to this transaction that calls the add* methods for you based on type */
fun withItems(vararg items: Any): TransactionBuilder {
for (t in items) {
when (t) {
is StateAndRef<*> -> addInputState(t)
is SecureHash -> addAttachment(t)
is TransactionState<*> -> addOutputState(t)
is ContractState -> addOutputState(t)
is Command<*> -> addCommand(t)
is CommandData -> throw IllegalArgumentException("You passed an instance of CommandData, but that lacks the pubkey. You need to wrap it in a Command object first.")
is TimeWindow -> setTimeWindow(t)
else -> throw IllegalArgumentException("Wrong argument type: ${t.javaClass}")
}
}
return this
}
// DOCEND 1
fun toWireTransaction() = WireTransaction(ArrayList(inputs), ArrayList(attachments),
ArrayList(outputs), ArrayList(commands), notary, signers.toList(), type, window)
@Throws(AttachmentResolutionException::class, TransactionResolutionException::class)
fun toLedgerTransaction(services: ServiceHub) = toWireTransaction().toLedgerTransaction(services)
@Throws(AttachmentResolutionException::class, TransactionResolutionException::class, TransactionVerificationException::class)
fun verify(services: ServiceHub) {
toLedgerTransaction(services).verify()
}
open fun addInputState(stateAndRef: StateAndRef<*>): TransactionBuilder {
val notary = stateAndRef.state.notary
require(notary == this.notary) { "Input state requires notary \"$notary\" which does not match the transaction notary \"${this.notary}\"." }
signers.add(notary.owningKey)
inputs.add(stateAndRef.ref)
return this
}
fun addAttachment(attachmentId: SecureHash): TransactionBuilder {
attachments.add(attachmentId)
return this
}
fun addOutputState(state: TransactionState<*>): TransactionBuilder {
outputs.add(state)
return this
}
@JvmOverloads
fun addOutputState(state: ContractState, notary: Party, encumbrance: Int? = null): TransactionBuilder {
return addOutputState(TransactionState(state, notary, encumbrance))
}
/** A default notary must be specified during builder construction to use this method */
fun addOutputState(state: ContractState): TransactionBuilder {
checkNotNull(notary) { "Need to specify a notary for the state, or set a default one on TransactionBuilder initialisation" }
addOutputState(state, notary!!)
return this
}
fun addCommand(arg: Command<*>): TransactionBuilder {
// TODO: replace pubkeys in commands with 'pointers' to keys in signers
signers.addAll(arg.signers)
commands.add(arg)
return this
}
fun addCommand(data: CommandData, vararg keys: PublicKey) = addCommand(Command(data, listOf(*keys)))
fun addCommand(data: CommandData, keys: List<PublicKey>) = addCommand(Command(data, keys))
/**
* Sets the [TimeWindow] for this transaction, replacing the existing [TimeWindow] if there is one. To be valid, the
* transaction must then be signed by the notary service within this window of time. In this way, the notary acts as
* the Timestamp Authority.
*/
fun setTimeWindow(timeWindow: TimeWindow): TransactionBuilder {
check(notary != null) { "Only notarised transactions can have a time-window" }
signers.add(notary!!.owningKey)
window = timeWindow
return this
}
/**
* The [TimeWindow] for the transaction can also be defined as [time] +/- [timeTolerance]. The tolerance should be
* chosen such that your code can finish building the transaction and sending it to the Timestamp Authority within
* that window of time, taking into account factors such as network latency. Transactions being built by a group of
* collaborating parties may therefore require a higher time tolerance than a transaction being built by a single
* node.
*/
fun setTimeWindow(time: Instant, timeTolerance: Duration) = setTimeWindow(TimeWindow.withTolerance(time, timeTolerance))
// Accessors that yield immutable snapshots.
fun inputStates(): List<StateRef> = ArrayList(inputs)
fun attachments(): List<SecureHash> = ArrayList(attachments)
fun outputStates(): List<TransactionState<*>> = ArrayList(outputs)
fun commands(): List<Command<*>> = ArrayList(commands)
/** The signatures that have been collected so far - might be incomplete! */
@Deprecated("Signatures should be gathered on a SignedTransaction instead.")
protected val currentSigs = arrayListOf<DigitalSignature.WithKey>()
@Deprecated("Use ServiceHub.signInitialTransaction() instead.")
fun signWith(key: KeyPair): TransactionBuilder {
val data = toWireTransaction().id
addSignatureUnchecked(key.sign(data.bytes))
return this
}
/** Adds the signature directly to the transaction, without checking it for validity. */
@Deprecated("Use ServiceHub.signInitialTransaction() instead.")
fun addSignatureUnchecked(sig: DigitalSignature.WithKey): TransactionBuilder {
currentSigs.add(sig)
return this
}
@Deprecated("Use ServiceHub.signInitialTransaction() instead.")
fun toSignedTransaction(checkSufficientSignatures: Boolean = true): SignedTransaction {
if (checkSufficientSignatures) {
val gotKeys = currentSigs.map { it.by }.toSet()
val missing: Set<PublicKey> = signers.filter { !it.isFulfilledBy(gotKeys) }.toSet()
if (missing.isNotEmpty())
throw IllegalStateException("Missing signatures on the transaction for the public keys: ${missing.joinToString()}")
}
val wtx = toWireTransaction()
return SignedTransaction(wtx, ArrayList(currentSigs))
}
/**
* Checks that the given signature matches one of the commands and that it is a correct signature over the tx, then
* adds it.
*
* @throws SignatureException if the signature didn't match the transaction contents.
* @throws IllegalArgumentException if the signature key doesn't appear in any command.
*/
@Deprecated("Use WireTransaction.checkSignature() instead.")
fun checkAndAddSignature(sig: DigitalSignature.WithKey) {
checkSignature(sig)
addSignatureUnchecked(sig)
}
/**
* Checks that the given signature matches one of the commands and that it is a correct signature over the tx.
*
* @throws SignatureException if the signature didn't match the transaction contents.
* @throws IllegalArgumentException if the signature key doesn't appear in any command.
*/
@Deprecated("Use WireTransaction.checkSignature() instead.")
fun checkSignature(sig: DigitalSignature.WithKey) {
require(commands.any { it.signers.any { sig.by in it.keys } }) { "Signature key doesn't match any command" }
sig.verify(toWireTransaction().id)
}
} | 0 | Kotlin | 0 | 0 | f9552a0d3e97ef48565583abf1a2a3edb70829fa | 10,055 | corda | Apache License 2.0 |
11-using-fragments-to-expand-ui/projects/starter/ListMaker/app/src/main/java/com/raywenderlich/listmaker/ui/main/ListSelectionRecyclerViewAdapter.kt | kodecocodes | 273,265,709 | false | {"Kotlin": 1539452, "Shell": 1914} | package com.trios2024amdj.listmaker.ui.main
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.trios2024amdj.listmaker.databinding.ListSelectionViewHolderBinding
import com.trios2024amdj.listmaker.models.TaskList
class ListSelectionRecyclerViewAdapter(private val lists : MutableList<TaskList>,
val clickListener: ListSelectionRecyclerViewClickListener) :
RecyclerView.Adapter<ListSelectionViewHolder>() {
val listTitles = arrayOf("Shopping List", "Chores", "Android Tutorials")
interface ListSelectionRecyclerViewClickListener {
fun listItemClicked(list: TaskList)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListSelectionViewHolder {
val binding =
ListSelectionViewHolderBinding.inflate(LayoutInflater.from(parent.context),
parent, false)
return ListSelectionViewHolder(binding)
}
override fun getItemCount(): Int {
return lists.size
}
override fun onBindViewHolder(holder: ListSelectionViewHolder, position: Int) {
holder.binding.itemNumber.text = (position + 1).toString()
holder.binding.itemString.text = lists[position].name
holder.itemView.setOnClickListener {
clickListener.listItemClicked(lists[position])}
}
fun listsUpdated() {
notifyItemInserted(lists.size-1)
}
} | 5 | Kotlin | 65 | 61 | 5883000783567b6c1ea90cb2f89a7e140d4e795e | 1,439 | aa-materials | Apache License 2.0 |
src/test/kotlin/fr/nicopico/n2rss/newsletter/handlers/jsoup/DocumentExtKtTest.kt | nicopico-dev | 747,919,496 | false | {"Kotlin": 355275, "HTML": 10832, "CSS": 3265, "JavaScript": 2724, "Shell": 2608} | /*
* Copyright (c) 2024 Nicolas PICON
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package fr.nicopico.n2rss.newsletter.handlers.jsoup
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.assertions.withClue
import io.kotest.matchers.shouldBe
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.junit.jupiter.api.Test
class DocumentExtKtTest {
@Test
fun `indexOf should return the index of the element`() {
// GIVEN
val document = createDocument(HTML_SAMPLE)
val element = document.selectFirst("span.bold")!!
// WHEN
val actual = document.indexOf(element)
// THEN
actual shouldBe 8
}
@Test
fun `indexOf should return -1 if the element does not exist in the document`() {
// GIVEN
val document = createDocument(HTML_SAMPLE)
val element = Element("a")
// WHEN
val actual = document.indexOf(element)
// THEN
actual shouldBe -1
}
@Test
fun `select should return the first element matching the selector after the provided index`() {
// GIVEN
val document = createDocument(HTML_SAMPLE)
// WHEN
val element = document.select("span", 8)
// THEN
withClue("element") {
element?.text() shouldBe "Else"
}
}
@Test
fun `select should return null if no elements match the selector`() {
// GIVEN
val document = createDocument(HTML_SAMPLE)
// WHEN
val element = document.select("a", 8)
// THEN
withClue("element") {
element shouldBe null
}
}
@Test
fun `select should throw if index is less than 0`() {
// GIVEN
val document = createDocument(HTML_SAMPLE)
// WHEN - THEN
shouldThrow<IllegalArgumentException> {
document.select("span", -1)
}
}
@Test
fun `select should throw if index is greater than the last index of the document`() {
// GIVEN
val document = createDocument(HTML_SAMPLE)
// WHEN - THEN
shouldThrow<IllegalArgumentException> {
document.select("span", 11)
}
}
companion object {
private const val HTML_SAMPLE = """
<table>
<tr>
<td>
<span class="bold">Something</span>
</td>
<td>
<span>Else</span>
</td>
</tr>
</table>
"""
private fun createDocument(html: String): Document {
return Jsoup.parseBodyFragment(html)
}
}
}
| 3 | Kotlin | 0 | 2 | c9d48fc886bba777749bed36d0e199d424772abc | 3,778 | n2rss | MIT License |
app/src/main/java/com/fracta7/crafter/domain/model/Category.kt | fracta7 | 749,375,185 | false | {"Kotlin": 447882} | package com.fracta7.crafter.domain.model
/**
* Represents item category
* @property id is the ID of category
* @property name is the name of category
* @property item is the item ID of category
*/
data class Category(
val id: TagID,
val name: TagName,
val item: ItemID,
val custom: Boolean = false
) | 0 | Kotlin | 0 | 2 | 7eb0c20e507c5251cadf24aee64b0dece0da5937 | 320 | crafter | MIT License |
app/src/main/java/com/composeweatherapp/presentation/navigation/NavRoutes.kt | AhmetOcak | 538,149,907 | false | {"Kotlin": 102846} | package com.composeweatherapp.presentation.navigation
object NavRoutes {
const val homeScreen = "Home Screen"
const val searchCityScreen = "Search City Screen"
} | 0 | Kotlin | 2 | 8 | 3132fd3814887d99b70fc78570fb39e899f2ac4d | 170 | JetpackCompose-WeatherApp | MIT License |
compose/ui/ui-test-junit4/src/androidAndroidTest/kotlin/androidx/compose/ui/test/junit4/IdlingResourceRegistryTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test.junit4
import androidx.compose.ui.test.IdlingResource
import androidx.compose.ui.test.InternalTestingApi
import androidx.test.annotation.UiThreadTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineScope
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
/*
* This class *could* be moved to the test source set, but that makes it more likely to be
* skipped if only connectedCheck is run.
*/
@SmallTest
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalCoroutinesApi::class)
class IdlingResourceRegistryTest {
private var onIdleCalled = false
@OptIn(ExperimentalCoroutinesApi::class)
private val scope = TestCoroutineScope()
@OptIn(InternalTestingApi::class)
private val registry = IdlingResourceRegistry(scope).apply {
setOnIdleCallback { onIdleCalled = true }
}
@After
fun verifyRegistryStoppedPolling() {
scope.cleanupTestCoroutines()
}
@Test
@UiThreadTest
fun isIdleNow_0_IdlingResources() {
assertThat(registry.isIdleNow).isTrue()
assertNotPolling()
}
@Test
@UiThreadTest
fun isIdleNow_1_IdlingResource() {
val resource = TestIdlingResource(true)
registry.registerIdlingResource(resource)
assertThat(registry.isIdleNow).isTrue()
resource.isIdleNow = false
assertThat(registry.isIdleNow).isFalse()
assertThatPollingStartsAndEnds {
resource.isIdleNow = true
}
resource.isIdleNow = false
assertThat(registry.isIdleNow).isFalse()
assertThatPollingStartsAndEnds {
resource.isIdleNow = true
}
}
@Test
@UiThreadTest
fun isIdleNow_2_IdlingResources() {
val resource1 = TestIdlingResource(true)
registry.registerIdlingResource(resource1)
val resource2 = TestIdlingResource(true)
registry.registerIdlingResource(resource2)
resource1.isIdleNow = true
resource2.isIdleNow = true
assertThat(registry.isIdleNow).isTrue()
resource1.isIdleNow = false
resource2.isIdleNow = true
assertThat(registry.isIdleNow).isFalse()
resource1.isIdleNow = true
resource2.isIdleNow = false
assertThat(registry.isIdleNow).isFalse()
resource1.isIdleNow = false
resource2.isIdleNow = false
assertThat(registry.isIdleNow).isFalse()
assertThatPollingStartsAndEnds {
resource1.isIdleNow = true
resource2.isIdleNow = true
}
}
@Test
@UiThreadTest
fun isIdleNow_true_doesNotStartPolling() {
registry.registerIdlingResource(TestIdlingResource(true))
assertThat(registry.isIdleNow).isTrue()
assertNotPolling()
}
@Test
@UiThreadTest
fun isIdleNow_false_doesNotStartPolling() {
registry.registerIdlingResource(TestIdlingResource(false))
assertThat(registry.isIdleNow).isFalse()
assertNotPolling()
}
@Test
@UiThreadTest
fun isIdleOrStartPolling_emptyRegister_doesNotStartPolling() {
assertThat(registry.isIdleNow).isTrue()
assertThat(registry.isIdleOrEnsurePolling()).isTrue()
assertNotPolling()
}
@Test
@UiThreadTest
fun isIdleOrStartPolling_idleRegister_doesNotStartPolling() {
registry.registerIdlingResource(TestIdlingResource(true))
assertThat(registry.isIdleOrEnsurePolling()).isTrue()
assertNotPolling()
}
@Test
@UiThreadTest
fun isIdleOrStartPolling_busyRegister_doesStartPolling() {
val resource = TestIdlingResource(false)
registry.registerIdlingResource(resource)
assertThatPollingStartsAndEnds {
resource.isIdleNow = true
}
}
private fun assertThatPollingStartsAndEnds(makeIdle: () -> Unit) {
// Check that we're not polling already ..
assertThat(scope.advanceUntilIdle()).isEqualTo(0L)
// .. and that we're not idle
assertThat(registry.isIdleNow).isFalse()
// Start the polling
onIdleCalled = false
assertThat(registry.isIdleOrEnsurePolling()).isFalse()
// Make the registry idle
makeIdle.invoke()
// Verify that it has polled ..
assertThat(scope.advanceUntilIdle()).isGreaterThan(0L)
// .. the registry is now idle
assertThat(registry.isIdleNow).isTrue()
// .. and the onIdle callback was called
assertThat(onIdleCalled).isTrue()
}
private fun assertNotPolling() {
// Check that no poll job is running ..
assertThat(scope.advanceUntilIdle()).isEqualTo(0L)
scope.cleanupTestCoroutines()
// .. and that the onIdle callback was not called
assertThat(onIdleCalled).isFalse()
}
private class TestIdlingResource(initialIdleness: Boolean) : IdlingResource {
override var isIdleNow: Boolean = initialIdleness
}
}
| 29 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 5,781 | androidx | Apache License 2.0 |
app/src/main/java/com/udc/apptfg/viewmodel/orders/AddItemOrderViewModel.kt | manuelmanteiga98 | 659,483,428 | false | null | package com.udc.apptfg.viewmodel.orders
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import com.udc.apptfg.model.ErrorModel
import java.io.File
class AddItemOrderViewModel : ViewModel() {
val error = MutableLiveData<ErrorModel>()
val photo = MutableLiveData<Bitmap>()
val finish = MutableLiveData<Boolean>()
private val auth = FirebaseAuth.getInstance()
private val db = FirebaseFirestore.getInstance()
private val storage = FirebaseStorage.getInstance()
fun getInfo(idItem: String) {
if (auth.currentUser != null) {
getItemImage(idItem)
exists(idItem)
}
}
private fun exists(idItem:String){
val email = auth.currentUser!!.email.toString()
db.collection("users").document(email)
.collection("items").document(idItem).get()
.addOnCompleteListener { res ->
if(!res.isSuccessful || !res.result.exists()){
error.postValue(
ErrorModel("item_not_found")
)
}
}
}
private fun getItemImage(id: String) {
val localFile = File.createTempFile(id, "jpg")
val path = auth.currentUser!!.email + "/items/" + id
val reference = storage.reference.child(path)
reference.getFile(localFile).addOnSuccessListener {
photo.postValue(
Bitmap.createScaledBitmap(
BitmapFactory.decodeFile(localFile.absolutePath),
200,
200,
false
)
)
}
}
fun addItemToOrder(idOrder: String, idItem: String, units: Int) {
if (units <= 0)
error.postValue(ErrorModel("units_zero"))
else
if (auth.currentUser != null) {
val email = auth.currentUser!!.email.toString()
db.collection("users").document(email)
.collection("orders").document(idOrder)
.collection("items").document(idItem).set(
hashMapOf(
"units" to units
)
).addOnSuccessListener {
finish.postValue(true)
}.addOnFailureListener {
error.postValue(ErrorModel("item_not_found"))
}
} else error.postValue(ErrorModel())
}
} | 0 | Kotlin | 0 | 0 | 7d0b135a10a3738b0f35d6c90c7335df2196f547 | 2,721 | virtual-shop | The Unlicense |
processors/db-processor/src/main/kotlin/net/corda/processors/db/internal/reconcile/db/HostedIdentityReconciler.kt | corda | 346,070,752 | false | {"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.processors.db.internal.reconcile.db
import net.corda.crypto.cipher.suite.KeyEncodingService
import net.corda.crypto.client.CryptoOpsClient
import net.corda.crypto.core.CryptoTenants.P2P
import net.corda.crypto.core.ShortHash
import net.corda.data.certificates.CertificateUsage
import net.corda.data.crypto.wire.CryptoSigningKey
import net.corda.data.p2p.HostedIdentityEntry
import net.corda.data.p2p.HostedIdentitySessionKeyAndCert
import net.corda.db.connection.manager.DbConnectionManager
import net.corda.lifecycle.LifecycleCoordinatorFactory
import net.corda.lifecycle.LifecycleCoordinatorName
import net.corda.membership.certificate.client.CertificatesResourceNotFoundException
import net.corda.membership.certificate.client.DbCertificateClient
import net.corda.membership.certificates.toPemCertificateChain
import net.corda.membership.datamodel.HostedIdentityEntity
import net.corda.membership.datamodel.HostedIdentitySessionKeyInfoEntity
import net.corda.reconciliation.Reconciler
import net.corda.reconciliation.ReconcilerFactory
import net.corda.reconciliation.ReconcilerReader
import net.corda.reconciliation.ReconcilerWriter
import net.corda.reconciliation.VersionedRecord
import net.corda.utilities.VisibleForTesting
import net.corda.utilities.debug
import net.corda.v5.base.exceptions.CordaRuntimeException
import net.corda.virtualnode.HoldingIdentity
import net.corda.virtualnode.read.VirtualNodeInfoReadService
import net.corda.virtualnode.toAvro
import net.corda.virtualnode.toCorda
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.stream.Stream
import javax.persistence.EntityManager
@Suppress("LongParameterList")
class HostedIdentityReconciler(
private val coordinatorFactory: LifecycleCoordinatorFactory,
dbConnectionManager: DbConnectionManager,
private val reconcilerFactory: ReconcilerFactory,
private val reconcilerReader: ReconcilerReader<String, HostedIdentityEntry>,
private val reconcilerWriter: ReconcilerWriter<String, HostedIdentityEntry>,
private val dbClient: DbCertificateClient,
private val cryptoOpsClient: CryptoOpsClient,
private val keyEncodingService: KeyEncodingService,
private val virtualNodeInfoReadService: VirtualNodeInfoReadService,
) : ReconcilerWrapper {
private companion object {
val logger: Logger = LoggerFactory.getLogger(this::class.java.enclosingClass)
val dependencies = setOf(
LifecycleCoordinatorName.forComponent<DbConnectionManager>(),
LifecycleCoordinatorName.forComponent<CryptoOpsClient>(),
LifecycleCoordinatorName.forComponent<VirtualNodeInfoReadService>(),
)
}
@VisibleForTesting
internal var dbReconciler: DbReconcilerReader<String, HostedIdentityEntry>? = null
@VisibleForTesting
internal var reconciler: Reconciler? = null
private val reconciliationContextFactory = {
Stream.of(ClusterReconciliationContext(dbConnectionManager))
}
override fun updateInterval(intervalMillis: Long) {
logger.debug { "Config reconciliation interval set to $intervalMillis ms" }
if (dbReconciler == null) {
dbReconciler =
DbReconcilerReader(
coordinatorFactory,
String::class.java,
HostedIdentityEntry::class.java,
dependencies,
reconciliationContextFactory,
::getAllHostedIdentities
).also {
it.start()
}
}
if (reconciler == null) {
reconciler = reconcilerFactory.create(
dbReader = dbReconciler!!,
kafkaReader = reconcilerReader,
writer = reconcilerWriter,
keyClass = String::class.java,
valueClass = HostedIdentityEntry::class.java,
reconciliationIntervalMs = intervalMillis,
forceInitialReconciliation = true,
).also { it.start() }
} else {
logger.info("Updating Hosted Identity ${Reconciler::class.java.name}")
reconciler!!.updateInterval(intervalMillis)
}
}
override fun stop() {
dbReconciler?.stop()
dbReconciler = null
reconciler?.stop()
reconciler = null
}
private fun getAllHostedIdentities(context: ReconciliationContext): Stream<VersionedRecord<String, HostedIdentityEntry>> {
val entityManager = context.getOrCreateEntityManager()
val identityQuery = entityManager.criteriaBuilder.createQuery(HostedIdentityEntity::class.java)
val identityRoot = identityQuery.from(HostedIdentityEntity::class.java)
identityQuery.select(identityRoot)
val hostedIdentityEntities = entityManager.createQuery(identityQuery).resultList.map {
it.toHostedIdentityEntry(entityManager)
}
return hostedIdentityEntities.stream().toVersionedRecords()
}
private fun HostedIdentityEntity.toHostedIdentityEntry(em: EntityManager): HostedIdentityEntry {
val holdingId = ShortHash.of(holdingIdentityShortHash)
val keysQuery = em.criteriaBuilder.createQuery(HostedIdentitySessionKeyInfoEntity::class.java)
val keysRoot = keysQuery.from(HostedIdentitySessionKeyInfoEntity::class.java)
keysQuery
.select(keysRoot)
.where(
em.criteriaBuilder.equal(
keysRoot.get<String>(HostedIdentitySessionKeyInfoEntity::holdingIdentityShortHash.name),
holdingIdentityShortHash
)
)
val (preferredKey, alternateKeys) = em.createQuery(keysQuery).resultList.let { allKeys ->
val preferred = allKeys.firstOrNull { it.sessionKeyId == preferredSessionKeyAndCertificate }
?: throw CordaRuntimeException("Failed to retrieve preferred session key for '$holdingIdentityShortHash'.")
preferred.toSessionKeyAndCertificate() to (allKeys - preferred).map { it.toSessionKeyAndCertificate() }
}
val (tlsKeyTenantId, tlsCertificateHoldingId) = when (useClusterLevelTlsCertificateAndKey) {
true -> P2P to null
false -> holdingIdentityShortHash to holdingId
}
val tlsCertificates = getCertificates(
tlsCertificateHoldingId, CertificateUsage.P2P_TLS, tlsCertificateChainAlias
)
return HostedIdentityEntry.newBuilder()
.setHoldingIdentity(getHoldingIdentity(holdingId).toAvro())
.setTlsCertificates(tlsCertificates)
.setTlsTenantId(tlsKeyTenantId)
.setPreferredSessionKeyAndCert(preferredKey)
.setAlternativeSessionKeysAndCerts(alternateKeys)
.setVersion(version)
.build()
}
private fun Stream<HostedIdentityEntry>.toVersionedRecords(): Stream<VersionedRecord<String, HostedIdentityEntry>> {
return map {
object : VersionedRecord<String, HostedIdentityEntry> {
override val version = it.version
override val isDeleted = false
override val key = it.holdingIdentity.toCorda().shortHash.value
override val value = it
}
}
}
private fun HostedIdentitySessionKeyInfoEntity.toSessionKeyAndCertificate(): HostedIdentitySessionKeyAndCert {
val holdingId = ShortHash.of(holdingIdentityShortHash)
val sessionCertificate = sessionCertificateAlias?.let {
getCertificates(
holdingId, CertificateUsage.P2P_SESSION, it
)
}
return HostedIdentitySessionKeyAndCert.newBuilder()
.setSessionPublicKey(
getSessionKey(
holdingId.value,
ShortHash.of(sessionKeyId),
)
)
.setSessionCertificates(sessionCertificate)
.build()
}
private fun getCertificates(
certificateHoldingId: ShortHash?,
usage: CertificateUsage,
certificateChainAlias: String,
): List<String> {
val certificateChain = dbClient.retrieveCertificates(
certificateHoldingId, usage, certificateChainAlias
)
return certificateChain?.toPemCertificateChain()
?: throw CertificatesResourceNotFoundException("Certificate with '$certificateChainAlias' not found.")
}
private fun getSessionKey(
tenantId: String,
sessionKeyId: ShortHash,
): String {
return cryptoOpsClient.lookupKeysByIds(tenantId, listOf(sessionKeyId)).firstOrNull()
?.toPem()
?: throw CertificatesResourceNotFoundException("Can not find session key for $tenantId")
}
private fun CryptoSigningKey.toPem(): String {
return keyEncodingService.encodeAsString(
keyEncodingService.decodePublicKey(
this.publicKey.array()
)
)
}
private fun getHoldingIdentity(holdingIdentityShortHash: ShortHash): HoldingIdentity {
return virtualNodeInfoReadService.getByHoldingIdentityShortHash(holdingIdentityShortHash)?.holdingIdentity
?: throw CordaRuntimeException("No virtual node with ID $holdingIdentityShortHash")
}
}
| 11 | Kotlin | 27 | 69 | d478e119ab288af663910f9a2df42a7a7b9f5bce | 9,331 | corda-runtime-os | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.