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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kotlin/src/main/kotlin/io/georocket/index/generic/DefaultMetaIndexerFactory.kt
|
georocket
| 58,203,049
| false
|
{"Kotlin": 521913, "Rust": 314054, "JavaScript": 21650, "ANTLR": 4307, "Dockerfile": 1356, "HTML": 1139}
|
package io.georocket.index.generic
import io.georocket.index.DatabaseIndex
import io.georocket.index.MetaIndexerFactory
import io.georocket.query.*
import io.georocket.query.QueryCompiler.MatchPriority
import io.georocket.query.QueryPart.ComparisonOperator.EQ
/**
* Factory for [DefaultMetaIndexer] instances
* @author Michel Kraemer
*/
class DefaultMetaIndexerFactory : MetaIndexerFactory {
override fun createIndexer() = DefaultMetaIndexer()
override fun getQueryPriority(queryPart: QueryPart): MatchPriority {
return when (queryPart) {
is StringQueryPart, is LongQueryPart, is DoubleQueryPart -> MatchPriority.SHOULD
}
}
override fun compileQuery(queryPart: QueryPart): IndexQuery {
return when (queryPart) {
is StringQueryPart, is LongQueryPart, is DoubleQueryPart -> {
val key = queryPart.key
if (key == null) {
// match values of all fields regardless of their name
val search = queryPart.value
Or(
Contains("tags", search),
ElemMatchExists("props", "value" to search)
)
} else {
val r = ElemMatchCompare(
"props",
listOf("key" to key),
Compare("value", queryPart.value, queryPart.comparisonOperator ?: EQ),
)
if (queryPart.comparisonOperator == EQ && queryPart.key == "correlationId") {
Or(r, Compare("correlationId", queryPart.value, EQ))
} else {
r
}
}
}
}
}
override fun getDatabaseIndexes(indexedFields: List<String>): List<DatabaseIndex> = listOf(
DatabaseIndex.Array("tags", "tags_array"),
DatabaseIndex.ElemMatchExists("props", listOf("value", "key"), "props_elem_match_exists"),
*indexedFields.map { fieldName ->
DatabaseIndex.ElemMatchCompare(
"props",
"key",
"value",
fieldName,
"props_${fieldName}_elem_match_cmp"
)
}.toTypedArray(),
DatabaseIndex.Eq("correlationId", "correlation_id_eq"),
DatabaseIndex.StartsWith("layer", "layer_starts_with")
)
}
| 1
|
Kotlin
|
27
| 74
|
5f84037bbc3f16d146823338070fc98de67dec6a
| 2,105
|
georocket
|
Apache License 2.0
|
dlang/psi-impl/src/main/kotlin/io/github/intellij/dlanguage/psi/ext/DLanguageReferenceExpressionImplMixin.kt
|
intellij-dlanguage
| 27,922,930
| false
|
{"D": 1787183, "Kotlin": 1068238, "Java": 834373, "Lex": 22913, "DTrace": 3220, "HTML": 1386, "Makefile": 457}
|
package io.github.intellij.dlanguage.psi.ext
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import io.github.intellij.dlanguage.psi.DLanguageReferenceExpression
import io.github.intellij.dlanguage.psi.interfaces.DTypedElement
import io.github.intellij.dlanguage.psi.references.GenericExpressionElementReference
import io.github.intellij.dlanguage.psi.types.DAliasType
import io.github.intellij.dlanguage.psi.types.DArrayType
import io.github.intellij.dlanguage.psi.types.DAssociativeArrayType
import io.github.intellij.dlanguage.psi.types.DPointerType
import io.github.intellij.dlanguage.psi.types.DPrimitiveType
import io.github.intellij.dlanguage.psi.types.DType
import io.github.intellij.dlanguage.psi.types.DUnknownType
import io.github.intellij.dlanguage.psi.types.UserDefinedDType
import io.github.intellij.dlanguage.utils.EnumDeclaration
import io.github.intellij.dlanguage.utils.FunctionDeclaration
abstract class DLanguageReferenceExpressionImplMixin(node: ASTNode) : ASTWrapperPsiElement(node),
DLanguageReferenceExpression {
override fun getDType(): DType? {
val result = reference?.resolve()
if (result is DTypedElement) {
return result.dType
}
if (result is FunctionDeclaration) {
return result.returnDType
}
val qualifierType = expression?.dType
// Compiler defined property? : https://dlang.org/spec/property.html
val dtype = when (identifier?.text) {
"init" -> qualifierType
"alignof",
"sizeof" -> DPrimitiveType.fromText("uint") // TODO actually it is a size_t
"mangleof",
"stringof" -> DArrayType(DPrimitiveType.fromText("char"), null) // TODO it is immutable(char) array
else -> null
}
if (dtype != null) {
return dtype
}
val arrayType = getArrayType(qualifierType)
val assocArrayType = getAssociativeArrayType(qualifierType)
if (arrayType != null) {
return when (identifier?.text) {
"dup" -> arrayType
"idup" -> arrayType // TODO idup return an immutable array
"length" -> DPrimitiveType.fromText("int") // TODO size_t
"ptr" -> DPointerType(arrayType)
"tupleof" -> if (arrayType.isFixedSize()) DUnknownType() else null // TODO replace DUnknownType by tuple
"capacity" -> if (arrayType.isFixedSize()) null else DPrimitiveType.fromText("int") // TODO size_t
else -> null
}
} else if (assocArrayType != null) {
return when (identifier?.text) {
"length" -> DPrimitiveType.fromText("int") // TODO size_t
"dup" -> assocArrayType
"keys" -> DArrayType(assocArrayType.keyType, null)
"values" -> DArrayType(assocArrayType.valueType, null)
"rehash" -> assocArrayType
"clear" -> DPrimitiveType.fromText("void")
"byKey" -> DUnknownType() // TODO
"byValue" -> DUnknownType() // TODO
"byKeyValue" -> DUnknownType() // TODO
// TODO get, require and update which are functions
else -> null
}
} else if (isEnumType(qualifierType)) {
return when (identifier?.text) {
"init" -> qualifierType
"min",
"max" -> DPrimitiveType.fromText("int") // TODO actually need to fetch the real type from the enum
else -> null
}
}
// TODO handle all compiler defined properties (class, struct, vector)
return null
}
private fun getArrayType(type: DType?): DArrayType? {
if (type is DPointerType) return getArrayType(type.base)
if (type is DAliasType) return getArrayType(type.aliased)
return type as? DArrayType
}
private fun getAssociativeArrayType(type: DType?): DAssociativeArrayType? {
if (type is DPointerType) return getAssociativeArrayType(type.base)
if (type is DAliasType) return getAssociativeArrayType(type.aliased)
return type as? DAssociativeArrayType
}
private fun isEnumType(type: DType?): Boolean {
if (type is DPointerType) return isEnumType(type.base)
if (type is DAliasType) return isEnumType(type.aliased)
return (type is UserDefinedDType && type.resolve() is EnumDeclaration)
}
override fun getReference(): PsiReference? {
val referenceElement: PsiElement
val range: TextRange
if (identifier != null) {
referenceElement = identifier!!
range = referenceElement.textRangeInParent
} else if (templateInstance != null && templateInstance!!.identifier != null) {
referenceElement = templateInstance!!.identifier!!
range = referenceElement.textRangeInParent.shiftRight(templateInstance!!.startOffsetInParent)
}
else {
return null
}
return GenericExpressionElementReference(this, range, expression, referenceElement.text)
}
}
| 160
|
D
|
51
| 328
|
298d1db45d2b35c1715a1b1b2e1c548709101f05
| 5,313
|
intellij-dlanguage
|
MIT License
|
src/main/kotlin/com/osm/gradle/plugins/wrapper/builder/OptionBuilder.kt
|
sam-osamu
| 183,719,935
| false
| null |
package com.osm.gradle.plugins.wrapper.builder
import com.osm.gradle.plugins.wrapper.builder.command.ICommandOption
class OptionBuilder {
private val options = ArrayList<ICommandOption>()
fun put(option: ICommandOption): OptionBuilder {
if (!option.multiple) {
removeIfMatchType(option.javaClass)
}
options.add(option)
return this
}
fun removeIfMatchType(option: Class<*>): OptionBuilder {
options.removeIf { option == it.javaClass }
return this
}
fun toList(): List<String> {
return options
.map { it.toList() }
.filter { it.isNotEmpty() }
.flatten()
.toList()
}
override fun toString(): String {
return toList().joinToString(" ")
}
}
| 0
|
Kotlin
|
0
| 0
|
1943303f1bbe3ed2a3cd192c766bb0faee1e2be2
| 802
|
rustic
|
MIT License
|
http4k-core/src/main/kotlin/org/http4k/template/Templates.kt
|
danschultz
| 118,152,914
| true
|
{"Kotlin": 770332, "JavaScript": 133258, "Java": 49492, "Shell": 6237, "HTML": 2067, "CSS": 568}
|
package org.http4k.template
typealias TemplateRenderer = (ViewModel) -> String
/**
* Supported template implementations for templating engine implementations
*/
interface Templates {
/**
* Loads and caches templates from the compiled classpath
*
* @param baseClasspathPackage the root package to load from (defaults to root)
*/
fun CachingClasspath(baseClasspathPackage: String = ""): TemplateRenderer
/**
* Load and caches templates from a file path
*
* @param baseTemplateDir the root path to load templates from
*/
fun Caching(baseTemplateDir: String = "./"): TemplateRenderer
/**
* Hot-reloads (no-caching) templates from a file path
*
* @param baseTemplateDir the root path to load templates from
*/
fun HotReload(baseTemplateDir: String = "./"): TemplateRenderer
}
/**
* Compose a TemplateRenderer with another, so you can fall back.
*/
fun TemplateRenderer.then(that: TemplateRenderer): TemplateRenderer = {
try {
this(it)
} catch (e: ViewNotFound) {
that(it)
}
}
| 0
|
Kotlin
|
0
| 0
|
7ea0046f8a4d256fe490de5d44ea6c5fc3ad2aa6
| 1,093
|
http4k
|
Apache License 2.0
|
backend/data/src/main/kotlin/io/tolgee/component/CurrentDateProvider.kt
|
tolgee
| 303,766,501
| false
|
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
|
package io.tolgee.component
import io.tolgee.development.OnDateForced
import io.tolgee.model.ForcedServerDateTime
import io.tolgee.util.Logging
import io.tolgee.util.executeInNewTransaction
import io.tolgee.util.logger
import jakarta.persistence.EntityManager
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.ApplicationEventPublisher
import org.springframework.context.annotation.Lazy
import org.springframework.context.annotation.Scope
import org.springframework.data.auditing.AuditingHandler
import org.springframework.data.auditing.DateTimeProvider
import org.springframework.stereotype.Component
import org.springframework.transaction.PlatformTransactionManager
import java.sql.Timestamp
import java.time.Duration
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
import java.util.*
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
class CurrentDateProvider(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") @Lazy
auditingHandler: AuditingHandler,
private val entityManager: EntityManager,
private val applicationEventPublisher: ApplicationEventPublisher,
private val transactionManager: PlatformTransactionManager,
) : Logging, DateTimeProvider {
var forcedDate: Date? = null
set(value) {
if (field != value) {
logger.debug("Forcing date to: {} (old value: {})", value, field)
field = value
updateEntity(field)
applicationEventPublisher.publishEvent(OnDateForced(this, value))
}
}
private fun updateEntity(forcedDate: Date?) {
executeInNewTransaction(transactionManager) {
getServerTimeEntity()?.let { entity ->
forcedDate?.let { date ->
entity.time = date
entityManager.persist(entity)
} ?: let { _ ->
entityManager.remove(entity)
}
} ?: let {
forcedDate?.let { date ->
entityManager.persist(
ForcedServerDateTime().apply {
time = date
},
)
}
}
}
}
init {
forcedDate = getForcedTime()
auditingHandler.setDateTimeProvider(this)
}
fun forceDateString(
dateString: String,
pattern: String = "yyyy-MM-dd HH:mm:ss z",
) {
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern(pattern)
val parsed = ZonedDateTime.parse(dateString, formatter).toInstant().toEpochMilli()
forcedDate = Date(parsed)
}
fun move(duration: Duration) {
forcedDate = Date(date.time + duration.toMillis())
}
val date: Date
get() {
return forcedDate ?: Date()
}
override fun getNow(): Optional<TemporalAccessor> {
return Optional.of(date.toInstant())
}
private fun getServerTimeEntity(): ForcedServerDateTime? =
entityManager.createQuery(
"select st from ForcedServerDateTime st where st.id = 1",
ForcedServerDateTime::class.java,
).resultList.singleOrNull()
private fun getForcedTime(): Timestamp? =
entityManager.createNativeQuery(
"select st.time from public.forced_server_date_time st where st.id = 1",
Timestamp::class.java,
).resultList.singleOrNull() as Timestamp?
}
| 170
|
TypeScript
|
188
| 1,837
|
6e01eec3a19c151a6e0aca49e187e2d0deef3082
| 3,254
|
tolgee-platform
|
Apache License 2.0
|
model/src/main/java/io/km/todo/model/User.kt
|
pickerX
| 506,482,283
| false
| null |
package io.km.todo.model
/**
* common user
*
* @author pengfei.huang
* create on 2022/6/23
*/
data class User(
val id: Int,
val login: String,
val pwd: String,
val avatar: String,
)
| 0
|
Kotlin
|
0
| 0
|
05f934776c3b87c6bc91df9ebbc57863c78ffa99
| 204
|
todo-shit
|
Apache License 2.0
|
reverse-string/src/main/kotlin/ReverseString.kt
|
sirech
| 189,113,734
| false
| null |
fun reverse(input: String): String {
val middle = input.length / 2
val acc = input.toCharArray()
(0 until middle).zip((input.length - 1).downTo(middle)).forEach { (left, right) ->
val tmp = input[left]
acc[left] = acc[right]
acc[right] = tmp
}
return String(acc)
}
| 0
|
Kotlin
|
0
| 0
|
253f4636f16f83f6b96f21532a3ca8fa16dace46
| 311
|
exercism-kotlin
|
MIT License
|
app/src/main/kotlin/io/github/bsfranca2/athena/RestExceptionHandler.kt
|
bsfranca2
| 275,465,877
| false
| null |
package io.github.bsfranca2.athena
import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException
import io.github.bsfranca2.athena.adapter.ExceptionAdapter
import io.github.bsfranca2.athena.adapter.ValidationExceptionAdapter
import io.github.bsfranca2.athena.dto.response.ErrorResponseDto
import io.github.bsfranca2.athena.exception.BadRequestException
import io.github.bsfranca2.athena.exception.EntityNotFoundException
import io.github.bsfranca2.athena.exception.UnauthorizedResourceException
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.context.request.WebRequest
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
import java.time.LocalDateTime
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
class RestExceptionHandler : ResponseEntityExceptionHandler() {
@ExceptionHandler(EntityNotFoundException::class)
fun handleEntityNotFound(ex: EntityNotFoundException): ResponseEntity<ErrorResponseDto> {
return ResponseEntity(ExceptionAdapter.toResponse(ex), HttpStatus.BAD_REQUEST)
}
override fun handleMethodArgumentNotValid(ex: MethodArgumentNotValidException, headers: HttpHeaders, status: HttpStatus, request: WebRequest): ResponseEntity<Any> {
return ResponseEntity(ValidationExceptionAdapter.toResponse(ex), HttpStatus.BAD_REQUEST)
}
override fun handleHttpMessageNotReadable(ex: HttpMessageNotReadableException, headers: HttpHeaders, status: HttpStatus, request: WebRequest): ResponseEntity<Any> {
val cause = ex.cause
if (cause is MissingKotlinParameterException) {
val parameter = getParameterNull(cause)
val errorResponse = ValidationExceptionAdapter.singleNotNullToResponse(parameter)
return ResponseEntity(errorResponse, status)
}
return ResponseEntity(ExceptionAdapter.toResponse(ex), status);
}
@ExceptionHandler(MethodArgumentTypeMismatchException::class)
fun handleMethodArgumentTypeMismatch(ex: MethodArgumentTypeMismatchException): ResponseEntity<Any> {
return ResponseEntity(ExceptionAdapter.toResponse(ex), HttpStatus.BAD_REQUEST)
}
private fun getParameterNull(cause: MissingKotlinParameterException): String {
val name = cause.path.fold("") { jsonPath, ref ->
val suffix = when {
ref.index > -1 -> "[${ref.index}]"
else -> ".${ref.fieldName}"
}
(jsonPath + suffix).removePrefix(".")
}
return name
}
@ExceptionHandler(UnauthorizedResourceException::class)
fun handleUnauthorizedResource(ex: UnauthorizedResourceException): ResponseEntity<Any> {
return ResponseEntity(ExceptionAdapter.toResponse(ex), HttpStatus.FORBIDDEN)
}
@ExceptionHandler(BadRequestException::class)
fun handleBadRequest(ex: BadRequestException): ResponseEntity<Any> {
return ResponseEntity(ExceptionAdapter.toResponse(ex), HttpStatus.BAD_REQUEST)
}
}
| 11
|
Kotlin
|
0
| 0
|
8a048990c1a6ebf23a567490476fc7e41fdadc71
| 3,546
|
Athena
|
MIT License
|
graph/graph-application/src/main/kotlin/eu/tib/orkg/prototype/statements/spi/PaperRepository.kt
|
TIBHannover
| 197,416,205
| false
|
{"Kotlin": 2518665, "Cypher": 215872, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240}
|
package eu.tib.orkg.prototype.statements.spi
import eu.tib.orkg.prototype.statements.domain.model.PaperResourceWithPath
import eu.tib.orkg.prototype.statements.domain.model.ThingId
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
interface PaperRepository {
fun findAllPapersRelatedToResource(id: ThingId, pageable: Pageable): Page<PaperResourceWithPath>
}
| 0
|
Kotlin
|
2
| 5
|
ce3f24748dd2d9c06e6125e033bc7ae83122925f
| 406
|
orkg-backend
|
MIT License
|
app/src/main/java/com/xquare/xquare_android/feature/home/HomeViewModel.kt
|
team-xquare
| 478,925,648
| false
| null |
package com.xquare.xquare_android.feature.home
import com.xquare.domain.entity.meal.MealEntity
import com.xquare.domain.entity.user.HomeUserEntity
import com.xquare.domain.usecase.meal.FetchTodayMealUseCase
import com.xquare.domain.usecase.point.FetchDormitoryPointUseCase
import com.xquare.domain.usecase.user.FetchUserSimpleDataUseCase
import com.xquare.xquare_android.base.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val fetchTodayMealUseCase: FetchTodayMealUseCase,
private val fetchUserSimpleDataUseCase: FetchUserSimpleDataUseCase,
) : BaseViewModel<HomeViewModel.Event>() {
private val _userSimpleData = MutableStateFlow(HomeUserEntity("", "", 0, 0))
val userSimpleData: StateFlow<HomeUserEntity> = _userSimpleData
private val _todayMeal = MutableStateFlow(
MealEntity(
emptyList(),
emptyList(),
emptyList(),
"", "", ""
))
val todayMeal: StateFlow<MealEntity> = _todayMeal
fun fetchUserSimpleData() {
execute(
job = { fetchUserSimpleDataUseCase.execute(Unit) },
onSuccess = { _userSimpleData.tryEmit(it) },
onFailure = { }
)
}
fun fetchTodayMeal() {
execute(
job = {
fetchTodayMealUseCase.execute(Unit)
},
onSuccess = {
it.collect { meal ->
_todayMeal.tryEmit(meal)
}
},
onFailure = {
}
)
}
sealed class Event {
}
}
| 20
|
Kotlin
|
1
| 13
|
6b80af309999b7c8e239aead440c438c1958020a
| 1,753
|
xquare-android
|
MIT License
|
docs-examples/example-kotlin/src/test/kotlin/io/micronaut/rabbitmq/docs/headers/ProductClient.kt
|
rajselvaraj-arch
| 359,574,256
| true
|
{"INI": 3, "Gradle": 7, "Shell": 1, "Markdown": 3, "Batchfile": 1, "Text": 1, "Ignore List": 1, "AsciiDoc": 32, "YAML": 9, "Java": 120, "XML": 6, "Groovy": 76, "Kotlin": 55}
|
package io.micronaut.rabbitmq.docs.headers
// tag::imports[]
import io.micronaut.rabbitmq.annotation.Binding
import io.micronaut.rabbitmq.annotation.RabbitClient
import io.micronaut.context.annotation.Requires
import io.micronaut.messaging.annotation.Header
import io.micronaut.messaging.annotation.Headers
import io.micronaut.messaging.MessageHeaders
// end::imports[]
@Requires(property = "spec.name", value = "HeadersSpec")
// tag::clazz[]
@RabbitClient
@Headers(
Header(name = "x-product-sealed", value = "true"), // <1>
Header(name = "productSize", value = "large")
)
interface ProductClient {
@Binding("product")
@Headers(
Header(name = "x-product-count", value = "10"), // <2>
Header(name = "productSize", value = "small")
)
fun send(data: ByteArray)
@Binding("product")
fun send(@Header productSize: String?, // <3>
@Header("x-product-count") count: Long,
data: ByteArray)
@Binding("product")
fun send(messageHeaders: MessageHeaders, // <4>
data: ByteArray)
}
// end::clazz[]
| 0
|
Java
|
0
| 0
|
5387922b1172d5c23dd81be3d55099a078300f53
| 1,092
|
micronaut-rabbitmq
|
Apache License 2.0
|
domain/storedetail/src/main/java/com/hankki/domain/storedetail/entity/StoreDetailNicknameEntity.kt
|
Team-Hankki
| 816,081,730
| false
|
{"Kotlin": 558108}
|
package com.hankki.domain.storedetail.entity
data class StoreDetailNicknameEntity(
val nickname: String,
val profileImageUrl: String
)
| 8
|
Kotlin
|
0
| 38
|
314a86e55e89d6a7d567ae4b0e633c6b34892b91
| 144
|
hankki-android
|
Apache License 2.0
|
app/src/main/java/com/zdcx/pos/data/local/Converters.kt
|
zengjianxiong
| 469,991,609
| false
|
{"Kotlin": 83849, "Java": 13788}
|
package com.zdcx.pos.data.local
import androidx.room.TypeConverter
import java.util.*
class Converters {
@TypeConverter
fun fromTimestamp(value: Long?): Date? = value?.let { Date(value) }
@TypeConverter
fun dateToTimestamp(value: Date?): Long? = value?.time
}
| 0
|
Kotlin
|
0
| 0
|
4dcc2b5b76e8854470fdbb14664f52fedbddb0a3
| 278
|
POS
|
Apache License 2.0
|
src/app/api/src/main/kotlin/yapp/be/apiapplication/system/config/FilterConfiguration.kt
|
YAPP-Github
| 634,126,325
| false
|
{"Kotlin": 460704, "HTML": 7648}
|
package yapp.be.apiapplication.system.config
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.Ordered
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter
import yapp.be.apiapplication.system.filter.servlet.WrappedHttpServletFilter
@Configuration
class FilterConfiguration {
@Bean
fun wrappedHttpServletFilter(): FilterRegistrationBean<WrappedHttpServletFilter> {
val registration = FilterRegistrationBean(WrappedHttpServletFilter())
registration.order = Ordered.LOWEST_PRECEDENCE
registration.addUrlPatterns("/*")
return registration
}
@Bean
fun setResourceUrlEncodingFilter(): FilterRegistrationBean<ResourceUrlEncodingFilter> {
val registration: FilterRegistrationBean<ResourceUrlEncodingFilter> = FilterRegistrationBean(ResourceUrlEncodingFilter())
registration.order = Ordered.LOWEST_PRECEDENCE - 1
registration.addUrlPatterns("/*")
return registration
}
}
| 0
|
Kotlin
|
1
| 7
|
ebee64b31bfe77106c0212605ba5e0f9b9957879
| 1,137
|
DangleDangle-server
|
Apache License 2.0
|
app/src/debug/java/br/com/wakim/eslpodclient/DebugApplication.kt
|
wakim
| 52,843,851
| false
|
{"Git Config": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 1, "XML": 63, "JSON": 1, "Kotlin": 84}
|
package br.com.wakim.eslpodclient
import com.facebook.stetho.Stetho
class DebugApplication : Application() {
override fun onCreate() {
super.onCreate()
Stetho.initializeWithDefaults(this)
}
}
| 0
|
Kotlin
|
1
| 6
|
a92dad2832f087f97fcbf9b2b7973a31efde551c
| 218
|
esl-pod-client
|
Apache License 2.0
|
app/src/main/java/com/ruskaof/myt/common/UilFunctions.kt
|
ruskaof
| 481,254,879
| false
|
{"Kotlin": 121946}
|
package com.ruskaof.myt.common
import java.time.LocalDateTime
fun niceTime(localDateTime: LocalDateTime): String {
var hour = localDateTime.hour.toString()
var minute = localDateTime.minute.toString()
if (hour.length < 2) hour = "0$hour"
if (minute.length < 2) minute = "0$minute"
return "$hour:$minute"
}
fun niceTime(hour1: Int, minute1: Int): String {
var hour = hour1.toString()
var minute = minute1.toString()
if (hour.length < 2) hour = "0$hour"
if (minute.length < 2) minute = "0$minute"
return "$hour:$minute"
}
| 0
|
Kotlin
|
0
| 1
|
89dd595f4b547ff4c6afb71fc5703943bdbd4918
| 564
|
MYT
|
Apache License 2.0
|
app/src/main/java/com/lukieoo/compassnetguru/di/DestinationModule.kt
|
Lukieoo
| 308,153,457
| false
| null |
package com.lukieoo.compassnetguru.di
import android.content.Context
import com.lukieoo.compassnetguru.utils.MathematicalOperations
import com.lukieoo.compassnetguru.utils.DestinationHolder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Singleton
@Module
@InstallIn(ApplicationComponent::class)
object DestinationModule {
@Singleton
@Provides
fun provideMathematicalOperations(): MathematicalOperations {
return MathematicalOperations()
}
@Singleton
@Provides
fun provideTargetHolder(mathematicalOperations:MathematicalOperations,@ApplicationContext context: Context): DestinationHolder {
return DestinationHolder(mathematicalOperations,context)
}
}
| 0
|
Kotlin
|
0
| 1
|
5af9a253f7914e0a695bf6730c4b2d6b4b7196ca
| 862
|
CompassNetguru
|
MIT License
|
shared-domain/src/main/kotlin/dev/programadorthi/shared/domain/provider/SharedTextProvider.kt
|
programadorthi
| 352,469,479
| false
| null |
package dev.programadorthi.shared.domain.provider
interface SharedTextProvider {
fun noInternetConnection(): String
fun somethingWrong(): String
}
| 0
|
Kotlin
|
1
| 23
|
f62cb1811621ec328c567bbe6bd61b02890ad46a
| 156
|
android-super-app
|
MIT License
|
app/src/main/java/com/cngal/app/repository/PeripheryRepository.kt
|
CnGal
| 648,083,407
| false
|
{"Kotlin": 421043}
|
package com.cngal.app.repository
import com.cngal.app.model.article.ArticleModel
import com.cngal.app.model.periphery.PeripheryModel
import com.cngal.app.service.ArticleService
import com.cngal.app.service.PeripheryService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
class PeripheryRepository
{
companion object
{
fun getPeripheryData(id: Long): Flow<PeripheryModel> = flow {
val data = PeripheryService.instance.getPeripheryData(id)
emit(data)
}.flowOn(Dispatchers.IO)
}
}
| 0
|
Kotlin
|
1
| 2
|
6703376adae97557825f39d7492a04b3aee55729
| 631
|
cngal-jetpack-app
|
MIT License
|
interoperable/src/nonJvmNonJsMain/kotlin/kollections/internal/AbstractIterable.kt
|
aSoft-Ltd
| 537,964,662
| false
|
{"Kotlin": 132802}
|
package kollections.internal
import kollections.Iterable
import kotlin.collections.count as kCount
actual abstract class AbstractIterable<out E> : Iterable<E>
| 0
|
Kotlin
|
1
| 9
|
8887905f6bd7c0984f6cb95b1f23db4038785bdd
| 160
|
kollections
|
MIT License
|
protocol/src/main/kotlin/com/github/traderjoe95/mls/protocol/message/padding/deterministic/Padme.kt
|
Traderjoe95
| 757,448,383
| false
|
{"Kotlin": 1143520}
|
package com.github.traderjoe95.mls.protocol.message.padding.deterministic
import com.github.traderjoe95.mls.protocol.message.padding.PaddingStrategy
import com.github.traderjoe95.mls.protocol.util.log2
import com.github.traderjoe95.mls.protocol.util.wipe
data object Padme : PaddingStrategy {
override fun applyPadding(content: ByteArray): ByteArray =
ByteArray(calculatePaddedLength(content.size)).also {
content.copyInto(it)
content.wipe()
}
private fun calculatePaddedLength(size: Int): Int {
if (size == 1) return 1
val e = log2(size)
val s = log2(e) + 1
val lastBits = e - s
val bitMask = (1 shl lastBits) - 1
return (size + bitMask) and bitMask.inv()
}
}
| 0
|
Kotlin
|
0
| 1
|
70bd7110b08713ae9425bbad6e6da13fa6fed8f3
| 717
|
mls-kotlin
|
MIT License
|
emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/RepeatListener.kt
|
vanniktech
| 53,511,222
| false
| null |
/*
* Copyright (C) 2016 - <NAME>, <NAME>, <NAME> and contributors
*
* 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.vanniktech.emoji
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
internal class RepeatListener(
private val initialInterval: Long,
private val normalInterval: Long,
private val clickListener: View.OnClickListener,
) : OnTouchListener {
private val handler = Handler(Looper.getMainLooper())
private var downView: View? = null
private val handlerRunnable: Runnable = object : Runnable {
override fun run() {
if (downView != null) {
handler.removeCallbacksAndMessages(downView)
handler.postAtTime(this, downView, SystemClock.uptimeMillis() + normalInterval)
clickListener.onClick(downView)
}
}
}
init {
require(!(initialInterval < 0 || normalInterval < 0)) { "negative interval" }
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(view: View, motionEvent: MotionEvent) = when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> {
handler.removeCallbacks(handlerRunnable)
handler.postAtTime(handlerRunnable, downView, SystemClock.uptimeMillis() + initialInterval)
downView = view
downView?.isPressed = true
clickListener.onClick(view)
true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_OUTSIDE -> {
handler.removeCallbacksAndMessages(downView)
downView?.isPressed = false
downView = null
true
}
else -> false
}
}
| 5
| null |
292
| 1,537
|
60efe8bbfe4f2900e424c4cdddf01dcc59e0b4bb
| 2,220
|
Emoji
|
Apache License 2.0
|
app/src/main/java/kr/co/witches/simplememo/ui/main/MainRepository.kt
|
juu124
| 554,712,442
| false
| null |
package kr.co.witches.simplememo.ui.main
class MainRepository {
// 메인에서 처리되는 데이터 - Api
}
| 0
|
Kotlin
|
0
| 0
|
78cac3d52b36fec125b01d49ca9b868ec38eca56
| 96
|
SimpleMemo
|
MIT License
|
src/main/kotlin/com/uchuhimo/konf/source/json/JsonProvider.kt
|
slomkowski
| 190,100,394
| true
|
{"Gradle Kotlin DSL": 4, "INI": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "YAML": 3, "Markdown": 1, "Java": 7, "Kotlin": 123, "TOML": 1, "XML": 1, "JSON": 1, "Java Properties": 1}
|
/*
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.uchuhimo.konf.source.json
import com.fasterxml.jackson.databind.ObjectMapper
import com.uchuhimo.konf.source.Provider
import com.uchuhimo.konf.source.Source
import java.io.InputStream
import java.io.Reader
/**
* Provider for JSON source.
*/
object JsonProvider : Provider {
override fun fromReader(reader: Reader): Source =
JsonSource(ObjectMapper().readTree(reader))
override fun fromInputStream(inputStream: InputStream): Source =
JsonSource(ObjectMapper().readTree(inputStream))
}
| 0
|
Kotlin
|
0
| 0
|
b26fa3a5dcae17ec92ec63e585881a33a6514cba
| 1,146
|
konf
|
Apache License 2.0
|
kstatemachine/src/test/kotlin/ru/nsk/kstatemachine/CrossLevelTransitionTest.kt
|
mahendran-sakkarai
| 351,689,452
| true
|
{"Kotlin": 107638}
|
package ru.nsk.kstatemachine
import io.mockk.verifySequence
import org.junit.jupiter.api.Test
class CrossLevelTransitionTest {
/**
* Currently transition from self to self is same as targetless transition
*/
@Test
fun selfToSelf() {
val callbacks = mockkCallbacks()
lateinit var state1: State
val machine = createStateMachine {
logger = StateMachine.Logger { println(it) }
state1 = initialState("1") {
callbacks.listen(this)
transitionOn<SwitchEvent> {
targetState = { state1 }
callbacks.listen(this)
}
}
}
verifySequenceAndClear(callbacks) { callbacks.onEntryState(state1) }
machine.processEvent(SwitchEvent)
verifySequence { callbacks.onTriggeredTransition(SwitchEvent) }
}
@Test
fun selfToSelfWithChildren() {
val callbacks = mockkCallbacks()
lateinit var state1: State
lateinit var state11: State
lateinit var state12: State
val machine = createStateMachine {
logger = StateMachine.Logger { println(it) }
state1 = initialState("1") {
callbacks.listen(this)
transitionOn<SwitchEventL1> {
targetState = { state1 }
callbacks.listen(this)
}
state11 = initialState("11") {
callbacks.listen(this)
transitionOn<SwitchEventL2> {
targetState = { state12 }
callbacks.listen(this)
}
}
state12 = state("12") {
callbacks.listen(this)
}
}
}
verifySequenceAndClear(callbacks) {
callbacks.onEntryState(state1)
callbacks.onEntryState(state11)
}
machine.processEvent(SwitchEventL2)
verifySequenceAndClear(callbacks) {
callbacks.onTriggeredTransition(SwitchEventL2)
callbacks.onExitState(state11)
callbacks.onEntryState(state12)
}
machine.processEvent(SwitchEventL1)
verifySequence {
callbacks.onTriggeredTransition(SwitchEventL1)
callbacks.onExitState(state12)
callbacks.onEntryState(state11)
}
}
@Test
fun parentToChild() {
val callbacks = mockkCallbacks()
lateinit var state1: State
lateinit var state11: State
lateinit var state12: State
val machine = createStateMachine {
logger = StateMachine.Logger { println(it) }
state1 = initialState("1") {
callbacks.listen(this)
transitionOn<SwitchEvent> {
targetState = { state12 }
callbacks.listen(this)
}
state11 = initialState("11") {
callbacks.listen(this)
}
state12 = state("12") {
callbacks.listen(this)
}
}
}
verifySequenceAndClear(callbacks) {
callbacks.onEntryState(state1)
callbacks.onEntryState(state11)
}
machine.processEvent(SwitchEvent)
verifySequence {
callbacks.onTriggeredTransition(SwitchEvent)
callbacks.onExitState(state11)
callbacks.onEntryState(state12)
}
}
@Test
fun toNeighborsChild() {
val callbacks = mockkCallbacks()
lateinit var state1: State
lateinit var state21: State
lateinit var state2: State
val machine = createStateMachine {
state1 = initialState("1") {
callbacks.listen(this)
transitionOn<SwitchEvent> {
targetState = { state21 }
callbacks.listen(this)
}
}
state2 = state("2") {
callbacks.listen(this)
state21 = initialState("21") {
callbacks.listen(this)
}
}
}
verifySequenceAndClear(callbacks) { callbacks.onEntryState(state1) }
machine.processEvent(SwitchEvent)
verifySequence {
callbacks.onTriggeredTransition(SwitchEvent)
callbacks.onExitState(state1)
callbacks.onEntryState(state2)
callbacks.onEntryState(state21)
}
}
@Test
fun childToNeighborsChild() {
val callbacks = mockkCallbacks()
lateinit var state1: State
lateinit var state11: State
lateinit var state2: State
lateinit var state22: State
val machine = createStateMachine {
state1 = initialState("1") {
callbacks.listen(this)
state11 = initialState("11") {
callbacks.listen(this)
transitionOn<SwitchEvent> {
targetState = { state22 }
callbacks.listen(this)
}
}
}
state2 = state("2") {
callbacks.listen(this)
initialState("21") {
callbacks.listen(this)
}
state22 = state("22") {
callbacks.listen(this)
}
}
}
verifySequenceAndClear(callbacks) {
callbacks.onEntryState(state1)
callbacks.onEntryState(state11)
}
machine.processEvent(SwitchEvent)
verifySequence {
callbacks.onTriggeredTransition(SwitchEvent)
callbacks.onExitState(state11)
callbacks.onExitState(state1)
callbacks.onEntryState(state2)
callbacks.onEntryState(state22)
}
}
@Test
fun childToTopLevelNeighbor() {
val callbacks = mockkCallbacks()
lateinit var state1: State
lateinit var state11: State
lateinit var state2: State
val machine = createStateMachine {
state1 = initialState("1") {
callbacks.listen(this)
state11 = initialState("11") {
callbacks.listen(this)
transitionOn<SwitchEvent> {
targetState = { state2 }
callbacks.listen(this)
}
}
}
state2 = state("2") {
callbacks.listen(this)
}
}
verifySequenceAndClear(callbacks) {
callbacks.onEntryState(state1)
callbacks.onEntryState(state11)
}
machine.processEvent(SwitchEvent)
verifySequence {
callbacks.onTriggeredTransition(SwitchEvent)
callbacks.onExitState(state11)
callbacks.onExitState(state1)
callbacks.onEntryState(state2)
}
}
@Test
fun childToParent() {
val callbacks = mockkCallbacks()
lateinit var state1: State
lateinit var state11: State
lateinit var state12: State
val machine = createStateMachine {
logger = StateMachine.Logger { println(it) }
state1 = initialState("1") {
callbacks.listen(this)
state11 = initialState("11") {
callbacks.listen(this)
transitionOn<SwitchEvent> {
targetState = { state12 }
callbacks.listen(this)
}
}
state12 = state("12") {
callbacks.listen(this)
transitionOn<SwitchEvent> {
targetState = { state1 }
callbacks.listen(this)
}
}
}
}
verifySequenceAndClear(callbacks) {
callbacks.onEntryState(state1)
callbacks.onEntryState(state11)
}
machine.processEvent(SwitchEvent)
verifySequenceAndClear(callbacks) {
callbacks.onTriggeredTransition(SwitchEvent)
callbacks.onExitState(state11)
callbacks.onEntryState(state12)
}
machine.processEvent(SwitchEvent)
verifySequence {
callbacks.onTriggeredTransition(SwitchEvent)
callbacks.onExitState(state12)
callbacks.onEntryState(state11)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7c5986549be84045329c8fb75a8a295e2a6cac5b
| 8,673
|
kstatemachine
|
MIT License
|
lib/kpindex/src/main/java/se/gustavkarlsson/skylight/android/lib/kpindex/KpIndexBody.kt
|
gustavkarlsson
| 128,669,768
| false
| null |
package se.gustavkarlsson.skylight.android.lib.kpindex
import kotlinx.serialization.Serializable
@Serializable
internal data class KpIndexBody(val value: Double)
| 0
|
Kotlin
|
3
| 6
|
c3b1b53a73a1de97ad0e6e9645ddae1df5815800
| 164
|
skylight-android
|
MIT License
|
src/main/kotlin/com/kotlindiscord/bot/config/spec/ChannelsSpec.kt
|
iLemonBr
| 304,703,681
| true
|
{"Kotlin": 108236, "Groovy": 1393, "Python": 1305, "Dockerfile": 356}
|
package com.kotlindiscord.bot.config.spec
import com.uchuhimo.konf.ConfigSpec
/**
* A class representing the `channels` section of the configuration.
*
* This is used by Konf, and will not need to be accessed externally.
*/
object ChannelsSpec : ConfigSpec() {
/** Configured bot-commands channel ID. **/
val botCommands by required<Long>()
/** Configured alerts channel ID. **/
val alerts by required<Long>()
/** Configured action-log channel ID. **/
val actionLog by required<Long>()
/** Configured moderator-log channel ID. **/
val moderatorLog by required<Long>()
/** Configured verification channel ID. **/
val verification by required<Long>()
}
| 0
| null |
0
| 0
|
4f194b0ed2aa03761d968e97147704aa84d8c942
| 701
|
bot
|
MIT License
|
eth/wallet/src/commonMain/kotlin/kosh/eth/wallet/Wallet.kt
|
niallkh
| 855,100,709
| false
|
{"Kotlin": 1813876, "Swift": 594}
|
package kosh.eth.wallet
import com.ionspin.kotlin.bignum.integer.BigInteger
import com.ionspin.kotlin.bignum.integer.toBigInteger
import kosh.eth.abi.Eip712
import kosh.eth.abi.Value
import kosh.eth.abi.coder.eip712StructHash
import kosh.eth.abi.keccak256
import kosh.eth.abi.rlp.toRlp
import kosh.eth.wallet.transaction.Signature
import kosh.eth.wallet.transaction.SignatureData
import kosh.eth.wallet.transaction.Transaction
import kosh.eth.wallet.transaction.concat
import kosh.eth.wallet.transaction.encode
import kosh.eth.wallet.transaction.vbg
import okio.Buffer
import okio.ByteString
import okio.ByteString.Companion.decodeHex
public object Wallet {
public fun generatePrivateKey(): ByteArray = ByteArray(32).fillSecureRandom()
public fun address(
privkey: PrivateKey,
): Value.Address = Secp256k1.publicKey(privkey.key)
.substring(1, 65)
.keccak256()
.substring(12, 32)
.let(Value.Address::invoke)
public fun verify(
privkey: PrivateKey,
data: ByteString,
messageHash: ByteString,
): Boolean = Secp256k1.verify(
signature = data,
messageHash = messageHash,
publicKey = Secp256k1.publicKey(privkey.key)
)
public fun recover(
signature: ByteString,
messageHash: ByteString,
): Value.Address = Secp256k1.recover(
signature = signature.substring(0, 64),
messageHash = messageHash,
recId = signature[64].toInt() - 27
)
.substring(1, 65)
.keccak256()
.substring(12, 32)
.let(Value.Address::invoke)
public fun personalSign(
privateKey: PrivateKey,
message: ByteString,
): Signature = personalHash(message)
.let { hash ->
Signature(
data = sign(privateKey, hash).concat(),
messageHash = hash,
)
}
public fun personalHash(message: ByteString): ByteString = Buffer().apply {
writeUtf8("\u0019Ethereum Signed Message:\n")
writeUtf8(message.size.toString())
write(message)
}
.readByteString()
.keccak256()
public fun signTypeData(
privateKey: PrivateKey,
eip712: Eip712,
): Signature = typeDataHash(eip712).let { hash ->
Signature(
data = sign(privateKey, hash).concat(),
messageHash = hash,
)
}
public fun typeDataHash(eip712: Eip712): ByteString = Buffer().apply {
write("1901".decodeHex())
write(eip712.domain.type.eip712StructHash(eip712.domain.value))
write(eip712.message.type.eip712StructHash(eip712.message.value))
}.readByteString()
.keccak256()
public fun signTransaction(
privateKey: PrivateKey,
transaction: Transaction,
): Signature = when (transaction) {
is Transaction.Legacy -> signLegacyTransaction(transaction, privateKey)
is Transaction.Type1559 -> sign1559Transaction(transaction, privateKey)
}
public fun signLegacyTransaction(
transaction: Transaction.Legacy,
privateKey: PrivateKey,
): Signature {
val chainId = BigInteger.fromULong(transaction.chainId)
val signature = SignatureData(v = chainId.toRlp.bytes)
val hash = transaction.encode(signature = signature).keccak256()
val signatureData = sign(
privkey = privateKey,
messageHash = hash
)
val v = signatureData.vbg() + chainId.shl(1) + 8.toBigInteger()
return Signature(
data = transaction.encode(signature = signatureData.copy(v = v.toRlp.bytes)),
messageHash = hash,
)
}
public fun sign1559Transaction(
transaction: Transaction.Type1559,
privateKey: PrivateKey,
): Signature {
val hash = transaction.encode(signatureData = null).keccak256()
val signatureData = sign(
privkey = privateKey,
messageHash = hash
)
return encode1559Transaction(transaction, signatureData.concat())
}
public fun encode1559Transaction(
transaction: Transaction.Type1559,
signature: ByteString,
): Signature {
val hash = transaction.encode(signatureData = null).keccak256()
return Signature(
data = transaction.encode(
signatureData = SignatureData(
r = signature.substring(0, 32),
s = signature.substring(32, 64),
v = signature.substring(64, 65)
)
),
messageHash = hash,
)
}
}
| 0
|
Kotlin
|
0
| 3
|
f48555a563dfee5b07184771a6c94c065765d570
| 4,644
|
kosh
|
MIT License
|
kotlin/kotlin-snippets/src/main/kotlin/Main.kt
|
d-kicinski
| 387,271,157
| false
| null |
import kotlin.reflect.KFunction1
fun customRun(f: () -> Unit): Unit {
println("Calling function")
f.invoke()
}
fun customRunWithParameter(f: (Int) -> Unit, p: Int): Unit {
println("Calling function with parameter $p")
f.invoke(p)
}
fun plainOldFunction(): Unit {
println("Plain old function")
}
fun plainOldFunctionWithParameter(p: Int): Unit {
println("Plain old function with parameter: $p")
}
class Foo(s: String) {
val name: String = s
fun hello(): Unit {
println("Hello, $name")
}
fun hello(s: String): Unit {
println("Hello, $s")
}
}
fun Foo.hi(): Unit {
println("Hi, $name")
}
fun main(args: Array<String>) {
// run(::plainOldFunction)
// run { println("run { println() }") }
// customRun(::plainOldFunction)
// customRun { println("Lambda expression passed in {}") }
// customRunWithParameter(::plainOldFunctionWithParameter, 42)
// customRunWithParameter({p: Int -> println("Lambda expression with parameter $p")}, 24)
//
//
// val foo = Foo("World")
// foo.hello()
// foo.hello("World2 ")
// foo.hi()
// forLoop()
// println(whenExpression(8))
// println(whenExpression(42))
// iterateOverRanges()
// collections()
// scopeFunctions()
}
| 0
|
Kotlin
|
0
| 0
|
1a5620538fe360ffd76beb721ac8781deffe8ff8
| 1,269
|
jvm-snippets
|
Apache License 2.0
|
eth/proposals/src/commonMain/kotlin/kosh/eth/proposals/call.kt
|
niallkh
| 855,100,709
| false
|
{"Kotlin": 1813876, "Swift": 594}
|
package kosh.eth.proposals
import kosh.eth.abi.Value.Address
import kosh.eth.rpc.Web3Provider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
public suspend fun <T : Any> Web3Provider.call(
target: Address,
call: FunctionCall<T>,
): T = withContext(Dispatchers.Default) {
val result = call(
target = target,
data = call.encode()
)
call.decode(result)
}
public suspend fun <T : Any> Web3Provider.call(
call: ContractCall<T>,
blockTag: Web3Provider.BlockTag = Web3Provider.BlockTag.Latest,
): Result<T> = withContext(Dispatchers.Default) {
val result = call(
target = call.target,
data = call.encode(),
blockTag = blockTag,
)
call.decodeResult(result)
call.result
}
| 0
|
Kotlin
|
0
| 3
|
f48555a563dfee5b07184771a6c94c065765d570
| 779
|
kosh
|
MIT License
|
sdk-scrapper/src/main/kotlin/io/github/wulkanowy/sdk/scrapper/timetable/CompletedLesson.kt
|
wulkanowy
| 138,756,468
| false
|
{"Kotlin": 496844, "HTML": 63871}
|
package io.github.wulkanowy.sdk.scrapper.timetable
import io.github.wulkanowy.sdk.scrapper.adapter.CustomDateAdapter
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
@Serializable
data class CompletedLesson(
@SerialName("Data")
@Serializable(with = CustomDateAdapter::class)
val date: LocalDateTime,
@SerialName("NrLekcji")
val number: Int = 0,
@SerialName("Przedmiot")
val subject: String? = "",
@SerialName("Temat")
val topic: String? = "",
@SerialName("Nauczyciel")
val teacher: String? = "",
val teacherSymbol: String? = "",
@SerialName("Zastepstwo")
val substitution: String? = "",
@SerialName("Nieobecnosc")
val absence: String? = "",
@SerialName("ZasobyPubliczne")
val resources: String? = "",
)
| 5
|
Kotlin
|
6
| 28
|
fc3ecf7257a377f8cb62ca6cf67ce626449bbf89
| 850
|
sdk
|
Apache License 2.0
|
langsmith-java-core/src/test/kotlin/com/langsmith/api/models/PublicLatestRunRetrieveParamsTest.kt
|
langchain-ai
| 774,515,765
| false
|
{"Kotlin": 2288977, "Shell": 1314, "Dockerfile": 305}
|
// File generated from our OpenAPI spec by Stainless.
package com.langsmith.api.models
import com.langsmith.api.models.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class PublicLatestRunRetrieveParamsTest {
@Test
fun createPublicLatestRunRetrieveParams() {
PublicLatestRunRetrieveParams.builder()
.shareToken("<PASSWORD>")
.build()
}
@Test
fun getPathParam() {
val params =
PublicLatestRunRetrieveParams.builder()
.shareToken("<PASSWORD>")
.build()
assertThat(params).isNotNull
// path param "shareToken"
assertThat(params.getPathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")
// out-of-bound path param
assertThat(params.getPathParam(1)).isEqualTo("")
}
}
| 1
|
Kotlin
|
0
| 2
|
922058acd6e168f6e1db8d9e67a24850ab7e93a0
| 863
|
langsmith-java
|
Apache License 2.0
|
src/main/kotlin/com/replmc/replcraft/Replcraft.kt
|
SkyfallWasTaken
| 861,218,847
| false
|
{"Kotlin": 3623, "Java": 520}
|
package com.replmc.replcraft
import com.replmc.replcraft.rpc.RpcServer
import net.fabricmc.api.ModInitializer
import net.minecraft.server.command.CommandManager
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback
import org.slf4j.LoggerFactory
import kotlinx.coroutines.*
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents
object Replcraft : ModInitializer {
private val logger = LoggerFactory.getLogger("Replcraft")
override fun onInitialize() = runBlocking {
// This code runs as soon as Minecraft is in a mod-load-ready state.
// However, some things (like resources) may still be uninitialized.
// Proceed with mild caution.
logger.info("Registering commands")
CommandRegistrationCallback.EVENT.register { dispatcher, registryAccess, environment ->
dispatcher.register(CommandManager.literal("tokens").executes(TokensCommand::execute))
}
launch {
logger.info("Starting RPC server...")
val rpcServer = RpcServer();
ServerLifecycleEvents.SERVER_STOPPING.register({
rpcServer.shutdown()
})
logger.info("Started RPC server")
}
logger.info("Initialized!")
}
}
| 0
|
Kotlin
|
0
| 0
|
c17775b5c43d3c5038ee6096b693a85cfbce88d7
| 1,248
|
replcraft
|
Creative Commons Zero v1.0 Universal
|
k8s-plugin-igor/src/main/kotlin/com/amazon/spinnaker/igor/k8s/controller/GitVersionController.kt
|
nimakaviani
| 287,605,692
| false
| null |
// Copyright 2022 Amazon.com, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.amazon.spinnaker.igor.k8s.controller
import com.amazon.spinnaker.igor.k8s.model.GitVersion
import com.amazon.spinnaker.igor.k8s.service.GitControllerService
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.util.MimeTypeUtils
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(path = ["/git"])
@ConditionalOnProperty("artifacts.gitrepo.enabled")
class GitVersionController(
private val gitControllerService: GitControllerService,
) {
@GetMapping(
path = ["/version/{type}/{project}/{slug}"],
produces = [MimeTypeUtils.APPLICATION_JSON_VALUE]
)
fun getGitVersions(
@PathVariable("type") type: String,
@PathVariable("project") project: String,
@PathVariable("slug") slug: String
): List<GitVersion> {
return gitControllerService.getVersions(type, project, slug)
}
@GetMapping(
path = ["/version/{type}/{project}/{slug}/{version}"],
produces = [MimeTypeUtils.APPLICATION_JSON_VALUE]
)
fun getGitVersion(
@PathVariable("type") type: String,
@PathVariable("project") project: String,
@PathVariable("slug") slug: String,
@PathVariable("version") version: String
): GitVersion {
return gitControllerService.getVersion(type, project, slug, version)
}
}
| 7
|
Kotlin
|
9
| 13
|
2a8bb2191ec71548fc318cdfde79b209707ede91
| 2,181
|
managed-delivery-k8s-plugin
|
Apache License 2.0
|
src/main/kotlin/com/github/darderion/mundaneassignmentpolice/statisticsservice/statistics/GeneralStatistics.kt
|
Darderion
| 410,550,044
| false
| null |
package com.github.darderion.mundaneassignmentpolice.statisticsservice.statistics
data class WordsStatistic(
val wordCount: Int,
val topKWords: Map<String,Int>
)
data class PageStatistic(
val lineCount: Int,
val sectionsStatistic: MutableList<SectionStatistics>
)
class GeneralStatistic(
val wordsStatistic: WordsStatistic,
val pageStatistic: PageStatistic?=null
)
| 13
|
HTML
|
7
| 11
|
06cf4ec09d8fb80fddc157c0e5d75c48bc56d24c
| 391
|
map
|
MIT License
|
feature-governance-api/src/main/java/io/novafoundation/nova/feature_governance_api/presentation/referenda/common/ReferendaStatusFormatter.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425}
|
package io.novafoundation.nova.feature_governance_api.presentation.referenda.common
import io.novafoundation.nova.feature_governance_api.domain.referendum.list.ReferendumStatusType
interface ReferendaStatusFormatter {
fun formatStatus(status: ReferendumStatusType): String
}
| 12
|
Kotlin
|
30
| 50
|
127f8739ca86dc74d006f018237daed0de5095a1
| 281
|
nova-wallet-android
|
Apache License 2.0
|
src/easy/Trees/628-BinaryTreeLevelOrderTraversal.kt
|
diov
| 170,882,024
| false
| null |
val result = mutableListOf<MutableList<Int>>()
fun levelOrder(root: TreeNode?): List<List<Int>> {
fillList(root, 0)
return result
}
fun fillList(node: TreeNode?, depth: Int) {
if (null == node) return
if (result.size == depth) {
result.add(mutableListOf())
}
result[depth].add(node.`val`)
fillList(node.left, depth + 1)
fillList(node.right, depth + 1)
}
| 0
|
Kotlin
|
0
| 0
|
668ef7d6d1296ab4df2654d5a913a0edabc72a3c
| 397
|
leetcode
|
MIT License
|
src/main/kotlin/com/tkroman/kerl/server/epmd/handler/processor/StopRequestProcessor.kt
|
tkroman
| 387,260,318
| false
| null |
package com.tkroman.kerl.server.epmd.handler.processor
import com.tkroman.kerl.server.epmd.InProcessEpmdServer
import io.appulse.epmd.java.core.model.request.Stop
import io.appulse.epmd.java.core.model.response.Response
import io.appulse.epmd.java.core.model.response.StopResult
import java.net.Socket
internal class StopRequestProcessor(
request: Stop,
socket: Socket,
private val server: InProcessEpmdServer
) : RequestProcessor<Stop>(request, socket) {
override fun respond(): Response {
return if (!server.config.unsafe) {
StopResult.NOEXIST
} else {
server.removeNode(request.name)
?.let {
it.close()
StopResult.STOPPED
}
?: StopResult.NOEXIST
}
}
}
| 0
|
Kotlin
|
0
| 0
|
994745ada93a016cfc22460b82f573d80c7b6250
| 813
|
kerl
|
MIT License
|
core/descriptors.jvm/src/org/jetbrains/kotlin/load/java/descriptors/PossiblyExternalAnnotationDescriptor.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.load.java.descriptors
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
interface PossiblyExternalAnnotationDescriptor : AnnotationDescriptor {
val isIdeExternalAnnotation: Boolean
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 450
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/net/jibini/check/entity/behavior/WanderingBehavior.kt
|
zgoethel
| 304,200,179
| false
| null |
package net.jibini.check.entity.behavior
import net.jibini.check.engine.RegisterObject
import net.jibini.check.engine.timing.DeltaTimer
import net.jibini.check.entity.ActionableEntity
import net.jibini.check.entity.Entity
import org.joml.Vector2d
import java.util.Random
import kotlin.math.cos
import kotlin.math.sin
/**
* An example entity behavior which allows characters to wander
* aimlessly around a top-down level.
*
* @author <NAME>
*/
@RegisterObject
class WanderingBehavior : EntityBehavior()
{
/**
* Track the time between wandering logic updates.
*/
private val deltaTimer = DeltaTimer(false)
/**
* Used to generate random movement frequencies.
*/
private val random = Random()
/**
* Keep a map of each entity's movement stateful data.
*/
private val states = mutableMapOf<ActionableEntity, EntityMovementTrack>()
override fun update(entity: Entity)
{
// Only applies to entities which can walk
if (entity !is ActionableEntity)
return
// Get the stateful data of the entity
val entityState = states.getOrPut(entity) { EntityMovementTrack() }
// Update the walking if currently walking
if (entityState.moving)
entity.walk(entityState.movement.x / 3, entityState.movement.y / 3)
// Check if the next movement should start
if (deltaTimer.delta >= entityState.changeAt)
{
// Toggle the moving flag
entityState.moving = !entityState.moving
// Generate a random direction to walk
val angle = Math.toRadians(random.nextInt(360).toDouble())
// and derive x- and y-scalars
entityState.movement.x = cos(angle)
entityState.movement.y = sin(angle)
// Cancel movement in directions which don't make sense
if (entity.movementRestrictions.up)
// Don't move up if character can't move up
entityState.movement.y = minOf(0.0, entityState.movement.y)
if (entity.movementRestrictions.down)
// Don't move down if character can't move down
entityState.movement.y = maxOf(0.0, entityState.movement.y)
if (entity.movementRestrictions.left)
// Don't move left if character can't move left
entityState.movement.x = maxOf(0.0, entityState.movement.x)
if (entity.movementRestrictions.right)
// Don't move right if character can't move right
entityState.movement.x = minOf(0.0, entityState.movement.x)
// Schedule the next time to walk again
entityState.changeAt = deltaTimer.delta + (random.nextInt(40) + 24).toDouble() / 40
}
}
/**
* Tracks a character's stateful movement information.
*/
private class EntityMovementTrack
{
/**
* Whether the character is currently walking.
*/
var moving: Boolean = true
/**
* The direction the character is moving.
*/
var movement = Vector2d()
/**
* The next time at which the character should walk.
*/
var changeAt: Double = 0.0
}
}
| 0
|
Kotlin
|
0
| 2
|
6a71ff5903d3bc0d1c0438235104637359244a63
| 3,268
|
CheckEngine
|
MIT License
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/stepfunctions/tasks/SparkSubmitJobDriverDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.stepfunctions.tasks
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.stepfunctions.tasks.SparkSubmitJobDriver
@Generated
public fun buildSparkSubmitJobDriver(initializer: @AwsCdkDsl
SparkSubmitJobDriver.Builder.() -> Unit): SparkSubmitJobDriver =
SparkSubmitJobDriver.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
e9a0ff020b0db2b99e176059efdb124bf822d754
| 446
|
aws-cdk-kt
|
Apache License 2.0
|
tree-leaf/src/main/kotlin/org/hchery/treeleaf/dao/CryptoDao.kt
|
hchery
| 799,787,264
| false
|
{"Kotlin": 60401, "Java": 11448}
|
package org.hchery.treeleaf.dao
import org.hchery.treeleaf.components.dao.Dao
import org.hchery.treeleaf.db.key.AesKeyDbModel
import org.hchery.treeleaf.db.key.KeyDbModel
import org.springframework.data.repository.NoRepositoryBean
/**
* DATE: 2024/5/29
* AUTHOR: hchery
* URL: https://github.com/hchery
* EMAIL: <EMAIL>
*/
@NoRepositoryBean
interface CryptoKeyDao<T : KeyDbModel> : Dao<T>
interface AesKeyDao : CryptoKeyDao<AesKeyDbModel>
| 0
|
Kotlin
|
0
| 0
|
5a1467c90ac14937a8f3cdbcb5403c264363daa7
| 447
|
TreeLeaf
|
MIT License
|
java/src/main/java/trinsic/services/ProviderServiceKt.kt
|
trinsic-id
| 361,889,702
| false
| null |
package trinsic.services
import com.google.protobuf.InvalidProtocolBufferException
import java.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import trinsic.okapi.DidException
import trinsic.sdk.options.v1.Options
import trinsic.services.provider.v1.*
class ProviderServiceKt(options: Options.ServiceOptions.Builder?) : ServiceBase(options) {
var stub = ProviderGrpcKt.ProviderCoroutineStub(this.channel)
@Throws(InvalidProtocolBufferException::class, DidException::class)
suspend fun createEcosystem(request: CreateEcosystemRequest): CreateEcosystemResponse {
val response: CreateEcosystemResponse =
if (request.name.isNullOrBlank() && request.details.email.isNullOrBlank()) {
stub.createEcosystem(request)
} else {
withMetadata(stub, request).createEcosystem(request)
}
val token = Base64.getUrlEncoder().encodeToString(response.profile.toByteArray())
withContext(Dispatchers.IO) { tokenProvider.save(token).get() }
return response
}
// BEGIN Code generated by protoc-gen-trinsic. DO NOT EDIT.
// target: /home/runner/work/sdk/sdk/java/src/main/java/trinsic/services/ProviderServiceKt.kt
@Throws(InvalidProtocolBufferException::class, DidException::class)
@Deprecated("This will be removed May 1, 2023")
suspend fun updateEcosystem(request: UpdateEcosystemRequest): UpdateEcosystemResponse {
/** This will be removed May 1, 2023 Update an existing ecosystem */
return withMetadata(stub, request).updateEcosystem(request)
}
@Throws(InvalidProtocolBufferException::class, DidException::class)
suspend fun ecosystemInfo(request: EcosystemInfoRequest): EcosystemInfoResponse {
/** Get ecosystem information */
return withMetadata(stub, request).ecosystemInfo(request)
}
@Throws(InvalidProtocolBufferException::class, DidException::class)
@Deprecated("This will be removed May 1, 2023")
suspend fun getPublicEcosystemInfo(
request: GetPublicEcosystemInfoRequest
): GetPublicEcosystemInfoResponse {
/** This will be removed May 1, 2023 Get public ecosystem information about *any* ecosystem */
return withMetadata(stub, request).getPublicEcosystemInfo(request)
}
@Throws(InvalidProtocolBufferException::class, DidException::class)
suspend fun getOberonKey(): GetOberonKeyResponse {
/** Returns the public key being used to create/verify oberon tokens */
val request = GetOberonKeyRequest.newBuilder().build()
return withMetadata(stub, request).getOberonKey(request)
}
@Throws(InvalidProtocolBufferException::class, DidException::class)
suspend fun upgradeDID(request: UpgradeDidRequest): UpgradeDidResponse {
/** Upgrade a wallet's DID from `did:key` to another method */
return withMetadata(stub, request).upgradeDID(request)
}
@Throws(InvalidProtocolBufferException::class, DidException::class)
suspend fun retrieveDomainVerificationRecord(): RetrieveDomainVerificationRecordResponse {
/** Retrieve a random hash TXT that can be used to verify domain ownership */
val request = RetrieveDomainVerificationRecordRequest.newBuilder().build()
return withMetadata(stub, request).retrieveDomainVerificationRecord(request)
}
@Throws(InvalidProtocolBufferException::class, DidException::class)
suspend fun refreshDomainVerificationStatus(): RefreshDomainVerificationStatusResponse {
/** Call to verify domain */
val request = RefreshDomainVerificationStatusRequest.newBuilder().build()
return withMetadata(stub, request).refreshDomainVerificationStatus(request)
}
@Throws(InvalidProtocolBufferException::class, DidException::class)
suspend fun searchWalletConfigurations(
request: SearchWalletConfigurationsRequest
): SearchWalletConfigurationResponse {
/** Search for issuers/providers/verifiers in the current ecosystem */
return withMetadata(stub, request).searchWalletConfigurations(request)
}
// END Code generated by protoc-gen-trinsic. DO NOT EDIT.
}
| 8
|
Dart
|
15
| 25
|
fd7439f78b1bb2c72db8ca91c11659e618974694
| 4,006
|
sdk
|
Apache License 2.0
|
Desenv. de APP I/ExViaCEPRetrofit/app/src/main/java/luiz/souza/exviacepretrofit/Constant.kt
|
LuizzSouza
| 311,798,611
| false
|
{"Kotlin": 84239}
|
package luiz.souza.exviacepretrofit
class Constant {
companion object {
// val PROTOCOL = "http://"
// val BASE_URL = "${PROTOCOL}viacep.com.br/ws/"
val BASE_URL = "http://viacep.com.br/ws/"
}
//http://viacep.com.br/ws/ 01001000/json/
//http://viacep.com.br/ws/ RS/Porto Alegre/Domingos/json/
}
| 0
|
Kotlin
|
0
| 0
|
ec8ca3a3422cd68ea1bf7fc90214659481690431
| 344
|
CursoQI-MOBILE
|
MIT License
|
src/main/java/dev/mikchan/mcnp/votereceiver/core/config/boosted/BoostedYamlConfig.kt
|
MikChanNoPlugins
| 612,779,274
| false
| null |
package dev.mikchan.mcnp.votereceiver.core.config.boosted
import dev.dejvokep.boostedyaml.YamlDocument
import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning
import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings
import dev.dejvokep.boostedyaml.settings.general.GeneralSettings
import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings
import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings
import dev.mikchan.mcnp.votereceiver.core.config.IConfig
import java.io.File
import java.io.InputStream
internal class BoostedYamlConfig(document: File, resource: InputStream) : IConfig {
private val config: YamlDocument = YamlDocument.create(
document,
resource,
GeneralSettings.DEFAULT,
LoaderSettings.builder().setAutoUpdate(true).build(),
DumperSettings.DEFAULT,
UpdaterSettings.builder().setVersioning(BasicVersioning("config-version")).build()
)
override fun reload(): Boolean {
return config.reload()
}
override val port: Int get() = config.getInt("port", 6418)
override val mineServTopKey: String? get() = config.getString("mineserv-top-key")
override val testEnabled: Boolean get() = config.getBoolean("enable-test-route", false)
}
| 0
|
Kotlin
|
0
| 0
|
120da22349a99cfb9bf106c44ec86eb9951917b8
| 1,251
|
VoteReceiver
|
MIT License
|
src/main/kotlin/br/com/skraper/crawler/models/CrawlerContext.kt
|
bruno-ortiz
| 113,599,410
| false
| null |
package br.com.skraper.crawler.models
import br.com.skraper.crawler.adapters.Crawler
import com.github.kittinunf.fuel.httpGet
import java.io.Closeable
import java.util.Collections
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
data class CrawlerContext(
val host: String,
val crawler: Crawler,
val documentURL: String, //TODO: Usar URL como abstração
private val activeTasks: AtomicInteger,
val pagesVisited: AtomicLong = AtomicLong(0),
val itemsCrawled: AtomicLong = AtomicLong(0),
val errors: MutableList<PageError> = Collections.synchronizedList(mutableListOf())
) : Closeable {
init {
activeTasks.incrementAndGet()
}
override fun close() {
activeTasks.decrementAndGet()
}
}
fun main() {
val path = "https://mangalivre.net/categories/series_list.json?page=1&id_category=23"
val (request, response, result) = path.httpGet().responseString()
println(response)
}
| 0
|
Kotlin
|
0
| 9
|
fc0af9caf103bf4321094c4116ab0e9bbffd6fbb
| 1,018
|
skraper
|
MIT License
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/SortBy.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: SortBy
*
* Full name: System`SortBy
*
* SortBy[list, f] sorts the elements of list in the order defined by applying f to each of them.
* SortBy[list, {f , f , …}] breaks ties by successively using the values obtained from the f .
* 1 2 i
* SortBy[list, f, p] sorts the elements of list using the function p to compare the results of applying f to each element.
* Usage: SortBy[f] represents an operator form of SortBy that can be applied to an expression.
*
* Options: None
*
* Attributes: Protected
*
* local: paclet:ref/SortBy
* Documentation: web: http://reference.wolfram.com/language/ref/SortBy.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun sortBy(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("SortBy", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,429
|
mathemagika
|
Apache License 2.0
|
app/src/main/java/sample/arf/clean_architecture_with_mvvm/presentation/viewmodel/MainActivityViewmodel.kt
|
ariarostamifarah
| 362,405,520
| false
| null |
package sample.arf.clean_architecture_with_mvvm.presentation.viewmodel
import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import sample.arf.core.domain.Category
import sample.arf.core.domain.User
import sample.arf.clean_architecture_with_mvvm.framework.Intractors
import sample.arf.clean_architecture_with_mvvm.framework.MainViewModel.MainViewModel
import sample.arf.clean_architecture_with_mvvm.framework.Util.FinishInitialData
import sample.arf.clean_architecture_with_mvvm.framework.db.DatabaseM
import kotlinx.coroutines.*
class MainActivityViewmodel(application: Application, intractors: Intractors) :
MainViewModel(application, intractors) , FinishInitialData {
init {
DatabaseM.finishInitialData =this
}
var users: MutableLiveData<MutableList<User>> = MutableLiveData()
var userById: MutableLiveData<User> = MutableLiveData()
var categorys: MutableLiveData<MutableList<Category>> = MutableLiveData()
var usersByCategoryId: MutableLiveData<MutableList<User>> = MutableLiveData()
var spinnerPos:Int = 0
fun addUser(user: User) = viewModelScope.launch(Dispatchers.IO) { intractors.addUser(user) }
fun updateUser(user: User) =
viewModelScope.launch(Dispatchers.IO) { intractors.updateUser(user) }
fun removeUser(user: User) =
viewModelScope.launch(Dispatchers.IO) { intractors.removeUser(user) }
fun loadAllUser() {
viewModelScope.launch(Dispatchers.Main) {
users.value = async(Dispatchers.IO) { intractors.getAllUser().toMutableList() }.await()
}
}
fun loadUserById(id: Long) {
viewModelScope.launch(Dispatchers.Main) {
userById.value = async(Dispatchers.IO) { intractors.getUserById(id) }.await()
}
}
fun loadAllCategory() {
viewModelScope.launch(Dispatchers.Main){
categorys.value = async(Dispatchers.IO) { intractors.getAllCategory().toMutableList() }.await()
}
}
fun loadUsersByCategoryId(id: Int) {
viewModelScope.launch(Dispatchers.Main) {
usersByCategoryId.value =
async(Dispatchers.IO) { intractors.getUserByCategoryId(id).toMutableList() }.await()
}
}
fun removeCategory(category: Category) {
viewModelScope.launch(Dispatchers.IO) { intractors.removeCategory(category) }
loadAllCategory()
}
override fun loadData() {
loadAllCategory()
}
}
| 0
|
Kotlin
|
0
| 0
|
aa4f26f3dfde5d3c992284d094588580dd3bf0e0
| 2,526
|
Sample_clean_architecture_with_mvvm
|
Apache License 2.0
|
app/src/main/java/com/example/AryaPutraRahma/Home.kt
|
205410025
| 558,495,893
| false
|
{"Kotlin": 14787}
|
package com.example.AryaPutraRahma
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.AryaPutraRahma.databinding.FragmentHomeBinding
/**
* A simple [Fragment] subclass.
* Use the [Home.newInstance] factory method to
* create an instance of this fragment.
*/
class Home : Fragment() {
// menyiapkan variable binding
private var _binding: FragmentHomeBinding? = null
// mnengatur variable binding
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// mengambil dan menampilkan layout
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// menghubungkan Home ke Wisata
binding.button.setOnClickListener {
findNavController().navigate(R.id.action_Home_to_WisataListFragment)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
3bf63db6fb5976d17fba24b77580eaa3227d65a2
| 1,331
|
UTS_Mobile_AryaPutra
|
Apache License 2.0
|
biz/main/src/main/kotlin/io/goooler/demoapp/main/model/MainCommonVhModel.kt
|
Goooler
| 188,988,687
| false
|
{"Kotlin": 153021, "Java": 152}
|
package io.goooler.demoapp.main.model
import io.goooler.demoapp.adapter.rv.core.ISpanSize
import io.goooler.demoapp.adapter.rv.diff.IDiffVhModelType
import io.goooler.demoapp.main.R
sealed interface MainCommonVhModel :
IDiffVhModelType,
ISpanSize {
data class Repo(
val logoUrl: String?,
val content: String?,
val fullName: String,
val shareCount: Int = 0,
) : MainCommonVhModel {
override val viewType: Int = R.layout.main_common_rv_item
override val spanSize: Int = ISpanSize.SPAN_SIZE_SINGLE
override fun isItemTheSame(that: IDiffVhModelType): Boolean =
(that as? Repo)?.fullName == this.fullName
override fun getPayloads(that: IDiffVhModelType): String? = when {
that !is Repo -> null
that.logoUrl != this@Repo.logoUrl -> KEY_LOGO_URL
that.content != this@Repo.content -> KEY_CONTENT
that.shareCount != this@Repo.shareCount -> KEY_SHARE_COUNT
else -> null
}
val shareCountStr: String get() = shareCount.toString()
interface OnEventListener {
fun onContentClick(fullName: String) {}
fun onShareClick(fullName: String) {}
fun onItemClick(item: MainCommonVhModel) {}
}
companion object {
internal const val KEY_LOGO_URL = "logoUrl"
internal const val KEY_CONTENT = "content"
internal const val KEY_SHARE_COUNT = "shareCount"
}
}
data object Empty : MainCommonVhModel {
override val viewType: Int = io.goooler.demoapp.common.R.layout.common_empty_layout
}
data object Error : MainCommonVhModel {
override val viewType: Int = io.goooler.demoapp.common.R.layout.common_error_layout
}
}
| 6
|
Kotlin
|
11
| 70
|
fa50451d91c7e553b1e302ffa0a3e3c0f1012d02
| 1,650
|
DemoApp
|
Apache License 2.0
|
command-core/src/main/kotlin/dev/gimme/command/commands/HelpCommand.kt
|
Gimme
| 315,114,245
| false
| null |
package dev.gimme.command.commands
import dev.gimme.command.Command
import dev.gimme.command.function.FunctionCommand
import dev.gimme.command.function.CommandFunction
/**
* Displays a list of available commands.
*/
class HelpCommand(private val commands: () -> Iterable<Command<*>>) : FunctionCommand<List<HelpCommand.CommandHelp>>("help") {
/** Prints available commands. */
@CommandFunction
fun printCommands(): List<CommandHelp> = commands().map { CommandHelp(it.path(" "), it.usage) }
/**
* Help info about a command.
*
* @property name the name of the command
* @property usage the usage info of the command
*/
data class CommandHelp(
val name: String,
val usage: String,
)
}
| 0
|
Kotlin
|
0
| 0
|
d37da3d45af7f525d3bb1106f2278a39df7685be
| 753
|
command
|
MIT License
|
buildSrc/src/main/kotlin/snippets/SnippetComparison.kt
|
sellmair
| 827,882,526
| false
|
{"Kotlin": 97045}
|
package snippets
import java.io.File
private val sampleRegex = Regex("""\[snippet]: \((.*)\)""")
internal fun findSnippets(
root: File,
docs: Iterable<File>,
sources: Iterable<File>,
): Map<DocSnippet, Snippet?> = buildMap {
docs.forEach { doc ->
putAll(findSnippets(root, doc, sources))
}
}
internal fun findSnippets(
root: File,
doc: File,
sources: Iterable<File>
): Map<DocSnippet, Snippet?> {
val result = mutableMapOf<DocSnippet, Snippet?>()
val text = doc.readText()
val docLines = text.lines()
val endIndices = docLines.mapIndexedNotNull { index, line ->
if (line.trim().startsWith("```")) index else null
}
text.lines().forEachIndexed { docLineIndex, docLine ->
val sampleMatch = sampleRegex.find(docLine) ?: return@forEachIndexed
val docNextLine = docLines.getOrNull(docLineIndex + 1) ?: return@forEachIndexed
if (!docNextLine.trim().startsWith("```kotlin"))
error("e: file://$doc:${docLineIndex +1} Missing ```kotlin after [snippet]")
val docEndLineIndex = endIndices.firstOrNull { endIndex -> endIndex > docLineIndex + 1 }
?: return@forEachIndexed
val sourceFilePath = sampleMatch.groupValues[1]
val sourceFile = root.resolve("snippets/src").resolve(sourceFilePath)
val docSnippet = DocSnippet(
Snippet(
file = doc,
startLineIndex = docLineIndex + 2,
endLineIndex = docEndLineIndex,
lines = docLines.subList(docLineIndex + 2, docEndLineIndex),
text = docLines.subList(docLineIndex + 2, docEndLineIndex).joinToString(System.lineSeparator()),
), sourceFile
)
val sourceSnippetFile = sources.find { it == sourceFile }
if (sourceSnippetFile == null) {
result[docSnippet] = null
return@forEachIndexed
}
val sourceLines = sourceSnippetFile.readText().lines()
val sourceSnippetStartIndex = sourceLines.indexOfFirst { it.trim() == "//Start" }
val sourceSnippetIndent = sourceLines[sourceSnippetStartIndex].takeWhile { it.isWhitespace() }
val sourceSnippetEndIndex = sourceLines.indexOfFirst { it.trim() == "//End" }
val sourceSnippetLines = sourceLines.subList(sourceSnippetStartIndex + 1, sourceSnippetEndIndex)
.joinToString(System.lineSeparator()) { it.removePrefix(sourceSnippetIndent) }
result[docSnippet] = Snippet(
file = sourceSnippetFile,
startLineIndex = sourceSnippetStartIndex + 1,
endLineIndex = sourceSnippetEndIndex,
lines = sourceSnippetLines.lines(),
text = sourceSnippetLines
)
}
return result
}
data class DocSnippet(
val snippet: Snippet,
val expectedSourceFile: File
)
data class Snippet(
val file: File,
val startLineIndex: Int,
val endLineIndex: Int,
val lines: List<String>,
val text: String
)
| 0
|
Kotlin
|
1
| 83
|
133d0ccb8046ce516062daeb43ee6e0142b02b7e
| 3,012
|
evas
|
MIT License
|
src/main/kotlin/org/arxing/bitrisesdk/core/calladapter/ResultCallAdapter.kt
|
Arxing
| 390,718,612
| false
| null |
package org.arxing.bitrisesdk.core.calladapter
import retrofit2.Call
import retrofit2.CallAdapter
import java.lang.reflect.Type
import kotlin.Result
class ResultCallAdapter<T>(
private val clazz: Class<T>
) : CallAdapter<T, Call<Result<T>>> {
override fun responseType(): Type = clazz
override fun adapt(call: Call<T>): Call<Result<T>> {
return ResultCall(call)
}
}
| 0
|
Kotlin
|
0
| 0
|
9639ad21b263fd1ece2383e9ca5a8cd0eb3f2022
| 382
|
Bitrise-Kotlin-Sdk
|
Apache License 2.0
|
app/src/main/java/com/bennyhuo/tieguanyin/sample/KotlinActivity.kt
|
zxxqc
| 143,941,797
| true
|
{"Java": 153717, "Kotlin": 13500, "Shell": 804}
|
package com.bennyhuo.tieguanyin.sample
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.bennyhuo.tieguanyin.annotations.*
import com.bennyhuo.tieguanyin.annotations.GenerateMode.Both
import kotlinx.android.synthetic.main.activity_main.*
/**
* Created by benny on 1/29/18.
*/
@ActivityBuilder(mode = Both,
pendingTransition = PendingTransition(enterAnim = 0, exitAnim = 0),
pendingTransitionOnFinish = PendingTransition(enterAnim = 0, exitAnim = 0),
resultTypes = [(ResultEntity(name = "java", type = Array<String>::class)), (ResultEntity(name = "kotlin", type = IntArray::class))],
flags = [Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT, Intent.FLAG_ACTIVITY_CLEAR_TOP],
categories = [Intent.CATEGORY_APP_BROWSER, Intent.CATEGORY_APP_CALENDAR]
)
class KotlinActivity : AppCompatActivity() {
@Required
var num: Int = 0
@Optional
var java: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setTitle(this.javaClass.simpleName)
openJavaActivity.setOnClickListener {
// JavaActivityBuilder.open(this@KotlinActivity, 1234, true){
// java, kotlin ->
// toast("Result From JavaActivity: java=$java, kotlin=$kotlin")
// }
}
openKotlinActivity.text = "Finish With java='I'm Kotlin!' & kotlin=12"
openKotlinActivity.setOnClickListener {
finishWithResult(arrayOf("I'm Kotlin!"), intArrayOf(12))
}
openGenerateBothActivity.setOnClickListener {
// openGenerateBothActivity(30, "bennyhuo", num = 1234)
num++
}
textView.text = "num=$num, java=$java"
}
}
| 0
|
Java
|
0
| 1
|
bc5e1174e8c3f6fcf32b68e4b31adc852b6247a7
| 1,837
|
TieGuanYin
|
Apache License 2.0
|
src/main/kotlin/com/query/utils/DataOutputStreamExt.kt
|
osrsquery
| 453,886,617
| false
|
{"Kotlin": 183180, "Java": 45630}
|
package com.query.utils
import java.io.DataOutputStream
fun DataOutputStream.writeParams(data : Map<Int, String>) {
writeByte(data.size)
for (entry in data.entries) {
writeByte(if (isObjectInteger(entry.value)) 1 else 0)
writeByte(entry.key shr 16)
writeByte(entry.key shr 8)
writeByte(entry.key)
if (isObjectInteger(entry.value)) {
writeInt(entry.value.toInt())
} else {
writeString(entry.value)
}
}
}
fun DataOutputStream.write24bitInt(content : Int) {
writeByte(content shr 16)
writeByte(content shr 8)
writeByte(content)
}
fun DataOutputStream.writeString(content : String) {
write(content.toByteArray())
writeByte(10)
}
| 1
|
Kotlin
|
3
| 3
|
00d256ae992ebdf2c2301bfb8b9a684aaeee3412
| 742
|
OsrsQuery
|
MIT License
|
module-5/solid-demo/src/main/kotlin/org/data4purpose/soliddemo/config/SecurityConfiguration.kt
|
data4purpose
| 609,145,529
| false
|
{"Kotlin": 23473, "Python": 19017, "JavaScript": 6302, "HTML": 1790, "Starlark": 841, "Shell": 322}
|
package org.data4purpose.soliddemo.config
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest
@EnableWebSecurity
@Configuration
class SecurityConfiguration(
val tokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest>
) : WebSecurityConfigurerAdapter() {
override fun configure(web: WebSecurity?) {
http.authorizeRequests()
.antMatchers("/solid-login", "/solid-login/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login().loginPage("/solid-login")
.and()
.oauth2Client()
}
override fun configure(http: HttpSecurity) {
http.oauth2Login().tokenEndpoint()
.accessTokenResponseClient(tokenResponseClient)
http.logout()
.logoutUrl("/logout")
.deleteCookies("JSESSIONID")
.clearAuthentication(true)
.invalidateHttpSession(true)
}
}
| 0
|
Kotlin
|
0
| 2
|
44c1eb79d753dca7f8e637af0f42bc06426d238a
| 1,498
|
workshop-solid-data-pod
|
Apache License 2.0
|
app/src/main/java/com/biotel/iot/ui/details/recyclerview/model/IBeaconItem.kt
|
pandeypiyush94
| 282,539,893
| false
|
{"Java": 79144, "Kotlin": 39672}
|
package com.biotel.iot.ui.details.recyclerview.model
import com.biotel.iot.ui.common.recyclerview.RecyclerViewItem
import uk.co.alt236.bluetoothlelib.device.beacon.ibeacon.IBeaconManufacturerData
class IBeaconItem(iBeaconData: IBeaconManufacturerData) : RecyclerViewItem {
val major: Int = iBeaconData.major
val minor: Int = iBeaconData.minor
val uuid: String = iBeaconData.uuid
val companyIdentifier: Int = iBeaconData.companyIdentifier
val iBeaconAdvertisement: Int = iBeaconData.iBeaconAdvertisement
val calibratedTxPower: Int = iBeaconData.calibratedTxPower
}
| 1
| null |
1
| 1
|
5e8d9614a90a1c3d40061597e25892f7ef28f0f3
| 589
|
Biotel-IoT
|
Apache License 2.0
|
src/main/kotlin/sample/usecase/SecurityService.kt
|
jkazama
| 145,971,105
| false
| null |
package sample.usecase
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UsernameNotFoundException
import sample.ErrorKeys
import sample.context.security.ActorDetails
import sample.context.security.SecurityAdminService
import sample.context.security.SecurityUserService
import sample.usecase.admin.MasterAdminService
import sample.util.ConvertUtils
import java.util.*
/**
* SpringSecurityのユーザアクセスコンポーネントを定義します。
*/
@Configuration
class SecurityService {
/** 一般利用者情報を提供します。(see SecurityActorFinder) */
@Bean
fun securityUserService(service: AccountService): SecurityUserService =
object : SecurityUserService {
/**
* 以下の手順で利用口座を特定します。
*
* ログインID(全角は半角に自動変換)に合致するログイン情報があるか
* 口座IDに合致する有効な口座情報があるか
*
* 一般利用者には「ROLE_USER」の権限が自動で割り当てられます。
*/
override fun loadUserByUsername(username: String): ActorDetails =
Optional.ofNullable(username)
.map { ConvertUtils.zenkakuToHan(it)!! }
.flatMap {
service.getLoginByLoginId(it).flatMap { login ->
// account to actorDetails
service.getAccount(login.id!!).map { account ->
val authorities = listOf(SimpleGrantedAuthority("ROLE_USER"))
ActorDetails(account.actor(), login.password, authorities)
}
}
}.orElseThrow { UsernameNotFoundException(ErrorKeys.Login) }
}
/** 社内管理向けの利用者情報を提供します。(see SecurityActorFinder) */
@Bean
fun securityAdminService(service: MasterAdminService): SecurityAdminService =
object : SecurityAdminService {
/**
* 以下の手順で社員を特定します。
*
* 社員ID(全角は半角に自動変換)に合致する社員情報があるか
* 社員情報に紐付く権限があるか
*
* 社員には「ROLE_ADMIN」の権限が自動で割り当てられます。
*/
override fun loadUserByUsername(username: String): ActorDetails =
Optional.ofNullable(username)
.map { ConvertUtils.zenkakuToHan(it)!! }
.flatMap { staffId ->
// staff to actorDetails
service.getStaff(staffId).map { staff ->
val authorities = mutableListOf(SimpleGrantedAuthority("ROLE_ADMIN"))
service.findStaffAuthority(staffId).forEach { authorities.add(SimpleGrantedAuthority(it.authority)) }
ActorDetails(staff.actor(), staff.password, authorities)
}
}.orElseThrow({ UsernameNotFoundException(ErrorKeys.Login) })
}
}
| 1
|
Kotlin
|
1
| 7
|
8d03ce29d4988325c0e369c54b9b784071c3da29
| 3,146
|
sample-boot-kotlin
|
MIT License
|
ui/src/main/kotlin/com/wb/ui/compose/molecules/cells/InfoCell.kt
|
waynils
| 756,295,236
| false
|
{"Kotlin": 99166}
|
package com.wb.ui.compose.molecules.cells
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Star
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import com.wb.ui.compose.molecules.card.CardApp
import com.wb.ui.theme.MyAppTheme
import com.wb.ui.utils.LightDarkModeOneDevicePreviews
import com.wb.ui.utils.UIString
import com.wb.ui.utils.toUIString
sealed class AlbumInfoCellData(val info: UIString, val icon: ImageVector) {
data class Title(val title: UIString, val titleIcon: ImageVector = Icons.Default.Info) :
AlbumInfoCellData(info = title, icon = titleIcon)
data class Rank(val rank: UIString, val rankIcon: ImageVector = Icons.Default.Star) :
AlbumInfoCellData(info = rank, icon = rankIcon)
}
@Composable
fun AlbumInfoCell(data: AlbumInfoCellData, modifier: Modifier) {
CardApp(
modifier = modifier,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = data.info.buildString(),
style = MaterialTheme.typography.body1,
color = MaterialTheme.colors.onBackground,
modifier = Modifier.weight(1f)
)
Icon(
imageVector = data.icon,
contentDescription = data.info.buildString(),
tint = MaterialTheme.colors.onBackground,
)
}
}
}
@LightDarkModeOneDevicePreviews
@Composable
private fun InfoCellPreview() {
MyAppTheme {
Surface(Modifier.fillMaxSize()) {
Column(modifier = Modifier) {
AlbumInfoCell(
data = AlbumInfoCellData.Title(
title = "Album title".toUIString(),
),
modifier = Modifier.fillMaxWidth()
)
AlbumInfoCell(
data = AlbumInfoCellData.Rank(
rank = "Rank 1".toUIString(),
),
modifier = Modifier.fillMaxWidth()
)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
57adf7bd499cf1f64633f8c9d427a326208d3c61
| 2,987
|
Album-app
|
Apache License 2.0
|
backend/src/main/kotlin/org/quizmania/question/adapter/out/QuestionJsonFileRepositoryAdapter.kt
|
stoerti
| 639,769,739
| false
|
{"Kotlin": 75245, "TypeScript": 50731, "HTML": 1721, "CSS": 930}
|
package org.quizmania.question.adapter.out
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import jakarta.annotation.PostConstruct
import org.apache.commons.io.FileUtils
import org.quizmania.game.common.Question
import org.quizmania.game.common.QuestionId
import org.quizmania.game.common.QuestionSet
import org.quizmania.game.common.QuestionSetId
import org.quizmania.question.port.out.QuestionRepository
import org.quizmania.question.port.out.QuestionSetRepository
import org.slf4j.LoggerFactory
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.stereotype.Component
import java.nio.charset.Charset
@Component
class QuestionJsonFileRepositoryAdapter : QuestionRepository, QuestionSetRepository {
private val log = LoggerFactory.getLogger(this.javaClass)
internal val objectMapper = jacksonObjectMapper();
internal val questions = mutableMapOf<QuestionId, Question>()
internal val questionSets = mutableMapOf<QuestionSetId, QuestionSet>()
@PostConstruct
fun postConstruct() {
PathMatchingResourcePatternResolver().getResources("classpath:questions/*.json").forEach { resource ->
val json: String = FileUtils.readFileToString(resource.file, Charset.defaultCharset())
val fileQuestions = objectMapper.readValue<List<Question>>(json).map { it.id to it }
log.info("Loaded ${fileQuestions.size} questions from ${resource.filename}")
questions.putAll(fileQuestions)
}
log.info("Loaded ${questions.size} questions into the database")
PathMatchingResourcePatternResolver().getResources("classpath:questionsets/*.json").forEach { resource ->
val json: String = FileUtils.readFileToString(resource.file, Charset.defaultCharset())
val fileQuestionSet = objectMapper.readValue<QuestionSet>(json)
log.info("Loaded ${fileQuestionSet.name} from ${resource.filename}")
questionSets[fileQuestionSet.id] = fileQuestionSet
}
log.info("Loaded ${questionSets.size} questionSets into the database")
}
override fun findQuestionById(questionId: QuestionId): Question? {
return questions[questionId]
}
override fun findQuestionSetById(questionSetId: QuestionSetId): QuestionSet? {
return questionSets[questionSetId]!!
}
override fun findAllQuestionSets(): List<QuestionSet> =
questionSets.values.sortedBy { it.name }
}
| 7
|
Kotlin
|
0
| 2
|
f877459e4765133f58ba545f8f6d5de78bc0e213
| 2,440
|
quizmania
|
MIT License
|
app/src/main/java/com/sagikor/android/jobao/viewmodel/JobViewModel.kt
|
sagiK11
| 362,213,223
| false
| null |
package com.sagikor.android.jobao.viewmodel
import androidx.hilt.Assisted
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.*
import com.sagikor.android.jobao.data.JobDao
import com.sagikor.android.jobao.data.PreferencesHandler
import com.sagikor.android.jobao.data.SortOrder
import com.sagikor.android.jobao.model.Job
import com.sagikor.android.jobao.model.JobStatus
import com.sagikor.android.jobao.ui.activities.ADD_JOB_RESULT_OK
import com.sagikor.android.jobao.ui.activities.EDIT_JOB_RESULT_OK
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
class JobViewModel @ViewModelInject constructor(
private val jobDao: JobDao,
private val preferencesHandler: PreferencesHandler,
@Assisted private val state: SavedStateHandle
) : ViewModel() {
private val TAG = JobViewModel::class.qualifiedName
private val jobsEventsChannel = Channel<JobsEvents>()
val jobsEvent = jobsEventsChannel.receiveAsFlow()
private val actionEventChannel = Channel<ActionEvent>()
val actionEvent = actionEventChannel.receiveAsFlow()
val searchQuery = state.getLiveData("searchQuery", "")
val preferencesFlow = preferencesHandler.preferenceFlow
val jobStatus = state.getLiveData("jobStatus", JobStatus.IN_PROCESS)
private val jobsFlow = combine(
searchQuery.asFlow(),
preferencesFlow
) { query, filteredPreferences ->
Pair(query, filteredPreferences)
}.flatMapLatest { (query, filteredPreferences) ->
jobDao.getFilteredJobs(
query, filteredPreferences.sortOrder, when (filteredPreferences.hideRejected) {
true -> JobStatus.PENDING
else -> JobStatus.REJECTED
}
)
}
val filteredJobs = jobsFlow.asLiveData()
private val allJobsFlow = jobDao.getAllJobs()
val allJobs = allJobsFlow.asLiveData()
private val filteredByStatusFlow = jobStatus.asFlow().flatMapLatest { jobStatus ->
jobDao.getFilteredJobByStatus(jobStatus)
}
val filteredByStatus = filteredByStatusFlow.asLiveData()
fun onSortOrderSelected(sortOrder: SortOrder) {
viewModelScope.launch {
preferencesHandler.updateSortOrder(sortOrder)
}
}
fun onHideRejectedSelected(hideRejected: Boolean) {
viewModelScope.launch {
preferencesHandler.updateHideRejected(hideRejected)
}
}
fun onJobSelected(job: Job) {
viewModelScope.launch {
jobsEventsChannel.send(JobsEvents.NavigateToEditJobScreen(job))
}
}
fun onJobDelete(job: Job) {
viewModelScope.launch {
jobDao.deleteJob(job)
jobsEventsChannel.send(JobsEvents.ShowUndoDeleteJobMessage(job))
}
}
fun onUndoDeleteJob(job: Job) {
viewModelScope.launch {
jobDao.addJob(job)
}
}
fun onAddEditResult(result: Int) {
when (result) {
ADD_JOB_RESULT_OK -> showJobSavedConfirmation(JOB_ADDED)
EDIT_JOB_RESULT_OK -> showJobSavedConfirmation(JOB_EDITED)
}
}
private fun showJobSavedConfirmation(text: String) {
viewModelScope.launch {
jobsEventsChannel.send(JobsEvents.ShowJobSavedConfirmationMessage(text))
}
}
fun onRateUsClick() {
viewModelScope.launch {
actionEventChannel.send(ActionEvent.NavigateToGooglePlayRate)
}
}
fun onSendToMailClick() {
viewModelScope.launch {
actionEventChannel.send(ActionEvent.SendToMailSuccess)
}
}
sealed class JobsEvents {
data class NavigateToEditJobScreen(val job: Job) : JobsEvents()
data class ShowUndoDeleteJobMessage(val job: Job) : JobsEvents()
data class ShowJobSavedConfirmationMessage(val message: String) : JobsEvents()
}
sealed class ActionEvent {
object NavigateToGooglePlayRate : ActionEvent()
object SendToMailSuccess : ActionEvent()
object SendToMailFail : ActionEvent()
}
}
const val JOB_ADDED = "job_added"
const val JOB_EDITED = "job_edited"
const val ADD_EDIT_REQUEST = "add_edit_request"
const val ADD_EDIT_RESULT = "add_edit_result"
| 0
|
Kotlin
|
0
| 0
|
e6d64e0db6efb1cc438a001a6553c3a8ca690375
| 4,350
|
Jobao-Android
|
MIT License
|
backend/src/main/kotlin/com/mobilispect/backend/data/gtfs/GTFSStopDataSource.kt
|
alandovskis
| 502,662,711
| false
|
{"Kotlin": 358105, "Shell": 472, "Swift": 345}
|
package com.mobilispect.backend.data.gtfs
import com.mobilispect.backend.data.stop.Stop
import com.mobilispect.backend.data.stop.StopDataSource
import com.mobilispect.backend.data.stop.StopIDDataSource
import com.mobilispect.backend.util.readTextAndNormalize
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerializationException
import kotlinx.serialization.csv.Csv
import kotlinx.serialization.decodeFromString
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
/**
* A [StopDataSource] that uses a GTFS feed as a source.
*/
@OptIn(ExperimentalSerializationApi::class)
internal class GTFSStopDataSource(private val stopIDDataSource: StopIDDataSource) : StopDataSource {
private val logger = LoggerFactory.getLogger(GTFSStopDataSource::class.java)
override fun stops(root: String, version: String, feedID: String): Result<Collection<Stop>> =
stopIDDataSource.stops(feedID)
.map { stopIDMap ->
return try {
val input = File(root, "stops.txt").readTextAndNormalize()
logger.trace("Input: $input")
val csv = Csv {
hasHeaderRecord = true
ignoreUnknownColumns = true
}
Result.success(csv.decodeFromString<Collection<GTFSStop>>(input).mapNotNull { stop ->
val id = stopIDMap.get(stop.stop_id) ?: return@mapNotNull null
Stop(
_id = id, name = stop.stop_name, version = version
)
})
} catch (e: IOException) {
Result.failure(e)
} catch (e: SerializationException) {
Result.failure(e)
}
}
}
| 3
|
Kotlin
|
0
| 0
|
25955b88c25b87fec7f69d64dd246155c2d17b92
| 1,866
|
mobilispect
|
Apache License 2.0
|
app/src/main/java/com/example/YTBoxing/DetailActivity.kt
|
dcalibri
| 708,411,836
| false
|
{"Kotlin": 16142}
|
package com.example.YTBoxing
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import android.widget.Button
import android.content.Intent
import com.example.YTBoxing.data.Datasource
class DetailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.title = "Detail of Boxers"
setContentView(R.layout.activity_detail)
val NamaBoxerText = intent.getStringExtra("affirmationText")
val imageResourceId = intent.getIntExtra("imageResourceId", 0)
val datasource = Datasource()
val affirmations = datasource.loadAffirmations()
// Here, you can access the additional text from the Affirmation object
val additionalText = getString(affirmations[3].additionalText) // Change the index as needed
//me-Tampilkan ke XML
val detailImage = findViewById<ImageView>(R.id.detail_image)
val detailText = findViewById<TextView>(R.id.detail_text)
val additionalTextView = findViewById<TextView>(R.id.additional_text)
detailText.text = NamaBoxerText
detailImage.setImageResource(imageResourceId)
additionalTextView.text = additionalText
val backButton = findViewById<Button>(R.id.back_to_main_button)
backButton.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9427753ad14520c99589f06fdf1c1e9d8adbf8c0
| 1,557
|
PPBM-02-7708213028-FadhliShafhanLubis
|
MIT License
|
core/src/main/java/com/karntrehan/posts/core/di/AppModule.kt
|
karntrehan
| 93,308,442
| false
| null |
package com.karntrehan.posts.core.di
import android.content.Context
import com.karntrehan.posts.core.networking.AppScheduler
import com.karntrehan.posts.core.networking.Scheduler
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class AppModule(val context: Context) {
@Provides
@Singleton
fun providesContext(): Context {
return context
}
@Provides
@Singleton
fun scheduler(): Scheduler {
return AppScheduler()
}
}
| 0
|
Kotlin
|
98
| 611
|
b22ec155b9ddf831a7670cf216187dde3b0264af
| 498
|
Posts
|
Apache License 2.0
|
src/main/java/org/warfarin/ckyschool/sidecarj/remote/model/CkyschoolProtocolHeader.kt
|
project-warfarin
| 339,115,138
| false
| null |
package org.warfarin.ckyschool.sidecarj.remote.model
import io.netty.buffer.ByteBuf
import kotlin.math.min
data class CkyschoolProtocolHeader(
val magic: Int,
val majorVersion: Byte,
val minorVersion: Byte,
val patchVersion: Byte,
val pluginId: Byte,
val features: List<CkyschoolRemotingFeatures>,
val payloadLength: Long
) {
companion object {
const val RAW_HEADER_LENGTH = 8 + 4 + 4
const val LENGTH_FIELD_SIZE = 4
const val LENGTH_FIELD_OFFSET = 8 + 4
fun fromBytes(input: ByteBuf): CkyschoolProtocolHeader? {
if (input.readableBytes() < RAW_HEADER_LENGTH) {
return null
}
return CkyschoolProtocolHeader(
magic = input.readInt(),
majorVersion = input.readByte(),
minorVersion = input.readByte(),
patchVersion = input.readByte(),
pluginId = input.readByte(),
features = CkyschoolRemotingFeatures.featuresFromInt(input.readInt()),
payloadLength = input.readUnsignedInt()
)
}
}
fun toBytes(output: ByteBuf) {
output.writeInt(magic)
output.writeBytes(byteArrayOf(majorVersion, minorVersion, patchVersion, pluginId))
output.writeInt(CkyschoolRemotingFeatures.featuresToInt(features))
output.writeInt(payloadLength.and(0xFFFFFFFF).toInt())
}
}
enum class CkyschoolRemotingFeatures {
HELO,
PING,
PAYLOAD;
companion object {
fun featuresFromInt(deflated: Int): List<CkyschoolRemotingFeatures> {
// TODO implementation
return listOf()
}
fun featuresToInt(features: List<CkyschoolRemotingFeatures>): Int {
// TODO implementation
return 0
}
}
}
| 0
|
Kotlin
|
0
| 0
|
15d2a22d81d937c79c01ecad51ea0fe2d013331b
| 1,863
|
ckyschool-sidecar-java
|
MIT License
|
falkon-sql-builder-h2/src/main/kotlin/com/jayrave/falkon/sqlBuilders/h2/H2InsertSqlBuilder.kt
|
jayrave
| 65,279,209
| false
| null |
package com.jayrave.falkon.sqlBuilders.h2
import com.jayrave.falkon.sqlBuilders.InsertSqlBuilder
import com.jayrave.falkon.sqlBuilders.common.SimpleInsertSqlBuilder
class H2InsertSqlBuilder : InsertSqlBuilder {
override fun build(tableName: String, columns: Iterable<String>): String {
return SimpleInsertSqlBuilder.build(tableName, columns)
}
}
| 6
|
Kotlin
|
2
| 12
|
ce42d553c578cd8e509bbfd7effc5d56bf3cdedd
| 364
|
falkon
|
Apache License 2.0
|
ui/src/commonMain/kotlin/kosh/ui/component/colors/dynamicColor.kt
|
niallkh
| 855,100,709
| false
|
{"Kotlin": 1942525, "Swift": 25802}
|
package kosh.ui.component.colors
import androidx.compose.material3.ColorScheme
import arrow.core.memoize
import com.ionspin.kotlin.bignum.integer.BigInteger
import com.ionspin.kotlin.bignum.integer.Sign
import com.materialkolor.dynamicColorScheme
import com.materialkolor.hct.Hct
import com.materialkolor.ktx.toColor
import okio.ByteString
val dynamicColorMemo = ::calculateDynamicColor.memoize()
fun dynamicColor(
bytes: ByteString,
isDark: Boolean,
): ColorScheme = calculateDynamicColor(bytes, isDark)
private fun calculateDynamicColor(
bytes: ByteString,
isDark: Boolean,
): ColorScheme {
val hue = BigInteger.fromByteArray(bytes.toByteArray(), Sign.POSITIVE)
.mod(BigInteger(360))
.intValue()
return dynamicColorScheme(
seedColor = Hct.from(hue.toDouble(), 36f.toDouble(), 50f.toDouble()).toColor(),
isDark = isDark,
isAmoled = false,
)
}
| 0
|
Kotlin
|
0
| 3
|
f48555a563dfee5b07184771a6c94c065765d570
| 917
|
kosh
|
MIT License
|
fastpermissions/src/main/java/com/karleinstein/fastpermissions/FastPermission.kt
|
tuannq-0847
| 287,727,055
| false
| null |
package com.karleinstein.fastpermissions
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
object FastPermission {
private var remainingPermissions: List<String> = mutableListOf()
private var permissionListener: PermissionsListener? = null
internal fun destroyPermissionActivity() {
permissionListener = null
}
internal fun getPermissionActivity(activity: Activity) {
Log.d("FastPermissions", "getPermissionActivity: ${remainingPermissions.size}")
if (remainingPermissions.isEmpty()) return
ActivityCompat.requestPermissions(activity, remainingPermissions.toTypedArray(), 8080)
}
internal fun getDeniedPermissions(
deniedPermissions: List<String>,
deniedPermissionsForever: List<String>
) {
deniedPermissions.forEach {
Log.d("FastPermissions", "getDeniedPermissions: $it")
}
deniedPermissionsForever.forEach {
Log.d("FastPermissions", "getDeniedPermissions: $it")
}
if (deniedPermissionsForever.isNotEmpty()) permissionListener?.onPermissionDeniedForever(
deniedPermissionsForever
)
if (deniedPermissions.isNotEmpty()) permissionListener?.onPermissionDenied(
deniedPermissions
)
}
fun check(
activity: Activity,
permissions: List<String>,
permissionListener: PermissionsListener
) {
this.permissionListener = permissionListener
val isAllPermissionsGranted = activity.isPermissionGranted(permissions)
Log.d("FastPermissions", "check: ${isAllPermissionsGranted.first}")
if (isAllPermissionsGranted.first) {
this.permissionListener?.onGranted()
} else {
remainingPermissions = isAllPermissionsGranted.second
startActivityTransparent(activity)
}
}
private fun startActivityTransparent(activity: Activity) {
val intent = Intent(activity, FastPermissionActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
Log.d("karleinstein", "${activity.isDestroyed}")
if (!activity.isDestroyed)
activity.startActivity(intent)
}
private fun Activity.isPermissionGranted(permissions: List<String>): Pair<Boolean, List<String>> {
val remainingPermissions = mutableListOf<String>()
permissions.forEach {
if (ActivityCompat.checkSelfPermission(
this@isPermissionGranted,
it
) != PackageManager.PERMISSION_GRANTED
) {
remainingPermissions.add(it)
}
}
if (remainingPermissions.isNotEmpty()) return Pair(false, remainingPermissions)
return Pair(true, listOf())
}
fun showDialogExplain(
activity: Activity,
title: String,
content: String,
dialogExplainListener: DialogExplainListener
) {
AlertDialog.Builder(activity)
.setMessage(content)
.setTitle(title)
.setPositiveButton("OK") { _, _ ->
dialogExplainListener.onAllowClicked()
}
.show()
}
internal fun onSuccess() {
permissionListener?.onGranted()
}
interface DialogExplainListener {
fun onAllowClicked()
}
interface PermissionsListener {
fun onGranted()
fun onPermissionDeniedForever(deniedPermissionsForever: List<String>)
fun onPermissionDenied(deniedPermissions: List<String>)
}
}
| 0
|
Kotlin
|
0
| 0
|
5ebd7e5c2eb665b6a153758fbc3b1f6447d44922
| 3,766
|
FastPermissions
|
MIT License
|
services/hanke-service/src/main/kotlin/fi/hel/haitaton/hanke/StatusController.kt
|
City-of-Helsinki
| 300,534,352
| false
| null |
package fi.hel.haitaton.hanke
import mu.KotlinLogging
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.jdbc.core.JdbcOperations
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
private val logger = KotlinLogging.logger {}
@RestController
@RequestMapping("/status")
class StatusController(@Autowired private val jdbcOperations: JdbcOperations) {
companion object {
const val QUERY = "SELECT COUNT(*) FROM tormays_central_business_area_polys LIMIT 1"
const val SUCCESS = 1
const val ERROR = 0
}
@GetMapping
fun getStatus(): ResponseEntity<Void> {
val count = getCount()
return if (count == SUCCESS) {
ResponseEntity.ok().build()
} else {
logger.error { "Unexpected count from central business area polys. count=$count" }
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build()
}
}
private fun getCount() =
try {
with(jdbcOperations) { queryForObject(QUERY, Int::class.java) ?: ERROR }
} catch (e: Throwable) {
logger.error(e) { "Error while checking database connection for status endpoint." }
ERROR
}
}
| 6
|
Kotlin
|
4
| 1
|
8f5d9dd7af0f78b8f19598c484ae657c26f3f9b8
| 1,454
|
haitaton-backend
|
MIT License
|
plugin/src/main/kotlin/eu/kakde/sonatypecentral/SonatypeCentralPublishExtension.kt
|
ani2fun
| 759,937,099
| false
|
{"Kotlin": 36627}
|
package eu.kakde.sonatypecentral
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.publish.VersionMappingStrategy
import org.gradle.api.publish.maven.MavenPom
import javax.inject.Inject
open class SonatypeCentralPublishExtension
@Inject
constructor(objectFactory: ObjectFactory) {
val groupId: Property<String> = objectFactory.property(String::class.java)
val artifactId: Property<String> = objectFactory.property(String::class.java)
val version: Property<String> = objectFactory.property(String::class.java)
val publishingType: Property<String> = objectFactory.property(String::class.java)
val componentType: Property<String> = objectFactory.property(String::class.java)
val shaAlgorithms: ListProperty<String> = objectFactory.listProperty(String::class.java)
val username: Property<String> = objectFactory.property(String::class.java)
val password: Property<String> = objectFactory.property(String::class.java)
val pomConfiguration: Property<Action<MavenPom>> =
objectFactory.property(Action::class.java) as Property<Action<MavenPom>>
fun pom(action: Action<MavenPom>) {
pomConfiguration.set(action)
}
var versionMappingStrategy: Action<VersionMappingStrategy>? = null
fun versionMapping(action: Action<VersionMappingStrategy>) {
this.versionMappingStrategy = action
}
companion object {
internal fun Project.toSonatypeExtension(): SonatypeCentralPublishExtension =
extensions.create("sonatypeCentralPublishExtension", SonatypeCentralPublishExtension::class.java)
}
}
| 1
|
Kotlin
|
0
| 2
|
bec44116976aa088247fe280af75340857ef5f48
| 1,839
|
sonatype-maven-central-publisher
|
Apache License 2.0
|
view/src/main/java/com/example/view/bezier/MeditationView.kt
|
yudengwei
| 287,524,563
| false
| null |
package com.example.view.bezier
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.RequiresApi
import com.example.view.R
import com.example.view.util.blur
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class MeditationView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyleAttr : Int = 0) : FrameLayout(context, attributeSet, defStyleAttr) {
private val mThreeView : ThreeView by lazy {
ThreeView(context, attributeSet, defStyleAttr).also { threeView ->
threeView.setListener(object : ThreeView.BigListener{
override fun bigAnimatorEnd() {
mParticleView.outParticle()
ObjectAnimator.ofFloat(mDynamicImageView,"alpha",0f,1f).also {
it.duration = 4000
it.start()
}
}
})
}
}
private val mParticleView : ParticleView by lazy {
ParticleView(context, attributeSet, defStyleAttr)
}
private val mImageView : ImageView by lazy {
ImageView(context, attributeSet, defStyleAttr).apply {
this.scaleType = ImageView.ScaleType.FIT_XY
val sourceBitmap = BitmapFactory.decodeResource(resources, R.drawable.nazha)
this.setImageBitmap(sourceBitmap.blur(25f, context))
}
}
private val mDynamicImageView : ImageView by lazy {
ImageView(context, attributeSet, defStyleAttr).apply {
this.scaleType = ImageView.ScaleType.FIT_XY
val sourceBitmap = BitmapFactory.decodeResource(resources, R.drawable.nazha)
this.setImageBitmap(sourceBitmap)
}
}
init {
addView(mImageView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
addView(mDynamicImageView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
addView(mThreeView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
addView(mParticleView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
fun start() {
mThreeView.big()
mParticleView.inParticle()
ObjectAnimator.ofFloat(mDynamicImageView,"alpha",1f,0f).also {
it.duration = 4000
it.start()
}
}
}
| 1
| null |
1
| 1
|
d6d644e330f5f2b3d43e2451933a30987a5d373e
| 2,607
|
Demo
|
Apache License 2.0
|
app/src/main/java/io/horizontalsystems/bankwallet/modules/intro/IntroPresenter.kt
|
fahimaltinordu
| 312,207,740
| true
|
{"Kotlin": 1883211, "Java": 33448, "Ruby": 5803, "Shell": 2024}
|
package io.horizontalsystems.bankwallet.modules.intro
import androidx.lifecycle.ViewModel
class IntroPresenter(val router: IntroModule.IRouter) : ViewModel() {
fun start() {
router.navigateToWelcome()
}
fun skip() {
router.navigateToWelcome()
}
}
| 0
|
Kotlin
|
0
| 4
|
d3094c4afaa92a5d63ce53583bc07c8fb343f90b
| 283
|
WILC-wallet-android
|
MIT License
|
sample/f2-sample-rsocket/src/main/kotlin/f2/sample/rsocket/F2SampleRSocketApp.kt
|
smartbcity
| 746,765,045
| false
|
{"Java": 132969, "Kotlin": 130142, "Gherkin": 24157, "JavaScript": 1654, "Dockerfile": 745, "Makefile": 481, "CSS": 102}
|
package f2.sample.rsocket
import f2.dsl.fnc.F2Function
import f2.dsl.fnc.f2Function
import java.security.MessageDigest
import java.util.Base64
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
/**
* Declare Spring Boot Application
*/
@SpringBootApplication
class F2SampleRSocketApp {
/**
* Declare function to calculate sha256 and return it in Base64
* f2Function is an helper to implement coroutine function
* and return suspend (Flow<T>) -> Flow<R>
*/
@Bean
fun sha256(): F2Function<String, String> = f2Function { bytes ->
val md = MessageDigest.getInstance("SHA-256")
val hash = md.digest(bytes.toByteArray())
Base64.getEncoder().encodeToString(hash)
}
@Bean
fun simpleSha256(): (String) -> String = { bytes ->
val md = MessageDigest.getInstance("SHA-256")
val hash = md.digest(bytes.toByteArray())
Base64.getEncoder().encodeToString(hash)
}
}
/**
* Main method to start Spring Boot Application
*/
fun main(args: Array<String>) {
runApplication<F2SampleRSocketApp>(*args)
}
| 1
|
Kotlin
|
1
| 0
|
c3fb65badd711c180f5ddebb68da49fb09968937
| 1,130
|
fixers-f2
|
Apache License 2.0
|
arrow-libs/core/arrow-core/src/commonTest/kotlin/arrow/core/raise/IorSpec.kt
|
arrow-kt
| 86,057,409
| false
| null |
package arrow.core.raise
import arrow.core.Either
import arrow.core.Ior
import arrow.core.left
import arrow.core.right
import arrow.core.test.nonEmptyList
import arrow.core.toIorNel
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.arbitrary.int
import io.kotest.property.checkAll
import kotlin.test.Test
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.test.runTest
@Suppress(
"UNREACHABLE_CODE",
"IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION",
"UNUSED_VARIABLE"
)
class IorSpec {
@Test fun accumulates() = runTest {
ior(String::plus) {
val one = Ior.Both("Hello", 1).bind()
val two = Ior.Both(", World!", 2).bind()
one + two
} shouldBe Ior.Both("Hello, World!", 3)
}
@Test fun accumulatesAndShortCircuitsWithLeft() = runTest {
ior(String::plus) {
val one = Ior.Both("Hello", 1).bind()
val two: Int = Ior.Left(", World!").bind()
one + two
} shouldBe Ior.Left("Hello, World!")
}
@Test fun accumulatesWithEither() = runTest {
ior(String::plus) {
val one = Ior.Both("Hello", 1).bind()
val two: Int = Either.Left(", World!").bind<Int>()
one + two
} shouldBe Ior.Left("Hello, World!")
}
@Test fun concurrentArrowIorBind() = runTest {
checkAll(Arb.nonEmptyList(Arb.int(), range = 0 .. 20)) { xs ->
ior(List<Int>::plus) {
xs.mapIndexed { index, s -> async { Ior.Both(listOf(s), index).bind() } }.awaitAll()
}
.mapLeft { it.toSet() } shouldBe Ior.Both(xs.toSet(), xs.indices.toList())
}
}
@Test fun accumulatesEagerly() = runTest {
ior(String::plus) {
val one = Ior.Both("Hello", 1).bind()
val two = Ior.Both(", World!", 2).bind()
one + two
} shouldBe Ior.Both("Hello, World!", 3)
}
@Test fun accumulatesWithEitherEagerly() = runTest {
ior(String::plus) {
val one = Ior.Both("Hello", 1).bind()
val two: Int = Either.Left(", World!").bind<Int>()
one + two
} shouldBe Ior.Left("Hello, World!")
}
@Test fun accumulatesAndShortCircuits() = runTest {
ior(String::plus) {
Ior.Both("Hello", Unit).bind()
raise(" World")
} shouldBe Ior.Left("Hello World")
}
@Test fun iorRethrowsException() = runTest {
val boom = RuntimeException("Boom!")
shouldThrow<RuntimeException> {
ior(String::plus) {
throw boom
}
}.message shouldBe "Boom!"
}
@Test fun recoverWorksAsExpected() = runTest {
ior(String::plus) {
val one = recover({
Ior.Both("Hi", Unit).bind()
Ior.Left("Hello").bind()
}) {
it shouldBe "Hello"
1
}
val two = Ior.Right(2).bind()
val three = Ior.Both(", World", 3).bind()
one + two + three
} shouldBe Ior.Both("Hi, World", 6)
}
@Test fun recoverWithThrow() = runTest {
ior(String::plus) {
val one = try {
recover({
Ior.Both("Hi", Unit).bind()
throw RuntimeException("Hello")
}) {
unreachable()
}
} catch (e: RuntimeException) {
1
}
val two = Ior.Right(2).bind()
val three = Ior.Both(", World", 3).bind()
one + two + three
} shouldBe Ior.Both("Hi, World", 6)
}
@Test fun recoverWithRaiseIsNoOp() = runTest {
ior(String::plus) {
val one: Int =
recover({
Ior.Both("Hi", Unit).bind()
Ior.Left(", Hello").bind()
}) {
raise(it)
}
val two = Ior.Right(2).bind()
val three = Ior.Both(", World", 3).bind()
one + two + three
} shouldBe Ior.Left("Hi, Hello")
}
@Test fun tryCatchRecoverRaise() = runTest {
ior(String::plus) {
val one = try {
Ior.Both("Hi", Unit).bind()
Ior.Left("Hello").bind()
} catch (e: Throwable) {
1
}
val two = Ior.Right(2).bind()
val three = Ior.Both(", World", 3).bind()
one + two + three
} shouldBe Ior.Both("Hi, World", 6)
}
@Test fun iorNelAccumulates() = runTest {
iorNel {
val one = Ior.Both("ErrorOne", 1).toIorNel().bind()
val two = Ior.Both("ErrorTwo", 2).toIorNel().bind()
one + two
} shouldBe Ior.Both(listOf("ErrorOne", "ErrorTwo"), 3)
}
@Test fun accumulateErrorManually() {
ior(String::plus) {
accumulate("nonfatal")
"output"
} shouldBe Ior.Both("nonfatal", "output")
}
@Test fun getOrAccumulateRightEither() {
ior(String::plus) {
val result = "success".right().getOrAccumulate { "failed" }
"output: $result"
} shouldBe Ior.Right("output: success")
}
@Test fun getOrAccumulateLeftEither() {
ior(String::plus) {
val result = "nonfatal".left().getOrAccumulate { "failed" }
"output: $result"
} shouldBe Ior.Both("nonfatal", "output: failed")
}
}
| 42
| null |
451
| 6,170
|
c47d9bcfbb402f827b312dbcfec1d5cf68ba2fc3
| 4,924
|
arrow
|
Apache License 2.0
|
src/main/kotlin/customConsole/CustomConsole.kt
|
zp4rker
| 328,897,992
| false
|
{"Gradle": 2, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 1, "XML": 1, "Kotlin": 15}
|
package customConsole
import io.leego.banana.BananaUtils
import io.leego.banana.Font
import io.leego.banana.Layout
import net.dv8tion.jda.api.JDABuilder
import net.dv8tion.jda.api.events.ReadyEvent
import net.dv8tion.jda.api.hooks.AnnotatedEventManager
import net.dv8tion.jda.api.hooks.SubscribeEvent
import org.fusesource.jansi.AnsiConsole
import org.slf4j.LoggerFactory
import java.io.File
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
/**
* @author zp4rker
*/
fun main() {
archive(File("logs/log.txt"))
if (!AnsiConsole.isInstalled()) AnsiConsole.systemInstall()
val name = linedText("CustomConsole")
LogInterceptor.log("\n${BananaUtils.bananaify(name, Font.BIG_MONEY_NW, Layout.SMUSH_R, Layout.SMUSH_R).trimEnd()}")
LogInterceptor.log(BananaUtils.bananaify("v${BananaUtils::class.java.`package`.implementationVersion}", Font.RECTANGLES).trimEnd() + " \tby zp4rker#3333\n")
val readyListener = object {
@SubscribeEvent
fun onReady(e: ReadyEvent) {
with(LoggerFactory.getLogger("test")) {
info("This is an info log")
debug("This is a debug log")
warn("This is a warn log")
error("This is an error log")
}
e.jda.shutdownNow()
}
}
with(JDABuilder.createLight(System.getenv("TOKEN"))) {
setEventManager(AnnotatedEventManager())
addEventListeners(readyListener)
}.build()
ConsoleThread().start()
}
private fun linedText(original: String): String {
fun components(original: String): List<String> {
val list = mutableListOf<String>()
for ((i, c) in original.toCharArray().withIndex()) {
if ((c.isUpperCase() || c.isWhitespace())) {
if (i == 0 || (original.elementAt(i - 1).isUpperCase() && original.elementAtOrElse(i + 1) { 'A' }.isUpperCase())) continue
list.add(original.substring(0, i))
list.addAll(components(original.substring(if (c.isWhitespace()) i + 1 else i, original.length)))
break
}
}
if (list.isEmpty()) list.add(original)
return list
}
return components(original).joinToString("\n")
}
fun archive(file: File, deleteOriginal: Boolean = true) {
if (!file.parentFile.exists()) file.parentFile.mkdir()
if (!file.exists()) return
val bytes = file.readBytes()
val outFile = file.name.let {
val date = Instant.ofEpochMilli(file.lastModified()).atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ISO_LOCAL_DATE)
var name = "$date-${it}.zip"
if (File(file.parentFile, name).exists()) {
var i = 2
name = "$date-$it.$i.zip"
while (File(file.parentFile, name).exists()) {
name = "$date-$it.${++i}.zip"
}
}
File(file.parentFile, name)
}
ZipOutputStream(outFile.outputStream()).use {
it.putNextEntry(ZipEntry(file.name))
it.write(bytes)
}
if (deleteOriginal) file.delete()
}
| 0
|
Kotlin
|
0
| 0
|
5b8ddc262130be96b5f5fb018247ec1279ae0b29
| 3,179
|
apples
|
Apache License 2.0
|
app/src/main/java/hive/com/paradiseoctopus/awareness/createplace/helper/WifiScanReceiver.kt
|
cliffroot
| 68,677,882
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "JSON": 1, "Proguard": 1, "Java": 2, "XML": 39, "Kotlin": 34}
|
package hive.com.paradiseoctopus.awareness.createplace.helper
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import rx.subjects.PublishSubject
import rx.subjects.ReplaySubject
/**
* Created by edanylenko on 9/20/16.
*/
class WifiScanReceiver(val context: Context, val resultSubject: ReplaySubject<List<ScanResult>>) : BroadcastReceiver() {
val wifiScanManager : WifiManager by lazy {
context.getSystemService(Context.WIFI_SERVICE) as WifiManager
}
override fun onReceive(context : Context, intent : Intent) {
if (intent.action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
resultSubject.onNext(wifiScanManager.scanResults)
resultSubject.onCompleted()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
77bd018fd938ebebe804ecceca9315112564246b
| 862
|
awareness
|
Apache License 2.0
|
common/src/main/java/com/worldline/connect/android/example/kotlin/common/utils/Status.kt
|
Worldline-Global-Collect
| 748,163,778
| false
|
{"Kotlin": 220841}
|
/*
* Copyright (c) 2022. Worldline Global Collect B.V
*/
package com.worldline.connect.android.example.kotlin.common.utils
import com.worldline.connect.sdk.client.android.network.ApiErrorResponse
/**
* This class is an example how to store the result of async call
*/
sealed class Status {
data class Success(val data: Any?) : Status()
data class Failed(val throwable: Throwable) : Status()
data class ApiError(val apiError: ApiErrorResponse) : Status()
data object Loading : Status()
data object None: Status()
}
| 0
|
Kotlin
|
0
| 0
|
79b89983be3b4cdb6f51da27385acd3117fe5a2f
| 542
|
connect-sdk-client-android-example-kotlin
|
Apache License 2.0
|
src/main/kotlin/nitrolang/typeinference/TConstraint.kt
|
cout970
| 699,028,788
| false
|
{"Markdown": 2, "Gradle Kotlin DSL": 2, "ANTLR": 2, "INI": 2, "Shell": 2, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Text": 1, "Kotlin": 86, "Java": 6, "JSON with Comments": 1, "HTML": 3, "HTTP": 1, "XML": 2}
|
package nitrolang.typeinference
import nitrolang.ast.LstTag
import nitrolang.util.Span
sealed interface TConstraint {
val span: Span
}
data class TBounds(
val id: Int,
val target: TypeBox,
val requiredTags: List<LstTag>,
override val span: Span
) : TConstraint
data class TFindField(
val id: Int,
val dependency: TypeBox,
val callback: (TType) -> Unit,
override val span: Span
) : TConstraint
data class TFindFunction(
val id: Int,
val dependencies: List<TypeBox>,
val callback: (List<TType>) -> Unit,
override val span: Span
) : TConstraint
data class TInitLambda(
val id: Int,
val dependency: TypeBox,
val callback: (TType) -> Unit,
override val span: Span
) : TConstraint
data class TUnify(
val id: Int,
val left: TypeBox,
val right: TypeBox,
override val span: Span
) : TConstraint
| 0
|
Java
|
0
| 3
|
9f501d19da02bd7022ac9029f23cd1d19205d150
| 877
|
NitroLang
|
MIT License
|
src/main/java/com/loanely/application/exceptions/PasswordMismatchException.kt
|
iankang
| 792,671,872
| false
|
{"JSON with Comments": 1, "Batchfile": 1, "JSON": 3, "Markdown": 2, "Shell": 1, "Maven POM": 1, "Ignore List": 1, "Java Properties": 1, "Java": 19, "HTML": 1, "CSS": 6, "Kotlin": 34, "Text": 1, "SQL": 1, "YAML": 1}
|
package com.thinkit.brs.exceptions
class PasswordMismatchException(message:String): RuntimeException(message) {
}
| 0
|
Java
|
0
| 0
|
1b61437c44a5bd444341d5dea4da4ac48cffd7ad
| 114
|
loanely-vaadin
|
The Unlicense
|
app/src/main/java/com/example/calculodoimc/ResultActivity.kt
|
Walace-Anjos
| 743,721,960
| false
|
{"Kotlin": 3731}
|
package com.example.calculodoimc
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.widget.TextView
class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val TvResult: TextView = findViewById(R.id.Tv_result)
val TvClassificacao: TextView = findViewById(R.id.Tv_Classificacao)
val Result = intent.getFloatExtra("EXTRA_RESULT", 0.1f)
TvResult.text = Result.toString()
val Classificacao = if (Result < 18.5f) {
"ABAIXO DO PESO"
}else if (Result in 18.5f..24.9f) {
"NORMAL"
}else if (Result in 24.9f..29.9f) {
"SOBREPESO"
}else if (Result in 29.9f..39.9f) {
"OBESIDADE"
}else {
"OBESIDADE GRAVE"
}
TvClassificacao.text = getString(R.string.messsage_Classificacao, Classificacao)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
finish()
return super.onOptionsItemSelected(item)
}
}
| 0
|
Kotlin
|
0
| 0
|
ec2943fa2093153aff608e88ab039e3c0d5dec5f
| 1,294
|
CalculoIMC
|
MIT License
|
app/src/main/java/com/example/calculodoimc/ResultActivity.kt
|
Walace-Anjos
| 743,721,960
| false
|
{"Kotlin": 3731}
|
package com.example.calculodoimc
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.widget.TextView
class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val TvResult: TextView = findViewById(R.id.Tv_result)
val TvClassificacao: TextView = findViewById(R.id.Tv_Classificacao)
val Result = intent.getFloatExtra("EXTRA_RESULT", 0.1f)
TvResult.text = Result.toString()
val Classificacao = if (Result < 18.5f) {
"ABAIXO DO PESO"
}else if (Result in 18.5f..24.9f) {
"NORMAL"
}else if (Result in 24.9f..29.9f) {
"SOBREPESO"
}else if (Result in 29.9f..39.9f) {
"OBESIDADE"
}else {
"OBESIDADE GRAVE"
}
TvClassificacao.text = getString(R.string.messsage_Classificacao, Classificacao)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
finish()
return super.onOptionsItemSelected(item)
}
}
| 0
|
Kotlin
|
0
| 0
|
ec2943fa2093153aff608e88ab039e3c0d5dec5f
| 1,294
|
CalculoIMC
|
MIT License
|
app/src/main/java/com/Mostoles/Hero_Dex/MenuActivity.kt
|
elgynmdz
| 627,766,126
| false
| null |
package com.Mostoles.Hero_Dex
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.Mostoles.Hero_Dex.superheroapp.SuperHeroListActivity
class MenuActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu)
val btnSuperhero = findViewById<Button>(R.id.btnSuperhero)
btnSuperhero.setOnClickListener { navigateToSuperheroApp() }
}
private fun navigateToSuperheroApp(){
val intent = Intent(this, SuperHeroListActivity::class.java)
startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
21e1eb7fdb7395d31fd45148102b644e93a7ef85
| 712
|
Hero_DEX
|
Apache License 2.0
|
src/main/kotlin/io/github/ugaikit/gemini4kt/EmbedResponse.kt
|
takanori-ugai
| 774,120,161
| false
|
{"Kotlin": 57353}
|
package io.github.ugaikit.gemini4kt
import kotlinx.serialization.Serializable
/**
* Represents the response from an embedding operation, containing the computed
* embedding values.
*
* @property embedding A [Values] object that holds the numerical representation
* of the embedded data. This could be a vector or set of values resulting from
* processing the input through an embedding model or algorithm.
*/
@Serializable
data class EmbedResponse(val embedding: Values)
| 0
|
Kotlin
|
0
| 0
|
3ab0a8f66d54497005140c3658744bfb3c074488
| 480
|
Gemini4KT
|
Apache License 2.0
|
app/src/main/java/io/benic/shoppinglist/view/ItemFragment.kt
|
BBenicio
| 325,425,619
| false
| null |
package io.benic.shoppinglist.view
import android.os.Bundle
import android.os.Handler
import android.text.TextWatcher
import android.util.Log
import android.view.*
import android.widget.EditText
import android.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import io.benic.shoppinglist.R
import io.benic.shoppinglist.model.Item
import io.benic.shoppinglist.model.ShoppingCart
import io.benic.shoppinglist.utils.CurrencyHelper
import io.benic.shoppinglist.viewmodel.ItemViewModel
import kotlinx.android.synthetic.main.fragment_item.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* A simple [Fragment] subclass as the second destination in the navigation.
*/
@AndroidEntryPoint
class ItemFragment : Fragment() {
private var cart: ShoppingCart = ShoppingCart()
private lateinit var checkAll: MenuItem
private lateinit var uncheckAll: MenuItem
private lateinit var searchItem: MenuItem
private lateinit var search: SearchView
private lateinit var handler: Handler
private lateinit var itemListAdapter: ItemRecycleAdapter
private val viewModel: ItemViewModel by viewModels()
private var unsavedChanges: Int = 0
private var itemsInitialized: Boolean = false
private var isInitializing: Boolean = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
handler = Handler(requireActivity().mainLooper)
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_item, container, false)
}
private fun initializeItems() {
for (i in 0 until cart.items.size) {
if (cart.items[i].position < 0) {
cart.items[i].position = i
++unsavedChanges
}
}
cart.items.sortWith { a, b -> if (a.position > b.position) 1 else -1 }
for (i in 0 until cart.items.size) {
if (cart.items[i].position != i) {
cart.items[i].position = i
++unsavedChanges
}
}
totalItems.text =
resources.getQuantityString(R.plurals.item, cart.items.size).format(cart.items.size)
itemListAdapter.changeData(cart.items)
isInitializing = false
updateProgress()
}
private fun initializeCart() {
if (!itemsInitialized) {
itemsInitialized = true
viewModel.fetchItems(cart.id).observe(viewLifecycleOwner, { items ->
if (cart.items.isEmpty()) {
Log.i(TAG, "showing items")
cart.items.addAll(items)
initializeItems()
} else {
Log.i(TAG, "won't reload items")
}
})
}
if (cart.maxCost > 0) {
maximumCost.setText(CurrencyHelper.getString(cart.maxCost))
}
cartTitleEdit.setText(cart.name)
totalValue.text = CurrencyHelper.getString(cart.cost)
}
private fun createAdapter() {
itemListAdapter = ItemRecycleAdapter(cart.items, object : ItemRecycleListener {
override fun onQuantityChanged(position: Int, text: String) {
val item = itemListAdapter.getItem(position)
val q = if (text.isEmpty()) 0 else text.toInt()
if (item.quantity != q) {
item.quantity = q
updateProgress()
}
}
override fun onNameChanged(position: Int, text: String) {
val item = itemListAdapter.getItem(position)
if (item.name != text) {
item.name = text
updateProgress()
}
}
override fun onPriceChanged(
position: Int,
text: String,
textWatcher: TextWatcher,
editText: EditText
) {
val item = itemListAdapter.getItem(position)
editText.removeTextChangedListener(textWatcher)
item.price = CurrencyHelper.getValue(text)
val formatted = CurrencyHelper.getString(item.price)
editText.setText(formatted)
editText.setSelection(formatted.length)
editText.addTextChangedListener(textWatcher)
updateProgress()
}
override fun onChecked(position: Int, checked: Boolean) {
val item = itemListAdapter.getItem(position)
item.checked = checked
updateProgress()
}
override fun onItemMoved(from: Int, to: Int) {
updateProgress()
}
})
itemList.adapter = itemListAdapter
}
private fun initView() {
itemList.layoutManager = LinearLayoutManager(requireContext())
createAdapter()
}
private fun initListeners() {
maximumCost.addTextChangedListener { t, w ->
val cost = CurrencyHelper.getValue(t)
maximumCost.removeTextChangedListener(w)
cart.maxCost = cost
if (cost == 0) {
maximumCost.setText("")
updateProgress()
} else {
val formatted = CurrencyHelper.getString(cart.maxCost)
maximumCost.setText(formatted)
maximumCost.setSelection(formatted.length)
updateProgress()
}
maximumCost.addTextChangedListener(w)
}
cartTitleEdit.addTextChangedListener { t, _ ->
if (cart.name != t) {
cart.name = t
}
}
progressCard.setOnClickListener {
findNavController().popBackStack()
}
fab.setOnClickListener {
addItem()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
initListeners()
val cartId = arguments?.getLong("cartId") ?: 0L
if (cartId >= 0) {
viewModel.fetchCart(cartId).observe(viewLifecycleOwner, { cart ->
Log.i(TAG, "loaded cart ${cart.name}")
this.cart = cart
viewModel.cart.removeObservers(viewLifecycleOwner)
initializeCart()
})
} else {
Log.i(TAG, "creating cart")
cart = ShoppingCart()
viewModel.createCart(cart).observe(viewLifecycleOwner, { id ->
cart.id = id
initializeCart()
})
}
lifecycleScope.launch(Dispatchers.IO) {
val cost = if (cart.items.size > 0)
cart.items.map { item -> item.price }
.reduce { acc, price -> acc + price }
else 0
withContext(Dispatchers.Main) {
totalValue.text = CurrencyHelper.getString(cost)
}
}
val swipeHelper = SwipeHelper(lifecycleScope) { remove, i ->
val item = itemListAdapter.getItem(i)
if (remove) {
viewModel.deleteItem(item)
cart.items.remove(item)
updateProgress()
itemListAdapter.notifyItemRemoved(i)
} else {
itemListAdapter.notifyItemChanged(i)
}
}
swipeHelper.setAdapter(itemListAdapter)
swipeHelper.setUpAnimationDecoratorHelper(itemList)
val itemTouchHelper = ItemTouchHelper(swipeHelper)
itemTouchHelper.attachToRecyclerView(itemList)
setItemsChecked(cart.items.none { item -> !item.checked })
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_item, menu)
checkAll = menu.findItem(R.id.check_all)
uncheckAll = menu.findItem(R.id.uncheck_all)
searchItem = menu.findItem(R.id.app_bar_search)
search = searchItem.actionView as SearchView
search.setOnQueryTextListener(itemList.adapter as ItemRecycleAdapter)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.check_all -> {
setItemsChecked(true)
setShowCheckAllActionInMenu(false)
true
}
R.id.uncheck_all -> {
setItemsChecked(false)
setShowCheckAllActionInMenu(true)
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun setShowCheckAllActionInMenu(showChecked: Boolean) {
if (this::checkAll.isInitialized) {
checkAll.isVisible = showChecked
uncheckAll.isVisible = !showChecked
}
}
private fun setItemsChecked(checked: Boolean) {
(itemList.adapter as ItemRecycleAdapter).setItemsChecked(checked)
}
private fun updateProgress() {
Log.d(TAG, "updateProgress()")
if (isInitializing) {
Log.i(TAG, "still initializing so won't update progress")
return
}
lifecycleScope.launch(Dispatchers.IO) {
val checked = cart.items.filter { item -> item.checked }
val progress = checked.size
val progressMax = cart.items.size
val totalCostVal =
if (checked.isNotEmpty()) checked.map { item -> item.price * item.quantity }
.reduce { acc, price -> acc + price } else 0
val totalValueVal =
if (cart.items.isNotEmpty()) cart.items.map { item -> item.price * item.quantity }
.reduce { acc, price -> acc + price } else 0
cart.cost = totalValueVal
cart.description =
cart.items.subList(0, if (cart.items.size > 3) 3 else cart.items.size)
.joinToString("\n") { item -> item.name }
if (++unsavedChanges > MAX_UNSAVED_CHANGES) {
save()
}
withContext(Dispatchers.Main) {
if (cart.maxCost in 1 until totalCostVal) {
totalValue.setTextColor(
ContextCompat.getColor(
requireActivity(),
R.color.colorOverSpent
)
)
} else {
totalValue.setTextColor(
ContextCompat.getColor(
requireActivity(),
R.color.textDarkSecondary
)
)
}
setShowCheckAllActionInMenu(checked.size < cart.items.size)
itemsSelected.text =
resources.getQuantityString(R.plurals.item, checked.size).format(checked.size)
totalCost.text = CurrencyHelper.getString(totalCostVal)
totalValue.text = CurrencyHelper.getString(totalValueVal)
progressBar.progress = progress
progressBar.max = progressMax
}
}
}
private fun addItem() {
Log.i(TAG, "add item to cart ${cart.id}")
val item = Item(cartId = cart.id)
item.position = cart.items.size
cart.items.add(item)
viewModel.addItem(item).observe(viewLifecycleOwner, { id -> item.id = id })
totalItems.text =
resources.getQuantityString(R.plurals.item, cart.items.size, cart.items.size)
updateProgress()
itemListAdapter.notifyItemInserted(cart.items.size - 1)
}
private fun save() {
Log.d(TAG, "save ${cart.name} (${cart.items.size} items)")
unsavedChanges = 0
viewModel.updateCart(cart)
for (item in cart.items) {
viewModel.updateItem(item)
}
}
override fun onDestroyView() {
save()
super.onDestroyView()
}
companion object {
private const val TAG = "ItemFragment"
private const val MAX_UNSAVED_CHANGES = 0
}
}
| 0
|
Kotlin
|
0
| 0
|
f1ee39e0ef2e61c0a78066483918c51a15d9223f
| 12,808
|
shoppinglist
|
MIT License
|
feature-crowdloan-impl/src/main/java/jp/co/soramitsu/crowdloan/impl/presentation/contribute/custom/karura/KaruraContributeSubmitter.kt
|
soramitsu
| 278,060,397
| false
|
{"Kotlin": 5738291, "Java": 18796}
|
package jp.co.soramitsu.crowdloan.impl.presentation.contribute.custom.karura
import java.math.BigDecimal
import jp.co.soramitsu.crowdloan.impl.domain.contribute.custom.karura.KaruraContributeInteractor
import jp.co.soramitsu.crowdloan.impl.presentation.contribute.custom.BonusPayload
import jp.co.soramitsu.crowdloan.impl.presentation.contribute.custom.CustomContributeSubmitter
import jp.co.soramitsu.crowdloan.impl.presentation.contribute.select.parcel.ParachainMetadataParcelModel
class KaruraContributeSubmitter(
private val interactor: KaruraContributeInteractor
) : CustomContributeSubmitter {
override suspend fun submitOffChain(
payload: BonusPayload,
amount: BigDecimal,
metadata: ParachainMetadataParcelModel?
): Result<Unit> {
require(payload is KaruraBonusPayload)
return interactor.registerInBonusProgram(payload.referralCode, amount)
}
}
| 15
|
Kotlin
|
30
| 89
|
812c6ed5465d19a0616865cbba3e946d046720a1
| 912
|
fearless-Android
|
Apache License 2.0
|
feature-crowdloan-impl/src/main/java/jp/co/soramitsu/crowdloan/impl/presentation/contribute/custom/karura/KaruraContributeSubmitter.kt
|
soramitsu
| 278,060,397
| false
|
{"Kotlin": 5738291, "Java": 18796}
|
package jp.co.soramitsu.crowdloan.impl.presentation.contribute.custom.karura
import java.math.BigDecimal
import jp.co.soramitsu.crowdloan.impl.domain.contribute.custom.karura.KaruraContributeInteractor
import jp.co.soramitsu.crowdloan.impl.presentation.contribute.custom.BonusPayload
import jp.co.soramitsu.crowdloan.impl.presentation.contribute.custom.CustomContributeSubmitter
import jp.co.soramitsu.crowdloan.impl.presentation.contribute.select.parcel.ParachainMetadataParcelModel
class KaruraContributeSubmitter(
private val interactor: KaruraContributeInteractor
) : CustomContributeSubmitter {
override suspend fun submitOffChain(
payload: BonusPayload,
amount: BigDecimal,
metadata: ParachainMetadataParcelModel?
): Result<Unit> {
require(payload is KaruraBonusPayload)
return interactor.registerInBonusProgram(payload.referralCode, amount)
}
}
| 15
|
Kotlin
|
30
| 89
|
812c6ed5465d19a0616865cbba3e946d046720a1
| 912
|
fearless-Android
|
Apache License 2.0
|
paint2/src/main/kotlin/ru/nsu/e/shelbogashev/art/studio/paint/context/ApplicationContext.kt
|
EricShelbogashev
| 745,928,535
| false
|
{"Kotlin": 101898, "Java": 224}
|
package ru.nsu.e.shelbogashev.art.studio.paint.context
data class ApplicationContext(
val properties: ApplicationProperties,
val components: ApplicationComponents
)
| 0
|
Kotlin
|
0
| 0
|
6881eb773624fa420425983e2a4b73cb76ce5f17
| 173
|
engineering-computer-graphics
|
MIT License
|
sei-chain/src/commonMain/kotlin/seiprotocol/seichain/dex/pair.converter.kt
|
jdekim43
| 759,720,689
| false
|
{"Kotlin": 8940168, "Java": 3242559}
|
// Transform from dex/pair.proto
@file:GeneratorVersion(version = "0.3.1")
package seiprotocol.seichain.dex
import google.protobuf.Any
import java.lang.IllegalStateException
import kr.jadekim.protobuf.`annotation`.GeneratorVersion
import kr.jadekim.protobuf.converter.ProtobufConverter
import kr.jadekim.protobuf.converter.parseProtobuf
public expect object PairConverter : ProtobufConverter<Pair>
public fun Pair.toAny(): Any = Any(Pair.TYPE_URL, with(PairConverter) { toByteArray() })
public fun Any.parse(converter: ProtobufConverter<Pair>): Pair {
if (typeUrl != Pair.TYPE_URL) throw IllegalStateException("Please check the type_url")
return value.parseProtobuf(converter)
}
public expect object BatchContractPairConverter : ProtobufConverter<BatchContractPair>
public fun BatchContractPair.toAny(): Any = Any(BatchContractPair.TYPE_URL,
with(BatchContractPairConverter) { toByteArray() })
public fun Any.parse(converter: ProtobufConverter<BatchContractPair>): BatchContractPair {
if (typeUrl != BatchContractPair.TYPE_URL) throw
IllegalStateException("Please check the type_url")
return value.parseProtobuf(converter)
}
| 0
|
Kotlin
|
0
| 0
|
eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc
| 1,151
|
chameleon.proto
|
Apache License 2.0
|
pr_1/app/src/main/java/com/example/pr_1/Expense.kt
|
THE80X
| 861,451,505
| false
|
{"Kotlin": 9943}
|
package com.example.pr_1
import java.util.Date
import java.util.UUID
class Expense {
val Id: UUID = UUID.randomUUID()
var Sum: Double
var Category: String
var Date: Date
constructor(Sum: Double, Category: String, Date: Date){
this.Sum = Sum
this.Category = Category
this.Date = Date
}
fun showInfo(): String {
return "Сумма: $Sum | Категория: $Category | Дата: $Date"
}
}
| 0
|
Kotlin
|
0
| 0
|
4897011197c0cdba6897682d3db1c3fead0003d2
| 439
|
Mirea
|
MIT License
|
CameraSample/app/src/main/java/com/laima/camerasample/CameraActivity.kt
|
LaimaPark
| 565,465,598
| false
|
{"Kotlin": 36486}
|
package com.laima.camerasample
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.laima.camerasample.databinding.ActivityCameraBinding
import java.io.File
class CameraActivity : AppCompatActivity() {
private lateinit var binding: ActivityCameraBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCameraBinding.inflate(layoutInflater)
setContentView(binding.root)
}
} // end of class
| 0
|
Kotlin
|
0
| 0
|
b50c30ae76c91ea80e06e92b7cdf256ba206b2f9
| 782
|
Jetpack_Sample
|
Apache License 2.0
|
kraii-compiler-plugin/src/main/kotlin/kraii/KraiiSyntheticResolveExtension.kt
|
jbarop
| 566,958,919
| false
| null |
package kraii
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.extensions.SyntheticResolveExtension
/**
* Adds [AutoCloseable.close] to classes which implement [AutoCloseable].
*/
class KraiiSyntheticResolveExtension : SyntheticResolveExtension {
override fun getSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List<Name> =
listOf(closeName)
override fun generateSyntheticMethods(
thisDescriptor: ClassDescriptor,
name: Name,
bindingContext: BindingContext,
fromSupertypes: List<SimpleFunctionDescriptor>,
result: MutableCollection<SimpleFunctionDescriptor>,
) {
if (name != closeName) return
if (result.any { it.name == closeName }) return
if (!thisDescriptor.implementsAutoClosable()) return
val functionDescriptor = SimpleFunctionDescriptorImpl.create(
/* containingDeclaration = */ thisDescriptor,
/* annotations = */ Annotations.EMPTY,
/* name = */ name,
/* kind = */ CallableMemberDescriptor.Kind.SYNTHESIZED,
/* source = */ thisDescriptor.source,
)
functionDescriptor.initialize(
/* extensionReceiverParameter = */ null,
/* dispatchReceiverParameter = */ thisDescriptor.thisAsReceiverParameter,
/* contextReceiverParameters = */ emptyList(),
/* typeParameters = */ emptyList(),
/* unsubstitutedValueParameters = */ emptyList(),
/* unsubstitutedReturnType = */ thisDescriptor.builtIns.unitType,
/* modality = */ Modality.OPEN,
/* visibility = */ DescriptorVisibilities.PUBLIC,
)
result += functionDescriptor
}
}
| 0
|
Kotlin
|
0
| 0
|
a8c4ffa35fcb4591ed8a6dfbd143e81bdae058ca
| 1,895
|
kraii
|
MIT License
|
app/src/main/java/io/github/incalc/iresta/data/MealDao.kt
|
incalc
| 206,979,230
| false
|
{"Kotlin": 14613}
|
package io.github.incalc.iresta.data
import androidx.room.*
@Dao
interface MealDao {
@Delete
fun delete(meal: Meal)
@Delete
fun deleteAll(meals: List<Meal>)
@Query("SELECT * FROM meals")
fun getAll(): List<Meal>
@Insert
fun insert(meal: Meal)
@Insert
fun insert(vararg meals: Meal)
@Insert
fun insertAll(meals: List<Meal>)
@Update
fun update(meal: Meal)
@Update
fun updateAll(meals: List<Meal>)
}
| 0
|
Kotlin
|
0
| 1
|
a05ede693b1b3c783a23794c4bdfcb8dffd4b7bf
| 471
|
iresta
|
MIT License
|
app/src/main/java/io/github/incalc/iresta/data/MealDao.kt
|
incalc
| 206,979,230
| false
|
{"Kotlin": 14613}
|
package io.github.incalc.iresta.data
import androidx.room.*
@Dao
interface MealDao {
@Delete
fun delete(meal: Meal)
@Delete
fun deleteAll(meals: List<Meal>)
@Query("SELECT * FROM meals")
fun getAll(): List<Meal>
@Insert
fun insert(meal: Meal)
@Insert
fun insert(vararg meals: Meal)
@Insert
fun insertAll(meals: List<Meal>)
@Update
fun update(meal: Meal)
@Update
fun updateAll(meals: List<Meal>)
}
| 0
|
Kotlin
|
0
| 1
|
a05ede693b1b3c783a23794c4bdfcb8dffd4b7bf
| 471
|
iresta
|
MIT License
|
src/main/kotlin/eu/automateeverything/nspanelplugin/blocks/NsPanelBlockCategories.kt
|
tomaszbabiuk
| 669,691,372
| false
| null |
/*
* Copyright (c) 2019-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 eu.automateeverything.nspanelplugin.blocks
import eu.automateeverything.data.localization.Resource
import eu.automateeverything.domain.automation.blocks.BlockCategory
import eu.automateeverything.nspanelplugin.R
enum class NsPanelBlockCategories(
override val categoryName: Resource,
override val color: Int
) : BlockCategory {
NSPanel(R.category_nspanel, 180),
}
| 0
|
Kotlin
|
0
| 0
|
d22c52d3d85f97cf7195e09d6d7f71f2b1a5867c
| 985
|
aeplugin-nspanel
|
Apache License 2.0
|
gleam-core/src/test/kotlin/at/hannesmoser/gleam/transforms/CollectionTest.kt
|
eliias
| 289,132,196
| false
|
{"Kotlin": 73096, "Shell": 591, "Dockerfile": 31}
|
package at.hannesmoser.gleam.transforms
import io.github.serpro69.kfaker.Faker
import org.apache.beam.sdk.testing.PAssert
import org.apache.beam.sdk.testing.TestPipeline
import org.apache.beam.sdk.transforms.Create
import org.junit.Rule
import org.junit.Test
internal class CollectionTest {
@Rule
@JvmField
val pipeline: TestPipeline = TestPipeline.create()
@Test
fun testReduce() {
val faker = Faker()
val data = (1..100).map { faker.color.name() }
val result = pipeline
.apply(Create.of(data))
.apply(Collection.reduce { s, batch -> batch.add(s); batch })
PAssert
.that(result)
.satisfies {
assert(it.toList().isNotEmpty())
return@satisfies null
}
pipeline.run()
}
}
| 0
|
Kotlin
|
0
| 3
|
9689cea73d7a4603a987208843a03b9365ae735d
| 753
|
gleam
|
MIT License
|
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/loops/handlers/ReversedHandler.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.common.lower.loops.handlers
import org.jetbrains.kotlin.backend.common.CommonBackendContext
import org.jetbrains.kotlin.backend.common.lower.loops.HeaderInfoBuilder
import org.jetbrains.kotlin.backend.common.lower.loops.HeaderInfoHandler
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.types.defaultType
import org.jetbrains.kotlin.ir.util.kotlinFqName
import org.jetbrains.kotlin.name.FqName
/** Builds a [HeaderInfo] for calls to reverse an iterable. */
internal class ReversedHandler(context: CommonBackendContext, private val visitor: HeaderInfoBuilder) :
HeaderInfoHandler<IrCall, Nothing?> {
private val progressionClassesTypes = context.ir.symbols.progressionClasses.map { it.defaultType }.toSet()
override fun matchIterable(expression: IrCall): Boolean {
// TODO: Handle reversed String, Progression.withIndex(), etc.
val callee = expression.symbol.owner
return callee.valueParameters.isEmpty() &&
callee.extensionReceiverParameter?.type in progressionClassesTypes &&
callee.kotlinFqName == FqName("kotlin.ranges.reversed")
}
// Reverse the HeaderInfo from the underlying progression or array (if any).
override fun build(expression: IrCall, data: Nothing?, scopeOwner: IrSymbol) =
expression.extensionReceiver!!.accept(visitor, null)?.asReversed()
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,679
|
kotlin
|
Apache License 2.0
|
android/app/src/main/java/com/algorand/android/modules/parity/data/mapper/CurrencyDetailDTOMapper.kt
|
perawallet
| 364,359,642
| false
|
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
|
/*
* Copyright 2022 Pera Wallet, LDA
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.algorand.android.modules.parity.data.mapper
import com.algorand.android.modules.parity.data.model.CurrencyDetailResponse
import com.algorand.android.modules.parity.domain.model.CurrencyDetailDTO
import javax.inject.Inject
class CurrencyDetailDTOMapper @Inject constructor() {
fun mapToCurrencyDetailDTO(
currencyDetailResponse: CurrencyDetailResponse
): CurrencyDetailDTO {
return with(currencyDetailResponse) {
CurrencyDetailDTO(
id = id,
name = name,
exchangePrice = exchangePrice,
symbol = symbol,
usdValue = usdValue,
lastUpdateTimestamp = lastUpdateTimestamp,
source = source
)
}
}
}
| 22
|
Swift
|
62
| 181
|
92fc77f73fa4105de82d5e87b03c1e67600a57c0
| 1,360
|
pera-wallet
|
Apache License 2.0
|
app/src/main/java/github/alexzhirkevich/studentbsuby/data/models/News.kt
|
alexzhirkevich
| 452,910,975
| false
|
{"Kotlin": 479612}
|
package github.alexzhirkevich.studentbsuby.data.models
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class News(
@PrimaryKey val id : Int,
val title : String,
val preview : String?,
)
@Entity
data class NewsContent(
@PrimaryKey val id : Int,
val content : String,
)
| 0
|
Kotlin
|
0
| 5
|
bf04ce772bb3d9485dffd5d3abf252be1754ce51
| 315
|
student-bsu-by
|
MIT License
|
app/src/main/java/com/savi/portadecinema/repositories/MovieRepository.kt
|
lostptr
| 537,272,567
| false
| null |
package com.savi.portadecinema.repositories
import com.savi.portadecinema.data.local.dao.MovieDao
import com.savi.portadecinema.data.local.entities.MovieEntity
import com.savi.portadecinema.data.remote.tmdb.TmdbService
import com.savi.portadecinema.models.MovieDetails
class MovieRepository(private val tmdbService: TmdbService, private val dao: MovieDao) :
IMovieRepository {
override fun getPopular(page: Int) = tmdbService.getPopularMovies(page)
override fun getDetails(movieId: Int) = tmdbService.getMovieDetails(movieId)
override fun getFavorites() = dao.getAll()
override suspend fun saveAsFavorite(movie: MovieDetails) =
dao.insert(with(movie) {
MovieEntity(
id = 0,
tmdbId = id,
title = title,
overview = overview,
rating = rating,
duration = duration,
genres = genres.joinToString(","),
releaseDate = releaseDate.toString(),
poster = poster,
backdrop = backdrop
)
})
override suspend fun removeFavorite(movieId: Int) = dao.delete(movieId)
override suspend fun checkIsFavorite(movieId: Int) = dao.checkIsFavorite(movieId)
}
| 3
|
Kotlin
|
0
| 0
|
91007176167e640ae61c06cff8658dc7b0755295
| 1,268
|
porta_de_cinema
|
MIT License
|
app/src/main/java/com/example/aguadiaria/GlassType.kt
|
afoliveira111
| 728,381,700
| false
|
{"Kotlin": 3380}
|
package com.example.aguadiaria
enum class GlassType(val value: Int) {
SMALL(200),
MEDIUM(250),
LARGE(500)
}
| 0
|
Kotlin
|
0
| 0
|
d7660956bf9c98c1466e571e6441106d7304ad84
| 120
|
AguaDiaria
|
The Unlicense
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.