path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/referral/jparepo/JpaReferralRepositoryTest.kt
|
ministryofjustice
| 615,402,552
| false
| null |
package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.referral.jparepo
import io.kotest.matchers.optional.shouldBePresent
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jdbc.core.JdbcTemplate
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.RepositoryTest
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.commitAndStartNewTx
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.course.domain.CourseEntity
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.course.domain.CourseRepository
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.course.domain.Offering
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.referral.domain.Referral
import java.util.UUID
class JpaReferralRepositoryTest
@Autowired
constructor(
val repository: JpaReferralRepository,
val courseRepository: CourseRepository,
jdbcTemplate: JdbcTemplate,
) : RepositoryTest(jdbcTemplate) {
@Test
fun `save and retrieve a referral`() {
val persistentOfferingId = persistOffering()
val referralId = repository.save(Referral(referrerId = "refId", prisonNumber = "A1234AA", offeringId = persistentOfferingId)).id!!
commitAndStartNewTx()
repository.findById(referralId) shouldBePresent {
referrerId shouldBe "refId"
prisonNumber shouldBe "A1234AA"
offeringId shouldBe persistentOfferingId
}
}
private fun persistOffering(): UUID {
courseRepository.saveCourse(
CourseEntity(
identifier = "C",
name = "Course",
alternateName = "Alt C",
).apply {
offerings.add(Offering(organisationId = "MDI", contactEmail = "a@b.c"))
},
)
commitAndStartNewTx()
return courseRepository.allCourses()[0].offerings.first().id
}
}
| 4
|
Kotlin
|
0
| 0
|
7fb76dccd8953bb0da90b5c906236a3de8b0592a
| 1,904
|
hmpps-accredited-programmes-api
|
MIT License
|
model/src/commonMain/kotlin/ScannerJob.kt
|
eclipse-apoapsis
| 760,319,414
| false
|
{"Kotlin": 2994047, "Dockerfile": 24090, "Shell": 6277}
|
/*
* Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.eclipse.apoapsis.ortserver.model
import kotlinx.datetime.Instant
import kotlinx.serialization.Serializable
@Serializable
data class EvaluatorJob(
/**
* The unique identifier.
*/
override val id: Long,
/**
* The ID of the [OrtRun] this [EvaluatorJob] is a part of.
*/
override val ortRunId: Long,
/**
* The time the job was created.
*/
override val createdAt: Instant,
/**
* The time the job was started.
*/
override val startedAt: Instant?,
/**
* The time the job finished.
*/
override val finishedAt: Instant?,
/**
* The job configuration.
*/
val configuration: EvaluatorJobConfiguration,
/**
* The job status.
*/
override val status: JobStatus
) : WorkerJob
| 18
|
Kotlin
|
2
| 9
|
0af70d6382a86f0ebc35d9b377f4229c6a71637a
| 1,561
|
ort-server
|
Apache License 2.0
|
app/src/main/java/com/example/gitapp/provider/UserContentProvider.kt
|
ni-sh-a-char
| 455,244,685
| false
|
{"Kotlin": 42314, "Shell": 3185}
|
package com.example.gitapp.provider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import com.example.gitapp.data.local.FavoriteUser
import com.example.gitapp.data.local.FavoriteUserDao
import com.example.gitapp.data.local.UserDatabase
class UserContentProvider : ContentProvider() {
companion object{
const val AUTHORITY = "com.example.gitapp"
const val TABLE_NAME = "favorite_user"
const val ID_FAVORITE_USER_DATA = 1
val uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
init {
uriMatcher.addURI(AUTHORITY, TABLE_NAME, ID_FAVORITE_USER_DATA)
}
}
private lateinit var userDao: FavoriteUserDao
override fun onCreate(): Boolean {
userDao = context?.let{ ctx ->
UserDatabase.getDatabase(ctx)?.favoriteUserDao()
}!!
return false
}
override fun query(
uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?, sortOrder: String?
): Cursor? {
var cursor: Cursor?
when (uriMatcher.match(uri)) {
ID_FAVORITE_USER_DATA -> {
cursor = userDao.findAll()
if (context != null){
cursor.setNotificationUri(context?.contentResolver, uri)
}
}
else -> {
cursor = null
}
}
return cursor
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
return 0
}
override fun getType(uri: Uri): String? {
return null
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
return null
}
override fun update(
uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<String>?
): Int {
return 0
}
}
| 0
|
Kotlin
|
0
| 0
|
85a273918982842e00493063a8a7e8258cbdbe15
| 1,951
|
Gitapp
|
MIT License
|
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/types/KeyboardButton.kt
|
gagarski
| 314,041,476
| false
|
{"Kotlin": 339081}
|
package ski.gagar.vxutil.vertigram.types
data class KeyboardButton(
val text: String,
val requestContact: Boolean? = false,
val requestLocation: Boolean? = false,
val requestPoll: KeyboardButtonPollType? = null,
val webApp: WebAppInfo? = null,
// Since Telegram Bot Api 6.5
val requestUser: KeyboardButtonRequestUser? = null,
val requestChat: KeyboardButtonRequestChat? = null,
)
| 0
|
Kotlin
|
0
| 0
|
76fcae3eb17c34d4afc463403e49195070589139
| 413
|
vxutil
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/opensearchserverless/CfnSecurityConfigDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.opensearchserverless
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.opensearchserverless.CfnSecurityConfig
import software.constructs.Construct
/**
* Specifies a security configuration for OpenSearch Serverless.
*
* For more information, see
* [SAML authentication for Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-saml.html)
* .
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.opensearchserverless.*;
* CfnSecurityConfig cfnSecurityConfig = CfnSecurityConfig.Builder.create(this,
* "MyCfnSecurityConfig")
* .description("description")
* .name("name")
* .samlOptions(SamlConfigOptionsProperty.builder()
* .metadata("metadata")
* // the properties below are optional
* .groupAttribute("groupAttribute")
* .sessionTimeout(123)
* .userAttribute("userAttribute")
* .build())
* .type("type")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opensearchserverless-securityconfig.html)
*/
@CdkDslMarker
public class CfnSecurityConfigDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnSecurityConfig.Builder = CfnSecurityConfig.Builder.create(scope, id)
/**
* The description of the security configuration.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opensearchserverless-securityconfig.html#cfn-opensearchserverless-securityconfig-description)
*
* @param description The description of the security configuration.
*/
public fun description(description: String) {
cdkBuilder.description(description)
}
/**
* The name of the security configuration.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opensearchserverless-securityconfig.html#cfn-opensearchserverless-securityconfig-name)
*
* @param name The name of the security configuration.
*/
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* SAML options for the security configuration in the form of a key-value map.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opensearchserverless-securityconfig.html#cfn-opensearchserverless-securityconfig-samloptions)
*
* @param samlOptions SAML options for the security configuration in the form of a key-value
* map.
*/
public fun samlOptions(samlOptions: IResolvable) {
cdkBuilder.samlOptions(samlOptions)
}
/**
* SAML options for the security configuration in the form of a key-value map.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opensearchserverless-securityconfig.html#cfn-opensearchserverless-securityconfig-samloptions)
*
* @param samlOptions SAML options for the security configuration in the form of a key-value
* map.
*/
public fun samlOptions(samlOptions: CfnSecurityConfig.SamlConfigOptionsProperty) {
cdkBuilder.samlOptions(samlOptions)
}
/**
* The type of security configuration.
*
* Currently the only option is `saml` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opensearchserverless-securityconfig.html#cfn-opensearchserverless-securityconfig-type)
*
* @param type The type of security configuration.
*/
public fun type(type: String) {
cdkBuilder.type(type)
}
public fun build(): CfnSecurityConfig = cdkBuilder.build()
}
| 4
| null |
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 4,145
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
android/src/main/java/com/rnmapbox/rnmbx/utils/extensions/Dynamic.kt
|
rnmapbox
| 180,028,389
| false
|
{"Kotlin": 752850, "Swift": 462623, "TypeScript": 454914, "JavaScript": 335927, "Java": 131768, "Objective-C++": 120743, "Objective-C": 37244, "EJS": 24288, "Ruby": 13289, "C": 3203, "Starlark": 1328, "Shell": 446}
|
package com.rnmapbox.rnmbx.utils.extensions
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.ReadableType
import com.mapbox.bindgen.Value
fun ReadableMap.toValueHashMap(): HashMap<String, Value> {
var result = hashMapOf<String, Value>()
var iterator = keySetIterator()
while (iterator.hasNextKey()) {
val i = iterator.nextKey()
result[i] = when (getType(i)) {
ReadableType.Null -> Value.nullValue()
ReadableType.Boolean -> Value.valueOf(getBoolean(i))
ReadableType.Number -> Value.valueOf(getDouble(i))
ReadableType.String -> Value.valueOf(getString(i)!!)
ReadableType.Array -> getArray(i)!!.toValue()
ReadableType.Map -> getMap(i)!!.toValue()
}
}
return result
}
fun ReadableMap.toValue() : Value {
return Value.valueOf(toValueHashMap())
}
fun ReadableArray.toValue(): Value {
var result = ArrayList<Value>(size())
for (i in 0 until size()) {
result.add(
when (getType(i)) {
ReadableType.Null -> Value.nullValue()
ReadableType.Boolean -> Value.valueOf(getBoolean(i))
ReadableType.Number -> Value.valueOf(getDouble(i))
ReadableType.String -> Value.valueOf(getString(i))
ReadableType.Array -> getArray(i).toValue()
ReadableType.Map -> getMap(i).toValue()
})
}
return Value.valueOf(result)
}
fun Dynamic.toValue(): Value {
return when (type) {
ReadableType.Null -> Value.nullValue()
ReadableType.Boolean -> Value.valueOf(asBoolean())
ReadableType.Number -> Value.valueOf(asDouble())
ReadableType.String -> Value.valueOf(asString())
ReadableType.Array -> asArray().toValue()
ReadableType.Map -> asMap().toValue()
}
}
| 95
|
Kotlin
|
844
| 2,244
|
f87653dc694e9478a4fda1d2e7585f22bc1b95cb
| 1,926
|
maps
|
MIT License
|
src/main/kotlin/com/github/zerocode/map4k/configuration/TypeMapBuilder.kt
|
zerocode
| 159,180,311
| false
| null |
package com.github.zerocode.map4k.configuration
import com.github.zerocode.map4k.MappingException
import com.github.zerocode.map4k.extensions.returnTypeClass
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.createType
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.primaryConstructor
data class TypeMapBuilder(
val sourceClass: KClass<*>,
val targetClass: KClass<*>,
val userDefinedPropertyMaps: List<PropertyMap> = emptyList()
) {
inline fun <reified TSource : Any, reified TSourceReturn : Any, reified TTarget : Any, reified TTargetReturn> propertyMap(
sourceProperty: KProperty1<TSource, TSourceReturn>,
targetProperty: KProperty1<TTarget, TTargetReturn>
): TypeMapBuilder {
return this.copy(
userDefinedPropertyMaps = this.userDefinedPropertyMaps + PropertyMap(
targetProperty = targetProperty,
targetParameter = TTarget::class.primaryConstructor?.parameters?.first { it.name == targetProperty.name }!!,
sourceResolution = NamedSourceResolution(sourceProperty),
conversion = TypeConversions.noopConverter(sourceProperty.returnTypeClass, sourceProperty.returnType, targetProperty.returnTypeClass)
))
}
inline fun <reified TSource : Any, reified TSourceReturn : Any, reified TTarget : Any, reified TTargetReturn> propertyMap(
sourceProperty: KProperty1<TSource, TSourceReturn>,
targetProperty: KProperty1<TTarget, TTargetReturn>,
noinline converter: Function1<TSourceReturn, TTargetReturn>
): TypeMapBuilder {
return this.copy(
userDefinedPropertyMaps = this.userDefinedPropertyMaps + PropertyMap(
targetProperty = targetProperty,
targetParameter = TTarget::class.primaryConstructor?.parameters?.first { it.name == targetProperty.name }!!,
sourceResolution = ConvertedSourceResolution(
sourceProperty = sourceProperty
),
conversion = SimpleTypeConverter(TSourceReturn::class, TTargetReturn::class, converter as (Any) -> Any)
))
}
inline fun <reified TSource : Any, reified TTarget : Any, reified TTargetReturn> propertyMap(
targetProperty: KProperty1<TTarget, TTargetReturn>,
noinline generator: Function1<TSource, TTargetReturn>
): TypeMapBuilder {
return this.copy(
userDefinedPropertyMaps = this.userDefinedPropertyMaps + PropertyMap(
targetProperty = targetProperty,
targetParameter = TTarget::class.primaryConstructor?.parameters?.first { it.name == targetProperty.name }!!,
sourceResolution = GeneratedSourceResolution(generator = generator as Function1<Any?, *>),
conversion = TypeConversions.noopConverter(TSource::class, TSource::class.createType(), targetProperty.returnTypeClass)
))
}
// TODO test & refactor
fun build(
typeConversions: TypeConversions = TypeConversions(),
options: MappingOptions = MappingOptions()
): TypeMap {
try {
val generatedPropertyMaps = autoGeneratedPropertyMaps()
val propertyMapsWithTypeConversions = addGlobalTypeConversionsToPropertyMaps(typeConversions, generatedPropertyMaps)
return TypeMap(sourceClass, targetClass, propertyMapsWithTypeConversions)
} catch (ex: Exception) {
throw MappingException("Cannot create type map for $sourceClass and $targetClass. ${ex.message}")
}
}
private fun autoGeneratedPropertyMaps(): Collection<PropertyMap> {
return targetClass.declaredMemberProperties
.filterNot { targetProperty -> userDefinedPropertyMaps.map { it.targetPropertyName }.contains(targetProperty.name) }
.mapNotNull { targetProperty ->
targetClass.primaryConstructor?.parameters?.firstOrNull { it.name == targetProperty.name }?.let { targetParameter ->
sourceClass.declaredMemberProperties.firstOrNull { it.name == targetProperty.name }?.let { sourceProperty ->
PropertyMap(
targetProperty = targetProperty,
targetParameter = targetParameter,
sourceResolution = NamedSourceResolution(sourceProperty),
conversion = TypeConversions.noopConverter(sourceProperty.returnTypeClass, sourceProperty.returnType, targetProperty.returnTypeClass)
)
}
}
} + userDefinedPropertyMaps
}
private fun addGlobalTypeConversionsToPropertyMaps(typeConversions: TypeConversions, propertyMaps: Collection<PropertyMap>): List<PropertyMap> {
return propertyMaps.map {
when (it.sourceResolution) {
is NamedSourceResolution -> {
val converter = typeConversions.getConverter(it.sourceResolution.sourceProperty.returnTypeClass, it.targetPropertyClass)
if (converter != null) {
it.copy(conversion = converter)
} else {
it
}
}
else -> it
}
}
}
}
| 1
|
Kotlin
|
1
| 1
|
fae9b311fcfd1386652b2d87ef01b074c1aa9d84
| 5,471
|
map4k
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Sausage.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.Sausage: ImageVector
get() {
if (_sausage != null) {
return _sausage!!
}
_sausage = Builder(name = "Sausage", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(20.333f, 3.2f)
arcTo(4.589f, 4.589f, 0.0f, false, false, 22.0f, 0.0f)
horizontalLineTo(20.0f)
arcToRelative(2.732f, 2.732f, 0.0f, false, true, -1.0f, 1.709f)
arcTo(2.739f, 2.739f, 0.0f, false, true, 18.0f, 0.0f)
horizontalLineTo(16.0f)
arcToRelative(4.585f, 4.585f, 0.0f, false, false, 1.665f, 3.2f)
arcTo(4.932f, 4.932f, 0.0f, false, false, 14.0f, 7.905f)
arcToRelative(6.7f, 6.7f, 0.0f, false, true, -2.2f, 3.916f)
arcToRelative(7.091f, 7.091f, 0.0f, false, true, -3.881f, 2.2f)
arcToRelative(4.934f, 4.934f, 0.0f, false, false, -4.716f, 3.652f)
arcTo(4.586f, 4.586f, 0.0f, false, false, 0.0f, 16.0f)
verticalLineToRelative(2.0f)
arcToRelative(2.732f, 2.732f, 0.0f, false, true, 1.709f, 1.0f)
arcTo(2.734f, 2.734f, 0.0f, false, true, 0.0f, 20.0f)
verticalLineToRelative(2.0f)
arcToRelative(4.587f, 4.587f, 0.0f, false, false, 3.2f, -1.664f)
arcTo(5.0f, 5.0f, 0.0f, false, false, 8.0f, 24.0f)
curveToRelative(0.962f, 0.0f, 6.011f, -0.271f, 10.865f, -5.115f)
curveTo(23.753f, 14.014f, 24.0f, 8.987f, 24.0f, 8.029f)
arcTo(5.017f, 5.017f, 0.0f, false, false, 20.333f, 3.2f)
close()
}
}
.build()
return _sausage!!
}
private var _sausage: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 2,642
|
icons
|
MIT License
|
kotlin/lib-spring-boot-llm-os/src/main/kotlin/com/github/frtu/kotlin/llm/os/llm/MessageBuilder.kt
|
frtu
| 338,595,537
| false
|
{"Kotlin": 396231, "Java": 157399, "Shell": 10826, "Dockerfile": 248}
|
package com.github.frtu.kotlin.llm.os.llm
import com.aallam.openai.api.chat.ChatMessage
import com.aallam.openai.api.chat.ChatRole
import com.aallam.openai.api.chat.FunctionCall
/**
* Encapsulate aallam chat message builder and role into function
*/
object MessageBuilder {
fun system(content: String) = createMessage(ChatRole.System, content)
fun user(content: String) = createMessage(ChatRole.User, content)
fun assistant(content: String) = createMessage(ChatRole.Assistant, content)
fun function(functionName: String, content: String) = createMessage(ChatRole.Function, content, functionName)
fun createMessage(
role: ChatRole,
content: String? = null,
name: String? = null,
functionCall: FunctionCall? = null,
) = ChatMessage(role, content, name, functionCall)
}
| 0
|
Kotlin
|
0
| 1
|
d641ca6826d57d91985da34492eff8a92ad9261e
| 830
|
lib-toolbox
|
Apache License 2.0
|
spring-batch-plus-kotlin/src/main/kotlin/com/navercorp/spring/batch/plus/kotlin/configuration/support/LazyConfigurer.kt
|
naver
| 558,165,952
| false
|
{"Kotlin": 961076, "Java": 446765}
|
/*
* Spring Batch Plus
*
* Copyright 2022-present NAVER Corp.
*
* 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.navercorp.spring.batch.plus.kotlin.configuration.support
internal fun interface Configurer<T : Any> : (T) -> Unit
/**
* A class to configure builder lazily.
*/
internal class LazyConfigurer<T : Any> : Configurer<T> {
private val configurers = mutableListOf<Configurer<T>>()
fun add(configurer: Configurer<T>) {
configurers.add(configurer)
}
override fun invoke(target: T) {
configurers.forEach {
target.apply(it)
}
}
}
| 4
|
Kotlin
|
9
| 99
|
01a5aefe9b860b8ea951832114422581ff49d101
| 1,122
|
spring-batch-plus
|
Apache License 2.0
|
favorite/src/main/java/com/aprian1337/favorite/FavoriteComponent.kt
|
aprian1337
| 374,189,692
| false
| null |
package com.aprian1337.favorite
import android.content.Context
import com.aprian1337.batique.di.FavDependencies
import dagger.BindsInstance
import dagger.Component
@Component(dependencies = [FavDependencies::class])
interface FavoriteComponent {
fun inject(act: FavoriteFragment)
@Component.Builder
interface Builder{
fun context(@BindsInstance context: Context): Builder
fun dependencies(dependency: FavDependencies): Builder
fun build(): FavoriteComponent
}
}
| 0
|
Kotlin
|
0
| 0
|
ca39d150ac57d5b2d3cb80d21a240fa581826fd5
| 504
|
batique
|
MIT License
|
foundation/src/commonMain/kotlin/me.lincolnstuart.funblocks.foundation.ui/token/content/border/FunBlocksBorderWidth.kt
|
LincolnStuart
| 645,064,211
| false
|
{"Kotlin": 451042}
|
package me.lincolnstuart.funblocks.foundation.ui.token.content.border
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* Object that provides border width tokens to standard surface components.
*
* Based on [androidx.compose.ui.unit.Dp].
*/
public object FunBlocksBorderWidth {
public val none: Dp = 0.dp
public val tiny: Dp = 0.5.dp
public val regular: Dp = 1.dp
public val large: Dp = 2.dp
}
| 0
|
Kotlin
|
0
| 4
|
5a9d60f062132df12a6022530dfa10692fbf6c6d
| 441
|
fun-blocks
|
MIT License
|
sketch-core/src/commonTest/kotlin/com/github/panpf/sketch/core/common/test/request/internal/RequestInterceptorChainTest.kt
|
panpf
| 14,798,941
| false
|
{"Kotlin": 2979756, "Shell": 1469}
|
package com.github.panpf.sketch.core.common.test.request.internal
class RequestInterceptorChainTest {
// TODO test
}
| 8
|
Kotlin
|
309
| 2,057
|
89784530da0de6085a5b08f810415147cb3165cf
| 121
|
sketch
|
Apache License 2.0
|
core/src/main/kotlin/sh/christian/aaraar/utils/files.kt
|
christiandeange
| 588,680,111
| false
|
{"Kotlin": 266948, "Shell": 1171}
|
package sh.christian.aaraar.utils
import java.io.File
import java.net.URI
import java.nio.file.FileSystem
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
internal operator fun Path.div(path: String): Path {
return resolve(path)
}
internal operator fun FileSystem.div(path: String): Path {
return getPath(path)
}
internal fun Path.mkdirs(): Path {
return apply { parent?.let(Files::createDirectories) }
}
internal fun Path.deleteIfExists(): Path {
return apply { Files.deleteIfExists(this) }
}
/**
* Creates a new archive file at the specified path, returning a [FileSystem] that represents the internal structure
* of the archive to which files can be read, written, and deleted.
*/
fun <T> Path.createArchive(block: (FileSystem) -> T): T = asArchiveFileSystem(env = mapOf("create" to true), block)
/**
* Opens an existing archive file at the specified path, returning a [FileSystem] that represents the internal structure
* of the archive to which files can be read, written, and deleted.
*/
fun <T> Path.openArchive(block: (FileSystem) -> T): T = asArchiveFileSystem(env = emptyMap(), block)
private fun <T> Path.asArchiveFileSystem(
env: Map<String, Any?> = emptyMap(),
block: (FileSystem) -> T,
): T {
val fileSystemUri = if (File.separatorChar == '\\') {
URI.create("jar:file:/${toAbsolutePath().toString().replace("\\", "/")}")
} else {
URI.create("jar:file:${toAbsolutePath()}")
}
return runCatching {
FileSystems.newFileSystem(fileSystemUri, env)
}.getOrElse { e ->
throw IllegalStateException("Cannot create filesystem for ${toAbsolutePath()}", e)
}.use(block)
}
| 1
|
Kotlin
|
2
| 32
|
9e1bb7ca023d4e3f40dc24fd93b6360fde252d5e
| 1,665
|
aaraar
|
Apache License 2.0
|
plugins/base/src/main/kotlin/transformers/documentables/DeprecatedDocumentableFilterTransformer.kt
|
hamza1311
| 289,545,081
| true
|
{"Kotlin": 1390491, "CSS": 20105, "JavaScript": 15166, "TypeScript": 11065, "SCSS": 1734, "Java": 1484}
|
package org.jetbrains.dokka.base.transformers.documentables
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.model.*
import org.jetbrains.dokka.model.properties.WithExtraProperties
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.transformers.documentation.PreMergeDocumentableTransformer
class DeprecatedDocumentableFilterTransformer(val context: DokkaContext) : PreMergeDocumentableTransformer {
override fun invoke(modules: List<DModule>) = modules.map { original ->
val sourceSet = original.sourceSets.single()
val packageOptions =
sourceSet.perPackageOptions
original.let {
DeprecatedDocumentableFilter(sourceSet, packageOptions).processModule(it)
}
}
private class DeprecatedDocumentableFilter(
val globalOptions: DokkaConfiguration.DokkaSourceSet,
val packageOptions: List<DokkaConfiguration.PackageOptions>
) {
fun <T> T.isAllowedInPackage(): Boolean where T : WithExtraProperties<T>, T : Documentable {
val packageName = this.dri.packageName
val condition = packageName != null && packageOptions.firstOrNull {
packageName.startsWith(it.prefix)
}?.skipDeprecated
?: globalOptions.skipDeprecated
fun T.isDeprecated() = extra[Annotations]?.let { annotations ->
annotations.content.values.flatten().any {
it.dri.toString() == "kotlin/Deprecated///PointingToDeclaration/"
}
} ?: false
return !(condition && this.isDeprecated())
}
fun processModule(original: DModule) =
filterPackages(original.packages).let { (modified, packages) ->
if (!modified) original
else
DModule(
original.name,
packages = packages,
documentation = original.documentation,
sourceSets = original.sourceSets,
extra = original.extra
)
}
private fun filterPackages(packages: List<DPackage>): Pair<Boolean, List<DPackage>> {
var packagesListChanged = false
val filteredPackages = packages.mapNotNull { pckg ->
var modified = false
val functions = filterFunctions(pckg.functions).let { (listModified, list) ->
modified = modified || listModified
list
}
val properties = filterProperties(pckg.properties).let { (listModified, list) ->
modified = modified || listModified
list
}
val classlikes = filterClasslikes(pckg.classlikes).let { (listModified, list) ->
modified = modified || listModified
list
}
when {
!modified -> pckg
else -> {
packagesListChanged = true
DPackage(
pckg.dri,
functions,
properties,
classlikes,
pckg.typealiases,
pckg.documentation,
pckg.expectPresentInSet,
pckg.sourceSets,
pckg.extra
)
}
}
}
return Pair(packagesListChanged, filteredPackages)
}
private fun filterFunctions(
functions: List<DFunction>
) = functions.filter { it.isAllowedInPackage() }.let {
Pair(it.size != functions.size, it)
}
private fun filterProperties(
properties: List<DProperty>
): Pair<Boolean, List<DProperty>> = properties.filter {
it.isAllowedInPackage()
}.let {
Pair(properties.size != it.size, it)
}
private fun filterEnumEntries(entries: List<DEnumEntry>) =
entries.filter { it.isAllowedInPackage() }.map { entry ->
DEnumEntry(
entry.dri,
entry.name,
entry.documentation,
entry.expectPresentInSet,
filterFunctions(entry.functions).second,
filterProperties(entry.properties).second,
filterClasslikes(entry.classlikes).second,
entry.sourceSets,
entry.extra
)
}
private fun filterClasslikes(
classlikeList: List<DClasslike>
): Pair<Boolean, List<DClasslike>> {
var modified = false
return classlikeList.filter { classlike ->
when (classlike) {
is DClass -> classlike.isAllowedInPackage()
is DInterface -> classlike.isAllowedInPackage()
is DEnum -> classlike.isAllowedInPackage()
is DObject -> classlike.isAllowedInPackage()
is DAnnotation -> classlike.isAllowedInPackage()
}
}.map { classlike ->
fun helper(): DClasslike = when (classlike) {
is DClass -> DClass(
classlike.dri,
classlike.name,
filterFunctions(classlike.constructors).let {
modified = modified || it.first; it.second
},
filterFunctions(classlike.functions).let {
modified = modified || it.first; it.second
},
filterProperties(classlike.properties).let {
modified = modified || it.first; it.second
},
filterClasslikes(classlike.classlikes).let {
modified = modified || it.first; it.second
},
classlike.sources,
classlike.visibility,
classlike.companion,
classlike.generics,
classlike.supertypes,
classlike.documentation,
classlike.expectPresentInSet,
classlike.modifier,
classlike.sourceSets,
classlike.extra
)
is DAnnotation -> DAnnotation(
classlike.name,
classlike.dri,
classlike.documentation,
classlike.expectPresentInSet,
classlike.sources,
filterFunctions(classlike.functions).let {
modified = modified || it.first; it.second
},
filterProperties(classlike.properties).let {
modified = modified || it.first; it.second
},
filterClasslikes(classlike.classlikes).let {
modified = modified || it.first; it.second
},
classlike.visibility,
classlike.companion,
filterFunctions(classlike.constructors).let {
modified = modified || it.first; it.second
},
classlike.generics,
classlike.sourceSets,
classlike.extra
)
is DEnum -> DEnum(
classlike.dri,
classlike.name,
filterEnumEntries(classlike.entries),
classlike.documentation,
classlike.expectPresentInSet,
classlike.sources,
filterFunctions(classlike.functions).let {
modified = modified || it.first; it.second
},
filterProperties(classlike.properties).let {
modified = modified || it.first; it.second
},
filterClasslikes(classlike.classlikes).let {
modified = modified || it.first; it.second
},
classlike.visibility,
classlike.companion,
filterFunctions(classlike.constructors).let {
modified = modified || it.first; it.second
},
classlike.supertypes,
classlike.sourceSets,
classlike.extra
)
is DInterface -> DInterface(
classlike.dri,
classlike.name,
classlike.documentation,
classlike.expectPresentInSet,
classlike.sources,
filterFunctions(classlike.functions).let {
modified = modified || it.first; it.second
},
filterProperties(classlike.properties).let {
modified = modified || it.first; it.second
},
filterClasslikes(classlike.classlikes).let {
modified = modified || it.first; it.second
},
classlike.visibility,
classlike.companion,
classlike.generics,
classlike.supertypes,
classlike.sourceSets,
classlike.extra
)
is DObject -> DObject(
classlike.name,
classlike.dri,
classlike.documentation,
classlike.expectPresentInSet,
classlike.sources,
filterFunctions(classlike.functions).let {
modified = modified || it.first; it.second
},
filterProperties(classlike.properties).let {
modified = modified || it.first; it.second
},
filterClasslikes(classlike.classlikes).let {
modified = modified || it.first; it.second
},
classlike.visibility,
classlike.supertypes,
classlike.sourceSets,
classlike.extra
)
}
helper()
}.let {
Pair(it.size != classlikeList.size || modified, it)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
dfc5910730a1e09d09ad4de199bf7636c225dfc4
| 11,336
|
dokka
|
Apache License 2.0
|
remote/src/main/java/com/icgen/movieapp/remote/common/ApiHelper.kt
|
Ahnset
| 539,038,324
| false
|
{"Kotlin": 138435}
|
package com.icgen.movieapp.remote.common
object ApiHelper {
const val OKHTTP_MAX_CACHE_SIZE: Long = 50 * 1024 * 1024
const val CACHE_CONTROL = "Cache-Control"
const val CACHE_TIMEOUT = 5
}
| 0
|
Kotlin
|
2
| 3
|
a5ddc921f8f4df80cc13f17284015086fe6112b0
| 202
|
movieapp
|
Apache License 2.0
|
library/src/main/kotlin/eu/tib/orkg/prototype/community/adapter/output/jpa/internal/PostgresObservatoryRepository.kt
|
TIBHannover
| 197,416,205
| false
| null |
package eu.tib.orkg.prototype.community.adapter.output.jpa.internal
import java.util.Optional
import java.util.UUID
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
interface PostgresObservatoryRepository : JpaRepository<ObservatoryEntity, UUID> {
fun findByOrganizationsId(id: UUID): List<ObservatoryEntity>
fun findByName(name: String): Optional<ObservatoryEntity>
@Query("""FROM ObservatoryEntity WHERE (displayId=:name or displayId=LOWER(:name))""")
fun findByDisplayId(name: String): Optional<ObservatoryEntity>
fun findByResearchField(researchField: String): List<ObservatoryEntity>
}
| 0
|
Kotlin
|
1
| 4
|
84e17adb51e35e7123e1d853d49ae1d8ea95d400
| 681
|
orkg-backend
|
MIT License
|
app/server/src/main/jooq/io/github/novemdecillion/adapter/jooq/tables/records/AccountGroupAuthority_1Record.kt
|
novemdecillion
| 332,666,905
| false
| null |
/*
* This file is generated by jOOQ.
*/
package io.github.novemdecillion.adapter.jooq.tables.records
import io.github.novemdecillion.adapter.jooq.tables.AccountGroupAuthority_1Table
import io.github.novemdecillion.adapter.jooq.tables.interfaces.IAccountGroupAuthority_1
import java.util.UUID
import org.jooq.Field
import org.jooq.JSONB
import org.jooq.Record3
import org.jooq.Record4
import org.jooq.Row4
import org.jooq.impl.UpdatableRecordImpl
/**
* This class is generated by jOOQ.
*/
@Suppress("UNCHECKED_CAST")
open class AccountGroupAuthority_1Record() : UpdatableRecordImpl<AccountGroupAuthority_1Record>(AccountGroupAuthority_1Table.ACCOUNT_GROUP_AUTHORITY_1), Record4<UUID?, UUID?, Int?, JSONB?>, IAccountGroupAuthority_1 {
override var accountId: UUID?
set(value) = set(0, value)
get() = get(0) as UUID?
override var groupTransitionId: UUID?
set(value) = set(1, value)
get() = get(1) as UUID?
override var groupGenerationId: Int?
set(value) = set(2, value)
get() = get(2) as Int?
override var role: JSONB?
set(value) = set(3, value)
get() = get(3) as JSONB?
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
override fun key(): Record3<UUID?, UUID?, Int?> = super.key() as Record3<UUID?, UUID?, Int?>
// -------------------------------------------------------------------------
// Record4 type implementation
// -------------------------------------------------------------------------
override fun fieldsRow(): Row4<UUID?, UUID?, Int?, JSONB?> = super.fieldsRow() as Row4<UUID?, UUID?, Int?, JSONB?>
override fun valuesRow(): Row4<UUID?, UUID?, Int?, JSONB?> = super.valuesRow() as Row4<UUID?, UUID?, Int?, JSONB?>
override fun field1(): Field<UUID?> = AccountGroupAuthority_1Table.ACCOUNT_GROUP_AUTHORITY_1.ACCOUNT_ID
override fun field2(): Field<UUID?> = AccountGroupAuthority_1Table.ACCOUNT_GROUP_AUTHORITY_1.GROUP_TRANSITION_ID
override fun field3(): Field<Int?> = AccountGroupAuthority_1Table.ACCOUNT_GROUP_AUTHORITY_1.GROUP_GENERATION_ID
override fun field4(): Field<JSONB?> = AccountGroupAuthority_1Table.ACCOUNT_GROUP_AUTHORITY_1.ROLE
override fun component1(): UUID? = accountId
override fun component2(): UUID? = groupTransitionId
override fun component3(): Int? = groupGenerationId
override fun component4(): JSONB? = role
override fun value1(): UUID? = accountId
override fun value2(): UUID? = groupTransitionId
override fun value3(): Int? = groupGenerationId
override fun value4(): JSONB? = role
override fun value1(value: UUID?): AccountGroupAuthority_1Record {
this.accountId = value
return this
}
override fun value2(value: UUID?): AccountGroupAuthority_1Record {
this.groupTransitionId = value
return this
}
override fun value3(value: Int?): AccountGroupAuthority_1Record {
this.groupGenerationId = value
return this
}
override fun value4(value: JSONB?): AccountGroupAuthority_1Record {
this.role = value
return this
}
override fun values(value1: UUID?, value2: UUID?, value3: Int?, value4: JSONB?): AccountGroupAuthority_1Record {
this.value1(value1)
this.value2(value2)
this.value3(value3)
this.value4(value4)
return this
}
// -------------------------------------------------------------------------
// FROM and INTO
// -------------------------------------------------------------------------
override fun from(from: IAccountGroupAuthority_1) {
accountId = from.accountId
groupTransitionId = from.groupTransitionId
groupGenerationId = from.groupGenerationId
role = from.role
}
override fun <E : IAccountGroupAuthority_1> into(into: E): E {
into.from(this)
return into
}
/**
* Create a detached, initialised AccountGroupAuthority_1Record
*/
constructor(accountId: UUID? = null, groupTransitionId: UUID? = null, groupGenerationId: Int? = null, role: JSONB? = null): this() {
this.accountId = accountId
this.groupTransitionId = groupTransitionId
this.groupGenerationId = groupGenerationId
this.role = role
}
}
| 10
|
Kotlin
|
0
| 0
|
ea259afd23a28ccf03aa7c5c6f35b932d2c22182
| 4,435
|
magic-lantern
|
Apache License 2.0
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/teleops/auto/MainAuto.kt
|
LincolnRoboticsFTC14298
| 694,390,163
| false
|
{"Kotlin": 261529, "Java": 140195}
|
package org.firstinspires.ftc.teamcode.teleops.auto
import android.util.Log
import androidx.annotation.NonNull
import com.acmerobotics.dashboard.telemetry.TelemetryPacket
import com.acmerobotics.roadrunner.Action
import com.acmerobotics.roadrunner.InstantAction
import com.acmerobotics.roadrunner.Pose2d
import com.acmerobotics.roadrunner.SequentialAction
import com.acmerobotics.roadrunner.SleepAction
import com.acmerobotics.roadrunner.Vector2d
import com.acmerobotics.roadrunner.ftc.runBlocking
import com.qualcomm.robotcore.eventloop.opmode.Autonomous
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode
import com.qualcomm.robotcore.util.ElapsedTime
import org.firstinspires.ftc.teamcode.subsystems.DualClaw
import org.firstinspires.ftc.teamcode.subsystems.Passthrough
import org.firstinspires.ftc.teamcode.subsystems.Vision
import org.firstinspires.ftc.teamcode.subsystems.actions.*
import org.firstinspires.ftc.teamcode.subsystems.localization.StartingPose
import org.firstinspires.ftc.teamcode.subsystems.localization.StartingPoseStorage
import java.lang.Math.toRadians
//TODO test autos!
//TODO double check tangents (I'm pretty sure I screwed some of them up (polarity) also some them I found were screwed up)
//TODO just double check everything in general ig
@Autonomous
class MainAuto : LinearOpMode() {
private var spikePosition: Vision.SpikeDirection = Vision.SpikeDirection.LEFT
val autoTimer = ElapsedTime()
override fun runOpMode() {
val drive = MecanumDriveRR( //TODO check with normal drive subsystem
hardwareMap,
StartingPoseStorage.startingPose.pose
)
val vision = Vision(hardwareMap)
val passthrough = Passthrough(hardwareMap)
val claw = DualClaw(hardwareMap)
autoTimer.reset()
// Trajectories
//Blue Right - DONE
val blueRightPartOne = drive.actionBuilder(drive.pose)
.setTangent(toRadians(-90.0))
.splineToConstantHeading(Vector2d(-57.0, -42.0), toRadians(0.0))
.splineToLinearHeading(Pose2d(-45.0, -36.0, toRadians(0.0)), toRadians(180.0))
.build()
val blueRightPixelLeft = drive.actionBuilder(Pose2d(-45.0, -36.0, toRadians(0.0)))
.setTangent(toRadians(-90.0))
.splineToLinearHeading(Pose2d(-32.0, -39.5, toRadians(90.0)), toRadians(-90.0))
.build()
val blueRightPixelCenter = drive.actionBuilder(Pose2d(-45.0, -36.0, toRadians(0.0)))
.setTangent(toRadians(0.0))
.splineToLinearHeading(Pose2d(-42.0, -36.0, toRadians(0.0)), toRadians(0.0))
.build()
val blueRightPixelRight = drive.actionBuilder(Pose2d(-45.0, -36.0, toRadians(0.0)))
.setTangent(toRadians(90.0))
.splineToLinearHeading(Pose2d(-45.0, -40.5, toRadians(-30.0)), toRadians(90.0))
.build()
val blueRightPartTwo = drive.actionBuilder(Pose2d(-59.0, -48.0, toRadians(-90.0)))
.setTangent(toRadians(90.0))
.splineToConstantHeading(Vector2d(-60.0, 36.0), toRadians(90.0))
.splineToConstantHeading(Vector2d(-36.0, 36.0), toRadians(0.0))
.build()
val blueRightBackdropLeft = drive.actionBuilder(Pose2d(-36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(180.0))
.splineToConstantHeading(Vector2d(-40.0, 40.0), toRadians(90.0))
.build()
val blueRightBackdropCenter = drive.actionBuilder(Pose2d(-36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(-90.0))
.splineToConstantHeading(Vector2d(-36.0, 40.0), toRadians(90.0))
.build()
val blueRightBackdropRight = drive.actionBuilder(Pose2d(-36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(0.0))
.splineToConstantHeading(Vector2d(-32.0, 40.0), toRadians(90.0))
.build()
//Blue Left - DONE
val blueLeftPartOne = drive.actionBuilder(drive.pose)
.setTangent(toRadians(90.0))
.splineToConstantHeading(Vector2d(-54.0, 24.0), toRadians(45.0))
.splineToLinearHeading(Pose2d(-54.0, 18.0, toRadians(0.0)), toRadians(-90.0))
.splineToConstantHeading(Vector2d(-45.0, 12.0), toRadians(90.0))
.build()
val blueLeftPixelLeft = drive.actionBuilder(Pose2d(-45.0, 12.0, toRadians(0.0)))
.setTangent(toRadians(0.0))
.splineToLinearHeading(Pose2d(-29.0, 15.5, toRadians(90.0)), toRadians(30.0))
.build()
val blueLeftPixelCenter = drive.actionBuilder(Pose2d(-45.0, 12.0, toRadians(0.0)))
.setTangent(toRadians(0.0))
.splineToLinearHeading(Pose2d(-39.0, 12.0, toRadians(0.0)), toRadians(0.0))
.build()
val blueLeftPixelRight = drive.actionBuilder(Pose2d(-45.0, 12.0, toRadians(0.0)))
.setTangent(toRadians(0.0))
.splineToLinearHeading(Pose2d(-45.0, 8.5, toRadians(90.0)), toRadians(-30.0))
.build()
val blueLeftPartTwo = drive.actionBuilder(Pose2d(-54.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(90.0))
.splineToConstantHeading(Vector2d(-36.0, 36.0), toRadians(0.0))
.build()
val blueLeftBackdropLeft = drive.actionBuilder(Pose2d(-36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(180.0))
.splineToConstantHeading(Vector2d(-40.0, 40.0), toRadians(90.0))
.build()
val blueLeftBackdropCenter = drive.actionBuilder(Pose2d(-36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(-90.0))
.splineToConstantHeading(Vector2d(-36.0, 40.0), toRadians(90.0))
.build()
val blueLeftBackdropRight = drive.actionBuilder(Pose2d(-36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(0.0))
.splineToConstantHeading(Vector2d(-32.0, 40.0), toRadians(90.0))
.build()
//Blue Part Three Left
val bluePartThreeLeft = drive.actionBuilder(Pose2d(-36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(90.0)) //Idk if you need this
.splineToConstantHeading(Vector2d(-60.0, 48.0), toRadians(90.0))
.splineToConstantHeading(Vector2d(-60.0, 60.0), toRadians(90.0))
.build()
//Blue Part Three Right
val bluePartThreeRight = drive.actionBuilder(Pose2d(-36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(90.0)) //Idk if you need this
.splineToConstantHeading(Vector2d(-12.0, 48.0), toRadians(90.0))
.splineToConstantHeading(Vector2d(-12.0, 60.0), toRadians(90.0))
.build()
//Red Left
val redLeftPartOne = drive.actionBuilder(drive.pose)
.setTangent(toRadians(-90.0))
.splineToConstantHeading(Vector2d(57.0, -42.0), toRadians(180.0))
.splineToLinearHeading(Pose2d(45.0, -36.0, toRadians(180.0)), toRadians(0.0))
.build()
val redLeftPixelLeft = drive.actionBuilder(Pose2d(45.0, -36.0, toRadians(180.0)))
.setTangent(toRadians(-90.0))
.splineToLinearHeading(Pose2d(45.0, -32.5, toRadians(150.0)), toRadians(-90.0))
.build()
val redLeftPixelCenter = drive.actionBuilder(Pose2d(45.0, -36.0, toRadians(180.0)))
.setTangent(toRadians(0.0))
.splineToLinearHeading(Pose2d(42.0, -36.0, toRadians(0.0)), toRadians(0.0))
.build()
val redLeftPixelRight = drive.actionBuilder(Pose2d(45.0, -36.0, toRadians(180.0)))
.setTangent(toRadians(90.0))
.splineToLinearHeading(Pose2d(45.0, -39.5, toRadians(-150.0)), toRadians(-90.0))
.build()
val redLeftPartTwo = drive.actionBuilder(Pose2d(60.0, -48.0, toRadians(-90.0)))
.setTangent(toRadians(90.0))
.splineToConstantHeading(Vector2d(60.0, 36.0), toRadians(90.0))
.splineToConstantHeading(Vector2d(36.0, 36.0), toRadians(180.0))
.build()
val redLeftBackdropLeft = drive.actionBuilder(Pose2d(36.0, 36.0, toRadians(90.0)))
.setTangent(toRadians(180.0))
.splineToConstantHeading(Vector2d(32.0, 40.0), toRadians(-90.0))
.build()
val redLeftBackdropCenter = drive.actionBuilder(Pose2d(36.0, 36.0, toRadians(90.0)))
.setTangent(toRadians(-90.0))
.splineToConstantHeading(Vector2d(36.0, 40.0), toRadians(-90.0))
.build()
val redLeftBackdropRight = drive.actionBuilder(Pose2d(36.0, 36.0, toRadians(90.0)))
.setTangent(toRadians(0.0))
.splineToConstantHeading(Vector2d(40.0, 40.0), toRadians(-90.0))
.build()
//Red Right
val redRightPartOne = drive.actionBuilder(drive.pose)
.setTangent(toRadians(90.0))
.splineToConstantHeading(Vector2d(54.0, 24.0), toRadians(135.0))
.splineToLinearHeading(Pose2d(54.0, 18.0, toRadians(180.0)), toRadians(-90.0))
.splineToConstantHeading(Vector2d(45.0, 12.0), toRadians(90.0))
.build()
val redRightPixelLeft = drive.actionBuilder(Pose2d(45.0, 12.0, toRadians(-180.0)))
.setTangent(toRadians(90.0))
.splineToLinearHeading(Pose2d(45.0, 15.5, toRadians(150.0)), toRadians(90.0))
.build()
val redRightPixelCenter = drive.actionBuilder(Pose2d(45.0, 12.0, toRadians(-180.0)))
.setTangent(toRadians(0.0))
.splineToLinearHeading(Pose2d(42.0, 12.0, toRadians(0.0)), toRadians(0.0))
.build()
val redRightPixelRight = drive.actionBuilder(Pose2d(45.0, 12.0, toRadians(-180.0)))
.setTangent(toRadians(-90.0))
.splineToLinearHeading(Pose2d(45.0, 8.5, toRadians(-150.0)), toRadians(90.0))
.build()
val redRightPartTwo = drive.actionBuilder(Pose2d(54.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(90.0))
.splineToConstantHeading(Vector2d(36.0, 36.0), toRadians(90.0))
.build()
val redRightBackdropLeft = drive.actionBuilder(Pose2d(36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(180.0))
.splineToConstantHeading(Vector2d(32.0, 40.0), toRadians(90.0))
.build()
val redRightBackdropCenter = drive.actionBuilder(Pose2d(36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(90.0))
.splineToConstantHeading(Vector2d(36.0, 40.0), toRadians(90.0))
.build()
val redRightBackdropRight = drive.actionBuilder(Pose2d(36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(180.0))
.splineToConstantHeading(Vector2d(32.0, 40.0), toRadians(90.0))
.build()
//Red Part Three Left
val redPartThreeLeft = drive.actionBuilder(Pose2d(36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(90.0)) //Idk if you need this
.splineToConstantHeading(Vector2d(60.0, 48.0), toRadians(90.0))
.splineToConstantHeading(Vector2d(60.0, 60.0), toRadians(90.0))
.build()
//Red Part Three Right
val redPartThreeRight = drive.actionBuilder(Pose2d(36.0, 36.0, toRadians(-90.0)))
.setTangent(toRadians(90.0)) //Idk if you need this
.splineToConstantHeading(Vector2d(12.0, 48.0), toRadians(90.0))
.splineToConstantHeading(Vector2d(12.0, 60.0), toRadians(90.0))
.build()
waitForStart()
if (isStopRequested) return
// Initialize variable to store spike position reads
val voteCount = mutableMapOf<Vision.SpikeDirection, Int>()
voteCount[Vision.SpikeDirection.LEFT] = 0
voteCount[Vision.SpikeDirection.CENTER] = 0
voteCount[Vision.SpikeDirection.RIGHT] = 0
// Store each spike position read
val maxReads = 25
while (voteCount.values.sum() < maxReads && autoTimer.seconds() < 5.0) { //TODO make this a safe loop
val spikeDirectionUpdate = vision.getSpikeMarkDirectionUpdate() ?: continue
voteCount[spikeDirectionUpdate] = voteCount[spikeDirectionUpdate]!! + 1
Log.i("Votes", voteCount.toString())
telemetry.addData("Votes", voteCount.toString())
telemetry.update()
}
// Set spikePosition to the highest voted position
spikePosition = voteCount.entries.maxByOrNull {it.value}?.key ?: Vision.SpikeDirection.LEFT
telemetry.addData("Spike Position", spikePosition.name)
telemetry.update()
// Initialize claw and passthrough position
runBlocking(
SequentialAction(
claw.clawClose(),
passthrough.passthroughDeposit()
)
)
// Trajectory Decision Tree
when (StartingPoseStorage.startingPose) {
StartingPose.BLUE_RIGHT -> {
// Drives to pixel placement branching node
runBlocking(blueRightPartOne)
// Extend passthrough
runBlocking(
SequentialAction(
passthrough.passthroughHalfway(),
SleepAction(1.5)
)
)
// Drives to 1 of 3 pixel placement spots depending on vision data
when (spikePosition) {
Vision.SpikeDirection.LEFT -> runBlocking(blueRightPixelLeft)
Vision.SpikeDirection.CENTER -> runBlocking(blueRightPixelCenter)
Vision.SpikeDirection.RIGHT -> runBlocking(blueRightPixelRight)
}
// Pixel placement sequence
runBlocking(
SequentialAction(
passthrough.passthroughPickup(), // Place pixel
SleepAction(1.0),
claw.clawPartial(), // Release pixel
SleepAction(1.0),
passthrough.passthroughHalfway(), // Lift passthrough up
SleepAction(0.5),
claw.clawClose(), // Close claw
passthrough.passthroughDeposit(), // Retract Passthrough
SleepAction(2.0)
)
)
// Converges branched nodes
runBlocking(drive.actionBuilder(drive.pose)
.setTangent(toRadians(-135.0))
.splineToLinearHeading(Pose2d(-59.0, -48.0, toRadians(-90.0)), toRadians(-90.0))
.build()
)
// Continues from node convergence to backdrop branch
runBlocking(blueRightPartTwo)
// Drives to 1 of 3 backdrop placement spots depending on vision data
when (spikePosition) {
Vision.SpikeDirection.LEFT -> runBlocking(blueRightBackdropLeft)
Vision.SpikeDirection.CENTER -> runBlocking(blueRightBackdropCenter)
Vision.SpikeDirection.RIGHT -> runBlocking(blueRightBackdropRight)
}
//TODO add actions, lift actions, vision auto align?
// Converges to parking node
runBlocking(drive.actionBuilder(drive.pose)
.setTangent(toRadians(90.0))
.splineToLinearHeading(Pose2d(-36.0, 36.0, toRadians(-90.0)), toRadians(90.0))
.build()
)
// Finish path and park
runBlocking(bluePartThreeLeft) //TODO make option in starting pose selector to pick parking location
}
StartingPose.BLUE_LEFT -> {
runBlocking(blueLeftPartOne) // Drives to pixel placement branch
runBlocking(passthrough.passthroughHalfway())
runBlocking(drive.actionBuilder(drive.pose).waitSeconds(2.0).build()) // Wait for passthrough to extend
when (spikePosition) { // Drives to 1 of 3 pixel placement spots depending on vision data
Vision.SpikeDirection.LEFT -> runBlocking(blueLeftPixelLeft) //TODO make and add pixel placement command
Vision.SpikeDirection.CENTER -> runBlocking(blueLeftPixelCenter)
Vision.SpikeDirection.RIGHT -> runBlocking(blueLeftPixelRight)
}
runBlocking(passthrough.passthroughPickup())
runBlocking(drive.actionBuilder(drive.pose).waitSeconds(1.0).build()) // Wait for passthrough to extend
runBlocking(claw.clawPartial())
runBlocking(passthrough.passthroughHalfway())
runBlocking(drive.actionBuilder(drive.pose).waitSeconds(1.0).build()) // Wait for passthrough to extend
runBlocking(drive.actionBuilder(drive.pose) // Drives to next node
.setTangent(toRadians(135.0))
.splineToLinearHeading(Pose2d(-54.0, 36.0, toRadians(-90.0)), toRadians(90.0))
.build()
)
runBlocking(blueLeftPartTwo) // Continues rest of path up to the backdrop
when (spikePosition) { // Drives to 1 of 3 backdrop placement spots depending on vision data
Vision.SpikeDirection.LEFT -> runBlocking(blueLeftBackdropLeft) //TODO make and add pixel placement command, make vision auto align code(?)
Vision.SpikeDirection.CENTER -> runBlocking(blueLeftBackdropCenter)
Vision.SpikeDirection.RIGHT -> runBlocking(blueLeftBackdropRight)
}
runBlocking(drive.actionBuilder(drive.pose) // Drives to next node
.setTangent(toRadians(90.0))
.splineToLinearHeading(Pose2d(-36.0, 36.0, toRadians(-90.0)), toRadians(90.0))
.build()
)
runBlocking(bluePartThreeLeft) // Finish path
}
StartingPose.RED_RIGHT -> {
runBlocking(redRightPartOne)
}
StartingPose.RED_LEFT -> {
runBlocking(redLeftPartOne)
}
}
}
}
| 1
|
Kotlin
|
1
| 0
|
b010f166a95cbfc6283530dfaa5bbd7036fa3459
| 18,638
|
Robotics2023-24
|
BSD 3-Clause Clear License
|
app/src/main/java/com/bubelov/coins/editplace/EditPlaceViewModel.kt
|
msgpo
| 266,929,338
| true
|
{"Kotlin": 227542, "Dockerfile": 847}
|
package com.bubelov.coins.editplace
import androidx.lifecycle.ViewModel
import com.bubelov.coins.data.Place
import com.bubelov.coins.repository.place.PlacesRepository
import com.bubelov.coins.util.BasicTaskState
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.HttpException
import kotlin.time.ExperimentalTime
@ExperimentalTime
class EditPlaceViewModel(
private val placesRepository: PlacesRepository
) : ViewModel() {
fun submitChanges(
originalPlace: Place?,
updatedPlace: Place
): Flow<BasicTaskState> {
return flow {
emit(BasicTaskState.Progress)
try {
if (originalPlace == null) {
placesRepository.addPlace(updatedPlace)
} else {
placesRepository.updatePlace(updatedPlace)
}
emit(BasicTaskState.Success)
} catch (httpException: HttpException) {
val message = withContext(Dispatchers.IO) {
httpException.response()?.errorBody()?.string() ?: "Unknown error"
}
emit(BasicTaskState.Error(message))
} catch (e: Exception) {
emit(BasicTaskState.Error(e.message ?: ""))
}
}
}
}
| 0
| null |
0
| 0
|
f3033534d1c104b04a98f9e734853f533a6c26dd
| 1,346
|
coin-map-android
|
MIT License
|
src/hackhub/app/src/main/java/com/univpm/hackhub/adapters/MessageAdapter.kt
|
NourCheriff
| 792,292,205
| false
|
{"Kotlin": 258512, "TeX": 48232, "Dart": 45042, "C++": 24274, "CMake": 19478, "Swift": 2209, "HTML": 1849, "C": 1425, "Objective-C": 38}
|
package com.univpm.hackhub.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.univpm.hackhub.R
import com.univpm.hackhub.databinding.ReceiverMessageBinding
import com.univpm.hackhub.databinding.SenderMessageBinding
import com.univpm.hackhub.model.Message
import com.univpm.hackhub.utils.Utils
import java.text.SimpleDateFormat
import java.util.Locale
class MessageAdapter(private val messageList: List<Message>, private val uid: String) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val RECEIVED_MESSAGE_TYPE = 0
const val SENT_MESSAGE_TYPE = 1
}
class ReceivedMessageViewHolder(val binding: ReceiverMessageBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(message: Message) {
binding.msg.text = message.content
binding.msgDatetime.text = Utils.dateToString("HH:mm", message.timestamp)
}
}
class SentMessageViewHolder(val binding: SenderMessageBinding) : RecyclerView.ViewHolder(binding.root){
fun bind(message: Message) {
binding.msg.text = message.content
binding.msgDatetime.text = Utils.dateToString("HH:mm", message.timestamp)
binding.iconIsVisualized.isVisible = message.isVisualized
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
when(viewType){
SENT_MESSAGE_TYPE -> {
SentMessageViewHolder(
DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.sender_message, parent, false)
)
}
RECEIVED_MESSAGE_TYPE -> {
ReceivedMessageViewHolder(
DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.receiver_message, parent, false)
)
}
else -> {
throw IllegalArgumentException("Unknown viewType: $viewType")
}
}
override fun getItemCount(): Int = messageList.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = messageList[position]
when (holder) {
is ReceivedMessageViewHolder -> {
holder.bind(item)
}
is SentMessageViewHolder -> {
holder.bind(item)
}
}
}
override fun getItemViewType(position: Int): Int =
when {
messageList[position].sender == uid -> SENT_MESSAGE_TYPE
messageList[position].receiver == uid -> RECEIVED_MESSAGE_TYPE
else -> throw IllegalArgumentException("Unknown view type")
}
}
| 1
|
Kotlin
|
0
| 0
|
95337cbef1cbd7a659e49475de3caa28a62bf41d
| 2,875
|
hackhub
|
MIT License
|
src/main/kotlin/org/jetbrains/research/ml/tasktracker/tracking/dialog/CustomDialogWrapper.kt
|
JetBrains-Research
| 217,919,960
| false
|
{"Kotlin": 130961, "CSS": 5631}
|
package org.jetbrains.research.ml.tasktracker.tracking.dialog
import com.intellij.openapi.ui.DialogWrapper
import org.jetbrains.research.ml.tasktracker.models.PaneLanguage
import org.jetbrains.research.ml.tasktracker.ui.panes.util.LanguagePaneUiData
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
abstract class CustomDialogWrapper : DialogWrapper(true) {
protected val currentLanguage: PaneLanguage? by lazy {
LanguagePaneUiData.language.currentValue
}
abstract val customPreferredSize: Dimension?
override fun createCenterPanel(): JComponent? {
val dialogPanel = JPanel(BorderLayout())
val label = JLabel(createMessage())
// Todo: should I set it?
customPreferredSize?.let {
label.preferredSize = it
}
dialogPanel.add(label, BorderLayout.CENTER)
return dialogPanel
}
abstract fun createMessage(): String
}
| 2
|
Kotlin
|
7
| 7
|
86d67c60e93a3dc150a9fe77a8f998624fbe58a4
| 1,003
|
task-tracker-plugin
|
MIT License
|
app/src/common/annotations/Day.kt
|
henningBunk
| 432,858,990
| false
|
{"Kotlin": 124495}
|
package common.annotations
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Day(val day: Int) {
}
| 0
|
Kotlin
|
0
| 0
|
94235f97c436f434561a09272642911c5588560d
| 139
|
advent-of-code-2021
|
Apache License 2.0
|
app/src/main/java/com/letter/days/service/CoreService.kt
|
NevermindZZT
| 164,197,780
| false
| null |
package com.letter.days.service
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.letter.days.R
import com.letter.days.database.AppDatabase
import com.letter.days.utils.setAllAnniversaryAlarm
import com.letter.days.utils.showAnniversaryNotification
import android.content.createNotificationChannel
import android.text.TextUtils
import androidx.preference.PreferenceManager
import com.letter.days.repository.NotifyRepo
import com.letter.days.utils.getIntentNotification
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* 核心服务
*
* @author Letter(<EMAIL>)
* @since 1.0.0
*/
class CoreService : Service() {
override fun onBind(intent: Intent): IBinder {
throw UnsupportedOperationException("Not yet implemented")
}
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(
getString(R.string.notification_channel_anni_id),
getString(R.string.notification_channel_anni_name),
NotificationManager.IMPORTANCE_HIGH)
createNotificationChannel(
getString(R.string.notification_channel_intent_id),
getString(R.string.notification_channel_intent_name),
NotificationManager.IMPORTANCE_MIN)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("intent_notification", false)) {
startForeground(-1, getIntentNotification(this))
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(-1)
} else {
stopForeground(true)
}
}
if (intent?.getBooleanExtra(EXTRA_IS_DAYS_NOTIFY, false) == true) {
val anniId = intent.getIntExtra(EXTRA_ANNI_ID, -1)
if (anniId != -1) {
GlobalScope.launch {
val anniversary = AppDatabase.instance(this@CoreService)
.anniversaryDao()
.get(anniId)
if (anniversary != null) {
withContext(Dispatchers.Main) {
showAnniversaryNotification(this@CoreService, anniversary)
}
}
}
}
}
if (PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("enable_notify", false)) {
GlobalScope.launch {
NotifyRepo().setNotifyAlarm(this@CoreService)
}
}
if (intent?.getBooleanExtra(EXTRA_IS_TIMER_NOTIFY, false) == true) {
val title = intent.getStringExtra(EXTRA_NOTIFY_TITLE)
if (!TextUtils.isEmpty(title)) {
NotifyRepo().showNotification(this,
title,
intent.getStringExtra(EXTRA_NOTIFY_CONTENT))
}
}
GlobalScope.launch {
setAllAnniversaryAlarm(this@CoreService)
}
return super.onStartCommand(intent, flags, startId)
}
companion object {
const val EXTRA_IS_DAYS_NOTIFY = "is_days_notify"
const val EXTRA_ANNI_ID = "anni_id"
const val EXTRA_IS_TIMER_NOTIFY = "is_timer_notify"
const val EXTRA_NOTIFY_TITLE = "notify_title"
const val EXTRA_NOTIFY_CONTENT = "notify_content"
}
}
| 0
|
Kotlin
|
1
| 9
|
641bc9587bc8edbe569653c3242cb08fc7bfc071
| 3,704
|
Days
|
MIT License
|
app/src/main/java/com/github/anastr/myscore/fragments/CourseListFragment.kt
|
anastr
| 347,355,104
| false
| null |
package com.github.anastr.myscore.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewGroupCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import com.github.anastr.domain.constant.MAX_COURSES
import com.github.anastr.myscore.MainActivity
import com.github.anastr.myscore.R
import com.github.anastr.myscore.adapter.CourseAdapter
import com.github.anastr.myscore.databinding.FragmentCourseListBinding
import com.github.anastr.myscore.util.launchAndRepeatOnLifecycle
import com.github.anastr.myscore.viewmodel.CourseListViewModel
import com.github.anastr.myscore.viewmodel.State
import com.google.android.material.transition.MaterialSharedAxis
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
@AndroidEntryPoint
class CourseListFragment : Fragment() {
private var _binding: FragmentCourseListBinding? = null
private val binding get() =_binding!!
private val courseListViewModel: CourseListViewModel by viewModels()
private val courseAdapter = CourseAdapter()
private val mainActivity: MainActivity? get() = (requireActivity() as? MainActivity)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true).apply {
duration = resources.getInteger(R.integer.motion_duration_large).toLong()
}
returnTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false).apply {
duration = resources.getInteger(R.integer.motion_duration_large).toLong()
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentCourseListBinding.inflate(inflater, container, false)
ViewGroupCompat.setTransitionGroup(binding.root, true)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.apply {
setHasFixedSize(true)
adapter = courseAdapter
}
launchAndRepeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
courseListViewModel.passDegreeFlow.collect { passDegree ->
courseAdapter.passDegree = passDegree
}
}
launch {
courseListViewModel.coursesFlow.collect { state ->
when (state) {
is State.Loading -> {
binding.progressBar.visibility = View.VISIBLE
binding.textMessage.visibility = View.GONE
}
is State.Error -> {
binding.progressBar.visibility = View.GONE
binding.textMessage.visibility = View.VISIBLE
binding.textMessage.text = state.error.message
}
is State.Success -> {
binding.progressBar.visibility = View.GONE
if (state.data.isEmpty()) {
binding.textMessage.visibility = View.VISIBLE
binding.textMessage.setText(R.string.noData)
} else {
binding.textMessage.visibility = View.GONE
}
if (state.data.size >= MAX_COURSES)
mainActivity?.hideFab()
else
mainActivity?.showFab()
courseAdapter.submitList(state.data)
}
}
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
ef1b8e66a472762477b2cfe1da142521942a8a78
| 4,155
|
MyDegree
|
Apache License 2.0
|
prj-website/src/commonMain/kotlin/state/State.kt
|
simonegiacomelli
| 473,571,649
| false
| null |
package state
var stateOrNull: () -> ClientState = { error("no State handler") }
val state get() = stateOrNull()
| 0
|
Kotlin
|
1
| 0
|
9cb30a5139c268a7c3037fa335fdec9d118d463e
| 115
|
kotlin-mpp-starter
|
Apache License 2.0
|
app/src/main/java/com/ema/jannik/logbook/activity/AddDriveActivity.kt
|
osti11
| 157,562,778
| false
| null |
package com.ema.jannik.logbook.activity
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import com.ema.jannik.logbook.fragment.TimePickerFragmentStart
import kotlinx.android.synthetic.main.activity_add_drive.*
import com.google.android.gms.common.GooglePlayServicesNotAvailableException
import com.google.android.gms.common.GooglePlayServicesRepairableException
import com.google.android.gms.location.places.ui.PlaceAutocomplete
import android.content.Intent
import android.util.Log
import android.widget.*
import androidx.core.content.ContextCompat
import com.ema.jannik.logbook.R
import com.ema.jannik.logbook.fragment.DatePickerFragment
import com.ema.jannik.logbook.model.AddDriveRepository
import com.ema.jannik.logbook.model.database.Drive
import com.ema.jannik.logbook.model.database.Stage
import com.ema.jannik.logbook.view.ExplanationDialogAddDrive
import com.google.android.gms.location.places.Place
import java.text.DateFormat
import java.util.*
/**
* in this Activity the user can add a past ride to the db.
*/
open class AddDriveActivity : AppCompatActivity(), TimePickerDialog.OnTimeSetListener,
DatePickerDialog.OnDateSetListener, NumberPicker.OnValueChangeListener{
val TAG = this::class.java.name
companion object {
/**
* Um die placeAutocomplete Anfrage zu identifizieren.
*/
const val PLACE_AUTOCOMPLETE_REQUEST_CODE = 1
}
/**
* This boolean is true when onClickStartAddressAutoComplete() start the autocomplete Activity.
* To know where to set the result
*/
var startIntentAutoComplete: Boolean? = null
/**
* This boolean is true when the onClickEndTime() start the startTimePickerFragment().
*/
var startFragmentTimePicker: Boolean? = null
/**
* Representiert die Startadresse. Enthält lng, lat und die Adresse als String zum späteren speichern in der DB.
*/
var startAddress: Place? = null
/**
* Representiert die Zieladresse. Enthält lng, lat und die Adresse als String zum späteren speichern in der DB.
*/
var destinationAddress: Place? = null
/**
* Representiert die ausgewählt Katigorie in form eines Imagebuttons.
*/
var category: Int = 0
/**
* Representiert den Abfahrtszeitpunkt.
*/
var startTime: Calendar = Calendar.getInstance()
/**
* Ankunftszeit
*/
var endTime: Calendar = Calendar.getInstance()
/**
* Diese Funktion wird beim erstellen der 'activity' aufgerufen und setzt die 'actionBar', 'imageButton' und 'numberPicker'.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_drive)
//--set ActionBar--
supportActionBar!!.setHomeAsUpIndicator(R.drawable.ic_back) //set back button
title = getString(R.string.menu_addDrive) //Text for action bar
//--set Numberpicker--
numberPicker_odometerStart.maxValue = 400000
numberPicker_odometerStart.minValue = 0
numberPicker_distance.minValue = 0
numberPicker_distance.maxValue = 1000
numberPicker_odometer_end.minValue = 0
numberPicker_odometer_end.maxValue = 400000
setNumberpickerwithLastEntry()
//--set Button--
resetImageButtonBackgroundColor()
imageButton_noCategory.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.colorPrimary
)
)
setOnChangedNumberPicker()
}
/**
* onValueChangeListener for NumberPicker.
* Update the other numberPickers when thge value of one numberPicker change.
*/
override fun onValueChange(picker: NumberPicker?, oldVal: Int, newVal: Int) {
when (picker!!.id) {
R.id.numberPicker_odometerStart -> {
numberPicker_odometer_end.value = numberPicker_odometerStart.value + numberPicker_distance.value
}
R.id.numberPicker_odometer_end -> {
numberPicker_distance.value = numberPicker_odometer_end.value - numberPicker_odometerStart.value
}
R.id.numberPicker_distance -> {
numberPicker_odometer_end.value = numberPicker_distance.value + numberPicker_odometerStart.value
}
}
}
/**
* Set OnValueChangedListener for the NumberPickers.
*/
private fun setOnChangedNumberPicker() {
numberPicker_odometerStart.setOnValueChangedListener(this)
numberPicker_odometer_end.setOnValueChangedListener(this)
numberPicker_distance.setOnValueChangedListener(this)
}
/**
* set the value of the Numberpickers with the values from the last entry in the db.
*/
private fun setNumberpickerwithLastEntry() {
val repository: AddDriveRepository = AddDriveRepository(application)
var drive: Drive?
try {
drive = repository.getLastDrive()
} catch (e: Exception) {
drive = null
}
if (drive != null) {
numberPicker_odometerStart.value = drive.mileageStart
numberPicker_odometer_end.value = drive.mileageDestination
numberPicker_distance.value = drive.distance
}
}
/**
* set add_drive_menu.xml as menu layout.
*/
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.add_drive_menu, menu)
return true //when true Menu will shown
}
/**
* Call the function 'saveDrive()' when the save icon in the toolbar is clicked.
*/
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item!!.itemId == R.id.save_drive) {
saveDrive()
return true
} else {
return super.onOptionsItemSelected(item)
}
}
/**
* Save the input in the db.
*/
private fun saveDrive() {
val purpose = edit_text_purpose.text.toString()
Log.i(TAG, "purpose: " + purpose)
val startAddress = startAddress
Log.i(TAG, "startAddress " + startAddress)
val destinationAddress = destinationAddress
Log.i(TAG, "destinationAddress " + destinationAddress)
val startMilage = numberPicker_odometerStart.value
Log.i(TAG, "distance " + startMilage)
val distance = numberPicker_distance.value
Log.i(TAG, distance.toString())
val endMilage = numberPicker_odometer_end.value
Log.i(TAG, endMilage.toString())
val startTime = startTime
Log.i(TAG, startTime.time.toString())
val endTime = endTime
Log.i(TAG, endTime.time.toString())
var message: String = ""
if (startAddress == null)
message += getString(R.string.toast_startAddress) + "\n"
if (destinationAddress == null)
message += getString(R.string.toast_destinationAddress) + "\n"
if (endMilage - startMilage != distance)
message += getString(R.string.toast_mileage) + "\n"
if (editText_start_time.text == null || editText_start_time.text == null
|| startTime.timeInMillis > endTime.timeInMillis
)
message += getString(R.string.toast_time)
if (message != "") { //when message has benn modified then show the message
val dialog = ExplanationDialogAddDrive(message)
dialog.show(supportFragmentManager, "false input")
return
}
val duration = Calendar.getInstance()
duration.timeInMillis = endTime.timeInMillis - startTime.timeInMillis
duration.set(Calendar.HOUR_OF_DAY, duration.get(Calendar.HOUR_OF_DAY) - 1)
//save in db
val repository: AddDriveRepository = AddDriveRepository(application)
repository.insert(
Drive
(
purpose = purpose,
start = Stage(
longitude = startAddress!!.latLng.longitude,
latitude = startAddress.latLng.latitude,
address = startAddress.address.toString()
),
destination = Stage(
longitude = destinationAddress!!.latLng.longitude,
latitude = destinationAddress.latLng.latitude,
address = destinationAddress.address.toString()
),
mileageDestination = endMilage,
mileageStart = startMilage,
distance = distance,
start_timestamp = startTime,
destination_timestamp = endTime,
category = category,
duration = duration
)
)
Toast.makeText(this, R.string.toast_addSuccessfully, Toast.LENGTH_LONG).show()
finish()
}
/**
* Set the result from the TimePickerFragment.
* startFragmentTimePicker == false -> set the result to 'endTime'.
* startFragmentTimePicker == true -> set the result to 'startTime'.
*/
override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
Log.i(TAG, "onTimeSet()")
if (startFragmentTimePicker == false) {
endTime.set(Calendar.HOUR_OF_DAY, hourOfDay)
endTime.set(Calendar.MINUTE, minute)
endTime.set(Calendar.SECOND, 0)
Log.i(TAG, "setTime(start)")
setTime(endTime, editText_endTime)
} else if (startFragmentTimePicker == true) {
startTime.set(Calendar.HOUR_OF_DAY, hourOfDay)
startTime.set(Calendar.MINUTE, minute)
startTime.set(Calendar.SECOND, 0)
Log.i(TAG, "setTime(start)")
setTime(startTime, editText_start_time)
}
startFragmentTimePicker = null
}
/**
*
*/
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
Log.i(TAG, "onDataSet()")
startTime.set(year, month, dayOfMonth)
startTimePickerFragment()
}
/**
* set the time in editText
*/
private fun setTime(calendar: Calendar, editText: EditText) {
Log.i(TAG, "setTime()")
val text: String = DateFormat.getDateTimeInstance().format(calendar.time)
Log.i(TAG, "setText")
editText.setText(text)
Log.i(TAG, "setTime() finish")
}
/**
* This function is called when the user click on an imageButton.
* The imageButton who call this function become a different background colour, show a toast message and set an value to the integer category
*/
fun onClickCategory(view: View) {
resetImageButtonBackgroundColor()
var message: String = getString(R.string.category) + ": "
when (view.id) {
R.id.imageButton_noCategory -> {
imageButton_noCategory.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.colorPrimary
)
)
category = 0
message += getString(R.string.category_0)
}
R.id.imageButton_private -> {
imageButton_private.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.colorPrimary
)
)
category = 1
message += getString(R.string.category_1)
}
R.id.imageButton_work -> {
imageButton_work.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.colorPrimary
)
)
category = 2
message += getString(R.string.category_2)
}
R.id.imageButton_way -> {
imageButton_way.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.colorPrimary
)
)
category = 3
message += getString(R.string.category_3)
}
}
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
/**
* This function set the background of all imageButton elments to the default value
*/
private fun resetImageButtonBackgroundColor() {
imageButton_noCategory.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.button_material_light
)
)
imageButton_private.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.button_material_light
)
)
imageButton_work.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.button_material_light
)
)
imageButton_way.setBackgroundColor(
ContextCompat.getColor(
applicationContext,
R.color.button_material_light
)
)
}
/**
* set the boolean startFragmentTimePicker to true and call the function startTimePickerFragment()
*/
fun onClickEndTime(view: View) {
Log.i(TAG, "onClickEndTime")
startFragmentTimePicker = false
startDatePickerFragment()
}
/**
* set the boolean startFragmentTimePicker to false and call the function startTimePickerFragment()
*/
fun onClickStartTime(view: View) {
Log.i(TAG, "onClick start Time()")
startFragmentTimePicker = true
startDatePickerFragment()
}
/**
* This function start the TimePickerFragment to choose a time
*/
private fun startTimePickerFragment() {
Log.i(TAG, "startTimePicker()")
val timePicker: DialogFragment = TimePickerFragmentStart()
timePicker.show(supportFragmentManager, "time picker")
}
private fun startDatePickerFragment() {
Log.i(TAG, "startDatePicker()")
val datePicker: DialogFragment = DatePickerFragment()
datePicker.show(supportFragmentManager, "datePicker")
}
/**
* set the boolean startIntentAutoComplete to true and call the function buildPlaceAutocompleteIntent()
*/
fun onClickStartAddressAutoComplete(view: View) {
startIntentAutoComplete = true
buildPlaceAutocompleteIntent()
}
/**
* set the boolean startIntentAutoComplete to false and call the function buildPlaceAutocompleteIntent()
*/
fun onClickDestinationAddressAutoComplete(view: View) {
startIntentAutoComplete = false
buildPlaceAutocompleteIntent()
}
/**
* start an PlaceAutocompleteActivity
*/
private fun buildPlaceAutocompleteIntent() {
try {
val intent = PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(this)
startActivityForResult(
intent,
PLACE_AUTOCOMPLETE_REQUEST_CODE
)
} catch (e: GooglePlayServicesRepairableException) {
// TODO: Handle the error.
} catch (e: GooglePlayServicesNotAvailableException) {
// TODO: Handle the error.
}
}
/**
* set the result of the PlaceAutocompleteActivity.
* When the boolean startIntentAutoComplete is true the result is set to textView_startAddress otherwise to textView_destinationAddress.
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
val placeResult = PlaceAutocomplete.getPlace(this, data!!)
if (startIntentAutoComplete == true) { //Event wurd durch klick auf StartAdresse ausgelöst
startAddress = placeResult
editText_startAddress.setText(placeResult!!.address, TextView.BufferType.EDITABLE)
} else if (startIntentAutoComplete == false) { //Event wurd durch klick auf ZielAdresse ausgelöst
destinationAddress = placeResult
editText_destinationAddress.setText(placeResult!!.address, TextView.BufferType.EDITABLE)
}
startIntentAutoComplete = null
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
val status = PlaceAutocomplete.getStatus(this, data!!)
// TODO: Handle the error.
} else if (resultCode == Activity.RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
65ea8d3f9baef9021433faba8ff6695627ea06fc
| 17,175
|
logbook
|
MIT License
|
heroesdesk/src/test/kotlin/org/hexastacks/heroesdesk/kotlin/impl/task/PendingTaskIdTest.kt
|
ManoManoTech
| 739,443,317
| false
|
{"Kotlin": 122086}
|
package org.hexastacks.heroesdesk.kotlin.impl.task
import arrow.core.EitherNel
import org.hexastacks.heroesdesk.kotlin.impl.scope.Scope
class PendingTaskIdTest : AbstractTaskIdTest<PendingTaskId>() {
override fun createTaskId(scope: Scope, value: String): EitherNel<TaskId.TaskIdError, PendingTaskId> =
PendingTaskId(scope, value)
}
| 8
|
Kotlin
|
1
| 0
|
8e8e2371b2be9893b633c74e9c9c982da60db02c
| 348
|
hexa-playground
|
MIT License
|
app/src/main/java/com/github/zsoltk/chesso/ui/dialogs/GameDialog.kt
|
zsoltk
| 369,016,520
| false
| null |
package com.github.zsoltk.chesso.ui.dialogs
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.github.zsoltk.chesso.R
@Composable
fun GameDialog(
onDismiss: () -> Unit,
onNewGame: () -> Unit,
onImportGame: () -> Unit,
onExportGame: () -> Unit,
) {
ClickableListItemsDialog(
onDismiss = onDismiss,
items = listOf(
stringResource(R.string.game_new) to onNewGame,
stringResource(R.string.game_import) to onImportGame,
stringResource(R.string.game_export) to onExportGame,
)
)
}
@Preview
@Composable
private fun GameDialogContent() {
GameDialog(
onDismiss = {},
onNewGame = {},
onImportGame = {},
onExportGame = {},
)
}
| 2
| null |
6
| 87
|
e31f0913a6af64f7769112f49a909e8ee52d8d09
| 843
|
chesso
|
Apache License 2.0
|
app/src/main/java/com/shuhart/md5gallery/media/Photo.kt
|
shuhart
| 115,040,485
| false
| null |
package com.shuhart.md5gallery.media
data class Photo(val imageId: Long,
val dateTaken: Long,
val path: String,
val size: Long,
val orientation: Int,
var md5: String = "",
var thumbPath: String = "",
val isProviderPath: Boolean) {
companion object {
val EMPTY = Photo(0, 0, "", 0, 0, isProviderPath = false)
}
}
| 0
|
Kotlin
|
0
| 0
|
22fad06a47c8c5050cce5446a6c09f6febe1896f
| 447
|
Md5Gallery
|
Apache License 2.0
|
src/test/java/com/digitalpetri/strictmachine/dsl/ViaBuilderTest.kt
|
digitalpetri
| 159,901,587
| false
| null |
/*
* Copyright 2018 Kevin Herron
*
* 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.digitalpetri.strictmachine.dsl
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.concurrent.atomic.AtomicBoolean
class ViaBuilderTest {
@Test
fun `Action built with via Instance`() {
val fb = FsmBuilder<State, Event>()
fb.`when`(State.S1)
.on(Event.E1)
.transitionTo(State.S2)
val executed = AtomicBoolean(false)
fb.onTransitionFrom(State.S1)
.to(State.S2)
.via(Event.E1)
.execute { executed.set(true) }
fb.build(State.S1).fireEventBlocking(Event.E1)
assertTrue(executed.get()) {
"expected execute callback to set executed=true"
}
}
@Test
fun `Action built with via Class`() {
val fb = FsmBuilder<State, Event>()
fb.`when`(State.S1)
.on(Event.E1)
.transitionTo(State.S2)
val executed = AtomicBoolean(false)
fb.onTransitionFrom(State.S1)
.to(State.S2)
.via(Event.E1::class.java)
.execute { executed.set(true) }
fb.build(State.S1).fireEventBlocking(Event.E1)
assertTrue(executed.get()) {
"expected execute callback to set executed=true"
}
}
@Test
fun `Action built with via Predicate`() {
val fb = FsmBuilder<State, Event>()
fb.`when`(State.S1)
.on(Event.E1)
.transitionTo(State.S2)
val executed = AtomicBoolean(false)
fb.onTransitionFrom(State.S1)
.to(State.S2)
.via { e -> e == Event.E1 }
.execute { executed.set(true) }
fb.build(State.S1).fireEventBlocking(Event.E1)
assertTrue(executed.get()) {
"expected execute callback to set executed=true"
}
}
@Test
fun `Action built with via Any`() {
val fb = FsmBuilder<State, Event>()
fb.`when`(State.S1)
.onAny()
.transitionTo(State.S2)
val executed = AtomicBoolean(false)
fb.onTransitionFrom(State.S1)
.to(State.S2)
.viaAny()
.execute { executed.set(true) }
for (event in listOf(
Event.E1,
Event.E2,
Event.E3,
Event.E4
)) {
executed.set(false)
fb.build(State.S1).fireEventBlocking(event)
assertTrue(executed.get()) {
"expected execute callback to set executed=true"
}
}
}
}
| 0
| null |
5
| 17
|
cc9c26dd37657bedd6584f2a6d29c98e5f772169
| 3,168
|
strict-machine
|
Apache License 2.0
|
RichTextEditorAndroid/src/main/kotlin/net/dankito/richtexteditor/android/command/AlignRightCommand.kt
|
E-Mans-Application
| 141,055,104
| false
| null |
package net.dankito.richtexteditor.android.command
import net.dankito.richtexteditor.Icon
import net.dankito.richtexteditor.android.AndroidIcon
import net.dankito.richtexteditor.android.R
import net.dankito.richtexteditor.command.AlignRightCommandBase
class AlignRightCommand(icon: Icon = AndroidIcon(R.drawable.ic_format_align_right_white_48dp)) : AlignRightCommandBase(icon)
| 1
| null |
1
| 1
|
1fa7c2617d3f2fe775d893e176e9bac4e7b8658e
| 379
|
RichTextEditor
|
MIT License
|
src/main/kotlin/com/funivan/idea/phpClean/inspections/methodCanBePrivate/MethodCanBePrivateInspection.kt
|
funivan
| 144,475,458
| false
|
{"Kotlin": 98271, "HTML": 3584}
|
package com.funivan.idea.phpClean.inspections.methodCanBePrivate
import com.funivan.idea.phpClean.qf.makeClassMemberPrivate.MakeClassMemberPrivateQF
import com.funivan.idea.phpClean.spl.PhpCleanInspection
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import com.jetbrains.php.lang.psi.elements.PhpClass
import com.jetbrains.php.lang.psi.elements.PhpModifierList
import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor
class MethodCanBePrivateInspection : PhpCleanInspection() {
override fun getShortName() = "MethodCanBePrivateInspection"
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : PhpElementVisitor() {
override fun visitPhpClass(clazz: PhpClass) {
if (clazz.isFinal && clazz.extendsList.referenceElements.isEmpty()) {
for (method in clazz.ownMethods.filter { it.modifier.isProtected }) {
holder.registerProblem(
method.nameIdentifier ?: method,
"Method can be private",
MakeClassMemberPrivateQF.create(
method.firstChild as PhpModifierList?,
"Make method private"
)
)
}
}
}
}
}
}
| 6
|
Kotlin
|
6
| 86
|
103124c4a270989bd24e59151358acbb80407ffd
| 1,480
|
PhpClean
|
MIT License
|
bloom/src/main/java/com/fjoglar/composechallenge/bloom/ui/components/BloomTextButton.kt
|
felipejoglar
| 412,404,654
| false
| null |
package com.fjoglar.composechallenge.bloom.ui.components
import android.content.res.Configuration
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.fjoglar.composechallenge.bloom.ui.theme.BloomTheme
@Composable
fun BloomTextButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
TextButton(
onClick = onClick,
shape = RoundedCornerShape(50),
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.secondary),
modifier = modifier
.height(48.dp),
) {
Text(text)
}
}
@Preview(
name = "Day Mode",
uiMode = Configuration.UI_MODE_NIGHT_NO,
)
@Preview(
name = "Night Mode",
uiMode = Configuration.UI_MODE_NIGHT_YES,
)
@Composable
private fun BloomButtonPreview() {
BloomTheme {
BloomTextButton(
text = "Bloom Button",
onClick = {}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
688692b44e59e9e25f966426ff08beaf1dd50d27
| 1,328
|
jetpack-compose-challenge
|
MIT License
|
src/main/kotlin/com/refinedmods/refinedstorage/api/storage/disk/IStorageDiskManager.kt
|
thinkslynk
| 290,596,653
| true
|
{"Kotlin": 695976, "Shell": 456}
|
package com.refinedmods.refinedstorage.api.storage.disk
import net.minecraft.item.ItemStack
import java.util.*
/**
* Stores storage disks.
*/
interface IStorageDiskManager {
/**
* Gets a storage disk by id.
*
* @param id the id
* @return the storage disk, or null if no storage disk is found
*/
operator fun get(id: UUID): IStorageDisk<*>?
/**
* Gets a storage disk by disk stack (a [IStorageDiskProvider]).
*
* @param disk the disk stack
* @return the storage disk, or null if no storage disk is found
*/
fun getByStack(disk: ItemStack): IStorageDisk<*>?
/**
* @return a map of all storage disks
*/
fun getAll(): Map<UUID, IStorageDisk<*>>
/**
* Sets a storage disk.
*
* @param id the id
* @param disk the disk
*/
operator fun set(id: UUID, disk: IStorageDisk<*>)
/**
* Removes a storage disk.
*
* @param id the id
*/
fun remove(id: UUID)
/**
* Marks this manager for saving.
*/
fun markForSaving()
}
| 1
|
Kotlin
|
0
| 2
|
c92afa51af0e5e08caded00882f91171652a89e3
| 1,076
|
refinedstorage
|
MIT License
|
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/memoir/generated/equip3000005.kt
|
qwewqa
| 390,928,568
| false
| null |
package xyz.qwewqa.relive.simulator.core.presets.memoir.generated
import xyz.qwewqa.relive.simulator.core.stage.actor.StatData
import xyz.qwewqa.relive.simulator.core.stage.autoskill.EffectTag
import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters
import xyz.qwewqa.relive.simulator.core.stage.memoir.CutinBlueprint
import xyz.qwewqa.relive.simulator.core.stage.memoir.PartialMemoirBlueprint
val equip3000005 = PartialMemoirBlueprint(
id = 3000005,
name = "熱を帯びた視線、見つめる先は",
rarity = 3,
cost = 6,
baseStats = StatData(
hp = 147,
actPower = 0,
normalDefense = 0,
specialDefense = 12,
),
growthStats = StatData(
hp = 19173,
actPower = 0,
normalDefense = 0,
specialDefense = 1643,
),
additionalTags = listOf(EffectTag.Tamao, EffectTag.Rui)
)
| 0
|
Kotlin
|
11
| 7
|
70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74
| 801
|
relight
|
MIT License
|
app/src/main/java/cn/cqautotest/sunnybeach/http/glide/GlideConfig.kt
|
anjiemo
| 378,095,612
| false
| null |
package cn.android52.demo.http.glide
import android.content.Context
import cn.android52.demo.R
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool
import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions
import com.hjq.http.EasyConfig
import java.io.File
import java.io.InputStream
/**
* author : Android 轮子哥
* github : https://github.com/getActivity/AndroidProject-Kotlin
* time : 2019/12/15
* desc : Glide 全局配置
*/
@GlideModule
class GlideConfig : AppGlideModule() {
companion object {
/** 本地图片缓存文件最大值 */
private const val IMAGE_DISK_CACHE_MAX_SIZE: Int = 500 * 1024 * 1024
}
override fun applyOptions(context: Context, builder: GlideBuilder) {
// 读写外部缓存目录不需要申请存储权限
val diskCacheFile = File(context.cacheDir, "glide")
// 如果这个路径是一个文件
if (diskCacheFile.exists() && diskCacheFile.isFile) {
// 执行删除操作
diskCacheFile.delete()
}
// 如果这个路径不存在
if (!diskCacheFile.exists()) {
// 创建多级目录
diskCacheFile.mkdirs()
}
builder.setDiskCache {
DiskLruCacheWrapper.create(diskCacheFile, IMAGE_DISK_CACHE_MAX_SIZE.toLong())
}
val calculator: MemorySizeCalculator = MemorySizeCalculator.Builder(context).build()
val defaultMemoryCacheSize: Int = calculator.memoryCacheSize
val defaultBitmapPoolSize: Int = calculator.bitmapPoolSize
val customMemoryCacheSize: Long = (1.2 * defaultMemoryCacheSize).toLong()
val customBitmapPoolSize: Long = (1.2 * defaultBitmapPoolSize).toLong()
builder.setMemoryCache(LruResourceCache(customMemoryCacheSize))
builder.setBitmapPool(LruBitmapPool(customBitmapPoolSize))
builder.setDefaultRequestOptions(
RequestOptions()
// 设置默认加载中占位图
.placeholder(R.drawable.image_loading_ic)
// 设置默认加载出错占位图
.error(R.drawable.image_error_ic)
)
}
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
// Glide 默认使用的是 HttpURLConnection 来做网络请求,这里切换成更高效的 OkHttp
registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpLoader.Factory(EasyConfig.getInstance().client))
}
override fun isManifestParsingEnabled(): Boolean {
return false
}
}
| 1
| null |
3
| 95
|
a2402da1cb6af963c829a69d9783053f15d866b5
| 2,789
|
SunnyBeach
|
Apache License 2.0
|
src/main/kotlin/com/luxoft/ness/tmdbgraphql/TheMovieDbGraphQlApiWrapperApplication.kt
|
nestorperezdev
| 624,112,410
| false
| null |
package com.luxoft.ness.tmdbgraphql
import com.luxoft.ness.tmdbgraphql.tmdb.TMDBApi
import com.luxoft.ness.tmdbgraphql.tmdb.interceptor.ErrorHandlingInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.core.env.Environment
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
@SpringBootApplication
class TheMovieDbGraphQlApiWrapperApplication {
@Bean
fun loggingInterceptor(environment: Environment) = HttpLoggingInterceptor().apply {
level = if (environment.activeProfiles.contains("prod")) {
HttpLoggingInterceptor.Level.BASIC
} else {
HttpLoggingInterceptor.Level.BODY
}
}
@Bean
fun okHttpClient(loggingInterceptor: HttpLoggingInterceptor) = OkHttpClient.Builder()
.addInterceptor(ErrorHandlingInterceptor())
.addInterceptor(loggingInterceptor)
.build()
@Bean
fun createRegistryClient(@Autowired client: OkHttpClient) =
Retrofit.Builder()
.client(client)
.baseUrl("https://api.themoviedb.org/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(TMDBApi::class.java)
}
fun main(args: Array<String>) {
runApplication<TheMovieDbGraphQlApiWrapperApplication>(*args)
}
| 0
|
Kotlin
|
0
| 0
|
b484d03a8dcc8dd6bc7b4dc0728b04a65242e246
| 1,579
|
tmdb-graphql-server
|
Apache License 2.0
|
androidApp/src/main/java/io/github/lazyengineer/castaway/androidApp/view/onboarding/TextButton.kt
|
lazy-engineer
| 321,396,462
| false
| null |
package io.github.lazyengineer.castaway.androidApp.view.onboarding
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.LayoutScopeMarker
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.github.lazyengineer.castaway.androidApp.ext.toColor
import io.github.lazyengineer.castaway.androidApp.theme.CastawayTheme
import io.github.lazyengineer.castaway.domain.resource.Colors
@Composable
fun TextButton(
text: String,
color: Color,
modifier: Modifier = Modifier,
textColor: Color = CastawayTheme.colors.onSurface,
shape: Shape = CircleShape,
onClick: () -> Unit
) {
TextButton(
modifier = modifier,
color = color,
shape = shape,
onClick = onClick
) {
this.ButtonText(text = text, color = textColor)
}
}
@Composable
fun GradientTextButton(
text: String,
gradient: Brush,
modifier: Modifier = Modifier,
textColor: Color = CastawayTheme.colors.onSurface,
shape: Shape = CircleShape,
onClick: () -> Unit
) {
TextButton(
modifier = modifier,
gradient = gradient,
shape = shape,
onClick = onClick
) {
this.ButtonText(text = text, color = textColor)
}
}
@Composable
internal fun TextButton(
shape: Shape,
onClick: () -> Unit,
modifier: Modifier = Modifier,
color: Color? = null,
gradient: Brush? = null,
text: @Composable TextButtonScope.() -> Unit
) {
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.Transparent
),
contentPadding = PaddingValues(),
shape = shape,
onClick = onClick
) {
val backgroundModifier = if (gradient != null) {
modifier.background(gradient)
} else {
color?.let { modifier.background(color) } ?: modifier
}
Box(
modifier = backgroundModifier
.padding(horizontal = 16.dp, vertical = 8.dp),
contentAlignment = Alignment.Center
) {
TextButtonScope.text()
}
}
}
@LayoutScopeMarker
interface TextButtonScope {
@Composable
fun ButtonText(text: String, color: Color) {
Text(text = text, color = color)
}
companion object : TextButtonScope
}
@Preview
@Composable
fun TextButtonPreview() {
TextButton(
modifier = Modifier,
text = "Some Button Text",
color = CastawayTheme.colors.surface,
) {}
}
@Preview
@Composable
fun GradientTextButtonPreview() {
GradientTextButton(
modifier = Modifier,
text = "Some Button Text",
textColor = Color.White,
shape = RoundedCornerShape(8.dp),
gradient = Brush.linearGradient(
listOf(
Colors.azurGradientStart.toColor(),
Colors.azurGradientMiddle.toColor(),
Colors.azurGradientEnd.toColor(),
)
),
) {}
}
| 0
|
Kotlin
|
0
| 2
|
b65ffceb9b9a9e4e17302c69f50b307a17b7f372
| 3,219
|
castaway
|
MIT License
|
app/src/main/java/com/febers/uestc_bbs/io/CacheHelper.kt
|
WattledGnata
| 221,683,082
| true
|
{"Kotlin": 626855, "Java": 281346, "HTML": 5241, "IDL": 746}
|
package com.febers.uestc_bbs.io
import android.os.Looper
import com.bumptech.glide.Glide
import com.febers.uestc_bbs.MyApp
import com.febers.uestc_bbs.io.FileHelper.appApkDir
import com.febers.uestc_bbs.io.FileHelper.appCacheDir
import com.febers.uestc_bbs.io.FileHelper.deleteFolderFile
import com.febers.uestc_bbs.io.FileHelper.getFolderSize
import com.febers.uestc_bbs.io.FileHelper.getFormatSize
import com.febers.uestc_bbs.io.FileHelper.glideCacheDir
import java.io.File
/**
* 提供清除缓存功能
*/
object CacheHelper {
/**
* 获取图片缓存大小
* 包括Glide的缓存和Android/data/uestc_bbs/cache中的文件
*/
val CacheSize: String
get() {
return try {
getFormatSize(size = getFolderSize(File(glideCacheDir)).toDouble()
+ getFolderSize(File(appCacheDir)).toDouble()
+ getFolderSize(File(appApkDir)).toDouble())
} catch (e: Exception) {
e.printStackTrace()
"获取失败"
}
}
// 清除磁盘缓存,自己获取缓存文件夹并删除方法
fun clearCache(): Boolean {
if (deleteFolderFile(glideCacheDir, deleteThisPath = false)
&& deleteFolderFile(appCacheDir, deleteThisPath = false)
&& deleteFolderFile(appApkDir, deleteThisPath = false)) {
return true
}
return false
}
// 清除图片磁盘缓存,调用Glide自带方法
fun clearGlideCache(): Boolean {
return try {
if (Looper.myLooper() == Looper.getMainLooper()) {
Thread(Runnable {
Glide.get(MyApp.context()).clearDiskCache()
}).start()
} else {
Glide.get(MyApp.context()).clearDiskCache()
}
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
}
| 0
| null |
0
| 0
|
682790f32c02a5b2a517f07f69dc048f12add0c0
| 1,839
|
UESTC_BBS
|
Apache License 2.0
|
app/src/main/java/com/comjeong/nomadworker/domain/model/place/LocationPlaceResult.kt
|
HUFSummer-Hackathon
| 512,365,622
| false
| null |
package com.comjeong.nomadworker.domain.model.place
data class LocationPlaceResult(
val message: String,
val status: Int,
val data: Result?
) {
data class Result(
val locationName: String?,
val place: List<Place>?
) {
data class Place(
val placeId: Long,
val placeName: String,
val placeAddress: String,
val placeWeekTime: String,
val placeWeekEndTime: String,
val placeRate: Float,
val placeThumbnailImageUrl: String
)
}
}
| 2
|
Kotlin
|
0
| 0
|
5857dbe020888785367e0e4596a7b342aa1ec4a7
| 565
|
NomadWorker-Android
|
MIT License
|
app/src/main/java/com/dialogapp/dialog/util/Event.kt
|
microdotblog
| 204,969,556
| false
| null |
package com.dialogapp.dialog.util
/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {
var consumed = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun consume(): T? {
return if (consumed) {
null
} else {
consumed = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peek(): T = content
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Event<*>
if (content != other.content) return false
if (consumed != other.consumed) return false
return true
}
override fun hashCode(): Int {
var result = content?.hashCode() ?: 0
result = 31 * result + consumed.hashCode()
return result
}
}
| 1
|
Kotlin
|
1
| 5
|
3e484f76f702a855726b92eec906443a61f510a1
| 1,062
|
dialog
|
Apache License 2.0
|
features/core/database/src/main/kotlin/dev/marlonlom/apps/bookbar/core/database/db.kt
|
marlonlom
| 740,270,327
| false
| null |
/*
* Copyright 2024 Marlonlom
* SPDX-License-Identifier: Apache-2.0
*/
package dev.marlonlom.apps.bookbar.core.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import dev.marlonlom.apps.bookbar.core.database.dao.BookDetailsDao
import dev.marlonlom.apps.bookbar.core.database.dao.FavoriteBooksDao
import dev.marlonlom.apps.bookbar.core.database.dao.NewBooksDao
import dev.marlonlom.apps.bookbar.core.database.entities.BookDetailEntity
import dev.marlonlom.apps.bookbar.core.database.entities.FavoriteBookEntity
import dev.marlonlom.apps.bookbar.core.database.entities.NewBookEntity
/**
* IT Bookstore database abstract class.
*
* @author marlonlom
*/
@Database(
version = 1,
exportSchema = false,
entities = [
NewBookEntity::class,
FavoriteBookEntity::class,
BookDetailEntity::class,
]
)
abstract class BookbarDatabase : RoomDatabase() {
/**
* Returns the new books dao.
*
* @return New books dao.
*/
abstract fun newBooksDao(): NewBooksDao
/**
* Returns the favorite books dao.
*
* @return Favorite books dao.
*/
abstract fun favoriteBooksDao(): FavoriteBooksDao
/**
* Returns the book details dao.
*
* @return Book details dao.
*/
abstract fun bookDetailsDao(): BookDetailsDao
companion object {
private const val DATABASE_NAME = "bookbar-db"
@Volatile
private var instance: BookbarDatabase? = null
/**
* Creates a singleton instance of database.
*
* @param context application context.
*
* @return room database instance.
*/
fun getInstance(context: Context): BookbarDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
/**
* Creates a Room database instance.
*
* @param context Application context.
*
* @return Room database instance for the app.
*/
private fun buildDatabase(context: Context): BookbarDatabase = Room.databaseBuilder(
context,
BookbarDatabase::class.java,
DATABASE_NAME
).fallbackToDestructiveMigration()
.build()
}
}
| 4
| null |
0
| 1
|
246bf6c765cb41aec494591e056a8b26a83bc5d3
| 2,210
|
bookbar
|
Apache License 2.0
|
PaperclipEngine/src/main/kotlin/com/paperclip/engine/application/Display.kt
|
Nick-Fanelli
| 575,598,132
| false
|
{"Kotlin": 80132, "GLSL": 1313}
|
package com.paperclip.engine.application
import com.paperclip.engine.utils.Logger
import com.paperclip.engine.utils.PaperclipEngineFatalException
import com.paperclip.engine.utils.RuntimeConfig
import org.lwjgl.BufferUtils
import org.lwjgl.glfw.Callbacks.glfwFreeCallbacks
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.glfw.GLFWErrorCallback
import org.lwjgl.glfw.GLFWWindowSizeCallback
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GLCapabilities
import org.lwjgl.system.MemoryStack.stackPush
import org.lwjgl.system.MemoryUtil.NULL
import java.awt.Dimension
private val DISPLAYS = ArrayList<Display>()
private fun initializeGLFW() {
// Setup an error callback. The default implementation
// will print the error message in System.err.
// Setup an error callback. The default implementation
// will print the error message in System.err.
Logger.info("Initializing GLFW")
GLFWErrorCallback.createPrint(System.err).set()
// Initialize GLFW. Most GLFW functions will not work before doing this.
check(glfwInit()) { "Unable to initialize GLFW" }
}
private fun disposeGLFW() {
Logger.info("Disposing GLFW")
glfwTerminate()
glfwSetErrorCallback(null)?.free()
}
class DisplayPreferences {
var displayName: String? = null
var displaySize = Dimension(1280, 720)
var isVsyncEnabled = true
}
class Display(private val windowTitle: String, private var displayPreferences: DisplayPreferences) {
var windowPtr: Long = 0
private set
var fps = 0
private set
var aspectRatio = 0.0f
private set
private lateinit var updateCallback: (_: Float) -> Unit
private val windowResizeCallbackArray: ArrayList<(width: Int, height: Int) -> Unit> = ArrayList()
fun addWindowResizeCallback(callback: (width: Int, height: Int) -> Unit) { windowResizeCallbackArray.add(callback) }
fun removeWindowResizeCallback(callback: (width: Int, height: Int) -> Unit) { windowResizeCallbackArray.remove(callback) }
private lateinit var glCapabilities: GLCapabilities
private var endTime = 0.0f
private var startTime = 0.0f
private var deltaTime = 0.0f
private var accumulatedDeltaTime = 0.0f
private var frameCount = 0
fun createDisplay(updateCallback: (_: Float) -> Unit) {
if(DISPLAYS.size <= 0)
initializeGLFW()
DISPLAYS.add(this)
this.updateCallback = updateCallback
// Configure GLFW
glfwDefaultWindowHints() // optional, the current window hints are already the default
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE) // the window will stay hidden after creation
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE) // the window will be resizable
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
// Create the window
windowPtr = glfwCreateWindow(displayPreferences.displaySize.width, displayPreferences.displaySize.height,
if(displayPreferences.displayName == null) windowTitle else displayPreferences.displayName!! , NULL, NULL)
if (windowPtr == NULL) throw PaperclipEngineFatalException("Failed to create the GLFW window")
aspectRatio = displayPreferences.displaySize.width.toFloat() / displayPreferences.displaySize.height.toFloat()
// Get the thread stack and push a new frame
stackPush().use { stack ->
val pWidth = stack.mallocInt(1) // int*
val pHeight = stack.mallocInt(1) // int*
// Get the window size passed to glfwCreateWindow
glfwGetWindowSize(windowPtr, pWidth, pHeight)
// Get the resolution of the primary monitor
val vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor())
// Center the window
glfwSetWindowPos(
windowPtr,
(vidMode!!.width() - pWidth[0]) / 2,
(vidMode.height() - pHeight[0]) / 2
)
}
// Make the OpenGL context current
glfwMakeContextCurrent(windowPtr)
// Enable v-sync
glfwSwapInterval(if(displayPreferences.isVsyncEnabled) 1 else 0)
glfwSetWindowSizeCallback(windowPtr, object : GLFWWindowSizeCallback() {
override operator fun invoke(window: Long, width: Int, height: Int) {
aspectRatio = width.toFloat() / height.toFloat()
glViewport(0, 0, width, height)
for(callback in windowResizeCallbackArray) {
callback(width, height)
}
}
})
// Make the window visible
glfwShowWindow(windowPtr)
this.glCapabilities = GL.createCapabilities()
RuntimeConfig.OpenGLRuntimeConfig.initialize()
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
glCullFace(GL_BACK)
Logger.info("Created Display")
}
fun requestUpdate(callback: () -> Unit) {
glClearColor(0.2f, 0.2f, 0.2f, 1.0f)
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
callback()
glfwSwapBuffers(windowPtr)
glfwPollEvents()
}
private fun update() {
glClearColor(0.2f, 0.2f, 0.2f, 1.0f)
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
if(deltaTime >= 0) {
updateCallback(deltaTime)
}
glfwSwapBuffers(windowPtr)
glfwPollEvents()
endTime = glfwGetTime().toFloat()
deltaTime = endTime - startTime
startTime = endTime
accumulatedDeltaTime += deltaTime
if(accumulatedDeltaTime > 1.0f) {
fps = frameCount
frameCount = 0
accumulatedDeltaTime = 0.0f
}
frameCount++
}
fun getWindowSize() : Pair<Int, Int> {
val width = BufferUtils.createIntBuffer(1)
val height = BufferUtils.createIntBuffer(1)
glfwGetWindowSize(windowPtr, width, height)
return Pair(width[0], height[0])
}
fun continuouslyUpdateDisplayUntilCloseRequested() {
while(!glfwWindowShouldClose(this.windowPtr))
this.update()
}
fun closeDisplay() {
glfwSetWindowShouldClose(windowPtr, true)
Logger.info("Set window to close")
}
fun cleanUp() {
glfwFreeCallbacks(windowPtr)
glfwDestroyWindow(windowPtr)
DISPLAYS.remove(this)
if(DISPLAYS.size <= 0)
disposeGLFW()
}
}
| 0
|
Kotlin
|
0
| 0
|
f269666b0980f75e08f31d91523beb9ab2a9f88d
| 6,642
|
Paperclip
|
MIT License
|
src/main/kotlin/me/devoxin/jukebot/utils/HttpClient.kt
|
devoxin
| 104,263,117
| false
| null |
package me.devoxin.jukebot.utils
import okhttp3.*
import okhttp3.Headers.Companion.headersOf
import org.slf4j.LoggerFactory
import java.io.IOException
import java.util.concurrent.CompletableFuture
class RequestUtil {
private val httpClient = OkHttpClient()
inner class PendingRequest(private val request: Request) {
fun submit(): CompletableFuture<Response> {
val fut = CompletableFuture<Response>()
httpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
logger.error("An error occurred during a HTTP request to ${call.request().url}", e)
fut.completeExceptionally(e)
}
override fun onResponse(call: Call, response: Response) {
logger.debug("Response: code=${response.code} message=${response.message}")
fut.complete(response)
}
})
return fut
}
fun queue(success: (Response) -> Unit, failure: (IOException) -> Unit) {
submit()
.thenAccept(success)
.exceptionally {
failure(it as IOException)
null
}
}
}
fun get(url: String, headers: Headers = headersOf()): PendingRequest {
return request {
get()
url(url)
headers(headers)
}
}
fun request(opts: Request.Builder.() -> Unit): PendingRequest {
val req = Request.Builder()
.header("User-Agent", "JukeBot (https://github.com/Devoxin/JukeBot)")
.apply(opts)
.build()
return PendingRequest(req)
}
fun request(request: Request) = PendingRequest(request)
companion object {
private val logger = LoggerFactory.getLogger(RequestUtil::class.java)
}
}
| 0
| null |
11
| 39
|
7754d73038ecc1657ff858a11fb2ef960b607a11
| 1,931
|
JukeBot
|
Apache License 2.0
|
vector/src/main/java/im/vector/app/features/settings/devices/v2/GetDeviceFullInfoListUseCase.kt
|
tchapgouv
| 340,329,238
| false
| null |
/*
* Copyright (c) 2022 New Vector Ltd
*
* 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 im.vector.app.features.settings.devices.v2
import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.core.session.clientinfo.GetMatrixClientInfoUseCase
import im.vector.app.features.settings.devices.v2.filter.DeviceManagerFilterType
import im.vector.app.features.settings.devices.v2.filter.FilterDevicesUseCase
import im.vector.app.features.settings.devices.v2.list.CheckIfSessionIsInactiveUseCase
import im.vector.app.features.settings.devices.v2.verification.CurrentSessionCrossSigningInfo
import im.vector.app.features.settings.devices.v2.verification.GetCurrentSessionCrossSigningInfoUseCase
import im.vector.app.features.settings.devices.v2.verification.GetEncryptionTrustLevelForDeviceUseCase
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.emptyFlow
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo
import org.matrix.android.sdk.flow.flow
import javax.inject.Inject
class GetDeviceFullInfoListUseCase @Inject constructor(
private val activeSessionHolder: ActiveSessionHolder,
private val checkIfSessionIsInactiveUseCase: CheckIfSessionIsInactiveUseCase,
private val getEncryptionTrustLevelForDeviceUseCase: GetEncryptionTrustLevelForDeviceUseCase,
private val getCurrentSessionCrossSigningInfoUseCase: GetCurrentSessionCrossSigningInfoUseCase,
private val filterDevicesUseCase: FilterDevicesUseCase,
private val parseDeviceUserAgentUseCase: ParseDeviceUserAgentUseCase,
private val getMatrixClientInfoUseCase: GetMatrixClientInfoUseCase,
) {
fun execute(filterType: DeviceManagerFilterType, excludeCurrentDevice: Boolean = false): Flow<List<DeviceFullInfo>> {
return activeSessionHolder.getSafeActiveSession()?.let { session ->
val deviceFullInfoFlow = combine(
getCurrentSessionCrossSigningInfoUseCase.execute(),
session.flow().liveUserCryptoDevices(session.myUserId),
session.flow().liveMyDevicesInfo()
) { currentSessionCrossSigningInfo, cryptoList, infoList ->
val deviceFullInfoList = convertToDeviceFullInfoList(session, currentSessionCrossSigningInfo, cryptoList, infoList)
val excludedDeviceIds = if (excludeCurrentDevice) {
listOf(currentSessionCrossSigningInfo.deviceId)
} else {
emptyList()
}
filterDevicesUseCase.execute(currentSessionCrossSigningInfo, deviceFullInfoList, filterType, excludedDeviceIds)
}
deviceFullInfoFlow.distinctUntilChanged()
} ?: emptyFlow()
}
private fun convertToDeviceFullInfoList(
session: Session,
currentSessionCrossSigningInfo: CurrentSessionCrossSigningInfo,
cryptoList: List<CryptoDeviceInfo>,
infoList: List<DeviceInfo>,
): List<DeviceFullInfo> {
return infoList
.sortedByDescending { it.lastSeenTs }
.map { deviceInfo ->
val cryptoDeviceInfo = cryptoList.firstOrNull { it.deviceId == deviceInfo.deviceId }
val roomEncryptionTrustLevel = getEncryptionTrustLevelForDeviceUseCase.execute(currentSessionCrossSigningInfo, cryptoDeviceInfo)
val isInactive = checkIfSessionIsInactiveUseCase.execute(deviceInfo.lastSeenTs ?: 0)
val isCurrentDevice = currentSessionCrossSigningInfo.deviceId == cryptoDeviceInfo?.deviceId
val deviceExtendedInfo = parseDeviceUserAgentUseCase.execute(deviceInfo.getBestLastSeenUserAgent())
val matrixClientInfo = deviceInfo.deviceId
?.takeIf { it.isNotEmpty() }
?.let { getMatrixClientInfoUseCase.execute(session, it) }
DeviceFullInfo(
deviceInfo = deviceInfo,
cryptoDeviceInfo = cryptoDeviceInfo,
roomEncryptionTrustLevel = roomEncryptionTrustLevel,
isInactive = isInactive,
isCurrentDevice = isCurrentDevice,
deviceExtendedInfo = deviceExtendedInfo,
matrixClientInfo = matrixClientInfo
)
}
}
}
| 91
|
Kotlin
|
6
| 9
|
a2c060c687b0aa69af681138c5788d6933d19860
| 5,185
|
tchap-android
|
Apache License 2.0
|
app/src/main/java/me/hegj/wandroid/mvp/ui/adapter/TodoAdapter.kt
|
hegaojian
| 206,478,384
| false
| null |
package me.hegj.wandroid.mvp.ui.adapter
import android.util.TypedValue
import android.widget.ImageView
import androidx.cardview.widget.CardView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import me.hegj.wandroid.R
import me.hegj.wandroid.app.utils.DatetimeUtil
import me.hegj.wandroid.app.utils.SettingUtil
import me.hegj.wandroid.mvp.model.entity.TodoResponse
import me.hegj.wandroid.mvp.model.entity.enums.TodoType
/**
* 积分排行 adapter
* @Author: hegaojian
* @CreateDate: 2019/9/1 9:52
*/
class TodoAdapter(data: ArrayList<TodoResponse>?) : BaseQuickAdapter<TodoResponse, BaseViewHolder>(R.layout.item_todo, data) {
override fun convert(helper: BaseViewHolder, item: TodoResponse?) {
//赋值
item?.run {
helper.setText(R.id.item_todo_title, title)
helper.setText(R.id.item_todo_content, content)
helper.setText(R.id.item_todo_date, dateStr)
helper.addOnClickListener(R.id.item_todo_setting)
if (status == 1) {
//已完成
helper.setVisible(R.id.item_todo_status, true)
helper.setImageResource(R.id.item_todo_status, R.drawable.ic_done)
helper.getView<CardView>(R.id.item_todo_cardview).foreground = mContext.getDrawable(R.drawable.forground_shap)
} else {
if (date < DatetimeUtil.nows.time) {
//未完成并且超过了预定完成时间
helper.setVisible(R.id.item_todo_status, true)
helper.setImageResource(R.id.item_todo_status, R.drawable.ic_yiguoqi)
helper.getView<CardView>(R.id.item_todo_cardview).foreground = mContext.getDrawable(R.drawable.forground_shap)
} else {
//未完成
helper.setVisible(R.id.item_todo_status, false)
TypedValue().apply {
mContext.theme.resolveAttribute(R.attr.selectableItemBackground, this, true)
}.run {
helper.getView<CardView>(R.id.item_todo_cardview).foreground = mContext.getDrawable(resourceId)
}
}
}
helper.getView<ImageView>(R.id.item_todo_tag).imageTintList = SettingUtil.getOneColorStateList(TodoType.byType(priority).color)
}
}
}
| 1
|
Kotlin
|
100
| 713
|
622016c9695c01f3a134a23c4af1f76686aad6f1
| 2,387
|
WanAndroid
|
Apache License 2.0
|
info/src/main/java/com/droidcon/info/presentation/InfoOptionViewHolders.kt
|
rockndroid
| 219,824,667
| false
| null |
package com.droidcon.info.presentation
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.FitCenter
import com.droidcon.info.R
sealed class InfoOptionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class InfoOptionRowViewHolder(itemView: View) : InfoOptionViewHolder(itemView) {
fun bind(infoOptionRow: InfoOption.Row) {
itemView.findViewById<TextView>(R.id.title).run {
text = context.getString(infoOptionRow.title)
setCompoundDrawablesRelativeWithIntrinsicBounds(infoOptionRow.icon, 0, R.drawable.ic_arrow, 0)
}
itemView.setOnClickListener { infoOptionRow.action() }
}
}
class InfoOptionMapViewHolder(itemView: View) : InfoOptionViewHolder(itemView) {
fun bind(infoOptionMap: InfoOption.Map) {
itemView.findViewById<ImageView>(R.id.venueMap).run {
Glide.with(itemView)
.load(infoOptionMap.image)
.transform(FitCenter())
.placeholder(R.drawable.staticmap_bg)
.into(this)
}
itemView.findViewById<View>(R.id.dummyViewForRipple).setOnClickListener {
infoOptionMap.action()
}
}
}
| 2
|
Kotlin
|
0
| 0
|
01e1bbb55b65ee57f186eb0fd98cbc84ea92b3f9
| 1,347
|
android-droidcon-madrid-19
|
Apache License 2.0
|
features/src/main/kotlin/ru/mobileup/template/features/pokemons/ui/details/FakePokemonDetailsComponent.kt
|
MobileUpLLC
| 485,284,340
| false
| null |
package ru.mobileup.template.features.pokemons.ui.details
import kotlinx.coroutines.flow.MutableStateFlow
import ru.mobileup.template.core.utils.LoadableState
import ru.mobileup.template.features.pokemons.domain.DetailedPokemon
import ru.mobileup.template.features.pokemons.domain.PokemonId
import ru.mobileup.template.features.pokemons.domain.PokemonType
class FakePokemonDetailsComponent : PokemonDetailsComponent {
override val pokemonState = MutableStateFlow(
LoadableState(
loading = true,
data = DetailedPokemon(
id = PokemonId("1"),
name = "Bulbasaur",
imageUrl = "",
height = 0.7f,
weight = 6.9f,
types = listOf(PokemonType.Grass, PokemonType.Poison)
)
)
)
override fun onRetryClick() = Unit
override fun onRefresh() = Unit
}
| 1
| null |
2
| 8
|
75c3350979d4d2a92d8b685194b80ef3747201e9
| 903
|
MobileUp-Android-Template
|
MIT License
|
android/src/com/android/tools/idea/welcome/install/Aehd.kt
|
JetBrains
| 60,701,247
| false
|
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.welcome.install
import com.android.tools.idea.avdmanager.AccelerationErrorCode
import com.android.tools.idea.avdmanager.AccelerationErrorSolution.SolutionCode
import com.android.tools.idea.observable.core.IntValueProperty
import com.android.tools.idea.sdk.install.VmType
import com.android.tools.idea.welcome.install.InstallationIntention.UNINSTALL
import com.android.tools.idea.welcome.wizard.HaxmInstallSettingsStep
import com.android.tools.idea.welcome.wizard.deprecated.AehdInstallInfoStep
import com.android.tools.idea.welcome.wizard.deprecated.VmUninstallInfoStep
import com.android.tools.idea.wizard.dynamic.ScopedStateStore
import com.android.tools.idea.wizard.model.ModelWizardStep
import com.intellij.openapi.util.SystemInfo
/**
* Google AEHD installable component
*/
class Aehd(
installationIntention: InstallationIntention,
isCustomInstall: ScopedStateStore.Key<Boolean>
) : Vm(Aehd, installationIntention, isCustomInstall) {
override val filePrefix = "aehd"
override val installUrl = AEHD_WINDOWS_INSTALL_URL
override val steps: Collection<ModelWizardStep<*>>
get() = setOf(if (installationIntention == UNINSTALL) com.android.tools.idea.welcome.wizard.VmUninstallInfoStep(VmType.AEHD)
else HaxmInstallSettingsStep(IntValueProperty(1024))) // FIXME
override fun createSteps() =
setOf(if (installationIntention === UNINSTALL) VmUninstallInfoStep(VmType.AEHD)
else AehdInstallInfoStep(isCustomInstall))
companion object InstallerInfo : VmInstallerInfo("Android Emulator hypervisor driver") {
override val vendor = "google"
override val installSolution = SolutionCode.INSTALL_AEHD
override val reinstallSolution = SolutionCode.REINSTALL_AEHD
override val incompatibleSystemError = when {
!SystemInfo.isWindows -> AccelerationErrorCode.AEHD_REQUIRES_WINDOWS
else -> null
}
override val componentPath = "Android_Emulator_Hypervisor_Driver"
}
}
| 5
|
Kotlin
|
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 2,584
|
android
|
Apache License 2.0
|
app/src/main/java/com/yashk9/githubapp/ui/adapter/RepoAdapter.kt
|
yash-k9
| 450,887,409
| false
|
{"Kotlin": 32123}
|
package com.yashk9.githubapp.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.yashk9.githubapp.R
import com.yashk9.githubapp.databinding.RepoListItemBinding
import com.yashk9.githubapp.model.Repo
//Adapter for the HomeFragment - Handles data from Paging
class RepoAdapter: PagingDataAdapter<Repo, RecyclerView.ViewHolder>(diffUtil){
class RepoViewHolder(val binding: RepoListItemBinding): RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val binding = RepoListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return RepoViewHolder(binding)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val binding = (holder as RepoViewHolder).binding
val curr = getItem(position)
with(holder.binding){
curr?.let{ curr ->
user.text = curr.owner.login
repo.text = curr.name
description.text = curr.description
language.text = curr.language
stars.text = "${curr.stargazers_count}"
Glide.with(holder.itemView.context)
.load(curr.owner.avatar_url)
.placeholder(R.drawable.ic_launcher_foreground)
.into(imageView)
}
}
}
companion object{
private val diffUtil = object : DiffUtil.ItemCallback<Repo>(){
override fun areItemsTheSame(oldItem: Repo, newItem: Repo): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Repo, newItem: Repo): Boolean {
return oldItem.id == newItem.id
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
bd9190c8b3e6ee5c68fecad4a37a947f4eaf2cc5
| 2,002
|
GithubApp
|
Apache License 2.0
|
wear/src/main/java/io/homeassistant/companion/android/tiles/TemplateTile.kt
|
home-assistant
| 179,008,173
| false
| null |
package io.homeassistant.companion.android.tiles
import androidx.wear.tiles.ActionBuilders
import androidx.wear.tiles.DimensionBuilders
import androidx.wear.tiles.DimensionBuilders.dp
import androidx.wear.tiles.LayoutElementBuilders
import androidx.wear.tiles.LayoutElementBuilders.Box
import androidx.wear.tiles.LayoutElementBuilders.Layout
import androidx.wear.tiles.LayoutElementBuilders.LayoutElement
import androidx.wear.tiles.ModifiersBuilders
import androidx.wear.tiles.RequestBuilders.ResourcesRequest
import androidx.wear.tiles.RequestBuilders.TileRequest
import androidx.wear.tiles.ResourceBuilders
import androidx.wear.tiles.ResourceBuilders.Resources
import androidx.wear.tiles.TileBuilders.Tile
import androidx.wear.tiles.TileService
import androidx.wear.tiles.TimelineBuilders.Timeline
import androidx.wear.tiles.TimelineBuilders.TimelineEntry
import com.google.common.util.concurrent.ListenableFuture
import dagger.hilt.android.AndroidEntryPoint
import io.homeassistant.companion.android.R
import io.homeassistant.companion.android.common.data.integration.IntegrationRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.guava.future
import javax.inject.Inject
import io.homeassistant.companion.android.common.R as commonR
@AndroidEntryPoint
class TemplateTile : TileService() {
private val serviceJob = Job()
private val serviceScope = CoroutineScope(Dispatchers.IO + serviceJob)
@Inject
lateinit var integrationUseCase: IntegrationRepository
override fun onTileRequest(requestParams: TileRequest): ListenableFuture<Tile> =
serviceScope.future {
val template = integrationUseCase.getTemplateTileContent()
val renderedText = try {
integrationUseCase.renderTemplate(template, mapOf())
} catch (e: Exception) {
getString(commonR.string.template_tile_error)
}
Tile.Builder()
.setResourcesVersion("1")
.setFreshnessIntervalMillis(
integrationUseCase.getTemplateTileRefreshInterval().toLong() * 60 * 1000
)
.setTimeline(
Timeline.Builder().addTimelineEntry(
TimelineEntry.Builder().setLayout(
Layout.Builder().setRoot(
layout(renderedText)
).build()
).build()
).build()
).build()
}
override fun onResourcesRequest(requestParams: ResourcesRequest): ListenableFuture<Resources> =
serviceScope.future {
Resources.Builder()
.setVersion("1")
.addIdToImageMapping(
"refresh",
ResourceBuilders.ImageResource.Builder()
.setAndroidResourceByResId(
ResourceBuilders.AndroidImageResourceByResId.Builder()
.setResourceId(R.drawable.ic_refresh)
.build()
).build()
)
.build()
}
override fun onDestroy() {
super.onDestroy()
// Cleans up the coroutine
serviceJob.cancel()
}
fun layout(renderedText: String): LayoutElement = Box.Builder().apply {
addContent(
LayoutElementBuilders.Text.Builder()
.setText(
if (renderedText.isEmpty()) {
getString(commonR.string.template_tile_empty)
} else {
renderedText
}
)
.setMaxLines(10)
.build()
)
addContent(
LayoutElementBuilders.Arc.Builder()
.setAnchorAngle(
DimensionBuilders.DegreesProp.Builder()
.setValue(180f)
.build()
)
.addContent(
LayoutElementBuilders.ArcAdapter.Builder()
.setContent(
LayoutElementBuilders.Image.Builder()
.setResourceId("refresh")
.setWidth(dp(24f))
.setHeight(dp(24f))
.setModifiers(
ModifiersBuilders.Modifiers.Builder()
.setClickable(
ModifiersBuilders.Clickable.Builder()
.setOnClick(
ActionBuilders.LoadAction.Builder().build()
)
.build()
)
.build()
)
.build()
)
.setRotateContents(false)
.build()
)
.build()
)
}
.build()
}
| 90
|
Kotlin
|
345
| 1,187
|
e3bd338bf1ebf8256c65d45737fd236f70ac9098
| 5,328
|
home-assistant-android
|
Apache License 2.0
|
src/test/kotlin/app/infinityflow/keycloak/events/tests/TemporalTest.kt
|
InfinityFlowApp
| 784,920,727
| false
|
{"Kotlin": 13363}
|
package app.infinityflow.keycloak.events.tests
import app.infinityflow.keycloak.events.TemporalEventListenerProviderFactory
import org.keycloak.events.Event
import org.keycloak.events.EventType
import org.keycloak.events.admin.AdminEvent
import org.keycloak.events.admin.AuthDetails
import org.keycloak.events.admin.OperationType
import org.keycloak.events.admin.ResourceType
import java.util.Date
import java.util.UUID
import kotlin.test.Test
class TemporalTest {
@Test
fun testConnect() {
val factory = TemporalEventListenerProviderFactory()
factory.init(TestScope())
val provider = factory.create(null)
val event = createEvent()
val adminEvent = createAdminEvent()
val nextAdminEvent = createAdminEvent()
provider.onEvent(event)
provider.onEvent(adminEvent, false)
provider.onEvent(nextAdminEvent, true)
provider.close()
factory.close()
}
private fun createEvent(): Event {
val details = mapOf("a" to "b")
val ev = Event()
ev.id = UUID.randomUUID().toString()
ev.type = EventType.LOGIN
ev.time = Date().toInstant().epochSecond
ev.realmId = "test"
ev.clientId = "test"
ev.details = details
ev.error = ""
ev.ipAddress = "127.0.0.1"
ev.sessionId = "test"
ev.userId = "test"
return ev
}
private fun createAdminEvent(): AdminEvent {
val details = AuthDetails()
details.clientId = "clientId"
details.userId = "userId"
details.ipAddress = "127.0.0.1"
details.realmId = "realmId"
val ev = AdminEvent()
ev.id = UUID.randomUUID().toString()
ev.operationType = OperationType.CREATE
ev.realmId = "realm"
ev.resourceTypeAsString = "CREATE"
ev.time = Date().toInstant().epochSecond
ev.resourceType = ResourceType.USER
ev.authDetails = details
ev.error = "error"
ev.representation = "representation"
ev.resourcePath = "resource/path/to/somewhere"
return ev
}
}
| 4
|
Kotlin
|
0
| 2
|
5065a5a17ed5c918bda6472ea5d7a5b8504f9c9d
| 2,113
|
keycloak-event-listener-temporal
|
Apache License 2.0
|
src/main/kotlin/SettingsPanel.kt
|
antonarhipov
| 501,758,453
| false
| null |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Slider
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun StepSlider(
initialValue: Int,
minValue: Int,
maxValue: Int,
label: String,
onChange: (Int) -> Unit,
) {
var value by remember { mutableStateOf(initialValue.toFloat()) }
Column(
modifier = Modifier.padding(10.dp)
) {
Row {
Text(text = "$label: ", fontSize = 14.sp)
Text(text = "%d".format(value.toInt()), fontSize = 14.sp)
}
Slider(
value = value,
valueRange = minValue.toFloat()..maxValue.toFloat(),
onValueChange = { value = it; onChange(value.toInt()) },
onValueChangeFinished = { onChange(value.toInt()) }
)
}
}
val padding = Modifier.padding(10.dp)
@Composable
fun PropertySlider(
initialValue: Double,
minValue: Double,
maxValue: Double,
label: String,
onChange: (Double) -> Unit,
) {
var value by remember { mutableStateOf(initialValue.toFloat()) }
Column(
modifier = padding
) {
Row {
Text(text = "$label: ", fontSize = 14.sp)
Text(text = "%.2f".format(value), fontSize = 14.sp)
}
Slider(
value = value,
valueRange = minValue.toFloat()..maxValue.toFloat(),
onValueChange = { value = it; onChange(value.toDouble()) },
onValueChangeFinished = { onChange(value.toDouble()) }
)
}
}
const val MIN_RANDOM = 0.1
const val MAX_RANDOM = 50.0
const val MIN_ORBIT_RADIUS = 100.00
const val MAX_ORBIT_RADIUS = 600.00
const val MIN_INNER_RADIUS = 100.00
const val MAX_INNER_RADIUS = 200.00
const val MIN_OUTER_RADIUS = 200.00
const val MAX_OUTER_RADIUS = 300.00
const val MIN_STEPS = 1
const val MAX_STEPS = 360
data class Settings(
val orbitRadius: Double = 300.0,
val innerCirclesRadius: Double = MIN_INNER_RADIUS,
val outerCirclesRadius: Double = MIN_OUTER_RADIUS,
val randomCoefficient: Double = MIN_RANDOM,
val stepsInnerOrbit: Int = 3,
val stepsOuterOrbit: Int = 5,
val drawInnerOrbit: Boolean = true,
val drawOuterOrbit: Boolean = true,
)
@Preview
@Composable
fun SettingsPanel(settings: Settings, onValueChange: (Settings) -> Unit) {
LazyColumn(
modifier = Modifier.width(400.dp)
) {
item {
Text(
"Settings",
color = MaterialTheme.colors.primaryVariant,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(vertical = 10.dp, horizontal = 10.dp)
)
}
item {
Text(modifier = padding, text = "Draw inner orbit")
Switch(modifier = padding, checked = settings.drawInnerOrbit, onCheckedChange = { newValue ->
onValueChange(settings.copy(drawInnerOrbit = newValue))
})
}
item {
Text(modifier = padding, text = "Draw outer orbit")
Switch(modifier = padding, checked = settings.drawOuterOrbit, onCheckedChange = { newValue ->
onValueChange(settings.copy(drawOuterOrbit = newValue))
})
}
item {
PropertySlider(
settings.orbitRadius,
MIN_ORBIT_RADIUS,
MAX_ORBIT_RADIUS,
"Orbits radius"
) { newValue -> onValueChange(settings.copy(orbitRadius = newValue)) }
}
item {
StepSlider(
settings.stepsInnerOrbit,
MIN_STEPS,
MAX_STEPS,
"Steps for inner orbit"
) { newValue -> onValueChange(settings.copy(stepsInnerOrbit = newValue)) }
}
item {
StepSlider(
settings.stepsOuterOrbit,
MIN_STEPS,
MAX_STEPS,
"Steps for outer orbit"
) { newValue -> onValueChange(settings.copy(stepsOuterOrbit = newValue)) }
}
item {
PropertySlider(
settings.innerCirclesRadius,
MIN_INNER_RADIUS,
MAX_INNER_RADIUS,
"Inner orbit circles radius"
) { newValue -> onValueChange(settings.copy(innerCirclesRadius = newValue)) }
}
item {
PropertySlider(
settings.outerCirclesRadius,
MIN_OUTER_RADIUS,
MAX_OUTER_RADIUS,
"Outer orbit circles radius"
) { newValue -> onValueChange(settings.copy(outerCirclesRadius = newValue)) }
}
item {
PropertySlider(
settings.randomCoefficient,
MIN_RANDOM,
MAX_RANDOM,
"Random"
) { newValue -> onValueChange(settings.copy(randomCoefficient = newValue)) }
}
}
}
| 0
|
Kotlin
|
3
| 61
|
f3c2a4f6f58ee3ad58a1c2a683d783dafbcfcf2d
| 5,444
|
compose-for-desktop-samples
|
Apache License 2.0
|
design-library/src/main/kotlin/app/dapk/st/design/components/itemRow.kt
|
ShadowJonathan
| 471,471,233
| true
|
{"Kotlin": 586327, "Java": 13756, "Shell": 763, "Prolog": 113}
|
package app.dapk.st.design.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun TextRow(title: String, content: String? = null, includeDivider: Boolean = true, onClick: (() -> Unit)? = null, body: @Composable () -> Unit = {}) {
val modifier = Modifier.padding(horizontal = 24.dp)
Column(
Modifier
.fillMaxWidth()
.clickable(enabled = onClick != null) { onClick?.invoke() }) {
Spacer(modifier = Modifier.height(24.dp))
Column(modifier) {
when (content) {
null -> {
Text(text = title, fontSize = 18.sp)
}
else -> {
Text(text = title, fontSize = 12.sp)
Spacer(modifier = Modifier.height(2.dp))
Text(text = content, fontSize = 18.sp)
}
}
body()
Spacer(modifier = Modifier.height(24.dp))
}
if (includeDivider) {
Divider(modifier = Modifier.fillMaxWidth())
}
}
}
@Composable
fun IconRow(icon: ImageVector, title: String, onClick: (() -> Unit)? = null) {
Row(
Modifier
.fillMaxWidth()
.clickable(enabled = onClick != null) { onClick?.invoke() }
.padding(24.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(icon, contentDescription = null)
Spacer(modifier = Modifier.width(12.dp))
Text(text = title, fontSize = 18.sp)
}
}
@Composable
fun SettingsTextRow(title: String, subtitle: String?, onClick: (() -> Unit)?) {
TextRow(title = title, subtitle, includeDivider = false, onClick)
}
| 0
| null |
0
| 0
|
2ab2253e7a1335f8c25b5e69be0dc1ec9c254958
| 2,091
|
small-talk
|
Apache License 2.0
|
client/src/main/kotlin/com/github/bvfnbk/plopp/client/components/application/bar/ApplicationBarStyles.kt
|
bvfnbk
| 427,322,781
| false
| null |
package com.github.bvfnbk.plopp.client.components.application.bar
import com.github.bvfnbk.plopp.client.DefaultTheme
import kotlinx.css.*
import styled.StyleSheet
/**
* @author bvfnbk
*/
object ApplicationBarStyles : StyleSheet("ApplicationBarStyles", isStatic = true) {
val appBar by css {
flex(0.0)
display = Display.flex
alignItems = Align.center
padding(1.5.rem)
backgroundColor = DefaultTheme.inverse.background
color = DefaultTheme.inverse.foreground
}
}
| 21
|
Kotlin
|
0
| 0
|
f613efba000533114b90d46b554d0854db00d07f
| 524
|
plopp
|
Apache License 2.0
|
src/main/kotlin/org/arend/psi/ext/impl/MetaAdapter.kt
|
JetBrains
| 96,068,447
| false
| null |
package org.arend.psi.ext.impl
import com.intellij.lang.ASTNode
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.stubs.IStubElementType
import org.arend.ArendIcons
import org.arend.naming.reference.GlobalReferable
import org.arend.naming.reference.LocatedReferable
import org.arend.naming.reference.MetaReferable
import org.arend.naming.reference.Referable
import org.arend.naming.resolving.visitor.TypeClassReferenceExtractVisitor
import org.arend.psi.*
import org.arend.psi.ext.PsiLocatedReferable
import org.arend.psi.stubs.ArendDefMetaStub
import org.arend.resolving.util.ReferableExtractVisitor
import org.arend.term.abs.Abstract
import org.arend.term.abs.AbstractDefinitionVisitor
import java.util.function.Supplier
abstract class MetaAdapter : DefinitionAdapter<ArendDefMetaStub>, ArendDefMeta, Abstract.MetaDefinition {
constructor(node: ASTNode) : super(node)
constructor(stub: ArendDefMetaStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
var metaRef: MetaReferable?
get() = tcReferableCache as MetaReferable?
set(value) {
tcReferableCache = value
}
private fun prepareTCRef(parent: LocatedReferable?) =
MetaReferable(precedence, refName, aliasPrecedence, aliasName, documentation?.toString() ?: "", null, null, parent)
override fun makeTCReferable(data: SmartPsiElementPointer<PsiLocatedReferable>, parent: LocatedReferable?) =
prepareTCRef(parent).apply { underlyingReferable = Supplier { runReadAction { data.element } } }
fun makeTCReferable(parent: LocatedReferable?) =
prepareTCRef(parent).apply { underlyingReferable = Supplier { this } }
override fun getBodyReference(visitor: TypeClassReferenceExtractVisitor): Referable? =
ReferableExtractVisitor(requiredAdditionalInfo = false, isExpr = true).findReferable(expr)
override fun getKind() = GlobalReferable.Kind.OTHER
override fun getIcon(flags: Int) = ArendIcons.META_DEFINITION
override fun getTerm(): Abstract.Expression? = expr
override fun getParameters(): MutableList<ArendNameTeleUntyped> = nameTeleUntypedList
override fun getPLevelParams(): ArendPLevelParams? = null
override fun getHLevelParams(): ArendHLevelParams? = null
override fun getPLevelParameters(): Abstract.LevelParameters? = metaPLevels?.metaPLevelsSeq?.let { MetaPLevelParameters(it) }
override fun getHLevelParameters(): Abstract.LevelParameters? = metaHLevels?.metaHLevelsSeq?.let { MetaHLevelParameters(it) }
override fun <R : Any?> accept(visitor: AbstractDefinitionVisitor<out R>): R =
visitor.visitMeta(this)
}
private class MetaPLevelParameters(private val levels: ArendMetaPLevelsSeq) : Abstract.LevelParameters {
override fun getData() = levels
override fun getReferables(): List<ArendPLevelIdentifier> = levels.pLevelIdentifierList
override fun getComparisonList(): List<Abstract.Comparison> = emptyList()
override fun isIncreasing() = true
}
private class MetaHLevelParameters(private val levels: ArendMetaHLevelsSeq) : Abstract.LevelParameters {
override fun getData() = levels
override fun getReferables(): List<ArendHLevelIdentifier> = levels.hLevelIdentifierList
override fun getComparisonList(): List<Abstract.Comparison> = emptyList()
override fun isIncreasing() = true
}
| 67
|
Kotlin
|
13
| 79
|
65a989952c2c9830ade7b0b303b09a827ab7dfff
| 3,419
|
intellij-arend
|
Apache License 2.0
|
app/src/main/java/com/budget/tracker/requests/AddCategoryRequest.kt
|
PWSZ-Budget-Tracker
| 245,879,552
| false
| null |
package com.budget.tracker.requests
data class AddCategoryRequest(val name: String, val type: Int)
| 0
|
Kotlin
|
0
| 1
|
81e37d1ee99f3d9c2a09b727b36fd2b44d359f5b
| 99
|
mobile
|
MIT License
|
plugin-development/version-catalog-accessor/src/test/resources/fixture/VersionCatalogDependency.kt
|
bitfunk
| 462,763,869
| false
| null |
package com.example.catalog.generated
import kotlin.String
public interface VersionCatalogDependency {
public interface Group : VersionCatalogDependency
public interface GroupLeaf : VersionCatalogDependency {
public fun `get`(): String
public fun getStatic(): String
}
public interface Leaf : VersionCatalogDependency {
public fun `get`(): String
public fun getStatic(): String
}
}
| 11
|
Kotlin
|
0
| 3
|
84546f26717eafae6d214069eeb66f7a92240376
| 440
|
gradle-plugins
|
ISC License
|
features/total_cases/src/main/java/com/pimenta/pandreports/totalcases/di/module/TotalCasesRemoteDataSourceModule.kt
|
marcuspimenta
| 250,781,614
| false
| null |
/*
* Copyright (C) 2020 <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 com.pimenta.pandreports.totalcases.di.module
import com.pimenta.pandreports.presentation.di.annotation.ActivityScope
import com.pimenta.pandreports.totalcases.data.datasource.remote.datasource.TotalCasesRemoteDataSource
import com.pimenta.pandreports.totalcases.data.datasource.remote.datasource.TotalCasesRemoteDataSourceInterface
import dagger.Binds
import dagger.Module
/**
* Created by marcus on 13-04-2020.
*/
@Module
interface TotalCasesRemoteDataSourceModule {
@Binds
@ActivityScope
fun providesTotalCasesRemoteDataSource(
remoteDateSource: TotalCasesRemoteDataSource
): TotalCasesRemoteDataSourceInterface
}
| 0
|
Kotlin
|
0
| 0
|
1503d6626f1eb82ca649b8b155f6f343dd7351bb
| 1,237
|
Pandemic-reports
|
Apache License 2.0
|
graphecule-client/src/main/kotlin/graphecule/client/model/GraphModelBuilder.kt
|
josesamuel
| 259,990,102
| false
| null |
/*
* Copyright (C) 2020 <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 graphecule.client.model
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import graphecule.client.asSafeString
import graphecule.client.asStringOrNull
import graphecule.client.isNotNull
import graphecule.client.logMessage
import graphecule.common.HttpRequestAdapter
import graphecule.common.RequestSender
import kotlinx.coroutines.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
/**
* Builds the [GraphModel] of a given graphql
*
* @param apiHost The graphql api host url to parse
* @param httpRequestAdapter [HttpRequestAdapter] if any to handle authentication or interception.
*/
internal class GraphModelBuilder(private val apiHost: String, private val httpRequestAdapter: HttpRequestAdapter? = null) {
private val LOCK = Any()
private val modelMap: MutableMap<String, ClassInfo> = ConcurrentHashMap<String, ClassInfo>()
private val processedTypes = ConcurrentHashMap<String, ClassInfo>()
private val pendingTypesToProcess = ConcurrentHashMap.newKeySet<String>()
private val currentlyProcessingTypes = ConcurrentHashMap.newKeySet<String>()
private val requestSender by lazy { RequestSender(apiHost, httpRequestAdapter) }
/**
* Builds and returns the [GraphModel]
*/
suspend fun buildGraphModel(): GraphModel = withContext(Dispatchers.IO) {
val schemaQuery = "{__schema {queryType {name} mutationType {name} }}"
val response = requestSender.sendRequest("{\"query\" : \"$schemaQuery\"}")
var queryInfo: ClassInfo? = null
var mutationInfo: ClassInfo? = null
var errorMessage = response ?: "Failed to get reply from server"
if (response != null) {
val resultJson = JsonParser.parseString(response) as JsonObject
if (resultJson.has("errors")) {
errorMessage = resultJson.get("errors").asSafeString()
} else {
val dataJson = resultJson.getAsJsonObject("data")
if (dataJson != null) {
val schemaJsonObject = dataJson.getAsJsonObject("__schema")
if (schemaJsonObject != null) {
val queryTypeJsonObject = schemaJsonObject.getAsJsonObject("queryType")
if (queryTypeJsonObject != null) {
val queryTypeName = queryTypeJsonObject.get("name").asString
queryInfo = getClassInfo(queryTypeName)
addTypeToProcess(queryTypeName)
}
val mutationType = schemaJsonObject.get("mutationType")
if (mutationType.isNotNull()) {
val mutationTypeJsonObject = mutationType as JsonObject
val mutationTypeName = mutationTypeJsonObject.get("name").asString
mutationInfo = getClassInfo(mutationTypeName)
addTypeToProcess(mutationTypeName)
}
}
}
}
}
val maxThread = httpRequestAdapter?.maxParallelRequests ?: 8
val asyncExecutor = Executors.newFixedThreadPool(maxThread)
val asyncScope = asyncExecutor.asCoroutineDispatcher()
val deferredList: MutableList<Deferred<ClassInfo>> = mutableListOf()
do {
var deferredLimit = 0
while (pendingTypesToProcess.isNotEmpty() && deferredLimit <= maxThread) {
synchronized(LOCK) {
val typeToProcess = pendingTypesToProcess.first()
pendingTypesToProcess.remove(typeToProcess)
currentlyProcessingTypes.add(typeToProcess)
deferredList.add(async(context = asyncScope) { processType(typeToProcess) })
}
deferredLimit++
}
val results = deferredList.awaitAll()
currentlyProcessingTypes.clear()
results.forEach {
processedTypes[it.name] = it
}
deferredList.clear()
if (httpRequestAdapter?.rateLimit ?: 0 > 0) {
logMessage("Throttling for ${httpRequestAdapter?.rateLimit} ms")
delay(httpRequestAdapter?.rateLimit!!)
}
} while (pendingTypesToProcess.isNotEmpty())
asyncScope.close()
asyncExecutor.shutdownNow()
val classNameCount = mutableMapOf<String, Int>()
processedTypes.keys.forEach {
val nameLowerCase = it.toLowerCase()
var currentCount = classNameCount.getOrPut(nameLowerCase) {
0
}
currentCount++
classNameCount[nameLowerCase] = currentCount
}
logMessage("Processing Complete")
if (queryInfo != null) {
GraphModel(apiHost, queryInfo, mutationInfo, processedTypes, classNameCount)
} else {
throw RuntimeException("Failed to get query class. $errorMessage")
}
}
private fun sendRequest(queryString: String): String? =
runBlocking {
requestSender.sendRequest(queryString)
}
/**
* Process a given type to get all the information about it
*/
private fun processType(typeName: String): ClassInfo {
val classInfo: ClassInfo = getClassInfo(typeName)
if (!processedTypes.containsKey(typeName)) {
logMessage("Processing $typeName")
val queryBody = getTypeQuery(typeName)
val queryString = "{\"query\" : \"$queryBody\"}"
val result = sendRequest(queryString)
if (result != null) {
val resultJson = JsonParser.parseString(result) as? JsonObject ?: return classInfo.also {
println("Parse error, returning default for $typeName $result")
}
if (resultJson.has("errors")) {
println("Failed to get type $typeName : ${resultJson.get("errors")}")
} else {
val dataJson = resultJson.getAsJsonObject("data")
if (dataJson != null) {
val typeJsonObject = dataJson.getAsJsonObject("__type")
if (typeJsonObject != null) {
classInfo.typeKind = getClassTypeKind(typeJsonObject)
classInfo.description = typeJsonObject.get("description").asStringOrNull()
getTypeConnections(typeJsonObject, "interfaces")?.forEach {
classInfo.addParent(it)
}
classInfo.childClasses = getTypeConnections(typeJsonObject, "possibleTypes", classInfo.childClasses)
classInfo.childClasses?.forEach {
val childConnection = getClassInfo(it)
childConnection.addParent(typeName)
}
updateEnumValues(typeJsonObject, classInfo)
classInfo.fields = getFields(typeJsonObject, "fields")
classInfo.queryArgs = getFields(typeJsonObject, "inputFields")
}
} else {
println("Failed to process type $typeName : $result. \nSpecify custom httpRequestAdapter to throttle requests\n\n")
}
}
}
modelMap[typeName] = classInfo
}
return classInfo
}
/**
* Returns type information
*/
private fun getClassTypeKind(typeKindJson: JsonObject): TypeKind {
return when (val kind = typeKindJson.get("kind").asString) {
"OBJECT" -> TypeKind.OBJECT
"INTERFACE" -> TypeKind.INTERFACE
"UNION" -> TypeKind.UNION
"ENUM" -> TypeKind.ENUM
"INPUT_OBJECT" -> TypeKind.INPUT_OBJECT
else -> {
println("Unexpected type for class $kind")
TypeKind.OBJECT
}
}
}
/**
* Adds a type to be processed
*/
private fun addTypeToProcess(typeName: String) {
synchronized(LOCK) {
if (!processedTypes.containsKey(typeName)
&& !pendingTypesToProcess.contains(typeName)
&& !currentlyProcessingTypes.contains(typeName)
) {
pendingTypesToProcess.add(typeName)
}
}
}
/**
* Returns the field type
*/
private fun getFieldType(typeKindJson: JsonObject, isNullable: Boolean = true): FieldType {
return when (val kind = typeKindJson.get("kind").asString) {
"OBJECT", "INTERFACE", "UNION", "ENUM", "INPUT_OBJECT" -> {
val name = typeKindJson.get("name").asString
addTypeToProcess(name)
FieldType(name, TypeKind.valueOf(kind), isNullable)
}
"NON_NULL" -> return getFieldType(typeKindJson.getAsJsonObject("ofType"), false)
"LIST" -> {
val listType = FieldType("", TypeKind.LIST, isNullable)
listType.subType = getFieldType(typeKindJson.getAsJsonObject("ofType"))
listType
}
else -> {
val name = typeKindJson.get("name").asString.toUpperCase()
try {
FieldType(name, TypeKind.valueOf(name), isNullable)
} catch (exception: Exception) {
FieldType(name, TypeKind.STRING, isNullable)
}
}
}
}
/**
* Returns the connection of this given type, either parent or child relations
*/
private fun getTypeConnections(typeKindJson: JsonObject, collectionName: String, currentConnections: MutableSet<String>? = null): MutableSet<String>? {
var connections: MutableSet<String>? = currentConnections
val connectionJson = typeKindJson.get(collectionName)
if (connectionJson.isNotNull()) {
if (connections == null) {
connections = mutableSetOf()
}
val possibleTypes = connectionJson as JsonArray
possibleTypes.forEach {
(it as JsonObject).get("name")?.asStringOrNull()?.let { connectionName:String ->
addTypeToProcess(connectionName)
connections.add(connectionName)
}
}
}
return connections
}
/**
* Update the enum values
*/
private fun updateEnumValues(typeKindJson: JsonObject, classInfo: ClassInfo) {
val enumJson = typeKindJson.get("enumValues")
if (enumJson.isNotNull()) {
val possibleTypes = enumJson as JsonArray
if (classInfo.enumValues == null) {
classInfo.enumValues = mutableSetOf()
}
possibleTypes.forEach {
val enumJsonObject = it as JsonObject
classInfo.enumValues!!.add(
EnumValue(
enumJsonObject.get("name").asString, enumJsonObject.get("description").asStringOrNull()
)
)
}
}
}
/**
* Returns the fields if any
*/
private fun getFields(typeKindJson: JsonObject, jsonName: String): MutableSet<FieldInfo>? {
var fields: MutableSet<FieldInfo>? = null
val fieldsJson = typeKindJson.get(jsonName)
if (fieldsJson.isNotNull()) {
val possibleTypes = fieldsJson as JsonArray
fields = mutableSetOf()
possibleTypes.forEach {
val fieldJson = it as JsonObject
val fieldName = fieldJson.get("name").asString
val fieldDescription = fieldJson.get("description").asStringOrNull()
val fieldDefault = fieldJson.get("defaultValue").asStringOrNull()
val fieldType = getFieldType(fieldJson.getAsJsonObject("type"))
val fieldInfo = FieldInfo(fieldName, fieldDescription, fieldType, fieldDefault)
if (fieldJson.has("args")) {
fieldInfo.fieldArgs = getFields(fieldJson, "args")
}
fields.add(fieldInfo)
}
}
return fields
}
/**
* Return the discovered [ClassInfo] of the given name, adding it if needed.
*/
@Synchronized
private fun getClassInfo(className: String): ClassInfo = modelMap.getOrPut(className) {
ClassInfo(className)
}
/**
* Returns the query for the given type name
*/
private fun getTypeQuery(typeName: String) = """
{
__type(name:"$typeName"){
name
kind
description
interfaces {
name
}
inputFields {
name
description
defaultValue
type {
...typeInfo
}
}
fields {
name
description
args {
name
defaultValue
description
type {
...typeInfo
}
}
type {
...typeInfo
}
}
possibleTypes {
name
}
enumValues {
name
description
}
ofType {
name
}
}
}
fragment typeInfo on __Type {
name
kind
ofType {
name
kind
ofType {
name
kind
ofType {
name
kind
}
}
}
}
""".trimIndent().replace("\"", "\\\"").replace("\n", "\\n")
}
| 1
|
Kotlin
|
1
| 2
|
82bd348f06a84eccf946541a1683f32f509cfe5a
| 14,788
|
graphecule
|
Apache License 2.0
|
src/main/kotlin/bot/extensions/StatsReport.kt
|
zxcqirara
| 499,319,820
| false
|
{"Kotlin": 101588}
|
package bot.extensions
import bot.botLogger
import bot.lib.Config
import bot.lib.Database
import com.kotlindiscord.kord.extensions.extensions.Extension
import com.kotlindiscord.kord.extensions.i18n.TranslationsProvider
import com.kotlindiscord.kord.extensions.utils.scheduling.Scheduler
import dev.kord.common.entity.Snowflake
import dev.kord.core.behavior.channel.createMessage
import dev.kord.core.entity.channel.GuildMessageChannel
import kotlinx.coroutines.delay
import kotlinx.datetime.*
import org.koin.core.component.inject
import kotlin.time.Duration.Companion.days
import kotlin.time.ExperimentalTime
@ExperimentalTime
class StatsReport : Extension() {
override val name = "stats-report"
override val bundle = "cs_dsbot"
private val translationsProvider: TranslationsProvider by inject()
override suspend fun setup() {
val timeZone = TimeZone.of(Config.discord.timeZone)
botLogger.info(translationsProvider.translate(
"extensions.experience.stats.timeZone", bundle, arrayOf(timeZone.id)
))
val initMoment = Clock.System.now()
val currentTime = initMoment.toLocalDateTime(timeZone)
val initPublishTime = LocalDateTime(
currentTime.year, currentTime.month + 1, 1,
0, 0
).toInstant(timeZone)
val initialDelay = initPublishTime - initMoment
// Log start time
botLogger.info(translationsProvider.translate(
"extensions.experience.stats.reportLog", bundle, arrayOf(initPublishTime)
))
// Log initial delay
botLogger.info(translationsProvider.translate(
"extensions.experience.stats.logDelay", bundle, arrayOf(initialDelay)
))
Scheduler().schedule(initialDelay, repeat = true) {
// Save start time
val startTime = Clock.System.now()
// Get channel from config
val channel = kord.getChannelOf<GuildMessageChannel>(Snowflake(Config.discord.statsReportChannelId))
if (channel == null) { // Unload if can't resolve channel
botLogger.error("Failed to get channel! Unloading...")
doUnload()
return@schedule
}
// Get users from DB
val users = Database.getTopUsers(10)
// Send top
channel.createMessage {
embeds?.plusAssign(
Experience.topEmbed(
kord, translationsProvider, this@StatsReport.bundle, users, channel.guild, true
)
)
}
// Clear DB
Database.cleanUp()
// Zeroing joined users list
Experience.joinedMembers.clear()
channel.guild.voiceStates.collect {
Experience.joinedMembers[it.getMember()] = startTime
}
// Wait 1 month
delay(1.days * 365.2425 / 12)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
599cee06e9a200e1ba8dbebd64be3039e5f937fb
| 2,529
|
Kyrtizanka-Bot
|
MIT License
|
android-hce-app/app/src/main/java/com/lexycon/hostcardemulation/HostCardEmulatorService.kt
|
Lexycon
| 254,213,031
| false
| null |
package com.lexycon.hostcardemulation
import android.nfc.cardemulation.HostApduService
import android.os.Bundle
import android.util.Log
class HostCardEmulatorService: HostApduService() {
companion object {
val TAG = "Host Card Emulator"
val STATUS_SUCCESS = "9000"
val STATUS_FAILED = "6F00"
val CLA_NOT_SUPPORTED = "6E00"
val INS_NOT_SUPPORTED = "6D00"
val AID = "A0000001020304"
val SELECT_INS = "A4"
val DEFAULT_CLA = "00"
val MIN_APDU_LENGTH = 12
}
override fun onDeactivated(reason: Int) {
}
override fun processCommandApdu(commandApdu: ByteArray?,
extras: Bundle?): ByteArray {
Log.d(TAG, "APDU process command")
if (commandApdu == null) {
return ByteArrayHexUtil.hexStringToByteArray(STATUS_FAILED)
}
val hexCommandApdu = ByteArrayHexUtil.toHex(commandApdu)
if (hexCommandApdu.length < MIN_APDU_LENGTH) {
return ByteArrayHexUtil.hexStringToByteArray(STATUS_FAILED)
}
if (hexCommandApdu.substring(0, 2) != DEFAULT_CLA) {
return ByteArrayHexUtil.hexStringToByteArray(CLA_NOT_SUPPORTED)
}
if (hexCommandApdu.substring(2, 4) != SELECT_INS) {
return ByteArrayHexUtil.hexStringToByteArray(INS_NOT_SUPPORTED)
}
if (hexCommandApdu.substring(10, 24) == AID) {
// we wont return success 90 00, we respond with our uid
// return ByteArrayHexUtil.hexStringToByteArray(STATUS_SUCCESS)
val dataStore = DataStoreUtil(this);
val uid = dataStore.getID();
return ByteArrayHexUtil.hexStringToByteArray(uid)
} else {
return ByteArrayHexUtil.hexStringToByteArray(STATUS_FAILED)
}
}
}
| 0
|
Kotlin
|
5
| 8
|
06b84a3c8c7dfcedc0fbf929d0d587e92c399d3b
| 1,840
|
android-pn532-hce
|
MIT License
|
src/test/kotlin/org/rust/ide/template/postfix/OkPostfixTemplateTest.kt
|
intellij-rust
| 42,619,487
| false
|
{"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.template.postfix
class OkPostfixTemplateTest : RsPostfixTemplateTest(OkPostfixTemplate(RsPostfixTemplateProvider())) {
fun `test expr`() = doTest("""
fn foo(number: i32) -> Result<i32, ()> {
number.ok/*caret*/
}
""", """
fn foo(number: i32) -> Result<i32, ()> {
Ok(number)
}
""")
fun `test not expr`() = doTestNotApplicable("""
fn main() {
println!("Hello!");.ok/*caret*/
}
""")
}
| 1,841
|
Kotlin
|
380
| 4,528
|
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
| 617
|
intellij-rust
|
MIT License
|
src/main/kotlin/com/rarnu/mdpro3/database/entity/CardData.kt
|
rarnu
| 809,611,315
| false
|
{"Kotlin": 125118}
|
package com.rarnu.mdpro3.database.entity
import org.ktorm.entity.Entity
interface CardData : Entity<CardData> {
companion object : Entity.Factory<CardData>()
var id: Long
var ot: Int
var alias: Long
var setcode: Long
var type: Long
var atk: Int
var def: Int
var level: Int
var race: Long
var attribute: Long
var category: Long
var genre: Long
var script: ByteArray
var support: Long
var ocgdate: Long
var tcgdate: Long
}
| 0
|
Kotlin
|
0
| 1
|
2965b8d9c178f101640d54c6777cfefb8257df5c
| 492
|
mdpro3-deck-center
|
Apache License 2.0
|
liveview-android/src/test/java/com/dockyard/liveviewtest/liveview/util/LiveViewComposableTest.kt
|
liveview-native
| 459,214,950
| false
|
{"Kotlin": 2067475, "Elixir": 74863, "ANTLR": 12846}
|
package com.dockyard.liveviewtest.liveview.util
import androidx.activity.ComponentActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onRoot
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.takahirom.roborazzi.ExperimentalRoborazziApi
import com.github.takahirom.roborazzi.RobolectricDeviceQualifiers
import com.github.takahirom.roborazzi.captureRoboImage
import com.github.takahirom.roborazzi.captureScreenRoboImage
import org.junit.Rule
import org.junit.runner.RunWith
import org.phoenixframework.liveview.BuildConfig.IS_RECORDING_SHOT_TEST
import org.phoenixframework.liveview.domain.LiveViewCoordinator
import org.phoenixframework.liveview.ui.phx_components.PhxLiveView
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
// Tips: You can use Robolectric while using AndroidJUnit4
@RunWith(AndroidJUnit4::class)
// Enable Robolectric Native Graphics (RNG)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(qualifiers = RobolectricDeviceQualifiers.Pixel5)
@OptIn(ExperimentalRoborazziApi::class)
abstract class LiveViewComposableTest {
@get:Rule
val composeRule = createAndroidComposeRule<ComponentActivity>()
private val isRecording = IS_RECORDING_SHOT_TEST
fun compareNativeComposableWithTemplate(
nativeComposable: @Composable () -> Unit,
template: String,
testTag: String? = null,
captureScreenImage: Boolean = false,
delayBeforeScreenshot: Long = 0,
coordinator: LiveViewCoordinator = LiveViewCoordinator(
httpBaseUrl = "",
wsBaseUrl = "",
route = null
),
onBeforeScreenShot: ((ComposeContentTestRule) -> Unit)? = null
) {
composeRule.setContent {
val state by coordinator.composableTree.collectAsState()
if (isRecording) {
nativeComposable()
} else {
val json = "{\"s\": [\"${template.templateToTest()}\"]}"
coordinator.parseTemplate(json)
if (state.children.isNotEmpty()) {
PhxLiveView(
composableNode = state.children.first(),
pushEvent = coordinator::pushEvent
)
}
}
}
// Do some action on the UI before capture the screenshot
onBeforeScreenShot?.invoke(composeRule)
if (delayBeforeScreenshot > 0) {
Thread.sleep(delayBeforeScreenshot)
}
when {
captureScreenImage ->
captureScreenRoboImage()
testTag != null ->
composeRule.onNodeWithTag(testTag, useUnmergedTree = true).captureRoboImage()
else ->
composeRule.onRoot().captureRoboImage()
}
}
private fun String.templateToTest() =
this.trimIndent().trimMargin().trimEnd().replace("\"", "\\\"").lines().joinToString("")
protected fun String.toJsonForTemplate() =
this.trimIndent().trim().replace("\n", "")
}
| 44
|
Kotlin
|
3
| 75
|
ef08559f9bda7e74fdaf80859b47e2db9502303c
| 3,351
|
liveview-client-jetpack
|
MIT License
|
kross2d-core/src/commonMain/kotlin/bitspittle/kross2d/engine/context/DrawContext.kt
|
bitspittle
| 171,082,426
| false
| null |
package bitspittle.kross2d.engine.context
import bitspittle.kross2d.engine.GameState
import bitspittle.kross2d.engine.graphics.DrawSurface
import bitspittle.kross2d.engine.graphics.Screen
import bitspittle.kross2d.engine.time.Timer
/**
* Classes that may be useful to [GameState.update]
*/
interface DrawContext {
val screen: Screen
val timer: Timer
}
| 2
|
Kotlin
|
1
| 2
|
bc40c0b71ee6826be06044c5f3f1239e30252872
| 363
|
kross2d
|
MIT License
|
app/src/main/java/cn/lyric/getter/hook/app/SystemUi.kt
|
xiaowine
| 650,612,086
| false
| null |
package cn.lyric.getter.hook.app
import android.media.MediaMetadata
import android.media.session.PlaybackState
import android.os.Build
import cn.lyric.getter.BuildConfig
import cn.lyric.getter.R
import cn.lyric.getter.api.data.LyricData
import cn.lyric.getter.api.listener.LyricListener
import cn.lyric.getter.api.listener.LyricReceiver
import cn.lyric.getter.api.tools.Tools
import cn.lyric.getter.hook.BaseHook
import cn.lyric.getter.tool.HookTools.eventTools
import cn.lyric.getter.tool.HookTools.getApplication
import cn.xiaowine.xkt.LogTool.log
import cn.xiaowine.xkt.Tool.isNotNull
import cn.xiaowine.xkt.Tool.observableChange
import com.github.kyuubiran.ezxhelper.ClassUtils.loadClassOrNull
import com.github.kyuubiran.ezxhelper.EzXHelper.moduleRes
import com.github.kyuubiran.ezxhelper.HookFactory.`-Static`.createHook
import com.github.kyuubiran.ezxhelper.finders.MethodFinder.`-Static`.methodFinder
object SystemUi : BaseHook() {
private lateinit var receiver: LyricReceiver
private var title: String by observableChange("") { _, _, newValue ->
if (newValue.isNotEmpty()) {
eventTools.cleanLyric()
}
}
private var useOwnMusicController: Boolean = false
private fun Class<*>.hasMethod(methodName: String): Boolean {
val methods = declaredMethods
for (method in methods) {
if (method.name == methodName) {
return true
}
}
return false
}
override fun init() {
super.init()
if (Build.VERSION.SDK_INT <= 33) {
// Android13及其以下适用这个方法
loadClassOrNull("com.android.systemui.statusbar.NotificationMediaManager").isNotNull {
it.methodFinder().filterByName("clearCurrentMediaNotification").first().createHook {
after {
if (!useOwnMusicController) {
eventTools.cleanLyric()
}
}
}
}
} else {
// Android14 clearCurrentMediaNotification消失了,使用removePlayer代替
loadClassOrNull("com.android.systemui.media.controls.ui.MediaCarouselController").isNotNull {
it.methodFinder().filterByName("removePlayer\$default").first().createHook {
after {
if (!useOwnMusicController) {
eventTools.cleanLyric()
}
}
}
}
}
for (i in 0..10) {
val clazz = loadClassOrNull("com.android.systemui.statusbar.NotificationMediaManager$$i")
if (clazz.isNotNull()) {
if (clazz!!.hasMethod("onPlaybackStateChanged")) {
clazz.methodFinder().filterByName("onPlaybackStateChanged").first().createHook {
after { hookParam ->
if (!useOwnMusicController) {
val playbackState = hookParam.args[0] as PlaybackState
if (playbackState.state == 2) {
eventTools.cleanLyric()
}
}
}
}
break
}
}
}
if (config.enhancedHiddenLyrics) {
moduleRes.getString(R.string.enhanced_hidden_lyrics).log()
for (i in 0..10) {
val clazz = loadClassOrNull("com.android.systemui.statusbar.NotificationMediaManager$$i")
clazz.log()
if (clazz.isNotNull()) {
if (clazz!!.hasMethod("onMetadataChanged")) {
clazz.methodFinder().filterByName("onMetadataChanged").first().createHook {
after { hookParam ->
val metadata = hookParam.args[0] as MediaMetadata
title = metadata.getString(MediaMetadata.METADATA_KEY_TITLE)
}
}
break
}
}
}
}
getApplication { application ->
receiver = LyricReceiver(object : LyricListener() {
override fun onUpdate(lyricData: LyricData) {
useOwnMusicController = lyricData.extraData.useOwnMusicController
}
})
Tools.registerLyricListener(application, BuildConfig.API_VERSION, receiver)
}
}
}
| 7
| null |
8
| 433
|
63e6881376a7b19af997536c33cfc0cf15c85db7
| 4,608
|
Lyric-Getter
|
Apache License 2.0
|
compiler/testData/ir/irText/js/dynamic/dynamicMemberAugmentedAssignment.kt
|
mcpiroman
| 375,462,779
| true
|
{"Kotlin": 73023707, "Java": 6608057, "Swift": 4256908, "C": 2635707, "C++": 2546276, "Objective-C": 636652, "JavaScript": 211357, "Objective-C++": 165224, "Groovy": 103363, "Python": 44364, "Shell": 31842, "TypeScript": 22854, "Lex": 18369, "Batchfile": 11692, "CSS": 11368, "HTML": 6971, "Ruby": 6839, "EJS": 5241, "Dockerfile": 4685, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "LLVM": 395, "Scala": 80}
|
// TARGET_BACKEND: JS_IR
// MUTE_SIGNATURE_COMPARISON_K2: ANY
// ^ KT-57566
fun testAugmentedMemberAssignment(d: dynamic) {
d.m += "+="
d.m -= "-="
d.m *= "*="
d.m /= "/="
d.m %= "%="
}
// see KT-29768
fun testSafeAugmentedMemberAssignment(d: dynamic) {
d?.m += "+="
d?.m -= "-="
d?.m *= "*="
d?.m /= "/="
d?.m %= "%="
}
| 0
|
Kotlin
|
0
| 1
|
973adb6a38df87d16ee089eee7faafa1983fd76a
| 364
|
kotlin
|
Apache License 2.0
|
simulator/src/main/kotlin/util/svg/elementdsl/path.kt
|
jGleitz
| 239,469,794
| false
| null |
package de.joshuagleitze.transformationnetwork.simulator.util.svg.elementdsl
import kotlinx.html.HTMLTag
import kotlinx.html.TagConsumer
import kotlinx.html.attributesMapOf
import react.RBuilder
import react.dom.tag
import styled.StyledDOMBuilder
import styled.styledTag
fun RBuilder.styledPath(
id: String? = null,
d: String,
filter: String? = null,
block: StyledDOMBuilder<PATH>.() -> Unit
) =
styledTag(block) {
PATH(attributesMapOf("id", id, "d", d, "filter", filter), it)
}
fun RBuilder.path(id: String? = null, d: String, filter: String? = null) =
tag({}) { PATH(attributesMapOf("id", id, "d", d, "filter", filter), it) }
class PATH(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) :
HTMLTag("path", consumer, initialAttributes, null, false, true)
| 3
|
Kotlin
|
0
| 1
|
d5d0bd7722abe3260bc204f128337c25c0fb340e
| 829
|
transformationnetwork-simulator
|
MIT License
|
android/app/src/main/java/com/algorand/android/repository/FeedbackRepository.kt
|
perawallet
| 364,359,642
| false
| null |
/*
* Copyright 2022 <NAME>, 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.repository
import com.algorand.android.models.Feedback
import com.algorand.android.models.FeedbackCategory
import com.algorand.android.models.Result
import com.algorand.android.network.MobileAlgorandApi
import com.algorand.android.network.requestWithHipoErrorHandler
import com.algorand.android.network.safeApiCall
import com.algorand.android.exceptions.RetrofitErrorHandler
import javax.inject.Inject
class FeedbackRepository @Inject constructor(
private val mobileAlgorandApi: MobileAlgorandApi,
private val hipoApiErrorHandler: RetrofitErrorHandler
) {
suspend fun postFeedback(feedback: Feedback): Result<Unit> =
safeApiCall { requestPostFeedback(feedback) }
private suspend fun requestPostFeedback(feedback: Feedback) = requestWithHipoErrorHandler(hipoApiErrorHandler) {
mobileAlgorandApi.postFeedback(feedback)
}
suspend fun getFeedbackCategories(): Result<List<FeedbackCategory>> =
safeApiCall { requestGetFeedbackCategories() }
private suspend fun requestGetFeedbackCategories() = requestWithHipoErrorHandler(hipoApiErrorHandler) {
mobileAlgorandApi.getFeedbackCategories()
}
}
| 22
| null |
62
| 181
|
92fc77f73fa4105de82d5e87b03c1e67600a57c0
| 1,764
|
pera-wallet
|
Apache License 2.0
|
src/main/kotlin/eu/glatz/tomeyreader/Settings.kt
|
glatzan
| 251,613,613
| false
| null |
package eu.glatz.tomeyreader
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.system.ApplicationHome
import picocli.CommandLine
import java.io.File
@CommandLine.Command(name = "settings", mixinStandardHelpOptions = true, showAtFileInUsageHelp = true)
class Settings {
private val logger: Logger = LoggerFactory.getLogger(this.javaClass)
@CommandLine.Option(names = ["-sourceFolder", "-s"], description = ["Path containing .exam files"])
var dataFolder: String = ""
@CommandLine.Option(names = ["-fileExtension"], description = ["Extension of .exam files; Default: .exam"])
var fileExtensions: String = ".exam"
@CommandLine.Option(names = ["-targetFolder", "-t"], description = ["Target folder for extracted images"])
var targetFolder: String = "export"
@CommandLine.Option(names = ["-d"], description = ["Set to true if a new subdirectory within the target folder should be created for every exam file; Default: true"])
var createNewDirForFile: Boolean = true
@CommandLine.Option(names = ["-x"], description = ["Width of extracted images within the exam file; Default: Autodetect"])
var xResolution = -1
@CommandLine.Option(names = ["-y"], description = ["Height of extracted images within the exam file; Default: Autodetect"])
var yResolution = -1
@CommandLine.Option(names = ["-imageCount"], description = ["Total number of images within the exam file; Default: Autodetect"])
var imageCount = -1
@CommandLine.Option(names = ["-z"], description = ["Pixel depth of an image; Default: Autodetect"])
var bytesPerPixel = -1
@CommandLine.Option(names = ["-offset"], description = ["Starting position of the first image within the exam file; Default: Autodetect"])
var startOffset = -1
@CommandLine.Option(names = ["-macro"], description = ["Imagej macro for postprocessing of extracted images"])
var postProcessMacro: String = ""
@CommandLine.Option(names = ["-postPlugins"], description = ["Plugins for imagej postprocessing"])
var postProcessPluginDir: String = ""
@CommandLine.Option(names = ["-postDir"], description = ["Target folder for post processed images"])
var postProcessTargetDir: String = ""
@CommandLine.Option(names = ["-postCreatDir"], description = ["Set to true if a new subdirectory within the post processing folder should be created for every exam file; Default: true"])
var createNewPostDirForFile: Boolean = true
@CommandLine.Option(names = ["-mode"], description = ["Mode: 3 = extract VAA-Images, Eye-Images, Patient-Infos, 2 = extract VAA-Images, 1 = extract Eye-Images, 0 = extract Patient-Infos; Default: 3"])
var mode: Int = 3
val freeMemory: Long
get() = Runtime.getRuntime().freeMemory()
val maxMemory: Long
get() = Runtime.getRuntime().maxMemory()
val runDirectory: String
get() {
val home = ApplicationHome(Settings::class.java)
return home.dir.absolutePath
}
val getAbsoluteDataFolder: File
get() = getAbsoluteFile(dataFolder)
val getAbsoluteTargetFolder: File
get() = getAbsoluteFile(targetFolder)
val getAbsolutePostProcessMacro: File
get() = getAbsoluteFile(postProcessMacro)
val getAbsolutePostProcessDir: File
get() = getAbsoluteFile(postProcessTargetDir)
private fun getAbsoluteFile(dir: String): File {
return if (!File(dir).isAbsolute)
File(runDirectory, dir)
else
File(dir)
}
fun validate(): Boolean {
logger.info("Source folder: ${getAbsoluteDataFolder.path}")
logger.info("Target folder: ${getAbsoluteTargetFolder.path}")
logger.info("File extension: ${fileExtensions}")
if (!getAbsoluteDataFolder.isDirectory) {
logger.error("Source folder not valid! ${dataFolder}")
return false
}
if (fileExtensions.isEmpty() || !fileExtensions.matches(Regex("\\..*"))) {
logger.error("File-Extension not valid, must match .xxxx is ${fileExtensions}")
return false
}
if (!getAbsoluteTargetFolder.isDirectory)
if (!getAbsoluteTargetFolder.mkdirs()) {
logger.error("Target folder not valid! ${targetFolder}")
return false
}
if (postProcessMacro.isNotEmpty() && !File(postProcessMacro).isFile) {
logger.error("Makro not found: $postProcessMacro")
return false
}
if (postProcessMacro.isNotEmpty() && postProcessPluginDir.isNotEmpty() && !File(postProcessPluginDir).isDirectory) {
logger.error("ImageJ Plugin dir ist not valid: $postProcessPluginDir")
return false
}
return true
}
companion object {
fun toMByte(bytes: Long): Long {
return bytes / (1024 * 1024)
}
}
}
| 1
|
Kotlin
|
0
| 1
|
5605edee32305003b2bbe4f59eb6c934c42137b9
| 4,945
|
TomeyReader2
|
MIT License
|
web/src/test/kotlin/com/github/jactor/web/model/UserModelTest.kt
|
jactor-rises
| 178,705,353
| false
|
{"Kotlin": 58604, "HTML": 10548, "CSS": 2049}
|
package com.github.jactor.web.model
import com.github.jactor.shared.dto.AddressDto
import com.github.jactor.shared.dto.PersonDto
import com.github.jactor.shared.dto.UserDto
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
internal class UserModelTest {
@Test
fun `should fetch the address of the user as a list of strings`() {
val testUserModel = UserModel(
UserDto(
person = PersonDto(
address = AddressDto(
addressLine1 = "address line 1",
addressLine2 = "address line 2",
addressLine3 = "address line 3",
zipCode = "1234",
city = "somewhere"
)
)
)
)
val address = testUserModel.fetchAddress()
assertThat(address).containsExactly(
"address line 1",
"address line 2",
"address line 3",
"1234",
"somewhere"
)
}
@Test
fun `should not fetch parts of address being null`() {
val testUserModel = UserModel(UserDto(person = PersonDto(address = AddressDto(addressLine1 = "address line 1", zipCode = "1234"))))
val address = testUserModel.fetchAddress()
assertThat(address).containsExactly(
"address line 1",
"1234"
)
}
@Test
fun `should fetch the username of the user`() {
val testUserModel = UserModel(UserDto(username = "user"))
assertThat(testUserModel.fetchUsername()).isEqualTo("user")
}
@Test
fun `should fetch the person behind the user`() {
val testUserModel = UserModel(UserDto(person = PersonDto(firstName = "John", surname = "Smith", description = "description")))
assertAll(
{ assertThat(testUserModel.fetchFullName()).isEqualTo("<NAME>") },
{ assertThat(testUserModel.fetchDescriptionCode()).isEqualTo("description") }
)
}
}
| 0
|
Kotlin
|
0
| 0
|
544edcb274744bd91ecf2d4e939d18f50e3f4d79
| 2,098
|
jactor-web
|
MIT License
|
desktop/views/src/testFixtures/kotlin/scene/sceneSetting/doubles/RemoveLocationFromSceneControllerDouble.kt
|
Soyle-Productions
| 239,407,827
| false
| null |
package com.soyle.stories.desktop.view.scene.sceneSetting.doubles
import com.soyle.stories.domain.location.Location
import com.soyle.stories.domain.scene.Scene
import com.soyle.stories.scene.locationsInScene.removeLocationFromScene.RemoveLocationFromSceneController
import kotlinx.coroutines.Job
class RemoveLocationFromSceneControllerDouble(
private val onRemoveLocation: (Scene.Id, Location.Id) -> Unit = { _, _ -> },
private val job: Job = Job()
) : RemoveLocationFromSceneController {
override fun removeLocation(sceneId: Scene.Id, locationId: Location.Id): Job {
onRemoveLocation(sceneId, locationId)
return job
}
}
| 45
|
Kotlin
|
0
| 9
|
1a110536865250dcd8d29270d003315062f2b032
| 655
|
soyle-stories
|
Apache License 2.0
|
src/jvmMain/kotlin/com/ditchoom/websocket/WebsocketKeyGenerator.kt
|
DitchOoM
| 600,892,985
| false
|
{"Kotlin": 98736, "Ruby": 2416, "JavaScript": 483}
|
package com.ditchoom.websocket
import java.util.Base64
import kotlin.random.Random
import kotlin.random.nextInt
actual fun generateWebSocketKey(): String =
Base64.getEncoder().encodeToString(ByteArray(16) { Random.nextInt(97..122).toByte() })
| 1
|
Kotlin
|
0
| 3
|
921307e59eeabac9869432aa10094894d966a22c
| 249
|
websocket
|
Apache License 2.0
|
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/frontend/fir/handlers/FirIdenticalChecker.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.test.frontend.fir.handlers
import org.jetbrains.kotlin.test.WrappedException
import org.jetbrains.kotlin.test.model.AfterAnalysisChecker
import org.jetbrains.kotlin.test.services.TestServices
import org.jetbrains.kotlin.test.services.moduleStructure
import org.jetbrains.kotlin.test.utils.FirIdenticalCheckerHelper
import org.jetbrains.kotlin.test.utils.firTestDataFile
import org.jetbrains.kotlin.test.utils.isFirTestData
import org.jetbrains.kotlin.test.utils.originalTestDataFile
import java.io.File
class FirIdenticalChecker(testServices: TestServices) : AfterAnalysisChecker(testServices) {
private val helper = object : FirIdenticalCheckerHelper(testServices) {
override fun getClassicFileToCompare(testDataFile: File): File {
return if (testDataFile.isFirTestData) testDataFile.originalTestDataFile else testDataFile
}
override fun getFirFileToCompare(testDataFile: File): File {
return if (testDataFile.isFirTestData) testDataFile else testDataFile.firTestDataFile
}
}
override fun check(failedAssertions: List<WrappedException>) {
if (failedAssertions.isNotEmpty()) return
val testDataFile = testServices.moduleStructure.originalTestDataFiles.first()
if (testDataFile.isFirTestData) {
val firFile = helper.getFirFileToCompare(testDataFile)
val classicFile = helper.getClassicFileToCompare(testDataFile)
if (helper.contentsAreEquals(classicFile, firFile, trimLines = true)) {
helper.deleteFirFile(testDataFile)
helper.addDirectiveToClassicFileAndAssert(classicFile)
}
} else {
removeFirFileIfExist(testDataFile)
}
}
private fun removeFirFileIfExist(testDataFile: File) {
val firFile = helper.getFirFileToCompare(testDataFile)
firFile.delete()
}
}
| 157
|
Kotlin
|
5209
| 42,102
|
65f712ab2d54e34c5b02ffa3ca8c659740277133
| 2,127
|
kotlin
|
Apache License 2.0
|
plugins/jvm-abi-gen/testData/compile/privateClassesFromJavaLib/lib/lib.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
package lib
private class A {
fun result() = "OK"
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 57
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/comunidadedevspace/taskbeats/core/data/repository/TaskRepositoryImpl.kt
|
RenanPdeOliveira
| 615,246,251
| false
|
{"Kotlin": 83912}
|
package com.comunidadedevspace.taskbeats.core.data.repository
import androidx.lifecycle.LiveData
import com.comunidadedevspace.taskbeats.news.data.local.NewsDao
import com.comunidadedevspace.taskbeats.news.data.local.NewsItem
import com.comunidadedevspace.taskbeats.tasks.data.TaskDao
import com.comunidadedevspace.taskbeats.tasks.data.TaskItem
import com.comunidadedevspace.taskbeats.news.data.mappers.toNewsItem
import com.comunidadedevspace.taskbeats.news.data.remote.NewsService
import com.comunidadedevspace.taskbeats.core.domain.repository.TaskRepository
import com.comunidadedevspace.taskbeats.core.domain.util.Resource
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.Flow
class TaskRepositoryImpl(
private val taskDao: TaskDao,
private val newsDao: NewsDao,
private val api: NewsService
) : TaskRepository {
override suspend fun insert(task: TaskItem) {
taskDao.insert(task)
}
override suspend fun delete(task: TaskItem) {
taskDao.delete(task)
}
override suspend fun update(task: TaskItem) {
taskDao.update(task)
}
override suspend fun deleteAll() {
taskDao.deleteAll()
}
override fun getAll(): LiveData<List<TaskItem>> {
return taskDao.getAll()
}
override suspend fun fetchTopNews(): Resource<List<NewsItem>> {
return try {
Resource.Success(data = api.fetchTopNews().data.toNewsItem())
} catch (e: Exception) {
if (e is CancellationException) throw e
e.printStackTrace()
Resource.Error(message = e.message ?: "Top news failed request")
}
}
override suspend fun fetchAllNews(): Resource<List<NewsItem>> {
return try {
Resource.Success(data = api.fetchAllNews().data.toNewsItem())
} catch (e: Exception) {
if (e is CancellationException) throw e
e.printStackTrace()
Resource.Error(message = e.message ?: "All news failed request")
}
}
override suspend fun insertNews(news: NewsItem) {
newsDao.insertNews(news)
}
override suspend fun deleteNewsById(id: String) {
newsDao.deleteNewsById(id)
}
override fun getAllNews(): Flow<List<NewsItem>> {
return newsDao.getAllNews()
}
}
| 0
|
Kotlin
|
0
| 0
|
ea0e5957af3ccd54e7312e06af0bfb98a9461dd0
| 2,320
|
TaskBeats
|
The Unlicense
|
chat-demo-android/src/main/kotlin/com/twilio/chat/demo/activities/LoginActivity.kt
|
twilio
| 47,708,643
| false
| null |
package com.twilio.chat.demo.activities
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.twilio.chat.ChatClient
import com.twilio.chat.demo.BasicChatClient.LoginListener
import com.twilio.chat.demo.R
import com.twilio.chat.demo.BuildConfig
import android.net.Uri
import android.app.Activity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ProgressBar
import android.widget.Toast
import android.preference.PreferenceManager
import android.view.View
import android.widget.ArrayAdapter
import com.twilio.chat.demo.TwilioApplication
import com.twilio.chat.demo.services.RegistrationIntentService
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.*
class LoginActivity : Activity(), LoginListener, AnkoLogger {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
login.setOnClickListener {
val userName = clientNameTextBox.text.toString()
val certPinningChosen = certPinning.isChecked
val realm = realmSelect.selectedItem as String
val ttl = tokenTtlTextBox.text.toString()
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
sharedPreferences.edit()
.putString("userName", userName)
.putBoolean("pinCerts", certPinningChosen)
.putString("realm", realm)
.putString("ttl", ttl)
.apply()
val url = Uri.parse(BuildConfig.ACCESS_TOKEN_SERVICE_URL)
.buildUpon()
.appendQueryParameter("identity", userName)
.appendQueryParameter("realm", realm)
.appendQueryParameter("ttl", ttl)
.build()
.toString()
debug { "url string : $url" }
TwilioApplication.instance.basicClient.login(userName, certPinningChosen, realm, url, this@LoginActivity)
}
if (checkPlayServices()) {
fcmAvailable.isChecked = true
// Start IntentService to register this application with GCM.
startService<RegistrationIntentService>()
}
}
override fun onResume() {
super.onResume()
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
val userName = sharedPreferences.getString("userName", DEFAULT_CLIENT_NAME)
val certPin = sharedPreferences.getBoolean("pinCerts", true)
val realm = sharedPreferences.getString("realm", DEFAULT_REALM)
val ttl = sharedPreferences.getString("ttl", DEFAULT_TTL)
clientNameTextBox.setText(userName)
certPinning.isChecked = certPin
realmSelect.setSelection((realmSelect.adapter as ArrayAdapter<String>).getPosition(realm))
tokenTtlTextBox.setText(ttl)
// Make sure no chatclient is created
if (TwilioApplication.instance.basicClient.chatClient != null) {
TwilioApplication.instance.basicClient.shutdown()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.login, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_about) {
showAboutDialog()
}
return super.onOptionsItemSelected(item)
}
private fun showAboutDialog() {
alert("Version: ${ChatClient.getSdkVersion()}", "About") {
positiveButton("OK") { dialog -> dialog.cancel() }
}.show()
}
fun setLoginProgressVisible(enable: Boolean) {
if (enable) {
loginInputsLayout.visibility = View.GONE
loginProgressLayout.visibility = View.VISIBLE
} else {
loginInputsLayout.visibility = View.VISIBLE
loginProgressLayout.visibility = View.GONE
}
}
override fun onLoginStarted() {
debug { "Log in started" }
setLoginProgressVisible(true)
}
override fun onLoginFinished() {
setLoginProgressVisible(false)
startActivity<ChannelActivity>()
}
override fun onLoginError(errorMessage: String) {
setLoginProgressVisible(false)
TwilioApplication.instance.showToast("Error logging in : " + errorMessage, Toast.LENGTH_LONG)
}
override fun onLogoutFinished() {
setLoginProgressVisible(false)
TwilioApplication.instance.showToast("Log out finished")
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private fun checkPlayServices(): Boolean {
val apiAvailability = GoogleApiAvailability.getInstance()
val resultCode = apiAvailability.isGooglePlayServicesAvailable(this)
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show()
} else {
info { "This device is not supported." }
finish()
}
return false
}
return true
}
companion object {
private val DEFAULT_CLIENT_NAME = "TestUser"
private val DEFAULT_REALM = "us1"
private val DEFAULT_TTL = "3000"
private val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
}
}
| 0
| null |
49
| 65
|
643f861aceaccb924a2c3fed2027e500e4aaa4d0
| 5,845
|
twilio-chat-demo-android
|
MIT License
|
src/main/kotlin/ar/edu/unq/dao/mongodb/MongoUsuarioDAOImpl.kt
|
CristianGonzalez1980
| 320,041,280
| false
| null |
package ar.edu.unq.dao.mongodb
import ar.edu.unq.dao.UsuarioDAO
import ar.edu.unq.modelo.Usuario
class MongoUsuarioDAOImpl : UsuarioDAO, GenericMongoDAO<Usuario>(Usuario::class.java)
| 1
|
Kotlin
|
0
| 0
|
28553d578b6c6ec24c32759d604731bfbc40627a
| 184
|
exposicion-virtual
|
The Unlicense
|
app/src/main/java/com/manu/foodacious/view/ui/MainActivity.kt
|
ManaswiniKundeti
| 279,084,751
| false
| null |
package com.manu.foodacious.view.ui
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.manu.foodacious.R
import com.manu.foodacious.extensions.hide
import com.manu.foodacious.extensions.show
import com.manu.foodacious.model.collection.CollectionApiModel
import com.manu.foodacious.model.collection.CollectionEntity
import com.manu.foodacious.view.controllers.CollectionController
import com.manu.foodacious.viewmodel.MainActivityViewModel
import com.manu.foodacious.viewmodel.MainActivityViewModelFactory
import com.manu.foodacious.viewstate.Error
import com.manu.foodacious.viewstate.Loading
import com.manu.foodacious.viewstate.Success
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_splash.*
class MainActivity : AppCompatActivity(),CollectionController.IControllerCallback {
private val viewmodelFactory by lazy { MainActivityViewModelFactory(this) }
private val viewModel by viewModels<MainActivityViewModel> {
viewmodelFactory
}
companion object {
const val CITY_ID = "city_id"
const val TORONTO_CITY_ID = 89
private val TAG = MainActivity::class.java.simpleName
}
private lateinit var fusedLocationClient: FusedLocationProviderClient
private var cityId: Int? = null
private lateinit var cityName : String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent : Intent = intent
cityId = intent.getIntExtra(CITY_ID, TORONTO_CITY_ID)
if (cityId == null) {
finish()
return
}
val collectionController = CollectionController(this).apply {
spanCount = 2
}
val gridLayoutManager = GridLayoutManager(this, 2)
gridLayoutManager.spanSizeLookup = collectionController.spanSizeLookup
main_recycler_view.apply {
layoutManager = gridLayoutManager
setController(collectionController)
}
viewModel.locationLiveData.observe(this, Observer{ viewState ->
when(viewState){
is Loading -> { main_progress_bar.show() }
is Success -> {
main_progress_bar.hide()
cityName = viewState.data.cityName
Toast.makeText(this, "Location : $cityName ", Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
intent.putExtra(MainActivity.CITY_ID, viewState.data.cityId)
this.startActivity(intent)
finish()
}
is Error -> {
main_progress_bar.hide()
Toast.makeText(this, "Error fetching cityId", Toast.LENGTH_LONG).show()}
}
})
viewModel.collectionLiveData.observe(this, Observer {viewState ->
when(viewState){
is Loading -> { main_progress_bar.show() }
is Success -> {
main_progress_bar.hide()
collectionController.setData(viewState.data)
}
is Error -> {
main_progress_bar.hide()
Toast.makeText(this, "Error fetching data", Toast.LENGTH_LONG).show()}
}
})
viewModel.getCollections(cityId!!)
}
override fun onCollectionClicked(collection: CollectionEntity) {
val intent = Intent(this, RestaurantActivity::class.java)
intent.putExtra(RestaurantActivity.ARG_COLLECTION_ID, collection.collectionId)
intent.putExtra(RestaurantActivity.ARG_CITY_ID, collection.cityId)
intent.putExtra(RestaurantActivity.ARG_COLLECTION_NAME, collection.title)
this.startActivity(intent)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main_activity, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.update_location -> {
//Fetch current location
fetchUserLocation()
true
}
else -> true
}
}
private fun fetchUserLocation() {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
try {
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
viewModel.getLocationData(location.latitude, location.longitude)
}
} catch (e: SecurityException) {
Log.e(TAG, "Security exception", e)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5842ff938c2fbd82fcf41dccff2ab719786d2b92
| 5,227
|
Foodacious
|
Apache License 2.0
|
app/main/kotlin/tilgang/Config.kt
|
navikt
| 819,933,604
| false
|
{"Kotlin": 105450, "Dockerfile": 248}
|
package tilgang
import tilgang.auth.AzureConfig
import java.net.URI
import java.util.*
private fun getEnvVar(envar: String) = System.getenv(envar) ?: error("missing envvar $envar")
data class Config(
val azureConfig: AzureConfig = AzureConfig(
clientId = getEnvVar("AZURE_APP_CLIENT_ID"),
clientSecret = getEnvVar("AZURE_APP_CLIENT_SECRET"),
tokenEndpoint = URI.create(getEnvVar("AZURE_OPENID_CONFIG_TOKEN_ENDPOINT")).toURL(),
jwks = URI.create(getEnvVar("AZURE_OPENID_CONFIG_JWKS_URI")).toURL(),
issuer = getEnvVar("AZURE_OPENID_CONFIG_ISSUER")
),
val roles: List<Role> = listOf(
Role(Rolle.VEILEDER, UUID.fromString(getEnvVar("AAP_VEILEDER"))),
Role(Rolle.SAKSBEHANDLER, UUID.fromString(getEnvVar("AAP_SAKSBEHANDLER"))),
Role(Rolle.VEILEDER, UUID.fromString(getEnvVar("AAP_VEILEDER"))),
Role(Rolle.BESLUTTER, UUID.fromString(getEnvVar("AAP_BESLUTTER"))),
Role(Rolle.LES, UUID.fromString(getEnvVar("AAP_LES"))),
// Role(Rolle.AVDELINGSLEDER, UUID.fromString(getEnvVar("AAP_AVDELINGSLEDER"))),
// Role(Rolle.UTVIKLER, UUID.fromString(getEnvVar("AAP_UTVIKLER"))),
Role(Rolle.STRENGT_FORTROLIG_ADRESSE, UUID.fromString(getEnvVar("STRENGT_FORTROLIG_ADRESSE"))),
Role(
Rolle.FORTROLIG_ADRESSE, UUID.fromString(getEnvVar("FORTROLIG_ADRESSE"))
)
// TODO: Skjermet/Egne ansatte
),
val pdlConfig: PdlConfig = PdlConfig(),
val msGraphConfig: MsGraphConfig = MsGraphConfig(),
val behandlingsflytConfig: BehandlingsflytConfig = BehandlingsflytConfig(),
val skjermingConfig: SkjermingConfig = SkjermingConfig(),
val nomConfig: NOMConfig = NOMConfig(),
val redis: RedisConfig = RedisConfig()
)
data class PdlConfig(
val baseUrl: String = getEnvVar("PDL_BASE_URL"),
val audience: String = getEnvVar("PDL_AUDIENCE"),
val scope: String = getEnvVar("PDL_SCOPE")
)
data class MsGraphConfig(
val baseUrl: String = getEnvVar("MS_GRAPH_BASE_URL"),
val scope: String = getEnvVar("MS_GRAPH_SCOPE")
)
data class BehandlingsflytConfig(
val baseUrl: String = getEnvVar("BEHANDLINGSFLYT_BASE_URL"),
val scope: String = getEnvVar("BEHANDLINGSFLYT_SCOPE")
)
data class SkjermingConfig(
val baseUrl: String = getEnvVar("SKJERMING_BASE_URL"),
val scope: String = getEnvVar("SKJERMING_SCOPE")
)
data class NOMConfig(
val baseUrl: String = getEnvVar("NOM_BASE_URL"),
val scope: String = getEnvVar("NOM_SCOPE")
)
data class Role(
val name: Rolle,
val objectId: UUID,
)
data class RedisConfig(
val uri: URI = URI(getEnvVar("REDIS_URI_TILGANG")),
val username: String = getEnvVar("REDIS_USERNAME_TILGANG"),
val password: String = getEnvVar("REDIS_PASSWORD_TILGANG"),
)
enum class Rolle {
VEILEDER,
SAKSBEHANDLER,
BESLUTTER,
LES,
AVDELINGSLEDER,
UTVIKLER,
STRENGT_FORTROLIG_ADRESSE,
FORTROLIG_ADRESSE,
KAN_BEHANDLE_SKJERMET,
}
| 0
|
Kotlin
|
0
| 0
|
ad73f13132698cf5642c092a331e3e0c885ca3dd
| 2,980
|
aap-tilgang
|
MIT License
|
app/src/main/java/com/meier/marina/magiccoroutines/data/MagicWand.kt
|
MarinaShaposhnikova
| 136,235,329
| false
|
{"Kotlin": 15404}
|
package com.meier.marina.magiccoroutines.data
data class MagicWand(val wood: String, val core: String, val length: Int)
| 0
|
Kotlin
|
0
| 0
|
9b4c60571f6129d8d54b868ac282e476cec3a1e8
| 121
|
MagicCoroutines
|
Apache License 2.0
|
src/main/kotlin/no/nav/lydia/ia/sak/api/IASakRådgiverRoutes.kt
|
navikt
| 444,072,054
| false
| null |
package no.nav.lydia.ia.sak.api
import arrow.core.flatMap
import arrow.core.getOrElse
import arrow.core.right
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import no.nav.lydia.ADGrupper
import no.nav.lydia.AuditLog
import no.nav.lydia.AuditType
import no.nav.lydia.appstatus.Metrics
import no.nav.lydia.ia.sak.IASakService
import no.nav.lydia.ia.sak.api.IASakDto.Companion.toDto
import no.nav.lydia.ia.sak.domene.IATjeneste
import no.nav.lydia.ia.sak.domene.TilstandsmaskinFeil
import no.nav.lydia.integrasjoner.azure.AzureService
import no.nav.lydia.tilgangskontroll.*
import no.nav.lydia.tilgangskontroll.fia.objectId
const val IA_SAK_RADGIVER_PATH = "iasak/radgiver"
const val SAK_HENDELSE_SUB_PATH = "hendelse"
const val SAMARBEIDSHISTORIKK_PATH = "historikk"
const val IA_SAK_LEVERANSE_PATH = "leveranse"
const val IA_TJENESTER_PATH = "tjenester"
const val IA_MODULER_PATH = "moduler"
fun Route.iaSakRådgiver(
iaSakService: IASakService,
adGrupper: ADGrupper,
auditLog: AuditLog,
azureService: AzureService,
) {
post("$IA_SAK_RADGIVER_PATH/{orgnummer}") {
val orgnummer = call.parameters["orgnummer"] ?: return@post call.respond(IASakError.`ugyldig orgnummer`)
call.somSuperbruker(adGrupper = adGrupper) { superbruker ->
azureService.hentNavenhet(call.objectId()).flatMap { navEnhet ->
iaSakService.opprettSakOgMerkSomVurdert(
orgnummer = orgnummer,
superbruker = superbruker,
navEnhet = navEnhet
).map { it.toDto(superbruker) }
}
}.also { iaSakEither ->
auditLog.auditloggEither(
call = call,
either = iaSakEither,
orgnummer = orgnummer,
auditType = AuditType.create,
saksnummer = iaSakEither.map { iaSak -> iaSak.saksnummer }.getOrNull()
)
}.map {
call.respond(HttpStatusCode.Created, it)
}.mapLeft {
call.respond(it.httpStatusCode, it.feilmelding)
}
}
get("$IA_SAK_RADGIVER_PATH/{orgnummer}") {
val orgnummer = call.parameters["orgnummer"] ?: return@get call.respond(IASakError.`ugyldig orgnummer`)
call.somHøyestTilgang(adGrupper = adGrupper) { navAnsatt ->
iaSakService.hentSakerForOrgnummer(orgnummer).sortedByDescending { it.opprettetTidspunkt }.toDto(navAnsatt = navAnsatt).right()
}.also { either ->
auditLog.auditloggEither(
call = call,
either = either,
orgnummer = orgnummer,
auditType = AuditType.access,
)
}.map {
call.respond(it)
}.mapLeft {
call.respond(status = it.httpStatusCode, message = it.feilmelding)
}
}
get("$IA_SAK_RADGIVER_PATH/{orgnummer}/aktiv") {
val orgnummer = call.parameters["orgnummer"] ?: return@get call.respond(IASakError.`ugyldig orgnummer`)
call.somHøyestTilgang(adGrupper = adGrupper) { navAnsatt ->
iaSakService.hentSakerForOrgnummer(orgnummer)
.sortedByDescending { it.opprettetTidspunkt }
.toDto(navAnsatt = navAnsatt)
.firstOrNull { !it.lukket }
.right()
}.also { either ->
auditLog.auditloggEither(
call = call,
either = either,
orgnummer = orgnummer,
auditType = AuditType.access,
)
}.map {
val response = it ?: HttpStatusCode.NoContent
call.respond(response)
}.mapLeft {
call.respond(status = it.httpStatusCode,message = it.feilmelding)
}
}
get("$IA_SAK_RADGIVER_PATH/$SAMARBEIDSHISTORIKK_PATH/{orgnummer}") {
val orgnummer = call.parameters["orgnummer"] ?: return@get call.respond(IASakError.`ugyldig orgnummer`)
call.somLesebruker(adGrupper = adGrupper) { _ ->
val hendelser = iaSakService.hentHendelserForOrgnummer(orgnr = orgnummer)
iaSakService.hentSakerForOrgnummer(orgnummer = orgnummer)
.map { sak ->
sak.addHendelser(hendelser.filter { hendelse -> hendelse.saksnummer == sak.saksnummer})
}
.sortedByDescending { it.opprettetTidspunkt }
.right()
}. also { either ->
if (either.isLeft()) {
auditLog.auditloggEither(
call = call,
either = either,
orgnummer = orgnummer,
auditType = AuditType.access,
)
} else {
val iaSaker = either.getOrElse { listOf() }
iaSaker.forEach { iaSak ->
auditLog.auditloggEither(
call = call,
either = either,
orgnummer = orgnummer,
auditType = AuditType.access,
saksnummer = iaSak.saksnummer
)
}
}
}.map { iaSaker ->
call.respond(iaSaker.tilSamarbeidshistorikk()).right()
}.mapLeft {
call.respond(status = it.httpStatusCode, message = it.feilmelding)
}
}
post("$IA_SAK_RADGIVER_PATH/$SAK_HENDELSE_SUB_PATH") {
val hendelseDto = call.receive<IASakshendelseDto>()
call.somSaksbehandler(adGrupper = adGrupper) { saksbehandler ->
azureService.hentNavenhet(call.objectId()).flatMap { navEnhet ->
iaSakService.behandleHendelse(hendelseDto, saksbehandler = saksbehandler, navEnhet = navEnhet).map { it.toDto(saksbehandler) }
.onRight { Metrics.loggHendelse(hendelseDto.hendelsesType) }
}
}.also {
auditLog.auditloggEither(
call = call,
either = it,
orgnummer = hendelseDto.orgnummer,
auditType = AuditType.update,
saksnummer = hendelseDto.saksnummer
)
}.map {
call.respond(HttpStatusCode.Created, it)
}.mapLeft {
call.respond(it.httpStatusCode, it.feilmelding)
}
}
get("$IA_SAK_RADGIVER_PATH/$IA_SAK_LEVERANSE_PATH/{orgnr}/{saksnummer}") {
val orgnr = call.parameters["orgnr"] ?: return@get call.sendFeil(IASakError.`ugyldig orgnummer`)
val saksnummer = call.parameters["saksnummer"] ?: return@get call.sendFeil(IASakError.`ugyldig saksnummer`)
call.somLesebruker(adGrupper = adGrupper) { _ ->
iaSakService.hentIASakLeveranser(saksnummer = saksnummer)
}.also {
auditLog.auditloggEither(
call = call,
either = it,
orgnummer = orgnr,
auditType = AuditType.access,
saksnummer = saksnummer
)
}.map {
call.respond(it.tilIASakLeveranserPerTjenesteDto().sorted())
}.mapLeft {
call.respond(message = it.feilmelding, status = it.httpStatusCode)
}
}
post("$IA_SAK_RADGIVER_PATH/$IA_SAK_LEVERANSE_PATH/{orgnr}/{saksnummer}") {
val orgnr = call.parameters["orgnr"] ?: return@post call.sendFeil(IASakError.`ugyldig orgnummer`)
val saksnummer = call.parameters["saksnummer"] ?: return@post call.sendFeil(IASakError.`ugyldig saksnummer`)
val leveranse = call.receive<IASakLeveranseOpprettelsesDto>()
call.somSaksbehandler(adGrupper = adGrupper) { saksbehandler ->
iaSakService.opprettIASakLeveranse(leveranse = leveranse, saksbehandler = saksbehandler)
}.also {
auditLog.auditloggEither(
call = call,
either = it,
orgnummer = orgnr,
auditType = AuditType.update,
saksnummer = saksnummer
)
}.map {
call.respond(status = HttpStatusCode.Created, message = it.tilDto())
}.mapLeft {
call.respond(status = it.httpStatusCode, message = it.feilmelding)
}
}
put("$IA_SAK_RADGIVER_PATH/$IA_SAK_LEVERANSE_PATH/{orgnr}/{saksnummer}/{iaSakLeveranseId}") {
val orgnr = call.parameters["orgnr"] ?: return@put call.sendFeil(IASakError.`ugyldig orgnummer`)
val saksnummer = call.parameters["saksnummer"] ?: return@put call.sendFeil(IASakError.`ugyldig saksnummer`)
val iaSakLeveranseId = call.parameters["iaSakLeveranseId"] ?: return@put call.sendFeil(IASakError.`ugyldig iaSakLeveranseId`)
val oppdateringsDto = call.receive<IASakLeveranseOppdateringsDto>()
call.somSaksbehandler(adGrupper = adGrupper) { saksbehandler ->
iaSakService.oppdaterIASakLeveranse(iaSakLeveranseId = iaSakLeveranseId.toInt(), oppdateringsDto = oppdateringsDto, saksbehandler = saksbehandler)
}.also {
auditLog.auditloggEither(
call = call,
either = it,
orgnummer = orgnr,
auditType = AuditType.update,
saksnummer = saksnummer
)
}.map {
call.respond(it.tilDto())
}.mapLeft {
call.respond(message = it.feilmelding, status = it.httpStatusCode)
}
}
delete("$IA_SAK_RADGIVER_PATH/$IA_SAK_LEVERANSE_PATH/{orgnr}/{saksnummer}/{iaSakLeveranseId}") {
val orgnr = call.parameters["orgnr"] ?: return@delete call.sendFeil(IASakError.`ugyldig orgnummer`)
val saksnummer = call.parameters["saksnummer"] ?: return@delete call.sendFeil(IASakError.`ugyldig saksnummer`)
val iaSakLeveranseId = call.parameters["iaSakLeveranseId"] ?: return@delete call.sendFeil(IASakError.`ugyldig iaSakLeveranseId`)
call.somSaksbehandler(adGrupper = adGrupper) { saksbehandler ->
iaSakService.slettIASakLeveranse(iaSakLeveranseId = iaSakLeveranseId.toInt(), saksbehandler)
}.also {
auditLog.auditloggEither(
call = call,
either = it,
orgnummer = orgnr,
auditType = AuditType.delete,
saksnummer = saksnummer
)
}.map {
call.respond(it)
}.mapLeft {
call.respond(message = it.feilmelding, status = it.httpStatusCode)
}
}
get("$IA_SAK_RADGIVER_PATH/$IA_SAK_LEVERANSE_PATH/$IA_TJENESTER_PATH") {
call.somLesebruker(adGrupper = adGrupper) { _ ->
iaSakService.hentTjenester()
}.map {
call.respond(it.map(IATjeneste::tilDto).sorted())
}.mapLeft {
call.respond(message = it.feilmelding, status = it.httpStatusCode)
}
}
get("$IA_SAK_RADGIVER_PATH/$IA_SAK_LEVERANSE_PATH/$IA_MODULER_PATH") {
call.somSaksbehandler(adGrupper = adGrupper) { _ ->
iaSakService.hentModuler()
}.map {
call.respond(it.map { modul -> modul.tilDto() })
}.mapLeft {
call.respond(message = it.feilmelding, status = it.httpStatusCode)
}
}
}
suspend fun ApplicationCall.sendFeil(feil: Feil) = respond(feil.httpStatusCode, feil.feilmelding)
class Feil(val feilmelding: String, val httpStatusCode: HttpStatusCode) {
companion object {
fun TilstandsmaskinFeil.tilFeilMedHttpFeilkode() = Feil(this.feilmelding, HttpStatusCode.UnprocessableEntity)
}
}
object IASakError {
val `prøvde å legge til en hendelse på en tom sak` =
Feil("Prøvde å legge til en hendelse på en tom sak", HttpStatusCode.Conflict)
val `prøvde å legge til en hendelse på en gammel sak` = Feil(
"Prøvde å legge til hendelse på gammel sak", HttpStatusCode.Conflict
)
val `fikk ikke oppdatert sak` = Feil("Fikk ikke oppdatert sak", HttpStatusCode.Conflict)
val `fikk ikke oppdatert leveranse` = Feil("Fikk ikke oppdatert leveranse", HttpStatusCode.Conflict)
val `fikk ikke slettet sak` = Feil("Fikk ikke slettet sak", HttpStatusCode.InternalServerError)
val `ugyldig orgnummer` = Feil("Ugyldig orgnummer", HttpStatusCode.BadRequest)
val `ugyldig saksnummer` = Feil("Ugyldig saksnummer", HttpStatusCode.BadRequest)
val `ugyldig iaSakLeveranseId` = Feil("Ugyldig leveranseId", HttpStatusCode.BadRequest)
val `ugyldig modul` = Feil("Ugyldig modul", HttpStatusCode.BadRequest)
val `ikke eier av sak` = Feil("Ikke eier av sak", HttpStatusCode.BadRequest)
val `det finnes flere saker på dette orgnummeret som ikke regnes som avsluttet` = Feil(
"Det finnes flere saker på dette orgnummeret som ikke regnes som avsluttet", HttpStatusCode.NotImplemented
)
val `generell feil under uthenting` = Feil("Generell feil under uthenting", HttpStatusCode.InternalServerError)
val `kan ikke fullføre med gjenstående leveranser` = Feil("Kan ikke fullføre med gjenstående leveranser", HttpStatusCode.BadRequest)
val `kan ikke fullføre da ingen leveranser står på saken` = Feil("Kan ikke fullføre uten leveranser", HttpStatusCode.BadRequest)
}
| 1
|
Kotlin
|
1
| 2
|
cf80398e555acfb4bfabe1e0f18d1ace19b133e4
| 13,211
|
lydia-api
|
MIT License
|
src/main/kotlin/io/framed/framework/render/html/HtmlShapeContainer.kt
|
Eden-06
| 138,000,306
| false
| null |
package io.framed.framework.render.html
import de.westermann.kobserve.event.EventHandler
import de.westermann.kobserve.event.EventListener
import io.framed.framework.JsPlumbInstance
import io.framed.framework.pictogram.BoxShape
import io.framed.framework.pictogram.IconShape
import io.framed.framework.pictogram.Shape
import io.framed.framework.pictogram.TextShape
import io.framed.framework.view.View
import io.framed.framework.view.ViewCollection
class HtmlShapeContainer(
private val htmlRenderer: HtmlRenderer,
private val containerShape: BoxShape,
private val container: ViewCollection<View<*>, *>,
jsPlumbInstanceParent: JsPlumbInstance? = null,
private val parent: HtmlContentShape? = null
) {
val jsPlumbInstance = if (containerShape.position == BoxShape.Position.ABSOLUTE || jsPlumbInstanceParent == null) {
htmlRenderer.htmlConnections.createJsPlumb(containerShape, container)
} else jsPlumbInstanceParent
private val shapeMap: MutableMap<Shape, HtmlShape> = mutableMapOf()
fun create(shape: Shape): HtmlShape = when (shape) {
is BoxShape -> {
if (shape.position == BoxShape.Position.BORDER && parent != null) {
HtmlBorderShape(htmlRenderer, shape, parent, this, container, containerShape.position, jsPlumbInstance)
} else {
HtmlBoxShape(htmlRenderer, shape, parent, this, container, containerShape.position, jsPlumbInstance)
}
}
is TextShape -> HtmlTextShape(htmlRenderer, shape, parent, this, container, jsPlumbInstance)
is IconShape -> HtmlIconShape(htmlRenderer, shape, parent, this, container, containerShape.position, jsPlumbInstance)
else -> throw UnsupportedOperationException()
}
private fun add(shape: Shape) {
if (shape !in shapeMap) {
val html = create(shape)
shapeMap += shape to html
if (shape.id != null) {
htmlRenderer.shapeMap += shape to html
}
if (html is HtmlContentShape) {
onParentMove(html.content.onParentMove::emit)
}
htmlRenderer.htmlConnections.addShape(shape)
}
}
private fun remove(shape: Shape) {
shapeMap.remove(shape)?.let { html ->
if (html is HtmlContentShape) {
onParentMove.removeListener(html.content.onParentMove::emit)
}
html.remove()
}
htmlRenderer.shapeMap -= shape
htmlRenderer.htmlConnections.deleteShape(shape)
}
val onParentMove = EventHandler<Shape>()
private val references: MutableList<EventListener<*>> = mutableListOf()
init {
containerShape.shapes.forEach(this::add)
references += containerShape.onAdd.reference(this::add)
references += containerShape.onRemove.reference(this::remove)
}
fun remove() {
shapeMap.keys.forEach(this::remove)
for (it in references) {
it.detach()
}
references.clear()
}
}
| 5
| null |
1
| 2
|
27f4a4c44d90f20f748ab779c3c184cb012a59fe
| 3,074
|
FRaMED-io
|
MIT License
|
petsearch-shared/core/util/src/commonMain/kotlin/com/msa/petsearch/shared/core/util/resource/MessageDeque.kt
|
msa1422
| 534,594,528
| false
| null |
package com.msa.petsearch.shared.core.util.resource
import com.rickclephas.kmp.nativecoroutines.NativeCoroutines
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
object MessageDeque : Queue<ResourceMessage> {
private val deque = ArrayDeque<ResourceMessage>()
private val message = MutableSharedFlow<ResourceMessage>()
@NativeCoroutines
operator fun invoke() = message.asSharedFlow()
override val count: Int
get() = deque.size
override suspend fun enqueue(element: ResourceMessage): Boolean {
// If deque contains the element id return false,
// No need to take any action in this case
if (deque.any { it.id == element.id }) {
return false
}
// Add the element to the deque
val transaction = deque.add(element)
// If the element being enqueued is the only element in Deque, emit the message
// else wait for the Deque to be dequeued
if (count == 1) {
peekAndUpdate()
}
return transaction
}
override suspend fun dequeue(): ResourceMessage? {
// First remove the message from the ArrayDeque
val transaction = deque.removeFirstOrNull()
// Now peek and see if there are other messages in queue. If yes, then update FlowData
peekAndUpdate()
// Finally return the transaction data
return transaction
}
override suspend fun peekAndUpdate() {
deque.firstOrNull()?.let { message.emit(it) }
}
}
| 1
| null |
0
| 19
|
b67e8e287e0d2b3fc0f2d3feaf3d0a21fd525c88
| 1,560
|
KMM-Arch-PetSearch
|
MIT License
|
androidOlympusBlog/src/main/java/com/olympusblog/android/presentation/screens/search/SearchScreen.kt
|
sentrionic
| 551,827,184
| false
| null |
package com.olympusblog.android.presentation.screens.search
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import coil.ImageLoader
import com.olympusblog.android.presentation.components.common.EmptyPlaceholder
import com.olympusblog.android.presentation.components.common.RefreshListener
import com.olympusblog.android.presentation.components.core.NavigationBar
import com.olympusblog.presentation.refresh.RefreshViewState
import com.olympusblog.android.presentation.navigation.Screen
import com.olympusblog.android.presentation.screens.articles.list.components.ArticleList
import com.olympusblog.android.presentation.screens.search.components.*
import com.olympusblog.android.presentation.theme.AppTheme
import com.olympusblog.domain.core.DialogState
import com.olympusblog.presentation.search.SearchEvents
import com.olympusblog.presentation.search.SearchFilter
import com.olympusblog.presentation.search.SearchState
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun SearchScreen(
state: SearchState,
onTriggerEvent: (SearchEvents) -> Unit,
navController: NavController,
imageLoader: ImageLoader,
refreshState: RefreshViewState
) {
RefreshListener(
state = refreshState,
handleEvent = { refresher ->
onTriggerEvent(SearchEvents.HandleRefresherEvent(refresher = refresher))
},
)
val controller = LocalSoftwareKeyboardController.current
AppTheme(
displayProgressBar = state.isLoading,
dialogQueue = state.queue,
onRemoveHeadMessageFromQueue = {
onTriggerEvent(SearchEvents.OnRemoveHeadFromQueue)
}
) {
Scaffold(
topBar = {
SearchTopBar {
onTriggerEvent(SearchEvents.UpdateFilterDialogState(DialogState.Show))
}
},
bottomBar = {
NavigationBar(navController = navController)
}
) { padding ->
Box {
if (state.filterDialogState is DialogState.Show) {
SearchListFilter(
searchFilter = state.filter,
onUpdateFilter = { filter ->
onTriggerEvent(SearchEvents.UpdateFilter(filter))
},
onCloseDialog = {
onTriggerEvent(SearchEvents.UpdateFilterDialogState(DialogState.Hide))
}
)
}
Column(
modifier = Modifier.fillMaxSize(),
) {
SearchInput(
query = state.query,
onUpdateQuery = { query -> onTriggerEvent(SearchEvents.UpdateQuery(query)) },
executeSearch = {
controller?.hide()
onTriggerEvent(SearchEvents.NewSearch)
}
)
if (state.tags.isNotEmpty()) {
PopularTags(
tags = state.tags,
onSelect = { tag ->
onTriggerEvent(SearchEvents.UpdateQuery(tag))
onTriggerEvent(SearchEvents.UpdateFilter(SearchFilter.Tags()))
}
)
Spacer(modifier = Modifier.height(20.dp))
}
Divider()
when {
state.articles.isNotEmpty() -> {
ArticleList(
articles = state.articles,
page = state.page,
isLoading = state.isLoading,
paddingValues = padding,
imageLoader = imageLoader,
onSelectArticle = { slug ->
navController.navigate(Screen.ArticleDetail.route + "/$slug")
},
onChangeScrollPosition = { index ->
onTriggerEvent(SearchEvents.OnUpdateScrollPosition(index))
},
fetchNextPage = {
onTriggerEvent(SearchEvents.NextPage)
},
onToggleBookmark = { slug ->
onTriggerEvent(SearchEvents.ToggleBookmarkEvent(slug))
},
onToggleFavorite = { slug ->
onTriggerEvent(SearchEvents.ToggleFavoriteEvent(slug))
},
)
}
state.authors.isNotEmpty() -> {
ProfileList(
authors = state.authors,
padding = padding,
navigateToProfile = { username ->
navController.navigate(Screen.Profile.route + "/$username")
}
)
}
state.isLoading -> {
// Display Nothing
}
else -> {
EmptyPlaceholder(text = "Nothing to see here")
}
}
}
}
}
}
}
@Preview
@Composable
fun PreviewSearchScreen() {
SearchScreen(
state = SearchState(),
onTriggerEvent = {},
navController = rememberNavController(),
imageLoader = ImageLoader.Builder(LocalContext.current).build(),
refreshState = RefreshViewState(),
)
}
| 0
|
Kotlin
|
0
| 0
|
bb61f26adcdded63b83c505d2f67c50715e8b859
| 6,449
|
OlympusKMM
|
MIT License
|
home/src/main/java/com/kingsland/home/data/repository/TaskRepository.kt
|
data-programmer
| 599,861,493
| false
| null |
package com.kingsland.home.data.repository
import com.kingsland.home.convertTaskDtoToDomain
import com.kingsland.home.data.source.TaskDataSource
import com.kingsland.home.domain.model.TaskDomain
import com.kingsland.home.domain.repository.ITaskRepository
import javax.inject.Inject
class TaskRepository @Inject constructor(
private val taskDataSource: TaskDataSource
) : ITaskRepository {
override fun getTasksByStatus(status: Int): List<TaskDomain> = taskDataSource
.getTasksByStatus(status)
.convertTaskDtoToDomain()
}
| 0
|
Kotlin
|
0
| 0
|
bcd53b9784689e5b60d893248ccc2910b17391e0
| 547
|
ProjectTrakAndroid
|
MIT License
|
analysis/analysis-api/testData/components/inheritorsProvider/sealedInheritors/sealedInheritorWrongPackageSameModule.kt
|
JetBrains
| 3,432,266
| false
| null |
// FILE: main.kt
package foo.bar
sealed class MySealedClass
class Inheritor1 : MySealedClass()
// FILE: Inheritor2.kt
package foo
import foo.bar.MySealedClass
class Inheritor2 : MySealedClass()
// class: foo/bar/MySealedClass
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 232
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/org/rust/lang/core/mir/schemas/MirBinaryOperator.kt
|
intellij-rust
| 42,619,487
| false
| null |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.mir.schemas
import org.rust.lang.core.psi.ext.ArithmeticOp
import org.rust.lang.core.psi.ext.BinaryOperator
import org.rust.lang.core.psi.ext.ComparisonOp
import org.rust.lang.core.psi.ext.EqualityOp
sealed interface MirBinaryOperator {
val underlyingOp: BinaryOperator?
data class Arithmetic(val op: ArithmeticOp) : MirBinaryOperator {
override val underlyingOp get() = op
}
data class Equality(val op: EqualityOp) : MirBinaryOperator {
override val underlyingOp get() = op
}
data class Comparison(val op: ComparisonOp) : MirBinaryOperator {
override val underlyingOp get() = op
}
object Offset : MirBinaryOperator {
override val underlyingOp get() = null
}
companion object {
fun BinaryOperator.toMir() = when (this) {
is ArithmeticOp -> Arithmetic(this)
is EqualityOp -> Equality(this)
is ComparisonOp -> Comparison(this)
else -> error("$this cannot be a mir operator")
}
}
}
| 1,841
| null |
380
| 4,528
|
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
| 1,161
|
intellij-rust
|
MIT License
|
common/src/main/java/com/ishow/common/manager/CacheManager.kt
|
i-show
| 62,766,394
| false
| null |
package com.ishow.common.manager
import android.os.SystemClock
import androidx.collection.LruCache
import com.ishow.common.extensions.parseJSON
import com.ishow.common.extensions.toJSON
import com.ishow.common.utils.StorageUtils
import java.util.concurrent.TimeUnit
/**
* Created by yuhaiyang on 2020/7/30.
* 缓存管理
*/
class CacheManager private constructor() {
companion object {
private val ramCache: LruCache<String, String> = LruCache(20)
private val ramCacheExpire: LruCache<String, Long> = LruCache(20)
/**
* 缓存对应key 的请求信息
*/
fun cache(key: String, value: Any?, expire: Int = 0) {
if (value == null) return
StorageUtils.save()
.group("cache")
.addParam(key, value.toJSON())
.expire(expire, TimeUnit.SECONDS)
.apply()
}
/**
* 获取缓存对应Url的值
*/
inline fun <reified T> get(key: String): T? {
val cacheStr = getCacheString(key)
if (cacheStr.isNullOrEmpty()) return null
return cacheStr.parseJSON()
}
/**
* 移除对应Url的缓存
*/
fun remove(key: String) {
StorageUtils.remove()
.group("cache")
.key(key)
.apply()
}
/**
* 获取缓存Str
*/
fun getCacheString(key: String): String? {
val cacheStr = ramCache.get(key)
if (!cacheStr.isNullOrEmpty()) {
return getCacheStringFromRam(key, cacheStr)
}
return StorageUtils.get()
.group("cache")
.key(key)
.apply()
}
/**
* 从内存中获取缓存数据
*/
@Suppress("LiftReturnOrAssignment", "CascadeIf")
private fun getCacheStringFromRam(key: String, value: String): String? {
val expire = ramCacheExpire.get(key)
if (expire == null) {
return value
} else if (expire < SystemClock.elapsedRealtime()) {
ramCache.remove(key)
ramCacheExpire.remove(key)
StorageUtils.remove()
.group("cache")
.key(key)
.apply()
return null
} else {
return value
}
}
}
}
| 1
| null |
1
| 1
|
0b823a69256345078a0c110798c8e9ac4ae2b565
| 2,420
|
android-Common
|
Apache License 2.0
|
src/main/kotlin/land/src/toolbox/jvm/oop/InstanceKlass.kt
|
JVMInspect
| 874,749,033
| false
|
{"Kotlin": 138930}
|
package land.src.toolbox.jvm.oop
import land.src.toolbox.jvm.dsl.*
import land.src.toolbox.jvm.primitive.Address
import land.src.toolbox.jvm.primitive.Array
import land.src.toolbox.jvm.primitive.ByteArray
import land.src.toolbox.jvm.util.*
class InstanceKlass(address: Address) : Klass(address) {
val majorVersion: Short get() = constantPool.majorVersion
val minorVersion: Short get() = constantPool.minorVersion
val constantPool: ConstantPool by nonNull("_constants")
val superClass: Klass? by maybeNull("_super")
val nestHostIndex: Short by lazy {
val staticOopFieldCountAddress = address.base + type.field("_static_oop_field_count")!!.offsetOrAddress
unsafe.getShort(staticOopFieldCountAddress - Short.SIZE_BYTES * 2)
}
val nestMembers: Array<Short> by lazy {
val nestMembersAddress = address.base + type.field("_inner_classes")!!.offsetOrAddress + pointerSize
arrays(nestMembersAddress, false)!!
}
val permittedSubclasses: Array<Short> by lazy {
val nestHostAddress = address.base + type.field("_inner_classes")!!.offsetOrAddress + (pointerSize * 2)
val permittedSubclassesAddress = nestHostAddress + pointerSize
arrays(permittedSubclassesAddress, false)!!
}
val recordComponents: Array<RecordComponent>? by lazy {
val nestHostAddress = address.base + type.field("_inner_classes")!!.offsetOrAddress + (pointerSize * 2)
val permittedSubclassesAddress = nestHostAddress + pointerSize
val recordComponentsAddress = permittedSubclassesAddress + pointerSize
if (unsafe.getAddress(recordComponentsAddress) == 0L)
return@lazy null
arrays(recordComponentsAddress, true)
}
val sourceDebugExtension: String? by lazy {
val nestHostAddress = address.base + type.field("_inner_classes")!!.offsetOrAddress + (pointerSize * 2)
val permittedSubclassesAddress = nestHostAddress + pointerSize
val recordComponentsAddress = permittedSubclassesAddress + pointerSize
val sourceDebugExtensionAddress = recordComponentsAddress + pointerSize
if (unsafe.getAddress(sourceDebugExtensionAddress) == 0L)
return@lazy null
unsafe.getString(unsafe.getAddress(sourceDebugExtensionAddress))
}
val sourceFileNameIndex: Short get() = constantPool.sourceFileNameIndex
val genericSignatureIndex: Short get() = constantPool.genericSignatureIndex
val annotations: Annotations? by maybeNull("_annotations")
val innerClasses: Array<Short>? by maybeNullArray("_inner_classes")
val localInterfaces: Array<InstanceKlass>? by maybeNullArray("_local_interfaces")
val methods: Array<Method> by nonNullArray("_methods")
val fieldData: Array<Short> by nonNullArray("_fields")
val methodOrdering: Array<Int>? by maybeNullArray("_method_ordering")
val accessFlagsOffset: Int by constant("FieldInfo::access_flags_offset")
val nameIndexOffset: Int by constant("FieldInfo::name_index_offset")
val signatureIndexOffset: Int by constant("FieldInfo::signature_index_offset")
val initialValueIndexOffset: Int by constant("FieldInfo::initval_index_offset")
val lowPackedOffset: Int by constant("FieldInfo::low_packed_offset")
val highPackedOffset: Int by constant("FieldInfo::high_packed_offset")
val miscFlags: Short by nonNull("_misc_flags")
fun isFlagSet(flag: InstanceKlassFlag): Boolean {
return (miscFlags.toInt() and flag.bit(this)) != 0
}
val fieldInfos: List<FieldInfo> by lazy {
val info = mutableListOf<FieldInfo>()
var fieldCount = fieldData.length
var index = 0
while (index < fieldData.length) {
val accessFlags: Short = fieldData[index]!!
if ((accessFlags.toInt() and JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE) != 0) {
fieldCount--
}
index += 6
}
fieldCount /= 6
for (i in 0 until fieldCount) {
val accessFlags = fieldData[i * 6 + accessFlagsOffset]!!
val nameIndex = fieldData[i * 6 + nameIndexOffset]!!
val signatureIndex = fieldData[i * 6 + signatureIndexOffset]!!
val initialValIndex = fieldData[i * 6 + initialValueIndexOffset]!!
val lowOffset = fieldData[i * 6 + lowPackedOffset]!!
val highOffset = fieldData[i * 6 + highPackedOffset]!!
info += FieldInfo(
accessFlags,
nameIndex,
signatureIndex,
initialValIndex,
lowOffset,
highOffset
)
}
info
}
val javaFieldInfos: List<FieldInfo> by lazy {
fieldInfos.filter { it.accessFlags.toInt() and JVM_ACC_FIELD_INTERNAL == 0 }
}
}
| 0
|
Kotlin
|
0
| 6
|
dfd87cc5a2462a582696a0a1e2752e8830bcbd09
| 4,808
|
toolbox
|
MIT License
|
app/src/main/java/com/appbusters/robinpc/constitutionofindia/di/component/activity/MiddleActivityComponent.kt
|
kumar4Vipul
| 213,992,183
| false
|
{"Kotlin": 141940, "Java": 708}
|
package com.appbusters.robinpc.constitutionofindia.di.component.activity
import com.appbusters.robinpc.constitutionofindia.di.component.ConstitutionAppComponent
import com.appbusters.robinpc.constitutionofindia.di.module.ViewModelFactoryModule
import com.appbusters.robinpc.constitutionofindia.di.module.ViewModelModule
import com.appbusters.robinpc.constitutionofindia.di.module.activity.MiddleActivityModule
import com.appbusters.robinpc.constitutionofindia.di.scope.PerFragmentScope
import com.appbusters.robinpc.constitutionofindia.ui.intermediate.MiddleActivity
import dagger.Component
@PerFragmentScope
@Component(modules = [MiddleActivityModule::class, ViewModelFactoryModule::class, ViewModelModule::class],
dependencies = [ConstitutionAppComponent::class])
interface MiddleActivityComponent {
fun injectMiddleActivity(activity: MiddleActivity)
}
| 1
| null |
1
| 1
|
82a916316ac6822023392991f1efc74ff2ed571f
| 868
|
Indian-Constitution-App
|
Apache License 2.0
|
test-framework/src/main/kotlin/com/aemtools/test/parser/BaseParserTest.kt
|
iannovic
| 112,768,567
| true
|
{"Kotlin": 618081, "HTML": 14958, "Lex": 3652}
|
package com.aemtools.blocks.parser
import com.intellij.lang.ParserDefinition
import com.intellij.testFramework.ParsingTestCase
/**
* @author Dmytro_Troynikov
*/
abstract class BaseParserTest(dataPath: String,
fileExt: String,
parserDefinition: ParserDefinition,
lowercaseFirstLetter: Boolean = true)
: ParsingTestCase(dataPath, fileExt, lowercaseFirstLetter, parserDefinition) {
fun doTest() = doTest(true)
override fun getTestDataPath(): String = "src/test/resources"
override fun checkAllPsiRoots() = false
}
| 0
|
Kotlin
|
0
| 0
|
d9c1558872fd5e32f18e0bab0afa8f4495da95b0
| 617
|
aemtools
|
MIT License
|
app/src/main/java/com/example/slabber/composables/NewChat.kt
|
Wahabahmad694
| 477,558,751
| false
| null |
package com.example.slabber.composables
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import coil.compose.rememberImagePainter
import coil.transform.CircleCropTransformation
import com.example.slabber.R
import com.example.slabber.data.DataHolder
import com.example.slabber.models.User
import com.example.slabber.screens.Screen
import com.example.slabber.viewModels.AuthViewModel
@Composable
fun NewChat(navController: NavController) {
val chatViewModel = AuthViewModel()
Surface {
NewChat(newChatList = chatViewModel.allUserResponse, navController = navController)
chatViewModel.allUsers()
}
}
//********** List View Item ********* //
@Composable
fun NewChatItem(user: User) {
Card(
modifier = Modifier
.background(Color.Black)
.padding(8.dp, 4.dp)
.fillMaxWidth()
.height(80.dp), shape = RoundedCornerShape(8.dp), elevation = 4.dp
) {
Surface {
Row(
Modifier
.background(Color.Black)
.padding(4.dp)
.fillMaxSize()
) {
Image(
painter = rememberImagePainter(
data = "",
builder = {
scale(coil.size.Scale.FIT)
placeholder(R.drawable.bg_placeholder_user)
transformations(CircleCropTransformation())
}
),
contentDescription = "",
modifier = Modifier
.fillMaxHeight()
.weight(0.2f)
)
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier
.padding(start = 8.dp)
.fillMaxHeight()
.weight(0.8f)
) {
Text(
text = user.name,
style = MaterialTheme.typography.subtitle1,
fontWeight = FontWeight.Bold,
color = Color.White
)
Text(
text = user.email,
style = MaterialTheme.typography.body1,
maxLines = 1,
color = Color.White
)
}
}
}
}
//********** Line Separator ********* //
Divider(
color = Color.LightGray,
thickness = 1.dp,
modifier = Modifier.padding(horizontal = 8.dp)
)
}
// endregion list view item
@Composable
fun NewChat(newChatList: List<User>, navController: NavController) {
Scaffold(backgroundColor = Color.LightGray) {
Column(
Modifier
.padding(top = 20.dp, start = 8.dp, end = 8.dp)
.fillMaxSize()
) {
Row(
Modifier
.fillMaxWidth()
) {
Text(
text = "New Chat",
fontWeight = FontWeight.ExtraBold,
fontSize = 32.sp,
textAlign = TextAlign.Center,
fontFamily = FontFamily.Serif,
color = Color.Black,
modifier = Modifier.fillMaxWidth()
)
}
Spacer(modifier = Modifier.height(15.dp))
LazyColumn {
itemsIndexed(items = newChatList) { _, item ->
Surface(modifier = Modifier.clickable {
DataHolder.chatUsers = listOf(DataHolder.to!!, item)
navController.navigate(Screen.ChatDetail.routes)
}) {
NewChatItem(user = item)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d7f87252662fc50db0089810b231702eb5e97e35
| 4,683
|
Slabber
|
Apache License 2.0
|
src/test/kotlin/org/learning/by/example/reactive/kotlin/microservices/KotlinReactiveMS/application/mainTest.kt
|
LearningByExample
| 92,105,897
| false
| null |
package org.learning.by.example.reactive.kotlin.microservices.KotlinReactiveMS.application
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.learning.by.example.reactive.kotlin.microservices.KotlinReactiveMS.test.BasicIntegrationTest
import org.learning.by.example.reactive.kotlin.microservices.KotlinReactiveMS.test.tags.UnitTest
@UnitTest
@DisplayName("main Unit Tests")
private class mainTests : BasicIntegrationTest() {
@Test
fun mainTest() {
main(arrayOf())
}
}
| 0
| null |
13
| 34
|
05acfe82f670d9a9aa31206ba4c6b3cffa506b9d
| 526
|
KotlinReactiveMS
|
MIT License
|
reactive-crypto-bithumb/src/main/kotlin/com/njkim/reactivecrypto/bithumb/BithumbWebsocketClient.kt
|
namjug-kim
| 184,743,851
| false
| null |
/*
* Copyright 2019 namjug-kim
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.njkim.reactivecrypto.bithumb
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.njkim.reactivecrypto.bithumb.model.BithumbOrderBook
import com.njkim.reactivecrypto.bithumb.model.BithumbResponseWrapper
import com.njkim.reactivecrypto.bithumb.model.BithumbTickData
import com.njkim.reactivecrypto.core.websocket.AbstractExchangeWebsocketClient
import com.njkim.reactivecrypto.core.ExchangeJsonObjectMapper
import com.njkim.reactivecrypto.core.common.model.ExchangeVendor
import com.njkim.reactivecrypto.core.common.model.currency.Currency
import com.njkim.reactivecrypto.core.common.model.currency.CurrencyPair
import com.njkim.reactivecrypto.core.common.model.order.OrderBook
import com.njkim.reactivecrypto.core.common.model.order.OrderBookUnit
import com.njkim.reactivecrypto.core.common.model.order.OrderSideType
import com.njkim.reactivecrypto.core.common.model.order.TickData
import com.njkim.reactivecrypto.core.common.util.toEpochMilli
import mu.KotlinLogging
import reactor.core.publisher.Flux
import reactor.core.publisher.toFlux
import reactor.netty.http.client.HttpClient
import java.time.ZonedDateTime
class BithumbWebsocketClient : AbstractExchangeWebsocketClient() {
private val log = KotlinLogging.logger {}
private val baseUri = "wss://wss.bithumb.com/public"
private val objectMapper: ObjectMapper = createJsonObjectMapper().objectMapper()
override fun createJsonObjectMapper(): ExchangeJsonObjectMapper {
return BithumbJsonObjectMapper()
}
override fun createTradeWebsocket(subscribeTargets: List<CurrencyPair>): Flux<TickData> {
val subscribeRequests = subscribeTargets.stream()
.map {
if (it.baseCurrency == Currency.KRW) {
"${it.targetCurrency}"
} else {
"${it.targetCurrency}${it.baseCurrency}"
}
}
.map { "{\"currency\":\"$it\",\"tickDuration\":\"24H\",\"service\":\"transaction\"}" }
.toFlux()
return subscribeRequests.flatMap { subscribeRequest ->
HttpClient.create()
.headers { it.add("Origin", "https://www.bithumb.com") }
.wiretap(log.isDebugEnabled)
.websocket()
.uri(baseUri)
.handle { inbound, outbound ->
outbound.sendString(Flux.just(subscribeRequest))
.then()
.thenMany(inbound.receive().asString())
}
.map { objectMapper.readValue<BithumbResponseWrapper<List<BithumbTickData>>>(it) }
.flatMapIterable {
it.data.map { bithumbTickData ->
TickData(
bithumbTickData.countNo.toString(),
bithumbTickData.transactionDate,
bithumbTickData.price,
bithumbTickData.unitsTraded,
CurrencyPair(it.header.currency, Currency.KRW), // Bithumb only have KRW market
ExchangeVendor.BITHUMB,
bithumbTickData.type
)
}
}
}
}
override fun createDepthSnapshot(subscribeTargets: List<CurrencyPair>): Flux<OrderBook> {
val subscribeRequests = subscribeTargets.stream()
.map {
if (it.baseCurrency == Currency.KRW) {
"${it.targetCurrency}"
} else {
"${it.targetCurrency}${it.baseCurrency}"
}
}
.map { "{\"currency\":\"$it\",\"tickDuration\":\"24H\",\"service\":\"orderbook\"}" }
.toFlux()
return subscribeRequests.flatMap { subscribeRequest ->
HttpClient.create()
.headers { it.add("Origin", "https://www.bithumb.com") }
.wiretap(log.isDebugEnabled)
.websocket()
.uri(baseUri)
.handle { inbound, outbound ->
outbound.sendString(Flux.just(subscribeRequest))
.then()
.thenMany(inbound.receive().asString())
}
.map { objectMapper.readValue<BithumbResponseWrapper<BithumbOrderBook>>(it) }
.map {
OrderBook(
"${it.header.currency}${ZonedDateTime.now().toEpochMilli()}",
CurrencyPair(it.header.currency, Currency.KRW), // Bithumb only have KRW market
ZonedDateTime.now(),
ExchangeVendor.BITHUMB,
it.data.bids.map { bithumbBid ->
OrderBookUnit(
bithumbBid.price,
bithumbBid.quantity,
OrderSideType.BID,
null
)
},
it.data.asks.map { bithumbAsk ->
OrderBookUnit(
bithumbAsk.price,
bithumbAsk.quantity,
OrderSideType.ASK,
null
)
}
)
}
}
}
}
| 22
| null |
30
| 92
|
68ea8859f8900e2b3e041874504bd6343c0dff49
| 6,145
|
reactive-crypto
|
Apache License 2.0
|
reactive-crypto-bithumb/src/main/kotlin/com/njkim/reactivecrypto/bithumb/BithumbWebsocketClient.kt
|
namjug-kim
| 184,743,851
| false
| null |
/*
* Copyright 2019 namjug-kim
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.njkim.reactivecrypto.bithumb
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.njkim.reactivecrypto.bithumb.model.BithumbOrderBook
import com.njkim.reactivecrypto.bithumb.model.BithumbResponseWrapper
import com.njkim.reactivecrypto.bithumb.model.BithumbTickData
import com.njkim.reactivecrypto.core.websocket.AbstractExchangeWebsocketClient
import com.njkim.reactivecrypto.core.ExchangeJsonObjectMapper
import com.njkim.reactivecrypto.core.common.model.ExchangeVendor
import com.njkim.reactivecrypto.core.common.model.currency.Currency
import com.njkim.reactivecrypto.core.common.model.currency.CurrencyPair
import com.njkim.reactivecrypto.core.common.model.order.OrderBook
import com.njkim.reactivecrypto.core.common.model.order.OrderBookUnit
import com.njkim.reactivecrypto.core.common.model.order.OrderSideType
import com.njkim.reactivecrypto.core.common.model.order.TickData
import com.njkim.reactivecrypto.core.common.util.toEpochMilli
import mu.KotlinLogging
import reactor.core.publisher.Flux
import reactor.core.publisher.toFlux
import reactor.netty.http.client.HttpClient
import java.time.ZonedDateTime
class BithumbWebsocketClient : AbstractExchangeWebsocketClient() {
private val log = KotlinLogging.logger {}
private val baseUri = "wss://wss.bithumb.com/public"
private val objectMapper: ObjectMapper = createJsonObjectMapper().objectMapper()
override fun createJsonObjectMapper(): ExchangeJsonObjectMapper {
return BithumbJsonObjectMapper()
}
override fun createTradeWebsocket(subscribeTargets: List<CurrencyPair>): Flux<TickData> {
val subscribeRequests = subscribeTargets.stream()
.map {
if (it.baseCurrency == Currency.KRW) {
"${it.targetCurrency}"
} else {
"${it.targetCurrency}${it.baseCurrency}"
}
}
.map { "{\"currency\":\"$it\",\"tickDuration\":\"24H\",\"service\":\"transaction\"}" }
.toFlux()
return subscribeRequests.flatMap { subscribeRequest ->
HttpClient.create()
.headers { it.add("Origin", "https://www.bithumb.com") }
.wiretap(log.isDebugEnabled)
.websocket()
.uri(baseUri)
.handle { inbound, outbound ->
outbound.sendString(Flux.just(subscribeRequest))
.then()
.thenMany(inbound.receive().asString())
}
.map { objectMapper.readValue<BithumbResponseWrapper<List<BithumbTickData>>>(it) }
.flatMapIterable {
it.data.map { bithumbTickData ->
TickData(
bithumbTickData.countNo.toString(),
bithumbTickData.transactionDate,
bithumbTickData.price,
bithumbTickData.unitsTraded,
CurrencyPair(it.header.currency, Currency.KRW), // Bithumb only have KRW market
ExchangeVendor.BITHUMB,
bithumbTickData.type
)
}
}
}
}
override fun createDepthSnapshot(subscribeTargets: List<CurrencyPair>): Flux<OrderBook> {
val subscribeRequests = subscribeTargets.stream()
.map {
if (it.baseCurrency == Currency.KRW) {
"${it.targetCurrency}"
} else {
"${it.targetCurrency}${it.baseCurrency}"
}
}
.map { "{\"currency\":\"$it\",\"tickDuration\":\"24H\",\"service\":\"orderbook\"}" }
.toFlux()
return subscribeRequests.flatMap { subscribeRequest ->
HttpClient.create()
.headers { it.add("Origin", "https://www.bithumb.com") }
.wiretap(log.isDebugEnabled)
.websocket()
.uri(baseUri)
.handle { inbound, outbound ->
outbound.sendString(Flux.just(subscribeRequest))
.then()
.thenMany(inbound.receive().asString())
}
.map { objectMapper.readValue<BithumbResponseWrapper<BithumbOrderBook>>(it) }
.map {
OrderBook(
"${it.header.currency}${ZonedDateTime.now().toEpochMilli()}",
CurrencyPair(it.header.currency, Currency.KRW), // Bithumb only have KRW market
ZonedDateTime.now(),
ExchangeVendor.BITHUMB,
it.data.bids.map { bithumbBid ->
OrderBookUnit(
bithumbBid.price,
bithumbBid.quantity,
OrderSideType.BID,
null
)
},
it.data.asks.map { bithumbAsk ->
OrderBookUnit(
bithumbAsk.price,
bithumbAsk.quantity,
OrderSideType.ASK,
null
)
}
)
}
}
}
}
| 22
| null |
30
| 92
|
68ea8859f8900e2b3e041874504bd6343c0dff49
| 6,145
|
reactive-crypto
|
Apache License 2.0
|
app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/repos/InfoRepoMessage.kt
|
cuong-tran
| 808,519,905
| false
|
{"Kotlin": 3259056}
|
package eu.kanade.tachiyomi.ui.source.browse.repos
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder
class InfoRepoMessage : AbstractFlexibleItem<InfoRepoMessage.Holder>() {
/**
* Returns the layout resource for this item.
*/
override fun getLayoutRes(): Int {
return R.layout.info_repo_message
}
/**
* Returns a new view holder for this item.
*
* @param view The view of this item.
* @param adapter The adapter of this item.
*/
override fun createViewHolder(
view: View,
adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>,
): Holder {
return Holder(view, adapter)
}
/**
* Binds the given view holder with this item.
*
* @param adapter The adapter of this item.
* @param holder The holder to bind.
* @param position The position of this item in the adapter.
* @param payloads List of partial changes.
*/
override fun bindViewHolder(
adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>,
holder: Holder,
position: Int,
payloads: MutableList<Any>,
) {
}
/**
* Returns true if this item is draggable.
*/
override fun isDraggable(): Boolean = false
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is InfoRepoMessage
}
override fun hashCode(): Int {
return "Info repo message".hashCode()
}
class Holder(val view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>) :
BaseFlexibleViewHolder(view, adapter, true)
}
| 1
|
Kotlin
|
2
| 5
|
ccc5052fdd450b937e478c7017aad427f3da8b9e
| 1,919
|
tachiyomiJ2K
|
Apache License 2.0
|
buildSrc/lint-checks/src/main/java/androidx/build/lint/BanTargetApiAnnotation.kt
|
FYI-Google
| 258,765,297
| false
| null |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.lint
import com.android.tools.lint.detector.api.AnnotationUsageType
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UAnnotation
import org.jetbrains.uast.UElement
import java.util.Collections
class BanTargetApiAnnotation : Detector(), Detector.UastScanner {
override fun applicableAnnotations(): List<String>? {
return Collections.singletonList("android.annotation.TargetApi")
}
override fun visitAnnotationUsage(
context: JavaContext,
usage: UElement,
type: AnnotationUsageType,
annotation: UAnnotation,
qualifiedName: String,
method: PsiMethod?,
annotations: List<UAnnotation>,
allMemberAnnotations: List<UAnnotation>,
allClassAnnotations: List<UAnnotation>,
allPackageAnnotations: List<UAnnotation>
) {
if (type == AnnotationUsageType.METHOD_CALL) {
context.report(ISSUE, annotation, context.getNameLocation(annotation),
"Uses @TargetApi annotation")
}
}
companion object {
val ISSUE = Issue.create("BanTargetApiAnnotation",
"Uses @TargetApi annotation",
"Use of @TargetApi annotation is not allowed, please consider " +
"using the @RequiresApi annotation instead.",
Category.CORRECTNESS, 5, Severity.ERROR,
Implementation(BanTargetApiAnnotation::class.java, Scope.JAVA_FILE_SCOPE))
}
}
| 0
| null |
0
| 6
|
b9cd83371e928380610719dfbf97c87c58e80916
| 2,479
|
platform_frameworks_support
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.